text:
package com.mobileer.oboetester;

import android.content.Context;
import android.media.AudioManager;
import android.media.audiofx.AcousticEchoCanceler;
import android.media.audiofx.AutomaticGainControl;
import android.media.audiofx.BassBoost;
import android.media.audiofx.LoudnessEnhancer;
import android.util.AttributeSet;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.SeekBar;
import android.widget.Spinner;
import android.widget.TableRow;
import android.widget.TextView;
import android.widget.LinearLayout;
import android.util.Log;

import com.mobileer.audio_device.AudioDeviceListEntry;
import com.mobileer.audio_device.AudioDeviceSpinner;

/**
 * View for Editing a requested StreamConfiguration
 * and displaying the actual StreamConfiguration.
 */

public class StreamConfigurationView extends LinearLayout {
    private static final String TAG = "StreamConfigurationView";

    protected Spinner mNativeApiSpinner;
    private TextView mActualNativeApiView;

    private TextView mActualMMapView;
    private CheckBox mRequestedMMapView;
    private TextView mActualExclusiveView;
    private TextView mActualPerformanceView;
    private Spinner  mPerformanceSpinner;
    private CheckBox mRequestedExclusiveView;
    private CheckBox mChannelConversionBox;
    private CheckBox mFormatConversionBox;
    private Spinner  mChannelCountSpinner;
    private TextView mActualChannelCountView;
    private Spinner mChannelMaskSpinner;
    private TextView mActualChannelMaskView;
    private TextView mActualFormatView;

    private TableRow mInputPresetTableRow;
    private Spinner  mInputPresetSpinner;
    private TextView mActualInputPresetView;

    private TableRow mUsageTableRow;
    private Spinner  mUsageSpinner;
    private TextView mActualUsageView;

    private TableRow mContentTypeTableRow;
    private Spinner  mContentTypeSpinner;
    private TextView mActualContentTypeView;

    private Spinner  mFormatSpinner;
    private Spinner  mSampleRateSpinner;
    private Spinner  mRateConversionQualitySpinner;
    private TextView mActualSampleRateView;
    private LinearLayout mHideableView;

    private AudioDeviceSpinner mDeviceSpinner;
    private TextView mActualSessionIdView;
    private CheckBox mRequestAudioEffect;

    private TextView mStreamInfoView;
    private TextView mStreamStatusView;
    private TextView mOptionExpander;
    private String mHideSettingsText;
    private String mShowSettingsText;

    private LinearLayout mInputEffectsLayout;
    private LinearLayout mOutputEffectsLayout;

    private CheckBox mAutomaticGainControlCheckBox;
    private CheckBox mAcousticEchoCancelerCheckBox;
    private TextView mBassBoostTextView;
    private SeekBar mBassBoostSeekBar;
    private TextView mLoudnessEnhancerTextView;
    private SeekBar mLoudnessEnhancerSeekBar;

    private boolean mIsChannelMaskLastSelected;

    private boolean misOutput;

    private BassBoost mBassBoost;
    private LoudnessEnhancer mLoudnessEnhancer;
    private AcousticEchoCanceler mAcousticEchoCanceler;
    private AutomaticGainControl mAutomaticGainControl;

    // Create an anonymous implementation of OnClickListener
    private View.OnClickListener mToggleListener = new View.OnClickListener() {
        public void onClick(View v) {
            if (mHideableView.isShown()) {
                hideSettingsView();
            } else {
                showSettingsView();
            }
        }
    };

    public static String yesOrNo(boolean b) {
        return b ?  "YES" : "NO";
    }

    private void updateSettingsViewText() {
        if (mHideableView.isShown()) {
            mOptionExpander.setText(mHideSettingsText);
        } else {
            mOptionExpander.setText(mShowSettingsText);
        }
    }

    public void showSettingsView() {
        mHideableView.setVisibility(View.VISIBLE);
        updateSettingsViewText();
    }

    public void hideSampleRateMenu() {
        if (mSampleRateSpinner != null) {
            mSampleRateSpinner.setVisibility(View.GONE);
        }
    }

    public void hideSettingsView() {
        mHideableView.setVisibility(View.GONE);
        updateSettingsViewText();
    }

    public StreamConfigurationView(Context context) {
        super(context);
        initializeViews(context);
    }

    public StreamConfigurationView(Context context, AttributeSet attrs) {
        super(context, attrs);
        initializeViews(context);
    }

    public StreamConfigurationView(Context context,
                                   AttributeSet attrs,
                                   int defStyle) {
        super(context, attrs, defStyle);
        initializeViews(context);
    }

