text:
package com.android.email.activity;

import android.app.ActionBar;
import android.app.LoaderManager;
import android.app.LoaderManager.LoaderCallbacks;
import android.content.Context;
import android.content.Loader;
import android.database.Cursor;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.text.SpannableString;
import android.text.SpannableStringBuilder;
import android.text.TextUtils;
import android.text.style.TextAppearanceSpan;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ListPopupWindow;
import android.widget.ListView;
import android.widget.SearchView;
import android.widget.TextView;

import com.android.email.R;
import com.android.emailcommon.provider.Account;
import com.android.emailcommon.provider.Mailbox;
import com.android.emailcommon.utility.DelayedOperations;
import com.android.emailcommon.utility.Utility;

/**
 * Manages the account name and the custom view part on the action bar.
 */
public class ActionBarController {
    private static final String BUNDLE_KEY_MODE = "ActionBarController.BUNDLE_KEY_MODE";

    /**
     * Constants for {@link #mSearchMode}.
     *
     * In {@link #MODE_NORMAL} mode, we don't show the search box.
     * In {@link #MODE_SEARCH} mode, we do show the search box.
     * The action bar doesn't really care if the activity is showing search results.
     * If the activity is showing search results, and the {@link Callback#onSearchExit} is called,
     * the activity probably wants to close itself, but this class doesn't make the desision.
     */
    private static final int MODE_NORMAL = 0;
    private static final int MODE_SEARCH = 1;

    private static final int LOADER_ID_ACCOUNT_LIST
            = EmailActivity.ACTION_BAR_CONTROLLER_LOADER_ID_BASE + 0;

    private static final int DISPLAY_TITLE_MULTIPLE_LINES = 0x20;
    private static final int ACTION_BAR_MASK =
            ActionBar.DISPLAY_SHOW_HOME | ActionBar.DISPLAY_SHOW_CUSTOM
                    | ActionBar.DISPLAY_SHOW_TITLE | DISPLAY_TITLE_MULTIPLE_LINES;
    private static final int CUSTOM_ACTION_BAR_OPTIONS =
            ActionBar.DISPLAY_SHOW_HOME | ActionBar.DISPLAY_SHOW_CUSTOM;

    private final Context mContext;
    private final LoaderManager mLoaderManager;
    private final ActionBar mActionBar;
    private final DelayedOperations mDelayedOperations;

    /** "Folders" label shown with account name on 1-pane mailbox list */
    private final String mAllFoldersLabel;

    private final ViewGroup mActionBarCustomView;
    private final ViewGroup mAccountSpinnerContainer;
    private final View mAccountSpinner;
    private final Drawable mAccountSpinnerDefaultBackground;
    private final TextView mAccountSpinnerLine1View;
    private final TextView mAccountSpinnerLine2View;
    private final TextView mAccountSpinnerCountView;

    private View mSearchContainer;
    private SearchView mSearchView;

    private final AccountDropdownPopup mAccountDropdown;

    private final AccountSelectorAdapter mAccountsSelectorAdapter;

    private AccountSelectorAdapter.CursorWithExtras mCursor;

    /** The current account ID; used to determine if the account has changed. */
    private long mLastAccountIdForDirtyCheck = Account.NO_ACCOUNT;

    /** The current mailbox ID; used to determine if the mailbox has changed. */
    private long mLastMailboxIdForDirtyCheck = Mailbox.NO_MAILBOX;

    /** Either {@link #MODE_NORMAL} or {@link #MODE_SEARCH}. */
    private int mSearchMode = MODE_NORMAL;

    /** The current title mode, which should be one of {@code Callback TITLE_MODE_*} */
    private int mTitleMode;

    public final Callback mCallback;

    public interface SearchContext {
        public long getTargetMailboxId();
    }

    private static final int TITLE_MODE_SPINNER_ENABLED = 0x10;

    public interface Callback {
        /** Values for {@link #getTitleMode}.  Show only account name */
        public static final int TITLE_MODE_ACCOUNT_NAME_ONLY = 0 | TITLE_MODE_SPINNER_ENABLED;

        /**
         * Show the current account name with "Folders"
         * The account spinner will be disabled in this mode.
         */
        public static final int TITLE_MODE_ACCOUNT_WITH_ALL_FOLDERS_LABEL = 1;

        /**
         * Show the current account name and the current mailbox name.
         */
        public static final int TITLE_MODE_ACCOUNT_WITH_MAILBOX = 2 | TITLE_MODE_SPINNER_ENABLED;
        /**
         * Show the current message subject.  Actual subject is obtained via
         * {@link #getMessageSubject()}.
         *
         * The account spinner will be disabled in this mode.
         */
        public static final int TITLE_MODE_MESSAGE_SUBJECT = 3;

        /** @return true if an account is selected. */
        public boolean isAccountSelected();

        /**
         * @return currently selected account ID, {@link Account#ACCOUNT_ID_COMBINED_VIEW},
         * or -1 if no account is selected.
         */
        public long getUIAccountId();

        /**
         * @return currently selected mailbox ID, or {@link Mailbox#NO_MAILBOX} if no mailbox is
         * selected.
         */
        public long getMailboxId();

        /**
         * @return constants such as {@link #TITLE_MODE_ACCOUNT_NAME_ONLY}.
         */
        public int getTitleMode();

        /** @see #TITLE_MODE_MESSAGE_SUBJECT */
        public String getMessageSubject();

        /** @return the "UP" arrow should be shown. */
        public boolean shouldShowUp();

        /**
         * Called when an account is selected on the account spinner.
         * @param accountId ID of the selected account, or {@link Account#ACCOUNT_ID_COMBINED_VIEW}.
         */
        public void onAccountSelected(long accountId);

        /**
         * Invoked when a recent mailbox is selected on the account spinner.
         *
         * @param accountId ID of the selected account, or {@link Account#ACCOUNT_ID_COMBINED_VIEW}.
         * @param mailboxId The ID of the selected mailbox, or {@link Mailbox#NO_MAILBOX} if the
         *          special option "show all mailboxes" was selected.
         */
        public void onMailboxSelected(long accountId, long mailboxId);

        /** Called when no accounts are found in the database. */
        public void onNoAccountsFound();

        /**
         * Retrieves the hint text to be shown for when a search entry is being made.
         */
        public String getSearchHint();

        /**
         * Called when the action bar initially shows the search entry field.
         */
        public void onSearchStarted();

        /**
         * Called when a search is submitted.
         *
         * @param queryTerm query string
         */
        public void onSearchSubmit(String queryTerm);

        /**
         * Called when the search box is closed.
         */
        public void onSearchExit();

        public void onUpPressed();
    }

