text:
package org.apache.fineract.portfolio.savings.data;

import java.math.BigDecimal;
import java.util.Collection;
import java.util.List;
import java.util.Map;

import org.apache.fineract.accounting.common.AccountingRuleType;
import org.apache.fineract.accounting.glaccount.data.GLAccountData;
import org.apache.fineract.accounting.producttoaccountmapping.data.ChargeToGLAccountMapper;
import org.apache.fineract.accounting.producttoaccountmapping.data.PaymentTypeToGLAccountMapper;
import org.apache.fineract.infrastructure.core.data.EnumOptionData;
import org.apache.fineract.organisation.monetary.data.CurrencyData;
import org.apache.fineract.portfolio.charge.data.ChargeData;
import org.apache.fineract.portfolio.interestratechart.data.InterestRateChartData;
import org.apache.fineract.portfolio.paymenttype.data.PaymentTypeData;
import org.apache.fineract.portfolio.tax.data.TaxGroupData;

/**
 * Immutable data object represents a partial data of Deposit Proucts.
 */
public class DepositProductData {

    protected final Long id;
    protected final String name;
    protected final String shortName;
    protected final String description;
    protected final CurrencyData currency;
    protected final BigDecimal nominalAnnualInterestRate;
    protected final EnumOptionData interestCompoundingPeriodType;
    protected final EnumOptionData interestPostingPeriodType;
    protected final EnumOptionData interestCalculationType;
    protected final EnumOptionData interestCalculationDaysInYearType;
    // protected final BigDecimal minRequiredOpeningBalance;
    protected final Integer lockinPeriodFrequency;
    protected final EnumOptionData lockinPeriodFrequencyType;
    // protected final boolean withdrawalFeeForTransfers;
    protected final BigDecimal minBalanceForInterestCalculation;
    protected final boolean withHoldTax;
    protected final TaxGroupData taxGroup;

    // accounting
    protected final EnumOptionData accountingRule;
    protected final Map<String, Object> accountingMappings;
    protected final Collection<PaymentTypeToGLAccountMapper> paymentChannelToFundSourceMappings;
    protected final Collection<ChargeToGLAccountMapper> feeToIncomeAccountMappings;
    protected final Collection<ChargeToGLAccountMapper> penaltyToIncomeAccountMappings;

    // charges
    protected final Collection<ChargeData> charges;

    // interest rate charts
    protected final Collection<InterestRateChartData> interestRateCharts;
    protected final InterestRateChartData activeChart;

    // template
    protected final Collection<CurrencyData> currencyOptions;
    protected final Collection<EnumOptionData> interestCompoundingPeriodTypeOptions;
    protected final Collection<EnumOptionData> interestPostingPeriodTypeOptions;
    protected final Collection<EnumOptionData> interestCalculationTypeOptions;
    protected final Collection<EnumOptionData> interestCalculationDaysInYearTypeOptions;
    protected final Collection<EnumOptionData> lockinPeriodFrequencyTypeOptions;
    protected final Collection<EnumOptionData> withdrawalFeeTypeOptions;
    protected final Collection<PaymentTypeData> paymentTypeOptions;
    protected final Collection<EnumOptionData> accountingRuleOptions;
    protected final Map<String, List<GLAccountData>> accountingMappingOptions;
    protected final Collection<ChargeData> chargeOptions;
    protected final Collection<ChargeData> penaltyOptions;
    protected final InterestRateChartData chartTemplate;
    protected final Collection<TaxGroupData> taxGroupOptions;

    public static DepositProductData template(final CurrencyData currency, final EnumOptionData interestCompoundingPeriodType,
            final EnumOptionData interestPostingPeriodType, final EnumOptionData interestCalculationType,
            final EnumOptionData interestCalculationDaysInYearType, final EnumOptionData accountingRule,
            final Collection<CurrencyData> currencyOptions, final Collection<EnumOptionData> interestCompoundingPeriodTypeOptions,
            final Collection<EnumOptionData> interestPostingPeriodTypeOptions,
            final Collection<EnumOptionData> interestCalculationTypeOptions,
            final Collection<EnumOptionData> interestCalculationDaysInYearTypeOptions,
            final Collection<EnumOptionData> lockinPeriodFrequencyTypeOptions, final Collection<EnumOptionData> withdrawalFeeTypeOptions,
            final Collection<PaymentTypeData> paymentTypeOptions, final Collection<EnumOptionData> accountingRuleOptions,
            final Map<String, List<GLAccountData>> accountingMappingOptions, final Collection<ChargeData> chargeOptions,
            final Collection<ChargeData> penaltyOptions, final InterestRateChartData chartTemplate,
            final Collection<TaxGroupData> taxGroupOptions) {

        final Long id = null;
        final String name = null;
        final String shortName = null;
        final String description = null;
        final BigDecimal nominalAnnualInterestRate = null;
        final Integer lockinPeriodFrequency = null;
        final EnumOptionData lockinPeriodFrequencyType = null;
        final BigDecimal minBalanceForInterestCalculation = null;
        final Map<String, Object> accountingMappings = null;
        final Collection<PaymentTypeToGLAccountMapper> paymentChannelToFundSourceMappings = null;
        final Collection<ChargeData> charges = null;
        final Collection<ChargeToGLAccountMapper> feeToIncomeAccountMappings = null;
        final Collection<ChargeToGLAccountMapper> penaltyToIncomeAccountMappings = null;
        final Collection<InterestRateChartData> interestRateCharts = null;
        final boolean withHoldTax = false;
        final TaxGroupData taxGroup = null;

        return new DepositProductData(id, name, shortName, description, currency, nominalAnnualInterestRate, interestCompoundingPeriodType,
                interestPostingPeriodType, interestCalculationType, interestCalculationDaysInYearType, lockinPeriodFrequency,
                lockinPeriodFrequencyType, accountingRule, accountingMappings, paymentChannelToFundSourceMappings, currencyOptions,
                interestCompoundingPeriodTypeOptions, interestPostingPeriodTypeOptions, interestCalculationTypeOptions,
                interestCalculationDaysInYearTypeOptions, lockinPeriodFrequencyTypeOptions, withdrawalFeeTypeOptions, paymentTypeOptions,
                accountingRuleOptions, accountingMappingOptions, charges, chargeOptions, penaltyOptions, feeToIncomeAccountMappings,
                penaltyToIncomeAccountMappings, interestRateCharts, chartTemplate, minBalanceForInterestCalculation, withHoldTax, taxGroup,
                taxGroupOptions);
    }

    public static DepositProductData withCharges(final DepositProductData existingProduct, final Collection<ChargeData> charges) {
        return new DepositProductData(existingProduct.id, existingProduct.name, existingProduct.shortName, existingProduct.description,
                existingProduct.currency, existingProduct.nominalAnnualInterestRate, existingProduct.interestCompoundingPeriodType,
                existingProduct.interestPostingPeriodType, existingProduct.interestCalculationType,
                existingProduct.interestCalculationDaysInYearType, existingProduct.lockinPeriodFrequency,
                existingProduct.lockinPeriodFrequencyType, existingProduct.accountingRule, existingProduct.accountingMappings,
                existingProduct.paymentChannelToFundSourceMappings, existingProduct.currencyOptions,
                existingProduct.interestCompoundingPeriodTypeOptions, existingProduct.interestPostingPeriodTypeOptions,
                existingProduct.interestCalculationTypeOptions, existingProduct.interestCalculationDaysInYearTypeOptions,
                existingProduct.lockinPeriodFrequencyTypeOptions, existingProduct.withdrawalFeeTypeOptions,
                existingProduct.paymentTypeOptions, existingProduct.accountingRuleOptions, existingProduct.accountingMappingOptions,
                charges, existingProduct.chargeOptions, existingProduct.penaltyOptions, existingProduct.feeToIncomeAccountMappings,
                existingProduct.penaltyToIncomeAccountMappings, existingProduct.interestRateCharts, existingProduct.chartTemplate,
                existingProduct.minBalanceForInterestCalculation, existingProduct.withHoldTax, existingProduct.taxGroup,
                existingProduct.taxGroupOptions);
    }

    /**
     * Returns a {@link DepositProductData} that contains and exist
     * {@link DepositProductData} data with further template data for dropdowns.
     *
     * @param taxGroupOptions
     *            TODO
     */
    public static DepositProductData withTemplate(final DepositProductData existingProduct, final Collection<CurrencyData> currencyOptions,
            final Collection<EnumOptionData> interestCompoundingPeriodTypeOptions,
            final Collection<EnumOptionData> interestPostingPeriodTypeOptions,
            final Collection<EnumOptionData> interestCalculationTypeOptions,
            final Collection<EnumOptionData> interestCalculationDaysInYearTypeOptions,
            final Collection<EnumOptionData> lockinPeriodFrequencyTypeOptions, final Collection<EnumOptionData> withdrawalFeeTypeOptions,
            final Collection<PaymentTypeData> paymentTypeOptions, final Collection<EnumOptionData> accountingRuleOptions,
            final Map<String, List<GLAccountData>> accountingMappingOptions, final Collection<ChargeData> chargeOptions,
            final Collection<ChargeData> penaltyOptions, final InterestRateChartData chartTemplate, Collection<TaxGroupData> taxGroupOptions) {

        return new DepositProductData(existingProduct.id, existingProduct.name, existingProduct.shortName, existingProduct.description,
                existingProduct.currency, existingProduct.nominalAnnualInterestRate, existingProduct.interestCompoundingPeriodType,
                existingProduct.interestPostingPeriodType, existingProduct.interestCalculationType,
                existingProduct.interestCalculationDaysInYearType, existingProduct.lockinPeriodFrequency,
                existingProduct.lockinPeriodFrequencyType, existingProduct.accountingRule, existingProduct.accountingMappings,
                existingProduct.paymentChannelToFundSourceMappings, currencyOptions, interestCompoundingPeriodTypeOptions,
                interestPostingPeriodTypeOptions, interestCalculationTypeOptions, interestCalculationDaysInYearTypeOptions,
                lockinPeriodFrequencyTypeOptions, withdrawalFeeTypeOptions, paymentTypeOptions, accountingRuleOptions,
                accountingMappingOptions, existingProduct.charges, chargeOptions, penaltyOptions,
                existingProduct.feeToIncomeAccountMappings, existingProduct.penaltyToIncomeAccountMappings,
                existingProduct.interestRateCharts, chartTemplate, existingProduct.minBalanceForInterestCalculation,
                existingProduct.withHoldTax, existingProduct.taxGroup, taxGroupOptions);
    }

