text:
.class Landroid/support/v4/widget/MaterialProgressDrawable$Ring;
.super Ljava/lang/Object;
.source "MaterialProgressDrawable.java"

# annotations
.annotation system Ldalvik/annotation/EnclosingClass;
    value = Landroid/support/v4/widget/MaterialProgressDrawable;
.end annotation

.annotation system Ldalvik/annotation/InnerClass;
    accessFlags = 0xa
    name = "Ring"
.end annotation

# instance fields
.field private mAlpha:I

.field private mArrow:Landroid/graphics/Path;

.field private mArrowHeight:I

.field private final mArrowPaint:Landroid/graphics/Paint;

.field private mArrowScale:F

.field private mArrowWidth:I

.field private mBackgroundColor:I

.field private final mCallback:Landroid/graphics/drawable/Drawable$Callback;

.field private final mCirclePaint:Landroid/graphics/Paint;

.field private mColorIndex:I

.field private mColors:[I

.field private mCurrentColor:I

.field private mEndTrim:F

.field private final mPaint:Landroid/graphics/Paint;

.field private mRingCenterRadius:D

.field private mRotation:F

.field private mShowArrow:Z

.field private mStartTrim:F

.field private mStartingEndTrim:F

.field private mStartingRotation:F

.field private mStartingStartTrim:F

.field private mStrokeInset:F

.field private mStrokeWidth:F

.field private final mTempBounds:Landroid/graphics/RectF;

# direct methods
.method constructor <init>(Landroid/graphics/drawable/Drawable$Callback;)V
    .locals 3

    const/4 v2, 0x1

    const/4 v1, 0x0

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

    new-instance v0, Landroid/graphics/RectF;

    invoke-direct {v0}, Landroid/graphics/RectF;-><init>()V

    iput-object v0, p0, Landroid/support/v4/widget/MaterialProgressDrawable$Ring;->mTempBounds:Landroid/graphics/RectF;

    new-instance v0, Landroid/graphics/Paint;

    invoke-direct {v0}, Landroid/graphics/Paint;-><init>()V

    iput-object v0, p0, Landroid/support/v4/widget/MaterialProgressDrawable$Ring;->mPaint:Landroid/graphics/Paint;

    new-instance v0, Landroid/graphics/Paint;

    invoke-direct {v0}, Landroid/graphics/Paint;-><init>()V

    iput-object v0, p0, Landroid/support/v4/widget/MaterialProgressDrawable$Ring;->mArrowPaint:Landroid/graphics/Paint;

    iput v1, p0, Landroid/support/v4/widget/MaterialProgressDrawable$Ring;->mStartTrim:F

    iput v1, p0, Landroid/support/v4/widget/MaterialProgressDrawable$Ring;->mEndTrim:F

    iput v1, p0, Landroid/support/v4/widget/MaterialProgressDrawable$Ring;->mRotation:F

    const/high16 v0, 0x40a00000    # 5.0f

    iput v0, p0, Landroid/support/v4/widget/MaterialProgressDrawable$Ring;->mStrokeWidth:F

    const/high16 v0, 0x40200000    # 2.5f

    iput v0, p0, Landroid/support/v4/widget/MaterialProgressDrawable$Ring;->mStrokeInset:F

    new-instance v0, Landroid/graphics/Paint;

    invoke-direct {v0, v2}, Landroid/graphics/Paint;-><init>(I)V

    iput-object v0, p0, Landroid/support/v4/widget/MaterialProgressDrawable$Ring;->mCirclePaint:Landroid/graphics/Paint;

    iput-object p1, p0, Landroid/support/v4/widget/MaterialProgressDrawable$Ring;->mCallback:Landroid/graphics/drawable/Drawable$Callback;

    iget-object v0, p0, Landroid/support/v4/widget/MaterialProgressDrawable$Ring;->mPaint:Landroid/graphics/Paint;

    sget-object v1, Landroid/graphics/Paint$Cap;->SQUARE:Landroid/graphics/Paint$Cap;

    invoke-virtual {v0, v1}, Landroid/graphics/Paint;->setStrokeCap(Landroid/graphics/Paint$Cap;)V

    iget-object v0, p0, Landroid/support/v4/widget/MaterialProgressDrawable$Ring;->mPaint:Landroid/graphics/Paint;

    invoke-virtual {v0, v2}, Landroid/graphics/Paint;->setAntiAlias(Z)V

    iget-object v0, p0, Landroid/support/v4/widget/MaterialProgressDrawable$Ring;->mPaint:Landroid/graphics/Paint;

    sget-object v1, Landroid/graphics/Paint$Style;->STROKE:Landroid/graphics/Paint$Style;

    invoke-virtual {v0, v1}, Landroid/graphics/Paint;->setStyle(Landroid/graphics/Paint$Style;)V

    iget-object v0, p0, Landroid/support/v4/widget/MaterialProgressDrawable$Ring;->mArrowPaint:Landroid/graphics/Paint;

    sget-object v1, Landroid/graphics/Paint$Style;->FILL:Landroid/graphics/Paint$Style;

    invoke-virtual {v0, v1}, Landroid/graphics/Paint;->setStyle(Landroid/graphics/Paint$Style;)V

    iget-object v0, p0, Landroid/support/v4/widget/MaterialProgressDrawable$Ring;->mArrowPaint:Landroid/graphics/Paint;

    invoke-virtual {v0, v2}, Landroid/graphics/Paint;->setAntiAlias(Z)V

    return-void
.end method

.method private drawTriangle(Landroid/graphics/Canvas;FFLandroid/graphics/Rect;)V
    .locals 8

    iget-boolean v3, p0, Landroid/support/v4/widget/MaterialProgressDrawable$Ring;->mShowArrow:Z

    if-eqz v3, :cond_0

    iget-object v3, p0, Landroid/support/v4/widget/MaterialProgressDrawable$Ring;->mArrow:Landroid/graphics/Path;

    if-nez v3, :cond_1

    new-instance v3, Landroid/graphics/Path;

    invoke-direct {v3}, Landroid/graphics/Path;-><init>()V

    iput-object v3, p0, Landroid/support/v4/widget/MaterialProgressDrawable$Ring;->mArrow:Landroid/graphics/Path;

    iget-object v3, p0, Landroid/support/v4/widget/MaterialProgressDrawable$Ring;->mArrow:Landroid/graphics/Path;

    sget-object v4, Landroid/graphics/Path$FillType;->EVEN_ODD:Landroid/graphics/Path$FillType;

    invoke-virtual {v3, v4}, Landroid/graphics/Path;->setFillType(Landroid/graphics/Path$FillType;)V

    :goto_0
    iget v3, p0, Landroid/support/v4/widget/MaterialProgressDrawable$Ring;->mStrokeInset:F

    float-to-int v3, v3

    div-int/lit8 v3, v3, 0x2

    int-to-float v3, v3

    iget v4, p0, Landroid/support/v4/widget/MaterialProgressDrawable$Ring;->mArrowScale:F

    mul-float v0, v3, v4

    iget-wide v4, p0, Landroid/support/v4/widget/MaterialProgressDrawable$Ring;->mRingCenterRadius:D

    const-wide/16 v6, 0x0

    invoke-static {v6, v7}, Ljava/lang/Math;->cos(D)D

    move-result-wide v6

    mul-double/2addr v4, v6

    invoke-virtual {p4}, Landroid/graphics/Rect;->exactCenterX()F

    move-result v3

    float-to-double v6, v3

    add-double/2addr v4, v6

    double-to-float v1, v4

    iget-wide v4, p0, Landroid/support/v4/widget/MaterialProgressDrawable$Ring;->mRingCenterRadius:D

    const-wide/16 v6, 0x0

    invoke-static {v6, v7}, Ljava/lang/Math;->sin(D)D

    move-result-wide v6

    mul-double/2addr v4, v6

    invoke-virtual {p4}, Landroid/graphics/Rect;->exactCenterY()F

    move-result v3

    float-to-double v6, v3

    add-double/2addr v4, v6

    double-to-float v2, v4

    iget-object v3, p0, Landroid/support/v4/widget/MaterialProgressDrawable$Ring;->mArrow:Landroid/graphics/Path;

    const/4 v4, 0x0

    const/4 v5, 0x0

    invoke-virtual {v3, v4, v5}, Landroid/graphics/Path;->moveTo(FF)V

    iget-object v3, p0, Landroid/support/v4/widget/MaterialProgressDrawable$Ring;->mArrow:Landroid/graphics/Path;

    iget v4, p0, Landroid/support/v4/widget/MaterialProgressDrawable$Ring;->mArrowWidth:I

    int-to-float v4, v4

    iget v5, p0, Landroid/support/v4/widget/MaterialProgressDrawable$Ring;->mArrowScale:F

    mul-float/2addr v4, v5

    const/4 v5, 0x0

    invoke-virtual {v3, v4, v5}, Landroid/graphics/Path;->lineTo(FF)V

    iget-object v3, p0, Landroid/support/v4/widget/MaterialProgressDrawable$Ring;->mArrow:Landroid/graphics/Path;

    iget v4, p0, Landroid/support/v4/widget/MaterialProgressDrawable$Ring;->mArrowWidth:I

    int-to-float v4, v4

    iget v5, p0, Landroid/support/v4/widget/MaterialProgressDrawable$Ring;->mArrowScale:F

    mul-float/2addr v4, v5

    const/high16 v5, 0x40000000    # 2.0f

    div-float/2addr v4, v5

    iget v5, p0, Landroid/support/v4/widget/MaterialProgressDrawable$Ring;->mArrowHeight:I

    int-to-float v5, v5

    iget v6, p0, Landroid/support/v4/widget/MaterialProgressDrawable$Ring;->mArrowScale:F

    mul-float/2addr v5, v6

    invoke-virtual {v3, v4, v5}, Landroid/graphics/Path;->lineTo(FF)V

    iget-object v3, p0, Landroid/support/v4/widget/MaterialProgressDrawable$Ring;->mArrow:Landroid/graphics/Path;

    sub-float v4, v1, v0

    invoke-virtual {v3, v4, v2}, Landroid/graphics/Path;->offset(FF)V

    iget-object v3, p0, Landroid/support/v4/widget/MaterialProgressDrawable$Ring;->mArrow:Landroid/graphics/Path;

    invoke-virtual {v3}, Landroid/graphics/Path;->close()V

    iget-object v3, p0, Landroid/support/v4/widget/MaterialProgressDrawable$Ring;->mArrowPaint:Landroid/graphics/Paint;

    iget v4, p0, Landroid/support/v4/widget/MaterialProgressDrawable$Ring;->mCurrentColor:I

    invoke-virtual {v3, v4}, Landroid/graphics/Paint;->setColor(I)V

    add-float v3, p2, p3

    const/high16 v4, 0x40a00000    # 5.0f

    sub-float/2addr v3, v4

    invoke-virtual {p4}, Landroid/graphics/Rect;->exactCenterX()F

    move-result v4

    invoke-virtual {p4}, Landroid/graphics/Rect;->exactCenterY()F

    move-result v5

    invoke-virtual {p1, v3, v4, v5}, Landroid/graphics/Canvas;->rotate(FFF)V

    iget-object v3, p0, Landroid/support/v4/widget/MaterialProgressDrawable$Ring;->mArrow:Landroid/graphics/Path;

    iget-object v4, p0, Landroid/support/v4/widget/MaterialProgressDrawable$Ring;->mArrowPaint:Landroid/graphics/Paint;

    invoke-virtual {p1, v3, v4}, Landroid/graphics/Canvas;->drawPath(Landroid/graphics/Path;Landroid/graphics/Paint;)V

    :cond_0
    return-void

    :cond_1
    iget-object v3, p0, Landroid/support/v4/widget/MaterialProgressDrawable$Ring;->mArrow:Landroid/graphics/Path;

    invoke-virtual {v3}, Landroid/graphics/Path;->reset()V

    goto/16 :goto_0
.end method

.method private getNextColorIndex()I
    .locals 2

    iget v0, p0, Landroid/support/v4/widget/MaterialProgressDrawable$Ring;->mColorIndex:I

    add-int/lit8 v0, v0, 0x1

    iget-object v1, p0, Landroid/support/v4/widget/MaterialProgressDrawable$Ring;->mColors:[I

    array-length v1, v1

    rem-int/2addr v0, v1

    return v0
.end method

.method private invalidateSelf()V
    .locals 2

    iget-object v0, p0, Landroid/support/v4/widget/MaterialProgressDrawable$Ring;->mCallback:Landroid/graphics/drawable/Drawable$Callback;

    const/4 v1, 0x0

    invoke-interface {v0, v1}, Landroid/graphics/drawable/Drawable$Callback;->invalidateDrawable(Landroid/graphics/drawable/Drawable;)V

    return-void
.end method

# virtual methods
.method public draw(Landroid/graphics/Canvas;Landroid/graphics/Rect;)V
    .locals 8

    const/high16 v5, 0x43b40000    # 360.0f

    iget-object v1, p0, Landroid/support/v4/widget/MaterialProgressDrawable$Ring;->mTempBounds:Landroid/graphics/RectF;

    invoke-virtual {v1, p2}, Landroid/graphics/RectF;->set(Landroid/graphics/Rect;)V

    iget v0, p0, Landroid/support/v4/widget/MaterialProgressDrawable$Ring;->mStrokeInset:F

    iget v4, p0, Landroid/support/v4/widget/MaterialProgressDrawable$Ring;->mStrokeInset:F

    invoke-virtual {v1, v0, v4}, Landroid/graphics/RectF;->inset(FF)V

    iget v0, p0, Landroid/support/v4/widget/MaterialProgressDrawable$Ring;->mStartTrim:F

    iget v4, p0, Landroid/support/v4/widget/MaterialProgressDrawable$Ring;->mRotation:F

    add-float/2addr v0, v4

    mul-float v2, v0, v5

    iget v0, p0, Landroid/support/v4/widget/MaterialProgressDrawable$Ring;->mEndTrim:F

    iget v4, p0, Landroid/support/v4/widget/MaterialProgressDrawable$Ring;->mRotation:F

    add-float/2addr v0, v4

    mul-float v6, v0, v5

    sub-float v3, v6, v2

    iget-object v0, p0, Landroid/support/v4/widget/MaterialProgressDrawable$Ring;->mPaint:Landroid/graphics/Paint;

    iget v4, p0, Landroid/support/v4/widget/MaterialProgressDrawable$Ring;->mCurrentColor:I

    invoke-virtual {v0, v4}, Landroid/graphics/Paint;->setColor(I)V

    iget-object v5, p0, Landroid/support/v4/widget/MaterialProgressDrawable$Ring;->mPaint:Landroid/graphics/Paint;

    const/4 v4, 0x0

    move-object v0, p1

    invoke-virtual/range {v0 .. v5}, Landroid/graphics/Canvas;->drawArc(Landroid/graphics/RectF;FFZLandroid/graphics/Paint;)V

    invoke-direct {p0, p1, v2, v3, p2}, Landroid/support/v4/widget/MaterialProgressDrawable$Ring;->drawTriangle(Landroid/graphics/Canvas;FFLandroid/graphics/Rect;)V

    iget v0, p0, Landroid/support/v4/widget/MaterialProgressDrawable$Ring;->mAlpha:I

    const/16 v4, 0xff

    if-ge v0, v4, :cond_0

    iget-object v0, p0, Landroid/support/v4/widget/MaterialProgressDrawable$Ring;->mCirclePaint:Landroid/graphics/Paint;

    iget v4, p0, Landroid/support/v4/widget/MaterialProgressDrawable$Ring;->mBackgroundColor:I

    invoke-virtual {v0, v4}, Landroid/graphics/Paint;->setColor(I)V

    iget-object v0, p0, Landroid/support/v4/widget/MaterialProgressDrawable$Ring;->mCirclePaint:Landroid/graphics/Paint;

    iget v4, p0, Landroid/support/v4/widget/MaterialProgressDrawable$Ring;->mAlpha:I

    rsub-int v4, v4, 0xff

    invoke-virtual {v0, v4}, Landroid/graphics/Paint;->setAlpha(I)V

    invoke-virtual {p2}, Landroid/graphics/Rect;->exactCenterX()F

    move-result v0

    invoke-virtual {p2}, Landroid/graphics/Rect;->exactCenterY()F

    move-result v4

    invoke-virtual {p2}, Landroid/graphics/Rect;->width()I

    move-result v5

    div-int/lit8 v5, v5, 0x2

    int-to-float v5, v5

    iget-object v7, p0, Landroid/support/v4/widget/MaterialProgressDrawable$Ring;->mCirclePaint:Landroid/graphics/Paint;

    invoke-virtual {p1, v0, v4, v5, v7}, Landroid/graphics/Canvas;->drawCircle(FFFLandroid/graphics/Paint;)V

    :cond_0
    return-void
.end method

.method public getAlpha()I
    .locals 1

    iget v0, p0, Landroid/support/v4/widget/MaterialProgressDrawable$Ring;->mAlpha:I

    return v0
.end method

.method public getCenterRadius()D
    .locals 2

    iget-wide v0, p0, Landroid/support/v4/widget/MaterialProgressDrawable$Ring;->mRingCenterRadius:D

    return-wide v0
.end method

.method public getEndTrim()F
    .locals 1

    iget v0, p0, Landroid/support/v4/widget/MaterialProgressDrawable$Ring;->mEndTrim:F

    return v0
.end method

.method public getNextColor()I
    .locals 2

    iget-object v0, p0, Landroid/support/v4/widget/MaterialProgressDrawable$Ring;->mColors:[I

    invoke-direct {p0}, Landroid/support/v4/widget/MaterialProgressDrawable$Ring;->getNextColorIndex()I

    move-result v1

    aget v0, v0, v1

    return v0
.end method

.method public getStartTrim()F
    .locals 1

    iget v0, p0, Landroid/support/v4/widget/MaterialProgressDrawable$Ring;->mStartTrim:F

    return v0
.end method

.method public getStartingColor()I
    .locals 2

    iget-object v0, p0, Landroid/support/v4/widget/MaterialProgressDrawable$Ring;->mColors:[I

    iget v1, p0, Landroid/support/v4/widget/MaterialProgressDrawable$Ring;->mColorIndex:I

    aget v0, v0, v1

    return v0
.end method

.method public getStartingEndTrim()F
    .locals 1

    iget v0, p0, Landroid/support/v4/widget/MaterialProgressDrawable$Ring;->mStartingEndTrim:F

    return v0
.end method

.method public getStartingRotation()F
    .locals 1

    iget v0, p0, Landroid/support/v4/widget/MaterialProgressDrawable$Ring;->mStartingRotation:F

    return v0
.end method

.method public getStartingStartTrim()F
    .locals 1

    iget v0, p0, Landroid/support/v4/widget/MaterialProgressDrawable$Ring;->mStartingStartTrim:F

    return v0
.end method

.method public getStrokeWidth()F
    .locals 1

    iget v0, p0, Landroid/support/v4/widget/MaterialProgressDrawable$Ring;->mStrokeWidth:F

    return v0
.end method

.method public goToNextColor()V
    .locals 1

    invoke-direct {p0}, Landroid/support/v4/widget/MaterialProgressDrawable$Ring;->getNextColorIndex()I

    move-result v0

    invoke-virtual {p0, v0}, Landroid/support/v4/widget/MaterialProgressDrawable$Ring;->setColorIndex(I)V

    return-void
.end method

.method public resetOriginals()V
    .locals 1

    const/4 v0, 0x0

    iput v0, p0, Landroid/support/v4/widget/MaterialProgressDrawable$Ring;->mStartingStartTrim:F

    iput v0, p0, Landroid/support/v4/widget/MaterialProgressDrawable$Ring;->mStartingEndTrim:F

    iput v0, p0, Landroid/support/v4/widget/MaterialProgressDrawable$Ring;->mStartingRotation:F

    invoke-virtual {p0, v0}, Landroid/support/v4/widget/MaterialProgressDrawable$Ring;->setStartTrim(F)V

    invoke-virtual {p0, v0}, Landroid/support/v4/widget/MaterialProgressDrawable$Ring;->setEndTrim(F)V

    invoke-virtual {p0, v0}, Landroid/support/v4/widget/MaterialProgressDrawable$Ring;->setRotation(F)V

    return-void
.end method

.method public setAlpha(I)V
    .locals 0

    iput p1, p0, Landroid/support/v4/widget/MaterialProgressDrawable$Ring;->mAlpha:I

    return-void
.end method

.method public setArrowDimensions(FF)V
    .locals 1

    float-to-int v0, p1

    iput v0, p0, Landroid/support/v4/widget/MaterialProgressDrawable$Ring;->mArrowWidth:I

    float-to-int v0, p2

    iput v0, p0, Landroid/support/v4/widget/MaterialProgressDrawable$Ring;->mArrowHeight:I

    return-void
.end method

.method public setArrowScale(F)V
    .locals 1

    iget v0, p0, Landroid/support/v4/widget/MaterialProgressDrawable$Ring;->mArrowScale:F

    cmpl-float v0, p1, v0

    if-eqz v0, :cond_0

    iput p1, p0, Landroid/support/v4/widget/MaterialProgressDrawable$Ring;->mArrowScale:F

    invoke-direct {p0}, Landroid/support/v4/widget/MaterialProgressDrawable$Ring;->invalidateSelf()V

    :cond_0
    return-void
.end method

.method public setBackgroundColor(I)V
    .locals 0

    iput p1, p0, Landroid/support/v4/widget/MaterialProgressDrawable$Ring;->mBackgroundColor:I

    return-void
.end method

.method public setCenterRadius(D)V
    .locals 1

    iput-wide p1, p0, Landroid/support/v4/widget/MaterialProgressDrawable$Ring;->mRingCenterRadius:D

    return-void
.end method

.method public setColor(I)V
    .locals 0

    iput p1, p0, Landroid/support/v4/widget/MaterialProgressDrawable$Ring;->mCurrentColor:I

    return-void
.end method

.method public setColorFilter(Landroid/graphics/ColorFilter;)V
    .locals 1

    iget-object v0, p0, Landroid/support/v4/widget/MaterialProgressDrawable$Ring;->mPaint:Landroid/graphics/Paint;

    invoke-virtual {v0, p1}, Landroid/graphics/Paint;->setColorFilter(Landroid/graphics/ColorFilter;)Landroid/graphics/ColorFilter;

    invoke-direct {p0}, Landroid/support/v4/widget/MaterialProgressDrawable$Ring;->invalidateSelf()V

    return-void
.end method

.method public setColorIndex(I)V
    .locals 2

    iput p1, p0, Landroid/support/v4/widget/MaterialProgressDrawable$Ring;->mColorIndex:I

    iget-object v0, p0, Landroid/support/v4/widget/MaterialProgressDrawable$Ring;->mColors:[I

    iget v1, p0, Landroid/support/v4/widget/MaterialProgressDrawable$Ring;->mColorIndex:I

    aget v0, v0, v1

    iput v0, p0, Landroid/support/v4/widget/MaterialProgressDrawable$Ring;->mCurrentColor:I

    return-void
.end method

.method public setColors([I)V
    .locals 1
    .param p1    # [I
        .annotation build Landroid/support/annotation/NonNull;
        .end annotation
    .end param

    iput-object p1, p0, Landroid/support/v4/widget/MaterialProgressDrawable$Ring;->mColors:[I

    const/4 v0, 0x0

    invoke-virtual {p0, v0}, Landroid/support/v4/widget/MaterialProgressDrawable$Ring;->setColorIndex(I)V

    return-void
.end method

.method public setEndTrim(F)V
    .locals 0

    iput p1, p0, Landroid/support/v4/widget/MaterialProgressDrawable$Ring;->mEndTrim:F

    invoke-direct {p0}, Landroid/support/v4/widget/MaterialProgressDrawable$Ring;->invalidateSelf()V

    return-void
.end method

.method public setInsets(II)V
    .locals 7

    const/high16 v6, 0x40000000    # 2.0f

    invoke-static {p1, p2}, Ljava/lang/Math;->min(II)I

    move-result v2

    int-to-float v1, v2

    iget-wide v2, p0, Landroid/support/v4/widget/MaterialProgressDrawable$Ring;->mRingCenterRadius:D

    const-wide/16 v4, 0x0

    cmpg-double v2, v2, v4

    if-lez v2, :cond_0

    const/4 v2, 0x0

    cmpg-float v2, v1, v2

    if-gez v2, :cond_1

    :cond_0
    iget v2, p0, Landroid/support/v4/widget/MaterialProgressDrawable$Ring;->mStrokeWidth:F

    div-float/2addr v2, v6

    float-to-double v2, v2

    invoke-static {v2, v3}, Ljava/lang/Math;->ceil(D)D

    move-result-wide v2

    double-to-float v0, v2

    :goto_0
    iput v0, p0, Landroid/support/v4/widget/MaterialProgressDrawable$Ring;->mStrokeInset:F

    return-void

    :cond_1
    div-float v2, v1, v6

    float-to-double v2, v2

    iget-wide v4, p0, Landroid/support/v4/widget/MaterialProgressDrawable$Ring;->mRingCenterRadius:D

    sub-double/2addr v2, v4

    double-to-float v0, v2

    goto :goto_0
.end method

.method public setRotation(F)V
    .locals 0

    iput p1, p0, Landroid/support/v4/widget/MaterialProgressDrawable$Ring;->mRotation:F

    invoke-direct {p0}, Landroid/support/v4/widget/MaterialProgressDrawable$Ring;->invalidateSelf()V

    return-void
.end method

.method public setShowArrow(Z)V
    .locals 1

    iget-boolean v0, p0, Landroid/support/v4/widget/MaterialProgressDrawable$Ring;->mShowArrow:Z

    if-eq v0, p1, :cond_0

    iput-boolean p1, p0, Landroid/support/v4/widget/MaterialProgressDrawable$Ring;->mShowArrow:Z

    invoke-direct {p0}, Landroid/support/v4/widget/MaterialProgressDrawable$Ring;->invalidateSelf()V

    :cond_0
    return-void
.end method

.method public setStartTrim(F)V
    .locals 0

    iput p1, p0, Landroid/support/v4/widget/MaterialProgressDrawable$Ring;->mStartTrim:F

    invoke-direct {p0}, Landroid/support/v4/widget/MaterialProgressDrawable$Ring;->invalidateSelf()V

    return-void
.end method

.method public setStrokeWidth(F)V
    .locals 1

    iput p1, p0, Landroid/support/v4/widget/MaterialProgressDrawable$Ring;->mStrokeWidth:F

    iget-object v0, p0, Landroid/support/v4/widget/MaterialProgressDrawable$Ring;->mPaint:Landroid/graphics/Paint;

    invoke-virtual {v0, p1}, Landroid/graphics/Paint;->setStrokeWidth(F)V

    invoke-direct {p0}, Landroid/support/v4/widget/MaterialProgressDrawable$Ring;->invalidateSelf()V

    return-void
.end method

.method public storeOriginals()V
    .locals 1

    iget v0, p0, Landroid/support/v4/widget/MaterialProgressDrawable$Ring;->mStartTrim:F

    iput v0, p0, Landroid/support/v4/widget/MaterialProgressDrawable$Ring;->mStartingStartTrim:F

    iget v0, p0, Landroid/support/v4/widget/MaterialProgressDrawable$Ring;->mEndTrim:F

    iput v0, p0, Landroid/support/v4/widget/MaterialProgressDrawable$Ring;->mStartingEndTrim:F

    iget v0, p0, Landroid/support/v4/widget/MaterialProgressDrawable$Ring;->mRotation:F

    iput v0, p0, Landroid/support/v4/widget/MaterialProgressDrawable$Ring;->mStartingRotation:F

    return-void
.end method


text:
package de.csw.ontomaven.util;

import org.codehaus.plexus.classworlds.realm.ClassRealm;
import org.codehaus.plexus.component.configurator.AbstractComponentConfigurator;
import org.codehaus.plexus.component.configurator.ComponentConfigurationException;
import org.codehaus.plexus.component.configurator.ConfigurationListener;
import org.codehaus.plexus.component.configurator.converters.composite.ObjectWithFieldsConverter;
import org.codehaus.plexus.component.configurator.converters.special.ClassRealmConverter;
import org.codehaus.plexus.component.configurator.expression.ExpressionEvaluationException;
import org.codehaus.plexus.component.configurator.expression.ExpressionEvaluator;
import org.codehaus.plexus.configuration.PlexusConfiguration;

import java.io.File;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;

/**
 * Based on the stackoverflow thread:
 * http://stackoverflow.com/questions/2659048/add-maven-build-classpath-to-plugin-execution-classpath
 *
 * and the Nabble thread:
 * http://old.nabble.com/Adding-project-dependencies-and-generated-classes-to-classpath-of-my-plugin-td18624435.html
 *
 *
 * A custom ComponentConfigurator which adds the project's runtime classpath elements
 * to the
 *
 * @author Brian Jackson
 * @since Aug 1, 2008 3:04:17 PM
 *
 * @plexus.component role="org.codehaus.plexus.component.configurator.ComponentConfigurator"
 *                   role-hint="include-project-dependencies"
 * @plexus.requirement role="org.codehaus.plexus.component.configurator.converters.lookup.ConverterLookup"
 *                   role-hint="default"
 */
public class IncludeProjectDependenciesComponentConfigurator extends AbstractComponentConfigurator {

	public void configureComponent(Object component, PlexusConfiguration configuration,
	                               ExpressionEvaluator expressionEvaluator, ClassRealm containerRealm,
	                               ConfigurationListener listener )
			throws ComponentConfigurationException {

		addProjectDependenciesToClassRealm(expressionEvaluator, containerRealm);

		converterLookup.registerConverter( new ClassRealmConverter( containerRealm ) );

		ObjectWithFieldsConverter converter = new ObjectWithFieldsConverter();

		converter.processConfiguration( converterLookup, component, containerRealm, configuration,
				expressionEvaluator, listener );
	}

	private void addProjectDependenciesToClassRealm(ExpressionEvaluator expressionEvaluator, ClassRealm containerRealm) throws ComponentConfigurationException {
		List<String> runtimeClasspathElements;
		try {
			//noinspection unchecked
			runtimeClasspathElements = (List<String>) expressionEvaluator.evaluate("${project.runtimeClasspathElements}");
		} catch (ExpressionEvaluationException e) {
			throw new ComponentConfigurationException("There was a problem evaluating: ${project.runtimeClasspathElements}", e);
		}

		// Add the project dependencies to the ClassRealm
		final URL[] urls = buildURLs(runtimeClasspathElements);
		for (URL url : urls) {
			containerRealm.addURL(url);
		}
	}

	private URL[] buildURLs(List<String> runtimeClasspathElements) throws ComponentConfigurationException {
		// Add the projects classes and dependencies
		List<URL> urls = new ArrayList<URL>(runtimeClasspathElements.size());
		for (String element : runtimeClasspathElements) {
			try {
				final URL url = new File(element).toURI().toURL();
				urls.add(url);
			} catch (MalformedURLException e) {
				throw new ComponentConfigurationException("Unable to access project dependency: " + element, e);
			}
		}

		// Add the plugin's dependencies (so Trove stuff works if Trove isn't on
		return urls.toArray(new URL[urls.size()]);
	}

}

redpajama_set_name: RedPajamaGithub


text:
package main

import (
	"fmt"
	"net/http"
	"strings"
	"time"

	"github.com/rs/cors"
	"gopkg.in/h2non/bimg.v1"
	"gopkg.in/throttled/throttled.v2"
	"gopkg.in/throttled/throttled.v2/store/memstore"
)

func Middleware(fn func(http.ResponseWriter, *http.Request), o ServerOptions) http.Handler {
	next := http.Handler(http.HandlerFunc(fn))

	if len(o.Endpoints) > 0 {
		next = filterEndpoint(next, o)
	}
	if o.Concurrency > 0 {
		next = throttle(next, o)
	}
	if o.CORS {
		next = cors.Default().Handler(next)
	}
	if o.APIKey != "" {
		next = authorizeClient(next, o)
	}
	if o.HTTPCacheTTL >= 0 {
		next = setCacheHeaders(next, o.HTTPCacheTTL)
	}

	return validate(defaultHeaders(next), o)
}

func ImageMiddleware(o ServerOptions) func(Operation) http.Handler {
	return func(fn Operation) http.Handler {
		return validateImage(Middleware(imageController(o, Operation(fn)), o), o)
	}
}

func filterEndpoint(next http.Handler, o ServerOptions) http.Handler {
	return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		if o.Endpoints.IsValid(r) {
			next.ServeHTTP(w, r)
			return
		}
		ErrorReply(r, w, ErrNotImplemented, o)
	})
}

func throttleError(err error) http.Handler {
	return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		http.Error(w, "throttle error: "+err.Error(), http.StatusInternalServerError)
	})
}

func throttle(next http.Handler, o ServerOptions) http.Handler {
	store, err := memstore.New(65536)
	if err != nil {
		return throttleError(err)
	}

	quota := throttled.RateQuota{throttled.PerSec(o.Concurrency), o.Burst}
	rateLimiter, err := throttled.NewGCRARateLimiter(store, quota)
	if err != nil {
		return throttleError(err)
	}

	httpRateLimiter := throttled.HTTPRateLimiter{
		RateLimiter: rateLimiter,
		VaryBy:      &throttled.VaryBy{Method: true},
	}

	return httpRateLimiter.RateLimit(next)
}

func validate(next http.Handler, o ServerOptions) http.Handler {
	return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		if r.Method != "GET" && r.Method != "POST" {
			ErrorReply(r, w, ErrMethodNotAllowed, o)
			return
		}

		next.ServeHTTP(w, r)
	})
}

func validateImage(next http.Handler, o ServerOptions) http.Handler {
	return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		path := r.URL.Path
		if r.Method == "GET" && isPublicPath(path) {
			next.ServeHTTP(w, r)
			return
		}

		if r.Method == "GET" && o.Mount == "" && o.EnableURLSource == false {
			ErrorReply(r, w, ErrMethodNotAllowed, o)
			return
		}

		next.ServeHTTP(w, r)
	})
}

