for (int i = 0; i < oa.length; i++) {
            splatts[i] = (Splatt) oa[i];
            sum += splatts[i].weight;
        }

package net.sf.jaer.eventprocessing.filter;

import com.jogamp.opengl.GL;
import java.util.ArrayList;
import java.util.Observable;
import java.util.Observer;
import com.jogamp.opengl.GL2;
import com.jogamp.opengl.GLAutoDrawable;
import net.sf.jaer.Description;
import net.sf.jaer.DevelopmentStatus;
import net.sf.jaer.chip.AEChip;
import net.sf.jaer.event.EventPacket;
import net.sf.jaer.event.OutputEventIterator;
import net.sf.jaer.event.PolarityEvent;
import net.sf.jaer.eventprocessing.EventFilter2D;
import net.sf.jaer.graphics.FrameAnnotater;

/**
 * Computes circular convolutions by splatting out events and checking receiving
 * pixels to see if they exceed a threshold. A behavioral model of
 * Raphael/Bernabe convolution chip, but limited in that it presently only
 * allows positive binary kernel weights, thus the output events can be
 * triggered by lots of input activity.
 *
 * @author tobi
 */
@Description("Computes circular convolutions by splatting out events and checking receiving pixels to see if they exceed a threshold")
@DevelopmentStatus(DevelopmentStatus.Status.Experimental)
public final class CircularConvolutionFilter extends EventFilter2D implements Observer, FrameAnnotater {

    static final int NUM_INPUT_CELL_TYPES = 1;

    protected boolean useBalancedKernel = getBoolean("useBalancedKernel", true);

    protected float negativeKernelDimMultiple = getFloat("negativeKernelDimMultiple", 2);

    private float negativeWeight = 0;

    private int negativeKernelRadius = 0;

    /**
     * the number of cell output types
     */
    // we make it big so rendering is in color
    public final int NUM_OUTPUT_TYPES = 1;

    /**
     * Creates a new instance of CircularConvolutionFilter
     */
    public CircularConvolutionFilter(AEChip chip) {
        super(chip);
        chip.addObserver(this);
        resetFilter();
        setFilterEnabled(false);
        setPropertyTooltip("useBalancedKernel", "balances kernel to zero sum with positive and negative weights");
    }

    @Override
    synchronized public EventPacket filterPacket(EventPacket in) {
        checkOutputPacketEventType(in);
        int sx = chip.getSizeX() - 1;
        int sy = chip.getSizeY() - 1;
        int n = in.getSize();
        OutputEventIterator oi = out.outputIterator();
        for (Object o : in) {
            if (o == null) {
                continue;
            }
            PolarityEvent e = (PolarityEvent) o;
            if (e.isSpecial() || e.isFilteredOut()) {
                PolarityEvent oe = (PolarityEvent) oi.nextOutput();
                oe.copyFrom(e);
                continue;
            }
            x = e.x;
            y = e.y;
            ts = e.timestamp;
            for (Splatt s : splatts) {
                int xoff = x + s.x;
                if ((xoff < 0) || (xoff > sx)) {
                    // precheck array access
                    continue;
                }
                int yoff = y + s.y;
                if ((yoff < 0) || (yoff > sy)) {
                    continue;
                }
                float dtMs = (ts - convolutionLastEventTime[xoff][yoff]) * 1e-3f;
                if (dtMs < 0) {
                    convolutionLastEventTime[xoff][yoff] = ts;
                    // ignore negative dt
                    continue;
                }
                float vmold = convolutionVm[xoff][yoff];
                if (s.weight < 0) {
                    float vm = vmold + s.weight;
                    convolutionVm[xoff][yoff] = vm;
                } else {
                    vmold = (float) (vmold * (Math.exp(-dtMs / tauMs)));
                    float vm = vmold + s.weight;
                    convolutionVm[xoff][yoff] = vm;
                    convolutionLastEventTime[xoff][yoff] = ts;
                    if (vm > threshold) {
                        PolarityEvent oe = (PolarityEvent) oi.nextOutput();
                        oe.copyFrom(e);
                        oe.x = (short) xoff;
                        oe.y = (short) yoff;
                        convolutionVm[xoff][yoff] = 0;
                    }
                }
            }
        }
        return out;
    }

    @Override
    synchronized public void resetFilter() {
        allocateMap();
    }

    @Override
    public void annotate(GLAutoDrawable drawable) {
        // TODO make this a displaylist
        GL2 gl = drawable.getGL().getGL2();
        // where to draw it
        final int xp = -20, yp = 10;
        // how big each one, 1 for actual size
        final int sz = 1;
        // draw negative part as big rectangle
        gl.glColor4f(-negativeWeight, 0, 0, 1);
        gl.glRectf(xp + ((-negativeKernelRadius - .5f) * sz), yp + ((-negativeKernelRadius - .5f) * sz), xp + ((negativeKernelRadius + .5f) * sz), yp + ((negativeKernelRadius + .5f) * sz));
        gl.glColor4f(0, 0, 1, .5f);
        gl.glBegin(GL.GL_LINE_LOOP);
        gl.glVertex2f(xp + ((-negativeKernelRadius - .5f) * sz), yp + ((-negativeKernelRadius - .5f) * sz));
        gl.glVertex2f(xp + ((negativeKernelRadius - .5f) * sz), yp + ((-negativeKernelRadius - .5f) * sz));
        gl.glVertex2f(xp + ((negativeKernelRadius - .5f) * sz), yp + ((negativeKernelRadius - .5f) * sz));
        gl.glVertex2f(xp + ((-negativeKernelRadius - .5f) * sz), yp + ((negativeKernelRadius - .5f) * sz));
        gl.glEnd();
        // draw each positive kernel pixel on top
        for (Splatt s : splatts) {
            if (s.weight > 0) {
                gl.glColor4f(0, s.weight, 0, 1);
                gl.glRectf(xp + ((s.x - .5f) * sz), yp + ((s.y - .5f) * sz), xp + ((s.x + .5f) * sz), yp + ((s.y + .5f) * sz));
            } else {
            }
        }
    }

    /**
     * @return the useBalancedKernel
     */
    public boolean isUseBalancedKernel() {
        return useBalancedKernel;
    }

    /**
     * @param useBalancedKernel the useBalancedKernel to set
     */
    synchronized public void setUseBalancedKernel(boolean useBalancedKernel) {
        this.useBalancedKernel = useBalancedKernel;
        putBoolean("useBalancedKernel", useBalancedKernel);
        computeSplattLookup();
    }

    /**
     * @return the negativeKernelDimMultiple
     */
    public float getNegativeKernelDimMultiple() {
        return negativeKernelDimMultiple;
    }

    /**
     * @param negativeKernelDimMultiple the negativeKernelDimMultiple to set
     */
    public void setNegativeKernelDimMultiple(float negativeKernelDimMultiple) {
        this.negativeKernelDimMultiple = negativeKernelDimMultiple;
        putFloat("negativeKernelDimMultiple", negativeKernelDimMultiple);
        computeSplattLookup();
    }

    final class Splatt {

        int x, y;

        float weight = 1;

        Splatt() {
            x = 0;
            y = 0;
            weight = 1;
        }

        Splatt(int x, int y) {
            this.x = x;
            this.y = y;
        }

        Splatt(int x, int y, float w) {
            this.x = x;
            this.y = y;
            weight = w;
        }

        @Override
        public String toString() {
            return "Splatt: " + x + "," + y + "," + String.format("%.1f", weight);
        }
    }

    private Splatt[] splatts;

    // computes the indices to splatt to from a source event
    // these are octagonal around a point to the neighboring pixels at a certain radius
    // eg, radius=0, impulse kernal=identity kernel
    // radius=1, nearest neighbors in 8 directions
    // TODO include negative weights where there is no kernel circle to end with zero net kernel sum
    synchronized void computeSplattLookup() {
        ArrayList<Splatt> list = new ArrayList<Splatt>();
        // num pixels
        double circum = 2 * Math.PI * radius;
        int xlast = -1, ylast = -1;
        int n = (int) Math.ceil(circum);
        if (radius < 3) {
            switch(radius) {
                case // identity
                0:
                    list.add(new Splatt());
                    break;
                case 1:
                    list.add(new Splatt(1, 0, .25f));
                    list.add(new Splatt(0, 1, .25f));
                    list.add(new Splatt(-1, 0, .25f));
                    list.add(new Splatt(0, -1, .25f));
                    break;
                case 2:
                    list.add(new Splatt(1, 0));
                    list.add(new Splatt(0, 1));
                    list.add(new Splatt(-1, 0));
                    list.add(new Splatt(0, -1));
                    list.add(new Splatt(1, 1));
                    list.add(new Splatt(-1, 1));
                    list.add(new Splatt(-1, -1));
                    list.add(new Splatt(1, -1));
                    float f = 1f / list.size();
                    for (Splatt s : list) {
                        s.weight *= f;
                    }
                    break;
                default:
            }
        } else {
            for (int i = 0; i < n; i++) {
                double theta = (2 * Math.PI * i) / circum;
                double xoff = Math.cos(theta) * radius;
                double yoff = Math.sin(theta) * radius;
                double xround = Math.round(xoff);
                double yround = Math.round(yoff);
                if ((xlast != xround) || (ylast != yround)) {
                    // dont make multiple copies of the same splatt around the circle
                    Splatt s = new Splatt();
                    s.x = (int) xround;
                    s.y = (int) yround;
                    s.weight = 1;
                    xlast = s.x;
                    ylast = s.y;
                    list.add(s);
                }
            }
        }
        // // make negative outside ring, 1/2 weight
        // if((xlast!=xround) || (ylast!=yround)){ // dont make multiple copies of the same splatt around the circle
        // if((xlast!=xround) || (ylast!=yround)){ // dont make multiple copies of the same splatt around the circle
        float sum = 0;
        for (Splatt s : list) {
            sum += s.weight;
        }
        log.info("splatt total positive weight = " + sum + " num weights=" + list.size());
        if (isUseBalancedKernel()) {
            negativeKernelRadius = (int) Math.round(radius * negativeKernelDimMultiple);
            final int numNegWeights = (2 * negativeKernelRadius + 1) * (2 * negativeKernelRadius + 1);
            negativeWeight = -sum / numNegWeights;
            for (int x = -negativeKernelRadius; x <= negativeKernelRadius; x++) {
                for (int y = -negativeKernelRadius; y <= negativeKernelRadius; y++) {
                    list.add(new Splatt(x, y, negativeWeight));
                }
            }
        }
        Object[] oa = list.toArray();
        splatts = new Splatt[oa.length];
        sum = 0;

        log.info("splatt final total weight = " + sum + " num weights=" + splatts.length);
    }

