text:
package com.phonemetra.turbo.launcher;

import android.content.ComponentName;
import android.content.Context;
import android.content.res.Resources;
import android.graphics.Bitmap;
import android.graphics.Point;
import android.graphics.PointF;
import android.graphics.Rect;
import android.os.Handler;
import android.os.IBinder;
import android.util.Log;
import android.view.*;
import android.view.inputmethod.InputMethodManager;

import java.util.ArrayList;

import com.phonemetra.turbo.launcher.R;

/**
 * Class for initiating a drag within a view or across multiple views.
 */
public class DragController {
    private static final String TAG = "Launcher.DragController";

    /** Indicates the drag is a move.  */
    public static int DRAG_ACTION_MOVE = 0;

    /** Indicates the drag is a copy.  */
    public static int DRAG_ACTION_COPY = 1;

    private static final int SCROLL_DELAY = 500;
    private static final int RESCROLL_DELAY = PagedView.PAGE_SNAP_ANIMATION_DURATION + 150;

    private static final boolean PROFILE_DRAWING_DURING_DRAG = false;

    private static final int SCROLL_OUTSIDE_ZONE = 0;
    private static final int SCROLL_WAITING_IN_ZONE = 1;

    static final int SCROLL_NONE = -1;
    static final int SCROLL_LEFT = 0;
    static final int SCROLL_RIGHT = 1;

    private static final float MAX_FLING_DEGREES = 35f;

    private Launcher mLauncher;
    private Handler mHandler;

    // temporaries to avoid gc thrash
    private Rect mRectTemp = new Rect();
    private final int[] mCoordinatesTemp = new int[2];

    /** Whether or not we're dragging. */
    private boolean mDragging;

    /** X coordinate of the down event. */
    private int mMotionDownX;

    /** Y coordinate of the down event. */
    private int mMotionDownY;

    /** the area at the edge of the screen that makes the workspace go left
     *   or right while you're dragging.
     */
    private int mScrollZone;

    private DropTarget.DragObject mDragObject;

    /** Who can receive drop events */
    private ArrayList<DropTarget> mDropTargets = new ArrayList<DropTarget>();
    private ArrayList<DragListener> mListeners = new ArrayList<DragListener>();
    private DropTarget mFlingToDeleteDropTarget;

    /** The window token used as the parent for the DragView. */
    private IBinder mWindowToken;

    /** The view that will be scrolled when dragging to the left and right edges of the screen. */
    private View mScrollView;

    private View mMoveTarget;

    private DragScroller mDragScroller;
    private int mScrollState = SCROLL_OUTSIDE_ZONE;
    private ScrollRunnable mScrollRunnable = new ScrollRunnable();

    private DropTarget mLastDropTarget;

    private InputMethodManager mInputMethodManager;

    private int mLastTouch[] = new int[2];
    private long mLastTouchUpTime = -1;
    private int mDistanceSinceScroll = 0;

    private int mTmpPoint[] = new int[2];
    private Rect mDragLayerRect = new Rect();

    protected int mFlingToDeleteThresholdVelocity;
    private VelocityTracker mVelocityTracker;

    /**
     * Interface to receive notifications when a drag starts or stops
     */
    interface DragListener {
        /**
         * A drag has begun
         *
         * @param source An object representing where the drag originated
         * @param info The data associated with the object that is being dragged
         * @param dragAction The drag action: either {@link DragController#DRAG_ACTION_MOVE}
         *        or {@link DragController#DRAG_ACTION_COPY}
         */
        void onDragStart(DragSource source, Object info, int dragAction);

        /**
         * The drag has ended
         */
        void onDragEnd();
    }

    /**
     * Used to create a new DragLayer from XML.
     *
     * @param context The application's context.
     */
    public DragController(Launcher launcher) {
        Resources r = launcher.getResources();
        mLauncher = launcher;
        mHandler = new Handler();
        mScrollZone = r.getDimensionPixelSize(R.dimen.scroll_zone);
        mVelocityTracker = VelocityTracker.obtain();

        float density = r.getDisplayMetrics().density;
        mFlingToDeleteThresholdVelocity =
                (int) (r.getInteger(R.integer.config_flingToDeleteMinVelocity) * density);
    }

    public boolean dragging() {
        return mDragging;
    }

    /**
     * Starts a drag.
     *
     * @param v The view that is being dragged
     * @param bmp The bitmap that represents the view being dragged
     * @param source An object representing where the drag originated
     * @param dragInfo The data associated with the object that is being dragged
     * @param dragAction The drag action: either {@link #DRAG_ACTION_MOVE} or
     *        {@link #DRAG_ACTION_COPY}
     * @param dragRegion Coordinates within the bitmap b for the position of item being dragged.
     *          Makes dragging feel more precise, e.g. you can clip out a transparent border
     */
    public void startDrag(View v, Bitmap bmp, DragSource source, Object dragInfo, int dragAction,
            Point extraPadding, float initialDragViewScale) {
        int[] loc = mCoordinatesTemp;
        mLauncher.getDragLayer().getLocationInDragLayer(v, loc);
        int viewExtraPaddingLeft = extraPadding != null ? extraPadding.x : 0;
        int viewExtraPaddingTop = extraPadding != null ? extraPadding.y : 0;
        int dragLayerX = loc[0] + v.getPaddingLeft() + viewExtraPaddingLeft +
                (int) ((initialDragViewScale * bmp.getWidth() - bmp.getWidth()) / 2);
        int dragLayerY = loc[1] + v.getPaddingTop() + viewExtraPaddingTop +
                (int) ((initialDragViewScale * bmp.getHeight() - bmp.getHeight()) / 2);

        startDrag(bmp, dragLayerX, dragLayerY, source, dragInfo, dragAction, null,
                null, initialDragViewScale);

        if (dragAction == DRAG_ACTION_MOVE) {
            v.setVisibility(View.GONE);
        }
    }

    /**
     * Starts a drag.
     *
     * @param b The bitmap to display as the drag image.  It will be re-scaled to the
     *          enlarged size.
     * @param dragLayerX The x position in the DragLayer of the left-top of the bitmap.
     * @param dragLayerY The y position in the DragLayer of the left-top of the bitmap.
     * @param source An object representing where the drag originated
     * @param dragInfo The data associated with the object that is being dragged
     * @param dragAction The drag action: either {@link #DRAG_ACTION_MOVE} or
     *        {@link #DRAG_ACTION_COPY}
     * @param dragRegion Coordinates within the bitmap b for the position of item being dragged.
     *          Makes dragging feel more precise, e.g. you can clip out a transparent border
     */
    public DragView startDrag(Bitmap b, int dragLayerX, int dragLayerY,
            DragSource source, Object dragInfo, int dragAction, Point dragOffset, Rect dragRegion,
            float initialDragViewScale) {
        if (PROFILE_DRAWING_DURING_DRAG) {
            android.os.Debug.startMethodTracing("Launcher");
        }

        // Hide soft keyboard, if visible
        if (mInputMethodManager == null) {
            mInputMethodManager = (InputMethodManager)
                    mLauncher.getSystemService(Context.INPUT_METHOD_SERVICE);
        }
        mInputMethodManager.hideSoftInputFromWindow(mWindowToken, 0);

        for (DragListener listener : mListeners) {
            listener.onDragStart(source, dragInfo, dragAction);
        }

        final int registrationX = mMotionDownX - dragLayerX;
        final int registrationY = mMotionDownY - dragLayerY;

        final int dragRegionLeft = dragRegion == null ? 0 : dragRegion.left;
        final int dragRegionTop = dragRegion == null ? 0 : dragRegion.top;

        mDragging = true;

        mDragObject = new DropTarget.DragObject();

        mDragObject.dragComplete = false;
        mDragObject.xOffset = mMotionDownX - (dragLayerX + dragRegionLeft);
        mDragObject.yOffset = mMotionDownY - (dragLayerY + dragRegionTop);
        mDragObject.dragSource = source;
        mDragObject.dragInfo = dragInfo;

        final DragView dragView = mDragObject.dragView = new DragView(mLauncher, b, registrationX,
                registrationY, 0, 0, b.getWidth(), b.getHeight(), initialDragViewScale);

        if (dragOffset != null) {
            dragView.setDragVisualizeOffset(new Point(dragOffset));
        }
        if (dragRegion != null) {
            dragView.setDragRegion(new Rect(dragRegion));
        }

        mLauncher.getDragLayer().performHapticFeedback(HapticFeedbackConstants.LONG_PRESS);
        dragView.show(mMotionDownX, mMotionDownY);
        handleMoveEvent(mMotionDownX, mMotionDownY);
        return dragView;
    }

    /**
     * Draw the view into a bitmap.
     */
    Bitmap getViewBitmap(View v) {
        v.clearFocus();
        v.setPressed(false);

        boolean willNotCache = v.willNotCacheDrawing();
        v.setWillNotCacheDrawing(false);

        // Reset the drawing cache background color to fully transparent
        // for the duration of this operation
        int color = v.getDrawingCacheBackgroundColor();
        v.setDrawingCacheBackgroundColor(0);
        float alpha = v.getAlpha();
        v.setAlpha(1.0f);

        if (color != 0) {
            v.destroyDrawingCache();
        }
        v.buildDrawingCache();
        Bitmap cacheBitmap = v.getDrawingCache();
        if (cacheBitmap == null) {
            Log.e(TAG, "failed getViewBitmap(" + v + ")", new RuntimeException());
            return null;
        }

        Bitmap bitmap = Bitmap.createBitmap(cacheBitmap);

        // Restore the view
        v.destroyDrawingCache();
        v.setAlpha(alpha);
        v.setWillNotCacheDrawing(willNotCache);
        v.setDrawingCacheBackgroundColor(color);

        return bitmap;
    }

    /**
     * Call this from a drag source view like this:
     *
     * <pre>
     *  @Override
     *  public boolean dispatchKeyEvent(KeyEvent event) {
     *      return mDragController.dispatchKeyEvent(this, event)
     *              || super.dispatchKeyEvent(event);
     * </pre>
     */
    public boolean dispatchKeyEvent(KeyEvent event) {
        return mDragging;
    }

    public boolean isDragging() {
        return mDragging;
    }

    /**
     * Stop dragging without dropping.
     */
    public void cancelDrag() {
        if (mDragging) {
            if (mLastDropTarget != null) {
                mLastDropTarget.onDragExit(mDragObject);
            }
            mDragObject.deferDragViewCleanupPostAnimation = false;
            mDragObject.cancelled = true;
            mDragObject.dragComplete = true;
            mDragObject.dragSource.onDropCompleted(null, mDragObject, false, false);
        }
        endDrag();
    }
    public void onAppsRemoved(final ArrayList<String> packageNames, ArrayList<AppInfo> appInfos) {
        // Cancel the current drag if we are removing an app that we are dragging
        if (mDragObject != null) {
            Object rawDragInfo = mDragObject.dragInfo;
            if (rawDragInfo instanceof ShortcutInfo) {
                ShortcutInfo dragInfo = (ShortcutInfo) rawDragInfo;
                for (AppInfo info : appInfos) {
                    // Added null checks to prevent NPE we've seen in the wild
                    if (dragInfo != null &&
                            dragInfo.intent != null && info != null) {
                        ComponentName cn = dragInfo.intent.getComponent();
                        boolean isSameComponent = cn.equals(info.componentName) ||
                                packageNames.contains(cn.getPackageName());
                        if (isSameComponent) {
                            cancelDrag();
                            return;
                        }
                    }
                }
            }
        }
    }

    private void endDrag() {
        if (mDragging) {
            mDragging = false;
            clearScrollRunnable();
            boolean isDeferred = false;
            if (mDragObject.dragView != null) {
                isDeferred = mDragObject.deferDragViewCleanupPostAnimation;
                if (!isDeferred) {
                    mDragObject.dragView.remove();
                }
                mDragObject.dragView = null;
            }

            // Only end the drag if we are not deferred
            if (!isDeferred) {
                for (DragListener listener : mListeners) {
                    listener.onDragEnd();
                }
            }
        }

        releaseVelocityTracker();
    }