    public ActionBarController(Context context, LoaderManager loaderManager,
            ActionBar actionBar, Callback callback) {
        mContext = context;
        mLoaderManager = loaderManager;
        mActionBar = actionBar;
        mCallback = callback;
        mDelayedOperations = new DelayedOperations(Utility.getMainThreadHandler());
        mAllFoldersLabel = mContext.getResources().getString(
                R.string.action_bar_mailbox_list_title);
        mAccountsSelectorAdapter = new AccountSelectorAdapter(mContext);

        // Configure action bar.
        enterCustomActionBarMode();

        // Prepare the custom view
        mActionBar.setCustomView(R.layout.action_bar_custom_view);
        mActionBarCustomView = (ViewGroup) mActionBar.getCustomView();

        // Account spinner
        mAccountSpinnerContainer =
                UiUtilities.getView(mActionBarCustomView, R.id.account_spinner_container);
        mAccountSpinner = UiUtilities.getView(mActionBarCustomView, R.id.account_spinner);
        mAccountSpinnerDefaultBackground = mAccountSpinner.getBackground();

        mAccountSpinnerLine1View = UiUtilities.getView(mActionBarCustomView, R.id.spinner_line_1);
        mAccountSpinnerLine2View = UiUtilities.getView(mActionBarCustomView, R.id.spinner_line_2);
        mAccountSpinnerCountView = UiUtilities.getView(mActionBarCustomView, R.id.spinner_count);

        // Account dropdown
        mAccountDropdown = new AccountDropdownPopup(mContext);
        mAccountDropdown.setAdapter(mAccountsSelectorAdapter);

        mAccountSpinner.setOnClickListener(new View.OnClickListener() {
            @Override public void onClick(View v) {
                if (mAccountsSelectorAdapter.getCount() > 0) {
                    mAccountDropdown.show();
                }
            }
        });
        // this other click listener handles clicks that ought to be aliased to "up"
        // only one or the other listener should be active at any time
        mActionBarCustomView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mCallback.onUpPressed();
            }
        });
        // pick a sane default. later enabled in updateTitle().
        mActionBarCustomView.setClickable(false);
    }

    private void initSearchViews() {
        if (mSearchContainer == null) {
            final LayoutInflater inflater = LayoutInflater.from(mContext);
            mSearchContainer = inflater.inflate(R.layout.action_bar_search, null);
            mSearchView = UiUtilities.getView(mSearchContainer, R.id.search_view);
            mSearchView.setSubmitButtonEnabled(false);
            mSearchView.setOnQueryTextListener(mOnQueryText);
            mSearchView.onActionViewExpanded();
            mActionBarCustomView.addView(mSearchContainer);
        }
    }

    /** Must be called from {@link UIControllerBase#onActivityCreated()} */
    public void onActivityCreated() {
        refresh();
    }

    /** Must be called from {@link UIControllerBase#onActivityDestroy()} */
    public void onActivityDestroy() {
        if (mAccountDropdown.isShowing()) {
            mAccountDropdown.dismiss();
        }
    }

    /** Must be called from {@link UIControllerBase#onSaveInstanceState} */
    public void onSaveInstanceState(Bundle outState) {
        mDelayedOperations.removeCallbacks(); // Remove all pending operations
        outState.putInt(BUNDLE_KEY_MODE, mSearchMode);
    }

    /** Must be called from {@link UIControllerBase#onRestoreInstanceState} */
    public void onRestoreInstanceState(Bundle savedState) {
        int mode = savedState.getInt(BUNDLE_KEY_MODE);
        if (mode == MODE_SEARCH) {
            // No need to re-set the initial query, as the View tree restoration does that
            enterSearchMode(null);
        }
    }

    /**
     * @return true if the search box is shown.
     */
    public boolean isInSearchMode() {
        return mSearchMode == MODE_SEARCH;
    }

    /**
     * @return Whether or not the search bar should be shown. This is a function of whether or not a
     *     search is active, and if the current layout supports it.
     */
    private boolean shouldShowSearchBar() {
        return isInSearchMode() && (mTitleMode != Callback.TITLE_MODE_MESSAGE_SUBJECT);
    }

    /**
     * Show the search box.
     *
     * @param initialQueryTerm if non-empty, set to the search box.
     */
    public void enterSearchMode(String initialQueryTerm) {
        initSearchViews();
        if (isInSearchMode()) {
            return;
        }
        if (!TextUtils.isEmpty(initialQueryTerm)) {
            mSearchView.setQuery(initialQueryTerm, false);
        } else {
            mSearchView.setQuery("", false);
        }
        mSearchView.setQueryHint(mCallback.getSearchHint());

        mSearchMode = MODE_SEARCH;

        // Focus on the search input box and throw up the IME if specified.
        // TODO: HACK. this is a workaround IME not popping up.
        mSearchView.setIconified(false);

        refresh();
        mCallback.onSearchStarted();
    }

    public void exitSearchMode() {
        if (!isInSearchMode()) {
            return;
        }
        mSearchMode = MODE_NORMAL;

        refresh();
        mCallback.onSearchExit();
    }

    /**
     * Performs the back action.
     *
     * @param isSystemBackKey true if the system back key was pressed.
     * false if it's caused by the "home" icon click on the action bar.
     */
    public boolean onBackPressed(boolean isSystemBackKey) {
        if (shouldShowSearchBar()) {
            exitSearchMode();
            return true;
        }
        return false;
    }

    /** Refreshes the action bar display. */
    public void refresh() {
        // The actual work is in refreshInernal(), but we don't call it directly here, because:
        // 1. refresh() is called very often.
        // 2. to avoid nested fragment transaction.
        //    refresh is often called during a fragment transaction, but updateTitle() may call
        //    a callback which would initiate another fragment transaction.
        mDelayedOperations.removeCallbacks(mRefreshRunnable);
        mDelayedOperations.post(mRefreshRunnable);
    }

    private final Runnable mRefreshRunnable = new Runnable() {
        @Override public void run() {
            refreshInernal();
        }
    };
    private void refreshInernal() {
        final boolean showUp = isInSearchMode() || mCallback.shouldShowUp();
        mActionBar.setDisplayOptions(showUp
                ? ActionBar.DISPLAY_HOME_AS_UP : 0, ActionBar.DISPLAY_HOME_AS_UP);

        final long accountId = mCallback.getUIAccountId();
        final long mailboxId = mCallback.getMailboxId();
        if ((mLastAccountIdForDirtyCheck != accountId)
                || (mLastMailboxIdForDirtyCheck != mailboxId)) {
            mLastAccountIdForDirtyCheck = accountId;
            mLastMailboxIdForDirtyCheck = mailboxId;

            if (accountId != Account.NO_ACCOUNT) {
                loadAccountMailboxInfo(accountId, mailboxId);
            }
        }

        updateTitle();
    }

    /**
     * Load account/mailbox info, and account/recent mailbox list.
     */
    private void loadAccountMailboxInfo(final long accountId, final long mailboxId) {
        mLoaderManager.restartLoader(LOADER_ID_ACCOUNT_LIST, null,
                new LoaderCallbacks<Cursor>() {
            @Override
            public Loader<Cursor> onCreateLoader(int id, Bundle args) {
                return AccountSelectorAdapter.createLoader(mContext, accountId, mailboxId);
            }

            @Override
            public void onLoadFinished(Loader<Cursor> loader, Cursor data) {
                mCursor = (AccountSelectorAdapter.CursorWithExtras) data;
                updateTitle();
            }

            @Override
            public void onLoaderReset(Loader<Cursor> loader) {
                mCursor = null;
                updateTitle();
            }
        });
    }

    /**
     * Update the "title" part.
     */
    private void updateTitle() {
        mAccountsSelectorAdapter.swapCursor(mCursor);

        enterCustomActionBarMode();
        if (mCursor == null) {
            // Initial load not finished.
            mActionBarCustomView.setVisibility(View.GONE);
            return;
        }
        mActionBarCustomView.setVisibility(View.VISIBLE);

        if (mCursor.getAccountCount() == 0) {
            mCallback.onNoAccountsFound();
            return;
        }

        if ((mCursor.getAccountId() != Account.NO_ACCOUNT) && !mCursor.accountExists()) {
            // Account specified, but does not exist.
            if (isInSearchMode()) {
                exitSearchMode();
            }

            // Switch to the default account.
            mCallback.onAccountSelected(Account.getDefaultAccountId(mContext));
            return;
        }

        mTitleMode = mCallback.getTitleMode();

        if (shouldShowSearchBar()) {
            initSearchViews();
            // In search mode, the search box is a replacement of the account spinner, so ignore
            // the work needed to update that. It will get updated when it goes visible again.
            mAccountSpinnerContainer.setVisibility(View.GONE);
            mSearchContainer.setVisibility(View.VISIBLE);
            return;
        }

        // Account spinner visible.
        mAccountSpinnerContainer.setVisibility(View.VISIBLE);
        UiUtilities.setVisibilitySafe(mSearchContainer, View.GONE);

        if (mTitleMode == Callback.TITLE_MODE_MESSAGE_SUBJECT) {
            // Use two line title action bar mode
            enterMultiLineTitleActionBarMode();
            String subject = mCallback.getMessageSubject();
            if (subject == null) {
                subject = "";
            }
            final SpannableString title = new SpannableString(subject);
            final SpannableStringBuilder builder = new SpannableStringBuilder();
            title.setSpan(new TextAppearanceSpan(mContext, R.style.subject_action_bar_title_text),
                    0, subject.length(), 0);
            builder.append(title);
            mActionBar.setTitle(builder);
            mActionBar.setSubtitle(null);
        } else if (mTitleMode == Callback.TITLE_MODE_ACCOUNT_WITH_ALL_FOLDERS_LABEL) {
            enterSingleLineTitleActionBarMode();
            mActionBar.setTitle(mAllFoldersLabel);
            mActionBar.setSubtitle(mCursor.getAccountDisplayName());
        } else {
            // Get mailbox name
            final String mailboxName;
            if (mTitleMode == Callback.TITLE_MODE_ACCOUNT_WITH_MAILBOX) {
                mailboxName = mCursor.getMailboxDisplayName();
            } else {
                mailboxName = null;
            }

            // Note - setSingleLine is needed as well as setMaxLines since they set different
            // flags on the view.
            mAccountSpinnerLine1View.setSingleLine();
            mAccountSpinnerLine1View.setMaxLines(1);
            if (TextUtils.isEmpty(mailboxName)) {
                mAccountSpinnerLine1View.setText(mCursor.getAccountDisplayName());

                // Change the visibility of line 2, so line 1 will be vertically-centered.
                mAccountSpinnerLine2View.setVisibility(View.GONE);
            } else {
                mAccountSpinnerLine1View.setText(mailboxName);
                mAccountSpinnerLine2View.setVisibility(View.VISIBLE);
                mAccountSpinnerLine2View.setText(mCursor.getAccountDisplayName());
            }

            mAccountSpinnerCountView.setVisibility(View.VISIBLE);
            mAccountSpinnerCountView.setText(UiUtilities.getMessageCountForUi(
                    mContext, mCursor.getMailboxMessageCount(), true));
        }

        boolean spinnerEnabled =
            ((mTitleMode & TITLE_MODE_SPINNER_ENABLED) != 0) && mCursor.shouldEnableSpinner();

        setSpinnerEnabled(spinnerEnabled);
    }

    private void enterCustomActionBarMode() {
        mActionBar.setDisplayOptions(CUSTOM_ACTION_BAR_OPTIONS, ACTION_BAR_MASK);
    }

    private void enterMultiLineTitleActionBarMode() {
        mActionBar.setDisplayOptions(ActionBar.DISPLAY_SHOW_HOME | ActionBar.DISPLAY_SHOW_TITLE
                | DISPLAY_TITLE_MULTIPLE_LINES, ACTION_BAR_MASK);
    }

    private void enterSingleLineTitleActionBarMode() {
        mActionBar.setDisplayOptions(ActionBar.DISPLAY_SHOW_HOME | ActionBar.DISPLAY_SHOW_TITLE,
                ACTION_BAR_MASK);
    }

    private void setSpinnerEnabled(boolean enabled) {
        if (enabled == mAccountSpinner.isEnabled()) {
            return;
        }

        mAccountSpinner.setEnabled(enabled);
        mAccountSpinner.setClickable(enabled);
        mActionBarCustomView.setClickable(!enabled);
        if (enabled) {
            mAccountSpinner.setBackgroundDrawable(mAccountSpinnerDefaultBackground);
        } else {
            mAccountSpinner.setBackgroundDrawable(null);
        }

        // For some reason, changing the background mucks with the padding so we have to manually
        // reset vertical padding here (also specified in XML, but it seems to be ignored for
        // some reason.
        mAccountSpinner.setPadding(
                mAccountSpinner.getPaddingLeft(),
                0,
                mAccountSpinner.getPaddingRight(),
                0);
    }

    private final SearchView.OnQueryTextListener mOnQueryText
            = new SearchView.OnQueryTextListener() {
        @Override
        public boolean onQueryTextChange(String newText) {
            // Event not handled.  Let the search do the default action.
            return false;
        }

        @Override
        public boolean onQueryTextSubmit(String query) {
            mCallback.onSearchSubmit(mSearchView.getQuery().toString());
            return true; // Event handled.
        }
    };

    private void onAccountSpinnerItemClicked(int position) {
        if (mAccountsSelectorAdapter == null) { // just in case...
            return;
        }
        final long accountId = mAccountsSelectorAdapter.getAccountId(position);

        if (mAccountsSelectorAdapter.isAccountItem(position)) {
            mCallback.onAccountSelected(accountId);
        } else if (mAccountsSelectorAdapter.isMailboxItem(position)) {
            mCallback.onMailboxSelected(accountId,
                    mAccountsSelectorAdapter.getId(position));
        }
    }

    // Based on Spinner.DropdownPopup
    private class AccountDropdownPopup extends ListPopupWindow {
        public AccountDropdownPopup(Context context) {
            super(context);
            setAnchorView(mAccountSpinner);
            setModal(true);
            setPromptPosition(POSITION_PROMPT_ABOVE);
            setOnItemClickListener(new OnItemClickListener() {
                public void onItemClick(AdapterView<?> parent, View v, int position, long id) {
                    onAccountSpinnerItemClicked(position);
                    dismiss();
                }
            });
        }

        @Override
        public void show() {
            setWidth(mContext.getResources().getDimensionPixelSize(
                    R.dimen.account_dropdown_dropdownwidth));
            setInputMethodMode(ListPopupWindow.INPUT_METHOD_NOT_NEEDED);
            super.show();
            // List view is instantiated in super.show(), so we need to do this after...
            getListView().setChoiceMode(ListView.CHOICE_MODE_SINGLE);
        }
    }
}


text:
default_target: all

.PHONY : default_target

# Allow only one "make -f Makefile2" at a time, but pass parallelism.
.NOTPARALLEL:

#=============================================================================
# Special targets provided by cmake.

# Disable implicit rules so canonical targets will work.
.SUFFIXES:

# Remove some rules from gmake that .SUFFIXES does not remove.
SUFFIXES =

.SUFFIXES: .hpux_make_needs_suffix_list

# Suppress display of executed commands.
$(VERBOSE).SILENT:

# A target that is always out of date.
cmake_force:

.PHONY : cmake_force

#=============================================================================
# Set environment variables for the build.

# The shell in which to execute make rules.
SHELL = /bin/sh

# The CMake executable.
CMAKE_COMMAND = /cygdrive/c/Users/Owner/.CLion2017.2/system/cygwin_cmake/bin/cmake.exe

# The command to remove a file.
RM = /cygdrive/c/Users/Owner/.CLion2017.2/system/cygwin_cmake/bin/cmake.exe -E remove -f

# Escaping for special characters.
EQUALS = =

# The top-level source directory on which CMake was run.
CMAKE_SOURCE_DIR = /cygdrive/c/Users/Owner/Desktop/Github-Code/CppLibraries/Date

# The top-level build directory on which CMake was run.
CMAKE_BINARY_DIR = /cygdrive/c/Users/Owner/Desktop/Github-Code/CppLibraries/Date/cmake-build-debug

#=============================================================================
# Targets provided globally by CMake.

# Special rule for the target rebuild_cache
rebuild_cache:
	@$(CMAKE_COMMAND) -E cmake_echo_color --switch=$(COLOR) --cyan "Running CMake to regenerate build system..."
	/cygdrive/c/Users/Owner/.CLion2017.2/system/cygwin_cmake/bin/cmake.exe -H$(CMAKE_SOURCE_DIR) -B$(CMAKE_BINARY_DIR)
.PHONY : rebuild_cache

# Special rule for the target rebuild_cache
rebuild_cache/fast: rebuild_cache

.PHONY : rebuild_cache/fast

# Special rule for the target edit_cache
edit_cache:
	@$(CMAKE_COMMAND) -E cmake_echo_color --switch=$(COLOR) --cyan "No interactive CMake dialog available..."
	/cygdrive/c/Users/Owner/.CLion2017.2/system/cygwin_cmake/bin/cmake.exe -E echo No\ interactive\ CMake\ dialog\ available.
.PHONY : edit_cache

# Special rule for the target edit_cache
edit_cache/fast: edit_cache

.PHONY : edit_cache/fast

# The main all target
all: cmake_check_build_system
	$(CMAKE_COMMAND) -E cmake_progress_start /cygdrive/c/Users/Owner/Desktop/Github-Code/CppLibraries/Date/cmake-build-debug/CMakeFiles /cygdrive/c/Users/Owner/Desktop/Github-Code/CppLibraries/Date/cmake-build-debug/CMakeFiles/progress.marks
	$(MAKE) -f CMakeFiles/Makefile2 all
	$(CMAKE_COMMAND) -E cmake_progress_start /cygdrive/c/Users/Owner/Desktop/Github-Code/CppLibraries/Date/cmake-build-debug/CMakeFiles 0
.PHONY : all

# The main clean target
clean:
	$(MAKE) -f CMakeFiles/Makefile2 clean
.PHONY : clean

# The main clean target
clean/fast: clean

.PHONY : clean/fast

# Prepare targets for installation.
preinstall: all
	$(MAKE) -f CMakeFiles/Makefile2 preinstall
.PHONY : preinstall

# Prepare targets for installation.
preinstall/fast:
	$(MAKE) -f CMakeFiles/Makefile2 preinstall
.PHONY : preinstall/fast

# clear depends
depend:
	$(CMAKE_COMMAND) -H$(CMAKE_SOURCE_DIR) -B$(CMAKE_BINARY_DIR) --check-build-system CMakeFiles/Makefile.cmake 1
.PHONY : depend

#=============================================================================
# Target rules for targets named Date