func authorizeClient(next http.Handler, o ServerOptions) http.Handler {
	return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		key := r.Header.Get("API-Key")
		if key == "" {
			key = r.URL.Query().Get("key")
		}

		if key != o.APIKey {
			ErrorReply(r, w, ErrInvalidApiKey, o)
			return
		}

		next.ServeHTTP(w, r)
	})
}

func defaultHeaders(next http.Handler) http.Handler {
	return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		w.Header().Set("Server", fmt.Sprintf("imaginary %s (bimg %s)", Version, bimg.Version))
		next.ServeHTTP(w, r)
	})
}

func setCacheHeaders(next http.Handler, ttl int) http.Handler {
	return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		defer next.ServeHTTP(w, r)

		if r.Method != "GET" || isPublicPath(r.URL.Path) {
			return
		}

		ttlDiff := time.Duration(ttl) * time.Second
		expires := time.Now().Add(ttlDiff)

		w.Header().Add("Expires", strings.Replace(expires.Format(time.RFC1123), "UTC", "GMT", -1))
		w.Header().Add("Cache-Control", getCacheControl(ttl))
	})
}

func getCacheControl(ttl int) string {
	if ttl == 0 {
		return "private, no-cache, no-store, must-revalidate"
	}
	return fmt.Sprintf("public, s-maxage=%d, max-age=%d, no-transform", ttl, ttl)
}

