switch(backoffPolicy) {
            case LINEAR:
                return JobRequest.BackoffPolicy.LINEAR;
            case EXPONENTIAL:
            default:
                return JobRequest.BackoffPolicy.EXPONENTIAL;
        }

package com.cloudinary.android;

import android.content.Context;
import android.os.PowerManager;
import androidx.annotation.NonNull;
import com.cloudinary.android.callback.UploadStatus;
import com.cloudinary.android.policy.UploadPolicy;
import com.evernote.android.job.Job;
import com.evernote.android.job.JobManager;
import com.evernote.android.job.JobRequest;
import com.evernote.android.job.util.support.PersistableBundleCompat;
import java.lang.ref.WeakReference;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * Background work strategy implementation based on com.evernote.android.job
 */
class AndroidJobStrategy implements BackgroundRequestStrategy {

    private static final String JOB_TAG = "CLD";

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

    private static final Map<String, WeakReference<Thread>> threads = new ConcurrentHashMap<>();

    private static final Object threadsMapLockObject = new Object();

    private static final int RUN_NOW_TIME_WINDOW_START = 10_000;

    private static final int RUN_NOW_TIME_WINDOW_END = 60_000;

    static JobRequest adapt(UploadRequest request) {
        PersistableBundleCompat extras = new PersistableBundleCompat();
        request.populateParamsFromFields(new AndroidJobRequestParams(extras));
        UploadPolicy policy = request.getUploadPolicy();
        JobRequest.Builder builder = new JobRequest.Builder(JOB_TAG).setBackoffCriteria(policy.getBackoffMillis(), adaptPolicy(policy.getBackoffPolicy())).setExtras(extras).setExecutionWindow(request.getTimeWindow().getMinLatencyOffsetMillis(), request.getTimeWindow().getMaxExecutionDelayMillis()).setRequiredNetworkType(adaptNetworkType(policy.getNetworkType())).setRequiresCharging(policy.isRequiresCharging()).setRequiresDeviceIdle(policy.isRequiresIdle()).setRequirementsEnforced(true);
        return builder.build();
    }

    private static JobRequest.BackoffPolicy adaptPolicy(UploadPolicy.BackoffPolicy backoffPolicy) {

    }

    private static JobRequest.NetworkType adaptNetworkType(UploadPolicy.NetworkType networkType) {
        switch(networkType) {
            case NONE:
                return JobRequest.NetworkType.ANY;
            case ANY:
                return JobRequest.NetworkType.CONNECTED;
            case UNMETERED:
                return JobRequest.NetworkType.UNMETERED;
        }
        return JobRequest.NetworkType.ANY;
    }

    @NonNull
    private static Job.Result adaptResult(UploadStatus res) {
        switch(res) {
            case FAILURE:
                return Job.Result.FAILURE;
            case SUCCESS:
                return Job.Result.SUCCESS;
            case RESCHEDULE:
                return Job.Result.RESCHEDULE;
        }
        // unexpected result, we don't want to retry because we have no idea why it failed.
        return Job.Result.FAILURE;
    }

    @Override
    public void init(Context context) {
        JobManager.create(context).addJobCreator(new JobCreator());
    }

    @Override
    public void doDispatch(UploadRequest request) {
        JobRequest job = adapt(request);
        job.schedule();
    }

    @Override
    public void executeRequestsNow(int howMany) {
        int started = 0;
        for (JobRequest jobRequest : JobManager.instance().getAllJobRequests()) {
            if (isSoonButNotImmediate(jobRequest)) {
                JobRequest.Builder builder = jobRequest.cancelAndEdit();
                long endMillis = Math.max(jobRequest.getEndMs(), RUN_NOW_TIME_WINDOW_END);
                builder.setExecutionWindow(RUN_NOW_TIME_WINDOW_START, endMillis).build().schedule();
                started++;
            }
            if (started == howMany) {
                break;
            }
        }
        Logger.d(TAG, String.format("Job scheduled started %d requests.", started));
    }

    private boolean isSoonButNotImmediate(JobRequest jobRequest) {
        return IMMEDIATE_THRESHOLD < jobRequest.getStartMs() && jobRequest.getStartMs() < SOON_THRESHOLD;
    }

    @Override
    public boolean cancelRequest(String requestId) {
        boolean cancelled = false;
        for (Job job : JobManager.instance().getAllJobs()) {
            String currJobId = ((UploadJob) job).requestId;
            if (requestId.equals(currJobId)) {
                job.cancel();
                cancelled = true;
            }
        }
        if (!cancelled) {
            for (JobRequest job : JobManager.instance().getAllJobRequests()) {
                String id = job.getExtras().getString("requestId", null);
                if (requestId.equals(id)) {
                    cancelled = JobManager.instance().cancel(job.getJobId());
                    break;
                }
            }
        }
        killThread(requestId);
        Logger.i(TAG, String.format("Cancelling request %s, success: %s", requestId, cancelled));
        return cancelled;
    }

    private void killThread(String requestId) {
        synchronized (threadsMapLockObject) {
            WeakReference<Thread> ref = threads.remove(requestId);
            if (ref != null) {
                Thread thread = ref.get();
                if (thread != null) {
                    thread.interrupt();
                }
                ref.clear();
            }
        }
    }

    @Override
    public int cancelAllRequests() {
        Logger.i(TAG, "All requests cancelled.");
        int count = JobManager.instance().cancelAll();
        killAllThreads();
        return count;
    }

    private void killAllThreads() {
        synchronized (threadsMapLockObject) {
            for (String requestId : threads.keySet()) {
                WeakReference<Thread> ref = threads.get(requestId);
                Thread thread = ref.get();
                if (thread != null) {
                    thread.interrupt();
                }
                ref.clear();
            }
            threads.clear();
        }
    }

    @Override
    public int getPendingImmediateJobsCount() {
        int pending = 0;
        for (JobRequest jobRequest : JobManager.instance().getAllJobRequests()) {
            if (isImmediate(jobRequest)) {
                pending++;
            }
        }
        return pending;
    }

    private boolean isImmediate(JobRequest jobRequest) {
        return jobRequest.getStartMs() < IMMEDIATE_THRESHOLD;
    }

    @Override
    public int getRunningJobsCount() {
        int running = 0;
        for (Job job : JobManager.instance().getAllJobs()) {
            if (!job.isFinished()) {
                running++;
            }
        }
        return running;
    }

    private static class JobCreator implements com.evernote.android.job.JobCreator {

        @Override
        public Job create(String tag) {
            return new UploadJob();
        }
    }

    private static final class UploadJob extends Job {

        private String requestId;

        UploadJob() {
        }

        @NonNull
        @Override
        protected Result onRunJob(Params params) {
            PowerManager pm = (PowerManager) getContext().getSystemService(Context.POWER_SERVICE);
            final PowerManager.WakeLock wl = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "CLD_UPLOADER");
            this.requestId = params.getExtras().getString("requestId", null);
            registerThread();
            // Acquire wake readWriteLock - evernote android job only takes wakelock for 3 minutes and file uploads can take (much) longer.
            wl.acquire();
            try {
                // call the generic processor:
                UploadStatus result = MediaManager.get().processRequest(getContext(), new AndroidJobRequestParams(params.getExtras()));
                return adaptResult(result);
            } finally {
                wl.release();
                unregisterThread();
            }
        }

        private void unregisterThread() {
            synchronized (threadsMapLockObject) {
                WeakReference<Thread> removed = threads.remove(requestId);
                if (removed != null) {
                    removed.clear();
                }
            }
        }

        private void registerThread() {
            synchronized (threadsMapLockObject) {
                threads.put(requestId, new WeakReference<>(Thread.currentThread()));
            }
        }
    }

    private static final class AndroidJobRequestParams implements RequestParams {

        private final PersistableBundleCompat bundle;

        private AndroidJobRequestParams(PersistableBundleCompat bundle) {
            this.bundle = bundle;
        }

        @Override
        public void putString(String key, String value) {
            this.bundle.putString(key, value);
        }

        @Override
        public void putInt(String key, int value) {
            this.bundle.putInt(key, value);
        }

        @Override
        public void putLong(String key, long value) {
            this.bundle.putLong(key, value);
        }

        @Override
        public void putBoolean(String key, boolean value) {
            this.bundle.putBoolean(key, value);
        }

        @Override
        public String getString(String key, String defaultValue) {
            return bundle.getString(key, defaultValue);
        }

        @Override
        public int getInt(String key, int defaultValue) {
            return bundle.getInt(key, defaultValue);
        }

        @Override
        public long getLong(String key, long defaultValue) {
            return bundle.getLong(key, defaultValue);
        }

        @Override
        public boolean getBoolean(String key, boolean defaultValue) {
            return bundle.getBoolean(key, defaultValue);
        }
    }
}


switch(launchViewId) {
            case R.id.btn_choose_pic:
                EditCropRotateActivity.start(getActivity(), extra.get(0).getPath());
                break;
            case R.id.btn_sticker_test:
                StickerImageActivity.start(getActivity(), extra.get(0).getPath());
                break;
        }

package com.march.picedit;

import android.Manifest;
import android.content.Intent;
import android.os.Build;
import android.view.View;
import com.march.common.model.ImageInfo;
import com.march.picedit.edit.EditCropRotateActivity;
import com.march.picedit.graffiti.GraffitiActivity;
import com.march.picedit.sticker.StickerImageActivity;
import com.march.picedit.test.TestCompressImageActivity;
import com.march.picedit.test.TestPorterDuffXfermodeActivity;
import com.march.uikit.annotation.UILayout;
import com.march.uikit.annotation.UITitle;
import java.util.ArrayList;
import butterknife.OnClick;

@UILayout(R.layout.home_activity)
@UITitle(titleText = "首页")
public class MainActivity extends PicEditActivity {

