text:
#include "src/core/SkScanPriv.h"

#include "include/core/SkMatrix.h"
#include "include/core/SkPath.h"
#include "include/core/SkRegion.h"
#include "include/private/SkTo.h"
#include "src/core/SkAntiRun.h"
#include "src/core/SkBlitter.h"
#include "src/core/SkPathPriv.h"

#define SHIFT   SK_SUPERSAMPLE_SHIFT
#define SCALE   (1 << SHIFT)
#define MASK    (SCALE - 1)

/** @file
    We have two techniques for capturing the output of the supersampler:
    - SUPERMASK, which records a large mask-bitmap
        this is often faster for small, complex objects
    - RLE, which records a rle-encoded scanline
        this is often faster for large objects with big spans

    These blitters use two coordinate systems:
    - destination coordinates, scale equal to the output - often
        abbreviated with 'i' or 'I' in variable names
    - supersampled coordinates, scale equal to the output * SCALE
 */

//#define FORCE_SUPERMASK
//#define FORCE_RLE

///////////////////////////////////////////////////////////////////////////////

/// Base class for a single-pass supersampled blitter.
class BaseSuperBlitter : public SkBlitter {
public:
    BaseSuperBlitter(SkBlitter* realBlitter, const SkIRect& ir,
                     const SkIRect& clipBounds, bool isInverse);

    /// Must be explicitly defined on subclasses.
    void blitAntiH(int x, int y, const SkAlpha antialias[], const int16_t runs[]) override {
        SkDEBUGFAIL("How did I get here?");
    }
    /// May not be called on BaseSuperBlitter because it blits out of order.
    void blitV(int x, int y, int height, SkAlpha alpha) override {
        SkDEBUGFAIL("How did I get here?");
    }

protected:
    SkBlitter*  fRealBlitter;
    /// Current y coordinate, in destination coordinates.
    int         fCurrIY;
    /// Widest row of region to be blitted, in destination coordinates.
    int         fWidth;
    /// Leftmost x coordinate in any row, in destination coordinates.
    int         fLeft;
    /// Leftmost x coordinate in any row, in supersampled coordinates.
    int         fSuperLeft;

    SkDEBUGCODE(int fCurrX;)
    /// Current y coordinate in supersampled coordinates.
    int fCurrY;
    /// Initial y coordinate (top of bounds).
    int fTop;

    SkIRect fSectBounds;
};

BaseSuperBlitter::BaseSuperBlitter(SkBlitter* realBlit, const SkIRect& ir,
                                   const SkIRect& clipBounds, bool isInverse) {
    fRealBlitter = realBlit;

    SkIRect sectBounds;
    if (isInverse) {
        // We use the clip bounds instead of the ir, since we may be asked to
        //draw outside of the rect when we're a inverse filltype
        sectBounds = clipBounds;
    } else {
        if (!sectBounds.intersect(ir, clipBounds)) {
            sectBounds.setEmpty();
        }
    }

    const int left = sectBounds.left();
    const int right = sectBounds.right();

    fLeft = left;
    fSuperLeft = SkLeftShift(left, SHIFT);
    fWidth = right - left;
    fTop = sectBounds.top();
    fCurrIY = fTop - 1;
    fCurrY = SkLeftShift(fTop, SHIFT) - 1;

    SkDEBUGCODE(fCurrX = -1;)
}

/// Run-length-encoded supersampling antialiased blitter.
class SuperBlitter : public BaseSuperBlitter {
public:
    SuperBlitter(SkBlitter* realBlitter, const SkIRect& ir, const SkIRect& clipBounds,
                 bool isInverse);

    ~SuperBlitter() override {
        this->flush();
    }

    /// Once fRuns contains a complete supersampled row, flush() blits
    /// it out through the wrapped blitter.
    void flush();

    /// Blits a row of pixels, with location and width specified
    /// in supersampled coordinates.
    void blitH(int x, int y, int width) override;
    /// Blits a rectangle of pixels, with location and size specified
    /// in supersampled coordinates.
    void blitRect(int x, int y, int width, int height) override;

private:
    // The next three variables are used to track a circular buffer that
    // contains the values used in SkAlphaRuns. These variables should only
    // ever be updated in advanceRuns(), and fRuns should always point to
    // a valid SkAlphaRuns...
    int         fRunsToBuffer;
    void*       fRunsBuffer;
    int         fCurrentRun;
    SkAlphaRuns fRuns;

    // extra one to store the zero at the end
    int getRunsSz() const { return (fWidth + 1 + (fWidth + 2)/2) * sizeof(int16_t); }

    // This function updates the fRuns variable to point to the next buffer space
    // with adequate storage for a SkAlphaRuns. It mostly just advances fCurrentRun
    // and resets fRuns to point to an empty scanline.
    void advanceRuns() {
        const size_t kRunsSz = this->getRunsSz();
        fCurrentRun = (fCurrentRun + 1) % fRunsToBuffer;
        fRuns.fRuns = reinterpret_cast<int16_t*>(
            reinterpret_cast<uint8_t*>(fRunsBuffer) + fCurrentRun * kRunsSz);
        fRuns.fAlpha = reinterpret_cast<SkAlpha*>(fRuns.fRuns + fWidth + 1);
        fRuns.reset(fWidth);
    }

    int         fOffsetX;
};

SuperBlitter::SuperBlitter(SkBlitter* realBlitter, const SkIRect& ir, const SkIRect& clipBounds,
                           bool isInverse)
        : BaseSuperBlitter(realBlitter, ir, clipBounds, isInverse)
{
    fRunsToBuffer = realBlitter->requestRowsPreserved();
    fRunsBuffer = realBlitter->allocBlitMemory(fRunsToBuffer * this->getRunsSz());
    fCurrentRun = -1;

    this->advanceRuns();

    fOffsetX = 0;
}

void SuperBlitter::flush() {
    if (fCurrIY >= fTop) {

        SkASSERT(fCurrentRun < fRunsToBuffer);
        if (!fRuns.empty()) {
            // SkDEBUGCODE(fRuns.dump();)
            fRealBlitter->blitAntiH(fLeft, fCurrIY, fRuns.fAlpha, fRuns.fRuns);
            this->advanceRuns();
            fOffsetX = 0;
        }

        fCurrIY = fTop - 1;
        SkDEBUGCODE(fCurrX = -1;)
    }
}

/** coverage_to_partial_alpha() is being used by SkAlphaRuns, which
    *accumulates* SCALE pixels worth of "alpha" in [0,(256/SCALE)]
    to produce a final value in [0, 255] and handles clamping 256->255
    itself, with the same (alpha - (alpha >> 8)) correction as
    coverage_to_exact_alpha().
*/
static inline int coverage_to_partial_alpha(int aa) {
    aa <<= 8 - 2*SHIFT;
    return aa;
}

/** coverage_to_exact_alpha() is being used by our blitter, which wants
    a final value in [0, 255].
*/
static inline int coverage_to_exact_alpha(int aa) {
    int alpha = (256 >> SHIFT) * aa;
    // clamp 256->255
    return alpha - (alpha >> 8);
}

void SuperBlitter::blitH(int x, int y, int width) {
    SkASSERT(width > 0);

    int iy = y >> SHIFT;
    SkASSERT(iy >= fCurrIY);

    x -= fSuperLeft;
    // hack, until I figure out why my cubics (I think) go beyond the bounds
    if (x < 0) {
        width += x;
        x = 0;
    }

#ifdef SK_DEBUG
    SkASSERT(y != fCurrY || x >= fCurrX);
#endif
    SkASSERT(y >= fCurrY);
    if (fCurrY != y) {
        fOffsetX = 0;
        fCurrY = y;
    }

    if (iy != fCurrIY) {  // new scanline
        this->flush();
        fCurrIY = iy;
    }

    int start = x;
    int stop = x + width;

    SkASSERT(start >= 0 && stop > start);
    // integer-pixel-aligned ends of blit, rounded out
    int fb = start & MASK;
    int fe = stop & MASK;
    int n = (stop >> SHIFT) - (start >> SHIFT) - 1;

    if (n < 0) {
        fb = fe - fb;
        n = 0;
        fe = 0;
    } else {
        if (fb == 0) {
            n += 1;
        } else {
            fb = SCALE - fb;
        }
    }

    fOffsetX = fRuns.add(x >> SHIFT, coverage_to_partial_alpha(fb),
                         n, coverage_to_partial_alpha(fe),
                         (1 << (8 - SHIFT)) - (((y & MASK) + 1) >> SHIFT),
                         fOffsetX);

#ifdef SK_DEBUG
    fRuns.assertValid(y & MASK, (1 << (8 - SHIFT)));
    fCurrX = x + width;
#endif
}

#if 0 // UNUSED
static void set_left_rite_runs(SkAlphaRuns& runs, int ileft, U8CPU leftA,
                               int n, U8CPU riteA) {
    SkASSERT(leftA <= 0xFF);
    SkASSERT(riteA <= 0xFF);

    int16_t* run = runs.fRuns;
    uint8_t* aa = runs.fAlpha;

    if (ileft > 0) {
        run[0] = ileft;
        aa[0] = 0;
        run += ileft;
        aa += ileft;
    }

    SkASSERT(leftA < 0xFF);
    if (leftA > 0) {
        *run++ = 1;
        *aa++ = leftA;
    }

    if (n > 0) {
        run[0] = n;
        aa[0] = 0xFF;
        run += n;
        aa += n;
    }

    SkASSERT(riteA < 0xFF);
    if (riteA > 0) {
        *run++ = 1;
        *aa++ = riteA;
    }
    run[0] = 0;
}
#endif

void SuperBlitter::blitRect(int x, int y, int width, int height) {
    SkASSERT(width > 0);
    SkASSERT(height > 0);

    // blit leading rows
    while ((y & MASK)) {
        this->blitH(x, y++, width);
        if (--height <= 0) {
            return;
        }
    }
    SkASSERT(height > 0);

    // Since this is a rect, instead of blitting supersampled rows one at a
    // time and then resolving to the destination canvas, we can blit
    // directly to the destintion canvas one row per SCALE supersampled rows.
    int start_y = y >> SHIFT;
    int stop_y = (y + height) >> SHIFT;
    int count = stop_y - start_y;
    if (count > 0) {
        y += count << SHIFT;
        height -= count << SHIFT;

        // save original X for our tail blitH() loop at the bottom
        int origX = x;

        x -= fSuperLeft;
        // hack, until I figure out why my cubics (I think) go beyond the bounds
        if (x < 0) {
            width += x;
            x = 0;
        }

        // There is always a left column, a middle, and a right column.
        // ileft is the destination x of the first pixel of the entire rect.
        // xleft is (SCALE - # of covered supersampled pixels) in that
        // destination pixel.
        int ileft = x >> SHIFT;
        int xleft = x & MASK;
        // irite is the destination x of the last pixel of the OPAQUE section.
        // xrite is the number of supersampled pixels extending beyond irite;
        // xrite/SCALE should give us alpha.
        int irite = (x + width) >> SHIFT;
        int xrite = (x + width) & MASK;
        if (!xrite) {
            xrite = SCALE;
            irite--;
        }

        // Need to call flush() to clean up pending draws before we
        // even consider blitV(), since otherwise it can look nonmonotonic.
        SkASSERT(start_y > fCurrIY);
        this->flush();

        int n = irite - ileft - 1;
        if (n < 0) {
            // If n < 0, we'll only have a single partially-transparent column
            // of pixels to render.
            xleft = xrite - xleft;
            SkASSERT(xleft <= SCALE);
            SkASSERT(xleft > 0);
            fRealBlitter->blitV(ileft + fLeft, start_y, count,
                coverage_to_exact_alpha(xleft));
        } else {
            // With n = 0, we have two possibly-transparent columns of pixels
            // to render; with n > 0, we have opaque columns between them.

            xleft = SCALE - xleft;

            // Using coverage_to_exact_alpha is not consistent with blitH()
            const int coverageL = coverage_to_exact_alpha(xleft);
            const int coverageR = coverage_to_exact_alpha(xrite);

            SkASSERT(coverageL > 0 || n > 0 || coverageR > 0);
            SkASSERT((coverageL != 0) + n + (coverageR != 0) <= fWidth);

            fRealBlitter->blitAntiRect(ileft + fLeft, start_y, n, count,
                                       coverageL, coverageR);
        }

        // preamble for our next call to blitH()
        fCurrIY = stop_y - 1;
        fOffsetX = 0;
        fCurrY = y - 1;
        fRuns.reset(fWidth);
        x = origX;
    }

    // catch any remaining few rows
    SkASSERT(height <= MASK);
    while (--height >= 0) {
        this->blitH(x, y++, width);
    }
}

