text:
package nkarasch.repeatingreminder.gui;

import android.app.ActionBar.LayoutParams;
import android.content.Context;
import android.content.DialogInterface;
import android.content.res.Resources;
import android.content.res.TypedArray;
import android.os.Bundle;
import android.support.v4.app.DialogFragment;
import android.support.v4.content.ContextCompat;
import android.text.format.DateFormat;
import android.util.Log;
import android.view.KeyCharacterMap;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnKeyListener;
import android.view.ViewGroup;
import android.view.Window;
import android.widget.Button;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.codetroopers.betterpickers.HapticFeedbackController;
import com.codetroopers.betterpickers.R;
import com.codetroopers.betterpickers.Utils;
import com.codetroopers.betterpickers.numberpicker.NumberPickerErrorTextView;
import com.codetroopers.betterpickers.radialtimepicker.RadialPickerLayout;
import com.codetroopers.betterpickers.radialtimepicker.RadialPickerLayout.OnValueSelectedListener;
import com.nineoldandroids.animation.ObjectAnimator;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.text.DateFormatSymbols;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Locale;

/**
 * Dialog to set a time.
 *
 * Sloppily modified from android-betterpickers RadialTimePickerDialogFragment to allow setting theme colors programatically
 * https://github.com/code-troopers/android-betterpickers
 */
public class ProgrammableStyleableRadialTimePickerDialogFragment extends DialogFragment implements OnValueSelectedListener {

    private static final String TAG = "TimePickerDialog";

    private static final String KEY_HOUR_OF_DAY = "hour_of_day";
    private static final String KEY_MINUTE = "minute";
    private static final String KEY_IS_24_HOUR_VIEW = "is_24_hour_view";
    private static final String KEY_CURRENT_ITEM_SHOWING = "current_item_showing";
    private static final String KEY_IN_KB_MODE = "in_kb_mode";
    private static final String KEY_TYPED_TIMES = "typed_times";
    private static final String KEY_STYLE = "theme";
    private static final String KEY_FUTURE_MINUTES_LIMIT = "future_minutes_limit";
    private static final String KEY_PAST_MINUTES_LIMIT = "past_minutes_limit";
    private static final String KEY_CURRENT_DATE = "current_date";
    private static final String KEY_PICKER_DATE = "picker_date";

    public static final int HOUR_INDEX = 0;
    public static final int MINUTE_INDEX = 1;
    // NOT a real index for the purpose of what's showing.
    public static final int AMPM_INDEX = 2;
    // Also NOT a real index, just used for keyboard mode.
    public static final int ENABLE_PICKER_INDEX = 3;
    public static final int AM = 0;
    public static final int PM = 1;

    // Delay before starting the pulse animation, in ms.
    private static final int PULSE_ANIMATOR_DELAY = 300;

    private OnDialogDismissListener mDimissCallback;
    private OnTimeSetListener mCallback;

    private HapticFeedbackController mHapticFeedbackController;

    private Button mDoneButton;
    private TextView mHourView;
    private TextView mHourSpaceView;
    private TextView mMinuteView;
    private TextView mMinuteSpaceView;
    private TextView mAmPmTextView;
    private View mAmPmHitspace;
    private RadialPickerLayout mTimePicker;
    private TextView mTitleTextView;
    private NumberPickerErrorTextView mError;

    private int mSelectedColor;
    private int mUnselectedColor;
    private String mAmText;
    private String mPmText;
    private String mDoneText;
    private String mCancelText;
    private String mTitleText;

    private boolean mAllowAutoAdvance;
    private int mInitialHourOfDay;
    private int mInitialMinute;
    private Boolean mIs24HourMode;
    private int mStyleResId;
    private Integer mFutureMinutesLimit;
    private Integer mPastMinutesLimit;
    private Calendar mValidateDateTime;
    private Calendar mPickerDate;

    // For hardware IME input.
    private char mPlaceholderText;
    private String mDoublePlaceholderText;
    private String mDeletedKeyFormat;
    private boolean mInKbMode;
    private ArrayList<Integer> mTypedTimes;
    private Node mLegalTimesTree;
    private int mAmKeyCode;
    private int mPmKeyCode;

    // Accessibility strings.
    private String mHourPickerDescription;
    private String mSelectHours;
    private String mMinutePickerDescription;
    private String mSelectMinutes;

    private ProgrammableStyle mProgrammableStyle;

    /**
     * The callback interface used to indicate the user is done filling in the time (they clicked on the 'Set' button).
     */
    public interface OnTimeSetListener {

        /**
         * @param dialog    The view associated with this listener.
         * @param hourOfDay The hour that was set.
         * @param minute    The minute that was set.
         */
        void onTimeSet(ProgrammableStyleableRadialTimePickerDialogFragment dialog, int hourOfDay, int minute);
    }

    public interface OnDialogDismissListener {

        void onDialogDismiss(DialogInterface dialoginterface);
    }

    public ProgrammableStyleableRadialTimePickerDialogFragment() {
        Calendar calendar = Calendar.getInstance();
        mInitialMinute = calendar.get(Calendar.MINUTE);
        mInitialHourOfDay = calendar.get(Calendar.HOUR_OF_DAY);
        mInKbMode = false;
        mStyleResId = R.style.BetterPickersRadialTimePickerDialog_PrimaryColor;
        mProgrammableStyle = new ProgrammableStyle();
    }

    public ProgrammableStyleableRadialTimePickerDialogFragment setThemeDark() {
        mStyleResId = R.style.BetterPickersRadialTimePickerDialog_Dark;
        return this;
    }

    public ProgrammableStyleableRadialTimePickerDialogFragment setThemeLight() {
        mStyleResId = R.style.BetterPickersRadialTimePickerDialog_Light;
        return this;
    }

    public ProgrammableStyleableRadialTimePickerDialogFragment setStyleProgramatically(ProgrammableStyle programmableStyle) {
        this.mProgrammableStyle = programmableStyle;
        return this;
    }

    /**
     * @param styleResId a style modeled after the styleable "BetterPickersRadialTimePickerDialog".
     *                   There is an example in the android-betterpickers sample under res/values/styles.xml
     */
    public ProgrammableStyleableRadialTimePickerDialogFragment setThemeCustom(int styleResId) {
        mStyleResId = styleResId;
        return this;
    }

    public boolean isThemeDark() {
        return mStyleResId == R.style.BetterPickersRadialTimePickerDialog_Dark;
    }

    public ProgrammableStyleableRadialTimePickerDialogFragment setOnDismissListener(OnDialogDismissListener ondialogdismisslistener) {
        mDimissCallback = ondialogdismisslistener;
        return this;
    }

    public ProgrammableStyleableRadialTimePickerDialogFragment setOnTimeSetListener(OnTimeSetListener callback) {
        mCallback = callback;
        return this;
    }

    public ProgrammableStyleableRadialTimePickerDialogFragment setStartTime(int hourOfDay, int minute) {
        mInitialHourOfDay = hourOfDay;
        mInitialMinute = minute;
        mInKbMode = false;
        return this;
    }

    public ProgrammableStyleableRadialTimePickerDialogFragment setTitleText(String text) {
        mTitleText = text;
        return this;
    }

    public ProgrammableStyleableRadialTimePickerDialogFragment setDoneText(String text) {
        mDoneText = text;
        return this;
    }

    public ProgrammableStyleableRadialTimePickerDialogFragment setFutureMinutesLimit(Integer futureMinutesLimit) {
        this.mFutureMinutesLimit = futureMinutesLimit;
        return this;
    }

    public ProgrammableStyleableRadialTimePickerDialogFragment setPastMinutesLimit(Integer pastMinutesLimit) {
        this.mPastMinutesLimit = pastMinutesLimit;
        return this;
    }

    public ProgrammableStyleableRadialTimePickerDialogFragment setValidateDateTime(Calendar validateDateTime) {
        this.mValidateDateTime = validateDateTime;
        return this;
    }

    public ProgrammableStyleableRadialTimePickerDialogFragment setPickerDate(Calendar pickerDate) {
        this.mPickerDate = pickerDate;
        return this;
    }

    public ProgrammableStyleableRadialTimePickerDialogFragment setCancelText(String text) {
        mCancelText = text;
        return this;
    }

    public ProgrammableStyleableRadialTimePickerDialogFragment setForced24hFormat() {
        mIs24HourMode = true;
        return this;
    }

    public ProgrammableStyleableRadialTimePickerDialogFragment setForced12hFormat() {
        mIs24HourMode = false;
        return this;
    }

    /**
     * Autodetect is done by default if nothing is specified
     */
    @Deprecated
    public ProgrammableStyleableRadialTimePickerDialogFragment setAutodetectDateFormat(Context context) {
        mIs24HourMode = DateFormat.is24HourFormat(context);
        return this;
    }

