text:
package org.faudroids.boredrudolf.ui;

import android.content.Context;
import android.graphics.Rect;
import android.support.v4.view.ViewCompat;
import android.support.v4.view.ViewPager;
import android.util.AttributeSet;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewConfiguration;
import android.view.ViewGroup;
import android.view.animation.Animation;
import android.view.animation.Animation.AnimationListener;
import android.view.animation.DecelerateInterpolator;
import android.view.animation.Transformation;
import android.widget.AbsListView;

import org.faudroids.boredrudolf.R;

/**
 * The CustomSwipeRefreshLayout should be used whenever the user can refresh the
 * contents of a view via a vertical swipe gesture. The activity that
 * instantiates this view should add an OnRefreshListener to be notified
 * whenever the swipe to refresh gesture is completed. And refreshComplete()
 * should be called whenever the refreshing is complete. The CustomSwipeRefreshLayout
 * will notify the listener each and every time the gesture is completed again.
 */
public class CustomSwipeRefreshLayout extends ViewGroup {

	private static final boolean DEBUG = false;
	private static final String TAG = CustomSwipeRefreshHeadLayout.class.getName();

	// time out for no movements during swipe action
	private static final int RETURN_TO_ORIGINAL_POSITION_TIMEOUT = 500;

	// Duration of the animation from the top of the content view to parent top
	private static final int RETURN_TO_TOP_DURATION = 500;

	// Duration of the animation from the top of the content view to the height of header
	private static final int RETURN_TO_HEADER_DURATION = 500;

	// deceleration of progress bar
	private static final float DECELERATE_INTERPOLATION_FACTOR = 2f;

	// maximum swipe distance( percent of parent container)
	private static final float MAX_SWIPE_DISTANCE_FACTOR = .9f;

	// swipe resistance factor
	private static final float RESISTANCE_FACTOR = .9f;

	private final DecelerateInterpolator mDecelerateInterpolator;
	private final Animation mAnimateStayComplete = new Animation() {
		@Override
		public void applyTransformation(float interpolatedTime, Transformation t) {
			// DO NOTHING
		}
	};
	private State currentState = new State(State.STATE_NORMAL);
	private State lastState = new State(-1);
	private ScrollUpHandler mScrollUpHandler;
	private ScrollLeftOrRightHandler mScrollLeftOrRightHandler;
	private int mRefreshCompleteTimeout;
	private View mHeadView;
	//the content that gets pulled down
	private View mTarget = null;
	private int mTargetOriginalTop;
	private OnRefreshListener mListener;
	private MotionEvent mDownEvent;
	private int mFrom;
	private boolean mRefreshing = false;
	private int mTouchSlop;
	private int mDistanceToTriggerSync = -1;
	private float mPrevY;
	private boolean enableHorizontalScroll = true;
	private boolean isHorizontalScroll;
	private boolean checkHorizontalMove;
	private boolean mCheckValidMotionFlag = true;
	private int mCurrentTargetOffsetTop = 0;
	private final AnimationListener mReturningAnimationListener = new BaseAnimationListener() {
		@Override
		public void onAnimationEnd(Animation animation) {
			// Once the target content has returned to its start position, reset
			// the target offset to 0
			// mCurrentTargetOffsetTop = 0;
			mInReturningAnimation = false;
		}
	};
	private RefreshCheckHandler mRefreshCheckHandler;

	private boolean mInReturningAnimation;
	private int mTriggerOffset = 0;

	private final Runnable mReturnToTriggerPosition = new Runnable() {

		@Override
		public void run() {
			mInReturningAnimation = true;
			animateOffsetToTriggerPosition(mTarget.getTop(),
					mReturningAnimationListener);
		}

	};

	private final Runnable mReturnToStartPosition = new Runnable() {

		@Override
		public void run() {
			mInReturningAnimation = true;
			animateOffsetToStartPosition(mTarget.getTop(),
					mReturningAnimationListener);
		}

	};

	private final AnimationListener mStayCompleteListener = new BaseAnimationListener() {
		@Override
		public void onAnimationEnd(Animation animation) {
			mReturnToStartPosition.run();
			mRefreshing = false;
		}
	};

	// Cancel the refresh gesture and animate everything back to its original state.
	private final Runnable mCancel = new Runnable() {
		@Override
		public void run() {
			mInReturningAnimation = true;
			animateOffsetToStartPosition(mTarget.getTop(), mReturningAnimationListener);
		}
	};

	private final Animation mAnimateToStartPosition = new Animation() {
		@Override
		public void applyTransformation(float interpolatedTime, Transformation t) {
			int targetTop = mTargetOriginalTop;
			if (mFrom != mTargetOriginalTop) {
				targetTop = (mFrom + (int) ((mTargetOriginalTop - mFrom) * interpolatedTime));
			}
			int offset = targetTop - mTarget.getTop();
			final int currentTop = mTarget.getTop();
			if (offset + currentTop < 0) {
				offset = 0 - currentTop;
			}
			setTargetOffsetTop(offset, true);
		}
	};

	private final Animation mAnimateToTriggerPosition = new Animation() {
		@Override
		public void applyTransformation(float interpolatedTime, Transformation t) {
			int targetTop = mDistanceToTriggerSync;
			if (mFrom > mDistanceToTriggerSync) {
				targetTop = (mFrom + (int) ((mDistanceToTriggerSync - mFrom) * interpolatedTime));
			}
			int offset = targetTop - mTarget.getTop();
			final int currentTop = mTarget.getTop();
			if (offset + currentTop < 0) {
				offset = 0 - currentTop;
			}
			setTargetOffsetTop(offset, true);
		}
	};

	/**
	 * Simple constructor to use when creating a CustomSwipeRefreshLayout from code.
	 *
	 * @param context
	 */
	public CustomSwipeRefreshLayout(Context context) {
		this(context, null);
	}

	/**
	 * Constructor that is called when inflating CustomSwipeRefreshLayout from XML.
	 *
	 * @param context
	 * @param attrs
	 */
	public CustomSwipeRefreshLayout(Context context, AttributeSet attrs) {
		this(context, attrs, 0);
	}

	public CustomSwipeRefreshLayout(Context context, AttributeSet attrs, int defStyle) {
		super(context, attrs, defStyle);
		mTouchSlop = ViewConfiguration.get(context).getScaledTouchSlop();
		setWillNotDraw(false);
		mDecelerateInterpolator = new DecelerateInterpolator(DECELERATE_INTERPOLATION_FACTOR);
		mRefreshCompleteTimeout = context.getResources().getInteger(R.integer.game_shutdown_delay);
		mTriggerOffset = getResources().getDimensionPixelOffset(R.dimen.game_height);
	}

	private void animateStayComplete(AnimationListener listener) {
		mAnimateStayComplete.reset();
		mAnimateStayComplete.setDuration(mRefreshCompleteTimeout);
		mAnimateStayComplete.setAnimationListener(listener);
		mTarget.startAnimation(mAnimateStayComplete);
	}

	private void animateOffsetToTriggerPosition(int from, AnimationListener listener) {
		mFrom = from;
		mAnimateToTriggerPosition.reset();
		mAnimateToTriggerPosition.setDuration(RETURN_TO_HEADER_DURATION);
		mAnimateToTriggerPosition.setAnimationListener(listener);
		mAnimateToTriggerPosition.setInterpolator(mDecelerateInterpolator);
		mTarget.startAnimation(mAnimateToTriggerPosition);
	}

	private void animateOffsetToStartPosition(int from, AnimationListener listener) {
		mFrom = from;
		mAnimateToStartPosition.reset();
		mAnimateToStartPosition.setDuration(RETURN_TO_TOP_DURATION);
		mAnimateToStartPosition.setAnimationListener(listener);
		mAnimateToStartPosition.setInterpolator(mDecelerateInterpolator);
		mTarget.startAnimation(mAnimateToStartPosition);
	}

	/**
	 * @return Whether it is possible for the child view of this layout to
	 * scroll up. Override this if the child view is a custom view.
	 */
	private boolean canViewScrollUp(View view, MotionEvent event) {
		boolean ret;

		event.offsetLocation(view.getScrollX() - view.getLeft(), view.getScrollY() - view.getTop());
		if (mScrollUpHandler != null) {
			boolean canViewScrollUp = mScrollUpHandler.canScrollUp(view);
			if (canViewScrollUp)
				return true;
		}

		if (android.os.Build.VERSION.SDK_INT < 14) {
			if (view instanceof AbsListView) {
				final AbsListView absListView = (AbsListView) view;
				ret = absListView.getChildCount() > 0
						&& (absListView.getFirstVisiblePosition() > 0 || absListView.getChildAt(0)
						.getTop() < absListView.getPaddingTop());
			} else {
				ret = view.getScrollY() > 0 || canChildrenScrollUp(view, event);
			}
		} else {
			ret = ViewCompat.canScrollVertically(view, -1) || canChildrenScrollUp(view, event);
		}
		if (DEBUG)
			Log.d(TAG, "canViewScrollUp " + view.getClass().getName() + " " + ret);
		return ret;
	}

	private boolean canChildrenScrollUp(View view, MotionEvent event) {
		if (view instanceof ViewGroup) {
			final ViewGroup viewgroup = (ViewGroup) view;
			int count = viewgroup.getChildCount();
			for (int i = 0; i < count; ++i) {
				View child = viewgroup.getChildAt(i);
				Rect bounds = new Rect();
				child.getHitRect(bounds);
				if (bounds.contains((int) event.getX(), (int) event.getY())) {
					return canViewScrollUp(child, event);
				}
			}
		}

		return false;
	}

	/**
	 * @param direction Negative to check scrolling left, positive to check scrolling right.
	 * @return Whether it is possible for the child view of this layout to
	 * scroll left or right. Override this if the child view is a custom view.
	 */
	private boolean canViewScrollHorizontally(View view, MotionEvent event, int direction) {
		boolean ret;
		event.offsetLocation(view.getScrollX() - view.getLeft(), view.getScrollY() - view.getTop());
		if (mScrollLeftOrRightHandler != null) {
			boolean canViewScrollLeftOrRight = mScrollLeftOrRightHandler.canScrollLeftOrRight(view, direction);
			if (canViewScrollLeftOrRight)
				return true;
		}
		if (android.os.Build.VERSION.SDK_INT < 14) {
			if (view instanceof ViewPager) {
				ret = ((ViewPager) view).canScrollHorizontally(direction);
			} else {
				ret = view.getScrollX() * direction > 0;
			}
		} else {
			ret = ViewCompat.canScrollHorizontally(view, direction);
		}

		ret = ret || canChildrenScrollHorizontally(view, event, direction);
		if (DEBUG)
			Log.d(TAG, "canViewScrollHorizontally " + view.getClass().getName() + " " + ret);
		return ret;
	}

	private boolean canChildrenScrollHorizontally(View view, MotionEvent event, int direction) {
		if (view instanceof ViewGroup) {
			final ViewGroup viewgroup = (ViewGroup) view;
			int count = viewgroup.getChildCount();
			for (int i = 0; i < count; ++i) {
				View child = viewgroup.getChildAt(i);
				Rect bounds = new Rect();
				child.getHitRect(bounds);
				if (bounds.contains((int) event.getX(), (int) event.getY())) {
					if (DEBUG)
						Log.d(TAG, "in child " + child.getClass().getName());
					return canViewScrollHorizontally(child, event, direction);
				}
			}
		}
		return false;
	}

	@Override
	public void onAttachedToWindow() {
		super.onAttachedToWindow();
		removeCallbacks(mCancel);
		removeCallbacks(mReturnToStartPosition);
	}

	@Override
	public void onDetachedFromWindow() {
		super.onDetachedFromWindow();
		removeCallbacks(mReturnToStartPosition);
		removeCallbacks(mCancel);
	}

	/**
	 * Set the listener to be notified when a refresh is triggered via the swipe
	 * gesture.
	 */
	public void setOnRefreshListener(OnRefreshListener listener) {
		mListener = listener;
	}

	// for headview
	private void setRefreshState(int state) {
		currentState.update(state, mCurrentTargetOffsetTop, mTriggerOffset);
		((CustomSwipeRefreshHeadLayout) mHeadView).onStateChange(currentState, lastState);
		lastState.update(state, mCurrentTargetOffsetTop, mTriggerOffset);
	}

	private void updateHeadViewState(boolean changeHeightOnly) {
		if (changeHeightOnly) {
			setRefreshState(currentState.getRefreshState());
		} else {
			if (mTarget.getTop() > mDistanceToTriggerSync) {
				setRefreshState(State.STATE_READY);
			} else {
				setRefreshState(State.STATE_NORMAL);
			}
		}
	}

	public void refreshComplete() {
		setRefreshing(false);
	}

	/**
	 * @return Whether the SwipeRefreshWidget is actively showing refresh
	 * progress.
	 */
	public boolean isRefreshing() {
		return mRefreshing;
	}