    public static DepositProductData withAccountingDetails(final DepositProductData existingProduct,
            final Map<String, Object> accountingMappings,
            final Collection<PaymentTypeToGLAccountMapper> paymentChannelToFundSourceMappings,
            final Collection<ChargeToGLAccountMapper> feeToIncomeAccountMappings,
            final Collection<ChargeToGLAccountMapper> penaltyToIncomeAccountMappings) {

        final Collection<CurrencyData> currencyOptions = null;
        final Collection<EnumOptionData> interestCompoundingPeriodTypeOptions = null;
        final Collection<EnumOptionData> interestPostingPeriodTypeOptions = null;
        final Collection<EnumOptionData> interestCalculationTypeOptions = null;
        final Collection<EnumOptionData> interestCalculationDaysInYearTypeOptions = null;
        final Collection<EnumOptionData> lockinPeriodFrequencyTypeOptions = null;
        final Collection<EnumOptionData> withdrawalFeeTypeOptions = null;
        final Collection<PaymentTypeData> paymentTypeOptions = null;
        final Collection<EnumOptionData> accountingRuleOptions = null;
        final Map<String, List<GLAccountData>> accountingMappingOptions = null;
        final Collection<ChargeData> chargeOptions = null;
        final Collection<ChargeData> penaltyOptions = null;
        final Collection<TaxGroupData> taxGroupOptions = null;

        return new DepositProductData(existingProduct.id, existingProduct.name, existingProduct.shortName, existingProduct.description,
                existingProduct.currency, existingProduct.nominalAnnualInterestRate, existingProduct.interestCompoundingPeriodType,
                existingProduct.interestPostingPeriodType, existingProduct.interestCalculationType,
                existingProduct.interestCalculationDaysInYearType, existingProduct.lockinPeriodFrequency,
                existingProduct.lockinPeriodFrequencyType, existingProduct.accountingRule, accountingMappings,
                paymentChannelToFundSourceMappings, currencyOptions, interestCompoundingPeriodTypeOptions,
                interestPostingPeriodTypeOptions, interestCalculationTypeOptions, interestCalculationDaysInYearTypeOptions,
                lockinPeriodFrequencyTypeOptions, withdrawalFeeTypeOptions, paymentTypeOptions, accountingRuleOptions,
                accountingMappingOptions, existingProduct.charges, chargeOptions, penaltyOptions, feeToIncomeAccountMappings,
                penaltyToIncomeAccountMappings, existingProduct.interestRateCharts, existingProduct.chartTemplate,
                existingProduct.minBalanceForInterestCalculation, existingProduct.withHoldTax, existingProduct.taxGroup, taxGroupOptions);
    }

    public static DepositProductData instance(final Long id, final String name, final String shortName, final String description,
            final CurrencyData currency, final BigDecimal nominalAnnualInterestRate, final EnumOptionData interestCompoundingPeriodType,
            final EnumOptionData interestPostingPeriodType, final EnumOptionData interestCalculationType,
            final EnumOptionData interestCalculationDaysInYearType, final Integer lockinPeriodFrequency,
            final EnumOptionData lockinPeriodFrequencyType, final EnumOptionData accountingType,
            final BigDecimal minBalanceForInterestCalculation, boolean withHoldTax, TaxGroupData taxGroup) {

        final Map<String, Object> accountingMappings = null;
        final Collection<PaymentTypeToGLAccountMapper> paymentChannelToFundSourceMappings = null;

        final Collection<CurrencyData> currencyOptions = null;
        final Collection<EnumOptionData> interestCompoundingPeriodTypeOptions = null;
        final Collection<EnumOptionData> interestPostingPeriodTypeOptions = null;
        final Collection<EnumOptionData> interestCalculationTypeOptions = null;
        final Collection<EnumOptionData> interestCalculationDaysInYearTypeOptions = null;
        final Collection<EnumOptionData> lockinPeriodFrequencyTypeOptions = null;
        final Collection<EnumOptionData> withdrawalFeeTypeOptions = null;
        final Collection<PaymentTypeData> paymentTypeOptions = null;
        final Collection<EnumOptionData> accountingRuleOptions = null;
        final Map<String, List<GLAccountData>> accountingMappingOptions = null;
        final Collection<ChargeData> chargeOptions = null;
        final Collection<ChargeData> penaltyOptions = null;
        final Collection<ChargeData> charges = null;
        final Collection<ChargeToGLAccountMapper> feeToIncomeAccountMappings = null;
        final Collection<ChargeToGLAccountMapper> penaltyToIncomeAccountMappings = null;
        final Collection<InterestRateChartData> interestRateCharts = null;
        final InterestRateChartData chartTemplate = null;
        final Collection<TaxGroupData> taxGroupOptions = null;

        return new DepositProductData(id, name, shortName, description, currency, nominalAnnualInterestRate, interestCompoundingPeriodType,
                interestPostingPeriodType, interestCalculationType, interestCalculationDaysInYearType, lockinPeriodFrequency,
                lockinPeriodFrequencyType, accountingType, accountingMappings, paymentChannelToFundSourceMappings, currencyOptions,
                interestCompoundingPeriodTypeOptions, interestPostingPeriodTypeOptions, interestCalculationTypeOptions,
                interestCalculationDaysInYearTypeOptions, lockinPeriodFrequencyTypeOptions, withdrawalFeeTypeOptions, paymentTypeOptions,
                accountingRuleOptions, accountingMappingOptions, charges, chargeOptions, penaltyOptions, feeToIncomeAccountMappings,
                penaltyToIncomeAccountMappings, interestRateCharts, chartTemplate, minBalanceForInterestCalculation, withHoldTax, taxGroup,
                taxGroupOptions);
    }

    public static DepositProductData lookup(final Long id, final String name) {

        final String shortName = null;
        final CurrencyData currency = null;
        final String description = null;
        final BigDecimal nominalAnnualInterestRate = null;
        final EnumOptionData interestCompoundingPeriodType = null;
        final EnumOptionData interestPostingPeriodType = null;
        final EnumOptionData interestCalculationType = null;
        final EnumOptionData interestCalculationDaysInYearType = null;
        final Integer lockinPeriodFrequency = null;
        final EnumOptionData lockinPeriodFrequencyType = null;
        final BigDecimal minBalanceForInterestCalculation = null;

        final EnumOptionData accountingType = null;
        final Map<String, Object> accountingMappings = null;
        final Collection<PaymentTypeToGLAccountMapper> paymentChannelToFundSourceMappings = null;

        final Collection<CurrencyData> currencyOptions = null;
        final Collection<EnumOptionData> interestCompoundingPeriodTypeOptions = null;
        final Collection<EnumOptionData> interestPostingPeriodTypeOptions = null;
        final Collection<EnumOptionData> interestCalculationTypeOptions = null;
        final Collection<EnumOptionData> interestCalculationDaysInYearTypeOptions = null;
        final Collection<EnumOptionData> lockinPeriodFrequencyTypeOptions = null;
        final Collection<EnumOptionData> withdrawalFeeTypeOptions = null;
        final Collection<PaymentTypeData> paymentTypeOptions = null;
        final Collection<EnumOptionData> accountingRuleOptions = null;
        final Map<String, List<GLAccountData>> accountingMappingOptions = null;
        final Collection<ChargeData> charges = null;
        final Collection<ChargeData> chargeOptions = null;
        final Collection<ChargeData> penaltyOptions = null;
        final Collection<ChargeToGLAccountMapper> feeToIncomeAccountMappings = null;
        final Collection<ChargeToGLAccountMapper> penaltyToIncomeAccountMappings = null;
        final Collection<InterestRateChartData> interestRateCharts = null;
        final InterestRateChartData chartTemplate = null;
        final boolean withHoldTax = false;
        final TaxGroupData taxGroup = null;
        final Collection<TaxGroupData> taxGroupOptions = null;

        return new DepositProductData(id, name, shortName, description, currency, nominalAnnualInterestRate, interestCompoundingPeriodType,
                interestPostingPeriodType, interestCalculationType, interestCalculationDaysInYearType, lockinPeriodFrequency,
                lockinPeriodFrequencyType, accountingType, accountingMappings, paymentChannelToFundSourceMappings, currencyOptions,
                interestCompoundingPeriodTypeOptions, interestPostingPeriodTypeOptions, interestCalculationTypeOptions,
                interestCalculationDaysInYearTypeOptions, lockinPeriodFrequencyTypeOptions, withdrawalFeeTypeOptions, paymentTypeOptions,
                accountingRuleOptions, accountingMappingOptions, charges, chargeOptions, penaltyOptions, feeToIncomeAccountMappings,
                penaltyToIncomeAccountMappings, interestRateCharts, chartTemplate, minBalanceForInterestCalculation, withHoldTax, taxGroup,
                taxGroupOptions);
    }

    public static DepositProductData withInterestChart(final DepositProductData existingProduct,
            final Collection<InterestRateChartData> interestRateCharts) {
        return new DepositProductData(existingProduct.id, existingProduct.name, existingProduct.shortName, existingProduct.description,
                existingProduct.currency, existingProduct.nominalAnnualInterestRate, existingProduct.interestCompoundingPeriodType,
                existingProduct.interestPostingPeriodType, existingProduct.interestCalculationType,
                existingProduct.interestCalculationDaysInYearType, existingProduct.lockinPeriodFrequency,
                existingProduct.lockinPeriodFrequencyType, existingProduct.accountingRule, existingProduct.accountingMappings,
                existingProduct.paymentChannelToFundSourceMappings, existingProduct.currencyOptions,
                existingProduct.interestCompoundingPeriodTypeOptions, existingProduct.interestPostingPeriodTypeOptions,
                existingProduct.interestCalculationTypeOptions, existingProduct.interestCalculationDaysInYearTypeOptions,
                existingProduct.lockinPeriodFrequencyTypeOptions, existingProduct.withdrawalFeeTypeOptions,
                existingProduct.paymentTypeOptions, existingProduct.accountingRuleOptions, existingProduct.accountingMappingOptions,
                existingProduct.charges, existingProduct.chargeOptions, existingProduct.penaltyOptions,
                existingProduct.feeToIncomeAccountMappings, existingProduct.penaltyToIncomeAccountMappings, interestRateCharts,
                existingProduct.chartTemplate, existingProduct.minBalanceForInterestCalculation, existingProduct.withHoldTax,
                existingProduct.taxGroup, existingProduct.taxGroupOptions);
    }