func isPublicPath(path string) bool {
	return path == "/" || path == "/health" || path == "/form"
}


text:
class Card

 attr_accessor :question, :answer

 def initialize(question, answer)
   @question = question
   @answer = answer
 end

end


text:
package cubicchunks.world.cube;

import com.google.common.base.Predicate;
import cubicchunks.generator.GeneratorStage;
import cubicchunks.world.column.Column;
import cubicchunks.world.cube.Cube;
import java.util.List;
import net.minecraft.block.Block;
import net.minecraft.block.Blocks;
import net.minecraft.block.entity.BlockEntity;
import net.minecraft.block.state.IBlockState;
import net.minecraft.entity.Entity;
import net.minecraft.util.AxisAlignedBB;
import net.minecraft.util.BlockPos;
import net.minecraft.world.LightType;
import net.minecraft.world.World;
import net.minecraft.world.chunk.Chunk;
import net.minecraft.world.chunk.storage.ChunkSection;

/**
 * Cube implementation used clientside used when cube is not loaded.
 * It does nothing. Contains only Blocks.AIR.
 */
public class BlankCube extends Cube {

	public BlankCube(World world, Column column) {
		super(world, column, 0, 0, 0, false);
	}

	@Override
	public boolean isEmpty() {
		return true;
	}

