private void visit(Insn insn) {
            RegisterSpec result = insn.getResult();
            if (result != null) {
                processReg(result);
            }
            RegisterSpecList sources = insn.getSources();
            int sz = sources.size();
            for (int i = 0; i < sz; i++) {
                processReg(sources.get(i));
            }
        }

package com.baidu.titan.dexlib.dx.rop.code;

import com.baidu.titan.dexlib.dx.rop.type.StdTypeList;
import com.baidu.titan.dexlib.dx.rop.type.TypeList;
import com.baidu.titan.dexlib.dx.util.Hex;
import com.baidu.titan.dexlib.dx.util.IntList;
import com.baidu.titan.dexlib.dx.util.LabeledList;

/**
 * List of {@link BasicBlock} instances.
 */
public final class BasicBlockList extends LabeledList {

    /**
     * {@code >= -1;} the count of registers required by this method or
     * {@code -1} if not yet calculated
     */
    private int regCount;

    /**
     * Constructs an instance. All indices initially contain {@code null},
     * and the first-block label is initially {@code -1}.
     *
     * @param size the size of the list
     */
    public BasicBlockList(int size) {
        super(size);
        regCount = -1;
    }

    /**
     * Constructs a mutable copy for {@code getMutableCopy()}.
     *
     * @param old block to copy
     */
    private BasicBlockList(BasicBlockList old) {
        super(old);
        regCount = old.regCount;
    }

    /**
     * Gets the element at the given index. It is an error to call
     * this with the index for an element which was never set; if you
     * do that, this will throw {@code NullPointerException}.
     *
     * @param n {@code >= 0, < size();} which index
     * @return {@code non-null;} element at that index
     */
    public BasicBlock get(int n) {
        return (BasicBlock) get0(n);
    }

    /**
     * Sets the basic block at the given index.
     *
     * @param n {@code >= 0, < size();} which index
     * @param bb {@code null-ok;} the element to set at {@code n}
     */
    public void set(int n, BasicBlock bb) {
        super.set(n, bb);
        // Reset regCount, since it will need to be recalculated.
        regCount = -1;
    }

    /**
     * Returns how many registers this method requires. This is simply
     * the maximum of register-number-plus-category referred to by this
     * instance's instructions (indirectly through {@link BasicBlock}
     * instances).
     *
     * @return {@code >= 0;} the register count
     */
    public int getRegCount() {
        if (regCount == -1) {
            RegCountVisitor visitor = new RegCountVisitor();
            forEachInsn(visitor);
            regCount = visitor.getRegCount();
        }
        return regCount;
    }

    /**
     * Gets the total instruction count for this instance. This is the
     * sum of the instruction counts of each block.
     *
     * @return {@code >= 0;} the total instruction count
     */
    public int getInstructionCount() {
        int sz = size();
        int result = 0;
        for (int i = 0; i < sz; i++) {
            BasicBlock one = (BasicBlock) getOrNull0(i);
            if (one != null) {
                result += one.getInsns().size();
            }
        }
        return result;
    }

    /**
     * Gets the total instruction count for this instance, ignoring
     * mark-local instructions which are not actually emitted.
     *
     * @return {@code >= 0;} the total instruction count
     */
    public int getEffectiveInstructionCount() {
        int sz = size();
        int result = 0;
        for (int i = 0; i < sz; i++) {
            BasicBlock one = (BasicBlock) getOrNull0(i);
            if (one != null) {
                InsnList insns = one.getInsns();
                int insnsSz = insns.size();
                for (int j = 0; j < insnsSz; j++) {
                    Insn insn = insns.get(j);
                    if (insn.getOpcode().getOpcode() != RegOps.MARK_LOCAL) {
                        result++;
                    }
                }
            }
        }
        return result;
    }

    /**
     * Gets the first block in the list with the given label, if any.
     *
     * @param label {@code >= 0;} the label to look for
     * @return {@code non-null;} the so-labelled block
     * @throws IllegalArgumentException thrown if the label isn't found
     */
    public BasicBlock labelToBlock(int label) {
        int idx = indexOfLabel(label);
        if (idx < 0) {
            throw new IllegalArgumentException("no such label: " + Hex.u2(label));
        }
        return get(idx);
    }

    /**
     * Visits each instruction of each block in the list, in order.
     *
     * @param visitor {@code non-null;} visitor to use
     */
    public void forEachInsn(Insn.Visitor visitor) {
        int sz = size();
        for (int i = 0; i < sz; i++) {
            BasicBlock one = get(i);
            InsnList insns = one.getInsns();
            insns.forEach(visitor);
        }
    }

    /**
     * Returns an instance that is identical to this one, except that
     * the registers in each instruction are offset by the given
     * amount. Mutability of the result is inherited from the
     * original.
     *
     * @param delta the amount to offset register numbers by
     * @return {@code non-null;} an appropriately-constructed instance
     */
    public BasicBlockList withRegisterOffset(int delta) {
        int sz = size();
        BasicBlockList result = new BasicBlockList(sz);
        for (int i = 0; i < sz; i++) {
            BasicBlock one = (BasicBlock) get0(i);
            if (one != null) {
                result.set(i, one.withRegisterOffset(delta));
            }
        }
        if (isImmutable()) {
            result.setImmutable();
        }
        return result;
    }

    /**
     * Returns a mutable copy of this list.
     *
     * @return {@code non-null;} an appropriately-constructed instance
     */
    public BasicBlockList getMutableCopy() {
        return new BasicBlockList(this);
    }

    /**
     * Gets the preferred successor for the given block. If the block
     * only has one successor, then that is the preferred successor.
     * Otherwise, if the block has a primay successor, then that is
     * the preferred successor. If the block has no successors, then
     * this returns {@code null}.
     *
     * @param block {@code non-null;} the block in question
     * @return {@code null-ok;} the preferred successor, if any
     */
    public BasicBlock preferredSuccessorOf(BasicBlock block) {
        int primarySuccessor = block.getPrimarySuccessor();
        IntList successors = block.getSuccessors();
        int succSize = successors.size();
        switch(succSize) {
            case 0:
                {
                    return null;
                }
            case 1:
                {
                    return labelToBlock(successors.get(0));
                }
        }
        if (primarySuccessor != -1) {
            return labelToBlock(primarySuccessor);
        } else {
            return labelToBlock(successors.get(0));
        }
    }

    /**
     * Compares the catches of two blocks for equality. This includes
     * both the catch types and target labels.
     *
     * @param block1 {@code non-null;} one block to compare
     * @param block2 {@code non-null;} the other block to compare
     * @return {@code true} if the two blocks' non-primary successors
     * are identical
     */
    public boolean catchesEqual(BasicBlock block1, BasicBlock block2) {
        TypeList catches1 = block1.getExceptionHandlerTypes();
        TypeList catches2 = block2.getExceptionHandlerTypes();
        if (!StdTypeList.equalContents(catches1, catches2)) {
            return false;
        }
        IntList succ1 = block1.getSuccessors();
        IntList succ2 = block2.getSuccessors();
        // Both are guaranteed to be the same size.
        int size = succ1.size();
        int primary1 = block1.getPrimarySuccessor();
        int primary2 = block2.getPrimarySuccessor();
        if (((primary1 == -1) || (primary2 == -1)) && (primary1 != primary2)) {
            /*
             * For the current purpose, both blocks in question must
             * either both have a primary or both not have a primary to
             * be considered equal, and it turns out here that that's not
             * the case.
             */
            return false;
        }
        for (int i = 0; i < size; i++) {
            int label1 = succ1.get(i);
            int label2 = succ2.get(i);
            if (label1 == primary1) {
                /*
                 * It should be the case that block2's primary is at the
                 * same index. If not, we consider the blocks unequal for
                 * the current purpose.
                 */
                if (label2 != primary2) {
                    return false;
                }
                continue;
            }
            if (label1 != label2) {
                return false;
            }
        }
        return true;
    }

    /**
     * Instruction visitor class for counting registers used.
     */
    private static class RegCountVisitor implements Insn.Visitor {

        /**
         * {@code >= 0;} register count in-progress
         */
        private int regCount;

        /**
         * Constructs an instance.
         */
        public RegCountVisitor() {
            regCount = 0;
        }

        /**
         * Gets the register count.
         *
         * @return {@code >= 0;} the count
         */
        public int getRegCount() {
            return regCount;
        }

        public void visitPlainInsn(PlainInsn insn) {
            visit(insn);
        }

        public void visitPlainCstInsn(PlainCstInsn insn) {
            visit(insn);
        }

        public void visitSwitchInsn(SwitchInsn insn) {
            visit(insn);
        }

        public void visitThrowingCstInsn(ThrowingCstInsn insn) {
            visit(insn);
        }

        public void visitThrowingInsn(ThrowingInsn insn) {
            visit(insn);
        }

        public void visitFillArrayDataInsn(FillArrayDataInsn insn) {
            visit(insn);
        }

        /**
         * Helper for all the {@code visit*} methods.
         *
         * @param insn {@code non-null;} instruction being visited
         */

        /**
         * Processes the given register spec.
         *
         * @param spec {@code non-null;} the register spec
         */
        private void processReg(RegisterSpec spec) {
            int reg = spec.getNextReg();
            if (reg > regCount) {
                regCount = reg;
            }
        }
    }
}


switch(succSize) {
            case 0:
                {
                    return null;
                }
            case 1:
                {
                    return labelToBlock(successors.get(0));
                }
        }

package com.baidu.titan.dexlib.dx.rop.code;

import com.baidu.titan.dexlib.dx.rop.type.StdTypeList;
import com.baidu.titan.dexlib.dx.rop.type.TypeList;
import com.baidu.titan.dexlib.dx.util.Hex;
import com.baidu.titan.dexlib.dx.util.IntList;
import com.baidu.titan.dexlib.dx.util.LabeledList;

/**
 * List of {@link BasicBlock} instances.
 */
public final class BasicBlockList extends LabeledList {

    /**
     * {@code >= -1;} the count of registers required by this method or
     * {@code -1} if not yet calculated
     */
    private int regCount;

    /**
     * Constructs an instance. All indices initially contain {@code null},
     * and the first-block label is initially {@code -1}.
     *
     * @param size the size of the list
     */
    public BasicBlockList(int size) {
        super(size);
        regCount = -1;
    }

    /**
     * Constructs a mutable copy for {@code getMutableCopy()}.
     *
     * @param old block to copy
     */
    private BasicBlockList(BasicBlockList old) {
        super(old);
        regCount = old.regCount;
    }

    /**
     * Gets the element at the given index. It is an error to call
     * this with the index for an element which was never set; if you
     * do that, this will throw {@code NullPointerException}.
     *
     * @param n {@code >= 0, < size();} which index
     * @return {@code non-null;} element at that index
     */
    public BasicBlock get(int n) {
        return (BasicBlock) get0(n);
    }

    /**
     * Sets the basic block at the given index.
     *
     * @param n {@code >= 0, < size();} which index
     * @param bb {@code null-ok;} the element to set at {@code n}
     */
    public void set(int n, BasicBlock bb) {
        super.set(n, bb);
        // Reset regCount, since it will need to be recalculated.
        regCount = -1;
    }