    @Override
    public void initBeforeViewCreated() {
        super.initBeforeViewCreated();
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            requestPermissions(new String[] { Manifest.permission.READ_EXTERNAL_STORAGE, Manifest.permission.WRITE_EXTERNAL_STORAGE }, 100);
        }
    }

    private int launchViewId = -1;

    @OnClick({ R.id.btn_xfermode, R.id.btn_choose_pic, R.id.btn_test, R.id.btn_sticker_test, R.id.btn_graffiti })
    public void clickView(View view) {
        launchViewId = view.getId();
        switch(view.getId()) {
            case R.id.btn_choose_pic:
                SelectImageActivity.startActivity(getActivity());
                break;
            case R.id.btn_test:
                startActivity(TestCompressImageActivity.class);
                break;
            case R.id.btn_sticker_test:
                SelectImageActivity.startActivity(getActivity());
                break;
            case R.id.btn_graffiti:
                GraffitiActivity.start(getActivity());
                break;
            case R.id.btn_xfermode:
                startActivity(TestPorterDuffXfermodeActivity.class);
                break;
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (data == null) {
            return;
        }
        if (launchViewId == -1) {
            return;
        }
        ArrayList<ImageInfo> extra = data.getParcelableArrayListExtra(SelectImageActivity.KEY_DATA);
        if (extra.size() != 1) {
            return;
        }


switch(switchTarget) {
            case 'A':
                bar = param;
                break;
            case 'B':
                bar = "bobs_your_uncle";
                break;
            case 'C':
            case 'D':
                bar = param;
                break;
            default:
                bar = "bobs_your_uncle";
                break;
        }

/**
 * OWASP Benchmark Project v1.2
 *
 *
This file is part of the Open Web Application Security Project (OWASP) Benchmark Project. For
 * details, please see http://example.com.
 *
 * @author Nick Sanidas
 * @created 2015
 */
package org.owasp.benchmark.testcode;

import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@WebServlet(value = "/sqli-01/BenchmarkTest00593")
public class BenchmarkTest00593 extends HttpServlet {

    private static final long serialVersionUID = 1L;

    @Override
    public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doPost(request, response);
    }

    @Override
    public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        response.setContentType("text/html;charset=UTF-8");
        String param = "";
        boolean flag = true;
        java.util.Enumeration<String> names = request.getParameterNames();
        while (names.hasMoreElements() && flag) {
            String name = (String) names.nextElement();
            String[] values = request.getParameterValues(name);
            if (values != null) {
                for (int i = 0; i < values.length && flag; i++) {
                    String value = values[i];
                    if (value.equals("BenchmarkTest00593")) {
                        param = name;
                        flag = false;
                    }
                }
            }
        }
        String bar;
        String guess = "ABC";
        char switchTarget = guess.charAt(2);
        // Simple case statement that assigns param to bar on conditions 'A', 'C', or 'D'

        String sql = "SELECT * from USERS where USERNAME=? and PASSWORD='" + bar + "'";
        try {
            java.sql.Connection connection = org.owasp.benchmark.helpers.DatabaseHelper.getSqlConnection();
            java.sql.PreparedStatement statement = connection.prepareStatement(sql, java.sql.ResultSet.TYPE_FORWARD_ONLY, java.sql.ResultSet.CONCUR_READ_ONLY, java.sql.ResultSet.CLOSE_CURSORS_AT_COMMIT);
            statement.setString(1, "foo");
            statement.execute();
            org.owasp.benchmark.helpers.DatabaseHelper.printResults(statement, sql, response);
        } catch (java.sql.SQLException e) {
            if (org.owasp.benchmark.helpers.DatabaseHelper.hideSQLErrors) {
                response.getWriter().println("Error processing request.");
                return;
            } else
                throw new ServletException(e);
        }
    }
}


switch(selectedPanel) {
                case TAB_DOCUMENT:
                    return TabDocumentComunicator.getDocument().getUuid();
                case TAB_FOLDER:
                    return TabFolderComunicator.getFolder().getUuid();
                case TAB_MAIL:
                    return TabMailComunicator.getMail().getUuid();
                default:
                    return null;
            }

/**
 * OpenKM, Open Document Management System (http://www.openkm.com)
 *

 * No bytes were intentionally harmed during the development of this application.
 *

 */
package com.openkm.extension.frontend.client.widget.workflow;

import com.google.gwt.user.client.ui.Widget;
import com.openkm.frontend.client.constants.ui.UIDockPanelConstants;
import com.openkm.frontend.client.extension.comunicator.TabDocumentComunicator;
import com.openkm.frontend.client.extension.comunicator.TabFolderComunicator;
import com.openkm.frontend.client.extension.comunicator.TabMailComunicator;
import com.openkm.frontend.client.extension.comunicator.WorkspaceComunicator;
import com.openkm.frontend.client.extension.event.HasLanguageEvent;
import com.openkm.frontend.client.extension.event.HasLanguageEvent.LanguageEventConstant;
import com.openkm.frontend.client.extension.event.handler.LanguageHandlerExtension;
import java.util.ArrayList;
import java.util.List;

/**
 * Workflow
 *
 * @author jllort
 */
public class Workflow implements LanguageHandlerExtension {

    public static final int TAB_DOCUMENT = 0;

    public static final int TAB_FOLDER = 1;

    public static final int TAB_MAIL = 2;

    public static Workflow singleton;

    private static final String UUID = "fa7f4556-3249-4268-88e0-0dd78a79872a";

    // By default the folder tab is selected at starting
    private int selectedPanel = TAB_FOLDER;

    private TabDocumentWorkflow tabDocumentWorkflow;

    private TabFolderWorkflow tabFolderWorkflow;

    /**
     * Workflow
     *
     * @param uuidList
     */
    public Workflow(List<String> uuidList) {
        if (isRegistered(uuidList)) {
            singleton = this;
            tabDocumentWorkflow = new TabDocumentWorkflow();
            tabFolderWorkflow = new TabFolderWorkflow();
        }
    }

    public List<Object> getExtensions() {
        List<Object> extensions = new ArrayList<Object>();
        extensions.add(singleton);
        extensions.add(tabDocumentWorkflow);
        extensions.add(tabFolderWorkflow);
        return extensions;
    }

    public static Workflow get() {
        return singleton;
    }

    public Widget getWidgetTab() {
        Widget widget = null;
        if (WorkspaceComunicator.getSelectedWorkspace() == UIDockPanelConstants.DESKTOP) {
            if (selectedPanel == TAB_DOCUMENT) {
                widget = tabDocumentWorkflow;
            } else if (selectedPanel == TAB_FOLDER) {
                widget = tabFolderWorkflow;
            } else if (selectedPanel == TAB_MAIL) {
            }
        }
        return widget;
    }

    public void setTabDocumentSelected() {
        selectedPanel = TAB_DOCUMENT;
    }

    public void setTabFolderSelected() {
        selectedPanel = TAB_FOLDER;
    }

    public void setTabMailSelected() {
        selectedPanel = TAB_MAIL;
    }

    public String getUuid() {
        if (WorkspaceComunicator.getSelectedWorkspace() == UIDockPanelConstants.DESKTOP) {

        } else {
            return null;
        }
    }

    @Override
    public void onChange(LanguageEventConstant event) {
        if (event.equals(HasLanguageEvent.LANGUAGE_CHANGED)) {
            tabDocumentWorkflow.langRefresh();
        }
    }

    /**
     * isRegistered
     *
     * @param uuidList
     * @return
     */
    public static boolean isRegistered(List<String> uuidList) {
        return uuidList.contains(UUID);
    }
}


switch(cse.getState()) {
                case INTEREST_OPS:
                    // Continue writing when the channel becomes writable.
                    flush(ctx, true);
                    break;
                case OPEN:
                    if (!Boolean.TRUE.equals(cse.getValue())) {
                        // Fail all pending writes
                        flush(ctx, true);
                    }
                    break;
            }

package org.jboss.netty.handler.stream;

import org.jboss.netty.buffer.ChannelBuffers;
import org.jboss.netty.channel.Channel;
import org.jboss.netty.channel.ChannelDownstreamHandler;
import org.jboss.netty.channel.ChannelEvent;
import org.jboss.netty.channel.ChannelFuture;
import org.jboss.netty.channel.ChannelFutureListener;
import org.jboss.netty.channel.ChannelHandler;
import org.jboss.netty.channel.ChannelHandlerContext;
import org.jboss.netty.channel.ChannelPipeline;
import org.jboss.netty.channel.ChannelStateEvent;
import org.jboss.netty.channel.ChannelUpstreamHandler;
import org.jboss.netty.channel.LifeCycleAwareChannelHandler;
import org.jboss.netty.channel.MessageEvent;
import org.jboss.netty.logging.InternalLogger;
import org.jboss.netty.logging.InternalLoggerFactory;
import java.io.IOException;
import java.nio.channels.ClosedChannelException;
import java.util.Queue;
import java.util.concurrent.ConcurrentLinkedQueue;
import java.util.concurrent.atomic.AtomicBoolean;
import static org.jboss.netty.channel.Channels.*;

/**
 * A {@link ChannelHandler} that adds support for writing a large data stream
 * asynchronously neither spending a lot of memory nor getting
 * {@link OutOfMemoryError}.  Large data streaming such as file
 * transfer requires complicated state management in a {@link ChannelHandler}
 * implementation.  {@link ChunkedWriteHandler} manages such complicated states
 * so that you can send a large data stream without difficulties.
 *

 * To use {@link ChunkedWriteHandler} in your application, you have to insert
 * a new {@link ChunkedWriteHandler} instance:
 *

 * {@link ChannelPipeline} p = ...;
 * p.addLast("streamer", new {@link ChunkedWriteHandler}());
 * p.addLast("handler", new MyHandler());
 *

 * Once inserted, you can write a {@link ChunkedInput} so that the
 * {@link ChunkedWriteHandler} can pick it up and fetch the content of the
 * stream chunk by chunk and write the fetched chunk downstream:
 *

 * {@link Channel} ch = ...;
 * ch.write(new {@link ChunkedFile}(new File("video.mkv"));
 *

 *
 *
Sending a stream which generates a chunk intermittently

 *
 * Some {@link ChunkedInput} generates a chunk on a certain event or timing.
 * Such {@link ChunkedInput} implementation often returns {@code null} on
 * {@link ChunkedInput#nextChunk()}, resulting in the indefinitely suspended
 * transfer.  To resume the transfer when a new chunk is available, you have to
 * call {@link #resumeTransfer()}.
 * @apiviz.landmark
 * @apiviz.has org.jboss.netty.handler.stream.ChunkedInput oneway - - reads from
 */
public class ChunkedWriteHandler implements ChannelUpstreamHandler, ChannelDownstreamHandler, LifeCycleAwareChannelHandler {

    private static final InternalLogger logger = InternalLoggerFactory.getInstance(ChunkedWriteHandler.class);

    private final Queue<MessageEvent> queue = new ConcurrentLinkedQueue<MessageEvent>();

    private volatile ChannelHandlerContext ctx;

    private final AtomicBoolean flush = new AtomicBoolean(false);

    private MessageEvent currentEvent;

    private volatile boolean flushNeeded;

    /**
     * Continues to fetch the chunks from the input.
     */
    public void resumeTransfer() {
        ChannelHandlerContext ctx = this.ctx;
        if (ctx == null) {
            return;
        }
        try {
            flush(ctx, false);
        } catch (Exception e) {
            if (logger.isWarnEnabled()) {
                logger.warn("Unexpected exception while sending chunks.", e);
            }
        }
    }