    /**
     * This only gets called as a result of drag view cleanup being deferred in endDrag();
     */
    void onDeferredEndDrag(DragView dragView) {
        dragView.remove();

        if (mDragObject.deferDragViewCleanupPostAnimation) {
            // If we skipped calling onDragEnd() before, do it now
            for (DragListener listener : mListeners) {
                listener.onDragEnd();
            }
        }
    }

    void onDeferredEndFling(DropTarget.DragObject d) {
        d.dragSource.onFlingToDeleteCompleted();
    }

    /**
     * Clamps the position to the drag layer bounds.
     */
    private int[] getClampedDragLayerPos(float x, float y) {
        mLauncher.getDragLayer().getLocalVisibleRect(mDragLayerRect);
        mTmpPoint[0] = (int) Math.max(mDragLayerRect.left, Math.min(x, mDragLayerRect.right - 1));
        mTmpPoint[1] = (int) Math.max(mDragLayerRect.top, Math.min(y, mDragLayerRect.bottom - 1));
        return mTmpPoint;
    }

    long getLastGestureUpTime() {
        if (mDragging) {
            return System.currentTimeMillis();
        } else {
            return mLastTouchUpTime;
        }
    }

    void resetLastGestureUpTime() {
        mLastTouchUpTime = -1;
    }

    /**
     * Call this from a drag source view.
     */
    public boolean onInterceptTouchEvent(MotionEvent ev) {

        acquireVelocityTrackerAndAddMovement(ev);

        final int action = ev.getAction();
        final int[] dragLayerPos = getClampedDragLayerPos(ev.getX(), ev.getY());
        final int dragLayerX = dragLayerPos[0];
        final int dragLayerY = dragLayerPos[1];

        switch (action) {
            case MotionEvent.ACTION_MOVE:
                break;
            case MotionEvent.ACTION_DOWN:
                // Remember location of down touch
                mMotionDownX = dragLayerX;
                mMotionDownY = dragLayerY;
                mLastDropTarget = null;
                break;
            case MotionEvent.ACTION_UP:
                mLastTouchUpTime = System.currentTimeMillis();
                if (mDragging) {
                    PointF vec = isFlingingToDelete(mDragObject.dragSource);
                    if (!DeleteDropTarget.willAcceptDrop(mDragObject.dragInfo)) {
                        vec = null;
                    }
                    if (vec != null) {
                        dropOnFlingToDeleteTarget(dragLayerX, dragLayerY, vec);
                    } else {
                        drop(dragLayerX, dragLayerY);
                    }
                }
                endDrag();
                break;
            case MotionEvent.ACTION_CANCEL:
                cancelDrag();
                break;
        }

        return mDragging;
    }

    /**
     * Sets the view that should handle move events.
     */
    void setMoveTarget(View view) {
        mMoveTarget = view;
    }

    public boolean dispatchUnhandledMove(View focused, int direction) {
        return mMoveTarget != null && mMoveTarget.dispatchUnhandledMove(focused, direction);
    }

    private void clearScrollRunnable() {
        mHandler.removeCallbacks(mScrollRunnable);
        if (mScrollState == SCROLL_WAITING_IN_ZONE) {
            mScrollState = SCROLL_OUTSIDE_ZONE;
            mScrollRunnable.setDirection(SCROLL_RIGHT);
            mDragScroller.onExitScrollArea();
            mLauncher.getDragLayer().onExitScrollArea();
        }
    }

    private void handleMoveEvent(int x, int y) {
        mDragObject.dragView.move(x, y);

        // Drop on someone?
        final int[] coordinates = mCoordinatesTemp;
        DropTarget dropTarget = findDropTarget(x, y, coordinates);
        mDragObject.x = coordinates[0];
        mDragObject.y = coordinates[1];
        checkTouchMove(dropTarget);

        // Check if we are hovering over the scroll areas
        mDistanceSinceScroll +=
            Math.sqrt(Math.pow(mLastTouch[0] - x, 2) + Math.pow(mLastTouch[1] - y, 2));
        mLastTouch[0] = x;
        mLastTouch[1] = y;
        checkScrollState(x, y);
    }

    public void forceTouchMove() {
        int[] dummyCoordinates = mCoordinatesTemp;
        DropTarget dropTarget = findDropTarget(mLastTouch[0], mLastTouch[1], dummyCoordinates);
        mDragObject.x = dummyCoordinates[0];
        mDragObject.y = dummyCoordinates[1];
        checkTouchMove(dropTarget);
    }

    private void checkTouchMove(DropTarget dropTarget) {
        if (dropTarget != null) {
            if (mLastDropTarget != dropTarget) {
                if (mLastDropTarget != null) {
                    mLastDropTarget.onDragExit(mDragObject);
                }
                dropTarget.onDragEnter(mDragObject);
            }
            dropTarget.onDragOver(mDragObject);
        } else {
            if (mLastDropTarget != null) {
                mLastDropTarget.onDragExit(mDragObject);
            }
        }
        mLastDropTarget = dropTarget;
    }

    private void checkScrollState(int x, int y) {
        final int slop = ViewConfiguration.get(mLauncher).getScaledWindowTouchSlop();
        final int delay = mDistanceSinceScroll < slop ? RESCROLL_DELAY : SCROLL_DELAY;
        final DragLayer dragLayer = mLauncher.getDragLayer();
        final boolean isRtl = (dragLayer.getLayoutDirection() == View.LAYOUT_DIRECTION_RTL);
        final int forwardDirection = isRtl ? SCROLL_RIGHT : SCROLL_LEFT;
        final int backwardsDirection = isRtl ? SCROLL_LEFT : SCROLL_RIGHT;

        if (x < mScrollZone) {
            if (mScrollState == SCROLL_OUTSIDE_ZONE) {
                mScrollState = SCROLL_WAITING_IN_ZONE;
                if (mDragScroller.onEnterScrollArea(x, y, forwardDirection)) {
                    dragLayer.onEnterScrollArea(forwardDirection);
                    mScrollRunnable.setDirection(forwardDirection);
                    mHandler.postDelayed(mScrollRunnable, delay);
                }
            }
        } else if (x > mScrollView.getWidth() - mScrollZone) {
            if (mScrollState == SCROLL_OUTSIDE_ZONE) {
                mScrollState = SCROLL_WAITING_IN_ZONE;
                if (mDragScroller.onEnterScrollArea(x, y, backwardsDirection)) {
                    dragLayer.onEnterScrollArea(backwardsDirection);
                    mScrollRunnable.setDirection(backwardsDirection);
                    mHandler.postDelayed(mScrollRunnable, delay);
                }
            }
        } else {
            clearScrollRunnable();
        }
    }

    /**
     * Call this from a drag source view.
     */
    public boolean onTouchEvent(MotionEvent ev) {
        if (!mDragging) {
            return false;
        }

        // Update the velocity tracker
        acquireVelocityTrackerAndAddMovement(ev);

        final int action = ev.getAction();
        final int[] dragLayerPos = getClampedDragLayerPos(ev.getX(), ev.getY());
        final int dragLayerX = dragLayerPos[0];
        final int dragLayerY = dragLayerPos[1];

        switch (action) {
        case MotionEvent.ACTION_DOWN:
            // Remember where the motion event started
            mMotionDownX = dragLayerX;
            mMotionDownY = dragLayerY;

            if ((dragLayerX < mScrollZone) || (dragLayerX > mScrollView.getWidth() - mScrollZone)) {
                mScrollState = SCROLL_WAITING_IN_ZONE;
                mHandler.postDelayed(mScrollRunnable, SCROLL_DELAY);
            } else {
                mScrollState = SCROLL_OUTSIDE_ZONE;
            }
            handleMoveEvent(dragLayerX, dragLayerY);
            break;
        case MotionEvent.ACTION_MOVE:
            handleMoveEvent(dragLayerX, dragLayerY);
            break;
        case MotionEvent.ACTION_UP:
            // Ensure that we've processed a move event at the current pointer location.
            handleMoveEvent(dragLayerX, dragLayerY);
            mHandler.removeCallbacks(mScrollRunnable);

            if (mDragging) {
                PointF vec = isFlingingToDelete(mDragObject.dragSource);
                if (!DeleteDropTarget.willAcceptDrop(mDragObject.dragInfo)) {
                    vec = null;
                }
                if (vec != null) {
                    dropOnFlingToDeleteTarget(dragLayerX, dragLayerY, vec);
                } else {
                    drop(dragLayerX, dragLayerY);
                }
            }
            endDrag();
            break;
        case MotionEvent.ACTION_CANCEL:
            mHandler.removeCallbacks(mScrollRunnable);
            cancelDrag();
            break;
        }

        return true;
    }

    /**
     * Determines whether the user flung the current item to delete it.
     *
     * @return the vector at which the item was flung, or null if no fling was detected.
     */
    private PointF isFlingingToDelete(DragSource source) {
        if (mFlingToDeleteDropTarget == null) return null;
        if (!source.supportsFlingToDelete()) return null;

        ViewConfiguration config = ViewConfiguration.get(mLauncher);
        mVelocityTracker.computeCurrentVelocity(1000, config.getScaledMaximumFlingVelocity());

        if (mVelocityTracker.getYVelocity() < mFlingToDeleteThresholdVelocity) {
            // Do a quick dot product test to ensure that we are flinging upwards
            PointF vel = new PointF(mVelocityTracker.getXVelocity(),
                    mVelocityTracker.getYVelocity());
            PointF upVec = new PointF(0f, -1f);
            float theta = (float) Math.acos(((vel.x * upVec.x) + (vel.y * upVec.y)) /
                    (vel.length() * upVec.length()));
            if (theta <= Math.toRadians(MAX_FLING_DEGREES)) {
                return vel;
            }
        }
        return null;
    }

    private void dropOnFlingToDeleteTarget(float x, float y, PointF vel) {
        final int[] coordinates = mCoordinatesTemp;

        mDragObject.x = coordinates[0];
        mDragObject.y = coordinates[1];

        // Clean up dragging on the target if it's not the current fling delete target otherwise,
        // start dragging to it.
        if (mLastDropTarget != null && mFlingToDeleteDropTarget != mLastDropTarget) {
            mLastDropTarget.onDragExit(mDragObject);
        }

        // Drop onto the fling-to-delete target
        boolean accepted = false;
        mFlingToDeleteDropTarget.onDragEnter(mDragObject);
        // We must set dragComplete to true _only_ after we "enter" the fling-to-delete target for
        // "drop"
        mDragObject.dragComplete = true;
        mFlingToDeleteDropTarget.onDragExit(mDragObject);
        if (mFlingToDeleteDropTarget.acceptDrop(mDragObject)) {
            mFlingToDeleteDropTarget.onFlingToDelete(mDragObject, mDragObject.x, mDragObject.y,
                    vel);
            accepted = true;
        }
        mDragObject.dragSource.onDropCompleted((View) mFlingToDeleteDropTarget, mDragObject, true,
                accepted);
    }

    private void drop(float x, float y) {
        final int[] coordinates = mCoordinatesTemp;
        final DropTarget dropTarget = findDropTarget((int) x, (int) y, coordinates);

        mDragObject.x = coordinates[0];
        mDragObject.y = coordinates[1];
        boolean accepted = false;
        if (dropTarget != null) {
            mDragObject.dragComplete = true;
            dropTarget.onDragExit(mDragObject);
            if (dropTarget.acceptDrop(mDragObject)) {
                dropTarget.onDrop(mDragObject);
                accepted = true;
            }
        }
        mDragObject.dragSource.onDropCompleted((View) dropTarget, mDragObject, false, accepted);
    }

    private DropTarget findDropTarget(int x, int y, int[] dropCoordinates) {
        final Rect r = mRectTemp;

        final ArrayList<DropTarget> dropTargets = mDropTargets;
        final int count = dropTargets.size();
        for (int i=count-1; i>=0; i--) {
            DropTarget target = dropTargets.get(i);
            if (!target.isDropEnabled())
                continue;

            target.getHitRectRelativeToDragLayer(r);

            mDragObject.x = x;
            mDragObject.y = y;
            if (r.contains(x, y)) {

                dropCoordinates[0] = x;
                dropCoordinates[1] = y;
                mLauncher.getDragLayer().mapCoordInSelfToDescendent((View) target, dropCoordinates);

                return target;
            }
        }
        return null;
    }