///////////////////////////////////////////////////////////////////////////////

/// Masked supersampling antialiased blitter.
class MaskSuperBlitter : public BaseSuperBlitter {
public:
    MaskSuperBlitter(SkBlitter* realBlitter, const SkIRect& ir, const SkIRect&, bool isInverse);
    ~MaskSuperBlitter() override {
        fRealBlitter->blitMask(fMask, fClipRect);
    }

    void blitH(int x, int y, int width) override;

    static bool CanHandleRect(const SkIRect& bounds) {
#ifdef FORCE_RLE
        return false;
#endif
        int width = bounds.width();
        int64_t rb = SkAlign4(width);
        // use 64bits to detect overflow
        int64_t storage = rb * bounds.height();

        return (width <= MaskSuperBlitter::kMAX_WIDTH) &&
               (storage <= MaskSuperBlitter::kMAX_STORAGE);
    }

private:
    enum {
#ifdef FORCE_SUPERMASK
        kMAX_WIDTH = 2048,
        kMAX_STORAGE = 1024 * 1024 * 2
#else
        kMAX_WIDTH = 32,    // so we don't try to do very wide things, where the RLE blitter would be faster
        kMAX_STORAGE = 1024
#endif
    };

    SkMask      fMask;
    SkIRect     fClipRect;
    // we add 1 because add_aa_span can write (unchanged) 1 extra byte at the end, rather than
    // perform a test to see if stopAlpha != 0
    uint32_t    fStorage[(kMAX_STORAGE >> 2) + 1];
};

MaskSuperBlitter::MaskSuperBlitter(SkBlitter* realBlitter, const SkIRect& ir,
                                   const SkIRect& clipBounds, bool isInverse)
    : BaseSuperBlitter(realBlitter, ir, clipBounds, isInverse)
{
    SkASSERT(CanHandleRect(ir));
    SkASSERT(!isInverse);

    fMask.fImage    = (uint8_t*)fStorage;
    fMask.fBounds   = ir;
    fMask.fRowBytes = ir.width();
    fMask.fFormat   = SkMask::kA8_Format;

    fClipRect = ir;
    if (!fClipRect.intersect(clipBounds)) {
        SkASSERT(0);
        fClipRect.setEmpty();
    }

    // For valgrind, write 1 extra byte at the end so we don't read
    // uninitialized memory. See comment in add_aa_span and fStorage[].
    memset(fStorage, 0, fMask.fBounds.height() * fMask.fRowBytes + 1);
}

static void add_aa_span(uint8_t* alpha, U8CPU startAlpha) {
    /*  I should be able to just add alpha[x] + startAlpha.
        However, if the trailing edge of the previous span and the leading
        edge of the current span round to the same super-sampled x value,
        I might overflow to 256 with this add, hence the funny subtract.
    */
    unsigned tmp = *alpha + startAlpha;
    SkASSERT(tmp <= 256);
    *alpha = SkToU8(tmp - (tmp >> 8));
}

static inline uint32_t quadplicate_byte(U8CPU value) {
    uint32_t pair = (value << 8) | value;
    return (pair << 16) | pair;
}

// Perform this tricky subtract, to avoid overflowing to 256. Our caller should
// only ever call us with at most enough to hit 256 (never larger), so it is
// enough to just subtract the high-bit. Actually clamping with a branch would
// be slower (e.g. if (tmp > 255) tmp = 255;)
//
static inline void saturated_add(uint8_t* ptr, U8CPU add) {
    unsigned tmp = *ptr + add;
    SkASSERT(tmp <= 256);
    *ptr = SkToU8(tmp - (tmp >> 8));
}

// minimum count before we want to setup an inner loop, adding 4-at-a-time
#define MIN_COUNT_FOR_QUAD_LOOP  16

static void add_aa_span(uint8_t* alpha, U8CPU startAlpha, int middleCount,
                        U8CPU stopAlpha, U8CPU maxValue) {
    SkASSERT(middleCount >= 0);

    saturated_add(alpha, startAlpha);
    alpha += 1;

    if (middleCount >= MIN_COUNT_FOR_QUAD_LOOP) {
        // loop until we're quad-byte aligned
        while (reinterpret_cast<intptr_t>(alpha) & 0x3) {
            alpha[0] = SkToU8(alpha[0] + maxValue);
            alpha += 1;
            middleCount -= 1;
        }

        int bigCount = middleCount >> 2;
        uint32_t* qptr = reinterpret_cast<uint32_t*>(alpha);
        uint32_t qval = quadplicate_byte(maxValue);
        do {
            *qptr++ += qval;
        } while (--bigCount > 0);

        middleCount &= 3;
        alpha = reinterpret_cast<uint8_t*> (qptr);
        // fall through to the following while-loop
    }

    while (--middleCount >= 0) {
        alpha[0] = SkToU8(alpha[0] + maxValue);
        alpha += 1;
    }

    // potentially this can be off the end of our "legal" alpha values, but that
    // only happens if stopAlpha is also 0. Rather than test for stopAlpha != 0
    // every time (slow), we just do it, and ensure that we've allocated extra space
    // (see the + 1 comment in fStorage[]
    saturated_add(alpha, stopAlpha);
}

void MaskSuperBlitter::blitH(int x, int y, int width) {
    int iy = (y >> SHIFT);

    SkASSERT(iy >= fMask.fBounds.fTop && iy < fMask.fBounds.fBottom);
    iy -= fMask.fBounds.fTop;   // make it relative to 0

    // This should never happen, but it does.  Until the true cause is
    // discovered, let's skip this span instead of crashing.
    // See http://crbug.com/17569.
    if (iy < 0) {
        return;
    }

#ifdef SK_DEBUG
    {
        int ix = x >> SHIFT;
        SkASSERT(ix >= fMask.fBounds.fLeft && ix < fMask.fBounds.fRight);
    }
#endif

    x -= SkLeftShift(fMask.fBounds.fLeft, SHIFT);

    // hack, until I figure out why my cubics (I think) go beyond the bounds
    if (x < 0) {
        width += x;
        x = 0;
    }

    uint8_t* row = fMask.fImage + iy * fMask.fRowBytes + (x >> SHIFT);

    int start = x;
    int stop = x + width;

    SkASSERT(start >= 0 && stop > start);
    int fb = start & MASK;
    int fe = stop & MASK;
    int n = (stop >> SHIFT) - (start >> SHIFT) - 1;

    if (n < 0) {
        SkASSERT(row >= fMask.fImage);
        SkASSERT(row < fMask.fImage + kMAX_STORAGE + 1);
        add_aa_span(row, coverage_to_partial_alpha(fe - fb));
    } else {
        fb = SCALE - fb;
        SkASSERT(row >= fMask.fImage);
        SkASSERT(row + n + 1 < fMask.fImage + kMAX_STORAGE + 1);
        add_aa_span(row,  coverage_to_partial_alpha(fb),
                    n, coverage_to_partial_alpha(fe),
                    (1 << (8 - SHIFT)) - (((y & MASK) + 1) >> SHIFT));
    }

#ifdef SK_DEBUG
    fCurrX = x + width;
#endif
}

///////////////////////////////////////////////////////////////////////////////

static SkIRect safeRoundOut(const SkRect& src) {
    // roundOut will pin huge floats to max/min int
    SkIRect dst = src.roundOut();

    // intersect with a smaller huge rect, so the rect will not be considered empty for being
    // too large. e.g. { -SK_MaxS32 ... SK_MaxS32 } is considered empty because its width
    // exceeds signed 32bit.
    const int32_t limit = SK_MaxS32 >> SK_SUPERSAMPLE_SHIFT;
    (void)dst.intersect({ -limit, -limit, limit, limit});

    return dst;
}

constexpr int kSampleSize = 8;
#if !defined(SK_DISABLE_AAA)
    constexpr SkScalar kComplexityThreshold = 0.25;
#endif

static void compute_complexity(const SkPath& path, SkScalar& avgLength, SkScalar& complexity) {
    int n = path.countPoints();
    if (n < kSampleSize || path.getBounds().isEmpty()) {
        // set to invalid value to indicate that we failed to compute
        avgLength = complexity = -1;
        return;
    }

    SkScalar sumLength = 0;
    SkPoint lastPoint = path.getPoint(0);
    for(int i = 1; i < kSampleSize; ++i) {
        SkPoint point = path.getPoint(i);
        sumLength += SkPoint::Distance(lastPoint, point);
        lastPoint = point;
    }
    avgLength = sumLength / (kSampleSize - 1);

    auto sqr = [](SkScalar x) { return x*x; };

    SkScalar diagonalSqr = sqr(path.getBounds().width()) + sqr(path.getBounds().height());

    // If the path consists of random line segments, the number of intersections should be
    // proportional to this.
    SkScalar intersections = sk_ieee_float_divide(sqr(n) * sqr(avgLength), diagonalSqr);

    // The number of intersections per scanline should be proportional to this number.
    complexity = sk_ieee_float_divide(intersections, path.getBounds().height());

    if (sk_float_isnan(complexity)) {  // it may be possible to have 0.0 / 0.0; inf is fine for us.
        complexity = -1;
    }
}

static bool ShouldUseAAA(const SkPath& path, SkScalar avgLength, SkScalar complexity) {
#if defined(SK_DISABLE_AAA)
    return false;
#else
    if (gSkForceAnalyticAA) {
        return true;
    }
    if (!gSkUseAnalyticAA) {
        return false;
    }
    if (path.isRect(nullptr)) {
        return true;
    }

    #ifdef SK_SUPPORT_LEGACY_AAA_CHOICE
        const SkRect& bounds = path.getBounds();
        // When the path have so many points compared to the size of its
        // bounds/resolution, it indicates that the path is not quite smooth in
        // the current resolution: the expected number of turning points in
        // every pixel row/column is significantly greater than zero. Hence
        // Aanlytic AA is not likely to produce visible quality improvements,
        // and Analytic AA might be slower than supersampling.
        return path.countPoints() < std::max(bounds.width(), bounds.height()) / 2 - 10;
    #else
        if (path.countPoints() >= path.getBounds().height()) {
            // SAA is faster than AAA in this case even if there are no
            // intersections because AAA will have too many scan lines. See
            // skbug.com/8272
            return false;
        }
        // We will use AAA if the number of verbs < kSampleSize and therefore complexity < 0
        return complexity < kComplexityThreshold;
    #endif
#endif
}

void SkScan::SAAFillPath(const SkPath& path, SkBlitter* blitter, const SkIRect& ir,
                  const SkIRect& clipBounds, bool forceRLE) {
    bool containedInClip = clipBounds.contains(ir);
    bool isInverse = path.isInverseFillType();

    // MaskSuperBlitter can't handle drawing outside of ir, so we can't use it
    // if we're an inverse filltype
    if (!isInverse && MaskSuperBlitter::CanHandleRect(ir) && !forceRLE) {
        MaskSuperBlitter superBlit(blitter, ir, clipBounds, isInverse);
        SkASSERT(SkIntToScalar(ir.fTop) <= path.getBounds().fTop);
        sk_fill_path(path, clipBounds, &superBlit, ir.fTop, ir.fBottom, SHIFT, containedInClip);
    } else {
        SuperBlitter superBlit(blitter, ir, clipBounds, isInverse);
        sk_fill_path(path, clipBounds, &superBlit, ir.fTop, ir.fBottom, SHIFT, containedInClip);
    }
}