    public void handleDownstream(ChannelHandlerContext ctx, ChannelEvent e) throws Exception {
        if (!(e instanceof MessageEvent)) {
            ctx.sendDownstream(e);
            return;
        }
        boolean offered = queue.offer((MessageEvent) e);
        assert offered;
        final Channel channel = ctx.getChannel();
        // call flush if the channel is writable or not connected. flush(..) will take care of the rest
        if (channel.isWritable() || !channel.isConnected()) {
            this.ctx = ctx;
            flush(ctx, false);
        }
    }

    public void handleUpstream(ChannelHandlerContext ctx, ChannelEvent e) throws Exception {
        if (e instanceof ChannelStateEvent) {
            ChannelStateEvent cse = (ChannelStateEvent) e;

        }
        ctx.sendUpstream(e);
    }

    private void discard(ChannelHandlerContext ctx, boolean fireNow) {
        ClosedChannelException cause = null;
        for (; ; ) {
            MessageEvent currentEvent = this.currentEvent;
            if (this.currentEvent == null) {
                currentEvent = queue.poll();
            } else {
                this.currentEvent = null;
            }
            if (currentEvent == null) {
                break;
            }
            Object m = currentEvent.getMessage();
            if (m instanceof ChunkedInput) {
                closeInput((ChunkedInput) m);
            }
            // Trigger a ClosedChannelException
            if (cause == null) {
                cause = new ClosedChannelException();
            }
            currentEvent.getFuture().setFailure(cause);
        }
        if (cause != null) {
            if (fireNow) {
                fireExceptionCaught(ctx.getChannel(), cause);
            } else {
                fireExceptionCaughtLater(ctx.getChannel(), cause);
            }
        }
    }

    private void flush(ChannelHandlerContext ctx, boolean fireNow) throws Exception {
        boolean acquired;
        final Channel channel = ctx.getChannel();
        boolean suspend = false;
        flushNeeded = true;
        // use CAS to see if the have flush already running, if so we don't need to take futher actions
        if (acquired = flush.compareAndSet(false, true)) {
            flushNeeded = false;
            try {
                if (!channel.isConnected()) {
                    discard(ctx, fireNow);
                    return;
                }
                while (channel.isWritable()) {
                    if (currentEvent == null) {
                        currentEvent = queue.poll();
                    }
                    if (currentEvent == null) {
                        break;
                    }
                    if (currentEvent.getFuture().isDone()) {
                        // Skip the current request because the previous partial write
                        // attempt for the current request has been failed.
                        currentEvent = null;
                    } else {
                        final MessageEvent currentEvent = this.currentEvent;
                        Object m = currentEvent.getMessage();
                        if (m instanceof ChunkedInput) {
                            final ChunkedInput chunks = (ChunkedInput) m;
                            Object chunk;
                            boolean endOfInput;
                            try {
                                chunk = chunks.nextChunk();
                                endOfInput = chunks.isEndOfInput();
                                if (chunk == null) {
                                    chunk = ChannelBuffers.EMPTY_BUFFER;
                                    // No need to suspend when reached at the end.
                                    suspend = !endOfInput;
                                } else {
                                    suspend = false;
                                }
                            } catch (Throwable t) {
                                this.currentEvent = null;
                                currentEvent.getFuture().setFailure(t);
                                if (fireNow) {
                                    fireExceptionCaught(ctx, t);
                                } else {
                                    fireExceptionCaughtLater(ctx, t);
                                }
                                closeInput(chunks);
                                break;
                            }
                            if (suspend) {
                                // ChunkedInput.nextChunk() returned null and it has
                                // not reached at the end of input.  Let's wait until
                                // more chunks arrive.  Nothing to write or notify.
                                break;
                            } else {
                                ChannelFuture writeFuture;
                                if (endOfInput) {
                                    this.currentEvent = null;
                                    writeFuture = currentEvent.getFuture();
                                    // Register a listener which will close the input once the write
                                    // is complete. This is needed because the Chunk may have some
                                    // resource bound that can not be closed before its not written
                                    writeFuture.addListener(new ChannelFutureListener() {

                                        public void operationComplete(ChannelFuture future) throws Exception {
                                            closeInput(chunks);
                                        }
                                    });
                                } else {
                                    writeFuture = future(channel);
                                    writeFuture.addListener(new ChannelFutureListener() {

                                        public void operationComplete(ChannelFuture future) throws Exception {
                                            if (!future.isSuccess()) {
                                                currentEvent.getFuture().setFailure(future.getCause());
                                                closeInput((ChunkedInput) currentEvent.getMessage());
                                            }
                                        }
                                    });
                                }
                                write(ctx, writeFuture, chunk, currentEvent.getRemoteAddress());
                            }
                        } else {
                            this.currentEvent = null;
                            ctx.sendDownstream(currentEvent);
                        }
                    }
                    if (!channel.isConnected()) {
                        discard(ctx, fireNow);
                        return;
                    }
                }
            } finally {
                // mark the flush as done
                flush.set(false);
            }
        }
        if (acquired && (!channel.isConnected() || channel.isWritable() && !queue.isEmpty() && !suspend || flushNeeded)) {
            flush(ctx, fireNow);
        }
    }

    static void closeInput(ChunkedInput chunks) {
        try {
            chunks.close();
        } catch (Throwable t) {
            if (logger.isWarnEnabled()) {
                logger.warn("Failed to close a chunked input.", t);
            }
        }
    }

    public void beforeAdd(ChannelHandlerContext ctx) throws Exception {
        // nothing to do
    }

    public void afterAdd(ChannelHandlerContext ctx) throws Exception {
        // nothing to do
    }

    public void beforeRemove(ChannelHandlerContext ctx) throws Exception {
        // try to flush again a last time.
        flush(ctx, false);
    }

    // This method should not need any synchronization as the ChunkedWriteHandler will not receive any new events
    public void afterRemove(ChannelHandlerContext ctx) throws Exception {
        // Fail all MessageEvent's that are left. This is needed because otherwise we would never notify the
        // ChannelFuture and the registered FutureListener. See #304
        Throwable cause = null;
        boolean fireExceptionCaught = false;
        for (; ; ) {
            MessageEvent currentEvent = this.currentEvent;
            if (this.currentEvent == null) {
                currentEvent = queue.poll();
            } else {
                this.currentEvent = null;
            }
            if (currentEvent == null) {
                break;
            }
            Object m = currentEvent.getMessage();
            if (m instanceof ChunkedInput) {
                closeInput((ChunkedInput) m);
            }
            // Create exception
            if (cause == null) {
                cause = new IOException("Unable to flush event, discarding");
            }
            currentEvent.getFuture().setFailure(cause);
            fireExceptionCaught = true;
        }
        if (fireExceptionCaught) {
            fireExceptionCaughtLater(ctx.getChannel(), cause);
        }
    }
}


switch(msg.what) {
            case HANDLE_RESPONSE:
                LoadListener loader = (LoadListener) msg.obj;
                synchronized (SslErrorHandlerImpl.this) {
                    handleSslErrorResponse(loader, loader.sslError(), msg.arg1 == 1);
                    mLoaderQueue.remove(loader);
                    fastProcessQueuedSslErrors();
                }
                break;
        }

package android.webkit;

import android.net.http.SslError;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import java.util.LinkedList;
import java.util.ListIterator;

/**
 * SslErrorHandler's implementation for Android Java HTTP stack.
 * This class is not needed if the Chromium HTTP stack is used.
 */
class SslErrorHandlerImpl extends SslErrorHandler {

    /* One problem here is that there may potentially be multiple SSL errors
     * coming from multiple loaders. Therefore, we keep a queue of loaders
     * that have SSL-related problems and process errors one by one in the
     * order they were received.
     */
    private static final String LOGTAG = "network";

    /**
     * Queue of loaders that experience SSL-related problems.
     */
    private LinkedList<LoadListener> mLoaderQueue;

    /**
     * SSL error preference table.
     */
    private Bundle mSslPrefTable;

    // These are only used in the client facing SslErrorHandler.
    private final SslErrorHandler mOriginHandler;

    private final LoadListener mLoadListener;

    // Message id for handling the response from the client.
    private static final int HANDLE_RESPONSE = 100;

    @Override
    public void handleMessage(Message msg) {

    }

    /**
     * Creates a new error handler with an empty loader queue.
     */
    SslErrorHandlerImpl() {
        mLoaderQueue = new LinkedList<LoadListener>();
        mSslPrefTable = new Bundle();
        // These are used by client facing SslErrorHandlers.
        mOriginHandler = null;
        mLoadListener = null;
    }

    /**
     * Create a new error handler that will be passed to the client.
     */
    private SslErrorHandlerImpl(SslErrorHandler origin, LoadListener listener) {
        mOriginHandler = origin;
        mLoadListener = listener;
    }

    /**
     * Saves this handler's state into a map.
     * @return True iff succeeds.
     */
    synchronized boolean saveState(Bundle outState) {
        boolean success = (outState != null);
        if (success) {
            outState.putBundle("ssl-error-handler", mSslPrefTable);
        }
        return success;
    }

    /**
     * Restores this handler's state from a map.
     * @return True iff succeeds.
     */
    synchronized boolean restoreState(Bundle inState) {
        boolean success = (inState != null);
        if (success) {
            success = inState.containsKey("ssl-error-handler");
            if (success) {
                mSslPrefTable = inState.getBundle("ssl-error-handler");
            }
        }
        return success;
    }

    /**
     * Clears SSL error preference table.
     */
    synchronized void clear() {
        mSslPrefTable.clear();
    }

    /**
     * Handles requests from the network stack about whether to proceed with a
     * load given an SSL error(s). We may ask the client what to do, or use a
     * cached response.
     */
    synchronized void handleSslErrorRequest(LoadListener loader) {
        if (DebugFlags.SSL_ERROR_HANDLER) {
            Log.v(LOGTAG, "SslErrorHandler.handleSslErrorRequest(): " + "url=" + loader.url());
        }
        if (!loader.cancelled()) {
            mLoaderQueue.offer(loader);
            if (loader == mLoaderQueue.peek()) {
                fastProcessQueuedSslErrors();
            }
        }
    }

    /**
     * Check the preference table to see if we already have a 'proceed' decision
     * from the client for this host and for an error of equal or greater
     * severity than the supplied error. If so, instruct the loader to proceed
     * and return true. Otherwise return false.
     */
    synchronized boolean checkSslPrefTable(LoadListener loader, SslError error) {
        final String host = loader.host();
        final int primary = error.getPrimaryError();
        if (DebugFlags.SSL_ERROR_HANDLER) {
            assert host != null;
            assert primary != -1;
        }
        if (mSslPrefTable.containsKey(host) && primary <= mSslPrefTable.getInt(host)) {
            if (!loader.cancelled()) {
                loader.handleSslErrorResponse(true);
            }
            return true;
        }
        return false;
    }

