text:
package br.com.liveo.searchliveo;

import android.animation.Animator;
import android.annotation.TargetApi;
import android.app.Activity;
import android.content.ActivityNotFoundException;
import android.content.Context;
import android.content.Intent;
import android.content.res.Resources;
import android.content.res.TypedArray;
import android.os.Build;
import android.os.Bundle;
import android.os.Parcelable;
import android.speech.RecognizerIntent;
import android.support.v4.content.ContextCompat;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.AttributeSet;
import android.util.DisplayMetrics;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewAnimationUtils;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.view.inputmethod.EditorInfo;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import java.util.ArrayList;
import java.util.Locale;
import java.util.Timer;
import java.util.TimerTask;

public class SearchLiveo extends FrameLayout {

    private Timer mTimer;
    private Activity mContext;

    private EditText mEdtSearch;
    private ImageView mImgArrow;
    private ImageView mImgVoice;
    private ImageView mImgClose;

    private boolean voice = true;
    private boolean active = false;
    private boolean hideKeyboard = false;
    private boolean imeActionSearch = false;

    private int mColorIcon = -1;
    private int mMinToSearch = 4;
    private int mSearchDelay = 800;

    private int mColorIconArrow = R.color.search_liveo_icon;
    private int mColorIconVoice = R.color.search_liveo_icon;
    private int mColorIconClose = R.color.search_liveo_icon;

    private int mColorPrimaryDark;
    private int mStatusBarHideColor = -1;
    private int mStatusBarShowColor = -1;

    private RelativeLayout mViewSearch;

    private OnSearchListener mSearchListener;
    private OnHideSearchListener mHideSearchListener;

    public static int REQUEST_CODE_SPEECH_INPUT = 7777;

    private static String SEARCH_LIVEO_SEARCH_TEXT = "searchText";
    private static String SEARCH_LIVEO_STATE_TO_SAVE = "stateToSave";
    private static String SEARCH_LIVEO_INSTANCE_STATE = "instanceState";

    public interface OnSearchListener {
        void changedSearch(CharSequence text);
    }

    public interface OnHideSearchListener {
        void hideSearch();
    }

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

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

    public SearchLiveo(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        if (!isInEditMode()) {
            initView(context);
            initViewAttribute(context, attrs, defStyleAttr);
        }
    }

    //region Methods init
    private void initView(Context context) {
        View view = LayoutInflater.from(context).inflate(
                R.layout.search_liveo, this, true);

        mImgArrow = view.findViewById(R.id.img_arrow);
        mImgVoice = view.findViewById(R.id.img_voice);
        mImgClose = view.findViewById(R.id.img_close);

        mEdtSearch = view.findViewById(R.id.edt_search);
        mImgClose.setVisibility(isVoice() ? View.GONE : View.VISIBLE);

        mViewSearch = view.findViewById(R.id.view_search);
        mViewSearch.setVisibility(View.INVISIBLE);

        mEdtSearch.setOnKeyListener(onKeyListener);

        mImgArrow.setOnClickListener(onClickSearch);
        mImgVoice.setOnClickListener(onClickVoice);
        mImgClose.setOnClickListener(onClickClose);

        mEdtSearch.setOnEditorActionListener(onEditorActionListener);
        mEdtSearch.addTextChangedListener(new OnTextWatcherEdtSearch());
    }

    private void initViewAttribute(Context context, AttributeSet attributeSet, int defStyleAttr) {
        TypedArray attr = context.obtainStyledAttributes(attributeSet,
                R.styleable.SearchLiveo, defStyleAttr, 0);
        if (attr != null) {
            try {

                if (attr.hasValue(R.styleable.SearchLiveo_searchLiveoHint)) {
                    hint(attr.getString(R.styleable.SearchLiveo_searchLiveoHint));
                }

                if (attr.hasValue(R.styleable.SearchLiveo_searchLiveoTextColor)) {
                    mEdtSearch.setTextColor(attr.getColor(
                            R.styleable.SearchLiveo_searchLiveoTextColor, -1));
                }

                if (attr.hasValue(R.styleable.SearchLiveo_searchLiveoHintColor)) {
                    mEdtSearch.setHintTextColor(attr.getColor(
                            R.styleable.SearchLiveo_searchLiveoHintColor, -1));
                }

                if (attr.hasValue(R.styleable.SearchLiveo_searchLiveoColorIcon)) {
                    setColorIcon(attr.getColor(
                            R.styleable.SearchLiveo_searchLiveoColorIcon, -1));
                }

                if (attr.hasValue(R.styleable.SearchLiveo_searchLiveoColorArrow)) {
                    setColorIconArrow(attr.getColor(
                            R.styleable.SearchLiveo_searchLiveoColorArrow, -1));
                }

                if (attr.hasValue(R.styleable.SearchLiveo_searchLiveoColorVoice)) {
                    setColorIconVoice(attr.getColor(
                            R.styleable.SearchLiveo_searchLiveoColorVoice, -1));
                }

                if (attr.hasValue(R.styleable.SearchLiveo_searchLiveoColorClose)) {
                    setColorIconClose(attr.getColor(
                            R.styleable.SearchLiveo_searchLiveoColorClose, -1));
                }

                if (attr.hasValue(R.styleable.SearchLiveo_searchLiveoBackground)) {
                    mViewSearch.setBackgroundColor(attr.getColor(
                            R.styleable.SearchLiveo_searchLiveoBackground, -1));
                }

                if (attr.hasValue(R.styleable.SearchLiveo_searchLiveoStatusBarShowColor)) {
                    setStatusBarShowColor(attr.getColor(
                            R.styleable.SearchLiveo_searchLiveoStatusBarShowColor, -1));
                }

                if (attr.hasValue(R.styleable.SearchLiveo_searchLiveoStatusBarHideColor)) {
                    setStatusBarHideColor(attr.getColor(
                            R.styleable.SearchLiveo_searchLiveoStatusBarHideColor, -1));
                }
            } finally {
                attr.recycle();
            }
        }
    }
    //endregion

    //region Methods with - build

    /**
     * Start context and the listener Search Live library.
     * Use this method when you are using an Activity
     *
     * @param context - Context Activity
     */
    public SearchLiveo with(Context context) {

        if (this.mContext == null) {
            try {
                this.mContext = (Activity) context;
                this.mSearchListener = (OnSearchListener) context;
            } catch (ClassCastException ignored) {

            }
        } else {
            build();
        }

        return this;
    }

    /**
     * Start context and the listener Search Live library.
     * Use this method when you are using an Fragment
     *
     * @param getActivity - Context Fragment
     * @param context     - Listener
     */
    public SearchLiveo with(Activity getActivity, OnSearchListener context) {

        if (this.mContext == null) {
            try {
                this.mContext = getActivity;
                this.mSearchListener = context;
            } catch (ClassCastException ignored) {
            }
        } else {
            build();
        }

        return this;
    }

    /**
     * Use when you want to know the exact moment that SearchLiveo is hidden
     *
     * @param onHideSearchListener - Listener
     */
    public SearchLiveo hideSearch(OnHideSearchListener onHideSearchListener) {
        this.mHideSearchListener = onHideSearchListener;
        return this;
    }