# Build rule for target.
Date: cmake_check_build_system
	$(MAKE) -f CMakeFiles/Makefile2 Date
.PHONY : Date

# fast build rule for target.
Date/fast:
	$(MAKE) -f CMakeFiles/Date.dir/build.make CMakeFiles/Date.dir/build
.PHONY : Date/fast

main.o: main.cpp.o

.PHONY : main.o

# target to build an object file
main.cpp.o:
	$(MAKE) -f CMakeFiles/Date.dir/build.make CMakeFiles/Date.dir/main.cpp.o
.PHONY : main.cpp.o

main.i: main.cpp.i

.PHONY : main.i

# target to preprocess a source file
main.cpp.i:
	$(MAKE) -f CMakeFiles/Date.dir/build.make CMakeFiles/Date.dir/main.cpp.i
.PHONY : main.cpp.i

main.s: main.cpp.s

.PHONY : main.s

# target to generate assembly for a file
main.cpp.s:
	$(MAKE) -f CMakeFiles/Date.dir/build.make CMakeFiles/Date.dir/main.cpp.s
.PHONY : main.cpp.s

sources/date.o: sources/date.cpp.o

.PHONY : sources/date.o

# target to build an object file
sources/date.cpp.o:
	$(MAKE) -f CMakeFiles/Date.dir/build.make CMakeFiles/Date.dir/sources/date.cpp.o
.PHONY : sources/date.cpp.o

sources/date.i: sources/date.cpp.i

.PHONY : sources/date.i

# target to preprocess a source file
sources/date.cpp.i:
	$(MAKE) -f CMakeFiles/Date.dir/build.make CMakeFiles/Date.dir/sources/date.cpp.i
.PHONY : sources/date.cpp.i

sources/date.s: sources/date.cpp.s

.PHONY : sources/date.s

# target to generate assembly for a file
sources/date.cpp.s:
	$(MAKE) -f CMakeFiles/Date.dir/build.make CMakeFiles/Date.dir/sources/date.cpp.s
.PHONY : sources/date.cpp.s

sources/date_operators.o: sources/date_operators.cpp.o

.PHONY : sources/date_operators.o

# target to build an object file
sources/date_operators.cpp.o:
	$(MAKE) -f CMakeFiles/Date.dir/build.make CMakeFiles/Date.dir/sources/date_operators.cpp.o
.PHONY : sources/date_operators.cpp.o

sources/date_operators.i: sources/date_operators.cpp.i

.PHONY : sources/date_operators.i

# target to preprocess a source file
sources/date_operators.cpp.i:
	$(MAKE) -f CMakeFiles/Date.dir/build.make CMakeFiles/Date.dir/sources/date_operators.cpp.i
.PHONY : sources/date_operators.cpp.i

sources/date_operators.s: sources/date_operators.cpp.s

.PHONY : sources/date_operators.s

# target to generate assembly for a file
sources/date_operators.cpp.s:
	$(MAKE) -f CMakeFiles/Date.dir/build.make CMakeFiles/Date.dir/sources/date_operators.cpp.s
.PHONY : sources/date_operators.cpp.s

# Help Target
help:
	@echo "The following are some of the valid targets for this Makefile:"
	@echo "... all (the default if no target is provided)"
	@echo "... clean"
	@echo "... depend"
	@echo "... rebuild_cache"
	@echo "... edit_cache"
	@echo "... Date"
	@echo "... main.o"
	@echo "... main.i"
	@echo "... main.s"
	@echo "... sources/date.o"
	@echo "... sources/date.i"
	@echo "... sources/date.s"
	@echo "... sources/date_operators.o"
	@echo "... sources/date_operators.i"
	@echo "... sources/date_operators.s"
.PHONY : help

#=============================================================================
# Special targets to cleanup operation of make.

# Special rule to run CMake to check the build system integrity.
# No rule that depends on this can have commands that come from listfiles
# because they might be regenerated.
cmake_check_build_system:
	$(CMAKE_COMMAND) -H$(CMAKE_SOURCE_DIR) -B$(CMAKE_BINARY_DIR) --check-build-system CMakeFiles/Makefile.cmake 0
.PHONY : cmake_check_build_system

redpajama_set_name: RedPajamaGithub


text:
ACCEPTED

#### According to
The Catalogue of Life, 3rd January 2011

#### Published in
Sydowia 4: 345 (1950)

#### Original name
Allonectella rubescens Petr., 1950

### Remarks
null


text:
namespace EasyNetQ.Migrations {
    using System;
    using System.Collections.Generic;
    using EasyNetQ.Migrations.Actions;
    using EasyNetQ.Management.Client;

    public abstract class Migration : IDeclare, IDelete, IPurge, IMove {
        readonly List<MigrationAction> _actions = new List<MigrationAction>();

        public IDeclare Declare => this;
        public IDelete Delete => this;
        public IPurge Purge => this;
        public IMove Move => this;

        IBindingDeclare IDeclare.Binding() {
            var bindingDeclare = new BindingDeclareAction();
            _actions.Add(bindingDeclare);
            return bindingDeclare;
        }

        IExchangeDeclare IDeclare.Exchange(Type messageType) {
            var exchangeDeclare = new ExchangeDeclareAction(messageType);
            _actions.Add(exchangeDeclare);
            return exchangeDeclare;
        }

        IExchangeDeclare IDeclare.Exchange(String name) {
            var exchangeDeclare = new ExchangeDeclareAction(name);
            _actions.Add(exchangeDeclare);
            return exchangeDeclare;
        }

        IPermissionDeclare IDeclare.Permission() {
            var permissionDeclare = new PermissionDeclareAction();
            _actions.Add(permissionDeclare);
            return permissionDeclare;
        }

        IQueueDeclare IDeclare.Queue(String name) {
            var queueDeclare = new QueueDeclareAction(name);
            _actions.Add(queueDeclare);
            return queueDeclare;
        }

        IQueueDeclare IDeclare.Queue(Type messageType, String subscriptionId) {
            var queueDeclare = new QueueDeclareAction(messageType, subscriptionId);
            _actions.Add(queueDeclare);
            return queueDeclare;
        }

        void IDeclare.VirtualHost(string name) {
            var virtualHostDeclare = new VirtualHostDeclareAction(name);
            _actions.Add(virtualHostDeclare);
        }

        IExchangeDelete IDelete.Exchange(String exchange) {
            var exchangeDelete = new ExchangeDeleteAction(exchange);
            _actions.Add(exchangeDelete);
            return exchangeDelete;
        }

        IExchangeDelete IDelete.Exchange(Type messageType) {
            var exchangeDelete = new ExchangeDeleteAction(messageType);
            _actions.Add(exchangeDelete);
            return exchangeDelete;
        }

        IQueueDelete IDelete.Queue(String queue) {
            var queueDelete = new QueueDeleteAction(queue);
            _actions.Add(queueDelete);
            return queueDelete;
        }

        IQueueDelete IDelete.Queue(Type messageType, String subscriptionId) {
            var queueDelete = new QueueDeleteAction(messageType, subscriptionId);
            _actions.Add(queueDelete);
            return queueDelete;
        }

        void IDelete.VirtualHost(string name) {
            var virtualHostDelete = new VirtualHostDeleteAction(name);
            _actions.Add(virtualHostDelete);
        }

        IQueuePurge IPurge.Queue(String queue) {
            var queuePurge = new QueuePurgeAction(queue);
            _actions.Add(queuePurge);
            return queuePurge;
        }

        IQueuePurge IPurge.Queue(Type messageType, String subscriptionId) {
            var queuePurge = new QueuePurgeAction(messageType, subscriptionId);
            _actions.Add(queuePurge);
            return queuePurge;
        }

        IMessagesMove IMove.Messages() {
            var messagesMove = new MessagesMoveAction();
            _actions.Add(messagesMove);
            return messagesMove;
        }

        public abstract void Apply();

        public void Run(IManagementClient managementClient) {
            Apply();

            _actions.ForEach(action => action.VerifyState());
            _actions.ForEach(action => action.Apply(managementClient));
        }

        public void DryRun() {
            Apply();

            _actions.ForEach(action => action.VerifyState());
            _actions.ForEach(action => action.DryRun());
        }
    }
}


text:
fn main() {
    extern crate syntex;
    extern crate diesel_codegen_syntex as diesel_codegen;

    use std::env;
    use std::path::Path;

    let out_dir = env::var_os("OUT_DIR").unwrap();
    let mut registry = syntex::Registry::new();
    diesel_codegen::register(&mut registry);

    let src = Path::new("src/lib.in.rs");
    let dst = Path::new(&out_dir).join("lib.rs");

    registry.expand("", &src, &dst).unwrap();
}


text:
IFML Editor
===========