    int PADDING = 0, P = 0;

    float[][] convolutionVm;

    int[][] convolutionLastEventTime;

    private void allocateMap() {
        if ((chip.getSizeX() == 0) || (chip.getSizeY() == 0)) {
            // log.warning("tried to allocateMap in CircularConvolutionFilter but chip size is 0");
            return;
        }
        convolutionVm = new float[chip.getSizeX()][chip.getSizeY()];
        convolutionLastEventTime = new int[chip.getSizeX()][chip.getSizeY()];
        computeSplattLookup();
    }

    private short x, y;

    private byte type;

    private int ts;

    @Override
    public void initFilter() {
        resetFilter();
    }

    @Override
    public void update(Observable o, Object arg) {
        if (!isFilterEnabled()) {
            return;
        }
        initFilter();
    }

    private int radius = getInt("radius", 3);

    {
        setPropertyTooltip("radius", "radius in pixels of kernal");
    }

    public int getRadius() {
        return radius;
    }

    synchronized public void setRadius(int radius) {
        if (radius < 0) {
            radius = 0;
        } else if (radius > chip.getMaxSize()) {
            radius = chip.getMaxSize();
        }
        if (radius != this.radius) {
            this.radius = radius;
            putInt("radius", radius);
            resetFilter();
        }
    }

    private float tauMs = getFloat("tauMs", 10f);

    {
        setPropertyTooltip("tauMs", "time constant in ms of integrator neuron potential decay");
    }

    public float getTauMs() {
        return tauMs;
    }

    synchronized public void setTauMs(float tauMs) {
        if (tauMs < 0) {
            tauMs = 0;
        } else if (tauMs > 10000) {
            tauMs = 10000f;
        }
        this.tauMs = tauMs;
        getPrefs().putFloat("CircularConvolutionFilter.tauMs", tauMs);
    }

    private float threshold = getFloat("threshold", 1f);

    {
        setPropertyTooltip("threshold", "threahold on ms for firing output event from integrating neuron");
    }

    public float getThreshold() {
        return threshold;
    }

    synchronized public void setThreshold(float threshold) {
        if (threshold < 0) {
            threshold = 0;
        } else if (threshold > 100) {
            threshold = 100;
        }
        this.threshold = threshold;
        putFloat("threshold", threshold);
    }
}


for (int i = 0; i < this.Descriptor.length; i++) {
                this.Descriptor[i] = framedata[i + 6];
            }

package com.zsmartsystems.zigbee.dongle.cc2531.network.packet.zdo;

import java.util.Arrays;
import com.zsmartsystems.zigbee.dongle.cc2531.network.packet.ResponseStatus;
import com.zsmartsystems.zigbee.dongle.cc2531.network.packet.ZToolCMD;
import com.zsmartsystems.zigbee.dongle.cc2531.network.packet.ZToolPacket;
import com.zsmartsystems.zigbee.dongle.cc2531.zigbee.util.DoubleByte;
import com.zsmartsystems.zigbee.dongle.cc2531.zigbee.util.ZToolAddress16;

/**
 * @author Alvaro Fides Valero
 */
public class ZDO_USER_DESC_RSP extends ZToolPacket {

    // / Length, in bytes, of the user descriptor
    public int DescLen;

    // / Dynamic array, User descriptor array (can be up to 15 bytes).
    public int[] Descriptor;

    public ZToolAddress16 nwkAddr;

    // / the message's source network address.
    public ZToolAddress16 SrcAddress;

    // / this field indicates either SUCCESS or FAILURE.
    public int Status;

    public ZDO_USER_DESC_RSP() {
        this.Descriptor = new int[0xff];
    }

    public ZDO_USER_DESC_RSP(int[] framedata) {
        this.SrcAddress = new ZToolAddress16(framedata[1], framedata[0]);
        this.Status = framedata[2];
        if (framedata.length > 3) {
            this.nwkAddr = new ZToolAddress16(framedata[4], framedata[3]);
            this.DescLen = framedata[5];
            this.Descriptor = new int[this.DescLen];

        } else {
            this.nwkAddr = new ZToolAddress16();
            this.DescLen = 0;
            this.Descriptor = new int[0];
        }
        super.buildPacket(new DoubleByte(ZToolCMD.ZDO_USER_DESC_RSP), framedata);
    }

    @Override
    public String toString() {
        return "ZDO_USER_DESC_RSP{" + "DescLen=" + DescLen + ", Descriptor=" + Arrays.toString(Descriptor) + ", nwkAddr=" + nwkAddr + ", SrcAddress=" + SrcAddress + ", Status=" + ResponseStatus.getStatus(Status) + '}';
    }
}


try {
                    delegate.onItemAdded(item);
                } catch (Throwable t) {
                    LOG.warn("Error notifying listener of itemAdded(" + item + ")", t);
                    Exceptions.propagate(t);
                }

package org.apache.brooklyn.core.mgmt.internal;

import static com.google.common.base.Preconditions.checkNotNull;
import org.apache.brooklyn.api.mgmt.ExecutionManager;
import org.apache.brooklyn.util.collections.MutableMap;
import org.apache.brooklyn.util.core.task.BasicExecutionManager;
import org.apache.brooklyn.util.core.task.SingleThreadedScheduler;
import org.apache.brooklyn.util.exceptions.Exceptions;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class AsyncCollectionChangeAdapter<Item> implements CollectionChangeListener<Item> {

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

    private final ExecutionManager executor;

    private final CollectionChangeListener<Item> delegate;

    public AsyncCollectionChangeAdapter(ExecutionManager executor, CollectionChangeListener<Item> delegate) {
        this.executor = checkNotNull(executor, "executor");
        this.delegate = checkNotNull(delegate, "delegate");
        ((BasicExecutionManager) executor).setTaskSchedulerForTag(delegate, SingleThreadedScheduler.class);
    }

    @Override
    public void onItemAdded(final Item item) {
        executor.submit(MutableMap.of("tag", delegate), new Runnable() {

            @Override
            public void run() {

            }
        });
    }

    @Override
    public void onItemRemoved(final Item item) {
        executor.submit(MutableMap.of("tag", delegate), new Runnable() {

            @Override
            public void run() {
                try {
                    delegate.onItemRemoved(item);
                } catch (Throwable t) {
                    LOG.warn("Error notifying listener of itemAdded(" + item + ")", t);
                    Exceptions.propagate(t);
                }
            }
        });
    }

    @Override
    public int hashCode() {
        return delegate.hashCode();
    }

    @Override
    public boolean equals(Object other) {
        return (other instanceof AsyncCollectionChangeAdapter) && delegate.equals(((AsyncCollectionChangeAdapter<?>) other).delegate);
    }
}


try {
            Long.parseLong(argument);
            return true;
        } catch (final NumberFormatException e1) {
            try {
                Double.parseDouble(argument);
                return true;
            } catch (final NumberFormatException e2) {
                return false;
            }
        }

package org.rf.ide.core.validation;

import java.util.regex.Pattern;

/**
 * @author Michal Anglart
 */
public class RobotTimeFormat {

    public static boolean isValidRobotTimeArgument(final String argument) {
        return isPlainNumber(argument) || isTimeString(argument) || isTimerString(argument);
    }

    private static boolean isPlainNumber(final String argument) {

    }

    private static boolean isTimeString(final String argument) {
        return Pattern.matches("^\\s*" + daySpecifier() + hoursSpecifier() + minutesSpecifier() + secondsSpecifier() + millisSpecifier() + "$", argument);
    }

    private static String daySpecifier() {
        return "(-?\\d+(\\.\\d*)?\\s*(days|day|d)\\s*)?";
    }

    private static String hoursSpecifier() {
        return "(-?\\d+(\\.\\d*)?\\s*(hours|hour|h)\\s*)?";
    }

    private static String minutesSpecifier() {
        return "(-?\\d+(\\.\\d*)?\\s*(minutes|minute|mins|min|m)\\s*)?";
    }

    private static String secondsSpecifier() {
        return "(-?\\d+(\\.\\d*)?\\s*(seconds|second|sec|s)\\s*)?";
    }

    private static String millisSpecifier() {
        return "(-?\\d+(\\.\\d*)?\\s*(milliseconds|millisecond|millis|ms)\\s*)?";
    }

    private static boolean isTimerString(final String argument) {
        return Pattern.matches("^-?(\\d+:)?\\d+:\\d+(\\.\\d+)?$", argument);
    }
}


private void releaseVelocityTracker() {
        if (null != mVelocityTracker) {
            mVelocityTracker.clear();
            mVelocityTracker.recycle();
            mVelocityTracker = null;
        }
    }

package com.mcxtzhang.swipemenulib;

import android.animation.Animator;
import android.animation.AnimatorListenerAdapter;
import android.animation.ValueAnimator;
import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.PointF;
import android.util.AttributeSet;
import android.view.MotionEvent;
import android.view.VelocityTracker;
import android.view.View;
import android.view.ViewConfiguration;
import android.view.ViewGroup;
import android.view.animation.AccelerateInterpolator;
import android.view.animation.OvershootInterpolator;

/**
 * 【Item侧滑删除菜单】
 * 继承自ViewGroup，实现滑动出现删除等选项的效果，
 * 思路：跟随手势将item向左滑动，
 * 在onMeasure时 将第一个Item设为屏幕宽度
 * 【解决屏幕上多个侧滑删除菜单】：内设一个类静态View类型变量 ViewCache，存储的是当前正处于右滑状态的CstSwipeMenuItemViewGroup，
 * 每次Touch时对比，如果两次Touch的不是一个View，那么令ViewCache恢复普通状态，并且设置新的CacheView
 * 只要有一个侧滑菜单处于打开状态， 就不给外层布局上下滑动了
 *

 * 平滑滚动使用的是Scroller,20160811，最新平滑滚动又用属性动画做了，因为这样更酷炫(设置加速器不同)
 *

 * 20160824,fix 【多指一起滑我的情况】：只接第一个客人(使用一个类静态布尔变量)
 * other:
 * 1 菜单处于侧滑时，拦截长按事件
 * 2 解决侧滑时 点击 的冲突
 * 3 通过 isIos 变量控制是否是IOS阻塞式交互，默认是打开的。
 * 4 通过 isSwipeEnable 变量控制是否开启右滑菜单，默认打开。（某些场景，复用item，没有编辑权限的用户不能右滑）
 * 5 2016 09 29 add,，通过开关 isLeftSwipe支持左滑右滑
 * 6 2016 10 21 add , 增加viewChache 的 get()方法，可以用在：当点击外部空白处时，关闭正在展开的侧滑菜单。
 * 7 2016 10 22 fix , 当父控件宽度不是全屏时的bug。
 * 2016 10 22 add , 仿QQ，侧滑菜单展开时，点击除侧滑菜单之外的区域，关闭侧滑菜单。
 * 8 2016 11 03 add,判断手指起始落点，如果距离属于滑动了，就屏蔽一切点击事件。
 * 9 2016 11 04 fix 长按事件和侧滑的冲突。
 * 10 2016 11 09 add,适配GridLayoutManager，将以第一个子Item(即ContentItem)的宽度为控件宽度。
 * 11 2016 11 14 add,支持padding,且后续计划加入上滑下滑，因此不再支持ContentItem的margin属性。
 * 2016 11 14 add,修改回弹的动画，更平滑。
 * 2016 11 14 fix,微小位移的move不回回弹的bug
 * 2016 11 18,fix 当ItemView存在高度可变的情况
 * 2016 12 07,fix 禁止侧滑时(isSwipeEnable false)，点击事件不受干扰。
 * 2016 12 09,fix ListView快速滑动快速删除时，偶现菜单不消失的bug。
 * Created by zhangxutong .
 * Date: 16/04/24
 */