    /**
     * Returns how many registers this method requires. This is simply
     * the maximum of register-number-plus-category referred to by this
     * instance's instructions (indirectly through {@link BasicBlock}
     * instances).
     *
     * @return {@code >= 0;} the register count
     */
    public int getRegCount() {
        if (regCount == -1) {
            RegCountVisitor visitor = new RegCountVisitor();
            forEachInsn(visitor);
            regCount = visitor.getRegCount();
        }
        return regCount;
    }

    /**
     * Gets the total instruction count for this instance. This is the
     * sum of the instruction counts of each block.
     *
     * @return {@code >= 0;} the total instruction count
     */
    public int getInstructionCount() {
        int sz = size();
        int result = 0;
        for (int i = 0; i < sz; i++) {
            BasicBlock one = (BasicBlock) getOrNull0(i);
            if (one != null) {
                result += one.getInsns().size();
            }
        }
        return result;
    }

    /**
     * Gets the total instruction count for this instance, ignoring
     * mark-local instructions which are not actually emitted.
     *
     * @return {@code >= 0;} the total instruction count
     */
    public int getEffectiveInstructionCount() {
        int sz = size();
        int result = 0;
        for (int i = 0; i < sz; i++) {
            BasicBlock one = (BasicBlock) getOrNull0(i);
            if (one != null) {
                InsnList insns = one.getInsns();
                int insnsSz = insns.size();
                for (int j = 0; j < insnsSz; j++) {
                    Insn insn = insns.get(j);
                    if (insn.getOpcode().getOpcode() != RegOps.MARK_LOCAL) {
                        result++;
                    }
                }
            }
        }
        return result;
    }

    /**
     * Gets the first block in the list with the given label, if any.
     *
     * @param label {@code >= 0;} the label to look for
     * @return {@code non-null;} the so-labelled block
     * @throws IllegalArgumentException thrown if the label isn't found
     */
    public BasicBlock labelToBlock(int label) {
        int idx = indexOfLabel(label);
        if (idx < 0) {
            throw new IllegalArgumentException("no such label: " + Hex.u2(label));
        }
        return get(idx);
    }

    /**
     * Visits each instruction of each block in the list, in order.
     *
     * @param visitor {@code non-null;} visitor to use
     */
    public void forEachInsn(Insn.Visitor visitor) {
        int sz = size();
        for (int i = 0; i < sz; i++) {
            BasicBlock one = get(i);
            InsnList insns = one.getInsns();
            insns.forEach(visitor);
        }
    }

    /**
     * Returns an instance that is identical to this one, except that
     * the registers in each instruction are offset by the given
     * amount. Mutability of the result is inherited from the
     * original.
     *
     * @param delta the amount to offset register numbers by
     * @return {@code non-null;} an appropriately-constructed instance
     */
    public BasicBlockList withRegisterOffset(int delta) {
        int sz = size();
        BasicBlockList result = new BasicBlockList(sz);
        for (int i = 0; i < sz; i++) {
            BasicBlock one = (BasicBlock) get0(i);
            if (one != null) {
                result.set(i, one.withRegisterOffset(delta));
            }
        }
        if (isImmutable()) {
            result.setImmutable();
        }
        return result;
    }

    /**
     * Returns a mutable copy of this list.
     *
     * @return {@code non-null;} an appropriately-constructed instance
     */
    public BasicBlockList getMutableCopy() {
        return new BasicBlockList(this);
    }

    /**
     * Gets the preferred successor for the given block. If the block
     * only has one successor, then that is the preferred successor.
     * Otherwise, if the block has a primay successor, then that is
     * the preferred successor. If the block has no successors, then
     * this returns {@code null}.
     *
     * @param block {@code non-null;} the block in question
     * @return {@code null-ok;} the preferred successor, if any
     */
    public BasicBlock preferredSuccessorOf(BasicBlock block) {
        int primarySuccessor = block.getPrimarySuccessor();
        IntList successors = block.getSuccessors();
        int succSize = successors.size();

        if (primarySuccessor != -1) {
            return labelToBlock(primarySuccessor);
        } else {
            return labelToBlock(successors.get(0));
        }
    }

    /**
     * Compares the catches of two blocks for equality. This includes
     * both the catch types and target labels.
     *
     * @param block1 {@code non-null;} one block to compare
     * @param block2 {@code non-null;} the other block to compare
     * @return {@code true} if the two blocks' non-primary successors
     * are identical
     */
    public boolean catchesEqual(BasicBlock block1, BasicBlock block2) {
        TypeList catches1 = block1.getExceptionHandlerTypes();
        TypeList catches2 = block2.getExceptionHandlerTypes();
        if (!StdTypeList.equalContents(catches1, catches2)) {
            return false;
        }
        IntList succ1 = block1.getSuccessors();
        IntList succ2 = block2.getSuccessors();
        // Both are guaranteed to be the same size.
        int size = succ1.size();
        int primary1 = block1.getPrimarySuccessor();
        int primary2 = block2.getPrimarySuccessor();
        if (((primary1 == -1) || (primary2 == -1)) && (primary1 != primary2)) {
            /*
             * For the current purpose, both blocks in question must
             * either both have a primary or both not have a primary to
             * be considered equal, and it turns out here that that's not
             * the case.
             */
            return false;
        }
        for (int i = 0; i < size; i++) {
            int label1 = succ1.get(i);
            int label2 = succ2.get(i);
            if (label1 == primary1) {
                /*
                 * It should be the case that block2's primary is at the
                 * same index. If not, we consider the blocks unequal for
                 * the current purpose.
                 */
                if (label2 != primary2) {
                    return false;
                }
                continue;
            }
            if (label1 != label2) {
                return false;
            }
        }
        return true;
    }

    /**
     * Instruction visitor class for counting registers used.
     */
    private static class RegCountVisitor implements Insn.Visitor {

        /**
         * {@code >= 0;} register count in-progress
         */
        private int regCount;

        /**
         * Constructs an instance.
         */
        public RegCountVisitor() {
            regCount = 0;
        }

        /**
         * Gets the register count.
         *
         * @return {@code >= 0;} the count
         */
        public int getRegCount() {
            return regCount;
        }

        public void visitPlainInsn(PlainInsn insn) {
            visit(insn);
        }

        public void visitPlainCstInsn(PlainCstInsn insn) {
            visit(insn);
        }

        public void visitSwitchInsn(SwitchInsn insn) {
            visit(insn);
        }

        public void visitThrowingCstInsn(ThrowingCstInsn insn) {
            visit(insn);
        }

        public void visitThrowingInsn(ThrowingInsn insn) {
            visit(insn);
        }

        public void visitFillArrayDataInsn(FillArrayDataInsn insn) {
            visit(insn);
        }

        /**
         * Helper for all the {@code visit*} methods.
         *
         * @param insn {@code non-null;} instruction being visited
         */
        private void visit(Insn insn) {
            RegisterSpec result = insn.getResult();
            if (result != null) {
                processReg(result);
            }
            RegisterSpecList sources = insn.getSources();
            int sz = sources.size();
            for (int i = 0; i < sz; i++) {
                processReg(sources.get(i));
            }
        }

        /**
         * Processes the given register spec.
         *
         * @param spec {@code non-null;} the register spec
         */
        private void processReg(RegisterSpec spec) {
            int reg = spec.getNextReg();
            if (reg > regCount) {
                regCount = reg;
            }
        }
    }
}


protected void unreadBuffer(ICharacterScanner scanner) {
        for (int i = fBuffer.length() - 1; i >= 0; i--) scanner.unread();
    }

/**
 * Any modifications to this file must keep this entire header intact.
 */
/*
 * Created on Mar 2, 2006
 */
package org.python.pydev.editor;

import java.util.HashMap;
import java.util.Map;
import org.eclipse.core.runtime.Assert;
import org.eclipse.jface.text.rules.ICharacterScanner;
import org.eclipse.jface.text.rules.IRule;
import org.eclipse.jface.text.rules.IToken;
import org.eclipse.jface.text.rules.IWordDetector;
import org.eclipse.jface.text.rules.Token;
import org.python.pydev.shared_core.string.FastStringBuffer;

/**
 * This class is a copy of the WordRule, with the exception that when we detected a 'def' or a 'class', the next default token
 * is not the regular, but the token identifying the class name or the function name.
 *
 * The changes were:
 *
 * added the classNameToken and funcNameToken attributes (and constructor parameters)
 * changed the evaluate to store the last found and return things accordingly
 *
 * @see IWordDetector
 */
public class PyWordRule implements IRule {

    /**
     * Internal setting for the un-initialized column constraint
     */
    protected static final int UNDEFINED = -1;

    /**
     * The word detector used by this rule
     */
    protected IWordDetector fDetector;

    /**
     * The default token to be returned on success and if nothing else has been specified.
     */
    protected IToken fDefaultToken;

    /**
     * The column constraint
     */
    protected int fColumn = UNDEFINED;

    /**
     * The table of predefined words and token for this rule
     */
    protected Map<String, IToken> fWords = new HashMap<String, IToken>();

    /**
     * Buffer used for pattern detection
     */
    private FastStringBuffer fBuffer = new FastStringBuffer();

    private IToken classNameToken;

    private IToken funcNameToken;

    private IToken parensToken;

    private IToken operatorsToken;

    /**
     * Creates a rule which, with the help of a word detector, will return the token
     * associated with the detected word. If no token has been associated, the
     * specified default token will be returned.
     *
     * @param detector the word detector to be used by this rule, may not be null
     * @param defaultToken the default token to be returned on success
     *      if nothing else is specified, may not be null
     * @param funcNameToken
     * @param classNameToken
     *
     * @see #addWord(String, IToken)
     */
    public PyWordRule(IWordDetector detector, IToken defaultToken, IToken classNameToken, IToken funcNameToken, IToken parensToken, IToken operatorsToken) {
        Assert.isNotNull(detector);
        Assert.isNotNull(defaultToken);
        fDetector = detector;
        fDefaultToken = defaultToken;
        this.classNameToken = classNameToken;
        this.funcNameToken = funcNameToken;
        this.parensToken = parensToken;
        this.operatorsToken = operatorsToken;
    }

    /**
     * Adds a word and the token to be returned if it is detected.
     *
     * @param word the word this rule will search for, may not be null
     * @param token the token to be returned if the word has been found, may not be null
     */
    public void addWord(String word, IToken token) {
        Assert.isNotNull(word);
        Assert.isNotNull(token);
        fWords.put(word, token);
    }

    /**
     * Sets a column constraint for this rule. If set, the rule's token
     * will only be returned if the pattern is detected starting at the
     * specified column. If the column is smaller then 0, the column
     * constraint is considered removed.
     *
     * @param column the column in which the pattern starts
     */
    public void setColumnConstraint(int column) {
        if (column < 0)
            column = UNDEFINED;
        fColumn = column;
    }

    private String lastFound = "";