    protected DepositProductData(final Long id, final String name, final String shortName, final String description,
            final CurrencyData currency, final BigDecimal nominalAnnualInterestRate, final EnumOptionData interestCompoundingPeriodType,
            final EnumOptionData interestPostingPeriodType, final EnumOptionData interestCalculationType,
            final EnumOptionData interestCalculationDaysInYearType, final Integer lockinPeriodFrequency,
            final EnumOptionData lockinPeriodFrequencyType, final EnumOptionData accountingType,
            final Map<String, Object> accountingMappings,
            final Collection<PaymentTypeToGLAccountMapper> paymentChannelToFundSourceMappings,
            final Collection<CurrencyData> currencyOptions, final Collection<EnumOptionData> interestCompoundingPeriodTypeOptions,
            final Collection<EnumOptionData> interestPostingPeriodTypeOptions,
            final Collection<EnumOptionData> interestCalculationTypeOptions,
            final Collection<EnumOptionData> interestCalculationDaysInYearTypeOptions,
            final Collection<EnumOptionData> lockinPeriodFrequencyTypeOptions, final Collection<EnumOptionData> withdrawalFeeTypeOptions,
            final Collection<PaymentTypeData> paymentTypeOptions, final Collection<EnumOptionData> accountingRuleOptions,
            final Map<String, List<GLAccountData>> accountingMappingOptions, final Collection<ChargeData> charges,
            final Collection<ChargeData> chargeOptions, final Collection<ChargeData> penaltyOptions,
            final Collection<ChargeToGLAccountMapper> feeToIncomeAccountMappings,
            final Collection<ChargeToGLAccountMapper> penaltyToIncomeAccountMappings,
            final Collection<InterestRateChartData> interestRateCharts, final InterestRateChartData chartTemplate,
            final BigDecimal minBalanceForInterestCalculation, final boolean withHoldTax, final TaxGroupData taxGroup,
            final Collection<TaxGroupData> taxGroupOptions) {

        this.id = id;
        this.name = name;
        this.shortName = shortName;
        this.description = description;
        this.currency = currency;
        this.nominalAnnualInterestRate = nominalAnnualInterestRate;
        this.interestCompoundingPeriodType = interestCompoundingPeriodType;
        this.interestPostingPeriodType = interestPostingPeriodType;
        this.interestCalculationType = interestCalculationType;
        this.interestCalculationDaysInYearType = interestCalculationDaysInYearType;
        this.accountingRule = accountingType;
        this.lockinPeriodFrequency = lockinPeriodFrequency;
        this.lockinPeriodFrequencyType = lockinPeriodFrequencyType;

        this.currencyOptions = currencyOptions;
        this.interestCompoundingPeriodTypeOptions = interestCompoundingPeriodTypeOptions;
        this.interestPostingPeriodTypeOptions = interestPostingPeriodTypeOptions;
        this.interestCalculationTypeOptions = interestCalculationTypeOptions;
        this.interestCalculationDaysInYearTypeOptions = interestCalculationDaysInYearTypeOptions;
        this.lockinPeriodFrequencyTypeOptions = lockinPeriodFrequencyTypeOptions;
        this.withdrawalFeeTypeOptions = withdrawalFeeTypeOptions;

        this.paymentTypeOptions = paymentTypeOptions;
        this.accountingMappingOptions = accountingMappingOptions;
        this.accountingRuleOptions = accountingRuleOptions;
        if (accountingMappings == null || accountingMappings.isEmpty()) {
            this.accountingMappings = null;
        } else {
            this.accountingMappings = accountingMappings;
        }
        this.paymentChannelToFundSourceMappings = paymentChannelToFundSourceMappings;

        this.charges = charges;// charges associated with Savings product
        this.chargeOptions = chargeOptions;// charges available for adding to
                                           // Savings product
        this.penaltyOptions = penaltyOptions;// penalties available for adding
                                             // to Savings product

        this.feeToIncomeAccountMappings = feeToIncomeAccountMappings;
        this.penaltyToIncomeAccountMappings = penaltyToIncomeAccountMappings;
        this.interestRateCharts = interestRateCharts;
        this.activeChart = activeChart(this.interestRateCharts);
        this.chartTemplate = chartTemplate;
        this.minBalanceForInterestCalculation = minBalanceForInterestCalculation;
        this.taxGroup = taxGroup;
        this.withHoldTax = withHoldTax;
        this.taxGroupOptions = taxGroupOptions;
    }

    public static InterestRateChartData activeChart(Collection<InterestRateChartData> interestRateCharts) {
        InterestRateChartData activeChart = null;
        if (interestRateCharts != null) {
            for (InterestRateChartData chartData : interestRateCharts) {
                if (activeChart == null) {
                    activeChart = chartData;
                } else {
                    if (!activeChart.isFromDateAfter(chartData.endDate())) {
                        activeChart = chartData;
                    }
                }
            }
        }
        return activeChart;
    }

    public boolean hasAccountingEnabled() {
        return this.accountingRule.getId() > AccountingRuleType.NONE.getValue();
    }

    public int accountingRuleTypeId() {
        return this.accountingRule.getId().intValue();
    }

    public String getName() {
        return this.name;
    }
}


text:
namespace Lemonade
{
    public abstract class FeatureWrapper
    {
        public bool IsEnabled => Feature.Switches[Key];

        public void Execute()
        {
            if (IsEnabled) OnExecute();
        }

        protected abstract void OnExecute();
        protected abstract string Key { get; }
    }
}

redpajama_set_name: RedPajamaGithub


text:
describe BinaryBlobPart do
  context "#data= and #data" do
    before(:each) do
      @part = FactoryGirl.create(:binary_blob_part)
    end

    subject do
      @part.data = @data
      @part.save
      @part.reload
      @part.data
    end

    it "without UTF-8 data" do
      @data = "--- Quota - Max CPUs\n...\n"
      expect(subject.bytes.to_a).to eq(@data.bytes.to_a)
    end

    it "with UTF-8 data" do
      @data = "--- Quota \xE2\x80\x93 Max CPUs\n...\n"
      expect(subject.bytes.to_a).to eq(@data.bytes.to_a)
    end
  end
end


text:
package com.asakusafw.yaess.basic;

import java.io.IOException;
import java.text.MessageFormat;
import java.util.HashMap;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.TreeSet;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.CancellationException;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.LinkedBlockingQueue;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.asakusafw.yaess.basic.JobExecutor.Executing;
import com.asakusafw.yaess.core.ExecutionContext;
import com.asakusafw.yaess.core.Job;
import com.asakusafw.yaess.core.JobScheduler;
import com.asakusafw.yaess.core.PhaseMonitor;
import com.asakusafw.yaess.core.PhaseMonitor.JobStatus;
import com.asakusafw.yaess.core.YaessLogger;

/**
 * An abstract implementation of {@link JobScheduler}.
 * @since 0.2.3
 */
public abstract class AbstractJobScheduler extends JobScheduler {

    static final YaessLogger YSLOG = new YaessBasicLogger(AbstractJobScheduler.class);

    static final Logger LOG = LoggerFactory.getLogger(AbstractJobScheduler.class);

    /**
     * Returns a {@link JobExecutor} for this scheduler.
     * @return the {@link JobExecutor}
     */
    protected abstract JobExecutor getJobExecutor();

    @Override
    public final void execute(
            PhaseMonitor monitor,
            ExecutionContext context,
            List<? extends Job> jobs,
            ErrorHandler errorHandler) throws InterruptedException, IOException {
        if (monitor == null) {
            throw new IllegalArgumentException("monitor must not be null"); //$NON-NLS-1$
        }
        if (context == null) {
            throw new IllegalArgumentException("context must not be null"); //$NON-NLS-1$
        }
        if (jobs == null) {
            throw new IllegalArgumentException("jobs must not be null"); //$NON-NLS-1$
        }
        if (errorHandler == null) {
            throw new IllegalArgumentException("errorHandler must not be null"); //$NON-NLS-1$
        }
        monitor.open(jobs.size());
        try {
            monitor.checkCancelled();
            Engine engine = new Engine(getJobExecutor(), monitor, context, errorHandler, jobs);
            engine.run();
        } finally {
            monitor.close();
        }
    }

    private static final class Engine {

        private final JobExecutor executor;

        final PhaseMonitor monitor;

        final ExecutionContext context;

        private final ErrorHandler handler;

        private final LinkedList<Job> waiting;

        private final Map<String, Executing> executing;

        private final BlockingQueue<Executing> doneQueue;

        private final Set<String> blockers;

        private boolean sawError;

        Engine(
                JobExecutor executor,
                PhaseMonitor monitor,
                ExecutionContext context,
                ErrorHandler handler,
                List<? extends Job> waiting) {
            assert executor != null;
            assert monitor != null;
            assert context != null;
            assert handler != null;
            assert waiting != null;
            this.executor = executor;
            this.monitor = monitor;
            this.context = context;
            this.handler = handler;
            this.waiting = new LinkedList<>(waiting);
            this.executing = new HashMap<>();
            this.doneQueue = new LinkedBlockingQueue<>();
            this.blockers = new TreeSet<>();
            for (Job job : waiting) {
                blockers.add(job.getId());
            }
            this.sawError = false;
        }

        void run() throws IOException, InterruptedException {
            while (waiting.isEmpty() == false) {
                boolean submitted = submitAllWaiting();
                if (submitted == false && executing.isEmpty()) {
                    assert waiting.isEmpty() == false;
                    if (sawError) {
                        waiting.clear();
                    } else {
                        throw new IOException(MessageFormat.format(
                                "Jobnet execution was deadlocked: {4} (batch={0}, flow={1}, phase={2}, execution={3})",
                                context.getBatchId(),
                                context.getFlowId(),
                                context.getPhase(),
                                context.getExecutionId(),
                                blockers));
                    }
                } else {
                    waitForDone();
                }
            }
            while (executing.isEmpty() == false) {
                waitForDone();
            }
            if (sawError) {
                throw new IOException(MessageFormat.format(
                        "Jobnet was failed by preceding errors (batch={0}, flow={1}, phase={2}, execution={3})",
                        context.getBatchId(),
                        context.getFlowId(),
                        context.getPhase(),
                        context.getExecutionId()));
            }
        }

        private boolean submitAllWaiting() throws IOException, InterruptedException {
            boolean sawSubmit = false;
            for (Iterator<Job> iter = waiting.iterator(); iter.hasNext();) {
                Job next = iter.next();
                LOG.debug("Attemps to submit job: {}", next.getId());
                if (isBlocked(next)) {
                    LOG.debug("Job is currently blocked: {}", next.getId());
                    continue;
                }
                iter.remove();
                if (submit(next)) {
                    sawSubmit = true;
                }
            }
            return sawSubmit;
        }

        private void waitForDone() throws InterruptedException, IOException {
            assert executing.isEmpty() == false;
            monitor.checkCancelled();
            Executing done = doneQueue.take();
            assert done.isDone();
            handleDone(done);
            while (true) {
                monitor.checkCancelled();
                Executing rest = doneQueue.poll();
                if (rest == null) {
                    break;
                }
                assert rest.isDone();
                handleDone(rest);
            }
        }

        private void handleDone(Executing done) throws InterruptedException, IOException {
            assert done != null;
            assert done.isDone();
            Executing removed = executing.remove(done.getJob().getId());
            assert removed != null;
            try {
                done.get();
                done(done.getJob());
                monitor.reportJobStatus(done.getJob().getId(), JobStatus.SUCCESS, null);
            } catch (CancellationException e) {
                sawError = true;
                monitor.reportJobStatus(done.getJob().getId(), JobStatus.CANCELLED, e);
            } catch (ExecutionException e) {
                sawError = true;
                Throwable cause = e.getCause();
                if (cause instanceof InterruptedException) {
                    monitor.reportJobStatus(done.getJob().getId(), JobStatus.CANCELLED, cause);
                    cancelExecution();
                    throw (InterruptedException) cause;
                } else if (cause instanceof IOException) {
                    monitor.reportJobStatus(done.getJob().getId(), JobStatus.FAILED, cause);
                    handleException(done.getJob(), (IOException) cause);
                } else if (cause instanceof Error) {
                    monitor.reportJobStatus(done.getJob().getId(), JobStatus.FAILED, cause);
                    cancelExecution();
                    throw (Error) cause;
                } else if (cause instanceof RuntimeException) {
                    monitor.reportJobStatus(done.getJob().getId(), JobStatus.FAILED, cause);
                    cancelExecution();
                    throw (RuntimeException) cause;
                } else {
                    monitor.reportJobStatus(done.getJob().getId(), JobStatus.FAILED, cause);
                    cancelExecution();
                    throw new AssertionError(cause);
                }
            }
        }

