text:
namespace System.EnterpriseServices
{

using System.Runtime.InteropServices;

#if !ECMA_COMPAT
[Serializable]
[Guid("36dcda30-dc3b-4d93-be42-90b2d74c64e7")]
#endif
public class RegistrationConfig
{
	// Internal state.
	private String application;
	private String applicationRootDirectory;
	private String assemblyFile;
	private InstallationFlags installationFlags;
	private String partition;
	private String typeLibrary;

	// Constructor.
	public RegistrationConfig() {}

	// Get or set this object's properties.
	public String Application
			{
				get
				{
					return application;
				}
				set
				{
					application = value;
				}
			}
	public String ApplicationRootDirectory
			{
				get
				{
					return applicationRootDirectory;
				}
				set
				{
					applicationRootDirectory = value;
				}
			}
	public String AssemblyFile
			{
				get
				{
					return assemblyFile;
				}
				set
				{
					assemblyFile = value;
				}
			}
	public InstallationFlags InstallationFlags
			{
				get
				{
					return installationFlags;
				}
				set
				{
					installationFlags = value;
				}
			}
	public String Partition
			{
				get
				{
					return partition;
				}
				set
				{
					partition = value;
				}
			}
	public String TypeLibrary
			{
				get
				{
					return typeLibrary;
				}
				set
				{
					typeLibrary = value;
				}
			}

}; // class RegistrationConfig

}; // namespace System.EnterpriseServices


text:
<ItemPools>
    <Pool Name="treasure">
        <Item Name="Lifeline" Weight="1" DecreaseBy="1" RemoveOn="0.1"/>
        <Item Name="Bugged Bombs" Weight="1" DecreaseBy="1" RemoveOn="0.1"/>
        <Item Name="Graphics Error" Weight="1" DecreaseBy="1" RemoveOn="0.1"/>
        <Item Name="Stoned Buddy" Weight="1" DecreaseBy="1" RemoveOn="0.1"/>
        <Item Name="Cool Bean" Weight="1" DecreaseBy="1" RemoveOn="0.1"/>
        <Item Name="Black Pepper" Weight="1" DecreaseBy="1" RemoveOn="0.1"/>
        <Item Name="Tearleporter" Weight="1" DecreaseBy="1" RemoveOn="0.1"/>
        <Item Name="Mutant Fetus" Weight="1" DecreaseBy="1" RemoveOn="0.1"/>
        <Item Name="Cologne" Weight="1" DecreaseBy="1" RemoveOn="0.1"/>
        <Item Name="Delirium's Brain" Weight="1" DecreaseBy="1" RemoveOn="0.1"/>
        <Item Name="Furnace" Weight="1" DecreaseBy="1" RemoveOn="0.1" />
        <Item Name="White Candle" Weight="1" DecreaseBy="1" RemoveOn="0.1" />
        <Item Name="Pseudobulbar Affect" Weight="1" DecreaseBy="1" RemoveOn="0.1" />
        <Item Name="Talisman of Absorption" Weight="1" DecreaseBy="1" RemoveOn="0.1" />
    </Pool>
    <Pool Name="shop">
        <Item Name="Old Controller" Weight="1" DecreaseBy="1" RemoveOn="0.1"/>
        <Item Name="Addicted" Weight="1" DecreaseBy="1" RemoveOn="0.1"/>
        <Item Name="Isaac's Apple" Weight="1" DecreaseBy="1" RemoveOn="0.1"/>
        <Item Name="Black Pepper" Weight="1" DecreaseBy="1" RemoveOn="0.1"/>
        <Item Name="Cologne" Weight="1" DecreaseBy="1" RemoveOn="0.1"/>
        <Item Name="Beggar's Cup" Weight="1" DecreaseBy="1" RemoveOn="0.1"/>
        <Item Name="White Candle" Weight="1" DecreaseBy="1" RemoveOn="0.1" />
        <Item Name="Green Candle" Weight="1" DecreaseBy="1" RemoveOn="0.1" />
        <Item Name="Candle Kit" Weight="1" DecreaseBy="1" RemoveOn="0.1" />
    </Pool>
    <Pool Name="devil">
        <Item Name="Satan's Contract" Weight="1" DecreaseBy="1" RemoveOn="0.1"/>
    </Pool>
    <Pool Name="angel">
        <Item Name="Divine Wrath" Weight="1" DecreaseBy="1" RemoveOn="0.1" />
        <Item Name="White Candle" Weight="1" DecreaseBy="1" RemoveOn="0.1" />
        <Item Name="Diligence" Weight="1" DecreaseBy="1" RemoveOn="0.1" />
        <Item Name="Patience" Weight="1" DecreaseBy="1" RemoveOn="0.1" />
        <Item Name="Charity" Weight="1" DecreaseBy="1" RemoveOn="0.1" />
        <Item Name="Temperance" Weight="1" DecreaseBy="1" RemoveOn="0.1" />
        <Item Name="Humility" Weight="1" DecreaseBy="1" RemoveOn="0.1" />
        <Item Name="Chastity" Weight="1" DecreaseBy="1" RemoveOn="0.1" />
        <Item Name="Kindness" Weight="1" DecreaseBy="1" RemoveOn="0.1" />
        <Item Name="Candle Kit" Weight="1" DecreaseBy="1" RemoveOn="0.1" />
    </Pool>
    <Pool Name="secret">
        <Item Name="Old Controller" Weight="1" DecreaseBy="1" RemoveOn="0.1"/>
        <Item Name="Graphics Error" Weight="1" DecreaseBy="1" RemoveOn="0.1"/>
        <Item Name="Trash Bag" Weight="1" DecreaseBy="1" RemoveOn="0.1"/>
        <Item Name="Diligence" Weight="1" DecreaseBy="1" RemoveOn="0.1" />
        <Item Name="Patience" Weight="1" DecreaseBy="1" RemoveOn="0.1" />
        <Item Name="Charity" Weight="1" DecreaseBy="1" RemoveOn="0.1" />
        <Item Name="Temperance" Weight="1" DecreaseBy="1" RemoveOn="0.1" />
        <Item Name="Humility" Weight="1" DecreaseBy="1" RemoveOn="0.1" />
        <Item Name="Chastity" Weight="1" DecreaseBy="1" RemoveOn="0.1" />
        <Item Name="Kindness" Weight="1" DecreaseBy="1" RemoveOn="0.1" />
        <Item Name="Candle Kit" Weight="1" DecreaseBy="1" RemoveOn="0.1" />
    </Pool>
    <Pool Name="beggar">
        <Item Name="Trash Bag" Weight="1" DecreaseBy="1" RemoveOn="0.1"/>
        <Item Name="Beggar's Cup" Weight="1" DecreaseBy="1" RemoveOn="0.1"/>
        <Item Name="Talisman of Absorption" Weight="1" DecreaseBy="1" RemoveOn="0.1" />
        <Item Name="Kindness" Weight="1" DecreaseBy="1" RemoveOn="0.1" />
    </Pool>
    <Pool Name="bombBum">
        <Item Name="Bugged Bombs" Weight="1" DecreaseBy="1" RemoveOn="0.1"/>
    </Pool>
    <Pool Name="redChest">
        <Item Name="Trash Bag" Weight="1" DecreaseBy="1" RemoveOn="0.1"/>
    </Pool>
    <Pool Name="greedTreasure">
        <Item Name="Bugged Bombs" Weight="1" DecreaseBy="1" RemoveOn="0.1"/>
        <Item Name="Graphics Error" Weight="1" DecreaseBy="1" RemoveOn="0.1"/>
        <Item Name="Lifeline" Weight="1" DecreaseBy="1" RemoveOn="0.1"/>
        <Item Name="Stoned Buddy" Weight="1" DecreaseBy="1" RemoveOn="0.1"/>
        <Item Name="Cool Bean" Weight="1" DecreaseBy="1" RemoveOn="0.1"/>
        <Item Name="Black Pepper" Weight="1" DecreaseBy="1" RemoveOn="0.1"/>
        <Item Name="Tearleporter" Weight="1" DecreaseBy="1" RemoveOn="0.1"/>
        <Item Name="Mutant Fetus" Weight="1" DecreaseBy="1" RemoveOn="0.1"/>
        <Item Name="Cologne" Weight="1" DecreaseBy="1" RemoveOn="0.1"/>
        <Item Name="Delirium's Brain" Weight="1" DecreaseBy="1" RemoveOn="0.1"/>
        <Item Name="Furnace" Weight="1" DecreaseBy="1" RemoveOn="0.1" />
        <Item Name="Pseudobulbar Affect" Weight="1" DecreaseBy="1" RemoveOn="0.1" />
        <Item Name="White Candle" Weight="1" DecreaseBy="1" RemoveOn="0.1" />
    </Pool>
    <Pool Name="greedShop">
        <Item Name="Addicted" Weight="1" DecreaseBy="1" RemoveOn="0.1"/>
        <Item Name="Old Controller" Weight="1" DecreaseBy="1" RemoveOn="0.1"/>
        <Item Name="Isaac's Apple" Weight="1" DecreaseBy="1" RemoveOn="0.1"/>
        <Item Name="Black Pepper" Weight="1" DecreaseBy="1" RemoveOn="0.1"/>
        <Item Name="Cologne" Weight="1" DecreaseBy="1" RemoveOn="0.1"/>
        <Item Name="Green Candle" Weight="1" DecreaseBy="1" RemoveOn="0.1" />
        <Item Name="White Candle" Weight="1" DecreaseBy="1" RemoveOn="0.1" />
        <Item Name="Candle Kit" Weight="1" DecreaseBy="1" RemoveOn="0.1" />
    </Pool>
    <Pool Name="greedDevil">
        <Item Name="Satan's Contract" Weight="1" DecreaseBy="1" RemoveOn="0.1"/>
    </Pool>
    <Pool Name="greedAngel">
        <Item Name="Divine Wrath" Weight="1" DecreaseBy="1" RemoveOn="0.1" />
        <Item Name="White Candle" Weight="1" DecreaseBy="1" RemoveOn="0.1" />
        <Item Name="Diligence" Weight="1" DecreaseBy="1" RemoveOn="0.1" />
        <Item Name="Patience" Weight="1" DecreaseBy="1" RemoveOn="0.1" />
        <Item Name="Charity" Weight="1" DecreaseBy="1" RemoveOn="0.1" />
        <Item Name="Temperance" Weight="1" DecreaseBy="1" RemoveOn="0.1" />
        <Item Name="Humility" Weight="1" DecreaseBy="1" RemoveOn="0.1" />
        <Item Name="Chastity" Weight="1" DecreaseBy="1" RemoveOn="0.1" />
        <Item Name="Kindness" Weight="1" DecreaseBy="1" RemoveOn="0.1" />
        <Item Name="Candle Kit" Weight="1" DecreaseBy="1" RemoveOn="0.1" />
    </Pool>
    <Pool Name="greedSecret">
        <Item Name="Old Controller" Weight="1" DecreaseBy="1" RemoveOn="0.1"/>
        <Item Name="Graphics Error" Weight="1" DecreaseBy="1" RemoveOn="0.1"/>
        <Item Name="Trash Bag" Weight="1" DecreaseBy="1" RemoveOn="0.1"/>
        <Item Name="Diligence" Weight="1" DecreaseBy="1" RemoveOn="0.1" />
        <Item Name="Patience" Weight="1" DecreaseBy="1" RemoveOn="0.1" />
        <Item Name="Charity" Weight="1" DecreaseBy="1" RemoveOn="0.1" />
        <Item Name="Temperance" Weight="1" DecreaseBy="1" RemoveOn="0.1" />
        <Item Name="Humility" Weight="1" DecreaseBy="1" RemoveOn="0.1" />
        <Item Name="Chastity" Weight="1" DecreaseBy="1" RemoveOn="0.1" />
        <Item Name="Kindness" Weight="1" DecreaseBy="1" RemoveOn="0.1" />
        <Item Name="Candle Kit" Weight="1" DecreaseBy="1" RemoveOn="0.1" />
    </Pool>
</ItemPools>

redpajama_set_name: RedPajamaGithub


text:
require File.dirname(__FILE__) + '/test_helper'

class ArrayTest < Test::Unit::TestCase

  def test_an_array_of_activerecords_responds_to_ids
    assert_respond_to [1,2,:foo, 'whatever'], :ids
  end

  def test_an_array_is_visualized_in_a_nice_way
    assert_equal [1,2,:foo, 'ciao'].to_s, "[ 1, 2, foo, ciao ]"
  end

end


text:
/*
 * This file provided by Facebook is for non-commercial testing and evaluation
 * purposes only.  Facebook reserves all rights not expressly granted.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
 * FACEBOOK BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
 * ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
 * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
 */