public class SwipeMenuLayout extends ViewGroup {

    private static final String TAG = "zxt/SwipeMenuLayout";

    // 为了处理单击事件的冲突
    private int mScaleTouchSlop;

    // 计算滑动速度用
    private int mMaxVelocity;

    // 多点触摸只算第一根手指的速度
    private int mPointerId;

    // 自己的高度
    private int mHeight;

    private int mRightMenuWidths;

    // 滑动判定临界值（右侧菜单宽度的40%） 手指抬起时，超过了展开，没超过收起menu
    private int mLimit;

    // 2016 11 13 add ，存储contentView(第一个View)
    private View mContentView;

    // private Scroller mScroller;//以前item的滑动动画靠它做，现在用属性动画做
    // 上一次的xy
    private PointF mLastP = new PointF();

    // 2016 10 22 add , 仿QQ，侧滑菜单展开时，点击除侧滑菜单之外的区域，关闭侧滑菜单。
    // 增加一个布尔值变量，dispatch函数里，每次down时，为true，move时判断，如果是滑动动作，设为false。
    // 在Intercept函数的up时，判断这个变量，如果仍为true 说明是点击事件，则关闭菜单。
    private boolean isUnMoved = true;

    // 2016 11 03 add,判断手指起始落点，如果距离属于滑动了，就屏蔽一切点击事件。
    // up-down的坐标，判断是否是滑动，如果是，则屏蔽一切点击事件
    private PointF mFirstP = new PointF();

    private boolean isUserSwiped;

    // 存储的是当前正在展开的View
    private static SwipeMenuLayout mViewCache;

    // 防止多只手指一起滑我的flag 在每次down里判断， touch事件结束清空
    private static boolean isTouching;

    // 滑动速度变量
    private VelocityTracker mVelocityTracker;

    private android.util.Log LogUtils;

    private boolean isSwipeEnable;

    /**
     * IOS、QQ式交互，默认开
     */
    private boolean isIos;

    // IOS类型下，是否拦截事件的flag
    private boolean iosInterceptFlag;

    private boolean isLeftSwipe;

    public SwipeMenuLayout(Context context) {
        this(context, null);
    }

    public SwipeMenuLayout(Context context, AttributeSet attrs) {
        this(context, attrs, 0);
    }

    public SwipeMenuLayout(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        init(context, attrs, defStyleAttr);
    }

    public boolean isSwipeEnable() {
        return isSwipeEnable;
    }

    /**
     * 设置侧滑功能开关
     *
     * @param swipeEnable
     */
    public void setSwipeEnable(boolean swipeEnable) {
        isSwipeEnable = swipeEnable;
    }

    public boolean isIos() {
        return isIos;
    }

    /**
     * 设置是否开启IOS阻塞式交互
     *
     * @param ios
     */
    public SwipeMenuLayout setIos(boolean ios) {
        isIos = ios;
        return this;
    }

    public boolean isLeftSwipe() {
        return isLeftSwipe;
    }

    /**
     * 设置是否开启左滑出菜单，设置false 为右滑出菜单
     *
     * @param leftSwipe
     * @return
     */
    public SwipeMenuLayout setLeftSwipe(boolean leftSwipe) {
        isLeftSwipe = leftSwipe;
        return this;
    }

    public static SwipeMenuLayout getViewCache() {
        return mViewCache;
    }