    @Override
    public void onDismiss(DialogInterface dialoginterface) {
        super.onDismiss(dialoginterface);
        if (mDimissCallback != null) {
            mDimissCallback.onDialogDismiss(dialoginterface);
        }
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (savedInstanceState != null && savedInstanceState.containsKey(KEY_HOUR_OF_DAY)
                && savedInstanceState.containsKey(KEY_MINUTE)
                && savedInstanceState.containsKey(KEY_IS_24_HOUR_VIEW)) {
            mInitialHourOfDay = savedInstanceState.getInt(KEY_HOUR_OF_DAY);
            mInitialMinute = savedInstanceState.getInt(KEY_MINUTE);
            mIs24HourMode = savedInstanceState.getBoolean(KEY_IS_24_HOUR_VIEW);
            mInKbMode = savedInstanceState.getBoolean(KEY_IN_KB_MODE);
            mStyleResId = savedInstanceState.getInt(KEY_STYLE);
            if (savedInstanceState.containsKey(KEY_FUTURE_MINUTES_LIMIT)) {
                mFutureMinutesLimit = savedInstanceState.getInt(KEY_FUTURE_MINUTES_LIMIT);
            }
            if (savedInstanceState.containsKey(KEY_PAST_MINUTES_LIMIT)) {
                mPastMinutesLimit = savedInstanceState.getInt(KEY_PAST_MINUTES_LIMIT);
            }
            if (savedInstanceState.containsKey(KEY_CURRENT_DATE)) {
                mValidateDateTime = (Calendar) savedInstanceState.getSerializable(KEY_CURRENT_DATE);
            }
            if (savedInstanceState.containsKey(KEY_PICKER_DATE)) {
                mPickerDate = (Calendar) savedInstanceState.getSerializable(KEY_PICKER_DATE);
            }
        } else {
            if (mIs24HourMode == null) {
                mIs24HourMode = DateFormat.is24HourFormat(getContext());
            }
        }
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        if (getShowsDialog()) {
            getDialog().getWindow().requestFeature(Window.FEATURE_NO_TITLE);
        }

        View view = inflater.inflate(R.layout.radial_time_picker_dialog, null);
        KeyboardListener keyboardListener = new KeyboardListener();
        view.findViewById(R.id.time_picker_dialog).setOnKeyListener(keyboardListener);

        Resources res = getResources();
        TypedArray themeColors = getActivity().obtainStyledAttributes(mStyleResId, R.styleable.BetterPickersDialogs);

        // Prepare some colors to use.
        int headerBgColor = (mProgrammableStyle.headerBgColor == -1) ? themeColors.getColor(R.styleable.BetterPickersDialogs_bpHeaderBackgroundColor, ContextCompat.getColor(getContext(), R.color.bpBlue)) : mProgrammableStyle.headerBgColor;
        int bodyBgColor = (mProgrammableStyle.bodyBgColor == -1) ? themeColors.getColor(R.styleable.BetterPickersDialogs_bpBodyBackgroundColor, ContextCompat.getColor(getContext(), R.color.bpWhite)) : mProgrammableStyle.bodyBgColor;
        int buttonBgColor = (mProgrammableStyle.buttonBgColor == -1) ? themeColors.getColor(R.styleable.BetterPickersDialogs_bpButtonsBackgroundColor, ContextCompat.getColor(getContext(), R.color.bpWhite)) : mProgrammableStyle.buttonBgColor;
        int buttonTextColor = (mProgrammableStyle.buttonTextColor == -1) ? themeColors.getColor(R.styleable.BetterPickersDialogs_bpButtonsTextColor, ContextCompat.getColor(getContext(), R.color.bpBlue)) : mProgrammableStyle.buttonTextColor;
        mSelectedColor = (mProgrammableStyle.selectedColor == - 1) ? themeColors.getColor(R.styleable.BetterPickersDialogs_bpHeaderSelectedTextColor, ContextCompat.getColor(getContext(), R.color.bpWhite)) : mProgrammableStyle.selectedColor;
        mUnselectedColor = (mProgrammableStyle.unselectedColor == - 1) ? themeColors.getColor(R.styleable.BetterPickersDialogs_bpHeaderUnselectedTextColor, ContextCompat.getColor(getContext(), R.color.radial_gray_light)) : mProgrammableStyle.unselectedColor;

        mHourPickerDescription = res.getString(R.string.hour_picker_description);
        mSelectHours = res.getString(R.string.select_hours);
        mMinutePickerDescription = res.getString(R.string.minute_picker_description);
        mSelectMinutes = res.getString(R.string.select_minutes);

        mHourView = (TextView) view.findViewById(R.id.hours);
        mHourView.setOnKeyListener(keyboardListener);
        mHourSpaceView = (TextView) view.findViewById(R.id.hour_space);
        mMinuteSpaceView = (TextView) view.findViewById(R.id.minutes_space);
        mMinuteView = (TextView) view.findViewById(R.id.minutes);
        mMinuteView.setOnKeyListener(keyboardListener);
        mAmPmTextView = (TextView) view.findViewById(R.id.ampm_label);
        mAmPmTextView.setOnKeyListener(keyboardListener);
        String[] amPmTexts = new DateFormatSymbols().getAmPmStrings();
        mAmText = amPmTexts[0];
        mPmText = amPmTexts[1];

        mHapticFeedbackController = new HapticFeedbackController(getActivity());

        mTimePicker = (RadialPickerLayout) view.findViewById(R.id.time_picker);
        mTimePicker.setOnValueSelectedListener(this);
        mTimePicker.setOnKeyListener(keyboardListener);
        mTimePicker.initialize(getActivity(), mHapticFeedbackController, mInitialHourOfDay, mInitialMinute, mIs24HourMode);

        int currentItemShowing = HOUR_INDEX;
        if (savedInstanceState != null && savedInstanceState.containsKey(KEY_CURRENT_ITEM_SHOWING)) {
            currentItemShowing = savedInstanceState.getInt(KEY_CURRENT_ITEM_SHOWING);
        }
        setCurrentItemShowing(currentItemShowing, false, true, true);
        mTimePicker.invalidate();

        mHourView.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                setCurrentItemShowing(HOUR_INDEX, true, false, true);
                tryVibrate();
            }
        });
        mMinuteView.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                setCurrentItemShowing(MINUTE_INDEX, true, false, true);
                tryVibrate();
            }
        });

        mTitleTextView = (TextView) view.findViewById(R.id.time_picker_header);
        if (mTitleText != null) {
            mTitleTextView.setVisibility(View.VISIBLE);
            mTitleTextView.setText(mTitleText);
        } else {
            mTitleTextView.setVisibility(View.GONE);
        }

        mError = (NumberPickerErrorTextView) view.findViewById(R.id.error);

        if (hasTimeLimits()) {
            mError.setVisibility(View.INVISIBLE);
        } else {
            mError.setVisibility(View.GONE);
        }

        mDoneButton = (Button) view.findViewById(R.id.done_button);
        if (mDoneText != null) {
            mDoneButton.setText(mDoneText);
        }
        mDoneButton.setTextColor(buttonTextColor);
        mDoneButton.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                if (mInKbMode && isTypedTimeFullyLegal()) {
                    finishKbMode(false);
                } else {
                    tryVibrate();
                }
                doneClickValidateAndCallback();
            }
        });
        mDoneButton.setOnKeyListener(keyboardListener);

        Button cancelButton = (Button) view.findViewById(R.id.cancel_button);
        if (mCancelText != null) {
            cancelButton.setText(mCancelText);
        }
        cancelButton.setTextColor(buttonTextColor);
        cancelButton.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                tryVibrate();
                dismiss();
            }
        });

        // Enable or disable the AM/PM view.
        mAmPmHitspace = view.findViewById(R.id.ampm_hitspace);
        if (mIs24HourMode) {
            mAmPmTextView.setVisibility(View.GONE);

            RelativeLayout.LayoutParams paramsSeparator = new RelativeLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
            paramsSeparator.addRule(RelativeLayout.CENTER_IN_PARENT);
            TextView separatorView = (TextView) view.findViewById(R.id.separator);
            separatorView.setLayoutParams(paramsSeparator);
        } else {
            mAmPmTextView.setVisibility(View.VISIBLE);
            updateAmPmDisplay(mInitialHourOfDay < 12 ? AM : PM);
            mAmPmHitspace.setOnClickListener(new OnClickListener() {
                @Override
                public void onClick(View v) {
                    tryVibrate();
                    int amOrPm = mTimePicker.getIsCurrentlyAmOrPm();
                    if (amOrPm == AM) {
                        amOrPm = PM;
                    } else if (amOrPm == PM) {
                        amOrPm = AM;
                    }
                    updateAmPmDisplay(amOrPm);
                    mTimePicker.setAmOrPm(amOrPm);
                }
            });
        }

        mAllowAutoAdvance = true;
        setHour(mInitialHourOfDay, true);
        setMinute(mInitialMinute);

        // Set up for keyboard mode.
        mDoublePlaceholderText = res.getString(R.string.time_placeholder);
        mDeletedKeyFormat = res.getString(R.string.deleted_key);
        mPlaceholderText = mDoublePlaceholderText.charAt(0);
        mAmKeyCode = mPmKeyCode = -1;
        generateLegalTimesTree();
        if (mInKbMode) {
            mTypedTimes = savedInstanceState.getIntegerArrayList(KEY_TYPED_TIMES);
            tryStartingKbMode(-1);
            mHourView.invalidate();
        } else if (mTypedTimes == null) {
            mTypedTimes = new ArrayList<>();
        }

        // Set the theme at the end so that the initialize()s above don't counteract the theme.
        try {
            Method setTheme = RadialPickerLayout.class.getDeclaredMethod("setTheme", TypedArray.class);
            setTheme.setAccessible(true);
            setTheme.invoke(mTimePicker, themeColors);
        } catch (NoSuchMethodException e) {
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        }

        // Set the colors for each view based on the theme.
        view.findViewById(R.id.time_display_background).setBackgroundColor(headerBgColor);
        view.findViewById(R.id.ok_cancel_buttons_layout).setBackgroundColor(buttonBgColor);
        view.findViewById(R.id.time_display).setBackgroundColor(headerBgColor);
        view.findViewById(R.id.time_picker_error_holder).setBackgroundColor(headerBgColor);
        ((TextView) view.findViewById(R.id.separator)).setTextColor(mUnselectedColor);
        ((TextView) view.findViewById(R.id.ampm_label)).setTextColor(mUnselectedColor);
        mTimePicker.setBackgroundColor(bodyBgColor);
        return view;
    }

    private boolean hasTimeLimits() {
        return mFutureMinutesLimit != null || mPastMinutesLimit != null;
    }

    @Override
    public void onResume() {
        super.onResume();
        mHapticFeedbackController.start();
    }

    @Override
    public void onPause() {
        super.onPause();
        mHapticFeedbackController.stop();
    }

    public void tryVibrate() {
        mHapticFeedbackController.tryVibrate();
    }

    private void updateAmPmDisplay(int amOrPm) {
        if (amOrPm == AM) {
            mAmPmTextView.setText(mAmText);
            Utils.tryAccessibilityAnnounce(mTimePicker, mAmText);
            mAmPmHitspace.setContentDescription(mAmText);
        } else if (amOrPm == PM) {
            mAmPmTextView.setText(mPmText);
            Utils.tryAccessibilityAnnounce(mTimePicker, mPmText);
            mAmPmHitspace.setContentDescription(mPmText);
        } else {
            mAmPmTextView.setText(mDoublePlaceholderText);
        }
    }

    @Override
    public void onSaveInstanceState(Bundle outState) {
        if (mTimePicker != null) {
            outState.putInt(KEY_HOUR_OF_DAY, mTimePicker.getHours());
            outState.putInt(KEY_MINUTE, mTimePicker.getMinutes());
            outState.putBoolean(KEY_IS_24_HOUR_VIEW, mIs24HourMode);
            outState.putInt(KEY_CURRENT_ITEM_SHOWING, mTimePicker.getCurrentItemShowing());
            outState.putBoolean(KEY_IN_KB_MODE, mInKbMode);
            if (mFutureMinutesLimit != null)
                outState.putInt(KEY_FUTURE_MINUTES_LIMIT, mFutureMinutesLimit);
            if (mPastMinutesLimit != null)
                outState.putInt(KEY_PAST_MINUTES_LIMIT, mPastMinutesLimit);
            outState.putSerializable(KEY_CURRENT_DATE, mValidateDateTime);
            outState.putSerializable(KEY_PICKER_DATE, mPickerDate);
            if (mInKbMode) outState.putIntegerArrayList(KEY_TYPED_TIMES, mTypedTimes);
            outState.putInt(KEY_STYLE, mStyleResId);
        }
    }

    /**
     * Checks if the selected time lays too far in the future
     *
     * @return true if too far in the future, false if not
     */
    public boolean isSelectionTooFarInTheFuture() {
        if (this.mPickerDate != null && this.mValidateDateTime != null && this.mFutureMinutesLimit != null) {
            Calendar selectedDate = Calendar.getInstance();
            selectedDate.setTime(this.mPickerDate.getTime());
            selectedDate.set(Calendar.HOUR_OF_DAY, mTimePicker.getHours());
            selectedDate.set(Calendar.MINUTE, mTimePicker.getMinutes());

            Calendar futureLimit = Calendar.getInstance();
            futureLimit.setTime(this.mValidateDateTime.getTime());
            futureLimit.add(Calendar.MINUTE, this.mFutureMinutesLimit);
            return selectedDate.compareTo(futureLimit) > 0;
        }
        return false;
    }

    /**
     * Checks if the selected time lays too far in the past
     *
     * @return true if too far in the past, false if not
     */
    public boolean isSelectionTooFarInPast() {
        if (this.mPickerDate != null && this.mValidateDateTime != null && this.mPastMinutesLimit != null) {
            Calendar selectedDate = Calendar.getInstance();
            selectedDate.setTime(this.mPickerDate.getTime());
            selectedDate.set(Calendar.HOUR_OF_DAY, mTimePicker.getHours());
            selectedDate.set(Calendar.MINUTE, mTimePicker.getMinutes());

            Calendar pastLimit = Calendar.getInstance();
            pastLimit.setTime(this.mValidateDateTime.getTime());
            pastLimit.add(Calendar.MINUTE, -this.mPastMinutesLimit);
            return selectedDate.compareTo(pastLimit) < 0;
        }
        return false;
    }

    /**
     * Called when the done button is pressed. Validates the input and performs a callback if valid.
     */
    public void doneClickValidateAndCallback() {
        if (isSelectionTooFarInTheFuture()) {
            if (mError != null) {
                mError.setText(getString(R.string.max_time_error));
                mError.show();
            }
        } else if (isSelectionTooFarInPast()) {
            if (mError != null) {
                mError.setText(getString(R.string.min_time_error));
                mError.show();
            }
        } else {
            if (mCallback != null) {
                mCallback.onTimeSet(ProgrammableStyleableRadialTimePickerDialogFragment.this, mTimePicker.getHours(), mTimePicker.getMinutes());
            }
            dismiss();
        }
    }

    /**
     * Called by the picker for updating the header display.
     */
    @Override
    public void onValueSelected(int pickerIndex, int newValue, boolean autoAdvance) {
        if (hasTimeLimits()) {
            mError.hideImmediately();
        }
        if (pickerIndex == HOUR_INDEX) {
            setHour(newValue, false);
            String announcement = String.format("%d", newValue);
            if (mAllowAutoAdvance && autoAdvance) {
                setCurrentItemShowing(MINUTE_INDEX, true, true, false);
                announcement += ". " + mSelectMinutes;
            } else {
                mTimePicker.setContentDescription(mHourPickerDescription + ": " + newValue);
            }
            Utils.tryAccessibilityAnnounce(mTimePicker, announcement);
        } else if (pickerIndex == MINUTE_INDEX) {
            setMinute(newValue);
            mTimePicker.setContentDescription(mMinutePickerDescription + ": " + newValue);
        } else if (pickerIndex == AMPM_INDEX) {
            updateAmPmDisplay(newValue);
        } else if (pickerIndex == ENABLE_PICKER_INDEX) {
            if (!isTypedTimeFullyLegal()) {
                mTypedTimes.clear();
            }
            finishKbMode(true);
        }
    }

    private void setHour(int value, boolean announce) {
        String format;
        if (mIs24HourMode) {
            format = "%02d";
        } else {
            format = "%d";
            value = value % 12;
            if (value == 0) {
                value = 12;
            }
        }

        CharSequence text = String.format(format, value);
        mHourView.setText(text);
        mHourSpaceView.setText(text);
        if (announce) {
            Utils.tryAccessibilityAnnounce(mTimePicker, text);
        }
    }

    private void setMinute(int value) {
        if (value == 60) {
            value = 0;
        }
        CharSequence text = String.format(Locale.getDefault(), "%02d", value);
        Utils.tryAccessibilityAnnounce(mTimePicker, text);
        mMinuteView.setText(text);
        mMinuteSpaceView.setText(text);
    }

    // Show either Hours or Minutes.
    private void setCurrentItemShowing(int index, boolean animateCircle, boolean delayLabelAnimate,
                                       boolean announce) {
        mTimePicker.setCurrentItemShowing(index, animateCircle);

        TextView labelToAnimate;
        if (index == HOUR_INDEX) {
            int hours = mTimePicker.getHours();
            if (!mIs24HourMode) {
                hours = hours % 12;
            }
            mTimePicker.setContentDescription(mHourPickerDescription + ": " + hours);
            if (announce) {
                Utils.tryAccessibilityAnnounce(mTimePicker, mSelectHours);
            }
            labelToAnimate = mHourView;
        } else {
            int minutes = mTimePicker.getMinutes();
            mTimePicker.setContentDescription(mMinutePickerDescription + ": " + minutes);
            if (announce) {
                Utils.tryAccessibilityAnnounce(mTimePicker, mSelectMinutes);
            }
            labelToAnimate = mMinuteView;
        }

        int hourColor = (index == HOUR_INDEX) ? mSelectedColor : mUnselectedColor;
        int minuteColor = (index == MINUTE_INDEX) ? mSelectedColor : mUnselectedColor;
        mHourView.setTextColor(hourColor);
        mMinuteView.setTextColor(minuteColor);

        ObjectAnimator pulseAnimator = Utils.getPulseAnimator(labelToAnimate, 0.85f, 1.1f);
        if (delayLabelAnimate) {
            pulseAnimator.setStartDelay(PULSE_ANIMATOR_DELAY);
        }
        pulseAnimator.start();
    }

    /**
     * For keyboard mode, processes key events.
     *
     * @param keyCode the pressed key.
     * @return true if the key was successfully processed, false otherwise.
     */
    private boolean processKeyUp(int keyCode) {
        if (keyCode == KeyEvent.KEYCODE_ESCAPE || keyCode == KeyEvent.KEYCODE_BACK) {
            dismiss();
            return true;
        } else if (keyCode == KeyEvent.KEYCODE_TAB) {
            if (mInKbMode) {
                if (isTypedTimeFullyLegal()) {
                    finishKbMode(true);
                }
                return true;
            }
        } else if (keyCode == KeyEvent.KEYCODE_ENTER) {
            if (mInKbMode) {
                if (!isTypedTimeFullyLegal()) {
                    return true;
                }
                finishKbMode(false);
            }
            doneClickValidateAndCallback();
            return true;
        } else if (keyCode == KeyEvent.KEYCODE_DEL) {
            if (mInKbMode) {
                if (!mTypedTimes.isEmpty()) {
                    int deleted = deleteLastTypedKey();
                    String deletedKeyStr;
                    if (deleted == getAmOrPmKeyCode(AM)) {
                        deletedKeyStr = mAmText;
                    } else if (deleted == getAmOrPmKeyCode(PM)) {
                        deletedKeyStr = mPmText;
                    } else {
                        deletedKeyStr = String.format("%d", getValFromKeyCode(deleted));
                    }
                    Utils.tryAccessibilityAnnounce(mTimePicker,
                            String.format(mDeletedKeyFormat, deletedKeyStr));
                    updateDisplay(true);
                }
            }
        } else if (keyCode == KeyEvent.KEYCODE_0 || keyCode == KeyEvent.KEYCODE_1
                || keyCode == KeyEvent.KEYCODE_2 || keyCode == KeyEvent.KEYCODE_3
                || keyCode == KeyEvent.KEYCODE_4 || keyCode == KeyEvent.KEYCODE_5
                || keyCode == KeyEvent.KEYCODE_6 || keyCode == KeyEvent.KEYCODE_7
                || keyCode == KeyEvent.KEYCODE_8 || keyCode == KeyEvent.KEYCODE_9
                || (!mIs24HourMode &&
                (keyCode == getAmOrPmKeyCode(AM) || keyCode == getAmOrPmKeyCode(PM)))) {
            if (!mInKbMode) {
                if (mTimePicker == null) {
                    // Something's wrong, because time picker should definitely not be null.
                    Log.e(TAG, "Unable to initiate keyboard mode, TimePicker was null.");
                    return true;
                }
                mTypedTimes.clear();
                tryStartingKbMode(keyCode);
                return true;
            }
            // We're already in keyboard mode.
            if (addKeyIfLegal(keyCode)) {
                updateDisplay(false);
            }
            return true;
        }
        return false;
    }

    /**
     * Try to start keyboard mode with the specified key, as long as the timepicker is not in the middle of a
     * touch-event.
     *
     * @param keyCode The key to use as the first press. Keyboard mode will not be started if the key is not legal to
     *                start with. Or, pass in -1 to get into keyboard mode without a starting key.
     */
    private void tryStartingKbMode(int keyCode) {
        if (mTimePicker.trySettingInputEnabled(false) &&
                (keyCode == -1 || addKeyIfLegal(keyCode))) {
            mInKbMode = true;
            mDoneButton.setEnabled(false);
            updateDisplay(false);
        }
    }

    private boolean addKeyIfLegal(int keyCode) {
        // If we're in 24hour mode, we'll need to check if the input is full. If in AM/PM mode,
        // we'll need to see if AM/PM have been typed.
        if ((mIs24HourMode && mTypedTimes.size() == 4) ||
                (!mIs24HourMode && isTypedTimeFullyLegal())) {
            return false;
        }

        mTypedTimes.add(keyCode);
        if (!isTypedTimeLegalSoFar()) {
            deleteLastTypedKey();
            return false;
        }

        int val = getValFromKeyCode(keyCode);
        Utils.tryAccessibilityAnnounce(mTimePicker, String.format("%d", val));
        // Automatically fill in 0's if AM or PM was legally entered.
        if (isTypedTimeFullyLegal()) {
            if (!mIs24HourMode && mTypedTimes.size() <= 3) {
                mTypedTimes.add(mTypedTimes.size() - 1, KeyEvent.KEYCODE_0);
                mTypedTimes.add(mTypedTimes.size() - 1, KeyEvent.KEYCODE_0);
            }
            mDoneButton.setEnabled(true);
        }

        return true;
    }

    /**
     * Traverse the tree to see if the keys that have been typed so far are legal as is, or may become legal as more
     * keys are typed (excluding backspace).
     */
    private boolean isTypedTimeLegalSoFar() {
        Node node = mLegalTimesTree;
        for (int keyCode : mTypedTimes) {
            node = node.canReach(keyCode);
            if (node == null) {
                return false;
            }
        }
        return true;
    }

    /**
     * Check if the time that has been typed so far is completely legal, as is.
     */
    private boolean isTypedTimeFullyLegal() {
        if (mIs24HourMode) {
            // For 24-hour mode, the time is legal if the hours and minutes are each legal. Note:
            // getEnteredTime() will ONLY call isTypedTimeFullyLegal() when NOT in 24hour mode.
            int[] values = getEnteredTime(null);
            return (values[0] >= 0 && values[1] >= 0 && values[1] < 60);
        } else {
            // For AM/PM mode, the time is legal if it contains an AM or PM, as those can only be
            // legally added at specific times based on the tree's algorithm.
            return (mTypedTimes.contains(getAmOrPmKeyCode(AM)) ||
                    mTypedTimes.contains(getAmOrPmKeyCode(PM)));
        }
    }

    private int deleteLastTypedKey() {
        int deleted = mTypedTimes.remove(mTypedTimes.size() - 1);
        if (!isTypedTimeFullyLegal()) {
            mDoneButton.setEnabled(false);
        }
        return deleted;
    }

    /**
     * Get out of keyboard mode. If there is nothing in typedTimes, revert to TimePicker's time.
     *
     * @param updateDisplays If true, update the displays with the relevant time.
     */
    private void finishKbMode(boolean updateDisplays) {
        mInKbMode = false;
        if (!mTypedTimes.isEmpty()) {
            int values[] = getEnteredTime(null);
            mTimePicker.setTime(values[0], values[1]);
            if (!mIs24HourMode) {
                mTimePicker.setAmOrPm(values[2]);
            }
            mTypedTimes.clear();
        }
        if (updateDisplays) {
            updateDisplay(false);
            mTimePicker.trySettingInputEnabled(true);
        }
    }

    /**
     * Update the hours, minutes, and AM/PM displays with the typed times. If the typedTimes is empty, either show an
     * empty display (filled with the placeholder text), or update from the timepicker's values.
     *
     * @param allowEmptyDisplay if true, then if the typedTimes is empty, use the placeholder text. Otherwise, revert to
     *                          the timepicker's values.
     */
    private void updateDisplay(boolean allowEmptyDisplay) {
        if (!allowEmptyDisplay && mTypedTimes.isEmpty()) {
            int hour = mTimePicker.getHours();
            int minute = mTimePicker.getMinutes();
            setHour(hour, true);
            setMinute(minute);
            if (!mIs24HourMode) {
                updateAmPmDisplay(hour < 12 ? AM : PM);
            }
            setCurrentItemShowing(mTimePicker.getCurrentItemShowing(), true, true, true);
            mDoneButton.setEnabled(true);
        } else {
            Boolean[] enteredZeros = {false, false};
            int[] values = getEnteredTime(enteredZeros);
            String hourFormat = enteredZeros[0] ? "%02d" : "%2d";
            String minuteFormat = (enteredZeros[1]) ? "%02d" : "%2d";
            String hourStr = (values[0] == -1) ? mDoublePlaceholderText :
                    String.format(hourFormat, values[0]).replace(' ', mPlaceholderText);
            String minuteStr = (values[1] == -1) ? mDoublePlaceholderText :
                    String.format(minuteFormat, values[1]).replace(' ', mPlaceholderText);
            mHourView.setText(hourStr);
            mHourSpaceView.setText(hourStr);
            mHourView.setTextColor(mUnselectedColor);
            mMinuteView.setText(minuteStr);
            mMinuteSpaceView.setText(minuteStr);
            mMinuteView.setTextColor(mUnselectedColor);
            if (!mIs24HourMode) {
                updateAmPmDisplay(values[2]);
            }
        }
    }

    private int getValFromKeyCode(int keyCode) {
        switch (keyCode) {
            case KeyEvent.KEYCODE_0:
                return 0;
            case KeyEvent.KEYCODE_1:
                return 1;
            case KeyEvent.KEYCODE_2:
                return 2;
            case KeyEvent.KEYCODE_3:
                return 3;
            case KeyEvent.KEYCODE_4:
                return 4;
            case KeyEvent.KEYCODE_5:
                return 5;
            case KeyEvent.KEYCODE_6:
                return 6;
            case KeyEvent.KEYCODE_7:
                return 7;
            case KeyEvent.KEYCODE_8:
                return 8;
            case KeyEvent.KEYCODE_9:
                return 9;
            default:
                return -1;
        }
    }

    /**
     * Get the currently-entered time, as integer values of the hours and minutes typed.
     *
     * @param enteredZeros A size-2 boolean array, which the caller should initialize, and which may then be used for
     *                     the caller to know whether zeros had been explicitly entered as either hours of minutes. This is helpful for
     *                     deciding whether to show the dashes, or actual 0's.
     * @return A size-3 int array. The first value will be the hours, the second value will be the minutes, and the
     * third will be either TimePickerDialog.AM or TimePickerDialog.PM.
     */
    private int[] getEnteredTime(Boolean[] enteredZeros) {
        int amOrPm = -1;
        int startIndex = 1;
        if (!mIs24HourMode && isTypedTimeFullyLegal()) {
            int keyCode = mTypedTimes.get(mTypedTimes.size() - 1);
            if (keyCode == getAmOrPmKeyCode(AM)) {
                amOrPm = AM;
            } else if (keyCode == getAmOrPmKeyCode(PM)) {
                amOrPm = PM;
            }
            startIndex = 2;
        }
        int minute = -1;
        int hour = -1;
        for (int i = startIndex; i <= mTypedTimes.size(); i++) {
            int val = getValFromKeyCode(mTypedTimes.get(mTypedTimes.size() - i));
            if (i == startIndex) {
                minute = val;
            } else if (i == startIndex + 1) {
                minute += 10 * val;
                if (enteredZeros != null && val == 0) {
                    enteredZeros[1] = true;
                }
            } else if (i == startIndex + 2) {
                hour = val;
            } else if (i == startIndex + 3) {
                hour += 10 * val;
                if (enteredZeros != null && val == 0) {
                    enteredZeros[0] = true;
                }
            }
        }

        return new int[]{hour, minute, amOrPm};
    }

    /**
     * Get the keycode value for AM and PM in the current language.
     */
    private int getAmOrPmKeyCode(int amOrPm) {
        // Cache the codes.
        if (mAmKeyCode == -1 || mPmKeyCode == -1) {
            // Find the first character in the AM/PM text that is unique.
            KeyCharacterMap kcm = KeyCharacterMap.load(KeyCharacterMap.VIRTUAL_KEYBOARD);
            char amChar;
            char pmChar;
            for (int i = 0; i < Math.max(mAmText.length(), mPmText.length()); i++) {
                amChar = mAmText.toLowerCase(Locale.getDefault()).charAt(i);
                pmChar = mPmText.toLowerCase(Locale.getDefault()).charAt(i);
                if (amChar != pmChar) {
                    KeyEvent[] events = kcm.getEvents(new char[]{amChar, pmChar});
                    // There should be 4 events: a down and up for both AM and PM.
                    if (events != null && events.length == 4) {
                        mAmKeyCode = events[0].getKeyCode();
                        mPmKeyCode = events[2].getKeyCode();
                    } else {
                        Log.e(TAG, "Unable to find keycodes for AM and PM.");
                    }
                    break;
                }
            }
        }
        if (amOrPm == AM) {
            return mAmKeyCode;
        } else if (amOrPm == PM) {
            return mPmKeyCode;
        }

        return -1;
    }

    /**
     * Create a tree for deciding what keys can legally be typed.
     */
    private void generateLegalTimesTree() {
        // Create a quick cache of numbers to their keycodes.
        int k0 = KeyEvent.KEYCODE_0;
        int k1 = KeyEvent.KEYCODE_1;
        int k2 = KeyEvent.KEYCODE_2;
        int k3 = KeyEvent.KEYCODE_3;
        int k4 = KeyEvent.KEYCODE_4;
        int k5 = KeyEvent.KEYCODE_5;
        int k6 = KeyEvent.KEYCODE_6;
        int k7 = KeyEvent.KEYCODE_7;
        int k8 = KeyEvent.KEYCODE_8;
        int k9 = KeyEvent.KEYCODE_9;

        // The root of the tree doesn't contain any numbers.
        mLegalTimesTree = new Node();
        if (mIs24HourMode) {
            // We'll be re-using these nodes, so we'll save them.
            Node minuteFirstDigit = new Node(k0, k1, k2, k3, k4, k5);
            Node minuteSecondDigit = new Node(k0, k1, k2, k3, k4, k5, k6, k7, k8, k9);
            // The first digit must be followed by the second digit.
            minuteFirstDigit.addChild(minuteSecondDigit);

            // The first digit may be 0-1.
            Node firstDigit = new Node(k0, k1);
            mLegalTimesTree.addChild(firstDigit);

            // When the first digit is 0-1, the second digit may be 0-5.
            Node secondDigit = new Node(k0, k1, k2, k3, k4, k5);
            firstDigit.addChild(secondDigit);
            // We may now be followed by the first minute digit. E.g. 00:09, 15:58.
            secondDigit.addChild(minuteFirstDigit);

            // When the first digit is 0-1, and the second digit is 0-5, the third digit may be 6-9.
            Node thirdDigit = new Node(k6, k7, k8, k9);
            // The time must now be finished. E.g. 0:55, 1:08.
            secondDigit.addChild(thirdDigit);

            // When the first digit is 0-1, the second digit may be 6-9.
            secondDigit = new Node(k6, k7, k8, k9);
            firstDigit.addChild(secondDigit);
            // We must now be followed by the first minute digit. E.g. 06:50, 18:20.
            secondDigit.addChild(minuteFirstDigit);

            // The first digit may be 2.
            firstDigit = new Node(k2);
            mLegalTimesTree.addChild(firstDigit);

            // When the first digit is 2, the second digit may be 0-3.
            secondDigit = new Node(k0, k1, k2, k3);
            firstDigit.addChild(secondDigit);
            // We must now be followed by the first minute digit. E.g. 20:50, 23:09.
            secondDigit.addChild(minuteFirstDigit);

            // When the first digit is 2, the second digit may be 4-5.
            secondDigit = new Node(k4, k5);
            firstDigit.addChild(secondDigit);
            // We must now be followd by the last minute digit. E.g. 2:40, 2:53.
            secondDigit.addChild(minuteSecondDigit);

            // The first digit may be 3-9.
            firstDigit = new Node(k3, k4, k5, k6, k7, k8, k9);
            mLegalTimesTree.addChild(firstDigit);
            // We must now be followed by the first minute digit. E.g. 3:57, 8:12.
            firstDigit.addChild(minuteFirstDigit);
        } else {
            // We'll need to use the AM/PM node a lot.
            // Set up AM and PM to respond to "a" and "p".
            Node ampm = new Node(getAmOrPmKeyCode(AM), getAmOrPmKeyCode(PM));

            // The first hour digit may be 1.
            Node firstDigit = new Node(k1);
            mLegalTimesTree.addChild(firstDigit);
            // We'll allow quick input of on-the-hour times. E.g. 1pm.
            firstDigit.addChild(ampm);

            // When the first digit is 1, the second digit may be 0-2.
            Node secondDigit = new Node(k0, k1, k2);
            firstDigit.addChild(secondDigit);
            // Also for quick input of on-the-hour times. E.g. 10pm, 12am.
            secondDigit.addChild(ampm);

            // When the first digit is 1, and the second digit is 0-2, the third digit may be 0-5.
            Node thirdDigit = new Node(k0, k1, k2, k3, k4, k5);
            secondDigit.addChild(thirdDigit);
            // The time may be finished now. E.g. 1:02pm, 1:25am.
            thirdDigit.addChild(ampm);

            // When the first digit is 1, the second digit is 0-2, and the third digit is 0-5,
            // the fourth digit may be 0-9.
            Node fourthDigit = new Node(k0, k1, k2, k3, k4, k5, k6, k7, k8, k9);
            thirdDigit.addChild(fourthDigit);
            // The time must be finished now. E.g. 10:49am, 12:40pm.
            fourthDigit.addChild(ampm);

            // When the first digit is 1, and the second digit is 0-2, the third digit may be 6-9.
            thirdDigit = new Node(k6, k7, k8, k9);
            secondDigit.addChild(thirdDigit);
            // The time must be finished now. E.g. 1:08am, 1:26pm.
            thirdDigit.addChild(ampm);

            // When the first digit is 1, the second digit may be 3-5.
            secondDigit = new Node(k3, k4, k5);
            firstDigit.addChild(secondDigit);

            // When the first digit is 1, and the second digit is 3-5, the third digit may be 0-9.
            thirdDigit = new Node(k0, k1, k2, k3, k4, k5, k6, k7, k8, k9);
            secondDigit.addChild(thirdDigit);
            // The time must be finished now. E.g. 1:39am, 1:50pm.
            thirdDigit.addChild(ampm);

            // The hour digit may be 2-9.
            firstDigit = new Node(k2, k3, k4, k5, k6, k7, k8, k9);
            mLegalTimesTree.addChild(firstDigit);
            // We'll allow quick input of on-the-hour-times. E.g. 2am, 5pm.
            firstDigit.addChild(ampm);

            // When the first digit is 2-9, the second digit may be 0-5.
            secondDigit = new Node(k0, k1, k2, k3, k4, k5);
            firstDigit.addChild(secondDigit);

            // When the first digit is 2-9, and the second digit is 0-5, the third digit may be 0-9.
            thirdDigit = new Node(k0, k1, k2, k3, k4, k5, k6, k7, k8, k9);
            secondDigit.addChild(thirdDigit);
            // The time must be finished now. E.g. 2:57am, 9:30pm.
            thirdDigit.addChild(ampm);
        }
    }

    public class ProgrammableStyle {
        int headerBgColor = -1;
        int bodyBgColor = -1;
        int buttonBgColor = -1;
        int buttonTextColor = -1;
        int selectedColor = -1;
        int unselectedColor = -1;
    }

    /**
     * Simple node class to be used for traversal to check for legal times. mLegalKeys represents the keys that can be
     * typed to get to the node. mChildren are the children that can be reached from this node.
     */
    private class Node {

        private int[] mLegalKeys;
        private ArrayList<Node> mChildren;

        public Node(int... legalKeys) {
            mLegalKeys = legalKeys;
            mChildren = new ArrayList<>();
        }

        public void addChild(Node child) {
            mChildren.add(child);
        }

        public boolean containsKey(int key) {
            for (int mLegalKey : mLegalKeys) {
                if (mLegalKey == key) {
                    return true;
                }
            }
            return false;
        }

        public Node canReach(int key) {
            if (mChildren == null) {
                return null;
            }
            for (Node child : mChildren) {
                if (child.containsKey(key)) {
                    return child;
                }
            }
            return null;
        }
    }

    private class KeyboardListener implements OnKeyListener {

        @Override
        public boolean onKey(View v, int keyCode, KeyEvent event) {
            return event.getAction() == KeyEvent.ACTION_UP && processKeyUp(keyCode);
        }
    }
}