	/**
	 * Notify the widget that refresh state has changed. Do not call this when
	 * refresh is triggered by a swipe gesture.
	 *
	 * @param refreshing Whether or not the view should show refresh progress.
	 */
	protected void setRefreshing(boolean refreshing) {
		if (mRefreshing != refreshing) {
			ensureTarget();
			mRefreshing = refreshing;
			if (mRefreshing) {
				mReturnToTriggerPosition.run();

			} else {
				// keep refreshing state for refresh complete
				mRefreshing = true;
				removeCallbacks(mReturnToStartPosition);
				removeCallbacks(mCancel);
				animateStayComplete(mStayCompleteListener);
				setRefreshState(State.STATE_COMPLETE);
			}
		}
	}

	private View getContentView() {
		return getChildAt(0) == mHeadView ? getChildAt(1) : getChildAt(0);
	}

	private void ensureTarget() {
		// Don't bother getting the parent height if the parent hasn't been laid out yet.
		if (mTarget == null) {
			if (getChildCount() > 2 && !isInEditMode()) {
				throw new IllegalStateException(
						"CustomSwipeRefreshLayout can host ONLY one direct child");
			}
			mTarget = getContentView();
			mTargetOriginalTop = mTarget.getTop();
			int mOriginalOffsetBottom = mTargetOriginalTop + mTarget.getHeight();

			if (DEBUG) {
				Log.d(TAG, "mTargetOriginalTop = " + mTargetOriginalTop +
						", mOriginalOffsetBottom = " + mOriginalOffsetBottom);
			}
		}
		if (mDistanceToTriggerSync == -1) {
			if (getParent() != null && ((View) getParent()).getHeight() > 0) {
				mDistanceToTriggerSync = (int) Math.min(
						((View) getParent()).getHeight() * MAX_SWIPE_DISTANCE_FACTOR,
						mTriggerOffset + mTargetOriginalTop);

			}
		}
	}

	@Override
	protected void onLayout(boolean changed, int left, int top, int right, int bottom) {
		if (getChildCount() == 0) {
			return;
		}
		MarginLayoutParams lp = (MarginLayoutParams) mHeadView.getLayoutParams();
		final int headViewLeft = getPaddingLeft() + lp.leftMargin;
		final int headViewTop = mCurrentTargetOffsetTop - mHeadView.getMeasuredHeight() +
				getPaddingTop() + lp.topMargin;
		final int headViewRight = headViewLeft + mHeadView.getMeasuredWidth();
		final int headViewBottom = headViewTop + mHeadView.getMeasuredHeight();
		mHeadView.layout(headViewLeft, headViewTop, headViewRight, headViewBottom);
		if (DEBUG)
			Log.d(TAG, String.format("@@ onLayout() : mHeadview [%d,%d,%d,%d] ",
					headViewLeft, headViewTop, headViewRight, headViewBottom));

		final View content = getContentView();
		lp = (MarginLayoutParams) content.getLayoutParams();
		final int childLeft = getPaddingLeft() + lp.leftMargin;
		final int childTop = mCurrentTargetOffsetTop + getPaddingTop() + lp.topMargin;
		final int childRight = childLeft + content.getMeasuredWidth();
		final int childBottom = childTop + content.getMeasuredHeight();
		content.layout(childLeft, childTop, childRight, childBottom);
		if (DEBUG)
			Log.d(TAG, String.format("@@ onLayout() %d : content [%d,%d,%d,%d] ",
					getChildAt(0) == mHeadView ? 1 : 0, childLeft, childTop, childRight, childBottom));
	}

	@Override
	protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
		super.onMeasure(widthMeasureSpec, heightMeasureSpec);
		if (mHeadView == null) {
			mHeadView = new GameView(getContext());
			addView(mHeadView, new MarginLayoutParams(LayoutParams.MATCH_PARENT, getResources().getDimensionPixelOffset(R.dimen.game_height)));
		}

		if (getChildCount() > 2 && !isInEditMode()) {
			throw new IllegalStateException("CustomSwipeRefreshLayout can host one child content view.");
		}

		measureChildWithMargins(mHeadView, widthMeasureSpec, 0, heightMeasureSpec, 0);

		final View content = getContentView();
		if (getChildCount() > 0) {
			MarginLayoutParams lp = (MarginLayoutParams) content.getLayoutParams();
			content.measure(
					MeasureSpec.makeMeasureSpec(
							getMeasuredWidth() - getPaddingLeft() - getPaddingRight() -
									lp.leftMargin - lp.rightMargin,
							MeasureSpec.EXACTLY),
					MeasureSpec.makeMeasureSpec(
							getMeasuredHeight() - getPaddingTop() - getPaddingBottom() -
									lp.topMargin - lp.bottomMargin,
							MeasureSpec.EXACTLY));
		}

		if (DEBUG) {
			Log.d(TAG, String.format("onMeasure(): swiperefreshlayout: width=%d, height=%d",
					getMeasuredWidth(), getMeasuredHeight()));
			Log.d(TAG, String.format("onMeasure(): headview: width=%d, height=%d",
					mHeadView.getMeasuredWidth(), mHeadView.getMeasuredHeight()));
			Log.d(TAG, String.format("onMeasure(): content: width=%d, height=%d",
					content.getMeasuredWidth(), content.getMeasuredHeight()));
		}
	}

	@Override
	protected boolean checkLayoutParams(ViewGroup.LayoutParams p) {
		return p instanceof MarginLayoutParams;
	}

	@Override
	protected ViewGroup.LayoutParams generateDefaultLayoutParams() {
		return new MarginLayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT);
	}

	@Override
	protected ViewGroup.LayoutParams generateLayoutParams(ViewGroup.LayoutParams p) {
		return new MarginLayoutParams(p);
	}

	@Override
	public ViewGroup.LayoutParams generateLayoutParams(AttributeSet attrs) {
		return new MarginLayoutParams(getContext(), attrs);
	}

	@Override
	public void addView(View child, int index, LayoutParams params) {
		if (getChildCount() > 1 && !isInEditMode()) {
			throw new IllegalStateException("CustomSwipeRefreshLayout can host ONLY one child content view");
		}
		super.addView(child, index, params);
	}

	private boolean checkCanDoRefresh() {
		if (mRefreshCheckHandler != null) {
			return mRefreshCheckHandler.canRefresh();
		}
		return true;
	}

	@Override
	public boolean dispatchTouchEvent(MotionEvent event) {
		if (DEBUG)
			Log.d(TAG, "dispatchTouchEvent() start ");
		boolean ret = super.dispatchTouchEvent(event);
		if (event.getAction() == MotionEvent.ACTION_DOWN)
			ret = true;
		if (DEBUG)
			Log.d(TAG, "dispatchTouchEvent() " + ret);
		return ret;
	}

	@Override
	public boolean onInterceptTouchEvent(MotionEvent ev) {
		if (DEBUG)
			Log.d(TAG, "onInterceptTouchEvent() start " + ev);
		ensureTarget();
		boolean handled = false;
		float curY = ev.getY();

		if (!isEnabled()) {
			return false;
		}

		// record the first event:
		if (ev.getAction() == MotionEvent.ACTION_DOWN) {
			mDownEvent = MotionEvent.obtain(ev);
			mPrevY = mDownEvent.getY();
			mCheckValidMotionFlag = true;
			checkHorizontalMove = true;
		} else if (ev.getAction() == MotionEvent.ACTION_MOVE) {
			float yDiff = Math.abs(curY - mDownEvent.getY());

			if (enableHorizontalScroll) {

				MotionEvent event = MotionEvent.obtain(ev);
				int horizontalScrollDirection = ev.getX() > mDownEvent.getX() ? -1 : 1;
				float xDiff = Math.abs(ev.getX() - mDownEvent.getX());
				if (isHorizontalScroll) {
					if (DEBUG)
						Log.d(TAG, "onInterceptTouchEvent(): in horizontal scroll");
					mPrevY = curY;
					checkHorizontalMove = false;
					return false;
				} else if (xDiff <= mTouchSlop) {
					checkHorizontalMove = true;
					//return false;
				} else if (canViewScrollHorizontally(mTarget, event, horizontalScrollDirection) &&
						checkHorizontalMove && xDiff > 2 * yDiff) {
					if (DEBUG)
						Log.d(TAG, "onInterceptTouchEvent(): start horizontal scroll");
					mPrevY = curY;
					isHorizontalScroll = true;
					checkHorizontalMove = false;
					return false;
				} else {
					checkHorizontalMove = false;
				}
			}

			if (yDiff < mTouchSlop) {
				mPrevY = curY;
				return false;
			}
		} else if (ev.getAction() == MotionEvent.ACTION_UP) {
			float yDiff = Math.abs(curY - mDownEvent.getY());
			if (enableHorizontalScroll && isHorizontalScroll) {
				if (DEBUG)
					Log.d(TAG, "onInterceptTouchEvent(): finish horizontal scroll");
				isHorizontalScroll = false;
				mPrevY = ev.getY();
				return false;
			} else if (yDiff < mTouchSlop) {
				mPrevY = curY;
				return false;
			}
		}

		MotionEvent event = MotionEvent.obtain(ev);
		if (!mInReturningAnimation && !canViewScrollUp(mTarget, event)) {
			handled = onTouchEvent(ev);
			if (DEBUG)
				Log.d(TAG, "onInterceptTouchEvent(): handled = onTouchEvent(event);" + handled);
		} else {
			// keep updating last Y position when the event is not intercepted!
			mPrevY = ev.getY();
		}

		boolean ret = !handled ? super.onInterceptTouchEvent(ev) : handled;
		if (DEBUG)
			Log.d(TAG, "onInterceptTouchEvent() " + ret);
		return ret;
	}

	@Override
	public void requestDisallowInterceptTouchEvent(boolean b) {
		// Nope.
	}

	@Override
	public boolean onTouchEvent(MotionEvent event) {
		if (DEBUG)
			Log.d(TAG, "onTouchEvent() start");

		if (!isEnabled()) {
			return false;
		}

		final int action = event.getAction();
		boolean handled = false;
		int curTargetTop = mTarget.getTop();
		mCurrentTargetOffsetTop = curTargetTop - mTargetOriginalTop;
		switch (action) {

			case MotionEvent.ACTION_MOVE:
				if (mDownEvent != null && !mInReturningAnimation) {
					final float eventY = event.getY();
					float yDiff = eventY - mDownEvent.getY();

					boolean isScrollUp = eventY - mPrevY > 0;

					// if yDiff is large enough to be counted as one move event
					if (mCheckValidMotionFlag && (yDiff > mTouchSlop || yDiff < -mTouchSlop)) {
						mCheckValidMotionFlag = false;
					}
					// keep refresh head above mTarget when refreshing
					if (isRefreshing()) {
						mPrevY = event.getY();
						handled = false;
						break;
					}

					// curTargetTop is bigger than trigger
					if (curTargetTop >= mDistanceToTriggerSync) {
						// User movement passed distance; trigger a refresh
						removeCallbacks(mCancel);
					}
					// curTargetTop is not bigger than trigger
					else {
						// Just track the user's movement
						if (!isScrollUp && (curTargetTop < mTargetOriginalTop + 1)) {
							removeCallbacks(mCancel);
							mPrevY = event.getY();
							handled = false;
							break;
						} else {
							updatePositionTimeout(true);
						}

					}

					handled = true;
					if (curTargetTop >= mTargetOriginalTop && !isRefreshing())
						setTargetOffsetTop((int) ((eventY - mPrevY) * RESISTANCE_FACTOR), false);
					else
						setTargetOffsetTop((int) ((eventY - mPrevY)), true);
					mPrevY = event.getY();
				}

				break;
			case MotionEvent.ACTION_UP:
				if (mRefreshing) break;
				if (mCurrentTargetOffsetTop >= mTriggerOffset) {
					startRefresh();
				} else {
					updatePositionTimeout(false);
				}
				handled = true;
				break;

			case MotionEvent.ACTION_CANCEL:
				if (mDownEvent != null) {
					mDownEvent.recycle();
					mDownEvent = null;
				}
				break;
		}

		if (DEBUG)
			Log.d(TAG, "onTouchEvent() " + handled);
		return handled;
	}

	private void startRefresh() {
		if (!checkCanDoRefresh()) {
			updatePositionTimeout(false);
			return;
		}
		removeCallbacks(mCancel);
		setRefreshState(State.STATE_REFRESHING);
		setRefreshing(true);
		if (mListener != null)
			mListener.onRefresh();
	}

	private void updateContentOffsetTop(int targetTop, boolean changeHeightOnly) {
		final int currentTop = mTarget.getTop();
		if (targetTop < mTargetOriginalTop) {
			targetTop = mTargetOriginalTop;
		}
		setTargetOffsetTop(targetTop - currentTop, changeHeightOnly);
	}

	private void setTargetOffsetTop(int offset, boolean changeHeightOnly) {
		if (offset == 0)
			return;
		// check whether the mTarget total top offset is going to be smaller than 0
		if (mCurrentTargetOffsetTop + offset >= 0) {
			mTarget.offsetTopAndBottom(offset);
			mHeadView.offsetTopAndBottom(offset);
			mCurrentTargetOffsetTop += offset;
			invalidate();
		} else {
			updateContentOffsetTop(mTargetOriginalTop, changeHeightOnly);
		}
		updateHeadViewState(changeHeightOnly);
	}

	private void updatePositionTimeout(boolean isDelayed) {
		removeCallbacks(mCancel);
		postDelayed(mCancel, isDelayed ? RETURN_TO_ORIGINAL_POSITION_TIMEOUT : 0);
	}

	public void setEnableHorizontalScroll(boolean isEnable) {
		enableHorizontalScroll = isEnable;
	}

	public void setScroolUpHandler(ScrollUpHandler handler) {
		mScrollUpHandler = handler;
	}

	public void setScroolLeftOrRightHandler(ScrollLeftOrRightHandler handler) {
		mScrollLeftOrRightHandler = handler;
	}

	public void setRefreshCheckHandler(RefreshCheckHandler handler) {
		mRefreshCheckHandler = handler;
	}

	/**
	 * Classes that wish to be notified when the swipe gesture correctly
	 * triggers a refresh should implement this interface.
	 */
	public interface OnRefreshListener {
		void onRefresh();
	}

	/**
	 * Classes that checking whether refresh can be triggered
	 */
	public interface RefreshCheckHandler {
		boolean canRefresh();
	}

	public interface ScrollUpHandler {
		boolean canScrollUp(View view);
	}

	public interface ScrollLeftOrRightHandler {
		boolean canScrollLeftOrRight(View view, int direction);
	}

	/**
	 * Classes that must be implemented by for custom headview
	 */
	public interface CustomSwipeRefreshHeadLayout {
		void onStateChange(State currentState, State lastState);
	}

	/**
	 * Refresh state
	 */
	public static class State {
		public final static int STATE_NORMAL = 0;
		public final static int STATE_READY = 1;
		public final static int STATE_REFRESHING = 2;
		public final static int STATE_COMPLETE = 3;

		/**
		 * detailed refresh state code
		 */
		private int refreshState = STATE_NORMAL;

		/**
		 * scroll distance relative to refresh trigger distance
		 * percent = top / trigger;
		 */
		private float percent;

		/**
		 * distance from header top to parent top.
		 */
		private int headerTop;

		/**
		 * distance from header top to parent top to trigger refresh
		 */
		private int trigger;

		public State(int refreshState) {
			this.refreshState = refreshState;
		}

		void update(int refreshState, int top, int trigger) {
			this.refreshState = refreshState;
			this.headerTop = top;
			this.trigger = trigger;
			this.percent = (float) top / trigger;
		}

		public int getRefreshState() {
			return refreshState;
		}

		public float getPercent() {
			return percent;
		}
	}

	/**
	 * Simple AnimationListener to avoid having to implement unneeded methods in
	 * AnimationListeners.
	 */
	private class BaseAnimationListener implements AnimationListener {
		@Override
		public void onAnimationStart(Animation animation) {
		}

		@Override
		public void onAnimationEnd(Animation animation) {
		}

		@Override
		public void onAnimationRepeat(Animation animation) {
		}
	}
}