    private void init(Context context, AttributeSet attrs, int defStyleAttr) {
        mScaleTouchSlop = ViewConfiguration.get(context).getScaledTouchSlop();
        mMaxVelocity = ViewConfiguration.get(context).getScaledMaximumFlingVelocity();
        // 初始化滑动帮助类对象
        // 右滑删除功能的开关,默认开
        isSwipeEnable = true;
        // IOS、QQ式交互，默认开
        isIos = true;
        // 左滑右滑的开关,默认左滑打开菜单
        isLeftSwipe = true;
        TypedArray ta = context.getTheme().obtainStyledAttributes(attrs, R.styleable.SwipeMenuLayout, defStyleAttr, 0);
        int count = ta.getIndexCount();
        for (int i = 0; i < count; i++) {
            int attr = ta.getIndex(i);
            // 如果引用成AndroidLib 资源都不是常量，无法使用switch case
            if (attr == R.styleable.SwipeMenuLayout_swipeEnable) {
                isSwipeEnable = ta.getBoolean(attr, true);
            } else if (attr == R.styleable.SwipeMenuLayout_ios) {
                isIos = ta.getBoolean(attr, true);
            } else if (attr == R.styleable.SwipeMenuLayout_leftSwipe) {
                isLeftSwipe = ta.getBoolean(attr, true);
            }
        }
        ta.recycle();
    }

    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        super.onMeasure(widthMeasureSpec, heightMeasureSpec);
        // 令自己可点击，从而获取触摸事件
        setClickable(true);
        // 由于ViewHolder的复用机制，每次这里要手动恢复初始值
        mRightMenuWidths = 0;
        mHeight = 0;
        // 2016 11 09 add,适配GridLayoutManager，将以第一个子Item(即ContentItem)的宽度为控件宽度
        int contentWidth = 0;
        int childCount = getChildCount();
        // add by 2016 08 11 为了子View的高，可以matchParent(参考的FrameLayout 和LinearLayout的Horizontal)
        final boolean measureMatchParentChildren = MeasureSpec.getMode(heightMeasureSpec) != MeasureSpec.EXACTLY;
        boolean isNeedMeasureChildHeight = false;
        for (int i = 0; i < childCount; i++) {
            View childView = getChildAt(i);
            // 令每一个子View可点击，从而获取触摸事件
            childView.setClickable(true);
            if (childView.getVisibility() != GONE) {
                // 后续计划加入上滑、下滑，则将不再支持Item的margin
                measureChild(childView, widthMeasureSpec, heightMeasureSpec);
                final MarginLayoutParams lp = (MarginLayoutParams) childView.getLayoutParams();
                mHeight = Math.max(mHeight, childView.getMeasuredHeight());
                if (measureMatchParentChildren && lp.height == LayoutParams.MATCH_PARENT) {
                    isNeedMeasureChildHeight = true;
                }
                if (i > 0) {
                    // 第一个布局是Left item，从第二个开始才是RightMenu
                    mRightMenuWidths += childView.getMeasuredWidth();
                } else {
                    mContentView = childView;
                    contentWidth = childView.getMeasuredWidth();
                }
            }
        }
        setMeasuredDimension(getPaddingLeft() + getPaddingRight() + contentWidth, // 宽度取第一个Item(Content)的宽度
        mHeight + getPaddingTop() + getPaddingBottom());
        // 滑动判断的临界值
        mLimit = mRightMenuWidths * 4 / 10;
        if (isNeedMeasureChildHeight) {
            // 如果子View的height有MatchParent属性的，设置子View高度
            forceUniformHeight(childCount, widthMeasureSpec);
        }
    }

    @Override
    public LayoutParams generateLayoutParams(AttributeSet attrs) {
        return new MarginLayoutParams(getContext(), attrs);
    }

    /**
     * 给MatchParent的子View设置高度
     *
     * @param count
     * @param widthMeasureSpec
     * @see android.widget.LinearLayout# 同名方法
     */
    private void forceUniformHeight(int count, int widthMeasureSpec) {
        // Pretend that the linear layout has an exact size. This is the measured height of
        // ourselves. The measured height should be the max height of the children, changed
        // to accommodate the heightMeasureSpec from the parent
        int uniformMeasureSpec = MeasureSpec.makeMeasureSpec(getMeasuredHeight(), // 以父布局高度构建一个Exactly的测量参数
        MeasureSpec.EXACTLY);
        for (int i = 0; i < count; ++i) {
            final View child = getChildAt(i);
            if (child.getVisibility() != GONE) {
                MarginLayoutParams lp = (MarginLayoutParams) child.getLayoutParams();
                if (lp.height == LayoutParams.MATCH_PARENT) {
                    // Temporarily force children to reuse their old measured width
                    // FIXME: this may not be right for something like wrapping text?
                    // measureChildWithMargins 这个函数会用到宽，所以要保存一下
                    int oldWidth = lp.width;
                    lp.width = child.getMeasuredWidth();
                    // Remeasure with new dimensions
                    measureChildWithMargins(child, widthMeasureSpec, 0, uniformMeasureSpec, 0);
                    lp.width = oldWidth;
                }
            }
        }
    }

    @Override
    protected void onLayout(boolean changed, int l, int t, int r, int b) {
        int childCount = getChildCount();
        int left = 0 + getPaddingLeft();
        int right = 0 + getPaddingLeft();
        for (int i = 0; i < childCount; i++) {
            View childView = getChildAt(i);
            if (childView.getVisibility() != GONE) {
                if (i == 0) {
                    // 第一个子View是内容 宽度设置为全屏
                    childView.layout(left, getPaddingTop(), left + childView.getMeasuredWidth(), getPaddingTop() + childView.getMeasuredHeight());
                    left = left + childView.getMeasuredWidth();
                } else {
                    if (isLeftSwipe) {
                        childView.layout(left, getPaddingTop(), left + childView.getMeasuredWidth(), getPaddingTop() + childView.getMeasuredHeight());
                        left = left + childView.getMeasuredWidth();
                    } else {
                        childView.layout(right - childView.getMeasuredWidth(), getPaddingTop(), right, getPaddingTop() + childView.getMeasuredHeight());
                        right = right - childView.getMeasuredWidth();
                    }
                }
            }
        }
    }

    @Override
    public boolean dispatchTouchEvent(MotionEvent ev) {
        if (isSwipeEnable) {
            acquireVelocityTracker(ev);
            final VelocityTracker verTracker = mVelocityTracker;
            switch(ev.getAction()) {
                case MotionEvent.ACTION_DOWN:
                    // 2016 11 03 add,判断手指起始落点，如果距离属于滑动了，就屏蔽一切点击事件。
                    isUserSwiped = false;
                    // 2016 10 22 add , 仿QQ，侧滑菜单展开时，点击内容区域，关闭侧滑菜单。
                    isUnMoved = true;
                    // add by 2016 09 11 ，每次DOWN时，默认是不拦截的
                    iosInterceptFlag = false;
                    if (isTouching) {
                        // 如果有别的指头摸过了，那么就return false。这样后续的move..等事件也不会再来找这个View了。
                        return false;
                    } else {
                        // 第一个摸的指头，赶紧改变标志，宣誓主权。
                        isTouching = true;
                    }
                    mLastP.set(ev.getRawX(), ev.getRawY());
                    // 2016 11 03 add,判断手指起始落点，如果距离属于滑动了，就屏蔽一切点击事件。
                    mFirstP.set(ev.getRawX(), ev.getRawY());
                    // 如果down，view和cacheview不一样，则立马让它还原。且把它置为null
                    if (mViewCache != null) {
                        if (mViewCache != this) {
                            mViewCache.smoothClose();
                            // add by 2016 09 11 ，IOS模式开启的话，且当前有侧滑菜单的View，且不是自己的，就该拦截事件咯。
                            iosInterceptFlag = isIos;
                        }
                        // 只要有一个侧滑菜单处于打开状态， 就不给外层布局上下滑动了
                        getParent().requestDisallowInterceptTouchEvent(true);
                    }
                    // 求第一个触点的id， 此时可能有多个触点，但至少一个，计算滑动速率用
                    mPointerId = ev.getPointerId(0);
                    break;
                case MotionEvent.ACTION_MOVE:
                    // add by 2016 09 11 ，IOS模式开启的话，且当前有侧滑菜单的View，且不是自己的，就该拦截事件咯。滑动也不该出现
                    if (iosInterceptFlag) {
                        break;
                    }
                    float gap = mLastP.x - ev.getRawX();
                    // 为了在水平滑动中禁止父类ListView等再竖直滑动
                    if (Math.abs(gap) > 10 || Math.abs(getScrollX()) > 10) {
                        // 2016 09 29 修改此处，使屏蔽父布局滑动更加灵敏，
                        getParent().requestDisallowInterceptTouchEvent(true);
                    }
                    // 2016 10 22 add , 仿QQ，侧滑菜单展开时，点击内容区域，关闭侧滑菜单。begin
                    if (Math.abs(gap) > mScaleTouchSlop) {
                        isUnMoved = false;
                    }
                    // 2016 10 22 add , 仿QQ，侧滑菜单展开时，点击内容区域，关闭侧滑菜单。end
                    // 如果scroller还没有滑动结束 停止滑动动画
                    // 滑动使用scrollBy
                    scrollBy((int) (gap), 0);
                    // 越界修正
                    if (isLeftSwipe) {
                        // 左滑
                        if (getScrollX() < 0) {
                            scrollTo(0, 0);
                        }
                        if (getScrollX() > mRightMenuWidths) {
                            scrollTo(mRightMenuWidths, 0);
                        }
                    } else {
                        // 右滑
                        if (getScrollX() < -mRightMenuWidths) {
                            scrollTo(-mRightMenuWidths, 0);
                        }
                        if (getScrollX() > 0) {
                            scrollTo(0, 0);
                        }
                    }
                    mLastP.set(ev.getRawX(), ev.getRawY());
                    break;
                case MotionEvent.ACTION_UP:
                case MotionEvent.ACTION_CANCEL:
                    // 2016 11 03 add,判断手指起始落点，如果距离属于滑动了，就屏蔽一切点击事件。
                    if (Math.abs(ev.getRawX() - mFirstP.x) > mScaleTouchSlop) {
                        isUserSwiped = true;
                    }
                    // add by 2016 09 11 ，IOS模式开启的话，且当前有侧滑菜单的View，且不是自己的，就该拦截事件咯。滑动也不该出现
                    if (!iosInterceptFlag) {
                        // 且滑动了 才判断是否要收起、展开menu
                        // 求伪瞬时速度
                        verTracker.computeCurrentVelocity(1000, mMaxVelocity);
                        final float velocityX = verTracker.getXVelocity(mPointerId);
                        if (Math.abs(velocityX) > 1000) {
                            // 滑动速度超过阈值
                            if (velocityX < -1000) {
                                if (isLeftSwipe) {
                                    // 左滑
                                    // 平滑展开Menu
                                    smoothExpand();
                                } else {
                                    // 平滑关闭Menu
                                    smoothClose();
                                }
                            } else {
                                if (isLeftSwipe) {
                                    // 左滑
                                    // 平滑关闭Menu
                                    smoothClose();
                                } else {
                                    // 平滑展开Menu
                                    smoothExpand();
                                }
                            }
                        } else {
                            if (Math.abs(getScrollX()) > mLimit) {
                                // 否则就判断滑动距离
                                // 平滑展开Menu
                                smoothExpand();
                            } else {
                                // 平滑关闭Menu
                                smoothClose();
                            }
                        }
                    }
                    // 释放
                    releaseVelocityTracker();
                    // LogUtils.i(TAG, "onTouch A ACTION_UP ACTION_CANCEL:velocityY:" + velocityX);
                    // 没有手指在摸我了
                    isTouching = false;
                    break;
                default:
                    break;
            }
        }
        return super.dispatchTouchEvent(ev);
    }

    @Override
    public boolean onInterceptTouchEvent(MotionEvent ev) {
        // add by zhangxutong 2016 12 07 begin:
        // 禁止侧滑时，点击事件不受干扰。
        if (isSwipeEnable) {
            switch(ev.getAction()) {
                // add by zhangxutong 2016 11 04 begin :
                // fix 长按事件和侧滑的冲突。
                case MotionEvent.ACTION_MOVE:
                    // 屏蔽滑动时的事件
                    if (Math.abs(ev.getRawX() - mFirstP.x) > mScaleTouchSlop) {
                        return true;
                    }
                    break;
                // add by zhangxutong 2016 11 04 end
                case MotionEvent.ACTION_UP:
                    // 为了在侧滑时，屏蔽子View的点击事件
                    if (isLeftSwipe) {
                        if (getScrollX() > mScaleTouchSlop) {
                            // add by 2016 09 10 解决一个智障问题~ 居然不给点击侧滑菜单 我跪着谢罪
                            // 这里判断落点在内容区域屏蔽点击，内容区域外，允许传递事件继续向下的的。。。
                            if (ev.getX() < getWidth() - getScrollX()) {
                                // 2016 10 22 add , 仿QQ，侧滑菜单展开时，点击内容区域，关闭侧滑菜单。
                                if (isUnMoved) {
                                    smoothClose();
                                }
                                return true;
                            }
                        }
                    } else {
                        if (-getScrollX() > mScaleTouchSlop) {
                            if (ev.getX() > -getScrollX()) {
                                // 点击范围在菜单外 屏蔽
                                // 2016 10 22 add , 仿QQ，侧滑菜单展开时，点击内容区域，关闭侧滑菜单。
                                if (isUnMoved) {
                                    smoothClose();
                                }
                                return true;
                            }
                        }
                    }
                    // add by zhangxutong 2016 11 03 begin:
                    // 判断手指起始落点，如果距离属于滑动了，就屏蔽一切点击事件。
                    if (isUserSwiped) {
                        return true;
                    }
                    // add by zhangxutong 2016 11 03 end
                    break;
            }
            // 模仿IOS 点击其他区域关闭：
            if (iosInterceptFlag) {
                // IOS模式开启，且当前有菜单的View，且不是自己的 拦截点击事件给子View
                return true;
            }
        }
        return super.onInterceptTouchEvent(ev);
    }

    private ValueAnimator mExpandAnim, mCloseAnim;

    private boolean isExpand;

    public void smoothExpand() {
        // 展开就加入ViewCache：
        mViewCache = SwipeMenuLayout.this;
        // 2016 11 13 add 侧滑菜单展开，屏蔽content长按
        if (null != mContentView) {
            mContentView.setLongClickable(false);
        }
        cancelAnim();
        mExpandAnim = ValueAnimator.ofInt(getScrollX(), isLeftSwipe ? mRightMenuWidths : -mRightMenuWidths);
        mExpandAnim.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {

            @Override
            public void onAnimationUpdate(ValueAnimator animation) {
                scrollTo((Integer) animation.getAnimatedValue(), 0);
            }
        });
        mExpandAnim.setInterpolator(new OvershootInterpolator());
        mExpandAnim.addListener(new AnimatorListenerAdapter() {

            @Override
            public void onAnimationEnd(Animator animation) {
                isExpand = true;
            }
        });
        mExpandAnim.setDuration(300).start();
    }

    private void cancelAnim() {
        if (mCloseAnim != null && mCloseAnim.isRunning()) {
            mCloseAnim.cancel();
        }
        if (mExpandAnim != null && mExpandAnim.isRunning()) {
            mExpandAnim.cancel();
        }
    }

    public void smoothClose() {
        mViewCache = null;
        // 2016 11 13 add 侧滑菜单展开，屏蔽content长按
        if (null != mContentView) {
            mContentView.setLongClickable(true);
        }
        cancelAnim();
        mCloseAnim = ValueAnimator.ofInt(getScrollX(), 0);
        mCloseAnim.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {

            @Override
            public void onAnimationUpdate(ValueAnimator animation) {
                scrollTo((Integer) animation.getAnimatedValue(), 0);
            }
        });
        mCloseAnim.setInterpolator(new AccelerateInterpolator());
        mCloseAnim.addListener(new AnimatorListenerAdapter() {

            @Override
            public void onAnimationEnd(Animator animation) {
                isExpand = false;
            }
        });
        mCloseAnim.setDuration(300).start();
    }

    /**
     * @param event 向VelocityTracker添加MotionEvent
     * @see VelocityTracker#obtain()
     * @see VelocityTracker#addMovement(MotionEvent)
     */
    private void acquireVelocityTracker(final MotionEvent event) {
        if (null == mVelocityTracker) {
            mVelocityTracker = VelocityTracker.obtain();
        }
        mVelocityTracker.addMovement(event);
    }

    /**
     * * 释放VelocityTracker
     *
     * @see VelocityTracker#clear()
     * @see VelocityTracker#recycle()
     */

    // 每次ViewDetach的时候，判断一下 ViewCache是不是自己，如果是自己，关闭侧滑菜单，且ViewCache设置为null，
    // 理由：1 防止内存泄漏(ViewCache是一个静态变量)
    // 2 侧滑删除后自己后，这个View被Recycler回收，复用，下一个进入屏幕的View的状态应该是普通状态，而不是展开状态。
    @Override
    protected void onDetachedFromWindow() {
        if (this == mViewCache) {
            mViewCache.smoothClose();
            mViewCache = null;
        }
        super.onDetachedFromWindow();
    }

    // 展开时，禁止长按
    @Override
    public boolean performLongClick() {
        if (Math.abs(getScrollX()) > mScaleTouchSlop) {
            return false;
        }
        return super.performLongClick();
    }

    // 平滑滚动 弃用 改属性动画实现
    /*    @Override
    public void computeScroll() {
        //判断Scroller是否执行完毕：
        if (mScroller.computeScrollOffset()) {
            scrollTo(mScroller.getCurrX(), mScroller.getCurrY());
            //通知View重绘-invalidate()->onDraw()->computeScroll()
            invalidate();
        }
    }*/
    /**
     * 快速关闭。
     * 用于 点击侧滑菜单上的选项,同时想让它快速关闭(删除 置顶)。
     * 这个方法在ListView里是必须调用的，
     * 在RecyclerView里，视情况而定，如果是mAdapter.notifyItemRemoved(pos)方法不用调用。
     */
    public void quickClose() {
        if (this == mViewCache) {
            // 先取消展开动画
            cancelAnim();
            // 关闭
            mViewCache.scrollTo(0, 0);
            mViewCache = null;
        }
    }
}