    public void build() {

        try {
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
                Resources.Theme theme = this.mContext.getTheme();
                TypedArray typedArray = theme.obtainStyledAttributes(
                        new int[]{android.R.attr.colorPrimaryDark});

                this.mColorPrimaryDark = ContextCompat.getColor(mContext,
                        typedArray.getResourceId(0, 0));
            }
        } catch (Exception e) {
            e.getStackTrace();
        }
    }
    //endregion

    //region Methods custom
    public boolean isActive() {
        return active;
    }

    public boolean isVoice() {
        return voice;
    }

    /**
     * Hiding the keyboard as soon as you finish it
     *
     *
     */
    public SearchLiveo hideKeyboardAfterSearch() {
        this.hideKeyboard = true;
        return this;
    }

    /**
     * Time in milliseconds of delay. Only after the given time will the search be made.
     *
     * @param delay default 800
     */
    public SearchLiveo searchDelay(int delay) {
        this.mSearchDelay = delay;
        return this;
    }

    /**
     * Remove search delay
     *
     *
     */
    public SearchLiveo removeSearchDelay() {
        this.mSearchDelay = 0;
        return this;
    }

    /**
     * Minimum number of characters to start the search
     *
     * @param minToSearch default >= 4
     */
    public SearchLiveo minToSearch(int minToSearch) {
        this.mMinToSearch = minToSearch;
        return this;
    }

    public SearchLiveo removeMinToSearch() {
        this.mMinToSearch = 0;
        return this;
    }

    /**
     * Set a new background color. If you do not use this method and standard color is white SearchLiveo.
     * In his layout.xml you can use the "app:searchLiveoBackground="@color/..."" attribute
     *
     * @param resId color attribute - colors.xml file
     */
    public SearchLiveo backgroundResource(int resId) {
        mViewSearch.setBackgroundResource(resId);
        return this;
    }

    /**
     * Set a new background color. If you do not use this method and standard color is white SearchLiveo.
     * In his layout.xml you can use the "app:searchLiveoBackground="@color/..."" attribute
     *
     * @param color color attribute - colors.xml file
     */
    public SearchLiveo backgroundColor(int color) {
        mViewSearch.setBackgroundColor(ContextCompat.getColor(mContext, color));
        return this;
    }

    /**
     * Set a new text color.
     * In his layout.xml you can use the "app:searchLiveoTextColor="@color/..."" attribute
     *
     * @param color color attribute - colors.xml file
     */
    public SearchLiveo textColor(int color) {
        mEdtSearch.setTextColor(ContextCompat.getColor(mContext, color));
        return this;
    }

    /**
     * Set a new hint color.
     * In his layout.xml you can use the "app:searchLiveoHintColor="@color/..."" attribute
     *
     * @param color color attribute - colors.xml file
     */
    public SearchLiveo hintColor(int color) {
        mEdtSearch.setHintTextColor(ContextCompat.getColor(mContext, color));
        return this;
    }

    /**
     * Set a new text.
     *
     * @param text "valeu"
     */
    public SearchLiveo text(String text) {
        mEdtSearch.setText(text);
        return this;
    }

    /**
     * Set a new text.
     *
     * @param text string attribute - string.xml file
     */
    public SearchLiveo text(int text) {
        mEdtSearch.setText(mContext.getString(text));
        return this;
    }

    /**
     * Set a new hint.
     * In his layout.xml you can use the "app:searchLiveoHint="value"" attribute
     *
     * @param text "valeu"
     */
    public SearchLiveo hint(String text) {
        mEdtSearch.setHint(text);
        return this;
    }

    /**
     * Set a new hint.
     * In his layout.xml you can use the "app:searchLiveoHint="@string/..."" attribute
     *
     * @param text string attribute - string.xml file
     */
    public SearchLiveo hint(int text) {
        mEdtSearch.setHint(mContext.getString(text));
        return this;
    }

    /**
     * Set a new color for all icons (arrow, voice and close).
     * In his layout.xml you can use the "app:searchLiveoColorIcon="@color/..."" attribute
     *
     * @param color color attribute - colors.xml file
     */
    public SearchLiveo colorIcon(int color) {
        this.setColorIcon(ContextCompat.getColor(mContext, color));
        return this;
    }

    /**
     * Set a new color for back arrow
     * In his layout.xml you can use the "app:searchLiveoColorArrow="@color/..."" attribute
     *
     * @param color color attribute - colors.xml file
     */
    public SearchLiveo colorIconArrow(int color) {
        this.setColorIconArrow(ContextCompat.getColor(mContext, color));
        return this;
    }

    /**
     * Set a new color for voice
     * In his layout.xml you can use the "app:searchLiveoColorVoice="@color/..."" attribute
     *
     * @param color color attribute - colors.xml file
     */
    public SearchLiveo colorIconVoice(int color) {
        this.setColorIconVoice(ContextCompat.getColor(mContext, color));
        return this;
    }

    /**
     * Returns the value typed
     */
    public String queryText() {
        return mEdtSearch.getText().toString().trim();
    }

    /**
     * Set a new color for close
     * In his layout.xml you can use the "app:searchLiveoColorClose="@color/..."" attribute
     *
     * @param color color attribute - colors.xml file
     */
    public SearchLiveo colorIconClose(int color) {
        this.setColorIconClose(ContextCompat.getColor(mContext, color));
        return this;
    }

    /**
     * Set a new color for statusBar when the SearchLiveo is closed
     * In his layout.xml you can use the "app:searchLiveoStatusBarHideColor="@color/..."" attribute
     *
     * @param color color attribute - colors.xml file
     */
    public SearchLiveo statusBarHideColor(int color) {
        setStatusBarHideColor(ContextCompat.getColor(mContext, color));
        return this;
    }

    /**
     * Set a new color for statusBar when the SearchLiveo for visible
     * In his layout.xml you can use the "app:searchLiveoStatusBarShowColor="@color/..."" attribute
     *
     * @param color color attribute - colors.xml file
     */
    public SearchLiveo statusBarShowColor(int color) {
        setStatusBarShowColor(ContextCompat.getColor(mContext, color));
        return this;
    }

    /**
     * By enabling imeActionSearch you are only activating the search when you click the imeActionSearch on the keyboard.
     * This disables the search as you type.
     *
     *
     */
    public SearchLiveo imeActionSearch(){
        this.imeActionSearch = true;
        return this;
    }

    /**
     * Hide voice icon
     */
    public SearchLiveo hideVoice() {
        setVoice(false);
        mImgVoice.setVisibility(View.GONE);
        return this;
    }

    /**
     * Show voice icon
     */
    public SearchLiveo showVoice() {
        setVoice(true);
        mImgVoice.setVisibility(View.VISIBLE);
        return this;
    }

    private void colorIcon() {
        if (getColorIcon() != -1 && getColorIconArrow() == -1) {
            mImgArrow.setColorFilter(this.getColorIcon());
        }

        if (getColorIcon() != -1 && getColorIconVoice() == -1) {
            mImgVoice.setColorFilter(this.getColorIcon());
        }

        if (getColorIcon() != -1 && getColorIconClose() == -1) {
            mImgClose.setColorFilter(this.getColorIcon());
        }
    }

    private void colorIconArrow() {
        if (getColorIconArrow() != -1) {
            mImgArrow.setColorFilter(this.getColorIconArrow());
        }
    }

    private void colorIconVoice() {
        if (this.getColorIconVoice() != -1) {
            mImgVoice.setColorFilter(this.getColorIconVoice());
        } else {
            mImgVoice.clearColorFilter();
        }
    }

    private void colorIconClose() {
        if (this.getColorIconClose() != -1) {
            mImgClose.setColorFilter(this.getColorIconClose());
        } else {
            mImgClose.clearColorFilter();
        }
    }

    /**
     * If SearchView is active(show), this method returns the value true
     */
    private void setActive(boolean active) {
        this.active = active;
    }

    private void setVoice(boolean isVoice) {
        this.voice = isVoice;
    }

    private void setStatusBarHideColor(int statusBarHideColor) {
        this.mStatusBarHideColor = statusBarHideColor;
    }

    private void setStatusBarShowColor(int statusBarShowColor) {
        this.mStatusBarShowColor = statusBarShowColor;
    }

    private int getColorIcon() {
        return mColorIcon;
    }

    private void setColorIcon(int colorIcon) {
        this.mColorIcon = colorIcon;
        this.colorIcon();
    }

    private int getColorIconArrow() {
        return ContextCompat.getColor(mContext, mColorIconArrow);
    }

    private void setColorIconArrow(int color) {
        this.mColorIconArrow = color;
        this.colorIconArrow();
    }

    private int getColorIconVoice() {
        return ContextCompat.getColor(mContext, mColorIconVoice);
    }

    private void setColorIconVoice(int color) {
        this.mColorIconVoice = color;
        this.colorIconVoice();
    }

    private int getColorIconClose() {
        return ContextCompat.getColor(mContext, mColorIconClose);
    }

    private void setColorIconClose(int color) {
        this.mColorIconClose = color;
        this.colorIconClose();
    }
    //endregion

    //region Methods Listener
    private OnKeyListener onKeyListener = new OnKeyListener() {
        @Override
        public boolean onKey(View v, int keyCode, KeyEvent event) {
            if (event.getAction() == KeyEvent.ACTION_DOWN) {
                if (keyCode == KeyEvent.KEYCODE_BACK) {
                    hide();
                    return true;
                }
            }
            return false;
        }
    };

    private TextView.OnEditorActionListener onEditorActionListener = new TextView.OnEditorActionListener() {
        @Override
        public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
            if (actionId == EditorInfo.IME_ACTION_SEARCH && imeActionSearch) {
                if (mSearchListener != null) {
                    mSearchListener.changedSearch(queryText());
                }

                hide();
                return true;
            }

            hide();
            return false;
        }
    };

    private class OnTextWatcherEdtSearch implements TextWatcher {

        @Override
        public void beforeTextChanged(CharSequence s, int start, int count, int after) {
        }

        @Override
        public void onTextChanged(CharSequence s, int start, int before, int count) {
            try {

                if (mTimer != null) {
                    mTimer.cancel();
                }

                if (queryText().isEmpty()) {
                    mImgClose.setVisibility(isVoice() ? View.GONE : View.VISIBLE);
                    mImgVoice.setVisibility(isVoice() ? View.VISIBLE : View.GONE);
                    mImgVoice.setImageResource(R.drawable.ic_liveo_keyboard_voice);
                    colorIconVoice();
                } else {
                    mImgVoice.setVisibility(View.GONE);
                    mImgClose.setVisibility(View.VISIBLE);
                    mImgClose.setImageResource(R.drawable.ic_liveo_close);
                    colorIconClose();
                }

                colorIcon();
                colorIconArrow();
            } catch (Exception e) {
                e.getStackTrace();
            }
        }

        @Override
        public void afterTextChanged(Editable s) {
            if (imeActionSearch){
                return;
            }

            if (s.length() >= mMinToSearch) {

                mTimer = new Timer();
                mTimer.schedule(new TimerTask() {
                    @Override
                    public void run() {
                        // TODO: do what you need here (refresh list)
                        if (mTimer != null) {
                            mTimer.cancel();
                            mContext.runOnUiThread(new Runnable() {
                                @Override
                                public void run() {

                                    if (mSearchListener != null) {
                                        mSearchListener.changedSearch(queryText());
                                    }

                                    if (hideKeyboard) {
                                        hideKeybord();
                                    }
                                }
                            });
                        }
                    }

                }, mSearchDelay);
            }
        }
    }

    private OnClickListener onClickSearch = new OnClickListener() {
        @Override
        public void onClick(View v) {
            hide();
        }
    };

    private OnClickListener onClickVoice = new OnClickListener() {
        @Override
        public void onClick(View v) {
            startVoice();
        }
    };

    private OnClickListener onClickClose = new OnClickListener() {
        @Override
        public void onClick(View v) {
            if (!queryText().isEmpty()) {
                mEdtSearch.setText("");

                showKeyboardRunOnUiThread();
            }
        }
    };
    //endregion

    //region Methods animation
    /**
     * Hide SearchLiveo
     */
    public void hide() {
        try {
            hideAnimation();
            setActive(false);
        } catch (Exception e) {
            e.getStackTrace();
        }
    }

    /**
     * Show SearchLiveo
     */
    public void show() {
        setActive(true);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {

            try {
                showAnimation();
            } catch (ClassCastException ignored) {
            }

        } else {

            Animation fadeIn = AnimationUtils.loadAnimation(
                    mContext.getApplicationContext(), android.R.anim.fade_in);

            mViewSearch.setEnabled(true);
            mViewSearch.setVisibility(View.VISIBLE);
            mViewSearch.setAnimation(fadeIn);

            showKeyboardRunOnUiThread();
        }

        mEdtSearch.requestFocus();
    }

    @TargetApi(Build.VERSION_CODES.LOLLIPOP)
    private void showAnimation() {
        try {

            int DEFAULT_STATUS_BAR_SHOW_COLOR = -1;

            mContext.getWindow().setStatusBarColor(
                    mStatusBarShowColor != DEFAULT_STATUS_BAR_SHOW_COLOR ?
                            mStatusBarShowColor : ContextCompat.getColor(
                            mContext, R.color.search_liveo_primary_dark));

            final Animator animator = ViewAnimationUtils.createCircularReveal(mViewSearch,
                    mViewSearch.getWidth() - (int) dpToPixel(24, this.mContext),
                    (int) dpToPixel(23, this.mContext), 0,
                    (float) Math.hypot(mViewSearch.getWidth(), mViewSearch.getHeight()));
            animator.addListener(new Animator.AnimatorListener() {
                @Override
                public void onAnimationStart(Animator animation) {
                }

                @Override
                public void onAnimationEnd(Animator animation) {
                    showKeyboardRunOnUiThread();
                }

                @Override
                public void onAnimationCancel(Animator animation) {

                }

                @Override
                public void onAnimationRepeat(Animator animation) {

                }
            });

            animator.setDuration(300);
            animator.start();
        } catch (Exception e) {
            e.getStackTrace();
            mContext.runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    showKeyboardRunOnUiThread();
                }
            });
        }

        mViewSearch.setVisibility(View.VISIBLE);
    }

    @TargetApi(Build.VERSION_CODES.LOLLIPOP)
    private void hideAnimation() {

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {

            int DEFAULT_STATUS_BAR_HIDE_COLOR = -1;

            mContext.getWindow().setStatusBarColor(
                    mStatusBarHideColor != DEFAULT_STATUS_BAR_HIDE_COLOR ?
                            mStatusBarHideColor : mColorPrimaryDark);

            final Animator animatorHide = ViewAnimationUtils.createCircularReveal(mViewSearch,
                    mViewSearch.getWidth() - (int) dpToPixel(24, mContext),
                    (int) dpToPixel(23, mContext),
                    (float) Math.hypot(mViewSearch.getWidth(), mViewSearch.getHeight()), 0);
            animatorHide.addListener(new Animator.AnimatorListener() {
                @Override
                public void onAnimationStart(Animator animation) {
                    mContext.runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            hideKeybord();
                        }
                    });
                }

                @Override
                public void onAnimationEnd(Animator animation) {
                    mViewSearch.setVisibility(View.GONE);

                    if (mHideSearchListener != null) {
                        mHideSearchListener.hideSearch();
                    }
                }

                @Override
                public void onAnimationCancel(Animator animation) {

                }

                @Override
                public void onAnimationRepeat(Animator animation) {

                }
            });
            animatorHide.setDuration(200);
            animatorHide.start();

        } else {

            mContext.runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    hideKeybord();
                }
            });

            Animation mFadeOut = AnimationUtils.loadAnimation(
                    mContext.getApplicationContext(), android.R.anim.fade_out);

            mViewSearch.setAnimation(mFadeOut);
            mViewSearch.setVisibility(View.INVISIBLE);

            if (mHideSearchListener != null) {
                mHideSearchListener.hideSearch();
            }
        }

        mEdtSearch.setText("");
        mViewSearch.setEnabled(false);
    }

    private float dpToPixel(float dp, Context context) {
        Resources resources = context.getResources();
        DisplayMetrics metrics = resources.getDisplayMetrics();
        return dp * (metrics.densityDpi / 160f);
    }
    //endregion

    //region Methods InstanceState
    @Override
    public Parcelable onSaveInstanceState() {
        Bundle bundle = new Bundle();
        bundle.putParcelable(SEARCH_LIVEO_INSTANCE_STATE, super.onSaveInstanceState());
        bundle.putBoolean(SEARCH_LIVEO_STATE_TO_SAVE, this.isActive());

        if (!queryText().isEmpty()) {
            bundle.putString(SEARCH_LIVEO_SEARCH_TEXT, queryText());
        }

        return bundle;
    }

    @Override
    public void onRestoreInstanceState(Parcelable state) {

        if (state instanceof Bundle) {
            Bundle bundle = (Bundle) state;
            this.setActive(bundle.getBoolean(SEARCH_LIVEO_STATE_TO_SAVE));

            String text = bundle.getString(SEARCH_LIVEO_SEARCH_TEXT, "");
            if (!text.trim().equals("")) {
                mEdtSearch.setText(text);
            }

            if (this.isActive()) {
                show();
            }

            state = bundle.getParcelable(SEARCH_LIVEO_INSTANCE_STATE);
        }

        super.onRestoreInstanceState(state);
    }
    //endregion

    //region Methods keyboard
    private void showKeyboardRunOnUiThread() {
        if (mContext != null && !mContext.isFinishing()) {
            mContext.runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    InputMethodManager inputMethodManager = (InputMethodManager)
                            mContext.getSystemService(Context.INPUT_METHOD_SERVICE);

                    if (inputMethodManager != null) {
                        inputMethodManager.toggleSoftInput(
                                InputMethodManager.SHOW_FORCED, InputMethodManager.HIDE_IMPLICIT_ONLY);
                    }

                }
            });
        }
    }

    private void hideKeybord() {
        if (mContext != null && !mContext.isFinishing()) {
            InputMethodManager inputMethodManager = (InputMethodManager)
                    mContext.getSystemService(Context.INPUT_METHOD_SERVICE);

            if (mContext != null && inputMethodManager != null) {
                inputMethodManager.hideSoftInputFromWindow(
                        mViewSearch.getWindowToken(), 0);
            }
        }
    }
    //endregion

    //region Methods voice
    private void startVoice() {
        hideKeybord();

        Intent intent = new Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH);
        intent.putExtra(RecognizerIntent.EXTRA_LANGUAGE_MODEL, RecognizerIntent.LANGUAGE_MODEL_FREE_FORM);
        intent.putExtra(RecognizerIntent.EXTRA_LANGUAGE, Locale.getDefault());
        intent.putExtra(RecognizerIntent.EXTRA_PROMPT, mContext.getString(R.string.liveo_search_view_voice));

        try {
            mContext.startActivityForResult(intent, REQUEST_CODE_SPEECH_INPUT);
        } catch (ActivityNotFoundException a) {
            Toast.makeText(mContext.getApplicationContext(), R.string.liveo_not_supported, Toast.LENGTH_SHORT).show();
        }
    }

    public void resultVoice(int requestCode, int resultCode, Intent data) {
        if (requestCode == SearchLiveo.REQUEST_CODE_SPEECH_INPUT) {
            if (resultCode == Activity.RESULT_OK && null != data) {
                ArrayList<String> result = data.getStringArrayListExtra(RecognizerIntent.EXTRA_RESULTS);

                if (mSearchListener != null) {
                    mEdtSearch.setText(result.get(0));
                    mSearchListener.changedSearch(result.get(0));
                }
            }
        }
    }
    //endregion
}