package com.miguelgaeta.bootstrap.mg_images.samples.zoomable;

import android.graphics.Matrix;
import android.graphics.PointF;
import android.graphics.RectF;
import android.support.annotation.Nullable;
import android.view.MotionEvent;
import android.view.animation.DecelerateInterpolator;

import com.facebook.common.internal.Preconditions;
import com.miguelgaeta.bootstrap.mg_images.samples.gestures.TransformGestureDetector;
import com.nineoldandroids.animation.Animator;
import com.nineoldandroids.animation.AnimatorListenerAdapter;
import com.nineoldandroids.animation.ValueAnimator;

/**
 * Zoomable controller that calculates transformation based on touch events.
 */
public class DefaultZoomableController
    implements ZoomableController, TransformGestureDetector.Listener {

  private static final RectF IDENTITY_RECT = new RectF(0, 0, 1, 1);

  private TransformGestureDetector mGestureDetector;

  private Listener mListener = null;

  private boolean mIsEnabled = false;
  private boolean mIsRotationEnabled = false;
  private boolean mIsScaleEnabled = true;
  private boolean mIsTranslationEnabled = true;

  private float mMinScaleFactor = 1.0f;
  private float mMaxScaleFactor = Float.POSITIVE_INFINITY;

  private final RectF mViewBounds = new RectF();
  private final RectF mImageBounds = new RectF();
  private final RectF mTransformedImageBounds = new RectF();
  private final Matrix mPreviousTransform = new Matrix();
  private final Matrix mActiveTransform = new Matrix();
  private final Matrix mActiveTransformInverse = new Matrix();
  private final float[] mTempValues = new float[9];
  private final RectF mTempRect = new RectF();

  private final ValueAnimator mValueAnimator;
  private final float[] mAnimationStartValues = new float[9];
  private final float[] mAnimationDestValues = new float[9];
  private final float[] mAnimationCurrValues = new float[9];
  private final Matrix mNewTransform = new Matrix();

  public DefaultZoomableController(TransformGestureDetector gestureDetector) {
    mGestureDetector = gestureDetector;
    mGestureDetector.setListener(this);
    mValueAnimator = ValueAnimator.ofFloat(0, 1);
    mValueAnimator.setInterpolator(new DecelerateInterpolator());
  }

  public static DefaultZoomableController newInstance() {
    return new DefaultZoomableController(TransformGestureDetector.newInstance());
  }

  @Override
  public void setListener(Listener listener) {
    mListener = listener;
  }

  /** Rests the controller. */
  public void reset() {
    mGestureDetector.reset();
    mPreviousTransform.reset();
    mActiveTransform.reset();
    onTransformChanged();
  }

  /** Sets whether the controller is enabled or not. */
  @Override
  public void setEnabled(boolean enabled) {
    mIsEnabled = enabled;
    if (!enabled) {
      reset();
    }
  }

  /** Returns whether the controller is enabled or not. */
  @Override
  public boolean isEnabled() {
    return mIsEnabled;
  }

  /** Sets whether the rotation gesture is enabled or not. */
  public void setRotationEnabled(boolean enabled) {
    mIsRotationEnabled = enabled;
  }

  /** Gets whether the rotation gesture is enabled or not. */
  public boolean isRotationEnabled() {
    return  mIsRotationEnabled;
  }

  /** Sets whether the scale gesture is enabled or not. */
  public void setScaleEnabled(boolean enabled) {
    mIsScaleEnabled = enabled;
  }

  /** Gets whether the scale gesture is enabled or not. */
  public boolean isScaleEnabled() {
    return  mIsScaleEnabled;
  }

  /** Sets whether the translation gesture is enabled or not. */
  public void setTranslationEnabled(boolean enabled) {
    mIsTranslationEnabled = enabled;
  }

  /** Gets whether the translations gesture is enabled or not. */
  public boolean isTranslationEnabled() {
    return  mIsTranslationEnabled;
  }

  /** Gets the image bounds before zoomable transformation is applied. */
  public RectF getImageBounds() {
    return mImageBounds;
  }

  protected RectF getTransformedImageBounds() {
    return mTransformedImageBounds;
  }

  /** Sets the image bounds before zoomable transformation is applied. */
  @Override
  public void setImageBounds(RectF imageBounds) {
    if (!imageBounds.equals(mImageBounds)) {
      mImageBounds.set(imageBounds);
      onTransformChanged();
    }
  }

  /** Gets the view bounds. */
  public RectF getViewBounds() {
    return mViewBounds;
  }

  /** Sets the view bounds. */
  @Override
  public void setViewBounds(RectF viewBounds) {
    mViewBounds.set(viewBounds);
  }

  /** Gets the minimum scale factor allowed. */
  public float getMinScaleFactor() {
    return mMinScaleFactor;
  }

  /**
   * Sets the minimum scale factor allowed.
   *

   * Note that the hierarchy performs scaling as well, which
   * is not accounted here, so the actual scale factor may differ.
   */
  public void setMinScaleFactor(float minScaleFactor) {
    mMinScaleFactor = minScaleFactor;
  }

  /** Gets the maximum scale factor allowed. */
  public float getMaxScaleFactor() {
    return mMaxScaleFactor;
  }

  /**
   * Sets the maximum scale factor allowed.
   *

   * Note that the hierarchy performs scaling as well, which
   * is not accounted here, so the actual scale factor may differ.
   */
  public void setMaxScaleFactor(float maxScaleFactor) {
    mMaxScaleFactor = maxScaleFactor;
  }

  /**
   * Maps point from the view's to the image's relative coordinate system.
   * This takes into account the zoomable transformation.
   */
  public PointF mapViewToImage(PointF viewPoint) {
    float[] points = mTempValues;
    points[0] = viewPoint.x;
    points[1] = viewPoint.y;
    mActiveTransform.invert(mActiveTransformInverse);
    mActiveTransformInverse.mapPoints(points, 0, points, 0, 1);
    mapAbsoluteToRelative(points, points, 1);
    return new PointF(points[0], points[1]);
  }

  /**
   * Maps point from the image's relative to the view's coordinate system.
   * This takes into account the zoomable transformation.
   */
  public PointF mapImageToView(PointF imagePoint) {
    float[] points = mTempValues;
    points[0] = imagePoint.x;
    points[1] = imagePoint.y;
    mapRelativeToAbsolute(points, points, 1);
    mActiveTransform.mapPoints(points, 0, points, 0, 1);
    return new PointF(points[0], points[1]);
  }

  /**
   * Maps array of 2D points from absolute to the image's relative coordinate system,
   * and writes the transformed points back into the array.
   * Points are represented by float array of [x0, y0, x1, y1, ...].
   *
   * @param destPoints destination array (may be the same as source array)
   * @param srcPoints source array
   * @param numPoints number of points to map
   */
  private void mapAbsoluteToRelative(float[] destPoints, float[] srcPoints, int numPoints) {
    for (int i = 0; i < numPoints; i++) {
      destPoints[i * 2 + 0] = (srcPoints[i * 2 + 0] - mImageBounds.left) / mImageBounds.width();
      destPoints[i * 2 + 1] = (srcPoints[i * 2 + 1] - mImageBounds.top)  / mImageBounds.height();
    }
  }

  /**
   * Maps array of 2D points from relative to the image's absolute coordinate system,
   * and writes the transformed points back into the array
   * Points are represented by float array of [x0, y0, x1, y1, ...].
   *
   * @param destPoints destination array (may be the same as source array)
   * @param srcPoints source array
   * @param numPoints number of points to map
   */
  private void mapRelativeToAbsolute(float[] destPoints, float[] srcPoints, int numPoints) {
    for (int i = 0; i < numPoints; i++) {
      destPoints[i * 2 + 0] = srcPoints[i * 2 + 0] * mImageBounds.width() + mImageBounds.left;
      destPoints[i * 2 + 1] = srcPoints[i * 2 + 1] * mImageBounds.height() + mImageBounds.top;
    }
  }

  /**
   * Gets the zoomable transformation
   * Internal matrix is exposed for performance reasons and is not to be modified by the callers.
   */
  @Override
  public Matrix getTransform() {
    return mActiveTransform;
  }

  /**
   * Returns the matrix that fully transforms the image from image-relative coordinates
   * to scaled view-absolute coordinates.
   */
  public void getImageRelativeToViewAbsoluteTransform(Matrix outMatrix) {
    mActiveTransform.mapRect(mTempRect, mImageBounds);
    outMatrix.setRectToRect(IDENTITY_RECT, mTempRect, Matrix.ScaleToFit.FILL);
  }

  // TODO(balazsbalazs) resolve issues with interrupting an existing animation/gesture with
  // a new animation or transform

  /**
   * Sets a new zoom transformation.
   *
   *
If this method is called while an animation or gesture is already in progress,
   * this will currently result in undefined behavior.
   */
  public void setTransform(Matrix newTransform) {
    setTransform(newTransform, 0, null);
  }

  /**
   * Sets a new zoomable transformation and animates to it if desired.
   *
   *
If this method is called while an animation or gesture is already in progress,
   * this will currently result in undefined behavior.
   *
   * @param newTransform new transform to make active
   * @param durationMs duration of the animation, or 0 to not animate
   * @param onAnimationComplete code to run when the animation completes. Ignored if durationMs=0
   */
  public void setTransform(
      Matrix newTransform,
      long durationMs,
      @Nullable Runnable onAnimationComplete) {
    if (mGestureDetector.isGestureInProgress()) {
      mGestureDetector.reset();
    }
    cancelAnimation();
    if (durationMs <= 0) {
      mActiveTransform.set(newTransform);
      onTransformChanged();
    } else {
      setTransformAnimated(newTransform, durationMs, onAnimationComplete);
    }
  }

  /** Do not call this method directly; call it only from setTransform. */
  private void setTransformAnimated(
      final Matrix newTransform,
      long durationMs,
      @Nullable final Runnable onAnimationComplete) {
    Preconditions.checkArgument(durationMs > 0);
    Preconditions.checkState(!mValueAnimator.isRunning());
    mValueAnimator.setDuration(durationMs);
    mActiveTransform.getValues(mAnimationStartValues);
    newTransform.getValues(mAnimationDestValues);
    mValueAnimator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
      @Override
      public void onAnimationUpdate(ValueAnimator valueAnimator) {
        float fraction = (float) valueAnimator.getAnimatedValue();
        for (int i = 0; i < mAnimationCurrValues.length; i++) {
          mAnimationCurrValues[i] = (1 - fraction) * mAnimationStartValues[i] +
              fraction * mAnimationDestValues[i];
        }
        mActiveTransform.setValues(mAnimationCurrValues);
        onTransformChanged();
      }
    });
    if (onAnimationComplete != null) {
      mValueAnimator.addListener(new AnimatorListenerAdapter() {
        @Override
        public void onAnimationEnd(Animator animation) {
          onAnimationComplete.run();
        }
      });
    }
    mValueAnimator.start();
  }

  private void cancelAnimation() {
    mValueAnimator.removeAllUpdateListeners();
    mValueAnimator.removeAllListeners();
    if (mValueAnimator.isRunning()) {
      mValueAnimator.cancel();
    }
  }

  /** Notifies controller of the received touch event.  */
  @Override
  public boolean onTouchEvent(MotionEvent event) {
    if (mIsEnabled) {
      return mGestureDetector.onTouchEvent(event);
    }
    return false;
  }

  protected void onTransformChanged() {
    mActiveTransform.mapRect(mTransformedImageBounds, mImageBounds);
    if (mListener != null && isEnabled()) {
      mListener.onTransformChanged(mActiveTransform);
    }
  }

  /**
   * Zooms to the desired scale and positions the view so that imagePoint is in the center.
   *
   *
If this method is called while an animation or gesture is already in progress,
   * this will currently result in undefined behavior.
   *
   * @param scale desired scale, will be limited to {min, max} scale factor
   * @param imagePoint 2D point in image's relative coordinate system (i.e. 0 <= x, y <= 1)
   * @param viewPoint 2D point in view's absolute coordinate system
   * @param limitTransX  Whether to adjust the transform to prevent black bars from appearing on
   *                     the left or right.
   * @param limitTransY Whether to adjust the transform to prevent black bars from appearing on
   *                    the top or bottom.
   * @param durationMs length of animation of the zoom, or 0 if no animation desired
   * @param onAnimationComplete code to execute when the animation is complete.
   *                            Ignored if durationMs=0
   */
  public void zoomToImagePoint(
      float scale,
      PointF imagePoint,
      PointF viewPoint,
      boolean limitTransX,
      boolean limitTransY,
      long durationMs,
      @Nullable Runnable onAnimationComplete) {
    scale = limit(scale, mMinScaleFactor, mMaxScaleFactor);
    float[] viewAbsolute = mTempValues;
    viewAbsolute[0] = imagePoint.x;
    viewAbsolute[1] = imagePoint.y;
    mapRelativeToAbsolute(viewAbsolute, viewAbsolute, 1);
    float distanceX = viewPoint.x - viewAbsolute[0];
    float distanceY = viewPoint.y - viewAbsolute[1];
    mNewTransform.setScale(scale, scale, viewAbsolute[0], viewAbsolute[1]);
    mNewTransform.postTranslate(distanceX, distanceY);
    limitTranslation(mNewTransform, limitTransX, limitTransY);

    setTransform(mNewTransform, durationMs, onAnimationComplete);
  }

  /* TransformGestureDetector.Listener methods  */

  @Override
  public void onGestureBegin(TransformGestureDetector detector) {
    mPreviousTransform.set(mActiveTransform);
    // TODO(balazsbalazs): animation should be cancelled here
  }

  @Override
  public void onGestureUpdate(TransformGestureDetector detector) {
    mActiveTransform.set(mPreviousTransform);
    if (mIsRotationEnabled) {
      float angle = detector.getRotation() * (float) (180 / Math.PI);
      mActiveTransform.postRotate(angle, detector.getPivotX(), detector.getPivotY());
    }
    if (mIsScaleEnabled) {
      float scale = detector.getScale();
      mActiveTransform.postScale(scale, scale, detector.getPivotX(), detector.getPivotY());
    }
    limitScale(detector.getPivotX(), detector.getPivotY());
    if (mIsTranslationEnabled) {
      mActiveTransform.postTranslate(detector.getTranslationX(), detector.getTranslationY());
    }
    if (limitTranslation(mActiveTransform, true, true)) {
      mGestureDetector.restartGesture();
    }
    onTransformChanged();
  }

  @Override
  public void onGestureEnd(TransformGestureDetector detector) {
    mPreviousTransform.set(mActiveTransform);
  }

  /** Gets the current scale factor. */
  @Override
  public float getScaleFactor() {
    mActiveTransform.getValues(mTempValues);
    return mTempValues[Matrix.MSCALE_X];
  }

  private void limitScale(float pivotX, float pivotY) {
    float currentScale = getScaleFactor();
    float targetScale = limit(currentScale, mMinScaleFactor, mMaxScaleFactor);
    if (targetScale != currentScale) {
      float scale = targetScale / currentScale;
      mActiveTransform.postScale(scale, scale, pivotX, pivotY);
    }
  }

  /**
   * Keeps the view inside the image if possible, if not (i.e. image is smaller than view)
   * centers the image.
   * @param limitX whether to apply the limit on the x-axis
   * @param limitY whether to apply the limit on the y-axis
   * @return whether adjustments were needed or not
   */
  private boolean limitTranslation(Matrix newTransform, boolean limitX, boolean limitY) {
    RectF bounds = mTransformedImageBounds;
    bounds.set(mImageBounds);
    newTransform.mapRect(bounds);
    float offsetLeft = limitX ?
        getOffset(bounds.left, bounds.width(), mViewBounds.width()) : bounds.left;
    float offsetTop = limitY ?
        getOffset(bounds.top, bounds.height(), mViewBounds.height()) : bounds.top;
    if (offsetLeft != bounds.left || offsetTop != bounds.top) {
      newTransform.postTranslate(offsetLeft - bounds.left, offsetTop - bounds.top);
      return true;
    }
    return false;
  }

  private float getOffset(float offset, float imageDimension, float viewDimension) {
    float diff = viewDimension - imageDimension;
    return (diff > 0) ? diff / 2 : limit(offset, diff, 0);
  }

  private float limit(float value, float min, float max) {
    return Math.min(Math.max(min, value), max);
  }

}