	@Override
	public void setEmpty(boolean isEmpty) {}

	@Override
	public GeneratorStage getGeneratorStage() {
		//if client has it - it must be LIVE
		return GeneratorStage.LIVE;
	}

	@Override
	public void setGeneratorStage(GeneratorStage val) {}

	@Override
	public long getAddress() {
		return 0;
	}

	@Override
	public boolean containsBlockPos(BlockPos blockPos) {
		return false;
	}

	@Override
	public ChunkSection getStorage() {
		return null;
	}

	@Override
	public Block getBlockAt(final BlockPos pos) {
		return Blocks.AIR;
	}

	@Override
	public Block getBlockAt(final int localX, final int localY, final int localZ) {
		return Blocks.AIR;
	}

	@Override
	public IBlockState getBlockState(BlockPos pos) {
		return Blocks.AIR.getDefaultState();
	}

	@Override
	public IBlockState getBlockState(int localX, int localY, int localZ) {
		return Blocks.AIR.getDefaultState();
	}

	@Override
	public IBlockState setBlockState(BlockPos pos, IBlockState newBlockState) {
		return Blocks.AIR.getDefaultState();
	}

	@Override
	public IBlockState setBlockForGeneration(BlockPos pos, IBlockState newBlockState) {
		throw new UnsupportedOperationException("Eighter someone used BlankCube on server or someone generates terrain on client.");
	}

	@Override
	public boolean hasBlocks() {
		return false;
	}

	@Override
	public void addEntity(Entity entity) {}

	@Override
	public boolean removeEntity(Entity entity) {
		return false;
	}

	@Override
	public void findEntitiesExcept(Entity excludedEntity, AxisAlignedBB queryBox, List<Entity> out, Predicate<? super Entity> predicate) {}

	@Override
	public <T extends Entity> void findEntities(Class<? extends T> entityType, AxisAlignedBB queryBox, List<T> out, Predicate<? super T> predicate) {}

	@Override
	public void getMigratedEntities(List<Entity> out) {}

	@Override
	public BlockEntity getBlockEntity(BlockPos pos, Chunk.ChunkEntityCreationType creationType) {
		return null;
	}

	@Override
	public void addBlockEntity(BlockPos pos, BlockEntity blockEntity) {}

	@Override
	public void removeBlockEntity(BlockPos pos) {}

	@Override
	public void onLoad() {}

	@Override
	public void onUnload() {}

	@Override
	public boolean needsSaving() {
		return false;
	}

	@Override
	public void markSaved() {
	}

	@Override
	public boolean isUnderground(BlockPos pos) {
		return false;
	}

	@Override
	public int getBrightestLight(BlockPos pos, int skyLightDampeningTerm) {
		//TODO: BlankCube.getBrightnessLight - is it correct?
		return 15 - skyLightDampeningTerm;
	}

	@Override
	public int getLightValue(LightType lightType, BlockPos pos) {
		//TODO: BlankCube.getLightValue - maybe return 0?
		return 15;
	}

	@Override
	public void setLightValue(LightType lightType, BlockPos pos, int light) {}

	@Override
	public void doRandomTicks() {}

	@Override
	public void markForRenderUpdate() {}
}


text:
package alluxio.master;

import alluxio.Constants;
import alluxio.ProcessUtils;
import alluxio.conf.PropertyKey;
import alluxio.conf.ServerConfiguration;
import alluxio.master.PrimarySelector.State;
import alluxio.master.journal.JournalSystem;
import alluxio.metrics.MetricKey;
import alluxio.metrics.MetricsSystem;
import alluxio.util.CommonUtils;
import alluxio.util.ThreadUtils;
import alluxio.util.WaitForOptions;
import alluxio.util.interfaces.Scoped;

import com.codahale.metrics.Timer;
import com.google.common.base.Preconditions;
import com.google.common.base.Throwables;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;
import java.util.concurrent.TimeoutException;
import java.util.concurrent.atomic.AtomicBoolean;

import javax.annotation.concurrent.NotThreadSafe;

/**
 * The fault tolerant version of {@link AlluxioMaster} that uses zookeeper and standby masters.
 */
@NotThreadSafe
final class FaultTolerantAlluxioMasterProcess extends AlluxioMasterProcess {
  private static final Logger LOG =
      LoggerFactory.getLogger(FaultTolerantAlluxioMasterProcess.class);

  private final long mServingThreadTimeoutMs =
      ServerConfiguration.getMs(PropertyKey.MASTER_SERVING_THREAD_TIMEOUT);

  private PrimarySelector mLeaderSelector;
  private Thread mServingThread;

  /** An indicator for whether the process is running (after start() and before stop()). */
  private volatile boolean mRunning;

  /**
   * Creates a {@link FaultTolerantAlluxioMasterProcess}.
   */
  protected FaultTolerantAlluxioMasterProcess(JournalSystem journalSystem,
      PrimarySelector leaderSelector) {
    super(journalSystem);
    try {
      stopServing();
    } catch (Exception e) {
      throw new RuntimeException(e);
    }
    mLeaderSelector = Preconditions.checkNotNull(leaderSelector, "leaderSelector");
    mServingThread = null;
    mRunning = false;
  }

  @Override
  public void start() throws Exception {
    mRunning = true;
    mJournalSystem.start();
    try {
      mLeaderSelector.start(getRpcAddress());
    } catch (IOException e) {
      LOG.error(e.getMessage(), e);
      throw new RuntimeException(e);
    }

    startMasters(false);
    LOG.info("Secondary started");
    while (!Thread.interrupted()) {
      mLeaderSelector.waitForState(State.PRIMARY);
      if (!mRunning) {
        break;
      }
      if (gainPrimacy()) {
        mLeaderSelector.waitForState(State.SECONDARY);
        if (!mRunning) {
          break;
        }
        losePrimacy();
      }
    }
  }

  /**
   * Upgrades the master to primary mode.
   *
   * If the master loses primacy during the journal upgrade, this method will clean up the partial
   * upgrade, leaving the master in secondary mode.
   *
   * @return whether the master successfully upgraded to primary
   */
  private boolean gainPrimacy() throws Exception {
    // Don't upgrade if this master's primacy is unstable.
    AtomicBoolean unstable = new AtomicBoolean(false);
    try (Scoped scoped = mLeaderSelector.onStateChange(state -> unstable.set(true))) {
      if (mLeaderSelector.getState() != State.PRIMARY) {
        unstable.set(true);
      }
      stopMasters();
      LOG.info("Secondary stopped");
      try (Timer.Context ctx = MetricsSystem
          .timer(MetricKey.MASTER_JOURNAL_GAIN_PRIMACY_TIMER.getName()).time()) {
        mJournalSystem.gainPrimacy();
      }
      // We only check unstable here because mJournalSystem.gainPrimacy() is the only slow method
      if (unstable.get()) {
        losePrimacy();
        return false;
      }
    }
    startMasters(true);
    mServingThread = new Thread(() -> {
      try {
        startServing(" (gained leadership)", " (lost leadership)");
      } catch (Throwable t) {
        Throwable root = Throwables.getRootCause(t);
        if ((root != null && (root instanceof InterruptedException)) || Thread.interrupted()) {
          return;
        }
        ProcessUtils.fatalError(LOG, t, "Exception thrown in main serving thread");
      }
    }, "MasterServingThread");
    mServingThread.start();
    if (!waitForReady(10 * Constants.MINUTE_MS)) {
      ThreadUtils.logAllThreads();
      throw new RuntimeException("Alluxio master failed to come up");
    }
    LOG.info("Primary started");
    return true;
  }

  private void losePrimacy() throws Exception {
    if (mServingThread != null) {
      stopServing();
    }
    // Put the journal in secondary mode ASAP to avoid interfering with the new primary. This must
    // happen after stopServing because downgrading the journal system will reset master state,
    // which could cause NPEs for outstanding RPC threads. We need to first close all client
    // sockets in stopServing so that clients don't see NPEs.
    mJournalSystem.losePrimacy();
    if (mServingThread != null) {
      mServingThread.join(mServingThreadTimeoutMs);
      if (mServingThread.isAlive()) {
        ProcessUtils.fatalError(LOG,
            "Failed to stop serving thread after %dms. Serving thread stack trace:%n%s",
            mServingThreadTimeoutMs, ThreadUtils.formatStackTrace(mServingThread));
      }
      mServingThread = null;
      stopMasters();
      LOG.info("Primary stopped");
    }
    startMasters(false);
    LOG.info("Secondary started");
  }

  @Override
  public void stop() throws Exception {
    mRunning = false;
    super.stop();
    if (mLeaderSelector != null) {
      mLeaderSelector.stop();
    }
  }

  @Override
  public boolean waitForReady(int timeoutMs) {
    try {
      CommonUtils.waitFor(this + " to start", () -> (mServingThread == null || isServing()),
          WaitForOptions.defaults().setTimeoutMs(timeoutMs));
      return true;
    } catch (InterruptedException e) {
      Thread.currentThread().interrupt();
      return false;
    } catch (TimeoutException e) {
      return false;
    }
  }
}