text:
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
  <component name="Behat">
    <behat_settings>
      <BehatSettings behat_path="$PROJECT_DIR$" />
    </behat_settings>
  </component>
  <component name="PhpProjectSharedConfiguration" php_language_level="5.5.0" />
  <component name="PhpUnit">
    <phpunit_settings>
      <PhpUnitSettings load_method="CUSTOM_LOADER" custom_loader_path="$PROJECT_DIR$/vendor/autoload.php" phpunit_phar_path="" />
    </phpunit_settings>
  </component>
</project>

redpajama_set_name: RedPajamaGithub


text:
package tk.mybatis.springboot.model;

/**
 * Created by GLS on 2016/10/12.
 */
public class WpPost extends BaseEntity{
    private String postTitle;
    private String postContent;
    private String urlencodePostName;

    public String getPostTitle() {
        return postTitle;
    }

    public void setPostTitle(String postTitle) {
        this.postTitle = postTitle;
    }

    public String getPostContent() {
        return postContent;
    }

    public void setPostContent(String postContent) {
        this.postContent = postContent;
    }

    public String getUrlencodePostName() {
        return urlencodePostName;
    }

    public void setUrlencodePostName(String urlencodePostName) {
        this.urlencodePostName = urlencodePostName;
    }
}


text:
const { MongoClient } = require("mongodb");
const _ = require("lodash");
const config = require("./config");

module.exports = {
  async connect() {
    const configContent = await config.read();
    const url = _.get(configContent, "mongodb.url");
    const databaseName = _.get(configContent, "mongodb.databaseName");
    const options = _.get(configContent, "mongodb.options");

    if (!url) {
      throw new Error("No `url` defined in config file!");
    }

    const client = await MongoClient.connect(
      url,
      options
    );

    const db = client.db(databaseName);
    db.close = client.close;
    return {
      client,
      db,
    };
  }
};


text:
class WindowManager
{
public:
	static WindowManager* getInstance();
	SDL_Renderer * getRenderer();
	SDL_Window* createWindow(std::string name, int xpos, int ypos, int w, int h, Uint32 windowFlags, Uint32 renderFlags);
private:
	SDL_Window* gWindow;
	SDL_Renderer* gRenderer;
	static WindowManager* gInstance;
	WindowManager();

	~WindowManager();
};
#endif


text:
const AWS          = require('aws-sdk');
const fs           = require('fs-extra');
const path         = require('path');
const async        = require('async');
const chalk        = require('chalk');
const recursive    = require('recursive-readdir');
const gulp         = require('gulp');
const install      = require('gulp-install');
const fancy        = require('fancy-log');
const next         = require('gulp-next');
const glob         = require('glob');

let data = {
  folderPath: null,   //e.g. ./functions/hello-world
  distPath: null,     //e.g. ./dist/hello-world
  environment: null   //e.g. staging
};

const getIdentity = (callback) => {
  const sts = new AWS.STS();
  sts.getCallerIdentity({}, (err, result) => {
    if (err) return callback(err);
    data.accountId = result.Account;
    callback(null);
  })
};

const clean = (callback) => {
  fancy.info('clean...');

  fs.remove(path.join(process.cwd(), 'dist'), (err) => {
    if (err) return callback(err);
    fs.ensureDir(data.distPath, (err) => callback(err));
  });
};