text:
'use strict';

/**
 * Module dependencies.
 */
var mongoose = require('mongoose'),
    Schema = mongoose.Schema;

/**
 * Mission Schema
 */
var MissionSchema = new Schema({
    name: {
        type: String,
        default: '',
        required: 'Please fill Mission name',
        unique: true,
        trim: true
    },
    createdBy: {
        type: Schema.ObjectId,
        ref: 'User'
    },
    summary: {
        type: String,
        default: ''
    },
    presentation: {
        type: String,
        default: ''
    },
    members: [{
        user: {
            type: Schema.ObjectId,
            ref: 'User'
        },
        role: {
            type: String
        },
        _id: false
    }],
    guild: [{
        type: Schema.ObjectId,
        ref: 'Guild'
    }],
    competencies: [{
        type: Schema.ObjectId,
        ref: 'Competence'
    }],
    themes: [{
        type: Schema.ObjectId,
        ref: 'Theme'
    }],
    template:{
        type:String,
        default: ''
    },
    steps: [{
        number: {
            type: Number
        },
        tasks: [{
            type: Schema.ObjectId,
            ref: 'Task'
        }]
    }],
    game: [{
        cards: [{
            type: Schema.ObjectId,
            ref: 'Card'
        }],
        pattern: {
            type: Schema.ObjectId,
            ref: 'Pattern'
        }
    }],
    createdOn: {
        type: Date,
        default: Date.now
    },
    modifiedOn: {
        type: Date,
        default: Date.now
    }
});

/**
 * Mission methods
 */
MissionSchema.methods.addUser = function(userId, userIdToAdd, userRoleToAdd){
    MissionSchema.methods.verifyRole(userId, 'admin', function(){
        var userToAdd = {
            user: userIdToAdd,
            role: userRoleToAdd
        };
        this.model('Mission').members.push(userToAdd, function(){
            console.log(userToAdd + ' ajouté');
        });
    });
};

MissionSchema.methods.deleteTaskFromMission = function(userId, taskToRemove){
    //Vérifie si la personne appelant cette méthode est admin dans la mission
    MissionSchema.methods.verifyRole(userId, 'admin', function(){
        this.model('Mission').steps.remove({tasks: taskToRemove}, function(){
            console.log('Tâche ' + taskToRemove + ' supprimée');
        });
    });
};

MissionSchema.methods.deleteStepFromMission = function(userId, stepToRemove){
    //Vérifie si la personne appelant cette méthode est admin dans la mission
    MissionSchema.methods.verifyRole(userId, 'admin', function(){
        this.model('Mission').steps.remove({number: stepToRemove}, function(){
            console.log('Étape ' + stepToRemove + ' supprimée');
        });
    });
};

MissionSchema.methods.deleteMission = function(userId, missionId){
    //Vérifie si la personne appelant cette méthode est admin dans la mission
    MissionSchema.methods.verifyRole(userId, 'admin', function(){
        this.model('Mission').remove({_id: missionId}, function(){
            console.log('Mission ' + missionId + ' supprimée');
        });
    });
};

MissionSchema.methods.verifyRole = function(userId, userRole, cb){
    return this.model('Mission').members.findOne({user : userId}, function(foundMember){
        if(userRole.indexOf(foundMember.role) > -1){
            return cb;
        }
        else{
            return console.log('Vous n\'avez pas accès à cela');
        }
    });
};

mongoose.model('Mission', MissionSchema);

redpajama_set_name: RedPajamaGithub


text:
<!--
  ~ Copyright 2017, Abhi Muktheeswarar
  ~
  ~ 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.
  -->

<resources>
    <string name="app_name">Arena</string>
    <string name="action_settings">Settings</string>
    <string name="title_activity_movies">MoviesActivity</string>
    <string name="title_activity_movie_search">MovieSearchActivity</string>
    <string name="title_activity_search_menu">SearchMenuActivity</string>
    <string name="hint_search">Search for moves by title</string>
    <string name="title_activity_search_spinner">SearchSpinnerActivity</string>
    <string name="title_activity_movie_list">MovieListActivity</string>
</resources>