    /**
     * Processes queued SSL-error confirmation requests in
     * a tight loop while there is no need to ask the client.
     */
    void fastProcessQueuedSslErrors() {
        while (processNextLoader()) ;
    }

    /**
     * Processes the next loader in the queue.
     * @return True iff should proceed to processing the
     * following loader in the queue
     */
    private synchronized boolean processNextLoader() {
        LoadListener loader = mLoaderQueue.peek();
        if (loader != null) {
            // if this loader has been cancelled
            if (loader.cancelled()) {
                // go to the following loader in the queue. Make sure this
                // loader has been removed from the queue.
                mLoaderQueue.remove(loader);
                return true;
            }
            SslError error = loader.sslError();
            if (DebugFlags.SSL_ERROR_HANDLER) {
                assert error != null;
            }
            // checkSslPrefTable() will instruct the loader to proceed if we
            // have a cached 'proceed' decision. It does not remove the loader
            // from the queue.
            if (checkSslPrefTable(loader, error)) {
                mLoaderQueue.remove(loader);
                return true;
            }
            // If we can not proceed based on a cached decision, ask the client.
            CallbackProxy proxy = loader.getFrame().getCallbackProxy();
            proxy.onReceivedSslError(new SslErrorHandlerImpl(this, loader), error);
        }
        // the queue must be empty, stop
        return false;
    }

    public void proceed() {
        mOriginHandler.sendMessage(mOriginHandler.obtainMessage(HANDLE_RESPONSE, 1, 0, mLoadListener));
    }

    /**
     * Cancel this load and all pending loads for the WebView that had the
     * error.
     */
    public void cancel() {
        mOriginHandler.sendMessage(mOriginHandler.obtainMessage(HANDLE_RESPONSE, 0, 0, mLoadListener));
    }

    /**
     * Handles the response from the client about whether to proceed with this
     * load. We save the response to be re-used in the future.
     */
    synchronized void handleSslErrorResponse(LoadListener loader, SslError error, boolean proceed) {
        if (DebugFlags.SSL_ERROR_HANDLER) {
            assert loader != null;
            assert error != null;
        }
        if (DebugFlags.SSL_ERROR_HANDLER) {
            Log.v(LOGTAG, "SslErrorHandler.handleSslErrorResponse():" + " proceed: " + proceed + " url:" + loader.url());
        }
        if (!loader.cancelled()) {
            if (proceed) {
                // Update the SSL error preference table
                int primary = error.getPrimaryError();
                String host = loader.host();
                if (DebugFlags.SSL_ERROR_HANDLER) {
                    assert host != null;
                    assert primary != -1;
                }
                boolean hasKey = mSslPrefTable.containsKey(host);
                if (!hasKey || primary > mSslPrefTable.getInt(host)) {
                    mSslPrefTable.putInt(host, primary);
                }
            }
            loader.handleSslErrorResponse(proceed);
        }
    }
}


switch(kind) {
            case FALSE:
            case TRUE:
                return 0;
            case INF:
            case FIN:
            case INF_NOT:
            case FIN_NOT:
                return 1;
            case OR:
            case AND:
                return left.countAcceptanceSets() + right.countAcceptanceSets();
        }

// * Joachim Klein <example@nnthink.com> (TU Dresden)
// * Dave Parker <example@nnthink.com> (University of Birmingham/Oxford)
// This file is part of PRISM.
package acceptance;

import java.io.PrintStream;
import java.util.ArrayList;
import java.util.BitSet;
import java.util.Collections;
import java.util.List;
import java.util.Stack;
import acceptance.AcceptanceRabin.RabinPair;
import acceptance.AcceptanceStreett.StreettPair;
import prism.PrismException;
import prism.PrismNotSupportedException;
import jdd.JDDVars;

/**
 * A generic acceptance condition (based on BitSet state sets).
 * This is an AST of a boolean formula (conjunction and disjunction) over
 * atoms of the form Inf(states), Inf(!states), Fin(states) and Fin(!states).
 *

 * Semantics:
 *  Inf(states)  <=> G F states
 *  Inf(!states) <=> G F !states
 *  Fin(states)  <=> F G !states
 *  Fin(!states) <=> F G states
 */
public class AcceptanceGeneric implements AcceptanceOmega {

    /**
     * The types of elements in the AST
     */
    public enum ElementType {

        FALSE,
        TRUE,
        OR,
        AND,
        INF,
        FIN,
        INF_NOT,
        FIN_NOT
    }

    /**
     * The type of this node in the AST
     */
    private ElementType kind;

    /**
     * The left child (if it exists)
     */
    private AcceptanceGeneric left = null;

    /**
     * The right child (if it exists)
     */
    private AcceptanceGeneric right = null;

    /**
     * The set of states (if this is one of INF, FIN, INF_NOT, FIN_NOT)
     */
    private BitSet states = null;

    /**
     * Constructor for TRUE or FALSE
     * @param value true or false?
     */
    public AcceptanceGeneric(boolean value) {
        kind = value ? ElementType.TRUE : ElementType.FALSE;
    }

    /**
     * Constructor for an INF, FIN, INF_NOT or FIN_NOT element.
     */
    public AcceptanceGeneric(ElementType kind, BitSet states) {
        this.kind = kind;
        this.states = states;
    }

    /**
     * Constructor for a binary operator (AND/OR).
     * @param kind
     * @param left
     * @param right
     */
    public AcceptanceGeneric(ElementType kind, AcceptanceGeneric left, AcceptanceGeneric right) {
        this.kind = kind;
        this.left = left;
        this.right = right;
    }

    /**
     * Get the ElementType of this AST element
     */
    public ElementType getKind() {
        return kind;
    }

    /**
     * Get the left child of this AST element
     */
    public AcceptanceGeneric getLeft() {
        return left;
    }

    /**
     * Get the right child of this AST element
     */
    public AcceptanceGeneric getRight() {
        return right;
    }

    /**
     * Get the state set of this element (if kind is one of INF, FIN, INF_NOT, FIN_NOT).
     */
    public BitSet getStates() {
        return states;
    }

    @Override
    public boolean isBSCCAccepting(BitSet bscc) {
        switch(kind) {
            case TRUE:
                return true;
            case FALSE:
                return false;
            case AND:
                return left.isBSCCAccepting(bscc) && right.isBSCCAccepting(bscc);
            case OR:
                return left.isBSCCAccepting(bscc) || right.isBSCCAccepting(bscc);
            case INF:
                // bscc |= G F states?
                // there exists a state in bscc and states
                return bscc.intersects(states);
            case INF_NOT:
                {
                    // the BSCC does not consist only of states
                    BitSet bs = (BitSet) bscc.clone();
                    bs.andNot(states);
                    return !bs.isEmpty();
                }
            case FIN:
                {
                    // <=> there exists no states state in BSCC
                    return !bscc.intersects(states);
                }
            case FIN_NOT:
                {
                    // bscc |= F G states?
                    // the BSCC consists entirely of states
                    BitSet bs = (BitSet) bscc.clone();
                    bs.and(states);
                    return bs.equals(bscc);
                }
        }
        return false;
    }

    /**
     * Get a list of all the (non-true/false) leaf nodes in this acceptance condition
     */
    public List<AcceptanceGeneric> getLeafNodes() {
        switch(getKind()) {
            case AND:
            case OR:
                {
                    List<AcceptanceGeneric> result = new ArrayList<AcceptanceGeneric>();
                    result.addAll(left.getLeafNodes());
                    result.addAll(right.getLeafNodes());
                    return result;
                }
            case TRUE:
            case FALSE:
                return Collections.emptyList();
            case FIN:
            case FIN_NOT:
            case INF:
            case INF_NOT:
                return Collections.singletonList(this);
        }
        throw new UnsupportedOperationException("Unknown kind");
    }

    @Override
    public String getSignatureForState(int stateIndex) {
        List<AcceptanceGeneric> leafNodes = getLeafNodes();
        String result = "";
        for (int i = 0; i < leafNodes.size(); i++) {
            if (leafNodes.get(i).getStates().get(stateIndex)) {
                result += (result.isEmpty() ? "" : ",") + i;
            }
        }
        result = "{" + result + "}";
        return result;
    }

    @Override
    public String getSignatureForStateHOA(int stateIndex) {
        List<AcceptanceGeneric> leafNodes = getLeafNodes();
        String result = "";
        for (int i = 0; i < leafNodes.size(); i++) {
            if (leafNodes.get(i).getStates().get(stateIndex)) {
                result += (result.isEmpty() ? "" : " ") + i;
            }
        }
        if (!result.isEmpty())
            result = "{" + result + "}";
        return result;
    }

    @Override
    public String getSizeStatistics() {
        return "generic acceptance with " + countAcceptanceSets() + " acceptance sets";
    }

    @Override
    public AcceptanceType getType() {
        return AcceptanceType.GENERIC;
    }

    @Override
    @Deprecated
    public String getTypeAbbreviated() {
        return getType().getNameAbbreviated();
    }

    @Override
    @Deprecated
    public String getTypeName() {
        return getType().getName();
    }

    @Override
    public AcceptanceGeneric clone() {
        switch(kind) {
            case FIN:
            case FIN_NOT:
            case INF:
            case INF_NOT:
                return new AcceptanceGeneric(kind, states);
            case AND:
            case OR:
                return new AcceptanceGeneric(kind, left.clone(), right.clone());
            case FALSE:
                return new AcceptanceGeneric(false);
            case TRUE:
                return new AcceptanceGeneric(true);
        }
        throw new UnsupportedOperationException("Unsupported operator in generic acceptance condition");
    }

    /**
     * Returns a new generic acceptance condition that corresponds to the conjunction
     * of this and the other acceptance condition. Both conditions are not
     * cloned; take care not to modify the conditions or clone beforehand.
     * @param other the other generic acceptance condition
     * @return new AcceptanceRabin, conjunction of this and other
     */
    public AcceptanceGeneric and(AcceptanceGeneric other) {
        return new AcceptanceGeneric(ElementType.AND, this, other);
    }

    /**
     * Returns a new generic acceptance condition that corresponds to the disjunction
     * of this and the other acceptance condition. Both conditions are not
     * cloned; take care not to modify the conditions or clone beforehand.
     * @param other the other generic acceptance condition
     * @return new AcceptanceGeneric, disjunction of this and other
     */
    public AcceptanceGeneric or(AcceptanceGeneric other) {
        return new AcceptanceGeneric(ElementType.OR, this, other);
    }