text:
<?xml version="1.0" encoding="UTF-8" standalone="no"?>

<project name="testSimpleTriggerHooks">
	<taskdef resource="net/meisen/ant/tasks/antlib.xml" />

	<defineHook name="SimpleHook">
		<attribute name="testAttribute1" />
		<attribute name="testAttribute2" default="true" />
	</defineHook>

	<hook name="SimpleHook">
		<sequential>
			<echo>Called SimpleHook</echo>
		</sequential>
	</hook>

	<target name="testTarget">
		<triggerHooks name="SimpleHook">
			<attributeValue name="testAttribute2" value="sampleValue" />
		</triggerHooks>
	</target>
</project>

redpajama_set_name: RedPajamaGithub


text:
package blobDetection;

//==================================================
//class EdgeVertex
//==================================================
public class EdgeVertex
{
	public float x,y;
	public EdgeVertex(float x, float y){this.x=x;this.y=y;}
};


text:
using System;
using System.IO;
using System.Linq;
using System.Net;
using System.Runtime.Serialization.Formatters;
using System.Runtime.Serialization.Formatters.Binary;
using System.Text;

namespace ObjectStream.IO
{
    public class ObjectStreamWrapper<TReadWrite> : ObjectStreamWrapper<TReadWrite, TReadWrite>
        where TReadWrite : class
    {
        public ObjectStreamWrapper(Stream inStream, Stream outStream) : base(inStream, outStream)
        {
        }
    }