    public IToken evaluate(ICharacterScanner scanner) {
        int c = scanner.read();
        IToken found = null;
        switch(c) {
            case '(':
            case ')':
            case '[':
            case ']':
            case '{':
            case '}':
                found = this.parensToken;
                break;
            case '<':
            case '>':
            case '=':
            case '+':
            case '-':
            case '/':
            case '*':
            case '!':
            case '&':
            case '|':
            case '%':
            case '~':
            case '^':
            case ',':
                found = this.operatorsToken;
                break;
        }
        if (found != null) {
            lastFound = "";
            return found;
        }
        if (fDetector.isWordStart((char) c)) {
            if (fColumn == UNDEFINED || (fColumn == scanner.getColumn() - 1)) {
                fBuffer.clear();
                do {
                    fBuffer.append((char) c);
                    c = scanner.read();
                } while (c != ICharacterScanner.EOF && fDetector.isWordPart((char) c));
                scanner.unread();
                String str = fBuffer.toString();
                IToken token = (IToken) fWords.get(str);
                if (token != null) {
                    lastFound = str;
                    return token;
                }
                if (fDefaultToken.isUndefined())
                    unreadBuffer(scanner);
                if (lastFound.equals("def")) {
                    lastFound = str;
                    return funcNameToken;
                }
                if (lastFound.equals("class")) {
                    lastFound = str;
                    return classNameToken;
                }
                return fDefaultToken;
            }
        }
        scanner.unread();
        return Token.UNDEFINED;
    }

    /**
     * Returns the characters in the buffer to the scanner.
     *
     * @param scanner the scanner to be used
     */


public void updateCustomTemplates(Preferences preference) {
        String[] keys = {};
        try {
            keys = preference.childrenNames();
        } catch (BackingStoreException e) {
            logger.warn("Error reading preferences");
        }
        this.customTemplates = new HashMap<>(keys.length, 1);
        for (String key : keys) {
            FSPath path = new FSPath(preference.node(key));
            customTemplates.put(key, path.getPath());
        }
    }

package org.apache.cayenne.modeler;

import java.net.URISyntaxException;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.prefs.BackingStoreException;
import java.util.prefs.Preferences;
import org.apache.cayenne.gen.ClassGenerationAction;
import org.apache.cayenne.gen.ClientClassGenerationAction;
import org.apache.cayenne.modeler.pref.FSPath;
import org.apache.cayenne.resource.Resource;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * Manages code generation templates.
 */
public class CodeTemplateManager {

    public static final String STANDARD_SERVER_SUPERCLASS = "Standard Server Superclass";

    public static final String STANDARD_SERVER_SUBCLASS = "Standard Server Subclass";

    public static final String SINGLE_SERVER_CLASS = "Single Server Class";

    static final String STANDARD_CLIENT_SUPERCLASS = "Standard Client Superclass";

    static final String STANDARD_CLIENT_SUBCLASS = "Standard Client Subclass";

    private static final String STANDARD_EMBEDDABLE_SUPERCLASS = "Standard Embeddable Superclass";

    private static final String STANDARD_EMBEDDABLE_SUBCLASS = "Standard Embeddable Subclass";

    private static final String SINGLE_EMBEDDABLE_CLASS = "Single Embeddable Class";

    private static final String STANDARD_SERVER_DATAMAP_SUPERCLASS = "Standard Server DataMap Superclass";

    private static final String STANDARD_SERVER_DATAMAP_SUBCLASS = "Standard Server DataMap Subclass";

    private static final String STANDARD_CLIENT_DATAMAP_SUPERCLASS = "Standard Client DataMap Superclass";

    private static final String STANDARD_CLIENT_DATAMAP_SUBCLASS = "Standard Client DataMap Subclass";

    private static final String SINGLE_DATAMAP_CLASS = "Single DataMap Class";

    public static final String NODE_NAME = "codeTemplateManager";

    private List<String> standardSubclassTemplates;

    private List<String> standardSuperclassTemplates;

    private List<String> standardClientSubclassTemplates;

    private List<String> standardClientSuperclassTemplates;

    private Map<String, String> customTemplates;

    private Map<String, String> reverseCustomTemplate;

    private Map<String, String> standardTemplates;

    private List<String> standardEmbeddableTemplates;

    private List<String> standardEmbeddableSuperclassTemplates;

    private List<String> standardServerDataMapTemplates;

    private List<String> standardServerDataMapSuperclassTemplates;

    private List<String> standardClientDataMapTemplates;

    private List<String> standardClientDataMapSuperclassTemplates;

    private Map<String, String> reverseStandartTemplates;

    private static Logger logger = LoggerFactory.getLogger(CodeTemplateManager.class);

    public Preferences getTemplatePreferences(Application application) {
        return application.getPreferencesNode(this.getClass(), NODE_NAME);
    }

    public CodeTemplateManager(Application application) {
        standardSuperclassTemplates = new ArrayList<>(2);
        standardSuperclassTemplates.add(STANDARD_SERVER_SUPERCLASS);
        standardClientSuperclassTemplates = new ArrayList<>();
        standardClientSuperclassTemplates.add(STANDARD_CLIENT_SUPERCLASS);
        standardSubclassTemplates = new ArrayList<>(2);
        standardSubclassTemplates.add(SINGLE_SERVER_CLASS);
        standardSubclassTemplates.add(STANDARD_SERVER_SUBCLASS);
        standardClientSubclassTemplates = new ArrayList<>();
        standardClientSubclassTemplates.add(STANDARD_CLIENT_SUBCLASS);
        standardEmbeddableTemplates = new ArrayList<>();
        standardEmbeddableTemplates.add(STANDARD_EMBEDDABLE_SUBCLASS);
        standardEmbeddableTemplates.add(SINGLE_EMBEDDABLE_CLASS);
        standardEmbeddableSuperclassTemplates = new ArrayList<>();
        standardEmbeddableSuperclassTemplates.add(STANDARD_EMBEDDABLE_SUPERCLASS);
        standardServerDataMapTemplates = new ArrayList<>();
        standardServerDataMapTemplates.add(STANDARD_SERVER_DATAMAP_SUBCLASS);
        standardServerDataMapTemplates.add(SINGLE_DATAMAP_CLASS);
        standardServerDataMapSuperclassTemplates = new ArrayList<>();
        standardServerDataMapSuperclassTemplates.add(STANDARD_SERVER_DATAMAP_SUPERCLASS);
        standardClientDataMapTemplates = new ArrayList<>();
        standardClientDataMapTemplates.add(STANDARD_CLIENT_DATAMAP_SUBCLASS);
        standardClientDataMapSuperclassTemplates = new ArrayList<>();
        standardClientDataMapSuperclassTemplates.add(STANDARD_CLIENT_DATAMAP_SUPERCLASS);
        updateCustomTemplates(getTemplatePreferences(application));
        reverseCustomTemplate = new HashMap<>();
        for (Map.Entry<String, String> entry : customTemplates.entrySet()) {
            reverseCustomTemplate.put(entry.getValue(), entry.getKey());
        }
        standardTemplates = new HashMap<>();
        standardTemplates.put(STANDARD_SERVER_SUPERCLASS, ClassGenerationAction.SUPERCLASS_TEMPLATE);
        standardTemplates.put(STANDARD_CLIENT_SUPERCLASS, ClientClassGenerationAction.SUPERCLASS_TEMPLATE);
        standardTemplates.put(STANDARD_SERVER_SUBCLASS, ClassGenerationAction.SUBCLASS_TEMPLATE);
        standardTemplates.put(STANDARD_CLIENT_SUBCLASS, ClientClassGenerationAction.SUBCLASS_TEMPLATE);
        standardTemplates.put(SINGLE_SERVER_CLASS, ClassGenerationAction.SINGLE_CLASS_TEMPLATE);
        standardTemplates.put(STANDARD_EMBEDDABLE_SUPERCLASS, ClassGenerationAction.EMBEDDABLE_SUPERCLASS_TEMPLATE);
        standardTemplates.put(STANDARD_EMBEDDABLE_SUBCLASS, ClassGenerationAction.EMBEDDABLE_SUBCLASS_TEMPLATE);
        standardTemplates.put(SINGLE_EMBEDDABLE_CLASS, ClassGenerationAction.EMBEDDABLE_SINGLE_CLASS_TEMPLATE);
        standardTemplates.put(STANDARD_SERVER_DATAMAP_SUBCLASS, ClassGenerationAction.DATAMAP_SUBCLASS_TEMPLATE);
        standardTemplates.put(STANDARD_CLIENT_DATAMAP_SUBCLASS, ClientClassGenerationAction.DMAP_SUBCLASS_TEMPLATE);
        standardTemplates.put(SINGLE_DATAMAP_CLASS, ClassGenerationAction.DATAMAP_SINGLE_CLASS_TEMPLATE);
        standardTemplates.put(STANDARD_SERVER_DATAMAP_SUPERCLASS, ClassGenerationAction.DATAMAP_SUPERCLASS_TEMPLATE);
        standardTemplates.put(STANDARD_CLIENT_DATAMAP_SUPERCLASS, ClientClassGenerationAction.DMAP_SUPERCLASS_TEMPLATE);
        reverseStandartTemplates = new HashMap<>();
        reverseStandartTemplates.put(ClassGenerationAction.SUBCLASS_TEMPLATE, STANDARD_SERVER_SUBCLASS);
        reverseStandartTemplates.put(ClientClassGenerationAction.SUBCLASS_TEMPLATE, STANDARD_CLIENT_SUBCLASS);
        reverseStandartTemplates.put(ClassGenerationAction.SINGLE_CLASS_TEMPLATE, SINGLE_SERVER_CLASS);
        reverseStandartTemplates.put(ClientClassGenerationAction.SUPERCLASS_TEMPLATE, STANDARD_CLIENT_SUPERCLASS);
        reverseStandartTemplates.put(ClassGenerationAction.SUPERCLASS_TEMPLATE, STANDARD_SERVER_SUPERCLASS);
        reverseStandartTemplates.put(ClassGenerationAction.EMBEDDABLE_SUPERCLASS_TEMPLATE, STANDARD_EMBEDDABLE_SUPERCLASS);
        reverseStandartTemplates.put(ClassGenerationAction.EMBEDDABLE_SUBCLASS_TEMPLATE, STANDARD_EMBEDDABLE_SUBCLASS);
        reverseStandartTemplates.put(ClassGenerationAction.EMBEDDABLE_SINGLE_CLASS_TEMPLATE, SINGLE_EMBEDDABLE_CLASS);
        reverseStandartTemplates.put(ClassGenerationAction.DATAMAP_SUBCLASS_TEMPLATE, STANDARD_SERVER_DATAMAP_SUBCLASS);
        reverseStandartTemplates.put(ClientClassGenerationAction.DMAP_SUBCLASS_TEMPLATE, STANDARD_CLIENT_DATAMAP_SUBCLASS);
        reverseStandartTemplates.put(ClassGenerationAction.DATAMAP_SINGLE_CLASS_TEMPLATE, SINGLE_DATAMAP_CLASS);
        reverseStandartTemplates.put(ClassGenerationAction.DATAMAP_SUPERCLASS_TEMPLATE, STANDARD_SERVER_DATAMAP_SUPERCLASS);
        reverseStandartTemplates.put(ClientClassGenerationAction.DMAP_SUPERCLASS_TEMPLATE, STANDARD_CLIENT_DATAMAP_SUPERCLASS);
    }

    /**
     * Updates custom templates from preferences.
     */