The open source Eclipse editor for [IFML](http://www.ifml.org/) (Interaction Flow Modeling Language).

The editor is based on [Sirius](http://www.eclipse.org/sirius/) an Eclipse project to facilitate the creation of modeling editors.

Using the tool
==============

Instructions on how to install and get started with the tool are available in the [tool web page](http://ifml.github.io)

Projects
=========
- IFMLEditor: project with model and model sources.
  * Folder "Model": contains the .ecore and the .genmodel.
- IFMLEditor.edit : project with the generated edit code.
- IFMLEditor.editor: project with the generated editor code.
- IFMLEditorDesign: project with the editor design
  * Folder "description": IFML.odesign file which specifies the editor
  * Source Folder "templates" inside the src folder: helper.mtl file, which specifies some queries, used by the IFML.odesign.

Remarks
=========

- In order to avoid problems due to the existence of elements with the same name in other metamodels the following elements were renamed only for the Editor:
```
        - Action --> IFML Action
        - Menu --> IFMLMenu
        - Slot --> IFMLSlot
        - Parameter --> IFMLParameter
        - Window --> IFMLWindow
        - Port --> IFMLPort
        - Module --> IFMLModule
```
- In order to generate a unique identifier for each element the ElementImpl.java class in the package IFML.Core.impl in the Model Project was modified:
```
        - inserting the following line in the ElementImpl Constructor
          id=EcoreUtil.generateUUID();
        - marking the constructor @generated NOT
        - changing the variable ID_EDEFAULT value from null to "":
          protected static final String ID_DEFAULT = ""
```

Authors
=======

IFML Editor is the result of a collaboration between [WebRatio](http://www.webratio.com/), [Politecnico di Milano](http://www.polimi.it/en/) and the INRIA research team [AtlanMod](http://www.emn.fr/z-info/atlanmod/index.php/Main_Page).


text:
cask 'coqide' do
  version '8.11.0'
  sha256 '6cce1ec6502a3086d7e02c59a6903fad082e81a3f8a8ee03be21179ab25a08cf'

  # github.com/coq/coq was verified as official when first introduced to the cask
  url "https://github.com/coq/coq/releases/download/V#{version.major_minor_patch}/coq-#{version}-installer-macos.dmg"
  appcast 'https://github.com/coq/coq/releases.atom'
  name 'Coq'
  homepage 'https://coq.inria.fr/'

  depends_on macos: '>= :sierra'

  app "CoqIDE_#{version.major_minor_patch}.app"
end


text:
package com.martinodutto.services;

import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import org.jetbrains.annotations.PropertyKey;

import java.text.MessageFormat;
import java.util.Locale;
import java.util.ResourceBundle;

/**
 * Contains static methods useful to translate the externalized strings.
 */
public class I18nSupport {

    private static final ResourceBundle bundle = ResourceBundle.getBundle("Language", Locale.US);

    /**
     * Gets a translation for the passed externalized string.
     *
     * @param key Key of the externalized string.
     * @return Translation for the string.
     */
    public static String i18nize(@NotNull @PropertyKey(resourceBundle = "Language") String key) {
        return bundle.getString(key);
    }

    /**
     * Gets a translation for the passed externalized string and the given parameters.
     *
     * @param key    Key of the externalized string.
     * @param params Parameters to be substituted into the resulting string.
     * @return Translation for the string, with the given parameters.
     */
    @NotNull
    public static String i18nize(@NotNull @PropertyKey(resourceBundle = "Language") String key, @Nullable Object... params) {
        String value = bundle.getString(key);

        if (params != null && params.length > 0) return MessageFormat.format(value, params);

        return value;
    }
}


text:
from ansible.utils import template
import ansible.utils as utils

class LookupModule(object):

    def __init__(self, basedir=None, **kwargs):
        self.basedir = basedir

    def run(self, terms, inject=None, **kwargs):

        terms = utils.listify_lookup_plugin_terms(terms, self.basedir, inject)

        ret = []
        for term in terms:
            ret.append(template.template_from_file(self.basedir, term, inject))
        return ret


text:
#include <winsock2.h>
#include <ws2tcpip.h>
#include "api/replay/stringise.h"
#include "common/common.h"
#include "common/formatting.h"
#include "os/os_specific.h"

#ifndef WSA_FLAG_NO_HANDLE_INHERIT
#define WSA_FLAG_NO_HANDLE_INHERIT 0x80
#endif

#ifndef WSA_FLAG_OVERLAPPED
#define WSA_FLAG_OVERLAPPED 0x01
#endif

static rdcstr wsaerr_string(int err)
{
  switch(err)
  {
    case WSAENOTSOCK:
      return "WSAENOTSOCK: An operation was attempted on something that is not a socket";
    case WSAEWOULDBLOCK:
      return "WSAEWOULDBLOCK: A non-blocking socket operation could not be completed immediately";
    case WSAEADDRINUSE:
      return "WSAEADDRINUSE: Only one usage of each socket address (protocol/network address/port) "
             "is normally permitted.";
    case WSAENETDOWN: return "WSAENETDOWN: A socket operation encountered a dead network.";
    case WSAENETUNREACH:
      return "WSAENETUNREACH: A socket operation was attempted to an unreachable network.";
    case WSAENETRESET:
      return "WSAENETRESET: The connection has been broken due to keep-alive activity detecting a "
             "failure while the operation was in progress.";
    case WSAECONNABORTED:
      return "WSAECONNABORTED: An established connection was aborted by the software in your host "
             "machine.";
    case WSAECONNRESET:
      return "WSAECONNRESET: An existing connection was forcibly closed by the remote host.";
    case WSAETIMEDOUT: return "WSAETIMEDOUT: A socket operation timed out.";
    case WSAECONNREFUSED:
      return "WSAECONNREFUSED: No connection could be made because the target machine actively "
             "refused "
             "it.";
    case WSAEHOSTDOWN:
      return "WSAEHOSTDOWN: A socket operation failed because the destination host was down.";
    case WSAEHOSTUNREACH:
      return "WSAETIMEDOUT: A socket operation was attempted to an unreachable host.";
    case WSATRY_AGAIN: return "WSATRY_AGAIN: A temporary failure in name resolution occurred.";
    case WSAEINVAL:
      return "WSAEINVAL: An invalid value was provided for the ai_flags member of the pHints "
             "parameter.";
    case WSANO_RECOVERY:
      return "WSANO_RECOVERY: A nonrecoverable failure in name resolution occurred.";
    case WSAEAFNOSUPPORT:
      return "WSAEAFNOSUPPORT: The ai_family member of the pHints parameter is not supported.";
    case WSA_NOT_ENOUGH_MEMORY:
      return "WSA_NOT_ENOUGH_MEMORY: A memory allocation failure occurred.";
    case WSAHOST_NOT_FOUND:
      return "WSAHOST_NOT_FOUND: The name does not resolve for the supplied parameters or the "
             "pNodeName and pServiceName parameters were not provided.";
    case WSATYPE_NOT_FOUND:
      return "WSATYPE_NOT_FOUND: The pServiceName parameter is not supported for the specified "
             "ai_socktype member of the pHints parameter.";
    case WSAESOCKTNOSUPPORT:
      return "WSAESOCKTNOSUPPORT: The ai_socktype member of the pHints parameter is not supported.";
    case WSANO_DATA:
      return "WSANO_DATA: The requested name is valid, but no data of the requested type was "
             "found.";
    case WSANOTINITIALISED:
      return "WSANOTINITIALISED: A successful WSAStartup call must occur before using this "
             "function.";
    default: break;
  }

  return StringFormat::Fmt("Unknown error %d", err);
}

namespace Network
{
void Init()
{
  WSAData wsaData = {0};
  WSAStartup(MAKEWORD(2, 2), &wsaData);
}

void Shutdown()
{
  // we'd normally call WSACleanup() here but we can't - like many functions we call anyway it's not
  // safe to call in DllMain when shutting down. Unlike other functions, it has minimal impact to
  // just skip the call and 'leak' winsock since we're shutting down the process anyway.
  // WSACleanup();
}

Socket::~Socket()
{
  Shutdown();
}

void Socket::Shutdown()
{
  if(Connected())
  {
    shutdown((SOCKET)socket, SD_BOTH);
    closesocket((SOCKET)socket);
    socket = -1;
  }
}

bool Socket::Connected() const
{
  return (SOCKET)socket != INVALID_SOCKET;
}

uint32_t Socket::GetRemoteIP() const
{
  sockaddr_in addr = {};
  socklen_t len = sizeof(addr);

  getpeername((SOCKET)socket, (sockaddr *)&addr, &len);

  return ntohl(addr.sin_addr.s_addr);
}

Socket *Socket::AcceptClient(uint32_t timeoutMilliseconds)
{
  do
  {
    SOCKET s = accept(socket, NULL, NULL);

    if(s != INVALID_SOCKET)
    {
      u_long enable = 1;
      ioctlsocket(s, FIONBIO, &enable);

      BOOL nodelay = TRUE;
      setsockopt(s, IPPROTO_TCP, TCP_NODELAY, (const char *)&nodelay, sizeof(nodelay));

      return new Socket((ptrdiff_t)s);
    }

    int err = WSAGetLastError();

    if(err != WSAEWOULDBLOCK)
    {
      SET_WARNING_RESULT(m_Error, ResultCode::NetworkIOFailed, "accept failed: %s",
                         wsaerr_string(err).c_str());
      Shutdown();
    }

    const uint32_t sleeptime = 4;

    Threading::Sleep(sleeptime);

    if(sleeptime < timeoutMilliseconds)
      timeoutMilliseconds -= sleeptime;
    else
      timeoutMilliseconds = 0U;
  } while(timeoutMilliseconds);

  return NULL;
}

bool Socket::SendDataBlocking(const void *buf, uint32_t length)
{
  if(length == 0)
    return true;

  uint32_t sent = 0;

  char *src = (char *)buf;

  u_long enable = 0;
  ioctlsocket(socket, FIONBIO, &enable);

  DWORD oldtimeout = 0;
  int len = sizeof(oldtimeout);
  getsockopt(socket, SOL_SOCKET, SO_SNDTIMEO, (char *)&oldtimeout, &len);

  DWORD timeout = timeoutMS;
  setsockopt(socket, SOL_SOCKET, SO_SNDTIMEO, (const char *)&timeout, sizeof(timeout));

  while(sent < length)
  {
    int ret = send(socket, src, length - sent, 0);

    if(ret <= 0)
    {
      int err = WSAGetLastError();

      if(err == WSAEWOULDBLOCK || err == WSAETIMEDOUT)
      {
        SET_WARNING_RESULT(m_Error, ResultCode::NetworkIOFailed, "Timeout in send");
        Shutdown();
        return false;
      }
      else
      {
        SET_WARNING_RESULT(m_Error, ResultCode::NetworkIOFailed, "send failed: %s",
                           wsaerr_string(err).c_str());
        Shutdown();
        return false;
      }
    }

    sent += ret;
    src += ret;
  }

  enable = 1;
  ioctlsocket(socket, FIONBIO, &enable);

  setsockopt(socket, SOL_SOCKET, SO_SNDTIMEO, (const char *)&oldtimeout, sizeof(oldtimeout));

  RDCASSERT(sent == length);

  return true;
}

bool Socket::IsRecvDataWaiting()
{
  char dummy;
  int ret = recv(socket, &dummy, 1, MSG_PEEK);

  if(ret == 0)
  {
    Shutdown();
    return false;
  }
  else if(ret <= 0)
  {
    int err = WSAGetLastError();

    if(err == WSAEWOULDBLOCK)
    {
      ret = 0;
    }
    else
    {
      SET_WARNING_RESULT(m_Error, ResultCode::NetworkIOFailed, "recv peek failed: %s",
                         wsaerr_string(err).c_str());
      Shutdown();
      return false;
    }
  }

  return ret > 0;
}

bool Socket::RecvDataNonBlocking(void *buf, uint32_t &length)
{
  if(length == 0)
    return true;

  // socket is already blocking, don't have to change anything
  int ret = recv(socket, (char *)buf, length, 0);

  if(ret > 0)
  {
    length = (uint32_t)ret;
  }
  else
  {
    length = 0;
    int err = WSAGetLastError();

    if(err == WSAEWOULDBLOCK)
    {
      return true;
    }
    else
    {
      SET_WARNING_RESULT(m_Error, ResultCode::NetworkIOFailed, "recv non blocking failed: %s",
                         wsaerr_string(err).c_str());
      Shutdown();
      return false;
    }
  }

  return true;
}

bool Socket::RecvDataBlocking(void *buf, uint32_t length)
{
  if(length == 0)
    return true;

  uint32_t received = 0;

  char *dst = (char *)buf;

  u_long enable = 0;
  ioctlsocket(socket, FIONBIO, &enable);

  DWORD oldtimeout = 0;
  int len = sizeof(oldtimeout);
  getsockopt(socket, SOL_SOCKET, SO_RCVTIMEO, (char *)&oldtimeout, &len);

  DWORD timeout = timeoutMS;
  setsockopt(socket, SOL_SOCKET, SO_RCVTIMEO, (const char *)&timeout, sizeof(timeout));

  while(received < length)
  {
    int ret = recv(socket, dst, length - received, 0);

    if(ret == 0)
    {
      Shutdown();
      return false;
    }
    else if(ret <= 0)
    {
      int err = WSAGetLastError();

      if(err == WSAEWOULDBLOCK || err == WSAETIMEDOUT)
      {
        SET_WARNING_RESULT(m_Error, ResultCode::NetworkIOFailed, "Timeout in recv");
        Shutdown();
        return false;
      }
      else
      {
        SET_WARNING_RESULT(m_Error, ResultCode::NetworkIOFailed, "recv blocking failed: %s",
                           wsaerr_string(err).c_str());
        Shutdown();
        return false;
      }
    }

    received += ret;
    dst += ret;
  }

  enable = 1;
  ioctlsocket(socket, FIONBIO, &enable);

  setsockopt(socket, SOL_SOCKET, SO_RCVTIMEO, (const char *)&oldtimeout, sizeof(oldtimeout));

  RDCASSERT(received == length);

  return true;
}

Socket *CreateServerSocket(const rdcstr &bindaddr, uint16_t port, int queuesize)
{
  SOCKET s = WSASocket(AF_INET, SOCK_STREAM, IPPROTO_TCP, NULL, 0,
                       WSA_FLAG_NO_HANDLE_INHERIT | WSA_FLAG_OVERLAPPED);

  if(s == INVALID_SOCKET)
    return NULL;

  sockaddr_in addr;
  RDCEraseEl(addr);

  addr.sin_family = AF_INET;
  inet_pton(AF_INET, bindaddr.c_str(), &addr.sin_addr);
  addr.sin_port = htons(port);

  int result = bind(s, (SOCKADDR *)&addr, sizeof(addr));
  if(result == SOCKET_ERROR)
  {
    RDCWARN("Failed to bind to %s:%d - %d", bindaddr.c_str(), port, WSAGetLastError());
    closesocket(s);
    return NULL;
  }

  result = listen(s, queuesize);
  if(result == SOCKET_ERROR)
  {
    RDCWARN("Failed to listen on %s:%d - %d", bindaddr.c_str(), port, WSAGetLastError());
    closesocket(s);
    return NULL;
  }

  u_long nonblock = 1;
  ioctlsocket(s, FIONBIO, &nonblock);

  return new Socket((ptrdiff_t)s);
}

Socket *CreateClientSocket(const rdcstr &host, uint16_t port, int timeoutMS)
{
  wchar_t portwstr[7] = {0};

  {
    rdcstr buf = ToStr(port);
    for(size_t i = 0; i < buf.size(); i++)
      portwstr[i] = (wchar_t)buf[i];
  }

  addrinfoW hints;
  RDCEraseEl(hints);
  hints.ai_family = AF_INET;
  hints.ai_socktype = SOCK_STREAM;
  hints.ai_protocol = IPPROTO_TCP;

  rdcwstr whost = StringFormat::UTF82Wide(host);

  addrinfoW *addrResult = NULL;
  int res = GetAddrInfoW(whost.c_str(), portwstr, &hints, &addrResult);
  if(res != 0)
  {
    RDCDEBUG("%s", wsaerr_string(res).c_str());
    return NULL;
  }

  for(addrinfoW *ptr = addrResult; ptr != NULL; ptr = ptr->ai_next)
  {
    SOCKET s = WSASocket(AF_INET, SOCK_STREAM, IPPROTO_TCP, NULL, 0,
                         WSA_FLAG_NO_HANDLE_INHERIT | WSA_FLAG_OVERLAPPED);

    if(s == INVALID_SOCKET)
    {
      FreeAddrInfoW(addrResult);
      return NULL;
    }

    u_long enable = 1;
    ioctlsocket(s, FIONBIO, &enable);

    int result = connect(s, ptr->ai_addr, (int)ptr->ai_addrlen);
    if(result == SOCKET_ERROR)
    {
      fd_set setW = {}, setE = {};
      FD_ZERO(&setW);
      FD_ZERO(&setE);

// macro FD_SET contains the do { } while(0) idiom, which warns
#pragma warning(push)
#pragma warning(disable : 4127)    // conditional expression is constant
      FD_SET(s, &setW);
      FD_SET(s, &setE);
#pragma warning(pop)

      int err = WSAGetLastError();

      if(err == WSAEWOULDBLOCK)
      {
        timeval timeout;
        timeout.tv_sec = (timeoutMS / 1000);
        timeout.tv_usec = (timeoutMS % 1000) * 1000;
        result = select((int)s + 1, NULL, &setW, &setE, &timeout);

        socklen_t len = sizeof(err);
        getsockopt(s, SOL_SOCKET, SO_ERROR, (char *)&err, &len);

        // if select never returned, if the timeout is less than 1 second we treat it as a
        // connection refused. This is inaccurate but we don't want to have to wait a full second
        // for the connect to time out. On Winsock there seems to be a minimum of 1 second before
        // it will actually return connection refused.
        if(result <= 0 && timeoutMS <= 1000)
        {
          err = WSAECONNREFUSED;
        }
      }

      if(err != 0)
      {
        RDCDEBUG("%s", wsaerr_string(err).c_str());
        closesocket(s);
        continue;
      }
    }

    BOOL nodelay = TRUE;
    setsockopt(s, IPPROTO_TCP, TCP_NODELAY, (const char *)&nodelay, sizeof(nodelay));

    FreeAddrInfoW(addrResult);

    return new Socket((ptrdiff_t)s);
  }

  FreeAddrInfoW(addrResult);

  RDCDEBUG("Failed to connect to %s:%d", host.c_str(), port);
  return NULL;
}
};


text:
package action;

import java.util.ArrayList;

import forms.PaymentRecordForm;
import service.PaymentManager;

public class ShowPaymentAction extends BaseAction {

	private static final long serialVersionUID = 1L;
	private ArrayList<PaymentRecordForm> paymentRecordList = new ArrayList<>();
	private PaymentManager paymentManager;

	public ArrayList<PaymentRecordForm> getPaymentRecordList() {
		return paymentRecordList;
	}

	public void setPaymentRecordList(ArrayList<PaymentRecordForm> paymentRecordList) {
		this.paymentRecordList = paymentRecordList;
	}

	public void setPaymentManager(PaymentManager paymentManager) {
		this.paymentManager = paymentManager;
	}

	public String showPaymentRecordForUser() {
		try {
			System.out.println("Show Payment Action");
			int userId = (int) session().getAttribute("userid");
			paymentRecordList = paymentManager.showPaymentRecord(userId);
			return SUCCESS;
		} catch (Exception e) {
			e.printStackTrace();
			return ERROR;
		}
	}

	public String showPaymentRecordForWaiter() {
		try {
			System.out.println("Show Payment Action");
			paymentRecordList = paymentManager.showPaymentRecord();
			return SUCCESS;
		} catch (Exception e) {
			e.printStackTrace();
			return ERROR;
		}
	}

}


text:
package jp.codic.plugins.netbeans.client.impl;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import jp.codic.plugins.netbeans.client.Entry;
import jp.codic.plugins.netbeans.client.EntryTranslation;
import jp.codic.plugins.netbeans.client.Pronunciation;
import jp.codic.plugins.netbeans.client.utils.StringUtils;

public class EntryJSONImpl implements Entry {

    private long id;
    private String title;
    private String digest;
    private List<PronunciationJSONImpl> pronunciations;
    private List<EntryTranslationJSONImpl> translations;
    private String note;

    @Override
    public long getId() {
        return id;
    }

    @Override
    public String getTitle() {
        return StringUtils.toNonNull(title);
    }

    @Override
    public String getDigest() {
        return StringUtils.toNonNull(digest);
    }

    @Override
    public List<Pronunciation> getPronunciations() {
        return pronunciations == null ? Collections.<Pronunciation>emptyList() : new ArrayList<Pronunciation>(pronunciations);
    }

    @Override
    public List<EntryTranslation> getTranslations() {
        return translations == null ? Collections.<EntryTranslation>emptyList() : new ArrayList<EntryTranslation>(translations);
    }

    @Override
    public String getNote() {
        return StringUtils.toNonNull(note);
    }

}


text:
<?php

final class PhabricatorProjectListController
  extends PhabricatorProjectController {

  private $filter;

  public function willProcessRequest(array $data) {
    $this->filter = idx($data, 'filter');
  }

  public function processRequest() {
    $request = $this->getRequest();

    $nav = $this->buildSideNavView($this->filter);
    $this->filter = $nav->selectFilter($this->filter, 'active');

    $pager = new AphrontPagerView();
    $pager->setPageSize(250);
    $pager->setURI($request->getRequestURI(), 'page');
    $pager->setOffset($request->getInt('page'));

    $query = new PhabricatorProjectQuery();
    $query->setViewer($request->getUser());
    $query->needMembers(true);

    $view_phid = $request->getUser()->getPHID();

    switch ($this->filter) {
      case 'active':
        $table_header = pht('Your Projects');
        $query->withMemberPHIDs(array($view_phid));
        $query->withStatus(PhabricatorProjectQuery::STATUS_ACTIVE);
        break;
      case 'allactive':
        $table_header = pht('Active Projects');
        $query->withStatus(PhabricatorProjectQuery::STATUS_ACTIVE);
        break;
      case 'all':
        $table_header = pht('All Projects');
        $query->withStatus(PhabricatorProjectQuery::STATUS_ANY);
        break;
    }

    $projects = $query->executeWithOffsetPager($pager);

    $project_phids = mpull($projects, 'getPHID');

    $profiles = array();
    if ($projects) {
      $profiles = id(new PhabricatorProjectProfile())->loadAllWhere(
        'projectPHID in (%Ls)',
        $project_phids);
      $profiles = mpull($profiles, null, 'getProjectPHID');
    }

    $tasks = array();
    $groups = array();
    if ($project_phids) {
      $query = id(new ManiphestTaskQuery())
        ->withAnyProjects($project_phids)
        ->withStatus(ManiphestTaskQuery::STATUS_OPEN)
        ->setLimit(PHP_INT_MAX);

      $tasks = $query->execute();
      foreach ($tasks as $task) {
        foreach ($task->getProjectPHIDs() as $phid) {
          $groups[$phid][] = $task;
        }
      }
    }

    $rows = array();
    foreach ($projects as $project) {
      $phid = $project->getPHID();

      $profile = idx($profiles, $phid);
      $members = $project->getMemberPHIDs();

      $group = idx($groups, $phid, array());
      $task_count = count($group);
      $population = count($members);

      if ($profile) {
        $blurb = $profile->getBlurb();
        $blurb = phutil_utf8_shorten($blurb, 64);
      } else {
        $blurb = null;
      }

      $tasks_href = pht('%d Open Task(s)', $task_count);

      $rows[] = array(
        $project->getName(),
        '/project/view/'.$project->getID().'/',
        PhabricatorProjectStatus::getNameForStatus($project->getStatus()),
        PhabricatorProjectStatus::getIconForStatus($project->getStatus()),
        $blurb,
        pht('%d Member(s)', $population),
        phutil_tag(
          'a',
          array(
            'href' => '/maniphest/view/all/?projects='.$phid,
          ),
          $tasks_href),
        '/project/edit/'.$project->getID().'/',
      );
    }

    $list = new PhabricatorObjectItemListView();
    $list->setStackable(true);
    foreach ($rows as $row) {
      $item = id(new PhabricatorObjectItemView())
        ->setHeader($row[0])
        ->setHref($row[1])
        ->addIcon($row[3], $row[2])
        ->addIcon('edit', pht('Edit Project'), array('href' => $row[7]));
      if ($row[4]) {
        $item->addAttribute($row[4]);
      }
      $item->addAttribute($row[5]);
      $item->addAttribute($row[6]);
      $list->addItem($item);
    }

    $nav->appendChild(
      array(
        $list,
        $pager,
      ));

    $crumbs = $this->buildApplicationCrumbs($this->buildSideNavView());
    $crumbs->addCrumb(
      id(new PhabricatorCrumbView())
        ->setName($table_header)
        ->setHref($this->getApplicationURI()));
    $nav->setCrumbs($crumbs);

    return $this->buildApplicationPage(
      $nav,
      array(
        'title' => pht('Projects'),
        'device' => true,
        'dust' => true,
      ));
  }

  public function buildApplicationMenu() {
    return $this->buildSideNavView(null, true)->getMenu();
  }
}


text:
importScripts("/resources/testharness.js");
importScripts("/html/canvas/resources/canvas-tests.js");

var t = async_test("");
var t_pass = t.done.bind(t);
var t_fail = t.step_func(function(reason) {
    throw reason;
});
t.step(function() {

var offscreenCanvas = new OffscreenCanvas(100, 50);
var ctx = offscreenCanvas.getContext('2d');

ctx.font = 'small-caps italic 400 12px/2 Unknown Font, sans-serif';
_assertSame(ctx.font, 'italic small-caps 12px "Unknown Font", sans-serif', "ctx.font", "'italic small-caps 12px \"Unknown Font\", sans-serif'");
t.done();

});
done();


text:
package com.glaf.base.modules.sys.rest;

import java.io.IOException;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.UriInfo;

import org.apache.commons.lang3.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.glaf.base.modules.sys.model.SysTree;
import com.glaf.base.modules.sys.query.SysTreeQuery;
import com.glaf.base.modules.sys.service.SysTreeService;
import com.glaf.base.utils.ParamUtil;
import com.glaf.core.res.MessageUtils;
import com.glaf.core.res.ViewMessage;
import com.glaf.core.res.ViewMessages;
import com.glaf.core.util.Paging;
import com.glaf.core.util.ParamUtils;
import com.glaf.core.util.RequestUtils;
import com.glaf.core.util.Tools;

@Controller("/rs/base/tree")
@Path("/rs/base/tree")
public class TreeResource {
	private static final Log logger = LogFactory.getLog(TreeResource.class);

	private SysTreeService sysTreeService;

	/**
	 * 批量删除信息
	 *
	 * @param request
	 * @param uriInfo
	 * @return
	 */
	@Path("batchDelete")
	@POST
	@Produces(MediaType.TEXT_PLAIN)
	public ModelAndView batchDelete(@Context HttpServletRequest request,
			@Context UriInfo uriInfo) {
		RequestUtils.setRequestParameterToAttribute(request);
		ViewMessages messages = new ViewMessages();
		messages.add(ViewMessages.GLOBAL_MESSAGE, new ViewMessage(
				"tree.delete_failure"));
		MessageUtils.addMessages(request, messages);
		return new ModelAndView("show_json_msg");
	}

	@GET
	@POST
	@Path("json")
	@Produces({ MediaType.APPLICATION_OCTET_STREAM })
	@ResponseBody
	public byte[] json(@Context HttpServletRequest request,
			@Context UriInfo uriInfo) throws IOException {
		Map<String, Object> params = RequestUtils.getParameterMap(request);
		SysTreeQuery query = new SysTreeQuery();
		Tools.populate(query, params);

		String gridType = ParamUtils.getString(params, "gridType");
		if (gridType == null) {
			gridType = "easyui";
		}
		int start = 0;
		int limit = 10;
		String orderName = null;
		String order = null;

		int pageNo = ParamUtils.getInt(params, "page");
		limit = ParamUtils.getInt(params, "rows");
		start = (pageNo - 1) * limit;
		orderName = ParamUtils.getString(params, "sortName");
		order = ParamUtils.getString(params, "sortOrder");

		if (start < 0) {
			start = 0;
		}

		if (limit <= 0) {
			limit = Paging.DEFAULT_PAGE_SIZE;
		}

		JSONObject result = new JSONObject();
		int total = sysTreeService.getSysTreeCountByQueryCriteria(query);
		if (total > 0) {
			result.put("total", total);
			result.put("totalCount", total);
			result.put("totalRecords", total);
			result.put("start", start);
			result.put("startIndex", start);
			result.put("limit", limit);
			result.put("pageSize", limit);

			if (StringUtils.isNotEmpty(orderName)) {
				query.setSortOrder(orderName);
				if (StringUtils.equals(order, "desc")) {
					query.setSortOrder(" desc ");
				}
			}

			List<SysTree> list = sysTreeService.getSysTreesByQueryCriteria(
					start, limit, query);

			if (list != null && !list.isEmpty()) {
				JSONArray rowsJSON = new JSONArray();

				result.put("rows", rowsJSON);

				for (SysTree sysTree : list) {
					JSONObject rowJSON = sysTree.toJsonObject();
					rowJSON.put("id", sysTree.getId());
					rowJSON.put("startIndex", ++start);
					rowsJSON.add(rowJSON);
				}

			}
		}
		return result.toJSONString().getBytes("UTF-8");
	}

	/**
	 * 提交增加信息
	 *
	 * @param request
	 * @param uriInfo
	 * @return
	 */
	@Path("saveAdd")
	@POST
	@Produces(MediaType.TEXT_PLAIN)
	public ModelAndView saveAdd(@Context HttpServletRequest request,
			@Context UriInfo uriInfo) {
		RequestUtils.setRequestParameterToAttribute(request);
		SysTree bean = new SysTree();
		bean.setParentId(ParamUtil.getIntParameter(request, "parent", 0));
		bean.setName(ParamUtil.getParameter(request, "name"));
		bean.setDesc(ParamUtil.getParameter(request, "desc"));
		bean.setCode(ParamUtil.getParameter(request, "code"));
		boolean ret = sysTreeService.create(bean);
		ViewMessages messages = new ViewMessages();
		if (ret) {// 保存成功
			messages.add(ViewMessages.GLOBAL_MESSAGE, new ViewMessage(
					"tree.add_success"));
		} else {// 保存失败
			messages.add(ViewMessages.GLOBAL_MESSAGE, new ViewMessage(
					"tree.add_failure"));
		}
		MessageUtils.addMessages(request, messages);
		return new ModelAndView("show_json_msg");
	}

	/**
	 * 提交修改信息
	 *
	 * @param request
	 * @param uriInfo
	 * @return
	 */
	@Path("saveModify")
	@POST
	@Produces(MediaType.TEXT_PLAIN)
	public ModelAndView saveModify(@Context HttpServletRequest request,
			@Context UriInfo uriInfo) {
		RequestUtils.setRequestParameterToAttribute(request);
		long id = ParamUtil.getIntParameter(request, "id", 0);
		SysTree bean = sysTreeService.findById(id);
		if (bean != null) {
			bean.setParentId(ParamUtil.getIntParameter(request, "parent", 0));
			bean.setName(ParamUtil.getParameter(request, "name"));
			bean.setDesc(ParamUtil.getParameter(request, "desc"));
			bean.setCode(ParamUtil.getParameter(request, "code"));
		}
		boolean ret = false;
		try {
			ret = sysTreeService.update(bean);
		} catch (Exception ex) {
			ret = false;
			logger.error(ex);
		}
		ViewMessages messages = new ViewMessages();
		if (ret) {// 保存成功
			messages.add(ViewMessages.GLOBAL_MESSAGE, new ViewMessage(
					"tree.modify_success"));
		} else {// 保存失败
			messages.add(ViewMessages.GLOBAL_MESSAGE, new ViewMessage(
					"tree.modify_failure"));
		}
		MessageUtils.addMessages(request, messages);
		// 显示列表页面
		return new ModelAndView("show_json_msg");
	}

	@javax.annotation.Resource
	public void setSysTreeService(SysTreeService sysTreeService) {
		this.sysTreeService = sysTreeService;
	}

	@POST
	@ResponseBody
	@Path("sort")
	public void sort(@Context HttpServletRequest request,
			@Context UriInfo uriInfo) {
		int id = ParamUtil.getIntParameter(request, "id", 0);
		int parent = ParamUtil.getIntParameter(request, "parent", 0);
		int operate = ParamUtil.getIntParameter(request, "operate", 0);
		logger.info("parent:" + parent + "; id:" + id + "; operate:" + operate);
		SysTree bean = sysTreeService.findById(id);
		sysTreeService.sort(parent, bean, operate);
	}
}


text:
xmlcreate
Copyright (C) 2016 Michael Kourlas


text:
package mocks

import mock "github.com/stretchr/testify/mock"
import peer "github.com/hyperledger/fabric-protos-go/peer"
import privdata "github.com/hyperledger/fabric/core/common/privdata"

// CollectionAccessFactory is an autogenerated mock type for the CollectionAccessFactory type
type CollectionAccessFactory struct {
	mock.Mock
}

// AccessPolicy provides a mock function with given fields: config, chainID
func (_m *CollectionAccessFactory) AccessPolicy(config *peer.CollectionConfig, chainID string) (privdata.CollectionAccessPolicy, error) {
	ret := _m.Called(config, chainID)

	var r0 privdata.CollectionAccessPolicy
	if rf, ok := ret.Get(0).(func(*peer.CollectionConfig, string) privdata.CollectionAccessPolicy); ok {
		r0 = rf(config, chainID)
	} else {
		if ret.Get(0) != nil {
			r0 = ret.Get(0).(privdata.CollectionAccessPolicy)
		}
	}

	var r1 error
	if rf, ok := ret.Get(1).(func(*peer.CollectionConfig, string) error); ok {
		r1 = rf(config, chainID)
	} else {
		r1 = ret.Error(1)
	}

	return r0, r1
}


text:
"use strict";

const childProcess = require('child_process');
const EventEmitter = require('events').EventEmitter;
const fs = require('fs');
require('./string.js');

const Executer = function () {
    this.child = null;
    EventEmitter.call(this);
};

Executer.prototype = Object.create(EventEmitter.prototype);

Executer.prototype.execute = function (command, args) {

    fs.readFile('scripts/start-adb-script.sh', {encoding: 'utf-8'}, (err, data) => {
       if (!err) {
           const startAdbScript = data.removeAllNewlines();

           childProcess.execSync(`adb shell "${startAdbScript}"`);

           const child = this.child = childProcess.spawn(command, args);

           child.stdout.on('data', (data) => {
               const buffer = new Buffer(data).toString();

               /*console.log(data);*/

               if (buffer !== '\r\r\n') {
                   const split = buffer.trim().split(' ');

                   const values = split.filter((value) => {
                       return value !== '';
                   });

                   /*console.log(values);*/

                   this.emit('data', values);
               }
           });

           child.on('close', (code) => {
               console.log('Closed with status: ' + code);
           });
       }
    });
};

Executer.prototype.terminate = function () {
    this.child.kill();
};

module.exports = Executer;


text:
<!doctype html>

        <title>jsPlumb 1.5.5 demo - MooTools</title>
		<meta http-equiv="content-type" content="text/html;charset=utf-8" />
        <link href="//netdna.bootstrapcdn.com/font-awesome/4.0.1/css/font-awesome.css" rel="stylesheet">
        <link rel="stylesheet" href="../demo-all.css">
        <link rel="stylesheet" href="demo.css">

                    DOCS
                    API
                    TESTS
                    CONTACT
                    GITHUB
                    DISCUSS
                    ISSUES

            Tweet

DYNAMIC ANCHORS

This is a demonstration of anchors that change position dependent on the location of the other element in a connection. Each Connection is decorated with a Diamond overlay, located halfway along the connector.

You can drag new connections between Endpoints.

Endpoints support an unlimited number of Connections.

This demonstration uses jsPlumb 1.5.5, MooTools 1.3.2 and MooTools More 1.3.2.1.

1

2

3

4

5

6


text:
Install_redis-server() {
  pushd ${oneinstack_dir}/src
  tar xzf redis-${redis_version}.tar.gz
  pushd redis-${redis_version}
  if [ "$OS_BIT" == '32' ]; then
    sed -i '1i\CFLAGS= -march=i686' src/Makefile
    sed -i 's@^OPT=.*@OPT=-O2 -march=i686@' src/.make-settings
  fi
  make -j ${THREAD}
  if [ -f "src/redis-server" ]; then
    mkdir -p ${redis_install_dir}/{bin,etc,var}
    /bin/cp src/{redis-benchmark,redis-check-aof,redis-check-rdb,redis-cli,redis-sentinel,redis-server} ${redis_install_dir}/bin/
    /bin/cp redis.conf ${redis_install_dir}/etc/
    ln -s ${redis_install_dir}/bin/* /usr/local/bin/
    sed -i 's@pidfile.*@pidfile /var/run/redis.pid@' ${redis_install_dir}/etc/redis.conf
    sed -i "s@logfile.*@logfile ${redis_install_dir}/var/redis.log@" ${redis_install_dir}/etc/redis.conf
    sed -i "s@^dir.*@dir ${redis_install_dir}/var@" ${redis_install_dir}/etc/redis.conf
    sed -i 's@daemonize no@daemonize yes@' ${redis_install_dir}/etc/redis.conf
    sed -i "s@^# bind 127.0.0.1@bind 127.0.0.1@" ${redis_install_dir}/etc/redis.conf
    redis_maxmemory=`expr $Mem / 8`000000
    [ -z "`grep ^maxmemory ${redis_install_dir}/etc/redis.conf`" ] && sed -i "s@maxmemory <bytes>@maxmemory <bytes>\nmaxmemory `expr $Mem / 8`000000@" ${redis_install_dir}/etc/redis.conf
    echo "${CSUCCESS}Redis-server installed successfully! ${CEND}"
    popd
    rm -rf redis-${redis_version}
    id -u redis >/dev/null 2>&1
    [ $? -ne 0 ] && useradd -M -s /sbin/nologin redis
    chown -R redis:redis ${redis_install_dir}/var
    /bin/cp ../init.d/Redis-server-init /etc/init.d/redis-server
    if [ "$OS" == 'CentOS' ]; then
      cc start-stop-daemon.c -o /sbin/start-stop-daemon
      chkconfig --add redis-server
      chkconfig redis-server on
    elif [[ $OS =~ ^Ubuntu$|^Debian$ ]]; then
      update-rc.d redis-server defaults
    fi
    sed -i "s@/usr/local/redis@${redis_install_dir}@g" /etc/init.d/redis-server
    #[ -z "`grep 'vm.overcommit_memory' /etc/sysctl.conf`" ] && echo 'vm.overcommit_memory = 1' >> /etc/sysctl.conf
    #sysctl -p
    service redis-server start
  else
    rm -rf ${redis_install_dir}
    echo "${CFAILURE}Redis-server install failed, Please contact the author! ${CEND}"
    kill -9 $$
  fi
  popd
}

Install_php-redis() {
  pushd ${oneinstack_dir}/src
  phpExtensionDir=`${php_install_dir}/bin/php-config --extension-dir`
  if [ -e "${php_install_dir}/bin/phpize" ]; then
    if [ "`${php_install_dir}/bin/php -r 'echo PHP_VERSION;' | awk -F. '{print $1}'`" == '7' ]; then
      tar xzf redis-${redis_pecl_for_php7_version}.tgz
      pushd redis-${redis_pecl_for_php7_version}
    else
      tar xzf redis-$redis_pecl_version.tgz
      pushd redis-$redis_pecl_version
    fi
    ${php_install_dir}/bin/phpize
    ./configure --with-php-config=${php_install_dir}/bin/php-config
    make -j ${THREAD} && make install
    if [ -f "${phpExtensionDir}/redis.so" ]; then
      echo 'extension=redis.so' > ${php_install_dir}/etc/php.d/ext-redis.ini
      echo "${CSUCCESS}PHP Redis module installed successfully! ${CEND}"
      popd
      rm -rf redis-${redis_pecl_for_php7_version} redis-$redis_pecl_version
    else
      echo "${CFAILURE}PHP Redis module install failed, Please contact the author! ${CEND}"
    fi
  fi
  popd
}


text:
"""
__LocalDef1ProcPart2_Complete_MDL.py_____________________________________________________

Automatically generated AToM3 Model File (Do not modify directly)
Author: gehan
Modified: Thu Mar  5 02:01:14 2015
_________________________________________________________________________________________
"""
from stickylink import *
from widthXfillXdecoration import *
from MT_pre__LocalDef import *
from MT_pre__directLink_T import *
from MT_pre__Proc import *
from LHS import *
from graph_MT_pre__directLink_T import *
from graph_MT_pre__LocalDef import *
from graph_MT_pre__Proc import *
from graph_LHS import *
from ATOM3Enum import *
from ATOM3String import *
from ATOM3BottomType import *
from ATOM3Constraint import *
from ATOM3Attribute import *
from ATOM3Float import *
from ATOM3List import *
from ATOM3Link import *
from ATOM3Connection import *
from ATOM3Boolean import *
from ATOM3Appearance import *
from ATOM3Text import *
from ATOM3Action import *
from ATOM3Integer import *
from ATOM3Port import *
from ATOM3MSEnum import *

def LocalDef1ProcPart2_Complete_MDL(self, rootNode, MoTifRuleRootNode=None, MT_pre__UMLRT2Kiltera_MMRootNode=None):

    # --- Generating attributes code for ASG MoTifRule ---
    if( MoTifRuleRootNode ):
        # author
        MoTifRuleRootNode.author.setValue('Annonymous')

        # description
        MoTifRuleRootNode.description.setValue('\n')
        MoTifRuleRootNode.description.setHeight(15)

        # name
        MoTifRuleRootNode.name.setValue('LocalDef1ProcPart2_Complete')
    # --- ASG attributes over ---

    # --- Generating attributes code for ASG MT_pre__UMLRT2Kiltera_MM ---
    if( MT_pre__UMLRT2Kiltera_MMRootNode ):
        # author
        MT_pre__UMLRT2Kiltera_MMRootNode.author.setValue('Annonymous')

        # description
        MT_pre__UMLRT2Kiltera_MMRootNode.description.setValue('\n')
        MT_pre__UMLRT2Kiltera_MMRootNode.description.setHeight(15)

        # name
        MT_pre__UMLRT2Kiltera_MMRootNode.name.setValue('')
        MT_pre__UMLRT2Kiltera_MMRootNode.name.setNone()
    # --- ASG attributes over ---

    self.obj136892=MT_pre__LocalDef(self)
    self.obj136892.isGraphObjectVisual = True

    if(hasattr(self.obj136892, '_setHierarchicalLink')):
      self.obj136892._setHierarchicalLink(False)

    # MT_label__
    self.obj136892.MT_label__.setValue('1')

    # MT_pivotOut__
    self.obj136892.MT_pivotOut__.setValue('element1')

    # MT_subtypeMatching__
    self.obj136892.MT_subtypeMatching__.setValue(('True', 0))
    self.obj136892.MT_subtypeMatching__.config = 0

    # MT_pre__classtype
    self.obj136892.MT_pre__classtype.setValue('\n#===============================================================================\n# This code is executed when evaluating if a node shall be matched by this rule.\n# You can access the value of the current node\'s attribute value by: attr_value.\n# You can access any attribute x of this node by: this[\'x\'].\n# If the constraint relies on attribute values from other nodes,\n# use the LHS/NAC constraint instead.\n# The given constraint must evaluate to a boolean expression.\n#===============================================================================\n\nreturn True\n')
    self.obj136892.MT_pre__classtype.setHeight(15)

    # MT_pre__cardinality
    self.obj136892.MT_pre__cardinality.setValue('\n#===============================================================================\n# This code is executed when evaluating if a node shall be matched by this rule.\n# You can access the value of the current node\'s attribute value by: attr_value.\n# You can access any attribute x of this node by: this[\'x\'].\n# If the constraint relies on attribute values from other nodes,\n# use the LHS/NAC constraint instead.\n# The given constraint must evaluate to a boolean expression.\n#===============================================================================\n\nreturn True\n')
    self.obj136892.MT_pre__cardinality.setHeight(15)

    # MT_pre__name
    self.obj136892.MT_pre__name.setValue('\n#===============================================================================\n# This code is executed when evaluating if a node shall be matched by this rule.\n# You can access the value of the current node\'s attribute value by: attr_value.\n# You can access any attribute x of this node by: this[\'x\'].\n# If the constraint relies on attribute values from other nodes,\n# use the LHS/NAC constraint instead.\n# The given constraint must evaluate to a boolean expression.\n#===============================================================================\n\nreturn True\n')
    self.obj136892.MT_pre__name.setHeight(15)

    # MT_pivotIn__
    self.obj136892.MT_pivotIn__.setValue('element1')

    self.obj136892.graphClass_= graph_MT_pre__LocalDef
    if self.genGraphics:
       new_obj = graph_MT_pre__LocalDef(60.0,40.0,self.obj136892)
       new_obj.DrawObject(self.UMLmodel)
       self.UMLmodel.addtag_withtag("MT_pre__LocalDef", new_obj.tag)
       new_obj.layConstraints = dict() # Graphical Layout Constraints
       new_obj.layConstraints['scale'] = [1.0, 1.0]
    else: new_obj = None
    self.obj136892.graphObject_ = new_obj

    # Add node to the root: rootNode
    rootNode.addNode(self.obj136892)
    self.globalAndLocalPostcondition(self.obj136892, rootNode)
    self.obj136892.postAction( rootNode.CREATE )

    self.obj147408=MT_pre__directLink_T(self)
    self.obj147408.isGraphObjectVisual = True

    if(hasattr(self.obj147408, '_setHierarchicalLink')):
      self.obj147408._setHierarchicalLink(False)

    # MT_label__
    self.obj147408.MT_label__.setValue('3')

    # MT_pivotOut__
    self.obj147408.MT_pivotOut__.setValue('')
    self.obj147408.MT_pivotOut__.setNone()

    # MT_subtypeMatching__
    self.obj147408.MT_subtypeMatching__.setValue(('True', 0))
    self.obj147408.MT_subtypeMatching__.config = 0

    # MT_pivotIn__
    self.obj147408.MT_pivotIn__.setValue('')
    self.obj147408.MT_pivotIn__.setNone()

    # MT_pre__associationType
    self.obj147408.MT_pre__associationType.setValue('\n#===============================================================================\n# This code is executed when evaluating if a node shall be matched by this rule.\n# You can access the value of the current node\'s attribute value by: attr_value.\n# You can access any attribute x of this node by: this[\'x\'].\n# If the constraint relies on attribute values from other nodes,\n# use the LHS/NAC constraint instead.\n# The given constraint must evaluate to a boolean expression.\n#===============================================================================\n\nreturn True\n')
    self.obj147408.MT_pre__associationType.setHeight(15)

    self.obj147408.graphClass_= graph_MT_pre__directLink_T
    if self.genGraphics:
       new_obj = graph_MT_pre__directLink_T(277.0,241.0,self.obj147408)
       new_obj.DrawObject(self.UMLmodel)
       self.UMLmodel.addtag_withtag("MT_pre__directLink_T", new_obj.tag)
       new_obj.layConstraints = dict() # Graphical Layout Constraints
    else: new_obj = None
    self.obj147408.graphObject_ = new_obj

    # Add node to the root: rootNode
    rootNode.addNode(self.obj147408)
    self.globalAndLocalPostcondition(self.obj147408, rootNode)
    self.obj147408.postAction( rootNode.CREATE )

    self.obj147405=MT_pre__Proc(self)
    self.obj147405.isGraphObjectVisual = True

    if(hasattr(self.obj147405, '_setHierarchicalLink')):
      self.obj147405._setHierarchicalLink(False)

    # MT_pivotOut__
    self.obj147405.MT_pivotOut__.setValue('')
    self.obj147405.MT_pivotOut__.setNone()

    # MT_subtypeMatching__
    self.obj147405.MT_subtypeMatching__.setValue(('True', 1))
    self.obj147405.MT_subtypeMatching__.config = 0

    # MT_pre__classtype
    self.obj147405.MT_pre__classtype.setValue('\n#===============================================================================\n# This code is executed when evaluating if a node shall be matched by this rule.\n# You can access the value of the current node\'s attribute value by: attr_value.\n# You can access any attribute x of this node by: this[\'x\'].\n# If the constraint relies on attribute values from other nodes,\n# use the LHS/NAC constraint instead.\n# The given constraint must evaluate to a boolean expression.\n#===============================================================================\n\nreturn True\n')
    self.obj147405.MT_pre__classtype.setHeight(15)

    # MT_pivotIn__
    self.obj147405.MT_pivotIn__.setValue('')
    self.obj147405.MT_pivotIn__.setNone()

    # MT_label__
    self.obj147405.MT_label__.setValue('2')

    # MT_pre__cardinality
    self.obj147405.MT_pre__cardinality.setValue('\n#===============================================================================\n# This code is executed when evaluating if a node shall be matched by this rule.\n# You can access the value of the current node\'s attribute value by: attr_value.\n# You can access any attribute x of this node by: this[\'x\'].\n# If the constraint relies on attribute values from other nodes,\n# use the LHS/NAC constraint instead.\n# The given constraint must evaluate to a boolean expression.\n#===============================================================================\n\nreturn True\n')
    self.obj147405.MT_pre__cardinality.setHeight(15)

    # MT_pre__name
    self.obj147405.MT_pre__name.setValue('\n#===============================================================================\n# This code is executed when evaluating if a node shall be matched by this rule.\n# You can access the value of the current node\'s attribute value by: attr_value.\n# You can access any attribute x of this node by: this[\'x\'].\n# If the constraint relies on attribute values from other nodes,\n# use the LHS/NAC constraint instead.\n# The given constraint must evaluate to a boolean expression.\n#===============================================================================\n\nreturn True\n')
    self.obj147405.MT_pre__name.setHeight(15)

    self.obj147405.graphClass_= graph_MT_pre__Proc
    if self.genGraphics:
       new_obj = graph_MT_pre__Proc(60.0,240.0,self.obj147405)
       new_obj.DrawObject(self.UMLmodel)
       self.UMLmodel.addtag_withtag("MT_pre__Proc", new_obj.tag)
       new_obj.layConstraints = dict() # Graphical Layout Constraints
       new_obj.layConstraints['scale'] = [1.0, 1.0]
    else: new_obj = None
    self.obj147405.graphObject_ = new_obj

    # Add node to the root: rootNode
    rootNode.addNode(self.obj147405)
    self.globalAndLocalPostcondition(self.obj147405, rootNode)
    self.obj147405.postAction( rootNode.CREATE )

    self.obj136891=LHS(self)
    self.obj136891.isGraphObjectVisual = True

    if(hasattr(self.obj136891, '_setHierarchicalLink')):
      self.obj136891._setHierarchicalLink(False)

    # constraint
    self.obj136891.constraint.setValue('#===============================================================================\n# This code is executed after the nodes in the LHS have been matched.\n# You can access a matched node labelled n by: PreNode(\'n\').\n# To access attribute x of node n, use: PreNode(\'n\')[\'x\'].\n# The given constraint must evaluate to a boolean expression:\n#    returning True enables the rule to be applied,\n#    returning False forbids the rule from being applied.\n#===============================================================================\n\nreturn True\n')
    self.obj136891.constraint.setHeight(15)

    self.obj136891.graphClass_= graph_LHS
    if self.genGraphics:
       new_obj = graph_LHS(40.0,20.0,self.obj136891)
       new_obj.DrawObject(self.UMLmodel)
       self.UMLmodel.addtag_withtag("LHS", new_obj.tag)
       new_obj.layConstraints = dict() # Graphical Layout Constraints
       new_obj.layConstraints['scale'] = [1.0, 1.0]
    else: new_obj = None
    self.obj136891.graphObject_ = new_obj

    # Add node to the root: rootNode
    rootNode.addNode(self.obj136891)
    self.globalAndLocalPostcondition(self.obj136891, rootNode)
    self.obj136891.postAction( rootNode.CREATE )

    # Connections for obj136892 (graphObject_: Obj25) of type MT_pre__LocalDef
    self.drawConnections(
(self.obj136892,self.obj147408,[277.0, 141.0, 277.0, 241.0],"true", 2) )
    # Connections for obj147408 (graphObject_: Obj27) of type MT_pre__directLink_T
    self.drawConnections(
(self.obj147408,self.obj147405,[277.0, 241.0, 277.0, 341.0],"true", 2) )
    # Connections for obj147405 (graphObject_: Obj26) of type MT_pre__Proc
    self.drawConnections(
 )
    # Connections for obj136891 (graphObject_: Obj24) of type LHS
    self.drawConnections(
 )

newfunction = LocalDef1ProcPart2_Complete_MDL

loadedMMName = ['MoTifRule_META', 'MT_pre__UMLRT2Kiltera_MM_META']

atom3version = '0.3'


text:
/*
 * 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.
 */

package org.nightcode.common.net.retry;

import org.nightcode.common.net.GeneralNetworkException;

import java.io.IOException;
import java.util.concurrent.CompletionException;
import java.util.concurrent.ExecutionException;

import org.junit.Assert;
import org.junit.Test;

public class DefaultRetryPolicyTest {

  @Test public void testOnException() {
    RetryPolicy retryPolicy = new DefaultRetryPolicy();

    Throwable retryException = new IOException();
    RetryPolicy.Decision target = retryPolicy.onException(retryException);
    Assert.assertEquals(RetryPolicy.Decision.RETRY, target);

    retryException = new GeneralNetworkException("message", retryException);
    target = retryPolicy.onException(retryException);
    Assert.assertEquals(RetryPolicy.Decision.RETRY, target);

    Throwable rethrowException = new IllegalArgumentException();
    target = retryPolicy.onException(rethrowException);
    Assert.assertEquals(RetryPolicy.Decision.RETHROW, target);

    Throwable retryCauseException = new ExecutionException("message", retryException);
    target = retryPolicy.onException(retryCauseException);
    Assert.assertEquals(RetryPolicy.Decision.RETRY, target);

    retryCauseException = new CompletionException("message", retryException);
    target = retryPolicy.onException(retryCauseException);
    Assert.assertEquals(RetryPolicy.Decision.RETRY, target);

    Throwable rethrowCauseException = new ExecutionException("message", rethrowException);
    target = retryPolicy.onException(rethrowCauseException);
    Assert.assertEquals(RetryPolicy.Decision.RETHROW, target);

    rethrowCauseException = new CompletionException("message", rethrowException);
    target = retryPolicy.onException(rethrowCauseException);
    Assert.assertEquals(RetryPolicy.Decision.RETHROW, target);
  }
}


text:
package com.pushtorefresh.storio.contentresolver.operations.get;

import android.database.Cursor;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.annotation.WorkerThread;

import com.pushtorefresh.storio.contentresolver.StorIOContentResolver;
import com.pushtorefresh.storio.contentresolver.queries.Query;
import com.pushtorefresh.storio.operations.internal.MapSomethingToExecuteAsBlocking;
import com.pushtorefresh.storio.operations.internal.OnSubscribeExecuteAsBlocking;

import rx.Observable;
import rx.schedulers.Schedulers;

import static com.pushtorefresh.storio.internal.Checks.checkNotNull;
import static com.pushtorefresh.storio.internal.Environment.throwExceptionIfRxJavaIsNotAvailable;

/**
 * Represents Get Operation for {@link StorIOContentResolver}
 * which performs query that retrieves data as {@link Cursor}.
 * from {@link android.content.ContentProvider}.
 */
public final class PreparedGetCursor extends PreparedGet<Cursor> {

    @NonNull
    private final Query query;

    @NonNull
    private final GetResolver<Cursor> getResolver;

    PreparedGetCursor(@NonNull StorIOContentResolver storIOContentResolver,
                      @NonNull GetResolver<Cursor> getResolver,
                      @NonNull Query query) {
        super(storIOContentResolver);
        this.query = query;
        this.getResolver = getResolver;
    }

    /**
     * Executes Get Operation immediately in current thread.
     *

     * Notice: This is blocking I/O operation that should not be executed on the Main Thread,
     * it can cause ANR (Activity Not Responding dialog), block the UI and drop animations frames.
     * So please, call this method on some background thread. See {@link WorkerThread}.
     *
     * @return non-null {@link Cursor}, can be empty.
     */
    @WorkerThread
    @NonNull
    @Override
    public Cursor executeAsBlocking() {
        return getResolver.performGet(storIOContentResolver, query);
    }

    /**
     * Creates "Hot" {@link Observable} which will be subscribed to changes of {@link #query} Uri
     * and will emit result each time change occurs.
     *

     * First result will be emitted immediately after subscription,
     * other emissions will occur only if changes of {@link #query} Uri will occur.
     *

     *
Scheduler:

     *
Operates on {@link Schedulers#io()}.

     *

     *

     * Please don't forget to unsubscribe from this {@link Observable} because
     * it's "Hot" and endless.
     *
     * @return non-null {@link Observable} which will emit non-null
     * list with mapped results and will be subscribed to changes of {@link #query} Uri.
     */
    @NonNull
    @Override
    public Observable<Cursor> createObservable() {
        throwExceptionIfRxJavaIsNotAvailable("createObservable()");

        return storIOContentResolver
                .observeChangesOfUri(query.uri()) // each change triggers executeAsBlocking
                .map(MapSomethingToExecuteAsBlocking.newInstance(this))
                .startWith(Observable.create(OnSubscribeExecuteAsBlocking.newInstance(this))) // start stream with first query result
                .subscribeOn(Schedulers.io());
    }

    /**
     * Builder for {@link PreparedGetCursor}.
     *

     * Required: You should specify query see {@link #withQuery(Query)}.
     */
    public static final class Builder {

        @NonNull
        final StorIOContentResolver storIOContentResolver;

        public Builder(@NonNull StorIOContentResolver storIOContentResolver) {
            this.storIOContentResolver = storIOContentResolver;
        }

        /**
         * Required: Specifies {@link Query} for Get Operation.
         *
         * @param query query.
         * @return builder.
         */
        @NonNull
        public CompleteBuilder withQuery(@NonNull Query query) {
            checkNotNull(query, "Please specify Query");
            return new CompleteBuilder(storIOContentResolver, query);
        }
    }

    /**
     * Compile-time safe part of builder for {@link PreparedGetCursor}.
     */
    public static final class CompleteBuilder {

        private static final GetResolver<Cursor> STANDARD_GET_RESOLVER = new DefaultGetResolver<Cursor>() {
            @NonNull
            @Override
            public Cursor mapFromCursor(@NonNull Cursor cursor) {
                return cursor; // easy
            }
        };

        @NonNull
        private final StorIOContentResolver storIOContentResolver;

        @NonNull
        private final Query query;

        private GetResolver<Cursor> getResolver;

        CompleteBuilder(@NonNull StorIOContentResolver storIOContentResolver, @NonNull Query query) {
            this.storIOContentResolver = storIOContentResolver;
            this.query = query;
        }

        /**
         * Optional: Specifies {@link GetResolver} for Get Operation
         * which allows you to customize behavior of Get Operation.
         *

         * If no value will be set, builder will use resolver that
         * simply redirects query to {@link StorIOContentResolver}.
         *
         * @param getResolver GetResolver.
         * @return builder.
         */
        @NonNull
        public CompleteBuilder withGetResolver(@Nullable GetResolver<Cursor> getResolver) {
            this.getResolver = getResolver;
            return this;
        }

        /**
         * Prepares Get Operation.
         *
         * @return {@link PreparedGetCursor} instance.
         */
        @NonNull
        public PreparedGetCursor prepare() {
            if (getResolver == null) {
                getResolver = STANDARD_GET_RESOLVER;
            }

            return new PreparedGetCursor(
                    storIOContentResolver,
                    getResolver,
                    query
            );
        }
    }
}


text:
package com.bazaarvoice.ostrich.examples.calculator.user;

import com.bazaarvoice.ostrich.ServicePool;
import com.bazaarvoice.ostrich.discovery.zookeeper.ZooKeeperHostDiscovery;
import com.bazaarvoice.ostrich.dropwizard.healthcheck.ContainsHealthyEndPointCheck;
import com.bazaarvoice.ostrich.examples.calculator.client.CalculatorService;
import com.bazaarvoice.ostrich.examples.calculator.client.CalculatorServiceFactory;
import com.bazaarvoice.ostrich.pool.ServiceCachingPolicy;
import com.bazaarvoice.ostrich.pool.ServiceCachingPolicyBuilder;
import com.bazaarvoice.ostrich.pool.ServicePoolBuilder;
import com.bazaarvoice.ostrich.retry.ExponentialBackoffRetry;
import com.codahale.metrics.MetricRegistry;
import com.codahale.metrics.health.HealthCheckRegistry;
import com.google.common.io.Closeables;
import io.dropwizard.client.JerseyClientConfiguration;
import io.dropwizard.configuration.ConfigurationException;
import io.dropwizard.configuration.ConfigurationFactory;
import io.dropwizard.configuration.YamlConfigurationFactory;
import io.dropwizard.jackson.Jackson;
import io.dropwizard.util.JarLocation;
import net.sourceforge.argparse4j.ArgumentParsers;
import net.sourceforge.argparse4j.inf.ArgumentParser;
import net.sourceforge.argparse4j.inf.ArgumentParserException;
import net.sourceforge.argparse4j.inf.Namespace;
import org.apache.curator.framework.CuratorFramework;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.validation.Validation;
import javax.validation.Validator;
import java.io.File;
import java.io.IOException;
import java.util.Random;
import java.util.concurrent.TimeUnit;

public class CalculatorUser {
    private static final Logger LOG = LoggerFactory.getLogger(CalculatorUser.class);

    private final Random _random = new Random();
    private final ServicePool<CalculatorService> _calculatorPool;

    public CalculatorUser(ServicePool<CalculatorService> calculatorPool) {
        _calculatorPool = calculatorPool;
    }

    public void use() throws InterruptedException {
        int i = 0;
        while (++i > 0) {
            try {
                final int a = _random.nextInt(10);
                final int b = 1 + _random.nextInt(9);
                final int op = _random.nextInt(4);
                int result = _calculatorPool.execute(new ExponentialBackoffRetry(5, 50, 1000, TimeUnit.MILLISECONDS),
                        service -> CalculatorUser.this.call(service, op, a, b));
                LOG.info("i:{}, result:{}", i, result);
            } catch (Exception e) {
                LOG.warn("i:{}, {}", i, e);
            }

            Thread.sleep(100);
        }
    }

    private int call(CalculatorService service, int op, int a, int b) {
        switch (op) {
            case 0:  return service.add(a, b);
            case 1:  return service.sub(a, b);
            case 2:  return service.mul(a, b);
            default: return service.div(a, b);
        }
    }

    public static void main(String[] args) throws Exception {
        Namespace parsedArgs = parseCommandLine(args);

        // Load the config.yaml file specified as the first argument (optional).
        CalculatorConfiguration config = loadConfigFile(parsedArgs.getString("config-file"));

        // Connect to ZooKeeper
        CuratorFramework curator = config.getZooKeeperConfiguration().newCurator();
        curator.start();

        // Connection caching is optional, but included here for the sake of demonstration.
        ServiceCachingPolicy cachingPolicy = new ServiceCachingPolicyBuilder()
                .withMaxNumServiceInstances(10)
                .withMaxNumServiceInstancesPerEndPoint(1)
                .withMaxServiceInstanceIdleTime(5, TimeUnit.MINUTES)
                .build();

        JerseyClientConfiguration httpClientConfiguration = config.getHttpClientConfiguration();
        MetricRegistry metrics = new MetricRegistry();
        CalculatorServiceFactory serviceFactory = new CalculatorServiceFactory(httpClientConfiguration, metrics);
        ServicePool<CalculatorService> pool = ServicePoolBuilder.create(CalculatorService.class)
                .withServiceFactory(serviceFactory)
                .withHostDiscovery(new ZooKeeperHostDiscovery(curator, serviceFactory.getServiceName(), metrics))
                .withMetricRegistry(metrics)
                .withCachingPolicy(cachingPolicy)
                .build();

        // If using Yammer Metrics or running in Dropwizard (which includes Yammer Metrics), you may want a health
        // check that pings a service you depend on. This will register a simple check that will confirm the service
        // pool contains at least one healthy end point.
        HealthCheckRegistry healthChecks = new HealthCheckRegistry();
        healthChecks.register("calculator-user", ContainsHealthyEndPointCheck.forPool(pool));

        CalculatorUser user = new CalculatorUser(pool);
        user.use();

        Closeables.close(pool, true);
        Closeables.close(curator, true);
    }

    private static Namespace parseCommandLine(String[] args) throws ArgumentParserException {
        String usage = "java -jar " + new JarLocation(CalculatorUser.class);
        ArgumentParser argParser = ArgumentParsers.newArgumentParser(usage).defaultHelp(true);
        argParser.addArgument("config-file").nargs("?").help("yaml configuration file");
        return argParser.parseArgs(args);
    }

    private static CalculatorConfiguration loadConfigFile(String configFile)
            throws IOException, ConfigurationException {
        Validator validator = Validation.buildDefaultValidatorFactory().getValidator();
        ConfigurationFactory<CalculatorConfiguration> configFactory = new YamlConfigurationFactory<>(
                CalculatorConfiguration.class, validator, Jackson.newObjectMapper(), "calculator"
        );
        if (configFile != null) {
            return configFactory.build(new File(configFile));
        } else {
            return configFactory.build();
        }
    }
}


text:
class Protagor::Interpreter
  class Response < String
    def initialize query
      response = ""

      query.clauses.each do |clause|
        response << execute(clause, in_context: Protagor::BIPs::Context) if clause.bip?
      end

      super (response << 'yes')
    end

    private

    def execute clause, in_context: SomeDefaultContext
      in_context.eval clause
    end
  end
end


text:
package com.springinaction.springidol;

public class Juggler implements Performer {

	private int beanBags = 3;

	public Juggler(){};

	public Juggler(int bags) {
		beanBags = bags;
	}

	public int getBeanBags() {
		return beanBags;
	}

	public void setBeanBags(int beanBags) {
		this.beanBags = beanBags;
	}

	@Override
	public void perform() throws PerformanceException {
		System.out.println("JUGGLING "+beanBags+" BEANBAGS");
	}

}