text:
namespace caffe { namespace db {

enum Mode { READ, WRITE, NEW };

class Cursor {
 public:
  Cursor() { }
  virtual ~Cursor() { }
  virtual void SeekToFirst() = 0;
  virtual void Next() = 0;
  virtual string key() = 0;
  virtual string value() = 0;
  virtual bool valid() = 0;

  DISABLE_COPY_AND_ASSIGN(Cursor);
};

class Transaction {
 public:
  Transaction() { }
  virtual ~Transaction() { }
  virtual void Put(const string& key, const string& value) = 0;
  virtual void Commit() = 0;

  DISABLE_COPY_AND_ASSIGN(Transaction);
};

class DB {
 public:
  DB() { }
  virtual ~DB() { }
  virtual void Open(const string& source, Mode mode) = 0;
  virtual void Close() = 0;
  virtual Cursor* NewCursor() = 0;
  virtual Transaction* NewTransaction() = 0;

  DISABLE_COPY_AND_ASSIGN(DB);
};

DB* GetDB(DataParameter::DB backend);
DB* GetDB(const string& backend);

}  // namespace db
}  // namespace caffe

#endif  // CAFFE_UTIL_DB_HPP


text:
import grpc

from google.cloud.spanner_v1.proto import (
    result_set_pb2 as google_dot_cloud_dot_spanner__v1_dot_proto_dot_result__set__pb2,
)
from google.cloud.spanner_v1.proto import (
    spanner_pb2 as google_dot_cloud_dot_spanner__v1_dot_proto_dot_spanner__pb2,
)
from google.cloud.spanner_v1.proto import (
    transaction_pb2 as google_dot_cloud_dot_spanner__v1_dot_proto_dot_transaction__pb2,
)
from google.protobuf import empty_pb2 as google_dot_protobuf_dot_empty__pb2

class SpannerStub(object):
    """Cloud Spanner API

  The Cloud Spanner API can be used to manage sessions and execute
  transactions on data stored in Cloud Spanner databases.
  """

    def __init__(self, channel):
        """Constructor.

    Args:
      channel: A grpc.Channel.
    """
        self.CreateSession = channel.unary_unary(
            "/google.spanner.v1.Spanner/CreateSession",
            request_serializer=google_dot_cloud_dot_spanner__v1_dot_proto_dot_spanner__pb2.CreateSessionRequest.SerializeToString,
            response_deserializer=google_dot_cloud_dot_spanner__v1_dot_proto_dot_spanner__pb2.Session.FromString,
        )
        self.BatchCreateSessions = channel.unary_unary(
            "/google.spanner.v1.Spanner/BatchCreateSessions",
            request_serializer=google_dot_cloud_dot_spanner__v1_dot_proto_dot_spanner__pb2.BatchCreateSessionsRequest.SerializeToString,
            response_deserializer=google_dot_cloud_dot_spanner__v1_dot_proto_dot_spanner__pb2.BatchCreateSessionsResponse.FromString,
        )
        self.GetSession = channel.unary_unary(
            "/google.spanner.v1.Spanner/GetSession",
            request_serializer=google_dot_cloud_dot_spanner__v1_dot_proto_dot_spanner__pb2.GetSessionRequest.SerializeToString,
            response_deserializer=google_dot_cloud_dot_spanner__v1_dot_proto_dot_spanner__pb2.Session.FromString,
        )
        self.ListSessions = channel.unary_unary(
            "/google.spanner.v1.Spanner/ListSessions",
            request_serializer=google_dot_cloud_dot_spanner__v1_dot_proto_dot_spanner__pb2.ListSessionsRequest.SerializeToString,
            response_deserializer=google_dot_cloud_dot_spanner__v1_dot_proto_dot_spanner__pb2.ListSessionsResponse.FromString,
        )
        self.DeleteSession = channel.unary_unary(
            "/google.spanner.v1.Spanner/DeleteSession",
            request_serializer=google_dot_cloud_dot_spanner__v1_dot_proto_dot_spanner__pb2.DeleteSessionRequest.SerializeToString,
            response_deserializer=google_dot_protobuf_dot_empty__pb2.Empty.FromString,
        )
        self.ExecuteSql = channel.unary_unary(
            "/google.spanner.v1.Spanner/ExecuteSql",
            request_serializer=google_dot_cloud_dot_spanner__v1_dot_proto_dot_spanner__pb2.ExecuteSqlRequest.SerializeToString,
            response_deserializer=google_dot_cloud_dot_spanner__v1_dot_proto_dot_result__set__pb2.ResultSet.FromString,
        )
        self.ExecuteStreamingSql = channel.unary_stream(
            "/google.spanner.v1.Spanner/ExecuteStreamingSql",
            request_serializer=google_dot_cloud_dot_spanner__v1_dot_proto_dot_spanner__pb2.ExecuteSqlRequest.SerializeToString,
            response_deserializer=google_dot_cloud_dot_spanner__v1_dot_proto_dot_result__set__pb2.PartialResultSet.FromString,
        )
        self.ExecuteBatchDml = channel.unary_unary(
            "/google.spanner.v1.Spanner/ExecuteBatchDml",
            request_serializer=google_dot_cloud_dot_spanner__v1_dot_proto_dot_spanner__pb2.ExecuteBatchDmlRequest.SerializeToString,
            response_deserializer=google_dot_cloud_dot_spanner__v1_dot_proto_dot_spanner__pb2.ExecuteBatchDmlResponse.FromString,
        )
        self.Read = channel.unary_unary(
            "/google.spanner.v1.Spanner/Read",
            request_serializer=google_dot_cloud_dot_spanner__v1_dot_proto_dot_spanner__pb2.ReadRequest.SerializeToString,
            response_deserializer=google_dot_cloud_dot_spanner__v1_dot_proto_dot_result__set__pb2.ResultSet.FromString,
        )
        self.StreamingRead = channel.unary_stream(
            "/google.spanner.v1.Spanner/StreamingRead",
            request_serializer=google_dot_cloud_dot_spanner__v1_dot_proto_dot_spanner__pb2.ReadRequest.SerializeToString,
            response_deserializer=google_dot_cloud_dot_spanner__v1_dot_proto_dot_result__set__pb2.PartialResultSet.FromString,
        )
        self.BeginTransaction = channel.unary_unary(
            "/google.spanner.v1.Spanner/BeginTransaction",
            request_serializer=google_dot_cloud_dot_spanner__v1_dot_proto_dot_spanner__pb2.BeginTransactionRequest.SerializeToString,
            response_deserializer=google_dot_cloud_dot_spanner__v1_dot_proto_dot_transaction__pb2.Transaction.FromString,
        )
        self.Commit = channel.unary_unary(
            "/google.spanner.v1.Spanner/Commit",
            request_serializer=google_dot_cloud_dot_spanner__v1_dot_proto_dot_spanner__pb2.CommitRequest.SerializeToString,
            response_deserializer=google_dot_cloud_dot_spanner__v1_dot_proto_dot_spanner__pb2.CommitResponse.FromString,
        )
        self.Rollback = channel.unary_unary(
            "/google.spanner.v1.Spanner/Rollback",
            request_serializer=google_dot_cloud_dot_spanner__v1_dot_proto_dot_spanner__pb2.RollbackRequest.SerializeToString,
            response_deserializer=google_dot_protobuf_dot_empty__pb2.Empty.FromString,
        )
        self.PartitionQuery = channel.unary_unary(
            "/google.spanner.v1.Spanner/PartitionQuery",
            request_serializer=google_dot_cloud_dot_spanner__v1_dot_proto_dot_spanner__pb2.PartitionQueryRequest.SerializeToString,
            response_deserializer=google_dot_cloud_dot_spanner__v1_dot_proto_dot_spanner__pb2.PartitionResponse.FromString,
        )
        self.PartitionRead = channel.unary_unary(
            "/google.spanner.v1.Spanner/PartitionRead",
            request_serializer=google_dot_cloud_dot_spanner__v1_dot_proto_dot_spanner__pb2.PartitionReadRequest.SerializeToString,
            response_deserializer=google_dot_cloud_dot_spanner__v1_dot_proto_dot_spanner__pb2.PartitionResponse.FromString,
        )