    /**
     * Complement this acceptance condition, return as AcceptanceGeneric.
     */
    public AcceptanceGeneric complementToGeneric() {
        switch(kind) {
            case TRUE:
                return new AcceptanceGeneric(false);
            case FALSE:
                return new AcceptanceGeneric(true);
            case AND:
                return new AcceptanceGeneric(ElementType.OR, getLeft().complementToGeneric(), getRight().complementToGeneric());
            case OR:
                return new AcceptanceGeneric(ElementType.AND, getLeft().complementToGeneric(), getRight().complementToGeneric());
            case FIN:
                return new AcceptanceGeneric(ElementType.INF, (BitSet) states.clone());
            case FIN_NOT:
                return new AcceptanceGeneric(ElementType.INF_NOT, (BitSet) states.clone());
            case INF:
                return new AcceptanceGeneric(ElementType.FIN, (BitSet) states.clone());
            case INF_NOT:
                return new AcceptanceGeneric(ElementType.FIN_NOT, (BitSet) states.clone());
            default:
                throw new UnsupportedOperationException();
        }
    }

    @Override
    public AcceptanceOmega complement(int numStates, AcceptanceType... allowedAcceptance) throws PrismException {
        if (AcceptanceType.contains(allowedAcceptance, AcceptanceType.GENERIC)) {
            return this.complementToGeneric();
        }
        throw new PrismNotSupportedException("Can not complement " + getType() + " acceptance to required acceptance type");
    }

    @Override
    public void lift(LiftBitSet lifter) {
        switch(kind) {
            case TRUE:
            case FALSE:
                return;
            case INF:
            case INF_NOT:
            case FIN:
            case FIN_NOT:
                states = lifter.lift(states);
                return;
            case AND:
            case OR:
                left.lift(lifter);
                right.lift(lifter);
                return;
        }
        throw new UnsupportedOperationException("Unsupported operator in generic acceptance condition");
    }

    /**
     * Count the number of state sets in this acceptance condition
     */
    public int countAcceptanceSets() {

throw new UnsupportedOperationException("Unsupported operator in generic acceptance condition");
    }

    @Override
    public AcceptanceOmegaDD toAcceptanceDD(JDDVars ddRowVars) {
        return new AcceptanceGenericDD(this, ddRowVars);
    }

    @Override
    public AcceptanceGeneric toAcceptanceGeneric() {
        return this.clone();
    }

    /**
     * Attempt to convert this generic acceptance condition
     * to a Rabin condition. If this condition does not have
     * the required form (top-level disjunctions with conjunctive pairs),
     * returns {@code null}.
     *

     * If the condition does not syntactically have the required
     * from but can be easily converted to one (e.g., by converting
     * a single Inf(S) to a Fin(emptyset) & Inf(S) etc) or by swapping
     * Inf and Fin, this will be done.
     *

     * The BitSets for the state sets are cloned, i.e., modifications of
     * the state sets of the returned acceptance condition will not affect
     * the original generic acceptance condition.
     *
     * @param numStates the number of states in the underlying model/automaton (for generating state sets for true)
     * @return the generated AcceptanceRabin condition, or false on failure
     */
    public AcceptanceRabin toAcceptanceRabin(int numStates) {
        AcceptanceRabin result = new AcceptanceRabin();
        List<AcceptanceGeneric> disjuncts = extractDisjuncts();
        for (AcceptanceGeneric term : disjuncts) {
            RabinPair pair = term.toAcceptanceRabinPair(numStates);
            if (pair == null)
                return null;
            result.add(pair);
        }
        return result;
    }

    /**
     * Attempt to convert this generic acceptance to a Rabin pair.
     *
     * @param numStates the number of states in the underlying model/automaton (for generating state sets for true)
     * @return the generated RabinPair, or false on failure
     */
    private RabinPair toAcceptanceRabinPair(int numStates) {
        BitSet L = null, K = null;
        switch(getKind()) {
            case TRUE:
                L = new BitSet();
                K = new BitSet();
                K.set(0, numStates);
                break;
            case FALSE:
                L = new BitSet();
                L.set(0, numStates);
                K = new BitSet();
                break;
            case AND:
                {
                    AcceptanceGeneric left = getLeft();
                    AcceptanceGeneric right = getRight();
                    if (left.getKind() == ElementType.INF || left.getKind() == ElementType.INF_NOT) {
                        // swap
                        AcceptanceGeneric tmp = left;
                        left = right;
                        right = tmp;
                    }
                    switch(left.getKind()) {
                        case AND:
                        case OR:
                        case FALSE:
                        case TRUE:
                        case INF:
                        case INF_NOT:
                            // not a Rabin condition
                            return null;
                        case FIN:
                            // L = A
                            L = (BitSet) left.getStates().clone();
                            break;
                        case FIN_NOT:
                            L = (BitSet) left.getStates().clone();
                            L.flip(0, numStates);
                            break;
                    }
                    switch(right.getKind()) {
                        case AND:
                        case OR:
                        case FALSE:
                        case TRUE:
                        case FIN:
                        case FIN_NOT:
                            // not a Rabin condition
                            return null;
                        case INF:
                            // K = A
                            K = (BitSet) right.getStates().clone();
                            break;
                        case INF_NOT:
                            K = (BitSet) right.getStates().clone();
                            K.flip(0, numStates);
                            break;
                    }
                    break;
                }
            case FIN:
                // L = A
                L = (BitSet) getStates().clone();
                K = new BitSet();
                K.set(0, numStates);
                break;
            case FIN_NOT:
                L = (BitSet) getStates().clone();
                L.flip(0, numStates);
                K = new BitSet();
                K.set(0, numStates);
                break;
            case INF:
                L = new BitSet();
                // K = A
                K = (BitSet) getStates().clone();
                break;
            case INF_NOT:
                L = new BitSet();
                K = (BitSet) getStates().clone();
                K.flip(0, numStates);
                break;
            case OR:
                // not a Rabin pair
                return null;
        }
        return new AcceptanceRabin.RabinPair(L, K);
    }

    /**
     * Attempt to convert this generic acceptance condition
     * to a Streett condition. If this condition does not have
     * the required form (top-level conjunction with disjunctive pairs),
     * returns {@code null}.
     *

     * If the condition does not syntactically have the required
     * from but can be easily converted to one (e.g., by converting
     * a single Inf(S) to a Fin(true) | Inf(S) etc) or by swapping
     * Inf and Fin, this will be done.
     *

     * The BitSets for the state sets are cloned, i.e., modifications of
     * the state sets of the returned acceptance condition will not affect
     * the original generic acceptance condition.
     *
     * @param numStates the number of states in the underlying model/automaton (for generating state sets for true)
     * @return the generated AcceptanceRabin condition, or false on failure
     */
    public AcceptanceStreett toAcceptanceStreett(int numStates) {
        AcceptanceStreett result = new AcceptanceStreett();
        List<AcceptanceGeneric> conjuncts = extractConjuncts();
        for (AcceptanceGeneric term : conjuncts) {
            StreettPair pair = term.toAcceptanceStreettPair(numStates);
            if (pair == null)
                return null;
            result.add(pair);
        }
        return result;
    }

    /**
     * Attempt to convert this generic acceptance to a Streett pair.
     *
     * @param numStates the number of states in the underlying model/automaton (for generating state sets for true)
     * @return the generated RabinPair, or false on failure
     */
    private StreettPair toAcceptanceStreettPair(int numStates) {
        BitSet R = null, G = null;
        switch(getKind()) {
            case TRUE:
                R = new BitSet();
                G = new BitSet();
                break;
            case FALSE:
                R = new BitSet();
                R.set(0, numStates);
                G = new BitSet();
                break;
            case OR:
                {
                    AcceptanceGeneric left = getLeft();
                    AcceptanceGeneric right = getRight();
                    if (left.getKind() == ElementType.INF || left.getKind() == ElementType.INF_NOT) {
                        // swap
                        AcceptanceGeneric tmp = left;
                        left = right;
                        right = tmp;
                    }
                    switch(left.getKind()) {
                        case AND:
                        case OR:
                        case FALSE:
                        case TRUE:
                        case INF:
                        case INF_NOT:
                            // not a Streett condition
                            return null;
                        case FIN:
                            R = (BitSet) left.getStates().clone();
                            break;
                        case FIN_NOT:
                            R = (BitSet) left.getStates().clone();
                            R.flip(0, numStates);
                            break;
                    }
                    switch(right.getKind()) {
                        case AND:
                        case OR:
                        case FALSE:
                        case TRUE:
                        case FIN:
                        case FIN_NOT:
                            // not a Streett condition
                            return null;
                        case INF:
                            G = (BitSet) right.getStates().clone();
                            break;
                        case INF_NOT:
                            G = (BitSet) right.getStates().clone();
                            G.flip(0, numStates);
                            break;
                    }
                    break;
                }
            case FIN:
                // R = A
                R = (BitSet) getStates().clone();
                G = new BitSet();
                break;
            case FIN_NOT:
                R = (BitSet) getStates().clone();
                R.flip(0, numStates);
                G = new BitSet();
                break;
            case INF:
                R = new BitSet();
                R.set(0, numStates);
                // G = A
                G = (BitSet) getStates().clone();
                break;
            case INF_NOT:
                R = new BitSet();
                R.set(0, numStates);
                G = (BitSet) getStates().clone();
                G.flip(0, numStates);
                break;
            case AND:
                // not a Streett pair
                return null;
        }
        return new AcceptanceStreett.StreettPair(R, G);
    }

    /**
     * Extract the operands of the top-level disjunctions, e.g.,
     * for (A & B) | (C | D)) would return the list [A&B,C,D].
     */
    public List<AcceptanceGeneric> extractDisjuncts() {
        ArrayList<AcceptanceGeneric> result = new ArrayList<AcceptanceGeneric>();
        Stack<AcceptanceGeneric> todo = new Stack<AcceptanceGeneric>();
        todo.add(this);
        while (!todo.isEmpty()) {
            AcceptanceGeneric current = todo.pop();
            switch(current.getKind()) {
                case AND:
                case FALSE:
                case TRUE:
                case FIN:
                case FIN_NOT:
                case INF:
                case INF_NOT:
                    // not a top level disjunction, add to list
                    result.add(current);
                    break;
                case OR:
                    // still a top level disjunction, recurse
                    todo.push(current.getRight());
                    todo.push(current.getLeft());
                    break;
            }
        }
        return result;
    }