    // TODO: andrus, 12/5/2007 - this should also take a "pairs" parameter to
    // correctly
    // assign standard templates
    public String getTemplatePath(String name, Resource rootPath) {
        Object value = customTemplates.get(name);
        if (value != null) {
            try {
                if (rootPath != null) {
                    Path path = Paths.get(rootPath.getURL().toURI()).getParent();
                    value = path.relativize(Paths.get((String) value));
                }
                return value.toString();
            } catch (URISyntaxException e) {
                logger.warn("Path for template named '{}' could not be resolved", name);
            }
        }
        value = standardTemplates.get(name);
        return value != null ? value.toString() : null;
    }

    public String getNameByPath(String name, Path rootPath) {
        String fullPath = rootPath.resolve(Paths.get(name)).normalize().toString();
        if (reverseCustomTemplate.containsKey(fullPath)) {
            return reverseCustomTemplate.get(fullPath);
        } else {
            Object value = reverseStandartTemplates.get(name);
            return value != null ? value.toString() : null;
        }
    }

    public Map<String, String> getCustomTemplates() {
        return customTemplates;
    }

    public List<String> getStandardSubclassTemplates() {
        return standardSubclassTemplates;
    }

    public List<String> getStandardClientSubclassTemplates() {
        return standardClientSubclassTemplates;
    }

    public List<String> getStandardSuperclassTemplates() {
        return standardSuperclassTemplates;
    }

    public List<String> getStandardClientSuperclassTemplates() {
        return standardClientSuperclassTemplates;
    }

    public List<String> getStandartEmbeddableTemplates() {
        return standardEmbeddableTemplates;
    }

    public List<String> getStandartEmbeddableSuperclassTemplates() {
        return standardEmbeddableSuperclassTemplates;
    }

    public List<String> getStandartDataMapTemplates() {
        return standardServerDataMapTemplates;
    }

    public List<String> getStandartDataMapSuperclassTemplates() {
        return standardServerDataMapSuperclassTemplates;
    }

    public List<String> getStandardClientDataMapTemplates() {
        return standardClientDataMapTemplates;
    }

    public List<String> getStandardClientDataMapSuperclassTemplates() {
        return standardClientDataMapSuperclassTemplates;
    }
}


public int getFaultCode() {
        return this.faultCode;
    }

/*
 * Created on Dec 12, 2007 at 11:58:19 PM.
 *
 *
 * This file is part of J2ME Polish.
 *
 *
 * Commercial licenses are also available, please
 * refer to the accompanying LICENSE.txt or visit
 * http://www.j2mepolish.org for details.
 */
package de.enough.polish.rmi.xmlrpc;

import de.enough.polish.rmi.RemoteException;

/**
 *
Provides access to XML RPC specific faults

 *
 *

 * history
 *        Dec 12, 2007 - rob creation
 *

 * @author Robert Virkus, example@nnthink.com
 */
public class XmlRpcRemoteException extends RemoteException {

    private final int faultCode;

    /**
     * Creates a new remote exception.
     *
     * @param faultCode the fault code of the server error
     * @param message the message of the server error
     */
    public XmlRpcRemoteException(int faultCode, String message) {
        super(message);
        this.faultCode = faultCode;
    }

    /**
     * Retrieves the XML RPC fault code of the server.
     *
     * @return an int with the fault code of the server
     */


private static void preparingCloudResources(Context context) {
        Set<Map.Entry<String, String>> entries = SCENE_RESOURCES.entrySet();
        for (Map.Entry<String, String> entry : entries) {
            uploadFile(context, SCENE_FOLDER + File.separator + entry.getKey(), entry.getValue());
        }
    }

package com.huawei.industrydemo.shopping.utils;

import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.Environment;
import android.text.TextUtils;
import android.util.Log;
import com.huawei.hmf.tasks.OnSuccessListener;
import com.huawei.industrydemo.shopping.R;
import com.huawei.industrydemo.shopping.base.BaseActivity;
import com.huawei.industrydemo.shopping.base.BaseDialog;
import com.huawei.industrydemo.shopping.constants.KeyConstants;
import com.huawei.industrydemo.shopping.entity.Product;
import com.huawei.industrydemo.shopping.page.SceneViewActivity;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;
import java.util.zip.ZipEntry;
import java.util.zip.ZipFile;
import java.util.zip.ZipInputStream;
import static com.huawei.industrydemo.shopping.base.BaseDialog.CONTENT;
import static com.huawei.industrydemo.shopping.utils.AgcUtil.uploadFile;

public class SceneUtil {

    private static final String TAG = SceneUtil.class.getSimpleName();

    private static final String MAC_IGNORE = "__MACOSX/";

    /**
     * Scene model folder
     */
    public static final String SCENE_FOLDER = "SceneView";

    private static final String[] BDG_MODEL_NAMES = { "bgd_model_1.dds", "bgd_model_2.dds", "bgd_model_3.dds" };

    private static final boolean IS_PREPARING = false;

    private static final Map<String, String> SCENE_RESOURCES = new HashMap<String, String>() {

        {
            put("bgd_model_1.dds", "6CF9F3254F3B27B707C680258F6742B913A5AB99D485C0533748428C2FEC2C3A");
            put("bgd_model_2.dds", "470CADFA1B6BC30498FBB6796AA00A8B27C267F22516F145497191FF5A2DAD24");
            put("bgd_model_3.dds", "D3D68C2A7F1BF2E83ED5827FEF83DA7954D4DB504AE342190EF2E8EA7C72136A");
            put("p40.zip", "53F15B1DB7CE87B589B90ADCE64F0EE29F5A998A9D1A0A942003B4CD0CBF3E23");
            put("handbag.zip", "B18487E7288EBD7F78E6F43892CC9EEF33B9B3A44B2DCF597BC13A8FEF94E495");
            put("sunglasses.zip", "3020D7813A645E562A54F5CC88CAEDDBEA7B53C4C3F8667AFC169B16DEFD971A");
        }
    };

    /**
     * download 3d Resources
     *
     * @param context Context
     * @param product Product
     */
    public static void download3dResources(Context context, Product product) {
        String rootPath = context.getExternalFilesDir(Environment.DIRECTORY_DOWNLOADS).getPath();
        Log.d(TAG, "rootPath: " + rootPath);
        File sceneDir = new File(rootPath + File.separator + SCENE_FOLDER);
        if (!sceneDir.exists()) {
            if (!sceneDir.mkdir()) {
                Log.e(TAG, "mkdir error!");
                return;
            }
        }
        if (IS_PREPARING) {
            preparingCloudResources(context);
        } else {
            ProgressDialog progressDialog = new ProgressDialog(context);
            progressDialog.setMessage(context.getString(R.string.downloading));
            progressDialog.setCancelable(false);
            progressDialog.setCanceledOnTouchOutside(false);
            progressDialog.setProgress(0);
            progressDialog.setIndeterminate(true);
            progressDialog.setProgressNumberFormat(null);
            progressDialog.setProgressPercentFormat(null);
            progressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
            progressDialog.show();
            downloadInSequence(context, progressDialog, o -> downloadKeyResources(context, progressDialog, rootPath, product));
        }
    }

    private static void downloadKeyResources(Context context, ProgressDialog progressDialog, String rootPath, Product product) {
        String threeDimensional = product.getThreeDimensional();
        String targetFilePath = SCENE_FOLDER + File.separator + threeDimensional.substring(0, threeDimensional.lastIndexOf("/")) + ".zip";
        File targetFile = new File(rootPath + File.separator + targetFilePath);
        Log.d(TAG, targetFile.getPath());
        AgcUtil.downloadFile(context, targetFilePath, progressDialog, downloadResult -> {
            decompressFile(targetFile.getParent(), targetFile);
            progressDialog.dismiss();
            Bundle data = new Bundle();
            data.putString(CONTENT, context.getString(R.string.downloaded));
            BaseDialog dialog = new BaseDialog(context, data, false);
            dialog.setConfirmListener(v -> {
                dialog.dismiss();
                show3dModel(context, product);
            });
            dialog.show();
        });
    }

    private static void downloadInSequence(Context context, ProgressDialog progressDialog, OnSuccessListener<Object> onSuccessListener) {
        String bdgModelPath1 = SCENE_FOLDER + File.separator + BDG_MODEL_NAMES[0];
        AgcUtil.downloadFile(context, bdgModelPath1, progressDialog, downloadResult -> {
            String bdgModelPath2 = SCENE_FOLDER + File.separator + BDG_MODEL_NAMES[1];
            AgcUtil.downloadFile(context, bdgModelPath2, progressDialog, downloadResult1 -> {
                String bdgModelPath3 = SCENE_FOLDER + File.separator + BDG_MODEL_NAMES[2];
                AgcUtil.downloadFile(context, bdgModelPath3, progressDialog, downloadResult2 -> {
                    onSuccessListener.onSuccess(new Object());
                });
            });
        });
    }

    /**
     * Only files uploaded using code can carry the SHA256 value for resumable download.
     *
     * @param context Context
     */

    private static void show3dModel(Context context, Product product) {
        if (context instanceof BaseActivity) {
            Intent intent3d = new Intent(context, SceneViewActivity.class);
            intent3d.putExtra(KeyConstants.THREE_DIMENSIONAL_DATA, product.getThreeDimensional());
            context.startActivity(intent3d);
            AnalyticsUtil.reportProductViewEvent("AR View", product);
        }
    }

    /**
     * decompress File
     *
     * @param target String
     * @param file File
     */
    private static void decompressFile(String target, File file) {
        if (TextUtils.isEmpty(target) || !file.exists()) {
            return;
        }
        try (ZipInputStream zipInputStream = new ZipInputStream(new FileInputStream(file));
            ZipFile zipFile = new ZipFile(file)) {
            ZipEntry zipEntry = null;
            while ((zipEntry = zipInputStream.getNextEntry()) != null) {
                String fileName = zipEntry.getName();
                if (fileName != null && fileName.contains(MAC_IGNORE)) {
                    continue;
                }
                File temp = new File(target + File.separator + fileName);
                if (zipEntry.isDirectory()) {
                    File dir = new File(target + File.separator + fileName);
                    if (!dir.mkdirs()) {
                        Log.e(TAG, "mkdirs error!");
                        return;
                    }
                    continue;
                }
                if (temp.getParentFile() != null && !temp.getParentFile().exists()) {
                    if (!temp.getParentFile().mkdirs()) {
                        Log.e(TAG, "mkdirs error!");
                        return;
                    }
                }
                byte[] buffer = new byte[1024];
                try (OutputStream os = new FileOutputStream(temp);
                    InputStream is = zipFile.getInputStream(zipEntry)) {
                    int len = 0;
                    while ((len = is.read(buffer)) != -1) {
                        os.write(buffer, 0, len);
                    }
                }
            }
        } catch (IOException e) {
            AgcUtil.reportException(TAG, e);
        }
    }
}


while ((len = is.read(buffer)) != -1) {
                        os.write(buffer, 0, len);
                    }

package com.huawei.industrydemo.shopping.utils;

import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.Environment;
import android.text.TextUtils;
import android.util.Log;
import com.huawei.hmf.tasks.OnSuccessListener;
import com.huawei.industrydemo.shopping.R;
import com.huawei.industrydemo.shopping.base.BaseActivity;
import com.huawei.industrydemo.shopping.base.BaseDialog;
import com.huawei.industrydemo.shopping.constants.KeyConstants;
import com.huawei.industrydemo.shopping.entity.Product;
import com.huawei.industrydemo.shopping.page.SceneViewActivity;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;
import java.util.zip.ZipEntry;
import java.util.zip.ZipFile;
import java.util.zip.ZipInputStream;
import static com.huawei.industrydemo.shopping.base.BaseDialog.CONTENT;
import static com.huawei.industrydemo.shopping.utils.AgcUtil.uploadFile;

public class SceneUtil {