text:
        <button data-field="search-button" class="btn btn-link btn-find" type="button">

        </button>

            <input data-field="search-input" type="text" class="form-control">

                0

                0

                <button data-field="prev-element" class="btn btn-link" type="button">

                </button>
                <button data-field="next-element" class="btn btn-link" type="button">

                </button>

                <button data-field="close-search" class="btn btn-link btn-find-close" type="button">

                </button>


text:
define(['plugins/router', 'durandal/app'], function (router, app) {
    return {
        //compositionComplete: function (view, parent) {
        //    app = require('durandal/app');
        //    console.log('below came from compo complete!');
        //    console.log(view, parent);
        //    app.trigger('test:compositionComplete', { view: view, viewModel: this });
        //},
        router: router,
        search: function() {
            //It's really easy to show a message box.
            //You can add custom options too. Also, it returns a promise for the user's response.
            app.showMessage('Search not yet implemented...');
        },
        activate: function () {
            router.map([
                { route: '', title:'Welcome', moduleId: 'viewmodels/welcome', nav: true },
                { route: 'flickr', moduleId: 'viewmodels/flickr', nav: true }
            ]).buildNavigationModel();

            return router.activate();
        }
    };
});


text:
import dbf_utilities as dbio
import shp_utilities as shio
import file_utilities as fio
from file_utilities import read_files, write_files


text:
package com.nkanaev.comics.fragment;

import java.io.File;
import java.util.ArrayList;

import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.view.MenuItemCompat;
import android.view.*;
import android.widget.*;
import android.support.v7.widget.SearchView;

import com.nkanaev.comics.R;
import com.nkanaev.comics.activity.MainActivity;
import com.nkanaev.comics.activity.ReaderActivity;
import com.nkanaev.comics.managers.LocalCoverHandler;
import com.nkanaev.comics.managers.Utils;
import com.nkanaev.comics.model.Comic;
import com.nkanaev.comics.model.Storage;
import com.nkanaev.comics.view.CoverImageView;
import com.squareup.picasso.Picasso;

public class LibraryBrowserFragment extends Fragment
        implements AdapterView.OnItemClickListener, SearchView.OnQueryTextListener {
    public static final String PARAM_PATH = "browserCurrentPath";

    private GridView mGridView;
    private ArrayList<Comic> mComics;
    private ArrayList<Integer> mDisplayedIndexes;
    private Picasso mPicasso;
    private String mFilterSearch = "";
    private int mFilterRead = R.id.menu_browser_filter_all;
    private String mPath;

    public static LibraryBrowserFragment create(String path) {
        LibraryBrowserFragment fragment = new LibraryBrowserFragment();
        Bundle args = new Bundle();
        args.putString(PARAM_PATH, path);
        fragment.setArguments(args);
        return fragment;
    }

    public LibraryBrowserFragment() {}

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        mPath = getArguments().getString(PARAM_PATH);
        getComics();
        setHasOptionsMenu(true);
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        final View view = inflater.inflate(R.layout.fragment_librarybrowser, container, false);
        final BrowserAdapter adapter = new BrowserAdapter();

        mPicasso = ((MainActivity) getActivity()).getPicasso();

        int deviceWidth = Utils.getDeviceWidth(getActivity());
        int columnWidth = getActivity().getResources().getInteger(R.integer.grid_comic_column_width);
        int numColumns = Math.round((float) deviceWidth / columnWidth);

        mGridView = (GridView)view.findViewById(R.id.gridView);
        mGridView.setAdapter(adapter);
        mGridView.setOnItemClickListener(this);
        mGridView.setNumColumns(numColumns);

        getActivity().setTitle(new File(getArguments().getString(PARAM_PATH)).getName());

        return view;
    }

    @Override
    public void onResume() {
        getComics();
        mGridView.invalidateViews();
        super.onResume();
    }

    @Override
    public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
        menu.clear();
        inflater.inflate(R.menu.browser, menu);

        MenuItem searchItem = menu.findItem(R.id.search);
        SearchView searchView = (SearchView) MenuItemCompat.getActionView(searchItem);
        searchView.setOnQueryTextListener(this);

        super.onCreateOptionsMenu(menu, inflater);
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
            case R.id.menu_browser_filter_all:
            case R.id.menu_browser_filter_read:
            case R.id.menu_browser_filter_unread:
            case R.id.menu_browser_filter_reading:
                item.setChecked(true);
                mFilterRead = item.getItemId();
                filterContent();
                return true;
        }

        return super.onOptionsItemSelected(item);
    }

    @Override
    public boolean onQueryTextChange(String s) {
        mFilterSearch = s;
        filterContent();
        return true;
    }

    @Override
    public boolean onQueryTextSubmit(String s) {
        return true;
    }

    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
        Comic comic = mComics.get(mDisplayedIndexes.get(position));

        Intent intent = new Intent(getActivity(), ReaderActivity.class);
        intent.putExtra(ReaderFragment.PARAM_HANDLER, comic.getId());
        intent.putExtra(ReaderFragment.PARAM_MODE, ReaderFragment.Mode.MODE_LIBRARY);
        startActivity(intent);
    }

    private void getComics() {
        mComics = Storage.getStorage(getActivity()).listComics(mPath);
        filterContent();
    }

    private void filterContent() {
        mDisplayedIndexes = new ArrayList<>();
        for (int i = 0; i < mComics.size(); i++) {
            Comic c = mComics.get(i);
            if (mFilterSearch.length() > 0 && !c.getFile().getName().contains(mFilterSearch))
                continue;
            if (mFilterRead != R.id.menu_browser_filter_all) {
                if (mFilterRead == R.id.menu_browser_filter_read && c.getCurrentPage() != c.getTotalPages())
                    continue;
                if (mFilterRead == R.id.menu_browser_filter_unread && c.getCurrentPage() != 0)
                    continue;
                if (mFilterRead == R.id.menu_browser_filter_reading &&
                        (c.getCurrentPage() == 0 || c.getCurrentPage() == c.getTotalPages()))
                    continue;
            }
            mDisplayedIndexes.add(i);
        }

        if (mGridView != null) mGridView.invalidateViews();
    }

    private final class BrowserAdapter extends BaseAdapter {
        @Override
        public int getCount() {
            return mDisplayedIndexes.size();
        }

        @Override
        public Object getItem(int position) {
            return mDisplayedIndexes.get(position);
        }

        @Override
        public long getItemId(int position) {
            return 0;
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            ViewGroup comicView = (ViewGroup) convertView;
            if (comicView == null) {
                comicView = (ViewGroup)getActivity()
                        .getLayoutInflater()
                        .inflate(R.layout.card_comic, parent, false);
            }

            Comic comic = mComics.get(mDisplayedIndexes.get(position));

            CoverImageView coverImageView = (CoverImageView)comicView.findViewById(R.id.comicImageView);
            TextView titleTextView = (TextView)comicView.findViewById(R.id.comicTitleTextView);
            TextView pagesTextView = (TextView)comicView.findViewById(R.id.comicPagerTextView);

            titleTextView.setText(comic.getFile().getName());
            pagesTextView.setText(Integer.toString(comic.getCurrentPage()) + '/' + Integer.toString(comic.getTotalPages()));

            mPicasso.load(LocalCoverHandler.getComicCoverUri(comic))
                    .into(coverImageView);

            return comicView;
        }
    }
}


text:
createTrackbar(trackbarname::String, winname::String, value::Ptr{Int32}, count::Int) =
     @cxx cv::createTrackbar(pointer(trackbarname),pointer(winname), value, count)

# createTrackbar(trackbarname::String, winname::String, value::Int, count::Int, onChange=C_NULL,
#     userdata=Ptr{Void}[0][1]) = @cxx cv::createTrackbar(pointer(trackbarname),pointer(winname), pointer([cint(value)]), count, onChange, userdata)

# trackbarname – Name of the created trackbar
# winname      – Name of the window that will be used as a parent of the created trackbar
# value        – Optional pointer to an integer variable whose value reflects the position of the slider
# count        – Maximal position of the slider. The minimal position is always 0.
# onChange     – Pointer to the function (TrackbarCallback) to be called every time the slider changes position.
#                 This function should be prototyped as void Foo(int,void*)
# userdata     – User data (void*) that is passed as is to the callback

# getTrackbarPos: Returns the trackbar position
getTrackbarPos(trackbarname::String,winname::String) = @cxx cv::getTrackbarPos(pointer(trackbarname),pointer(winname))

# namedWindow(const String& winname, int flags=WINDOW_AUTOSIZE)
namedWindow(windowName::String, flags=WINDOW_AUTOSIZE) = @cxx cv::namedWindow(pointer(windowName), flags)

# void imshow(const String& winname, InputArray mat)
imshow(windowName::String, img) = @cxx cv::imshow(pointer(windowName), img)