        private boolean submit(Job job) throws InterruptedException, IOException {
            assert job != null;
            monitor.checkCancelled();
            try {
                Executing execution = executor.submit(
                        monitor.createJobMonitor(job.getId(), 1), context, job, doneQueue);
                executing.put(execution.getJob().getId(), execution);
                return true;
            } catch (IOException e) {
                sawError = true;
                handleException(job, e);
                return false;
            }
        }

        private void handleException(Job job, IOException exception) throws IOException {
            assert job != null;
            assert exception != null;
            if (handler.handle(context, exception) == false) {
                cancelExecution();
                throw exception;
            }
        }

        private void cancelExecution() {
            for (Executing exec : executing.values()) {
                exec.cancel(true);
            }
        }

        private boolean isBlocked(Job job) {
            assert job != null;
            for (String blocker : job.getBlockerIds()) {
                if (blockers.contains(blocker)) {
                    return true;
                }
            }
            return false;
        }

        private void done(Job job) {
            assert job != null;
            blockers.remove(job.getId());
        }
    }
}


text:
<?php
namespace Pulsestorm\Xml_Library;
use DomDocument;
use Exception;
/**
* @command library
*/
function pestle_cli($argv)
{

}

function addSchemaToXmlString($xmlString, $schema=false)
{
    $schema = $schema ? $schema :
        'urn:magento:framework:Module/etc/module.xsd';

    $xml = str_replace(
        '<config>',
        '<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="'.$schema.'">',
        $xmlString);
    return $xml;
}

function getXmlNamespaceFromPrefix($xml, $prefix)
{
    $namespaces = $xml->getDocNamespaces();
    if(array_key_exists($prefix, $namespaces))
    {
        return $namespaces[$prefix];
    }

    throw new Exception("Unkonwn namespace in " . __FILE__);
}

function simpleXmlAddNodesXpathReturnOriginal($xml, $path)
{
    $result = simpleXmlAddNodesXpathWorker($xml, $path);
    return $result['original'];
}

function simpleXmlAddNodesXpath($xml, $path)
{
    $result = simpleXmlAddNodesXpathWorker($xml, $path);
    return $result['child'];
}

function simpleXmlAddNodesXpathWorker($xml, $path)
{
    $path = trim($path,'/');
    $node = $xml;
    foreach(explode('/',$path) as $part)
    {
        $parts = explode('[', $part);
        $node_name = array_shift($parts);
        $is_new_node = true;
        if(isset($node->{$node_name}))
        {
            $is_new_node = false;
            $node = $node->{$node_name};
        }
        else
        {
            $node = $node->addChild($node_name);
        }

        $attribute_string = trim(array_pop($parts),']');
        if(!$attribute_string) { continue; }
        $pairs = explode(',',$attribute_string);
        foreach($pairs as $pair)
        {
            if(!$is_new_node) { continue; }
            list($key,$value) = explode('=',$pair);
            if(strpos($key, '@') !== 0)
            {
                throw new Exception("Invalid Attribute Key");
            }
            $key = trim($key, '@');
            if(strpos($key, ':') !== false)
            {
                list($namespace_prefix, $rest) = explode(':', $key);
                $namespace = getXmlNamespaceFromPrefix($xml, $namespace_prefix);
                $node->addAttribute($key, $value, $namespace);
            }
            else
            {
                $node->addAttribute($key, $value);
            }

        }
//         exit;
    }

    return [
        'original'=>$xml,
        'child'=>$node
    ];
}

function getByAttributeXmlBlockWithNodeNames($attributeName, $xml, $value, $names=null)
{
    $search = '//*[@'.$attributeName.'="' . $value . '"]';
    $nodes = $xml->xpath($search);
    $nodes = array_filter($nodes, function($node) use ($names){
        if(!$names) { return true; }
        return in_array($node->getName(), $names);
    });
    return $nodes;
}

function getNamedXmlBlockWithNodeNames($xml, $name, $names)
{
    return getByAttributeXmlBlockWithNodeNames('name', $xml, $name, $names);
}

function formatXmlString($string)
{
    $dom = new DomDocument;
    $dom->preserveWhiteSpace = false;
    $dom->formatOutput = true;
    $dom->loadXml($string);
    $string = $dom->saveXml();

    $string = preg_replace('%(^\s*)%m', '$1$1', $string);

    return $string;
}


text:
using Microsoft.EntityFrameworkCore.Migrations;

namespace AbpCompanyName.AbpProjectName.Migrations
{
    public partial class Upgraded_To_Abp_4_7_0 : Migration
    {
        protected override void Up(MigrationBuilder migrationBuilder)
        {
            migrationBuilder.DropIndex(
                name: "IX_AbpSettings_TenantId_Name",
                table: "AbpSettings");

            migrationBuilder.CreateIndex(
                name: "IX_AbpSettings_TenantId_Name_UserId",
                table: "AbpSettings",
                columns: new[] { "TenantId", "Name", "UserId" },
                unique: true);
        }

        protected override void Down(MigrationBuilder migrationBuilder)
        {
            migrationBuilder.DropIndex(
                name: "IX_AbpSettings_TenantId_Name_UserId",
                table: "AbpSettings");

            migrationBuilder.CreateIndex(
                name: "IX_AbpSettings_TenantId_Name",
                table: "AbpSettings",
                columns: new[] { "TenantId", "Name" });
        }
    }
}


text:
this.__karma__ = window.__karma__;
if (window.__karma__) {
  var allTestFiles = [];
  var TEST_REGEXP = /spec\.js$/;

  var pathToModule = function(path) {
    return path.replace(/^\/base\/app\//, '').replace(/\.js$/, '');
  };

  Object.keys(window.__karma__.files).forEach(function(file) {
    if (TEST_REGEXP.test(file)) {
      // Normalize paths to RequireJS module names.
      allTestFiles.push(pathToModule(file));
    }
  });
}

require.config({
  paths: {
    jquery: 'bower_components/jquery/dist/jquery',
    angular: 'bower_components/angular/angular',
    angularAMD: 'bower_components/angularAMD/angularAMD',
    angularCookies: 'bower_components/angular-cookies/angular-cookies',
    angularLoader: 'bower_components/angular-loader/angular-loader',
    angularMocks: 'bower_components/angular-mocks/angular-mocks',
    angularMousewheel: 'bower_components/angular-mousewheel/mousewheel',
    angularResource: 'bower_components/angular-resource/angular-resource',
    angularRoute: 'bower_components/angular-route/angular-route',
    angularBootstrap: 'bower_components/angular-bootstrap/ui-bootstrap',
    angularUIRouter: 'bower_components/angular-ui-router/release/angular-ui-router',
    chartjs: 'bower_components/Chart.js/Chart',
    angularChart: 'bower_components/angular-chart.js/angular-chart',
    perfectScrollbarJquery: 'bower_components/perfect-scrollbar/js/perfect-scrollbar.jquery',
    perfectScrollbar: 'bower_components/perfect-scrollbar/js/perfect-scrollbar',
    jqueryAppear: 'bower_components/jquery_appear/jquery.appear',
    smt: 'bower_components/smt/dist/smt',
    // cant use .  when define paths name
    hamsterjs: 'bower_components/hamsterjs/hamster',
    modenizr: "bower_components/html5-boilerplate/dist/js/vendor/modernizr-2.8.3.min",
    ngStorage: 'bower_components/ngstorage/ngStorage',
    text: 'bower_components/requirejs-text/text',
    angularAnimate: 'bower_components/angular-animate/angular-animate.min',
    // must use 1.3
    //domReady: "bower_components/requirejs-domready/domready"
  },
  map: {
    "angularChart": {
      "chart.js": "chartjs"
    }
  },

  shim: {
    'angular': {
      'exports': 'angular'
    },
    'angularRoute': ['angular'],
    'angularResource': ['angular'],
    'angularUIRouter': ['angular'],
    'angularMocks': {
      deps: ['angular'],
      'exports': 'angular.mock'
    },
    'chartjs': {
      'exports': 'Chart'
    },
    'jqueryAppear': ['jquery'],
    'angularBootstrap': ['angular'],
    'angularAnimate': ['angular'],
    'angularMousewheel': {
      deps: ['angular']
    }
  },
  priority: [
    "angular"
  ],
  deps: this.__karma__ ? allTestFiles : [],
  callback: this.__karma__ ? this.__karma__.start : null,
  baseUrl: this.__karma__ ? '/base/app' : ''
});

require(["app"]);


text:
INSERT INTO Email (id,username,plus,host) VALUES (1,'Steve','NoCRUD','Jazd.com');
INSERT INTO Email (id,username,plus,host) VALUES (2,'Steve','NoCRUD','ADb.Net');


text:
'use strict';
const Code = require('code');
const Joi = require('joi');
const Lab = require('lab');
const Helper = require('../helper.js');

const expect = Code.expect;
const lab = exports.lab = Lab.script();

lab.experiment('file', () => {

    let routes = {
        method: 'POST',
        path: '/test/',
        config: {
            handler: Helper.defaultHandler,
            plugins: {
                'hapi-swagger': {
                    payloadType: 'form'
                }
            },
            tags: ['api'],
            validate: {
                payload: {
                    file: Joi.any()
                        .meta({ swaggerType: 'file' })
                        .required()
                }
            },
            payload: {
                maxBytes: 1048576,
                parse: true,
                output: 'stream'
            }
        }
    };

    lab.test('upload', (done) => {

        Helper.createServer({}, routes, (err, server) => {

            server.inject({ method: 'GET', url: '/swagger.json' }, function (response) {

                //console.log(JSON.stringify(response.result.paths['/test/'].post.parameters));
                expect(err).to.equal(null);
                expect(response.statusCode).to.equal(200);
                expect(response.result.paths['/test/'].post.parameters).to.equal([
                    {
                        'type': 'file',
                        'required': true,
                        'x-meta': {
                            'swaggerType': 'file'
                        },
                        'name': 'file',
                        'in': 'formData'
                    }
                ]);
                Helper.validate(response, done, expect);
            });
        });
    });

    lab.test('upload with binary file type', (done) => {
        routes.config.validate.payload.file = Joi.binary().meta({ swaggerType: 'file' }).required();

        Helper.createServer({}, routes, (err, server) => {

            server.inject({ method: 'GET', url: '/swagger.json' }, function (response) {

                //console.log(JSON.stringify(response.result.paths['/test/'].post.parameters));
                expect(err).to.equal(null);
                expect(response.statusCode).to.equal(200);
                expect(response.result.paths['/test/'].post.parameters).to.equal([
                    {
                        'type': 'file',
                        'format': 'binary',
                        'required': true,
                        'x-meta': {
                            'swaggerType': 'file'
                        },
                        'name': 'file',
                        'in': 'formData'
                    }
                ]);
                Helper.validate(response, done, expect);
            });
        });
    });

    lab.test('file type not fired on other meta properties', (done) => {

        routes.config.validate.payload.file = Joi.any().meta({ anything: 'test' }).required();

        Helper.createServer({}, routes, (err, server) => {

            server.inject({ method: 'GET', url: '/swagger.json' }, function (response) {

                //console.log(JSON.stringify(response.result.paths['/test/']));
                expect(err).to.equal(null);
                expect(response.statusCode).to.equal(200);
                expect(response.result.paths['/test/'].post.parameters).to.equal([
                    {
                        'required': true,
                        'x-meta': {
                            'anything': 'test'
                        },
                        'in': 'formData',
                        'name': 'file',
                        'type': 'string'
                    }
                ]);
                Helper.validate(response, done, expect);
            });
        });
    });

});


text:
'use strict';

// Classifieds controller
angular.module('classifieds').controller('ClassifiedsController', ['$q', '$scope', '$upload', '$stateParams', '$location', 'Authentication', 'Classifieds', 'Categories', 'Families', 'InstrumentTypes',
	function ($q, $scope, $upload, $stateParams, $location, Authentication, Classifieds, Categories, Families, InstrumentTypes) {
		$scope.authentication = Authentication;
		$scope.images = [];

		// Create new Classified
		$scope.create = function () {
			// Create new Classified object
			var classified = new Classifieds({
				shortDescription: this.shortDescription,
				longDescription: this.longDescription,
				price: this.price,
				category: this.category,
				family: this.family,
				instrumentType: this.instrumentType,
				pics: $scope.images
			});

			classified.$save(function(response) {
				$location.path('classifieds/' + response._id);

				// Clear form fields
				$scope.name = '';
			}, function(errorResponse) {
				$scope.error = errorResponse.data.message;
			});
		};

		// Remove existing Classified
		$scope.remove = function (classified) {
			if (classified) {
				classified.$remove();

				for (var i in $scope.classifieds) {
					if ($scope.classifieds [i] === classified) {
						$scope.classifieds.splice(i, 1);
					}
				}
			} else {
				$scope.classified.$remove(function () {
					$location.path('classifieds');
				});
			}
		};

		// Update existing Classified
		$scope.update = function () {
			var classified = $scope.classified;

			classified.$update(function () {
				$location.path('classifieds/' + classified._id);
			}, function (errorResponse) {
				$scope.error = errorResponse.data.message;
			});
		};

		// Find a list of Classifieds
		$scope.find = function () {
			$scope.classifieds = Classifieds.query();
		};

		$scope.loadAdditionalInfo = function () {
			$scope.categories = Categories.query();
			$scope.families = Families.query();
		};

		// Find existing Classified
		$scope.findOne = function () {
			$scope.classified = Classifieds.get({
				classifiedId: $stateParams.classifiedId
			});
			$scope.loadAdditionalInfo();
		};

		/*
		 $scope.$watch('classified.pic', function () {
		 if ($scope.classified.pic && document.getElementById('image-preview')) {
		 document.getElementById('image-preview').innerHTML = '<img class="img-responsive" src="data:' + $scope.classified.pic.contentType + ';base64,' + $scope.classified.pic.data + '"/>';
		 }
		 });
		 */

		$scope.$watch('family', function (newVal) {
			if (newVal) $scope.instrumentTypes = InstrumentTypes.query({family: newVal});
		});

		$scope.$watch('classified.family', function (newVal) {
			if (newVal) $scope.instrumentTypes = InstrumentTypes.query({family: newVal});
		});

		$scope.$watch('files', function () {
			if ($scope.files && $scope.files.length > 0) {

				for (var i in $scope.files) {
					new ImageResizer().resize($scope.files[i], function (imageUrl) {
						//$scope.images.push(imageUrl);
						$scope.images[0] = imageUrl;
						$scope.$apply();
					});
				}
			}
		});
	}
]);


text:
has($attribute)) has-error @endif">

                @if ($errors->has($attribute))

                @endif
                {{ $attributeTitle }}
                @if (isset($options['required']))
                    *
                @endif
                @if(isset($options['tooltip']))
                    ?
                @endif

            @if(isset($options['options']) && count($options['options']) > 0)
                <select class="form-control"
                        name="{{ $attribute }}{{ isset($options['multiple']) ? '[]' : '' }}"
                        id="{{ $attribute }}"
                        @if (isset($options['multiple'])) multiple="multiple" @endif
                        @if (isset($options['required'])) required="required" @endif
                    >
                    @if(!isset($options['required']))
                        <option></option>
                    @endif
                    @foreach ($options['options'] as $optionValue => $option)
                        <option value="{{ $optionValue }}"
                                        @if (
                                                (is_scalar($value) && $value == $optionValue)
                                            ||
                                                (is_array($value) && array_key_exists($optionValue, $value))
                                            ||
                                                (is_array($oldValue) && in_array($value, $oldValue))
                                            ||
                                                ($value instanceof \Illuminate\Database\Eloquent\Model && $optionValue == $value->getKey())
                                            ||
                                                ($value instanceof \Illuminate\Database\Eloquent\Collection && $value->find($optionValue))
                                            ) selected="selected" @endif
                                    >{{ $option }}</option>
                    @endforeach
                </select>

                @if(isset($options['help']))