for (int i = 0; i < outputs.size(); i++) {
            guiItemStacks.set(i + 1, outputs.get(i));
        }

package cofh.thermalexpansion.plugins.jei.machine.centrifuge;

import cofh.core.util.helpers.StringHelper;
import cofh.thermalexpansion.block.machine.BlockMachine;
import cofh.thermalexpansion.init.TEProps;
import cofh.thermalexpansion.item.ItemAugment;
import cofh.thermalexpansion.plugins.jei.RecipeUidsTE;
import cofh.thermalexpansion.util.managers.machine.CentrifugeManager;
import cofh.thermalexpansion.util.managers.machine.CentrifugeManager.CentrifugeRecipe;
import mezz.jei.api.IGuiHelper;
import mezz.jei.api.IJeiHelpers;
import mezz.jei.api.IModRegistry;
import mezz.jei.api.gui.IGuiFluidStackGroup;
import mezz.jei.api.gui.IGuiItemStackGroup;
import mezz.jei.api.gui.IRecipeLayout;
import mezz.jei.api.ingredients.IIngredients;
import net.minecraft.item.ItemStack;
import net.minecraftforge.fluids.FluidStack;
import javax.annotation.Nonnull;
import java.util.ArrayList;
import java.util.List;

public class CentrifugeRecipeCategoryMobs extends CentrifugeRecipeCategory {

    public static void initialize(IModRegistry registry) {
        IJeiHelpers jeiHelpers = registry.getJeiHelpers();
        IGuiHelper guiHelper = jeiHelpers.getGuiHelper();
        registry.addRecipes(getRecipes(guiHelper), RecipeUidsTE.CENTRIFUGE_MOBS);
        registry.addRecipeCatalyst(ItemAugment.machineCentrifugeMobs, RecipeUidsTE.CENTRIFUGE_MOBS);
        registry.addRecipeCatalyst(BlockMachine.machineCentrifuge, RecipeUidsTE.CENTRIFUGE_MOBS);
    }

    public static List<CentrifugeRecipeWrapper> getRecipes(IGuiHelper guiHelper) {
        List<CentrifugeRecipeWrapper> recipes = new ArrayList<>();
        for (CentrifugeRecipe recipe : CentrifugeManager.getRecipeListMobs()) {
            recipes.add(new CentrifugeRecipeWrapper(guiHelper, recipe, RecipeUidsTE.CENTRIFUGE_MOBS));
        }
        return recipes;
    }

    public CentrifugeRecipeCategoryMobs(IGuiHelper guiHelper) {
        super(guiHelper);
        localizedName = StringHelper.localize("item.thermalexpansion.augment.machineCentrifugeMobs.name");
    }

    @Nonnull
    @Override
    public String getUid() {
        return RecipeUidsTE.CENTRIFUGE_MOBS;
    }

    @Override
    public void setRecipe(IRecipeLayout recipeLayout, CentrifugeRecipeWrapper recipeWrapper, IIngredients ingredients) {
        List<List<ItemStack>> inputs = ingredients.getInputs(ItemStack.class);
        List<List<ItemStack>> outputs = ingredients.getOutputs(ItemStack.class);
        List<List<FluidStack>> outputFluids = ingredients.getOutputs(FluidStack.class);
        IGuiItemStackGroup guiItemStacks = recipeLayout.getItemStacks();
        IGuiFluidStackGroup guiFluidStacks = recipeLayout.getFluidStacks();
        guiItemStacks.init(0, true, 33, 14);
        guiItemStacks.init(1, false, 96, 14);
        guiItemStacks.init(2, false, 114, 14);
        guiItemStacks.init(3, false, 96, 32);
        guiItemStacks.init(4, false, 114, 32);
        guiFluidStacks.init(0, false, 141, 1, 16, 60, TEProps.MAX_FLUID_SMALL, false, tankOverlay);
        guiItemStacks.set(0, inputs.get(0));

        guiFluidStacks.set(0, outputFluids.get(0));
        guiItemStacks.addTooltipCallback((slotIndex, input, ingredient, tooltip) -> {
            if (!recipeWrapper.chance.isEmpty() && slotIndex >= 1 && slotIndex <= 4) {
                if (recipeWrapper.chance.get(slotIndex - 1) < 100) {
                    if (recipeWrapper.outputs.get(slotIndex - 1).getCount() > 1) {
                        tooltip.add(StringHelper.localize("gui.thermalexpansion.jei.centrifuge.mobNotice"));
                    }
                    tooltip.add(StringHelper.localize("gui.thermalexpansion.jei.centrifuge.mobChance") + ": " + recipeWrapper.chance.get(slotIndex - 1) + "%");
                }
            }
        });
    }
}


private void log_d(String msg) {
        if (Constant.DEBUG)
            Log.d(Constant.TAG, TAG_SUB + " " + msg);
    }

package jp.ohwada.android.listviewsample2;

import android.app.Activity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.Toast;
import java.util.ArrayList;
import java.util.List;

public class MainActivity extends Activity {

    // debug
    private final static String TAG_SUB = "MainActivity";

    // header footer
    private final static ViewGroup INFLATE_ROOT = null;

    private final static String HEADER_DATA = null;

    private final static boolean HEADER_ISSELECTABLE = true;

    private final static String FOOTER_DATA = null;

    private final static boolean FOOTER_ISSELECTABLE = true;

    private ListView mListView;

    private ListAdapter mAdapter;

    private List<VersionItem> mList;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        log_d("onCreate");
        setContentView(R.layout.activity_main);
        mListView = (ListView) findViewById(R.id.ListView_1);
        mList = AndroidVersion.getListVersionItem();
        mAdapter = new ListAdapter(this, ListAdapter.LAYOUT_RESOURCE_ID, mList);
        mListView.setAdapter(mAdapter);
        mListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {

            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                procItemClick(position, id);
            }
        });
        // setOnItemClickListener
        // inflate(Context context, int resource, ViewGroup root)
        View header = View.inflate(this, R.layout.list_header, INFLATE_ROOT);
        mListView.addHeaderView(header, HEADER_DATA, HEADER_ISSELECTABLE);
        View footer = View.inflate(this, R.layout.list_footer, INFLATE_ROOT);
        mListView.addFooterView(footer, FOOTER_DATA, FOOTER_ISSELECTABLE);
    }

    // onCreate
    /**
     *  procItemClick
     * @param int position
     * @param long id
     */
    private void procItemClick(int position, long id) {
        String msg = "procItemClick: " + position + ", " + id;
        log_d(msg);
        // header footer
        if (id == -1) {
            // header
            if (position == 0) {
                toast_short("header");
                return;
                // footer
            } else {
                toast_short("footer");
                return;
            }
        }
        // check position
        int n = position - 1;
        if ((n < 0) || (n >= mList.size()))
            return;
        VersionItem item = mList.get(n);
        toast_short(item.codename);
    }

    // procItemClick
    private void toast_short(String msg) {
        ToastMaster.makeText(this, msg, Toast.LENGTH_SHORT).show();
    }

    // toast_shor
    /**
     * write into logcat
     */


public boolean addValue(String text, int score) {
        strings.add(text);
        scores.add(score);
        return removeOne(text);
    }

package com.knowledgebooks.nlp.util;

import java.util.ArrayList;
import java.util.List;

public class ScoredList {

    private List<String> strings = new ArrayList<String>();

    private List<Integer> scores = new ArrayList<Integer>();

    private int max_to_keep = 9999999;

    public ScoredList(int max_to_keep) {
        this.max_to_keep = max_to_keep;
    }

    /**
     * Create an empty scored list
     */
    public ScoredList() {
    }

    /**
     * Add a value to a scored list
     *
     * @param text
     * @param score
     * @return true is a value was added. If the score is lower than
     *         all currently stored values and the maximum number of values to store has
     *         been reached, then the value will not be stored and the return value will be false.
     */

    /**
     * Add a value to a scored list. The "score" is not specified so
     * the "score" for a given value string is the number of times that it is added
     * to the scored list.
     *
     * @param text
     * @return true is a value was added. If the score is lower than
     *         all currently stored values and the maximum number of values to store has
     *         been reached, then the value will not be stored and the return value will be false.
     */
    public boolean addValue(String text) {
        int score = 1;
        if (strings.contains(text)) {
            int index = strings.indexOf(text);
            try {
                score = ((Integer) scores.get(index)).intValue() + 1;
            } catch (Exception ignore) {
                ignore.printStackTrace();
            }
            scores.set(index, new Integer(score));
        } else {
            strings.add(text);
            scores.add(new Integer(score));
        }
        return removeOne(text);
    }

    /**
     * Determine if a scored list contains a value string
     *
     * @param s
     * @return true if the value is stored in the scored list
     */
    public boolean contains(String s) {
        return strings.contains(s);
    }

    private final boolean removeOne(String text) {
        // WARNING: REALLY INEFFICIENT !!  TBD fix this
        int size = scores.size();
        if (size > max_to_keep) {
            int min_val = 999999999;
            int min_index = 0;
            for (int i = 0; i < size; i++) {
                if (((Integer) scores.get(i)).intValue() < min_val) {
                    min_val = ((Integer) scores.get(i)).intValue();
                    min_index = i;
                }
            }
            boolean ret = text.equals(strings.get(min_index)) == false;
            strings.remove(min_index);
            scores.remove(min_index);
            return ret;
        } else {
            // yes, the 'text/ item was added
            return true;
        }
    }