# waitKey
waitkey(delay) = @cxx cv::waitKey(delay)

# destroy GUI window(s)
destroyWindow(windowName::String) = @cxx cv::destroyWindow(pointer(windowName))
destroyAllWindows() = @cxx cv::destroyAllWindows()

# MoveWindow
moveWindow(winname::String, x::Int, y::Int) = @cxx cv::moveWindow(pointer(winname), x, y)
# x – The new x-coordinate of the window
# y – The new y-coordinate of the window

# ResizeWindow
resizeWindow(winname::String, width::Int, height::Int) = @cxx cv::resizeWindow(pointer(winname), width, height)

# SetMouseCallback: Sets mouse handler for the specified window
# create MouseCallback function wrapped in @cxx
setMouseCallback(winname::String, onMouse, userdata=Ptr{Void}[0]) =
    @cxx cv::setMouseCallback(pointer(winname), onMouse, userdata)

# Gets the mouse-wheel motion delta (multiple of 120)
@windows_only begin
    # EVENT_MOUSEWHEEL and EVENT_MOUSEHWHEEL
    getMouseWheelDelta(flags::Int) = @cxx getMouseWheelDelta(flags)
end

# setTrackbarPos (by value)
setTrackbarPos(trackbarname::String, winname::String, pos::Int) =
   @cxx cv::setTrackbarPos(pointer(trackbarname), pointer(winname), pos)


text:
//
// $Id$

package org.ductilej.tests;

import org.junit.Test;
import static org.junit.Assert.*;

/**
 * Tests initialization of transformed primitive fields.
 */
public class FieldInitTest
{
    @Test public void testInit ()
    {
        assertEquals(false, boolField);
        assertEquals((byte)0, byteField);
        assertEquals((char)0, charField);
        assertEquals(0, intField);
        assertEquals(0L, longField);
        assertEquals(0f, floatField, 0); // third arg is allowable error
        assertEquals(0d, doubleField, 0); // third arg is allowable error
        assertEquals(null, objectField);
    }

    protected boolean boolField;
    protected byte byteField;
    protected char charField;
    protected int intField;
    protected long longField;
    protected float floatField;
    protected double doubleField;
    protected Object objectField;
}


text:
package hudson.plugins.scm_sync_configuration.scms.customproviders.git.gitexe;

import org.apache.commons.io.FilenameUtils;
import org.apache.maven.scm.*;
import org.apache.maven.scm.command.checkin.CheckInScmResult;
import org.apache.maven.scm.log.ScmLogger;
import org.apache.maven.scm.provider.ScmProviderRepository;
import org.apache.maven.scm.provider.git.command.GitCommand;
import org.apache.maven.scm.provider.git.gitexe.GitExeScmProvider;
import org.apache.maven.scm.provider.git.gitexe.command.GitCommandLineUtils;
import org.apache.maven.scm.provider.git.gitexe.command.add.GitAddCommand;
import org.apache.maven.scm.provider.git.gitexe.command.branch.GitBranchCommand;
import org.apache.maven.scm.provider.git.gitexe.command.checkin.GitCheckInCommand;
import org.apache.maven.scm.provider.git.gitexe.command.status.GitStatusCommand;
import org.apache.maven.scm.provider.git.gitexe.command.status.GitStatusConsumer;
import org.apache.maven.scm.provider.git.repository.GitScmProviderRepository;
import org.codehaus.plexus.util.FileUtils;
import org.codehaus.plexus.util.cli.CommandLineUtils;
import org.codehaus.plexus.util.cli.Commandline;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

/**
 * @author fcamblor
 * Crappy hack because for the moment, in maven-scmprovider-gitext 1.8.1, when we checkIn file,
 * checkin is originally made by passing pushUrl instead of a local reference (such as "origin")
 * Problem is passing pushUrl doesn't update current local reference once pushed => after push,
 * origin/<targetBranch> will not be updated to latest commit => on next push, there will be an
 * error saying some pull is needed.
 * This workaround could be betterly handled when something like "checkinAndFetch" could be
 * implemented generically in maven-scm-api
 * (see http://maven.40175.n5.nabble.com/SCM-GitExe-no-fetch-after-push-td5745064.html)
 */
public class ScmSyncGitExeScmProvider extends GitExeScmProvider {
    public static class ScmSyncGitCheckInCommand extends GitCheckInCommand {
        // Retrieved implementation from GitCheckInCommande v1.8.1, only overriding call to createPushCommandLine()
        // by a *custom* implementation
        @Override
        protected CheckInScmResult executeCheckInCommand(
                ScmProviderRepository repo, ScmFileSet fileSet, String message, ScmVersion version ) throws ScmException {

            GitScmProviderRepository repository = (GitScmProviderRepository) repo;

            CommandLineUtils.StringStreamConsumer stderr = new CommandLineUtils.StringStreamConsumer();
            CommandLineUtils.StringStreamConsumer stdout = new CommandLineUtils.StringStreamConsumer();

            int exitCode;

            File messageFile = FileUtils.createTempFile("maven-scm-", ".commit", null);
            try
            {
                FileUtils.fileWrite( messageFile.getAbsolutePath(), message );
            }
            catch ( IOException ex )
            {
                return new CheckInScmResult( null, "Error while making a temporary file for the commit message: "
                    + ex.getMessage(), null, false );
            }

            try
            {
                if ( !fileSet.getFileList().isEmpty() )
                {
                    // if specific fileSet is given, we have to git-add them first
                    // otherwise we will use 'git-commit -a' later

                    Commandline clAdd = GitAddCommand.createCommandLine(fileSet.getBasedir(), fileSet.getFileList());

                    exitCode = GitCommandLineUtils.execute(clAdd, stdout, stderr, getLogger());

                    if ( exitCode != 0 )
                    {
                        return new CheckInScmResult( clAdd.toString(), "The git-add command failed.", stderr.getOutput(),
                                                     false );
                    }

                }

                // git-commit doesn't show single files, but only summary :/
                // so we must run git-status and consume the output
                // borrow a few things from the git-status command
                Commandline clStatus = GitStatusCommand.createCommandLine(repository, fileSet);

                GitStatusConsumer statusConsumer = new GitStatusConsumer( getLogger(), fileSet.getBasedir() );
                exitCode = GitCommandLineUtils.execute( clStatus, statusConsumer, stderr, getLogger() );
                if ( exitCode != 0 )
                {
                    // git-status returns non-zero if nothing to do
                    if ( getLogger().isInfoEnabled() )
                    {
                        getLogger().info( "nothing added to commit but untracked files present (use \"git add\" to " +
                                "track)" );
                    }
                }

                if ( statusConsumer.getChangedFiles().isEmpty() )
                {
                    return new CheckInScmResult( null, statusConsumer.getChangedFiles() );
                }

                Commandline clCommit = createCommitCommandLine( repository, fileSet, messageFile );

                exitCode = GitCommandLineUtils.execute( clCommit, stdout, stderr, getLogger() );
                if ( exitCode != 0 )
                {
                    return new CheckInScmResult( clCommit.toString(), "The git-commit command failed.", stderr.getOutput(),
                                                 false );
                }

                if( repo.isPushChanges() )
                {
                    Commandline cl = createSpecificPushCommandLine( getLogger(), repository, fileSet, version );

                    exitCode = GitCommandLineUtils.execute( cl, stdout, stderr, getLogger() );
                    if ( exitCode != 0 )
                    {
                        return new CheckInScmResult( cl.toString(), "The git-push command failed.", stderr.getOutput(), false );
                    }
                }

                List<ScmFile> checkedInFiles = new ArrayList<ScmFile>( statusConsumer.getChangedFiles().size() );

                // rewrite all detected files to now have status 'checked_in'
                for ( ScmFile changedFile : statusConsumer.getChangedFiles() )
                {
                    ScmFile scmfile = new ScmFile( changedFile.getPath(), ScmFileStatus.CHECKED_IN );

                    if ( fileSet.getFileList().isEmpty() )
                    {
                        checkedInFiles.add( scmfile );
                    }
                    else
                    {
                        // if a specific fileSet is given, we have to check if the file is really tracked
                        for ( File f : fileSet.getFileList() )
                        {
                            if ( FilenameUtils.separatorsToUnix(f.getPath()).equals( scmfile.getPath() ) )
                            {
                                checkedInFiles.add( scmfile );
                            }

                        }
                    }
                }

                return new CheckInScmResult( clCommit.toString(), checkedInFiles );
            }
            finally
            {
                try
                {
                    FileUtils.forceDelete( messageFile );
                }
                catch ( IOException ex )
                {
                    // ignore
                }
            }

        }

        // ----------------------------------------------------------------------
        //
        // ----------------------------------------------------------------------

        public static Commandline createSpecificPushCommandLine( ScmLogger logger, GitScmProviderRepository repository,
                                                         ScmFileSet fileSet, ScmVersion version )
            throws ScmException
        {
            Commandline cl = GitCommandLineUtils.getBaseGitCommandLine( fileSet.getBasedir(), "push" );

            String branch = GitBranchCommand.getCurrentBranch(logger, repository, fileSet);

            if ( branch == null || branch.length() == 0 )
            {
                throw new ScmException( "Could not detect the current branch. Don't know where I should push to!" );
            }

            // Overloaded branch name here : if repository.getUrl() is kept, during checkin(), current *local* branch
            // reference is not updated, whereas by using origin, it will be done !
            cl.createArg().setValue( "origin" );

            cl.createArg().setValue( branch + ":" + branch );

            return cl;
        }

    }

    @Override
    protected GitCommand getCheckInCommand() {
        return new ScmSyncGitCheckInCommand();
    }

}


text:
<?php
/**
 * Created by PhpStorm.
 * User: karlvaniseghem
 * Date: 19/06/15
 * Time: 10:04
 */

namespace Bakgat\Notos\Domain\Model;

class DomainException extends \Exception {

}


text:
package demolib1;

import static org.testng.Assert.*;

import org.testng.annotations.Test;

public class DemoLib1Test {
    @Test
    public void testVersion() {
        assertEquals(DemoLib1.getHardCodedVersion(), "1.2");
        assertEquals(DemoLib1.getVersionDefinedInPomXml(), "-");
    }
}


text:
from ctypes import (pythonapi, c_void_p, py_object)
import os

from vulkan import *
from PySide import (QtGui, QtCore)

pythonapi.PyCObject_AsVoidPtr.restype = c_void_p
pythonapi.PyCObject_AsVoidPtr.argtypes = [py_object]

WIDTH = 800
HEIGHT = 600

validationLayers = ["VK_LAYER_LUNARG_standard_validation"]
deviceExtensions = [VK_KHR_SWAPCHAIN_EXTENSION_NAME]

enableValidationLayers = True

def debugCallback(*args):
    print 'DEBUG: {} {}'.format(args[5], args[6])
    return 0

def createDebugReportCallbackEXT(instance, pCreateInfo, pAllocator):
    func = vkGetInstanceProcAddr(instance, 'vkCreateDebugReportCallbackEXT')
    if func:
        return func(instance, pCreateInfo, pAllocator)
    else:
        return VK_ERROR_EXTENSION_NOT_PRESENT

def destroyDebugReportCallbackEXT(instance, callback, pAllocator):
    func = vkGetInstanceProcAddr(instance, 'vkDestroyDebugReportCallbackEXT')
    if func:
        func(instance, callback, pAllocator)

def destroySurface(instance, surface, pAllocator=None):
    func = vkGetInstanceProcAddr(instance, 'vkDestroySurfaceKHR')
    if func:
        func(instance, surface, pAllocator)

def destroySwapChain(device, swapChain, pAllocator=None):
    func = vkGetDeviceProcAddr(device, 'vkDestroySwapchainKHR')
    if func:
        func(device, swapChain, pAllocator)

class Win32misc(object):
    @staticmethod
    def getInstance(hWnd):
        from cffi import FFI as _FFI
        _ffi = _FFI()
        _ffi.cdef('long __stdcall GetWindowLongA(void* hWnd, int nIndex);')
        _lib = _ffi.dlopen('User32.dll')
        return _lib.GetWindowLongA(_ffi.cast('void*', hWnd), -6)  # GWL_HINSTANCE

class QueueFamilyIndices(object):

    def __init__(self):
        self.graphicsFamily = -1
        self.presentFamily = -1

    def isComplete(self):
        return self.graphicsFamily >= 0 and self.presentFamily >= 0

class SwapChainSupportDetails(object):
    def __init__(self):
        self.capabilities = None
        self.formats = None
        self.presentModes = None