    public class ObjectStreamWrapper<TRead, TWrite>
        where TRead : class
        where TWrite : class
    {
        private readonly BinaryFormatter _binaryFormatter = new BinaryFormatter { Binder = new BindChanger(), AssemblyFormat = FormatterAssemblyStyle.Simple };
        private readonly Stream _inStream;
        private readonly Stream _outStream;

        private bool _run;

        public ObjectStreamWrapper(Stream inStream, Stream outStream)
        {
            _inStream = inStream;
            _outStream = outStream;
            _run = true;
        }

        public bool CanRead => _run && _inStream.CanRead;

        public bool CanWrite => _run && _outStream.CanWrite;

        public void Close()
        {
            if (!_run) return;
            _run = false;
            try
            {
                _outStream.Close();
            }
            catch (Exception) { }
            try
            {
                _inStream.Close();
            }
            catch (Exception) { }
        }

        public TRead ReadObject()
        {
            var len = ReadLength();
            return len == 0 ? null : ReadObject(len);
        }

        #region Private stream readers

        private int ReadLength()
        {
            const int lensize = sizeof(int);
            var lenbuf = new byte[lensize];
            var bytesRead = _inStream.Read(lenbuf, 0, lensize);
            if (bytesRead == 0) return 0;
            if (bytesRead != lensize)
            {
                //TODO hack to ignore BOM
                Array.Resize(ref lenbuf, Encoding.UTF8.GetPreamble().Length);
                if (Encoding.UTF8.GetPreamble().SequenceEqual(lenbuf)) return ReadLength();
                throw new IOException(string.Format("Expected {0} bytes but read {1}", lensize, bytesRead));
            }
            return IPAddress.NetworkToHostOrder(BitConverter.ToInt32(lenbuf, 0));
        }

        private TRead ReadObject(int len)
        {
            var data = new byte[len];
            int count;
            int sum = 0;
            while (len - sum > 0 && (count = _inStream.Read(data, sum, len - sum)) > 0)
                sum += count;
            using (var memoryStream = new MemoryStream(data))
            {
                return (TRead)_binaryFormatter.Deserialize(memoryStream);
            }
        }

        #endregion

        public void WriteObject(TWrite obj)
        {
            var data = Serialize(obj);
            WriteLength(data.Length);
            WriteObject(data);
            Flush();
        }

        #region Private stream writers

        private byte[] Serialize(TWrite obj)
        {
            using (var memoryStream = new MemoryStream())
            {
                _binaryFormatter.Serialize(memoryStream, obj);
                return memoryStream.ToArray();
            }
        }

        private void WriteLength(int len)
        {
            var lenbuf = BitConverter.GetBytes(IPAddress.HostToNetworkOrder(len));
            _outStream.Write(lenbuf, 0, lenbuf.Length);
        }

        private void WriteObject(byte[] data)
        {
            _outStream.Write(data, 0, data.Length);
        }

        private void Flush()
        {
            _outStream.Flush();
        }

        #endregion
    }
}