    public void setDragScoller(DragScroller scroller) {
        mDragScroller = scroller;
    }

    public void setWindowToken(IBinder token) {
        mWindowToken = token;
    }

    /**
     * Sets the drag listner which will be notified when a drag starts or ends.
     */
    public void addDragListener(DragListener l) {
        mListeners.add(l);
    }

    /**
     * Remove a previously installed drag listener.
     */
    public void removeDragListener(DragListener l) {
        mListeners.remove(l);
    }

    /**
     * Add a DropTarget to the list of potential places to receive drop events.
     */
    public void addDropTarget(DropTarget target) {
        mDropTargets.add(target);
    }

    /**
     * Don't send drop events to <em>target</em> any more.
     */
    public void removeDropTarget(DropTarget target) {
        mDropTargets.remove(target);
    }

    /**
     * Sets the current fling-to-delete drop target.
     */
    public void setFlingToDeleteDropTarget(DropTarget target) {
        mFlingToDeleteDropTarget = target;
    }

    private void acquireVelocityTrackerAndAddMovement(MotionEvent ev) {
        if (mVelocityTracker == null) {
            mVelocityTracker = VelocityTracker.obtain();
        }
        mVelocityTracker.addMovement(ev);
    }

    private void releaseVelocityTracker() {
        if (mVelocityTracker != null) {
            mVelocityTracker.recycle();
            mVelocityTracker = null;
        }
    }

    /**
     * Set which view scrolls for touch events near the edge of the screen.
     */
    public void setScrollView(View v) {
        mScrollView = v;
    }

    DragView getDragView() {
        return mDragObject.dragView;
    }

    private class ScrollRunnable implements Runnable {
        private int mDirection;

        ScrollRunnable() {
        }

        public void run() {
            if (mDragScroller != null) {
                if (mDirection == SCROLL_LEFT) {
                    mDragScroller.scrollLeft();
                } else {
                    mDragScroller.scrollRight();
                }
                mScrollState = SCROLL_OUTSIDE_ZONE;
                mDistanceSinceScroll = 0;
                mDragScroller.onExitScrollArea();
                mLauncher.getDragLayer().onExitScrollArea();

                if (isDragging()) {
                    checkScrollState(mLastTouch[0], mLastTouch[1]);
                }
            }
        }

        void setDirection(int direction) {
            mDirection = direction;
        }
    }
}


text:
/*
 * misc/bximage.c
 * $Id: bxcommit.c,v 1.13 2008/02/05 22:57:42 sshwarts Exp $
 *
 * Commits a redolog file in a flat file for bochs images.
 *
 */

#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#ifndef _MSC_VER
#include <unistd.h>
#else
#include <io.h>
#endif
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
#include <assert.h>
#ifdef WIN32
#  include <conio.h>
#endif
#include "config.h"

#include <string.h>

#if !BX_HAVE_SNPRINTF
#include <stdarg.h>
/* XXX use real snprintf */
/* if they don't have snprintf, just use sprintf */
int snprintf (char *s, size_t maxlen, const char *format, ...)
{
  va_list arg;
  int done;

  va_start (arg, format);
  done = vsprintf (s, format, arg);
  va_end (arg);

  return done;
}
#endif  /* !BX_HAVE_SNPRINTF */

#include "../osdep.h"

#define HDIMAGE_HEADERS_ONLY 1
#include "../iodev/hdimage.h"

char *EOF_ERR = "ERROR: End of input";
char *rcsid = "$Id: bxcommit.c,v 1.13 2008/02/05 22:57:42 sshwarts Exp $";
char *divider = "========================================================================";

void myexit (int code)
{
#ifdef WIN32
  printf ("\nPress any key to continue\n");
  getch();
#endif
  exit(code);
}

/* stolen from main.cc */
void bx_center_print (FILE *file, char *line, int maxwidth)
{
  int imax;
  int i;
  imax = (maxwidth - strlen(line)) >> 1;
  for (i=0; i<imax; i++) fputc (' ', file);
  fputs (line, file);
}

void
print_banner ()
{
  printf ("%s\n", divider);
  bx_center_print (stdout, "bxcommit\n", 72);
  bx_center_print (stdout, "Undoable Disk Image Commit Tool for Bochs\n", 72);
  bx_center_print (stdout, rcsid, 72);
  printf ("\n%s\n", divider);
}

/* this is how we crash */
void fatal (char *c)
{
  printf ("%s\n", c);
  myexit (1);
}

/* remove leading spaces, newline junk at end.  returns pointer to
 cleaned string, which is between s0 and the null */
char *
clean_string (char *s0)
{
  char *s = s0;
  char *ptr;
  /* find first nonblank */
  while (isspace (*s))
    s++;
  /* truncate string at first non-alphanumeric */
  ptr = s;
  while (isprint (*ptr))
    ptr++;
  *ptr = 0;
  return s;
}

/* returns 0 on success, -1 on failure.  The value goes into out. */
int
ask_int (char *prompt, int min, int max, int the_default, int *out)
{
  int n = max + 1;
  char buffer[1024];
  char *clean;
  int illegal;
  while (1) {
    printf ("%s", prompt);
    printf ("[%d] ", the_default);
    if (!fgets (buffer, sizeof(buffer), stdin))
      return -1;
    clean = clean_string (buffer);
    if (strlen(clean) < 1) {
      // empty line, use the default
      *out = the_default;
      return 0;
    }
    illegal = (1 != sscanf (buffer, "%d", &n));
    if (illegal || n<min || n>max) {
      printf ("Your choice (%s) was not an integer between %d and %d.\n\n",
	  clean, min, max);
    } else {
      // choice is okay
      *out = n;
      return 0;
    }
  }
}

int
ask_menu (char *prompt, int n_choices, char *choice[], int the_default, int *out)
{
  char buffer[1024];
  char *clean;
  int i;
  *out = -1;
  while (1) {
    printf ("%s", prompt);
    printf ("[%s] ", choice[the_default]);
    if (!fgets (buffer, sizeof(buffer), stdin))
      return -1;
    clean = clean_string (buffer);
    if (strlen(clean) < 1) {
      // empty line, use the default
      *out = the_default;
      return 0;
    }
    for (i=0; i<n_choices; i++) {
      if (!strcmp (choice[i], clean)) {
	// matched, return the choice number
	*out = i;
	return 0;
      }
    }
    printf ("Your choice (%s) did not match any of the choices:\n", clean);
    for (i=0; i<n_choices; i++) {
      if (i>0) printf (", ");
      printf ("%s", choice[i]);
    }
    printf ("\n");
  }
}

int
ask_yn (char *prompt, int the_default, int *out)
{
  char buffer[16];
  char *clean;
  *out = -1;
  while (1) {
    printf ("%s", prompt);
    printf ("[%s] ", the_default?"yes":"no");
    if (!fgets (buffer, sizeof(buffer), stdin))
      return -1;
    clean = clean_string (buffer);
    if (strlen(clean) < 1) {
      // empty line, use the default
      *out = the_default;
      return 0;
    }
    switch (tolower(clean[0])) {
      case 'y': *out=1; return 0;
      case 'n': *out=0; return 0;
    }
    printf ("Please type either yes or no.\n");
  }
}

int
ask_string (char *prompt, char *the_default, char *out)
{
  char buffer[1024];
  char *clean;
  out[0] = 0;
  printf ("%s", prompt);
  printf ("[%s] ", the_default);
  if (!fgets (buffer, sizeof(buffer), stdin))
    return -1;
  clean = clean_string (buffer);
  if (strlen(clean) < 1) {
    // empty line, use the default
    strcpy (out, the_default);
    return 0;
  }
  strcpy (out, clean);
  return 0;
}

/* produce the image file */
int commit_redolog (char *flatname, char *redologname )
{
  int flatfd, redologfd;
  redolog_header_t header;
  Bit32u *catalog, catalog_size;
  Bit8u  *bitmap;
  Bit32u i, bitmap_blocs, extent_blocs;
  Bit8u  buffer[512];

  // check if flat file exists
  flatfd = open (flatname, O_WRONLY
#ifdef O_BINARY
                         | O_BINARY
#endif
                  );
  if (flatfd<0) {
    fatal ("ERROR: flat file not found or not writable");
  }

  // Check if redolog exists
  printf("%s\n",redologname);
  redologfd = open (redologname, O_RDONLY
#ifdef O_BINARY
                         | O_BINARY
#endif
                  );
  if (redologfd<0) {
    fatal ("ERROR: redolog file not found");
  }

  printf ("\nReading redolog header: [");

  if (read(redologfd, &header, STANDARD_HEADER_SIZE) != STANDARD_HEADER_SIZE)
     fatal ("\nERROR: while reading redolog header!");

  // Print infos on redlog
  printf("Type='%s', Subtype='%s', Version=%d.%d] Done.",
           header.standard.type, header.standard.subtype,
           dtoh32(header.standard.version)/0x10000,
           dtoh32(header.standard.version)%0x10000);

  printf ("\nChecking redolog header: [");

  if (strcmp((char *)header.standard.magic, STANDARD_HEADER_MAGIC) != 0)
     fatal ("\nERROR: bad magic in redolog header!");

  if (strcmp((char *)header.standard.type, REDOLOG_TYPE) != 0)
     fatal ("\nERROR: bad type in redolog header!");

  if (strcmp((char *)header.standard.subtype, REDOLOG_SUBTYPE_UNDOABLE) != 0)
     fatal ("\nERROR: bad subtype in redolog header!");

  if (header.standard.version != htod32(STANDARD_HEADER_VERSION))
     fatal ("\nERROR: bad version in redolog header!");

  printf("#entries=%d, bitmap size=%d, exent size = %d] Done.",
         dtoh32(header.specific.catalog),
         dtoh32(header.specific.bitmap),
         dtoh32(header.specific.extent));

  catalog = (Bit32u*)malloc(dtoh32(header.specific.catalog) * sizeof(Bit32u));
  bitmap = (Bit8u*)malloc(dtoh32(header.specific.bitmap));
  printf ("\nReading Catalog: [");

  lseek(redologfd, dtoh32(header.standard.header), SEEK_SET);

  catalog_size = dtoh32(header.specific.catalog) * sizeof(Bit32u);
  if ((Bit32u) read(redologfd, catalog, catalog_size) != catalog_size)
     fatal ("\nERROR: while reading redolog catalog!");

  printf ("] Done.");

  printf ("\nCommitting changes to flat file: [  0%%]");

  bitmap_blocs = 1 + (dtoh32(header.specific.bitmap) - 1) / 512;
  extent_blocs = 1 + (dtoh32(header.specific.extent) - 1) / 512;

  for(i=0; i<dtoh32(header.specific.catalog); i++)
  {
          printf("\x8\x8\x8\x8\x8%3d%%]", (i+1)*100/dtoh32(header.specific.catalog));
          fflush(stdout);

          if (dtoh32(catalog[i]) != REDOLOG_PAGE_NOT_ALLOCATED)
          {
                  Bit64s bitmap_offset;
                  Bit32u bitmap_size, j;

                  bitmap_offset  = (Bit64s)STANDARD_HEADER_SIZE + (dtoh32(header.specific.catalog) * sizeof(Bit32u));
                  bitmap_offset += (Bit64s)512 * dtoh32(catalog[i]) * (extent_blocs + bitmap_blocs);

                  // Read bitmap
                  lseek(redologfd, bitmap_offset, SEEK_SET);

                  bitmap_size = dtoh32(header.specific.bitmap);
                  if ((Bit32u) read(redologfd, bitmap, bitmap_size) != bitmap_size)
                          fatal ("\nERROR: while reading bitmap from redolog !");

                  for(j=0; j<dtoh32(header.specific.bitmap); j++)
                  {
                          Bit32u bit;

                          for(bit=0; bit<8; bit++)
                          {
                                  if ( (bitmap[j] & (1<<bit)) != 0)
                                  {
                                          Bit64s flat_offset, bloc_offset;

                                          bloc_offset  = bitmap_offset + ((Bit64s)512 * (bitmap_blocs + ((j*8)+bit)));

                                          lseek(redologfd, (off_t)bloc_offset, SEEK_SET);

                                          if (read(redologfd, buffer, 512) != 512)
                                                fatal ("\nERROR: while reading bloc from redolog !");

                                          flat_offset  = (Bit64s)i * (dtoh32(header.specific.extent));
                                          flat_offset += (Bit64s)512 * ((j * 8) + bit);

                                          lseek(flatfd, (off_t)flat_offset, SEEK_SET);

                                          if (write(flatfd, buffer, 512) != 512)
                                                fatal ("\nERROR: while writing bloc in flatfile !");

                                  }
                          }
                  }
          }
  }
  printf (" Done.");
  printf ("\n");

  close (flatfd);
  close (redologfd);
  return 0;
}