class HelloTriangleApplication(QtGui.QWidget):

    def __init__(self, parent=None):
        super(HelloTriangleApplication, self).__init__(parent)

        self.__instance = None
        self.__callback = None
        self.__surface = None
        self.__physicalDevice = None
        self.__device = None
        self.__graphicsQueue = None
        self.__presentQueue = None

        self.__swapChain = None
        self.__swapChainImages = None
        self.__swapChainImageFormat = None
        self.__swapChainExtent = None

        self.__swapChainImageViews = None
        self.__swapChainFramebuffers = None

        self.__renderPass = None
        self.__pipelineLayout = None
        self.__graphicsPipeline = None

        self.__commandPool = None
        self.__commandBuffers = None

        self.__imageAvailableSemaphore = None
        self.__renderFinishedSemaphore = None

    def __del__(self):
        vkDeviceWaitIdle(self.__device)

        if self.__imageAvailableSemaphore:
            vkDestroySemaphore(self.__device, self.__imageAvailableSemaphore, None)

        if self.__renderFinishedSemaphore:
            vkDestroySemaphore(self.__device, self.__renderFinishedSemaphore, None)

        if self.__commandBuffers:
            self.__commandBuffers = None

        if self.__commandPool:
            vkDestroyCommandPool(self.__device, self.__commandPool, None)

        if self.__swapChainFramebuffers:
            for i in self.__swapChainFramebuffers:
                vkDestroyFramebuffer(self.__device, i, None)
            self.__swapChainFramebuffers = None

        if self.__renderPass:
            vkDestroyRenderPass(self.__device, self.__renderPass, None)

        if self.__pipelineLayout:
            vkDestroyPipelineLayout(self.__device, self.__pipelineLayout, None)

        if self.__graphicsPipeline:
            vkDestroyPipeline(self.__device, self.__graphicsPipeline, None)

        if self.__swapChainImageViews:
            for i in self.__swapChainImageViews:
                vkDestroyImageView(self.__device, i, None)

        if self.__swapChain:
            destroySwapChain(self.__device, self.__swapChain, None)

        if self.__device:
            vkDestroyDevice(self.__device, None)

        if self.__surface:
            destroySurface(self.__instance, self.__surface, None)

        if self.__callback:
            destroyDebugReportCallbackEXT(self.__instance, self.__callback, None)

        if self.__instance:
            vkDestroyInstance(self.__instance, None)

    def __initWindow(self):
        self.setWindowTitle('Vulkan')
        self.setFixedSize(WIDTH, HEIGHT)
        self.createWinId()
        self.show()

    def __initVulkan(self):
        self.__createInstance()
        self.__setupDebugCallback()
        self.__createSurface()
        self.__pickPhysicalDevice()
        self.__createLogicalDevice()
        self.__createSwapChain()
        self.__createImageViews()
        self.__createRenderPass()
        self.__createGraphicsPipeline()
        self.__createFramebuffers()
        self.__createCommandPool()
        self.__createCommandBuffers()
        self.__createSemaphores()

    def timerEvent(self, event):
        self.__drawFrame()

        super(HelloTriangleApplication, self).timerEvent(event)

    def __createInstance(self):
        if enableValidationLayers and not self.__checkValidationLayerSupport():
            raise Exception("validation layers requested, but not available!")

        appInfo = VkApplicationInfo(
            pApplicationName='Hello Triangle',
            applicationVersion=VK_MAKE_VERSION(1, 0, 0),
            pEngineName='No Engine',
            engineVersion=VK_MAKE_VERSION(1, 0, 0),
            apiVersion=VK_MAKE_VERSION(1, 0, 3)
        )

        createInfo = VkInstanceCreateInfo(
            sType=VK_STRUCTURE_TYPE_INSTANCE_CREATE_INFO,
            pApplicationInfo=appInfo
        )
        extensions = self.__getRequiredExtensions()
        ext = [ffi.new('char[]', i) for i in extensions]
        extArray = ffi.new('char*[]', ext)

        createInfo.enabledExtensionCount = len(extensions)
        createInfo.ppEnabledExtensionNames = extArray

        if enableValidationLayers:
            createInfo.enabledLayerCount = len(validationLayers)
            layers = [ffi.new('char[]', i) for i in validationLayers]
            vlayers = ffi.new('char*[]', layers)
            createInfo.ppEnabledLayerNames = vlayers
        else:
            createInfo.enabledLayerCount = 0

        self.__instance = vkCreateInstance(createInfo, None)

    def __setupDebugCallback(self):
        if not enableValidationLayers:
            return

        createInfo = VkDebugReportCallbackCreateInfoEXT(
            flags=VK_DEBUG_REPORT_ERROR_BIT_EXT | VK_DEBUG_REPORT_WARNING_BIT_EXT,
            pfnCallback=debugCallback
        )
        self.__callback = createDebugReportCallbackEXT(self.__instance, createInfo, None)
        if not self.__callback:
            raise Exception("failed to set up debug callback!")

    def __createSurface(self):
        vkCreateWin32SurfaceKHR = vkGetInstanceProcAddr(self.__instance, 'vkCreateWin32SurfaceKHR')

        hwnd = pythonapi.PyCObject_AsVoidPtr(self.winId())
        hinstance = Win32misc.getInstance(hwnd)
        createInfo = VkWin32SurfaceCreateInfoKHR(
            sType=VK_STRUCTURE_TYPE_WIN32_SURFACE_CREATE_INFO_KHR,
            hinstance=hinstance,
            hwnd=hwnd
        )
        self.__surface = vkCreateWin32SurfaceKHR(self.__instance, createInfo, None)
        if self.__surface is None:
            raise Exception("failed to create window surface!")

    def __pickPhysicalDevice(self):
        devices = vkEnumeratePhysicalDevices(self.__instance)

        for device in devices:
            if self.__isDeviceSuitable(device):
                self.__physicalDevice = device
                break

        if self.__physicalDevice is None:
            raise Exception("failed to find a suitable GPU!")

    def __createLogicalDevice(self):
        indices = self.__findQueueFamilies(self.__physicalDevice)
        uniqueQueueFamilies = {}.fromkeys((indices.graphicsFamily, indices.presentFamily))
        queueCreateInfos = []
        for queueFamily in uniqueQueueFamilies:
            queueCreateInfo = VkDeviceQueueCreateInfo(
                sType=VK_STRUCTURE_TYPE_DEVICE_QUEUE_CREATE_INFO,
                queueFamilyIndex=queueFamily,
                queueCount=1,
                pQueuePriorities=[1.0]
            )
            queueCreateInfos.append(queueCreateInfo)

        deviceFeatures = VkPhysicalDeviceFeatures()
        deArray = [ffi.new('char[]', i) for i in deviceExtensions]
        deviceExtensions_c = ffi.new('char*[]', deArray)
        createInfo = VkDeviceCreateInfo(
            sType=VK_STRUCTURE_TYPE_DEVICE_CREATE_INFO,
            flags=0,
            pQueueCreateInfos=queueCreateInfos,
            queueCreateInfoCount=len(queueCreateInfos),
            pEnabledFeatures=[deviceFeatures],
            enabledExtensionCount=len(deviceExtensions),
            ppEnabledExtensionNames=deviceExtensions_c
        )

        if enableValidationLayers:
            createInfo.enabledLayerCount = len(validationLayers)
            layers = [ffi.new('char[]', i) for i in validationLayers]
            vlayers = ffi.new('char*[]', layers)
            createInfo.ppEnabledLayerNames = vlayers
        else:
            createInfo.enabledLayerCount = 0

        self.__device = vkCreateDevice(self.__physicalDevice, createInfo, None)
        if self.__device is None:
            raise Exception("failed to create logical device!")
        self.__graphicsQueue = vkGetDeviceQueue(self.__device, indices.graphicsFamily, 0)
        self.__presentQueue = vkGetDeviceQueue(self.__device, indices.presentFamily, 0)

    def __createSwapChain(self):
        swapChainSupport = self.__querySwapChainSupport(self.__physicalDevice)

        surfaceFormat = self.__chooseSwapSurfaceFormat(swapChainSupport.formats)
        presentMode = self.__chooseSwapPresentMode(swapChainSupport.presentModes)
        extent = self.__chooseSwapExtent(swapChainSupport.capabilities)

        imageCount = swapChainSupport.capabilities.minImageCount + 1
        if swapChainSupport.capabilities.maxImageCount > 0 and imageCount > swapChainSupport.capabilities.maxImageCount:
            imageCount = swapChainSupport.capabilities.maxImageCount

        createInfo = VkSwapchainCreateInfoKHR(
            sType=VK_STRUCTURE_TYPE_SWAPCHAIN_CREATE_INFO_KHR,
            flags=0,
            surface=self.__surface,
            minImageCount=imageCount,
            imageFormat=surfaceFormat.format,
            imageColorSpace=surfaceFormat.colorSpace,
            imageExtent=extent,
            imageArrayLayers=1,
            imageUsage=VK_IMAGE_USAGE_COLOR_ATTACHMENT_BIT
        )

        indices = self.__findQueueFamilies(self.__physicalDevice)
        if indices.graphicsFamily != indices.presentFamily:
            createInfo.imageSharingMode = VK_SHARING_MODE_CONCURRENT
            createInfo.queueFamilyIndexCount = 2
            createInfo.pQueueFamilyIndices = [indices.graphicsFamily, indices.presentFamily]
        else:
            createInfo.imageSharingMode = VK_SHARING_MODE_EXCLUSIVE

        createInfo.preTransform = swapChainSupport.capabilities.currentTransform
        createInfo.compositeAlpha = VK_COMPOSITE_ALPHA_OPAQUE_BIT_KHR
        createInfo.presentMode = presentMode
        createInfo.clipped = True

        vkCreateSwapchainKHR = vkGetDeviceProcAddr(self.__device, 'vkCreateSwapchainKHR')
        self.__swapChain = vkCreateSwapchainKHR(self.__device, createInfo, None)

        vkGetSwapchainImagesKHR = vkGetDeviceProcAddr(self.__device, 'vkGetSwapchainImagesKHR')
        self.__swapChainImages = vkGetSwapchainImagesKHR(self.__device, self.__swapChain)

        self.__swapChainImageFormat = surfaceFormat.format
        self.__swapChainExtent = extent

    def __createImageViews(self):
        self.__swapChainImageViews = []
        components = VkComponentMapping(VK_COMPONENT_SWIZZLE_IDENTITY, VK_COMPONENT_SWIZZLE_IDENTITY,
                                        VK_COMPONENT_SWIZZLE_IDENTITY, VK_COMPONENT_SWIZZLE_IDENTITY)
        subresourceRange = VkImageSubresourceRange(VK_IMAGE_ASPECT_COLOR_BIT,
                                                   0, 1, 0, 1)
        for i, image in enumerate(self.__swapChainImages):
            createInfo = VkImageViewCreateInfo(
                sType=VK_STRUCTURE_TYPE_IMAGE_VIEW_CREATE_INFO,
                flags=0,
                image=image,
                viewType=VK_IMAGE_VIEW_TYPE_2D,
                format=self.__swapChainImageFormat,
                components=components,
                subresourceRange=subresourceRange
            )
            self.__swapChainImageViews.append(vkCreateImageView(self.__device, createInfo, None))

    def __createRenderPass(self):
        colorAttachment = VkAttachmentDescription(
            format=self.__swapChainImageFormat,
            samples=VK_SAMPLE_COUNT_1_BIT,
            loadOp=VK_ATTACHMENT_LOAD_OP_CLEAR,
            storeOp=VK_ATTACHMENT_STORE_OP_STORE,
            stencilLoadOp=VK_ATTACHMENT_LOAD_OP_DONT_CARE,
            stencilStoreOp=VK_ATTACHMENT_STORE_OP_DONT_CARE,
            initialLayout=VK_IMAGE_LAYOUT_UNDEFINED,
            finalLayout=VK_IMAGE_LAYOUT_PRESENT_SRC_KHR
        )

        colorAttachmentRef = VkAttachmentReference(
            attachment=0,
            layout=VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL
        )

        subPass = VkSubpassDescription(
            pipelineBindPoint=VK_PIPELINE_BIND_POINT_GRAPHICS,
            colorAttachmentCount=1,
            pColorAttachments=colorAttachmentRef
        )

        renderPassInfo = VkRenderPassCreateInfo(
            sType=VK_STRUCTURE_TYPE_RENDER_PASS_CREATE_INFO,
            attachmentCount=1,
            pAttachments=colorAttachment,
            subpassCount=1,
            pSubpasses=subPass
        )

        self.__renderPass = vkCreateRenderPass(self.__device, renderPassInfo, None)

    def __createGraphicsPipeline(self):
        path = os.path.dirname(os.path.abspath(__file__))
        vertShaderModule = self.__createShaderModule(os.path.join(path, 'hello_triangle_vert.spv'))
        fragShaderModule = self.__createShaderModule(os.path.join(path, 'hello_triangle_frag.spv'))

        vertShaderStageInfo = VkPipelineShaderStageCreateInfo(
            sType=VK_STRUCTURE_TYPE_PIPELINE_SHADER_STAGE_CREATE_INFO,
            flags=0,
            stage=VK_SHADER_STAGE_VERTEX_BIT,
            module=vertShaderModule,
            pName='main'
        )

        fragShaderStageInfo = VkPipelineShaderStageCreateInfo(
            sType=VK_STRUCTURE_TYPE_PIPELINE_SHADER_STAGE_CREATE_INFO,
            flags=0,
            stage=VK_SHADER_STAGE_FRAGMENT_BIT,
            module=fragShaderModule,
            pName='main'
        )

        shaderStages = [vertShaderStageInfo, fragShaderStageInfo]

        vertexInputInfo = VkPipelineVertexInputStateCreateInfo(
            sType=VK_STRUCTURE_TYPE_PIPELINE_VERTEX_INPUT_STATE_CREATE_INFO,
            vertexBindingDescriptionCount=0,
            vertexAttributeDescriptionCount=0
        )

        inputAssembly = VkPipelineInputAssemblyStateCreateInfo(
            sType=VK_STRUCTURE_TYPE_PIPELINE_INPUT_ASSEMBLY_STATE_CREATE_INFO,
            topology=VK_PRIMITIVE_TOPOLOGY_TRIANGLE_LIST,
            primitiveRestartEnable=True
        )

        viewport = VkViewport(0.0, 0.0,
                              float(self.__swapChainExtent.width),
                              float(self.__swapChainExtent.height),
                              0.0, 1.0)
        scissor = VkRect2D([0, 0], self.__swapChainExtent)
        viewportState = VkPipelineViewportStateCreateInfo(
            sType=VK_STRUCTURE_TYPE_PIPELINE_VIEWPORT_STATE_CREATE_INFO,
            viewportCount=1,
            pViewports=viewport,
            scissorCount=1,
            pScissors=scissor
        )

        rasterizer = VkPipelineRasterizationStateCreateInfo(
            sType=VK_STRUCTURE_TYPE_PIPELINE_RASTERIZATION_STATE_CREATE_INFO,
            depthClampEnable=False,
            rasterizerDiscardEnable=False,
            polygonMode=VK_POLYGON_MODE_FILL,
            lineWidth=1.0,
            cullMode=VK_CULL_MODE_BACK_BIT,
            frontFace=VK_FRONT_FACE_CLOCKWISE,
            depthBiasEnable=False
        )

        multisampling = VkPipelineMultisampleStateCreateInfo(
            sType=VK_STRUCTURE_TYPE_PIPELINE_MULTISAMPLE_STATE_CREATE_INFO,
            sampleShadingEnable=False,
            rasterizationSamples=VK_SAMPLE_COUNT_1_BIT
        )

        colorBlendAttachment = VkPipelineColorBlendAttachmentState(
            colorWriteMask=VK_COLOR_COMPONENT_R_BIT | VK_COLOR_COMPONENT_G_BIT | VK_COLOR_COMPONENT_B_BIT | VK_COLOR_COMPONENT_A_BIT,
            blendEnable=False
        )

        colorBlending = VkPipelineColorBlendStateCreateInfo(
            sType=VK_STRUCTURE_TYPE_PIPELINE_COLOR_BLEND_STATE_CREATE_INFO,
            logicOpEnable=False,
            logicOp=VK_LOGIC_OP_COPY,
            attachmentCount=1,
            pAttachments=colorBlendAttachment,
            blendConstants=[0.0, 0.0, 0.0, 0.0]
        )

        pipelineLayoutInfo = VkPipelineLayoutCreateInfo(
            sType=VK_STRUCTURE_TYPE_PIPELINE_LAYOUT_CREATE_INFO,
            setLayoutCount=0,
            pushConstantRangeCount=0
        )

        self.__pipelineLayout = vkCreatePipelineLayout(self.__device, pipelineLayoutInfo, None)

        pipelineInfo = VkGraphicsPipelineCreateInfo(
            sType=VK_STRUCTURE_TYPE_GRAPHICS_PIPELINE_CREATE_INFO,
            stageCount=2,
            pStages=shaderStages,
            pVertexInputState=vertexInputInfo,
            pInputAssemblyState=inputAssembly,
            pViewportState=viewportState,
            pRasterizationState=rasterizer,
            pMultisampleState=multisampling,
            pColorBlendState=colorBlending,
            layout=self.__pipelineLayout,
            renderPass=self.__renderPass,
            subpass=0
        )

        self.__graphicsPipeline = vkCreateGraphicsPipelines(self.__device, VK_NULL_HANDLE, 1, pipelineInfo, None)

        vkDestroyShaderModule(self.__device, vertShaderModule, None)
        vkDestroyShaderModule(self.__device, fragShaderModule, None)

    def __createFramebuffers(self):
        self.__swapChainFramebuffers = []

        for imageView in self.__swapChainImageViews:
            attachments = [imageView,]

            framebufferInfo = VkFramebufferCreateInfo(
                sType=VK_STRUCTURE_TYPE_FRAMEBUFFER_CREATE_INFO,
                renderPass=self.__renderPass,
                attachmentCount=1,
                pAttachments=attachments,
                width=self.__swapChainExtent.width,
                height=self.__swapChainExtent.height,
                layers=1
            )
            framebuffer = vkCreateFramebuffer(self.__device, framebufferInfo, None)
            self.__swapChainFramebuffers.append(framebuffer)

    def __createCommandPool(self):
        queueFamilyIndices = self.__findQueueFamilies(self.__physicalDevice)

        poolInfo = VkCommandPoolCreateInfo(
            sType=VK_STRUCTURE_TYPE_COMMAND_POOL_CREATE_INFO,
            queueFamilyIndex=queueFamilyIndices.graphicsFamily
        )

        self.__commandPool = vkCreateCommandPool(self.__device, poolInfo, None)

    def __createCommandBuffers(self):
        # self.__commandBuffers = []

        allocInfo = VkCommandBufferAllocateInfo(
            sType=VK_STRUCTURE_TYPE_COMMAND_BUFFER_ALLOCATE_INFO,
            commandPool=self.__commandPool,
            level=VK_COMMAND_BUFFER_LEVEL_PRIMARY,
            commandBufferCount=len(self.__swapChainFramebuffers)
        )

        commandBuffers = vkAllocateCommandBuffers(self.__device, allocInfo)
        self.__commandBuffers = [ffi.addressof(commandBuffers, i)[0] for i in range(len(self.__swapChainFramebuffers))]

        for i, cmdBuffer in enumerate(self.__commandBuffers):
            beginInfo = VkCommandBufferBeginInfo(
                sType=VK_STRUCTURE_TYPE_COMMAND_BUFFER_BEGIN_INFO,
                flags=VK_COMMAND_BUFFER_USAGE_SIMULTANEOUS_USE_BIT
            )

            vkBeginCommandBuffer(cmdBuffer, beginInfo)

            renderPassInfo = VkRenderPassBeginInfo(
                sType=VK_STRUCTURE_TYPE_RENDER_PASS_BEGIN_INFO,
                renderPass=self.__renderPass,
                framebuffer=self.__swapChainFramebuffers[i],
                renderArea=[[0, 0], self.__swapChainExtent]
            )

            clearColor = VkClearValue([[0.0, 0.0, 0.0, 1.0]])
            renderPassInfo.clearValueCount = 1
            renderPassInfo.pClearValues = ffi.addressof(clearColor)

            vkCmdBeginRenderPass(cmdBuffer, renderPassInfo, VK_SUBPASS_CONTENTS_INLINE)

            vkCmdBindPipeline(cmdBuffer, VK_PIPELINE_BIND_POINT_GRAPHICS, self.__graphicsPipeline)
            vkCmdDraw(cmdBuffer, 3, 1, 0, 0)

            vkCmdEndRenderPass(cmdBuffer)

            vkEndCommandBuffer(cmdBuffer)

    def __createSemaphores(self):
        semaphoreInfo = VkSemaphoreCreateInfo(
            sType=VK_STRUCTURE_TYPE_SEMAPHORE_CREATE_INFO
        )

        self.__imageAvailableSemaphore = vkCreateSemaphore(self.__device, semaphoreInfo, None)
        self.__renderFinishedSemaphore = vkCreateSemaphore(self.__device, semaphoreInfo, None)

    def __drawFrame(self):
        vkAcquireNextImageKHR = vkGetDeviceProcAddr(self.__device, 'vkAcquireNextImageKHR')
        vkQueuePresentKHR = vkGetDeviceProcAddr(self.__device, 'vkQueuePresentKHR')

        imageIndex = vkAcquireNextImageKHR(self.__device, self.__swapChain, 18446744073709551615,
                                           self.__imageAvailableSemaphore, VK_NULL_HANDLE)

        submitInfo = VkSubmitInfo(sType=VK_STRUCTURE_TYPE_SUBMIT_INFO)

        waitSemaphores = ffi.new('VkSemaphore[]', [self.__imageAvailableSemaphore])
        waitStages = ffi.new('uint32_t[]', [VK_PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT, ])
        submitInfo.waitSemaphoreCount = 1
        submitInfo.pWaitSemaphores = waitSemaphores
        submitInfo.pWaitDstStageMask = waitStages

        cmdBuffers = ffi.new('VkCommandBuffer[]', [self.__commandBuffers[imageIndex], ])
        submitInfo.commandBufferCount = 1
        submitInfo.pCommandBuffers = cmdBuffers

        signalSemaphores = ffi.new('VkSemaphore[]', [self.__renderFinishedSemaphore])
        submitInfo.signalSemaphoreCount = 1
        submitInfo.pSignalSemaphores = signalSemaphores

        vkQueueSubmit(self.__graphicsQueue, 1, submitInfo, VK_NULL_HANDLE)

        swapChains = [self.__swapChain]
        presentInfo = VkPresentInfoKHR(
            sType=VK_STRUCTURE_TYPE_PRESENT_INFO_KHR,
            waitSemaphoreCount=1,
            pWaitSemaphores=signalSemaphores,
            swapchainCount=1,
            pSwapchains=swapChains,
            pImageIndices=[imageIndex]
        )

        vkQueuePresentKHR(self.__presentQueue, presentInfo)

    def __createShaderModule(self, shaderFile):
        with open(shaderFile, 'rb') as sf:
            code = sf.read()
            codeSize = len(code)
            # c_code = ffi.new('unsigned char []', code)
            # pcode = ffi.cast('uint32_t*', c_code)

            createInfo = VkShaderModuleCreateInfo(
                sType=VK_STRUCTURE_TYPE_SHADER_MODULE_CREATE_INFO,
                codeSize=codeSize,
                pCode=code
            )

            return vkCreateShaderModule(self.__device, createInfo, None)

    def __chooseSwapSurfaceFormat(self, availableFormats):
        if len(availableFormats) == 1 and availableFormats[0].format == VK_FORMAT_UNDEFINED:
            return VkSurfaceFormatKHR(VK_FORMAT_B8G8R8A8_UNORM, 0)

        for availableFormat in availableFormats:
            if availableFormat.format == VK_FORMAT_B8G8R8A8_UNORM and availableFormat.colorSpace == 0:
                return availableFormat

        return availableFormats[0]

    def __chooseSwapPresentMode(self, availablePresentModes):
        for availablePresentMode in availablePresentModes:
            if availablePresentMode == VK_PRESENT_MODE_MAILBOX_KHR:
                return availablePresentMode

        return VK_PRESENT_MODE_FIFO_KHR

    def __chooseSwapExtent(self, capabilities):
        width = max(capabilities.minImageExtent.width, min(capabilities.maxImageExtent.width, WIDTH))
        height = max(capabilities.minImageExtent.height, min(capabilities.maxImageExtent.height, HEIGHT))
        return VkExtent2D(width, height)

    def __querySwapChainSupport(self, device):
        details = SwapChainSupportDetails()

        vkGetPhysicalDeviceSurfaceCapabilitiesKHR = vkGetInstanceProcAddr(self.__instance,
                                                                          'vkGetPhysicalDeviceSurfaceCapabilitiesKHR')
        details.capabilities = vkGetPhysicalDeviceSurfaceCapabilitiesKHR(device, self.__surface)

        vkGetPhysicalDeviceSurfaceFormatsKHR = vkGetInstanceProcAddr(self.__instance,
                                                                     'vkGetPhysicalDeviceSurfaceFormatsKHR')
        details.formats = vkGetPhysicalDeviceSurfaceFormatsKHR(device, self.__surface)

        vkGetPhysicalDeviceSurfacePresentModesKHR = vkGetInstanceProcAddr(self.__instance,
                                                                          'vkGetPhysicalDeviceSurfacePresentModesKHR')
        details.presentModes = vkGetPhysicalDeviceSurfacePresentModesKHR(device, self.__surface)

        return details

    def __isDeviceSuitable(self, device):
        indices = self.__findQueueFamilies(device)
        extensionsSupported = self.__checkDeviceExtensionSupport(device)
        swapChainAdequate = False
        if extensionsSupported:
            swapChainSupport = self.__querySwapChainSupport(device)
            swapChainAdequate = (not swapChainSupport.formats is None) and (not swapChainSupport.presentModes is None)
        return indices.isComplete() and extensionsSupported and swapChainAdequate

    def __checkDeviceExtensionSupport(self, device):
        availableExtensions = vkEnumerateDeviceExtensionProperties(device, None)

        for extension in availableExtensions:
            if extension.extensionName in deviceExtensions:
                return True

        return False

    def __findQueueFamilies(self, device):
        vkGetPhysicalDeviceSurfaceSupportKHR = vkGetInstanceProcAddr(self.__instance,
                                                                   'vkGetPhysicalDeviceSurfaceSupportKHR')
        indices = QueueFamilyIndices()

        queueFamilies = vkGetPhysicalDeviceQueueFamilyProperties(device)

        for i, queueFamily in enumerate(queueFamilies):
            if queueFamily.queueCount > 0 and queueFamily.queueFlags & VK_QUEUE_GRAPHICS_BIT:
                indices.graphicsFamily = i

            presentSupport = vkGetPhysicalDeviceSurfaceSupportKHR(device, i, self.__surface)

            if queueFamily.queueCount > 0 and presentSupport:
                indices.presentFamily = i

            if indices.isComplete():
                break

        return indices

    def __getRequiredExtensions(self):
        extensions = [i.extensionName for i in vkEnumerateInstanceExtensionProperties(None)]

        if enableValidationLayers:
            extensions.append(VK_EXT_DEBUG_REPORT_EXTENSION_NAME)

        return extensions

    def __checkValidationLayerSupport(self):
        availableLayers = vkEnumerateInstanceLayerProperties()

        for layerName in validationLayers:
            layerFound = False

            for layerProperties in availableLayers:

                if layerName == layerProperties.layerName:
                    layerFound = True
                    break
            if not layerFound:
                return False

        return True

    def run(self):
        self.__initWindow()
        self.__initVulkan()

        # self.__timer.start(30)
        self.startTimer(30)