class SpannerServicer(object):
    """Cloud Spanner API

  The Cloud Spanner API can be used to manage sessions and execute
  transactions on data stored in Cloud Spanner databases.
  """

    def CreateSession(self, request, context):
        """Creates a new session. A session can be used to perform
    transactions that read and/or modify data in a Cloud Spanner database.
    Sessions are meant to be reused for many consecutive
    transactions.

    Sessions can only execute one transaction at a time. To execute
    multiple concurrent read-write/write-only transactions, create
    multiple sessions. Note that standalone reads and queries use a
    transaction internally, and count toward the one transaction
    limit.

    Active sessions use additional server resources, so it is a good idea to
    delete idle and unneeded sessions.
    Aside from explicit deletes, Cloud Spanner can delete sessions for which no
    operations are sent for more than an hour. If a session is deleted,
    requests to it return `NOT_FOUND`.

    Idle sessions can be kept alive by sending a trivial SQL query
    periodically, e.g., `"SELECT 1"`.
    """
        context.set_code(grpc.StatusCode.UNIMPLEMENTED)
        context.set_details("Method not implemented!")
        raise NotImplementedError("Method not implemented!")

    def BatchCreateSessions(self, request, context):
        """Creates multiple new sessions.

    This API can be used to initialize a session cache on the clients.
    See https://goo.gl/TgSFN2 for best practices on session cache management.
    """
        context.set_code(grpc.StatusCode.UNIMPLEMENTED)
        context.set_details("Method not implemented!")
        raise NotImplementedError("Method not implemented!")

    def GetSession(self, request, context):
        """Gets a session. Returns `NOT_FOUND` if the session does not exist.
    This is mainly useful for determining whether a session is still
    alive.
    """
        context.set_code(grpc.StatusCode.UNIMPLEMENTED)
        context.set_details("Method not implemented!")
        raise NotImplementedError("Method not implemented!")

    def ListSessions(self, request, context):
        """Lists all sessions in a given database.
    """
        context.set_code(grpc.StatusCode.UNIMPLEMENTED)
        context.set_details("Method not implemented!")
        raise NotImplementedError("Method not implemented!")

    def DeleteSession(self, request, context):
        """Ends a session, releasing server resources associated with it. This will
    asynchronously trigger cancellation of any operations that are running with
    this session.
    """
        context.set_code(grpc.StatusCode.UNIMPLEMENTED)
        context.set_details("Method not implemented!")
        raise NotImplementedError("Method not implemented!")

    def ExecuteSql(self, request, context):
        """Executes an SQL statement, returning all results in a single reply. This
    method cannot be used to return a result set larger than 10 MiB;
    if the query yields more data than that, the query fails with
    a `FAILED_PRECONDITION` error.

    Operations inside read-write transactions might return `ABORTED`. If
    this occurs, the application should restart the transaction from
    the beginning. See [Transaction][google.spanner.v1.Transaction] for more
    details.

    Larger result sets can be fetched in streaming fashion by calling
    [ExecuteStreamingSql][google.spanner.v1.Spanner.ExecuteStreamingSql]
    instead.
    """
        context.set_code(grpc.StatusCode.UNIMPLEMENTED)
        context.set_details("Method not implemented!")
        raise NotImplementedError("Method not implemented!")

    def ExecuteStreamingSql(self, request, context):
        """Like [ExecuteSql][google.spanner.v1.Spanner.ExecuteSql], except returns the
    result set as a stream. Unlike
    [ExecuteSql][google.spanner.v1.Spanner.ExecuteSql], there is no limit on
    the size of the returned result set. However, no individual row in the
    result set can exceed 100 MiB, and no column value can exceed 10 MiB.
    """
        context.set_code(grpc.StatusCode.UNIMPLEMENTED)
        context.set_details("Method not implemented!")
        raise NotImplementedError("Method not implemented!")

    def ExecuteBatchDml(self, request, context):
        """Executes a batch of SQL DML statements. This method allows many statements
    to be run with lower latency than submitting them sequentially with
    [ExecuteSql][google.spanner.v1.Spanner.ExecuteSql].

    Statements are executed in sequential order. A request can succeed even if
    a statement fails. The
    [ExecuteBatchDmlResponse.status][google.spanner.v1.ExecuteBatchDmlResponse.status]
    field in the response provides information about the statement that failed.
    Clients must inspect this field to determine whether an error occurred.

    Execution stops after the first failed statement; the remaining statements
    are not executed.
    """
        context.set_code(grpc.StatusCode.UNIMPLEMENTED)
        context.set_details("Method not implemented!")
        raise NotImplementedError("Method not implemented!")

    def Read(self, request, context):
        """Reads rows from the database using key lookups and scans, as a
    simple key/value style alternative to
    [ExecuteSql][google.spanner.v1.Spanner.ExecuteSql].  This method cannot be
    used to return a result set larger than 10 MiB; if the read matches more
    data than that, the read fails with a `FAILED_PRECONDITION`
    error.

    Reads inside read-write transactions might return `ABORTED`. If
    this occurs, the application should restart the transaction from
    the beginning. See [Transaction][google.spanner.v1.Transaction] for more
    details.

    Larger result sets can be yielded in streaming fashion by calling
    [StreamingRead][google.spanner.v1.Spanner.StreamingRead] instead.
    """
        context.set_code(grpc.StatusCode.UNIMPLEMENTED)
        context.set_details("Method not implemented!")
        raise NotImplementedError("Method not implemented!")

    def StreamingRead(self, request, context):
        """Like [Read][google.spanner.v1.Spanner.Read], except returns the result set
    as a stream. Unlike [Read][google.spanner.v1.Spanner.Read], there is no
    limit on the size of the returned result set. However, no individual row in
    the result set can exceed 100 MiB, and no column value can exceed
    10 MiB.
    """
        context.set_code(grpc.StatusCode.UNIMPLEMENTED)
        context.set_details("Method not implemented!")
        raise NotImplementedError("Method not implemented!")

    def BeginTransaction(self, request, context):
        """Begins a new transaction. This step can often be skipped:
    [Read][google.spanner.v1.Spanner.Read],
    [ExecuteSql][google.spanner.v1.Spanner.ExecuteSql] and
    [Commit][google.spanner.v1.Spanner.Commit] can begin a new transaction as a
    side-effect.
    """
        context.set_code(grpc.StatusCode.UNIMPLEMENTED)
        context.set_details("Method not implemented!")
        raise NotImplementedError("Method not implemented!")

    def Commit(self, request, context):
        """Commits a transaction. The request includes the mutations to be
    applied to rows in the database.

    `Commit` might return an `ABORTED` error. This can occur at any time;
    commonly, the cause is conflicts with concurrent
    transactions. However, it can also happen for a variety of other
    reasons. If `Commit` returns `ABORTED`, the caller should re-attempt
    the transaction from the beginning, re-using the same session.
    """
        context.set_code(grpc.StatusCode.UNIMPLEMENTED)
        context.set_details("Method not implemented!")
        raise NotImplementedError("Method not implemented!")

    def Rollback(self, request, context):
        """Rolls back a transaction, releasing any locks it holds. It is a good
    idea to call this for any transaction that includes one or more
    [Read][google.spanner.v1.Spanner.Read] or
    [ExecuteSql][google.spanner.v1.Spanner.ExecuteSql] requests and ultimately
    decides not to commit.

    `Rollback` returns `OK` if it successfully aborts the transaction, the
    transaction was already aborted, or the transaction is not
    found. `Rollback` never returns `ABORTED`.
    """
        context.set_code(grpc.StatusCode.UNIMPLEMENTED)
        context.set_details("Method not implemented!")
        raise NotImplementedError("Method not implemented!")

    def PartitionQuery(self, request, context):
        """Creates a set of partition tokens that can be used to execute a query
    operation in parallel.  Each of the returned partition tokens can be used
    by [ExecuteStreamingSql][google.spanner.v1.Spanner.ExecuteStreamingSql] to
    specify a subset of the query result to read.  The same session and
    read-only transaction must be used by the PartitionQueryRequest used to
    create the partition tokens and the ExecuteSqlRequests that use the
    partition tokens.

    Partition tokens become invalid when the session used to create them
    is deleted, is idle for too long, begins a new transaction, or becomes too
    old.  When any of these happen, it is not possible to resume the query, and
    the whole operation must be restarted from the beginning.
    """
        context.set_code(grpc.StatusCode.UNIMPLEMENTED)
        context.set_details("Method not implemented!")
        raise NotImplementedError("Method not implemented!")

    def PartitionRead(self, request, context):
        """Creates a set of partition tokens that can be used to execute a read
    operation in parallel.  Each of the returned partition tokens can be used
    by [StreamingRead][google.spanner.v1.Spanner.StreamingRead] to specify a
    subset of the read result to read.  The same session and read-only
    transaction must be used by the PartitionReadRequest used to create the
    partition tokens and the ReadRequests that use the partition tokens.  There
    are no ordering guarantees on rows returned among the returned partition
    tokens, or even within each individual StreamingRead call issued with a
    partition_token.

    Partition tokens become invalid when the session used to create them
    is deleted, is idle for too long, begins a new transaction, or becomes too
    old.  When any of these happen, it is not possible to resume the read, and
    the whole operation must be restarted from the beginning.
    """
        context.set_code(grpc.StatusCode.UNIMPLEMENTED)
        context.set_details("Method not implemented!")
        raise NotImplementedError("Method not implemented!")

def add_SpannerServicer_to_server(servicer, server):
    rpc_method_handlers = {
        "CreateSession": grpc.unary_unary_rpc_method_handler(
            servicer.CreateSession,
            request_deserializer=google_dot_cloud_dot_spanner__v1_dot_proto_dot_spanner__pb2.CreateSessionRequest.FromString,
            response_serializer=google_dot_cloud_dot_spanner__v1_dot_proto_dot_spanner__pb2.Session.SerializeToString,
        ),
        "BatchCreateSessions": grpc.unary_unary_rpc_method_handler(
            servicer.BatchCreateSessions,
            request_deserializer=google_dot_cloud_dot_spanner__v1_dot_proto_dot_spanner__pb2.BatchCreateSessionsRequest.FromString,
            response_serializer=google_dot_cloud_dot_spanner__v1_dot_proto_dot_spanner__pb2.BatchCreateSessionsResponse.SerializeToString,
        ),
        "GetSession": grpc.unary_unary_rpc_method_handler(
            servicer.GetSession,
            request_deserializer=google_dot_cloud_dot_spanner__v1_dot_proto_dot_spanner__pb2.GetSessionRequest.FromString,
            response_serializer=google_dot_cloud_dot_spanner__v1_dot_proto_dot_spanner__pb2.Session.SerializeToString,
        ),
        "ListSessions": grpc.unary_unary_rpc_method_handler(
            servicer.ListSessions,
            request_deserializer=google_dot_cloud_dot_spanner__v1_dot_proto_dot_spanner__pb2.ListSessionsRequest.FromString,
            response_serializer=google_dot_cloud_dot_spanner__v1_dot_proto_dot_spanner__pb2.ListSessionsResponse.SerializeToString,
        ),
        "DeleteSession": grpc.unary_unary_rpc_method_handler(
            servicer.DeleteSession,
            request_deserializer=google_dot_cloud_dot_spanner__v1_dot_proto_dot_spanner__pb2.DeleteSessionRequest.FromString,
            response_serializer=google_dot_protobuf_dot_empty__pb2.Empty.SerializeToString,
        ),
        "ExecuteSql": grpc.unary_unary_rpc_method_handler(
            servicer.ExecuteSql,
            request_deserializer=google_dot_cloud_dot_spanner__v1_dot_proto_dot_spanner__pb2.ExecuteSqlRequest.FromString,
            response_serializer=google_dot_cloud_dot_spanner__v1_dot_proto_dot_result__set__pb2.ResultSet.SerializeToString,
        ),
        "ExecuteStreamingSql": grpc.unary_stream_rpc_method_handler(
            servicer.ExecuteStreamingSql,
            request_deserializer=google_dot_cloud_dot_spanner__v1_dot_proto_dot_spanner__pb2.ExecuteSqlRequest.FromString,
            response_serializer=google_dot_cloud_dot_spanner__v1_dot_proto_dot_result__set__pb2.PartialResultSet.SerializeToString,
        ),
        "ExecuteBatchDml": grpc.unary_unary_rpc_method_handler(
            servicer.ExecuteBatchDml,
            request_deserializer=google_dot_cloud_dot_spanner__v1_dot_proto_dot_spanner__pb2.ExecuteBatchDmlRequest.FromString,
            response_serializer=google_dot_cloud_dot_spanner__v1_dot_proto_dot_spanner__pb2.ExecuteBatchDmlResponse.SerializeToString,
        ),
        "Read": grpc.unary_unary_rpc_method_handler(
            servicer.Read,
            request_deserializer=google_dot_cloud_dot_spanner__v1_dot_proto_dot_spanner__pb2.ReadRequest.FromString,
            response_serializer=google_dot_cloud_dot_spanner__v1_dot_proto_dot_result__set__pb2.ResultSet.SerializeToString,
        ),
        "StreamingRead": grpc.unary_stream_rpc_method_handler(
            servicer.StreamingRead,
            request_deserializer=google_dot_cloud_dot_spanner__v1_dot_proto_dot_spanner__pb2.ReadRequest.FromString,
            response_serializer=google_dot_cloud_dot_spanner__v1_dot_proto_dot_result__set__pb2.PartialResultSet.SerializeToString,
        ),
        "BeginTransaction": grpc.unary_unary_rpc_method_handler(
            servicer.BeginTransaction,
            request_deserializer=google_dot_cloud_dot_spanner__v1_dot_proto_dot_spanner__pb2.BeginTransactionRequest.FromString,
            response_serializer=google_dot_cloud_dot_spanner__v1_dot_proto_dot_transaction__pb2.Transaction.SerializeToString,
        ),
        "Commit": grpc.unary_unary_rpc_method_handler(
            servicer.Commit,
            request_deserializer=google_dot_cloud_dot_spanner__v1_dot_proto_dot_spanner__pb2.CommitRequest.FromString,
            response_serializer=google_dot_cloud_dot_spanner__v1_dot_proto_dot_spanner__pb2.CommitResponse.SerializeToString,
        ),
        "Rollback": grpc.unary_unary_rpc_method_handler(
            servicer.Rollback,
            request_deserializer=google_dot_cloud_dot_spanner__v1_dot_proto_dot_spanner__pb2.RollbackRequest.FromString,
            response_serializer=google_dot_protobuf_dot_empty__pb2.Empty.SerializeToString,
        ),
        "PartitionQuery": grpc.unary_unary_rpc_method_handler(
            servicer.PartitionQuery,
            request_deserializer=google_dot_cloud_dot_spanner__v1_dot_proto_dot_spanner__pb2.PartitionQueryRequest.FromString,
            response_serializer=google_dot_cloud_dot_spanner__v1_dot_proto_dot_spanner__pb2.PartitionResponse.SerializeToString,
        ),
        "PartitionRead": grpc.unary_unary_rpc_method_handler(
            servicer.PartitionRead,
            request_deserializer=google_dot_cloud_dot_spanner__v1_dot_proto_dot_spanner__pb2.PartitionReadRequest.FromString,
            response_serializer=google_dot_cloud_dot_spanner__v1_dot_proto_dot_spanner__pb2.PartitionResponse.SerializeToString,
        ),
    }
    generic_handler = grpc.method_handlers_generic_handler(
        "google.spanner.v1.Spanner", rpc_method_handlers
    )
    server.add_generic_rpc_handlers((generic_handler,))