int main()
{
  char filename[256];
  char tmplogname[256];
  char redologname[256];
  int  remove;

  print_banner();
  filename[0] = 0;
  redologname[0] = 0;

  if (ask_string("\nWhat is the flat image name?\n", "c.img", filename) < 0)
    fatal (EOF_ERR);

  snprintf(tmplogname,256,"%s%s", filename, UNDOABLE_REDOLOG_EXTENSION);

  if (ask_string("\nWhat is the redolog name?\n", tmplogname, redologname) < 0)
    fatal (EOF_ERR);

  if (ask_yn("\nShall I remove the redolog afterwards?\n", 1, &remove) < 0)
    fatal (EOF_ERR);

  commit_redolog(filename, redologname);

  if (remove) {
    if (unlink(redologname) != 0)
       fatal ("ERROR: while removing the redolog !\n");
  }

  // make picky compilers (c++, gcc) happy,
  // even though we leave via 'myexit' just above
  return 0;
}

redpajama_set_name: RedPajamaGithub


text:
package me.ocs.commons.jpa;

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

/**
 * @author 刘飞 E-mail:liufei_it@126.com
 *
 * @version 1.0.0
 * @since 2014年12月17日 下午11:01:41
 */
public interface GenericDAO<T, PK extends Serializable> extends EntityManagerOperations {

	List<T> queryNative(String sql);

	List<T> queryNative(String sql, Map<String, Object> args);

	List<T> queryNative(String sql, Object[] args);

	T queryNativeForObject(String sql, Object[] args);

	T queryNativeForObject(String sql, Map<String, Object> args);

	List<T> query(String hql);

	List<T> query(String hql, Map<String, Object> args);

	List<T> query(String hql, Object[] args);

	T queryForObject(String hql, Object[] args);

	T queryForObject(String hql, Map<String, Object> args);

	List<T> queryNamed(String queryName);

	List<T> queryNamed(String queryName, Map<String, Object> args);

	List<T> queryNamed(String queryName, Object[] args);

	T queryNamedForObject(String queryName, Map<String, Object> args);

	T queryNamedForObject(String queryName, Object[] args);

	int queryUpdate(String hql, Map<String, Object> args);

	int queryUpdate(String hql, Object[] args);

	int queryNamedUpdate(String queryName, Map<String, Object> args);

	int queryNamedUpdate(String queryName, Object[] args);

	int queryNativeUpdate(String sql, Object[] args);

	int queryNativeUpdate(String sql, Map<String, Object> args);

	T get(PK id);

	T getForUpdate(PK id);

	T load(PK id);

	List<T> findAll();
}


text:
import React, { PropTypes } from 'react';
import Avatar from 'material-ui/lib/avatar';
import FontIcon from 'material-ui/lib/font-icon';
import List from 'material-ui/lib/lists/list';
import ListItem from 'material-ui/lib/lists/list-item';
import Divider from 'material-ui/lib/divider';

export default class MessageListItem extends React.Component {

  constructor(props) {
    super(props);

  }

  render() {
    const { message } = this.props;

    return (

        <ListItem
            disabled={true}
            leftAvatar={
              <Avatar src= {message.user_image || 'http://lorempixel.com/400/200'} />
            }
          >
          {message.user|| message.user_name}

          {message.time}

{message.text}

        </ListItem>
        <Divider inset={true} />

    );
  }
}


text:
exports.defineAutoTests = function() {

  var fail = function (done) {
    expect(true).toBe(false);
    done();
  },
  succeed = function (done) {
    expect(true).toBe(true);
    done();
  };

  describe('Plugin availability', function () {
    it("window.plugins.calendar should exist", function() {
      expect(window.plugins.calendar).toBeDefined();
    });
  });

  describe('API functions', function () {
    it("should define createEventWithOptions", function() {
      expect(window.plugins.calendar.createEventWithOptions).toBeDefined();
    });
  });

  /*
  TODO extend - this is a copy-paste example of Toast
  describe('Invalid usage', function () {
    it("should fail due to an invalid position", function(done) {
     window.plugins.toast.show('hi', 'short', 'nowhere', fail.bind(null, done), succeed.bind(null, done));
    });

    it("should fail due to an invalid duration", function(done) {
     window.plugins.toast.show('hi', 'medium', 'top', fail.bind(null, done), succeed.bind(null, done));
    });
  });
  */
};


text:
using System.Runtime.InteropServices;

namespace abbTools.AppRemoteABB
{
    class RemoteMouse
    {
        /********************************************************
         ***  REMOTE MOUSE - data
         ********************************************************/

        private enum myMouseBtn
        {
            left = 1,
            middle = 2,
            right = 3,
        }

        //dll method to simulate mouse movement
        [DllImport("user32.dll")]
        static extern bool SetCursorPos(int x, int y);

        //dll method to simulate mouse clicks
        [DllImport("user32.dll")]
        static extern void mouse_event(int dwFlags, int dx, int dy, int cButtons, int dwExtraInfo);

        //definition of mouse button events used in above dll method
        private const int MOUSE_EVENT_LD = 0x02;
        private const int MOUSE_EVENT_LU = 0x04;
        private const int MOUSE_EVENT_RD = 0x08;
        private const int MOUSE_EVENT_RU = 0x10;
        private const int MOUSE_EVENT_MD = 0x20;
        private const int MOUSE_EVENT_MU = 0x40;

        /********************************************************
         ***  REMOTE MOUSE - main actions
         ********************************************************/

        /// <summary>
        /// Method used to execute mouse actions
        /// </summary>
        /// <param name="actions">Mouse actions to do</param>
        public void doActions(string actions)
        {
            //sim mouse if there are some actions to do
            if (actions.Length > 0) {
                int startPos = 0, commaPos = 0;
                string currAction = "";
                //while there are actions to do
                while (commaPos != actions.Length) {
                    //find button identifier and comma(s)
                    startPos = actions.IndexOf('[', commaPos);
                    commaPos = actions.IndexOf(',', startPos + 1);
                    //if no start sign was found then end loop
                    if (startPos == -1) break;
                    //if no comma was found then this is the last command
                    if (commaPos == -1) commaPos = actions.Length;
                    //get action string
                    currAction = actions.Substring(startPos, commaPos - startPos);
                    //do current action
                    execute(interpret(currAction));
                }
            }
        }

        /// <summary>
        /// Function used to decode givent string action(s)
        /// </summary>
        /// <param name="action">String action to decode</param>
        /// <returns>Decoded mouse actions useful to execute</returns>
        private int[] interpret(string action)
        {
            int[] corrdsDiv = { action.IndexOf('['), action.IndexOf(';'), action.IndexOf(']') };
            string curr;
            //get coordinates from inputted action string
            curr = action.Substring(corrdsDiv[0] + 1, corrdsDiv[1] - corrdsDiv[0] - 1);
            int coordX = short.Parse(curr);
            curr = action.Substring(corrdsDiv[1] + 1, corrdsDiv[2] - corrdsDiv[1] - 1);
            int coordY = short.Parse(curr);
            //get button ID from inpputed action string
            curr = action.Substring(corrdsDiv[2] + 1, 1);
            int btn = -1;
            switch (curr) {
                case "L":
                    btn = (int)myMouseBtn.left;
                    break;
                case "M":
                    btn = (int)myMouseBtn.middle;
                    break;
                case "R":
                    btn = (int)myMouseBtn.right;
                    break;
                default:
                    break;
            }
            //fill result
            int[] result = { coordX, coordY, btn };

            return result;
        }

        /// <summary>
        /// Main method to simulate mouse move and key input
        /// </summary>
        /// <param name="details">Decoded action parameters [coordX, coordY, btn]</param>
        private void execute(int[] details)
        {
            //check input data (only positive integers are ok
            if (details[0] > 0 && details[1] > 0 && details[2] > 0) {
                int buttonActionDown = 0x00, buttonActionUp = 0x00;
                //convert int button to dlls accepted format
                switch (details[2]) {
                    case (int)myMouseBtn.left:
                        buttonActionDown = MOUSE_EVENT_LD;
                        buttonActionUp = MOUSE_EVENT_LU;
                        break;
                    case (int)myMouseBtn.middle:
                        buttonActionDown = MOUSE_EVENT_MD;
                        buttonActionUp = MOUSE_EVENT_MU;
                        break;
                    case (int)myMouseBtn.right:
                        buttonActionDown = MOUSE_EVENT_RD;
                        buttonActionUp = MOUSE_EVENT_RU;
                        break;
                    default:
                        break;
                }
                //move mouse cursor to defined position
                SetCursorPos(details[0], details[1]);
                mouse_event(buttonActionDown, details[0], details[1], 0, 0);
                System.Threading.Thread.Sleep(10);
                mouse_event(buttonActionUp, details[0], details[1], 0, 0);
            }
        }
    }
}


text:
package com.jwdroid;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import android.app.Activity;
import android.content.Context;
import android.database.Cursor;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Parcel;
import android.os.Parcelable;
import android.text.Html;
import android.util.AttributeSet;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.Display;
import android.view.GestureDetector;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.GestureDetector.SimpleOnGestureListener;
import android.widget.BaseAdapter;
import android.widget.HorizontalScrollView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.ScrollView;
import android.widget.SimpleAdapter;
import android.widget.TextView;

public class HorizontalPanelsView extends HorizontalScrollView {

	private static final String TAG = "JWHorizontalGroupsView";

    private static final int SWIPE_MIN_DISTANCE = 3;
    private static final int SWIPE_THRESHOLD_VELOCITY = 200;
    private static final int SCROLL_MIN_DISTANCE_X = 40;
    private static final int SCROLL_MIN_DISTANCE_Y = 20;

    private static final int NONE = 0;
    private static final int VERTICAL = 1;
    private static final int HORIZONTAL = 2;

    private GestureDetector mGestureDetector;
    private int mActiveScroll = 0;
    private float mDownX = 0, mDownY = 0, mLastX = 0, mLastY = 0;
    private int mLastScrollX = 0, mLastScrollY = 0;

    private int mScrollingDirection = 0;

    private LinearLayout mInternalWrapper;

    private OnActiveChangedListener mActiveChangedListener;

    public HorizontalPanelsView(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);