    /**
     * Inflates the views in the layout.
     *
     * @param context
     *           the current context for the view.
     */
    private void initializeViews(Context context) {
        LayoutInflater inflater = (LayoutInflater) context
                .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        inflater.inflate(R.layout.stream_config, this);

        mHideSettingsText = getResources().getString(R.string.hint_hide_settings);
        mShowSettingsText = getResources().getString(R.string.hint_show_settings);

        mHideableView = (LinearLayout) findViewById(R.id.hideableView);

        mOptionExpander = (TextView) findViewById(R.id.toggle_stream_config);
        mOptionExpander.setOnClickListener(mToggleListener);

        mNativeApiSpinner = (Spinner) findViewById(R.id.spinnerNativeApi);
        mNativeApiSpinner.setSelection(StreamConfiguration.NATIVE_API_UNSPECIFIED);

        mActualNativeApiView = (TextView) findViewById(R.id.actualNativeApi);

        mChannelConversionBox = (CheckBox) findViewById(R.id.checkChannelConversion);

        mFormatConversionBox = (CheckBox) findViewById(R.id.checkFormatConversion);

        mActualMMapView = (TextView) findViewById(R.id.actualMMap);
        mRequestedMMapView = (CheckBox) findViewById(R.id.requestedMMapEnable);
        boolean mmapSupported = NativeEngine.isMMapSupported();
        mRequestedMMapView.setEnabled(mmapSupported);
        mRequestedMMapView.setChecked(mmapSupported);

        mActualExclusiveView = (TextView) findViewById(R.id.actualExclusiveMode);
        mRequestedExclusiveView = (CheckBox) findViewById(R.id.requestedExclusiveMode);

        boolean mmapExclusiveSupported = NativeEngine.isMMapExclusiveSupported();
        mRequestedExclusiveView.setEnabled(mmapExclusiveSupported);
        mRequestedExclusiveView.setChecked(mmapExclusiveSupported);

        mActualSessionIdView = (TextView) findViewById(R.id.sessionId);
        mRequestAudioEffect = (CheckBox) findViewById(R.id.requestAudioEffect);

        mOutputEffectsLayout = (LinearLayout) findViewById(R.id.outputEffects);
        mInputEffectsLayout = (LinearLayout) findViewById(R.id.inputEffects);

        mRequestAudioEffect.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                onRequestAudioEffectClicked(((CheckBox) view).isChecked());
            }
        });

        mAutomaticGainControlCheckBox = (CheckBox) findViewById(R.id.checkBoxAutomaticGainControl);
        mAcousticEchoCancelerCheckBox = (CheckBox) findViewById(R.id.checkBoxAcousticEchoCanceler);
        mBassBoostTextView = (TextView) findViewById(R.id.textBassBoost);
        mBassBoostSeekBar = (SeekBar) findViewById(R.id.seekBarBassBoost);
        mLoudnessEnhancerTextView = (TextView) findViewById(R.id.textLoudnessEnhancer);
        mLoudnessEnhancerSeekBar = (SeekBar) findViewById(R.id.seekBarLoudnessEnhancer);

        mAutomaticGainControlCheckBox.setEnabled(AutomaticGainControl.isAvailable());
        mAcousticEchoCancelerCheckBox.setEnabled(AcousticEchoCanceler.isAvailable());

        mBassBoostSeekBar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
            public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
                onBassBoostSeekBarChanged(progress);
            }

            @Override
            public void onStartTrackingTouch(SeekBar seekBar) {
            }

            @Override
            public void onStopTrackingTouch(SeekBar seekBar) {
            }
        });

        mLoudnessEnhancerSeekBar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
            public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
                onLoudnessEnhancerSeekBarChanged(progress);
            }

            @Override
            public void onStartTrackingTouch(SeekBar seekBar) {
            }

            @Override
            public void onStopTrackingTouch(SeekBar seekBar) {
            }
        });

        mAutomaticGainControlCheckBox.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                onAutomaticGainControlCheckBoxChanged(isChecked);
            }
        });

        mAcousticEchoCancelerCheckBox.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                onAcousticEchoCancelerCheckBoxChanged(isChecked);
            }
        });

        mActualSampleRateView = (TextView) findViewById(R.id.actualSampleRate);
        mSampleRateSpinner = (Spinner) findViewById(R.id.spinnerSampleRate);
        mActualChannelCountView = (TextView) findViewById(R.id.actualChannelCount);
        mChannelCountSpinner = (Spinner) findViewById(R.id.spinnerChannelCount);
        mChannelCountSpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) {
                onChannelCountSpinnerSelected();
            }

            @Override
            public void onNothingSelected(AdapterView<?> adapterView) {
                // no-op
            }
        });
        mActualFormatView = (TextView) findViewById(R.id.actualAudioFormat);
        mFormatSpinner = (Spinner) findViewById(R.id.spinnerFormat);
        mRateConversionQualitySpinner = (Spinner) findViewById(R.id.spinnerSRCQuality);

        mActualPerformanceView = (TextView) findViewById(R.id.actualPerformanceMode);
        mPerformanceSpinner = (Spinner) findViewById(R.id.spinnerPerformanceMode);
        mPerformanceSpinner.setSelection(StreamConfiguration.PERFORMANCE_MODE_LOW_LATENCY
                - StreamConfiguration.PERFORMANCE_MODE_NONE);

        mInputPresetTableRow = (TableRow) findViewById(R.id.rowInputPreset);
        mActualInputPresetView = (TextView) findViewById(R.id.actualInputPreset);
        mInputPresetSpinner = (Spinner) findViewById(R.id.spinnerInputPreset);
        mInputPresetSpinner.setSelection(2); // TODO need better way to select voice recording default

        mUsageTableRow = (TableRow) findViewById(R.id.rowUsage);
        mActualUsageView = (TextView) findViewById(R.id.actualUsage);
        mUsageSpinner = (Spinner) findViewById(R.id.spinnerUsage);

        mContentTypeTableRow = (TableRow) findViewById(R.id.rowContentType);
        mActualContentTypeView = (TextView) findViewById(R.id.actualContentType);
        mContentTypeSpinner = (Spinner) findViewById(R.id.spinnerContentType);

        mStreamInfoView = (TextView) findViewById(R.id.streamInfo);

        mStreamStatusView = (TextView) findViewById(R.id.statusView);

        mDeviceSpinner = (AudioDeviceSpinner) findViewById(R.id.devices_spinner);

        mActualChannelMaskView = (TextView) findViewById(R.id.actualChannelMask);
        mChannelMaskSpinner = (Spinner) findViewById(R.id.spinnerChannelMask);
        ArrayAdapter<String> channelMaskSpinnerArrayAdapter = new ArrayAdapter<String>(context,
                android.R.layout.simple_spinner_item,
                StreamConfiguration.getAllChannelMasks());
        mChannelMaskSpinner.setAdapter(channelMaskSpinnerArrayAdapter);
        mChannelMaskSpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) {
                onChannelMaskSpinnerSelected();
            }

            @Override
            public void onNothingSelected(AdapterView<?> adapterView) {
                // no-op
            }
        });

        showSettingsView();
    }

    public void setOutput(boolean output) {
        misOutput = output;
        String ioText;
        if (output) {
            mDeviceSpinner.setDirectionType(AudioManager.GET_DEVICES_OUTPUTS);
            ioText = "OUTPUT";
        } else {
            mDeviceSpinner.setDirectionType(AudioManager.GET_DEVICES_INPUTS);
            ioText = "INPUT";
        }
        mHideSettingsText = getResources().getString(R.string.hint_hide_settings) + " - " + ioText;
        mShowSettingsText = getResources().getString(R.string.hint_show_settings) + " - " + ioText;
        updateSettingsViewText();

        // Don't show InputPresets for output streams.
        mInputPresetTableRow.setVisibility(output ? View.GONE : View.VISIBLE);
        // Don't show Usage and Content Type for input streams.
        mUsageTableRow.setVisibility(output ? View.VISIBLE : View.GONE);
        mContentTypeTableRow.setVisibility(output ? View.VISIBLE : View.GONE);
    }

    public void applyToModel(StreamConfiguration config) {
        // Menu position matches actual enum value for these properties.
        config.setNativeApi(mNativeApiSpinner.getSelectedItemPosition());
        config.setFormat(mFormatSpinner.getSelectedItemPosition());
        config.setRateConversionQuality(mRateConversionQualitySpinner.getSelectedItemPosition());

        int id =  ((AudioDeviceListEntry) mDeviceSpinner.getSelectedItem()).getId();
        config.setDeviceId(id);

        String text = mSampleRateSpinner.getSelectedItem().toString();
        int sampleRate = Integer.parseInt(text);
        config.setSampleRate(sampleRate);

        text = mInputPresetSpinner.getSelectedItem().toString();
        int inputPreset = StreamConfiguration.convertTextToInputPreset(text);
        config.setInputPreset(inputPreset);

        text = mUsageSpinner.getSelectedItem().toString();
        int usage = StreamConfiguration.convertTextToUsage(text);
        config.setUsage(usage);

        text = mContentTypeSpinner.getSelectedItem().toString();
        int contentType = StreamConfiguration.convertTextToContentType(text);
        config.setContentType(contentType);

        // The corresponding channel count of the selected channel mask may be different from
        // the selected channel count, the last selected will be respected.
        if (mIsChannelMaskLastSelected) {
            text = mChannelMaskSpinner.getSelectedItem().toString();
            int channelMask = StreamConfiguration.convertTextToChannelMask(text);
            config.setChannelMask(channelMask);
            config.setChannelCount(0);
            Log.d(TAG, String.format("Set channel mask as %s(%#x)", text, channelMask));
        } else {
            config.setChannelCount(mChannelCountSpinner.getSelectedItemPosition());
            config.setChannelMask(StreamConfiguration.UNSPECIFIED);
            Log.d(TAG, "Set channel count as " + mChannelCountSpinner.getSelectedItemPosition());
        }

        config.setMMap(mRequestedMMapView.isChecked());
        config.setChannelConversionAllowed(mChannelConversionBox.isChecked());
        config.setFormatConversionAllowed(mFormatConversionBox.isChecked());
        config.setSharingMode(mRequestedExclusiveView.isChecked()
                ? StreamConfiguration.SHARING_MODE_EXCLUSIVE
                : StreamConfiguration.SHARING_MODE_SHARED);
        config.setSessionId(mRequestAudioEffect.isChecked()
                ? StreamConfiguration.SESSION_ID_ALLOCATE
                : StreamConfiguration.SESSION_ID_NONE);

        config.setPerformanceMode(mPerformanceSpinner.getSelectedItemPosition()
                + StreamConfiguration.PERFORMANCE_MODE_NONE);
    }

    public void setChildrenEnabled(boolean enabled) {
        mNativeApiSpinner.setEnabled(enabled);
        mPerformanceSpinner.setEnabled(enabled);
        mRequestedMMapView.setEnabled(enabled && NativeEngine.isMMapSupported());
        mRequestedExclusiveView.setEnabled(enabled && NativeEngine.isMMapExclusiveSupported());
        mChannelConversionBox.setEnabled(enabled);
        mFormatConversionBox.setEnabled(enabled);
        mChannelCountSpinner.setEnabled(enabled);
        mChannelMaskSpinner.setEnabled(enabled);
        mInputPresetSpinner.setEnabled(enabled);
        mUsageSpinner.setEnabled(enabled);
        mContentTypeSpinner.setEnabled(enabled);
        mFormatSpinner.setEnabled(enabled);
        mSampleRateSpinner.setEnabled(enabled);
        mRateConversionQualitySpinner.setEnabled(enabled);
        mDeviceSpinner.setEnabled(enabled);
        mRequestAudioEffect.setEnabled(enabled);
    }

    // This must be called on the UI thread.
    void updateDisplay(StreamConfiguration actualConfiguration) {
        int value;

        value = actualConfiguration.getNativeApi();
        mActualNativeApiView.setText(StreamConfiguration.convertNativeApiToText(value));

        mActualMMapView.setText(yesOrNo(actualConfiguration.isMMap()));
        int sharingMode = actualConfiguration.getSharingMode();
        boolean isExclusive = (sharingMode == StreamConfiguration.SHARING_MODE_EXCLUSIVE);
        mActualExclusiveView.setText(yesOrNo(isExclusive));

        value = actualConfiguration.getPerformanceMode();
        mActualPerformanceView.setText(StreamConfiguration.convertPerformanceModeToText(value));
        mActualPerformanceView.requestLayout();

        value = actualConfiguration.getFormat();
        mActualFormatView.setText(StreamConfiguration.convertFormatToText(value));
        mActualFormatView.requestLayout();

        value = actualConfiguration.getInputPreset();
        mActualInputPresetView.setText(StreamConfiguration.convertInputPresetToText(value));
        mActualInputPresetView.requestLayout();

        value = actualConfiguration.getUsage();
        mActualUsageView.setText(StreamConfiguration.convertUsageToText(value));
        mActualUsageView.requestLayout();

        value = actualConfiguration.getContentType();
        mActualContentTypeView.setText(StreamConfiguration.convertContentTypeToText(value));
        mActualContentTypeView.requestLayout();

        mActualChannelCountView.setText(actualConfiguration.getChannelCount() + "");
        mActualSampleRateView.setText(actualConfiguration.getSampleRate() + "");
        mActualSessionIdView.setText("S#: " + actualConfiguration.getSessionId());
        value = actualConfiguration.getChannelMask();
        mActualChannelMaskView.setText(StreamConfiguration.convertChannelMaskToText(value));

        boolean isMMap = actualConfiguration.isMMap();
        mStreamInfoView.setText("burst = " + actualConfiguration.getFramesPerBurst()
                + ", capacity = " + actualConfiguration.getBufferCapacityInFrames()
                + ", devID = " + actualConfiguration.getDeviceId()
                + ", " + (actualConfiguration.isMMap() ? "MMAP" : "Legacy")
                + (isMMap ? ", " + StreamConfiguration.convertSharingModeToText(sharingMode) : "")
        );

        mHideableView.requestLayout();
    }

    // This must be called on the UI thread.
    public void setStatusText(String msg) {
        mStreamStatusView.setText(msg);
    }

    public void setExclusiveMode(boolean b) {
        mRequestedExclusiveView.setChecked(b);
    }

    public void setFormat(int format) {
        mFormatSpinner.setSelection(format); // position matches format
    }

    public void setFormatConversionAllowed(boolean allowed) {
        mFormatConversionBox.setChecked(allowed);
    }

    private void onChannelCountSpinnerSelected() {
        mIsChannelMaskLastSelected = false;
    }

    private void onChannelMaskSpinnerSelected() {
        mIsChannelMaskLastSelected = true;
    }

    private void onRequestAudioEffectClicked(boolean isChecked) {
        if (isChecked){
            if (misOutput) {
                mOutputEffectsLayout.setVisibility(VISIBLE);
            } else {
                mInputEffectsLayout.setVisibility(VISIBLE);
            }
        } else {
            if (misOutput) {
                mOutputEffectsLayout.setVisibility(GONE);
            } else {
                mInputEffectsLayout.setVisibility(GONE);
            }
        }
    }

    public void setupEffects(int sessionId) {
        if (misOutput) {
            mBassBoost = new BassBoost(0, sessionId);
            mBassBoost.setStrength((short) mBassBoostSeekBar.getProgress());
            mLoudnessEnhancer = new LoudnessEnhancer(sessionId);
            mLoudnessEnhancer.setTargetGain((short) mLoudnessEnhancerSeekBar.getProgress());
        } else {
            // If AEC is not available, the checkbox will be disabled in initializeViews().
            if (mAcousticEchoCancelerCheckBox.isEnabled()) {
                mAcousticEchoCanceler = AcousticEchoCanceler.create(sessionId);
                if (mAcousticEchoCanceler != null) {
                    mAcousticEchoCanceler.setEnabled(mAcousticEchoCancelerCheckBox.isChecked());
                } else {
                    Log.e(TAG, String.format("Could not create AcousticEchoCanceler"));
                }
            }
            // If AGC is not available, the checkbox will be disabled in initializeViews().
            if (mAutomaticGainControlCheckBox.isEnabled()) {
                mAutomaticGainControl = AutomaticGainControl.create(sessionId);
                if (mAutomaticGainControl != null) {
                    mAutomaticGainControl.setEnabled(mAutomaticGainControlCheckBox.isChecked());
                } else {
                    Log.e(TAG, String.format("Could not create AutomaticGainControl"));
                }
            }
        }
    }

    private void onLoudnessEnhancerSeekBarChanged(int progress) {
        if (mLoudnessEnhancer != null) {
            mLoudnessEnhancer.setTargetGain(progress);
        }
        mLoudnessEnhancerTextView.setText("Loudness Enhancer: " + progress);
    }

    private void onBassBoostSeekBarChanged(int progress) {
        if (mBassBoost != null) {
            mBassBoost.setStrength((short) progress);
        }
        mBassBoostTextView.setText("Bass Boost: " + progress);
    }

    private void onAutomaticGainControlCheckBoxChanged(boolean isChecked) {
        if (mAutomaticGainControlCheckBox.isEnabled() && mAutomaticGainControl != null) {
            mAutomaticGainControl.setEnabled(isChecked);
        }
    }

    private void onAcousticEchoCancelerCheckBoxChanged(boolean isChecked) {
        if (mAcousticEchoCancelerCheckBox.isEnabled() && mAcousticEchoCanceler != null) {
            mAcousticEchoCanceler.setEnabled(isChecked);
        }
    }
}


text:
package com.spotify.heroic.suggest.elasticsearch;

import static com.google.common.base.Preconditions.checkNotNull;
import static java.lang.Math.toIntExact;
import static java.util.Optional.empty;
import static java.util.Optional.of;
import static java.util.concurrent.TimeUnit.MINUTES;
import static java.util.concurrent.TimeUnit.SECONDS;

import com.fasterxml.jackson.annotation.JsonCreator;
import com.fasterxml.jackson.annotation.JsonIgnore;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.google.common.cache.Cache;
import com.google.common.cache.CacheBuilder;
import com.google.common.collect.ImmutableList;
import com.google.common.hash.HashCode;
import com.google.common.util.concurrent.RateLimiter;
import com.spotify.heroic.ExtraParameters;
import com.spotify.heroic.common.Duration;
import com.spotify.heroic.common.DynamicModuleId;
import com.spotify.heroic.common.Groups;
import com.spotify.heroic.common.ModuleId;
import com.spotify.heroic.dagger.PrimaryComponent;
import com.spotify.heroic.elasticsearch.BackendType;
import com.spotify.heroic.elasticsearch.Connection;
import com.spotify.heroic.elasticsearch.ConnectionModule;
import com.spotify.heroic.elasticsearch.DefaultRateLimitedCache;
import com.spotify.heroic.elasticsearch.DisabledRateLimitedCache;
import com.spotify.heroic.elasticsearch.DistributedRateLimitedCache;
import com.spotify.heroic.elasticsearch.MemcachedConnection;
import com.spotify.heroic.elasticsearch.RateLimitedCache;
import com.spotify.heroic.lifecycle.LifeCycle;
import com.spotify.heroic.lifecycle.LifeCycleManager;
import com.spotify.heroic.statistics.HeroicReporter;
import com.spotify.heroic.suggest.NumSuggestionsLimit;
import com.spotify.heroic.suggest.SuggestBackend;
import com.spotify.heroic.suggest.SuggestModule;
import dagger.Component;
import dagger.Lazy;
import dagger.Module;
import dagger.Provides;
import eu.toolchain.async.Managed;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.function.Supplier;
import javax.inject.Named;
import org.apache.commons.lang3.tuple.Pair;

@ModuleId("elasticsearch")
public final class ElasticsearchSuggestModule implements SuggestModule, DynamicModuleId {
    public static final String ELASTICSEARCH_CONFIGURE_PARAM = "elasticsearch.configure";