text:
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
var ClickMode_1 = require("../Enums/Modes/ClickMode");
var InteractivityDetect_1 = require("../Enums/InteractivityDetect");
var Constants_1 = require("./Constants");
var EventListeners = (function () {
    function EventListeners(container) {
        var _this = this;
        this.container = container;
        this.canPush = true;
        this.mouseMoveHandler = function (e) { return _this.mouseTouchMove(e); };
        this.touchStartHandler = function (e) { return _this.mouseTouchMove(e); };
        this.touchMoveHandler = function (e) { return _this.mouseTouchMove(e); };
        this.touchEndHandler = function () { return _this.mouseTouchFinish(); };
        this.mouseLeaveHandler = function () { return _this.mouseTouchFinish(); };
        this.touchCancelHandler = function () { return _this.mouseTouchFinish(); };
        this.touchEndClickHandler = function (e) { return _this.mouseTouchClick(e); };
        this.mouseUpHandler = function (e) { return _this.mouseTouchClick(e); };
        this.visibilityChangeHandler = function () { return _this.handleVisibilityChange(); };
        this.resizeHandler = function () { return _this.handleWindowResize(); };
    }
    EventListeners.manageListener = function (element, event, handler, add, options) {
        if (add) {
            var addOptions = { passive: true };
            if (typeof options === "boolean") {
                addOptions.capture = options;
            }
            else if (options !== undefined) {
                addOptions = options;
            }
            EventListeners.addListener(element, event, handler, addOptions);
        }
        else {
            EventListeners.removeListener(element, event, handler, options);
        }
    };
    EventListeners.addListener = function (element, event, handler, options) {
        element.addEventListener(event, handler, options);
    };
    EventListeners.removeListener = function (element, event, handler, options) {
        element.removeEventListener(event, handler, options);
    };
    EventListeners.prototype.addListeners = function () {
        this.manageListeners(true);
    };
    EventListeners.prototype.removeListeners = function () {
        this.manageListeners(false);
    };
    EventListeners.prototype.manageListeners = function (add) {
        var container = this.container;
        var options = container.options;
        if (options.interactivity.detectsOn === InteractivityDetect_1.InteractivityDetect.window) {
            container.interactivity.element = window;
        }
        else if (options.interactivity.detectsOn === InteractivityDetect_1.InteractivityDetect.parent && container.canvas.element) {
            container.interactivity.element = container.canvas.element.parentNode;
        }
        else {
            container.interactivity.element = container.canvas.element;
        }
        var interactivityEl = container.interactivity.element;
        if (interactivityEl && (options.interactivity.events.onHover.enable ||
            options.interactivity.events.onClick.enable)) {
            EventListeners.manageListener(interactivityEl, Constants_1.Constants.mouseMoveEvent, this.mouseMoveHandler, add);
            EventListeners.manageListener(interactivityEl, Constants_1.Constants.touchStartEvent, this.touchStartHandler, add);
            EventListeners.manageListener(interactivityEl, Constants_1.Constants.touchMoveEvent, this.touchMoveHandler, add);
            if (!options.interactivity.events.onClick.enable) {
                EventListeners.manageListener(interactivityEl, Constants_1.Constants.touchEndEvent, this.touchEndHandler, add);
            }
            EventListeners.manageListener(interactivityEl, Constants_1.Constants.mouseLeaveEvent, this.mouseLeaveHandler, add);
            EventListeners.manageListener(interactivityEl, Constants_1.Constants.touchCancelEvent, this.touchCancelHandler, add);
        }
        if (options.interactivity.events.onClick.enable && interactivityEl) {
            EventListeners.manageListener(interactivityEl, Constants_1.Constants.touchEndEvent, this.touchEndClickHandler, add);
            EventListeners.manageListener(interactivityEl, Constants_1.Constants.mouseUpEvent, this.mouseUpHandler, add);
        }
        if (options.interactivity.events.resize) {
            EventListeners.manageListener(window, Constants_1.Constants.resizeEvent, this.resizeHandler, add);
        }
        if (document) {
            EventListeners.manageListener(document, Constants_1.Constants.visibilityChangeEvent, this.visibilityChangeHandler, add, false);
        }
    };
    EventListeners.prototype.handleWindowResize = function () {
        var container = this.container;
        var options = container.options;
        if (!container.canvas.element) {
            return;
        }
        container.canvas.size.width = container.canvas.element.offsetWidth;
        container.canvas.size.height = container.canvas.element.offsetHeight;
        if (container.retina.isRetina) {
            container.canvas.size.width *= container.retina.pixelRatio;
            container.canvas.size.height *= container.retina.pixelRatio;
        }
        container.canvas.element.width = container.canvas.size.width;
        container.canvas.element.height = container.canvas.size.height;
        if (!options.particles.move.enable) {
            container.particles.redraw();
        }
        container.densityAutoParticles();
        for (var _i = 0, _a = container.plugins; _i < _a.length; _i++) {
            var plugin = _a[_i];
            if (plugin.resize !== undefined) {
                plugin.resize();
            }
        }
    };
    EventListeners.prototype.handleVisibilityChange = function () {
        var container = this.container;
        var options = container.options;
        if (!options.pauseOnBlur) {
            return;
        }
        if (document === null || document === void 0 ? void 0 : document.hidden) {
            container.pageHidden = true;
            container.pause();
        }
        else {
            container.pageHidden = false;
            if (container.getAnimationStatus()) {
                container.lastFrameTime = performance.now();
                container.play();
            }
        }
    };
    EventListeners.prototype.mouseTouchMove = function (e) {
        var _a, _b, _c, _d;
        var container = this.container;
        var options = container.options;
        var pos;
        if (e.type.startsWith("mouse")) {
            this.canPush = true;
            var mouseEvent = e;
            if (((_a = container.interactivity) === null || _a === void 0 ? void 0 : _a.element) === undefined) {
                return;
            }
            if (container.interactivity.element === window) {
                if (container.canvas.element) {
                    var clientRect = container.canvas.element.getBoundingClientRect();
                    pos = {
                        x: mouseEvent.clientX - clientRect.left,
                        y: mouseEvent.clientY - clientRect.top,
                    };
                }
            }
            else if (options.interactivity.detectsOn === InteractivityDetect_1.InteractivityDetect.parent) {
                var source = mouseEvent.target;
                var target = mouseEvent.currentTarget;
                if (source && target) {
                    var sourceRect = source.getBoundingClientRect();
                    var targetRect = target.getBoundingClientRect();
                    pos = {
                        x: mouseEvent.offsetX + sourceRect.left - targetRect.left,
                        y: mouseEvent.offsetY + sourceRect.top - targetRect.top,
                    };
                }
                else {
                    pos = {
                        x: mouseEvent.offsetX || mouseEvent.clientX,
                        y: mouseEvent.offsetY || mouseEvent.clientY,
                    };
                }
            }
            else {
                if (mouseEvent.target === container.canvas.element) {
                    pos = {
                        x: mouseEvent.offsetX || mouseEvent.clientX,
                        y: mouseEvent.offsetY || mouseEvent.clientY,
                    };
                }
            }
        }
        else {
            this.canPush = e.type !== "touchmove";
            var touchEvent = e;
            var lastTouch = touchEvent.touches[touchEvent.touches.length - 1];
            var canvasRect = (_b = container.canvas.element) === null || _b === void 0 ? void 0 : _b.getBoundingClientRect();
            pos = {
                x: lastTouch.clientX - ((_c = canvasRect === null || canvasRect === void 0 ? void 0 : canvasRect.left) !== null && _c !== void 0 ? _c : 0),
                y: lastTouch.clientY - ((_d = canvasRect === null || canvasRect === void 0 ? void 0 : canvasRect.top) !== null && _d !== void 0 ? _d : 0),
            };
        }
        container.interactivity.mouse.position = pos;
        if (container.retina.isRetina && container.interactivity.mouse.position) {
            container.interactivity.mouse.position.x *= container.retina.pixelRatio;
            container.interactivity.mouse.position.y *= container.retina.pixelRatio;
        }
        container.interactivity.status = Constants_1.Constants.mouseMoveEvent;
    };
    EventListeners.prototype.mouseTouchFinish = function () {
        var container = this.container;
        delete container.interactivity.mouse.position;
        container.interactivity.status = Constants_1.Constants.mouseLeaveEvent;
    };
    EventListeners.prototype.mouseTouchClick = function (e) {
        var container = this.container;
        var options = container.options;
        var handled = false;
        var mousePosition = container.interactivity.mouse.position;
        if (mousePosition === undefined || !options.interactivity.events.onClick.enable) {
            return;
        }
        for (var _i = 0, _a = container.plugins; _i < _a.length; _i++) {
            var plugin = _a[_i];
            if (plugin.clickPositionValid !== undefined) {
                handled = plugin.clickPositionValid(mousePosition);
                if (handled) {
                    break;
                }
            }
        }
        if (!handled) {
            this.doMouseTouchClick(e);
        }
    };
    EventListeners.prototype.doMouseTouchClick = function (e) {
        var _this = this;
        var container = this.container;
        var options = container.options;
        if (this.canPush) {
            if (container.interactivity.mouse.position) {
                container.interactivity.mouse.clickPosition = {
                    x: container.interactivity.mouse.position.x,
                    y: container.interactivity.mouse.position.y,
                };
            }
            else {
                return;
            }
            container.interactivity.mouse.clickTime = new Date().getTime();
            if (options.interactivity.events.onClick.mode instanceof Array) {
                for (var _i = 0, _a = options.interactivity.events.onClick.mode; _i < _a.length; _i++) {
                    var mode = _a[_i];
                    this.handleClickMode(mode);
                }
            }
            else {
                var mode = options.interactivity.events.onClick.mode;
                this.handleClickMode(mode);
            }
        }
        if (e.type === "touchend") {
            setTimeout(function () { return _this.mouseTouchFinish(); }, 500);
        }
    };
    EventListeners.prototype.handleClickMode = function (mode) {
        var container = this.container;
        var options = container.options;
        var pushNb = options.interactivity.modes.push.quantity;
        var removeNb = options.interactivity.modes.remove.quantity;
        switch (mode) {
            case ClickMode_1.ClickMode.push:
                if (options.particles.move.enable) {
                    container.particles.push(pushNb, container.interactivity.mouse);
                }
                else {
                    if (options.interactivity.modes.push.quantity === 1) {
                        container.particles.push(pushNb, container.interactivity.mouse);
                    }
                    else if (options.interactivity.modes.push.quantity > 1) {
                        container.particles.push(pushNb);
                    }
                }
                break;
            case ClickMode_1.ClickMode.remove:
                container.particles.removeQuantity(removeNb);
                break;
            case ClickMode_1.ClickMode.bubble:
                container.bubble.clicking = true;
                break;
            case ClickMode_1.ClickMode.repulse:
                container.repulse.clicking = true;
                container.repulse.count = 0;
                for (var _i = 0, _a = container.repulse.particles; _i < _a.length; _i++) {
                    var particle = _a[_i];
                    particle.velocity.horizontal = particle.initialVelocity.horizontal;
                    particle.velocity.vertical = particle.initialVelocity.vertical;
                }
                container.repulse.particles = [];
                container.repulse.finish = false;
                setTimeout(function () {
                    if (!container.destroyed) {
                        container.repulse.clicking = false;
                    }
                }, options.interactivity.modes.repulse.duration * 1000);
                break;
        }
        for (var _b = 0, _c = container.plugins; _b < _c.length; _b++) {
            var plugin = _c[_b];
            if (plugin.handleClickMode) {
                plugin.handleClickMode(mode);
            }
        }
    };
    return EventListeners;
}());
exports.EventListeners = EventListeners;