if __name__ == '__main__':
    import sys

    app = QtGui.QApplication(sys.argv)

    win = HelloTriangleApplication()

    win.run()

    def cleanUp():
        global win
        del win

    app.aboutToQuit.connect(cleanUp)

    sys.exit(app.exec_())


text:
package quizleague.rest

import javax.ws.rs.core.EntityTag
import java.util.UUID
import javax.cache.CacheManager
import java.util.Collections
import scala.collection.JavaConverters._

object EtagCache {

  private val cache = CacheManager.getInstance.getCacheFactory.createCache(Collections.emptyMap()).asInstanceOf[java.util.Map[String,String]].asScala

  def add(id:String):EntityTag = {
    val etag = EntityTag.valueOf(s""""${UUID.randomUUID().toString()}"""")
    cache.put(factorId(id), etag.getValue)
    etag
  }

  def remove(id:String) = cache.remove(factorId(id))

  def get(id:String) = cache.get(factorId(id)).fold(add(id))(t => EntityTag.valueOf(s""""$t""""))

  private def factorId(id:String) = s"$id-etag"

 }


text:
package oot.fruh_jando.studentenverwaltung;

import java.util.Date;

public class Verwaltung {

    public static void main(String[] args) {
        Student student1 = new Student("Max Jando", new Date(1987, 8, 3), Geschlecht.Maennlich);
        //Student student2 = new Student("Sieglinde Bürger", new Date(1980, 12, 7), Geschlecht.Weiblich);
        Kurs oot = new Kurs("OOT", "09:00", "12:00");
        Kurs tpe = new Kurs("TPE", "09:00", "12:00");
        student1.addKurs(oot);
        student1.addKurs(tpe);
        System.out.println(student1.getStundenplan());

    }
}


text:
/**
 * Autogenerated by Thrift Compiler (0.9.1)
 *
 * DO NOT EDIT UNLESS YOU ARE SURE THAT YOU KNOW WHAT YOU ARE DOING
 *  @generated
 */
package org.wso2.carbon.databridge.commons.thrift.data;

import org.apache.thrift.scheme.IScheme;
import org.apache.thrift.scheme.SchemeFactory;
import org.apache.thrift.scheme.StandardScheme;

import org.apache.thrift.scheme.TupleScheme;
import org.apache.thrift.protocol.TTupleProtocol;
import org.apache.thrift.protocol.TProtocolException;
import org.apache.thrift.EncodingUtils;
import org.apache.thrift.TException;
import org.apache.thrift.async.AsyncMethodCallback;
import org.apache.thrift.server.AbstractNonblockingServer.*;
import java.util.List;
import java.util.ArrayList;
import java.util.Map;
import java.util.HashMap;
import java.util.EnumMap;
import java.util.Set;
import java.util.HashSet;
import java.util.EnumSet;
import java.util.Collections;
import java.util.BitSet;
import java.nio.ByteBuffer;
import java.util.Arrays;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class ThriftAttribute implements org.apache.thrift.TBase<ThriftAttribute, ThriftAttribute._Fields>, java.io.Serializable, Cloneable, Comparable<ThriftAttribute> {
  private static final org.apache.thrift.protocol.TStruct STRUCT_DESC = new org.apache.thrift.protocol.TStruct("ThriftAttribute");

  private static final org.apache.thrift.protocol.TField NAME_FIELD_DESC = new org.apache.thrift.protocol.TField("name", org.apache.thrift.protocol.TType.STRING, (short)1);
  private static final org.apache.thrift.protocol.TField ATTRIBUTE_TYPE_FIELD_DESC = new org.apache.thrift.protocol.TField("attributeType", org.apache.thrift.protocol.TType.I32, (short)2);

  private static final Map<Class<? extends IScheme>, SchemeFactory> schemes = new HashMap<Class<? extends IScheme>, SchemeFactory>();
  static {
    schemes.put(StandardScheme.class, new ThriftAttributeStandardSchemeFactory());
    schemes.put(TupleScheme.class, new ThriftAttributeTupleSchemeFactory());
  }

  public String name; // optional
  /**
   *
   * @see org.wso2.carbon.databridge.commons.thrift.data.ThriftAttributeType
   */
  public ThriftAttributeType attributeType; // optional

  /** The set of fields this struct contains, along with convenience methods for finding and manipulating them. */
  public enum _Fields implements org.apache.thrift.TFieldIdEnum {
    NAME((short)1, "name"),
    /**
     *
     * @see org.wso2.carbon.databridge.commons.thrift.data.ThriftAttributeType
     */
    ATTRIBUTE_TYPE((short)2, "attributeType");

    private static final Map<String, _Fields> byName = new HashMap<String, _Fields>();

    static {
      for (_Fields field : EnumSet.allOf(_Fields.class)) {
        byName.put(field.getFieldName(), field);
      }
    }

    /**
     * Find the _Fields constant that matches fieldId, or null if its not found.
     */
    public static _Fields findByThriftId(int fieldId) {
      switch(fieldId) {
        case 1: // NAME
          return NAME;
        case 2: // ATTRIBUTE_TYPE
          return ATTRIBUTE_TYPE;
        default:
          return null;
      }
    }

    /**
     * Find the _Fields constant that matches fieldId, throwing an exception
     * if it is not found.
     */
    public static _Fields findByThriftIdOrThrow(int fieldId) {
      _Fields fields = findByThriftId(fieldId);
      if (fields == null) throw new IllegalArgumentException("Field " + fieldId + " doesn't exist!");
      return fields;
    }

    /**
     * Find the _Fields constant that matches name, or null if its not found.
     */
    public static _Fields findByName(String name) {
      return byName.get(name);
    }

    private final short _thriftId;
    private final String _fieldName;

    _Fields(short thriftId, String fieldName) {
      _thriftId = thriftId;
      _fieldName = fieldName;
    }

    public short getThriftFieldId() {
      return _thriftId;
    }

    public String getFieldName() {
      return _fieldName;
    }
  }

  // isset id assignments
  private _Fields optionals[] = {_Fields.NAME,_Fields.ATTRIBUTE_TYPE};
  public static final Map<_Fields, org.apache.thrift.meta_data.FieldMetaData> metaDataMap;
  static {
    Map<_Fields, org.apache.thrift.meta_data.FieldMetaData> tmpMap = new EnumMap<_Fields, org.apache.thrift.meta_data.FieldMetaData>(_Fields.class);
    tmpMap.put(_Fields.NAME, new org.apache.thrift.meta_data.FieldMetaData("name", org.apache.thrift.TFieldRequirementType.OPTIONAL,
        new org.apache.thrift.meta_data.FieldValueMetaData(org.apache.thrift.protocol.TType.STRING)));
    tmpMap.put(_Fields.ATTRIBUTE_TYPE, new org.apache.thrift.meta_data.FieldMetaData("attributeType", org.apache.thrift.TFieldRequirementType.OPTIONAL,
        new org.apache.thrift.meta_data.EnumMetaData(org.apache.thrift.protocol.TType.ENUM, ThriftAttributeType.class)));
    metaDataMap = Collections.unmodifiableMap(tmpMap);
    org.apache.thrift.meta_data.FieldMetaData.addStructMetaDataMap(ThriftAttribute.class, metaDataMap);
  }

  public ThriftAttribute() {
  }

  /**
   * Performs a deep copy on <i>other</i>.
   */
  public ThriftAttribute(ThriftAttribute other) {
    if (other.isSetName()) {
      this.name = other.name;
    }
    if (other.isSetAttributeType()) {
      this.attributeType = other.attributeType;
    }
  }

  public ThriftAttribute deepCopy() {
    return new ThriftAttribute(this);
  }

  @Override
  public void clear() {
    this.name = null;
    this.attributeType = null;
  }

  public String getName() {
    return this.name;
  }

  public ThriftAttribute setName(String name) {
    this.name = name;
    return this;
  }

  public void unsetName() {
    this.name = null;
  }

  /** Returns true if field name is set (has been assigned a value) and false otherwise */
  public boolean isSetName() {
    return this.name != null;
  }

  public void setNameIsSet(boolean value) {
    if (!value) {
      this.name = null;
    }
  }

  /**
   *
   * @see org.wso2.carbon.databridge.commons.thrift.data.ThriftAttributeType
   */
  public ThriftAttributeType getAttributeType() {
    return this.attributeType;
  }

  /**
   *
   * @see org.wso2.carbon.databridge.commons.thrift.data.ThriftAttributeType
   */
  public ThriftAttribute setAttributeType(ThriftAttributeType attributeType) {
    this.attributeType = attributeType;
    return this;
  }

  public void unsetAttributeType() {
    this.attributeType = null;
  }

  /** Returns true if field attributeType is set (has been assigned a value) and false otherwise */
  public boolean isSetAttributeType() {
    return this.attributeType != null;
  }

  public void setAttributeTypeIsSet(boolean value) {
    if (!value) {
      this.attributeType = null;
    }
  }

  public void setFieldValue(_Fields field, Object value) {
    switch (field) {
    case NAME:
      if (value == null) {
        unsetName();
      } else {
        setName((String)value);
      }
      break;

    case ATTRIBUTE_TYPE:
      if (value == null) {
        unsetAttributeType();
      } else {
        setAttributeType((ThriftAttributeType)value);
      }
      break;

    }
  }

  public Object getFieldValue(_Fields field) {
    switch (field) {
    case NAME:
      return getName();

    case ATTRIBUTE_TYPE:
      return getAttributeType();

    }
    throw new IllegalStateException();
  }

  /** Returns true if field corresponding to fieldID is set (has been assigned a value) and false otherwise */
  public boolean isSet(_Fields field) {
    if (field == null) {
      throw new IllegalArgumentException();
    }

    switch (field) {
    case NAME:
      return isSetName();
    case ATTRIBUTE_TYPE:
      return isSetAttributeType();
    }
    throw new IllegalStateException();
  }

  @Override
  public boolean equals(Object that) {
    if (that == null)
      return false;
    if (that instanceof ThriftAttribute)
      return this.equals((ThriftAttribute)that);
    return false;
  }

  public boolean equals(ThriftAttribute that) {
    if (that == null)
      return false;

    boolean this_present_name = true && this.isSetName();
    boolean that_present_name = true && that.isSetName();
    if (this_present_name || that_present_name) {
      if (!(this_present_name && that_present_name))
        return false;
      if (!this.name.equals(that.name))
        return false;
    }

    boolean this_present_attributeType = true && this.isSetAttributeType();
    boolean that_present_attributeType = true && that.isSetAttributeType();
    if (this_present_attributeType || that_present_attributeType) {
      if (!(this_present_attributeType && that_present_attributeType))
        return false;
      if (!this.attributeType.equals(that.attributeType))
        return false;
    }

    return true;
  }

  @Override
  public int hashCode() {
    return 0;
  }

  @Override
  public int compareTo(ThriftAttribute other) {
    if (!getClass().equals(other.getClass())) {
      return getClass().getName().compareTo(other.getClass().getName());
    }

    int lastComparison = 0;

    lastComparison = Boolean.valueOf(isSetName()).compareTo(other.isSetName());
    if (lastComparison != 0) {
      return lastComparison;
    }
    if (isSetName()) {
      lastComparison = org.apache.thrift.TBaseHelper.compareTo(this.name, other.name);
      if (lastComparison != 0) {
        return lastComparison;
      }
    }
    lastComparison = Boolean.valueOf(isSetAttributeType()).compareTo(other.isSetAttributeType());
    if (lastComparison != 0) {
      return lastComparison;
    }
    if (isSetAttributeType()) {
      lastComparison = org.apache.thrift.TBaseHelper.compareTo(this.attributeType, other.attributeType);
      if (lastComparison != 0) {
        return lastComparison;
      }
    }
    return 0;
  }

  public _Fields fieldForId(int fieldId) {
    return _Fields.findByThriftId(fieldId);
  }

  public void read(org.apache.thrift.protocol.TProtocol iprot) throws TException {
    schemes.get(iprot.getScheme()).getScheme().read(iprot, this);
  }

  public void write(org.apache.thrift.protocol.TProtocol oprot) throws TException {
    schemes.get(oprot.getScheme()).getScheme().write(oprot, this);
  }

  @Override
  public String toString() {
    StringBuilder sb = new StringBuilder("ThriftAttribute(");
    boolean first = true;

    if (isSetName()) {
      sb.append("name:");
      if (this.name == null) {
        sb.append("null");
      } else {
        sb.append(this.name);
      }
      first = false;
    }
    if (isSetAttributeType()) {
      if (!first) sb.append(", ");
      sb.append("attributeType:");
      if (this.attributeType == null) {
        sb.append("null");
      } else {
        sb.append(this.attributeType);
      }
      first = false;
    }
    sb.append(")");
    return sb.toString();
  }

  public void validate() throws TException {
    // check for required fields
    // check for sub-struct validity
  }

  private void writeObject(java.io.ObjectOutputStream out) throws java.io.IOException {
    try {
      write(new org.apache.thrift.protocol.TCompactProtocol(new org.apache.thrift.transport.TIOStreamTransport(out)));
    } catch (TException te) {
      throw new java.io.IOException(te);
    }
  }

  private void readObject(java.io.ObjectInputStream in) throws java.io.IOException, ClassNotFoundException {
    try {
      read(new org.apache.thrift.protocol.TCompactProtocol(new org.apache.thrift.transport.TIOStreamTransport(in)));
    } catch (TException te) {
      throw new java.io.IOException(te);
    }
  }

  private static class ThriftAttributeStandardSchemeFactory implements SchemeFactory {
    public ThriftAttributeStandardScheme getScheme() {
      return new ThriftAttributeStandardScheme();
    }
  }

  private static class ThriftAttributeStandardScheme extends StandardScheme<ThriftAttribute> {

    public void read(org.apache.thrift.protocol.TProtocol iprot, ThriftAttribute struct) throws TException {
      org.apache.thrift.protocol.TField schemeField;
      iprot.readStructBegin();
      while (true)
      {
        schemeField = iprot.readFieldBegin();
        if (schemeField.type == org.apache.thrift.protocol.TType.STOP) {
          break;
        }
        switch (schemeField.id) {
          case 1: // NAME
            if (schemeField.type == org.apache.thrift.protocol.TType.STRING) {
              struct.name = iprot.readString();
              struct.setNameIsSet(true);
            } else {
              org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type);
            }
            break;
          case 2: // ATTRIBUTE_TYPE
            if (schemeField.type == org.apache.thrift.protocol.TType.I32) {
              struct.attributeType = ThriftAttributeType.findByValue(iprot.readI32());
              struct.setAttributeTypeIsSet(true);
            } else {
              org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type);
            }
            break;
          default:
            org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type);
        }
        iprot.readFieldEnd();
      }
      iprot.readStructEnd();

      // check for required fields of primitive type, which can't be checked in the validate method
      struct.validate();
    }

    public void write(org.apache.thrift.protocol.TProtocol oprot, ThriftAttribute struct) throws TException {
      struct.validate();

      oprot.writeStructBegin(STRUCT_DESC);
      if (struct.name != null) {
        if (struct.isSetName()) {
          oprot.writeFieldBegin(NAME_FIELD_DESC);
          oprot.writeString(struct.name);
          oprot.writeFieldEnd();
        }
      }
      if (struct.attributeType != null) {
        if (struct.isSetAttributeType()) {
          oprot.writeFieldBegin(ATTRIBUTE_TYPE_FIELD_DESC);
          oprot.writeI32(struct.attributeType.getValue());
          oprot.writeFieldEnd();
        }
      }
      oprot.writeFieldStop();
      oprot.writeStructEnd();
    }

  }