static int overflows_short_shift(int value, int shift) {
    const int s = 16 + shift;
    return (SkLeftShift(value, s) >> s) - value;
}

/**
  Would any of the coordinates of this rectangle not fit in a short,
  when left-shifted by shift?
*/
static int rect_overflows_short_shift(SkIRect rect, int shift) {
    SkASSERT(!overflows_short_shift(8191, shift));
    SkASSERT(overflows_short_shift(8192, shift));
    SkASSERT(!overflows_short_shift(32767, 0));
    SkASSERT(overflows_short_shift(32768, 0));

    // Since we expect these to succeed, we bit-or together
    // for a tiny extra bit of speed.
    return overflows_short_shift(rect.fLeft, shift) |
           overflows_short_shift(rect.fRight, shift) |
           overflows_short_shift(rect.fTop, shift) |
           overflows_short_shift(rect.fBottom, shift);
}

void SkScan::AntiFillPath(const SkPath& path, const SkRegion& origClip,
                          SkBlitter* blitter, bool forceRLE) {
    if (origClip.isEmpty()) {
        return;
    }

    const bool isInverse = path.isInverseFillType();
    SkIRect ir = safeRoundOut(path.getBounds());
    if (ir.isEmpty()) {
        if (isInverse) {
            blitter->blitRegion(origClip);
        }
        return;
    }

    // If the intersection of the path bounds and the clip bounds
    // will overflow 32767 when << by SHIFT, we can't supersample,
    // so draw without antialiasing.
    SkIRect clippedIR;
    if (isInverse) {
       // If the path is an inverse fill, it's going to fill the entire
       // clip, and we care whether the entire clip exceeds our limits.
       clippedIR = origClip.getBounds();
    } else {
       if (!clippedIR.intersect(ir, origClip.getBounds())) {
           return;
       }
    }
    if (rect_overflows_short_shift(clippedIR, SHIFT)) {
        SkScan::FillPath(path, origClip, blitter);
        return;
    }

    // Our antialiasing can't handle a clip larger than 32767, so we restrict
    // the clip to that limit here. (the runs[] uses int16_t for its index).
    //
    // A more general solution (one that could also eliminate the need to
    // disable aa based on ir bounds (see overflows_short_shift) would be
    // to tile the clip/target...
    SkRegion tmpClipStorage;
    const SkRegion* clipRgn = &origClip;
    {
        static const int32_t kMaxClipCoord = 32767;
        const SkIRect& bounds = origClip.getBounds();
        if (bounds.fRight > kMaxClipCoord || bounds.fBottom > kMaxClipCoord) {
            SkIRect limit = { 0, 0, kMaxClipCoord, kMaxClipCoord };
            tmpClipStorage.op(origClip, limit, SkRegion::kIntersect_Op);
            clipRgn = &tmpClipStorage;
        }
    }
    // for here down, use clipRgn, not origClip

    SkScanClipper   clipper(blitter, clipRgn, ir);

    if (clipper.getBlitter() == nullptr) { // clipped out
        if (isInverse) {
            blitter->blitRegion(*clipRgn);
        }
        return;
    }

    SkASSERT(clipper.getClipRect() == nullptr ||
            *clipper.getClipRect() == clipRgn->getBounds());

    // now use the (possibly wrapped) blitter
    blitter = clipper.getBlitter();

    if (isInverse) {
        sk_blit_above(blitter, ir, *clipRgn);
    }

    SkScalar avgLength, complexity;
    compute_complexity(path, avgLength, complexity);

    if (ShouldUseAAA(path, avgLength, complexity)) {
        // Do not use AAA if path is too complicated:
        // there won't be any speedup or significant visual improvement.
        SkScan::AAAFillPath(path, blitter, ir, clipRgn->getBounds(), forceRLE);
    } else {
        SkScan::SAAFillPath(path, blitter, ir, clipRgn->getBounds(), forceRLE);
    }

    if (isInverse) {
        sk_blit_below(blitter, ir, *clipRgn);
    }
}

///////////////////////////////////////////////////////////////////////////////

#include "src/core/SkRasterClip.h"

void SkScan::FillPath(const SkPath& path, const SkRasterClip& clip, SkBlitter* blitter) {
    if (clip.isEmpty() || !path.isFinite()) {
        return;
    }

    if (clip.isBW()) {
        FillPath(path, clip.bwRgn(), blitter);
    } else {
        SkRegion        tmp;
        SkAAClipBlitter aaBlitter;

        tmp.setRect(clip.getBounds());
        aaBlitter.init(blitter, &clip.aaRgn());
        SkScan::FillPath(path, tmp, &aaBlitter);
    }
}

void SkScan::AntiFillPath(const SkPath& path, const SkRasterClip& clip, SkBlitter* blitter) {
    if (clip.isEmpty() || !path.isFinite()) {
        return;
    }

    if (clip.isBW()) {
        AntiFillPath(path, clip.bwRgn(), blitter, false);
    } else {
        SkRegion        tmp;
        SkAAClipBlitter aaBlitter;

        tmp.setRect(clip.getBounds());
        aaBlitter.init(blitter, &clip.aaRgn());
        AntiFillPath(path, tmp, &aaBlitter, true); // SkAAClipBlitter can blitMask, why forceRLE?
    }
}


text:
class Cart < ActiveRecord::Base
  include Repia::UUIDModel
  acts_as_paranoid

  belongs_to :user, foreign_key: "user_uuid", primary_key: "uuid"
  has_many :items, foreign_key: "cart_uuid", primary_key: "uuid"

  validates :user, presence: true
  validate :must_have_no_duplicate_products
  validate :only_one_cart_per_user

  ##
  # Allow only one cart per user.
  #
  def only_one_cart_per_user
    carts = Cart.where(user_uuid: user_uuid)
    if carts.length > 1
      # :nocov:
      errors.add(:user_uuid, "already has a cart")
      # :nocov:
    elsif carts.length == 1 && carts.first != self
      errors.add(:user_uuid, "already has a cart")
    end
  end

  ##
  # Ensure that no duplicate products exist in the cart. That is, each item
  # must be a unique product within the cart.
  #
  def must_have_no_duplicate_products
    seen = []
    items.each do |item|
      if seen.include?(item.product.uuid) then
        errors.add(:items, "cannot have duplicate products")
      else
        seen << item.product.uuid
      end
    end
  end

  ##
  # Calculates the shipping amount for the whole cart. If there is only one
  # item with a quantity of 1, the original shipping is used for that
  # product. Otherwise, use add-on shipping cost.
  #
  def shipping
    total_quantity = items.inject(0) {|q, item| q + item.quantity}
    if total_quantity == 1
      return items.first.product.base_shipping
    else
      return items.inject(0) {|total, item|
        total + (item.product.add_on_shipping * item.quantity)
      }
    end
  end

  ##
  # This method calculates the subtotal of the whole cart. The amount is
  # before tax and shipping amount.
  def subtotal
    return items.inject(0) {|total, item| total + item.subtotal}
  end

  # # Total before tax is shipping plus subtotal.
  # def total_before_tax
  #   return shipping + subtotal
  # end
end

redpajama_set_name: RedPajamaGithub


text:
package org.drools;

import org.drools.RuleBaseConfiguration.AssertBehaviour;
import org.drools.RuleBaseConfiguration.SequentialAgenda;
import org.drools.common.ArrayAgendaGroupFactory;
import org.drools.common.PriorityQueueAgendaGroupFactory;
import org.junit.Test;

import java.util.Properties;

import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;

public class RuleBaseConfigurationTest {

    @Test
    public void testSystemProperties() {
        RuleBaseConfiguration cfg = new RuleBaseConfiguration();
        assertEquals( AssertBehaviour.IDENTITY,
                      cfg.getAssertBehaviour() );

        System.setProperty( "drools.equalityBehavior",
                            "EQUALITY" );
        cfg = new RuleBaseConfiguration();
        assertEquals( AssertBehaviour.EQUALITY,
                      cfg.getAssertBehaviour() );

        System.getProperties().remove( "drools.equalityBehavior" );
    }

    @Test
    public void testProgrammaticPropertiesFile() {
        RuleBaseConfiguration cfg = new RuleBaseConfiguration();
        assertEquals( true,
                      cfg.isIndexLeftBetaMemory() );

        Properties properties = new Properties();
        properties.setProperty( "drools.indexLeftBetaMemory",
                                "false" );
        cfg = new RuleBaseConfiguration( properties );

        assertEquals( false,
                      cfg.isIndexLeftBetaMemory() );

        System.getProperties().remove( "drools.indexLeftBetaMemory" );
    }

    @Test
    public void testAssertBehaviour() {
        Properties properties = new Properties();
        properties.setProperty( "drools.equalityBehavior", "identity" );
        RuleBaseConfiguration cfg = new RuleBaseConfiguration(properties);

        assertEquals( AssertBehaviour.IDENTITY, cfg.getAssertBehaviour() );

        properties = new Properties();
        properties.setProperty( "drools.equalityBehavior", "equality" );
        cfg = new RuleBaseConfiguration(properties);

        assertEquals( AssertBehaviour.EQUALITY, cfg.getAssertBehaviour() );
    }

    @Test
    public void testSequential() {
        Properties properties = new Properties();
        properties.setProperty( "drools.sequential", "false" );
        RuleBaseConfiguration cfg = new RuleBaseConfiguration(properties);

        assertFalse( cfg.isSequential() );
        assertTrue( cfg.getAgendaGroupFactory() instanceof PriorityQueueAgendaGroupFactory );

        properties = new Properties();
        properties.setProperty( "drools.sequential.agenda", "sequential" );
        properties.setProperty( "drools.sequential", "true" );
        cfg = new RuleBaseConfiguration(properties);

        assertTrue( cfg.isSequential() );
        assertEquals( SequentialAgenda.SEQUENTIAL, cfg.getSequentialAgenda() );
        assertTrue( cfg.getAgendaGroupFactory() instanceof ArrayAgendaGroupFactory );

        properties = new Properties();
        properties.setProperty( "drools.sequential.agenda", "dynamic" );
        properties.setProperty( "drools.sequential", "true" );
        cfg = new RuleBaseConfiguration(properties);

        assertTrue( cfg.isSequential() );
        assertEquals( SequentialAgenda.DYNAMIC, cfg.getSequentialAgenda() );
        assertTrue( cfg.getAgendaGroupFactory() instanceof PriorityQueueAgendaGroupFactory );
    }

    @Test
    public void testLRUnlinking() {
        RuleBaseConfiguration cfg = new RuleBaseConfiguration();
        assertEquals( false,
                      cfg.isUnlinkingEnabled() );

        Properties properties = new Properties();
        properties.setProperty( "drools.lrUnlinkingEnabled",
                                "true" );
        cfg = new RuleBaseConfiguration( properties );

        assertEquals( true,
                      cfg.isUnlinkingEnabled() );
    }

}


text:
<?php

/**
 * CPAC_Column_Term_Parent
 *
 * @since 2.0.0
 */
class CPAC_Column_Term_Parent extends CPAC_Column {

	public function init() {
		parent::init();
		$this->properties['type'] = 'column-term_parent';
		$this->properties['label'] = __( 'Parent', 'codepress-admin-columns' );

		$this->options['term_property'] = '';
	}

	/**
	 * @see CPAC_Column::get_value()
	 * @since 2.0.0
	 */
	public function get_value( $term_id ) {
		$parent_id = $this->get_raw_value( $term_id );
		if ( ! $parent_id ) {
			return false;
		}
		switch ( $this->get_option( 'term_property' ) ) {
			case 'slug':
				$label = $this->get_term_field( 'slug', $parent_id, $this->storage_model->taxonomy );
				break;
			case 'id':
				$label = $parent_id;
				break;
			default:
				$label = $this->get_term_field( 'name', $parent_id, $this->storage_model->taxonomy );
				break;
		}
		$link = get_edit_term_link( $parent_id, $this->storage_model->taxonomy );

		return $link ? "{$label}" : $label;
	}