text:
import-call-extractor is a program to analyze go programs. It extracts calls made to imported packages. It can work either on a single go source file or a go package. On a go package, it will also recursively analyze the imported packages.

## Install

    go get github.com/freenerd/import-call-extractor

## Use

For basic usage give the absolute go source file path as first argument. In this example, we analyze the code of this package:

    import-call-extractor $GOPATH/src/github.com/freenerd/import-call-extractor/main.go

The output goes to STDOUT and is formated as yaml. It looks like this:

```yaml
flag:
  Parse:
    - /Users/johan/Code/go/src/github.com/freenerd/import-call-extractor/main.go:87:3
  Args:
    - /Users/johan/Code/go/src/github.com/freenerd/import-call-extractor/main.go:88:10
fmt:
  Printf:
    - /Users/johan/Code/go/src/github.com/freenerd/import-call-extractor/main.go:108:3
    - /Users/johan/Code/go/src/github.com/freenerd/import-call-extractor/main.go:111:4
    - /Users/johan/Code/go/src/github.com/freenerd/import-call-extractor/main.go:114:5
```

To analyze a whole package, call like this:

    import-call-extractor -p github.com/freenerd/import-call-extractor

Output can be filtered by specific suspect package calls (TODO: make customizable)

    import-call-extractor -p github.com/freenerd/import-call-extractor -s

## Limitations

- It is assumed that all calls are made on the object with the package name string split after last "/". This is a casual convention and not how go imports are actually implemented. Therefore anything exported publicly by a package, that is not within the packages name, will not be detected.
  - This will be detected: `import "flag"; ...; flag.Parse()`
  - This will not be detected: `import "flag"; ...; flags := NewFlagSet(...)`
- In package mode, if a package is imported several times, it will be analyzed each time, resulting in duplicate call occurences
- Calls made in a `var` block will not be detected
- Overriding objects will not be respected
  - `import "fmt"; ...; fmt := "anything";`

## Todo

- How are package renames handled?
- Handle all publicl exports by a package
- Regarding finding network connections: Also within the stdlib, try to traceback network connections to `net.Dial`


text:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE sqlMapConfig PUBLIC "-//iBATIS.com//DTD SQL Map Config 2.0//EN"
    "http://www.ibatis.com/dtd/sql-map-config-2.dtd">

<sqlMapConfig>

    <sqlMap resource="egovframework/sqlmap/com/sec/ram/EgovAuthorManage_SQL_Sqlite.xml"/>

</sqlMapConfig>


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using WebSpider.Data.DatabaseManager;
using WebSpider.Objects.General;

namespace WebSpider.Data.General
{
    public class FinalExportManager : DataManager
    {
        #region [ Constructor ]
        public FinalExportManager(String ConnectionString)
        {
            this.ConnectionString = ConnectionString;
        }
        #endregion

        #region [ Get Data ]
        public List<FinalExport> GetData()
        {
            String Query = "SELECT * FROM FinalExport ORDER BY CreatedDate";
            SqlCeDataManager oDm = new SqlCeDataManager(ConnectionString, Query, true);
            return DataParser.ToList<FinalExport>(oDm.GetTable());
        }

        public FinalExport GetTop()
        {
            String Query = "SELECT TOP 1 * FROM FinalExport ORDER BY CreatedDate";
            SqlCeDataManager oDm = new SqlCeDataManager(ConnectionString, Query, true);
            List<FinalExport> finalExports = DataParser.ToList<FinalExport>(oDm.GetTable());
            return finalExports.Count == 0 ? null : finalExports[0];
        }

        public FinalExport GetTopBySite(String ExportSite)
        {
            String Query = "SELECT TOP 1 * FROM FinalExport WHERE ExportSite = @ExportSite ORDER BY CreatedDate";
            SqlCeDataManager oDm = new SqlCeDataManager(ConnectionString, Query, true);
            oDm.AddVarcharPara("ExportSite", 4000, ExportSite);
            List<FinalExport> finalExports = DataParser.ToList<FinalExport>(oDm.GetTable());
            return finalExports.Count == 0 ? null : finalExports[0];
        }

        public List<FinalExport> GetBySite(String ExportSite)
        {
            String Query = "SELECT * FROM FinalExport WHERE ExportSite = @ExportSite ORDER BY CreatedDate";
            SqlCeDataManager oDm = new SqlCeDataManager(ConnectionString, Query, true);
            oDm.AddVarcharPara("ExportSite", 4000, ExportSite);
            return DataParser.ToList<FinalExport>(oDm.GetTable());
        }
        #endregion

        #region [Insert]
        public void Insert(FinalExport fe)
        {
            Insert(fe.ExportSite, fe.ExportType, fe.ExportValue);
        }

        public int Insert(String ExportSite, String ExportType, String ExportValue)
        {
            String Query = "INSERT INTO FinalExport (ExportSite, ExportType, ExportValue, CreatedDate) "
                + "VALUES (@ExportSite, @ExportType, @ExportValue, @CreatedDate)";
            SqlCeDataManager oDm = new SqlCeDataManager(ConnectionString, Query, true);
            oDm.AddVarcharPara("ExportSite", 4000, ExportSite);
            oDm.AddVarcharPara("ExportType", 4000, ExportType);
            oDm.AddVarcharPara("ExportValue", 4000, ExportValue);
            oDm.AddDateTimePara("CreatedDate", DateTime.Now);
            return oDm.RunActionQuery();
        }
        #endregion

        #region [Delete]
        public int Delete(String ExportSite, String ExportType, String ExportValue, DateTime CreatedDate)
        {
            String Query = "DELETE FROM FinalExport WHERE "
                + "ExportSite = @ExportSite AND ExportType = @ExportType AND ExportValue = @ExportValue AND CreatedDate = @CreatedDate";
            SqlCeDataManager oDm = new SqlCeDataManager(ConnectionString, Query, true);
            oDm.AddVarcharPara("ExportSite", 4000, ExportSite);
            oDm.AddVarcharPara("ExportType", 4000, ExportType);
            oDm.AddVarcharPara("ExportValue", 4000, ExportValue);
            oDm.AddDateTimePara("CreatedDate", CreatedDate);
            return oDm.RunActionQuery();
        }
        #endregion

    }
}


text:
<!DOCTYPE html>
<html>

<head>
  <meta charset="utf-8">
  <style>
  .box{
    background-color: blue;
    position: absolute;
  }
  body{
    margin: 0;
    padding: 0;
  }
  </style>
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.4/jquery.min.js"></script>
  <script type="text/javascript">
    $(document).ready(function() {
      var box_size = 1;
      screen_height = screen.height;
			screen_width = screen.width;
      $('canvas').attr('height', screen_height);
			$('canvas').attr('width', screen_width);
      var rows = Math.floor(screen.height/box_size);
      var columns = Math.floor(screen.width/box_size);
      var boxes = [];
      var canvas = document.getElementById("canvas");
      var ctx = canvas.getContext("2d");
      ctx.fillStyle = color;
      var color = "black";
      for (row = 0; row < rows; row++) {
        boxes[row] = [];
        for (column = 0; column < columns; column++) {
          boxes[row][column] = box_size;
          ctx.fillRect(column*box_size, row*box_size, box_size, box_size);
          ctx.fillStyle = '#' + Math.floor((row*column) / (rows*columns) * 16777215).toString(16);
        }
      }
    });
  </script>
</head>

<body>
  <canvas id="canvas" width="0" height="0"></canvas>
</body>

</html>


text:
//******************************************************************************************************
//  SystemSection.cs - Gbtc
//
//  Copyright © 2014, Grid Protection Alliance.  All Rights Reserved.
//
//  Licensed to the Grid Protection Alliance (GPA) under one or more contributor license agreements. See
//  the NOTICE file distributed with this work for additional information regarding copyright ownership.
//  The GPA licenses this file to you under the Eclipse Public License -v 1.0 (the "License"); you may
//  not use this file except in compliance with the License. You may obtain a copy of the License at:
//
//      http://www.opensource.org/licenses/eclipse-1.0.php
//
//  Unless agreed to in writing, the subject software distributed under the License is distributed on an
//  "AS-IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. Refer to the
//  License for the specific language governing permissions and limitations.
//
//  Code Modification History:
//  ----------------------------------------------------------------------------------------------------
//  09/30/2014 - Stephen C. Wills
//       Generated original version of source code.
//
//******************************************************************************************************

using System;
using System.ComponentModel;
using System.Configuration;

namespace openXDA.Configuration
{
    /// <summary>
    /// Represents the system settings for openXDA.
    /// </summary>
    public class SystemSection
    {
        public const string CategoryName = "System";

        /// <summary>
        /// Gets or sets the time zone identifier for the time zone
        /// used by meters in the system unless configured otherwise.
        /// </summary>
        [Setting]
        [DefaultValue("UTC")]
        public string DefaultMeterTimeZone
        {
            get => DefaultMeterTimeZoneInfo.Id;
            set => DefaultMeterTimeZoneInfo = string.IsNullOrEmpty(value)
                ? TimeZoneInfo.Local
                : TimeZoneInfo.FindSystemTimeZoneById(value);
        }

        /// <summary>
        /// Gets the <see cref="TimeZoneInfo"/> used by meters
        /// in the system unless configured otherwise.
        /// </summary>
        public TimeZoneInfo DefaultMeterTimeZoneInfo { get; private set; }

        /// <summary>
        /// Gets or sets the amount of time each database
        /// query is given to complete, in seconds.
        /// </summary>
        [Setting]
        [DefaultValue(120)]
        public int DbTimeout { get; set; }

        /// <summary>
        /// Gets or sets the time zone identifier for the
        /// time zone used by openXDA to store data.
        /// </summary>
        /// <remarks>
        /// The default value for this setting (empty string)
        /// causes the setting to assume the value of the local
        /// time zone of the system openXDA is running on.
        /// </remarks>
        [Setting]
        [DefaultValue("UTC")]
        public string XDATimeZone
        {
            get
            {
                return _XDATimeZone;
            }
            set
            {
                if (string.IsNullOrEmpty(value))
                    _XDATimeZone = TimeZoneInfo.Local.Id;
                else
                    _XDATimeZone = value;
            }
        }

        /// <summary>
        /// Gets the <see cref="TimeZoneInfo"/> for the
        /// time zone used by openXDA to store data.
        /// </summary>
        public TimeZoneInfo XDATimeZoneInfo
        {
            get
            {
                if ((object)_XDATimeZoneInfo == null)
                    _XDATimeZoneInfo = TimeZoneInfo.FindSystemTimeZoneById(_XDATimeZone);

                return _XDATimeZoneInfo;
            }
        }

        private string _XDATimeZone { get; set; }
        private TimeZoneInfo _XDATimeZoneInfo { get; set; }
    }
}


text:
package org.basex.query.func.fn;

import org.basex.core.locks.*;
import org.basex.query.*;
import org.basex.query.func.*;
import org.basex.query.util.*;
import org.basex.query.value.item.*;
import org.basex.query.value.node.*;
import org.basex.util.*;

/**
 * Function implementation.
 *
 * @author BaseX Team 2005-15, BSD License
 * @author Christian Gruen
 */
public final class FnGenerateId extends StandardFunc {
  @Override
  public Item item(final QueryContext qc, final InputInfo ii) throws QueryException {
    final ANode node = toEmptyNode(ctxArg(0, qc), qc);
    return node == null ? Str.ZERO :
      Str.get(new TokenBuilder(QueryText.ID).addInt(node.id).finish());
  }