        initInternalWrapper();
        mGestureDetector = new GestureDetector(new MyGestureDetector());
    }

    public HorizontalPanelsView(Context context, AttributeSet attrs) {
        super(context, attrs);

        initInternalWrapper();
        mGestureDetector = new GestureDetector(new MyGestureDetector());
    }

    public HorizontalPanelsView(Context context) {
        super(context);

        initInternalWrapper();
        mGestureDetector = new GestureDetector(new MyGestureDetector());
    }

    public void setOnActiveChangedListener(OnActiveChangedListener listener) {
    	mActiveChangedListener = listener;
    }

    public int getActivePos() {
    	return mActiveScroll;
    }

    public ViewGroup getActiveViewGroup() {
    	return (ViewGroup)mInternalWrapper.getChildAt(mActiveScroll);
    }

    public void setActiveViewGroup(int n) {

    	post(new Runnable() {
    	    @Override
    	    public void run() {
    	        int featureWidth = getMeasuredWidth();
    	    	scrollTo(featureWidth*mActiveScroll, 0);
    	    }
    	});

    	mActiveScroll = n;
    }

    public void initInternalWrapper() {
    	 mInternalWrapper = new LinearLayout(getContext());
         mInternalWrapper.setLayoutParams(new LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT));
         mInternalWrapper.setOrientation(LinearLayout.HORIZONTAL);
         addView(mInternalWrapper);
    }

    public void addViewGroup(ViewGroup viewGroup) {
    	mInternalWrapper.addView(viewGroup);
    }

    public void removeViewGroups() {
    	mInternalWrapper.removeAllViews();
    }

    public int getViewGroupsCount() {
    	return mInternalWrapper.getChildCount();
    }

    public ViewGroup getViewGroupAt(int index) {
    	return (ViewGroup)mInternalWrapper.getChildAt(index);
    }

    @Override
    public boolean onTouchEvent(MotionEvent event) {
    	Log.w(TAG, String.format("touch action=%d x=%f y=%f dir=%d",event.getAction(),event.getX(),event.getY(),mScrollingDirection));

    	return processTouchEvent(event);
    }

    @Override
    public boolean onInterceptTouchEvent(MotionEvent event) {
    	Log.w(TAG, String.format("intercept action=%d x=%f y=%f dir=%d",event.getAction(),event.getX(),event.getY(),mScrollingDirection));

    	processTouchEvent(event);

    	return mScrollingDirection == HORIZONTAL;
    }

    private boolean processTouchEvent(MotionEvent event) {

    	float density = getResources().getDisplayMetrics().density;

    	if (mGestureDetector.onTouchEvent(event)) {
            return false;
        }
    	else if(event.getAction() == MotionEvent.ACTION_DOWN) {
    		 mDownX = mLastX = event.getX();
    		 mDownY = mLastY = event.getY();
    		 mLastScrollX = getScrollX();
    		 mScrollingDirection = NONE;
    		 return true;
    	 }
    	 else if(event.getAction() == MotionEvent.ACTION_MOVE ) {
    		 float curX = event.getX();
    		 float curY = event.getY();

    		 if(mDownX == 0) {
    			 mDownX = curX;
    			 mDownY = curY;
    			 mLastScrollX = getScrollX();
    		 }

    		 if(mScrollingDirection == NONE && Math.abs(Math.round(mDownX-curX)) > SCROLL_MIN_DISTANCE_X*density || mScrollingDirection == HORIZONTAL ) {
	    		 mScrollingDirection = HORIZONTAL;
	    		 scrollTo(Math.round(getScrollX() - curX + mLastX), 0);
    		 }
    		 if(mScrollingDirection == NONE && Math.abs(Math.round(mDownY-curY)) > SCROLL_MIN_DISTANCE_Y*density || mScrollingDirection == VERTICAL ) {
	    		 mScrollingDirection = VERTICAL;
	    	}

    		 mLastX = curX;
    		 mLastY = curY;
    		 return true;
    	 }
         else if(event.getAction() == MotionEvent.ACTION_UP || event.getAction() == MotionEvent.ACTION_CANCEL ){
        	 if(mScrollingDirection == HORIZONTAL) {
	             int scrollX = getScrollX();
	             Display display = ((Activity)getContext()).getWindowManager().getDefaultDisplay();
	         	 int width = display.getWidth();
	             int featureWidth = getMeasuredWidth();
	             mActiveScroll = (scrollX + featureWidth/2)/featureWidth;
	             int scrollTo = mActiveScroll*featureWidth;
	             smoothScrollTo(scrollTo, 0);
	             if(mActiveChangedListener != null)
	            	 mActiveChangedListener.onActiveChanged(mActiveScroll);
        	 }
        	 mDownX = mDownY = 0;
             mScrollingDirection = NONE;
             return true;
         }
         else{
             return false;
         }
    }

    class MyGestureDetector extends SimpleOnGestureListener {
        @Override
        public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) {
            try {

            	float density = getResources().getDisplayMetrics().density;

            	if( mScrollingDirection != VERTICAL ) {
	            	Log.w(TAG, String.format("onFling x1:%f (%f), x2:%f", e1.getX(), mDownX, e2.getX()));

	                if(e1.getX() - e2.getX() > SWIPE_MIN_DISTANCE*density && Math.abs(velocityX) > SWIPE_THRESHOLD_VELOCITY*density) {
	                	int featureWidth = getMeasuredWidth();
	                    mActiveScroll = (mActiveScroll < (getViewGroupsCount() - 1))? mActiveScroll + 1:getViewGroupsCount() -1;
	                    smoothScrollTo(mActiveScroll*featureWidth, 0);
	                    if(mActiveChangedListener != null)
	   	            	 	mActiveChangedListener.onActiveChanged(mActiveScroll);
	                    mScrollingDirection = NONE;
	                    return true;
	                }

	                else if (e2.getX() - e1.getX() > SWIPE_MIN_DISTANCE*density && Math.abs(velocityX) > SWIPE_THRESHOLD_VELOCITY*density) {
	                	int featureWidth = getMeasuredWidth();
	                    mActiveScroll = (mActiveScroll > 0)? mActiveScroll - 1:0;
	                    smoothScrollTo(mActiveScroll*featureWidth, 0);
	                    if(mActiveChangedListener != null)
	   	            	 	mActiveChangedListener.onActiveChanged(mActiveScroll);
	                    mScrollingDirection = NONE;
	                    return true;
	                }
            	}
            	else {
            		mScrollingDirection = NONE;
            	}

            } catch (Exception e) {
                    Log.e("Fling", "There was an error processing the Fling event:" + e.getMessage());
            }
            return false;
        }
    }

    public interface OnActiveChangedListener {
    	public void  onActiveChanged(int newActive);
    };

}


text:
from abc import abstractmethod, ABC

from common.numpy_fast import clip
from common.realtime import DT_CTRL

MIN_STEER_SPEED = 0.3

class LatControl(ABC):
  def __init__(self, CP, CI):
    self.sat_count_rate = 1.0 * DT_CTRL
    self.sat_limit = CP.steerLimitTimer
    self.sat_count = 0.

    # we define the steer torque scale as [-1.0...1.0]
    self.steer_max = 1.0

  @abstractmethod
  def update(self, active, CS, VM, params, last_actuators, steer_limited, desired_curvature, desired_curvature_rate, llk):
    pass

  def reset(self):
    self.sat_count = 0.

  def _check_saturation(self, saturated, CS, steer_limited):
    if saturated and CS.vEgo > 10. and not steer_limited and not CS.steeringPressed:
      self.sat_count += self.sat_count_rate
    else:
      self.sat_count -= self.sat_count_rate
    self.sat_count = clip(self.sat_count, 0.0, self.sat_limit)
    return self.sat_count > (self.sat_limit - 1e-3)


text:
<!DOCTYPE html>

    <meta charset="UTF-8">

    <title>A Pen by  Cristal Garcia</title>

     The Basics of the Web and HTML

The worldwide web is made up of HTML documents that are processed and communicated via computers. The HTML documents are what glue evertything together and form the basis of the web. Hyperlinks link everything; making the web weblike.

The way the process starts is, an individual goes to a webpage by sending an  HTTP  request to a  server via a computer.
The server then searches for the appropriate html document and sends it back to the user's page where the  web browser
 interprets the information into a form that can be seen on the user's screen.

 HTML (Hyper Text Markup Language)

As mentioned before, these documents make up the heart of the web. HTML consists of:

-Text context (what you see)

-Markup (what the information will look like)

-References to other documents (i.e. images and videos)

-Links to other pages

HTML Markup:  are made up of tags using the less than  and greater than symbols and contribute to the aesthetics and functionality of content.
There are multiple uses for markups. For the most part, HTML markups contain an  opening tag , the  content is then written after the opening tag, and is followed by a  closing tag. This whole expression is called an element.
You can put content in bold, italics; create links for additional content; and divide sentence structures. You can also nest multiple markups with each other.

 That said, because computers do not have the flexibility as humans, the commands and element markups must be precise; otherwise mistakes can produce huge programming issues. Being familiar with whitespace and inline vs. block elements can help demonstrate how the markup language must be literal.

Inline vs. Block Elements
 White space consists of the characters that represent horizontal or vertical space in typography. HTML elements are all found in the white space and because the typography is represented in either a horizontal or vertical space,