    private static final String TAG = SceneUtil.class.getSimpleName();

    private static final String MAC_IGNORE = "__MACOSX/";

    /**
     * Scene model folder
     */
    public static final String SCENE_FOLDER = "SceneView";

    private static final String[] BDG_MODEL_NAMES = { "bgd_model_1.dds", "bgd_model_2.dds", "bgd_model_3.dds" };

    private static final boolean IS_PREPARING = false;

    private static final Map<String, String> SCENE_RESOURCES = new HashMap<String, String>() {

        {
            put("bgd_model_1.dds", "6CF9F3254F3B27B707C680258F6742B913A5AB99D485C0533748428C2FEC2C3A");
            put("bgd_model_2.dds", "470CADFA1B6BC30498FBB6796AA00A8B27C267F22516F145497191FF5A2DAD24");
            put("bgd_model_3.dds", "D3D68C2A7F1BF2E83ED5827FEF83DA7954D4DB504AE342190EF2E8EA7C72136A");
            put("p40.zip", "53F15B1DB7CE87B589B90ADCE64F0EE29F5A998A9D1A0A942003B4CD0CBF3E23");
            put("handbag.zip", "B18487E7288EBD7F78E6F43892CC9EEF33B9B3A44B2DCF597BC13A8FEF94E495");
            put("sunglasses.zip", "3020D7813A645E562A54F5CC88CAEDDBEA7B53C4C3F8667AFC169B16DEFD971A");
        }
    };

    /**
     * download 3d Resources
     *
     * @param context Context
     * @param product Product
     */
    public static void download3dResources(Context context, Product product) {
        String rootPath = context.getExternalFilesDir(Environment.DIRECTORY_DOWNLOADS).getPath();
        Log.d(TAG, "rootPath: " + rootPath);
        File sceneDir = new File(rootPath + File.separator + SCENE_FOLDER);
        if (!sceneDir.exists()) {
            if (!sceneDir.mkdir()) {
                Log.e(TAG, "mkdir error!");
                return;
            }
        }
        if (IS_PREPARING) {
            preparingCloudResources(context);
        } else {
            ProgressDialog progressDialog = new ProgressDialog(context);
            progressDialog.setMessage(context.getString(R.string.downloading));
            progressDialog.setCancelable(false);
            progressDialog.setCanceledOnTouchOutside(false);
            progressDialog.setProgress(0);
            progressDialog.setIndeterminate(true);
            progressDialog.setProgressNumberFormat(null);
            progressDialog.setProgressPercentFormat(null);
            progressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
            progressDialog.show();
            downloadInSequence(context, progressDialog, o -> downloadKeyResources(context, progressDialog, rootPath, product));
        }
    }

    private static void downloadKeyResources(Context context, ProgressDialog progressDialog, String rootPath, Product product) {
        String threeDimensional = product.getThreeDimensional();
        String targetFilePath = SCENE_FOLDER + File.separator + threeDimensional.substring(0, threeDimensional.lastIndexOf("/")) + ".zip";
        File targetFile = new File(rootPath + File.separator + targetFilePath);
        Log.d(TAG, targetFile.getPath());
        AgcUtil.downloadFile(context, targetFilePath, progressDialog, downloadResult -> {
            decompressFile(targetFile.getParent(), targetFile);
            progressDialog.dismiss();
            Bundle data = new Bundle();
            data.putString(CONTENT, context.getString(R.string.downloaded));
            BaseDialog dialog = new BaseDialog(context, data, false);
            dialog.setConfirmListener(v -> {
                dialog.dismiss();
                show3dModel(context, product);
            });
            dialog.show();
        });
    }

    private static void downloadInSequence(Context context, ProgressDialog progressDialog, OnSuccessListener<Object> onSuccessListener) {
        String bdgModelPath1 = SCENE_FOLDER + File.separator + BDG_MODEL_NAMES[0];
        AgcUtil.downloadFile(context, bdgModelPath1, progressDialog, downloadResult -> {
            String bdgModelPath2 = SCENE_FOLDER + File.separator + BDG_MODEL_NAMES[1];
            AgcUtil.downloadFile(context, bdgModelPath2, progressDialog, downloadResult1 -> {
                String bdgModelPath3 = SCENE_FOLDER + File.separator + BDG_MODEL_NAMES[2];
                AgcUtil.downloadFile(context, bdgModelPath3, progressDialog, downloadResult2 -> {
                    onSuccessListener.onSuccess(new Object());
                });
            });
        });
    }

    /**
     * Only files uploaded using code can carry the SHA256 value for resumable download.
     *
     * @param context Context
     */
    private static void preparingCloudResources(Context context) {
        Set<Map.Entry<String, String>> entries = SCENE_RESOURCES.entrySet();
        for (Map.Entry<String, String> entry : entries) {
            uploadFile(context, SCENE_FOLDER + File.separator + entry.getKey(), entry.getValue());
        }
    }

    private static void show3dModel(Context context, Product product) {
        if (context instanceof BaseActivity) {
            Intent intent3d = new Intent(context, SceneViewActivity.class);
            intent3d.putExtra(KeyConstants.THREE_DIMENSIONAL_DATA, product.getThreeDimensional());
            context.startActivity(intent3d);
            AnalyticsUtil.reportProductViewEvent("AR View", product);
        }
    }

    /**
     * decompress File
     *
     * @param target String
     * @param file File
     */
    private static void decompressFile(String target, File file) {
        if (TextUtils.isEmpty(target) || !file.exists()) {
            return;
        }
        try (ZipInputStream zipInputStream = new ZipInputStream(new FileInputStream(file));
            ZipFile zipFile = new ZipFile(file)) {
            ZipEntry zipEntry = null;
            while ((zipEntry = zipInputStream.getNextEntry()) != null) {
                String fileName = zipEntry.getName();
                if (fileName != null && fileName.contains(MAC_IGNORE)) {
                    continue;
                }
                File temp = new File(target + File.separator + fileName);
                if (zipEntry.isDirectory()) {
                    File dir = new File(target + File.separator + fileName);
                    if (!dir.mkdirs()) {
                        Log.e(TAG, "mkdirs error!");
                        return;
                    }
                    continue;
                }
                if (temp.getParentFile() != null && !temp.getParentFile().exists()) {
                    if (!temp.getParentFile().mkdirs()) {
                        Log.e(TAG, "mkdirs error!");
                        return;
                    }
                }
                byte[] buffer = new byte[1024];
                try (OutputStream os = new FileOutputStream(temp);
                    InputStream is = zipFile.getInputStream(zipEntry)) {
                    int len = 0;

                }
            }
        } catch (IOException e) {
            AgcUtil.reportException(TAG, e);
        }
    }
}


@ExceptionHandler(UsernameNotFoundException.class)
    public Result usernameNotFoundExceptionHandler(HttpServletRequest request, UsernameNotFoundException e) {
        logger.error("Request URL : {}, Exception :", request.getRequestURL(), e);
        return Result.create(401, "用户名或密码错误！");
    }

package top.naccl.handler;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import top.naccl.exception.NotFoundException;
import top.naccl.exception.PersistenceException;
import top.naccl.model.vo.Result;
import javax.servlet.http.HttpServletRequest;

/**
 * @Description: 对Controller层全局异常处理
 * @RestControllerAdvice 捕获异常后，返回json数据类型
 * @Author: Naccl
 * @Date: 2020-08-14
 */
@RestControllerAdvice
public class ControllerExceptionHandler {

    private final Logger logger = LoggerFactory.getLogger(this.getClass());

    /**
     * 捕获自定义的404异常
     *
     * @param request 请求
     * @param e       自定义抛出的异常信息
     * @return
     */
    @ExceptionHandler(NotFoundException.class)
    public Result notFoundExceptionHandler(HttpServletRequest request, NotFoundException e) {
        logger.error("Request URL : {}, Exception :", request.getRequestURL(), e);
        return Result.create(404, e.getMessage());
    }

    /**
     * 捕获自定义的持久化异常
     *
     * @param request 请求
     * @param e       自定义抛出的异常信息
     * @return
     */
    @ExceptionHandler(PersistenceException.class)
    public Result persistenceExceptionHandler(HttpServletRequest request, PersistenceException e) {
        logger.error("Request URL : {}, Exception :", request.getRequestURL(), e);
        return Result.create(500, e.getMessage());
    }

    /**
     * 捕获自定义的登录失败异常
     *
     * @param request 请求
     * @param e       自定义抛出的异常信息
     * @return
     */

    /**
     * 捕获其它异常
     *
     * @param request 请求
     * @param e       异常信息
     * @return
     */
    @ExceptionHandler(Exception.class)
    public Result exceptionHandler(HttpServletRequest request, Exception e) {
        logger.error("Request URL : {}, Exception :", request.getRequestURL(), e);
        return Result.create(500, "异常错误");
    }
}


package com.jasper.deploymentcontroller.action.pod;

import io.fabric8.kubernetes.api.model.Pod;

/**
 * @author zhoumeng
 * @version $Id: PodAddedWatcher.java, v 0.1 2018/12/10 下午3:56 zhoumeng Exp $
 */
public interface PodAddedWatcher {

    /**
     * 当MyDeployment管理的Pod添加时的回调方法
     * @param pod
     */


package org.camunda.bpm.engine.history;

import java.io.Serializable;
import java.util.Date;
import java.util.List;
import java.util.Set;
import org.camunda.bpm.engine.ProcessEngineConfiguration;
import org.camunda.bpm.engine.ProcessEngineException;
import org.camunda.bpm.engine.query.Query;
import org.camunda.bpm.engine.runtime.ProcessInstanceQuery;

/**
 * Allows programmatic querying of {@link HistoricProcessInstance}s.
 *
 * @author Tom Baeyens
 * @author Joram Barrez
 * @author Falko Menge
 */
public interface HistoricProcessInstanceQuery extends Query<HistoricProcessInstanceQuery, HistoricProcessInstance> {

    /**
     * Only select historic process instances with the given process instance.
     * {@link ProcessInstance) ids and {@link HistoricProcessInstance} ids match.
     */
    HistoricProcessInstanceQuery processInstanceId(String processInstanceId);

    /**
     * Only select historic process instances whose id is in the given set of ids.
     * {@link ProcessInstance) ids and {@link HistoricProcessInstance} ids match.
     */
    HistoricProcessInstanceQuery processInstanceIds(Set<String> processInstanceIds);

    /**
     * Only select historic process instances for the given process definition
     */
    HistoricProcessInstanceQuery processDefinitionId(String processDefinitionId);

    /**
     * Only select historic process instances that are defined by a process
     * definition with the given key.
     */
    HistoricProcessInstanceQuery processDefinitionKey(String processDefinitionKey);

    /**
     * Only select historic process instances that are defined by any given process
     * definition key.
     */
    HistoricProcessInstanceQuery processDefinitionKeyIn(String... processDefinitionKeys);

    /**
     * Only select historic process instances that don't have a process-definition of which the key is present in the given list
     */
    HistoricProcessInstanceQuery processDefinitionKeyNotIn(List<String> processDefinitionKeys);