{!! $options['help'] !!}

                @endif
            @else

                        No options available for {{ $attributeTitle }}!

            @endif

            @if ($errors->has($attribute))

                    {{ $errors->first($attribute) }}

            @endif


text:
<?php

/*
 * This file is part of the Symfony framework.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *
 * This source file is subject to the MIT license that is bundled
 * with this source code in the file LICENSE.
 */

namespace Symfony\Component\DependencyInjection\Exception;

/**
 * This exception is thrown when a non-existent service is requested.
 *
 * @author Johannes M. Schmitt <schmittjoh@gmail.com>
 */
class ServiceNotFoundException extends InvalidArgumentException
{
    private $id;
    private $sourceId;

    public function __construct($id, $sourceId = null)
    {
        if (null === $sourceId) {
            $msg = sprintf('You have requested a non-existent service "%s".', $id);
        } else {
            $msg = sprintf('The service "%s" has a dependency on a non-existent service "%s".', $sourceId, $id);
        }

        parent::__construct($msg);

        $this->id = $id;
        $this->sourceId = $sourceId;
    }

    public function getId()
    {
        return $this->id;
    }

    public function getSourceId()
    {
        return $this->sourceId;
    }
}


text:
namespace base {
class Clock;
class TickClock;
class Value;
}

namespace net {

class HttpServerPropertiesManager;
class IPAddress;
class NetLog;
struct SSLConfig;

struct NET_EXPORT SupportsQuic {
  SupportsQuic() : used_quic(false) {}
  SupportsQuic(bool used_quic, const std::string& address)
      : used_quic(used_quic), address(address) {}

  bool Equals(const SupportsQuic& other) const {
    return used_quic == other.used_quic && address == other.address;
  }

  bool used_quic;
  std::string address;
};

struct NET_EXPORT ServerNetworkStats {
  ServerNetworkStats() : bandwidth_estimate(quic::QuicBandwidth::Zero()) {}

  bool operator==(const ServerNetworkStats& other) const {
    return srtt == other.srtt && bandwidth_estimate == other.bandwidth_estimate;
  }

  bool operator!=(const ServerNetworkStats& other) const {
    return !this->operator==(other);
  }

