text:
package org.efaps.esjp.sales.document;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.efaps.admin.datamodel.Status;
import org.efaps.admin.datamodel.Type;
import org.efaps.admin.datamodel.ui.IUIValue;
import org.efaps.admin.dbproperty.DBProperties;
import org.efaps.admin.event.Parameter;
import org.efaps.admin.event.Parameter.ParameterValues;
import org.efaps.admin.program.esjp.EFapsApplication;
import org.efaps.admin.program.esjp.EFapsUUID;
import org.efaps.admin.ui.field.Field;
import org.efaps.admin.ui.field.Field.Display;
import org.efaps.ci.CIType;
import org.efaps.db.Context;
import org.efaps.db.Delete;
import org.efaps.db.Insert;
import org.efaps.db.Instance;
import org.efaps.db.MultiPrintQuery;
import org.efaps.db.PrintQuery;
import org.efaps.db.QueryBuilder;
import org.efaps.db.SelectBuilder;
import org.efaps.db.Update;
import org.efaps.esjp.ci.CISales;
import org.efaps.esjp.erp.Currency;
import org.efaps.esjp.erp.NumberFormatter;
import org.efaps.esjp.erp.RateInfo;
import org.efaps.util.EFapsException;
import org.efaps.util.RandomUtil;
import org.joda.time.DateTime;

/**
 * TODO comment!
 *
 * @author The eFaps Team
 */