text:
ACCEPTED

#### According to
International Plant Names Index

#### Published in
Ill. fl. Archip Ind. 76. 1870

#### Original name
null

### Remarks
null


text:
'use strict';

/**
 * @typedef {Object} ElementInterface
 * @property {function} constructor
 * @property {string} name
 * @property {object} prototype
 * @property {Array.<string>} tagNames
 */

var common = require('./common'),
    isValidCustomElementName = require('./is-valid-custom-element-name'),
    PrivatePropertyStore = require('./private-property-store'),
    tagNames = require('../data/tag-names'),

    createElement = Document.prototype.createElement.bind(document),
    getPrototypeOf = Object.getPrototypeOf,
    hasOwnProperty = common.hasOwnProperty,
    HTMLElement = window.HTMLElement,
    HTMLElementProto = HTMLElement.prototype,
    interfaces = [],
    interfacesByName = Object.create(null),
    interfacesByTagName = Object.create(null),
    isPrototypeOf = common.isPrototypeOf,
    nameOf = common.nameOf,
    priv = new PrivatePropertyStore('ElementInterface'),
    reg_capital = /^[A-Z]/,
    reg_htmlInterface = /^HTML(.+)Element$/,
    String = window.String,

    HTMLElementInterface = createInterface(HTMLElementProto, HTMLElement, 'HTMLElement'),
    HTMLUnknownElementInterface = createInterface(HTMLUnknownElement.prototype, HTMLUnknownElement, 'HTMLUnknownElement'),

    I = 0,
    props, ctor, interf, name, proto, tagName, x, y;

/**
 * @param {ElementInterface} interf
 * @param {string} tagName
 */
function addTagName(interf, tagName) {
    interfacesByTagName[tagName] = interf;
    interf.tagNames[interf.tagNames.length] = tagName;
}

/**
 * @param {object} prototype
 * @param {function} [constructor]
 * @param {string} [name]
 * @returns {?ElementInterface}
 */
function createInterface(prototype, constructor, name) {
    var interf;
    constructor = constructor || prototype.constructor;
    if (!name) {
        name = nameOf(prototype);
        if (!reg_capital.test(name) || name === 'Object') {
            name = null;
        }
    }
    interf = {
        constructor: constructor,
        name: name,
        prototype: prototype,
        tagNames: []
    };
    interfaces[I++] = interf;
    priv.set(constructor, interf);
    priv.set(prototype, interf);
    if (name) {
        interfacesByName[name] = interf;
    }
    return interf;
}

/**
 * @param {object} prototype
 * @param {function} [constructor]
 * @param {string} [name]
 * @returns {?ElementInterface}
 */
function getOrCreateInterface(prototype, constructor, name) {
    var interf = priv.get(prototype);
    if (interf) {
        if (constructor) {
            priv.set(constructor, interf);
        }
        return interf;
    }
    if (!isPrototypeOf(HTMLElementProto, prototype)) {
        if (name) {
            interfacesByName[name] = null;
        }
        return null;
    }
    return createInterface(prototype, constructor, name);
}

/**
 * @param {string} tagName
 * @param {string} [name]
 * @returns {?ElementInterface}
 */
function getOrCreateInterfaceFromTagName(tagName, name) {
    var proto, interf;
    if (hasOwnProperty(interfacesByTagName, tagName)) {
        return interfacesByTagName[tagName];
    }
    try {
        proto = getPrototypeOf(createElement(tagName));
    } catch (ex) {
        interfacesByTagName[tagName] = null;
        return null;
    }
    interf = getOrCreateInterface(proto, proto.constructor, name);
    return interf === HTMLUnknownElementInterface ? null : interf;
}

// Loop through all window properties that appear to be an HTML element interface.
props = Object.getOwnPropertyNames(window);
x = 0;
y = props.length;
while (x < y) {
    name = props[x++];
    if (reg_htmlInterface.test(name)) {
        ctor = window[name];
        if (ctor && !priv.has(ctor)) {
            getOrCreateInterface(ctor.prototype, ctor, name);
        }
    }
}

// Add some other known interfaces by name.
createInterface(Image.prototype, Image, 'Image');
createInterface(Option.prototype, Option, 'Option');
if (window.Audio) {
    getOrCreateInterface(Audio.prototype, Audio, 'Audio');
}

// Loop through all predefined tag names and determine which ones are supported.
x = 0;
y = tagNames.length;
while (x < y) {
    tagName = tagNames[x++];
    /*
     * No need to use getOrCreateInterfaceFromTagName here because these tag names came
     * from ../data/tag-names.js. They're trusted to be valid HTML tag names, meaning
     * we can do the same operations from getOrCreateInterfaceFromTagName() but faster
     * (since we're not using a try / catch block).
     */
    proto = getPrototypeOf(createElement(tagName));
    interf = getOrCreateInterface(proto, proto.constructor, name);
    if (interf === HTMLUnknownElementInterface) {
        interf = null;
    }
    if (interf) {
        addTagName(interf, tagName);
    } else {
        interfacesByTagName[tagName] = null;
    }
}

module.exports = {
    /**
     * Returns the constructor for the built-in HTML element type associated with the given interface name (i.e. "HTMLDivElement"), or null if the current browser does not recognize the interface name.
     *
     * @param {string} interfaceName - The interface name (i.e. "HTMLDivElement") whose constructor should be returned.
     *
     * @returns {?function} - The constructor for the built-in HTML element type associated with the given interface name, or null if the current browser does not recognize the interface name.
     */
    constructorFromInterfaceName: function constructorFromInterfaceName(interfaceName) {
        var n = interfacesByName[interfaceName];
        return (n && n.constructor) || null;
    },
    /**
     * Returns the constructor for the built-in HTML element type associated with the given prototype interface object, or null if the current browser does not recognize the prototype interface object.
     *
     * @param {object} prototype - The prototype interface object whose constructor should be returned.
     *
     * @returns {?function} - The constructor for the built-in HTML element type associated with the given prototype interface object, or null if the current browser does not recognize the prototype interface object.
     */
    constructorFromPrototype: function constructorFromPrototype(prototype) {
        var n = priv.get(prototype);
        return (n && n.constructor) || null;
    },
    /**
     * Returns the constructor for the built-in HTML element type associated with the given tag name (i.e. "div"), or null if the current browser does not recognize the tag name.
     *
     * @param {string} tagName - The tag name (i.e. "div") whose constructor should be returned.
     *
     * @returns {?function} - The constructor for the built-in HTML element type associated with the given tag name, or null if the current browser does not recognize the tag name.
     */
    constructorFromTagName: function constructorFromTagName(tagName) {
        var n = getOrCreateInterfaceFromTagName(tagName);
        return (n && n.constructor) || null;
    },
    /**
     * An array containing all of the element interfaces that have been detected.
     *
     * @type {Array.<ElementInterface>}
     */
    interfaces: interfaces,
    /**
     * Determines whether the given object is the constructor function of a built-in HTML element type that is recognized by the current browser.
     *
     * @param {function} constructor - The object to test.
     *
     * @returns {boolean} - True if the given object is the constructor function of a built-in HTML element type that is recognized by the current browser; otherwise, false.
     */
    isElementInterface: function isElementInterface(constructor) {
        return priv.has(constructor);
    },
    /**
     * Determines whether the given object is the interface prototype object of a built-in HTML element type that is recognized by the current browser.
     *
     * @param {object} prototype - The object to test.
     *
     * @returns {boolean} - True if the given object is the interface prototype object of a built-in HTML element type that is recognized by the current browser; otherwise, false.
     */
    isElementPrototype: function isElementPrototype(prototype) {
        return priv.has(prototype);
    },
    /**
     * Determines whether the given tag name corresponds to a built-in HTML element that is recognized by the current browser.
     *
     * @param {string} tagName - The tag name of the element to test.
     *
     * @returns {boolean} - True if the tag name corresponds to a built-in HTML element that is recognized by the current browser; otherwise, false.
     */
    isKnownTagName: function isKnownTagName(tagName) {
        return !isValidCustomElementName(tagName) && !!getOrCreateInterfaceFromTagName(tagName);
    }
};