  base::TimeDelta srtt;
  quic::QuicBandwidth bandwidth_estimate;
};

typedef std::vector<AlternativeService> AlternativeServiceVector;

// Store at most 200 MRU RecentlyBrokenAlternativeServices in memory and disk.
// This ideally would be with the other constants in HttpServerProperties, but
// has to go here instead of prevent a circular dependency.
const int kMaxRecentlyBrokenAlternativeServiceEntries = 200;

// Store at most 5 MRU QUIC servers by default. This is mainly used by cronet.
const int kDefaultMaxQuicServerEntries = 5;

// The interface for setting/retrieving the HTTP server properties.
// Currently, this class manages servers':
// * HTTP/2 support;
// * Alternative Service support;
// * QUIC data (like ServerNetworkStats and QuicServerInfo).
//
// Optionally retrieves and saves properties from/to disk. This class is not
// threadsafe.
class NET_EXPORT HttpServerProperties
    : public BrokenAlternativeServices::Delegate {
 public:
  // Store at most 500 MRU ServerInfos in memory and disk.
  static const int kMaxServerInfoEntries = 500;

  // Provides an interface to interact with persistent preferences storage
  // implemented by the embedder. The prefs are assumed not to have been loaded
  // before HttpServerPropertiesManager construction.
  class NET_EXPORT PrefDelegate {
   public:
    virtual ~PrefDelegate();

    // Returns the branch of the preferences system for the server properties.
    // Returns nullptr if the pref system has no data for the server properties.
    virtual const base::DictionaryValue* GetServerProperties() const = 0;

    // Sets the server properties to the given value. If |callback| is
    // non-empty, flushes data to persistent storage and invokes |callback|
    // asynchronously when complete.
    virtual void SetServerProperties(const base::DictionaryValue& value,
                                     base::OnceClosure callback) = 0;

    // Starts listening for prefs to be loaded. If prefs are already loaded,
    // |pref_loaded_callback| will be invoked asynchronously. Callback will be
    // invoked even if prefs fail to load. Will only be called once by the
    // HttpServerPropertiesManager.
    virtual void WaitForPrefLoad(base::OnceClosure pref_loaded_callback) = 0;
  };

  // Contains metadata about a particular server. Note that all methods that
  // take a "SchemeHostPort" expect schemes of ws and wss to be mapped to http
  // and https, respectively. See GetNormalizedSchemeHostPort().
  struct NET_EXPORT ServerInfo {
    ServerInfo();
    ServerInfo(const ServerInfo& server_info);
    ServerInfo(ServerInfo&& server_info);
    ~ServerInfo();

    // Returns true if no fields are populated.
    bool empty() const;

    // Used in tests.
    bool operator==(const ServerInfo& other) const;

    // IMPORTANT:  When adding a field here, be sure to update
    // HttpServerProperties::OnServerInfoLoaded() as well as
    // HttpServerPropertiesManager to correctly load/save the from/to the pref
    // store.

    // Whether or not a server is known to support H2/SPDY. False indicates
    // known lack of support, true indicates known support, and not set
    // indicates unknown. The difference between false and not set only matters
    // when loading from disk, when an initialized false value will take
    // priority over a not set value.
    base::Optional<bool> supports_spdy;

    // True if the server has previously indicated it required HTTP/1.1. Unlike
    // other fields, not persisted to disk.
    base::Optional<bool> requires_http11;

    base::Optional<AlternativeServiceInfoVector> alternative_services;
    base::Optional<ServerNetworkStats> server_network_stats;
  };

  struct NET_EXPORT ServerInfoMapKey {
    // If |use_network_isolation_key| is false, an empty NetworkIsolationKey is
    // used instead of |network_isolation_key|. Note that |server| can be passed
    // in via std::move(), since most callsites can pass a recently created
    // SchemeHostPort.
    ServerInfoMapKey(url::SchemeHostPort server,
                     const NetworkIsolationKey& network_isolation_key,
                     bool use_network_isolation_key);
    ~ServerInfoMapKey();

    bool operator<(const ServerInfoMapKey& other) const;

    // IMPORTANT: The constructor normalizes the scheme so that "ws" is replaced
    // by "http" and "wss" by "https", so this should never be compared directly
    // with values passed into to HttpServerProperties methods.
    url::SchemeHostPort server;

    NetworkIsolationKey network_isolation_key;
  };

  class NET_EXPORT ServerInfoMap
      : public base::MRUCache<ServerInfoMapKey, ServerInfo> {
   public:
    ServerInfoMap();

    // If there's an entry corresponding to |key|, brings that entry to the
    // front and returns an iterator to it. Otherwise, inserts an empty
    // ServerInfo using |key|, and returns an iterator to it.
    iterator GetOrPut(const ServerInfoMapKey& key);

    // Erases the ServerInfo identified by |server_info_it| if no fields have
    // data. The iterator must point to an entry in the map. Regardless of
    // whether the entry is removed or not, returns iterator for the next entry.
    iterator EraseIfEmpty(iterator server_info_it);

   private:
    DISALLOW_COPY_AND_ASSIGN(ServerInfoMap);
  };

  struct NET_EXPORT QuicServerInfoMapKey {
    // If |use_network_isolation_key| is false, an empty NetworkIsolationKey is
    // used instead of |network_isolation_key|.
    QuicServerInfoMapKey(const quic::QuicServerId& server_id,
                         const NetworkIsolationKey& network_isolation_key,
                         bool use_network_isolation_key);
    ~QuicServerInfoMapKey();

    bool operator<(const QuicServerInfoMapKey& other) const;

    // Used in tests.
    bool operator==(const QuicServerInfoMapKey& other) const;

    quic::QuicServerId server_id;
    NetworkIsolationKey network_isolation_key;
  };

  // Max number of quic servers to store is not hardcoded and can be set.
  // Because of this, QuicServerInfoMap will not be a subclass of MRUCache.
  // Separate from ServerInfoMap because the key includes privacy mode (Since
  // this is analogous to the SSL session cache, which has separate caches for
  // privacy mode), and each entry can be quite large, so it has its own size
  // limit, which is much smaller than the ServerInfoMap's limit.
  typedef base::MRUCache<QuicServerInfoMapKey, std::string> QuicServerInfoMap;

  // If a |pref_delegate| is specified, it will be used to read/write the
  // properties to a pref file. Writes are rate limited to improve performance.
  //
  // |tick_clock| is used for setting expiration times and scheduling the
  // expiration of broken alternative services. If null, default clock will be
  // used.
  //
  // |clock| is used for converting base::TimeTicks to base::Time for
  // wherever base::Time is preferable.
  HttpServerProperties(std::unique_ptr<PrefDelegate> pref_delegate = nullptr,
                       NetLog* net_log = nullptr,
                       const base::TickClock* tick_clock = nullptr,
                       base::Clock* clock = nullptr);

  ~HttpServerProperties() override;

  // Deletes all data. If |callback| is non-null, flushes data to disk
  // and invokes the callback asynchronously once changes have been written to
  // disk.
  void Clear(base::OnceClosure callback);

  // Returns true if |server|, in the context of |network_isolation_key|, has
  // previously supported a network protocol which honors request
  // prioritization.
  //
  // Note that this also implies that the server supports request
  // multiplexing, since priorities imply a relationship between
  // multiple requests.
  bool SupportsRequestPriority(
      const url::SchemeHostPort& server,
      const net::NetworkIsolationKey& network_isolation_key);

  // Returns the value set by SetSupportsSpdy(). If not set, returns false.
  bool GetSupportsSpdy(const url::SchemeHostPort& server,
                       const net::NetworkIsolationKey& network_isolation_key);

  // Records whether |server| supports H2 or not. Information is restricted to
  // the context of |network_isolation_key|, to prevent cross-site information
  // leakage.
  void SetSupportsSpdy(const url::SchemeHostPort& server,
                       const net::NetworkIsolationKey& network_isolation_key,
                       bool supports_spdy);

  // Returns true if |server| has required HTTP/1.1 via HTTP/2 error code, in
  // the context of |network_isolation_key|.
  bool RequiresHTTP11(const url::SchemeHostPort& server,
                      const net::NetworkIsolationKey& network_isolation_key);

  // Require HTTP/1.1 on subsequent connections, in the context of
  // |network_isolation_key|.  Not persisted.
  void SetHTTP11Required(const url::SchemeHostPort& server,
                         const net::NetworkIsolationKey& network_isolation_key);

  // Modify SSLConfig to force HTTP/1.1 if necessary.
  void MaybeForceHTTP11(const url::SchemeHostPort& server,
                        const net::NetworkIsolationKey& network_isolation_key,
                        SSLConfig* ssl_config);

  // Return all alternative services for |origin|, learned in the context of
  // |network_isolation_key|, including broken ones. Returned alternative
  // services never have empty hostnames.
  AlternativeServiceInfoVector GetAlternativeServiceInfos(
      const url::SchemeHostPort& origin,
      const net::NetworkIsolationKey& network_isolation_key);

  // Set a single HTTP/2 alternative service for |origin|.  Previous
  // alternative services for |origin| are discarded.
  // |alternative_service.host| may be empty.
  void SetHttp2AlternativeService(
      const url::SchemeHostPort& origin,
      const NetworkIsolationKey& network_isolation_key,
      const AlternativeService& alternative_service,
      base::Time expiration);

  // Set a single QUIC alternative service for |origin|.  Previous alternative
  // services for |origin| are discarded.
  // |alternative_service.host| may be empty.
  void SetQuicAlternativeService(
      const url::SchemeHostPort& origin,
      const NetworkIsolationKey& network_isolation_key,
      const AlternativeService& alternative_service,
      base::Time expiration,
      const quic::ParsedQuicVersionVector& advertised_versions);

  // Set alternative services for |origin|, learned in the context of
  // |network_isolation_key|.  Previous alternative services for |origin| are
  // discarded. Hostnames in |alternative_service_info_vector| may be empty.
  // |alternative_service_info_vector| may be empty.
  void SetAlternativeServices(
      const url::SchemeHostPort& origin,
      const net::NetworkIsolationKey& network_isolation_key,
      const AlternativeServiceInfoVector& alternative_service_info_vector);

  // Marks |alternative_service| as broken in the context of
  // |network_isolation_key|. |alternative_service.host| must not be empty.
  void MarkAlternativeServiceBroken(
      const AlternativeService& alternative_service,
      const net::NetworkIsolationKey& network_isolation_key);

  // Marks |alternative_service| as broken in the context of
  // |network_isolation_key| until the default network changes.
  // |alternative_service.host| must not be empty.
  void MarkAlternativeServiceBrokenUntilDefaultNetworkChanges(
      const AlternativeService& alternative_service,
      const net::NetworkIsolationKey& network_isolation_key);

  // Marks |alternative_service| as recently broken in the context of
  // |network_isolation_key|. |alternative_service.host| must not be empty.
  void MarkAlternativeServiceRecentlyBroken(
      const AlternativeService& alternative_service,
      const net::NetworkIsolationKey& network_isolation_key);

  // Returns true iff |alternative_service| is currently broken in the context
  // of |network_isolation_key|. |alternative_service.host| must not be empty.
  bool IsAlternativeServiceBroken(
      const AlternativeService& alternative_service,
      const net::NetworkIsolationKey& network_isolation_key) const;

  // Returns true iff |alternative_service| was recently broken in the context
  // of |network_isolation_key|. |alternative_service.host| must not be empty.
  bool WasAlternativeServiceRecentlyBroken(
      const AlternativeService& alternative_service,
      const net::NetworkIsolationKey& network_isolation_key);

  // Confirms that |alternative_service| is working in the context of
  // |network_isolation_key|. |alternative_service.host| must not be empty.
  void ConfirmAlternativeService(
      const AlternativeService& alternative_service,
      const net::NetworkIsolationKey& network_isolation_key);

  // Called when the default network changes.
  // Clears all the alternative services that were marked broken until the
  // default network changed.
  void OnDefaultNetworkChanged();

  // Returns all alternative service mappings as human readable strings.
  // Empty alternative service hostnames will be printed as such.
  std::unique_ptr<base::Value> GetAlternativeServiceInfoAsValue() const;

  // Tracks the last local address when QUIC was known to work. The address
  // cannot be set to an empty address - use
  // ClearLastLocalAddressWhenQuicWorked() if it needs to be cleared.
  bool WasLastLocalAddressWhenQuicWorked(const IPAddress& local_address) const;
  bool HasLastLocalAddressWhenQuicWorked() const;
  void SetLastLocalAddressWhenQuicWorked(
      IPAddress last_local_address_when_quic_worked);
  void ClearLastLocalAddressWhenQuicWorked();

  // Sets |stats| for |server|.
  void SetServerNetworkStats(const url::SchemeHostPort& server,
                             const NetworkIsolationKey& network_isolation_key,
                             ServerNetworkStats stats);

  // Clears any stats for |server|.
  void ClearServerNetworkStats(
      const url::SchemeHostPort& server,
      const NetworkIsolationKey& network_isolation_key);

  // Returns any stats for |server| or nullptr if there are none.
  const ServerNetworkStats* GetServerNetworkStats(
      const url::SchemeHostPort& server,
      const NetworkIsolationKey& network_isolation_key);

  // Save QuicServerInfo (in std::string form) for the given |server_id|, in the
  // context of |network_isolation_key|.
  void SetQuicServerInfo(const quic::QuicServerId& server_id,
                         const NetworkIsolationKey& network_isolation_key,
                         const std::string& server_info);

  // Get QuicServerInfo (in std::string form) for the given |server_id|, in the
  // context of |network_isolation_key|.
  const std::string* GetQuicServerInfo(
      const quic::QuicServerId& server_id,
      const NetworkIsolationKey& network_isolation_key);

  // Returns all persistent QuicServerInfo objects.
  const QuicServerInfoMap& quic_server_info_map() const;

  // Returns the number of server configs (QuicServerInfo objects) persisted.
  size_t max_server_configs_stored_in_properties() const;

  // Sets the number of server configs (QuicServerInfo objects) to be persisted.
  void SetMaxServerConfigsStoredInProperties(
      size_t max_server_configs_stored_in_properties);

  // Returns whether HttpServerProperties is initialized.
  bool IsInitialized() const;

  // BrokenAlternativeServices::Delegate method.
  void OnExpireBrokenAlternativeService(
      const AlternativeService& expired_alternative_service,
      const NetworkIsolationKey& network_isolation_key) override;

  static base::TimeDelta GetUpdatePrefsDelayForTesting();

  // Test-only routines that call the methods used to load the specified
  // field(s) from a prefs file. Unlike OnPrefsLoaded(), these may be invoked
  // multiple times.
  void OnServerInfoLoadedForTesting(
      std::unique_ptr<ServerInfoMap> server_info_map) {
    OnServerInfoLoaded(std::move(server_info_map));
  }
  void OnLastLocalAddressWhenQuicWorkedForTesting(
      const IPAddress& last_local_address_when_quic_worked) {
    OnLastLocalAddressWhenQuicWorkedLoaded(last_local_address_when_quic_worked);
  }
  void OnQuicServerInfoMapLoadedForTesting(
      std::unique_ptr<QuicServerInfoMap> quic_server_info_map) {
    OnQuicServerInfoMapLoaded(std::move(quic_server_info_map));
  }
  void OnBrokenAndRecentlyBrokenAlternativeServicesLoadedForTesting(
      std::unique_ptr<BrokenAlternativeServiceList>
          broken_alternative_service_list,
      std::unique_ptr<RecentlyBrokenAlternativeServices>
          recently_broken_alternative_services) {
    OnBrokenAndRecentlyBrokenAlternativeServicesLoaded(
        std::move(broken_alternative_service_list),
        std::move(recently_broken_alternative_services));
  }

  const std::string* GetCanonicalSuffixForTesting(
      const std::string& host) const {
    return GetCanonicalSuffix(host);
  }

  const ServerInfoMap& server_info_map_for_testing() const {
    return server_info_map_;
  }

  // TODO(mmenke): Look into removing this.
  HttpServerPropertiesManager* properties_manager_for_testing() {
    return properties_manager_.get();
  }

 private:
  // TODO (wangyix): modify HttpServerProperties unit tests so this
  // friendness is no longer required.
  friend class HttpServerPropertiesPeer;

  typedef base::flat_map<ServerInfoMapKey, url::SchemeHostPort> CanonicalMap;
  typedef base::flat_map<QuicServerInfoMapKey, quic::QuicServerId>
      QuicCanonicalMap;
  typedef std::vector<std::string> CanonicalSuffixList;

  // Internal implementations of public methods. SchemeHostPort argument must be
  // normalized before calling (ws/wss replaced with http/https). Use wrapped
  // functions instead of putting the normalization in the public functions to
  // reduce chance of regression - normalization in ServerInfoMapKey's
  // constructor would leave |server.scheme| as wrong if not access through the
  // key, and explicit normalization to create |normalized_server| means the one
  // with the incorrect scheme would still be available.
  bool GetSupportsSpdyInternal(
      url::SchemeHostPort server,
      const net::NetworkIsolationKey& network_isolation_key);
  void SetSupportsSpdyInternal(
      url::SchemeHostPort server,
      const net::NetworkIsolationKey& network_isolation_key,
      bool supports_spdy);
  bool RequiresHTTP11Internal(
      url::SchemeHostPort server,
      const net::NetworkIsolationKey& network_isolation_key);
  void SetHTTP11RequiredInternal(
      url::SchemeHostPort server,
      const net::NetworkIsolationKey& network_isolation_key);
  void MaybeForceHTTP11Internal(
      url::SchemeHostPort server,
      const net::NetworkIsolationKey& network_isolation_key,
      SSLConfig* ssl_config);
  AlternativeServiceInfoVector GetAlternativeServiceInfosInternal(
      const url::SchemeHostPort& origin,
      const net::NetworkIsolationKey& network_isolation_key);
  void SetAlternativeServicesInternal(
      const url::SchemeHostPort& origin,
      const net::NetworkIsolationKey& network_isolation_key,
      const AlternativeServiceInfoVector& alternative_service_info_vector);
  void SetServerNetworkStatsInternal(
      url::SchemeHostPort server,
      const NetworkIsolationKey& network_isolation_key,
      ServerNetworkStats stats);
  void ClearServerNetworkStatsInternal(
      url::SchemeHostPort server,
      const NetworkIsolationKey& network_isolation_key);
  const ServerNetworkStats* GetServerNetworkStatsInternal(
      url::SchemeHostPort server,
      const NetworkIsolationKey& network_isolation_key);

  // Helper functions to use the passed in parameters and
  // |use_network_isolation_key_| to create a [Quic]ServerInfoMapKey.
  ServerInfoMapKey CreateServerInfoKey(
      const url::SchemeHostPort& server,
      const NetworkIsolationKey& network_isolation_key) const;
  QuicServerInfoMapKey CreateQuicServerInfoKey(
      const quic::QuicServerId& server_id,
      const NetworkIsolationKey& network_isolation_key) const;

  // Return the iterator for |server| in the context of |network_isolation_key|,
  // or for its canonical host, or end. Skips over ServerInfos without
  // |alternative_service_info| populated.
  ServerInfoMap::const_iterator GetIteratorWithAlternativeServiceInfo(
      const url::SchemeHostPort& server,
      const net::NetworkIsolationKey& network_isolation_key);

  // Return the canonical host for |server|  in the context of
  // |network_isolation_key|, or end if none exists.
  CanonicalMap::const_iterator GetCanonicalAltSvcHost(
      const url::SchemeHostPort& server,
      const net::NetworkIsolationKey& network_isolation_key) const;

  // Return the canonical host with the same canonical suffix as |server|.
  // The returned canonical host can be used to search for server info in
  // |quic_server_info_map_|. Return 'end' the host doesn't exist.
  QuicCanonicalMap::const_iterator GetCanonicalServerInfoHost(
      const QuicServerInfoMapKey& key) const;

  // Remove the canonical alt-svc host for |server| with
  // |network_isolation_key|.
  void RemoveAltSvcCanonicalHost(
      const url::SchemeHostPort& server,
      const NetworkIsolationKey& network_isolation_key);

  // Update |canonical_server_info_map_| with the new canonical host.
  // The |key| should have the corresponding server info associated with it
  // in |quic_server_info_map_|. If |canonical_server_info_map_| doesn't
  // have an entry associated with |key|, the method will add one.
  void UpdateCanonicalServerInfoMap(const QuicServerInfoMapKey& key);

  // Returns the canonical host suffix for |host|, or nullptr if none
  // exists.
  const std::string* GetCanonicalSuffix(const std::string& host) const;

  void OnPrefsLoaded(std::unique_ptr<ServerInfoMap> server_info_map,
                     const IPAddress& last_local_address_when_quic_worked,
                     std::unique_ptr<QuicServerInfoMap> quic_server_info_map,
                     std::unique_ptr<BrokenAlternativeServiceList>
                         broken_alternative_service_list,
                     std::unique_ptr<RecentlyBrokenAlternativeServices>
                         recently_broken_alternative_services);

  // These methods are called by OnPrefsLoaded to handle merging properties
  // loaded from prefs with what has been learned while waiting for prefs to
  // load.
  void OnServerInfoLoaded(std::unique_ptr<ServerInfoMap> server_info_map);
  void OnLastLocalAddressWhenQuicWorkedLoaded(
      const IPAddress& last_local_address_when_quic_worked);
  void OnQuicServerInfoMapLoaded(
      std::unique_ptr<QuicServerInfoMap> quic_server_info_map);
  void OnBrokenAndRecentlyBrokenAlternativeServicesLoaded(
      std::unique_ptr<BrokenAlternativeServiceList>
          broken_alternative_service_list,
      std::unique_ptr<RecentlyBrokenAlternativeServices>
          recently_broken_alternative_services);

  // Queue a delayed call to WriteProperties(). If |is_initialized_| is false,
  // or |properties_manager_| is nullptr, or there's already a queued call to
  // WriteProperties(), does nothing.
  void MaybeQueueWriteProperties();

  // Writes cached state to |properties_manager_|, which must not be null.
  // Invokes |callback| on completion, if non-null.
  void WriteProperties(base::OnceClosure callback) const;

  const base::TickClock* tick_clock_;  // Unowned
  base::Clock* clock_;                 // Unowned

  // Cached value of kPartitionHttpServerPropertiesByNetworkIsolationKey
  // feature. Cached to improve performance.
  const bool use_network_isolation_key_;

  // Set to true once initial properties have been retrieved from disk by
  // |properties_manager_|. Always true if |properties_manager_| is nullptr.
  bool is_initialized_;

  // Queue a write when resources finish loading. Set to true when
  // MaybeQueueWriteProperties() is invoked while still waiting on
  // initialization to complete.
  bool queue_write_on_load_;

  // Used to load/save properties from/to preferences. May be nullptr.
  std::unique_ptr<HttpServerPropertiesManager> properties_manager_;

  ServerInfoMap server_info_map_;

  BrokenAlternativeServices broken_alternative_services_;

  IPAddress last_local_address_when_quic_worked_;
  // Contains a map of servers which could share the same alternate protocol.
  // Map from a Canonical scheme/host/port/NIK (host is some postfix of host
  // names) to an actual origin, which has a plausible alternate protocol
  // mapping.
  CanonicalMap canonical_alt_svc_map_;

  // Contains list of suffixes (for example ".c.youtube.com",
  // ".googlevideo.com", ".googleusercontent.com") of canonical hostnames.
  const CanonicalSuffixList canonical_suffixes_;

  QuicServerInfoMap quic_server_info_map_;

  // Maps canonical suffixes to host names that have the same canonical suffix
  // and have a corresponding entry in |quic_server_info_map_|. The map can be
  // used to quickly look for server info for hosts that share the same
  // canonical suffix but don't have exact match in |quic_server_info_map_|. The
  // map exists solely to improve the search performance. It only contains
  // derived data that can be recalculated by traversing
  // |quic_server_info_map_|.
  QuicCanonicalMap canonical_server_info_map_;

  size_t max_server_configs_stored_in_properties_;

  // Used to post calls to WriteProperties().
  base::OneShotTimer prefs_update_timer_;

  THREAD_CHECKER(thread_checker_);

  DISALLOW_COPY_AND_ASSIGN(HttpServerProperties);
};

}  // namespace net