    /**
     * Only select historic process instances that are defined by a process
     * definition with the given name.
     */
    HistoricProcessInstanceQuery processDefinitionName(String processDefinitionName);

    /**
     * Only select historic process instances that are defined by process definition which name
     * is like the given value.
     *
     * @param nameLike The string can include the wildcard character '%' to express
     *    like-strategy: starts with (string%), ends with (%string) or contains (%string%).
     */
    HistoricProcessInstanceQuery processDefinitionNameLike(String nameLike);

    /**
     * Only select historic process instances with the given business key
     */
    HistoricProcessInstanceQuery processInstanceBusinessKey(String processInstanceBusinessKey);

    /**
     * Only select historic process instances which had a business key like the given value.
     *
     * @param processInstanceBusinessKeyLike The string can include the wildcard character '%' to express
     *    like-strategy: starts with (string%), ends with (%string) or contains (%string%).
     */
    HistoricProcessInstanceQuery processInstanceBusinessKeyLike(String processInstanceBusinessKeyLike);

    /**
     * Only select historic process instances that are completely finished.
     */
    HistoricProcessInstanceQuery finished();

    /**
     * Only select historic process instance that are not yet finished.
     */
    HistoricProcessInstanceQuery unfinished();

    /**
     * Only select historic process instances with incidents
     *
     * @return HistoricProcessInstanceQuery
     */
    HistoricProcessInstanceQuery withIncidents();

    /**
     * Only select historic process instances with root incidents
     *
     * @return HistoricProcessInstanceQuery
     */
    HistoricProcessInstanceQuery withRootIncidents();

    /**
     * Only select historic process instances with incident status either 'open' or 'resolved'.
     * To get all process instances with incidents, use {@link HistoricProcessInstanceQuery#withIncidents()}.
     *
     * @param status indicates the incident status, which is either 'open' or 'resolved'
     * @return {@link HistoricProcessInstanceQuery}
     */
    HistoricProcessInstanceQuery incidentStatus(String status);

    /**
     * Only selects process instances with the given incident type.
     */
    HistoricProcessInstanceQuery incidentType(String incidentType);

    /**
     * Only select historic process instances with the given incident message.
     *
     * @param incidentMessage Incidents Message for which the historic process instances should be selected
     *
     * @return HistoricProcessInstanceQuery
     */
    HistoricProcessInstanceQuery incidentMessage(String incidentMessage);

    /**
     * Only select historic process instances which had an incident message like the given value.
     *
     * @param incidentMessageLike The string can include the wildcard character '%' to express
     *    like-strategy: starts with (string%), ends with (%string) or contains (%string%).
     *
     * @return HistoricProcessInstanceQuery
     */
    HistoricProcessInstanceQuery incidentMessageLike(String incidentMessageLike);

    /**
     * Only select historic process instances which are associated with the given case instance id.
     */
    HistoricProcessInstanceQuery caseInstanceId(String caseInstanceId);

    /**
     * The query will match the names of variables in a case-insensitive way.
     */
    HistoricProcessInstanceQuery matchVariableNamesIgnoreCase();

    /**
     * The query will match the values of variables in a case-insensitive way.
     */
    HistoricProcessInstanceQuery matchVariableValuesIgnoreCase();

    /**
     * Only select process instances which had a global variable with the given value
     * when they ended. Only select process instances which have a variable value
     * greater than the passed value. The type only applies to already ended
     * process instances, otherwise use a {@link ProcessInstanceQuery} instead! of
     * variable is determined based on the value, using types configured in
     * {@link ProcessEngineConfiguration#getVariableSerializers()}. Byte-arrays and
     * {@link Serializable} objects (which are not primitive type wrappers) are
     * not supported.
     * @param name of the variable, cannot be null.
     */
    HistoricProcessInstanceQuery variableValueEquals(String name, Object value);

    /**
     * Only select process instances which had a global variable with the given name, but
     * with a different value than the passed value when they ended. Only select
     * process instances which have a variable value greater than the passed
     * value. Byte-arrays and {@link Serializable} objects (which are not
     * primitive type wrappers) are not supported.
     * @param name of the variable, cannot be null.
     */
    HistoricProcessInstanceQuery variableValueNotEquals(String name, Object value);

    /**
     * Only select process instances which had a global variable value greater than the
     * passed value when they ended. Booleans, Byte-arrays and
     * {@link Serializable} objects (which are not primitive type wrappers) are
     * not supported. Only select process instances which have a variable value
     * greater than the passed value.
     * @param name cannot be null.
     * @param value cannot be null.
     */
    HistoricProcessInstanceQuery variableValueGreaterThan(String name, Object value);

    /**
     * Only select process instances which had a global variable value greater than or
     * equal to the passed value when they ended. Booleans, Byte-arrays and
     * {@link Serializable} objects (which are not primitive type wrappers) are
     * not supported. Only applies to already ended process instances, otherwise
     * use a {@link ProcessInstanceQuery} instead!
     * @param name cannot be null.
     * @param value cannot be null.
     */
    HistoricProcessInstanceQuery variableValueGreaterThanOrEqual(String name, Object value);

    /**
     * Only select process instances which had a global variable value less than the
     * passed value when the ended. Only applies to already ended process
     * instances, otherwise use a {@link ProcessInstanceQuery} instead! Booleans,
     * Byte-arrays and {@link Serializable} objects (which are not primitive type
     * wrappers) are not supported.
     * @param name cannot be null.
     * @param value cannot be null.
     */
    HistoricProcessInstanceQuery variableValueLessThan(String name, Object value);

    /**
     * Only select process instances which has a global variable value less than or equal
     * to the passed value when they ended. Only applies to already ended process
     * instances, otherwise use a {@link ProcessInstanceQuery} instead! Booleans,
     * Byte-arrays and {@link Serializable} objects (which are not primitive type
     * wrappers) are not supported.
     * @param name cannot be null.
     * @param value cannot be null.
     */
    HistoricProcessInstanceQuery variableValueLessThanOrEqual(String name, Object value);

    /**
     * Only select process instances which had global variable value like the given value
     * when they ended. Only applies to already ended process instances, otherwise
     * use a {@link ProcessInstanceQuery} instead! This can be used on string
     * variables only.
     * @param name cannot be null.
     * @param value cannot be null. The string can include the
     *          wildcard character '%' to express like-strategy: starts with
     *          (string%), ends with (%string) or contains (%string%).
     */
    HistoricProcessInstanceQuery variableValueLike(String name, String value);

    /**
     * Only select historic process instances that were started before the given date.
     */
    HistoricProcessInstanceQuery startedBefore(Date date);

    /**
     * Only select historic process instances that were started after the given date.
     */
    HistoricProcessInstanceQuery startedAfter(Date date);

    /**
     * Only select historic process instances that were started before the given date.
     */
    HistoricProcessInstanceQuery finishedBefore(Date date);

    /**
     * Only select historic process instances that were started after the given date.
     */
    HistoricProcessInstanceQuery finishedAfter(Date date);

    /**
     * Only select historic process instance that are started by the given user.
     */

/**
     * Order by the process instance id (needs to be followed by {@link #asc()} or {@link #desc()}).
     */
    HistoricProcessInstanceQuery orderByProcessInstanceId();

    /**
     * Order by the process definition id (needs to be followed by {@link #asc()} or {@link #desc()}).
     */
    HistoricProcessInstanceQuery orderByProcessDefinitionId();

    /**
     * Order by the process definition key (needs to be followed by {@link #asc()} or {@link #desc()}).
     */
    HistoricProcessInstanceQuery orderByProcessDefinitionKey();

    /**
     * Order by the process definition name (needs to be followed by {@link #asc()} or {@link #desc()}).
     */
    HistoricProcessInstanceQuery orderByProcessDefinitionName();

    /**
     * Order by the process definition version (needs to be followed by {@link #asc()} or {@link #desc()}).
     */
    HistoricProcessInstanceQuery orderByProcessDefinitionVersion();

    /**
     * Order by the business key (needs to be followed by {@link #asc()} or {@link #desc()}).
     */
    HistoricProcessInstanceQuery orderByProcessInstanceBusinessKey();

    /**
     * Order by the start time (needs to be followed by {@link #asc()} or {@link #desc()}).
     */
    HistoricProcessInstanceQuery orderByProcessInstanceStartTime();

    /**
     * Order by the end time (needs to be followed by {@link #asc()} or {@link #desc()}).
     */
    HistoricProcessInstanceQuery orderByProcessInstanceEndTime();

    /**
     * Order by the duration of the process instance (needs to be followed by {@link #asc()} or {@link #desc()}).
     */
    HistoricProcessInstanceQuery orderByProcessInstanceDuration();

    /**
     * Only select historic process instances that are top level process instances.
     */
    HistoricProcessInstanceQuery rootProcessInstances();

    /**
     * Only select historic process instances started by the given process
     * instance. {@link ProcessInstance) ids and {@link HistoricProcessInstance}
     * ids match.
     */
    HistoricProcessInstanceQuery superProcessInstanceId(String superProcessInstanceId);

    /**
     * Only select historic process instances having a sub process instance
     * with the given process instance id.
     *
     * Note that there will always be maximum only one
     * such process instance that can be the result of this query.
     */
    HistoricProcessInstanceQuery subProcessInstanceId(String subProcessInstanceId);

    /**
     * Only select historic process instances started by the given case
     * instance.
     */
    HistoricProcessInstanceQuery superCaseInstanceId(String superCaseInstanceId);

    /**
     * Only select historic process instances having a sub case instance
     * with the given case instance id.
     *
     * Note that there will always be maximum only one
     * such process instance that can be the result of this query.
     */
    HistoricProcessInstanceQuery subCaseInstanceId(String subCaseInstanceId);

    /**
     * Only select historic process instances with one of the given tenant ids.
     */
    HistoricProcessInstanceQuery tenantIdIn(String... tenantIds);

    /**
     * Only selects historic process instances which have no tenant id.
     */
    HistoricProcessInstanceQuery withoutTenantId();

    /**
     * Order by tenant id (needs to be followed by {@link #asc()} or {@link #desc()}).
     * Note that the ordering of historic process instances without tenant id is database-specific.
     */
    HistoricProcessInstanceQuery orderByTenantId();

    /**
     * Only select historic process instances that were started as of the provided
     * date. (Date will be adjusted to reflect midnight)
     * @deprecated use {@link #startedAfter(Date)} and {@link #startedBefore(Date)} instead
     */
    @Deprecated
    HistoricProcessInstanceQuery startDateBy(Date date);

    /**
     * Only select historic process instances that were started on the provided date.
     * @deprecated use {@link #startedAfter(Date)} and {@link #startedBefore(Date)} instead
     */
    @Deprecated
    HistoricProcessInstanceQuery startDateOn(Date date);

    /**
     * Only select historic process instances that were finished as of the
     * provided date. (Date will be adjusted to reflect one second before midnight)
     * @deprecated use {@link #startedAfter(Date)} and {@link #startedBefore(Date)} instead
     */
    @Deprecated
    HistoricProcessInstanceQuery finishDateBy(Date date);

    /**
     * Only select historic process instances that were finished on provided date.
     * @deprecated use {@link #startedAfter(Date)} and {@link #startedBefore(Date)} instead
     */
    @Deprecated
    HistoricProcessInstanceQuery finishDateOn(Date date);