    /**
     * Extract the operands of the top-level conjunctions, e.g.,
     * for (A | B) & (C & D)) would return the list [A|B,C,D].
     */
    public List<AcceptanceGeneric> extractConjuncts() {
        ArrayList<AcceptanceGeneric> result = new ArrayList<AcceptanceGeneric>();
        Stack<AcceptanceGeneric> todo = new Stack<AcceptanceGeneric>();
        todo.add(this);
        while (!todo.isEmpty()) {
            AcceptanceGeneric current = todo.pop();
            switch(current.getKind()) {
                case OR:
                case FALSE:
                case TRUE:
                case FIN:
                case FIN_NOT:
                case INF:
                case INF_NOT:
                    // not a top level conjunction, add to list
                    result.add(current);
                    break;
                case AND:
                    // still a top level conjunction, recurse
                    todo.push(current.getRight());
                    todo.push(current.getLeft());
                    break;
            }
        }
        return result;
    }

    @Override
    public String toString() {
        switch(kind) {
            case TRUE:
                return "true";
            case FALSE:
                return "false";
            case AND:
                return "(" + left.toString() + " & " + right.toString() + ")";
            case OR:
                return "(" + left.toString() + " | " + right.toString() + ")";
            case INF:
                return "Inf(" + states.toString() + ")";
            case FIN:
                return "Fin(" + states.toString() + ")";
            case INF_NOT:
                return "Inf(!" + states.toString() + ")";
            case FIN_NOT:
                return "Fin(!" + states.toString() + ")";
            default:
                return null;
        }
    }

    @Override
    public void outputHOAHeader(PrintStream out) {
        List<AcceptanceGeneric> leafNodes = getLeafNodes();
        out.print("Acceptance: " + leafNodes.size() + " ");
        outputHOAFormula(out, 0);
        out.println();
    }

    private int outputHOAFormula(PrintStream out, int nextSetIndex) {
        switch(kind) {
            case AND:
                out.print("(");
                nextSetIndex = left.outputHOAFormula(out, nextSetIndex);
                out.print(")&(");
                nextSetIndex = right.outputHOAFormula(out, nextSetIndex);
                out.print(")");
                return nextSetIndex;
            case OR:
                out.print("(");
                nextSetIndex = left.outputHOAFormula(out, nextSetIndex);
                out.print(")|(");
                nextSetIndex = right.outputHOAFormula(out, nextSetIndex);
                out.print(")");
                return nextSetIndex;
            case TRUE:
                out.print("t");
                return nextSetIndex;
            case FALSE:
                out.print("f");
                return nextSetIndex;
            case FIN:
                out.print("Fin(" + nextSetIndex + ")");
                return nextSetIndex + 1;
            case FIN_NOT:
                out.print("Fin(!" + nextSetIndex + ")");
                return nextSetIndex + 1;
            case INF:
                out.print("Inf(" + nextSetIndex + ")");
                return nextSetIndex + 1;
            case INF_NOT:
                out.print("Inf(!" + nextSetIndex + ")");
                return nextSetIndex + 1;
        }
        throw new UnsupportedOperationException("Unknown kind");
    }
}


switch(value) {
            case 0:
                return "Normal (no macro)";
            case 1:
                return "Macro";
            default:
                return "Unknown (" + value + ")";
        }

/*
 * closed source licenses.  I do ask that you leave this header in tact.
 *
 * If you make modifications to this code that you think would benefit the
 * wider community, please send me a copy and I'll post it on my site.
 *
 * If you make use of this code, I'd appreciate hearing about it.
 *   metadata_extractor [at] drewnoakes [dot] com
 * Latest version of this software kept at
 *   http://example.com
 */
package sage.media.exif.metadata.exif;

import sage.media.exif.metadata.Directory;
import sage.media.exif.metadata.MetadataException;
import sage.media.exif.metadata.TagDescriptor;

/**
 * Provides human-readable string represenations of tag values stored in a OlympusMakernoteDirectory.
 */
public class OlympusMakernoteDescriptor extends TagDescriptor {

    public OlympusMakernoteDescriptor(Directory directory) {
        super(directory);
    }

    public String getDescription(int tagType) throws MetadataException {
        switch(tagType) {
            case OlympusMakernoteDirectory.TAG_OLYMPUS_SPECIAL_MODE:
                return getSpecialModeDescription();
            case OlympusMakernoteDirectory.TAG_OLYMPUS_JPEG_QUALITY:
                return getJpegQualityDescription();
            case OlympusMakernoteDirectory.TAG_OLYMPUS_MACRO_MODE:
                return getMacroModeDescription();
            case OlympusMakernoteDirectory.TAG_OLYMPUS_DIGI_ZOOM_RATIO:
                return getDigiZoomRatioDescription();
            default:
                return _directory.getString(tagType);
        }
    }

    public String getDigiZoomRatioDescription() throws MetadataException {
        if (!_directory.containsTag(OlympusMakernoteDirectory.TAG_OLYMPUS_DIGI_ZOOM_RATIO))
            return null;
        int value = _directory.getInt(OlympusMakernoteDirectory.TAG_OLYMPUS_DIGI_ZOOM_RATIO);
        switch(value) {
            case 0:
                return "Normal";
            case 2:
                return "Digital 2x Zoom";
            default:
                return "Unknown (" + value + ")";
        }
    }

    public String getMacroModeDescription() throws MetadataException {
        if (!_directory.containsTag(OlympusMakernoteDirectory.TAG_OLYMPUS_MACRO_MODE))
            return null;
        int value = _directory.getInt(OlympusMakernoteDirectory.TAG_OLYMPUS_MACRO_MODE);

    }

    public String getJpegQualityDescription() throws MetadataException {
        if (!_directory.containsTag(OlympusMakernoteDirectory.TAG_OLYMPUS_JPEG_QUALITY))
            return null;
        int value = _directory.getInt(OlympusMakernoteDirectory.TAG_OLYMPUS_JPEG_QUALITY);
        switch(value) {
            case 1:
                return "SQ";
            case 2:
                return "HQ";
            case 3:
                return "SHQ";
            default:
                return "Unknown (" + value + ")";
        }
    }

    public String getSpecialModeDescription() throws MetadataException {
        if (!_directory.containsTag(OlympusMakernoteDirectory.TAG_OLYMPUS_SPECIAL_MODE))
            return null;
        int[] values = _directory.getIntArray(OlympusMakernoteDirectory.TAG_OLYMPUS_SPECIAL_MODE);
        StringBuffer desc = new StringBuffer();
        switch(values[0]) {
            case 0:
                desc.append("Normal picture taking mode");
                break;
            case 1:
                desc.append("Unknown picture taking mode");
                break;
            case 2:
                desc.append("Fast picture taking mode");
                break;
            case 3:
                desc.append("Panorama picture taking mode");
                break;
            default:
                desc.append("Unknown picture taking mode");
                break;
        }
        desc.append(" - ");
        switch(values[1]) {
            case 0:
                desc.append("Unknown sequence number");
                break;
            case 1:
                desc.append("1st in a sequnce");
                break;
            case 2:
                desc.append("2nd in a sequence");
                break;
            case 3:
                desc.append("3rd in a sequence");
                break;
            default:
                desc.append(values[1]);
                desc.append("th in a sequence");
                break;
        }
        switch(values[2]) {
            case 1:
                desc.append("Left to right panorama direction");
                break;
            case 2:
                desc.append("Right to left panorama direction");
                break;
            case 3:
                desc.append("Bottom to top panorama direction");
                break;
            case 4:
                desc.append("Top to bottom panorama direction");
                break;
        }
        return desc.toString();
    }
}


switch(position) {
            case 3:
                return RecycleViewFragment.newInstance(position + 1);
            default:
                return PlaceholderFragment.newInstance(position + 1);
        }

package com.github.captain_miao.optionroundcardview;

import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;

/**
 * @author YanLu
 * @since 17/9/3
 */
public class SectionsPagerAdapter extends FragmentPagerAdapter {

    public SectionsPagerAdapter(FragmentManager fm) {
        super(fm);
    }

    @Override
    public Fragment getItem(int position) {
        // getItem is called to instantiate the fragment for the given page.

    }

    @Override
    public int getCount() {
        // Show 3 total pages.
        return 4;
    }

    @Override
    public CharSequence getPageTitle(int position) {
        switch(position) {
            case 0:
                return "Top corner";
            case 1:
                return "Bottom corner";
            case 2:
                return "Full corner";
            case 3:
                return "RecycleView";
        }
        return null;
    }
}


switch(ev.getType()) {
            case 1:
            case 2:
                LogUtil.d(TAG, "cancel event");
                if (ev.getArgs()[0] == this.mTaskRequest.getReqId()) {
                    this.mTaskRequest.setCancel();
                    return true;
                }
                break;
        }

package huawei.android.security.facerecognition.task;

import huawei.android.security.facerecognition.FaceRecognizeEvent;
import huawei.android.security.facerecognition.base.HwSecurityMsgCenter;
import huawei.android.security.facerecognition.base.HwSecurityTaskBase;
import huawei.android.security.facerecognition.base.HwSecurityTaskBase.EventListener;
import huawei.android.security.facerecognition.base.HwSecurityTaskBase.RetCallback;
import huawei.android.security.facerecognition.base.HwSecurityTaskBase.TimerOutProc;
import huawei.android.security.facerecognition.base.HwSecurityTimerTask;
import huawei.android.security.facerecognition.request.FaceRecognizeRequest;
import huawei.android.security.facerecognition.utils.LogUtil;

public class RetryWaitTask extends FaceRecognizeTask implements EventListener {

    private static final String TAG = "RetryWaitTask";

    private static final long TIMEOUT = 100;

    private int mReqType;

    TimerOutProc mTimeoutProc = new TimerOutProc() {

        public void onTimerOut() {
            if (RetryWaitTask.this.mTaskRequest.isCanceled()) {
                RetryWaitTask.this.endWithResult(2);
            } else {
                RetryWaitTask.this.endWithResult(0);
            }
        }
    };

    private HwSecurityTimerTask mTimer;

    public RetryWaitTask(HwSecurityTaskBase parent, RetCallback callback, FaceRecognizeRequest request) {
        super(parent, callback, request);
        this.mReqType = request.getType();
        this.mTimer = new HwSecurityTimerTask();
        if (1 == this.mReqType) {
            HwSecurityMsgCenter.staticRegisterEvent(1, this, this);
        } else if (this.mReqType == 0) {
            HwSecurityMsgCenter.staticRegisterEvent(2, this, this);
        }
    }

    public boolean onEvent(FaceRecognizeEvent ev) {

        return false;
    }

    public int doAction() {
        LogUtil.i("", "start RetryWaitTask");
        this.mTimer.setTimeout(TIMEOUT, this.mTimeoutProc);
        return -1;
    }

    public void onStop() {
        this.mTimer.cancel();
        if (1 == this.mReqType) {
            HwSecurityMsgCenter.staticUnregisterEvent(1, this);
        } else if (this.mReqType == 0) {
            HwSecurityMsgCenter.staticUnregisterEvent(2, this);
        }
    }
}