  @Override
  public boolean has(final Flag flag) {
    return flag == Flag.CTX && exprs.length == 0 || super.has(flag);
  }

  @Override
  public boolean accept(final ASTVisitor visitor) {
    return (exprs.length != 0 || visitor.lock(DBLocking.CONTEXT)) && super.accept(visitor);
  }
}


text:
<?xml version="1.0" encoding="UTF-8"?>
<!--
  ~ Copyright (c) 2010-2017 Evolveum and contributors
  ~
  ~ This work is dual-licensed under the Apache License 2.0
  ~ and European Union Public License. See LICENSE file for details.
  -->
<q:query xmlns:xsi='http://www.w3.org/2001/XMLSchema-instance'
    xmlns:c='http://midpoint.evolveum.com/xml/ns/public/common/common-3'
    xmlns:i='http://midpoint.evolveum.com/xml/ns/public/common/common-3'
    xmlns:dj="http://midpoint.evolveum.com/xml/ns/samples/localhostOpenDJ"
    xmlns:xsd="http://www.w3.org/2001/XMLSchema"
    xsi:schemaLocation='http://www.w3.org/2001/XMLSchema ../standard/XMLSchema.xsd
   http://midpoint.evolveum.com/xml/ns/public/common/common-3 ../../../main/resources/META-INF/wsdl/xml/ns/public/common/common-3.xsd'
    xmlns:foo="http://foo.com/" xmlns:q="http://prism.evolveum.com/xml/ns/public/query-3"
    xmlns:ri="http://midpoint.evolveum.com/xml/ns/public/resource/instance/ef2bc95b-76e0-59e2-86d6-3d4f02d3ffff">

    <!-- Query filter example -->
<q:filter>
    <q:and>
        <q:ref>
            <q:path>i:resourceRef</q:path>
            <q:value>
                <c:oid>ef2bc95b-76e0-59e2-86d6-3d4f02d3ffff</c:oid>
            </q:value>
        </q:ref>
        <q:equal>
            <q:path>i:objectClass</q:path>
            <q:value>ri:inetOrgPerson</q:value>
        </q:equal>
    </q:and>
</q:filter>
</q:query>


text:
import requests
from requests_oauthlib import OAuth1
import pprint
import json
from numpy import ceil
import yaml
import os
import argparse
import datetime

def single_audience_query(user_ids, groupings, audience_name,  max_upload_size = 100000, max_segment_size = 3000000, min_audience_size = 10000, log_file_location = None):
    """
    Make 1 request for audience information
    """

    if len(user_ids) < min_audience_size:
        return "Not enough users to run the audience API"

    # Set up credentials (user-specific)
    creds = yaml.load(open("/mnt/home/fiona/.audience_api_creds","r"))
    auth=OAuth1(creds["consumer_key"],creds["consumer_secret"],creds["token"],creds["token_secret"])

    base_url = creds["url"]
    json_header = {"Content-Type" : "application/json"}

    if log_file_location is None:
        log_file_loc = "/home/jkolb/DDIS-DSO/ABInBev/dsrp/data/audience_and_convo_insights/"
    else:
        log_file_loc = log_file_location

    try:
        os.stat(log_file_loc + audience_name + "_logging")
    except:
        os.mkdir(log_file_loc + audience_name + "_logging")

    logging = open(log_file_loc + audience_name + "_logging" + "/log_file_for_" + audience_name, "w")

    # split the UIDS into max_upload_size
    user_id_chunks = chunks(list(set(user_ids)), max_upload_size)
    uids_json_encoded = []
    for uid_chunk in user_id_chunks:
        uids_json_encoded.append(json.dumps({"user_ids": [str(x) for x in uid_chunk]}))

    # create a segment
    segment_response = requests.post(base_url + "/segments"
            , auth = auth
            , headers = json_header
            , data = json.dumps({"name": audience_name + "segment"})
            )
    logging.write(segment_response.text + "\n")
    segment_id = segment_response.json()["id"]

    # upload the chunks to a segment
    for uid_chunk_json_encoded in uids_json_encoded:
        segment_post_ids = requests.post(base_url + "/segments/" + segment_id + "/ids"
                , auth = auth
                , headers = json_header
                , data = uid_chunk_json_encoded
                )
        logging.write(segment_post_ids.text + "\n")

    # add the segment to an audience
    audience_post = requests.post(base_url + "/audiences"
            , auth = auth
            , headers = json_header
            , data = json.dumps({"name": audience_name, "segment_ids": [segment_id]})
            )
    logging.write(audience_post.text + "\n")
    audience_id = audience_post.json()["id"]

    # make a request for information about the audience
    audience_info = requests.post(base_url + "/audiences/" + audience_id + "/query"
            , auth = auth
            , headers = json_header
            , data = groupings
            )
    logging.write(groupings + "\n")
    logging.write(audience_info.text.encode("utf-8"))

    return audience_info.json()

def many_audience_query(user_ids, groupings, audience_name, max_upload_size = 100000, max_segment_size = 3000000, max_audience_size = 3000000, min_audience_size = 10000, log_file_location = None):
    """
    Make 1 request for audience information for each max_audience_size audience in the set
    """
    if len(user_ids) < min_audience_size:
        return "Audience is too small to use the Audience API"

    api_results = []
    unique_user_ids = list(set(user_ids))
    num_audiences = int(ceil(len(unique_user_ids)/float(max_audience_size)))
    size_audiences = int(ceil(len(unique_user_ids)/float(num_audiences)))

    for i, audience_chunk in enumerate(chunks(unique_user_ids, size_audiences)):
        api_results.append(single_audience_query(audience_chunk, groupings, audience_name + "_" + str(i), max_upload_size = 100000, max_segment_size = 3000000, log_file_location = log_file_location))
    return api_results

def existing_audience_query(groupings, audience_name, log_file_location = None):

    # Set up credentials (user-specific)
    creds = yaml.load(open("audience_api_creds.yaml","r"))
    auth=OAuth1(creds["consumer_key"],creds["consumer_secret"],creds["token"],creds["token_secret"])

    base_url = creds["url"]
    json_header = {"Content-Type" : "application/json"}

    if log_file_location is None:
        log_file_loc = "/home/jkolb/DDIS-DSO/ABInBev/dsrp/data/audience_and_convo_insights/"
    else:
        log_file_loc = log_file_location

    try:
        os.stat(log_file_loc + audience_name + "_logging")
    except:
        os.mkdir(log_file_loc + audience_name + "_logging")

    logging = open(log_file_loc + audience_name + "_logging" + "/log_file_for_" + audience_name.split("_")[0], "w")

    logging.write(groupings + "\n")
    # make a request for information about the audience
    all_audiences = requests.get(base_url + "/audiences"
            , auth = auth
            )

    audience_id = 0
    for audience in all_audiences.json():
        if audience["name"] == audience_name:
            audience_id = audience["id"]
            break
    if audience_id == 0:
        "That audience doesn't exist"

    else:
        audience_info = requests.post(base_url + "/audiences/" + audience_id + "/query"
                , auth = auth
                , headers = json_header
                , data = groupings
                )
        logging.write(audience_info.text)

        return audience_info.json()

def chunks(l, n):
    """Yield successive n-sized chunks from l."""
    for i in xrange(0, len(l), n):
        yield l[i:i+n]

def call_audience_api(user_ids,audience_name, groupings = None,max_audience_size=3000000, log_file_location=None):
    """ call to Audience API goes here """

    aud_name = audience_name
    if groupings is not None:
        use_groupings = groupings
    else:
        grouping_dict = {"groupings": {
            "gender": {"group_by": ["user.gender"]}
            , "location_country": {"group_by": ["user.location.country"]}
            , "location_country_region": {"group_by": ["user.location.country", "user.location.region"]}
            , "location_country_region_metro": {"group_by": ["user.location.country", "user.location.region", "user.location.metro"]}
            , "interest": {"group_by": ["user.interest"]}
            , "tv_genre": {"group_by": ["user.tv.genre"]}
            , "device_os": {"group_by": ["user.device.os"]}
            , "device_network": {"group_by": ["user.device.network"]}
            , "language": {"group_by": ["user.language"]}}}
        use_groupings = json.dumps(grouping_dict)

    audience_api_results = many_audience_query(user_ids, use_groupings, aud_name,
            max_upload_size = 100000, max_segment_size = 3000000, max_audience_size = max_audience_size, min_audience_size = 10000, log_file_location = log_file_location)

    return audience_api_results

def audience_insights_csv_1(audience_api_result):
    d = flatten_dict_1(audience_api_result)
    l = d.items()
    return sorted(l, key = lambda x : (x[0].split("|")[0], -1*int(x[-1])))
    #print i[0] + " | " + str(int(i[1]))

def flatten_dict_1(d):
    def expand(key, value):
        if isinstance(value, dict):
            return [ (key + ' | ' + k, v) for k, v in flatten_dict_1(value).items() ]
        else:
            return [ (key, value) ]
    items = [ item for k, v in d.items() for item in expand(k, v) ]
    return dict(items)

if __name__ == "__main__":
    parser = argparse.ArgumentParser()
    parser.add_argument("-n","--audience_name",dest="audience_identifier", default=None,
            help="must provide a name string for the conversation/audience, alphanumeric + underscore only")
    parser.add_argument("-i","--input-file-name",dest="input_file_name",default=None,
            help="file containing tweets, tweet IDs, or user IDs; take input from stdin if not present")
    parser.add_argument("-f","--full-tweet-input",dest="full_tweet_input",action="store_true",default=False,
            help="input is JSON-formatted tweet data")
    parser.add_argument("-u","--user-id-input",dest="user_id_input",action="store_true",default=True,
            help="input is user IDs")
    parser.add_argument("-g","--groupings",dest="groupings_file",default=None,
            help="groupings file, if None default groupings are used")
    parser.add_argument("-d", "--results-detination",dest="results_file",default="",
            help="destination file for the audience api results")
    parser.add_argument("-m","--max_audience_size",dest="max_audience_size",default=300000,type=int,
            help="the maximum audience size")
    args = parser.parse_args()

    assert args.audience_identifier is not None, "You must provide an id for the analysis"

    time_string = datetime.datetime.now().isoformat().split(".")[0].translate(None,":")
    aud_name =  args.audience_identifier + "_" + time_string

    if args.input_file_name is not None:
        generator = open(args.input_file_name)
    else:
        generator = sys.stdin

    if args.full_tweet_input:
        user_ids = []
        for line in generator:
            try:
                tweet = json.loads(line)
                if "actor" not in tweet:
                    continue
                user_id = int(tweet["actor"]["id"].split(":")[2])
                if user_id not in user_ids:
                    user_ids.append( user_id )
            except ValueError:
                continue

    if args.user_id_input:
        user_ids = [user_id.strip() for user_id in generator]
        user_ids = list(set(user_ids))

    try:
        os.stat(args.results_file + aud_name + "_logging")
    except:
        os.mkdir(args.results_file + aud_name + "_logging")

    try:
        os.stat(args.results_file + aud_name)
    except:
        os.mkdir(args.results_file + aud_name)

    if args.groupings_file is not None:
        groupings = json.dumps(json.load(open(args.groupings_file,"r")))
    else:
        groupings = None

    audience_api_results = call_audience_api(user_ids, aud_name, groupings=groupings, max_audience_size = args.max_audience_size, log_file_location = args.results_file + aud_name + "_logging/")

    print "\nAudience API Results"
    if audience_api_results != "Audience is too small to use the Audience API":
        for i, res in enumerate(audience_api_results):
            aud_csv = audience_insights_csv_1(res)
            audience_insights_file = open(args.results_file + aud_name + "/" + aud_name + "_audience_api_results_" + str(i) + ".piped", "w")
            audience_insights_file_json = open(args.results_file + aud_name + "/" + aud_name + "_audience_api_results_" + str(i) + ".json", "w")
            audience_insights_file_json.write(json.dumps(res).encode("utf-8"))
            audience_insights_file_json.close()
            for line in aud_csv:
                audience_insights_file.write(line[0].encode("utf-8") + " | " + str(int(line[1])) + "\n")
                if int(line[1]) > 15:
                    print line[0] + " | " + str(int(line[1]))
    else:
        print audience_api_results

    audience_insights_file.close()