    /**
     * Sort a scored list in highest value first order
     */
    public void sort() {
        for (int i = 0, size = strings.size(); i < (size - 1); i++) {
            for (int j = i + 1; j < size; j++) {
                // must be inside inner loop because of possible shuffle
                int score_i = ((Integer) scores.get(i)).intValue();
                int score_j = ((Integer) scores.get(j)).intValue();
                if (score_j > score_i) {
                    scores.set(i, new Integer(score_j));
                    scores.set(j, new Integer(score_i));
                    String o = strings.get(i);
                    strings.set(i, strings.get(j));
                    strings.set(j, o);
                }
            }
        }
    }

    /**
     * Determining the number of values in a scored list
     *
     * @return the size of the scored list
     */
    public int size() {
        return strings.size();
    }

    /**
     * Get a specific value
     *
     * @param index
     * @return the value at the specified index
     */
    public String getValue(int index) {
        return (String) strings.get(index);
    }

    /**
     * Get a specific score
     *
     * @param index
     * @return the score at the specified index
     */
    public int getScore(int index) {
        return ((Integer) scores.get(index)).intValue();
    }

    /**
     * Get all values and scores as a human readable string
     *
     * @return string
     */
    public String getValuesAsString() {
        return getValuesAsString(99999);
    }

    /**
     * Get a specified number of values as a human readable string
     *
     * @param max_return_values
     * @return string
     */
    public String getValuesAsString(int max_return_values) {
        StringBuffer sb = new StringBuffer(200);
        sort();
        int limit = strings.size();
        if (limit > max_return_values)
            limit = max_return_values;
        for (int i = 0; i < limit; i++) {
            sb.append(strings.get(i) + ":" + scores.get(i));
            if (i != (limit - 1))
                sb.append(", ");
        }
        return sb.toString();
    }

    public List<String> getStrings() {
        return strings;
    }

    public List<Integer> getScores() {
        return scores;
    }
}


for (int i = 0; i < limit; i++) {
            sb.append(strings.get(i) + ":" + scores.get(i));
            if (i != (limit - 1))
                sb.append(", ");
        }

package com.knowledgebooks.nlp.util;

import java.util.ArrayList;
import java.util.List;

public class ScoredList {

    private List<String> strings = new ArrayList<String>();

    private List<Integer> scores = new ArrayList<Integer>();

    private int max_to_keep = 9999999;

    public ScoredList(int max_to_keep) {
        this.max_to_keep = max_to_keep;
    }

    /**
     * Create an empty scored list
     */
    public ScoredList() {
    }

    /**
     * Add a value to a scored list
     *
     * @param text
     * @param score
     * @return true is a value was added. If the score is lower than
     *         all currently stored values and the maximum number of values to store has
     *         been reached, then the value will not be stored and the return value will be false.
     */
    public boolean addValue(String text, int score) {
        strings.add(text);
        scores.add(score);
        return removeOne(text);
    }

    /**
     * Add a value to a scored list. The "score" is not specified so
     * the "score" for a given value string is the number of times that it is added
     * to the scored list.
     *
     * @param text
     * @return true is a value was added. If the score is lower than
     *         all currently stored values and the maximum number of values to store has
     *         been reached, then the value will not be stored and the return value will be false.
     */
    public boolean addValue(String text) {
        int score = 1;
        if (strings.contains(text)) {
            int index = strings.indexOf(text);
            try {
                score = ((Integer) scores.get(index)).intValue() + 1;
            } catch (Exception ignore) {
                ignore.printStackTrace();
            }
            scores.set(index, new Integer(score));
        } else {
            strings.add(text);
            scores.add(new Integer(score));
        }
        return removeOne(text);
    }

    /**
     * Determine if a scored list contains a value string
     *
     * @param s
     * @return true if the value is stored in the scored list
     */
    public boolean contains(String s) {
        return strings.contains(s);
    }

    private final boolean removeOne(String text) {
        // WARNING: REALLY INEFFICIENT !!  TBD fix this
        int size = scores.size();
        if (size > max_to_keep) {
            int min_val = 999999999;
            int min_index = 0;
            for (int i = 0; i < size; i++) {
                if (((Integer) scores.get(i)).intValue() < min_val) {
                    min_val = ((Integer) scores.get(i)).intValue();
                    min_index = i;
                }
            }
            boolean ret = text.equals(strings.get(min_index)) == false;
            strings.remove(min_index);
            scores.remove(min_index);
            return ret;
        } else {
            // yes, the 'text/ item was added
            return true;
        }
    }

    /**
     * Sort a scored list in highest value first order
     */
    public void sort() {
        for (int i = 0, size = strings.size(); i < (size - 1); i++) {
            for (int j = i + 1; j < size; j++) {
                // must be inside inner loop because of possible shuffle
                int score_i = ((Integer) scores.get(i)).intValue();
                int score_j = ((Integer) scores.get(j)).intValue();
                if (score_j > score_i) {
                    scores.set(i, new Integer(score_j));
                    scores.set(j, new Integer(score_i));
                    String o = strings.get(i);
                    strings.set(i, strings.get(j));
                    strings.set(j, o);
                }
            }
        }
    }

    /**
     * Determining the number of values in a scored list
     *
     * @return the size of the scored list
     */
    public int size() {
        return strings.size();
    }

    /**
     * Get a specific value
     *
     * @param index
     * @return the value at the specified index
     */
    public String getValue(int index) {
        return (String) strings.get(index);
    }

    /**
     * Get a specific score
     *
     * @param index
     * @return the score at the specified index
     */
    public int getScore(int index) {
        return ((Integer) scores.get(index)).intValue();
    }

    /**
     * Get all values and scores as a human readable string
     *
     * @return string
     */
    public String getValuesAsString() {
        return getValuesAsString(99999);
    }

    /**
     * Get a specified number of values as a human readable string
     *
     * @param max_return_values
     * @return string
     */
    public String getValuesAsString(int max_return_values) {
        StringBuffer sb = new StringBuffer(200);
        sort();
        int limit = strings.size();
        if (limit > max_return_values)
            limit = max_return_values;

        return sb.toString();
    }

    public List<String> getStrings() {
        return strings;
    }

    public List<Integer> getScores() {
        return scores;
    }
}


try {
                score = ((Integer) scores.get(index)).intValue() + 1;
            } catch (Exception ignore) {
                ignore.printStackTrace();
            }

package com.knowledgebooks.nlp.util;

import java.util.ArrayList;
import java.util.List;

public class ScoredList {

    private List<String> strings = new ArrayList<String>();

    private List<Integer> scores = new ArrayList<Integer>();

    private int max_to_keep = 9999999;

    public ScoredList(int max_to_keep) {
        this.max_to_keep = max_to_keep;
    }

    /**
     * Create an empty scored list
     */
    public ScoredList() {
    }

    /**
     * Add a value to a scored list
     *
     * @param text
     * @param score
     * @return true is a value was added. If the score is lower than
     *         all currently stored values and the maximum number of values to store has
     *         been reached, then the value will not be stored and the return value will be false.
     */
    public boolean addValue(String text, int score) {
        strings.add(text);
        scores.add(score);
        return removeOne(text);
    }

    /**
     * Add a value to a scored list. The "score" is not specified so
     * the "score" for a given value string is the number of times that it is added
     * to the scored list.
     *
     * @param text
     * @return true is a value was added. If the score is lower than
     *         all currently stored values and the maximum number of values to store has
     *         been reached, then the value will not be stored and the return value will be false.
     */
    public boolean addValue(String text) {
        int score = 1;
        if (strings.contains(text)) {
            int index = strings.indexOf(text);

            scores.set(index, new Integer(score));
        } else {
            strings.add(text);
            scores.add(new Integer(score));
        }
        return removeOne(text);
    }

    /**
     * Determine if a scored list contains a value string
     *
     * @param s
     * @return true if the value is stored in the scored list
     */
    public boolean contains(String s) {
        return strings.contains(s);
    }

    private final boolean removeOne(String text) {
        // WARNING: REALLY INEFFICIENT !!  TBD fix this
        int size = scores.size();
        if (size > max_to_keep) {
            int min_val = 999999999;
            int min_index = 0;
            for (int i = 0; i < size; i++) {
                if (((Integer) scores.get(i)).intValue() < min_val) {
                    min_val = ((Integer) scores.get(i)).intValue();
                    min_index = i;
                }
            }
            boolean ret = text.equals(strings.get(min_index)) == false;
            strings.remove(min_index);
            scores.remove(min_index);
            return ret;
        } else {
            // yes, the 'text/ item was added
            return true;
        }
    }

    /**
     * Sort a scored list in highest value first order
     */
    public void sort() {
        for (int i = 0, size = strings.size(); i < (size - 1); i++) {
            for (int j = i + 1; j < size; j++) {
                // must be inside inner loop because of possible shuffle
                int score_i = ((Integer) scores.get(i)).intValue();
                int score_j = ((Integer) scores.get(j)).intValue();
                if (score_j > score_i) {
                    scores.set(i, new Integer(score_j));
                    scores.set(j, new Integer(score_i));
                    String o = strings.get(i);
                    strings.set(i, strings.get(j));
                    strings.set(j, o);
                }
            }
        }
    }

    /**
     * Determining the number of values in a scored list
     *
     * @return the size of the scored list
     */
    public int size() {
        return strings.size();
    }

    /**
     * Get a specific value
     *
     * @param index
     * @return the value at the specified index
     */
    public String getValue(int index) {
        return (String) strings.get(index);
    }

    /**
     * Get a specific score
     *
     * @param index
     * @return the score at the specified index
     */
    public int getScore(int index) {
        return ((Integer) scores.get(index)).intValue();
    }

    /**
     * Get all values and scores as a human readable string
     *
     * @return string
     */
    public String getValuesAsString() {
        return getValuesAsString(99999);
    }

    /**
     * Get a specified number of values as a human readable string
     *
     * @param max_return_values
     * @return string
     */
    public String getValuesAsString(int max_return_values) {
        StringBuffer sb = new StringBuffer(200);
        sort();
        int limit = strings.size();
        if (limit > max_return_values)
            limit = max_return_values;
        for (int i = 0; i < limit; i++) {
            sb.append(strings.get(i) + ":" + scores.get(i));
            if (i != (limit - 1))
                sb.append(", ");
        }
        return sb.toString();
    }

    public List<String> getStrings() {
        return strings;
    }

    public List<Integer> getScores() {
        return scores;
    }
}


@Override
    public void setAudioSourceListener(final AudioSourceListener listener) {
        mListener = Preconditions.checkNotNull(listener, "listener cannot be null");
    }