text:
RSpec.describe Compilers::Environments do
  describe '#save' do
    let(:params) do
      params_fixture.merge(environments: %w(development staging), staging: {
        target:   'server',
        host:     'myapp.com',
        port:     '22',
        username: 'ubuntu',
      })
    end
    let(:staging_inventory_path) { File.join(@dir, 'staging', 'inventory') }
    let(:staging_provision_path) { File.join(@dir, 'staging', 'provision.sh') }
    subject { described_class.new(params) }

    before { @dir = Dir.mktmpdir }
    before { Compilers::Copy.new(params).save(@dir) }
    before { subject.save(@dir) }

    it 'creates development directory' do
      expect(Dir).to exist(File.join(@dir, 'development'))
    end

    it 'creates staging directory' do
      expect(Dir).to exist(File.join(@dir, 'staging'))
    end

    it 'does not creates production directory' do
      expect(Dir).not_to exist(File.join(@dir, 'production'))
    end

    describe 'development - VirtualBox' do
      let(:vagrantfile_path) { File.join(@dir, 'development', 'Vagrantfile') }
      let(:config_path) { File.join(@dir, 'ansible/group_vars/development/config.yml') }

      it 'copies Vagrantfile' do
        expect(File).to exist(vagrantfile_path)
      end

      it 'does not creates development/inventory' do
        expect(File).not_to exist(File.join(@dir, 'development', 'inventory'))
      end

      it 'does not creates development/provision.sh' do
        expect(File).not_to exist(File.join(@dir, 'development', 'provision.sh'))
      end

      context 'ansible/group_vars/development/config.yml' do
        let(:output) { IO.read(config_path) }

        it 'sets rails_env' do
          expect(output).to include %Q(rails_env: development)
        end
      end

      context 'Vagrantfile' do
        let(:output) { IO.read(vagrantfile_path) }

        it 'sets name' do
          expect(output).to include %Q(.vm.define 'testapp')
          expect(output).to include %Q(hostname = 'localhost')
        end

        it 'sets operating system' do
          expect(output).to include %Q(.vm.box = 'ubuntu/trusty64')
        end

        it 'sets memory' do
          expect(output).to include %Q(sysctl -n hw.memsize)
        end

        it 'sets cores' do
          expect(output).to include %Q(sysctl -n hw.ncpu)
        end

        it 'sets forwarded port' do
          expect(output).to include %Q(vm.network 'forwarded_port', :guest => 80, :host => 8080)
        end

        it 'sets box ip' do
          expect(output).to include %Q(.vm.network 'private_network', ip: '192.168.20.50')
        end
      end
    end

    describe 'staging - remote server' do
      it 'creates staging/inventory' do
        expect(File).to exist(staging_inventory_path)
      end

      it 'creates staging/provision.sh' do
        expect(File).to exist(staging_provision_path)
      end

      it 'keeps executable flag on staging/provision.sh' do
        expect(File).to be_executable(staging_provision_path)
      end

      context 'inventory' do
        let(:output) { IO.read(staging_inventory_path) }

        it 'sets correct environment' do
          expect(output).to include %Q([staging])
        end
      end
    end

    after { FileUtils.remove_entry_secure @dir }
  end
end


text:
package org.apache.cassandra.stress.settings;

import java.io.Serializable;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;

import com.google.common.util.concurrent.Uninterruptibles;

import org.apache.cassandra.stress.operations.OpDistributionFactory;
import org.apache.cassandra.stress.util.JavaDriverClient;
import org.apache.cassandra.stress.util.ResultLogger;
import org.apache.cassandra.db.ConsistencyLevel;

// Generic command settings - common to read/write/etc
public abstract class SettingsCommand implements Serializable
{

    public static enum TruncateWhen
    {
        NEVER, ONCE, ALWAYS
    }

    public final Command type;
    public final long count;
    public final long duration;
    public final TimeUnit durationUnits;
    public final boolean noWarmup;
    public final TruncateWhen truncate;
    public final ConsistencyLevel consistencyLevel;
    public final double targetUncertainty;
    public final int minimumUncertaintyMeasurements;
    public final int maximumUncertaintyMeasurements;

    public abstract OpDistributionFactory getFactory(StressSettings settings);

    public SettingsCommand(Command type, GroupedOptions options)
    {
        this(type, (Options) options,
                options instanceof Count ? (Count) options : null,
                options instanceof Duration ? (Duration) options : null,
                options instanceof Uncertainty ? (Uncertainty) options : null
        );
    }

    public SettingsCommand(Command type, Options options, Count count, Duration duration, Uncertainty uncertainty)
    {
        this.type = type;
        this.consistencyLevel = ConsistencyLevel.valueOf(options.consistencyLevel.value().toUpperCase());
        this.noWarmup = options.noWarmup.setByUser();
        this.truncate = TruncateWhen.valueOf(options.truncate.value().toUpperCase());

        if (count != null)
        {
            this.count = OptionDistribution.parseLong(count.count.value());
            this.duration = 0;
            this.durationUnits = null;
            this.targetUncertainty = -1;
            this.minimumUncertaintyMeasurements = -1;
            this.maximumUncertaintyMeasurements = -1;
        }
        else if (duration != null)
        {
            this.count = -1;
            this.duration = Long.parseLong(duration.duration.value().substring(0, duration.duration.value().length() - 1));
            switch (duration.duration.value().toLowerCase().charAt(duration.duration.value().length() - 1))
            {
                case 's':
                    this.durationUnits = TimeUnit.SECONDS;
                    break;
                case 'm':
                    this.durationUnits = TimeUnit.MINUTES;
                    break;
                case 'h':
                    this.durationUnits = TimeUnit.HOURS;
                    break;
                case 'd':
                    this.durationUnits = TimeUnit.DAYS;
                    break;
                default:
                    throw new IllegalStateException();
            }
            this.targetUncertainty = -1;
            this.minimumUncertaintyMeasurements = -1;
            this.maximumUncertaintyMeasurements = -1;
        }
        else
        {
            this.count = -1;
            this.duration = 0;
            this.durationUnits = null;
            this.targetUncertainty = Double.parseDouble(uncertainty.uncertainty.value());
            this.minimumUncertaintyMeasurements = Integer.parseInt(uncertainty.minMeasurements.value());
            this.maximumUncertaintyMeasurements = Integer.parseInt(uncertainty.maxMeasurements.value());
        }
    }

    // Option Declarations

    static abstract class Options extends GroupedOptions
    {
        final OptionSimple noWarmup = new OptionSimple("no-warmup", "", null, "Do not warmup the process", false);
        final OptionSimple truncate = new OptionSimple("truncate=", "never|once|always", "never", "Truncate the table: never, before performing any work, or before each iteration", false);
        final OptionSimple consistencyLevel = new OptionSimple("cl=", "ONE|QUORUM|LOCAL_QUORUM|EACH_QUORUM|ALL|ANY|TWO|THREE|LOCAL_ONE|SERIAL|LOCAL_SERIAL", "LOCAL_ONE", "Consistency level to use", false);
    }

    static class Count extends Options
    {
        final OptionSimple count = new OptionSimple("n=", "[0-9]+[bmk]?", null, "Number of operations to perform", true);
        @Override
        public List<? extends Option> options()
        {
            return Arrays.asList(count, noWarmup, truncate, consistencyLevel);
        }
    }