@EFapsUUID("83f2f7db-b2d5-4817-bd4c-abf4a0cffa17")
@EFapsApplication("eFapsApp-Sales")
public abstract class AbstractDocumentTax_Base
    extends AbstractDocumentSum
{

    /**
     * Used to store the PerceptionValue in the Context.
     */
    public static final String TAXAMOUNTVALUE = AbstractDocumentTax.class.getName() + ".TaxAmountValue";

    /**
     * Used to store the PerceptionValue in the Context.
     */
    public static final String REQKEY4DOCTAXINFO = AbstractDocumentTax.class.getName() + ".RequestKey4DocTaxInfo";

    /**
     * Executed from a Command execute event to create a new Incoming
     * PerceptionCertificate.
     *
     * @param _parameter Parameter as passed from the eFaps API.
     * @param _createdDoc as CreatedDoc with values.
     * @return the newly created tax document
     * @throws EFapsException on error
     */
    public CreatedDoc createUpdate4Doc(final Parameter _parameter,
                                       final CreatedDoc _createdDoc)
        throws EFapsException
    {
        CreatedDoc ret = null;
        final Type type = getType4create4Doc(_parameter);
        final DocTaxInfo docTaxInfo = AbstractDocumentTax_Base.getDocTaxInfo(_parameter, _createdDoc.getInstance());

        final BigDecimal value = (BigDecimal) _createdDoc.getValue(AbstractDocumentTax_Base.TAXAMOUNTVALUE);
        if (value.compareTo(BigDecimal.ZERO) > 0) {
            ret = new CreatedDoc();
            final Update update;
            final Object[] rateObj;
            if (docTaxInfo.isValid() && docTaxInfo.isKindOf(type)) {
                update = new Update(docTaxInfo.getTaxDocInstance(type));

                final PrintQuery print = new PrintQuery(_createdDoc.getInstance());
                print.addAttribute(CISales.DocumentSumAbstract.Rate);
                print.executeWithoutAccessCheck();
                rateObj = print.<Object[]>getAttribute(CISales.DocumentSumAbstract.Rate);
            } else {
                update = new Insert(type);
                final PrintQuery print = new PrintQuery(_createdDoc.getInstance());
                print.addAttribute(CISales.DocumentSumAbstract.Date, CISales.DocumentSumAbstract.DueDate,
                                CISales.DocumentSumAbstract.Contact, CISales.DocumentSumAbstract.Salesperson,
                                CISales.DocumentSumAbstract.Group, CISales.DocumentSumAbstract.Rate,
                                CISales.DocumentSumAbstract.CurrencyId, CISales.DocumentSumAbstract.RateCurrencyId,
                                CISales.DocumentSumAbstract.Name);
                print.executeWithoutAccessCheck();
                rateObj = print.<Object[]>getAttribute(CISales.DocumentSumAbstract.Rate);
                update.add(CISales.DocumentSumAbstract.Date,
                                print.<DateTime>getAttribute(CISales.DocumentSumAbstract.Date));
                update.add(CISales.DocumentSumAbstract.DueDate,
                                print.<DateTime>getAttribute(CISales.DocumentSumAbstract.DueDate));
                update.add(CISales.DocumentSumAbstract.Contact,
                                print.<Long>getAttribute(CISales.DocumentSumAbstract.Contact));
                update.add(CISales.DocumentSumAbstract.Salesperson,
                                print.<Long>getAttribute(CISales.DocumentSumAbstract.Salesperson));
                update.add(CISales.DocumentSumAbstract.Group,
                                print.<Long>getAttribute(CISales.DocumentSumAbstract.Group));
                update.add(CISales.DocumentSumAbstract.Rate, rateObj);
                update.add(CISales.DocumentSumAbstract.CurrencyId,
                                print.<Long>getAttribute(CISales.DocumentSumAbstract.CurrencyId));
                update.add(CISales.DocumentSumAbstract.RateCurrencyId,
                                print.<Long>getAttribute(CISales.DocumentSumAbstract.RateCurrencyId));
                update.add(CISales.DocumentSumAbstract.Name,
                                print.<String>getAttribute(CISales.DocumentSumAbstract.Name));
                update.add(CISales.DocumentSumAbstract.RateNetTotal, BigDecimal.ZERO);
                update.add(CISales.DocumentSumAbstract.RateDiscountTotal, BigDecimal.ZERO);
                update.add(CISales.DocumentSumAbstract.NetTotal, BigDecimal.ZERO);
                update.add(CISales.DocumentSumAbstract.DiscountTotal, BigDecimal.ZERO);
                add2createUpdate4Doc(_parameter, _createdDoc, update);
            }

            final RateInfo rateInfo = RateInfo.getRateInfo(rateObj);
            final BigDecimal crossTotal = Currency.convertToBase(_parameter, value, rateInfo,
                            getTypeName4SysConf(_parameter));

            update.add(CISales.DocumentSumAbstract.RateCrossTotal, value);
            update.add(CISales.DocumentSumAbstract.CrossTotal, crossTotal);

            addStatus2create4Doc(_parameter, update, _createdDoc);
            update.execute();

            ret.setInstance(update.getInstance());
            if (update instanceof Insert) {
                connectDoc(_parameter, _createdDoc, ret);
            }
            docTaxInfo.clean4TaxDocInst(update.getInstance());
        }
        return ret;
    }

    /**
     * @param _parameter Parameter as passed from the eFaps API
     * @param _createdDoc created doc
     * @param _update       update to be used
     * @throws EFapsException on error
     */
    protected void add2createUpdate4Doc(final Parameter _parameter,
                                        final CreatedDoc _createdDoc,
                                        final Update _update)
        throws EFapsException
    {

    }

    /**
     * @param _parameter Parameter as passed from the eFaps API
     * @return type for create
     * @throws EFapsException on error
     */
    protected abstract Type getType4create4Doc(Parameter _parameter)
        throws EFapsException;

    /**
     * @param _parameter Parameter as passed from the eFaps API.
     * @param _origDoc the original document
     * @param _taxDoc the tax document
     * @throws EFapsException on error
     */
    protected abstract void connectDoc(Parameter _parameter,
                                       CreatedDoc _origDoc,
                                       CreatedDoc _taxDoc)
        throws EFapsException;

    /**
     * @param _parameter Parameter as passed from the eFaps API.
     * @param _insert insert to add to
     * @param _origDoc the original document
     * @throws EFapsException on error
     */
    protected void addStatus2create4Doc(final Parameter _parameter,
                                        final Update _insert,
                                        final CreatedDoc _origDoc)
        throws EFapsException
    {
        _insert.add(CISales.DocumentSumAbstract.StatusAbstract,
                        Status.find(_insert.getInstance().getType().getStatusAttribute().getLink().getUUID(), "Open"));
    }

    /**
     * @param _parameter Parameter as passed by the eFaps API
     * @param _docInst instance of the document
     * @return html field value
     * @throws EFapsException on error
     */
    public static StringBuilder getSmallTaxField4Doc(final Parameter _parameter,
                                                     final Instance _docInst)
        throws EFapsException
    {
        final StringBuilder ret = new StringBuilder();
        final IUIValue uiObject = (IUIValue) _parameter.get(ParameterValues.UIOBJECT);
        final DocTaxInfo doctaxInfo = AbstractDocumentTax_Base.getDocTaxInfo(_parameter, _docInst);
        final DecimalFormat formater = NumberFormatter.get().getTwoDigitsFormatter();
        if (uiObject instanceof Field ||  uiObject.getDisplay().equals(Display.EDITABLE)
                        || uiObject.getDisplay().equals(Display.HIDDEN)) {
            // TODO configurable
            final String fieldName = "taxDocType" + _docInst.getOid();
            final String id1 = RandomUtil.randomAlphanumeric(6);
            final String id2 = RandomUtil.randomAlphanumeric(6);
            final String id3 = RandomUtil.randomAlphanumeric(6);
            final String id4 = RandomUtil.randomAlphanumeric(6);

            ret.append("<input type=\"radio\" value=\"").append("NONE").append("\" name=\"")
                            .append(fieldName).append("\" id=\"").append(id1).append("\"");
            if (!doctaxInfo.isValid()) {
                ret.append(" checked=\"checked\" ");
            }
            ret.append("/>")
                            .append(DBProperties.getProperty(AbstractDocumentTax.class.getName() + ".NoneSmallLabel"))
                            .append("");

            ret.append("<input type=\"radio\" value=\"").append(CISales.IncomingDetraction.getType().getId())
                            .append("\" name=\"").append(fieldName).append("\" id=\"").append(id2).append("\"");
            if (doctaxInfo.isDetraction()) {
                ret.append(" checked=\"checked\" ");
            }
            ret.append("/>")
                            .append(DBProperties.getProperty(AbstractDocumentTax.class.getName()
                                            + ".IncomingDetractionSmallLabel"))
                            .append("");

            ret.append("<input type=\"radio\" value=\"").append(CISales.IncomingRetention.getType().getId())
                            .append("\" name=\"").append(fieldName).append("\" id=\"").append(id3).append("\"");
            if (doctaxInfo.isRetention()) {
                ret.append(" checked=\"checked\" ");
            }
            ret.append("/>")
                            .append(DBProperties.getProperty(AbstractDocumentTax.class.getName()
                                            + ".IncomingRetentionSmallLabel"))
                            .append("");

            ret.append("<input type=\"radio\" value=\"").append(CISales.IncomingPerceptionCertificate.getType().getId())
                            .append("\" name=\"").append(fieldName).append("\" id=\"").append(id4).append("\"");
            if (doctaxInfo.isPerception()) {
                ret.append(" checked=\"checked\" ");
            }
            ret.append("/>")
                            .append(DBProperties.getProperty(AbstractDocumentTax.class.getName()
                                            + ".IncomingPerceptionCertificateSmallLabel")).append("");

            ret.append("<input type=\"text\" name=\"taxDocAmount\" size=\"6\" value=\"")
                            .append(formater.format(doctaxInfo.getTaxAmount()))
                            .append("\">");
        } else if (uiObject.getDisplay().equals(Display.READONLY)
                        || uiObject.getDisplay().equals(Display.NONE)) {
            if (!doctaxInfo.isValid()) {
                ret.append(DBProperties.getProperty(AbstractDocumentTax.class.getName() + ".NoneSmallLabel"));
            } else {
                if (doctaxInfo.isDetraction()) {
                    ret.append(DBProperties.getProperty(AbstractDocumentTax.class.getName()
                                + ".IncomingDetractionSmallLabel"))
                        .append(": ").append(formater.format(doctaxInfo.getTaxAmount())).append(" (")
                        .append(formater.format(doctaxInfo.getPercent())).append("%)");
                } else if (doctaxInfo.isRetention()) {
                    ret.append(DBProperties.getProperty(AbstractDocumentTax.class.getName()
                                + ".IncomingRetentionSmallLabel"))
                        .append(": ").append(formater.format(doctaxInfo.getTaxAmount())).append(" (")
                        .append(formater.format(doctaxInfo.getPercent())).append("%)");
                } else if (doctaxInfo.isPerception()) {
                    ret.append(DBProperties.getProperty(AbstractDocumentTax.class.getName()
                                + ".IncomingPerceptionCertificateSmallLabel"))
                        .append(": ").append(formater.format(doctaxInfo.getTaxAmount())).append(" (")
                        .append(formater.format(doctaxInfo.getPercent())).append("%)");
                }

                if (doctaxInfo.isProfServRetention()) {
                    ret.append(DBProperties.getProperty(AbstractDocumentTax.class.getName()
                                    + ".IncomingProfServRetentionSmallLabel"))
                            .append(": ")
                            .append(formater.format(doctaxInfo.getTaxAmount(CISales.IncomingProfServRetention)))
                            .append(" (")
                            .append(formater.format(doctaxInfo.getPercent(CISales.IncomingProfServRetention)))
                            .append("%)");
                }
                if (doctaxInfo.isProfServInsurance()) {
                    ret.append(DBProperties.getProperty(AbstractDocumentTax.class.getName()
                                    + ".IncomingProfServInsuranceSmallLabel"))
                        .append(": ")
                        .append(formater.format(doctaxInfo.getTaxAmount(CISales.IncomingProfServInsurance)))
                        .append(" (")
                        .append(formater.format(doctaxInfo.getPercent(CISales.IncomingProfServInsurance)))
                        .append("%)");
                }
            }
        } else {
            ret.append("-");
        }
        return ret;
    }

    /**
     * @param _parameter Parameter as passed by the eFaps API
     * @param _docInst instance of the document
     * @return DocTaxInfo
     * @throws EFapsException on error
     */
    public static DocTaxInfo getDocTaxInfo(final Parameter _parameter,
                                           final Instance _docInst)
        throws EFapsException
    {
        if (!Context.getThreadContext().containsRequestAttribute(AbstractDocumentTax_Base.REQKEY4DOCTAXINFO)) {
            Context.getThreadContext().setRequestAttribute(AbstractDocumentTax_Base.REQKEY4DOCTAXINFO,
                            new HashMap<Instance, DocTaxInfo>());
        }
        @SuppressWarnings("unchecked")
        final Map<Instance, DocTaxInfo> mapping = (Map<Instance, DocTaxInfo>) Context.getThreadContext()
                        .getRequestAttribute(AbstractDocumentTax_Base.REQKEY4DOCTAXINFO);
        if (!mapping.containsKey(_docInst)) {
            mapping.put(_docInst, new DocTaxInfo(_docInst));
        }
        return mapping.get(_docInst);
    }

    /**
     * @param _parameter Parameter as passed by the eFaps API
     * @param _docInstances instance of the document
     *
     * @throws EFapsException on error
     */
    public static void evaluateDocTaxInfo(final Parameter _parameter,
                                          final List<Instance> _docInstances)
        throws EFapsException
    {
        if (!Context.getThreadContext().containsRequestAttribute(AbstractDocumentTax_Base.REQKEY4DOCTAXINFO)) {
            Context.getThreadContext().setRequestAttribute(AbstractDocumentTax_Base.REQKEY4DOCTAXINFO,
                            new HashMap<Instance, DocTaxInfo>());
        }
        @SuppressWarnings("unchecked")
        final Map<Instance, DocTaxInfo> mapping = (Map<Instance, DocTaxInfo>) Context.getThreadContext()
                        .getRequestAttribute(AbstractDocumentTax_Base.REQKEY4DOCTAXINFO);
        final List<Instance> instances = new ArrayList<>();
        final List<Instance> validInstances = new ArrayList<>();
        for (final Instance docInstance : _docInstances) {
            if (!mapping.containsKey(docInstance)) {
                instances.add(docInstance);
            }
        }
        if (!instances.isEmpty()) {
            final QueryBuilder queryBldr = new QueryBuilder(CISales.IncomingDocumentTax2Document);
            queryBldr.addWhereAttrEqValue(CISales.IncomingDocumentTax2Document.ToAbstractLink, instances.toArray());
            final MultiPrintQuery multi = queryBldr.getPrint();
            final SelectBuilder selDoc = SelectBuilder.get().linkto(
                            CISales.IncomingDocumentTax2Document.ToAbstractLink);
            final SelectBuilder selDocInst = new SelectBuilder(selDoc).instance();
            final SelectBuilder selDocTax = SelectBuilder.get().linkto(
                            CISales.IncomingDocumentTax2Document.FromAbstractLink);
            final SelectBuilder selDocTaxInst = new SelectBuilder(selDocTax).instance();
            final SelectBuilder selDocTaxCrossTotal = new SelectBuilder(selDocTax)
                            .attribute(CISales.DocumentSumAbstract.CrossTotal);
            final SelectBuilder selDocCrossTotal = new SelectBuilder(selDoc)
                            .attribute(CISales.DocumentSumAbstract.CrossTotal);
            multi.addSelect(selDocInst, selDocTaxInst, selDocTaxCrossTotal, selDocCrossTotal);
            multi.execute();
            while (multi.next()) {
                final Instance docInstance = multi.getSelect(selDocInst);
                validInstances.add(docInstance);
                final Instance relInstance = multi.getCurrentInstance();
                final Instance taxDocInstance = multi.getSelect(selDocTaxInst);
                final BigDecimal taxAmount = multi.getSelect(selDocTaxCrossTotal);
                final BigDecimal crossTotal = multi.getSelect(selDocCrossTotal);
                final BigDecimal percent = BigDecimal.ZERO.compareTo(crossTotal) == 0 ? BigDecimal.ZERO
                                : new BigDecimal(100).setScale(8).divide(crossTotal, RoundingMode.HALF_UP)
                                                .multiply(taxAmount);
                final DocTaxInfo docTaxInfo;
                if (mapping.containsKey(docInstance)) {
                    docTaxInfo = mapping.get(docInstance);
                } else {
                    docTaxInfo  = new DocTaxInfo(docInstance);
                    mapping.put(docInstance, docTaxInfo);
                }
                docTaxInfo.addRelInstance(relInstance);
                docTaxInfo.addTaxDocInstance(taxDocInstance);
                docTaxInfo.addTaxAmount(taxDocInstance, taxAmount);
                docTaxInfo.addPercent(taxDocInstance, percent);
                docTaxInfo.setInitialized(true);
            }
            for (final Instance inst : CollectionUtils.subtract(instances, validInstances)) {
                final DocTaxInfo docTaxInfo = new DocTaxInfo(inst);
                mapping.put(inst, docTaxInfo);
                docTaxInfo.setInitialized(true);
            }
        }
    }

    /**
     * Class containing info about DocTax.
     */
    public static class DocTaxInfo
    {
        /**
         * Instance of the document.
         */
        private Instance docInstance;

        /**
         * Instance of the DocTax.
         */
        private final List<Instance> taxDocInstances = new ArrayList<>();

        /**
         * Instance of the relation.
         */
        private final List<Instance> relInstances = new ArrayList<>();

        /**
         * initialized or not.
         */
        private boolean initialized = false;

        /**
         * Amount of tax.
         */
        private final Map<Instance, BigDecimal> tax2Amount = new HashMap<>();

        /**
         * Amount of tax.
         */
        private final Map<Instance, BigDecimal> tax2Percent = new HashMap<>();

        /**
         * Amount of tax.
         */
        private final Map<Instance, BigDecimal> tax2RateAmount = new HashMap<>();

        /**
         * Amount of the tax payed.
         */
        private BigDecimal paymentAmount = null;

        /**
         * Amount of the tax payed.
         */
        private String paymentName = null;

        /**
         * Amount of the tax payed.
         */
        private DateTime paymentDate = null;

        /**
         * @param _docInst instance of teh docuemnt the info belong to
         */
        public DocTaxInfo(final Instance _docInst)
        {
            docInstance = _docInst;
        }

        /**
         * @throws EFapsException on error
         */
        protected void initialize()
            throws EFapsException
        {
            if (!initialized && docInstance != null && docInstance.isValid()) {
                final QueryBuilder queryBldr = new QueryBuilder(CISales.IncomingDocumentTax2Document);
                queryBldr.addWhereAttrEqValue(CISales.IncomingDocumentTax2Document.ToAbstractLink, docInstance);
                final MultiPrintQuery multi = queryBldr.getPrint();
                final SelectBuilder selDoc = SelectBuilder.get().linkto(
                                CISales.IncomingDocumentTax2Document.ToAbstractLink);
                final SelectBuilder selDocTax = SelectBuilder.get().linkto(
                                CISales.IncomingDocumentTax2Document.FromAbstractLink);
                final SelectBuilder selDocTaxInst = new SelectBuilder(selDocTax).instance();
                final SelectBuilder selDocTaxCrossTotal = new SelectBuilder(selDocTax)
                                .attribute(CISales.DocumentSumAbstract.CrossTotal);
                final SelectBuilder selDocTaxRateCrossTotal = new SelectBuilder(selDocTax)
                                .attribute(CISales.DocumentSumAbstract.RateCrossTotal);
                final SelectBuilder selDocCrossTotal = new SelectBuilder(selDoc)
                                .attribute(CISales.DocumentSumAbstract.CrossTotal);
                multi.addSelect(selDocTaxInst, selDocTaxCrossTotal, selDocCrossTotal, selDocTaxRateCrossTotal);
                multi.execute();
                while (multi.next()) {
                    relInstances.add(multi.getCurrentInstance());
                    final Instance taxDocInst = multi.<Instance>getSelect(selDocTaxInst);
                    final BigDecimal taxAmount = multi.<BigDecimal>getSelect(selDocTaxCrossTotal);
                    final BigDecimal taxRateAmount = multi.<BigDecimal>getSelect(selDocTaxRateCrossTotal);
                    taxDocInstances.add(taxDocInst);
                    tax2Amount.put(taxDocInst, taxAmount);
                    tax2RateAmount.put(taxDocInst, taxRateAmount);
                    final BigDecimal crossTotal = multi.getSelect(selDocCrossTotal);
                    final BigDecimal percent = BigDecimal.ZERO.compareTo(crossTotal) == 0 ? BigDecimal.ZERO
                                    : new BigDecimal(100).setScale(8)
                                                    .divide(crossTotal, RoundingMode.HALF_UP)
                                                    .multiply(taxAmount);
                    tax2Percent.put(taxDocInst, percent);
                }
                initialized = true;
            }
        }

        /**
         * @param _taxDocInst instance to be retained, if null all will be removed
         * @throws EFapsException on error
         */
        public void clean4TaxDocInst(final Instance _taxDocInst)
            throws EFapsException
        {
            if (_taxDocInst == null
                            || _taxDocInst.getType().isKindOf(CISales.IncomingPerceptionCertificate)
                            || _taxDocInst.getType().isKindOf(CISales.IncomingRetention)
                            || _taxDocInst.getType().isKindOf(CISales.IncomingDetraction)) {
                final QueryBuilder queryBldr = new QueryBuilder(CISales.IncomingDocumentTax2Document);
                queryBldr.addWhereAttrEqValue(CISales.IncomingDocumentTax2Document.ToAbstractLink, docInstance);
                if (_taxDocInst != null) {
                    queryBldr.addWhereAttrNotEqValue(CISales.IncomingDocumentTax2Document.FromAbstractLink,
                                    _taxDocInst);
                }
                final MultiPrintQuery multi = queryBldr.getPrint();
                final SelectBuilder selDocTaxInst = SelectBuilder.get().linkto(
                                CISales.IncomingDocumentTax2Document.FromAbstractLink).instance();
                multi.addSelect(selDocTaxInst);
                multi.execute();
                while (multi.next()) {
                    final Instance docTaxInst = multi.getSelect(selDocTaxInst);

                    final Update update = new Update(docTaxInst);
                    update.add(CISales.DocumentSumAbstract.StatusAbstract, Status.find(
                                    docTaxInst.getType().getStatusAttribute().getLink().getUUID(),
                                    "Canceled"));
                    update.executeWithoutAccessCheck();

                    new Delete(multi.getCurrentInstance()).executeWithoutAccessCheck();
                }
            }
        }

        /**
         * @param _ciType tyep to be removed
         * @throws EFapsException on error
         */
        public void cleanByType(final CIType _ciType)
            throws EFapsException
        {
            final QueryBuilder attrQueryBldr = new QueryBuilder(_ciType);

            final QueryBuilder queryBldr = new QueryBuilder(CISales.IncomingDocumentTax2Document);
            queryBldr.addWhereAttrEqValue(CISales.IncomingDocumentTax2Document.ToAbstractLink, docInstance);
            queryBldr.addWhereAttrInQuery(CISales.IncomingDocumentTax2Document.FromAbstractLink,
                            attrQueryBldr.getAttributeQuery("ID"));
            final MultiPrintQuery multi = queryBldr.getPrint();
            final SelectBuilder selDocTaxInst = SelectBuilder.get().linkto(
                            CISales.IncomingDocumentTax2Document.FromAbstractLink).instance();
            multi.addSelect(selDocTaxInst);
            multi.execute();
            while (multi.next()) {
                final Instance docTaxInst = multi.getSelect(selDocTaxInst);

                final Update update = new Update(docTaxInst);
                update.add(CISales.DocumentSumAbstract.StatusAbstract, Status.find(
                                docTaxInst.getType().getStatusAttribute().getLink().getUUID(),
                                "Canceled"));
                update.executeWithoutAccessCheck();
                new Delete(multi.getCurrentInstance()).executeWithoutAccessCheck();
            }
        }

        /**
         * @param _taxDocInstance instance the percent belongs to
         * @param _percent percent
         */
        public void addPercent(final Instance _taxDocInstance,
                               final BigDecimal _percent)
        {
            tax2Percent.put(_taxDocInstance, _percent);
        }

        /**
         * @param _taxDocInstance instance the amount belongs to
         * @param _taxAmount amount
         */
        public void addTaxAmount(final Instance _taxDocInstance,
                                 final BigDecimal _taxAmount)
        {
            tax2Amount.put(_taxDocInstance, _taxAmount);
        }

        /**
         * Getter method for the instance variable {@link #perception}.
         *
         * @return value of instance variable {@link #perception}
         * @throws EFapsException on error
         */
        public boolean isPerception()
            throws EFapsException
        {
            initialize();
            return !taxDocInstances.isEmpty() && hasType(CISales.IncomingPerceptionCertificate);
        }

        /**
         * @param _type type to be checked for
         * @return true if has thegiven type
         */
        protected boolean hasType(final CIType _type)
        {
            return hasType(_type.getType());
        }

        /**
         * @param _type type to be checked for
         * @return true if has thegiven type
         */
        protected boolean hasType(final Type _type)
        {
            boolean ret = false;
            for (final Instance taxDocInst : taxDocInstances) {
                ret = taxDocInst.isValid() && taxDocInst.getType().isKindOf(_type);
                if (ret) {
                    break;
                }
            }
            return ret;
        }

        /**
         * @return true if valid else false
         * @throws EFapsException on error
         */
        public boolean isValid()
            throws EFapsException
        {
            initialize();
            return docInstance != null && docInstance.isValid() && !taxDocInstances.isEmpty();
        }

        /**
         * Getter method for the instance variable {@link #perception}.
         * @param _type type to be checked for
         * @return value of instance variable {@link #perception}
         * @throws EFapsException on error
         */
        public boolean isKindOf(final Type _type)
            throws EFapsException
        {
            initialize();
            return !taxDocInstances.isEmpty() && hasType(_type);
        }

        /**
         * Getter method for the instance variable {@link #retention}.
         *
         * @return value of instance variable {@link #retention}
         * @throws EFapsException on error
         */
        public boolean isRetention()
            throws EFapsException
        {
            initialize();
            return !taxDocInstances.isEmpty() && hasType(CISales.IncomingRetention);
        }

        /**
         * Getter method for the instance variable {@link #detraction}.
         *
         * @return value of instance variable {@link #detraction}
         * @throws EFapsException on error
         */
        public boolean isDetraction()
            throws EFapsException
        {
            initialize();
            return !taxDocInstances.isEmpty() && hasType(CISales.IncomingDetraction);
        }

        /**
         * Getter method for the instance variable {@link #detraction}.
         *
         * @return value of instance variable {@link #detraction}
         * @throws EFapsException on error
         */
        public boolean isDetractionPaid()
            throws EFapsException
        {
            initialize();
            boolean ret = false;
            if (isDetraction()) {
                final Instance taxDocInst = getTaxDocInstance(CISales.IncomingDetraction);
                final PrintQuery print = new PrintQuery(taxDocInst);
                print.addAttribute(CISales.IncomingDetraction.Status);
                print.execute();
                ret = Status.find(CISales.IncomingDetractionStatus.Paid).equals(Status.get(print.<Long>getAttribute(
                                CISales.IncomingDetraction.Status)));
            }
            return ret;
        }

        /**
         * Getter method for the instance variable {@link #retention}.
         *
         * @return value of instance variable {@link #retention}
         * @throws EFapsException on error
         */
        public boolean isPercetion()
            throws EFapsException
        {
            initialize();
            return !taxDocInstances.isEmpty() && hasType(CISales.IncomingPerceptionCertificate);
        }

        /**
         * Getter method for the instance variable {@link #docInstance}.
         *
         * @return value of instance variable {@link #docInstance}
         * @throws EFapsException on error
         */
        public Instance getDocInstance()
            throws EFapsException
        {
            initialize();
            return docInstance;
        }

        /**
         * Setter method for instance variable {@link #docInstance}.
         *
         * @param _docInstance value for instance variable {@link #docInstance}
         */
        public void setDocInstance(final Instance _docInstance)
        {
            docInstance = _docInstance;
        }

        /**
         * Setter method for instance variable {@link #taxDocInstance}.
         *
         * @param _taxDocInstance value for instance variable
         *            {@link #taxDocInstance}
         */
        public void addTaxDocInstance(final Instance _taxDocInstance)
        {
            taxDocInstances.add(_taxDocInstance);
        }

        /**
         * Getter method for the instance variable {@link #taxAmount}.
         *
         * @return value of instance variable {@link #taxAmount}
         * @throws EFapsException on error
         */
        public BigDecimal getTaxAmount()
            throws EFapsException
        {
            initialize();
            return tax2Amount.size() == 1 ? tax2Amount.values().iterator().next() : BigDecimal.ZERO;
        }

        /**
         * @param _taxDocInst taxdoc Instance the amount is wanted for
         * @return amount
         * @throws EFapsException on error
         */
        public BigDecimal getTaxAmount(final Instance _taxDocInst)
            throws EFapsException
        {
            initialize();
            return tax2Amount.get(_taxDocInst);
        }

        /**
         * @param _citype taxdoc type the amount is wanted for
         * @return amount
         * @throws EFapsException on error
         */
        public BigDecimal getTaxAmount(final CIType _citype)
            throws EFapsException
        {
            return getTaxAmount(getTaxDocInstance(_citype));
        }

        /**
         * Getter method for the instance variable {@link #taxAmount}.
         *
         * @return value of instance variable {@link #taxAmount}
         * @throws EFapsException on error
         */
        public BigDecimal getTaxRateAmount()
            throws EFapsException
        {
            initialize();
            return tax2RateAmount.size() == 1 ? tax2RateAmount.values().iterator().next() : BigDecimal.ZERO;
        }

        /**
         * @param _taxDocInst taxdoc Instance the amount is wanted for
         * @return amount
         * @throws EFapsException on error
         */
        public BigDecimal getTaxRateAmount(final Instance _taxDocInst)
            throws EFapsException
        {
            initialize();
            return tax2RateAmount.get(_taxDocInst);
        }

        /**
         * @param _citype taxdoc type the amount is wanted for
         * @return amount
         * @throws EFapsException on error
         */
        public BigDecimal getTaxRateAmount(final CIType _citype)
            throws EFapsException
        {
            return getTaxRateAmount(getTaxDocInstance(_citype));
        }

        /**
         * Getter method for the instance variable {@link #percent}.
         *
         * @return value of instance variable {@link #percent}
         * @throws EFapsException on error
         */
        public BigDecimal getPercent()
            throws EFapsException
        {
            initialize();
            return tax2Percent.size() == 1 ? tax2Percent.values().iterator().next() : BigDecimal.ZERO;
        }

        /**
         * @param _taxDocInst taxdoc Instance the percent is wanted for
         * @return percent
         * @throws EFapsException on error
         */
        public BigDecimal getPercent(final Instance _taxDocInst)
            throws EFapsException
        {
            initialize();
            return tax2Percent.get(_taxDocInst);
        }

        /**
         * @param _citype taxdoc type the percent is wanted for
         * @return percent
         * @throws EFapsException on error
         */
        public BigDecimal getPercent(final CIType _citype) throws EFapsException
        {
            return getPercent(getTaxDocInstance(_citype));
        }

        /**
         * Setter method for instance variable {@link #relInstance}.
         *
         * @param _relInstance value for instance variable {@link #relInstance}
         */
        public void addRelInstance(final Instance _relInstance)
        {
            relInstances.add(_relInstance);
        }

        /**
         * Getter method for the instance variable {@link #initialized}.
         *
         * @return value of instance variable {@link #initialized}
         */
        public boolean isInitialized()
        {
            return initialized;
        }

        /**
         * Setter method for instance variable {@link #initialized}.
         *
         * @param _initialized value for instance variable {@link #initialized}
         */
        public void setInitialized(final boolean _initialized)
        {
            initialized = _initialized;
        }

        /**
         * Analyze payment.
         * @throws EFapsException on error
         */
        protected void analyzePayment()
            throws EFapsException
        {
            final QueryBuilder attrQueryBldr = new QueryBuilder(CISales.PaymentDetractionOut);
            attrQueryBldr.addType(CISales.PaymentRetentionOut);

            final QueryBuilder queryBldr = new QueryBuilder(CISales.Payment);
            queryBldr.addWhereAttrEqValue(CISales.Payment.CreateDocument, taxDocInstances.toArray());
            queryBldr.addWhereAttrInQuery(CISales.Payment.TargetDocument,
                            attrQueryBldr.getAttributeQuery(CISales.PaymentDocumentAbstract.ID));
            final MultiPrintQuery multi = queryBldr.getPrint();
            final SelectBuilder selAmount = SelectBuilder.get()
                            .linkfrom(CISales.TransactionAbstract, CISales.TransactionAbstract.Payment)
                            .attribute(CISales.TransactionAbstract.Amount);
            final SelectBuilder selDate = SelectBuilder.get()
                            .linkto(CISales.Payment.TargetDocument)
                            .attribute(CISales.PaymentDocumentOutAbstract.Date);
            final SelectBuilder selName = SelectBuilder.get()
                            .linkto(CISales.Payment.TargetDocument)
                            .attribute(CISales.PaymentDocumentOutAbstract.Name);
            multi.addSelect(selAmount, selDate, selName);
            multi.execute();
            BigDecimal paymentAmountTmp = BigDecimal.ZERO;
            String paymentNameTmp = "";
            while (multi.next()) {
                paymentAmountTmp = paymentAmountTmp.add(multi.<BigDecimal>getSelect(selAmount));
                if (paymentDate == null) {
                    paymentDate = multi.getSelect(selDate);
                }
                if (StringUtils.isNotEmpty(paymentNameTmp)) {
                    paymentNameTmp = paymentNameTmp + ", ";
                }
                paymentNameTmp = paymentNameTmp + multi.getSelect(selName);
            }
            if (paymentAmount == null) {
                paymentAmount = paymentAmountTmp;
            }
            if (paymentName == null) {
                paymentName = paymentNameTmp;
            }
        }

        /**
         * Getter method for the instance variable {@link #paymentAmount}.
         *
         * @return value of instance variable {@link #paymentAmount}
         * @throws EFapsException on error
         */
        public BigDecimal getPaymentAmount()
            throws EFapsException
        {
            if (paymentAmount == null) {
                analyzePayment();
            }
            return paymentAmount;
        }

        /**
         * Setter method for instance variable {@link #paymentAmount}.
         *
         * @param _paymentAmount value for instance variable {@link #paymentAmount}
         */
        public void setPaymentAmount(final BigDecimal _paymentAmount)
        {
            paymentAmount = _paymentAmount;
        }

        /**
         * Getter method for the instance variable {@link #paymentName}.
         *
         * @return value of instance variable {@link #paymentName}
         * @throws EFapsException on error
         */
        public String getPaymentName()
            throws EFapsException
        {
            if (paymentName == null) {
                analyzePayment();
            }
            return paymentName;
        }

        /**
         * Setter method for instance variable {@link #paymentName}.
         *
         * @param _paymentName value for instance variable {@link #paymentName}
         */
        public void setPaymentName(final String _paymentName)
        {
            paymentName = _paymentName;
        }

        /**
         * Getter method for the instance variable {@link #paymentDate}.
         *
         * @return value of instance variable {@link #paymentDate}
         * @throws EFapsException on error
         */
        public DateTime getPaymentDate()
            throws EFapsException
        {
            if (paymentDate == null) {
                analyzePayment();
            }
            return paymentDate;
        }

        /**
         * Setter method for instance variable {@link #paymentDate}.
         *
         * @param _paymentDate value for instance variable {@link #paymentDate}
         */
        public void setPaymentDate(final DateTime _paymentDate)
        {
            paymentDate = _paymentDate;
        }

        /**
         * @return true if of this type
         * @throws EFapsException on error
         */
        public boolean isProfServRetention()
            throws EFapsException
        {
            initialize();
            return !taxDocInstances.isEmpty() && hasType(CISales.IncomingProfServRetention);
        }

        /**
         * @return true if of this type
         * @throws EFapsException on error
         */
        public boolean isProfServInsurance()
            throws EFapsException
        {
            initialize();
            return !taxDocInstances.isEmpty() && hasType(CISales.IncomingProfServInsurance);
        }

        /**
         * @param _type type the taxdoc instance is wanted for
         * @return if found instance, else null
         */
        public Instance getTaxDocInstance(final Type _type)
        {
            Instance ret = null;
            for (final Instance taxDocInst : taxDocInstances) {
                if (taxDocInst.isValid() && taxDocInst.getType().isKindOf(_type)) {
                    ret = taxDocInst;
                }
            }
            return ret;
        }

        /**
         * @param _citype type the taxdoc instance is wanted for
         * @return if found instance, else null
         */
        public Instance getTaxDocInstance(final CIType _citype)
        {
            return getTaxDocInstance(_citype.getType());
        }

        /**
         * Get the datraction type instance.
         * @return if found instance, else null
         * @throws EFapsException on error
         */
        public Instance getDetractionTypeInst()
            throws EFapsException
        {
            Instance ret = null;
            if (isDetraction()) {
                final Instance taxDocInst = getTaxDocInstance(CISales.IncomingDetraction);
                final PrintQuery print = new PrintQuery(taxDocInst);
                final SelectBuilder sel = SelectBuilder.get().linkto(CISales.IncomingDetraction.ServiceType).instance();
                print.addSelect(sel);
                print.execute();
                ret = print.getSelect(sel);
            }
            return ret;
        }
    }
}


text:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "DTD/xhtml1-transitional.dtd">

		<meta http-equiv="content-type" content="text/html; charset=ISO-8859-1" />
		<title>HBase 0.94.19 Reference Package org.apache.hadoop.hbase.master</title>
		<link rel="stylesheet" type="text/css" href="../../../../../stylesheet.css" title="style" />

        	org.apache.hadoop.hbase.master

Classes

            	AssignmentManagerWithExtrasForTesting

            	DummyMaster

            	Expr

            	MockLoadBalancer

            	MockMasterServices

            	MockServer

            	MockedLoadBalancer

            	Mocking

            	NodeDeletionListener

            	RegionSplitListener

            	ReopenEventListener

            	TestActiveMasterManager

            	TestAssignmentManager

            	TestCatalogJanitor

            	TestClockSkewDetection

            	TestDeadServer

            	TestDefaultLoadBalancer

            	TestDistributedLogSplitting

            	TestHMasterRPCException

            	TestMXBean

            	TestMaster

            	TestMasterFailover

            	TestMasterFileSystem

            	TestMasterRestartAfterDisablingTable

            	TestMasterShutdown

            	TestMasterStatusServlet

            	TestMasterTransitions

            	TestMasterZKSessionRecovery

            	TestOpenedRegionHandler

            	TestRestartCluster

            	TestRollingRestart

            	TestSplitLogManager

            	TestZKBasedOpenCloseRegion

            	TestZKBasedOpenCloseRegionRegionServer

            	WaitToBeMasterThread