switch(position) {
            case LEFT:
                return optionalLeftChild;
            case RIGHT:
                return optionalRightChild;
            default:
                throw new IllegalStateException("Unknown position: " + position);
        }

package it.unibz.inf.ontop.iq.impl.tree;

import com.google.common.collect.ImmutableList;
import it.unibz.inf.ontop.iq.node.BinaryOrderedOperatorNode;
import it.unibz.inf.ontop.iq.exception.IllegalTreeUpdateException;
import it.unibz.inf.ontop.iq.node.QueryNode;
import java.util.Map;
import java.util.Optional;
import java.util.stream.Stream;

public class BinaryChildrenRelation implements ChildrenRelation {

    private final TreeNode parent;

    private Optional<TreeNode> optionalLeftChild;

    private Optional<TreeNode> optionalRightChild;

    protected BinaryChildrenRelation(TreeNode parent) {
        if (!(parent.getQueryNode() instanceof BinaryOrderedOperatorNode)) {
            throw new IllegalArgumentException("The StandardChildrenRelation requires " + "BinaryAsymmetricOperatorNode as parents");
        }
        this.parent = parent;
        this.optionalLeftChild = Optional.empty();
        this.optionalRightChild = Optional.empty();
    }

    private BinaryChildrenRelation(TreeNode parent, Optional<TreeNode> optionalLeftChild, Optional<TreeNode> optionalRightChild) {
        this.parent = parent;
        this.optionalLeftChild = optionalLeftChild;
        this.optionalRightChild = optionalRightChild;
    }

    @Override
    public TreeNode getParent() {
        return parent;
    }

    @Override
    public ImmutableList<TreeNode> getChildren() {
        ImmutableList.Builder<TreeNode> builder = ImmutableList.builder();
        if (optionalLeftChild.isPresent()) {
            builder.add(optionalLeftChild.get());
        }
        if (optionalRightChild.isPresent()) {
            builder.add(optionalRightChild.get());
        }
        return builder.build();
    }

    @Override
    public Stream<TreeNode> getChildrenStream() {
        return Stream.of(optionalLeftChild, optionalRightChild).filter(Optional::isPresent).map(Optional::get);
    }

    @Override
    public boolean contains(TreeNode node) {
        return getChildren().contains(node);
    }

    @Override
    public void addChild(TreeNode childNode, Optional<BinaryOrderedOperatorNode.ArgumentPosition> optionalPosition, boolean canReplace) throws IllegalTreeUpdateException {
        if (!optionalPosition.isPresent()) {
            throw new IllegalArgumentException("The BinaryChildrenRelation requires argument positions");
        }
        switch(optionalPosition.get()) {
            case LEFT:
                if (optionalLeftChild.isPresent() && (!canReplace) && (optionalLeftChild.get() != childNode)) {
                    throw new IllegalTreeUpdateException("Left child node is already present");
                } else {
                    optionalLeftChild = Optional.of(childNode);
                }
                break;
            case RIGHT:
                if (optionalRightChild.isPresent() && (!canReplace) && (optionalRightChild.get() != childNode)) {
                    throw new IllegalTreeUpdateException("Right child node is already present");
                } else {
                    optionalRightChild = Optional.of(childNode);
                }
                break;
        }
    }

    @Override
    public void replaceChild(TreeNode formerChild, TreeNode newChild) {
        if (optionalLeftChild.isPresent() && (optionalLeftChild.get() == formerChild)) {
            optionalLeftChild = Optional.of(newChild);
        } else if (optionalRightChild.isPresent() && (optionalRightChild.get() == formerChild)) {
            optionalRightChild = Optional.of(newChild);
        } else {
            throw new IllegalArgumentException("Unknown former child " + formerChild);
        }
    }

    @Override
    public void removeChild(TreeNode childNode) {
        if (optionalLeftChild.isPresent() && (optionalLeftChild.get() == childNode)) {
            optionalLeftChild = Optional.empty();
        }
        // Compatible with the crazy case where the same node appears on the two sides.
        if (optionalRightChild.isPresent() && (optionalRightChild.get() == childNode)) {
            optionalRightChild = Optional.empty();
        }
    }

    @Override
    public ImmutableList<QueryNode> getChildQueryNodes() {
        ImmutableList.Builder<QueryNode> builder = ImmutableList.builder();
        for (TreeNode treeNode : getChildren()) {
            builder.add(treeNode.getQueryNode());
        }
        return builder.build();
    }

    @Override
    public Stream<QueryNode> getChildQueryNodeStream() {
        return getChildrenStream().map(TreeNode::getQueryNode);
    }

    @Override
    public Optional<BinaryOrderedOperatorNode.ArgumentPosition> getOptionalPosition(TreeNode childNode) {
        if (optionalLeftChild.isPresent() && (optionalLeftChild.get() == childNode)) {
            return Optional.of(BinaryOrderedOperatorNode.ArgumentPosition.LEFT);
        } else if (optionalRightChild.isPresent() && (optionalRightChild.get() == childNode)) {
            return Optional.of(BinaryOrderedOperatorNode.ArgumentPosition.RIGHT);
        } else {
            throw new IllegalArgumentException(childNode.getQueryNode() + " does not appear as a child.");
        }
    }

    @Override
    public Optional<TreeNode> getChild(BinaryOrderedOperatorNode.ArgumentPosition position) {

    }

    @Override
    public ChildrenRelation clone(Map<QueryNode, TreeNode> newNodeIndex) {
        return new BinaryChildrenRelation(parent.findNewTreeNode(newNodeIndex), optionalLeftChild.map(n -> n.findNewTreeNode(newNodeIndex)), optionalRightChild.map(n -> n.findNewTreeNode(newNodeIndex)));
    }

    @Override
    public ChildrenRelation convertToBinaryChildrenRelation() {
        return this;
    }

    @Override
    public ChildrenRelation convertToStandardChildrenRelation() {
        StandardChildrenRelation newRelation = new StandardChildrenRelation(parent);
        getChildrenStream().forEach(c -> newRelation.addChild(c, Optional.empty(), false));
        return newRelation;
    }
}


switch(args.size()) {
                    case 0:
                        return VOID;
                    case 1:
                        return args.get(0);
                    default:
                        return NodeFactory.makeTupleType(NodeFactory.makeSpan("impossible", args), args);
                }

/**
 * ****************************************************************************
 *     All rights reserved.
 *
 *     Use is subject to license terms.
 *
 *     This distribution may include materials developed by third parties.
 *
 * ****************************************************************************
 */
package com.sun.fortress.compiler;

import com.sun.fortress.nodes.*;
import com.sun.fortress.nodes_util.NodeFactory;
import com.sun.fortress.nodes_util.NodeUtil;
import com.sun.fortress.nodes_util.Span;
import com.sun.fortress.useful.NI;
import java.util.Collections;
import java.util.List;
import java.util.ArrayList;
import java.util.Map;
import java.util.LinkedHashMap;
import edu.rice.cs.plt.lambda.Lambda;
import edu.rice.cs.plt.iter.IterUtil;
import edu.rice.cs.plt.collect.CollectUtil;
import edu.rice.cs.plt.tuple.Option;
import static com.sun.fortress.nodes_util.NodeFactory.*;
import static com.sun.fortress.compiler.WellKnownNames.*;
import com.sun.fortress.Shell;

/**
 * General-purpose type constants and constructors/destructors for types.
 * Unlike the methods in {@link NodeFactory}, these pay no attention to the
 * {@code span} and {@code parenthesized} AST fields, and are more "aware"
 * of the semantics of Fortress types.
 */
public final class Types {

    private Types() {
    }

    private static Span span = NodeFactory.internalSpan;

    public static final Id ANY_NAME = makeId(span, anyTypeLibrary(), "Any");

    public static final Id ARRAY_NAME = makeId(span, fortressLibrary(), "Array");

    // TODO: Replace ImmutableArray with ImmutableHeapSequence when
    // ImmutableHeapSequence is put into the libraries.
    public static final Id IMMUTABLE_HEAP_SEQ_NAME = makeId(span, fortressLibrary(), "ImmutableArray");

    public static final AnyType ANY = NodeFactory.makeAnyType(span);

    public static final BottomType BOTTOM = NodeFactory.makeBottomType(span);

    public static final TraitType OBJECT = makeTraitType(span, fortressBuiltin(), "Object");

    public static final UnknownType UNKNOWN = NodeFactory.makeUnknownType();

    public static final Type BOTTOM_DOMAIN = BOTTOM;

    public static final ArrowType BOTTOM_ARROW = NodeFactory.makeArrowType(NodeFactory.typeSpan, ANY, BOTTOM);

    public static final TupleType VOID = NodeFactory.makeVoidType(span);

    public static final TraitType FLOAT_LITERAL = makeTraitType(span, fortressBuiltin(), "FloatLiteral");

    public static final TraitType INT_LITERAL = makeTraitType(span, fortressBuiltin(), "IntLiteral");

    public static final TraitType ZZ32 = makeTraitType(span, fortressLibrary(), "ZZ32");

    public static final TraitType BOOLEAN = makeTraitType(span, fortressBuiltin(), "Boolean");

    public static final TraitType CHARACTER = makeTraitType(span, fortressBuiltin(), "Character");

    public static TraitType STRING = makeTraitType(span, fortressLibrary(), "String");

    public static TraitType JAVASTRING = makeTraitType(span, fortressLibrary(), "JavaString");

    public static TraitType EXCEPTION = makeTraitType(span, fortressLibrary(), "Exception");

    public static TraitType CHECKED_EXCEPTION = makeTraitType(span, fortressLibrary(), "CheckedException");

    public static final TraitType REGION = makeTraitType(span, fortressLibrary(), "Region");

    /**
     * It's necessary to set STRING when using the compiler libraries because the location of String
     * in the compiler libraries differs from its location in the full libraries.
     * Similarly for JavaString and Exception and CheckedException.
     */
    public static void useCompilerLibraries() {
        STRING = makeTraitType(span, fortressBuiltin(), "String");
        JAVASTRING = makeTraitType(span, fortressBuiltin(), "JavaString");
        EXCEPTION = makeTraitType(span, fortressBuiltin(), "Exception");
        CHECKED_EXCEPTION = makeTraitType(span, fortressBuiltin(), "CheckedException");
    }

    public static void useFortressLibraries() {
        STRING = makeTraitType(span, fortressLibrary(), "String");
        JAVASTRING = makeTraitType(span, fortressLibrary(), "JavaString");
        EXCEPTION = makeTraitType(span, fortressLibrary(), "Exception");
        CHECKED_EXCEPTION = makeTraitType(span, fortressLibrary(), "CheckedException");
    }