	/**
	 * @see CPAC_Column::get_value()
	 * @since 2.0.3
	 */
	public function get_raw_value( $term_id ) {
		$term = get_term( $term_id, $this->storage_model->taxonomy );

		return $term->parent;
	}

	public function apply_conditional() {
		return is_taxonomy_hierarchical( $this->storage_model->taxonomy );
	}

	public function display_settings() {
		$this->display_field_select(
			'term_property',
			__( 'Display', 'codepress-admin-columns' ),
			array(
				''     => __( 'Title' ),
				'slug' => __( 'Slug' ),
				'id'   => __( 'ID' )
			)
		);
	}
}


text:
#include "SearchMethod.h"
#include <boost/random/mersenne_twister.hpp>
#include <boost/random/normal_distribution.hpp>
#include <boost/random/uniform_real_distribution.hpp>
#include "PFParams.h"

#ifdef ENABLE_PARALLEL
#include <memory>
#endif

_MTF_BEGIN_NAMESPACE

//! structure with all information about a particle
//! might be used for a possible future migration from
//! the use of seperate structures for different properties
struct Particle{
	VectorXd state[2];
	VectorXd ar[2];
	double wt;
	double cum_wt;
	int curr_set_id;
	void resize(int state_size){
		state[0].resize(state_size);
		state[1].resize(state_size);
		ar[0].resize(state_size);
		ar[1].resize(state_size);
	}
};

// Particle Filter
template<class AM, class SSM>
class PF : public SearchMethod < AM, SSM > {

public:

	typedef PFParams ParamType;
	typedef ParamType::DynamicModel DynamicModel;
	typedef ParamType::UpdateType UpdateType;
	typedef ParamType::LikelihoodFunc LikelihoodFunc;
	typedef ParamType::ResamplingType ResamplingType;
	typedef ParamType::MeanType MeanType;

	typedef boost::mt11213b RandGenT;
	typedef boost::normal_distribution<double> MeasureDistT;
	//typedef boost::variate_generator<RandGenT&, MeasureDistT> MeasureGenT;
	typedef boost::random::uniform_real_distribution<double> ResampleDistT;
	//typedef boost::variate_generator<RandGenT&, ResampleDistT> ResampleGenT;
	typedef ResampleDistT::param_type ResampleDistParamT;

	using SearchMethod<AM, SSM> ::am;
	using SearchMethod<AM, SSM> ::ssm;
	using typename SearchMethod<AM, SSM> ::AMParams;
	using typename SearchMethod<AM, SSM> ::SSMParams;
	using SearchMethod<AM, SSM> ::cv_corners_mat;
	using SearchMethod<AM, SSM> ::name;
	using SearchMethod<AM, SSM> ::initialize;
	using SearchMethod<AM, SSM> ::update;

	PF(const ParamType *pf_params = nullptr,
		const AMParams *am_params = nullptr,
		const SSMParams *ssm_params = nullptr);
	~PF(){}

	void initialize(const cv::Mat &corners) override;
	void update() override;
	void setRegion(const cv::Mat& corners) override;

protected:

#ifdef ENABLE_PARALLEL
	typedef std::unique_ptr<AM> AMPTr;
	typedef std::unique_ptr<SSM> SSMPTr;
	std::vector<AMPTr> am_vec;
	std::vector<SSMPTr> ssm_vec;
#endif

	ParamType params;

	RandGenT measurement_gen;
	MeasureDistT measurement_dist;

	RandGenT resample_gen;
	ResampleDistT resample_dist;

	//! similarity of the initial patch (or template) with itself
	double max_similarity;

	unsigned int ssm_state_size;
	int frame_id;

	Matrix3d warp_update;

	CornersT mean_corners;
	CornersT prev_corners;

	VectorXd mean_state;
	// SSM states for all particles
	// 2 sets of particles are stored for efficient resampling
	std::vector<VectorXd> particle_states[2];
	// Update history for Auto Regression
	std::vector<VectorXd> particle_ar[2];
	int curr_set_id;

	//! ID of the particle with the maximum weight
	int max_wt_id;

	VectorXd particle_wts;
	VectorXd particle_cum_wts;

	VectorXd perturbed_state;
	VectorXd perturbed_ar;

	VectorXd state_sigma, state_mean;
	VectorXi resample_ids;
	VectorXd uniform_rand_nums;
	bool using_pix_sigma;

	double measurement_likelihood;
	double measurement_factor;
	cv::Mat curr_img_uchar;

	bool enable_adaptive_resampling;
	double min_eff_particles;

	char *log_fname;
	char *time_fname;

	void initializeParticles();
	void linearMultinomialResampling();
	void binaryMultinomialResampling();
	void residualResampling();
	void updateMeanCorners();
};

_MTF_END_NAMESPACE

#endif


text: php vendor/bin/phpunit --bootstrap vendor/autoload.php --testdox tests


text:
using System;
using System.Threading;
using System.Threading.Tasks;
using FluentAssertions;
using FluentValidation;
using FluentValidation.Results;
using MediatR;
using Moq;
using NUnit.Framework;
using SFA.DAS.ProviderApprenticeshipsService.Application.Commands.UpdateUserNotificationSettings;
using SFA.DAS.ProviderApprenticeshipsService.Domain.Interfaces;

namespace SFA.DAS.ProviderApprenticeshipsService.Application.UnitTests.Queries.GetUserNotificationSettings
{
    [TestFixture]
    public class WhenUpdatingUserSettings
    {
        private IRequestHandler<UpdateUserNotificationSettingsCommand> _sut;
        private Mock<IUserSettingsRepository> _mockSettingsRepo;
        private Mock<IValidator<UpdateUserNotificationSettingsCommand>> _mockValidator;

        private const string UserRef = "userRef";

        private UpdateUserNotificationSettingsCommand _command;

        [SetUp]
        public void SetUp()
        {
            _mockSettingsRepo = new Mock<IUserSettingsRepository>();
            _mockValidator = new Mock<IValidator<UpdateUserNotificationSettingsCommand>>();

            _sut = new UpdateUserNotificationSettingsHandler(_mockSettingsRepo.Object, _mockValidator.Object, Mock.Of<IProviderCommitmentsLogger>());

            _command = new UpdateUserNotificationSettingsCommand { UserRef = UserRef, ReceiveNotifications = true };
        }

        [Test]
        public async Task ThenGettingUsersSettings()
        {
            _mockValidator.Setup(m => m.Validate(_command)) .Returns(new ValidationResult() );

            await _sut.Handle(_command, new CancellationToken());

            _mockSettingsRepo.Verify(m => m.GetUserSetting(It.IsAny<string>()), Times.Never);
            _mockSettingsRepo.Verify(m => m.UpdateUserSettings(_command.UserRef, _command.ReceiveNotifications), Times.Once);
        }

        [Test]
        public void ThenCreatingSettingsIfNoSettingsFoundGettingUsersSettings()
        {
            _mockValidator.Setup(m => m.Validate(_command))
                .Returns(new ValidationResult { Errors = { new ValidationFailure("Error", "Error message") } });

            Func<Task> act = async () => await _sut.Handle(_command, new CancellationToken());
            act.ShouldThrow<InvalidRequestException>();

            _mockSettingsRepo.Verify(m => m.GetUserSetting(It.IsAny<string>()), Times.Never);
            _mockSettingsRepo.Verify(m => m.UpdateUserSettings(It.IsAny<string>(), It.IsAny<bool>()), Times.Never);
        }
    }
}


text:
import b from './export-default-object-b.js';
import c from './export-default-object-c.js';

export { b };
export { c };


text:
/* -*- Mode: C++; tab-width: 4; c-basic-offset: 4; indent-tabs-mode: nil -*- */
/*
 *     Copyright 2016 Couchbase, Inc.
 *
 *   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.
 */

#pragma once

#include "kv_bucket.h"

/**
 * Eventually Persistent Bucket
 *
 * A bucket type which stores modifications to disk asynchronously
 * ("eventually").
 * Uses hash partitioning of the keyspace into VBuckets, to support
 * replication, rebalance, failover.
 */

class EPBucket : public KVBucket {
public:
    EPBucket(EventuallyPersistentEngine& theEngine);

    bool initialize() override;

    void deinitialize() override;

    protocol_binary_response_status evictKey(const DocKey& key,
                                             uint16_t vbucket,
                                             const char **msg,
                                             size_t *msg_size) override;

    void reset() override;

    /// Start the Flusher for all shards in this bucket.
    bool startFlusher();

    /// Stop the Flusher for all shards in this bucket.
    void stopFlusher();

    bool pauseFlusher() override;
    bool resumeFlusher() override;

    void wakeUpFlusher() override;

    /** Starts the background fetcher for each shard.
     * @return true if successful.
     */
    bool startBgFetcher();

    /// Stops the background fetcher for each shard.
    void stopBgFetcher();

    ENGINE_ERROR_CODE getFileStats(const void* cookie,
                                   ADD_STAT add_stat) override;

    ENGINE_ERROR_CODE getPerVBucketDiskStats(const void* cookie,
                                             ADD_STAT add_stat) override;
    /**
     * Creates a VBucket object.
     */
    RCPtr<VBucket> makeVBucket(VBucket::id_type id,
                               vbucket_state_t state,
                               KVShard* shard,
                               std::unique_ptr<FailoverTable> table,
                               NewSeqnoCallback newSeqnoCb,
                               vbucket_state_t initState,
                               int64_t lastSeqno,
                               uint64_t lastSnapStart,
                               uint64_t lastSnapEnd,
                               uint64_t purgeSeqno,
                               uint64_t maxCas) override;
};


text:
import os.path
import engage.drivers.genforma.django_worker_driver as django_worker_driver

import engage.utils.log_setup
logger = engage.utils.log_setup.setup_engage_logger(__name__)

class Manager(django_worker_driver.Manager):
    def __init__(self,metadata,config=None):
        django_worker_driver.Manager.__init__(self,metadata,config)

    def start(self):
        logger.info('Starting celeryd')
        self.start_worker('celeryd', [])
    def stop(self):
        self.stop_worker('celeryd')

    def force_stop(self):
        self.force_stop_worker('celeryd')

    def is_running(self):
        return self.is_running_worker('celeryd')

    def get_pid_file_path(self):
        return os.path.join(self.config.input_ports.django.log_directory, 'celeryd.pid')


text:
Machine Learning library for node.js

## Linear Regression