#endif  // NET_HTTP_HTTP_SERVER_PROPERTIES_H_


text:
package org.apereo.cas.ticket;

import org.apereo.cas.authentication.Authentication;

import com.fasterxml.jackson.annotation.JsonIdentityInfo;
import com.fasterxml.jackson.annotation.JsonIgnore;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import com.fasterxml.jackson.annotation.ObjectIdGenerators;
import lombok.EqualsAndHashCode;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;
import lombok.val;

import javax.persistence.Column;
import javax.persistence.Id;
import javax.persistence.Lob;
import javax.persistence.MappedSuperclass;
import java.time.ZoneOffset;
import java.time.ZonedDateTime;

/**
 * Abstract implementation of a ticket that handles all ticket state for
 * policies. Also incorporates properties common among all tickets. As this is
 * an abstract class, it cannot be created. It is recommended that
 * implementations of the Ticket interface extend the AbstractTicket as it
 * handles common functionality amongst different ticket types (such as state
 * updating).
 * <p>
 * AbstractTicket does not provide a logger instance to
 * avoid instantiating many such Loggers at runtime (there will be many instances
 * of subclasses of AbstractTicket in a typical running CAS server).  Instead
 * subclasses should use static Logger instances.
 *
 * @author Scott Battaglia
 * @since 3.0.0
 */
@MappedSuperclass
@JsonIdentityInfo(generator = ObjectIdGenerators.IntSequenceGenerator.class)
@JsonIgnoreProperties(ignoreUnknown = true)
@NoArgsConstructor
@EqualsAndHashCode(of = {"id"})
@Setter
public abstract class AbstractTicket implements Ticket, TicketState {

    private static final long serialVersionUID = -8506442397878267555L;

    /**
     * The {@link ExpirationPolicy} this ticket is associated with.
     **/
    @Lob
    @Column(name = "EXPIRATION_POLICY", length = Integer.MAX_VALUE, nullable = false)
    @Getter
    private ExpirationPolicy expirationPolicy;

    /**
     * The unique identifier for this ticket.
     */
    @Id
    @Column(name = "ID", nullable = false)
    @Getter
    private String id;

    /**
     * The last time this ticket was used.
     */
    @Column(name = "LAST_TIME_USED", length = Integer.MAX_VALUE)
    @Getter
    private ZonedDateTime lastTimeUsed;

    /**
     * The previous last time this ticket was used.
     */
    @Column(name = "PREVIOUS_LAST_TIME_USED", length = Integer.MAX_VALUE)
    @Getter
    private ZonedDateTime previousTimeUsed;