text:
var arrayToTrueMap = require('array-to-true-map');

/*
 * Usages:
 *
 *  transitionEnd(element, propertyName, transitionEndCallback)
 *      -element: (Element) on which the transition will occur
 *      -transitionEndCallback: (Function) callback function to be called if:
 *                                  1. element does not have a non-zero transition-duration for the transition-property from propertyName
 *                                  2. transitionEnd event is fired on element for each transition-property from propertyName
 *                                      -calls transitionEndCallback with an array of the transitionend event objects
 *      -propertyName: (String) comma or space separated list of the transition-properties for which to call the transitionEndCallback
 *      -removeListenerAfterTransition: (boolean) remove the transitionend event listener after all transition properties events have fired
 *
 *  transitionEnd(element, propertyNameToTransitionEndCallback)
 *      -element: (Element) on which the transition will occur
 *      -propertyNameToTransitionEndCallback: (Object) A map where the keys are a comma or space separated list of the transition-properties
 *                      and the values are callback functions to be called if:
 *                                  1. element does not have a non-zero transition-duration for the transition-properties in the key
 *                                  2. transitionEnd event is fired on element for each transition-property in the key
 *                                      -calls transitionEndCallback with an array of the transitionend event objects
 *      -removeListenerAfterTransition: (boolean) remove the transitionend event listener after all transition properties events have fired
 */

module.exports = function () {
    var elem = null,
        propertyName = '',
        removeListenerAfterTransition = false,
        transitionEndCallback,
        propToCallback;

    Array.prototype.slice.call(arguments).forEach(function (arg) {
        if (arg instanceof Element) {
            elem = arg;
        } else if (typeof arg === 'object') {
            propToCallback = arg;
        } else if (typeof arg === 'string') {
            propertyName = arg;
        } else if (typeof arg === 'function') {
            transitionEndCallback = arg;
        } else if (typeof arg === 'boolean') {
            removeListenerAfterTransition = arg;
        }
    });

    if (!elem) {
        throw new Error('transition-end requires an element as an argument');
    } else if (propToCallback) {
        processPropToCallback(elem, propToCallback, removeListenerAfterTransition);
    } else if (transitionEndCallback) {
        maybeBindTransitionEnd(elem, parseTransitionPropertiesMap(propertyName), transitionEndCallback, removeListenerAfterTransition);
    } else {
        throw new Error('Invalid arguments for transition-end');
    }
};

function processPropToCallback(elem, propToCallback, removeListenerAfterTransition) {
    Object.keys(propToCallback).forEach(function (propertyName) {
        maybeBindTransitionEnd(elem, parseTransitionPropertiesMap(propertyName), propToCallback[propertyName], removeListenerAfterTransition);
    });
}

function maybeBindTransitionEnd(elem, transitionProperties, transitionEndCallback, removeListenerAfterTransition) {
    if (typeof transitionEndCallback === 'function') {
        if (hasTransition(elem, transitionProperties)) {
            var events = [];

            function onTransitionEnd(e) {
                if (e.target === elem && (transitionProperties[e.propertyName] || transitionProperties.all)) {
                    events.push(e);

                    if (hasEventsForAllProperties(events, transitionProperties)) {
                        if (removeListenerAfterTransition) {
                            elem.removeEventListener('transitionend', onTransitionEnd);
                            elem.removeEventListener('webkitTransitionEnd', onTransitionEnd);
                        }

                        transitionEndCallback(events);

                        //create new object reference for events array because it's passed by reference to the callback function
                        events = [];
                    }
                }
            }

            elem.addEventListener('transitionend', onTransitionEnd);
            elem.addEventListener('webkitTransitionEnd', onTransitionEnd);
        } else {
            transitionEndCallback();
        }
    }
}

function hasEventsForAllProperties(storedEvents, transitionProperties) {
    if (transitionProperties.all) {
        return true;
    }

    var storedEventPropertyNameMap = {};

    storedEvents.forEach(function (e) {
        storedEventPropertyNameMap[e.propertyName] = true;
    });

    return Object.keys(transitionProperties).every(function (propertyName) {
        return storedEventPropertyNameMap[propertyName];
    });
}

function parseTransitionProperties(str) {
    if (str) {
        return str.trim().split(/[ ,]+/);
    } else {
        return ['all'];
    }
}

function parseTransitionPropertiesMap(str) {
    return arrayToTrueMap(parseTransitionProperties(str));
}

function hasTransition(elem, validPropsMap) {
    var computedStyle = window.getComputedStyle(elem);
    var duration = parseFloat(computedStyle.transitionDuration || computedStyle.webkitTransitionDuration);

    if (duration > 0) {
        var actualProps = parseTransitionProperties(computedStyle.transitionProperty || computedStyle.webkitTransitionProperty);

        if (actualProps.indexOf('all') >= 0) {
            return true;
        }

        return !actualProps.every(function (aProp) {
            return !validPropsMap[aProp];
        });
    }

    return false;
}


text:
package com.huawei.streaming.cql.executor.windowcreater;

import static org.junit.Assert.assertTrue;

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

import org.junit.Test;

import com.huawei.streaming.api.opereators.Window;
import com.huawei.streaming.api.streams.Column;
import com.huawei.streaming.api.streams.Schema;
import com.huawei.streaming.cql.exception.SemanticAnalyzerException;

/**
 * create group time slide window test case
 *
 */
public class GroupTimeSlideWindowCreatorTest
{

    /**
     * 测试用例
     *
     */
    @Test
    public void testCreateInstance()
        throws Exception
    {
        WindowCreator creater = new GroupTimeSlideWindowCreator();
        creater.createInstance(createWindow(), initSchema(), null);
        assertTrue(true);
    }

    private Window createWindow()
    {
        return Window.createGroupTimeSlideWindow(1, "id");
    }

    private List<Schema> initSchema()
        throws SemanticAnalyzerException
    {
        List<Schema> schemas = new ArrayList<Schema>();
        Schema s1 = new Schema("S1");

        s1.addCol(new Column("id", String.class));
        s1.addCol(new Column("name", String.class));

        schemas.add(s1);
        return schemas;
    }
}


text:
<?xml version="1.0"?><!--
  ~  Copyright 2016 Patrick Favre-Bulle
  ~
  ~  Licensed under the Apache License, Version 2.0 (the "License");
  ~  you may not use this file except in compliance with the License.
  ~  You may obtain a copy of the License at
  ~
  ~      http://www.apache.org/licenses/LICENSE-2.0
  ~
  ~ Unless required by applicable law or agreed to in writing, software
  ~ distributed under the License is distributed on an "AS IS" BASIS,
  ~ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  ~ See the License for the specific language governing permissions and
  ~ limitations under the License.
  -->

<!DOCTYPE suppressions PUBLIC
    "-//Puppy Crawl//DTD Suppressions 1.1//EN"
    "http://checkstyle.sourceforge.net/dtds/suppressions_1_1.dtd">

<!-- Add global checkstyle suppression here, see: http://checkstyle.sourceforge.net/config_filters.html -->
<suppressions>

</suppressions>