    private static final double DEFAULT_WRITES_PER_SECOND = 3000d;
    private static final long DEFAULT_RATE_LIMIT_SLOW_START_SECONDS = 0L;

    private static final long DEFAULT_WRITES_CACHE_DURATION_MINUTES = 240L;
    private static final int DEFAULT_WRITE_CACHE_CONCURRENCY = 4;
    private static final long DEFAULT_WRITE_CACHE_MAX_SIZE = 30_000_000L;

    private static final String DEFAULT_GROUP = "elasticsearch";
    private static final String DEFAULT_TEMPLATE_NAME = "heroic-suggest";
    private static final boolean DEFAULT_CONFIGURE = false;

    private final Optional<String> id;
    private final Groups groups;
    private final ConnectionModule connection;
    private final double writesPerSecond;
    private final Long rateLimitSlowStartSeconds;
    private final long writeCacheDurationMinutes;
    private final Integer writeCacheConcurrency;
    private final Long writeCacheMaxSize;
    private final String distributedCacheSrvRecord;
    private final String templateName;
    private final boolean configure;
    private final NumSuggestionsLimit numSuggestionsLimit;

    private static Supplier<BackendType> defaultSetup = SuggestBackendKV.factory();

    private static final Map<String, Supplier<BackendType>> backendTypes = new HashMap<>();

    static {
        backendTypes.put("kv", defaultSetup);
    }

    public static List<String> types() {
        return ImmutableList.copyOf(backendTypes.keySet());
    }

    @JsonIgnore
    private final Supplier<BackendType> type;

    @JsonCreator
    public ElasticsearchSuggestModule(
        @JsonProperty("id") Optional<String> id,
        @JsonProperty("groups") Optional<Groups> groups,
        @JsonProperty("connection") Optional<ConnectionModule> connection,
        @JsonProperty("writesPerSecond") Optional<Double> writesPerSecond,
        @JsonProperty("rateLimitSlowStartSeconds") Optional<Long> rateLimitSlowStartSeconds,
        @JsonProperty("writeCacheDurationMinutes") Optional<Long> writeCacheDurationMinutes,
        @JsonProperty("writeCacheConcurrency") Optional<Integer> writeCacheConcurrency,
        @JsonProperty("writeCacheMaxSize") Optional<Long> writeCacheMaxSize,
        @JsonProperty("distributedCacheSrvRecord") Optional<String> distributedCacheSrvRecord,
        @JsonProperty("templateName") Optional<String> templateName,
        @JsonProperty("backendType") Optional<String> backendType,
        @JsonProperty("configure") Optional<Boolean> configure,
        @JsonProperty("numSuggestionsLimit") Optional<Integer> numSuggestionsLimit
    ) {
        this.id = id;
        this.groups = groups.orElseGet(Groups::empty).or(DEFAULT_GROUP);
        this.connection = connection.orElseGet(ConnectionModule::buildDefault);
        this.writesPerSecond = writesPerSecond.orElse(DEFAULT_WRITES_PER_SECOND);
        this.rateLimitSlowStartSeconds =
            rateLimitSlowStartSeconds.orElse(DEFAULT_RATE_LIMIT_SLOW_START_SECONDS);

        this.writeCacheDurationMinutes =
            writeCacheDurationMinutes.orElse(DEFAULT_WRITES_CACHE_DURATION_MINUTES);
        this.writeCacheConcurrency = writeCacheConcurrency.orElse(DEFAULT_WRITE_CACHE_CONCURRENCY);
        this.writeCacheMaxSize = writeCacheMaxSize.orElse(DEFAULT_WRITE_CACHE_MAX_SIZE);

        this.distributedCacheSrvRecord = distributedCacheSrvRecord.orElse("");

        this.templateName = templateName.orElse(DEFAULT_TEMPLATE_NAME);
        this.type = backendType
                .map(ElasticsearchSuggestModule::lookupBackendType).orElse(defaultSetup);
        this.configure = configure.orElse(DEFAULT_CONFIGURE);

        this.numSuggestionsLimit = NumSuggestionsLimit.of(numSuggestionsLimit);
    }

    private static Supplier<BackendType> lookupBackendType(final String bt) {
        final Supplier<BackendType> type = backendTypes.get(bt);

        if (type == null) {
            throw new IllegalArgumentException(
                "Invalid backend type (" + bt + "), must be one of " + backendTypes.keySet());
        }

        return type;
    }

    @Override
    public Exposed module(PrimaryComponent primary,
                          Depends depends,
                          final String id) {
        final BackendType backendType = type.get();

        return DaggerElasticsearchSuggestModule_C
                .builder()
                .primaryComponent(primary)
                .depends(depends)
                .connectionModule(connection)
                .m(new M(backendType))
                .o(new O())
                .build();
    }

    @ElasticsearchScope
    @Component(modules = {M.class, O.class, ConnectionModule.class},
            dependencies = {PrimaryComponent.class, Depends.class})
    interface C extends Exposed {
        @Override
        SuggestBackend backend();

        @Override
        LifeCycle life();
    }

    @Module
    class M {
        private final BackendType backendType;

        public M(final BackendType backendType) {
            this.backendType = backendType;
        }

        @Provides
        @ElasticsearchScope
        public Groups groups() {
            return groups;
        }

        @Provides
        @ElasticsearchScope
        public Managed<Connection> connection(ConnectionModule.Provider provider) {
            return provider.construct(templateName, backendType);
        }

        @Provides
        @ElasticsearchScope
        @Named("configure")
        public boolean configure(ExtraParameters params) {
            return configure || params.contains(ExtraParameters.CONFIGURE) ||
                params.contains(ELASTICSEARCH_CONFIGURE_PARAM);
        }

        @Provides
        @ElasticsearchScope
        @Named("numSuggestionsLimit")
        public int numSuggestionsLimit(ExtraParameters params) {
            return numSuggestionsLimit.getLimit();
        }

        @Provides
        @ElasticsearchScope
        public RateLimitedCache<Pair<String, HashCode>> writeCache(final HeroicReporter reporter) {
            final Cache<Pair<String, HashCode>, Boolean> cache = CacheBuilder
                .newBuilder()
                .concurrencyLevel(writeCacheConcurrency)
                .maximumSize(writeCacheMaxSize)
                .expireAfterWrite(writeCacheDurationMinutes, MINUTES)
                .build();

            reporter.registerCacheSize("elasticsearch-suggest-write-through", cache::size);

            if (writesPerSecond <= 0d) {
                return new DisabledRateLimitedCache<>(cache.asMap());
            }

            if (distributedCacheSrvRecord.length() > 0) {
                return new DistributedRateLimitedCache<>(
                  cache.asMap(),
                  RateLimiter.create(writesPerSecond, rateLimitSlowStartSeconds, SECONDS),
                  MemcachedConnection.create(distributedCacheSrvRecord),
                  toIntExact(Duration.of(writeCacheDurationMinutes, MINUTES).convert(SECONDS)),
                  reporter.newMemcachedReporter("suggest")
                );
            }

            return new DefaultRateLimitedCache<>(cache.asMap(),
                RateLimiter.create(writesPerSecond, rateLimitSlowStartSeconds, SECONDS));
        }

        @Provides
        @ElasticsearchScope
        public SuggestBackend suggestBackend(Lazy<SuggestBackendKV> kv) {
            return kv.get();
        }

        @Provides
        @ElasticsearchScope
        public LifeCycle life(
                LifeCycleManager manager, Lazy<SuggestBackendKV> kv
        ) {
            return manager.build(kv.get());
        }
    }

    @Module
    class O {
        @Provides
        @ElasticsearchScope
        public Integer numSuggestionsLimit() {
            return numSuggestionsLimit.getLimit();
        }
    }

    @Override
    public Optional<String> id() {
        return id;
    }

    public static Builder builder() {
        return new Builder();
    }

    public static class Builder {
        private Optional<String> id = empty();
        private Optional<Groups> groups = empty();
        private Optional<ConnectionModule> connection = empty();
        private Optional<Double> writesPerSecond = empty();
        private Optional<Long> rateLimitSlowStartSeconds = empty();
        private Optional<Long> writeCacheDurationMinutes = empty();
        private Optional<Integer> writeCacheConcurrency = empty();
        private Optional<Long> writeCacheMaxSize = empty();
        private Optional<String> distributedCacheSrvRecord = empty();
        private Optional<String> templateName = empty();
        private Optional<String> backendType = empty();
        private Optional<Boolean> configure = empty();
        private Optional<NumSuggestionsLimit> numSuggestionsLimit =
                Optional.of(NumSuggestionsLimit.of());

        public Builder id(final String id) {
            checkNotNull(id, "id");
            this.id = of(id);
            return this;
        }

        public Builder numSuggestionsLimit(final NumSuggestionsLimit numSuggestionsLimit) {
            checkNotNull(numSuggestionsLimit, "numSuggestionsLimit");
            this.numSuggestionsLimit = of(numSuggestionsLimit);
            return this;
        }

        public Builder group(final Groups groups) {
            checkNotNull(groups, "groups");
            this.groups = of(groups);
            return this;
        }

        public Builder connection(final ConnectionModule connection) {
            checkNotNull(connection, "connection");
            this.connection = of(connection);
            return this;
        }

        public Builder writesPerSecond(double writesPerSecond) {
            checkNotNull(writesPerSecond, "writesPerSecond");
            this.writesPerSecond = of(writesPerSecond);
            return this;
        }

        public Builder rateLimitSlowStartSeconds(final long rateLimitSlowStartSeconds) {
            checkNotNull(rateLimitSlowStartSeconds, "rateLimitSlowStartSeconds");
            this.rateLimitSlowStartSeconds = of(rateLimitSlowStartSeconds);
            return this;
        }

        public Builder writeCacheDurationMinutes(long writeCacheDurationMinutes) {
            checkNotNull(writeCacheDurationMinutes, "writeCacheDurationMinutes");
            this.writeCacheDurationMinutes = of(writeCacheDurationMinutes);
            return this;
        }

        public Builder writeCacheConcurrency(final int writeCacheConcurrency) {
            this.writeCacheConcurrency = of(writeCacheConcurrency);
            return this;
        }

        public Builder writeCacheMaxSize(final long writeCacheMaxSize) {
            this.writeCacheMaxSize = of(writeCacheMaxSize);
            return this;
        }

        public Builder distributedCacheSrvRecord(final String distributedCacheSrvRecord) {
            checkNotNull(distributedCacheSrvRecord, "distributedCacheSrvRecord");
            this.distributedCacheSrvRecord = of(distributedCacheSrvRecord);
            return this;
        }

        public Builder templateName(final String templateName) {
            checkNotNull(templateName, "templateName");
            this.templateName = of(templateName);
            return this;
        }

        public Builder backendType(final String backendType) {
            checkNotNull(backendType, "backendType");
            this.backendType = of(backendType);
            return this;
        }

        public Builder configure(final boolean configure) {
            this.configure = of(configure);
            return this;
        }

        public ElasticsearchSuggestModule build() {
            return new ElasticsearchSuggestModule(
                id,
                groups,
                    connection,
                    writesPerSecond,
                    rateLimitSlowStartSeconds,
                    writeCacheDurationMinutes,
                    writeCacheConcurrency,
                    writeCacheMaxSize,
                    distributedCacheSrvRecord,
                    templateName,
                    backendType,
                    configure,
                    numSuggestionsLimit.get().asOptionalInt());
        }
    }
}

redpajama_set_name: RedPajamaGithub


text:
from typing import Union

from google.cloud import aiplatform, aiplatform_v1