    public static void useTypeCheckerLibraries() {
        useCompilerLibraries();
    }

    public static final LabelType LABEL = NodeFactory.makeLabelType(span);

    public static final TraitType makeVarargsParamType(Type varargsType) {
        return makeTraitType(IMMUTABLE_HEAP_SEQ_NAME, makeTypeArg(varargsType), makeTypeArg(ZZ32));
    }

    public static TraitType makeThreadType(Type typeArg) {
        return makeTraitType(makeId(span, fortressBuiltin(), "Thread"), makeTypeArg(typeArg));
    }

    public static Id getArrayKName(int k) {
        String name = "Array" + k;
        return makeId(span, fortressLibrary(), name);
    }

    public static TraitType makeArrayType(Type elem, Type indexed) {
        return makeTraitType(ARRAY_NAME, makeTypeArg(elem), makeTypeArg(indexed));
    }

    public static TraitType makeArrayKType(int k, List<StaticArg> args) {
        return makeTraitType(getArrayKName(k), args);
    }

    /**
     * Create a type {@code FortressLibrary.Generator[\typeArg\]}.
     */
    public static TraitType makeGeneratorType(Type typeArg) {
        return makeTraitType(makeId(span, fortressLibrary(), "Generator"), makeTypeArg(typeArg));
    }

    /**
     * Create a type {@code CompilerLibrary.GeneratorZZ32}.
     */
    public static TraitType makeGeneratorZZ32Type(Span span) {
        return makeTraitType(makeId(span, fortressLibrary(), "GeneratorZZ32"));
    }

    /**
     * Create a type {@code FortressLibrary.Condition[\typeArg\]}.
     */
    public static TraitType makeConditionType(Type typeArg) {
        return makeTraitType(makeId(span, fortressLibrary(), "Condition"), makeTypeArg(typeArg));
    }

    /**
     * Construct the appropriate type from a list of union elements.
     */
    public static Type makeUnion(Iterable<Type> disjuncts) {
        return MAKE_UNION.value(disjuncts);
    }

    /**
     * Construct the appropriate type from a list of union elements.
     */
    public static final Lambda<Iterable<Type>, Type> MAKE_UNION = new Lambda<Iterable<Type>, Type>() {

        public Type value(Iterable<Type> ts) {
            switch(IterUtil.sizeOf(ts, 2)) {
                case 0:
                    return BOTTOM;
                case 1:
                    return IterUtil.first(ts);
                default:
                    {
                        List<Type> l = CollectUtil.makeList(ts);
                        return NodeFactory.makeUnionType(NodeFactory.makeSpan("impossible", l), false, l);
                    }
            }
        }
    };

    /**
     * Construct the appropriate type from a list of intersection elements.
     */
    public static Type makeIntersection(Iterable<Type> conjuncts) {
        return MAKE_INTERSECTION.value(conjuncts);
    }

    /**
     * Construct the appropriate type from a list of intersection elements.
     */
    public static final Lambda<Iterable<Type>, Type> MAKE_INTERSECTION = new Lambda<Iterable<Type>, Type>() {

        public Type value(Iterable<Type> ts) {
            switch(IterUtil.sizeOf(ts, 2)) {
                case 0:
                    return ANY;
                case 1:
                    return IterUtil.first(ts);
                default:
                    {
                        List<Type> l = CollectUtil.makeList(ts);
                        return NodeFactory.makeIntersectionType(NodeFactory.makeSpan("impossible", l), l);
                    }
            }
        }
    };

    /**
     * Treat an arbitrary type as a union and enumerate its elements.
     */
    public static Iterable<Type> disjuncts(Type t) {
        return t.accept(DISJUNCTS);
    }

    /**
     * Treat an arbitrary type as a union and enumerate its elements.
     */
    public static final NodeVisitorLambda<Iterable<Type>> DISJUNCTS = new NodeAbstractVisitor<Iterable<Type>>() {

        @Override
        public Iterable<Type> forType(Type t) {
            return IterUtil.singleton(t);
        }

        @Override
        public Iterable<Type> forUnionType(UnionType t) {
            return t.getElements();
        }

        @Override
        public Iterable<Type> forBottomType(BottomType t) {
            return IterUtil.empty();
        }
    };

    /**
     * Treat an arbitrary type as an intersection and enumerate its elements.
     */
    public static Iterable<Type> conjuncts(Type t) {
        return t.accept(CONJUNCTS);
    }

    /**
     * Treat an arbitrary type as an intersection and enumerate its elements.
     */
    public static final NodeVisitorLambda<Iterable<Type>> CONJUNCTS = new NodeAbstractVisitor<Iterable<Type>>() {

        @Override
        public Iterable<Type> forType(Type t) {
            return IterUtil.singleton(t);
        }

        @Override
        public Iterable<Type> forIntersectionType(IntersectionType t) {
            return t.getElements();
        }
    };

    /**
     * Construct the appropriate type (void, a tuple, or the type itself) from a list of
     * tuple elements.
     */
    public static Type makeTuple(Iterable<Type> elements) {
        return MAKE_TUPLE.value(elements);
    }

    /**
     * Construct the appropriate type from a list of tuple elements.
     */
    public static final Lambda<Iterable<Type>, Type> MAKE_TUPLE = new Lambda<Iterable<Type>, Type>() {

        public Type value(Iterable<Type> ts) {
            switch(IterUtil.sizeOf(ts, 2)) {
                case 0:
                    return VOID;
                case 1:
                    return IterUtil.first(ts);
                default:
                    {
                        List<Type> l = CollectUtil.makeList(ts);
                        return NodeFactory.makeTupleType(NodeFactory.makeSpan("impossible", l), l);
                    }
            }
        }
    };

    /**
     * Produce the union disjunct of the given vararg tuple at a certain arity.
     * This is the arity+1st element of a union equivalent to the vararg tuple
     * like the following:

     *
(T...) = () | T | (T, T) | (T, T, T) | ...

     *
(A, B, C...) = Bottom | Bottom | (A, B) | (A, B, C) | ...

     *

     * Note that the result is defined for all arities, but may sometimes be
     * Bottom.
     */
    public static Type varargDisjunct(TupleType t, int arity) {
        List<Type> base = t.getElements();
        int baseSize = base.size();
        if (baseSize > arity) {
            return BOTTOM;
        } else {
            Iterable<Type> rest = IterUtil.copy(t.getVarargs().unwrap(), arity - baseSize);
            return makeTuple(IterUtil.compose(base, rest));
        }
    }

    /**
     * Produce a type representing a Domain with any keyword types removed.
     * May return a TupleType, a VoidType, a TupleType with varargs, or a type
     * representing a singleton argument.
     */
    public static Type stripKeywords(Type d) {
        if (d instanceof TupleType) {
            TupleType _d = (TupleType) d;
            if (NodeUtil.hasVarargs(_d)) {
                return NodeFactory.makeTupleType(NodeFactory.makeSpan(_d.getElements(), _d.getVarargs().unwrap()), false, _d.getElements(), _d.getVarargs(), Collections.<KeywordType>emptyList());
            } else {
                List<Type> args = _d.getElements();

            }
        } else
            return d;
    }

    /**
     * Produce a map from keyword names to types.  The iteration order of the
     * map is identical to that of the KeywordType list.
     */
    public static Map<Id, Type> extractKeywords(Type d) {
        if (d instanceof TupleType) {
            TupleType _d = (TupleType) d;
            // Don't waste time allocating a map if it will be empty (the usual case)
            if (_d.getKeywords().isEmpty()) {
                return Collections.<Id, Type>emptyMap();
            } else {
                Map<Id, Type> result = new LinkedHashMap<Id, Type>(8);
                for (KeywordType k : _d.getKeywords()) {
                    result.put(k.getName(), k.getKeywordType());
                }
                return result;
            }
        } else
            return Collections.<Id, Type>emptyMap();
    }

    /**
     * Construct a Domain from a single type representing the required arguments
     * and a keywords map representing the keyword arguments.
     */
    public static Type makeDomain(Type argsType, Map<Id, Type> keywords) {
        List<KeywordType> keywordList = new ArrayList<KeywordType>(keywords.size());
        for (Map.Entry<Id, Type> entry : keywords.entrySet()) {
            keywordList.add(NodeFactory.makeKeywordType(NodeFactory.makeSpan(entry.getKey(), entry.getValue()), entry.getKey(), entry.getValue()));
        }
        return makeDomain(argsType, keywordList);
    }

    /**
     * Construct a Domain from a single type representing the required arguments
     * and a list of KeywordTypes.  Unlike {@link NodeFactory#makeDomain}, does
     * not assume that {@code argsType} was produced by the parser.
     */
    public static Type makeDomain(Type argsType, final List<KeywordType> keywords) {
        return argsType.accept(new NodeAbstractVisitor<Type>() {

            @Override
            public Type forTupleType(TupleType t) {
                if (!NodeUtil.hasVarargs(t))
                    return NodeFactory.makeTupleType(NodeFactory.makeSpan(t, keywords), false, t.getElements(), Option.<Type>none(), keywords);
                else
                    return NodeFactory.makeTupleType(NodeFactory.makeSpan(t, keywords), false, t.getElements(), t.getVarargs(), keywords);
            }

            @Override
            public Type forType(Type t) {
                if (keywords.isEmpty())
                    return t;
                else
                    return NodeFactory.makeTupleType(NodeFactory.makeSpan(t, keywords), false, Collections.singletonList(t), Option.<Type>none(), keywords);
            }
        });
    }

    /**
     * Given A and Op, returns the type
     * TotalOperatorOrder[\A,<,<=,>=,>,Op]
     */
    public static Type makeTotalOperatorOrder(Type A, Op op) {
        return NI.nyi();
    }
}


switch(httpResult.getCode()) {
            case 0:
                message = "ERROR:解析失败";
                break;
            case -1:
                message = "ERROR:服务器通讯故障";
                break;
            default:
                message = "ERROR:网络连接异常";
        }

package com.lance.freebook.Data.Retrofit;

import com.lance.freebook.MVP.Entity.HttpResult;

/**
 * 异常类
 * 按照自己公司的接口需求来  不可直接套用
 * 使用需谨慎
 * 有什么问题可以联系我
 * 邮箱80945540@qq.com
 */
public class ApiException extends RuntimeException {

    public ApiException(HttpResult httpResult) {
        this(getApiExceptionMessage(httpResult));
    }

    public ApiException(String detailMessage) {
        super(detailMessage);
    }

    /**
     * 对服务器接口传过来的错误信息进行统一处理
     * 免除在Activity的过多的错误判断
     */
    private static String getApiExceptionMessage(HttpResult httpResult) {
        String message = "";