text: to try out the features


text:
package org.apache.aries.blueprint;

import java.util.List;

import org.apache.aries.blueprint.container.BlueprintContainerImpl;
import org.apache.aries.blueprint.parser.ComponentDefinitionRegistryImpl;
import org.apache.aries.proxy.ProxyManager;
import org.apache.aries.proxy.impl.JdkProxyManager;
import org.osgi.service.blueprint.reflect.ComponentMetadata;
import org.osgi.service.blueprint.reflect.Target;

public class TestBlueprintContainer extends BlueprintContainerImpl {

    public TestBlueprintContainer(ComponentDefinitionRegistryImpl registry) throws Exception {
        this(registry, new JdkProxyManager());
    }

    public TestBlueprintContainer(ComponentDefinitionRegistryImpl registry, ProxyManager proxyManager) throws Exception {
        super(null, new TestBundleContext(), null, null, null, null, null, null, proxyManager, null);
        resetComponentDefinitionRegistry();

        if (registry == null) {
            return;
        }

        List<Target> converters = registry.getTypeConverters();
        for (Target converter : converters) {
            getComponentDefinitionRegistry().registerTypeConverter(converter);
        }
        for (String name : registry.getComponentDefinitionNames()) {
            ComponentMetadata comp = registry.getComponentDefinition(name);
            if (!converters.contains(comp)) {
                getComponentDefinitionRegistry().registerComponentDefinition(comp);
                for (Interceptor interceptor : registry.getInterceptors(comp)) {
                    getComponentDefinitionRegistry().registerInterceptorWithComponent(comp, interceptor);
                }
            }
        }

        processTypeConverters();
        processProcessors();
    }

    @Override
    public Class loadClass(String name) throws ClassNotFoundException {
        return Thread.currentThread().getContextClassLoader().loadClass(name);
    }

    @Override
    public ClassLoader getClassLoader() {
        return Thread.currentThread().getContextClassLoader();
    }
}


text:
require 'test/unit'
extend Test::Unit::Assertions

class String
    def partition
        result = []
        String.palindrome(self, 0, [], result)
        result
    end

    def self.palindrome(s, index, partial, result)
        if index == s.size
            result << partial.dup
            return
        end

        for i in 1..(s.size - index)
            candidate = s[index, i]
            if candidate == candidate.reverse
                partial << candidate
                String.palindrome(s, index + i, partial, result)
                partial.pop
            end
        end
    end
end

assert_equal([
              ["n", "i", "t", "i", "n"],
              ["n", "iti", "n"],
              ["nitin"]
             ].sort, "nitin".partition.sort)

assert_equal([
              ["g", "e", "e", "k", "s"],
              ["g", "ee", "k", "s"]
             ].sort, "geeks".partition.sort)


text:
// <copyright file="ResourcePermissionResult.cs" company="DevDigital">
// Copyright (c) DevDigital. All rights reserved.
// </copyright>

namespace AutoResponse.AspNetCore.Results
{
    using AutoResponse.Core.ApiEvents;

    /// <summary>
    /// Resource permission result.
    /// </summary>
    /// <seealso cref="AutoResponse.AspNetCore.Results.AutoResponseResult" />
    public class ResourcePermissionResult : AutoResponseResult
    {
        /// <summary>
        /// Initializes a new instance of the <see cref="ResourcePermissionResult"/> class.
        /// </summary>
        /// <param name="userId">The user identifier.</param>
        /// <param name="resourceType">Type of the resource.</param>
        /// <param name="resourceId">The resource identifier.</param>
        public ResourcePermissionResult(string userId, string resourceType, string resourceId)
            : base(new EntityPermissionApiEvent(userId, resourceType, resourceId))
        {
        }
    }
}


text:
<xml xmlns:o="urn:schemas-microsoft-com:office:office">
 <o:MainFile HRef="../2018ClubChampionshipEvent11.htm"/>
 <o:File HRef="filelist.xml"/>
</xml>


text:
package leap

import (
	"io"

	"github.com/hybridgroup/gobot"
	"golang.org/x/net/websocket"
)

var _ gobot.Adaptor = (*LeapMotionAdaptor)(nil)

type LeapMotionAdaptor struct {
	name    string
	port    string
	ws      io.ReadWriteCloser
	connect func(string) (io.ReadWriteCloser, error)
}

// NewLeapMotionAdaptor creates a new leap motion adaptor using specified name and port
func NewLeapMotionAdaptor(name string, port string) *LeapMotionAdaptor {
	return &LeapMotionAdaptor{
		name: name,
		port: port,
		connect: func(port string) (io.ReadWriteCloser, error) {
			return websocket.Dial("ws://"+port+"/v3.json", "", "http://"+port)
		},
	}
}
func (l *LeapMotionAdaptor) Name() string { return l.name }
func (l *LeapMotionAdaptor) Port() string { return l.port }

// Connect returns true if connection to leap motion is established succesfully
func (l *LeapMotionAdaptor) Connect() (errs []error) {
	if ws, err := l.connect(l.Port()); err != nil {
		return []error{err}
	} else {
		l.ws = ws
	}
	return
}

// Finalize ends connection to leap motion
func (l *LeapMotionAdaptor) Finalize() (errs []error) { return }


text:
<?xml version='1.0' encoding='utf-8'?>
<!--

	Licensed under the Apache License, Version 2.0 (the "License");
	you may not use this file except in compliance with the License.
	You may obtain a copy of the License at

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

	Unless required by applicable law or agreed to in writing, software
	distributed under the License is distributed on an "AS IS" BASIS,
	WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
	See the License for the specific language governing permissions and
	limitations under the License.

-->
<Context privileged="true">
    <Resources allowLinking="true">
         <PreResources className="org.apache.catalina.webresources.DirResourceSet" base="target" internalPath="/logs" webAppMount="/static-content"/>
    </Resources>
</Context>


text:
<?php

namespace Flarum\Core\Users\Commands;

use Flarum\Events\AvatarWillBeSaved;
use Flarum\Core\Users\UserRepository;
use Flarum\Core\Support\DispatchesEvents;
use Illuminate\Support\Str;
use League\Flysystem\Adapter\Local;
use League\Flysystem\Filesystem;
use League\Flysystem\FilesystemInterface;
use League\Flysystem\MountManager;
use Intervention\Image\ImageManager;

class UploadAvatarHandler
{
    use DispatchesEvents;

    /**
     * @var UserRepository
     */
    protected $users;

    /**
     * @var FilesystemInterface
     */
    protected $uploadDir;

    /**
     * @param UserRepository $users
     * @param FilesystemInterface $uploadDir
     */
    public function __construct(UserRepository $users, FilesystemInterface $uploadDir)
    {
        $this->users = $users;
        $this->uploadDir = $uploadDir;
    }

    /**
     * @param UploadAvatar $command
     * @return \Flarum\Core\Users\User
     * @throws \Flarum\Core\Exceptions\PermissionDeniedException
     */
    public function handle(UploadAvatar $command)
    {
        $actor = $command->actor;

        $user = $this->users->findOrFail($command->userId);

        // Make sure the current user is allowed to edit the user profile.
        // This will let admins and the user themselves pass through, and
        // throw an exception otherwise.
        if ($actor->id !== $user->id) {
            $user->assertCan($actor, 'edit');
        }

        $tmpFile = tempnam(sys_get_temp_dir(), 'avatar');
        $command->file->moveTo($tmpFile);

        $manager = new ImageManager();
        $manager->make($tmpFile)->fit(100, 100)->save();

        event(new AvatarWillBeSaved($user, $actor, $tmpFile));

        $mount = new MountManager([
            'source' => new Filesystem(new Local(pathinfo($tmpFile, PATHINFO_DIRNAME))),
            'target' => $this->uploadDir,
        ]);

        if ($user->avatar_path && $mount->has($file = "target://$user->avatar_path")) {
            $mount->delete($file);
        }

        $uploadName = Str::lower(Str::quickRandom()) . '.jpg';

        $user->changeAvatarPath($uploadName);

        $mount->move("source://".pathinfo($tmpFile, PATHINFO_BASENAME), "target://$uploadName");

        $user->save();
        $this->dispatchEventsFor($user);

        return $user;
    }
}


text:
package cn.sheep3.config;

/**
 * Created by sheep3 on 16-9-17.
 */
public class Constant {

    public static final String PAGE_CACHE_NAME = "page_cache_name";
    public static final String TAG_CACHE_NAME = "tag_cache_name";
    public static final String POST_CACHE_NAME = "post_cache_name";
    public static final String USER_CACHE_NAME = "user_cache_name";
}


text:
<?php

// Exit if accessed directly
if ( ! defined( 'ABSPATH' ) ) {
	exit;
}

class es_cls_dbquery {
	public static function es_view_subscriber_search($search = "", $id = 0) {

		global $wpdb;

		$arrRes = array();

		$sSql = "SELECT * FROM `".$wpdb->prefix."es_emaillist` where es_email_mail != '' ";
		if($search != "" && $search != "ALL") {
			$letter = explode(',', $search);
			$length = count($letter);
			for ($i = 0; $i < $length; $i++) {
				if($i == 0) {
					$sSql = $sSql . " and";
				} else {
					$sSql = $sSql . " or";
				}
				$sSql = $sSql . " es_email_mail LIKE '" . $letter[$i]. "%'";
			}
		}
		if($id > 0) {
			$sSql = $sSql . " and es_email_id=".$id;

		}
		$sSql = $sSql . " order by es_email_id asc";
		$arrRes = $wpdb->get_results($sSql, ARRAY_A);

		return $arrRes;
	}

	// Query to fetch subscribers data on view subscribers screen
	public static function es_view_subscribers_details($id = 0, $search_sts = "", $offset = 0, $limit = 0, $search_group = "") {

		global $wpdb;

		$view_subscribers_details = array();

		$sSql = "SELECT * FROM `".$wpdb->prefix."es_emaillist` WHERE es_email_mail != '' ";
		if($search_sts != "") {
			$sSql = $sSql . " and es_email_status='".$search_sts."'";
		}

		if($search_group != "" && $search_group != "ALL") {
			$sSql = $sSql . ' and es_email_group="'.$search_group.'"';
		}

		if($id > 0) {
			$sSql = $sSql . " and es_email_id=".$id;

		}
		$sSql = $sSql . " order by es_email_id asc";
		$sSql = $sSql . " LIMIT $offset, $limit";
		$view_subscribers_details = $wpdb->get_results($sSql, ARRAY_A);

		return $view_subscribers_details;
	}

	public static function es_view_subscriber_delete($id = 0) {

		global $wpdb;

		$sSql = $wpdb->prepare("DELETE FROM `".$wpdb->prefix."es_emaillist` WHERE `es_email_id` = %d LIMIT 1", $id);
		$wpdb->query($sSql);

		return true;
	}