#  [START aiplatform_sdk_create_batch_prediction_job_dedicated_resources_bigquery_sample]
def create_batch_prediction_job_dedicated_resources_bigquery_sample(
    project: str,
    location: str,
    model_resource_name: str,
    job_display_name: str,
    bigquery_source: str,
    bigquery_destination_prefix: str,
    machine_type: str = "n1-standard-2",
    accelerator_count: int = 1,
    accelerator_type: Union[str, aiplatform_v1.AcceleratorType] = "NVIDIA_TESLA_K80",
    starting_replica_count: int = 1,
    max_replica_count: int = 1,
    sync: bool = True,
):
    aiplatform.init(project=project, location=location)

    my_model = aiplatform.Model(model_resource_name)

    batch_prediction_job = my_model.batch_predict(
        job_display_name=job_display_name,
        bigquery_source=bigquery_source,
        bigquery_destination_prefix=bigquery_destination_prefix,
        machine_type=machine_type,
        accelerator_count=accelerator_count,
        accelerator_type=accelerator_type,
        starting_replica_count=starting_replica_count,
        max_replica_count=max_replica_count,
        sync=sync,
    )

    batch_prediction_job.wait()

    print(batch_prediction_job.display_name)
    print(batch_prediction_job.resource_name)
    print(batch_prediction_job.state)
    return batch_prediction_job

#  [END aiplatform_sdk_create_batch_prediction_job_dedicated_resources_bigquery_sample]


text:
<?php
class Report_Model_DbTable_DbRptPaymentSchedule extends Zend_Db_Table_Abstract
{

    public function getUserId(){
    	$session_user=new Zend_Session_Namespace('auth');
    	return $session_user->user_id;
    }
    public function getPaymentSchedule($id,$payment_id=null){
    	$db=$this->getAdapter();
    	$sql = "SELECT *,
		(SELECT (paid_date) FROM `ln_client_receipt_money_detail` WHERE lfd_id=ln_saleschedule.id limit 1) as paid_date,
		(SELECT SUM(total_recieve) FROM `ln_client_receipt_money_detail` WHERE lfd_id=ln_saleschedule.id limit 1) as total_recieve,
		(SELECT SUM(total_interest) FROM `ln_client_receipt_money_detail` WHERE lfd_id=ln_saleschedule.id limit 1) as total_interestpaid,
		(SELECT SUM(principal_permonth) FROM `ln_client_receipt_money_detail` WHERE lfd_id=ln_saleschedule.id limit 1) as principal_paid
    	FROM `ln_saleschedule` WHERE sale_id= $id AND status=1 ";

    	if($payment_id==4){
    		$sql.=" AND is_installment=1 ";
    	};
    	return $db->fetchAll($sql);
    }
    public function getPaymentScheduleGroupById($id){//for group member total pay per month
    	$db=$this->getAdapter();
    	$sql = "SELECT f.*,
    	SUM(total_principal) AS total_principal,
    	SUM(total_interest) AS total_interest_permonth,SUM(f.principal_permonth) AS total_principal_permonth
    	             ,SUM(total_payment) AS total_payment_permonth FROM `ln_loan_member` AS m,`ln_loanmember_funddetail` AS f
				   WHERE m.member_id = f.member_id AND m.group_id=$id AND f.status=1
    			AND m.status=1 GROUP BY m.group_id ,f.date_payment";
    	return $db->fetchAll($sql);
    }
    public function getAllClientPaymentListRpt($search = null ){
    	$db = $this->getAdapter();
    	//$sql="select * FROM v_loanpaymentschedulelist";
    	$sql="SELECT m.member_id
    	,(SELECT `b`.`branch_namekh` FROM `ln_branch` AS b WHERE `b`.`br_id` =lg.`branch_id` LIMIT 1) AS `branch_namekh`
        ,`m`.`loan_number` ,`c`.`client_number`
  		,c.name_en ,m.total_capital,m.admin_fee
  		,m.interest_rate,
    	CONCAT( lg.total_duration,' ',(SELECT name_en FROM `ln_view` WHERE type = 14 AND key_code =lg.pay_term )),
    	(SELECT payment_nameen FROM `ln_payment_method` WHERE id = m.payment_method) AS payment_nameen,
    	lg.time_collect
    	,(SELECT `zone_name` FROM `ln_zone` WHERE zone_id = lg.zone_id) AS zone_name
    	,(SELECT co_khname FROM `ln_co` WHERE co_id = lg.co_id ) AS co_khname, m.status
    	    FROM `ln_loan_member` AS m,`ln_loan_group` AS lg,`ln_client` AS c
    		WHERE lg.g_id = m.group_id AND c.client_id = m.client_id ";
    	$Other =" ORDER BY member_id DESC ";

    	return $db->fetchAll($sql.$Other);
    }

}


text:
package org.apache.geode.redis.internal.executor.key;

import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashSet;
import java.util.List;
import java.util.Random;
import java.util.Set;
import java.util.concurrent.BrokenBarrierException;
import java.util.concurrent.Callable;
import java.util.concurrent.CyclicBarrier;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;

import org.junit.After;
import org.junit.AfterClass;
import org.junit.BeforeClass;
import org.junit.ClassRule;
import org.junit.Test;
import org.junit.experimental.categories.Category;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.Protocol;
import redis.clients.jedis.exceptions.JedisDataException;

import org.apache.geode.redis.GeodeRedisServerRule;
import org.apache.geode.redis.internal.RedisConstants;
import org.apache.geode.redis.internal.data.ByteArrayWrapper;
import org.apache.geode.redis.internal.executor.StripedExecutor;
import org.apache.geode.redis.internal.executor.SynchronizedStripedExecutor;
import org.apache.geode.test.awaitility.GeodeAwaitility;
import org.apache.geode.test.junit.categories.RedisTest;

@Category({RedisTest.class})
public class RenameIntegrationTest {
  static Jedis jedis;
  static Jedis jedis2;
  static Jedis jedis3;
  static final int REDIS_CLIENT_TIMEOUT = Math.toIntExact(GeodeAwaitility.getTimeout().toMillis());
  static Random rand;

  @ClassRule
  public static GeodeRedisServerRule server = new GeodeRedisServerRule();

  @BeforeClass
  public static void setUp() {
    rand = new Random();
    jedis = new Jedis("localhost", server.getPort(), REDIS_CLIENT_TIMEOUT);
    jedis2 = new Jedis("localhost", server.getPort(), REDIS_CLIENT_TIMEOUT);
    jedis3 = new Jedis("localhost", server.getPort(), REDIS_CLIENT_TIMEOUT);
  }

  @AfterClass
  public static void tearDown() {
    jedis.close();
    jedis2.close();
    jedis3.close();
  }

  public int getPort() {
    return server.getPort();
  }

  @After
  public void flush() {
    jedis.flushAll();
  }

  @Test
  public void testTooFewArgs() {
    assertThatThrownBy(() -> jedis.sendCommand(Protocol.Command.RENAME, "foo"))
        .hasMessageContaining("wrong number of arguments");
  }

  @Test
  public void testTooManyArgs() {
    assertThatThrownBy(() -> jedis.sendCommand(Protocol.Command.RENAME, "foo", "newfoo", "bluefoo"))
        .hasMessageContaining("wrong number of arguments");
  }

  @Test
  public void testNewKey() {
    jedis.set("foo", "bar");
    jedis.rename("foo", "newfoo");
    assertThat(jedis.get("newfoo")).isEqualTo("bar");
  }

  @Test
  public void testOldKeyIsDeleted() {
    jedis.set("foo", "bar");
    jedis.rename("foo", "newfoo");
    assertThat(jedis.get("foo")).isNull();
  }

  @Test
  public void testRenameKeyThatDoesNotExist() {
    try {
      jedis.rename("foo", "newfoo");
    } catch (JedisDataException e) {
      assertThat(e.getMessage()).contains(RedisConstants.ERROR_NO_SUCH_KEY);
    }
  }

  @Test
  public void testHashMap() {
    jedis.hset("foo", "field", "va");
    jedis.rename("foo", "newfoo");
    assertThat(jedis.hget("newfoo", "field")).isEqualTo("va");
  }

  @Test
  public void testSet() {
    jedis.sadd("foo", "data");
    jedis.rename("foo", "newfoo");
    assertThat(jedis.smembers("newfoo")).contains("data");
  }

  @Test
  public void testRenameSameKey() {
    jedis.set("blue", "moon");
    assertThat(jedis.rename("blue", "blue")).isEqualTo("OK");
    assertThat(jedis.get("blue")).isEqualTo("moon");
  }

  @Test
  public void testConcurrentSets() throws ExecutionException, InterruptedException {
    Set<String> stringsForK1 = new HashSet<String>();
    Set<String> stringsForK2 = new HashSet<String>();

    int numOfStrings = 500000;
    Callable<Long> callable1 =
        () -> addStringsToKeys(stringsForK1, "k1", numOfStrings, jedis);
    int numOfStringsForSecondKey = 30000;
    Callable<Long> callable2 =
        () -> addStringsToKeys(stringsForK2, "k2", numOfStringsForSecondKey, jedis2);
    Callable<String> callable3 = () -> renameKeys(jedis3);

    ExecutorService pool = Executors.newFixedThreadPool(4);
    Future<Long> future1 = pool.submit(callable1);
    Future<Long> future2 = pool.submit(callable2);
    Thread.sleep(rand.nextInt(1000));
    Future<String> future3 = pool.submit(callable3);

    future1.get();
    future2.get();
    try {
      future3.get();
      assertThat(jedis.scard("k2")).isEqualTo(numOfStrings);
      assertThat(jedis.get("k1")).isEqualTo(null);
    } catch (Exception e) {
      assertThat(e.getMessage()).contains(RedisConstants.ERROR_NO_SUCH_KEY);
      assertThat(jedis.scard("k1")).isEqualTo(numOfStrings);
      assertThat(jedis.scard("k2")).isEqualTo(numOfStringsForSecondKey);
    }

    jedis2.close();
    jedis3.close();
  }

  @Test
  public void should_succeed_givenTwoKeysOnDifferentStripes() {
    List<String> listOfKeys = getKeysOnDifferentStripes();
    String oldKey = listOfKeys.get(0);
    String newKey = listOfKeys.get(1);

    jedis.sadd(oldKey, "value1");
    jedis.sadd(newKey, "value2");

    assertThat(jedis.rename(oldKey, newKey)).isEqualTo("OK");
    assertThat(jedis.smembers(newKey)).containsExactly("value1");
    assertThat(jedis.exists(oldKey)).isFalse();
  }

  @Test
  public void should_succeed_givenTwoKeysOnSameStripe() {
    List<String> listOfKeys = new ArrayList<>(getKeysOnSameRandomStripe(2));
    String oldKey = listOfKeys.get(0);
    String newKey = listOfKeys.get(1);

    jedis.sadd(oldKey, "value1");
    jedis.sadd(newKey, "value2");

    assertThat(jedis.rename(oldKey, newKey)).isEqualTo("OK");
    assertThat(jedis.smembers(newKey)).containsExactly("value1");
    assertThat(jedis.exists(oldKey)).isFalse();
  }

  @Test
  public void shouldNotDeadlock_concurrentRenames_givenStripeContention()
      throws ExecutionException, InterruptedException {
    List<String> keysOnStripe1 = new ArrayList<>(getKeysOnSameRandomStripe(2));
    List<String> keysOnStripe2 = getKeysOnSameRandomStripe(2, keysOnStripe1.get(0));

    for (int i = 0; i < 5; i++) {
      doConcurrentRenamesDifferentKeys(
          Arrays.asList(keysOnStripe1.get(0), keysOnStripe2.get(0)),
          Arrays.asList(keysOnStripe2.get(1), keysOnStripe1.get(1)));
    }
  }

  @Test
  public void shouldThrowError_givenKeyDeletedDuringRename()
      throws ExecutionException, InterruptedException {
    CyclicBarrier startCyclicBarrier = new CyclicBarrier(2);
    ExecutorService pool = Executors.newFixedThreadPool(2);

    for (int i = 0; i < 100; i++) {
      jedis.set("oldKey", "foo");

      Runnable renameOldKeyToNewKey = () -> {
        cyclicBarrierAwait(startCyclicBarrier);

        jedis.rename("oldKey", "newKey");
      };

      Runnable deleteOldKey = () -> {
        cyclicBarrierAwait(startCyclicBarrier);

        jedis2.del("oldKey");
      };

      Future<?> future1 = pool.submit(renameOldKeyToNewKey);
      Future<?> future2 = pool.submit(deleteOldKey);

      try {
        future1.get();
        assertThat(jedis.get("newKey")).isEqualTo("foo");
      } catch (Exception e) {
        assertThat(e).hasMessageContaining("no such key");
      }
      future2.get();

      assertThat(jedis.get("oldKey")).isNull();
    }
  }