text:
<?xml version="1.0" encoding="UTF-8"?>
<!--
  ~ Copyright 2019, Emanuel Rabina (http://www.ultraq.net.nz/)
  ~
  ~ Licensed under the Apache License, Version 2.0 (the "License");
  ~ you may not use this file except in compliance with the License.
  ~ You may obtain a copy of the License at
  ~
  ~     http://www.apache.org/licenses/LICENSE-2.0
  ~
  ~ Unless required by applicable law or agreed to in writing, software
  ~ distributed under the License is distributed on an "AS IS" BASIS,
  ~ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  ~ See the License for the specific language governing permissions and
  ~ limitations under the License.
  -->

<beans xmlns="http://www.springframework.org/schema/beans"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="http://www.springframework.org/schema/beans
		https://www.springframework.org/schema/beans/spring-beans.xsd">

	<bean id="environment" class="org.springframework.web.context.support.StandardServletEnvironment">
		<property name="activeProfiles">
			<array>
				<value>development</value>
			</array>
		</property>
	</bean>
</beans>


text:
echo "======monitor the memory usage state for process com.xjt.letool======"
while true; do
adb shell dumpsys meminfo com.xjt.letool
sleep 1s
done
exit 0


text:
<?xml version="1.0" encoding="UTF-8"?>
<database xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="../../../../database/schema.xsd">
    <table name="guestbook" engine="InnoDB" since="guestbook 1.0">
        <field name="id" type="int(10) unsigned" default="null" autoincrement="true" primary="true" />
        <field name="idclient" type="int(10) unsigned" default="null">
            <constraint table="clients" column="idclient" onupdate="restrict" ondelete="cascade" />
        </field>
        <field name="name" type="varchar(255)" />
        <field name="email" type="varchar(255)" />
        <field name="message" type="text" />
        <field name="comment" type="text" />
        <field name="created" type="timestamp" default="0000-00-00 00:00:00"/>
        <field name="active" type="int(1) unsigned" default="0" />
    </table>
</database>


text:
package main

import (
	"k8s.io/component-base/metrics"
)

const (
	counterMetricType    = "Counter"
	gaugeMetricType      = "Gauge"
	histogramMetricType  = "Histogram"
	summaryMetricType    = "Summary"
	timingRatioHistogram = "TimingRatioHistogram"
)

type metric struct {
	Name              string              `yaml:"name"`
	Subsystem         string              `yaml:"subsystem,omitempty"`
	Namespace         string              `yaml:"namespace,omitempty"`
	Help              string              `yaml:"help,omitempty"`
	Type              string              `yaml:"type,omitempty"`
	DeprecatedVersion string              `yaml:"deprecatedVersion,omitempty"`
	StabilityLevel    string              `yaml:"stabilityLevel,omitempty"`
	Labels            []string            `yaml:"labels,omitempty"`
	Buckets           []float64           `yaml:"buckets,omitempty"`
	Objectives        map[float64]float64 `yaml:"objectives,omitempty"`
	AgeBuckets        uint32              `yaml:"ageBuckets,omitempty"`
	BufCap            uint32              `yaml:"bufCap,omitempty"`
	MaxAge            int64               `yaml:"maxAge,omitempty"`
	ConstLabels       map[string]string   `yaml:"constLabels,omitempty"`
}

func (m metric) buildFQName() string {
	return metrics.BuildFQName(m.Namespace, m.Subsystem, m.Name)
}

type byFQName []metric

func (ms byFQName) Len() int { return len(ms) }
func (ms byFQName) Less(i, j int) bool {
	if ms[i].StabilityLevel < ms[j].StabilityLevel {
		return true
	} else if ms[i].StabilityLevel > ms[j].StabilityLevel {
		return false
	}
	return ms[i].buildFQName() < ms[j].buildFQName()
}
func (ms byFQName) Swap(i, j int) {
	ms[i], ms[j] = ms[j], ms[i]
}


text:
package ru.matevosyan;

/**
 * User class.
 * Created on 28.04.2017.
 * @author Matevosyan Vardan
 * @version 1.0
 */

public class User implements Comparable<User> {

    private final String name;
    private final int age;

    /**
     * User class constructor.
     * @param name User name.
     * @param age User age.
     */

    public User(String name, int age) {
        this.name = name;
        this.age = age;
    }

    /**
     * Getter to get User name.
     * @return User name.
     */

    public String getName() {
        return name;
    }

    /**
     * Getter to get User age.
     * @return User name.
     */

    public int getAge() {
        return age;
    }

    /**
     * Override compareTo(User user) method to compare users by age.
     * @param user is User object.
     * @return int value.
     */

    @Override
    public int compareTo(User user) {
        return String.valueOf(this.age).compareTo(String.valueOf(user.getAge()));
    }
}


text:
<?php

namespace Owl\Event;

class Manager
{

    protected $listeners = array();

    /**
     * @param mixed $eventName
     * @param callable $callback
     */
    public function listen($eventName, $callback) {}

    /**
     * @param string $eventName
     * @param mixed $data
     */
    public function emit($eventName, $data = null) {}

}


text:
---
id: 587d7fb7367417b2b2512c0c
title: 使用 model.findOne() 从数据库中返回一个单一匹配的 Document
challengeType: 2
forumTopicId: 301545
dashedName: use-model-findone-to-return-a-single-matching-document-from-your-database
---

# --description--

`Model.findOne()` 与 `Model.find()` 十分类似,但就算数据库中有很多条数据可以匹配查询条件,它也只返回一个 document,而不会返回一个数组, 如果查询条件是声明为唯一值的属性,它会更加适用。

# --instructions--

修改 `findOneByFood` 函数,用 `Model.findOne() -> Person` 来查询在收藏夹中有某种食物的一个人。 将函数参数中的 `food` 作为检索条件。

# --hints--

应成功地找到一个数据

```js
(getUserInput) =>
  $.post(getUserInput('url') + '/_api/find-one-by-food', {
    name: 'Gary',
    age: 46,
    favoriteFoods: ['chicken salad']
  }).then(
    (data) => {
      assert.equal(data.name, 'Gary', 'item.name is not what expected');
      assert.deepEqual(
        data.favoriteFoods,
        ['chicken salad'],
        'item.favoriteFoods is not what expected'
      );
      assert.equal(data.__v, 0, 'The item should be not previously edited');
    },
    (xhr) => {
      throw new Error(xhr.responseText);
    }
  );
```

# --solutions--

```js
/**
  Backend challenges don't need solutions,
  because they would need to be tested against a full working project.
  Please check our contributing guidelines to learn more.
*/
```


text:
* Add openPatterns settings

## 0.1.1
* Support tree-view

## 0.1.0 - First Release
* Every feature added
* Every bug fixed


text:
require_relative '../../base_test'

class TestActionInteractorMultiLevel < BaseTest

  def setup
    super
    ui_steps.navigate_to_home
  end

  def test_is_visible!
    view('home').view('first-navigation').action('navigate').is_visible!
  end

  def test_is_not_visible!
    view('home').view('first-navigation').action('action-that-does-not-exist').is_not_visible!
  end

  def test_activate
    view('home').view('first-navigation').action('navigate').activate
    view('home').is_not_visible!
    view('another-section').is_visible!
  end

end


text:
import {
  ChangeDetectionStrategy,
  Component,
  EventEmitter,
  Input,
} from '@angular/core';

import {UserActions} from '../../actions/user-actions/user-actions';

import {
  InputOutput,
  isObservable,
  isSubject,
  isLargeArray,
} from '../../utils';

import {getPropertyPath} from '../../../backend/utils';

import {
  ComponentPropertyState,
  ExpandState,
} from '../../state';

import {
  Metadata,
  Path,
  PropertyMetadata,
  deserializePath,
  serializePath,
} from '../../../tree';

export enum EmitState {
  None,
  Emitted,
  Failed,
}

@Component({
  selector: 'bt-render-state',
  template: require('./render-state.html'),
  styles: [require('to-string!./render-state.css')],
})
export class RenderState {
  @Input() id: string;
  @Input() inputs: InputOutput;
  @Input() outputs: InputOutput;
  @Input() metadata: Metadata;
  @Input() level: number;
  @Input() path: Path;
  @Input() state;

  private EmitState = EmitState;

  private emitState = new Map<string, EmitState>();

  private PropertyMetadata = PropertyMetadata;

  constructor(
    private userActions: UserActions,
    private propertyState: ComponentPropertyState
  ) {}

  keys(obj): string[] {
    return (obj instanceof Object) ? Object.keys(obj) : [];
  }

  expandTree(key: string) {
    if (this.expandable(key)) {
      this.propertyState.toggleExpand(this.path.concat([key]));
    }
  }

  private metadataForKey(key: string): PropertyMetadata {
    const propertyPath = getPropertyPath(this.path).concat([key]);

    return this.metadata.get(this.state[key]);
  }

  private get none() {
    return this.state == null || Object.keys(this.state).length === 0;
  }

  private nest(key: string): boolean {
    return typeof this.state[key] === 'object' && this.state[key] != null;
  }

  private expanded(key: string): boolean {
    return this.propertyState.expansionState(this.path.concat([key])) === ExpandState.Expanded;
  }

  private displayType(key: string): string {
    const object = this.state[key];

    if (Array.isArray(object)) {
      return `Array[${object.length}]`;
    }
    else if (object != null) {
      if ((this.metadataForKey(key) & PropertyMetadata.Observable) !== 0) {
        return 'Observable';
      }
      else if (Object.keys(object).length === 0) {
        return '{}';
      }
      return 'Object';
    }

    if (object === null) {
      return 'null';
    }
    else if (object === undefined) {
      return 'undefined';
    }
  }

  private expandable(key: string) {
    return this.isEmittable(key) === false && Object.keys(this.state[key]).length > 0;
  }

  private evaluate(data: string) {
    try {
      return (new Function(`return ${data}`))();
    }
    catch (e) {
      return data;
    }
  }

  private isEmittable(key: string): boolean {
    const flags = this.metadataForKey(key);

    return (flags & PropertyMetadata.EventEmitter) !== 0
        || (flags & PropertyMetadata.Subject) !== 0;
  }

  private emitValue(outputProperty: string, data) {
    data = this.evaluate(data);

    const update = (state: EmitState) => this.emitState.set(outputProperty, state);

    const timedReset = () => setTimeout(() => update(EmitState.None), 3000);

    const path = this.path.concat([outputProperty]);

    return this.userActions.emitValue(path, data)
      .then(() => {
        update(EmitState.Emitted);
        timedReset();
      })
      .catch(error => {
        update(EmitState.Failed);
        timedReset();
      });
  }
}


text:
package org.cohorte.remote;

import java.util.Map;

/**
 * Specifies an export endpoint listener
 *
 * @author Thomas Calmant
 */
public interface IExportEndpointListener {

    /**
     * An export endpoint has been removed
     *
     * @param aEndpoint
     *            The removed endpoint
     */
    void endpointRemoved(ExportEndpoint aEndpoint);

    /**
     * Multiple endpoints have been created for export
     *
     * @param aEndpoints
     *            An array of exported endpoints
     */
    void endpointsAdded(ExportEndpoint[] aEndpoints);

    /**
     * An endpoint has been updated
     *
     * @param aEndpoint
     *            Updated endpoint
     * @param oldProperties
     *            Previous properties
     */
    void endpointUpdated(ExportEndpoint aEndpoint,
            Map<String, Object> oldProperties);
}


text:
import sys
import urllib2
import re

from StringIO import StringIO
from lxml import etree
from CoderState import *

def safe_int(x) :
    if x is None :
        return None
    return int(x)

def get_active_standings_url(round_id, page_idx = 0) :
    return 'http://www.topcoder.com/longcontest/?&module=ViewStandings&rd={0}&sr={1}&nr={2}'.format(round_id , page_idx * 100 + 1 , 100)

def download_active_contest_standing(round_id, page_idx):
    url = get_active_standings_url(round_id , page_idx)
    print 'loading ' + url
    opener = urllib2.build_opener()
    html = opener.open(url).read()
    return html

def get_active_contest_standing(coder_hash , round_id) :
    stat_list = []
    page_idx = 0
    memo_coder_id = {}
    last_rank = None
    pattern = re.compile('cr=([0-9]+)')
    while True :
        html = download_active_contest_standing(round_id, page_idx)
        tree = etree.parse(StringIO(html), etree.HTMLParser())

        index = 0

        for t in tree.xpath("//table[@class='statTable']/tr")[2:] :
            index = index + 1
            stat = CoderState()
            stat.coder_handle_name = t[0][0].text.strip()
            stat.coder_id = pattern.search(t[0][0].get('href')).group(1)
            if memo_coder_id.get(stat.coder_id) is not None :
                return None
            memo_coder_id [stat.coder_id] = True
            if t[2].text.strip() == '' :
                stat.provisional_score = 0.00
                stat.provisional_rank = last_rank
            else :
                stat.provisional_score = float(t[1].text.strip())
                stat.provisional_rank = safe_int(t[2].text.strip())
                stat.last_submission_time = t[3].text.strip()
            stat.language = t[4].text.strip()
            last_rank = stat.provisional_rank
            coder_info = coder_hash.get(stat.coder_id)
            if coder_info is not None :
                stat.current_rating = safe_int(coder_info.find('mar_rating').text)
                stat.current_volatility = safe_int(coder_info.find('mar_vol').text)
                stat.time_played = safe_int(coder_info.find('mar_num_ratings').text)
                stat.country = coder_info.find('country_name').text
                stat.is_newbie = False
                if stat.current_rating is None :
                    stat.is_newbie = True
                if stat.time_played is None :
                    stat.time_played = 0
            else :
                stat.is_newbie = True
            stat_list.append(stat)
        if index < 100 :
            break
        page_idx = page_idx + 1
    return stat_list


text:
  ID
  <input type="text" class="form-control" v-model="loginid">

  Password
  <input type="password" class="form-control" v-model="password">

  Email
  <input type="email" class="form-control" v-model="email" />

<button type="submit" class="btn btn-default" v-on="click: loginOrRegister" v-text="buttonValue"></button>


text:
/// Copyright (c) 2012 Ecma International.  All rights reserved.
/**
 * @path ch15/15.4/15.4.4/15.4.4.17/15.4.4.17-2-7.js
 * @description Array.prototype.some - 'length' is an own accessor property on an Array-like object
 */

function testcase() {
        function callbackfn1(val, idx, obj) {
            return val > 10;
        }

        function callbackfn2(val, idx, obj) {
            return val > 11;
        }

        var obj = { };

        Object.defineProperty(obj, "length", {
            get: function () {
                return 2;
            },
            configurable: true
        });

        obj[0] = 9;
        obj[1] = 11;
        obj[2] = 12;

        return Array.prototype.some.call(obj, callbackfn1) &&
            !Array.prototype.some.call(obj, callbackfn2);
    }
runTestCase(testcase);