    /**
     * The time the ticket was created.
     */
    @Column(name = "CREATION_TIME", length = Integer.MAX_VALUE)
    @Getter
    private ZonedDateTime creationTime;

    /**
     * The number of times this was used.
     */
    @Column(name = "NUMBER_OF_TIMES_USED")
    @Getter
    private int countOfUses;

    /**
     * Flag to enforce manual expiration.
     */
    @Column(name = "EXPIRED", nullable = false)
    private Boolean expired = Boolean.FALSE;

    public AbstractTicket(final String id, final ExpirationPolicy expirationPolicy) {
        this.id = id;
        this.creationTime = ZonedDateTime.now(ZoneOffset.UTC);
        this.lastTimeUsed = ZonedDateTime.now(ZoneOffset.UTC);
        this.expirationPolicy = expirationPolicy;
    }

    @Override
    public void update() {
        this.previousTimeUsed = this.lastTimeUsed;
        this.lastTimeUsed = ZonedDateTime.now(ZoneOffset.UTC);
        this.countOfUses++;

        val ticketGrantingTicket = getTicketGrantingTicket();
        if (ticketGrantingTicket != null && !ticketGrantingTicket.isExpired()) {
            val state = TicketState.class.cast(ticketGrantingTicket);
            state.update();
        }
    }

    @Override
    public boolean isExpired() {
        return this.expirationPolicy.isExpired(this) || isExpiredInternal();
    }

    @JsonIgnore
    protected boolean isExpiredInternal() {
        return this.expired;
    }

    @Override
    public int compareTo(final Ticket o) {
        return getId().compareTo(o.getId());
    }

    @Override
    public String toString() {
        return getId();
    }

    @Override
    public Authentication getAuthentication() {
        val ticketGrantingTicket = getTicketGrantingTicket();
        return ticketGrantingTicket != null
            ? ticketGrantingTicket.getAuthentication()
            : null;
    }

    @Override
    public TicketGrantingTicket getTicketGrantingTicket() {
        return null;
    }

    @Override
    public void markTicketExpired() {
        this.expired = Boolean.TRUE;
    }
}


text:
Edit Topic

        <form data-ng-submit="update()" novalidate>
            <fieldset>

                    Title

                        <input type="text" data-ng-model="topic.title" id="title" class="form-control" placeholder="Title" required>

                    Description

                        <textarea data-ng-model="topic.description" id="description" class="form-control" rows="4" placeholder="Description"></textarea>

                    Content Type

                        <input type="hidden" data-ui-select2="contentTypeOptions" data-ng-model="topic.content.type" id="content_type" class="form-control">

                    Content Reference

                        <input type="text" data-ng-model="topic.content.reference" id="content_reference" class="form-control" placeholder="Content Reference" required>

                        <input type="submit" class="btn btn-primary">

            </fieldset>
        </form>


text:
module Magento
  # http://www.magentocommerce.com/wiki/doc/webservices-api/api/cart
  # 1001   Can not make operation because store is not exists
  # 1002   Can not make operation because quote is not exists
  # 1041   Customer is not set.
  # 1042   The customer's identifier is not valid or customer is not existed
  # 1043   Customer could not be created.
  # 1044   Customer data is not valid.
  # 1045   Customer's mode is unknown
  # 1051   Customer address data is empty.
  # 1052   Customer's address data is not valid.
  # 1053   The customer's address identifier is not valid
  # 1054   Customer address is not set.
  # 1055   Customer address identifier do not belong customer, which set in quote
  class CartCustomer < Base
    # cart_customer.set
    # Add Customer Information into shopping cart
    #
    # Return: boolean
    #
    # Arguments:
    #
    # int quoteId - Shopping Cart Id (Quote Id)
    # CartCustomerEntity customerData - an associative array with customer information
    # mixed (int | string) storeView - Store view Id or code (optional)
    def set(*args)
      commit('set', *args)
    end

    # cart_customer.addresses
    # Set customer's addresses (shipping, billing) in shopping cart
    #
    # Return: boolean
    #
    # Arguments:
    #
    # int quoteId - Shopping Cart Id (Quote Id)
    # array of CartCustomerAddressEntity customerAddressData - an array with list of CartCustomerAddressEntity
    # mixed (int | string) storeView - Store view Id or code (optional)
    def addresses(*args)
      commit("addresses", *args)
    end
  end
end


text:
module.exports = function readfile (filename, use_include_path, context) {
  // http://kevin.vanzonneveld.net
  // +   original by: Brett Zamir (http://brett-zamir.me)
  // -    depends on: echo
  // *     example 1: readfile('http://kevin.vanzonneveld.net/pj_test_supportfile_1.htm');
  // *     returns 1: '123'

  var read_data = this.file_get_contents(filename, use_include_path, context); // bitwise-or use_include_path?
  this.echo(read_data);
  return read_data;
}


text:
HOSTNAME=$1

export SUDO='true'
export THIN='false'
export PYTHON='false'
export PYPY='false'
export ALL_MYSQL_PRIVS='true'

./prepare_node.sh "$HOSTNAME"

./restrict_memory.sh


text:
package org.dspace.app.xmlui.aspect.viewArtifacts;

import org.apache.cocoon.caching.CacheableProcessingComponent;
import org.apache.cocoon.environment.ObjectModelHelper;
import org.apache.cocoon.environment.Request;
import org.apache.cocoon.util.HashUtil;
import org.apache.excalibur.source.SourceValidity;
import org.apache.excalibur.source.impl.validity.NOPValidity;
import org.dspace.app.util.Util;
import org.dspace.app.xmlui.cocoon.AbstractDSpaceTransformer;
import org.dspace.app.xmlui.utils.HandleUtil;
import org.dspace.app.xmlui.utils.UIException;
import org.dspace.app.xmlui.wing.WingException;
import org.dspace.app.xmlui.wing.element.Options;
import org.dspace.app.xmlui.wing.element.PageMeta;
import org.dspace.authorize.AuthorizeException;
import org.dspace.content.Collection;
import org.dspace.content.Community;
import org.dspace.content.DSpaceObject;
import org.dspace.content.Item;
import org.dspace.core.ConfigurationManager;
import org.xml.sax.SAXException;

import java.io.IOException;
import java.io.Serializable;
import java.sql.SQLException;

/**
 * This transform applys the basic navigational links that should be available
 * on all pages generated by DSpace.
 *
 * @author Scott Phillips
 * @author Kevin Van de Velde (kevin at atmire dot com)
 * @author Mark Diggory (markd at atmire dot com)
 * @author Ben Bosman (ben at atmire dot com)
 */
public class Navigation extends AbstractDSpaceTransformer implements CacheableProcessingComponent {

    /**
     * Generate the unique caching key.
     * This key must be unique inside the space of this component.
     */
    public Serializable getKey() {
        try {
            Request request = ObjectModelHelper.getRequest(objectModel);
            String key = request.getScheme() + request.getServerName() + request.getServerPort() + request.getSitemapURI() + request.getQueryString();

            DSpaceObject dso = HandleUtil.obtainHandle(objectModel);
            if (dso != null)
            {
                key += "-" + dso.getHandle();
            }

            return HashUtil.hash(key);
        }
        catch (SQLException sqle)
        {
            // Ignore all errors and just return that the component is not cachable.
            return "0";
        }
    }

    /**
     * Generate the cache validity object.
     *
     * The cache is always valid.
     */
    public SourceValidity getValidity() {
        return NOPValidity.SHARED_INSTANCE;
    }

        public void addOptions(Options options) throws SAXException, WingException,
            UIException, SQLException, IOException, AuthorizeException
    {
        /* Create skeleton menu structure to ensure consistent order between aspects,
         * even if they are never used
         */
        options.addList("browse");
        options.addList("account");
        options.addList("context");
        options.addList("administrative");
    }

    /**
     * Insure that the context path is added to the page meta.
     */
    public void addPageMeta(PageMeta pageMeta) throws SAXException,
            WingException, UIException, SQLException, IOException,
            AuthorizeException
    {
        // FIXME: I don't think these should be set here, but there needed and I'm
        // not sure where else it could go. Perhaps the linkResolver?
        Request request = ObjectModelHelper.getRequest(objectModel);
        pageMeta.addMetadata("contextPath").addContent(contextPath);
        pageMeta.addMetadata("request","queryString").addContent(request.getQueryString());
        pageMeta.addMetadata("request","scheme").addContent(request.getScheme());
        pageMeta.addMetadata("request","serverPort").addContent(request.getServerPort());
        pageMeta.addMetadata("request","serverName").addContent(request.getServerName());
        pageMeta.addMetadata("request","URI").addContent(request.getSitemapURI());

        String dspaceVersion = Util.getSourceVersion();
        if (dspaceVersion != null)
        {
            pageMeta.addMetadata("dspace","version").addContent(dspaceVersion);
        }

        String analyticsKey = ConfigurationManager.getProperty("xmlui.google.analytics.key");
        if (analyticsKey != null && analyticsKey.length() > 0)
        {
                analyticsKey = analyticsKey.trim();
                pageMeta.addMetadata("google","analytics").addContent(analyticsKey);
        }

        // add metadata for OpenSearch auto-discovery links if enabled
        if (ConfigurationManager.getBooleanProperty("websvc.opensearch.autolink"))
        {
            pageMeta.addMetadata("opensearch", "shortName").addContent(
                                ConfigurationManager.getProperty("websvc.opensearch.shortname"));
            pageMeta.addMetadata("opensearch", "context").addContent(
                        ConfigurationManager.getProperty("websvc.opensearch.svccontext"));
        }

        pageMeta.addMetadata("page","contactURL").addContent(contextPath + "/contact");
        pageMeta.addMetadata("page","feedbackURL").addContent(contextPath + "/feedback");

        DSpaceObject dso = HandleUtil.obtainHandle(objectModel);
        if (dso != null)
        {
            if (dso instanceof Item)
            {
                pageMeta.addMetadata("focus","object").addContent("hdl:"+dso.getHandle());
                this.getObjectManager().manageObject(dso);
                dso = ((Item) dso).getOwningCollection();
            }

            if (dso instanceof Collection || dso instanceof Community)
            {
                pageMeta.addMetadata("focus","container").addContent("hdl:"+dso.getHandle());
                this.getObjectManager().manageObject(dso);
            }
        }
    }
}


text:
<?php

use yii\db\Migration;

/**
 * Handles the creation for table `tb_bn_solicitud_descargo`.
 */
class m161016_193902_create_TB_BN_SOLICITUD_DESCARGO_table extends Migration
{
    /**
     * @inheritdoc
     */
    public function safeUp()
    {
        $this->createTable('tb_bn_solicitud_descargo', [
            'CodigoSolicitud' => $this->primaryKey(),
            'FechaSolicitud' => $this->date(),
            'id' => $this->integer()->notNull(),
            'MotivoSolicitud' => $this->string(),
            'Estado' => $this->integer(),
            'SistemaFecha' => $this->dateTime(),
            'SistemaUsuario' => $this->string(50),
        ]);
        $this->addForeignKey('fk_DESCARGO_EMPLEADO','tb_bn_solicitud_descargo','id','user','id');
    }

    /**
     * @inheritdoc
     */
    public function down()
    {
        $this->dropTable('tb_bn_solicitud_descargo');
    }
}