  private static class ThriftAttributeTupleSchemeFactory implements SchemeFactory {
    public ThriftAttributeTupleScheme getScheme() {
      return new ThriftAttributeTupleScheme();
    }
  }

  private static class ThriftAttributeTupleScheme extends TupleScheme<ThriftAttribute> {

    @Override
    public void write(org.apache.thrift.protocol.TProtocol prot, ThriftAttribute struct) throws TException {
      TTupleProtocol oprot = (TTupleProtocol) prot;
      BitSet optionals = new BitSet();
      if (struct.isSetName()) {
        optionals.set(0);
      }
      if (struct.isSetAttributeType()) {
        optionals.set(1);
      }
      oprot.writeBitSet(optionals, 2);
      if (struct.isSetName()) {
        oprot.writeString(struct.name);
      }
      if (struct.isSetAttributeType()) {
        oprot.writeI32(struct.attributeType.getValue());
      }
    }

    @Override
    public void read(org.apache.thrift.protocol.TProtocol prot, ThriftAttribute struct) throws TException {
      TTupleProtocol iprot = (TTupleProtocol) prot;
      BitSet incoming = iprot.readBitSet(2);
      if (incoming.get(0)) {
        struct.name = iprot.readString();
        struct.setNameIsSet(true);
      }
      if (incoming.get(1)) {
        struct.attributeType = ThriftAttributeType.findByValue(iprot.readI32());
        struct.setAttributeTypeIsSet(true);
      }
    }
  }

}