	public static function es_view_subscriber_ins($data = array(), $action = "insert") {

		global $wpdb;

		$result = 0;

		if (!filter_var($data["es_email_mail"], FILTER_VALIDATE_EMAIL)) {
			return "invalid";
		}

		$es_subscriber_name = sanitize_text_field(esc_attr($data["es_email_name"]));
		$es_subscriber_status = sanitize_text_field(esc_attr($data["es_email_status"]));
		$es_subscriber_group = sanitize_text_field(esc_attr($data["es_email_group"]));
		$es_subscriber_email = sanitize_email(esc_attr($data["es_email_mail"]));

		$CurrentDate = date('Y-m-d G:i:s');
		if($action == "insert") {
			$sSql = "SELECT * FROM `".$wpdb->prefix."es_emaillist` where es_email_mail='".$es_subscriber_email."' and es_email_group='".trim($es_subscriber_group)."'";
			$result = $wpdb->get_var($sSql);
			if ( $result > 0) {
				return "ext";
			} else {
				$guid = es_cls_common::es_generate_guid(60);
				$sql = $wpdb->prepare("INSERT INTO `".$wpdb->prefix."es_emaillist`
						(`es_email_name`,`es_email_mail`, `es_email_status`, `es_email_created`, `es_email_viewcount`, `es_email_group`, `es_email_guid`)
						VALUES(%s, %s, %s, %s, %d, %s, %s)", array(trim($es_subscriber_name), trim($es_subscriber_email),
						trim($es_subscriber_status), $CurrentDate, 0, trim($es_subscriber_group), $guid));
				$wpdb->query($sql);

				/* Added from ES v3.1.5 - If subscribing via Rainmaker
				 * if double opt-in, send confirmation email to subscriber
				 * if single opt-in, send welcome email to subscriber
				 */
				$active_plugins = (array) get_option('active_plugins', array());
				if (is_multisite()) {
					$active_plugins = array_merge($active_plugins, get_site_option('active_sitewide_plugins', array()));
				}

				if (( in_array('icegram-rainmaker/icegram-rainmaker.php', $active_plugins) || array_key_exists('icegram-rainmaker/icegram-rainmaker.php', $active_plugins) )) {			// To Do- Handle via actions

					$es_settings = es_cls_settings::es_setting_select();
					$subscribers = array();
					$subscribers = self::es_view_subscriber_one($es_subscriber_email,$es_subscriber_group);

					if( did_action( 'rainmaker_post_lead' ) >= 1 ) {
						if ( (!empty($es_settings['es_c_optinoption'])) && ($es_settings['es_c_optinoption'] == 'Double Opt In') ) {
							es_cls_sendmail::es_sendmail("optin", $template = 0, $subscribers, "optin", 0);
						} else if ( (!empty($es_settings['es_c_optinoption'])) && ($es_settings['es_c_optinoption'] == 'Single Opt In' ) ) {
							es_cls_sendmail::es_sendmail("welcome", $template = 0, $subscribers, "welcome", 0);
						}
					}
				}
				return "sus";
			}
		} elseif($action == "update") {
			$sSql = "SELECT * FROM `".$wpdb->prefix."es_emaillist` where es_email_mail='".$es_subscriber_email."'";
			$sSql = $sSql . " and es_email_group='".trim($es_subscriber_group)."' and es_email_id != ".$data["es_email_id"];
			$result = $wpdb->get_var($sSql);
			if ( $result > 0) {
				return "ext";
			} else {
				$sSql = $wpdb->prepare("UPDATE `".$wpdb->prefix."es_emaillist` SET `es_email_name` = %s, `es_email_mail` = %s,
						`es_email_status` = %s, `es_email_group` = %s WHERE es_email_id = %d LIMIT 1", array($es_subscriber_name, $es_subscriber_email,
						$es_subscriber_status, $es_subscriber_group, $data["es_email_id"]));
				$wpdb->query($sSql);
				return "sus";
			}
		}
	}

	public static function es_view_subscriber_bulk($idlist = "") {

		global $wpdb;

		$arrRes = array();

		$sSql = "SELECT * FROM `".$wpdb->prefix."es_emaillist` where es_email_mail <> '' ";
		if($idlist != "") {
			$sSql = $sSql . " and es_email_id in (" . $idlist. ");";
		}
		$arrRes = $wpdb->get_results($sSql, ARRAY_A);

		return $arrRes;
	}

	public static function es_view_subscriber_group() {

		global $wpdb;

		$arrRes = array();

		$sSql = "SELECT distinct(es_email_group) FROM `".$wpdb->prefix."es_emaillist`";
		$arrRes = $wpdb->get_results($sSql, ARRAY_A);

		return $arrRes;
	}

	public static function es_view_subscriber_one($mail = "", $group = "") {

		global $wpdb;

		$arrRes = array();

		$sSql = "SELECT * FROM `".$wpdb->prefix."es_emaillist` WHERE es_email_mail = '".$mail."' AND es_email_group = '".$group."'";
		$arrRes = $wpdb->get_results($sSql, ARRAY_A);

		return $arrRes;
	}

	public static function es_view_subscriber_upd_status($status = "", $idlist = "") {

		global $wpdb;

		$sSql = "UPDATE `".$wpdb->prefix."es_emaillist` SET `es_email_status` = '".$status."'";
		$sSql = $sSql . " WHERE es_email_id IN (".$idlist.")";
		$wpdb->query($sSql);

		return "sus";
	}

	public static function es_view_subscriber_upd_group($group = "", $idlist = "") {

		global $wpdb;

		$sSql = "UPDATE `".$wpdb->prefix."es_emaillist` SET `es_email_group` = '".$group."'";
		$sSql = $sSql . " WHERE es_email_id IN (".$idlist.")";
		$wpdb->query($sSql);

		return "sus";
	}

	public static function es_view_subscriber_job($status = "", $id = 0, $guid = "", $email = "") {

		global $wpdb;

		$sSql = "SELECT COUNT(*) AS `count` FROM `".$wpdb->prefix."es_emaillist`";
		$sSql = $sSql . " WHERE es_email_id = %d";
		$sSql = $sSql . " and es_email_mail = %s";
		$sSql = $sSql . " and es_email_guid = %s Limit 1";
		$sSql = $wpdb->prepare($sSql, array($id, $email, $guid));
		$result = $wpdb->get_var($sSql);

		if ( $result > 0 ) {
			$sSql = "UPDATE `".$wpdb->prefix."es_emaillist` SET `es_email_status` = %s";
			$sSql = $sSql . " WHERE es_email_mail = %s Limit 10";
			$sSql = $wpdb->prepare($sSql, array($status, $email));
			$wpdb->query($sSql);
			return true;
		} else {
			return false;
		}
	}

	public static function es_view_subscriber_jobstatus($status = "", $id = 0, $guid = "", $email = "") {

		global $wpdb;

		$sSql = "SELECT COUNT(*) AS `count` FROM `".$wpdb->prefix."es_emaillist`";
		$sSql = $sSql . " WHERE es_email_id = %d";
		$sSql = $sSql . " and es_email_mail = %s";
		$sSql = $sSql . " and es_email_status = %s";
		$sSql = $sSql . " and es_email_guid = %s Limit 1";
		$sSql = $wpdb->prepare($sSql, array($id, $email, $status, $guid));
		$result = $wpdb->get_var($sSql);

		if ( $result > 0) {
			return true;
		} else {
			return false;
		}
	}

	public static function es_view_subscriber_widget($data = array()) {

		global $wpdb;

		$arrRes = array();
		$currentdate = date('Y-m-d G:i:s');

		$sSql = "SELECT * FROM `".$wpdb->prefix."es_emaillist` where es_email_mail='".$data["es_email_mail"]."' and es_email_group='".trim($data["es_email_group"])."'";
		$arrRes = $wpdb->get_results($sSql, ARRAY_A);

		if ( !empty( $arrRes ) && count($arrRes) > 0 ) {
			if( $arrRes[0]['es_email_status'] == "Confirmed" || $arrRes[0]['es_email_status'] == "Single Opt In" ) {
				return "ext";
			} else {
				$action = "";
				$form['es_email_name'] = sanitize_text_field(esc_attr($data["es_email_name"]));
				$form['es_email_mail'] = sanitize_email(esc_attr($data["es_email_mail"]));
				$form['es_email_group'] = sanitize_text_field(esc_attr($data["es_email_group"]));
				$form['es_email_status'] = sanitize_text_field(esc_attr($data["es_email_status"]));
				$form['es_email_id'] = $arrRes[0]["es_email_id"];
				$action = es_cls_dbquery::es_view_subscriber_ins($form, $action = "update");
				return $action;
			}
		} else {
			$action = es_cls_dbquery::es_view_subscriber_ins($data, $action = "insert");
			return $action;
		}
	}

	// Query to fetch count of subscribers from a particular group
	public static function es_subscriber_count_in_group( $groups = "" ) {

		global $wpdb;

		$sSql = "SELECT COUNT(*) AS `count` FROM `".$wpdb->prefix."es_emaillist` WHERE es_email_group = '".$groups."' AND ( es_email_status = 'Confirmed' OR es_email_status = 'Single Opt In' )";
		$total_subscribers = $wpdb->get_var( $sSql );

		return $total_subscribers;

	}

	// Query to fetch all subscribers data from a particular group
	public static function es_subscribers_data_in_group( $group = "" ) {

		global $wpdb;

		$subscribers_in_group = array();

		$sSql = "SELECT * FROM  `".$wpdb->prefix."es_emaillist` WHERE es_email_group = '".$group."' AND ( es_email_status = 'Confirmed' OR es_email_status = 'Single Opt In' ) ";
		$subscribers_in_group = $wpdb->get_results( $sSql, ARRAY_A );

		return $subscribers_in_group;

	}

	// Query to fetch subscribers count (all status)
	public static function es_view_subscriber_count( $id = 0 ) {

		global $wpdb;

		$result = '0';

		if($id > 0) {
			$sSql = $wpdb->prepare("SELECT COUNT(*) AS `count` FROM `".$wpdb->prefix."es_emaillist` WHERE `es_email_id` = %d", array($id));
		} else {
			$sSql = "SELECT COUNT(*) AS `count` FROM `".$wpdb->prefix."es_emaillist`";
		}

		$result = $wpdb->get_var( $sSql );

		return $result;

	}

	// Query to fetch active subscribers (status = Confirmed / Single Opt In)
	public static function es_active_subscribers() {

		global $wpdb;

		$active_subscribers_count = '0';

		$sSql = "SELECT COUNT(*) AS `count` FROM ". $wpdb->prefix . "es_emaillist WHERE es_email_status IN ( 'Confirmed', 'Single Opt In' )";
		$active_subscribers_count = $wpdb->get_var( $sSql );

		return $active_subscribers_count;

	}

}


text:
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
        PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
        "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.kevin.mirs.dao.UserRecommendedMoviesDao">

    <insert id="addUserRecommendedMovies">
        INSERT ignore INTO mirs_user_recommended_movies(uid, rmid, rmv)
        VALUES
        <foreach collection="rms" item="rm" index="index" separator=",">
            (#{uid}, #{rm.itemID}, #{rm.value})
        </foreach>
    </insert>

    <delete id="clearUserRecommendedMovies">
        DELETE FROM mirs_user_recommended_movies
        WHERE uid = #{uid}
    </delete>

    <select id="getUserRecommendedMovies" resultType="UserRecommendedMovies">
        SELECT rmid rmv FROM mirs_user_recommended_movies
        WHERE uid = #{uid}
    </select>

</mapper>