    /**
     * Only select historic process instances that executed an activity after the given date.
     */
    HistoricProcessInstanceQuery executedActivityAfter(Date date);

    /**
     * Only select historic process instances that executed an activity before the given date.
     */
    HistoricProcessInstanceQuery executedActivityBefore(Date date);

    /**
     * Only select historic process instances that executed activities with given ids.
     */
    HistoricProcessInstanceQuery executedActivityIdIn(String... ids);

    /**
     * Only select historic process instances that have active activities with given ids.
     */
    HistoricProcessInstanceQuery activeActivityIdIn(String... ids);

    /**
     * Only select historic process instances that executed an job after the given date.
     */
    HistoricProcessInstanceQuery executedJobAfter(Date date);

    /**
     * Only select historic process instances that executed an job before the given date.
     */
    HistoricProcessInstanceQuery executedJobBefore(Date date);

    /**
     * Only select historic process instances that are active.
     */
    HistoricProcessInstanceQuery active();

    /**
     * Only select historic process instances that are suspended.
     */
    HistoricProcessInstanceQuery suspended();

    /**
     * Only select historic process instances that are completed.
     */
    HistoricProcessInstanceQuery completed();

    /**
     * Only select historic process instances that are externallyTerminated.
     */
    HistoricProcessInstanceQuery externallyTerminated();

    /**
     * Only select historic process instances that are internallyTerminated.
     */
    HistoricProcessInstanceQuery internallyTerminated();

    /**
     *
After calling or(), a chain of several filter criteria could follow. Each filter criterion that follows or()
     * will be linked together with an OR expression until the OR query is terminated. To terminate the OR query right
     * after the last filter criterion was applied, {@link #endOr()} must be invoked.

     *
     * @return an object of the type {@link HistoricProcessInstanceQuery} on which an arbitrary amount of filter criteria could be applied.
     * The several filter criteria will be linked together by an OR expression.
     *
     * @throws ProcessEngineException when or() has been invoked directly after or() or after or() and trailing filter
     * criteria. To prevent throwing this exception, {@link #endOr()} must be invoked after a chain of filter criteria to
     * mark the end of the OR query.
     */
    HistoricProcessInstanceQuery or();

    /**
     *
endOr() terminates an OR query on which an arbitrary amount of filter criteria were applied. To terminate the
     * OR query which has been started by invoking {@link #or()}, endOr() must be invoked. Filter criteria which are
     * applied after calling endOr() are linked together by an AND expression.

     *
     * @return an object of the type {@link HistoricProcessInstanceQuery} on which an arbitrary amount of filter criteria could be applied.
     * The filter criteria will be linked together by an AND expression.
     *
     * @throws ProcessEngineException when endOr() has been invoked before {@link #or()} was invoked. To prevent throwing
     * this exception, {@link #or()} must be invoked first.
     */
    HistoricProcessInstanceQuery endOr();
}


public File getPipelineFile() {
        File file = new File(executionRoot, "pipeline.trig");
        file.getParentFile().mkdir();
        return file;
    }

package com.linkedpipes.etl.executor.execution;

import com.linkedpipes.etl.executor.execution.model.ExecutionComponent;
import java.io.File;

public class ResourceManager {

    /**
     * Root directory of all executions.
     */
    private final File root;

    /**
     * Root directory of the execution.
     */
    private final File executionRoot;

    private Integer counter = 0;

    public ResourceManager(File root, File executionRoot) {
        this.root = root;
        this.executionRoot = executionRoot;
    }

    /**
     * Search and return definition file.
     *
     * @return Pipeline as given for execution.
     */
    public File getDefinitionFile() {
        File directory = new File(executionRoot, "definition");
        File[] files = directory.listFiles();
        if (files == null) {
            return null;
        }
        for (File file : files) {
            String fileName = file.getName();
            if (fileName.startsWith("definition")) {
                return file;
            }
        }
        return null;
    }

    public File getExecutionRoot() {
        return executionRoot;
    }

    /**
     * Resolve relative path in given execution..
     */
    public File resolveExecutionPath(String execution, String path) {
        String executionId = execution.substring(execution.indexOf("executions/") + "executions/".length());
        return new File(root, executionId + "/" + path);
    }

    /**
     * Return path to input directory, the directory may not exist.
     */
    public File getInputDirectory() {
        return new File(executionRoot, "input");
    }

    public File getRootWorkingDirectory() {
        return new File(executionRoot, "working");
    }

    /**
     * Return path to working directory, does not create the directory.
     */
    public File getWorkingDirectory(String name) {
        counter += 1;
        return new File(executionRoot, "working/" + name + "-" + counter);
    }

    public File getDebugLogFile() {
        return new File(getExecutionLogDirectory(), "execution-debug.log");
    }

    public File getExecutionLogDirectory() {
        File file = new File(executionRoot, "log");
        file.mkdirs();
        return file;
    }

    public File getWarnLogFile() {
        return new File(getExecutionLogDirectory(), "execution-warn.log");
    }

    /**
     * Return output file for the pipeline execution.
     */

    public File getExecutionFile() {
        File file = new File(executionRoot, "execution.trig");
        file.getParentFile().mkdir();
        return file;
    }

    /**
     * Return output file for original execution file.
     */
    public File getComponentMessageFile(ExecutionComponent component) {
        String iri = component.getIri();
        String id = iri.substring(iri.lastIndexOf("/"));
        File file = new File(this.executionRoot, "messages/" + id + ".trig");
        file.getParentFile().mkdir();
        return file;
    }

    public File getPipelineMessageFile() {
        File file = new File(executionRoot, "messages/execution.trig");
        file.getParentFile().mkdir();
        return file;
    }

    public File getOverviewFile() {
        return new File(executionRoot, "execution-overview.jsonld");
    }

    /**
     * Return given path as relative to the execution root directory.
     */
    public String relative(File path) {
        return executionRoot.toPath().relativize(path.toPath()).toString();
    }
}


public RealMatrix getRootMatrix() {
        return root;
    }

package org.apache.commons.math3.linear;

import org.apache.commons.math3.util.FastMath;

/**
 * Calculates the rectangular Cholesky decomposition of a matrix.
 *
The rectangular Cholesky decomposition of a real symmetric positive
 * semidefinite matrix A consists of a rectangular matrix B with the same
 * number of rows such that: A is almost equal to BBT, depending
 * on a user-defined tolerance. In a sense, this is the square root of A.

 *
The difference with respect to the regular {@link CholeskyDecomposition}
 * is that rows/columns may be permuted (hence the rectangular shape instead
 * of the traditional triangular shape) and there is a threshold to ignore
 * small diagonal elements. This is used for example to generate {@link
 * org.apache.commons.math3.random.CorrelatedRandomVectorGenerator correlated
 * random n-dimensions vectors} in a p-dimension subspace (p < n).
 * In other words, it allows generating random vectors from a covariance
 * matrix that is only positive semidefinite, and not positive definite.

 *
Rectangular Cholesky decomposition is not suited for solving
 * linear systems, so it does not provide any {@link DecompositionSolver
 * decomposition solver}.

 *
 * @see MathWorld
 * @see Wikipedia
 * @version $Id$
 * @since 2.0 (changed to concrete class in 3.0)
 */
public class RectangularCholeskyDecomposition {

    /**
     * Permutated Cholesky root of the symmetric positive semidefinite matrix.
     */
    private final RealMatrix root;

    /**
     * Rank of the symmetric positive semidefinite matrix.
     */
    private int rank;

    /**
     * Decompose a symmetric positive semidefinite matrix.
     *

     * Note: this constructor follows the linpack method to detect dependent
     * columns by proceeding with the Cholesky algorithm until a nonpositive diagonal
     * element is encountered.
     *
     * @see
     * Analysis of the Cholesky Decomposition of a Semi-definite Matrix
     *
     * @param matrix Symmetric positive semidefinite matrix.
     * @exception NonPositiveDefiniteMatrixException if the matrix is not
     * positive semidefinite.
     */
    public RectangularCholeskyDecomposition(RealMatrix matrix) throws NonPositiveDefiniteMatrixException {
        this(matrix, 0);
    }

    /**
     * Decompose a symmetric positive semidefinite matrix.
     *
     * @param matrix Symmetric positive semidefinite matrix.
     * @param small Diagonal elements threshold under which columns are
     * considered to be dependent on previous ones and are discarded.
     * @exception NonPositiveDefiniteMatrixException if the matrix is not
     * positive semidefinite.
     */
    public RectangularCholeskyDecomposition(RealMatrix matrix, double small) throws NonPositiveDefiniteMatrixException {
        final int order = matrix.getRowDimension();
        final double[][] c = matrix.getData();
        final double[][] b = new double[order][order];
        int[] index = new int[order];
        for (int i = 0; i < order; ++i) {
            index[i] = i;
        }
        int r = 0;
        for (boolean loop = true; loop; ) {
            // find maximal diagonal element
            int swapR = r;
            for (int i = r + 1; i < order; ++i) {
                int ii = index[i];
                int isr = index[swapR];
                if (c[ii][ii] > c[isr][isr]) {
                    swapR = i;
                }
            }
            // swap elements
            if (swapR != r) {
                final int tmpIndex = index[r];
                index[r] = index[swapR];
                index[swapR] = tmpIndex;
                final double[] tmpRow = b[r];
                b[r] = b[swapR];
                b[swapR] = tmpRow;
            }
            // check diagonal element
            int ir = index[r];
            if (c[ir][ir] <= small) {
                if (r == 0) {
                    throw new NonPositiveDefiniteMatrixException(c[ir][ir], ir, small);
                }
                // check remaining diagonal elements
                for (int i = r; i < order; ++i) {
                    if (c[index[i]][index[i]] < -small) {
                        // there is at least one sufficiently negative diagonal element,
                        // the symmetric positive semidefinite matrix is wrong
                        throw new NonPositiveDefiniteMatrixException(c[index[i]][index[i]], i, small);
                    }
                }
                // all remaining diagonal elements are close to zero, we consider we have
                // found the rank of the symmetric positive semidefinite matrix
                loop = false;
            } else {
                // transform the matrix
                final double sqrt = FastMath.sqrt(c[ir][ir]);
                b[r][r] = sqrt;
                final double inverse = 1 / sqrt;
                final double inverse2 = 1 / c[ir][ir];
                for (int i = r + 1; i < order; ++i) {
                    final int ii = index[i];
                    final double e = inverse * c[ii][ir];
                    b[i][r] = e;
                    c[ii][ii] -= c[ii][ir] * c[ii][ir] * inverse2;
                    for (int j = r + 1; j < i; ++j) {
                        final int ij = index[j];
                        final double f = c[ii][ij] - e * b[j][r];
                        c[ii][ij] = f;
                        c[ij][ii] = f;
                    }
                }
                // prepare next iteration
                loop = ++r < order;
            }
        }
        // build the root matrix
        rank = r;
        root = MatrixUtils.createRealMatrix(order, r);
        for (int i = 0; i < order; ++i) {
            for (int j = 0; j < r; ++j) {
                root.setEntry(index[i], j, b[i][j]);
            }
        }
    }