shaman supports [both simple linear regression  and multiple linear
regression](http://en.wikipedia.org/wiki/Linear_regression#Simple_and_multiple_regression).

It supports two different algorithms to train the model:

0. [The Normal Equation](http://en.wikipedia.org/wiki/Linear_least_squares_(mathematics))
1. [The Gradient Descent Algorithm](http://en.wikipedia.org/wiki/Gradient_descent)

### Usage

By default, shaman uses the Normal Equation for linear regression.

```javascript
var X = [1, 2, 3, 4, 5];
var Y = [2, 2, 3, 3, 5];
var lr = new LinearRegression(X,Y);
lr.train(function(err) {
  if (err) { throw err; }

  // you can now start using lr.predict:
  console.log(lr.predict(1));
});
```

If your data does not work well with the Normal Equation, you can also
use the Gradient Descent algorithm as an alternative.

```javascript
var X = [1, 2, 3, 4, 5];
var Y = [2, 2, 3, 3, 5];
var lr = new LinearRegression(X,Y, {
  algorithm: 'GradientDescent'
});
lr.train(function(err) {
  if (err) { throw err; }

  // you can now start using lr.predict:
  console.log(lr.predict(1));
});
```

When using Gradient Descent, you can define the number of iterations
(numberOfIterations and the learning rate (learningRate) as options to
the LinearRegression function.

```javascript
var lr = new LinearRegression(X,Y, {
  algorithm: 'GradientDescent',
  numberOfIterations: 1000, // defaults to 8500
  learningRate: 0.5 // defaults to 0.1
});
```

When using the Gradient Descent algorithm, you can ask shaman to save
the results of the cost function at each iteration of the algorithm.
This can be useful if you would like to plot the cost function to ensure
that it is converging.

```javascript
var lr = new LinearRegression(X,Y, {
  algorithm: 'GradientDescent',
  saveCosts: true // defaults to false
});
lr.train(function(err) {
  // you can now get they array of costs:
  console.log(lr.costs);
});
```

If you are troubleshooting, you can pass in a debug option (set to
true). Shaman will then debug useful info in the console (such as the
cost at every iteration of the Gradient Descent algorithem).

```javascript
var lr = new LinearRegression(X,Y, {
  algorithm: 'GradientDescent',
  debug: true // defaults to false
});
lr.train(function(err) {
  // will console.log some useful info
});
```

### Examples

#### Simple Linear Regression - Cars

[Below](https://plot.ly/~luccastera/2) to see an example of Simple Linear Regression
using the Normal Equation to evaluate the price of cars based on their horsepower that was done with the shaman
library. Code is in [examples/cars.js](examples/cars.js)).

![Cars Example](examples/cars.png)

#### Simple Linear Regression - AAPL Stock Price

[Below](https://plot.ly/~luccastera/3/aapl-stock-prices/) to see an
example of Simple Linear Regression applies to the stock price of AAPL
using the Gradient Descent algorithm from 2008 to 2012. Code can be seen at
[examples/stock.js](examples/stock.js).

![Stock Example](examples/stock.png)

#### Multiple Linear Regression - Cigarettes

[Below](https://plot.ly/~luccastera/4/cigarettes/) to see an
example of Multiple Linear Regression to evaluate Carbon Monoxide in
cigarettes from nicotine and tar content. Code can be seen at
[examples/cigarettes.js](examples/cigarettes.js).

![Cigarettes Example](examples/cigarettes.png)

### License

[MIT](LICENSE)


text:
package org.rsna.ctp.stdstages.anonymizer.xml;

import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.w3c.dom.Text;

/**
 * A class to assist in walking down an XML path, with support for wildcards.
 * A path consists of a starting node and a series of path segments coded as
 * a text string in the format of an XPath expression, except that instead of
 * predicates, path segments can have wildcards or predicate-like qualifiers
 * as described in the documentation for the segment field below.
 *

 * An XmlPathElement is parsed into:
 *

 *
node: the parent node from which the path proceeds

 *
path: the full path from the parent node to the end

 *
segment: the first step along the path after the parent node

 * </l>remainingPath: the rest of the path after the segment.

 *

 */
public class XmlPathElement {

	/** The parent node of the segment (always a real Node). */
	public Node node;

	/** The path from the parent node (not including the parent node) to the end. */
	public String path;

	/** The name of the next path segment (may include modifiers):
	 *

	 *
attributes start with @

	 *
wildcard segment names are *

	 *
wildcard selections are name[*]

	 *
specific selections are name[n] for n an integer starting at 0

	 *

	 */
	public String segment;

	/** The path from the segment to the end, not including the segment. */
	public String remainingPath;

	/**
	 * Construct an XmlPathElement that starts from a node.
	 * @param node the current node - the parent of the path. This node
	 * can be a Document, and if so, the path will still start from the root
	 * Element.
	 * @param path the path from the node forward.
	 */
	public XmlPathElement(Node node, String path) {
		this.node = node;
		path = path.replaceAll("\\s","");
		this.path = path;
		segment = path;
		if (segment.startsWith("/")) segment = segment.substring(1);
		int k = segment.indexOf("/",1);
		if (k != -1) segment = segment.substring(0,k);
	}

	/**
	 * Get an XmlPathElement whose parent node is the segment name for
	 * this XmlPathElement. This method is used to create a node in a path
	 * when that node is not present in the Document.
	 * @return a new XmlPathElement child of the current XmlPathElement.
	 */
	public XmlPathElement createPathElement() {
		Element el = node.getOwnerDocument().createElement(getSegmentName());
		node.appendChild(el);
		return new XmlPathElement(el,getRemainingPath());
	}

	/**
	 * Get the sum of all the text child nodes for the parent node of this
	 * XmlPathElement. If the child segment of the parent node is an attribute,
	 * it returns the value of the attribute named by the segment.
	 * @return the text value of the parent node.
	 */
	public String getValue() {
		if (segmentIsAttribute())
			return (node instanceof Element) ?
						((Element)node).getAttribute(segment.substring(1)) :
						null;
		else {
			String value = "";
			Node n = node.getFirstChild();
			while (n != null) {
				if (n instanceof Text) value += n.getNodeValue();
				n = n.getNextSibling();
			}
			return value;
		}
	}

	/**
	 * If the child segment of the parent node is an attribute, set its value.
	 * Otherwise, remove all the text nodes for the parent node and then append
	 * a text node with the supplied value.
	 * @param value the text value to assign.
	 */
	public void setValue(String value) {
		//Attributes are easy; try that first.
		if (segmentIsAttribute()) {
			if (node instanceof Element)
				((Element)node).setAttribute(segment.substring(1),value);
			return;
		}
		//If we get here, we are setting the value of an element.
		//First remove all the text nodes of the element and then
		//append a text node. This will leave all the child elements
		//intact, if the parent element is mixed.
		Node n = node.getFirstChild();

		while (n != null) {
			Node nn = n.getNextSibling();
			if (n instanceof Text) node.removeChild(n);
			n = nn;
		}
		Text text = node.getOwnerDocument().createTextNode(value);
		node.appendChild(text);
	}

	/**
	 * See if the attribute identified by the current segment exists.
	 */
	public boolean attributeExists() {
		if (segmentIsAttribute() && (node instanceof Element)) {
			String name = segment.substring(1);
			return ( ((Element)node).getAttributeNode(name) != null );
		}
		return false;
	}

	/**
	 * Remove the attribute identified by the current segment.
	 */
	public void removeAttribute() {
		if (segmentIsAttribute() && (node instanceof Element))
			((Element)node).removeAttribute(segment.substring(1));
	}

	/**
	 * Remove the parent node.
	 */
	public void removeElement() {
		if (segmentIsAttribute()) return;
		node.getParentNode().removeChild(node);
	}

	/**
	 * Get the list of Element nodes that match the current segment,
	 * with support for wildcards in the segment.
	 * @return the list of children of the parent node that match
	 * the segment.
	 */
	public NodeList getNodeList() {
		XmlPathNodeList pnl = new XmlPathNodeList();
		NodeList nl;
		String name;
		Node node = this.node;
		Node n;
		if (node instanceof Document) {
			node = ((Document)node).getDocumentElement();
			if (segmentIsWildcardElement() || segment.equals(node.getNodeName()))
				pnl.add(node);
		}

		else if ((node instanceof Element) && !segmentIsAttribute()) {
			nl = ((Element)node).getChildNodes();
			if (segmentIsWildcardElement()) {
				for (int i=0; i<nl.getLength(); i++) {
					n = nl.item(i);
					if (n instanceof Element) pnl.add(n);
				}
			}
			else if (segment.startsWith("/")) {
				name = getSegmentName();
				return ((Element)node).getElementsByTagName(name);
			}
			else {
				name = getSegmentName();
				for (int i=0; i<nl.getLength(); i++) {
					n = nl.item(i);
					if ((n instanceof Element) && n.getNodeName().equals(name)) pnl.add(n);
				}
				int index = 0;
				if (segmentContainsQualifier()) {
					String indexString = getSegmentQualifier();
					if (containsWildcard(indexString)) return pnl;
					try { index = Integer.parseInt(indexString); }
					catch (Exception ex) { return new XmlPathNodeList(); }
				}
				n = pnl.item(index);
				pnl = new XmlPathNodeList();
				if (n != null) pnl.add(n);
			}
		}
		return pnl;
	}

	/**
	 * Get the name of the segment, with any qualifiers removed.
	 * @return the name of the segment.
	 */
	public String getSegmentName() {
		String name = segment;
		if (name.startsWith("/")) name = name.substring(1);
		int k = name.indexOf("[");
		if (k == -1) return name.replaceAll("\\]","");
		return name.substring(0,k);
	}

	/**
	 * Get the path following the segment.
	 * @return the remaining path after the segment.
	 */
	public String getRemainingPath() {
		String remPath = path;
		if (remPath.startsWith("//")) remPath = remPath.substring(2);
		else if (remPath.startsWith("/")) remPath = remPath.substring(1);
		int k = remPath.indexOf("/");
		if (k != -1) return remPath.substring(k);
		return "";
	}

	/**
	 * Determine whether the segment is the last one on the path.
	 * @return true if the segment is the last one on the path; false otherwise.
	 */
	public boolean isEndSegment() {
		return segment.equals("");
	}

	/**
	 * Determine whether the segment names an attribute.
	 * @return true if the segment is an attribute; false otherwise.
	 */
	public boolean segmentIsAttribute() {
		return segment.startsWith("@");
	}

	/**
	 * Determine whether the segment is a wildcard, defined as "*".
	 * @return true if the segment is a wildcard; false otherwise.
	 */
	public boolean segmentIsWildcardElement() {
		return segment.equals("*");
	}

	/**
	 * Determine whether the segment contains a wildcard qualifier,
	 * defined as a name followed by [*].
	 * @return true if the segment contains a wildcard qualifier; false otherwise.
	 */
	public boolean segmentContainsWildcard() {
		return containsWildcard(getSegmentQualifier());
	}

	/**
	 * Determine whether the segment contains a qualifier.
	 * @return true if the segment contains a qualifier; false otherwise.
	 */
	public boolean segmentContainsQualifier() {
		return !getSegmentQualifier().equals("");
	}

	/**
	 * Get the text of the qualifier, not including the "[" and "]".
	 * @return the text of the qualifier; otherwise, the empty string.
	 */
	public String getSegmentQualifier() {
		int k = segment.indexOf("[");
		if (k == -1) return "";
		int kk = segment.indexOf("]");
		if (kk < k) return "";
		return segment.substring(k+1,kk).trim();
	}

	//Look for a wildcard anywhere in some text

	private boolean containsWildcard(String text) {
		return (text.indexOf("*") != -1);
	}
}


text:
@interface ANLTableViewController ()

@property (strong, nonatomic) ANLData *nameData;

@end

@implementation ANLTableViewController

#pragma mark - lifeCycle

- (void)viewDidLoad {

    [super viewDidLoad];
    [self setNameData:[ANLData sharedInstance]];
}

-(void)viewWillAppear:(BOOL)animated {

    [super viewWillAppear:animated];
    [self setTitle:@"TableView"];

    [self setScrollViewInheritor:[self tableView]];
    [self setHiddenEnable:YES];
    [self setDuration:0];
}

#pragma mark - dataSource methods

-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {

    return 1;
}

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {

    return 100;
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {

    return 200;
}

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {

    NSString static *identifier = @"reusableCell";
    ANLTableViewCell *cell = (ANLTableViewCell *)[tableView dequeueReusableCellWithIdentifier:identifier];

    NSInteger row = [indexPath row] % 28;
    [[cell lblRow] setText:[[[self nameData] imagesNames] objectAtIndex:row]];
    [[cell imgView] setImage:[UIImage imageNamed:[NSString stringWithFormat:@"image%li", (long)row]]];

    return cell;
}

#pragma mark - Delegate methods

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {

    [tableView deselectRowAtIndexPath:indexPath animated:NO];
}

-(void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {

    [[segue destinationViewController] setImage:[[sender imgView] image]];
    [[segue destinationViewController] setTitle:[[sender lblRow] text]];

    [self showNavigationAndTabBar];
    [self setHiddenEnable:NO];
}

#pragma mark - Actions

- (IBAction)hideButtonPushed:(id)sender {

    [self setHiddenEnable:![self isHiddenEnable]];
    NSString *text = [self isHiddenEnable] ? @"HideOff" : @"HideOn";
    [sender setTitle:text];
}

@end


text:
module TransamMaintenanceProvider
  extend ActiveSupport::Concern

  included do

    # ----------------------------------------------------
    # Associations
    # ----------------------------------------------------

    # Each organization has 0 or more maintenance schedules
    has_many  :maintenance_schedules, :foreign_key => :organization_id

    # Each organization has 0 or more maintenance serice orders
    has_many  :maintenance_service_orders, :foreign_key => :organization_id

    # Each organization has 0 or more maintenance providers
    has_many  :maintenance_providers, :foreign_key => :organization_id

    # ----------------------------------------------------
    # Validations
    # ----------------------------------------------------

  end

  #------------------------------------------------------------------------------
  #
  # Class Methods
  #
  #------------------------------------------------------------------------------

  module ClassMethods

  end

  #------------------------------------------------------------------------------
  #
  # Instance Methods
  #
  #------------------------------------------------------------------------------

  # returns true if this instance has a maintenance schedule, false
  # otherwise
  def has_maintenance_schedules?
    maintenance_schedules.count > 0
  end

end


text:
tags: oi2 work
layout: post
title: "Upcoming job change"
---

Another job change is in the future. I'll be working for
myself -- I grabbed the domain name warefor.com just because
it sounded cool in a development sense, marketing sense and
old english sense. Working primarily on
OpenInteract and implementation projects, which
is excellent. OI development has been stalled for a few
weeks because I'm trying to get a life, so this will
kickstart all that.

More later...

(Originally posted elsewhere)


text:
package org.carlos.jpa.multitable_entity;

import javax.persistence.Entity;
import javax.persistence.SecondaryTable;
import javax.persistence.Table;

import com.google.common.base.MoreObjects;

@Entity
@Table(name = "base")
@SecondaryTable(name = "extensionb")
public class ExtensionB extends Base {

	private Integer extension;

	public ExtensionB() {
		super();
	}

	public ExtensionB( long id, int type, Integer extension ) {
		super( id, type );
		setExtension( extension );
	}

	public Integer getExtension() {
		return extension;
	}

	public void setExtension( Integer extension ) {
		this.extension = extension;
	}

	@Override
	public String toString() {
		return MoreObjects.toStringHelper( this )
				.add( "id", getId() )
				.add( "type", getType() )
				.add( "extension", extension )
				.toString();
	}

}


text:
#ifndef THIRD_PARTY_BLINK_RENDERER_CORE_HTML_FORMS_DATE_INPUT_TYPE_H_
#define THIRD_PARTY_BLINK_RENDERER_CORE_HTML_FORMS_DATE_INPUT_TYPE_H_

#include "third_party/blink/renderer/core/html/forms/base_temporal_input_type.h"

namespace blink {

class DateInputType final : public BaseTemporalInputType {
 public:
  explicit DateInputType(HTMLInputElement&);

 private:
  void CountUsage() override;
  const AtomicString& FormControlType() const override;
  StepRange CreateStepRange(AnyStepHandling) const override;
  bool ParseToDateComponentsInternal(const String&,
                                     DateComponents*) const override;
  bool SetMillisecondToDateComponents(double, DateComponents*) const override;
  void WarnIfValueIsInvalid(const String&) const override;

  // BaseTemporalInputType functions
  String FormatDateTimeFieldsState(const DateTimeFieldsState&) const override;
  void SetupLayoutParameters(DateTimeEditElement::LayoutParameters&,
                             const DateComponents&) const override;
  bool IsValidFormat(bool has_year,
                     bool has_month,
                     bool has_week,
                     bool has_day,
                     bool has_ampm,
                     bool has_hour,
                     bool has_minute,
                     bool has_second) const override;
  String AriaLabelForPickerIndicator() const override;
};

}  // namespace blink

#endif  // THIRD_PARTY_BLINK_RENDERER_CORE_HTML_FORMS_DATE_INPUT_TYPE_H_


text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<title>GuessDate</title>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<meta name="date" content="2018-08-26">
<link rel="stylesheet" type="text/css" href="../stylesheet.css" title="Style">
<link rel="stylesheet" type="text/css" href="../jquery/jquery-ui.css" title="Style">

JavaScript is disabled on your browser.

Skip navigation links

Package

Class

Use

Tree

Deprecated

Index

Help

Prev Class

Next Class

Frames

No Frames

All Classes

SEARCH:
<input type="text" id="search" value="search" disabled="disabled">
<input type="reset" id="reset" value="reset" disabled="disabled">

JavaScript is disabled on your browser.

Summary:

Nested |

Field |

Constr |

Method

Detail:

Field |

Constr |

Method

Package main

Class GuessDate

java.lang.Object

main.GuessDate

public class GuessDate
extends java.lang.Object

Author:

Tony Liang

Method Summary

All Methods Static Methods Concrete Methods

Modifier and Type
Method
Description

static int
getValue(int setNo,
        int row,
        int col)

Returns the date at the given row and column in the given set.

Methods inherited from class java.lang.Object

equals, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait

Method Detail

getValue

public static int getValue(int setNo,
                           int row,
                           int col)

Returns the date at the given row and column in the given set.

                If the set number is not between 1 and 5 inclusive, the date will default to -1.

                If the row and column are not between 0 and 3 inclusive, the date will default to -1.

Parameters:

setNo - set number

row - row

col - column

Returns:

the date at the given row and column in the given set

Skip navigation links

Package

Class

Use

Tree

Deprecated

Index

Help

Prev Class

Next Class

Frames

No Frames

All Classes

JavaScript is disabled on your browser.

Summary:

Nested |

Field |

Constr |

Method

Detail:

Field |

Constr |

Method


text: sap.ui.define(['jquery.sap.global','sap/ui/core/Renderer','sap/ui/layout/form/GridLayoutRenderer'],function(q,R,G){"use strict";var a=R.extend(G);return a;},true);


text:
import vcfpy

# Open input, add FILTER header, and open output file
reader = vcfpy.Reader.from_path("input.vcf.gz")
writer = vcfpy.Writer.from_path("/dev/stdout", reader.header)

# Fetch region 20:1,110,694-1,230,237.  Note that the coordinates
# in the API call are zero-based and describe half-open intervals.
for record in reader.fetch("20", 1110695, 1230237):
    writer.write_record(record)


text:
import React, { Component } from 'react';
import { connect } from 'react-redux';

import { setPassword } from '../../base/conference';
import { translate } from '../../base/i18n';

/**
 * A React {@code Component} for locking a JitsiConference with a password.
 */
class AddPasswordForm extends Component {
    /**
     * {@code AddPasswordForm}'s property types.
     *
     * @static
     */
    static propTypes = {
        /**
         * The JitsiConference on which to lock and set a password.
         *
         * @type {JitsiConference}
         */
        conference: React.PropTypes.object,

        /**
         * Invoked to set a password on the conference.
         */
        dispatch: React.PropTypes.func,

        /**
         * Invoked to obtain translated strings.
         */
        t: React.PropTypes.func
    };

    /**
     * Initializes a new {@code AddPasswordForm} instance.
     *
     * @param {Object} props - The read-only properties with which the new
     * instance is to be initialized.
     */
    constructor(props) {
        super(props);

        this.state = {
            /**
             * The current value to display in {@code AddPasswordForm}
             * component's input field. The value is also used as the desired
             * new password when creating a {@code setPassword} action.
             *
             * @type {string}
             */
            password: ''
        };

        // Bind event handlers so they are only bound once for every instance.
        this._onKeyDown = this._onKeyDown.bind(this);
        this._onPasswordChange = this._onPasswordChange.bind(this);
        this._onSubmit = this._onSubmit.bind(this);
    }

    /**
     * Implements React's {@link Component#render()}.
     *
     * @inheritdoc
     * @returns {ReactElement}
     */
    render() {
        const { t } = this.props;

        return (
            <div
                className = 'form-control'
                onSubmit = { this._onSubmit } >
                <div className = 'form-control__container'>
                    <input
                        autoFocus = { true }
                        className = 'input-control'
                        id = 'newPasswordInput'
                        onChange = { this._onPasswordChange }
                        onKeyDown = { this._onKeyDown }
                        placeholder = { t('dialog.createPassword') }
                        type = 'text' />
                    <button
                        className = 'button-control button-control_light'
                        disabled = { !this.state.password }
                        id = 'addPasswordBtn'
                        onClick = { this._onSubmit }
                        type = 'button'>
                        { t('dialog.add') }
                    </button>
                </div>
            </div>
        );
    }

    /**
     * Mimics form behavior by listening for enter key press and submitting the
     * entered password.
     *
     * @param {Object} event - DOM Event for keydown.
     * @private
     * @returns {void}
     */
    _onKeyDown(event) {
        event.stopPropagation();

        if (event.keyCode === /* Enter */ 13) {
            this._onSubmit();
        }
    }

    /**
     * Updates the internal state of the entered password.
     *
     * @param {Object} event - DOM Event for value change.
     * @private
     * @returns {void}
     */
    _onPasswordChange(event) {
        this.setState({ password: event.target.value });
    }

    /**
     * Dispatches a request to lock the conference with a password.
     *
     * @private
     * @returns {void}
     */
    _onSubmit() {
        if (!this.state.password) {
            return;
        }

        const { conference } = this.props;

        this.props.dispatch(setPassword(
            conference,
            conference.lock,
            this.state.password
        ));

        this.setState({ password: '' });
    }
}

export default translate(connect()(AddPasswordForm));


text:
#ifndef INCLUDED_flash_utils_Endian
#define INCLUDED_flash_utils_Endian

#ifndef HXCPP_H
#include <hxcpp.h>
#endif

HX_DECLARE_CLASS2(flash,utils,Endian)
namespace flash{
namespace utils{

class HXCPP_CLASS_ATTRIBUTES  Endian_obj : public hx::Object{
	public:
		typedef hx::Object super;
		typedef Endian_obj OBJ_;
		Endian_obj();
		Void __construct();

	public:
		static hx::ObjectPtr< Endian_obj > __new();
		static Dynamic __CreateEmpty();
		static Dynamic __Create(hx::DynamicArray inArgs);
		~Endian_obj();

		HX_DO_RTTI;
		static void __boot();
		static void __register();
		void __Mark(HX_MARK_PARAMS);
		void __Visit(HX_VISIT_PARAMS);
		::String __ToString() const { return HX_CSTRING("Endian"); }

};

} // end namespace flash
} // end namespace utils

#endif /* INCLUDED_flash_utils_Endian */


text:
package edu.umd.mith.topic

package object util {
  /** Symmetrized Kullback-Liebler divergence.
    *
    * For a very simple representation of two probability distributions.
    */
  def skld[A](ps: Iterable[(Double, Double)]): Double = ps.map {
    case (x, y) => x * math.log(x / y) + y * math.log(y / x)
  }.sum / 2.0
}


text:
package org.jbehave.core.junit.weld;

import org.jbehave.core.configuration.AnnotationBuilder;
import org.jbehave.core.configuration.weld.WeldAnnotationBuilder;
import org.jbehave.core.configuration.weld.WeldBootstrap;
import org.jbehave.core.junit.AnnotatedEmbedderRunner;
import org.junit.runners.model.InitializationError;

/**
 * AnnotatedEmbedderRunner that uses {@link WeldAnnotationBuilder}.
 *
 * @author Aaron Walker
 */
public class WeldAnnotatedEmbedderRunner extends AnnotatedEmbedderRunner {
    private WeldAnnotationBuilder annotationBuilder;
    private WeldBootstrap container;

    public WeldAnnotatedEmbedderRunner(Class<?> testClass) throws InitializationError {
        super(testClass);

        container = new WeldBootstrap();
        container.initialize();

        this.annotationBuilder = container.findAnnotationBuilder(testClass());
    }

    public AnnotationBuilder annotationBuilder() {
        return annotationBuilder;
    }
}


text:
using System;
using Orleans.Runtime;
using System.Runtime.Serialization;

namespace Orleans.Streams
{
    /// <summary>
    /// Exception indicates that the requested data is not available.
    /// </summary>
    [Serializable]
    public class DataNotAvailableException : OrleansException
    {
        public DataNotAvailableException() : this("Data not found") { }
        public DataNotAvailableException(string message) : base(message) { }
        public DataNotAvailableException(string message, Exception inner) : base(message, inner) { }

        public DataNotAvailableException(SerializationInfo info, StreamingContext context)
            : base(info, context)
        {
        }
    }
}


text:
module RailsAdmin
  module Models
    module Setup
      module CrossSharedCollectionAdmin
        extend ActiveSupport::Concern

        included do
          rails_admin do
            weight 010
            label 'Shared Collection'
            navigation_label 'Integrations'
            navigation_icon 'fa fa-puzzle-piece'
            object_label_method :versioned_name

            public_access true
            extra_associations do
              ::Setup::Collection.reflect_on_all_associations(:has_and_belongs_to_many).collect do |association|
                association = association.dup
                association[:name] = "data_#{association.name}".to_sym
                RailsAdmin::Adapters::Mongoid::Association.new(association, abstract_model.model)
              end
            end

            index_template_name :shared_collection_grid
            index_link_icon 'icon-th-large'

            register_instance_option(:discard_submit_buttons) do
              !(a = bindings[:action]) || a.key != :edit
            end

            asynchronous_persistence true

            instance_eval &RailsAdmin::Models::Setup::CollectionFieldsConfigAdmin::FIELDS_CONFIG
          end
        end
      end
    end
  end
end


text:
#include <string.h>
#include <stdio.h>
#include <stdlib.h>
#include <stdint.h>
#include <inttypes.h>
#include <stdarg.h>
#include <errno.h>
#include <sys/queue.h>

#include <rte_common.h>
#include <rte_log.h>
#include <rte_debug.h>
#include <rte_memory.h>
#include <rte_memzone.h>
#include <rte_launch.h>
#include <rte_cycles.h>
#include <rte_eal.h>
#include <rte_per_lcore.h>
#include <rte_lcore.h>
#include <rte_atomic.h>
#include <rte_branch_prediction.h>
#include <rte_ring.h>
#include <rte_mempool.h>
#include <rte_spinlock.h>
#include <rte_malloc.h>

#include "test.h"

/*
 * Mempool
 * =======
 *
 * Basic tests: done on one core with and without cache:
 *
 *    - Get one object, put one object
 *    - Get two objects, put two objects
 *    - Get all objects, test that their content is not modified and
 *      put them back in the pool.
 */

#define N 65536
#define TIME_S 5
#define MEMPOOL_ELT_SIZE 2048
#define MAX_KEEP 128
#define MEMPOOL_SIZE ((RTE_MAX_LCORE*(MAX_KEEP+RTE_MEMPOOL_CACHE_MAX_SIZE))-1)

static struct rte_mempool *mp;
static struct rte_mempool *mp_cache, *mp_nocache;

static rte_atomic32_t synchro;

/*
 * save the object number in the first 4 bytes of object data. All
 * other bytes are set to 0.
 */
static void
my_obj_init(struct rte_mempool *mp, __attribute__((unused)) void *arg,
	    void *obj, unsigned i)
{
	uint32_t *objnum = obj;
	memset(obj, 0, mp->elt_size);
	*objnum = i;
}

/* basic tests (done on one core) */
static int
test_mempool_basic(void)
{
	uint32_t *objnum;
	void **objtable;
	void *obj, *obj2;
	char *obj_data;
	int ret = 0;
	unsigned i, j;

	/* dump the mempool status */
	rte_mempool_dump(stdout, mp);

	printf("get an object\n");
	if (rte_mempool_get(mp, &obj) < 0)
		return -1;
	rte_mempool_dump(stdout, mp);

	/* tests that improve coverage */
	printf("get object count\n");
	if (rte_mempool_count(mp) != MEMPOOL_SIZE - 1)
		return -1;

	printf("get private data\n");
	if (rte_mempool_get_priv(mp) !=
			(char*) mp + MEMPOOL_HEADER_SIZE(mp, mp->pg_num))
		return -1;

	printf("get physical address of an object\n");
	if (MEMPOOL_IS_CONTIG(mp) &&
			rte_mempool_virt2phy(mp, obj) !=
			(phys_addr_t) (mp->phys_addr +
			(phys_addr_t) ((char*) obj - (char*) mp)))
		return -1;

	printf("put the object back\n");
	rte_mempool_put(mp, obj);
	rte_mempool_dump(stdout, mp);

	printf("get 2 objects\n");
	if (rte_mempool_get(mp, &obj) < 0)
		return -1;
	if (rte_mempool_get(mp, &obj2) < 0) {
		rte_mempool_put(mp, obj);
		return -1;
	}
	rte_mempool_dump(stdout, mp);

	printf("put the objects back\n");
	rte_mempool_put(mp, obj);
	rte_mempool_put(mp, obj2);
	rte_mempool_dump(stdout, mp);

	/*
	 * get many objects: we cannot get them all because the cache
	 * on other cores may not be empty.
	 */
	objtable = malloc(MEMPOOL_SIZE * sizeof(void *));
	if (objtable == NULL) {
		return -1;
	}

	for (i=0; i<MEMPOOL_SIZE; i++) {
		if (rte_mempool_get(mp, &objtable[i]) < 0)
			break;
	}

	/*
	 * for each object, check that its content was not modified,
	 * and put objects back in pool
	 */
	while (i--) {
		obj = objtable[i];
		obj_data = obj;
		objnum = obj;
		if (*objnum > MEMPOOL_SIZE) {
			printf("bad object number\n");
			ret = -1;
			break;
		}
		for (j=sizeof(*objnum); j<mp->elt_size; j++) {
			if (obj_data[j] != 0)
				ret = -1;
		}

		rte_mempool_put(mp, objtable[i]);
	}

	free(objtable);
	if (ret == -1)
		printf("objects were modified!\n");

	return ret;
}

static int test_mempool_creation_with_exceeded_cache_size(void)
{
	struct rte_mempool *mp_cov;

	mp_cov = rte_mempool_create("test_mempool_creation_with_exceeded_cache_size", MEMPOOL_SIZE,
					      MEMPOOL_ELT_SIZE,
					      RTE_MEMPOOL_CACHE_MAX_SIZE + 32, 0,
					      NULL, NULL,
					      my_obj_init, NULL,
					      SOCKET_ID_ANY, 0);
	if(NULL != mp_cov) {
		return -1;
	}

	return 0;
}

static struct rte_mempool *mp_spsc;
static rte_spinlock_t scsp_spinlock;
static void *scsp_obj_table[MAX_KEEP];

/*
 * single producer function
 */
static int test_mempool_single_producer(void)
{
	unsigned int i;
	void *obj = NULL;
	uint64_t start_cycles, end_cycles;
	uint64_t duration = rte_get_timer_hz() * 8;

	start_cycles = rte_get_timer_cycles();
	while (1) {
		end_cycles = rte_get_timer_cycles();
		/* duration uses up, stop producing */
		if (start_cycles + duration < end_cycles)
			break;
		rte_spinlock_lock(&scsp_spinlock);
		for (i = 0; i < MAX_KEEP; i ++) {
			if (NULL != scsp_obj_table[i]) {
				obj = scsp_obj_table[i];
				break;
			}
		}
		rte_spinlock_unlock(&scsp_spinlock);
		if (i >= MAX_KEEP) {
			continue;
		}
		if (rte_mempool_from_obj(obj) != mp_spsc) {
			printf("test_mempool_single_producer there is an obj not owned by this mempool\n");
			return -1;
		}
		rte_mempool_sp_put(mp_spsc, obj);
		rte_spinlock_lock(&scsp_spinlock);
		scsp_obj_table[i] = NULL;
		rte_spinlock_unlock(&scsp_spinlock);
	}

	return 0;
}

/*
 * single consumer function
 */
static int test_mempool_single_consumer(void)
{
	unsigned int i;
	void * obj;
	uint64_t start_cycles, end_cycles;
	uint64_t duration = rte_get_timer_hz() * 5;

	start_cycles = rte_get_timer_cycles();
	while (1) {
		end_cycles = rte_get_timer_cycles();
		/* duration uses up, stop consuming */
		if (start_cycles + duration < end_cycles)
			break;
		rte_spinlock_lock(&scsp_spinlock);
		for (i = 0; i < MAX_KEEP; i ++) {
			if (NULL == scsp_obj_table[i])
				break;
		}
		rte_spinlock_unlock(&scsp_spinlock);
		if (i >= MAX_KEEP)
			continue;
		if (rte_mempool_sc_get(mp_spsc, &obj) < 0)
			break;
		rte_spinlock_lock(&scsp_spinlock);
		scsp_obj_table[i] = obj;
		rte_spinlock_unlock(&scsp_spinlock);
	}

	return 0;
}

/*
 * test function for mempool test based on singple consumer and single producer, can run on one lcore only
 */
static int test_mempool_launch_single_consumer(__attribute__((unused)) void *arg)
{
	return test_mempool_single_consumer();
}

static void my_mp_init(struct rte_mempool * mp, __attribute__((unused)) void * arg)
{
	printf("mempool name is %s\n", mp->name);
	/* nothing to be implemented here*/
	return ;
}

/*
 * it tests the mempool operations based on singple producer and single consumer
 */
static int
test_mempool_sp_sc(void)
{
	int ret = 0;
	unsigned lcore_id = rte_lcore_id();
	unsigned lcore_next;

	/* create a mempool with single producer/consumer ring */
	if (NULL == mp_spsc) {
		mp_spsc = rte_mempool_create("test_mempool_sp_sc", MEMPOOL_SIZE,
						MEMPOOL_ELT_SIZE, 0, 0,
						my_mp_init, NULL,
						my_obj_init, NULL,
						SOCKET_ID_ANY, MEMPOOL_F_NO_CACHE_ALIGN | MEMPOOL_F_SP_PUT | MEMPOOL_F_SC_GET);
		if (NULL == mp_spsc) {
			return -1;
		}
	}
	if (rte_mempool_lookup("test_mempool_sp_sc") != mp_spsc) {
		printf("Cannot lookup mempool from its name\n");
		return -1;
	}
	lcore_next = rte_get_next_lcore(lcore_id, 0, 1);
	if (RTE_MAX_LCORE <= lcore_next)
		return -1;
	if (rte_eal_lcore_role(lcore_next) != ROLE_RTE)
		return -1;
	rte_spinlock_init(&scsp_spinlock);
	memset(scsp_obj_table, 0, sizeof(scsp_obj_table));
	rte_eal_remote_launch(test_mempool_launch_single_consumer, NULL, lcore_next);
	if(test_mempool_single_producer() < 0)
		ret = -1;

	if(rte_eal_wait_lcore(lcore_next) < 0)
		ret = -1;

	return ret;
}

/*
 * it tests some more basic of mempool
 */
static int
test_mempool_basic_ex(struct rte_mempool * mp)
{
	unsigned i;
	void **obj;
	void *err_obj;
	int ret = -1;

	if (mp == NULL)
		return ret;

	obj = rte_calloc("test_mempool_basic_ex", MEMPOOL_SIZE , sizeof(void *), 0);
	if (obj == NULL) {
		printf("test_mempool_basic_ex fail to rte_malloc\n");
		return ret;
	}
	printf("test_mempool_basic_ex now mempool (%s) has %u free entries\n", mp->name, rte_mempool_free_count(mp));
	if (rte_mempool_full(mp) != 1) {
		printf("test_mempool_basic_ex the mempool is not full but it should be\n");
		goto fail_mp_basic_ex;
	}

	for (i = 0; i < MEMPOOL_SIZE; i ++) {
		if (rte_mempool_mc_get(mp, &obj[i]) < 0) {
			printf("fail_mp_basic_ex fail to get mempool object for [%u]\n", i);
			goto fail_mp_basic_ex;
		}
	}
	if (rte_mempool_mc_get(mp, &err_obj) == 0) {
		printf("test_mempool_basic_ex get an impossible obj from mempool\n");
		goto fail_mp_basic_ex;
	}
	printf("number: %u\n", i);
	if (rte_mempool_empty(mp) != 1) {
		printf("test_mempool_basic_ex the mempool is not empty but it should be\n");
		goto fail_mp_basic_ex;
	}

	for (i = 0; i < MEMPOOL_SIZE; i ++) {
		rte_mempool_mp_put(mp, obj[i]);
	}
	if (rte_mempool_full(mp) != 1) {
		printf("test_mempool_basic_ex the mempool is not full but it should be\n");
		goto fail_mp_basic_ex;
	}

	ret = 0;

fail_mp_basic_ex:
	if (obj != NULL)
		rte_free((void *)obj);

	return ret;
}

static int
test_mempool_same_name_twice_creation(void)
{
	struct rte_mempool *mp_tc;

	mp_tc = rte_mempool_create("test_mempool_same_name_twice_creation", MEMPOOL_SIZE,
						MEMPOOL_ELT_SIZE, 0, 0,
						NULL, NULL,
						NULL, NULL,
						SOCKET_ID_ANY, 0);
	if (NULL == mp_tc)
		return -1;

	mp_tc = rte_mempool_create("test_mempool_same_name_twice_creation", MEMPOOL_SIZE,
						MEMPOOL_ELT_SIZE, 0, 0,
						NULL, NULL,
						NULL, NULL,
						SOCKET_ID_ANY, 0);
	if (NULL != mp_tc)
		return -1;

	return 0;
}

/*
 * BAsic test for mempool_xmem functions.
 */
static int
test_mempool_xmem_misc(void)
{
	uint32_t elt_num, total_size;
	size_t sz;
	ssize_t usz;

	elt_num = MAX_KEEP;
	total_size = rte_mempool_calc_obj_size(MEMPOOL_ELT_SIZE, 0, NULL);
	sz = rte_mempool_xmem_size(elt_num, total_size, MEMPOOL_PG_SHIFT_MAX);

	usz = rte_mempool_xmem_usage(NULL, elt_num, total_size, 0, 1,
		MEMPOOL_PG_SHIFT_MAX);

	if(sz != (size_t)usz)  {
		printf("failure @ %s: rte_mempool_xmem_usage(%u, %u) "
			"returns: %#zx, while expected: %#zx;\n",
			__func__, elt_num, total_size, sz, (size_t)usz);
		return (-1);
	}

	return (0);
}

static int
test_mempool(void)
{
	rte_atomic32_init(&synchro);

	/* create a mempool (without cache) */
	if (mp_nocache == NULL)
		mp_nocache = rte_mempool_create("test_nocache", MEMPOOL_SIZE,
						MEMPOOL_ELT_SIZE, 0, 0,
						NULL, NULL,
						my_obj_init, NULL,
						SOCKET_ID_ANY, 0);
	if (mp_nocache == NULL)
		return -1;

	/* create a mempool (with cache) */
	if (mp_cache == NULL)
		mp_cache = rte_mempool_create("test_cache", MEMPOOL_SIZE,
					      MEMPOOL_ELT_SIZE,
					      RTE_MEMPOOL_CACHE_MAX_SIZE, 0,
					      NULL, NULL,
					      my_obj_init, NULL,
					      SOCKET_ID_ANY, 0);
	if (mp_cache == NULL)
		return -1;

	/* retrieve the mempool from its name */
	if (rte_mempool_lookup("test_nocache") != mp_nocache) {
		printf("Cannot lookup mempool from its name\n");
		return -1;
	}

	rte_mempool_list_dump(stdout);

	/* basic tests without cache */
	mp = mp_nocache;
	if (test_mempool_basic() < 0)
		return -1;

	/* basic tests with cache */
	mp = mp_cache;
	if (test_mempool_basic() < 0)
		return -1;

	/* more basic tests without cache */
	if (test_mempool_basic_ex(mp_nocache) < 0)
		return -1;

	/* mempool operation test based on single producer and single comsumer */
	if (test_mempool_sp_sc() < 0)
		return -1;

	if (test_mempool_creation_with_exceeded_cache_size() < 0)
		return -1;

	if (test_mempool_same_name_twice_creation() < 0)
		return -1;

	if (test_mempool_xmem_misc() < 0)
		return -1;

	rte_mempool_list_dump(stdout);

	return 0;
}

static struct test_command mempool_cmd = {
	.command = "mempool_autotest",
	.callback = test_mempool,
};
REGISTER_TEST_COMMAND(mempool_cmd);


text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<title>AbstractListDecorator</title>
<meta name="date" content="2019-07-09">
<link rel="stylesheet" type="text/css" href="../../../../../stylesheet.css" title="Style">

JavaScript is disabled on your browser.

Skip navigation links

Overview

Package

Class

Tree

Deprecated

Index

Help

Prev Class

Next Class

Frames

No Frames

All Classes

Summary:

Nested |

Field |

Constr |

Method

Detail:

Field |

Constr |

Method

de.mrapp.android.adapter.decorator

Class AbstractListDecorator<DataType>

java.lang.Object

de.mrapp.android.util.view.AbstractViewHolderAdapter

de.mrapp.android.adapter.decorator.AbstractDecorator

de.mrapp.android.adapter.decorator.AbstractListDecorator<DataType>

Type Parameters:

DataType - The type of the adapter's underlying data

Direct Known Subclasses:

ListDecorator, SelectableListDecorator

public abstract class AbstractListDecorator<DataType>
extends AbstractDecorator

An abstract base class for all decorators, which should allow to customize the appearance of the
 view, which is used to visualize the items of a ListAdapter, SingleChoiceListAdapter or MultipleChoiceListAdapter.

Since:

0.2.0

Author:

Michael Rapp

Constructor Summary

Constructors

Constructor and Description

AbstractListDecorator()

Method Summary

All Methods Instance Methods Abstract Methods Concrete Methods

Modifier and Type
Method and Description

int
getViewType(DataType item)

The method which is invoked in order to retrieve the view type of a specific item, which is
 about to be visualized.

int
getViewTypeCount()

Returns the number of view types, which are used by the decorator in order to visualize
 items.

android.view.View
inflateView(android.view.LayoutInflater inflater,
           android.view.ViewGroup parent,
           DataType item)

The method which is invoked by an adapter to inflate the view, which should be used to
 visualize a specific item.

abstract android.view.View
onInflateView(android.view.LayoutInflater inflater,
             android.view.ViewGroup parent,
             int viewType)

The method which is invoked, when a view, which is used to visualize an item, should be
 inflated.

Methods inherited from class de.mrapp.android.adapter.decorator.AbstractDecorator

adaptViewState, areChildrenViewStatesAdapted, getView, isViewStateAdapted

Methods inherited from class de.mrapp.android.util.view.AbstractViewHolderAdapter

findViewById, setCurrentParentView

Methods inherited from class java.lang.Object

clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait

Constructor Detail

AbstractListDecorator

public AbstractListDecorator()

Method Detail

getViewType

public int getViewType(@NonNull
                       DataType item)

The method which is invoked in order to retrieve the view type of a specific item, which is
 about to be visualized. This method has to be overridden by custom decorators which should be
 able to visualize some items optically divergent from others, returning a different integer
 constant for each type.

Parameters:

item - The item, which should be visualized, as an instance of the generic type DataType.
         The item may not be null

Returns:

The view type of the item, which is about to be visualized, as an Integer
 value

getViewTypeCount

public int getViewTypeCount()

Returns the number of view types, which are used by the decorator in order to visualize
 items. This method has to be overridden by custom decorators in order to return a value,
 which is consistent with the implementation of the getViewType-method.

Returns:

The number of view types, which are used by the decorator in order to visualize
 items, as an Integer value

inflateView

public final android.view.View inflateView(@NonNull
                                           android.view.LayoutInflater inflater,
                                           @Nullable
                                           android.view.ViewGroup parent,
                                           @NonNull
                                           DataType item)

The method which is invoked by an adapter to inflate the view, which should be used to
 visualize a specific item.

Parameters:

inflater - The inflater, which should be used to inflate the view, as an instance of the class
         LayoutInflater. The inflater may not be null

parent - The parent view of the view, which should be inflated, as an instance of the class
         ViewGroup or null, if no parent view is available

item - The item, which should be visualized, as an instance of the generic type DataType.
         The item may not be null

Returns:

The view, which has been inflated, as an instance of the class View. The view
 may not be null

onInflateView

@NonNull
public abstract android.view.View onInflateView(@NonNull
                                                         android.view.LayoutInflater inflater,
                                                         @Nullable
                                                         android.view.ViewGroup parent,
                                                         int viewType)

The method which is invoked, when a view, which is used to visualize an item, should be
 inflated.

Parameters:

inflater - The inflater, which should be used to inflate the view, as an instance of the class
         LayoutInflater. The inflater may not be null

parent - The parent view of the view, which should be inflated, as an instance of the class
         ViewGroup or null, if no parent view is available

viewType - The view type of the item, which should be visualized, as an Integer value

Returns:

The view, which has been inflated, as an instance of the class View. The view
 may not be null

Skip navigation links

Overview

Package

Class

Tree

Deprecated

Index

Help

Prev Class

Next Class

Frames

No Frames

All Classes

Summary:

Nested |

Field |

Constr |

Method

Detail:

Field |

Constr |

Method


text:
package com.amazonaws.services.iotanalytics.model;

import java.io.Serializable;
import javax.annotation.Generated;
import com.amazonaws.protocol.StructuredPojo;
import com.amazonaws.protocol.ProtocolMarshaller;

/**
 *

 * Used to store data store data in an S3 bucket managed by the AWS IoT Analytics service.
 *

 *
 * @see AWS API Documentation
 */
@Generated("com.amazonaws:aws-java-sdk-code-generator")
public class ServiceManagedDatastoreS3StorageSummary implements Serializable, Cloneable, StructuredPojo {

    /**
     * Returns a string representation of this object. This is useful for testing and debugging. Sensitive data will be
     * redacted from this string using a placeholder value.
     *
     * @return A string representation of this object.
     *
     * @see java.lang.Object#toString()
     */
    @Override
    public String toString() {
        StringBuilder sb = new StringBuilder();
        sb.append("{");
        sb.append("}");
        return sb.toString();
    }

    @Override
    public boolean equals(Object obj) {
        if (this == obj)
            return true;
        if (obj == null)
            return false;

        if (obj instanceof ServiceManagedDatastoreS3StorageSummary == false)
            return false;
        ServiceManagedDatastoreS3StorageSummary other = (ServiceManagedDatastoreS3StorageSummary) obj;
        return true;
    }

    @Override
    public int hashCode() {
        final int prime = 31;
        int hashCode = 1;

        return hashCode;
    }

    @Override
    public ServiceManagedDatastoreS3StorageSummary clone() {
        try {
            return (ServiceManagedDatastoreS3StorageSummary) super.clone();
        } catch (CloneNotSupportedException e) {
            throw new IllegalStateException("Got a CloneNotSupportedException from Object.clone() " + "even though we're Cloneable!", e);
        }
    }

    @com.amazonaws.annotation.SdkInternalApi
    @Override
    public void marshall(ProtocolMarshaller protocolMarshaller) {
        com.amazonaws.services.iotanalytics.model.transform.ServiceManagedDatastoreS3StorageSummaryMarshaller.getInstance().marshall(this, protocolMarshaller);
    }
}


text:
<?php

namespace Concrete\Core\StyleCustomizer\Style\Value;

class FontFamilyValue extends Value
{
    /**
     * @var string
     */
    protected $fontFamily;

    /**
     * FontFamilyValue constructor.
     * @param string $fontFamily
     */
    public function __construct(string $fontFamily)
    {
        $this->fontFamily = $fontFamily;
    }

    /**
     * @return string
     */
    public function getFontFamily(): string
    {
        return $this->fontFamily;
    }

    /**
     * @param string $fontFamily
     */
    public function setFontFamily(string $fontFamily): void
    {
        $this->fontFamily = $fontFamily;
    }

    #[\ReturnTypeWillChange]
    public function jsonSerialize()
    {
        return [
            'fontFamily' => $this->getFontFamily(),
        ];
    }

}