redpajama_set_name: RedPajamaGithub


text:
package com.che.fast_ioc;

import android.app.Activity;
import android.view.View;

import com.che.base_util.LogUtil;
import com.che.fast_ioc.annotation.IClick;
import com.che.fast_ioc.annotation.IColor;
import com.che.fast_ioc.annotation.IContentView;
import com.che.fast_ioc.annotation.IString;
import com.che.fast_ioc.annotation.IView;

import java.lang.annotation.Annotation;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
import java.util.ArrayList;
import java.util.List;

/**
 * 注解工具类
 * <p>
 * 作者:余天然 on 16/9/16 上午2:10
 */
public class InjectUtil {

    /**
     * 绑定
     *
     * @param activity
     */
    public static void bind(Activity activity) {
        Class<? extends Activity> clazz = activity.getClass();
        //处理类注解
        processType(activity, clazz);
        //遍历所有的字段
        for (Field field : clazz.getDeclaredFields()) {
            LogUtil.print("field=" + field.getName() + "\t" + field.getType());
            //处理字段注解
            processField(activity, field);
        }
        //遍历所有的方法
        for (Method method : clazz.getDeclaredMethods()) {
            //处理方法注解
            processMethod(activity, method);
        }
    }

    /**
     * 解绑
     *
     * @param activity
     */
    public static void unbind(Activity activity) {
        try {
            Class<? extends Activity> clazz = activity.getClass();
            //遍历所有的字段
            for (Field field : clazz.getDeclaredFields()) {
                LogUtil.print("field=" + field.getName() + "\t" + field.getType());
                //将所有字段置空
                boolean accessible = field.isAccessible();
                field.setAccessible(true);
                field.set(activity, null);
                field.setAccessible(accessible);
            }
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        }
    }

    /**
     * 处理类注解
     */
    private static void processType(Activity activity, Class<? extends Activity> clazz) {
        List<Class<? extends Annotation>> annoList = new ArrayList<>();
        annoList.add(IContentView.class);

        for (Class<? extends Annotation> annotationType : annoList) {
            //判断是否存在IContentView注解
            if (clazz.isAnnotationPresent(annotationType)) {
                dispatchType(activity, clazz, annotationType);
            }
        }
    }

    /**
     * 分发类注解
     */
    private static void dispatchType(Activity activity, Class<? extends Activity> clazz, Class<? extends Annotation> annotationType) {
        if (annotationType == IContentView.class) {
            IContentView annotation = clazz.getAnnotation(IContentView.class);
            int value = annotation.value();
            activity.setContentView(value);
        }
    }

    /**
     * 处理字段注解
     */
    private static void processField(Activity activity, Field field) {
        List<Class<? extends Annotation>> annoList = new ArrayList<>();
        annoList.add(IView.class);
        annoList.add(IColor.class);
        annoList.add(IString.class);

        for (Class<? extends Annotation> annotationType : annoList) {
            if (field.isAnnotationPresent(annotationType)) {
                boolean accessible = field.isAccessible();
                field.setAccessible(true);
                dispatchFiled(activity, field, annotationType);
                field.setAccessible(accessible);
            }
        }
    }

    /**
     * 分发字段注解
     */
    private static void dispatchFiled(Activity activity, Field field, Class<?> annotationType) {
        try {
            if (annotationType == IView.class) {
                IView anno = field.getAnnotation(IView.class);
                int value = anno.value();
                field.set(activity, activity.findViewById(value));
            }
            if (annotationType == IString.class) {
                IString anno = field.getAnnotation(IString.class);
                int value = anno.value();
                field.set(activity, activity.getString(value));
            }
            if (annotationType == IColor.class) {
                IColor anno = field.getAnnotation(IColor.class);
                int value = anno.value();
                field.set(activity, activity.getResources().getColor(value));
            }
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        }

    }