text:
/**
 * This class provides a container DD instance that allows dragging of multiple child source nodes.
 *
 * This class does not move the drag target nodes, but a proxy element which may contain any DOM structure you wish. The
 * DOM element to show in the proxy is provided by either a provided implementation of {@link #getDragData}, or by
 * registered draggables registered with {@link Ext.dd.Registry}
 *
 * If you wish to provide draggability for an arbitrary number of DOM nodes, each of which represent some application
 * object (For example nodes in a {@link Ext.view.View DataView}) then use of this class is the most efficient way to
 * "activate" those nodes.
 *
 * By default, this class requires that draggable child nodes are registered with {@link Ext.dd.Registry}. However a
 * simpler way to allow a DragZone to manage any number of draggable elements is to configure the DragZone with an
 * implementation of the {@link #getDragData} method which interrogates the passed mouse event to see if it has taken
 * place within an element, or class of elements. This is easily done by using the event's {@link
 * Ext.EventObject#getTarget getTarget} method to identify a node based on a {@link Ext.DomQuery} selector. For example,
 * to make the nodes of a DataView draggable, use the following technique. Knowledge of the use of the DataView is
 * required:
 *
 *     myDataView.on('render', function(v) {
 *         myDataView.dragZone = new Ext.dd.DragZone(v.getEl(), {
 *
 *     //      On receipt of a mousedown event, see if it is within a DataView node.
 *     //      Return a drag data object if so.
 *             getDragData: function(e) {
 *
 *     //          Use the DataView's own itemSelector (a mandatory property) to
 *     //          test if the mousedown is within one of the DataView's nodes.
 *                 var sourceEl = e.getTarget(v.itemSelector, 10);
 *
 *     //          If the mousedown is within a DataView node, clone the node to produce
 *     //          a ddel element for use by the drag proxy. Also add application data
 *     //          to the returned data object.
 *                 if (sourceEl) {
 *                     d = sourceEl.cloneNode(true);
 *                     d.id = Ext.id();
 *                     return {
 *                         ddel: d,
 *                         sourceEl: sourceEl,
 *                         repairXY: Ext.fly(sourceEl).getXY(),
 *                         sourceStore: v.store,
 *                         draggedRecord: v.{@link Ext.view.View#getRecord getRecord}(sourceEl)
 *                     }
 *                 }
 *             },
 *
 *     //      Provide coordinates for the proxy to slide back to on failed drag.
 *     //      This is the original XY coordinates of the draggable element captured
 *     //      in the getDragData method.
 *             getRepairXY: function() {
 *                 return this.dragData.repairXY;
 *             }
 *         });
 *     });
 *
 * See the {@link Ext.dd.DropZone DropZone} documentation for details about building a DropZone which cooperates with
 * this DragZone.
 */
Ext.define('Ext.dd.DragZone', {
    extend: 'Ext.dd.DragSource',

    /**
     * Creates new DragZone.
     * @param {String/HTMLElement/Ext.Element} el The container element or ID of it.
     * @param {Object} config
     */
    constructor : function(el, config){
        var me = this,
            scroll = me.containerScroll;

        me.callParent([el, config]);
        if (scroll) {
            el = me.scrollEl || el;
            el = Ext.get(el);
            if (Ext.isObject(scroll)) {
                el.ddScrollConfig = scroll;
            }
            Ext.dd.ScrollManager.register(el);
        }
    },

    /**
     * @property {Object} dragData
     * This property contains the data representing the dragged object. This data is set up by the implementation of the
     * {@link #getDragData} method. It must contain a ddel property, but can contain any other data according to the
     * application's needs.
     */

    /**
     * @cfg {Object/Boolean} containerScroll
     * True to register this container with the Scrollmanager for auto scrolling during drag operations.
     * A {@link Ext.dd.ScrollManager} configuration may also be passed.
     */

    /**
     * @cfg {String/HTMLElement/Ext.dom.Element} scrollEl
     * An element to register with the ScrollManager if {@link #containerScroll}
     * is set. Defaults to the drag element.
     */

    /**
     * Called when a mousedown occurs in this container. Looks in {@link Ext.dd.Registry} for a valid target to drag
     * based on the mouse down. Override this method to provide your own lookup logic (e.g. finding a child by class
     * name). Make sure your returned object has a "ddel" attribute (with an HTML Element) for other functions to work.
     * @param {Event} e The mouse down event
     * @return {Object} The dragData
     */
    getDragData : function(e){
        return Ext.dd.Registry.getHandleFromEvent(e);
    },

    /**
     * Called once drag threshold has been reached to initialize the proxy element. By default, it clones the
     * this.dragData.ddel
     * @param {Number} x The x position of the click on the dragged object
     * @param {Number} y The y position of the click on the dragged object
     * @return {Boolean} true to continue the drag, false to cancel
     * @template
     */
    onInitDrag : function(x, y){
        this.proxy.update(this.dragData.ddel.cloneNode(true));
        this.onStartDrag(x, y);
        return true;
    },

    /**
     * Called before a repair of an invalid drop to get the XY to animate to. By default returns the XY of
     * this.dragData.ddel
     * @param {Event} e The mouse up event
     * @return {Number[]} The xy location (e.g. `[100, 200]`)
     * @template
     */
    getRepairXY : function(e){
        return Ext.fly(this.dragData.ddel).getXY();
    },

    destroy : function(){
        this.callParent();
        if (this.containerScroll) {
            Ext.dd.ScrollManager.unregister(this.scrollEl || this.el);
        }
    }
});