const npm = (callback) => {
  fancy.info('npm...');

  if (data.localNodeModules) {
    fancy.info('copying NPM modules for deployment...');
    fs.copySync(
      path.join(process.cwd(), 'node_modules'),
      path.join(data.distPath, 'node_modules')
    );
    callback(null);
  }
  else {
    fancy.info('...creating package.json for installing package dependencies...');
    let pkg = require(path.join(process.cwd(), 'package.json'));
    // search for `require` statements in function file to determine what packages are needed at runtime
    let re = /require\(["'].*["']\)/g;
    let functionFile = path.join(data.folderPath, data.functionName + '.js');
    let text = fs.readFileSync(functionFile, {encoding:'utf-8'});
    let reqs = text.match(re);
    let dependencies = {};

    reqs.forEach(function (r) {
      let m = r.replace(/\'/g, '').replace(/\"/g, '').replace('require(', '').replace(')', '');
      if (pkg.dependencies[m]) {
        dependencies[m] = pkg.dependencies[m];
      }
    });

    fs.ensureDirSync(data.distPath);
    let packagePath = path.join(data.distPath, 'package.json');
    let packages = {dependencies: dependencies};
    fs.writeFileSync(packagePath, JSON.stringify(packages, null, 2));
    fancy.info('installing function packages from NPM...');
    return gulp.src(packagePath)
      .pipe(install({ production: true }))
      .pipe(next(function() {
        callback(null);
      }));
  }
};

const envFile = (callback) => {
  fancy.info('checking for .env file for:', data.environment);
  //concat environment specific .env file if there is one
  let targetedEnv = path.join(data.folderPath, '.env.' + data.environment);
  let finalEnv = path.join(data.distPath, '.env');
  let hasTargetedEnv = fs.existsSync(targetedEnv);

  if (!hasTargetedEnv) {
    fancy.info('no .env found for ' + data.environment);
    return callback(null);
  }
  else {
    fancy.info('found .env.' + data.environment);
    fs.copy(targetedEnv, finalEnv, callback);
    // fs.createReadStream(targetedEnv).pipe(fs.createWriteStream(finalEnv));
    // callback(null);
  }
};

const copyFiles = (callback) => {
  fancy.info('copyFiles...');

  if (!data.dependencies) return callback(null);

  data.globs = [];

  for(let dependency of data.dependencies) {

    let functionDependency = path.join(data.folderPath, dependency);
    let globalDependency = path.join(data.globalDependenciesDir, dependency);

    if (glob.hasMagic(dependency)) {
      data.globs.push(dependency);
    }
    else {
      //look in function directory for file
      if (fs.existsSync(functionDependency)) {
        fancy.info('Using locally provided dependency:', functionDependency);
        fs.copySync(functionDependency, path.join(data.distPath, dependency));
      }
      //look in global dependencies folder
      else if (fs.existsSync(globalDependency)) {
        fancy.info('Using global dependency:', globalDependency);
        fs.copySync(globalDependency, path.join(data.distPath, dependency));
      }
    }
  }

  callback(null);
};

const processGlobs = (callback) => {
  fancy.info('processGlobs...');

  async.each(data.globs, (spec, globCallback) => {

    let functionDependency = path.join(data.folderPath, spec);
    let globalDependency = path.join(data.globalDependenciesDir, spec);

    glob(functionDependency, (err, matches) => {
      if (err) return globCallback(err);

      //for each file found in the glob...
      async.each(matches, (match, matchesCallback) => {

        fs.lstat(match, (err, stat) => {
          if (err) return matchesCallback(err);

          if (stat.isFile()) {
            let targetPath = path.join(data.distPath, match.replace(data.folderPath, ''));
            fs.ensureDir(path.dirname(targetPath), (err) => {
              if (err) return matchesCallback(err);

              fancy.info(targetPath);
              fs.copy(match, targetPath, matchesCallback);
            });
          }
          else {
            matchesCallback();
          }

        });

      }, (err) => {
        if (err) globCallback(err);
        else globCallback();
      });

    });

  }, (err) => {
    if (err) callback(err);
    else callback(null);
  });
};

const copySettings = (callback) => {
  //settings
  let settingsFile =  data.folderPath + '/settings';
  if (!data.envPrefixes) settingsFile += '.json';
  else settingsFile += '-' + data.environment + '.json';
  fancy.info('settings file:', settingsFile);

  if (fs.existsSync(settingsFile)) {
    //read settings file for environment
    let s = JSON.parse(fs.readFileSync(settingsFile, {encoding:'utf8'}));
    //add "env"
    s.env = data.environment;
    //write to settings.json
    fancy.info('write settings-' + data.environment + '.json to settings.json');
    try {
      fs.writeFileSync(path.join(data.runDir, 'settings.json'), JSON.stringify(s, null, 2), {encoding: 'utf8'});
      fs.writeFileSync(path.join(data.distPath, 'settings.json'), JSON.stringify(s, null, 2), {encoding: 'utf8'});
    }
    catch(err) {}
  }

  callback(null);
}

const copyFunction = (callback) => {
  fancy.info('copyFunction...');

  let functionFile = path.join(data.folderPath, data.functionName + '.js');
  let outputFile = path.join(data.distPath, data.functionName + '.js');

  // copy function itself
  fancy.info('copying function:', functionFile);
  fs.copySync(functionFile, outputFile);

  callback(null);
};

const zipFiles = (callback) => {
  fancy.info('zipFiles...');

  if (process.platform !== 'win32') {
    //use native zip
    let cmd = 'zip -r ' + data.distPath + '.zip' + ' .';
    let exec = require('child_process').exec;

    exec(cmd, {
      cwd: data.distPath,
      maxBuffer: 50 * 1024 * 1024
    }, function (err) {
      if (err) return callback(err);
      else return callback(null);
    });
  }
  else {
    //use npm lib for zipping
    // NODE-ZIP
    let zip = new require('node-zip')();
    let search = data.distPath;
    recursive(search, function(err, files) {

      files.forEach(function(file) {
        let path = file.substring(file.indexOf(search) + search.length + 1);
        if (fs.lstatSync(file).isFile()) {
          zip.file(path, fs.readFileSync(file));
        }
      });

      let buffer = zip.generate({type: 'nodebuffer', compression: 'DEFLATE'});

      fs.writeFile(data.distPath + '.zip', buffer, function(err) {
        if (err) callback(err)
        else callback(null);
      });

    });

  }
};

const runFunction = (callback) => {
  fancy.info('runFunction...');

  let startTime = new Date();
  let timeout;

  console.log('data.runDir', data.runDir);
  var functionFile = path.join(data.runDir, data.functionName + '.js');
  if (!fs.existsSync(functionFile)) {
    console.log('Could not find function:', functionFile);
    console.log('Make sure you are using `lamb run` from your project root directory.');
    process.exit();
  }

  let funcData = require(path.join(data.folderPath, 'lambinator.json'));
  timeout = funcData.timeout ? (funcData.timeout * 1000) : 300000;

  //change working directory
  if (!fs.existsSync(data.runDir)) {
    console.log('Could not find a function to run at:', data.runDir);
    console.log('Make sure you are using `lamb run` from your project root directory.');
    process.exit();
  }

  console.log('Changing working directory to:', data.runDir);
  process.chdir(data.runDir);

  //set env for lambinator
  process.env.lambinator = true;

  //mock context
  let context = {

    done: function(error, data) {
      if (error) {
        console.log(chalk.red('error running function'), error);
        process.exit(1);
      }
      else {
        console.log(chalk.green('function ran and returned:'), data);
        process.exit(0);
      }
    },

    fail: function(error) {
      console.log(chalk.red('error running function'), error);
      process.exit(1);
    },

    succeed: function (data) {
      console.log(chalk.green('function ran and returned:'), data);
      process.exit(0);
    },

    getRemainingTimeInMillis: function () {
      return timeout - ((new Date) - startTime);
    }
  };

  //custom script?
  if (funcData.customScript) {
    try {
      //call custom script and pass in mock context
      console.log('working dir:', process.cwd());
      let reqScript = process.cwd() + '/' + funcData.customScript;
      console.log('requiring script:', reqScript);
      require(reqScript)(context);
    }
    catch(err) {
      context.fail(err);
    }
  }
  else {
    //get mock event
    let evt = funcData.testEvents[data.testEvent || funcData.defaultEvent];
    if (!evt) {
      console.log('Could not find a mock event named "' + (testEvent || funcData.defaultEvent) + '"');
      process.exit();
    }
    fancy.info('mock event:', evt);

    //spin it up using mock event
    fancy.info('running function...');
    try {
      let funcToRun = require(process.cwd() + '/' + data.functionName);
      funcToRun.handler(evt, context, context.done);
    }
    catch (err) {
      fancy.info(chalk.red('error running function'));
      console.log();
      console.log((err.stack) ? err.stack : err.toString());
      console.log();
    }
  }
}

const uploadS3 = (callback) => {
  const bucketName = process.env.LAMBINATOR_BUCKET;
  if (!bucketName) callback(new Error('LAMBINATOR_BUCKET environment variable must be defined'));
  const lambinatorKeyPrefix = process.env.LAMBINATOR_KEY_PREFIX ? process.env.LAMBINATOR_KEY_PREFIX + '/' : '';
  const key = `${lambinatorKeyPrefix}${functionName}/${env}/${version}/package.zip`
};

const upload = (callback) => {
  fancy.info('upload...');

  const functionName = data.envPrefixes ? data.environment + '-' + data.functionName : data.functionName;
  data.functionArn = `arn:aws:lambda:${data.region}:${data.accountId}:function:${functionName}`;

  // for backwards compatibility, see if roleArn is already specified
  if (!data.roleArn && data.roleName) {
    data.roleArn = `arn:aws:iam::${data.accountId}:role/${data.roleName}`;
  }

  //set region from lambinator.config:region
  AWS.config.update({region:data.region});
  AWS.config.apiVersions = {lambda: '2015-03-31'};
  const lambda = new AWS.Lambda();

  let zipFile = data.distPath + '.zip';

  let createLambda = function() {
    fancy.info('Updating function ' + functionName);

    let params = {
      Code: {
        ZipFile: fs.readFileSync(zipFile)
      },
      FunctionName: functionName,
      Handler: data.handler,
      Role: data.roleArn,
      Runtime: data.runtime || 'nodejs12.x',
      Description: data.description,
      MemorySize: data.memorySize,
      Timeout: data.timeout
    };

    if (data.VpcConfig) params.VpcConfig = data.VpcConfig;

    lambda.createFunction(params, function(err, result) {
      if (err) {
        fancy.info(chalk.red('Error uploading ' + data.functionName), err);
        callback(err);
      }
      else  {
        callback(null);
      }
    });
  }

  let updateLambda = () => {
    let params = {
      FunctionName: functionName,
      ZipFile: fs.readFileSync(zipFile)
    };

    fancy.info('Updating function ' + functionName + ' from ' + zipFile);

    lambda.updateFunctionCode(params, function(err, result) {
      if (err) {
        fancy.info(chalk.red('Error uploading ' + functionName), err);
        callback(err);
      }
      else {

        let configParams = {
          FunctionName: functionName,
          Handler: data.handler,
          Role: data.roleArn,
          Runtime: data.runtime || 'nodejs12.x',
          Description: data.description,
          MemorySize: data.memorySize,
          Timeout: data.timeout
        };

        if (data.VpcConfig) configParams.VpcConfig = data.VpcConfig;

        // console.log('configParams', configParams);

        lambda.updateFunctionConfiguration(configParams, function(err, data) {
          if (err) {
            fancy.info(chalk.red('Error updating function config for ' + functionName), err);
            callback(err);
          }
          else callback(null);
        });
      }
    });
  }

  const startUpload = () => {
    fancy.info('Getting current lambda function info (if any)...');
    lambda.getFunction({FunctionName: functionName}, function(err, result) {
      if (err) {
        if (err.statusCode === 404) {
          //function doesn't exist yet -- call lambda.createFunction to create it
          createLambda();
        }
        else {
          let warning = 'AWS API request failed. '
          warning += 'Check your AWS credentials and permissions.'
          fancy.info(chalk.yellow(warning), JSON.stringify(lambda, null, 2));
          callback(new Error(warning));
        }
      }
      else {
        //function already exists -- upload latest version
        updateLambda();
      }
    });
  };

  startUpload();
};

const createSns = (callback) => {
  if (!data.snsTopic) return callback(null);

  // create topic if it does not exist
  const sns = new AWS.SNS();
  const topicName = data.envPrefixes ? data.environment + '-' + data.snsTopic : data.snsTopic;
  data.topicArn = `arn:aws:sns:${data.region}:${data.accountId}:${topicName}`;

  sns.getTopicAttributes({TopicArn: data.topicArn}, (err, topic) => {
    if (err) {
      if (err.statusCode == '404') {
        console.log('Creating SNS topic:', data.topicArn);
        sns.createTopic({Name: topicName}, (err, topic) => {
          if (err) return callback(err);
          console.log('Topic created:', topic);
          return callback(null);
        });
      }
      else {
        return callback(err);
      }
    }
    else {
      console.log('SNS topic exists:', data.topicArn);
      return callback(null);
    }
  });
};

const wireSns = (callback) => {
  if (!data.snsTopic) return callback(null);

  console.log('checking for SNS topic subscription...');
  const sns = new AWS.SNS();
  const subscribeFunction = (cb) => {
    const subscribeParams = {
      TopicArn: data.topicArn,
      Protocol: 'lambda',
      Endpoint: data.functionArn
    };

    sns.subscribe(subscribeParams, (err, result) => {
      if(err) return cb(err);
      else return cb(null);
    });
  };

  sns.listSubscriptionsByTopic({TopicArn: data.topicArn}, (err, result) => {
    if (err) return callback(err);
    if(result.Subscriptions.length == 0) {
      console.log('No subscription yet -- subscribing...');
      subscribeFunction(callback);
    }
    else {
      // see if this function is in the list of subscribers
      const exists = (result.Subscriptions.filter(f => f.Endpoint == data.functionArn).length == 1);
      if (exists) {
        console.log('Subscription exists.');
        return callback(null);
      }
      else {
        console.log('No subscription yet -- subscribing...');
        subscribeFunction(callback);
      }
    }
  });
};

const foo = (callback) => {
  fancy.info('foo');
  callback();
}

const main = (functionName, environment, options) => {
  fancy.info('main...');

  let folderPath = path.join(process.cwd(), '/functions', '/' + functionName);
  let action = options.action;

  //set up global data
  data = JSON.parse(fs.readFileSync(path.join(folderPath, 'lambinator.json'), {encoding:'utf-8'}));
  data.functionName = functionName;
  data.folderPath = folderPath;
  data.runDir = data.folderPath;
  data.distPath = path.join(process.cwd(), '/dist', functionName);
  data.environment = !data.envPrefixes ? 'production' : environment;
  data.localNodeModules = (options && options.localNodeModules) || false;
  data.globalDependenciesDir = path.resolve(path.dirname(fs.realpathSync(__filename)), '../dependencies');
  if (data.options && data.options.testEvent) data.testEvent = data.options.testEvent;

  if (data.testEvents) delete data.testEvents;
  if (data.defaultEvent) delete data.defaultEvent;
  if (data.defaultEnv) delete data.defaultEnv;

  fancy.info('data', data);

  let functionsToRun;
  switch(action) {
    case 'upload':
      functionsToRun = [upload];
      break;
    case 'run':
      functionsToRun = [copySettings, runFunction];
      break;
    case 'zip':
      functionsToRun = [envFile, npm, copyFiles, processGlobs, copySettings, copyFunction, zipFiles];
      break;
    case 'deploy':
      functionsToRun = [getIdentity, envFile, npm, copyFiles, processGlobs, copySettings, copyFunction, zipFiles, upload, createSns, wireSns]; //, zipFiles];
      break;
    case 'clean':
      functionsToRun = [clean];
      break;
    default:
      break;
  }

  //let the water fall baby
  async.waterfall(functionsToRun, function(err, results) {
    if (err) {
      fancy.info('ERROR', err);
    }
    else {
      fancy.info('Done!');
    }
  });
};

module.exports = main;


text:
/* globals $ */
/* globals window */

hqDefine('app_manager/js/preview_app.js', function() {
    'use strict';
    var module = {};
    var _private = {};

    module.SELECTORS = {
        BTN_TOGGLE_PREVIEW: '.js-preview-toggle',
        PREVIEW_WINDOW: '#js-appmanager-preview',
        PREVIEW_WINDOW_IFRAME: '#js-appmanager-preview iframe',
        APP_MANAGER_BODY: '#js-appmanager-body',
        PREVIEW_ACTION_TEXT_SHOW: '.js-preview-action-show',
        PREVIEW_ACTION_TEXT_HIDE: '.js-preview-action-hide',
    };

    module.EVENTS = {
        RESIZE: 'previewApp.resize',
    };

    module.POSITION = {
        FIXED: 'fixed',
        ABSOLUTE: 'absolute',
    };

    module.DATA = {
        OPEN: 'isopen',
        POSITION: 'position',
    };

    _private.showAppPreview = function() {
        $(module.SELECTORS.PREVIEW_ACTION_TEXT_SHOW).addClass('hide');
        $(module.SELECTORS.PREVIEW_ACTION_TEXT_HIDE).removeClass('hide');
    };
    _private.hideAppPreview = function() {
        $(module.SELECTORS.PREVIEW_ACTION_TEXT_SHOW).removeClass('hide');
        $(module.SELECTORS.PREVIEW_ACTION_TEXT_HIDE).addClass('hide');
    };

    _private.navigateBack = function() {
        var $appPreviewIframe = $(module.SELECTORS.PREVIEW_WINDOW_IFRAME),
            previewWindow = $appPreviewIframe[0].contentWindow;
        previewWindow.postMessage({
            action: 'back',
        }, window.location.origin);
    };

    _private.toggleAppPreview = function (e) {
        e.preventDefault();
        if (localStorage.getItem(module.DATA.OPEN) === module.DATA.OPEN) {
            localStorage.removeItem(module.DATA.OPEN);
        } else {
            localStorage.setItem(module.DATA.OPEN, module.DATA.OPEN);
        }
        $(window).trigger(module.EVENTS.RESIZE);
        if (localStorage.getItem(module.DATA.OPEN)) {
            _private.showAppPreview();
        } else {
            _private.hideAppPreview();
        }
    };

    module.initPreviewWindow = function (layoutController) {

        var $appPreview = $(module.SELECTORS.PREVIEW_WINDOW),
            $appBody = $(module.SELECTORS.APP_MANAGER_BODY),
            $togglePreviewBtn = $(module.SELECTORS.BTN_TOGGLE_PREVIEW),
            $messages = $(layoutController.selector.messages);

        $appPreview.data(module.DATA.POSITION, module.POSITION.FIXED);

        if (localStorage.getItem(module.DATA.OPEN)) {
            _private.showAppPreview();
        } else {
            _private.hideAppPreview();
        }

        $togglePreviewBtn.click(_private.toggleAppPreview);

        var _resizeAppPreview = function () {
            $appPreview.height($(window).outerHeight() + 'px');

            if (localStorage.getItem(module.DATA.OPEN)) {
                $appPreview.addClass('open');
                if ($('#formdesigner').length === 0) $appBody.addClass('offset-for-preview');
                $messages.addClass('offset-for-preview');
            } else {
                $appPreview.removeClass('open');
                if ($('#formdesigner').length === 0) $appBody.removeClass('offset-for-preview');
                $messages.removeClass('offset-for-preview');
            }

            var $nav = $(layoutController.selector.navigation);

            var maxHeight = $appPreview.find('.preview-phone-container').outerHeight() + $nav.outerHeight() + 80;
            if (($(window).height() <  maxHeight
                && $appPreview.data(module.DATA.POSITION) === module.POSITION.FIXED)
            ) {
                $appPreview.data(module.DATA.POSITION, module.POSITION.ABSOLUTE);
                $appPreview.addClass('small-height');
            } else if ($(window).height() >=  maxHeight
                && $appPreview.data(module.DATA.POSITION) === module.POSITION.ABSOLUTE) {
                $appPreview.data(module.DATA.POSITION, module.POSITION.FIXED);
                $appPreview.removeClass('small-height');
            }

            $(module.SELECTORS.BTN_TOGGLE_PREVIEW).fadeIn(500);

        };
        $(window).on(module.EVENTS.RESIZE, _resizeAppPreview);
        layoutController.utils.setBalancePreviewFn(_resizeAppPreview);
        $('.js-preview-back').click(_private.navigateBack);

    };

    module.prependToggleTo = function (selector, layout, attempts) {
        attempts = attempts || 0;
        if ($(selector).length) {
            var $toggleParent = $(selector);
            $toggleParent.prepend(layout);
            $toggleParent.find(module.SELECTORS.BTN_TOGGLE_PREVIEW).click(_private.toggleAppPreview);
            if (localStorage.getItem(module.DATA.OPEN)) {
                _private.showAppPreview();
            } else {
                _private.hideAppPreview();
            }
        } else if (attempts <= 30) {
            // give up appending element after waiting 30 seconds to load
            setTimeout(function () {
                module.prependToggleTo(selector, layout, attempts++);
            }, 1000);
        }
    };

    return module;
});


text:
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
	<modelVersion>4.0.0</modelVersion>
	<parent>
		<groupId>org.springframework.boot</groupId>
		<artifactId>spring-boot-starter-parent</artifactId>
		<version>1.4.0.RELEASE</version>
	</parent>
	<groupId>de.schaeftlein.microservices</groupId>
	<artifactId>sample-microservice</artifactId>
	<version>0.0.1-SNAPSHOT</version>
	<packaging>pom</packaging>
	<description>Parent POM for microservices with spring boot</description>
	<properties>
		<!-- Java Version -->
		<java.version>1.8</java.version>
		<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
		<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
		<maven.compiler.source>1.8</maven.compiler.source>
		<maven.compiler.target>1.8</maven.compiler.target>
	</properties>
	<licenses>
		<license>
			<name>Apache License, Version 2.0</name>
			<url>https://www.apache.org/licenses/LICENSE-2.0</url>
			<distribution>manual</distribution>
		</license>
	</licenses>
	<distributionManagement>
		<repository>
			<id>releases</id>
			<url>http://t60p:9081/nexus/content/repositories/releases</url>
		</repository>
		<snapshotRepository>
			<id>snapshots</id>
			<url>http://t60p:9081/nexus/content/repositories/snapshots</url>
		</snapshotRepository>
	</distributionManagement>
	<developers>
		<developer>
			<name>Ralf Schäftlein</name>
			<roles>
				<role>Developer</role>
			</roles>
		</developer>
	</developers>
	<dependencies>
		<!-- monitoring -->
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-actuator</artifactId>
		</dependency>
		<!-- Tests -->
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-test</artifactId>
			<scope>test</scope>
		</dependency>
	</dependencies>
	<build>
		<plugins>
			<plugin>
				<groupId>org.springframework.boot</groupId>
				<artifactId>spring-boot-maven-plugin</artifactId>
			</plugin>
		</plugins>
	</build>
	<modules>
		<module>aquarium-water-quality-service</module>
	</modules>
</project>


text:
/* $Id: audiodev.h 5255 2016-03-10 05:02:07Z ming $ */
/*
 * Copyright (C) 2008-2011 Teluu Inc. (http://www.teluu.com)
 * Copyright (C) 2003-2008 Benny Prijono <benny@prijono.org>
 *
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 2 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
 */
#ifndef __PJMEDIA_AUDIODEV_AUDIODEV_H__
#define __PJMEDIA_AUDIODEV_AUDIODEV_H__

/**
 * @file audiodev.h
 * @brief Audio subsystem API.
 */
#include <VialerPJSIP/pj/pool.h>
#include <VialerPJSIP/pjmedia/audiodev.h>

PJ_BEGIN_DECL

/**
 * @defgroup s2_audio_device_reference Audio Subsystem API Reference
 * @ingroup audio_subsystem_api
 * @brief API Reference
 * @{
 */

/**
 * Initialize the audio subsystem. This will register all supported audio
 * device factories to the audio subsystem. This function may be called
 * more than once, but each call to this function must have the
 * corresponding #pjmedia_aud_subsys_shutdown() call.
 *
 * @param pf		The pool factory.
 *
 * @return		PJ_SUCCESS on successful operation or the appropriate
 *			error code.
 */
PJ_DECL(pj_status_t) pjmedia_aud_subsys_init(pj_pool_factory *pf);

/**
 * Get the pool factory registered to the audio subsystem.
 *
 * @return		The pool factory.
 */
PJ_DECL(pj_pool_factory*) pjmedia_aud_subsys_get_pool_factory(void);

/**
 * Shutdown the audio subsystem. This will destroy all audio device factories
 * registered in the audio subsystem. Note that currently opened audio streams
 * may or may not be closed, depending on the implementation of the audio
 * device factories.
 *
 * @return		PJ_SUCCESS on successful operation or the appropriate
 *			error code.
 */
PJ_DECL(pj_status_t) pjmedia_aud_subsys_shutdown(void);

/**
 * Register a supported audio device factory to the audio subsystem. This
 * function can only be called after calling #pjmedia_aud_subsys_init().
 *
 * @param adf		The audio device factory.
 *
 * @return		PJ_SUCCESS on successful operation or the appropriate
 *			error code.
 */
PJ_DECL(pj_status_t)
pjmedia_aud_register_factory(pjmedia_aud_dev_factory_create_func_ptr adf);

/**
 * Unregister an audio device factory from the audio subsystem. This
 * function can only be called after calling #pjmedia_aud_subsys_init().
 * Devices from this factory will be unlisted. If a device from this factory
 * is currently in use, then the behavior is undefined.
 *
 * @param adf		The audio device factory.
 *
 * @return		PJ_SUCCESS on successful operation or the appropriate
 *			error code.
 */
PJ_DECL(pj_status_t)
pjmedia_aud_unregister_factory(pjmedia_aud_dev_factory_create_func_ptr adf);

/**
 * @}
 */

PJ_END_DECL

#endif	/* __PJMEDIA_AUDIODEV_AUDIODEV_H__ */


text:
package apple.uikit;

import apple.NSObject;
import apple.foundation.NSArray;
import apple.foundation.NSMethodSignature;
import apple.foundation.NSSet;
import apple.foundation.struct.NSRange;
import org.moe.natj.c.ann.FunctionPtr;
import org.moe.natj.general.NatJ;
import org.moe.natj.general.Pointer;
import org.moe.natj.general.ann.ByValue;
import org.moe.natj.general.ann.Generated;
import org.moe.natj.general.ann.Library;
import org.moe.natj.general.ann.Mapped;
import org.moe.natj.general.ann.NInt;
import org.moe.natj.general.ann.NUInt;
import org.moe.natj.general.ann.Owned;
import org.moe.natj.general.ann.Runtime;
import org.moe.natj.general.ptr.VoidPtr;
import org.moe.natj.objc.Class;
import org.moe.natj.objc.ObjCRuntime;
import org.moe.natj.objc.SEL;
import org.moe.natj.objc.ann.ObjCClassBinding;
import org.moe.natj.objc.ann.Selector;
import org.moe.natj.objc.map.ObjCObjectMapper;

/**
 * A UITextChecker object is used by a client (e.g. a document in an application) to check a given NSString. Generally
 * one UITextChecker instance should be created per document. Multiple related pieces of text may share a single
 * UITextChecker instance, if they are intended to share ignored words and other similar state.
 */
@Generated
@Library("UIKit")
@Runtime(ObjCRuntime.class)
@ObjCClassBinding
public class UITextChecker extends NSObject {
    static {
        NatJ.register();
    }

    @Generated
    protected UITextChecker(Pointer peer) {
        super(peer);
    }

    @Generated
    @Selector("accessInstanceVariablesDirectly")
    public static native boolean accessInstanceVariablesDirectly();

    @Generated
    @Owned
    @Selector("alloc")
    public static native UITextChecker alloc();

    @Owned
    @Generated
    @Selector("allocWithZone:")
    public static native UITextChecker allocWithZone(VoidPtr zone);

    @Generated
    @Selector("automaticallyNotifiesObserversForKey:")
    public static native boolean automaticallyNotifiesObserversForKey(String key);

    /**
     * Entries in the availableLanguages list are all available spellchecking languages in user preference order,
     * usually language abbreviations such as en_US.
     */
    @Generated
    @Selector("availableLanguages")
    public static native NSArray<String> availableLanguages();

    @Generated
    @Selector("cancelPreviousPerformRequestsWithTarget:")
    public static native void cancelPreviousPerformRequestsWithTarget(@Mapped(ObjCObjectMapper.class) Object aTarget);

    @Generated
    @Selector("cancelPreviousPerformRequestsWithTarget:selector:object:")
    public static native void cancelPreviousPerformRequestsWithTargetSelectorObject(
            @Mapped(ObjCObjectMapper.class) Object aTarget, SEL aSelector,
            @Mapped(ObjCObjectMapper.class) Object anArgument);

    @Generated
    @Selector("classFallbacksForKeyedArchiver")
    public static native NSArray<String> classFallbacksForKeyedArchiver();

    @Generated
    @Selector("classForKeyedUnarchiver")
    public static native Class classForKeyedUnarchiver();

    @Generated
    @Selector("debugDescription")
    public static native String debugDescription_static();

    @Generated
    @Selector("description")
    public static native String description_static();

    @Generated
    @Selector("hasLearnedWord:")
    public static native boolean hasLearnedWord(String word);

    @Generated
    @Selector("hash")
    @NUInt
    public static native long hash_static();

    @Generated
    @Selector("instanceMethodForSelector:")
    @FunctionPtr(name = "call_instanceMethodForSelector_ret")
    public static native NSObject.Function_instanceMethodForSelector_ret instanceMethodForSelector(SEL aSelector);

    @Generated
    @Selector("instanceMethodSignatureForSelector:")
    public static native NSMethodSignature instanceMethodSignatureForSelector(SEL aSelector);

    @Generated
    @Selector("instancesRespondToSelector:")
    public static native boolean instancesRespondToSelector(SEL aSelector);

    @Generated
    @Selector("isSubclassOfClass:")
    public static native boolean isSubclassOfClass(Class aClass);

    @Generated
    @Selector("keyPathsForValuesAffectingValueForKey:")
    public static native NSSet<String> keyPathsForValuesAffectingValueForKey(String key);

    /**
     * These allow clients to programmatically instruct the checker to learn and unlearn words, and to determine whether
     * a word has been learned (and hence can potentially be unlearned).
     */
    @Generated
    @Selector("learnWord:")
    public static native void learnWord(String word);

    @Generated
    @Owned
    @Selector("new")
    public static native UITextChecker new_objc();

    @Generated
    @Selector("resolveClassMethod:")
    public static native boolean resolveClassMethod(SEL sel);

    @Generated
    @Selector("resolveInstanceMethod:")
    public static native boolean resolveInstanceMethod(SEL sel);

    @Generated
    @Selector("setVersion:")
    public static native void setVersion_static(@NInt long aVersion);

    @Generated
    @Selector("superclass")
    public static native Class superclass_static();

    @Generated
    @Selector("unlearnWord:")
    public static native void unlearnWord(String word);

    @Generated
    @Selector("version")
    @NInt
    public static native long version_static();

    /**
     * Returns an array of strings, in the order in which they should be presented, representing complete words that the
     * user might be trying to type when starting by typing the partial word at the given range in the given string.
     */
    @Generated
    @Selector("completionsForPartialWordRange:inString:language:")
    public native NSArray<String> completionsForPartialWordRangeInStringLanguage(@ByValue NSRange range, String string,
            String language);

    /**
     * Returns an array of strings, in the order in which they should be presented, representing guesses for words that
     * might have been intended in place of the misspelled word at the given range in the given string.
     */
    @Generated
    @Selector("guessesForWordRange:inString:language:")
    public native NSArray<String> guessesForWordRangeInStringLanguage(@ByValue NSRange range, String string,
            String language);

    /**
     * Methods for dealing with ignored words.
     */
    @Generated
    @Selector("ignoreWord:")
    public native void ignoreWord(String wordToIgnore);

    @Generated
    @Selector("ignoredWords")
    public native NSArray<String> ignoredWords();

    @Generated
    @Selector("init")
    public native UITextChecker init();

    /**
     * Initiates a spell-check of a string. Returns the range of the first misspelled word, or {NSNotFound, 0} if none
     * is found. Checking is limited to the range specified, and starts at the specified offset (which should lie within
     * the range), but if wrapFlag is YES then it will check from the beginning of the range if no misspelling is found
     * between startingOffset and the end of the range.
     */
    @Generated
    @Selector("rangeOfMisspelledWordInString:range:startingAt:wrap:language:")
    @ByValue
    public native NSRange rangeOfMisspelledWordInStringRangeStartingAtWrapLanguage(String stringToCheck,
            @ByValue NSRange range, @NInt long startingOffset, boolean wrapFlag, String language);

    @Generated
    @Selector("setIgnoredWords:")
    public native void setIgnoredWords(NSArray<String> value);
}


text:
[![Build Status](https://travis-ci.org/jwmerrill/FastGaussTransforms.jl.svg?branch=master)](https://travis-ci.org/jwmerrill/FastGaussTransforms.jl)

Fast algorithm for repeated evaluation of the convolution of a point set with a gaussian kernel. Useful for, e.g. Kernel Density Estimation, or solving heat flow problems.

## Usage
The calculation proceeds in two steps. First, a pointset is summarized into a FastGaussTransform datastructure using `fastgausstransform`.

```julia
points = rand(10)
values = rand(10)
bandwidth = 0.04
t = fastgausstransform(points, values, bandwidth)
```

The transform may then be evaluated at a point using `evaluate`.
```julia
evaluate(t, 0.5)
```

`faustgausstransform` takes an optional keyword argument specifying the relative precision tolerance:

```julia
fastgausstransform(points, values, bandwidth; rtol=1e-3)
```

`rtol` defaults to `eps(1.0) ≈ 2e-16`. Decreased precision speeds evaluation. This setting should be especially useful for plotting.

Based on "Improved Fast Gauss Transform," Proceedings International Conference on Computer Vision, 464 -471, C. Yang, R. Duraiswami, N.A. Gumerov, L. Davis. [pdf](http://www.umiacs.umd.edu/~ramani/pubs/0464_yang.pdf)


text:
package docs.home.persistence;

import com.lightbend.lagom.javadsl.persistence.AggregateEventTag;
import com.lightbend.lagom.javadsl.persistence.ReadSideProcessor;
import org.pcollections.PSequence;

public interface BlogEventProcessorInitial {

  // #processor
  public class BlogEventProcessor extends ReadSideProcessor<BlogEvent> {

    @Override
    public ReadSideProcessor.ReadSideHandler<BlogEvent> buildHandler() {
      // TODO build read side handler
      return null;
    }

    @Override
    public PSequence<AggregateEventTag<BlogEvent>> aggregateTags() {
      // TODO return the tag for the events
      return null;
    }
  }
  // #processor
}


text:
package dataforms.devtool.page.func;

import java.io.File;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.log4j.Logger;

import dataforms.annotation.WebMethod;
import dataforms.app.dao.func.FuncInfoDao;
import dataforms.app.dao.func.FuncInfoTable;
import dataforms.app.field.func.FuncNameField;
import dataforms.controller.EditForm;
import dataforms.controller.JsonResponse;
import dataforms.controller.Page;
import dataforms.devtool.dao.db.TableManagerDao;
import dataforms.devtool.field.common.WebSourcePathField;
import dataforms.devtool.page.base.DeveloperPage;
import dataforms.field.base.FieldList;
import dataforms.htmltable.EditableHtmlTable;
import dataforms.servlet.DataFormsServlet;
import dataforms.util.FileUtil;
import dataforms.util.MessagesUtil;
import dataforms.util.SequentialProperties;

/**
 *
 * 機能編集フォームクラス。
 *

 * func_infoを編集するためのフォームです。
 *

 */
public class FuncEditForm extends EditForm {

    /**
     * Logger.
     */
    private static Logger log = Logger.getLogger(FuncEditForm.class.getName());

	/**
	 * コンストラクタ。
	 */
	public FuncEditForm() {
		this.addField(new WebSourcePathField());
		FuncInfoTable tbl = new FuncInfoTable();
		FieldList flist = new FieldList();
		flist.addAll(tbl.getFieldList());
		flist.add(new FuncNameField());
		EditableHtmlTable funcTable = new EditableHtmlTable("funcTable", flist);
		this.addHtmlTable(funcTable);
	}

	@Override
	public void init() throws Exception {
		super.init();
		this.setFormDataMap(this.queryData(null));
		this.setFormData("webSourcePath", DeveloperPage.getWebSourcePath());
	}

	@Override
	protected Map<String, Object> queryData(final Map<String, Object> data) throws Exception {
		Map<String, Object> ret = new HashMap<String, Object>();
		FuncInfoDao dao = new FuncInfoDao(this);
		List<Map<String, Object>> list = dao.queryFuncList(true);
		for (Map<String, Object> m: list) {
			FuncInfoTable.Entity e = new FuncInfoTable.Entity(m);
			String funcPath = e.getFuncPath(); // (String) m.get("funcPath");
			String propFile = funcPath + "/Function";
			String key = funcPath.substring(1).replaceAll("/", ".");
			log.debug("key=" + key);
			SequentialProperties prop = MessagesUtil.getProperties(this.getPage(), propFile);
			String name = prop.getProperty(key);
			m.put("funcName", name);
		}
		ret.put("funcTable", list);
		return ret;
	}

	/**
	 * {@inheritDoc}
	 *

	 * 常に更新モードで動作させる。
	 *

	 */
	@Override
	protected boolean isUpdate(final Map<String, Object> data) throws Exception {
		return true;
	}

	@Override
	protected void insertData(final Map<String, Object> data) throws Exception {
		// 何もしない
	}

	/**
	 * Function.propertiesのパスを新規作成します。
	 * @param path 機能のパス。
	 * @return 言語に応じたFunction.propertiesのバス。
	 * @throws Exception 例外。
	 */
	private String getFunctionPropertiesPath(final String path) throws Exception {
		String ret = path + "/Function.properties";
/*		String lang = this.getPage().getRequest().getLocale().getLanguage();
		String langlist = DataFormsServlet.getSupportLanguage();
		log.debug("langlist=" + langlist + "," + lang);
		if (langlist.indexOf(lang) >= 0) {
			ret = ret.replaceAll("\\.properties$", "_" + lang + ".properties");
		}*/
		return ret;
	}

	@Override
	protected void updateData(final Map<String, Object> data) throws Exception {
		this.setUserInfo(data);
		Page page = this.getPage();
		@SuppressWarnings("unchecked")
		List<Map<String, Object>> list = (List<Map<String, Object>>) data.get("funcTable");
		FuncInfoDao dao = new FuncInfoDao(this);
		dao.saveFuncList(list);
		String webResourcePath = (String) data.get("webSourcePath");
		for (Map<String, Object> m: list) {
			FuncInfoTable.Entity e = new FuncInfoTable.Entity(m);
			String path = e.getFuncPath(); //(String) m.get("funcPath");
			String name = (String) m.get("funcName");
			if (path.indexOf("/dataforms") != 0) {
				String funcprop = page.getAppropriatePath(path + "/Function.properties", page.getRequest());
				if (funcprop == null) {
					funcprop = this.getFunctionPropertiesPath(path);
				}
				funcprop = webResourcePath + funcprop;
				String text = "";
				File propfile = new File(funcprop);
				if (propfile.exists()) {
					text = FileUtil.readTextFile(funcprop, DataFormsServlet.getEncoding());
				}
				log.debug("funcprop=" + funcprop);
				SequentialProperties prop = new SequentialProperties();
				prop.loadText(text);
				prop.put(path.substring(1).replaceAll("/", "."), name);
				String str = prop.getSaveText();
				log.debug("str=" + str);
				FileUtil.writeTextFileWithBackup(funcprop, str, DataFormsServlet.getEncoding());
			}
		}
	}

	@Override
	public void deleteData(final Map<String, Object> data) throws Exception {
		// 何もしない
	}

	/**
	 * 列挙型関連テーブルのエクスポートを行います。
	 * @param p パラメータ。
	 * @return Json形式のエクスポート。
	 * @throws Exception 例外。
	 */
	@WebMethod
	public JsonResponse export(final Map<String, Object> p) throws Exception {
		JsonResponse ret = null;
		if (this.getPage().checkUserAttribute("userLevel", "developer")) {
			TableManagerDao dao = new TableManagerDao(this);
			String initialDataPath =  DeveloperPage.getExportInitalDataPath(this.getPage()); //DeveloperPage.getWebSourcePath() + "/WEB-INF/initialdata";
			dao.exportData("dataforms.app.dao.func.FuncInfoTable", initialDataPath);
			ret = new JsonResponse(JsonResponse.SUCCESS, MessagesUtil.getMessage(this.getPage(), "message.initializationdatacreated"));
		} else {
			ret = new JsonResponse(JsonResponse.INVALID, MessagesUtil.getMessage(this.getPage(), "error.permission"));
		}
		return ret;
	}

}


text:
- feat: controller.onunload transform should search more aggressively

## 3.5.1

- docs: document latest change

## 3.5.0

- feat: m.route.buildQueryString/parseQueryString rewritten to m.buildQueryString/parseQueryString (#30)

## 3.4.3

- fix: handle more than just m("...") in raw vnode rule
- fix: always rename controller properties to oninit (#25)

## 3.4.2

- fix: don't re-apply view(ctrl) -> view(vnode) transform

## 3.4.1

- docs: use mithril.js.org for links

## 3.4.0

- docs: Readme formatting (#24)
- feat: controller.onunload rewritten to controller.onremove (#23)

## 3.3.1

- fix: Expressions, not statements for m.route()

## 3.3.0

- refactor: use console.warn() instead of comments
- refactor: always run warnings last
- feat: warn about m.redraw.strategy()
- refactor: remove m.route.param rewriting

## 3.2.1

- chore: set up travis publishing
- test: travis tests on node 6/7/4

## 3.2.0

- docs: change-log added
- fix: support more m.route.param() types

## 3.1.0

- Alignment tweak
- Remove unecessary protections
- Not impossible to warn about, fortunately
- Warn about instances of m.deferred
- Sync up w/ work done
- Make sure every transform tracks stats
- Strip m.startComputation/m.endComputation
- Fix mithril documentation links
- Clean up
- Add missing transforms, tweak formatting
- Add issue template

## 3.0.1

- Don't really care about vulns for a CLI tool

## 3.0.0

- Better exclusions
- Warnings
- m.sync -> Promise.all
- Formatting
- Add coverage, rename ospec to tests
- Unused
- Clean up NPM package contents
- execa@0.5.0
- Make package.json match what's on NPM
- Badges! :pager:
- Remove m.request.run stuff
- More arrow-functiony
- m.sync -> Promise.all
- Formatting

## 2.0.2

- Readme updates

## 2.0.1

- ESLint

## 2.0.0

- Bring back safe/unsafe, tweak CLI
- Expand view rewriting to fn(ctrl)
- Clean up event cancelling
- Rework upwards() usage & features
- Use "function" for arrow support
- Use "Function" type in case arrows are involved
- Safer replacement via identifier.replace
- Strip empty config functions after transform
- Try & handle more config init cases (#17)
- Add migration doc link
- Prepend svg element href attr w/ xlink namespace (#16)
- Rename first param in controller functions to vnode (#15)
- Doc update & transform planning

## 1.1.2

- Attempt to fix bin line-endings
- Make m.route.get/set transform safer (#14)

## 1.1.1

- Take advantage of matchNode/j.match (#9)

## 1.1.0

- Fix lint issues
- Add view transform (no migration docs?!?)
- view function rewriting (#7)
- LTS & stable only
- Clean up filtering a bit
- Tests trim input to disparity (just in case)
- Support m.module and use oncreate instead of oninit (#5) (Rasmus Porsager)

## 1.0.2

- Remove a false-positive
- Fix bad check
- Robustify
- Robustify

## 1.0.1

- Minor cleanups

## 1.0.0

- Initial release


text:
package com.iobeam.api.client;

import com.iobeam.api.ApiException;
import com.iobeam.api.http.ContentType;
import com.iobeam.api.http.RequestBuilder;
import com.iobeam.api.http.RequestMethod;
import com.iobeam.api.http.StatusCode;

import java.io.IOException;
import java.util.concurrent.Callable;
import java.util.concurrent.Executor;
import java.util.concurrent.Future;

/**
 *
 */
public abstract class RestRequest<T> {

    private final RestClient client;
    private final RequestBuilder builder;
    private final StatusCode expectedCode;
    private final Class<T> responseClass;
    private final boolean needAuth;

    protected RestRequest(final RestClient client,
                          final RequestMethod method,
                          final String path,
                          final ContentType type,
                          final Object content,
                          final StatusCode expectedCode,
                          final Class<T> responseClass,
                          final boolean needAuth) {
        this.builder = new RequestBuilder(client.getBaseUrl() + path);
        this.client = client;
        this.responseClass = responseClass;
        this.expectedCode = expectedCode;
        this.builder.setRequestMethod(method)
            .setContentType(type)
            .setContent(content);
        this.needAuth = needAuth;
    }

    protected RestRequest(final RestClient client,
                          final RequestMethod method,
                          final String path,
                          final ContentType type,
                          final Object content,
                          final StatusCode expectedCode,
                          final Class<T> responseClass) {
        this.builder = new RequestBuilder(client.getBaseUrl() + path);
        this.client = client;
        this.responseClass = responseClass;
        this.expectedCode = expectedCode;
        this.builder.setRequestMethod(method)
            .setContentType(type)
            .setContent(content);
        this.needAuth = true;
    }

    protected RestRequest(final RestClient client,
                          final RequestMethod method,
                          final String path,
                          final StatusCode expectedCode,
                          final Class<T> responseClass,
                          final boolean needAuth) {
        this(client, method, path, ContentType.NONE,
             null, expectedCode, responseClass, needAuth);
    }

    protected RestRequest(final RestClient client,
                          final RequestMethod method,
                          final String path,
                          final StatusCode expectedCode,
                          final Class<T> responseClass) {
        this(client, method, path, ContentType.NONE,
             null, expectedCode, responseClass, true);
    }

    public RequestBuilder getBuilder() {
        return builder;
    }

    /**
     * Execute the REST request synchronously on the calling thread, returning the result when the
     * operation completes.
     *
     * @return The response result of the REST request.
     */
    public T execute() throws ApiException, IOException {
        return client.executeRequest(this.builder, expectedCode, responseClass, needAuth);
    }

    /**
     * Execute the REST request asynchronously and call the given handler when the operation
     * completes. While the request itself is executed on the client's executor service, the handler
     * runs on the executor service given as a parameter.
     *
     * @param handler  the handler to run once the request completes, or failure occurs.
     * @param executor the executor to run the handler on.
     * @return A future result of the asynchronous operation.
     */
    public Future<T> executeAsync(final RestCallback<T> handler,
                                  final Executor executor) {

        return client.submit(new Callable<T>() {

            @Override
            public T call() throws Exception {
                try {
                    final T result = execute();
                    executor.execute(new Runnable() {
                        @Override
                        public void run() {
                            handler.completed(result, RestRequest.this);
                        }
                    });
                    return result;
                } catch (final Exception e) {
                    executor.execute(new Runnable() {
                        @Override
                        public void run() {
                            handler.failed(e, RestRequest.this);
                        }
                    });
                    throw e;
                }
            }
        });
    }

    /**
     * Execute the REST request asynchronously and call the given handler when the operation
     * completes. The handler runs on the REST client's executor service.
     *
     * @param handler the handler to run once the request completes, or failure occurs.
     * @return A future result of the asynchronous operation.
     */
    public Future<T> executeAsync(final RestCallback<T> handler) {

        return client.submit(new Callable<T>() {

            @Override
            public T call() throws Exception {
                try {
                    final T result = execute();
                    handler.completed(result, RestRequest.this);
                    return result;
                } catch (Exception e) {
                    handler.failed(e, RestRequest.this);
                    throw e;
                }
            }
        });
    }

    /**
     * Execute the REST request asynchronously.
     *
     * @return A future result of the asynchronous operation.
     */
    public Future<T> executeAsync() {

        return client.submit(new Callable<T>() {

            @Override
            public T call() throws Exception {
                return execute();
            }
        });
    }
}


text:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
                      "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">

    <meta http-equiv="content-type" content="text/html; charset=UTF-8"/>
    <title>Zend Framework 1.8 - Zend Framework Manual</title>

                    Zend Framework 1.9

Zend Framework Migration Notes

                        Programmer's Reference Guide

Zend Framework 1.7

Zend Framework 1.8

        Lors de la migration d'un version précédente vers Zend Framework 1.8 ou plus récent
        vous devriez prendre note de ce qui suit.

Zend_Controller

Changement de la route standard

                Comme les segments traduits ont été ajoutés dans la nouvelle route standard, le
                caractère @ est maintenant un caractère spécial au début d'un segment
                de route. Pour être capable de l'utiliser dans un segment statique, vous devez
                l'échapper en le préfixant avec un second @. La même règle s'applique
                aussi au caractère :.

Zend_Locale

Default caching

                As with Zend Framework 1.8 a default caching was added. The reason behind this
                change was, that most users had performance problems but did not add caching at
                all. As the I18n core is a bottleneck when no caching is used we decided to add
                a default caching when no cache has been set to Zend_Locale.

                Sometimes it is still wanted to prevent caching at all even if this decreases
                performance. To do so you can simply disable caching by using the
                 disableCache() method.

Example #1 Disabling default caching

Zend_Locale::disableCache(true);

                    Zend Framework 1.9

Zend Framework Migration Notes

                        Programmer's Reference Guide

Zend Framework 1.7

Programmer's Reference Guide

Programmer's Reference Guide

Zend Framework Migration Notes

Zend Framework 1.10

Zend Framework 1.9

Zend Framework 1.8

Zend Framework 1.7

Zend Framework 1.6

Zend Framework 1.5

Zend Framework 1.0

Zend Framework 0.9

Zend Framework 0.8

Zend Framework 0.6


text:
{-# Language FlexibleContexts #-}
-- | Midi.
module Csound.Control.Midi(
    MidiChn(..), MidiFun, toMidiFun, toMidiFun_,
    Msg, Channel, midi, midin, pgmidi, ampCps,
    midi_, midin_, pgmidi_,
    -- * Mono-midi synth
    monoMsg, holdMsg, trigNamedMono,

    -- ** Custom temperament
    monoMsgTemp, holdMsgTemp,
    -- * Midi event streams
    midiKeyOn, midiKeyOff,
    -- * Reading midi note parameters
    cpsmidi, ampmidi, initc7, ctrl7, midiCtrl7, midiCtrl, umidiCtrl,
    ampmidinn,

    -- ** Custom temperament
    ampCps', cpsmidi', cpsmidi'D, cpsmidi'Sig,

    -- * Overload
    tryMidi, tryMidi', MidiInstr(..), MidiInstrTemp(..)
) where

import Data.Boolean

import Csound.Typed
import Csound.Typed.Opcode hiding (initc7)
import Csound.Control.Overload
import Csound.Control.Instr(alwaysOn)
import Csound.Control.Evt(Tick)

import Csound.Tuning

-- | Specifies the midi channel or programm.
data MidiChn = ChnAll | Chn Int | Pgm (Maybe Int) Int
	deriving (Show, Eq)

type MidiFun a = (Msg -> SE a) -> SE a

toMidiFun :: Sigs a => MidiChn -> MidiFun a
toMidiFun x = case x of
	ChnAll  -> midi
	Chn n   -> midin n
	Pgm a b -> pgmidi a b

toMidiFun_ :: MidiChn -> MidiFun ()
toMidiFun_ x = case x of
	ChnAll  -> midi_
	Chn n   -> midin_ n
	Pgm a b -> pgmidi_ a b

ampCps :: Msg -> (D, D)
ampCps msg = (ampmidi msg 1, cpsmidi msg)

-- | Converts midi velocity number to amplitude.
-- The first argument is dynamic range in decibels.
--
-- > ampmidinn (volMinDb, volMaxDb) volumeKey = amplitude
ampmidinn :: (D, D) -> D -> D
ampmidinn (volMin, volMax) volKey = ampdbfs (volMin + ir (ampmidid volKey (volMax - volMin)))

-- | Midi message convertion with custom temperament.
ampCps' :: Temp -> Msg -> (D, D)
ampCps' temp msg = (ampmidi msg 1, cpsmidi' temp msg)

-- | Midi message convertion to Hz with custom temperament.
cpsmidi' :: Temp -> Msg -> D
cpsmidi' (Temp t) msg = cpstmid msg t

-- | Midi pitch key convertion to Hz with custom temperament. It works on constants.
cpsmidi'D :: Temp -> D -> D
cpsmidi'D (Temp t) key = cpstuni key t

-- | Midi pitch key convertion to Hz with custom temperament. It works on signals.
cpsmidi'Sig :: Temp -> Sig -> Sig
cpsmidi'Sig (Temp t) key = cpstun 1 key t

-----------------------------------------------------------------------
-- Midi addons

-- mono midi

-- | Produces midi amplitude and frequency as a signal.
-- The signal fades out when nothing is pressed.
-- It can be used in mono-synths. Arguments are portamento time
-- and release time. A portamento time is time it takes for transition
-- from one note to another.
--
-- > monoMsg channel portamentoTime releaseTime
monoMsg :: MidiChn -> D -> D -> SE (Sig, Sig)
monoMsg = genMonoMsg cpsmidi

-- | Produces midi amplitude and frequency as a signal.
-- The signal fades out when nothing is pressed.
-- It can be used in mono-synths. Arguments are custom temperament, midi channel, portamento time
-- and release time. A portamento time is time it takes for transition
-- from one note to another.
--
-- > monoMsgTemp temperament channel portamentoTime releaseTime
monoMsgTemp :: Temp -> MidiChn -> D -> D -> SE (Sig, Sig)
monoMsgTemp tm = genMonoMsg (cpsmidi' tm)

genMonoMsg :: (Msg -> D) -> MidiChn -> D -> D -> SE (Sig, Sig)
genMonoMsg key2cps chn portTime relTime = do
	(amp, cps, status) <- genAmpCpsSig key2cps (toMidiFun chn)
	return (port amp portTime * port status relTime,  port cps portTime)

-- | Produces midi amplitude and frequency as a signal and holds the
-- last value till the next one is present.
-- It can be used in mono-synths. Arguments are portamento time
-- and release time. A portamento time is time it takes for transition
-- from one note to another.
--
-- > holdMsg portamentoTime
holdMsg :: MidiChn -> D -> SE (Sig, Sig)
holdMsg = genHoldMsg cpsmidi

-- | Produces midi amplitude and frequency as a signal and holds the
-- last value till the next one is present.
-- It can be used in mono-synths. Arguments are portamento time
-- and release time. A portamento time is time it takes for transition
-- from one note to another.
--
-- > holdMsg portamentoTime
holdMsgTemp :: Temp -> MidiChn -> D -> SE (Sig, Sig)
holdMsgTemp tm = genHoldMsg (cpsmidi' tm)

genHoldMsg :: (Msg -> D) -> MidiChn -> D -> SE (Sig, Sig)
genHoldMsg key2cps channel portTime = do
	(amp, cps) <- genHoldAmpCpsSig key2cps (toMidiFun_ channel)
	return (port amp portTime,  port cps portTime)

genAmpCpsSig :: (Msg -> D) -> ((Msg -> SE Sig) -> SE Sig) -> SE (Sig, Sig, Sig)
genAmpCpsSig key2cps midiFun = do
	ref <- newGlobalRef ((0, 0) :: (Sig, Sig))
	status <- midiFun (instr ref)
	let resStatus = ifB (downsamp status ==* 0) 0 1
	(amp, cps) <- readRef ref
	return (downsamp amp, downsamp cps, resStatus)
	where
		instr :: Ref (Sig, Sig) -> Msg -> SE Sig
		instr hNote msg = do
			writeRef hNote (sig $ ampmidi msg 1, sig $ key2cps msg)
			return 1

genHoldAmpCpsSig :: (Msg -> D) -> ((Msg -> SE ()) -> SE ()) -> SE (Sig, Sig)
genHoldAmpCpsSig key2cps midiFun = do
	ref <- newGlobalRef ((0, 0) :: (Sig, Sig))
	midiFun (instr ref)
	(amp, cps) <- readRef ref
	return (downsamp amp, downsamp cps)
	where
		instr :: Ref (Sig, Sig) -> Msg -> SE ()
		instr hNote msg = do
			writeRef hNote (sig $ ampmidi msg 1, sig $ key2cps msg)

-- | Creates a named instrument that can be triggered with Csound API.
-- This way we can create a csd file that can be used inside another program/language.
--
-- It simulates the input for monophonic midi-like instrument. Notes are encoded with messages:
--
-- > i "givenName" 1 pitchKey volumeKey     -- note on
-- > i "givenName" 0 pitchKey volumeKey     -- note off
--
-- The output is a pair of signals @(midiVolume, midiPitch)@.
trigNamedMono :: D -> D -> String -> SE (Sig, Sig)
trigNamedMono portTime relTime name = namedMonoMsg portTime relTime name

namedAmpCpsSig:: String -> SE (Sig, Sig, Sig)
namedAmpCpsSig name = do
	ref <- newGlobalRef ((0, 0) :: (Sig, Sig))
	statusRef <- newGlobalRef (0 :: Sig)
	status <- trigByNameMidi name (instr statusRef ref)
	writeRef statusRef status
	let resStatus = ifB (downsamp status ==* 0) 0 1
	(amp, cps) <- readRef ref
	return (downsamp amp, downsamp cps, resStatus)
	where
		instr :: Ref Sig -> Ref (Sig, Sig) -> (D, D, Unit) -> SE Sig
		instr statusRef hNote (pitchKey, volKey, _) = do
			curId <- readRef statusRef
			myIdRef <- newRef (ir curId)
			myId <- readRef myIdRef
			when1 (curId ==* (sig $ myId + 1)) $ do
				writeRef hNote (sig volKey, sig pitchKey)
			return 1

--------------------------------------------------------------

-- | Listens to midi on event on the given key as event stream.
-- The event stream carries the level of volume (ranges from 0 to 1).
midiKeyOn :: MidiChn -> D -> SE (Evt D)
midiKeyOn = midiKeyOnBy . toMidiFun

-- | Listens to midi on event off the given key as event stream.
midiKeyOff :: MidiChn -> D -> SE Tick
midiKeyOff = midiKeyOffBy . toMidiFun

midiKeyOnBy :: MidiFun Sig -> D -> SE (Evt D)
midiKeyOnBy midiFun key = do
	chRef  <- newGlobalRef (0 :: Sig)
	evtRef <- newGlobalRef (0 :: Sig)
	writeRef chRef =<< midiFun instr

	alwaysOn $ do
		a <- readRef chRef
		writeRef evtRef $ diff a

	evtSig <- readRef evtRef
	return $ filterE ( >* 0) $ snaps evtSig
	where
		instr msg = do
			print' [notnum msg]
			return $ ifB (boolSig $ notnum msg ==* key) (sig $ ampmidi msg 1) 0

midiKeyOffBy :: MidiFun Sig -> D -> SE Tick
midiKeyOffBy midiFun key = do
	chRef  <- newGlobalRef (0 :: Sig)
	evtRef <- newGlobalRef (0 :: Sig)
	writeRef chRef =<< midiFun instr

	alwaysOn $ do
		a <- readRef chRef
		writeRef evtRef $ diff a

	evtSig <- readRef evtRef
	return $ fmap (const unit) $ filterE ( `lessThan` 0) $ snaps evtSig
	where
		instr msg = do
			print' [notnum msg]
			return $ ifB (boolSig $ notnum msg ==* key) (sig $ ampmidi msg 1) 0

--------------------------------------------------------------

-- | Initialization of the midi control-messages.
initc7 :: D -> D -> D -> SE ()
initc7 = initMidiCtrl

-- | Initializes midi control and get the value in the specified range.
midiCtrl7 :: D -> D -> D -> D -> D -> SE Sig
midiCtrl7 chno ctrlno ival imin imax = do
    initc7 chno ctrlno ival
    return $ ctrl7 chno ctrlno imin imax

-- | Initializes midi control and get the value in the range (-1) to 1.
midiCtrl :: D -> D -> D -> SE Sig
midiCtrl chno ctrlno ival = midiCtrl7 chno ctrlno ival (-1) 1

-- | Unipolar midiCtrl. Initializes midi control and get the value in the range 0 to 1.
umidiCtrl :: D -> D -> D -> SE Sig
umidiCtrl chno ctrlno ival = midiCtrl7 chno ctrlno ival 0 1

--------------------------------------------------------------

-- | Invokes ooverloaded instruments with midi.
-- Example:
--
-- > dac $ tryMidi (mul (fades 0.01 0.1) . tri)
tryMidi :: (MidiInstr a, Sigs (MidiInstrOut a)) => a -> SE (MidiInstrOut a)
tryMidi x = midi $ onMsg x

-- | Invokes ooverloaded instruments with midi and custom temperament.
-- Example:
--
-- > dac $ tryMidi' youngTemp2 (mul (fades 0.01 0.1) . tri)
tryMidi' :: (MidiInstrTemp a, Sigs (MidiInstrOut a)) => Temp -> a -> SE (MidiInstrOut a)
tryMidi' tm x = midi $ onMsg' tm x


text:
import datetime

from nailgun.db import db
from nailgun.db.sqlalchemy import models
from nailgun.objects import NailgunCollection
from nailgun.objects import NailgunObject
from nailgun.objects.serializers.oswl import OpenStackWorkloadStatsSerializer
from nailgun.settings import settings

class OpenStackWorkloadStats(NailgunObject):

    #: SQLAlchemy model for OpenStackWorkloadStats
    model = models.OpenStackWorkloadStats

    #: Serializer for OpenStackWorkloadStats
    serializer = OpenStackWorkloadStatsSerializer

    @classmethod
    def get_last_by(cls, cluster_id, resource_type):
        """Get last entry by cluster_id and resource type."""
        instance = db().query(models.OpenStackWorkloadStats) \
            .order_by(models.OpenStackWorkloadStats.created_date.desc()) \
            .filter_by(cluster_id=cluster_id) \
            .filter_by(resource_type=resource_type) \
            .first()

        return instance

class OpenStackWorkloadStatsCollection(NailgunCollection):
    single = OpenStackWorkloadStats

    @classmethod
    def get_ready_to_send(cls):
        """Get entries which are ready to send but were not sent yet."""
        last_date = datetime.datetime.utcnow().date() - \
            datetime.timedelta(days=settings.OSWL_COLLECT_PERIOD)
        instance = db().query(models.OpenStackWorkloadStats) \
            .filter_by(is_sent=False) \
            .filter(models.OpenStackWorkloadStats.created_date <= last_date)

        return instance

    @classmethod
    def clean_expired_entries(cls):
        """Delete expired oswl entries from db"""
        # CAVEAT(aroma): if settings.OSWL_COLLECT_PERIOD is 0
        # then all oswl entries will be deleted from db
        last_date = datetime.datetime.utcnow().date() - \
            datetime.timedelta(days=settings.OSWL_STORING_PERIOD)
        instances = db().query(models.OpenStackWorkloadStats) \
            .filter(models.OpenStackWorkloadStats.created_date <= last_date)

        return instances.delete(synchronize_session=False)

    @classmethod
    def get_last_by_resource_type(cls, resource_type):
        """Get most recently created records for given resource_type

        Records (for some clusters) which were updated earlier than yesterday
        will not be selected.
        """
        instances = db().query(models.OpenStackWorkloadStats) \
            .order_by(models.OpenStackWorkloadStats.created_date.desc()) \
            .filter_by(resource_type=resource_type)
        if instances.count():
            date = instances.first().created_date
            return instances.filter(
                models.OpenStackWorkloadStats.created_date == date)
        return instances


text:
local ffi = require "ffi"
require "turbo.cdef"

-- Defines for epoll_ctl.
local epoll = {
    EPOLL_CTL_ADD = 1,
    EPOLL_CTL_DEL = 2,
    EPOLL_CTL_MOD = 3,
    EPOLL_EVENTS = {
        EPOLLIN  = 0x001,
        EPOLLPRI = 0x002,
        EPOLLOUT = 0x004,
        EPOLLERR = 0x008,
        EPOLLHUP = 0x0010,
    }
}

--- Create a new epoll fd. Returns the fd of the created epoll instance and -1
-- and errno on error.
-- @return epoll fd on success, else -1 and errno.
function epoll.epoll_create()
    local fd = ffi.C.epoll_create(124)

    if fd == -1 then
        return -1, ffi.errno()
    end

    return fd
end

--- Control a epoll fd.
-- @param epfd Epoll fd to control
-- @param op Operation for the target fd:
--  EPOLL_CTL_ADD
--  Register the target file descriptor fd on the epoll  instance referred to
--  by the file descriptor epfd and associate the event event with the internal
--  file linked to fd.
--  EPOLL_CTL_MOD
--  Change the event event associated with the target file descriptor fd.
--  EPOLL_CTL_DEL
--  Remove (deregister) the target file descriptor fd from the epoll instance
--  referred to by epfd. The epoll_events is ignored and can be nil.
-- @param fd (Number) The fd to control.
-- @param epoll_events (Number) The events bit mask to set. Defined in
-- epoll.EPOLL_EVENTS.
-- @return 0 on success and -1 on error together with errno.
local _event = ffi.new("epoll_event")
function epoll.epoll_ctl(epfd, op, fd, epoll_events)
    local rc

    ffi.fill(_event, ffi.sizeof(_event), 0)
    _event.data.fd = fd
    _event.events = epoll_events
    rc = ffi.C.epoll_ctl(epfd, op, fd, _event)
    if (rc == -1) then
        return -1, ffi.errno()
    end
    return rc
end

--- Wait for events on a epoll instance.
-- @param epfd (Number) Epoll fd to wait on.
-- @param timeout (Number) How long to wait if no events occur.
-- @return On success, epoll_event array is returned, on error, -1 and errno
-- are returned.
local _events = ffi.new("struct epoll_event[124]")
function epoll.epoll_wait(epfd, timeout)
    local num_events = ffi.C.epoll_wait(epfd, _events, 124, timeout)
    if num_events == -1 then
        return -1, ffi.errno()
    end
    return 0, num_events, _events
end

return epoll


text:
.class Landroid/view/LayoutInflater$BlinkLayout$1;
.super Ljava/lang/Object;
.source "LayoutInflater.java"

# interfaces
.implements Landroid/os/Handler$Callback;

# annotations
.annotation system Ldalvik/annotation/EnclosingMethod;
    value = Landroid/view/LayoutInflater$BlinkLayout;-><init>(Landroid/content/Context;Landroid/util/AttributeSet;)V
.end annotation

.annotation system Ldalvik/annotation/InnerClass;
    accessFlags = 0x0
    name = null
.end annotation

# instance fields
.field final synthetic this$0:Landroid/view/LayoutInflater$BlinkLayout;

# direct methods
.method constructor <init>(Landroid/view/LayoutInflater$BlinkLayout;)V
    .locals 0
    .parameter

    .prologue
    .line 936
    iput-object p1, p0, Landroid/view/LayoutInflater$BlinkLayout$1;->this$0:Landroid/view/LayoutInflater$BlinkLayout;

    invoke-direct {p0}, Ljava/lang/Object;-><init>()V

    return-void
.end method

# virtual methods
.method public handleMessage(Landroid/os/Message;)Z
    .locals 4
    .parameter "msg"

    .prologue
    const/4 v1, 0x1

    const/4 v0, 0x0

    .line 939
    iget v2, p1, Landroid/os/Message;->what:I

    const/16 v3, 0x42

    if-ne v2, v3, :cond_2

    .line 940
    iget-object v2, p0, Landroid/view/LayoutInflater$BlinkLayout$1;->this$0:Landroid/view/LayoutInflater$BlinkLayout;

    #getter for: Landroid/view/LayoutInflater$BlinkLayout;->mBlink:Z
    invoke-static {v2}, Landroid/view/LayoutInflater$BlinkLayout;->access$000(Landroid/view/LayoutInflater$BlinkLayout;)Z

    move-result v2

    if-eqz v2, :cond_1

    .line 941
    iget-object v2, p0, Landroid/view/LayoutInflater$BlinkLayout$1;->this$0:Landroid/view/LayoutInflater$BlinkLayout;

    iget-object v3, p0, Landroid/view/LayoutInflater$BlinkLayout$1;->this$0:Landroid/view/LayoutInflater$BlinkLayout;

    #getter for: Landroid/view/LayoutInflater$BlinkLayout;->mBlinkState:Z
    invoke-static {v3}, Landroid/view/LayoutInflater$BlinkLayout;->access$100(Landroid/view/LayoutInflater$BlinkLayout;)Z

    move-result v3

    if-nez v3, :cond_0

    move v0, v1

    :cond_0
    #setter for: Landroid/view/LayoutInflater$BlinkLayout;->mBlinkState:Z
    invoke-static {v2, v0}, Landroid/view/LayoutInflater$BlinkLayout;->access$102(Landroid/view/LayoutInflater$BlinkLayout;Z)Z

    .line 942
    iget-object v0, p0, Landroid/view/LayoutInflater$BlinkLayout$1;->this$0:Landroid/view/LayoutInflater$BlinkLayout;

    #calls: Landroid/view/LayoutInflater$BlinkLayout;->makeBlink()V
    invoke-static {v0}, Landroid/view/LayoutInflater$BlinkLayout;->access$200(Landroid/view/LayoutInflater$BlinkLayout;)V

    .line 944
    :cond_1
    iget-object v0, p0, Landroid/view/LayoutInflater$BlinkLayout$1;->this$0:Landroid/view/LayoutInflater$BlinkLayout;

    invoke-virtual {v0}, Landroid/view/View;->invalidate()V

    .line 947
    :goto_0
    return v1

    :cond_2
    move v1, v0

    goto :goto_0
.end method