    static class Duration extends Options
    {
        final OptionSimple duration = new OptionSimple("duration=", "[0-9]+[smhd]", null, "Time to run in (in seconds, minutes, hours or days)", true);
        @Override
        public List<? extends Option> options()
        {
            return Arrays.asList(duration, noWarmup, truncate, consistencyLevel);
        }
    }

    static class Uncertainty extends Options
    {
        final OptionSimple uncertainty = new OptionSimple("err<", "0\\.[0-9]+", "0.02", "Run until the standard error of the mean is below this fraction", false);
        final OptionSimple minMeasurements = new OptionSimple("n>", "[0-9]+", "30", "Run at least this many iterations before accepting uncertainty convergence", false);
        final OptionSimple maxMeasurements = new OptionSimple("n<", "[0-9]+", "200", "Run at most this many iterations before accepting uncertainty convergence", false);
        @Override
        public List<? extends Option> options()
        {
            return Arrays.asList(uncertainty, minMeasurements, maxMeasurements, noWarmup, truncate, consistencyLevel);
        }
    }

    public abstract void truncateTables(StressSettings settings);

    protected void truncateTables(StressSettings settings, String ks, String ... tables)
    {
        JavaDriverClient client = settings.getJavaDriverClient(false);
        assert settings.command.truncate != SettingsCommand.TruncateWhen.NEVER;
        for (String table : tables)
        {
            String cql = String.format("TRUNCATE %s.%s", ks, table);
            client.execute(cql, org.apache.cassandra.db.ConsistencyLevel.ONE);
        }
        System.out.println(String.format("Truncated %s.%s. Sleeping %ss for propagation.",
                                         ks, Arrays.toString(tables), settings.node.nodes.size()));
        Uninterruptibles.sleepUninterruptibly(settings.node.nodes.size(), TimeUnit.SECONDS);
    }

    // CLI Utility Methods

    public void printSettings(ResultLogger out)
    {
        out.printf("  Type: %s%n", type.toString().toLowerCase());
        out.printf("  Count: %,d%n", count);
        if (durationUnits != null)
        {
            out.printf("  Duration: %,d %s%n", duration, durationUnits.toString());
        }
        out.printf("  No Warmup: %s%n", noWarmup);
        out.printf("  Consistency Level: %s%n", consistencyLevel.toString());
        if (targetUncertainty != -1)
        {
            out.printf("  Target Uncertainty: %.3f%n", targetUncertainty);
            out.printf("  Minimum Uncertainty Measurements: %,d%n", minimumUncertaintyMeasurements);
            out.printf("  Maximum Uncertainty Measurements: %,d%n", maximumUncertaintyMeasurements);
        } else {
            out.printf("  Target Uncertainty: not applicable%n");
        }
    }

    static SettingsCommand get(Map<String, String[]> clArgs)
    {
        for (Command cmd : Command.values())
        {
            if (cmd.category == null)
                continue;

            for (String name : cmd.names)
            {
                final String[] params = clArgs.remove(name);
                if (params == null)
                    continue;

                switch (cmd.category)
                {
                    case BASIC:
                        return SettingsCommandPreDefined.build(cmd, params);
                    case MIXED:
                        return SettingsCommandPreDefinedMixed.build(params);
                    case USER:
                        return SettingsCommandUser.build(params);
                }
            }
        }
        return null;
    }

    static void printHelp(Command type)
    {
        printHelp(type.toString().toLowerCase());
    }

    static void printHelp(String type)
    {
        GroupedOptions.printOptions(System.out, type.toLowerCase(), new Uncertainty(), new Count(), new Duration());
    }

    static Runnable helpPrinter(final Command type)
    {
        return new Runnable()
        {
            @Override
            public void run()
            {
                printHelp(type);
            }
        };
    }
}


text:
'use strict';
var PaintersList    = require('./pages/PaintersList.js');
var PaintingsList    = require('./pages/PaintingsList.js');
describe('vincentApp', function() {
	var painters   = new PaintersList();
  var paintings   = new PaintingsList();
	beforeEach(function() {
    	painters.loadAll();
  });
	it('should load and have the correct title', function() {
  		browser.get('http://localhost:8000/app/');
    	expect(browser.getLocationAbsUrl()).toMatch("/game");
    	expect(browser.getTitle()).toEqual('Vincent');
  	});
  	it('should load a list of painters', function() {
      expect(painters.count()).toBeGreaterThan(1);
    });
    it('should load a list of paintings', function() {
      console.log('paintings '+paintings.count());
      expect(paintings.count()).toBeGreaterThan(1);
    });
});


text:
package org.openhds.integration;

import static org.junit.Assert.*;

import org.hibernate.SessionFactory;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.openhds.controller.service.CurrentUser;
import org.openhds.controller.service.LocationHierarchyService;
import org.openhds.dao.service.GenericDao;
import org.openhds.domain.model.FieldWorker;
import org.openhds.domain.model.Location;
import org.openhds.domain.model.LocationHierarchy;
import org.openhds.domain.service.SitePropertiesService;
import org.openhds.integration.util.JsfServiceMock;
import org.openhds.web.crud.impl.LocationCrudImpl;
import org.openhds.web.crud.impl.LocationHierarchyCrudImpl;
import org.openhds.web.service.JsfService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.AbstractTransactionalJUnit4SpringContextTests;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.transaction.annotation.Transactional;

@RunWith(SpringJUnit4ClassRunner.class)
@Transactional
@ContextConfiguration("/testContext.xml")
public class LocationTest extends AbstractTransactionalJUnit4SpringContextTests {

	 @Autowired
	 @Qualifier("locationCrud")
	 LocationCrudImpl locationCrud;

	 @Autowired
	 @Qualifier("locationHierarchyCrud")
	 LocationHierarchyCrudImpl locationHierarchyCrud;

	 @Autowired
	 @Qualifier("locationHierarchyService")
	 LocationHierarchyService locationHierarchyService;

	 @Autowired
	 SessionFactory sessionFactory;

	 @Autowired
	 GenericDao genericDao;

	 @Autowired
	 SitePropertiesService siteProperties;

	 @Autowired
	 JsfService jsfService;

	 @Autowired
	 @Qualifier("currentUser")
	 CurrentUser currentUser;

	 LocationHierarchy locH2;
	 LocationHierarchy item;
	 FieldWorker fieldWorker;
	 JsfServiceMock jsfServiceMock;

	 @Before
	 public void setUp() {
		 jsfServiceMock = (JsfServiceMock)jsfService;
		 currentUser.setProxyUser("admin", "test", new String[] {"VIEW_ENTITY", "CREATE_ENTITY"});
		 createLocationHierarchy();

		 fieldWorker = genericDao.findByProperty(FieldWorker.class, "extId", "FWEK1D");
	 }

	 @After
	 public void tearDown() {
		 jsfServiceMock.resetErrors();
	 }

	 @Test
	 public void testLocationCreate() {

		 Location location = new Location();
		 location.setLocationName("locationName");
		 location.setLocationType("RUR");
		 location.setLocationLevel(item);
		 location.setCollectedBy(fieldWorker);
		 locationCrud.setItem(location);
	     locationCrud.create();

	     Location savedLocation = genericDao.findByProperty(Location.class, "extId", location.getExtId());
	     assertNotNull(savedLocation);
	 }

	 @Test
	 public void testInvalidLocationCreate() {

		 Location location = new Location();
		 location.setLocationName("locationName");
		 location.setLocationType("RUR");
		 location.setLocationLevel(locH2);
		 location.setCollectedBy(fieldWorker);
		 locationCrud.setItem(location);

		 assertNull(locationCrud.create());
		 assertTrue(jsfServiceMock.getErrors().size() > 0);
	 }

	 private void createLocationHierarchy() {

    	 LocationHierarchy locH1 = new LocationHierarchy();

    	 locH1.setParent(new LocationHierarchy());
    	 locH1.setName(locationHierarchyService.getLevel(1).getName());
    	 locH1.setExtId("MOR");

    	 locationHierarchyCrud.setItem(locH1);
    	 locationHierarchyCrud.create();

	     locH2 = new LocationHierarchy();
	     locH2.setParent(locH1);
	     locH2.setName(locationHierarchyService.getLevel(2).getName());
	     locH2.setExtId("IFA");

 	     locationHierarchyCrud.setItem(locH2);
	     locationHierarchyCrud.create();

	     item = new LocationHierarchy();
	     item.setParent(locH2);
	     item.setName(locationHierarchyService.getLevel(3).getName());
	     item.setExtId("MBI");

	     locationHierarchyCrud.setItem(item);
 	     locationHierarchyCrud.create();
	 }
}


text:
<?php

declare (strict_types=1);
namespace RectorPrefix20210615\Helmich\TypoScriptParser\Parser\Traverser;

use RectorPrefix20210615\Helmich\TypoScriptParser\Parser\AST\ConditionalStatement;
use RectorPrefix20210615\Helmich\TypoScriptParser\Parser\AST\NestedAssignment;
use RectorPrefix20210615\Helmich\TypoScriptParser\Parser\AST\Statement;
/**
 * Class Traverser
 *
 * @package    Helmich\TypoScriptParser
 * @subpackage Parser\Traverser
 */
class Traverser
{
    /** @var Statement[] */
    private $statements;
    /** @var AggregatingVisitor */
    private $visitors;
    /**
     * @param Statement[] $statements
     */
    public function __construct(array $statements)
    {
        $this->statements = $statements;
        $this->visitors = new \RectorPrefix20210615\Helmich\TypoScriptParser\Parser\Traverser\AggregatingVisitor();
    }
    /**
     * @param Visitor $visitor
     */
    public function addVisitor(\RectorPrefix20210615\Helmich\TypoScriptParser\Parser\Traverser\Visitor $visitor) : void
    {
        $this->visitors->addVisitor($visitor);
    }
    /**
     * @return void
     */
    public function walk() : void
    {
        $this->visitors->enterTree($this->statements);
        $this->walkRecursive($this->statements);
        $this->visitors->exitTree($this->statements);
    }
    /**
     * @param Statement[] $statements
     * @return Statement[]
     */
    private function walkRecursive(array $statements) : array
    {
        foreach ($statements as $statement) {
            $this->visitors->enterNode($statement);
            if ($statement instanceof \RectorPrefix20210615\Helmich\TypoScriptParser\Parser\AST\NestedAssignment) {
                $statement->statements = $this->walkRecursive($statement->statements);
            } elseif ($statement instanceof \RectorPrefix20210615\Helmich\TypoScriptParser\Parser\AST\ConditionalStatement) {
                $statement->ifStatements = $this->walkRecursive($statement->ifStatements);
                $statement->elseStatements = $this->walkRecursive($statement->elseStatements);
            }
            $this->visitors->exitNode($statement);
        }
        return $statements;
    }
}