    /**
     * Get the root of the covariance matrix.
     * The root is the rectangular matrix B such that
     * the covariance matrix is equal to B.BT
     * @return root of the square matrix
     * @see #getRank()
     */

    /**
     * Get the rank of the symmetric positive semidefinite matrix.
     * The r is the number of independent rows in the symmetric positive semidefinite
     * matrix, it is also the number of columns of the rectangular
     * matrix of the decomposition.
     * @return r of the square matrix.
     * @see #getRootMatrix()
     */
    public int getRank() {
        return rank;
    }
}


public Long getSimCardId() {
        return simCardId;
    }

package com.huaweicloud.sdk.gsl.v3.model;

import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.annotation.JsonProperty;
import java.util.Objects;
import java.util.function.Consumer;

/**
 * Request Object
 */
public class StartStopNetRequest {

    @JsonInclude(JsonInclude.Include.NON_NULL)
    @JsonProperty(value = "sim_card_id")
    private Long simCardId;

    @JsonInclude(JsonInclude.Include.NON_NULL)
    @JsonProperty(value = "body")
    private CutNetReq body;

    public StartStopNetRequest withSimCardId(Long simCardId) {
        this.simCardId = simCardId;
        return this;
    }

    /**
     * SIM卡标识，可通过[查询SIM卡列表接口](http://example.com)获取 minimum: 0
     *
     * @return simCardId
     */

    public void setSimCardId(Long simCardId) {
        this.simCardId = simCardId;
    }

    public StartStopNetRequest withBody(CutNetReq body) {
        this.body = body;
        return this;
    }

    public StartStopNetRequest withBody(Consumer<CutNetReq> bodySetter) {
        if (this.body == null) {
            this.body = new CutNetReq();
            bodySetter.accept(this.body);
        }
        return this;
    }

    /**
     * Get body
     *
     * @return body
     */
    public CutNetReq getBody() {
        return body;
    }

    public void setBody(CutNetReq body) {
        this.body = body;
    }

    @Override
    public boolean equals(java.lang.Object o) {
        if (this == o) {
            return true;
        }
        if (o == null || getClass() != o.getClass()) {
            return false;
        }
        StartStopNetRequest startStopNetRequest = (StartStopNetRequest) o;
        return Objects.equals(this.simCardId, startStopNetRequest.simCardId) && Objects.equals(this.body, startStopNetRequest.body);
    }

    @Override
    public int hashCode() {
        return Objects.hash(simCardId, body);
    }

    @Override
    public String toString() {
        StringBuilder sb = new StringBuilder();
        sb.append("class StartStopNetRequest {\n");
        sb.append("    simCardId: ").append(toIndentedString(simCardId)).append("\n");
        sb.append("    body: ").append(toIndentedString(body)).append("\n");
        sb.append("}");
        return sb.toString();
    }

    /**
     * Convert the given object to string with each line indented by 4 spaces (except the first line).
     */
    private String toIndentedString(java.lang.Object o) {
        if (o == null) {
            return "null";
        }
        return o.toString().replace("\n", "\n    ");
    }
}


public void init(InetAddress bindAddress, Router router) throws InitializationException;

/*
 *
 * Common Development and Distribution License Version 1 or later
 * ("CDDL") (collectively, the "License"). You may not use this file
 * information.
 *
 */
package org.fourthline.cling.transport.spi;

import org.fourthline.cling.transport.Router;
import java.net.InetAddress;

/**
 * Service for receiving TCP (HTTP) streams, one per bound IP address.
 *

 * This service typically listens on a socket for TCP connections.
 *

 * This listening loop is started with the run() method, this service is
 * Runnable. Then {@link Router#received(UpnpStream)} is called with a custom
 * {@link UpnpStream}. This will start processing of the request and run() the
 * {@link UpnpStream} (which is also Runnable) in a separate thread,
 * freeing up the receiving thread immediately.
 *

 *

 * The {@link UpnpStream} then creates a {@link org.fourthline.cling.model.message.StreamRequestMessage}
 * and calls the {@link UpnpStream#process(org.fourthline.cling.model.message.StreamRequestMessage)}
 * method. The {@link UpnpStream} then returns the response to the network client.
 *

 *

 * In pseudo-code:
 *

 *

 * MyStreamServer implements StreamServer {
 *      run() {
 *          while (not stopped) {
 *              Connection con = listenToSocketAndBlock();
 *              router.received( new MyUpnpStream(con) );
 *          }
 *      }
 * }
 *
 * MyUpnpStream(con) extends UpnpStream {
 *      run() {
 *          try {
 *              StreamRequestMessage request = // ... Read request
 *              StreamResponseMessage response = process(request);
 *              // ... Send response
 *              responseSent(response))
 *          } catch (Exception ex) {
 *              responseException(ex);
 *          }
 *      }
 * }
 *

 *

 * An implementation has to be thread-safe.
 *

 *
 * @param <C> The type of the service's configuration.
 *
 * @author Christian Bauer
 */
public interface StreamServer<C extends StreamServerConfiguration> extends Runnable {

    /**
     * Configures the service and starts any listening sockets.
     *
     * @param bindAddress The address to bind any sockets on.
     * @param router The router which handles the incoming {@link org.fourthline.cling.transport.spi.UpnpStream}.
     * @throws InitializationException If the service could not be initialized or started.
     */

    /**
     * This method will be called potentially right after
     * {@link #init(java.net.InetAddress, org.fourthline.cling.transport.Router)}, the
     * actual assigned local port must be available before the server is started.
     *
     * @return The TCP port this service is listening on, e.g. the actual ephemeral port.
     */
    public int getPort();

    /**
     * Stops the service, closes any listening sockets.
     */
    public void stop();

    /**
     * @return This service's configuration.
     */
    public C getConfiguration();
}


@Endpoint(describeByClass = true)
    public static VarIsInitializedOp create(Scope scope, Operand<? extends TType> resource) {
        OperationBuilder opBuilder = scope.opBuilder(OP_NAME, "VarIsInitializedOp");
        opBuilder.addInput(resource.asOutput());
        return new VarIsInitializedOp(opBuilder.build());
    }

// This class has been generated, DO NOT EDIT!
package org.tensorflow.op.core;

import java.util.Arrays;
import org.tensorflow.GraphOperation;
import org.tensorflow.Operand;
import org.tensorflow.Operation;
import org.tensorflow.OperationBuilder;
import org.tensorflow.Output;
import org.tensorflow.op.RawOp;
import org.tensorflow.op.RawOpInputs;
import org.tensorflow.op.Scope;
import org.tensorflow.op.annotation.Endpoint;
import org.tensorflow.op.annotation.Operator;
import org.tensorflow.types.TBool;
import org.tensorflow.types.family.TType;

/**
 * Checks whether a resource handle-based variable has been initialized.
 */
@Operator
public final class VarIsInitializedOp extends RawOp implements Operand<TBool> {

    /**
     * The name of this op, as known by TensorFlow core engine
     */
    public static final String OP_NAME = "VarIsInitializedOp";

    private Output<TBool> isInitialized;

    private VarIsInitializedOp(Operation operation) {
        super(operation);
        int outputIdx = 0;
        isInitialized = operation.output(outputIdx++);
    }

    /**
     * Factory method to create a class wrapping a new VarIsInitializedOp operation.
     *
     * @param scope current scope
     * @param resource the input resource handle.
     * @return a new instance of VarIsInitializedOp
     */

    /**
     * Gets isInitialized.
     * a scalar boolean which is true if the variable has been
     * initialized.
     * @return isInitialized.
     */
    public Output<TBool> isInitialized() {
        return isInitialized;
    }

    @Override
    public Output<TBool> asOutput() {
        return isInitialized;
    }

    public static class Inputs extends RawOpInputs<VarIsInitializedOp> {

        /**
         * the input resource handle.
         */
        public final Operand<? extends TType> resource;

        public Inputs(GraphOperation op) {
            super(new VarIsInitializedOp(op), op, Arrays.asList());
            int inputIndex = 0;
            resource = (Operand<? extends TType>) op.input(inputIndex++);
        }
    }
}


@Override
    public Object getTransferData(DataFlavor flavor) throws UnsupportedFlavorException {
        if (false == DataFlavor.imageFlavor.equals(flavor)) {
            throw new UnsupportedFlavorException(flavor);
        }
        return image;
    }

package org.aoju.bus.core.swing;

import java.awt.*;
import java.awt.datatransfer.DataFlavor;
import java.awt.datatransfer.Transferable;
import java.awt.datatransfer.UnsupportedFlavorException;
import java.io.Serializable;

/**
 * 图片转换器,用于将图片对象转换为剪贴板支持的对象
 * 此对象也用于将图像文件和{@link DataFlavor#imageFlavor} 元信息对应
 *
 * @author Kimi Liu
 * @version 6.3.0
 * @since JDK 1.8+
 */
public class ImageSelection implements Transferable, Serializable {

    private static final long serialVersionUID = 1L;

    private final Image image;

    /**
     * 构造
     *
     * @param image 图片
     */
    public ImageSelection(Image image) {
        this.image = image;
    }

    @Override
    public DataFlavor[] getTransferDataFlavors() {
        return new DataFlavor[] { DataFlavor.imageFlavor };
    }

    /**
     * 是否支持指定元数据类型
     *
     * @param flavor 元数据类型
     * @return 是否支持
     */
    @Override
    public boolean isDataFlavorSupported(DataFlavor flavor) {
        return DataFlavor.imageFlavor.equals(flavor);
    }

    /**
     * 获取图片
     *
     * @param flavor 元数据类型
     * @return 转换后的对象
     */


public short getNodeType() {
        return nodeType;
    }

package org.apache.flex.forks.batik.css.engine.sac;

import org.w3c.css.sac.Selector;
import org.w3c.css.sac.SiblingSelector;
import org.w3c.css.sac.SimpleSelector;

/**
 * This class provides an abstract implementation of the {@link
 * org.w3c.css.sac.SiblingSelector} interface.
 *
 * @author Stephane Hillion
 * @version $Id: AbstractSiblingSelector.java 475685 2006-11-16 11:16:05Z cam $
 */
public abstract class AbstractSiblingSelector implements SiblingSelector, ExtendedSelector {

    /**
     * The node type.
     */
    protected short nodeType;

    protected Selector selector;

    /**
     * The simple selector.
     */
    protected SimpleSelector simpleSelector;

    /**
     * Creates a new SiblingSelector object.
     */
    protected AbstractSiblingSelector(short type, Selector sel, SimpleSelector simple) {
        nodeType = type;
        selector = sel;
        simpleSelector = simple;
    }

    /**
     * Returns the node type.
     */

    /**
     * Indicates whether some other object is "equal to" this one.
     * @param obj the reference object with which to compare.
     */
    public boolean equals(Object obj) {
        if (obj == null || (obj.getClass() != getClass())) {
            return false;
        }
        AbstractSiblingSelector s = (AbstractSiblingSelector) obj;
        return s.simpleSelector.equals(simpleSelector);
    }

    /**
     * Returns the specificity of this selector.
     */
    public int getSpecificity() {
        return ((ExtendedSelector) selector).getSpecificity() + ((ExtendedSelector) simpleSelector).getSpecificity();
    }

    public Selector getSelector() {
        return selector;
    }

    public SimpleSelector getSiblingSelector() {
        return simpleSelector;
    }
}