    /**
     * 处理方法注解
     */
    private static void processMethod(Activity activity, Method method) {
        List<Class<? extends Annotation>> annoList = new ArrayList<>();
        annoList.add(IClick.class);

        for (Class<? extends Annotation> annotationType : annoList) {
            //判断是否存在IContentView注解
            if (method.isAnnotationPresent(annotationType)) {
                dispatchMethod(activity, method, annotationType);
            }
        }
    }

    /**
     * 分发方法注解
     */
    private static void dispatchMethod(Activity activity, Method method, Class<? extends Annotation> annotationType) {
        try {
            if (annotationType == IClick.class) {
                IClick annotation = method.getAnnotation(IClick.class);
                // 获取注解里面的id
                int[] ids = annotation.value();
                // 当有注解的时候生成动态代理
                ClassLoader classLoader = View.OnClickListener.class.getClassLoader();
                Class<?>[] interfaces = {View.OnClickListener.class};
                Object proxy = Proxy.newProxyInstance(classLoader, interfaces, new DynaHandler(activity, method));
                for (int id : ids) {
                    View view = activity.findViewById(id);
                    Method onClickMethod = view.getClass().getMethod("setOnClickListener", View.OnClickListener.class);
                    // 调用setOnClickListener方法回调在动态类里面
                    onClickMethod.invoke(view, proxy);
                }
            }
        } catch (NoSuchMethodException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            e.printStackTrace();
        }
    }

}


text:
import smartzkclient.Monitor;

/**
 * Created by Sophie on 12/11/16.
 */
public class StartMonitor {