HTML elements are either inline ( in the same horizontal thred) or block ( can shift and stay within it's own vertical block space).

To see an example of the general structure of HTML,  click here .


text:
/*
 * File: rt.h
 * Provides common runtime interface for runner.
 */

#ifndef PEL_RT_H
#define PEL_RT_H

namespace pel{

//
//  Base class of runtime
//
class Runtime{
public:
  enum ClassID{
    Runtime_ = 0,
    RtSQLite_,
    RtMemory_,
    RtMySQL_,
    ClassIDSize,
  };

  ClassID ID()const { return id; }

  static bool classof(const Runtime* p){
    return p->ID() == Runtime_;
  }

  //!!! the only way to destory pointers.
  void Destroy();

  //------------------------------------------
  // Interfaces showed as below provided by runtime.

  // return field id
  int AddField(int model, const char* field, int type);

  // return model id
  int AddModel(const char* name);

  // return relation id
  int AddRel(int src, int dist, const char* rel);

  // Connect to runtime
  int Connect(const char* addr, int flags);

  //
  void Disconnect();

  // get field id
  int Field(int model, const char* field);

  // Get env var
  const char* Env(const char* name);

  // Set env var
  int Env(const char* name, const char* val);

  // Get model id
  int Model(const char* name);

  // return relation id
  int Rel(int model, const char* rel);

protected:
  Runtime(): id(Runtime_){}

  explicit Runtime(ClassID sid): id(sid){}

  ~Runtime(){} // empty

private:
  ClassID id;

private:
  Runtime(const Runtime&);
  Runtime& operator=(const Runtime&);
};

} // ~pel

#endif


text:
    #include <direct.h>
    #define GetCurrentDir _getcwd
#else
    #include <unistd.h>
    #define GetCurrentDir getcwd
 #endif

typedef long long Integer;
typedef unsigned long long UInteger;
typedef double Real;
typedef bool Boolean;

#define False false
#define True  true

// CONTROL FUNCTION INLINING
#if defined(__GNUC__) || defined(__GNUG__)
    #define ALWAYS_INLINE inline __attribute__((always_inline))
    #define NEVER_INLINE __attribute__((noinline))
#elif defined(_MSC_VER)
    #define ALWAYS_INLINE __forceinline
    #define NEVER_INLINE __declspec(noinline)
#endif

#define STATIC static

#define INF std::numeric_limits<double>::infinity()

#endif // STD_INC_HPP


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

package org.apache.tapestry.vlib;

import org.apache.tapestry.IPage;

/**
 *  String message property, for many pages that can display an informational message.
 *
 *  @author Howard Lewis Ship
 *  @version $Id$
 *  @since 3.0
 *
 **/

public interface IMessageProperty extends IPage
{
    public String getMessage();
    public void setMessage(String message);
}


text:
package net.md_5.bungee.protocol.packet;

import net.md_5.bungee.protocol.DefinedPacket;
import io.netty.buffer.ByteBuf;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.EqualsAndHashCode;
import lombok.NoArgsConstructor;
import net.md_5.bungee.protocol.AbstractPacketHandler;
import net.md_5.bungee.protocol.ProtocolConstants;

@Data
@NoArgsConstructor
@AllArgsConstructor
@EqualsAndHashCode(callSuper = false)
public class TabCompleteRequest extends DefinedPacket
{

    private String cursor;
    private boolean assumeCommand;
    private boolean hasPositon;
    private long position;

    @Override
    public void read(ByteBuf buf, ProtocolConstants.Direction direction, int protocolVersion)
    {
        cursor = readString( buf );
        if ( protocolVersion >= ProtocolConstants.MINECRAFT_1_9 )
        {
            assumeCommand = buf.readBoolean();
        }

        if ( hasPositon = buf.readBoolean() && protocolVersion >= ProtocolConstants.MINECRAFT_1_8 )
        {
            position = buf.readLong();
        }
    }

    @Override
    public void write(ByteBuf buf, ProtocolConstants.Direction direction, int protocolVersion)
    {
        writeString( cursor, buf );
        if ( protocolVersion >= ProtocolConstants.MINECRAFT_1_9 )
        {
            buf.writeBoolean( assumeCommand );
        }
        if ( protocolVersion >= ProtocolConstants.MINECRAFT_1_8 )
        {
            buf.writeBoolean( hasPositon );
            if ( hasPositon )
            {
                buf.writeLong( position );
            }
        }

    }

    @Override
    public void handle(AbstractPacketHandler handler) throws Exception
    {
        handler.handle( this );
    }
}


text:
/*
	Implementation notes:
	-	The Popup At Event Position popup has property floating:true to mitigate the sampler's
		horizontal scroll offset (the control that allows the side navigation to be dragged
		closed and open).
*/
enyo.kind({
	name: "enyo.sample.PopupSample",
	kind: "enyo.Scroller",
	classes: "popup-sample",
	components: [
		{content: "Popups", classes: "section"},
		{kind: "enyo.Button", name: "buttonBasicAuto", content: "Basic Popup (Auto Dismiss)", ontap: "showPopup", popup: "popupBasicAuto"},
		{kind: "enyo.Popup", name: "popupBasicAuto", classes: "popup", content: "Tap Outside Popup To Dismiss"},
		{classes: "divider"},
		{kind: "enyo.Button", name: "buttonBasic", content: "Basic Popup", ontap: "showPopup", popup: "popupBasic"},
		{kind: "enyo.Popup", name: "popupBasic", autoDismiss: false, classes: "popup", content: "Press Basic Popup Button To Dismiss (Tapping Outside Registers Event)"},
		{classes: "divider"},
		{kind: "enyo.Button", name: "buttonModal", content: "Modal Popup", ontap: "showPopup", popup: "popupModal"},
		{kind: "enyo.Popup", name: "popupModal", modal: true, autoDismiss: false, classes: "popup", components: [
			{content: "Modal Popup (Tapping Outside Does Not Register Event)"},
			{kind: "enyo.Button", name: "buttonCloseModal", content: "Close", ontap: "closeModal"}
		]},
		{classes: "divider"},
		{kind: "enyo.Button", name: "buttonCentered", content: "Centered Popup", ontap: "showPopup", popup: "popupCentered"},
		{kind: "enyo.Popup", name: "popupCentered", centered: true, classes: "popup", content: "Centered Popup"},
		{classes: "divider"},
		{kind: "enyo.Button", name: "buttonScrim", content: "Popup With Scrim", ontap: "showPopup", popup: "popupScrim"},
		{kind: "enyo.Popup", name: "popupScrim", centered: true, floating: true, scrim: true, classes: "popup", content: "Popup With Scrim"},
		{classes: "divider"},
		{kind: "enyo.Button", name: "buttonAtEventPosition", content: "Popup At Event Position", ontap: "showPopupAtEventPosition", popup: "popupEventPosition"},
		{kind: "enyo.Popup", name: "popupEventPosition", floating: true, classes: "popup", content: "Popup At Event Position"},
		{classes: "divider"},
		{kind: "enyo.Button", name: "buttonAtPosition", content: "Popup At Specific Position", ontap: "showPopupAtPosition", popup: "popupPosition"},
		{kind: "enyo.Popup", name: "popupPosition", classes: "popup", content: "Popup In Upper Right"},
		{classes: "divider"},
		{kind: "enyo.Button", name: "buttonAutoHide", content: "Auto Hide Popup", ontap: "showPopupAutoHide", popup: "popupAutoHide"},
		{kind: "enyo.Popup", name: "popupAutoHide", classes: "popup", content: "This Popup Will Disappear In 2s"},
		{classes: "divider"},
		{kind: "enyo.Button", name: "buttonFloating", content: "Floating Popup", ontap: "showPopupFloating", popup: "popupFloating"},
		{kind: "enyo.Popup", name: "popupFloating", floating: true, centered: true, classes: "popup floating", content: "This Popup Will Not Scroll", onHide: "hideFloating"},
		{name: "priority", classes: "priority", showing: false, content: "This Content Is Scrollable"},
		{name: "results", classes: "results"}
	],
	handlers: {
		ontap: "tap"
	},
	tap: function(inSender, inEvent) {
		this.$.results.destroyClientControls();
		this.$.results.createComponent({
			content: "Event  \"" + inEvent.type + "\" from \"" + inEvent.originator.getName() + "\"."
		});
		this.$.results.render();
	},
	closeModal: function(inSender, inEvent) {
		this.$.popupModal.setShowing(false);
	},
	hideFloating: function(inSender, inEvent) {
		this.$.priority.hide();
	},
	showPopup: function(inSender, inEvent) {
		var p = this.$[inSender.popup];
		if (p) {
			// toggle the visibility of the popup
			p.setShowing(!p.getShowing());
		}
	},
	showPopupAtEventPosition: function(inSender, inEvent) {
		var p = this.$[inSender.popup];
		if (p) {
			p.showAtEvent(inEvent);
		}
	},
	showPopupAtPosition: function(inSender, inEvent) {
		var p = this.$[inSender.popup];
		if (p) {
			p.showAtPosition({right: 0, top: 0});
		}
	},
	showPopupAutoHide: function(inSender, inEvent) {
		var p = this.$[inSender.popup];
		if (p) {
			p.setShowing(true);
			enyo.job("autoHidePopup", function() {
				p.hide();
			}, 2000);
		}
	},
	showPopupFloating: function(inSender, inEvent) {
		this.$.priority.setShowing(true);
		var p = this.$[inSender.popup];
		if (p) {
			p.showAtEvent(inEvent);
		}
	}
});


text: let expression = /pattern/flags;


text:
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<!--
Copyright 2016 Goldman Sachs.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

  http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing,
software distributed under the License is distributed on an
"AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
KIND, either express or implied.  See the License for the
specific language governing permissions and limitations
under the License.
-->
<ManagedObject xsi:noNamespaceSchemaLocation="../../../xsd/objectmanager.xsd"
               xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
    <Templates>javeneruma,interface,noki,nuzikuzu,riyoxadipojoxuj,wululu,tetahij</Templates>
    <PackageName>com.gs.fw.lilu.yad.domain.wuyemiy</PackageName>
    <ClassName>RixevohOtozuxeleNihiMaCowonebolekefa</ClassName>
    <SuperClassName>RirupilanoWoraVugi</SuperClassName>
    <DefaultTable>YAD_LAXAVI_TADE_GIMASIWEGELULU</DefaultTable>
    <SchemaName>mut</SchemaName>
    <DatabaseName>tiqo</DatabaseName>
    <ReadOnly>true</ReadOnly>
    <PrimaryKeyAttribute keyClass="CulopedOlorevalaGiduYiBeyidevaqedemoCem">
        <Attribute columnName="TEQUMUJIJ_TADE_PO" javaType="int" sqlType="Ciyisag" name="niwehivawOmimIr"/>
        <Attribute columnName="GIMASIWEGELULU_PO" javaType="int" sqlType="Ciyisag" name="niwuqaxaqukuhuPo"/>
        <Attribute columnName="businessDate" javaType="Timestamp" sqlType="XIZofuxafasElegexaLimanigaw"
                   name="businessDate"/>
    </PrimaryKeyAttribute>
    <Index name="businessDate">businessDate</Index>
</ManagedObject>


text:
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information

namespace DotNetNuke.Entities.Content.Workflow
{
    using System.Collections.Generic;

    using DotNetNuke.Entities.Content.Workflow.Entities;

    /// <summary>
    /// This class is responsible to manage the workflows of the portal.
    /// It provides CRUD operation methods and methods to know the usage of the workflow.
    /// </summary>
    public interface IWorkflowManager
    {
        /// <summary>
        /// This method returns the paginated list of Items that are associated with a workflow.
        /// </summary>
        /// <param name="workflowId">Workflow Id.</param>
        /// <param name="pageIndex">Page index (where 1 is the index of the first page).</param>
        /// <param name="pageSize">Page size.</param>
        /// <returns>List of Usage Items.</returns>
        IEnumerable<WorkflowUsageItem> GetWorkflowUsage(int workflowId, int pageIndex, int pageSize);

        /// <summary>
        /// This method returns the total number of Content Items that are associated with any State of a workflow (even the Published state).
        /// </summary>
        /// <param name="workflowId">Workflow Id.</param>
        /// <returns>Total count of Content Items that are using the specified workflow.</returns>
        int GetWorkflowUsageCount(int workflowId);

        /// <summary>
        /// This method return the list of the Workflows defined for the portal.
        /// </summary>
        /// <param name="portalId">Portal Id.</param>
        /// <returns>List of the Workflows for the portal.</returns>
        IEnumerable<Entities.Workflow> GetWorkflows(int portalId);

        /// <summary>
        /// This method adds a new workflow. It automatically add two system states: "Draft" and "Published".
        /// </summary>
        /// <param name="workflow">Workflow Entity.</param>
        /// <exception cref="DotNetNuke.Entities.Content.Workflow.Exceptions.WorkflowNameAlreadyExistsException">Thrown when a workflow with the same name already exist for the portal.</exception>
        void AddWorkflow(Entities.Workflow workflow);

        /// <summary>
        /// this method update a existing workflow.
        /// </summary>
        /// <param name="workflow">Workflow Entity.</param>
        /// <exception cref="DotNetNuke.Entities.Content.Workflow.Exceptions.WorkflowNameAlreadyExistsException">Thrown when a workflow with the same name already exist for the portal.</exception>
        void UpdateWorkflow(Entities.Workflow workflow);

        /// <summary>
        /// This method hard deletes a workflow.
        /// </summary>
        /// <param name="workflow">Workflow Entity.</param>
        /// <exception cref="DotNetNuke.Entities.Content.Workflow.Exceptions.WorkflowInvalidOperationException">Thrown when a workflow is in use or is a system workflow.</exception>
        void DeleteWorkflow(Entities.Workflow workflow);

        /// <summary>
        /// This method returns a workflow entity by Id.
        /// </summary>
        /// <param name="workflowId">Workflow Id.</param>
        /// <returns>Workflow Entity.</returns>
        Entities.Workflow GetWorkflow(int workflowId);

        /// <summary>
        /// This method returns a workflow entity by Content Item Id. It returns null if the Content Item is not under workflow.
        /// </summary>
        /// <param name="contentItem">Content Item.</param>
        /// <returns>Workflow Entity.</returns>
        Entities.Workflow GetWorkflow(ContentItem contentItem);
    }
}


text:
<?xml version="1.0" encoding="UTF-8"?>
<arquillian xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://jboss.org/schema/arquillian" xsi:schemaLocation="http://jboss.org/schema/arquillian
                         http://jboss.org/schema/arquillian/arquillian_1_0.xsd">

    <defaultProtocol type="Servlet 3.0"/>

    <container qualifier="test" default="true">
        <configuration>
            <property name="jbossHome">${serverRoot:target/wildfly-8.0.0.Final}</property>
            <property name="serverConfig">${serverProfile:standalone-full.xml}</property>
        </configuration>
    </container>
    <container qualifier="debug">
        <configuration>
            <property name="jbossHome">${serverRoot:target/wildfly-8.0.0.Final}</property>
            <property name="serverConfig">${serverProfile:standalone-full.xml}</property>
            <property name="javaVmArguments">-Xrunjdwp:transport=dt_socket,address=55407,server=y,suspend=y -Xmx512m -XX:MaxPermSize=128m</property>
        </configuration>
    </container>

</arquillian>


text:
using Microsoft.Azure.Commands.ScenarioTest.SqlTests;
using Microsoft.WindowsAzure.Commands.ScenarioTest;
using Xunit;
using Xunit.Abstractions;
using RestTestFramework = Microsoft.Rest.ClientRuntime.Azure.TestFramework;

namespace Microsoft.Azure.Commands.Sql.Test.ScenarioTests
{
    public class BlobAuditingClassicStorageTests : SqlTestsBase
    {
        protected override void SetupManagementClients(RestTestFramework.MockContext context)
        {
            var sqlClient = GetSqlClient(context);
            var storageV2Client = GetStorageV2Client(context);
            var newResourcesClient = GetResourcesClient(context);
            Helper.SetupSomeOfManagementClients(sqlClient, storageV2Client, newResourcesClient);
        }

        public BlobAuditingClassicStorageTests(ITestOutputHelper output) : base(output)
        {
        }

        [Fact]
        [Trait(Category.AcceptanceType, Category.CheckIn)]
        public void TestAuditingUpdatePolicyWithClassicStorage()
        {
            RunPowerShellTest("Test-BlobAuditingUpdatePolicyWithClassicStorage");
        }
    }
}


text:
from core.himesis import Himesis
import uuid

class HMapModule(Himesis):
    def __init__(self):

        """
        Creates the himesis graph representing the DSLTrans rule MapModule.
        """
        # Flag this instance as compiled now
        self.is_compiled = True

        super(HMapModule, self).__init__(name='HMapModule', num_nodes=0, edges=[])

        # Set the graph attributes
        self["mm__"] = ['HimesisMM']
        self["name"] = """MapModule"""
        self["GUID__"] = uuid.uuid3(uuid.NAMESPACE_DNS,'MapModule')

        # match model. We only support one match model
        self.add_node()
        self.vs[0]["mm__"] = """MatchModel"""

        # apply model node
        self.add_node()
        self.vs[1]["mm__"] = """ApplyModel"""

        # paired with relation between match and apply models

        self.add_node()
        self.vs[2]["mm__"] = """paired_with"""
        self.vs[2]["attr1"] = """MapModule"""

        # match class Module() node
        self.add_node()

        self.vs[3]["mm__"] = """Module"""
        self.vs[3]["attr1"] = """+"""
        # match class Partition() node
        self.add_node()

        self.vs[4]["mm__"] = """Partition"""
        self.vs[4]["attr1"] = """1"""
        # match class PhysicalNode() node
        self.add_node()

        self.vs[5]["mm__"] = """PhysicalNode"""
        self.vs[5]["attr1"] = """1"""

        # apply class SwCompToEcuMapping_component() node
        self.add_node()

        self.vs[6]["mm__"] = """SwCompToEcuMapping_component"""
        self.vs[6]["attr1"] = """1"""
        # apply class ComponentPrototype() node
        self.add_node()

        self.vs[7]["mm__"] = """ComponentPrototype"""
        self.vs[7]["attr1"] = """1"""

        # match association PhysicalNode--partition-->Partition node
        self.add_node()
        self.vs[8]["attr1"] = """partition"""
        self.vs[8]["mm__"] = """directLink_S"""
        # match association Partition--module-->Module node
        self.add_node()
        self.vs[9]["attr1"] = """module"""
        self.vs[9]["mm__"] = """directLink_S"""

        # apply association SwCompToEcuMapping_component--componentPrototype-->ComponentPrototype node
        self.add_node()
        self.vs[10]["attr1"] = """componentPrototype"""
        self.vs[10]["mm__"] = """directLink_T"""

        # Add the edges
        self.add_edges([
                (0,3), # matchmodel -> match_class Module()
                (0,4), # matchmodel -> match_class Partition()
                (0,5), # matchmodel -> match_class PhysicalNode()
                (1,6), # applymodel -> -> apply_class SwCompToEcuMapping_component()
                (1,7), # applymodel -> -> apply_class ComponentPrototype()
                (5,8), # match_class PhysicalNode() -> association partition
                (8,4), # association partition  -> match_class Partition()
                (4,9), # match_class Partition() -> association module
                (9,3), # association module  -> match_class Module()
                (6,10), # apply_class SwCompToEcuMapping_component() -> association componentPrototype
                (10,7), # association componentPrototype  -> apply_class ComponentPrototype()
                (0,2), # matchmodel -> pairedwith
                (2,1) # pairedwith -> applyModel
		])

        # Add the attribute equations
        self["equations"] = [((6,'ApplyAttribute'),('constant','solveRef')), ((7,'shortName'),(3,'name')), ]


text:
package org.apache.drill.exec.planner.logical;

import org.apache.drill.exec.physical.base.GroupScan;
import org.apache.calcite.plan.RelOptRuleCall;
import org.apache.calcite.rex.RexNode;

public class PartitionPruningUtil {
  public static void rewritePlan(RelOptRuleCall call, DrillFilterRel filterRel, DrillProjectRel projectRel, DrillScanRel scanRel, GroupScan newScan, DirPathBuilder builder) {
    RexNode origFilterCondition = filterRel.getCondition();
    RexNode newFilterCondition = builder.getFinalCondition();

    if (newFilterCondition.isAlwaysTrue()) {

      final DrillScanRel newScanRel =
          new DrillScanRel(scanRel.getCluster(),
              scanRel.getTraitSet().plus(DrillRel.DRILL_LOGICAL),
              scanRel.getTable(),
              newScan,
              scanRel.getRowType(),
              scanRel.getColumns());

      if (projectRel != null) {
        DrillProjectRel newProjectRel = new DrillProjectRel(projectRel.getCluster(), projectRel.getTraitSet(),
            newScanRel, projectRel.getProjects(), filterRel.getRowType());

        call.transformTo(newProjectRel);
      } else {
        call.transformTo(newScanRel);
      }
    } else {
      DrillRel inputRel;
      final DrillScanRel newScanRel =
          new DrillScanRel(scanRel.getCluster(),
              scanRel.getTraitSet().plus(DrillRel.DRILL_LOGICAL),
              scanRel.getTable(),
              newScan,
              scanRel.getRowType(),
              scanRel.getColumns());
      if (projectRel != null) {
        DrillProjectRel newProjectRel = new DrillProjectRel(projectRel.getCluster(), projectRel.getTraitSet(),
            newScanRel, projectRel.getProjects(), projectRel.getRowType());
        inputRel = newProjectRel;
      } else {
        inputRel = newScanRel;
      }
      final DrillFilterRel newFilterRel = new DrillFilterRel(filterRel.getCluster(), filterRel.getTraitSet(),
          inputRel, origFilterCondition /* for now keep the original condition until we add more test coverage */);

      call.transformTo(newFilterRel);
    }
  }

  public static String truncatePrefixFromPath(String fileName) {
    String pathPrefixComponent[] = fileName.split(":", 2);
    if (pathPrefixComponent.length == 1) {
      return pathPrefixComponent[0];
    } else {
      return pathPrefixComponent[1];
    }
  }
}


text:
class Audiofile < Formula
  desc "Reads and writes many common audio file formats"
  homepage "http://www.68k.org/~michael/audiofile/"
  url "http://audiofile.68k.org/audiofile-0.3.6.tar.gz"
  sha1 "3aba3ef724b1b5f88cfc20ab9f8ce098e6c35a0e"

  bottle do
    cellar :any
    sha1 "3ee5b808776b2ee6269aad02db795e8da61fa181" => :yosemite
    sha1 "a15e1ae96b15c18c62cfd19e387eb5d21f0992f2" => :mavericks
    sha1 "9994dc853442647fee82bf7291df0a2d35b93d16" => :mountain_lion
  end

  head do
    url "https://github.com/mpruett/audiofile.git"
    depends_on "asciidoc" => :build
    depends_on "autoconf" => :build
    depends_on "automake" => :build
    depends_on "libtool" => :build
  end

  option "with-lcov", "Enable Code Coverage support using lcov"
  option "with-check", "Run the test suite during install ~30sec"

  depends_on "lcov" => :optional

  def install
    if build.head?
      inreplace "autogen.sh", "libtool", "glibtool"
      ENV["XML_CATALOG_FILES"] = "#{etc}/xml/catalog"
    end

    configure = build.head? ? "./autogen.sh" : "./configure"
    args = ["--disable-dependency-tracking", "--prefix=#{prefix}"]
    args << "--enable-coverage" if build.with? "lcov"
    system configure, *args
    system "make"
    system "make", "check" if build.with? "check"
    system "make", "install"
  end

  test do
    inn  = "/System/Library/Sounds/Glass.aiff"
    out  = "Glass.wav"
    conv_bin = "#{bin}/sfconvert"
    info_bin = "#{bin}/sfinfo"

    unless File.exist?(conv_bin) and File.exist?(inn) and File.exist?(info_bin)
      opoo <<-EOS.undent
        One of the following files could not be located, and so
        the test was not executed:
           #{inn}
           #{conv_bin}
           #{info_bin}

        Audiofile can also be tested at build-time:
          brew install -v audiofile --with-check
      EOS
      return
    end

    system conv_bin, inn, out, "format", "wave"
    system info_bin, "--short", "--reporterror", out
  end
end


text:
E_BADARGS=65

EXPECTED_ARGS=3

if [ $# -ne $EXPECTED_ARGS ]
then
  echo " This script expect $EXPECTED_ARGS arguments instead of $#"
  exit $E_BADARGS
fi

MV=$(which mv)
RM=$(which rm)
DATE=$(which date)
SED=$(which sed)
CAT=$(which cat)
DRUSH=$(which drush)

### CONFIG
DEP_NAME=$1
DEP_BRANCH=$2
DEP_USER=$3

. $($(which dirname) $($(which readlink) -f "$0"))/autodeploy-common.sh

# Clonar RAMA REPO con submoduless en dir tmp
# clone-with-subs.sh $REPO $BRANCH $TARGET
. $LIB/clone-with-subs.sh $REPO_BARE $DEP_BRANCH $TMP_DIR $TAG

# Copiar files y settings
# copy-files-settings.sh $SOURCE $TARGET
. $LIB/symfony-copy-files-settings.sh $DST_DIR $TMP_DIR

# Arreglar permisos
# fix-drupal-perms.sh $TARGET
. $LIB/symfony-fix-perms.sh $TMP_DIR

# Firmar Robots
REPO_HASH=$($CAT $TMP_DIR/.git_hash)
REPO_DATE=$($CAT $TMP_DIR/.git_date)
SIGN="# Environment generated by $DEP_USER from $DEP_BRANCH (hash: $REPO_HASH, date: $REPO_DATE) for site $SITE_NAME on $($DATE '+%Y-%m-%d %H:%M %Z')"
$SED  -i  '1{s|^|'"${SIGN}\n"'|}' $TMP_DIR/web/robots.txt

# Eliminar archivos no para produccion
$RM $TMP_DIR/.git*

# Loggear despliegue
echo -e "$($DATE '+%Y-%m-%d %H:%M %Z')\t$DEP_BRANCH\t$REPO_DATE\t$REPO_HASH\t$DEP_USER" >> $LOG_FILE

$RM -r $DST_DIR
$MV $TMP_DIR $DST_DIR

# Reload apache
restartServerIfNecesary

# Borrar caches
pushd $(pwd)
cd $DST_DIR
if [ -e symfony ]; then
  php symfony cc
  php symfony doctrine:migrate
elif [ -e app/console ]; then
  php app/console cc
  php app/console doctrine:migrate
fi
popd

# Clean Varnish
cleanVarnishIfNecesary

exit 0


text:
import logging
import json
import textwrap
from json.encoder import JSONEncoder
from logging import StreamHandler, Formatter, FileHandler
from ethereum.utils import bcolors, is_numeric
import sys

DEFAULT_LOGLEVEL = 'INFO'

JSON_FORMAT = '%(message)s'

PRINT_FORMAT = '%(levelname)s:%(name)s\t%(message)s'
FILE_PREFIX = '%(asctime)s'

TRACE = 5

known_loggers = set()

log_listeners = []

def _inject_into_logger(name, code, namespace=None):
    # This is a hack to fool the logging module into reporting correct source files.
    # It determines the actual source of a logging call by inspecting the stack frame's
    # source file. So we use this `eval(compile())` construct to "inject" our additional
    # methods into the logging module.
    if namespace is None:
        namespace = {}
    eval(
        compile(
            code,
            logging._srcfile,
            'exec'
        ),
        namespace
    )
    setattr(logging.Logger, name, namespace[name])

# Add `trace()` level to Logger
_inject_into_logger(
    'trace',
    textwrap.dedent(
        """\
        def trace(self, msg, *args, **kwargs):
            if self.isEnabledFor(TRACE):
                self._log(TRACE, msg, args, **kwargs)
        """
    ),
    {'TRACE': TRACE}
)
logging.TRACE = TRACE
logging.addLevelName(TRACE, "TRACE")

# Add `DEV()` shortcut to loggers
_inject_into_logger(
    'DEV',
    textwrap.dedent(
        """\
        def DEV(self, msg, *args, **kwargs):
            '''Shortcut to output highlighted log text'''
            kwargs['highlight'] = True
            self.critical(msg, *args, **kwargs)
        """
    )
)

class LogRecorder(object):

    """
    temporarily records all logs, w/o level filtering
    use only once!
    """
    max_capacity = 1000 * 1000  # check we are not forgotten or abused

    def __init__(self, disable_other_handlers=False, log_config=None):
        self._records = []
        log_listeners.append(self._add_log_record)
        self._saved_config = None
        if log_config:
            self._saved_config = get_configuration()
            configure(log_config)
        self._saved_handlers = []
        if disable_other_handlers:
            self._saved_handlers = rootLogger.handlers[:]
            rootLogger.handlers = []

    def pop_records(self):
        # only returns records on the first call
        r = self._records[:]
        self._records = []
        try:
            log_listeners.remove(self._add_log_record)
        except ValueError:
            pass
        if self._saved_config:
            configure(**self._saved_config)
            self._saved_config = None
        if self._saved_handlers:
            rootLogger.handlers = self._saved_handlers[:]
            self._saved_handlers = []
        return r

    def _add_log_record(self, msg):
        self._records.append(msg)
        assert len(self._records) < self.max_capacity

def get_configuration():
    """
    get a configuration (snapshot) that can be used to call configure
    snapshot = get_configuration()
    configure(**snapshot)
    """
    root = getLogger()
    name_levels = [('', logging.getLevelName(root.level))]
    name_levels.extend(
        (name, logging.getLevelName(logger.level))
        for name, logger
        in root.manager.loggerDict.items()
        if hasattr(logger, 'level')
    )

    config_string = ','.join('%s:%s' % x for x in name_levels)

    return dict(config_string=config_string, log_json=SLogger.manager.log_json)

def get_logger_names():
    return sorted(known_loggers, key=lambda x: '' if not x else x)

class BoundLogger(object):

    def __init__(self, logger, context):
        self.logger = logger
        self.context = context

    def bind(self, **kwargs):
        return BoundLogger(self, kwargs)

    def _proxy(self, method_name, *args, **kwargs):
        context = self.context.copy()
        context.update(kwargs)
        return getattr(self.logger, method_name)(*args, **context)

    trace = lambda self, *args, **kwargs: self._proxy('trace', *args, **kwargs)
    debug = lambda self, *args, **kwargs: self._proxy('debug', *args, **kwargs)
    info = lambda self, *args, **kwargs: self._proxy('info', *args, **kwargs)
    warn = warning = lambda self, * \
        args, **kwargs: self._proxy('warning', *args, **kwargs)
    error = lambda self, *args, **kwargs: self._proxy('error', *args, **kwargs)
    exception = lambda self, * \
        args, **kwargs: self._proxy('exception', *args, **kwargs)
    fatal = critical = lambda self, * \
        args, **kwargs: self._proxy('critical', *args, **kwargs)

class _LogJSONEncoder(JSONEncoder):
    def default(self, o):
        return repr(o)

class SLogger(logging.Logger):

    def __init__(self, name, level=DEFAULT_LOGLEVEL):
        self.warn = self.warning
        super(SLogger, self).__init__(name, level=level)

    @property
    def log_json(self):
        return SLogger.manager.log_json

    def is_active(self, level_name='trace'):
        return self.isEnabledFor(logging._checkLevel(level_name.upper()))

    def format_message(self, msg, kwargs, highlight, level):
        if getattr(self, 'log_json', False):
            message = dict()
            message['event'] = '{}.{}'.format(
                self.name, msg.lower().replace(' ', '_'))
            message['level'] = logging.getLevelName(level)
            try:
                message.update(kwargs)
                try:
                    msg = json.dumps(message, cls=_LogJSONEncoder)
                except TypeError:
                    # Invalid value. With our custom encoder this can only happen with non-string
                    # dict keys (see: https://bugs.python.org/issue18820).
                    message = _stringify_dict_keys(message)
                    msg = json.dumps(message, cls=_LogJSONEncoder)
            except UnicodeDecodeError:
                message.update({
                    k: v if is_numeric(v) or isinstance(v, (float, complex)) else repr(v)
                    for k, v in kwargs.items()
                })
                msg = json.dumps(message, cls=_LogJSONEncoder)
        else:
            msg = "{}{} {}{}".format(
                bcolors.WARNING if highlight else "",
                msg,
                " ".join("{}={!s}".format(k, v) for k, v in kwargs.items()),
                bcolors.ENDC if highlight else ""
            )
        return msg

    def bind(self, **kwargs):
        return BoundLogger(self, kwargs)

    def _log(self, level, msg, args, **kwargs):
        exc_info = kwargs.pop('exc_info', None)
        extra = kwargs.pop('extra', {})
        highlight = kwargs.pop('highlight', False)
        extra['kwargs'] = kwargs
        extra['original_msg'] = msg
        msg = self.format_message(msg, kwargs, highlight, level)
        super(SLogger, self)._log(level, msg, args, exc_info, extra)

class RootLogger(SLogger):

    """
    A root logger is not that different to any other logger, except that
    it must have a logging level and there is only one instance of it in
    the hierarchy.
    """

    def __init__(self, level):
        """
        Initialize the logger with the name "root".
        """
        super(RootLogger, self).__init__("root", level)

    def handle(self, record):
        if log_listeners:
            rec_dict = getattr(record, 'kwargs', {}).copy()
            rec_dict['event'] = getattr(record, 'original_msg', "")
            for listener in log_listeners:
                listener(rec_dict)
        super(RootLogger, self).handle(record)

class SManager(logging.Manager):

    def __init__(self, rootnode):
        self.loggerClass = SLogger
        self.log_json = False
        super(SManager, self).__init__(rootnode)

    def getLogger(self, name):
        logging.setLoggerClass(SLogger)
        return super(SManager, self).getLogger(name)

rootLogger = RootLogger(DEFAULT_LOGLEVEL)
SLogger.root = rootLogger
SLogger.manager = SManager(SLogger.root)

def _stringify_dict_keys(input_):
    if isinstance(input_, dict):
        res = {}
        for k, v in input_.items():
            v = _stringify_dict_keys(v)
            if not isinstance(k, (int, long, bool, None.__class__)):
                k = str(k)
            res[k] = v
    elif isinstance(input_, (list, tuple)):
        res = input_.__class__([_stringify_dict_keys(i) for i in input_])
    else:
        res = input_
    return res

def getLogger(name=None):
    """
    Return a logger with the specified name, creating it if necessary.

    If no name is specified, return the root logger.
    """

    if name:
        logger = SLogger.manager.getLogger(name)
        return logger
    else:
        return rootLogger

def configure(config_string=None, log_json=False, log_file=None):
    if not config_string:
        config_string = ":{}".format(DEFAULT_LOGLEVEL)

    if log_json:
        SLogger.manager.log_json = True
        log_format = JSON_FORMAT
    else:
        SLogger.manager.log_json = False
        log_format = PRINT_FORMAT

    if len(rootLogger.handlers) == 0:
        #handler = StreamHandler()
        handler = StreamHandler(sys.stdout)
        formatter = Formatter(log_format)
        handler.setFormatter(formatter)
        rootLogger.addHandler(handler)
    if log_file:
        if not any(isinstance(hndlr, FileHandler)
                   for hndlr in rootLogger.handlers):
            handler = FileHandler(log_file)
            formatter = Formatter("{} {}".format(FILE_PREFIX, log_format))
            handler.setFormatter(formatter)
            rootLogger.addHandler(handler)

    # Reset logging levels before applying new config below
    for name, logger in SLogger.manager.loggerDict.items():
        if hasattr(logger, 'setLevel'):
            # Guard against `logging.PlaceHolder` instances
            logger.setLevel(logging.NOTSET)
            if config_string == ":{}".format(DEFAULT_LOGLEVEL):
                logger.propagate = True
            else:
                logger.propagate = True

    for name_levels in config_string.split(','):
        name, _, level = name_levels.partition(':')
        logger = getLogger(name)
        logger.setLevel(level.upper())
        logger.propagate = True

configure_logging = configure

def set_level(name, level):
    assert not isinstance(level, int)
    logger = getLogger(name)
    logger.setLevel(getattr(logging, level.upper()))

def get_logger(name=None):
    known_loggers.add(name)
    return getLogger(name)

def DEBUG(msg, *args, **kwargs):
    """temporary logger during development that is always on"""
    logger = getLogger("DEBUG")
    if len(logger.handlers) == 0:
        logger.addHandler(StreamHandler())
    logger.propagate = False
    logger.setLevel(logging.DEBUG)
    logger.DEV(msg, *args, **kwargs)


text:
#include "sdl_rpc_plugin/commands/hmi/ui_get_supported_languages_request.h"

namespace sdl_rpc_plugin {
using namespace application_manager;

namespace commands {

SDL_CREATE_LOG_VARIABLE("Commands")

UIGetSupportedLanguagesRequest::UIGetSupportedLanguagesRequest(
    const application_manager::commands::MessageSharedPtr& message,
    ApplicationManager& application_manager,
    rpc_service::RPCService& rpc_service,
    HMICapabilities& hmi_capabilities,
    policy::PolicyHandlerInterface& policy_handle)
    : RequestToHMI(message,
                   application_manager,
                   rpc_service,
                   hmi_capabilities,
                   policy_handle) {}

UIGetSupportedLanguagesRequest::~UIGetSupportedLanguagesRequest() {}

void UIGetSupportedLanguagesRequest::Run() {
  SDL_LOG_AUTO_TRACE();

  SendRequest();
}

void UIGetSupportedLanguagesRequest::OnTimeOut() {
  SDL_LOG_AUTO_TRACE();
  hmi_capabilities_.UpdateRequestsRequiredForCapabilities(
      hmi_apis::FunctionID::UI_GetSupportedLanguages);
}
}  // namespace commands

}  // namespace sdl_rpc_plugin


text:
using NUnit.Framework;
using Sensus.Context;
using Sensus.Test.Classes;

namespace Sensus.Tests //this namespace has to align with the tests we want this fixture for
{
    [SetUpFixture]
    public class SetUpFixture
    {
        [SetUp]
        public void SetUp()
        {
            SensusContext.Current = new TestSensusContext();
        }
    }
}


text:
layout: base
title:  'Statistics of expl:pass in UD_Portuguese-PetroGold'
udver: '2'
---

## Treebank Statistics: UD_Portuguese-PetroGold: Relations: `expl:pass`

This relation is a language-specific subtype of <tt>expl</tt>.
There are also 2 other language-specific subtypes of `expl`: <tt>expl:impers</tt>, <tt>expl:pv</tt>.

795 nodes (0%) are attached to their parents as `expl:pass`.

613 instances of `expl:pass` (77%) are left-to-right (parent precedes child).
Average distance between parent and child is 1.00251572327044.

The following 1 pairs of parts of speech are connected with `expl:pass`: <tt>VERB</tt>-<tt>PRON</tt> (795; 100% instances).

~~~ conllu
# visual-style 2	bgColor:blue
# visual-style 2	fgColor:white
# visual-style 1	bgColor:blue
# visual-style 1	fgColor:white
# visual-style 1 2 expl:pass	color:blue
1	Considerou	considerar	VERB	_	Mood=Ind|Number=Sing|Person=3|Tense=Past|VerbForm=Fin	0	root	_	Se=pass
2	se	se	PRON	_	_	1	expl:pass	_	_
3	a	o	DET	_	Definite=Def|Gender=Fem|Number=Sing|PronType=Art	4	det	_	_
4	densidade	densidade	NOUN	_	Gender=Fem|Number=Sing	1	nsubj:pass	_	_
5	de	de	ADP	_	_	7	case	_	_
6	a	o	DET	_	Definite=Def|Gender=Fem|Number=Sing|PronType=Art	7	det	_	_
7	água	água	NOUN	_	Gender=Fem|Number=Sing	4	nmod	_	_
8	como	como	ADP	_	_	10	case	_	_
9	999	999	NUM	_	NumType=Card	10	nummod	_	_
10	Kg/m3	Kg/m3	PROPN	_	Gender=Masc|Number=Sing	1	xcomp	_	SpaceAfter=No
11	.	.	PUNCT	_	_	1	punct	_	_

~~~