  @Test
  public void shouldNotDeadlock_concurrentRenames_givenTwoKeysOnDifferentStripe()
      throws ExecutionException, InterruptedException {
    doConcurrentRenamesSameKeys(getKeysOnDifferentStripes());
  }

  @Test
  public void shouldNotDeadlock_concurrentRenames_givenTwoKeysOnSameStripe()
      throws ExecutionException, InterruptedException {
    doConcurrentRenamesSameKeys(new ArrayList<>(getKeysOnSameRandomStripe(2)));
  }

  private List<String> getKeysOnDifferentStripes() {
    String key1 = "keyz" + new Random().nextInt();

    ByteArrayWrapper key1ByteArrayWrapper = new ByteArrayWrapper(key1.getBytes());
    StripedExecutor stripedExecutor = new SynchronizedStripedExecutor();
    int iterator = 0;
    String key2;
    do {
      key2 = "key" + iterator;
      iterator++;
    } while (stripedExecutor.compareStripes(key1ByteArrayWrapper,
        new ByteArrayWrapper(key2.getBytes())) == 0);

    return Arrays.asList(key1, key2);
  }

  private Set<String> getKeysOnSameRandomStripe(int numKeysNeeded) {
    Random random = new Random();
    String key1 = "keyz" + random.nextInt();
    ByteArrayWrapper key1ByteArrayWrapper = new ByteArrayWrapper(key1.getBytes());
    StripedExecutor stripedExecutor = new SynchronizedStripedExecutor();
    Set<String> keys = new HashSet<>();
    keys.add(key1);

    do {
      String key2 = "key" + random.nextInt();
      if (stripedExecutor.compareStripes(key1ByteArrayWrapper,
          new ByteArrayWrapper(key2.getBytes())) == 0) {
        keys.add(key2);
      }
    } while (keys.size() < numKeysNeeded);

    return keys;
  }

  public void doConcurrentRenamesDifferentKeys(List<String> listOfKeys1, List<String> listOfKeys2)
      throws ExecutionException, InterruptedException {
    CyclicBarrier startCyclicBarrier = new CyclicBarrier(2);

    String oldKey1 = listOfKeys1.get(0);
    String newKey1 = listOfKeys1.get(1);
    String oldKey2 = listOfKeys2.get(0);
    String newKey2 = listOfKeys2.get(1);

    jedis.sadd(oldKey1, "foo", "bar");
    jedis.sadd(oldKey2, "bar3", "back3");

    ExecutorService pool = Executors.newFixedThreadPool(2);

    Runnable renameOldKey1ToNewKey1 = () -> {
      cyclicBarrierAwait(startCyclicBarrier);

      jedis.rename(oldKey1, newKey1);
    };

    Runnable renameOldKey2ToNewKey2 = () -> {
      cyclicBarrierAwait(startCyclicBarrier);

      jedis2.rename(oldKey2, newKey2);
    };

    Future<?> future1 = pool.submit(renameOldKey1ToNewKey1);
    Future<?> future2 = pool.submit(renameOldKey2ToNewKey2);

    future1.get();
    future2.get();
  }

  private void cyclicBarrierAwait(CyclicBarrier startCyclicBarrier) {
    try {
      startCyclicBarrier.await();
    } catch (InterruptedException | BrokenBarrierException e) {
      throw new RuntimeException(e);
    }
  }

  private List<String> getKeysOnSameRandomStripe(int numKeysNeeded, Object toAvoid) {

    StripedExecutor stripedExecutor = new SynchronizedStripedExecutor();

    List<String> keys = new ArrayList<>();

    String key1;
    ByteArrayWrapper key1ByteArrayWrapper;
    do {
      key1 = "keyz" + new Random().nextInt();
      key1ByteArrayWrapper = new ByteArrayWrapper(key1.getBytes());
    } while (stripedExecutor.compareStripes(key1ByteArrayWrapper, toAvoid) == 0 && keys.add(key1));

    do {
      String key2 = "key" + new Random().nextInt();

      if (stripedExecutor.compareStripes(key1ByteArrayWrapper,
          new ByteArrayWrapper(key2.getBytes())) == 0) {
        keys.add(key2);
      }
    } while (keys.size() < numKeysNeeded);

    return keys;
  }

  public void doConcurrentRenamesSameKeys(List<String> listOfKeys)
      throws ExecutionException, InterruptedException {
    String key1 = listOfKeys.get(0);
    String key2 = listOfKeys.get(1);

    CyclicBarrier startCyclicBarrier = new CyclicBarrier(2);

    jedis.sadd(key1, "foo", "bar");
    jedis.sadd(key2, "bar", "back");

    ExecutorService pool = Executors.newFixedThreadPool(2);

    Runnable renameKey1ToKey2 = () -> {
      cyclicBarrierAwait(startCyclicBarrier);
      jedis.rename(key1, key2);
    };

    Runnable renameKey2ToKey1 = () -> {
      cyclicBarrierAwait(startCyclicBarrier);
      jedis2.rename(key2, key1);
    };

    Future<?> future1 = pool.submit(renameKey1ToKey2);
    Future<?> future2 = pool.submit(renameKey2ToKey1);

    future1.get();
    future2.get();
  }

  private Long addStringsToKeys(
      Set<String> strings,
      String key,
      int numOfStrings,
      Jedis client) {
    generateStrings(numOfStrings, strings);
    String[] stringArray = strings.toArray(new String[strings.size()]);
    return client.sadd(key, stringArray);
  }

  private String renameKeys(Jedis client) {
    return client.rename("k1", "k2");
  }

  private Set<String> generateStrings(int elements, Set<String> strings) {
    for (int i = 0; i < elements; i++) {
      String elem = String.valueOf(i);
      strings.add(elem);
    }
    return strings;
  }

  @Test
  public void renamenxIsUnimplemented() {
    assertThatThrownBy(() -> jedis.renamenx("foo", "newfoo"))
        .hasMessageContaining("RENAMENX is not implemented.");
  }

}


text:
using System;
using System.Collections.Generic;
using System.Text;

namespace Anlab.Core.Models
{
    public class ClientInfo
    {
        public string ClientId { get; set; }
        public string Email { get; set; }
        public string Employer { get; set; }
        public string Department { get; set; }
        public string Name { get; set; }
        public string PhoneNumber { get; set; }
        public string CopyPhone { get; set; }

        public string PiName { get; set; }
        public string PiEmail { get; set; }
    }
}


text:
'use strict';

/**
 * Module dependencies.
 */
var should = require('should'),
	mongoose = require('mongoose'),
	User = mongoose.model('User'),
	Geofence = mongoose.model('Geofence');

/**
 * Globals
 */
var user, geofence;

/**
 * Unit tests
 */
describe('Geofence Model Unit Tests:', function() {
	beforeEach(function(done) {
		user = new User({
			firstName: 'Full',
			lastName: 'Name',
			displayName: 'Full Name',
			email: 'test@test.com',
			username: 'username',
			password: 'password'
		});

		user.save(function() {
			geofence = new Geofence({
				name: 'Geofence Name',
				loc:{ type: 'Polygon',
    coordinates: [
      [ [ 100.0 , 0.0 ] , [ 101.0 , 0.0 ] , [ 101.0 , 1.0 ] , [ 100.0 , 1.0 ] , [ 100.0 , 0.0 ] ]]
		},
				user: user
			});

			done();
		});
	});

	describe('Method Save', function() {
		it('should be able to save without problems', function(done) {
			return geofence.save(function(err) {
				should.not.exist(err);
				done();
			});
		});

		it('should be able to show an error when try to save without name', function(done) {
			geofence.name = '';

			return geofence.save(function(err) {
				should.exist(err);
				done();
			});
		});
	});

	afterEach(function(done) {
		Geofence.remove().exec();
		User.remove().exec();

		done();
	});
});


text:
{% extends "gnotty/base.html" %}
{% block content %}

Login

<form method="post" class="login">
    {% csrf_token %}
    <input type="text" required placeholder="username" name="username" value="{{ request.POST.username }}">
    <input type="password" required placeholder="password" name="password">
    <input type="submit" class="btn btn-primary" value="Login">
</form>

{% for message in messages %}

{{ message }}

{% endfor %}

{% endblock %}


text:
using System;
using System.Text;
using System.Net.Sockets;
using System.Threading;
using System.Collections.Generic;

namespace ChatServer
{
    public class ClientHandler
    {
        TcpClient clientSocket;
        string clNo;

        public void startClient(TcpClient inClientSocket, string clineNo)
        {
            this.clientSocket = inClientSocket;
            this.clNo = clineNo;
            Thread ctThread = new Thread(doChat);
            ctThread.Start();
        }
        private void doChat()
        {
            int requestCount = 0;
            byte[] bytesFrom = new byte[1024];
            string dataFromClient = null;
            Byte[] sendBytes = new byte[1024];
            string rCount = null;
            requestCount = 0;

            bool runningClient = true;
            bool loggedIn = false;
            String username = null;
            String password = null;

            while (runningClient)
            {
                try
                {
                    requestCount = requestCount + 1;
                    NetworkStream networkStream = clientSocket.GetStream();
                    networkStream.Read(bytesFrom, 0, 1024);
                    dataFromClient = System.Text.Encoding.ASCII.GetString(bytesFrom);
                    dataFromClient = dataFromClient.Substring(0, dataFromClient.IndexOf("$"));
                    Console.WriteLine(" >> " + "From client-" + clNo + dataFromClient);

                    rCount = Convert.ToString(requestCount);

                    switch(dataFromClient)
                    {
                        case "who":
                            foreach(string person in Program.activeUsers.Keys)
                            {
                                Program.SendToUser(person, username, false, clientSocket, true);
                            }
                            break;

                        case "logout":
                            if(loggedIn)
                            {
                                runningClient = false;
                                //Change to unicast
                                Program.Broadcast("User " + username + " logged out.", username, true);
                                Program.activeUsers.Remove(username);
                            }
                            else
                            {
                                Program.SendToUser("Cannot logout if not logged in.", username, false, clientSocket, true);
                            }
                            break;

                        default:
                            if(dataFromClient.StartsWith("login "))
                            {
                                string loginStuff = RemoveString(dataFromClient, "login ");
                                username = null;
                                password = null;
                                ExtractLogin(ref username, ref password, loginStuff);

                                Console.WriteLine(username + " " + password);

                                if (username == null || password == null)
                                {
                                    Program.SendToUser("Login Failed.", username, false, clientSocket, true);
                                }
                                else
                                {
                                    string pass;
                                    if(Program.users.TryGetValue(username, out pass))
                                    {
                                        if (pass.Equals(password))
                                        {
                                            if (Program.activeUsers.Count == Program.maxClients)
                                            {
                                                Program.SendToUser("Max number of users in the chat, try again later.", username, false, clientSocket, true);
                                            }
                                            else
                                            {
                                                Program.Broadcast(username + " has joined.", username, true);
                                                Program.SendToUser("Login Accepted.", username, false, clientSocket, true);
                                                Program.activeUsers.Add(username, clientSocket);
                                                loggedIn = true;
                                            }
                                        }
                                        else
                                        {
                                            Program.SendToUser("Login Failed! ", username, false, clientSocket, true);
                                        }
                                    }
                                    else
                                    {
                                        Program.SendToUser("Login Failed.", username, false, clientSocket, true);
                                    }

                                }
                            }
                            else if(dataFromClient.StartsWith("send all "))
                            {
                                if (loggedIn)
                                {
                                    string message = RemoveString(dataFromClient, "send all ");
                                    Program.Broadcast(message, username, true);
                                }
                                else
                                {
                                    Program.SendToUser("You must be logged in to send messages.", username, false, clientSocket, true);
                                }
                            }
                            else if(dataFromClient.StartsWith("send "))
                            {
                                if(loggedIn)
                                {
                                    string message = RemoveString(dataFromClient, "send ");
                                    string[] pieces = message.Split(' ');

                                    bool found = false;
                                    foreach(string user in Program.activeUsers.Keys)
                                    {
                                        if(pieces[0].Equals(user))
                                        {
                                            found = true;
                                            message = RemoveString(message, user + " ");
                                            Program.SendToUser(message, user, true, Program.activeUsers[user], true);
                                        }
                                    }

                                    if(!found)
                                    {
                                        Program.SendToUser("User you tried to send to is not in the chat", username, false, clientSocket, true);
                                    }
                                }
                                else
                                {
                                    Program.SendToUser("You must be logged in to send messages.", username, false, clientSocket, true);
                                }
                            }
                            else
                            {
                                Program.SendToUser("Could not understand the command: " + dataFromClient + ".", username, false, clientSocket, true);
                            }
                            break;
                    }
                }
                catch (InvalidOperationException ioe)
                {
                    Console.WriteLine(ioe);
                    break;
                }
                catch (Exception ex)
                {
                    Console.WriteLine(" >> " + ex.ToString());
                }
            }
        }