text:
Workbench.Views.SensorLoggerView = Backbone.Marionette.ItemView.extend({
  template: "logger",

  modelEvents: {
    "sensorLoaded": "loadAttributes"
  },

  ui: {
    log: "#logger",
    endpoint: ".sensor-endpoint"
  },

  initialize: function() {
    this.renderDeferred = $.Deferred();
  },

  onRender: function() {
    this.renderDeferred.resolve();
  },

  loadAttributes: function() {
    var self = this;
    this.renderDeferred.done(function() {
      self.swapContent(self.ui.endpoint, self.model.get("endpoint"));
    });
  },

  // Animate out, update content, animate back in
  swapContent: function($element, content) {
    var self = this;
    $element.transition({ rotateX: '90deg' }).promise().done(function() {
      self.text(content).transition({ rotateX: '0deg' });
    });
  }
});


text:
import OverlayTrigger from '../../../components/overlayTrigger/overlayTrigger';

describe('OverlayTrigger: addOutsideClickListener', () => {
  beforeEach(() => {
    document.body.addEventListener = jest.fn();
  });

  afterEach(() => {
    document.body.addEventListener.mockReset();
  });

  it('should set handleOutsideClick method as a listener to on body click', () => {
    const prototype = {
      handleOutsideClick: jest.fn(),
    };

    OverlayTrigger.prototype.addOutsideClickListener.call(prototype);

    expect(document.body.addEventListener).toBeCalledWith('click', prototype.handleOutsideClick);
  });
});


text:
package org.cbioportal.genome_nexus.model;

import org.springframework.data.mongodb.core.mapping.Field;

public class CountByTumorType
{
    @Field("tumor_type")
    private String tumorType;

    @Field("tumor_type_count")
    private Integer tumorTypeCount;

    @Field("variant_count")
    private Integer variantCount;

    public String getTumorType() {
        return tumorType;
    }

    public void setTumorType(String tumorType) {
        this.tumorType = tumorType;
    }

    public Integer getTumorTypeCount() {
        return tumorTypeCount;
    }

    public void setTumorTypeCount(Integer tumorTypeCount) {
        this.tumorTypeCount = tumorTypeCount;
    }

    public Integer getVariantCount() {
        return variantCount;
    }

    public void setVariantCount(Integer variantCount) {
        this.variantCount = variantCount;
    }
}


text:
def longest_string(list_of_words)
  p list_of_words.max_by {|word| word.length}
end


text:
/*!
 * Module dependencies.
 */

var MongooseConnection = require('../../connection')
  , mongo = require('mongodb')
  , Db = mongo.Db
  , Server = mongo.Server
  , Mongos = mongo.Mongos
  , STATES = require('../../connectionstate')
  , ReplSetServers = mongo.ReplSetServers;

/**
 * A [node-mongodb-native](https://github.com/mongodb/node-mongodb-native) connection implementation.
 *
 * @inherits Connection
 * @api private
 */

function NativeConnection() {
  MongooseConnection.apply(this, arguments);
  this._listening = false;
};

/**
 * Expose the possible connection states.
 * @api public
 */

NativeConnection.STATES = STATES;

/*!
 * Inherits from Connection.
 */

NativeConnection.prototype.__proto__ = MongooseConnection.prototype;

/**
 * Opens the connection to MongoDB.
 *
 * @param {Function} fn
 * @return {Connection} this
 * @api private
 */

NativeConnection.prototype.doOpen = function (fn) {
  if (this.db) {
    mute(this);
  }

  var server = new Server(this.host, this.port, this.options.server);
  this.db = new Db(this.name, server, this.options.db);

  var self = this;
  this.db.open(function (err) {
    if (err) return fn(err);
    listen(self);
    fn();
  });

  return this;
};

/*!
 * Register listeners for important events and bubble appropriately.
 */

function listen (conn) {
  if (conn._listening) return;
  conn._listening = true;

  conn.db.on('close', function(){
    if (conn._closeCalled) return;

    // the driver never emits an `open` event. auto_reconnect still
    // emits a `close` event but since we never get another
    // `open` we can't emit close
    if (conn.db.serverConfig.autoReconnect) {
      conn.readyState = STATES.disconnected;
      conn.emit('close');
      return;
    }
    conn.onClose();
  });
  conn.db.on('error', function(err){
    conn.emit('error', err);
  });
  conn.db.on('timeout', function(err){
    var error = new Error(err && err.err || 'connection timeout');
    conn.emit('error', error);
  });
  conn.db.on('open', function (err, db) {
    if (STATES.disconnected === conn.readyState && db && db.databaseName) {
      conn.readyState = STATES.connected;
      conn.emit('reconnected')
    }
  })
}

/*!
 * Remove listeners registered in `listen`
 */

function mute (conn) {
  if (!conn.db) throw new Error('missing db');
  conn.db.removeAllListeners("close");
  conn.db.removeAllListeners("error");
  conn.db.removeAllListeners("timeout");
  conn.db.removeAllListeners("open");
  conn.db.removeAllListeners("fullsetup");
  conn._listening = false;
}

/**
 * Opens a connection to a MongoDB ReplicaSet.
 *
 * See description of [doOpen](#NativeConnection-doOpen) for server options. In this case `options.replset` is also passed to ReplSetServers.
 *
 * @param {Function} fn
 * @api private
 * @return {Connection} this
 */

NativeConnection.prototype.doOpenSet = function (fn) {
  if (this.db) {
    mute(this);
  }

  var servers = []
    , self = this;

  this.hosts.forEach(function (server) {
    var host = server.host || server.ipc;
    var port = server.port || 27017;
    servers.push(new Server(host, port, self.options.server));
  })

  var server = this.options.mongos
    ? new Mongos(servers, this.options.mongos)
    : new ReplSetServers(servers, this.options.replset);
  this.db = new Db(this.name, server, this.options.db);

  this.db.on('fullsetup', function () {
    self.emit('fullsetup')
  });

  this.db.open(function (err) {
    if (err) return fn(err);
    fn();
    listen(self);
  });

  return this;
};

/**
 * Closes the connection
 *
 * @param {Function} fn
 * @return {Connection} this
 * @api private
 */

NativeConnection.prototype.doClose = function (fn) {
  this.db.close();
  if (fn) fn();
  return this;
}

/**
 * Prepares default connection options for the node-mongodb-native driver.
 *
 * _NOTE: `passed` options take precedence over connection string options._
 *
 * @param {Object} passed options that were passed directly during connection
 * @param {Object} [connStrOptions] options that were passed in the connection string
 * @api private
 */

NativeConnection.prototype.parseOptions = function (passed, connStrOpts) {
  var o = passed || {};
  o.db || (o.db = {});
  o.auth || (o.auth = {});
  o.server || (o.server = {});
  o.replset || (o.replset = {});
  o.server.socketOptions || (o.server.socketOptions = {});
  o.replset.socketOptions || (o.replset.socketOptions = {});

  var opts = connStrOpts || {};
  Object.keys(opts).forEach(function (name) {
    switch (name) {
      case 'poolSize':
        if ('undefined' == typeof o.server.poolSize) {
          o.server.poolSize = o.replset.poolSize = opts[name];
        }
        break;
      case 'slaveOk':
        if ('undefined' == typeof o.server.slave_ok) {
          o.server.slave_ok = opts[name];
        }
        break;
      case 'autoReconnect':
        if ('undefined' == typeof o.server.auto_reconnect) {
          o.server.auto_reconnect = opts[name];
        }
        break;
      case 'ssl':
      case 'socketTimeoutMS':
      case 'connectTimeoutMS':
        if ('undefined' == typeof o.server.socketOptions[name]) {
          o.server.socketOptions[name] = o.replset.socketOptions[name] = opts[name];
        }
        break;
      case 'authdb':
        if ('undefined' == typeof o.auth.authdb) {
          o.auth.authdb = opts[name];
        }
        break;
      case 'authSource':
        if ('undefined' == typeof o.auth.authSource) {
          o.auth.authSource = opts[name];
        }
        break;
      case 'retries':
      case 'reconnectWait':
      case 'rs_name':
        if ('undefined' == typeof o.replset[name]) {
          o.replset[name] = opts[name];
        }
        break;
      case 'replicaSet':
        if ('undefined' == typeof o.replset.rs_name) {
          o.replset.rs_name = opts[name];
        }
        break;
      case 'readSecondary':
        if ('undefined' == typeof o.replset.read_secondary) {
          o.replset.read_secondary = opts[name];
        }
        break;
      case 'nativeParser':
        if ('undefined' == typeof o.db.native_parser) {
          o.db.native_parser = opts[name];
        }
        break;
      case 'w':
      case 'safe':
      case 'fsync':
      case 'journal':
      case 'wtimeoutMS':
        if ('undefined' == typeof o.db[name]) {
          o.db[name] = opts[name];
        }
        break;
      case 'readPreference':
        if ('undefined' == typeof o.db.read_preference) {
          o.db.read_preference = opts[name];
        }
        break;
      case 'readPreferenceTags':
        if ('undefined' == typeof o.db.read_preference_tags) {
          o.db.read_preference_tags = opts[name];
        }
        break;
    }
  })

  if (!('auto_reconnect' in o.server)) {
    o.server.auto_reconnect = true;
  }

  if (!o.db.read_preference) {
    // read from primaries by default
    o.db.read_preference = 'primary';
  }

  // mongoose creates its own ObjectIds
  o.db.forceServerObjectId = false;

  // default safe using new nomenclature
  if (!('journal' in o.db || 'j' in o.db ||
        'fsync' in o.db || 'safe' in o.db || 'w' in o.db)) {
    o.db.w = 1;
  }

  validate(o);
  return o;
}

/*!
 * Validates the driver db options.
 *
 * @param {Object} o
 */

function validate (o) {
  if (-1 === o.db.w || 0 === o.db.w) {
    if (o.db.journal || o.db.fsync || o.db.safe) {
      throw new Error(
          'Invalid writeConcern: '
        + 'w set to -1 or 0 cannot be combined with safe|fsync|journal');
    }
  }
}

/*!
 * Module exports.
 */

module.exports = NativeConnection;