    public static void main(String[] args) {
        //        String zkHost = "localhost:2181/Assignment1";
        Monitor monitor = new Monitor();
        monitor.startApp();

        monitor.setWatchOnInstanceManagers();

        monitor.setWatchOnOrchestrator();

        try{
            Thread.sleep(3000);

            System.out.println("Active orchestrators: ");
            for(String orch: monitor.listAllOrchestrators()) {
                System.out.println(orch);
            }

            Thread.sleep(2000);

            System.out.println("Active instanceMnagers: ");
            for(String im: monitor.listAllInstanceManagers()) {
                System.out.println(im);
            }

            Thread.sleep(15000);

        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}


text:
package uk.gov.dvla.vehicles.presentation.common.controllers

import com.google.inject.Inject
import play.api.mvc.{Action, Controller}
import uk.gov.dvla.vehicles.presentation.common.clientsidesession.ClientSideSessionFactory
import uk.gov.dvla.vehicles.presentation.common.views

class PlaybackController @Inject()(implicit clientSideSessionFactory: ClientSideSessionFactory)
  extends Controller{

  def present = Action { implicit request =>
    Ok(views.html.playbackView())
  }
}


text:
<?php

namespace SocialiteProviders\Discord;

use SocialiteProviders\Manager\SocialiteWasCalled;

class DiscordExtendSocialite
{
    /**
     * Register the provider.
     *
     * @param \SocialiteProviders\Manager\SocialiteWasCalled $socialiteWasCalled
     */
    public function handle(SocialiteWasCalled $socialiteWasCalled)
    {
        $socialiteWasCalled->extendSocialite('discord', __NAMESPACE__.'\Provider');
    }
}


text:
using System;

namespace Pharmatechnik.Nav.Language.Text;

[Serializable]
public readonly struct LinePosition: IEquatable<LinePosition>, IComparable<LinePosition> {

    readonly int _line;
    readonly int _character;

    public LinePosition(int line, int character) {

        if (line < 0) {
            throw new ArgumentOutOfRangeException(nameof(line));
        }

        if (character < 0) {
            throw new ArgumentOutOfRangeException(nameof(character));
        }

        _line      = line;
        _character = character;
    }

    // TODO Missing hinzufügen
    public static readonly LinePosition Empty = new(0, 0);

    /// <summary>
    /// The line number. The first line in a file is defined as line 0 (zero based line numbering).
    /// </summary>
    public int Line => _line;

    /// <summary>
    /// The character position within the line (zero based).
    /// </summary>
    public int Character => _character;

    /// <summary>
    /// Determines whether two <see cref="LinePosition"/> are the same.
    /// </summary>
    public static bool operator ==(LinePosition left, LinePosition right) {
        return left.Equals(right);
    }

    /// <summary>
    /// Determines whether two <see cref="LinePosition"/> are different.
    /// </summary>
    public static bool operator !=(LinePosition left, LinePosition right) {
        return !left.Equals(right);
    }

    /// <summary>
    /// Determines whether two <see cref="LinePosition"/> are the same.
    /// </summary>
    /// <param name="other">The object to compare.</param>
    public bool Equals(LinePosition other) {
        return other.Line == Line && other.Character == Character;
    }

    /// <summary>
    /// Determines whether two <see cref="LinePosition"/> are the same.
    /// </summary>
    /// <param name="obj">The object to compare.</param>
    public override bool Equals(object obj) {
        return obj is LinePosition position && Equals(position);
    }

    /// <summary>
    /// Provides a hash function for <see cref="LinePosition"/>.
    /// </summary>
    public override int GetHashCode() {
        return Line ^ Character;
    }

    /// <summary>
    /// Provides a string representation for <see cref="LinePosition"/>.
    /// For better readability line numbers and characters are converted to 1 based numbers.
    /// </summary>
    /// <example>1,5</example>
    public override string ToString() {
        return $"{Line + 1},{Character + 1}";
    }

    public int CompareTo(LinePosition other) {
        int result = _line.CompareTo(other._line);
        return result != 0 ? result : _character.CompareTo(other.Character);
    }

    public static bool operator >(LinePosition left, LinePosition right) {
        return left.CompareTo(right) > 0;
    }

    public static bool operator >=(LinePosition left, LinePosition right) {
        return left.CompareTo(right) >= 0;
    }

    public static bool operator <(LinePosition left, LinePosition right) {
        return left.CompareTo(right) < 0;
    }

    public static bool operator <=(LinePosition left, LinePosition right) {
        return left.CompareTo(right) <= 0;
    }

}


text:
class AddEventTypeIdToEvents < ActiveRecord::Migration
  def change
    add_column :events, :event_type, :integer
  end
end


text:
A hungry feed parser

## Getting Started
Install the module with: `npm install hungry`

```javascript
var Hungry = require('hungry');
var hungry = new Hungry('http://mysite.com/rss');
hungry.feed(function(err, contents) {...} );
```

## Documentation
_(Coming soon)_

## Examples
_(Coming soon)_

## Contributing
In lieu of a formal styleguide, take care to maintain the existing coding style. Add unit tests for any new or changed functionality. Lint and test your code using [Grunt](http://gruntjs.com/).

## Release History
_(Nothing yet)_

## License
Copyright (c) 2014 Nicola Orritos. Licensed under the Apache v2 license.


text:
<?php
namespace DigitalCanvas\Mailchimp\Test\Lists;

use DigitalCanvas\Mailchimp\Test\MailchimpTestTrait;
use PHPUnit_Framework_TestCase;

/**
 * Class SubscribeTest
 *
 * @package Lists
 */
class MemberTest extends PHPUnit_Framework_TestCase
{
    use MailchimpTestTrait;

    /**
     * @test
     */
    public function subscribe_to_list()
    {
        $list     = $this->haveList();
        $listid   = $list['id'];
        $email    = $this->faker->freeEmail;
        $memberid = md5(strtolower($email));
        try {
            $member = $this->api->members->create($listid, $email);
            $this->assertEquals($email, $member['email_address']);
            $this->assertEquals('subscribed', $member['status']);
            $this->assertEquals($memberid, $member['id']);
        } catch (\Exception $e) {
            $response = array_pop($this->requests)['response'];
            $error    = json_decode($response->getBody()->getContents(), true);
            $this->fail($error['detail']);
        } finally {
            if ($list['id']) {
                $this->api->lists->delete($list['id']);
            }

        }
    }

    /**
     * @test
     */
    public function list_subscribers()
    {
        $list = $this->haveList();
        try {
            $this->haveMember($list['id']);
            $this->haveMember($list['id']);
            $members = $this->api->members->getList($list['id']);
            $this->assertInstanceOf('DigitalCanvas\Mailchimp\Collection\PaginatedCollection', $members);
            $this->assertEquals(2, count($members));
            $this->assertEquals(2, $members->getTotalItems());
        } catch (\Exception $e) {
            $response = array_pop($this->requests)['response'];
            $error    = json_decode($response->getBody()->getContents(), true);
            $this->fail($error['detail']);
        } finally {
            if ($list['id']) {
                $this->api->lists->delete($list['id']);
            }
        }
    }

    /**
     * @test
     */
    public function get_member_details()
    {
        $email = $this->faker->freeEmail;
        $hash  = md5(strtolower($email));
        $list  = $this->haveList();
        try {
            $this->haveMember($list['id'], $email);
            $member = $this->api->members->getDetails($list['id'], $hash);
            $this->assertEquals($email, $member['email_address']);
        } catch (\Exception $e) {
            $response = array_pop($this->requests)['response'];
            $error    = json_decode($response->getBody()->getContents(), true);
            $this->fail($error['detail']);
        } finally {
            if ($list['id']) {
                $this->api->lists->delete($list['id']);
            }
        }
    }

    /**
     * @test
     */
    public function get_member_details_by_email()
    {
        $email = $this->faker->freeEmail;
        $list  = $this->haveList();
        try {
            $this->haveMember($list['id'], $email);
            $member = $this->api->members->getByEmail($list['id'], $email);
            $this->assertEquals($email, $member['email_address']);
        } catch (\Exception $e) {
            $response = array_pop($this->requests)['response'];
            $error    = json_decode($response->getBody()->getContents(), true);
            $this->fail($error['detail']);
        } finally {
            if ($list['id']) {
                $this->api->lists->delete($list['id']);
            }
        }
    }

    /**
     * @test
     */
    public function unsubscribe_from_list()
    {
        $email = $this->faker->freeEmail;
        $list  = $this->haveList();
        try {
            $member = $this->haveMember($list['id'], $email, 'subscribed');
            $result = $this->api->members->unsubscribe($list['id'], $email);
            $this->assertEquals($member['email_address'], $result['email_address']);
            $this->assertEquals('unsubscribed', $result['status']);
        } catch (\Exception $e) {
            $response = array_pop($this->requests)['response'];
            $error    = json_decode($response->getBody()->getContents(), true);
            $this->fail($error['detail']);
        } finally {
            if ($list['id']) {
                $this->api->lists->delete($list['id']);
            }
        }
    }

    /**
     * @test
     */
    public function resubscribe_to_list()
    {
        $email = $this->faker->freeEmail;
        $list  = $this->haveList();
        try {
            $member = $this->haveMember($list['id'], $email, 'unsubscribed');
            $this->assertEquals('unsubscribed', $member['status']);
            $result = $this->api->members->resubscribe($list['id'], $email);
            $this->assertEquals($member['email_address'], $result['email_address']);
            $this->assertEquals('subscribed', $result['status']);
        } catch (\Exception $e) {
            $response = array_pop($this->requests)['response'];
            $error    = json_decode($response->getBody()->getContents(), true);
            $this->fail($error['detail']);
        } finally {
            if ($list['id']) {
                $this->api->lists->delete($list['id']);
            }
        }
    }

    /**
     * @test
     */
    public function update_member_details()
    {
        $email = $this->faker->freeEmail;
        $list  = $this->haveList();
        $updates = [
            'status' => 'unsubscribed',
            'email_type' => 'text',
        ];
        try {
            $member = $this->haveMember($list['id'], $email, 'subscribed');
            $this->assertEquals('subscribed', $member['status']);
            $this->assertEquals('html', $member['email_type']);
            $result = $this->api->members->update($list['id'], $email, $updates);
            $this->assertEquals($updates['status'], $result['status']);
            $this->assertEquals($updates['email_type'], $result['email_type']);
        } catch (\Exception $e) {
            $response = array_pop($this->requests)['response'];
            $error    = json_decode($response->getBody()->getContents(), true);
            $this->fail($error['detail']);
        } finally {
            if ($list['id']) {
                $this->api->lists->delete($list['id']);
            }
        }
    }
}


text:
Communities

     All Feeds
     Python
     Android
     Javascript

View all


text:
[![Build Status](https://dev.azure.com/wikiazure/kemp%20toolkit/_apis/build/status/kemp%20toolkit?branchName=master)](https://dev.azure.com/wikiazure/kemp%20toolkit/_build/latest?definitionId=23&branchName=master)
# Kemp toolkit

## QuickStart Guide for POCs

## Scope of POC

Description: Define the administrative structure of the extended project team. Include roles and responsibilities, contact information, reporting structure, server share names, file directory structures, meeting schedules, and status reporting.

Determine what functionalities must be reviewed within a reasonable time frame (i.e. 75 mins) and within organizational and management constraints. Look at most the urgent and/or strategic aspects of the business problem and narrow down the assessment to a specific scope.

The scope document should answer the following questions:
- What goals does the operations assessment intend to accomplish?
- What are the applications that require highly available application delivery?
- How much traffic is generated by the applications for which the Load Balancer will service?
- How many application requests are received during peak utilization?
- Are there any special requirements for content manipulation, data caching, data compression or SSL handling?
- What security features do you need with your Load Balancers? i.e. Content Switching, SSL Acceleration, Data Compression, Data Caching Intrusion Prevention, Single Sign-On, Pre-Authentication...
- How many redundant application servers are currently working in your environment?
- Timeframe to implement an ADC within your infrastructure?


text:
package com.jme3.system.jopenvr;
import com.sun.jna.Pointer;
import com.sun.jna.Structure;
import java.util.Arrays;
import java.util.List;
/**
 * native declaration : headers\openvr_capi.h:1615

 * This file was autogenerated by JNAerator,

 * a tool written by Olivier Chafik that uses a few opensource projects..

 * For help, please visit NativeLibs4Java , Rococoa, or JNA.
 */
public class InputPoseActionData_t extends Structure {
	public byte bActive;
	/** C type : VRInputValueHandle_t */
	public long activeOrigin;
	/** C type : TrackedDevicePose_t */
	public TrackedDevicePose_t pose;
	public InputPoseActionData_t() {
		super();
	}
        @Override
	protected List<String> getFieldOrder() {
		return Arrays.asList("bActive", "activeOrigin", "pose");
	}
	/**
	 * @param activeOrigin C type : VRInputValueHandle_t

	 * @param pose C type : TrackedDevicePose_t
	 */
	public InputPoseActionData_t(byte bActive, long activeOrigin, TrackedDevicePose_t pose) {
		super();
		this.bActive = bActive;
		this.activeOrigin = activeOrigin;
		this.pose = pose;
	}
	public InputPoseActionData_t(Pointer peer) {
		super(peer);
	}
	public static class ByReference extends InputPoseActionData_t implements Structure.ByReference {

	};
	public static class ByValue extends InputPoseActionData_t implements Structure.ByValue {

	};
}


text:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent" android:layout_height="match_parent">

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textAppearance="?android:attr/textAppearanceMedium"
        android:text="@string/fingerprintSetupWizardTitleText"
        android:id="@+id/textView"
        android:layout_alignParentTop="true"
        android:layout_alignParentLeft="true"
        android:layout_alignParentStart="true" />

    <EditText
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:inputType="textPassword"
        android:ems="10"
        android:id="@+id/passwordInput"
        android:layout_below="@+id/textView"
        android:layout_alignParentLeft="true"
        android:layout_alignParentStart="true"
        android:layout_alignParentRight="true"
        android:layout_alignParentEnd="true"
        android:hint="@string/nfcWizard05PasswordInputText" />

    <EditText
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:inputType="textPassword"
        android:ems="10"
        android:id="@+id/passwordReInput"
        android:layout_below="@+id/passwordInput"
        android:layout_alignParentLeft="true"
        android:layout_alignParentStart="true"
        android:layout_alignParentRight="true"
        android:layout_alignParentEnd="true"
        android:hint="@string/nfcWizard05PasswordReInputText" />

</RelativeLayout>


text:
module Headlines
  module SecurityHeaders
    class ContentType < SecurityHeader
      def score
        value.start_with?("text/html") ? score_by_value : 0
      end

      private

      def score_by_value
        utf_charset? ? 2 : 1
      end

      def utf_charset?
        value.gsub(" ", "").downcase.scan("charset=utf-8").any?
      end

      private

      def rating
        ok? ? "OK" : "WARN"
      end

      def ok?
        score == 2
      end
    end
  end
end


text:
api
===
project defining the REST API itself. See api/api.json for a full
description of the API.

Generated Code
==============
The .apidoc file lists the specific targets which are generated by
apidoc. To regenerate code, clone github.com/mbryzek/apidoc-cli and

    apidoc update

To Run Locally
==============

    $ sbt
    sbt> project api
    sbt> run 9000

    Goto http://localhost:9000 in your browser


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

var ProductSchema = new mongoose.Schema({
  product_name: { type: String, trim: true },
  created_at: { type: Date, default: Date.now },
  updated_at: { type: Date, default: Date.now },
  description: {type: String},
  quantity: { type: Number},
  img_url: {type: String},
  orders: [{ type: mongoose.Schema.Types.ObjectId, ref:'Order'}]
});

mongoose.model('Product', ProductSchema);
ProductSchema.path('product_name').required(true, "Product Name is required");


text:
package org.apache.geode.management.internal.cli.result;

import org.apache.geode.management.cli.Result;

/**
 * Exception wrapper around a command result.
 *
 * @since GemFire 7.0
 */
public class CommandResultException extends Exception {
  private static final long serialVersionUID = 1L;

  private final Result result;

  public CommandResultException(final Result result) {
    this.result = result;
  }

  public Result getResult() {
    return this.result;
  }
}


text:
from .helper import DataHelper, EmailDelivery
"""
Module for work with data
"""

__all__ = [
    'DataHelper',
    'EmailDelivery'
]


text:
(function(){
	var receptionId = window.location.pathname.split("/")[2];

	angular
		.module("Kubik")
		.controller("ReceptionDetailsCtrl", ReceptionDetailsCtrl);

	function ReceptionDetailsCtrl($scope, $http, $timeout){
		var vm = this;

		vm.calculateReceptionQuantity = calculateReceptionQuantity;
		vm.cancelReception = cancelReception;
		vm.confirmReceptionValidation = confirmReceptionValidation;
		vm.loadReception = loadReception;
		vm.openProductCard = openProductCard;
		vm.openSupplierCard = openSupplierCard;
		vm.receptionChanged = receptionChanged;
		vm.redirectToPurchaseOrders = redirectToPurchaseOrders;
		vm.redirectToReceptions = redirectToReceptions;
		vm.saveReception = saveReception;
		vm.validateReception = validateReception;

		loadReception();

		$scope.$on("supplierSaved", function($event, supplier){
			vm.loadReception();
		});

		function calculateReceptionQuantity(reception){
			var quantity = 0;
			if(reception != undefined){
				for(var detailIndex in reception.details){
					var detail = reception.details[detailIndex];

					quantity += detail.quantityToReceive;
				}
			}

			return quantity;
		}

		function cancelReception(){
			vm.order.status = "CANCELED";

			vm.saveOrder(function(){
				$(".confirm-cancel").modal("hide");

				$(".redirection-modal").modal();
			});
		}

		function confirmReceptionValidation(){
			$(".confirm-validation").modal();
		}

		function loadReception(){
			$http.get(receptionId).success(receptionLoaded);

			function receptionLoaded(reception){
				vm.reception = reception;

				$timeout(function(){
					if(vm.inputIdToFocus != undefined){
						$("#" + vm.inputIdToFocus).focus();
					}
				});
			}
		}

		function openProductCard($event, product){
			$event.stopPropagation();

			$scope.$broadcast("openProductCard", product);
		}

		function openSupplierCard($event, supplier){
			$event.stopPropagation();

			$scope.$broadcast("openSupplierCard", supplier);
		}

		function receptionChanged($event){
			vm.inputIdToFocus = $event.target.id;
			if(vm.quantityChangedTimer != undefined) clearTimeout(vm.quantityChangedTimer);

			vm.quantityChangedTimer = setTimeout(vm.saveReception, 1000);
		}

		function redirectToPurchaseOrders(){
			location.href = "../purchaseOrder";
		}

		function redirectToReceptions(){
			location.href = "../reception";
		}

		function saveReception(success){
			vm.loading = true;

			return $http
				.post(".", vm.reception)
				.then(receptionSaved).finally(postCompleted);

			function postCompleted(){
				vm.loading = false;
			}

			function receptionSaved(reception){
				vm.loadReception();

				if(success != undefined){
					success();
				}
			}
		}

		function validateReception(){
			vm.reception.status = "CLOSED";

			vm.saveReception(receptionSaved);

			function receptionSaved(){
				$(".confirm-validation").modal("hide");

				$(".redirection-modal").modal();
			}
		}
	}
})();


text:
<?xml version="1.0" encoding="utf-8"?>
<resources>
    <color name="colorPrimary">#3F51B5</color>
    <color name="colorPrimaryDark">#303F9F</color>
    <color name="colorAccent">#FF4081</color>

    <color name="white">#efefef</color>

    <color name="black_50_alpha">#44000000</color>
    <color name="white_50_alpha">#44ffffff</color>
    <color name="colorPrimary_50_alpha">#553F51B5</color>
    <color name="colorAccent_50_alpha">#55FF4081</color>
</resources>


text:
package cd.go.contrib.elasticagents.marathon;

import java.util.Map;
import java.util.concurrent.Semaphore;

public class SetupSemaphore implements Runnable {
    private final Integer maxInstances;
    private final Map<?, ?> instances;
    private final Semaphore semaphore;

    SetupSemaphore(Integer maxInstances, Map<?, ?> instances, Semaphore semaphore) {
        this.maxInstances = maxInstances;
        this.instances = instances;
        this.semaphore = semaphore;
    }

    @Override
    public void run() {
        int currentContainers = instances.size();
        int availablePermits = maxInstances - currentContainers;
        if (availablePermits <= 0) {
            // no more capacity available.
            semaphore.drainPermits();
        } else {
            int semaphoreValueDifference = availablePermits - semaphore.availablePermits();
            if (semaphoreValueDifference > 0) {
                semaphore.release(semaphoreValueDifference);
            } else if (semaphoreValueDifference < 0) {
                semaphore.tryAcquire(Math.abs(semaphoreValueDifference));
            }
        }
    }
}


text:
var annotation = require('css-annotation')
var postcss = require('postcss')

module.exports = function (css) {
    var root = postcss.parse(css)

    var flags = []
    var tmpNodes = []
    var results = []
    root.each(function (node) {
        if (node.type === 'comment') {
            var res = annotation.read(node.text)
            if (res.start) {
                flags.push({
                    name: res.start,
                    start: true,
                    end: false
                })
                return
            }
            if (res.end){
                flags.forEach(function (flag) {
                    if (flag.name === res.end) {
                        flag.end = true
                    }
                })
            }
        }

        flags.forEach(function (flag) {
            if (flag.start === true && flag.end === false && node.type !== "comment") {
                tmpNodes.push(node)
            }

            if (flag.start === true && flag.end === true && tmpNodes.length !== 0) {
                results.push({
                    name: flag.name,
                    nodes: tmpNodes
                })
                tmpNodes = []
            }
        })

    })

    return results
}


text:
<?php

namespace PhpSpec\Wrapper\Subject\Expectation;

/**
 * Class NegativeThrow
 * @package PhpSpec\Wrapper\Subject\Expectation
 */
class NegativeThrow extends DuringCall implements ThrowExpectation
{
    /**
     * @param object $object
     * @param string $method
     * @param array  $arguments
     *
     * @return mixed
     */
    protected function runDuring($object, $method, array $arguments = array())
    {
        return $this->getMatcher()->negativeMatch('throw', $object, $this->getArguments())
            ->during($method, $arguments);
    }
}


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

namespace NavigationApp
{
    public partial class HomePage
    {
        public HomePage()
        {
            InitializeComponent();
        }
    }
}


text:
@class MainWindowController;

@interface AppDelegate : NSObject<NSApplicationDelegate>

@property (nonatomic, strong) MainWindowController *mainWindowController;

@end


text:
<?php
defined('C5_EXECUTE') or die("Access Denied.");
?>

<form method="post" action="<?php echo $view->action('submit'); ?>">
    <?php echo $token->output('submit'); ?>

        <?php echo $form->checkbox('enable_api', 1, $enable_api) ?>
        <?php echo t('Enable API'); ?>

<?=t('You must ensure that the HTTP Authorization header is available on your web server. Some web servers or proxies may strip it away.')?>

<?php if ($enable_api) { ?>

<?=t('API Integrations')?>

        <?php if ($clients && count($clients)) { ?>

                <?php foreach($clients as $client) { ?>

<a href="<?=URL::to('/dashboard/system/api/integrations', 'view_client', $client->getIdentifier())?>">

                        <?=$client->getName()?>

                    <?php
                }
                ?>

        <?php } else { ?>

<?=t('None')?>

        <?php } ?>

<a href="<?=URL::to('/dashboard/system/api/integrations', 'add')?>" class="btn btn-secondary btn-xs mb-3"><?=t('Add Integration')?>

<?=t('Enabled Grant Types')?>

<?=t('Choose which OAuth2 grant types you want to have access to the API for this site.')?>

        <?php foreach($availableGrantTypes as $key => $label) {
            $enabled = false;
            if (isset($grantTypes[$key]) && $grantTypes[$key] === true) {
                $enabled = true;
            }
            ?>

                <?=$form->checkbox('enabledGrantTypes[]', $key, $enabled)?>
                <?=$label?>

        <?php } ?>

<?php } ?>

            <button class="btn btn-primary float-end" type="submit"><?=t("Save")?></button>

</form>


text:
package info.joriki.pdf;

public interface DeviceColorSpaces
{
  final static int GRAY = 0;
  final static int RGB  = 1;
  final static int CMYK = 2;

  final static PDFColorSpace [] deviceColorSpaces = new PDFColorSpace [] {
    new DeviceGrayColorSpace (),
    new DeviceRGBColorSpace (),
    new DeviceCMYKColorSpace ()
      };

  final static String [] deviceColorSpaceSuffixes = {"Gray","RGB","CMYK"};
}


text:
package myapplicationishello.com.example.hsport.sch_app;

import android.content.ComponentName;
import android.content.ContentValues;
import android.content.Context;
import android.content.Intent;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.EditText;
import android.widget.Toast;

/**
 * Created by Surendra on 12/05/16.
 */
public class Second extends AppCompatActivity {
    EditText et13, et14, et15, et16, et17, et18, et19, et20;
    SQLiteDatabase dBase;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.second_main);
        dBase =openOrCreateDatabase("emp_db", Context.MODE_PRIVATE,null);
        dBase.execSQL("create table if not exists emp(id number,name varchar(100),desig varchar(100),dept varchar(100))");
        et13  = (EditText)findViewById(R.id.editText13);
        et14  = (EditText)findViewById(R.id.editText14);
        et15  = (EditText)findViewById(R.id.editText15);
        et16  = (EditText)findViewById(R.id.editText16);
        et17  = (EditText)findViewById(R.id.editText17);
        et18  = (EditText)findViewById(R.id.editText18);
        et19  = (EditText)findViewById(R.id.editText19);
        et20  = (EditText)findViewById(R.id.editText20);
    }
    public void submit(View v) {
        ContentValues values = new ContentValues();
        values.put("Home No",Integer.parseInt( et13.getText().toString()));
        values.put("Enter Street", et14.getText().toString());
        values.put("Enetr Village Name", et15.getText().toString());
        values.put("Enter post", et16.getText().toString());
        values.put("Enter Mandal", et17.getText().toString());
        values.put("Enter District Name",et18.getText().toString());
        values.put("Enter State Name", et19.getText().toString());
        values.put("Enter PIN",Integer.parseInt(et20.getText().toString()));
        long count = dBase.insert("emp", null, values);
        if (count > 0) {
            Toast.makeText(getApplicationContext(), " details is successfully submitted", Toast.LENGTH_LONG).show();
            et13.setText("");
            et14.setText("");
            et15.setText("");
            et16.setText("");
            et17.setText("");
            et18.setText("");
            et19.setText("");
            et20.setText("");
        } else {
            Toast.makeText(getApplicationContext(), "data is  successfully submitted", Toast.LENGTH_LONG).show();
        }
    }
       public  void next(View v){
        Intent i=new Intent();
        i.setComponent(new ComponentName(getApplicationContext(),Third.class));
        startActivity(i);
    }
}


text:
@interface PodsDummy_GifCameraController : NSObject
@end
@implementation PodsDummy_GifCameraController
@end


text:
using Spring.Web.Mvc;
using System.Web.Mvc;
using System.Web.Routing;

namespace LoTBlog
{
    // 注意: 有关启用 IIS6 或 IIS7 经典模式的说明,
    // 请访问 http://go.microsoft.com/?LinkId=9394801
    public class MvcApplication : SpringMvcApplication//System.Web.HttpApplication
    {
        protected void Application_Start()
        {
            AreaRegistration.RegisterAllAreas();

            FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
            RouteConfig.RegisterRoutes(RouteTable.Routes);

            //配置log4net日志
            log4net.Config.XmlConfigurator.Configure();
        }
    }
}


text:
package com.adeptj.modules.commons.jdbc;

import org.jetbrains.annotations.NotNull;
import org.osgi.annotation.versioning.ProviderType;

import javax.sql.DataSource;

/**
 * DataSourceService interface for providing Hikari JDBC DataSource.
 *
 * @author Rakesh.Kumar, AdeptJ.
 */
@ProviderType
public interface DataSourceService {

    /**
     * Returns the configured Hikari {@link DataSource} instance.
     * <p>
     * Note: Caller should NEVER try to close the DataSource as it's lifecycle is managed by HikariDataSourceService.
     *
     * @return The configured Hikari {@link DataSource} instance.
     */
    @NotNull DataSource getDataSource();
}


text:
"use strict";

var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault");

Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.default = void 0;

var _extends2 = _interopRequireDefault(require("@babel/runtime/helpers/extends"));

var _objectWithoutPropertiesLoose2 = _interopRequireDefault(require("@babel/runtime/helpers/objectWithoutPropertiesLoose"));

var React = _interopRequireWildcard(require("react"));

var _propTypes = _interopRequireDefault(require("prop-types"));

var _clsx = _interopRequireDefault(require("clsx"));

var _unstyled = require("@material-ui/unstyled");

var _utils = require("@material-ui/utils");

var _styled = _interopRequireDefault(require("../styles/styled"));

var _useThemeProps = _interopRequireDefault(require("../styles/useThemeProps"));

var _Input = _interopRequireDefault(require("../Input"));

var _FilledInput = _interopRequireDefault(require("../FilledInput"));

var _OutlinedInput = _interopRequireDefault(require("../OutlinedInput"));

var _InputLabel = _interopRequireDefault(require("../InputLabel"));

var _FormControl = _interopRequireDefault(require("../FormControl"));

var _FormHelperText = _interopRequireDefault(require("../FormHelperText"));

var _Select = _interopRequireDefault(require("../Select"));

var _textFieldClasses = require("./textFieldClasses");

var _jsxRuntime = require("react/jsx-runtime");

const _excluded = ["autoComplete", "autoFocus", "children", "className", "color", "defaultValue", "disabled", "error", "FormHelperTextProps", "fullWidth", "helperText", "id", "InputLabelProps", "inputProps", "InputProps", "inputRef", "label", "maxRows", "minRows", "multiline", "name", "onBlur", "onChange", "onFocus", "placeholder", "required", "rows", "select", "SelectProps", "type", "value", "variant"];

function _getRequireWildcardCache(nodeInterop) { if (typeof WeakMap !== "function") return null; var cacheBabelInterop = new WeakMap(); var cacheNodeInterop = new WeakMap(); return (_getRequireWildcardCache = function (nodeInterop) { return nodeInterop ? cacheNodeInterop : cacheBabelInterop; })(nodeInterop); }

function _interopRequireWildcard(obj, nodeInterop) { if (!nodeInterop && obj && obj.__esModule) { return obj; } if (obj === null || typeof obj !== "object" && typeof obj !== "function") { return { default: obj }; } var cache = _getRequireWildcardCache(nodeInterop); if (cache && cache.has(obj)) { return cache.get(obj); } var newObj = {}; var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var key in obj) { if (key !== "default" && Object.prototype.hasOwnProperty.call(obj, key)) { var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null; if (desc && (desc.get || desc.set)) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } newObj.default = obj; if (cache) { cache.set(obj, newObj); } return newObj; }

const variantComponent = {
  standard: _Input.default,
  filled: _FilledInput.default,
  outlined: _OutlinedInput.default
};

const useUtilityClasses = styleProps => {
  const {
    classes
  } = styleProps;
  const slots = {
    root: ['root']
  };
  return (0, _unstyled.unstable_composeClasses)(slots, _textFieldClasses.getTextFieldUtilityClass, classes);
};

const TextFieldRoot = (0, _styled.default)(_FormControl.default, {
  name: 'MuiTextField',
  slot: 'Root',
  overridesResolver: (props, styles) => styles.root
})({});
/**
 * The `TextField` is a convenience wrapper for the most common cases (80%).
 * It cannot be all things to all people, otherwise the API would grow out of control.
 *
 * ## Advanced Configuration
 *
 * It's important to understand that the text field is a simple abstraction
 * on top of the following components:
 *
 * - [FormControl](/api/form-control/)
 * - [InputLabel](/api/input-label/)
 * - [FilledInput](/api/filled-input/)
 * - [OutlinedInput](/api/outlined-input/)
 * - [Input](/api/input/)
 * - [FormHelperText](/api/form-helper-text/)
 *
 * If you wish to alter the props applied to the `input` element, you can do so as follows:
 *
 * ```jsx
 * const inputProps = {
 *   step: 300,
 * };
 *
 * return <TextField id="time" type="time" inputProps={inputProps} />;
 * ```
 *
 * For advanced cases, please look at the source of TextField by clicking on the
 * "Edit this page" button above. Consider either:
 *
 * - using the upper case props for passing values directly to the components
 * - using the underlying components directly as shown in the demos
 */

const TextField = /*#__PURE__*/React.forwardRef(function TextField(inProps, ref) {
  const props = (0, _useThemeProps.default)({
    props: inProps,
    name: 'MuiTextField'
  });
  const {
    autoComplete,
    autoFocus = false,
    children,
    className,
    color = 'primary',
    defaultValue,
    disabled = false,
    error = false,
    FormHelperTextProps,
    fullWidth = false,
    helperText,
    id,
    InputLabelProps,
    inputProps,
    InputProps,
    inputRef,
    label,
    maxRows,
    minRows,
    multiline = false,
    name,
    onBlur,
    onChange,
    onFocus,
    placeholder,
    required = false,
    rows,
    select = false,
    SelectProps,
    type,
    value,
    variant = 'outlined'
  } = props,
        other = (0, _objectWithoutPropertiesLoose2.default)(props, _excluded);
  const styleProps = (0, _extends2.default)({}, props, {
    autoFocus,
    color,
    disabled,
    error,
    fullWidth,
    multiline,
    required,
    select,
    variant
  });
  const classes = useUtilityClasses(styleProps);

  if (process.env.NODE_ENV !== 'production') {
    if (select && !children) {
      console.error('Material-UI: `children` must be passed when using the `TextField` component with `select`.');
    }
  }

  const InputMore = {};

  if (variant === 'outlined') {
    if (InputLabelProps && typeof InputLabelProps.shrink !== 'undefined') {
      InputMore.notched = InputLabelProps.shrink;
    }

    if (label) {
      var _InputLabelProps$requ;

      const displayRequired = (_InputLabelProps$requ = InputLabelProps == null ? void 0 : InputLabelProps.required) != null ? _InputLabelProps$requ : required;
      InputMore.label = /*#__PURE__*/(0, _jsxRuntime.jsxs)(React.Fragment, {
        children: [label, displayRequired && '\u00a0*']
      });
    }
  }

  if (select) {
    // unset defaults from textbox inputs
    if (!SelectProps || !SelectProps.native) {
      InputMore.id = undefined;
    }

    InputMore['aria-describedby'] = undefined;
  }

  const helperTextId = helperText && id ? `${id}-helper-text` : undefined;
  const inputLabelId = label && id ? `${id}-label` : undefined;
  const InputComponent = variantComponent[variant];
  const InputElement = /*#__PURE__*/(0, _jsxRuntime.jsx)(InputComponent, (0, _extends2.default)({
    "aria-describedby": helperTextId,
    autoComplete: autoComplete,
    autoFocus: autoFocus,
    defaultValue: defaultValue,
    fullWidth: fullWidth,
    multiline: multiline,
    name: name,
    rows: rows,
    maxRows: maxRows,
    minRows: minRows,
    type: type,
    value: value,
    id: id,
    inputRef: inputRef,
    onBlur: onBlur,
    onChange: onChange,
    onFocus: onFocus,
    placeholder: placeholder,
    inputProps: inputProps
  }, InputMore, InputProps));
  return /*#__PURE__*/(0, _jsxRuntime.jsxs)(TextFieldRoot, (0, _extends2.default)({
    className: (0, _clsx.default)(classes.root, className),
    disabled: disabled,
    error: error,
    fullWidth: fullWidth,
    ref: ref,
    required: required,
    color: color,
    variant: variant,
    styleProps: styleProps
  }, other, {
    children: [label && /*#__PURE__*/(0, _jsxRuntime.jsx)(_InputLabel.default, (0, _extends2.default)({
      htmlFor: id,
      id: inputLabelId
    }, InputLabelProps, {
      children: label
    })), select ? /*#__PURE__*/(0, _jsxRuntime.jsx)(_Select.default, (0, _extends2.default)({
      "aria-describedby": helperTextId,
      id: id,
      labelId: inputLabelId,
      value: value,
      input: InputElement
    }, SelectProps, {
      children: children
    })) : InputElement, helperText && /*#__PURE__*/(0, _jsxRuntime.jsx)(_FormHelperText.default, (0, _extends2.default)({
      id: helperTextId
    }, FormHelperTextProps, {
      children: helperText
    }))]
  }));
});
process.env.NODE_ENV !== "production" ? TextField.propTypes
/* remove-proptypes */
= {
  // ----------------------------- Warning --------------------------------
  // | These PropTypes are generated from the TypeScript type definitions |
  // |     To update them edit the d.ts file and run "yarn proptypes"     |
  // ----------------------------------------------------------------------

  /**
   * This prop helps users to fill forms faster, especially on mobile devices.
   * The name can be confusing, as it's more like an autofill.
   * You can learn more about it [following the specification](https://html.spec.whatwg.org/multipage/form-control-infrastructure.html#autofill).
   */
  autoComplete: _propTypes.default.string,

  /**
   * If `true`, the `input` element is focused during the first mount.
   * @default false
   */
  autoFocus: _propTypes.default.bool,

  /**
   * @ignore
   */
  children: _propTypes.default.node,

  /**
   * Override or extend the styles applied to the component.
   */
  classes: _propTypes.default.object,

  /**
   * @ignore
   */
  className: _propTypes.default.string,

  /**
   * The color of the component. It supports those theme colors that make sense for this component.
   * @default 'primary'
   */
  color: _propTypes.default
  /* @typescript-to-proptypes-ignore */
  .oneOfType([_propTypes.default.oneOf(['primary', 'secondary', 'error', 'info', 'success', 'warning']), _propTypes.default.string]),

  /**
   * The default value. Use when the component is not controlled.
   */
  defaultValue: _propTypes.default.any,

  /**
   * If `true`, the component is disabled.
   * @default false
   */
  disabled: _propTypes.default.bool,

  /**
   * If `true`, the label is displayed in an error state.
   * @default false
   */
  error: _propTypes.default.bool,

  /**
   * Props applied to the [`FormHelperText`](/api/form-helper-text/) element.
   */
  FormHelperTextProps: _propTypes.default.object,

  /**
   * If `true`, the input will take up the full width of its container.
   * @default false
   */
  fullWidth: _propTypes.default.bool,

  /**
   * The helper text content.
   */
  helperText: _propTypes.default.node,

  /**
   * The id of the `input` element.
   * Use this prop to make `label` and `helperText` accessible for screen readers.
   */
  id: _propTypes.default.string,

  /**
   * Props applied to the [`InputLabel`](/api/input-label/) element.
   */
  InputLabelProps: _propTypes.default.object,

  /**
   * [Attributes](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/input#Attributes) applied to the `input` element.
   */
  inputProps: _propTypes.default.object,

  /**
   * Props applied to the Input element.
   * It will be a [`FilledInput`](/api/filled-input/),
   * [`OutlinedInput`](/api/outlined-input/) or [`Input`](/api/input/)
   * component depending on the `variant` prop value.
   */
  InputProps: _propTypes.default.object,

  /**
   * Pass a ref to the `input` element.
   */
  inputRef: _utils.refType,

  /**
   * The label content.
   */
  label: _propTypes.default.node,

  /**
   * If `dense` or `normal`, will adjust vertical spacing of this and contained components.
   * @default 'none'
   */
  margin: _propTypes.default.oneOf(['dense', 'none', 'normal']),

  /**
   * Maximum number of rows to display when multiline option is set to true.
   */
  maxRows: _propTypes.default.oneOfType([_propTypes.default.number, _propTypes.default.string]),

  /**
   * Minimum number of rows to display when multiline option is set to true.
   */
  minRows: _propTypes.default.oneOfType([_propTypes.default.number, _propTypes.default.string]),

  /**
   * If `true`, a `textarea` element is rendered instead of an input.
   * @default false
   */
  multiline: _propTypes.default.bool,

  /**
   * Name attribute of the `input` element.
   */
  name: _propTypes.default.string,

  /**
   * @ignore
   */
  onBlur: _propTypes.default.func,

  /**
   * Callback fired when the value is changed.
   *
   * @param {object} event The event source of the callback.
   * You can pull out the new value by accessing `event.target.value` (string).
   */
  onChange: _propTypes.default.func,

  /**
   * @ignore
   */
  onFocus: _propTypes.default.func,

  /**
   * The short hint displayed in the `input` before the user enters a value.
   */
  placeholder: _propTypes.default.string,

  /**
   * If `true`, the label is displayed as required and the `input` element is required.
   * @default false
   */
  required: _propTypes.default.bool,

  /**
   * Number of rows to display when multiline option is set to true.
   */
  rows: _propTypes.default.oneOfType([_propTypes.default.number, _propTypes.default.string]),

  /**
   * Render a [`Select`](/api/select/) element while passing the Input element to `Select` as `input` parameter.
   * If this option is set you must pass the options of the select as children.
   * @default false
   */
  select: _propTypes.default.bool,

  /**
   * Props applied to the [`Select`](/api/select/) element.
   */
  SelectProps: _propTypes.default.object,

  /**
   * The size of the component.
   */
  size: _propTypes.default
  /* @typescript-to-proptypes-ignore */
  .oneOfType([_propTypes.default.oneOf(['medium', 'small']), _propTypes.default.string]),

  /**
   * The system prop that allows defining system overrides as well as additional CSS styles.
   */
  sx: _propTypes.default.object,

  /**
   * Type of the `input` element. It should be [a valid HTML5 input type](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/input#Form_%3Cinput%3E_types).
   */
  type: _propTypes.default.string,

  /**
   * The value of the `input` element, required for a controlled component.
   */
  value: _propTypes.default.any,

  /**
   * The variant to use.
   * @default 'outlined'
   */
  variant: _propTypes.default.oneOf(['filled', 'outlined', 'standard'])
} : void 0;
var _default = TextField;
exports.default = _default;


text:
Telescope.menuItems.add("adminMenu", {
  route: 'pages',
  label: 'Pages',
  description: 'manage_static_pages'
});

Telescope.subscriptions.preload('pages');

var PageController = RouteController.extend({
  currentPage: function () {
    return Pages.findOne({slug: this.params.slug});
  },
  getTitle: function () {
    return this.currentPage() && this.currentPage().title;
  },
  data: function () {
    return this.currentPage();
  }
});

Meteor.startup(function () {

  Router.onBeforeAction(Router._filters.isAdmin, {only: ['pages']});

  Router.route('/page/:slug', {
    name: 'page',
    controller: PageController
  });

  Router.route('/pages', {
    name: 'pages',
    controller: Telescope.controllers.admin
  });

});