package com.amazonaws.mobileconnectors.lex.interactionkit.internal.audio;

import com.google.common.base.Preconditions;
import com.google.common.net.MediaType;
import java.io.InputStream;

/**
 * An AudioSource that writes a stream of audio to the network connection in
 * chunks. Currently only audio/x-l16, audio/x-l16preamble, and
 * audio/x-cbr-opus-preamble are supported.
 */
public class ChunkedAudioStream extends AudioStream implements ChunkedAudioSource {

    private AudioSourceListener mListener;

    /**
     * Buffer size for reading bytes from the stream.
     */
    private static final int CHUNK_SIZE = 320;

    /**
     * Create a new AudioStream with the given ContentType and audio stream.
     *
     * @param contentType the content type of the audio.
     * @param stream the audio stream itself.
     */
    public ChunkedAudioStream(final MediaType contentType, final InputStream stream) {
        super(contentType, stream);
        mListener = new AudioSourceListener.NullListener();
    }

    /**
     * Set a listener for audio source events.
     *
     * @param listener the listener object.
     */

    /**
     * Get the AudioSourceListener for this AudioSource.
     *
     * @return the AudioSourceListener.
     */
    public AudioSourceListener getAudioSourceListener() {
        return mListener;
    }

    /**
     * Get the appropriate chunk size for this AudioSource.
     *
     * @return the chunk size.
     */
    @Override
    public int getChunkSize() {
        return CHUNK_SIZE;
    }
}


package org.w3c.dom.html;

/**
 *  The HTML document body. This element is always present in the DOM API,
 * even if the tags are not present in the source document. See the  BODY
 * element definition in HTML 4.0.
 *
See also the Document Object Model (DOM) Level 2 Specification.
 */
public interface HTMLBodyElement extends HTMLElement {

    /**
     *  Color of active links (after mouse-button down, but before
     * mouse-button up). See the  alink attribute definition in HTML 4.0.
     * This attribute is deprecated in HTML 4.0.
     */
    public String getALink();

    public void setALink(String aLink);

    /**
     *  URI of the background texture tile image. See the  background
     * attribute definition in HTML 4.0. This attribute is deprecated in HTML
     * 4.0.
     */
    public String getBackground();

    public void setBackground(String background);

    /**
     *  Document background color. See the  bgcolor attribute definition in
     * HTML 4.0. This attribute is deprecated in HTML 4.0.
     */
    public String getBgColor();

    public void setBgColor(String bgColor);

    /**
     *  Color of links that are not active and unvisited. See the  link
     * attribute definition in HTML 4.0. This attribute is deprecated in HTML
     * 4.0.
     */
    public String getLink();

    public void setLink(String link);

    /**
     *  Document text color. See the  text attribute definition in HTML 4.0.
     * This attribute is deprecated in HTML 4.0.
     */

    public void setText(String text);

    /**
     *  Color of links that have been visited by the user. See the  vlink
     * attribute definition in HTML 4.0. This attribute is deprecated in HTML
     * 4.0.
     */
    public String getVLink();

    public void setVLink(String vLink);
}


public static Element parserActivityInfo(String processDefContent, String activityDefId) {
        SAXReader reader = new SAXReader();
        Document document = null;
        Element element = null;
        try {
            document = reader.read(new StringReader(processDefContent));
            element = parserActivityInfo(document, activityDefId);
        } catch (Exception e) {
            throw new StarFlowParserException("流程定义信息不正确", e);
        }
        return element;
    }

package com.googlecode.starflow.engine.xml;

import java.io.StringReader;
import java.util.List;
import org.dom4j.Document;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;
import com.googlecode.starflow.engine.model.ProcessDefine;

/**
 * @author example@nnthink.com
 * @version 1.0
 */
public class Dom4jProcDefParser {

    /**
     * 获取流程信息
     *
     * @param processDefine
     * @return
     */
    public static ProcessDefine parserProcessInfo(ProcessDefine processDefine) {
        SAXReader reader = new SAXReader();
        Document document = null;
        try {
            document = reader.read(new StringReader(processDefine.getProcessDefContent()));
            Element rootElement = document.getRootElement();
            String _name = rootElement.attributeValue(StarFlowNames.FLOW_ATTR_NAME);
            String _chname = rootElement.attributeValue(StarFlowNames.FLOW_ATTR_CHNAME);
            String _version = rootElement.attributeValue(StarFlowNames.FLOW_ATTR_VERSION);
            String _xpath = "/ProcessDefine/ProcessProperty/".concat(StarFlowNames.FLOW_CHILD_DESC);
            String _description = rootElement.selectSingleNode(_xpath).getText();
            _xpath = "/ProcessDefine/ProcessProperty/".concat(StarFlowNames.FLOW_CHILD_LIMITTIME);
            String _limitTime = rootElement.selectSingleNode(_xpath).getText();
            processDefine.setProcessDefName(_name);
            if (_chname != null)
                processDefine.setProcessCHName(_chname);
            else
                processDefine.setProcessCHName(_name);
            processDefine.setVersionSign(_version);
            processDefine.setDescription(_description);
            processDefine.setLimitTime(Long.parseLong(_limitTime));
        } catch (Exception e) {
            throw new StarFlowParserException("流程定义信息不正确", e);
        }
        return processDefine;
    }

    /**
     * 根据环节定义ID。获取当前环节节点
     *
     * @param document
     * @param activityDefId
     * @return
     */
    public static Element parserActivityInfo(Document document, String activityDefId) {
        String _xpath = "/ProcessDefine/Activitys/Activity[@id='" + activityDefId + "']";
        Element element = (Element) document.selectSingleNode(_xpath);
        return element;
    }

    /**
     * 根据环节定义ID。获取当前环节节点
     *
     * @param document
     * @param activityDefId
     * @return
     */

    /**
     * 获取当前环节的所有分支环节
     *
     * @param document
     * @param activityDefId
     * @return
     */
    @SuppressWarnings("unchecked")
    public static List<Element> parserTransitionInfoFromTo(Document document, String activityDefId) {
        List<Element> list = null;
        String _xpath = "/ProcessDefine/Transitions/Transition[@from='" + activityDefId + "']";
        list = document.selectNodes(_xpath);
        return list;
    }

    /**
     * 获取当前环节的所有前驱环节
     *
     * @param document
     * @param activityDefId
     * @return
     */
    @SuppressWarnings("unchecked")
    public static List<Element> parserTransitionInfoToFrom(Document document, String activityDefId) {
        List<Element> list = null;
        String _xpath = "/ProcessDefine/Transitions/Transition[@to='" + activityDefId + "']";
        list = document.selectNodes(_xpath);
        return list;
    }

    /**
     * 获取当前环节的所有分支环节
     *
     * @param document
     * @param activityDefId
     * @return
     */
    public static List<Element> parserTransitionInfo(String processDefContent, String activityDefId) {
        SAXReader reader = new SAXReader();
        Document document = null;
        List<Element> list = null;
        try {
            document = reader.read(new StringReader(processDefContent));
            list = parserTransitionInfoFromTo(document, activityDefId);
        } catch (Exception e) {
            throw new StarFlowParserException("流程定义信息不正确", e);
        }
        return list;
    }
}


try {
            document = reader.read(new StringReader(processDefContent));
            list = parserTransitionInfoFromTo(document, activityDefId);
        } catch (Exception e) {
            throw new StarFlowParserException("流程定义信息不正确", e);
        }

package com.googlecode.starflow.engine.xml;

import java.io.StringReader;
import java.util.List;
import org.dom4j.Document;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;
import com.googlecode.starflow.engine.model.ProcessDefine;

/**
 * @author example@nnthink.com
 * @version 1.0
 */
public class Dom4jProcDefParser {

    /**
     * 获取流程信息
     *
     * @param processDefine
     * @return
     */
    public static ProcessDefine parserProcessInfo(ProcessDefine processDefine) {
        SAXReader reader = new SAXReader();
        Document document = null;
        try {
            document = reader.read(new StringReader(processDefine.getProcessDefContent()));
            Element rootElement = document.getRootElement();
            String _name = rootElement.attributeValue(StarFlowNames.FLOW_ATTR_NAME);
            String _chname = rootElement.attributeValue(StarFlowNames.FLOW_ATTR_CHNAME);
            String _version = rootElement.attributeValue(StarFlowNames.FLOW_ATTR_VERSION);
            String _xpath = "/ProcessDefine/ProcessProperty/".concat(StarFlowNames.FLOW_CHILD_DESC);
            String _description = rootElement.selectSingleNode(_xpath).getText();
            _xpath = "/ProcessDefine/ProcessProperty/".concat(StarFlowNames.FLOW_CHILD_LIMITTIME);
            String _limitTime = rootElement.selectSingleNode(_xpath).getText();
            processDefine.setProcessDefName(_name);
            if (_chname != null)
                processDefine.setProcessCHName(_chname);
            else
                processDefine.setProcessCHName(_name);
            processDefine.setVersionSign(_version);
            processDefine.setDescription(_description);
            processDefine.setLimitTime(Long.parseLong(_limitTime));
        } catch (Exception e) {
            throw new StarFlowParserException("流程定义信息不正确", e);
        }
        return processDefine;
    }

    /**
     * 根据环节定义ID。获取当前环节节点
     *
     * @param document
     * @param activityDefId
     * @return
     */
    public static Element parserActivityInfo(Document document, String activityDefId) {
        String _xpath = "/ProcessDefine/Activitys/Activity[@id='" + activityDefId + "']";
        Element element = (Element) document.selectSingleNode(_xpath);
        return element;
    }

    /**
     * 根据环节定义ID。获取当前环节节点
     *
     * @param document
     * @param activityDefId
     * @return
     */
    public static Element parserActivityInfo(String processDefContent, String activityDefId) {
        SAXReader reader = new SAXReader();
        Document document = null;
        Element element = null;
        try {
            document = reader.read(new StringReader(processDefContent));
            element = parserActivityInfo(document, activityDefId);
        } catch (Exception e) {
            throw new StarFlowParserException("流程定义信息不正确", e);
        }
        return element;
    }

    /**
     * 获取当前环节的所有分支环节
     *
     * @param document
     * @param activityDefId
     * @return
     */
    @SuppressWarnings("unchecked")
    public static List<Element> parserTransitionInfoFromTo(Document document, String activityDefId) {
        List<Element> list = null;
        String _xpath = "/ProcessDefine/Transitions/Transition[@from='" + activityDefId + "']";
        list = document.selectNodes(_xpath);
        return list;
    }

    /**
     * 获取当前环节的所有前驱环节
     *
     * @param document
     * @param activityDefId
     * @return
     */
    @SuppressWarnings("unchecked")
    public static List<Element> parserTransitionInfoToFrom(Document document, String activityDefId) {
        List<Element> list = null;
        String _xpath = "/ProcessDefine/Transitions/Transition[@to='" + activityDefId + "']";
        list = document.selectNodes(_xpath);
        return list;
    }