        private static string RemoveString(string input, string removal)
        {
            int index = input.IndexOf(removal);
            string message = (index < 0)
                ? input
                : input.Remove(index, removal.Length);

            return message;
        }

        private static void ExtractLogin(ref String userId, ref String password, string loginStuff)
        {
            //Error checking
            string[] stringSeparators = new string[] { " " };
            string[] inputs = loginStuff.Split(stringSeparators, StringSplitOptions.None);

            if (inputs.Length< 2 || inputs.Length> 2)
            {
                Console.WriteLine("Incorrect number of login arguments. Try again.");
            }

            foreach (string input in inputs)
            {
                if (String.IsNullOrEmpty(input) || String.IsNullOrWhiteSpace(input))
                {
                    Console.WriteLine("Empty or missing login arguments.");
                    break;
                }

                if (userId == null)
                {
                    userId = input;
                }
                else if (password == null)
                {
                    password = input;
                }
            }
        }
    }
}


text:
package fm.liu.timo.parser.visitor;

import java.util.Collection;
import fm.liu.timo.parser.ast.ASTNode;
import fm.liu.timo.parser.ast.expression.BinaryOperatorExpression;
import fm.liu.timo.parser.ast.expression.PolyadicOperatorExpression;
import fm.liu.timo.parser.ast.expression.UnaryOperatorExpression;
import fm.liu.timo.parser.ast.expression.comparison.BetweenAndExpression;
import fm.liu.timo.parser.ast.expression.comparison.ComparisionEqualsExpression;
import fm.liu.timo.parser.ast.expression.comparison.ComparisionGreaterThanExpression;
import fm.liu.timo.parser.ast.expression.comparison.ComparisionGreaterThanOrEqualsExpression;
import fm.liu.timo.parser.ast.expression.comparison.ComparisionIsExpression;
import fm.liu.timo.parser.ast.expression.comparison.ComparisionLessThanExpression;
import fm.liu.timo.parser.ast.expression.comparison.ComparisionLessThanOrEqualsExpression;
import fm.liu.timo.parser.ast.expression.comparison.ComparisionNullSafeEqualsExpression;
import fm.liu.timo.parser.ast.expression.comparison.InExpression;
import fm.liu.timo.parser.ast.expression.logical.LogicalAndExpression;
import fm.liu.timo.parser.ast.expression.logical.LogicalOrExpression;
import fm.liu.timo.parser.ast.expression.misc.InExpressionList;
import fm.liu.timo.parser.ast.expression.misc.UserExpression;
import fm.liu.timo.parser.ast.expression.primary.CaseWhenOperatorExpression;
import fm.liu.timo.parser.ast.expression.primary.DefaultValue;
import fm.liu.timo.parser.ast.expression.primary.ExistsPrimary;
import fm.liu.timo.parser.ast.expression.primary.Identifier;
import fm.liu.timo.parser.ast.expression.primary.MatchExpression;
import fm.liu.timo.parser.ast.expression.primary.ParamMarker;
import fm.liu.timo.parser.ast.expression.primary.PlaceHolder;
import fm.liu.timo.parser.ast.expression.primary.RowExpression;
import fm.liu.timo.parser.ast.expression.primary.SysVarPrimary;
import fm.liu.timo.parser.ast.expression.primary.UsrDefVarPrimary;
import fm.liu.timo.parser.ast.expression.primary.function.FunctionExpression;
import fm.liu.timo.parser.ast.expression.primary.function.cast.Cast;
import fm.liu.timo.parser.ast.expression.primary.function.cast.Convert;
import fm.liu.timo.parser.ast.expression.primary.function.datetime.Extract;
import fm.liu.timo.parser.ast.expression.primary.function.datetime.GetFormat;
import fm.liu.timo.parser.ast.expression.primary.function.datetime.Timestampadd;
import fm.liu.timo.parser.ast.expression.primary.function.datetime.Timestampdiff;
import fm.liu.timo.parser.ast.expression.primary.function.groupby.Avg;
import fm.liu.timo.parser.ast.expression.primary.function.groupby.Count;
import fm.liu.timo.parser.ast.expression.primary.function.groupby.GroupConcat;
import fm.liu.timo.parser.ast.expression.primary.function.groupby.Max;
import fm.liu.timo.parser.ast.expression.primary.function.groupby.Min;
import fm.liu.timo.parser.ast.expression.primary.function.groupby.Sum;
import fm.liu.timo.parser.ast.expression.primary.function.string.Char;
import fm.liu.timo.parser.ast.expression.primary.function.string.Trim;
import fm.liu.timo.parser.ast.expression.primary.literal.IntervalPrimary;
import fm.liu.timo.parser.ast.expression.primary.literal.LiteralBitField;
import fm.liu.timo.parser.ast.expression.primary.literal.LiteralBoolean;
import fm.liu.timo.parser.ast.expression.primary.literal.LiteralHexadecimal;
import fm.liu.timo.parser.ast.expression.primary.literal.LiteralNull;
import fm.liu.timo.parser.ast.expression.primary.literal.LiteralNumber;
import fm.liu.timo.parser.ast.expression.primary.literal.LiteralString;
import fm.liu.timo.parser.ast.expression.string.LikeExpression;
import fm.liu.timo.parser.ast.expression.type.CollateExpression;
import fm.liu.timo.parser.ast.fragment.GroupBy;
import fm.liu.timo.parser.ast.fragment.Limit;
import fm.liu.timo.parser.ast.fragment.OrderBy;
import fm.liu.timo.parser.ast.fragment.ddl.ColumnDefinition;
import fm.liu.timo.parser.ast.fragment.ddl.TableOptions;
import fm.liu.timo.parser.ast.fragment.ddl.datatype.DataType;
import fm.liu.timo.parser.ast.fragment.ddl.index.IndexColumnName;
import fm.liu.timo.parser.ast.fragment.ddl.index.IndexOption;
import fm.liu.timo.parser.ast.fragment.tableref.Dual;
import fm.liu.timo.parser.ast.fragment.tableref.IndexHint;
import fm.liu.timo.parser.ast.fragment.tableref.InnerJoin;
import fm.liu.timo.parser.ast.fragment.tableref.NaturalJoin;
import fm.liu.timo.parser.ast.fragment.tableref.OuterJoin;
import fm.liu.timo.parser.ast.fragment.tableref.StraightJoin;
import fm.liu.timo.parser.ast.fragment.tableref.SubqueryFactor;
import fm.liu.timo.parser.ast.fragment.tableref.TableRefFactor;
import fm.liu.timo.parser.ast.fragment.tableref.TableReferences;
import fm.liu.timo.parser.ast.stmt.dal.DALSetCharacterSetStatement;
import fm.liu.timo.parser.ast.stmt.dal.DALSetNamesStatement;
import fm.liu.timo.parser.ast.stmt.dal.DALSetStatement;
import fm.liu.timo.parser.ast.stmt.dal.ShowAuthors;
import fm.liu.timo.parser.ast.stmt.dal.ShowBinLogEvent;
import fm.liu.timo.parser.ast.stmt.dal.ShowBinaryLog;
import fm.liu.timo.parser.ast.stmt.dal.ShowCharaterSet;
import fm.liu.timo.parser.ast.stmt.dal.ShowCollation;
import fm.liu.timo.parser.ast.stmt.dal.ShowColumns;
import fm.liu.timo.parser.ast.stmt.dal.ShowContributors;
import fm.liu.timo.parser.ast.stmt.dal.ShowCreate;
import fm.liu.timo.parser.ast.stmt.dal.ShowDatabases;
import fm.liu.timo.parser.ast.stmt.dal.ShowEngine;
import fm.liu.timo.parser.ast.stmt.dal.ShowEngines;
import fm.liu.timo.parser.ast.stmt.dal.ShowErrors;
import fm.liu.timo.parser.ast.stmt.dal.ShowEvents;
import fm.liu.timo.parser.ast.stmt.dal.ShowFunctionCode;
import fm.liu.timo.parser.ast.stmt.dal.ShowFunctionStatus;
import fm.liu.timo.parser.ast.stmt.dal.ShowGrants;
import fm.liu.timo.parser.ast.stmt.dal.ShowIndex;
import fm.liu.timo.parser.ast.stmt.dal.ShowMasterStatus;
import fm.liu.timo.parser.ast.stmt.dal.ShowOpenTables;
import fm.liu.timo.parser.ast.stmt.dal.ShowPlugins;
import fm.liu.timo.parser.ast.stmt.dal.ShowPrivileges;
import fm.liu.timo.parser.ast.stmt.dal.ShowProcedureCode;
import fm.liu.timo.parser.ast.stmt.dal.ShowProcedureStatus;
import fm.liu.timo.parser.ast.stmt.dal.ShowProcesslist;
import fm.liu.timo.parser.ast.stmt.dal.ShowProfile;
import fm.liu.timo.parser.ast.stmt.dal.ShowProfiles;
import fm.liu.timo.parser.ast.stmt.dal.ShowSlaveHosts;
import fm.liu.timo.parser.ast.stmt.dal.ShowSlaveStatus;
import fm.liu.timo.parser.ast.stmt.dal.ShowStatus;
import fm.liu.timo.parser.ast.stmt.dal.ShowTableStatus;
import fm.liu.timo.parser.ast.stmt.dal.ShowTables;
import fm.liu.timo.parser.ast.stmt.dal.ShowTriggers;
import fm.liu.timo.parser.ast.stmt.dal.ShowVariables;
import fm.liu.timo.parser.ast.stmt.dal.ShowWarnings;
import fm.liu.timo.parser.ast.stmt.ddl.DDLAlterTableStatement;
import fm.liu.timo.parser.ast.stmt.ddl.DDLCreateIndexStatement;
import fm.liu.timo.parser.ast.stmt.ddl.DDLCreateTableStatement;
import fm.liu.timo.parser.ast.stmt.ddl.DDLDropIndexStatement;
import fm.liu.timo.parser.ast.stmt.ddl.DDLDropTableStatement;
import fm.liu.timo.parser.ast.stmt.ddl.DDLRenameTableStatement;
import fm.liu.timo.parser.ast.stmt.ddl.DDLTruncateStatement;
import fm.liu.timo.parser.ast.stmt.ddl.DescTableStatement;
import fm.liu.timo.parser.ast.stmt.ddl.DDLAlterTableStatement.AlterSpecification;
import fm.liu.timo.parser.ast.stmt.dml.DMLCallStatement;
import fm.liu.timo.parser.ast.stmt.dml.DMLDeleteStatement;
import fm.liu.timo.parser.ast.stmt.dml.DMLInsertStatement;
import fm.liu.timo.parser.ast.stmt.dml.DMLReplaceStatement;
import fm.liu.timo.parser.ast.stmt.dml.DMLSelectStatement;
import fm.liu.timo.parser.ast.stmt.dml.DMLSelectUnionStatement;
import fm.liu.timo.parser.ast.stmt.dml.DMLUpdateStatement;
import fm.liu.timo.parser.ast.stmt.extension.ExtDDLCreatePolicy;
import fm.liu.timo.parser.ast.stmt.extension.ExtDDLDropPolicy;
import fm.liu.timo.parser.ast.stmt.mts.MTSReleaseStatement;
import fm.liu.timo.parser.ast.stmt.mts.MTSRollbackStatement;
import fm.liu.timo.parser.ast.stmt.mts.MTSSavepointStatement;
import fm.liu.timo.parser.ast.stmt.mts.MTSSetTransactionStatement;
import fm.liu.timo.parser.util.Pair;

public abstract class Visitor {