    /**
     * 获取当前环节的所有分支环节
     *
     * @param document
     * @param activityDefId
     * @return
     */
    public static List<Element> parserTransitionInfo(String processDefContent, String activityDefId) {
        SAXReader reader = new SAXReader();
        Document document = null;
        List<Element> list = null;


public BigDecimal getSizeAdjustment(SizeAdjustment size) {
        if (sizeMultiplierMap.containsKey(size)) {
            return sizeMultiplierMap.get(size);
        }
        if (Logging.isDebugMode()) {
            Logging.debugPrint("Unable to find Load Multiplier for Size: " + size.getKeyName());
        }
        return BigDecimal.ONE;
    }

package pcgen.core.system;

import java.math.BigDecimal;
import java.net.URI;
import java.util.HashMap;
import java.util.Map;
import java.util.SortedMap;
import java.util.TreeMap;
import pcgen.cdom.base.Loadable;
import pcgen.cdom.reference.CDOMSingleRef;
import pcgen.core.SizeAdjustment;
import pcgen.util.Logging;

/**
 * {@code LoadInfo} describes the data associated with a loads and
 * encumbrance
 */
public class LoadInfo implements Loadable {

    private URI sourceURI;

    private String loadInfoName;

    private final Map<CDOMSingleRef<SizeAdjustment>, BigDecimal> rawSizeMultiplierMap = new HashMap<>();

    private final Map<SizeAdjustment, BigDecimal> sizeMultiplierMap = new HashMap<>();

    private final SortedMap<Integer, BigDecimal> strengthLoadMap = new TreeMap<>();

    private int minStrenghScoreWithLoad = 0;

    private int maxStrengthScoreWithLoad = 0;

    private BigDecimal loadScoreMultiplier = BigDecimal.ZERO;

    private int loadMultStep = 10;

    private final Map<String, LoadInfo.LoadMapEntry> loadMultiplierMap = new HashMap<>();

    private String modifyFormula;

    @Override
    public URI getSourceURI() {
        return sourceURI;
    }

    @Override
    public void setSourceURI(URI source) {
        sourceURI = source;
    }

    /**
     * @param multiplier the load score multiplier to set
     */
    public void setLoadScoreMultiplier(BigDecimal multiplier) {
        loadScoreMultiplier = multiplier;
    }

    public BigDecimal getLoadScoreMultiplier() {
        return loadScoreMultiplier;
    }

    /**
     * Add a load score/value pair
     *
     * @param score
     * @param load
     */
    public void addLoadScoreValue(int score, BigDecimal load) {
        strengthLoadMap.put(score, load);
        if (score > maxStrengthScoreWithLoad) {
            maxStrengthScoreWithLoad = score;
        }
        if (score < minStrenghScoreWithLoad) {
            minStrenghScoreWithLoad = score;
        }
    }

    /**
     * Get the value for a load score
     *
     * @param score
     * @return the value for a load score
     */
    public BigDecimal getLoadScoreValue(int score) {
        if (score < minStrenghScoreWithLoad) {
            return BigDecimal.ZERO;
        } else if (score > maxStrengthScoreWithLoad) {
            if (getLoadMultiplierCount() == 1) {
                // TODO Isn't this a bug??
                return getLoadScoreValue(minStrenghScoreWithLoad);
            }
            return loadScoreMultiplier.multiply(getLoadScoreValue(score - loadMultStep));
        } else {
            BigDecimal loadScore = strengthLoadMap.get(score);
            if (loadScore == null) {
                SortedMap<Integer, BigDecimal> headMap = strengthLoadMap.headMap(score);
                /*
				 * Assume headMap is populated, since minScore is tested, above -
				 * thpr Mar 14, 2007
				 */
                return strengthLoadMap.get(headMap.lastKey());
            }
            return loadScore;
        }
    }

    /**
     * Add a size adjustment
     *
     * @param size
     * @param multiplier
     */
    public void addSizeAdjustment(CDOMSingleRef<SizeAdjustment> size, BigDecimal multiplier) {
        rawSizeMultiplierMap.put(size, multiplier);
    }

    public void resolveSizeAdjustmentMap() {
        for (Map.Entry<CDOMSingleRef<SizeAdjustment>, BigDecimal> me : rawSizeMultiplierMap.entrySet()) {
            sizeMultiplierMap.put(me.getKey().get(), me.getValue());
        }
    }

    /**
     * Get the size adjustment
     *
     * @param size
     * @return the size adjustment
     */

    /**
     * Add load multiplier
     * @param encumbranceType
     * @param value
     * @param formula
     * @param checkPenalty
     */
    public void addLoadMultiplier(String encumbranceType, Float value, String formula, Integer checkPenalty) {
        LoadMapEntry newEntry = new LoadMapEntry(value, formula, checkPenalty);
        loadMultiplierMap.put(encumbranceType, newEntry);
    }

    /**
     * Get the load multiplier
     * @param encumbranceType
     * @return load multiplier
     */
    public Float getLoadMultiplier(String encumbranceType) {
        if (loadMultiplierMap.containsKey(encumbranceType)) {
            return loadMultiplierMap.get(encumbranceType).getMuliplier();
        }
        return null;
    }

    /**
     * Get the load move formula
     * @param encumbranceType
     * @return the load move formula
     */
    public String getLoadMoveFormula(String encumbranceType) {
        if (loadMultiplierMap.containsKey(encumbranceType)) {
            return loadMultiplierMap.get(encumbranceType).getFormula();
        }
        return "";
    }

    /**
     * Get the load check penalty
     * @param encumbranceType
     * @return the load check penalty
     */
    public int getLoadCheckPenalty(String encumbranceType) {
        if (loadMultiplierMap.containsKey(encumbranceType)) {
            return loadMultiplierMap.get(encumbranceType).getCheckPenalty();
        }
        return 0;
    }

    /**
     * Set the load modifier formula
     * @param argFormula
     */
    public void setLoadModifierFormula(final String argFormula) {
        modifyFormula = argFormula;
    }

    /**
     * Get the load modifier formula
     * @return the load modifier formula
     */
    public String getLoadModifierFormula() {
        return modifyFormula;
    }

    /**
     * Get the load multiplier count
     * @return the load multiplier count
     */
    public int getLoadMultiplierCount() {
        return loadMultiplierMap.size();
    }

    private static class LoadMapEntry {

        private final Float multiplier;

        private final String moveFormula;

        private final Integer checkPenalty;

        /**
         * Constructor
         * @param argMultiplier
         * @param argFormula
         * @param argPenalty
         */
        public LoadMapEntry(Float argMultiplier, String argFormula, Integer argPenalty) {
            multiplier = argMultiplier;
            moveFormula = argFormula;
            checkPenalty = argPenalty;
        }

        /**
         * Get multiplier
         * @return multiplier
         */
        public Float getMuliplier() {
            return multiplier;
        }

        public String getFormula() {
            return moveFormula;
        }

        /**
         * Get the check penalty
         * @return the check penalty
         */
        public int getCheckPenalty() {
            return checkPenalty;
        }
    }

    public void setLoadMultStep(int step) {
        loadMultStep = step;
    }

    @Override
    public String getDisplayName() {
        return loadInfoName;
    }

    @Override
    public String getKeyName() {
        return getDisplayName();
    }

    @Override
    public boolean isInternal() {
        return false;
    }

    @Override
    public boolean isType(String type) {
        return false;
    }

    @Override
    public void setName(String name) {
        loadInfoName = name;
    }
}


try {
            SQLiteDatabase.deleteDatabase(new File(fileName));
        } catch (Exception e) {
            /* print warning and ignore exception */
            Log.w(TAG, "delete failed: " + e.getMessage());
        }

// modified from original source see README at the top level of this project
package io.requery.android.database;

import android.database.sqlite.SQLiteException;
import android.util.Log;
import android.util.Pair;
import io.requery.android.database.sqlite.SQLiteDatabase;
import java.io.File;
import java.util.List;

/**
 * Default class used to define the actions to take when the database corruption is reported
 * by sqlite.
 *

 * An application can specify an implementation of {@link DatabaseErrorHandler} on the
 * following:
 *

 *
{@link SQLiteDatabase#openOrCreateDatabase(String,
 *      SQLiteDatabase.CursorFactory, DatabaseErrorHandler)}

 *
{@link SQLiteDatabase#openDatabase(String,
 *      SQLiteDatabase.CursorFactory, int, DatabaseErrorHandler)}

 *

 * The specified {@link DatabaseErrorHandler} is used to handle database corruption errors, if they
 * occur.
 *

 * If null is specified for DatabaeErrorHandler param in the above calls, then this class is used
 * as the default {@link DatabaseErrorHandler}.
 */
public final class DefaultDatabaseErrorHandler implements DatabaseErrorHandler {

    private static final String TAG = "DefaultDatabaseError";

    @Override
    public void onCorruption(SQLiteDatabase dbObj) {
        Log.e(TAG, "Corruption reported by sqlite on database: " + dbObj.getPath());
        // is the corruption detected even before database could be 'opened'?
        if (!dbObj.isOpen()) {
            // database files are not even openable. delete this database file.
            // NOTE if the database has attached databases, then any of them could be corrupt.
            // and not deleting all of them could cause corrupted database file to remain and
            // make the application crash on database open operation. To avoid this problem,
            // the application should provide its own {@link DatabaseErrorHandler} impl class
            // to delete ALL files of the database (including the attached databases).
            deleteDatabaseFile(dbObj.getPath());
            return;
        }
        List<Pair<String, String>> attachedDbs = null;
        try {
            // Close the database, which will cause subsequent operations to fail.
            // before that, get the attached database list first.
            try {
                attachedDbs = dbObj.getAttachedDbs();
            } catch (SQLiteException e) {
                /* ignore */
            }
            try {
                dbObj.close();
            } catch (SQLiteException e) {
                /* ignore */
            }
        } finally {
            // Delete all files of this corrupt database and/or attached databases
            if (attachedDbs != null) {
                for (Pair<String, String> p : attachedDbs) {
                    deleteDatabaseFile(p.second);
                }
            } else {
                // attachedDbs = null is possible when the database is so corrupt that even
                // "PRAGMA database_list;" also fails. delete the main database file
                deleteDatabaseFile(dbObj.getPath());
            }
        }
    }

    private void deleteDatabaseFile(String fileName) {
        if (fileName.equalsIgnoreCase(":memory:") || fileName.trim().length() == 0) {
            return;
        }
        Log.e(TAG, "deleting the database file: " + fileName);