    @SuppressWarnings({"rawtypes"})
    protected void visitChild(Object obj) {
        if (obj == null)
            return;
        if (obj instanceof ASTNode) {
            ((ASTNode) obj).accept(this);
        } else if (obj instanceof Collection) {
            for (Object o : (Collection) obj) {
                visitChild(o);
            }
        } else if (obj instanceof Pair) {
            visitChild(((Pair) obj).getKey());
            visitChild(((Pair) obj).getValue());
        }
    }

    public void visit(BetweenAndExpression node) {
        visitChild(node.getFirst());
        visitChild(node.getSecond());
        visitChild(node.getThird());
    }

    public void visit(ComparisionIsExpression node) {
        visitChild(node.getOperand());
    }

    public void visit(InExpressionList node) {
        visitChild(node.getList());
    }

    public void visit(LikeExpression node) {
        visitChild(node.getFirst());
        visitChild(node.getSecond());
        visitChild(node.getThird());
    }

    public void visit(CollateExpression node) {
        visitChild(node.getString());
    }

    public void visit(UserExpression node) {}

    public void visit(UnaryOperatorExpression node) {
        visitChild(node.getOperand());
    }

    public void visit(BinaryOperatorExpression node) {
        visitChild(node.getLeftOprand());
        visitChild(node.getRightOprand());
    }

    public void visit(PolyadicOperatorExpression node) {
        for (int i = 0, len = node.getArity(); i < len; ++i) {
            visitChild(node.getOperand(i));
        }
    }

    public void visit(LogicalAndExpression node) {
        visit((PolyadicOperatorExpression) node);
    }

    public void visit(LogicalOrExpression node) {
        visit((PolyadicOperatorExpression) node);
    }

    public void visit(ComparisionEqualsExpression node) {
        visit((BinaryOperatorExpression) node);
    }

    public void visit(ComparisionNullSafeEqualsExpression node) {
        visit((BinaryOperatorExpression) node);
    }

    public void visit(ComparisionGreaterThanExpression node) {
        visitChild(node.getLeftOprand());
        visitChild(node.getRightOprand());
    }

    public void visit(ComparisionGreaterThanOrEqualsExpression node) {
        visitChild(node.getLeftOprand());
        visitChild(node.getRightOprand());
    }

    public void visit(ComparisionLessThanExpression node) {
        visitChild(node.getLeftOprand());
        visitChild(node.getRightOprand());
    }

    public void visit(ComparisionLessThanOrEqualsExpression node) {
        visitChild(node.getLeftOprand());
        visitChild(node.getRightOprand());
    }

    public void visit(InExpression node) {
        visit((BinaryOperatorExpression) node);
    }

    public void visit(FunctionExpression node) {
        visitChild(node.getArguments());
    }

    public void visit(Char node) {
        visit((FunctionExpression) node);
    }

    public void visit(Convert node) {
        visit((FunctionExpression) node);
    }

    public void visit(Trim node) {
        visit((FunctionExpression) node);
        visitChild(node.getRemainString());
        visitChild(node.getString());
    }

    public void visit(Cast node) {
        visit((FunctionExpression) node);
        visitChild(node.getExpr());
        visitChild(node.getTypeInfo1());
        visitChild(node.getTypeInfo2());
    }

    public void visit(Avg node) {
        visit((FunctionExpression) node);
    }

    public void visit(Max node) {
        visit((FunctionExpression) node);
    }

    public void visit(Min node) {
        visit((FunctionExpression) node);
    }

    public void visit(Sum node) {
        visit((FunctionExpression) node);
    }

    public void visit(Count node) {
        visit((FunctionExpression) node);
    }

    public void visit(GroupConcat node) {
        visit((FunctionExpression) node);
        visitChild(node.getAppendedColumnNames());
        visitChild(node.getOrderBy());
    }

    public void visit(Timestampdiff node) {}

    public void visit(Timestampadd node) {}

    public void visit(Extract node) {}

    public void visit(GetFormat node) {}

    public void visit(IntervalPrimary node) {
        visitChild(node.getQuantity());
    }

    public void visit(LiteralBitField node) {}

    public void visit(LiteralBoolean node) {}

    public void visit(LiteralHexadecimal node) {}

    public void visit(LiteralNull node) {}

    public void visit(LiteralNumber node) {}

    public void visit(LiteralString node) {}

    public void visit(CaseWhenOperatorExpression node) {
        visitChild(node.getComparee());
        visitChild(node.getElseResult());
        visitChild(node.getWhenList());
    }

    public void visit(DefaultValue node) {}

    public void visit(ExistsPrimary node) {
        visitChild(node.getSubquery());
    }

    public void visit(PlaceHolder node) {}

    public void visit(Identifier node) {}

    public void visit(MatchExpression node) {
        visitChild(node.getColumns());
        visitChild(node.getPattern());
    }

    public void visit(ParamMarker node) {}

    public void visit(RowExpression node) {
        visitChild(node.getRowExprList());
    }

    public void visit(SysVarPrimary node) {}

    public void visit(UsrDefVarPrimary node) {}

    public void visit(IndexHint node) {}

    public void visit(InnerJoin node) {
        visitChild(node.getLeftTableRef());
        visitChild(node.getOnCond());
        visitChild(node.getRightTableRef());
    }

    public void visit(NaturalJoin node) {
        visitChild(node.getLeftTableRef());
        visitChild(node.getRightTableRef());
    }

    public void visit(OuterJoin node) {
        visitChild(node.getLeftTableRef());
        visitChild(node.getOnCond());
        visitChild(node.getRightTableRef());
    }

    public void visit(StraightJoin node) {
        visitChild(node.getLeftTableRef());
        visitChild(node.getOnCond());
        visitChild(node.getRightTableRef());
    }

    public void visit(SubqueryFactor node) {
        visitChild(node.getSubquery());
    }

    public void visit(TableReferences node) {
        visitChild(node.getTableReferenceList());
    }

    public void visit(TableRefFactor node) {
        visitChild(node.getHintList());
        visitChild(node.getTable());
    }

    public void visit(Dual dual) {}

    public void visit(GroupBy node) {
        visitChild(node.getOrderByList());
    }

    public void visit(Limit node) {
        visitChild(node.getOffset());
        visitChild(node.getSize());
    }

    public void visit(OrderBy node) {
        visitChild(node.getOrderByList());
    }

    public void visit(ColumnDefinition columnDefinition) {}

    public void visit(IndexOption indexOption) {}

    public void visit(IndexColumnName indexColumnName) {}

    public void visit(TableOptions node) {}

    public void visit(AlterSpecification node) {}

    public void visit(DataType node) {}

    public void visit(ShowAuthors node) {}

    public void visit(ShowBinaryLog node) {}

    public void visit(ShowBinLogEvent node) {
        visitChild(node.getLimit());
        visitChild(node.getPos());
    }

    public void visit(ShowCharaterSet node) {
        visitChild(node.getWhere());
    }

    public void visit(ShowCollation node) {
        visitChild(node.getWhere());
    }

    public void visit(ShowColumns node) {
        visitChild(node.getTable());
        visitChild(node.getWhere());
    }

    public void visit(ShowContributors node) {}

    public void visit(ShowCreate node) {
        visitChild(node.getId());
    }

    public void visit(ShowDatabases node) {
        visitChild(node.getWhere());
    }

    public void visit(ShowEngine node) {}

    public void visit(ShowEngines node) {}

    public void visit(ShowErrors node) {
        visitChild(node.getLimit());
    }

    public void visit(ShowEvents node) {
        visitChild(node.getSchema());
        visitChild(node.getWhere());
    }

    public void visit(ShowFunctionCode node) {
        visitChild(node.getFunctionName());
    }

    public void visit(ShowFunctionStatus node) {
        visitChild(node.getWhere());
    }

    public void visit(ShowGrants node) {
        visitChild(node.getUser());
    }

    public void visit(ShowIndex node) {
        visitChild(node.getTable());
    }

    public void visit(ShowMasterStatus node) {}

    public void visit(ShowOpenTables node) {
        visitChild(node.getSchema());
        visitChild(node.getWhere());
    }

    public void visit(ShowPlugins node) {}

    public void visit(ShowPrivileges node) {}

    public void visit(ShowProcedureCode node) {
        visitChild(node.getProcedureName());
    }

    public void visit(ShowProcedureStatus node) {
        visitChild(node.getWhere());
    }

    public void visit(ShowProcesslist node) {}

    public void visit(ShowProfile node) {
        visitChild(node.getForQuery());
        visitChild(node.getLimit());
    }

    public void visit(ShowProfiles node) {}

    public void visit(ShowSlaveHosts node) {}

    public void visit(ShowSlaveStatus node) {}

    public void visit(ShowStatus node) {
        visitChild(node.getWhere());
    }

    public void visit(ShowTables node) {
        visitChild(node.getSchema());
        visitChild(node.getWhere());
    }

    public void visit(ShowTableStatus node) {
        visitChild(node.getDatabase());
        visitChild(node.getWhere());
    }

    public void visit(ShowTriggers node) {
        visitChild(node.getSchema());
        visitChild(node.getWhere());
    }

    public void visit(ShowVariables node) {
        visitChild(node.getWhere());
    }

    public void visit(ShowWarnings node) {
        visitChild(node.getLimit());
    }

    public void visit(DescTableStatement node) {
        visitChild(node.getTable());
    }

    public void visit(DALSetStatement node) {
        visitChild(node.getAssignmentList());
    }

    public void visit(DALSetNamesStatement node) {}

    public void visit(DALSetCharacterSetStatement node) {}

    public void visit(DMLCallStatement node) {
        visitChild(node.getArguments());
        visitChild(node.getProcedure());
    }

    public void visit(DMLDeleteStatement node) {
        visitChild(node.getLimit());
        visitChild(node.getOrderBy());
        visitChild(node.getTableNames());
        visitChild(node.getTableRefs());
        visitChild(node.getWhereCondition());
    }

    public void visit(DMLInsertStatement node) {
        visitChild(node.getColumnNameList());
        visitChild(node.getDuplicateUpdate());
        visitChild(node.getRowList());
        visitChild(node.getSelect());
        visitChild(node.getTable());
    }

    public void visit(DMLReplaceStatement node) {
        visitChild(node.getColumnNameList());
        visitChild(node.getRowList());
        visitChild(node.getSelect());
        visitChild(node.getTable());
    }

    public void visit(DMLSelectStatement node) {
        visitChild(node.getGroup());
        visitChild(node.getHaving());
        visitChild(node.getLimit());
        visitChild(node.getOrder());
        visitChild(node.getSelectExprList());
        visitChild(node.getTables());
        visitChild(node.getWhere());
    }

    public void visit(DMLSelectUnionStatement node) {
        visitChild(node.getLimit());
        visitChild(node.getOrderBy());
        visitChild(node.getSelectStmtList());
    }

    public void visit(DMLUpdateStatement node) {
        visitChild(node.getLimit());
        visitChild(node.getOrderBy());
        visitChild(node.getTableRefs());
        visitChild(node.getValues());
        visitChild(node.getWhere());
    }

    public void visit(MTSSetTransactionStatement node) {}

    public void visit(MTSSavepointStatement node) {
        visitChild(node.getSavepoint());
    }

    public void visit(MTSReleaseStatement node) {
        visitChild(node.getSavepoint());
    }

    public void visit(MTSRollbackStatement node) {
        visitChild(node.getSavepoint());
    }

    public void visit(DDLTruncateStatement node) {
        visitChild(node.getTable());
    }

    public void visit(DDLAlterTableStatement node) {
        visitChild(node.getTable());
    }

    public void visit(DDLCreateIndexStatement node) {
        visitChild(node.getIndexName());
        visitChild(node.getTable());
    }

    public void visit(DDLCreateTableStatement node) {
        visitChild(node.getTable());
    }

    public void visit(DDLRenameTableStatement node) {
        visitChild(node.getList());
    }

    public void visit(DDLDropIndexStatement node) {
        visitChild(node.getIndexName());
        visitChild(node.getTable());
    }

    public void visit(DDLDropTableStatement node) {
        visitChild(node.getTableNames());
    }

    public void visit(ExtDDLCreatePolicy node) {}

    public void visit(ExtDDLDropPolicy node) {}

}


text:
1. OC调用JS

	- [context evaluateScript:alertJS]

2. JS调用OC

	- 2.1 使用JavaScriptCore.framework框架

	- 2.2 使用自定义url方法

3. 获取webView中的源码内容

	- [webView stringByEvaluatingJavaScriptFromString:titleString]

	- 字符串:document.title等等


text:
package org.lwjgl.system.jawt;

import java.nio.*;

import org.lwjgl.*;
import org.lwjgl.system.*;

import static org.lwjgl.system.MemoryUtil.*;
import static org.lwjgl.system.MemoryStack.*;

/**
 * Structure for a native rectangle.
 *
 *
Member documentation

 *
 *

 *
{@code x} – the rectangle X axis coordinate

 *
{@code y} – the rectangle Y axis coordinate

 *
{@code width} – the rectangle width

 *
{@code height} – the rectangle height

 *

 *
 *
Layout

 *
 *
struct JAWT_Rectangle {
    jint x;
    jint y;
    jint width;
    jint height;
}

 */
public class JAWTRectangle extends Struct implements NativeResource {

	/** The struct size in bytes. */
	public static final int SIZEOF;

	public static final int ALIGNOF;

	/** The struct member offsets. */
	public static final int
		X,
		Y,
		WIDTH,
		HEIGHT;

	static {
		Layout layout = __struct(
			__member(4),
			__member(4),
			__member(4),
			__member(4)
		);

		SIZEOF = layout.getSize();
		ALIGNOF = layout.getAlignment();

		X = layout.offsetof(0);
		Y = layout.offsetof(1);
		WIDTH = layout.offsetof(2);
		HEIGHT = layout.offsetof(3);
	}

	JAWTRectangle(long address, ByteBuffer container) {
		super(address, container);
	}

	/**
	 * Creates a {@link JAWTRectangle} instance at the current position of the specified {@link ByteBuffer} container. Changes to the buffer's content will be
	 * visible to the struct instance and vice versa.
	 *
	 *
The created instance holds a strong reference to the container object.

	 */
	public JAWTRectangle(ByteBuffer container) {
		this(memAddress(container), checkContainer(container, SIZEOF));
	}

	@Override
	public int sizeof() { return SIZEOF; }

	/** Returns the value of the {@code x} field. */
	public int x() { return nx(address()); }
	/** Returns the value of the {@code y} field. */
	public int y() { return ny(address()); }
	/** Returns the value of the {@code width} field. */
	public int width() { return nwidth(address()); }
	/** Returns the value of the {@code height} field. */
	public int height() { return nheight(address()); }

	/** Sets the specified value to the {@code x} field. */
	public JAWTRectangle x(int value) { nx(address(), value); return this; }
	/** Sets the specified value to the {@code y} field. */
	public JAWTRectangle y(int value) { ny(address(), value); return this; }
	/** Sets the specified value to the {@code width} field. */
	public JAWTRectangle width(int value) { nwidth(address(), value); return this; }
	/** Sets the specified value to the {@code height} field. */
	public JAWTRectangle height(int value) { nheight(address(), value); return this; }

	/** Initializes this struct with the specified values. */
	public JAWTRectangle set(
		int x,
		int y,
		int width,
		int height
	) {
		x(x);
		y(y);
		width(width);
		height(height);

		return this;
	}

	/** Unsafe version of {@link #set(JAWTRectangle) set}. */
	public JAWTRectangle nset(long struct) {
		memCopy(struct, address(), SIZEOF);
		return this;
	}

	/**
	 * Copies the specified struct data to this struct.
	 *
	 * @param src the source struct
	 *
	 * @return this struct
	 */
	public JAWTRectangle set(JAWTRectangle src) {
		return nset(src.address());
	}

	// -----------------------------------

	/** Returns a new {@link JAWTRectangle} instance allocated with {@link MemoryUtil#memAlloc memAlloc}. The instance must be explicitly freed. */
	public static JAWTRectangle malloc() {
		return create(nmemAlloc(SIZEOF));
	}

	/** Returns a new {@link JAWTRectangle} instance allocated with {@link MemoryUtil#memCalloc memCalloc}. The instance must be explicitly freed. */
	public static JAWTRectangle calloc() {
		return create(nmemCalloc(1, SIZEOF));
	}

	/** Returns a new {@link JAWTRectangle} instance allocated with {@link BufferUtils}. */
	public static JAWTRectangle create() {
		return new JAWTRectangle(BufferUtils.createByteBuffer(SIZEOF));
	}

	/** Returns a new {@link JAWTRectangle} instance for the specified memory address or {@code null} if the address is {@code NULL}. */
	public static JAWTRectangle create(long address) {
		return address == NULL ? null : new JAWTRectangle(address, null);
	}

	/**
	 * Returns a new {@link JAWTRectangle.Buffer} instance allocated with {@link MemoryUtil#memAlloc memAlloc}. The instance must be explicitly freed.
	 *
	 * @param capacity the buffer capacity
	 */
	public static Buffer malloc(int capacity) {
		return create(nmemAlloc(capacity * SIZEOF), capacity);
	}

	/**
	 * Returns a new {@link JAWTRectangle.Buffer} instance allocated with {@link MemoryUtil#memCalloc memCalloc}. The instance must be explicitly freed.
	 *
	 * @param capacity the buffer capacity
	 */
	public static Buffer calloc(int capacity) {
		return create(nmemCalloc(capacity, SIZEOF), capacity);
	}

	/**
	 * Returns a new {@link JAWTRectangle.Buffer} instance allocated with {@link BufferUtils}.
	 *
	 * @param capacity the buffer capacity
	 */
	public static Buffer create(int capacity) {
		return new Buffer(BufferUtils.createByteBuffer(capacity * SIZEOF));
	}

	/**
	 * Create a {@link JAWTRectangle.Buffer} instance at the specified memory.
	 *
	 * @param address  the memory address
	 * @param capacity the buffer capacity
	 */
	public static Buffer create(long address, int capacity) {
		return address == NULL ? null : new Buffer(address, null, -1, 0, capacity, capacity);
	}

	// -----------------------------------

	/** Returns a new {@link JAWTRectangle} instance allocated on the thread-local {@link MemoryStack}. */
	public static JAWTRectangle mallocStack() {
		return mallocStack(stackGet());
	}

	/** Returns a new {@link JAWTRectangle} instance allocated on the thread-local {@link MemoryStack} and initializes all its bits to zero. */
	public static JAWTRectangle callocStack() {
		return callocStack(stackGet());
	}

	/**
	 * Returns a new {@link JAWTRectangle} instance allocated on the specified {@link MemoryStack}.
	 *
	 * @param stack the stack from which to allocate
	 */
	public static JAWTRectangle mallocStack(MemoryStack stack) {
		return create(stack.nmalloc(ALIGNOF, SIZEOF));
	}

	/**
	 * Returns a new {@link JAWTRectangle} instance allocated on the specified {@link MemoryStack} and initializes all its bits to zero.
	 *
	 * @param stack the stack from which to allocate
	 */
	public static JAWTRectangle callocStack(MemoryStack stack) {
		return create(stack.ncalloc(ALIGNOF, 1, SIZEOF));
	}

	/**
	 * Returns a new {@link JAWTRectangle.Buffer} instance allocated on the thread-local {@link MemoryStack}.
	 *
	 * @param capacity the buffer capacity
	 */
	public static Buffer mallocStack(int capacity) {
		return mallocStack(capacity, stackGet());
	}

	/**
	 * Returns a new {@link JAWTRectangle.Buffer} instance allocated on the thread-local {@link MemoryStack} and initializes all its bits to zero.
	 *
	 * @param capacity the buffer capacity
	 */
	public static Buffer callocStack(int capacity) {
		return callocStack(capacity, stackGet());
	}

	/**
	 * Returns a new {@link JAWTRectangle.Buffer} instance allocated on the specified {@link MemoryStack}.
	 *
	 * @param stack the stack from which to allocate
	 * @param capacity the buffer capacity
	 */
	public static Buffer mallocStack(int capacity, MemoryStack stack) {
		return create(stack.nmalloc(ALIGNOF, capacity * SIZEOF), capacity);
	}

	/**
	 * Returns a new {@link JAWTRectangle.Buffer} instance allocated on the specified {@link MemoryStack} and initializes all its bits to zero.
	 *
	 * @param stack the stack from which to allocate
	 * @param capacity the buffer capacity
	 */
	public static Buffer callocStack(int capacity, MemoryStack stack) {
		return create(stack.ncalloc(ALIGNOF, capacity, SIZEOF), capacity);
	}

	// -----------------------------------

	/** Unsafe version of {@link #x}. */
	public static int nx(long struct) { return memGetInt(struct + JAWTRectangle.X); }
	/** Unsafe version of {@link #y}. */
	public static int ny(long struct) { return memGetInt(struct + JAWTRectangle.Y); }
	/** Unsafe version of {@link #width}. */
	public static int nwidth(long struct) { return memGetInt(struct + JAWTRectangle.WIDTH); }
	/** Unsafe version of {@link #height}. */
	public static int nheight(long struct) { return memGetInt(struct + JAWTRectangle.HEIGHT); }

	/** Unsafe version of {@link #x(int) x}. */
	public static void nx(long struct, int value) { memPutInt(struct + JAWTRectangle.X, value); }
	/** Unsafe version of {@link #y(int) y}. */
	public static void ny(long struct, int value) { memPutInt(struct + JAWTRectangle.Y, value); }
	/** Unsafe version of {@link #width(int) width}. */
	public static void nwidth(long struct, int value) { memPutInt(struct + JAWTRectangle.WIDTH, value); }
	/** Unsafe version of {@link #height(int) height}. */
	public static void nheight(long struct, int value) { memPutInt(struct + JAWTRectangle.HEIGHT, value); }

	// -----------------------------------

	/** An array of {@link JAWTRectangle} structs. */
	public static class Buffer extends StructBuffer<JAWTRectangle, Buffer> implements NativeResource {

		/**
		 * Creates a new {@link JAWTRectangle.Buffer} instance backed by the specified container.
		 *
		 * Changes to the container's content will be visible to the struct buffer instance and vice versa. The two buffers' position, limit, and mark values
		 * will be independent. The new buffer's position will be zero, its capacity and its limit will be the number of bytes remaining in this buffer divided
		 * by {@link JAWTRectangle#SIZEOF}, and its mark will be undefined.
		 *
		 *
The created buffer instance holds a strong reference to the container object.

		 */
		public Buffer(ByteBuffer container) {
			super(container, container.remaining() / SIZEOF);
		}

		Buffer(long address, ByteBuffer container, int mark, int pos, int lim, int cap) {
			super(address, container, mark, pos, lim, cap);
		}

		@Override
		protected Buffer self() {
			return this;
		}

		@Override
		protected Buffer newBufferInstance(long address, ByteBuffer container, int mark, int pos, int lim, int cap) {
			return new Buffer(address, container, mark, pos, lim, cap);
		}

		@Override
		protected JAWTRectangle newInstance(long address) {
			return new JAWTRectangle(address, container);
		}

		@Override
		protected int sizeof() {
			return SIZEOF;
		}

		/** Returns the value of the {@code x} field. */
		public int x() { return JAWTRectangle.nx(address()); }
		/** Returns the value of the {@code y} field. */
		public int y() { return JAWTRectangle.ny(address()); }
		/** Returns the value of the {@code width} field. */
		public int width() { return JAWTRectangle.nwidth(address()); }
		/** Returns the value of the {@code height} field. */
		public int height() { return JAWTRectangle.nheight(address()); }

		/** Sets the specified value to the {@code x} field. */
		public JAWTRectangle.Buffer x(int value) { JAWTRectangle.nx(address(), value); return this; }
		/** Sets the specified value to the {@code y} field. */
		public JAWTRectangle.Buffer y(int value) { JAWTRectangle.ny(address(), value); return this; }
		/** Sets the specified value to the {@code width} field. */
		public JAWTRectangle.Buffer width(int value) { JAWTRectangle.nwidth(address(), value); return this; }
		/** Sets the specified value to the {@code height} field. */
		public JAWTRectangle.Buffer height(int value) { JAWTRectangle.nheight(address(), value); return this; }

	}

}