text:
//
// Copyright (c) .NET Foundation and Contributors
// Portions Copyright (c) Microsoft Corporation.  All rights reserved.
// See LICENSE file in the project root for full license information.
//

#ifndef GRAPHICS_H
#define GRAPHICS_H

#include <string.h>

#include "nanoCLR_Types.h"
#include "nanoCLR_Interop.h"
#include "nanoCLR_Runtime.h"
#include "nanoCLR_PlatformDef.h"
#include "nanoCLR_Runtime__HeapBlock.h"
#include "nanoCLR_Checks.h"
#include "nanoPAL.h"
#include "nanoHAL_Time.h"
#include "nanoPAL_Events.h"
#include "nanoHAL.h"
#include "nanoHAL_v2.h"
#include "corlib_native.h"

#include "GraphicsMemoryHeap.h"

#include "nf_rt_events_native.h"
#include "nf_errors_exceptions.h"

#include "Display.h"

#define UNUSED(X) (void)X /* To avoid gcc/g++ warnings */

// ???? Redefined below but gets past the compile error of not defined
// CLR_GFX_Font needs CLR_GFX_Bitmap  and CLR_GFX_Bitmap needs CLR_GFX_Font
struct CLR_GFX_Bitmap;
struct CLR_GFX_Font;

#define __min(a, b) (((a) < (b)) ? (a) : (b))
#define abs(a)      (((a) < 0) ? -(a) : (a))
struct CLR_GFX_BitmapDescription
{
    static const CLR_UINT16 c_ReadOnly = 0x0001;
    static const CLR_UINT16 c_Compressed = 0x0002;
    static const CLR_UINT8 c_CompressedRun = 0x80;
    static const CLR_UINT8 c_CompressedRunSet = 0x40;
    static const CLR_UINT8 c_CompressedRunLengthMask = 0x3f;
    static const CLR_UINT8 c_UncompressedRunLength = 7;
    static const CLR_UINT8 c_CompressedRunOffset = c_UncompressedRunLength + 1;

    // static // Note that these type definitions has to match the ones defined in Bitmap.BitmapImageType enum defined
    // in Graphics.cs
    static const CLR_UINT8 c_Type_nanoCLRBitmap = 0;
    static const CLR_UINT8 c_TypeGif = 1;
    static const CLR_UINT8 c_TypeJpeg = 2;
    static const CLR_UINT8 c_TypeBmp = 3; // The windows .bmp format

    // When m_bitsPerPixel == c_NativeBpp it means that the data in this bitmap is in the native PAL graphics
    // format, the exact bit depth and format is something the CLR is abstracted away from.
    static const int c_NativeBpp = 0;
    static const CLR_INT32 c_MaxWidth = 524287; // 0x7ffff;
    static const CLR_INT32 c_MaxHeight = 65535; // 0x0ffff;

    CLR_UINT32 m_width;
    CLR_UINT32 m_height;
    CLR_UINT16 m_flags;
    CLR_UINT8 m_bitsPerPixel;
    CLR_UINT8 m_type;

    bool BitmapDescription_Initialize(int width, int height, int bitsPerPixel);
    int GetTotalSize() const;
    int GetWidthInWords() const;
};
struct CLR_GFX_FontMetrics
{
    CLR_UINT16 m_height;
    CLR_INT16 m_offset; // The bitmap could be actually smaller than the logical font height.
    CLR_INT16 m_ascent;
    CLR_INT16 m_descent;
    CLR_INT16 m_internalLeading;
    CLR_INT16 m_externalLeading;
    CLR_INT16 m_aveCharWidth;
    CLR_INT16 m_maxCharWidth;
};
struct CLR_GFX_FontMetricsExtended : public CLR_GFX_FontMetrics
{
    int m_offsetX;
    int m_offsetY;
    int m_marginLeft;
    int m_marginRight;
};
struct CLR_GFX_FontDescription
{
    static const CLR_UINT16 c_Bold = 0x0001;
    static const CLR_UINT16 c_Italic = 0x0002;
    static const CLR_UINT16 c_Underline = 0x0004;
    static const CLR_UINT16 c_FontEx = 0x0008;
    static const CLR_UINT16 c_AntiAliasMask = 0x00F0;
    static const CLR_UINT16 c_AntiAliasShift = 4;

    CLR_GFX_FontMetrics m_metrics;
    CLR_UINT16 m_ranges;
    CLR_UINT16 m_characters;
    CLR_UINT16 m_flags;
    CLR_UINT16 m_pad;

    CLR_UINT32 GetRangeSize() const;
    CLR_UINT32 GetCharacterSize() const;
    CLR_UINT32 GetCharacterExSize() const;
    CLR_UINT32 GetRangeExSize() const;
};
struct CLR_GFX_FontDescriptionEx
{
    CLR_UINT32 m_antiAliasSize;
    CLR_UINT32 GetAntiAliasSize() const;
};
struct CLR_GFX_FontCharacterRange
{
    CLR_UINT32 m_indexOfFirstFontCharacter;
    CLR_UINT16 m_firstChar;
    CLR_UINT16 m_lastChar;
    CLR_UINT32 m_rangeOffset; // the x-offset into the bitmap for this range.
};
struct CLR_GFX_FontCharacterRangeEx
{
    CLR_UINT32 m_offsetAntiAlias;
};
struct CLR_GFX_FontCharacter
{
    CLR_UINT16 m_offset;
    CLR_INT8 m_marginLeft;
    CLR_INT8 m_marginRight;
};
struct CLR_GFX_FontCharacterEx
{
    static const CLR_UINT16 c_offsetNoAntiAlias = 0xFFFF;
    CLR_UINT16 m_offsetAntiAlias;
};
struct CLR_GFX_FontCharacterInfo
{
    bool isValid;
    CLR_INT8 marginLeft;
    CLR_INT8 marginRight;
    CLR_UINT32 offset;
    CLR_UINT16 innerWidth;
    CLR_UINT16 width;
    CLR_UINT16 height;
    CLR_UINT8 *antiAlias;
    CLR_UINT8 iAntiAlias;
};
struct GFX_Rect
{
    int left;
    int top;
    int right;
    int bottom;

    int Width() const
    {
        return right - left + 1;
    }
    int Height() const
    {
        return bottom - top + 1;
    }
};
struct GFX_Brush
{
    // GFX_Brush is a structure to capture all information needed to perform a fill.
    // Note:
    // To create a solid brush, make gradientStartColor == gradientEndColor
    // To create a empty (no fill) brush, make opacity = c_ColorTransparent
    // To create a linear gradient brush, fill in the start and end information

    CLR_UINT32 gradientStartColor;
    int gradientStartX;
    int gradientStartY;
    CLR_UINT32 gradientEndColor;
    int gradientEndX;
    int gradientEndY;
    CLR_UINT16 opacity;
};
struct GFX_Pen
{
    CLR_UINT32 color;
    int thickness;
};
struct Draw4PointsRoundedRectParams
{
    int x1;
    int y1;
    int x2;
    int y2;
    GFX_Pen *pen;
    GFX_Brush *brush;
    int lastFillOffsetY;
};
struct Draw4PointsEllipseParams
{
    int centerX;
    int centerY;
    GFX_Pen *pen;
    GFX_Brush *brush;
    int lastFillOffsetY;
};
struct ConvertToNativeHelperParam
{
    CLR_UINT32 *srcFirstWord;
    CLR_UINT32 srcWidthInWords;
    union {
        CLR_UINT32 *srcCur1BppWord;
        CLR_UINT16 *srcCur16BppPixel;
    };
    CLR_UINT32 srcCur1BppPixelMask;
};
struct RADIAN
{
    float cos;
    float sin;
};
struct DivHelper
{
    // DivHelper is a support class used internally to assist calculating gradient fills
    // DivHelper uses the midpoint technique to perform integer division using only addition and few multiplications.
    // This is useful when we need to calculate y = a*x / b + c over a range of x values. All we need is a starting
    // point where the value of y is known.
    // Usage:
    // For example, we have f(x) = d*x / e + f, where we know f(n) = m
    // We construct the DivHelper struct by
    //          DivHelper helper(d, e, m)
    // By calling helper.Next(), we will get the result of f(n), f(n+1), f(n+2) ... etc.
    // Note that if b is 0, Next() will always return initY
    int a;
    int b;
    int D;
    int y;
    int stride;
    int DIncStride;
    int DIncStridePlus1;
    bool first;

    DivHelper(int _a, int _b, int initY)
    {
        // a and b are the constant in the formula y = a*x / b + c
        //       initY is the initial value of Y
        a = _a;
        b = _b;

        if (b != 0)
        {
            stride = a / b;
        }
        else
        {
            stride = 0;
        }

        DIncStride = 2 * (a - b * stride);
        DIncStridePlus1 = 2 * (a - b * (stride + 1));
        Reset(initY);
    }
    int Next() // return the next y value.
    {
        if (first)
        {
            if (b == 0)
                return y; // if b == 0, first will always be true

            first = false;
            return y;
        }
        if (D > 0)
        {
            D += DIncStride;
            y += stride;
        }
        else
        {
            D += DIncStridePlus1;
            y += stride + 1;
        }
        return y;
    }
    void Reset(int initY) // set a new initY value.
    {
        y = initY;
        D = 2 * a - b * (2 * stride + 1);
        first = true;
    }
};
static const RADIAN radian[] = {
    {1.0f, 0.0f},
    {0.999847695156391f, 0.017452406437284f},
    {0.999390827019096f, 0.034899496702501f},
    {0.998629534754574f, 0.052335956242944f},
    {0.997564050259824f, 0.069756473744125f},
    {0.996194698091746f, 0.087155742747658f},
    {0.994521895368273f, 0.104528463267653f},
    {0.992546151641322f, 0.121869343405147f},
    {0.990268068741570f, 0.139173100960065f},
    {0.987688340595138f, 0.156434465040231f},
    {0.984807753012208f, 0.173648177666930f},
    {0.981627183447664f, 0.190808995376545f},
    {0.978147600733806f, 0.207911690817759f},
    {0.974370064785235f, 0.224951054343865f},
    {0.970295726275996f, 0.241921895599668f},
    {0.965925826289068f, 0.258819045102521f},
    {0.961261695938319f, 0.275637355816999f},
    {0.956304755963035f, 0.292371704722737f},
    {0.951056516295154f, 0.309016994374947f},
    {0.945518575599317f, 0.325568154457157f},
    {0.939692620785908f, 0.342020143325669f},
    {0.933580426497202f, 0.358367949545300f},
    {0.927183854566787f, 0.374606593415912f},
    {0.920504853452440f, 0.390731128489274f},
    {0.913545457642601f, 0.406736643075800f},
    {0.906307787036650f, 0.422618261740699f},
    {0.898794046299167f, 0.438371146789077f},
    {0.891006524188368f, 0.453990499739547f},
    {0.882947592858927f, 0.469471562785891f},
    {0.874619707139396f, 0.484809620246337f},
    {0.866025403784439f, 0.500000000000000f},
    {0.857167300702112f, 0.515038074910054f},
    {0.848048096156426f, 0.529919264233205f},
    {0.838670567945424f, 0.544639035015027f},
    {0.829037572555042f, 0.559192903470747f},
    {0.819152044288992f, 0.573576436351046f},
    {0.809016994374947f, 0.587785252292473f},
    {0.798635510047293f, 0.601815023152048f},
    {0.788010753606722f, 0.615661475325658f},
    {0.777145961456971f, 0.629320391049837f},
    {0.766044443118978f, 0.642787609686539f},
    {0.754709580222772f, 0.656059028990507f},
    {0.743144825477394f, 0.669130606358858f},
    {0.731353701619171f, 0.681998360062498f},
    {0.719339800338651f, 0.694658370458997f},
    {0.707106781186548f, 0.707106781186547f},
    {0.694658370458997f, 0.719339800338651f},
    {0.681998360062498f, 0.731353701619170f},
    {0.669130606358858f, 0.743144825477394f},
    {0.656059028990507f, 0.754709580222772f},
    {0.642787609686539f, 0.766044443118978f},
    {0.629320391049838f, 0.777145961456971f},
    {0.615661475325658f, 0.788010753606722f},
    {0.601815023152048f, 0.798635510047293f},
    {0.587785252292473f, 0.809016994374947f},
    {0.573576436351046f, 0.819152044288992f},
    {0.559192903470747f, 0.829037572555042f},
    {0.544639035015027f, 0.838670567945424f},
    {0.529919264233205f, 0.848048096156426f},
    {0.515038074910054f, 0.857167300702112f},
    {0.500000000000000f, 0.866025403784439f},
    {0.484809620246337f, 0.874619707139396f},
    {0.469471562785891f, 0.882947592858927f},
    {0.453990499739547f, 0.891006524188368f},
    {0.438371146789077f, 0.898794046299167f},
    {0.422618261740699f, 0.906307787036650f},
    {0.406736643075800f, 0.913545457642601f},
    {0.390731128489274f, 0.920504853452440f},
    {0.374606593415912f, 0.927183854566787f},
    {0.358367949545300f, 0.933580426497202f},
    {0.342020143325669f, 0.939692620785908f},
    {0.325568154457157f, 0.945518575599317f},
    {0.309016994374947f, 0.951056516295154f},
    {0.292371704722737f, 0.956304755963035f},
    {0.275637355816999f, 0.961261695938319f},
    {0.258819045102521f, 0.965925826289068f},
    {0.241921895599668f, 0.970295726275996f},
    {0.224951054343865f, 0.974370064785235f},
    {0.207911690817759f, 0.978147600733806f},
    {0.190808995376545f, 0.981627183447664f},
    {0.173648177666930f, 0.984807753012208f},
    {0.156434465040231f, 0.987688340595138f},
    {0.139173100960066f, 0.990268068741570f},
    {0.121869343405147f, 0.992546151641322f},
    {0.104528463267653f, 0.994521895368273f},
    {0.087155742747658f, 0.996194698091746f},
    {0.069756473744125f, 0.997564050259824f},
    {0.052335956242944f, 0.998629534754574f},
    {0.034899496702501f, 0.999390827019096f},
    {0.017452406437283f, 0.999847695156391f},
};
// This is the callback signature for Graphics_SetPixelsHelper(). This callback will be called once for each pixel in
// the area specified. The parameters are as follow: 1) int -- the x coordinates of the current pixel 2) int -- the y
// coordinates of the current pixel 3) CLR_UINT32 -- flags that communicate the status of the SetPixels operation, more
// specifically --
//      c_SetPixels_First           - This is the first time the callback is called, can be used to
//                                    conditionally perform any initialization work
//      c_SetPixels_NewRow          - This is the first pixel of a new row (i.e. new y value)
//      c_SetPixels_PixelHidden     - This pixel is outside of the clipping area. Note that if
//                                    c_SetPixelsConfig_NoClipChecks is set, this bit will never be
//                                    set.
// 4) CLR_UINT16& -- the return value for opacity. Note that you can set this to c_OpacityTransparent if
//               you want to leave the pixel unchanged.
// 5) void* -- this is the custom parameter that was passed into Graphics_SetPixelsHelper(), and it is
//             persisted between each callback call
// Return Value -- The color of the pixel
typedef CLR_UINT32 (*GFX_SetPixelsCallback)(int, int, CLR_UINT32, CLR_UINT16 &, void *);
// Graphics_SetPixelsHelper is designed to allow the caller to fill an area of a bitmap without incurring unnecessary
// cost of calculating the x, y position for each pixel. The parameters are as follow: 1) bitmap -- the target bitmap 2)
// rect -- the area on the bitmap to iterate through 3) config -- configuration for how the callbacks will be made, more
// specifically:
//      c_SetPixelsConfig_NoClip        - No clipping will be done, each pixel in the rect area specified will received
//                                        a callback once in order.
//      c_SetPixelsConfig_Clip          - Clipping will be done against bitmap.clipping, and each pixel in the visible
//      area
//                                        will receive a callback once in order.
//      c_SetPixelsConfig_NoClipChecks  - By default, when c_SetPixelsConfig_NoClip is set, each pixel is passed through
//                                        a series of test to determine if the pixel is visible prior to the callback,
//                                        and the result is reflected in the c_SetPixels_PixelHidden flag. If those
//                                        check are unneccessary, this configuration option will save some time.
//      c_SetPixelsConfig_ReverseY      - The default order of the callback is increasing x, increasing y (top to
//      bottom,
//                                        and within each row, left to right). Setting c_SetPixelsConfig_ReverseY will
//                                        change the order to be increasing x, decreasing y (bottom to top, and within
//                                        each row, left to right).
// 4) param -- a custom pointer that's passed into each callback.
struct PAL_GFX_Bitmap
{
    int width;
    int height;
    CLR_UINT32 *data;
    GFX_Rect clipping;
    CLR_UINT32 transparentColor;

    static const CLR_UINT32 c_InvalidColor = 0xFF000000;
    static const CLR_UINT16 c_OpacityTransparent = 0;
    static const CLR_UINT16 c_OpacityOpaque = 256;
    static const CLR_UINT32 c_SetPixels_None = 0x00000000;
    static const CLR_UINT32 c_SetPixels_First = 0x00000001;
    static const CLR_UINT32 c_SetPixels_NewRow = 0x00000002;
    static const CLR_UINT32 c_SetPixels_PixelHidden = 0x00000004;
    static const CLR_UINT32 c_SetPixelsConfig_NoClip = 0x00000000;
    static const CLR_UINT32 c_SetPixelsConfig_Clip = 0x00000001;
    static const CLR_UINT32 c_SetPixelsConfig_NoClipChecks = 0x00000002;
    static const CLR_UINT32 c_SetPixelsConfig_ReverseY = 0x00000004;

    static void ResetClipping(PAL_GFX_Bitmap &bitmap)
    {
        bitmap.clipping.left = 0;
        bitmap.clipping.top = 0;
        bitmap.clipping.right = bitmap.width;
        bitmap.clipping.bottom = bitmap.height;
    }
};
struct CLR_GFX_Bitmap
{
    static const int FIELD__m_bitmap = 1;

    // These have to be kept in sync with the Microsft.SPOT.Bitmap.DT_ flags
    static const CLR_UINT32 c_DrawText_WordWrap = 0x00000001;
    // Note - 0x00000002 is used for Alignment (look below)
    static const CLR_UINT32 c_DrawText_TruncateAtBottom = 0x00000004;
    // Note - 0x00000008 is used for Trimming (look below)
    static const CLR_UINT32 c_DrawText_IgnoreHeight = 0x00000010;

    static const CLR_UINT32 c_DrawText_AlignmentLeft = 0x00000000;
    static const CLR_UINT32 c_DrawText_AlignmentCenter = 0x00000002;
    static const CLR_UINT32 c_DrawText_AlignmentRight = 0x00000020;
    static const CLR_UINT32 c_DrawText_AlignmentUnused = 0x00000022;
    static const CLR_UINT32 c_DrawText_AlignmentMask = 0x00000022;

    static const CLR_UINT32 c_DrawText_TrimmingNone = 0x00000000;
    static const CLR_UINT32 c_DrawText_TrimmingWordEllipsis = 0x00000008;
    static const CLR_UINT32 c_DrawText_TrimmingCharacterEllipsis = 0x00000040;
    static const CLR_UINT32 c_DrawText_TrimmingUnused = 0x00000048;
    static const CLR_UINT32 c_DrawText_TrimmingMask = 0x00000048;

    CLR_GFX_BitmapDescription m_bm; // Initialized by the caller!
    PAL_GFX_Bitmap m_palBitmap;

    static HRESULT CreateInstance(CLR_RT_HeapBlock &ref, const CLR_GFX_BitmapDescription &bm);
    static HRESULT CreateInstance(CLR_RT_HeapBlock &ref, const CLR_UINT8 *data, CLR_UINT32 size, CLR_RT_Assembly *assm);
    static HRESULT CreateInstance(
        CLR_RT_HeapBlock &ref,
        const CLR_UINT8 *data,
        const CLR_UINT32 size,
        const CLR_UINT8 type);

    static HRESULT CreateInstanceJpeg(CLR_RT_HeapBlock &ref, const CLR_UINT8 *data, const CLR_UINT32 size);
    static HRESULT CreateInstanceGif(CLR_RT_HeapBlock &ref, const CLR_UINT8 *data, const CLR_UINT32 size);
    static HRESULT CreateInstanceBmp(CLR_RT_HeapBlock &ref, const CLR_UINT8 *data, const CLR_UINT32 size);

    static HRESULT GetInstanceFromGraphicsHeapBlock(const CLR_RT_HeapBlock &ref, CLR_GFX_Bitmap *&bitmap);
    static HRESULT DeleteInstance(CLR_RT_HeapBlock &ref);

    static CLR_UINT32 CreateInstanceJpegHelper(int x, int y, CLR_UINT32 flags, CLR_UINT16 &opacity, void *param);
    static CLR_UINT32 ConvertToNative1BppHelper(int x, int y, CLR_UINT32 flags, CLR_UINT16 &opacity, void *param);
    static CLR_UINT32 ConvertToNative16BppHelper(int x, int y, CLR_UINT32 flags, CLR_UINT16 &opacity, void *param);

    void Bitmap_Initialize();
    void Clear();
    void SetClipping(GFX_Rect &rc);

    CLR_UINT32 GetPixel(int xPos, int yPos) const;
    void SetPixel(int xPos, int yPos, CLR_UINT32 color);

    void DrawLine(const GFX_Pen &pen, int x0, int y0, int x1, int y1);
    void DrawRectangle(const GFX_Pen &pen, const GFX_Brush &brush, const GFX_Rect &rectangle);
    void FillRectangle(const GFX_Brush &brush, const GFX_Rect &rectangle);
    void DrawRoundedRectangle(
        const GFX_Pen &pen,
        const GFX_Brush &brush,
        const GFX_Rect &rectangle,
        int radiusX,
        int radiusY);
    void DrawEllipse(const GFX_Pen &pen, const GFX_Brush &brush, int x, int y, int radiusX, int radiusY);

    void DrawImage(const GFX_Rect &dst, const CLR_GFX_Bitmap &bitmapSrc, const GFX_Rect &src, CLR_UINT16 opacity);
    void RotateImage(
        int angle,
        const GFX_Rect &dst,
        const CLR_GFX_Bitmap &bitmapSrc,
        const GFX_Rect &src,
        CLR_UINT16 opacity);

    void DrawChar(CLR_UINT16 c, CLR_GFX_Font &font, CLR_UINT32 color, int x, int y);
    void DrawText(LPCSTR str, CLR_GFX_Font &font, CLR_UINT32 color, int x, int y);
    static HRESULT DrawTextInRect(
        LPCSTR &szText,
        int &xRelStart,
        int &yRelStart,
        int &renderWidth,
        int &renderHeight,
        CLR_GFX_Bitmap *bm,
        int x,
        int y,
        int width,
        int height,
        CLR_UINT32 dtFlags,
        CLR_UINT32 color,
        CLR_GFX_Font *font);
    void SetPixelsHelper(const GFX_Rect &rect, CLR_UINT32 config, GFX_SetPixelsCallback callback, void *param);

    // Helper routine
    HRESULT GetBitmap(CLR_RT_HeapBlock *pThis, bool fForWrite, CLR_GFX_Bitmap *&bitmap);
    HRESULT GetBitmap(CLR_RT_StackFrame &stack, bool fForWrite, CLR_GFX_Bitmap *&bitmap);

  private:
    void Decompress(const CLR_UINT8 *data, CLR_UINT32 size);
    void ConvertToNative(const CLR_GFX_BitmapDescription *bmSrc, CLR_UINT32 *dataSrc);

    PROHIBIT_ALL_CONSTRUCTORS(CLR_GFX_Bitmap);
};

struct CLR_GFX_Font
{
    static const int FIELD__m_font = 1;

    /////////////////////////////////////////////////////////////////////
    // !!! KEEP IN SYNC WITH nanoFramework.UI.Font.DefaultKerning  !!! //
    /////////////////////////////////////////////////////////////////////
    static const CLR_INT32 c_DefaultKerning = 1024;
    static const CLR_UINT16 c_UnicodeReplacementCharacter = 0xFFFD;

    CLR_GFX_FontDescription m_font;
    CLR_GFX_FontCharacterRange *m_ranges;
    CLR_GFX_FontCharacter *m_chars;
    CLR_GFX_Bitmap m_bitmap;
    CLR_GFX_FontCharacterInfo m_defaultChar;
    CLR_GFX_FontDescriptionEx m_fontEx;
    CLR_GFX_FontCharacterRangeEx *m_rangesEx;
    CLR_GFX_FontCharacterEx *m_charsEx;
    CLR_UINT8 *m_antiAliasingData;

    static HRESULT CreateInstance(CLR_RT_HeapBlock &ref, const CLR_UINT8 *data, CLR_RT_Assembly *assm);
    void Font_Initialize();
    int StringOut(
        LPCSTR str,
        int maxChars,
        CLR_INT32 kerning,
        CLR_GFX_Bitmap *bm,
        int xPos,
        int yPos,
        CLR_UINT32 color);
    void CountCharactersInWidth(
        LPCSTR str,
        int maxChars,
        int width,
        int &totWidth,
        bool fWordWrap,
        LPCSTR &strNext,
        int &numChars);
    void DrawChar(CLR_GFX_Bitmap *bitmap, CLR_GFX_FontCharacterInfo &chr, int xDst, int yDst, CLR_UINT32 color);
    static CLR_UINT32 DrawCharHelper(int x, int y, CLR_UINT32 flags, CLR_UINT16 &opacity, void *param);
    void GetCharInfo(CLR_UINT16 c, CLR_GFX_FontCharacterInfo &chrEx);
    void Relocate();
    static void RelocationHandler(CLR_RT_HeapBlock_BinaryBlob *ptr);

    PROHIBIT_ALL_CONSTRUCTORS(CLR_GFX_Font);
};
struct DrawCharHelperParam
{
    int originalDstX;
    int originalDstY;
    int srcX;
    int srcY;
    CLR_UINT32 *srcFirstWord;
    CLR_UINT32 srcFirstPixelMask;
    CLR_UINT32 srcCurPixelMask;
    CLR_UINT32 *srcCurWord;
    CLR_UINT32 srcWidthInWords;
    CLR_UINT32 color;
    CLR_UINT8 *antiAlias;
    CLR_UINT8 iAntiAlias;
    CLR_UINT8 antiAliasStep;
    CLR_UINT8 antiAliasShift;
    CLR_UINT8 antiAliasShiftFirstPixel;
    CLR_UINT32 antiAliasMask;
    CLR_UINT32 antiAliasMaskFirstPixel;
};
int GetCharInfoCmp(const void *c, const void *r);
struct GraphicsDriver
{
  public:
    static int GetSize(CLR_INT32 width, CLR_INT32 height);
    static int GetWidthInWords(CLR_INT32 width);
    static int GetLongerSide();
    static int GetShorterSide();
    static int GetWidth();
    static int GetHeight();
    static int GetBitsPerPixel();
    static DisplayOrientation GetOrientation();
    static bool ChangeOrientation(DisplayOrientation newOrientation);

    static void Clear(const PAL_GFX_Bitmap &bitmap);

    static CLR_UINT32 GetPixel(const PAL_GFX_Bitmap &bitmap, int x, int y);
    static void SetPixel(const PAL_GFX_Bitmap &bitmap, int x, int y, CLR_UINT32 color);
    static void DrawLine(const PAL_GFX_Bitmap &bitmap, const GFX_Pen &pen, int x0, int y0, int x1, int y1);
    static void DrawLineRaw(const PAL_GFX_Bitmap &bitmap, const GFX_Pen &pen, int x0, int y0, int x1, int y1);
    static void DrawRectangle(
        const PAL_GFX_Bitmap &bitmap,
        const GFX_Pen &pen,
        const GFX_Brush &brush,
        const GFX_Rect &rectangle);
    static void FillRectangle(const PAL_GFX_Bitmap &bitmap, const GFX_Brush &brush, const GFX_Rect &rectangle);
    static void DrawRoundedRectangle(
        const PAL_GFX_Bitmap &bitmap,
        const GFX_Pen &pen,
        const GFX_Brush &brush,
        const GFX_Rect &rectangle,
        int radiusX,
        int radiusY);
    static void DrawEllipse(
        const PAL_GFX_Bitmap &bitmap,
        const GFX_Pen &pen,
        const GFX_Brush &brush,
        int x,
        int y,
        int radiusX,
        int radiusY);
    static void DrawImage(
        const PAL_GFX_Bitmap &bitmapDst,
        const GFX_Rect &dst,
        const PAL_GFX_Bitmap &bitmapSrc,
        const GFX_Rect &src,
        CLR_UINT16 opacity);
    static void SetPixelsHelper(
        const PAL_GFX_Bitmap &bitmap,
        const GFX_Rect &rect,
        CLR_UINT32 config,
        GFX_SetPixelsCallback callback,
        void *param);
    static void RotateImage(
        CLR_INT16 degree,
        const PAL_GFX_Bitmap &dst,
        const GFX_Rect &dstRect,
        const PAL_GFX_Bitmap &src,
        const GFX_Rect &srcRect,
        CLR_UINT16 opacity);

    static void Screen_Flush(
        CLR_GFX_Bitmap &bitmap,
        CLR_UINT16 srcX,
        CLR_UINT16 srcY,
        CLR_UINT16 width,
        CLR_UINT16 height,
        CLR_UINT16 screenX,
        CLR_UINT16 screenY);

  private:
    static const CLR_UINT32 c_MaxSize = 2097152; // 2MB
    static CLR_UINT32 GetPixelNative(const PAL_GFX_Bitmap &bitmap, int x, int y);
    static void SetPixelNative(const PAL_GFX_Bitmap &bitmap, int x, int y, CLR_UINT32 color);
    static void SetThickPixel(const PAL_GFX_Bitmap &bitmap, int x, int y, GFX_Pen &pen);

    static void DrawLineNative(const PAL_GFX_Bitmap &bitmap, GFX_Pen &pen, int x0, int y0, int x1, int y1);
    static void DrawRectangleNative(
        const PAL_GFX_Bitmap &bitmap,
        GFX_Pen &pen,
        GFX_Brush &brush,
        const GFX_Rect &rectangle);
    static void FillRectangleNative(const PAL_GFX_Bitmap &bitmap, GFX_Brush &brush, const GFX_Rect &rectangle);
    static void DrawRoundedRectangleNative(
        const PAL_GFX_Bitmap &bitmap,
        GFX_Pen &pen,
        GFX_Brush &brush,
        const GFX_Rect &rectangle,
        int radiusX,
        int radiusY);
    static void DrawRoundedRectangleNative(
        const PAL_GFX_Bitmap &bitmap,
        GFX_Pen &pen,
        const GFX_Rect &rectangle,
        int radiusX,
        int radiusY);
    static void DrawEllipseNative(
        const PAL_GFX_Bitmap &bitmap,
        GFX_Pen &pen,
        GFX_Brush &brush,
        int x,
        int y,
        int radiusX,
        int radiusY);

    static CLR_UINT32 *ComputePosition(
        const PAL_GFX_Bitmap &bitmap,
        int xPos,
        int yPos,
        CLR_UINT32 &mask,
        CLR_UINT32 &shift);

    static bool IsPixelVisible(const GFX_Rect &clipping, int x, int y);
    static bool ClipToVisible(
        const PAL_GFX_Bitmap &target,
        int &x,
        int &y,
        int &width,
        int &height,
        const PAL_GFX_Bitmap *pSrc,
        int &xSrc,
        int &ySrc);

    static void DrawBresLineNative(const PAL_GFX_Bitmap &bitmap, int x0, int y0, int x1, int y1, GFX_Pen &pen);

    static void DrawScanlineNative(
        const PAL_GFX_Bitmap &bitmap,
        int x1,
        int x2,
        int y,
        CLR_UINT32 color,
        CLR_UINT16 opacity);

    static CLR_UINT32 NativeColorInterpolate(CLR_UINT32 colorTo, CLR_UINT32 colorFrom, CLR_UINT16 scalar);

    __inline static CLR_UINT8 NativeColorRValue(CLR_UINT32 color)
    {
        return (color & 0xF800) >> 11;
    }
    __inline static CLR_UINT8 NativeColorGValue(CLR_UINT32 color)
    {
        return (color & 0x07E0) >> 5;
    }
    __inline static CLR_UINT8 NativeColorBValue(CLR_UINT32 color)
    {
        return color & 0x1F;
    }
    __inline static CLR_UINT32 NativeColorFromRGB(CLR_UINT8 r, CLR_UINT8 g, CLR_UINT8 b)
    {
        ASSERT((b <= 0x1F) && (g <= 0x3F) && (r <= 0x1F));
        return (r << 11) | (g << 5) | b;
    }

    __inline static CLR_UINT8 ColorRValue(CLR_UINT32 color)
    {
        return color & 0x0000FF;
    }
    __inline static CLR_UINT8 ColorGValue(CLR_UINT32 color)
    {
        return (color & 0x00FF00) >> 8;
    }
    __inline static CLR_UINT8 ColorBValue(CLR_UINT32 color)
    {
        return (color & 0xFF0000) >> 16;
    }
    __inline static CLR_UINT32 ColorFromRGB(CLR_UINT8 r, CLR_UINT8 g, CLR_UINT8 b)
    {
        return (b << 16) | (g << 8) | r;
    }

    __inline static CLR_UINT32 ConvertNativeToColor(CLR_UINT32 nativeColor)
    {
        int r = NativeColorRValue(nativeColor) << 3;
        if ((r & 0x8) != 0)
            r |= 0x7; // Copy LSB
        int g = NativeColorGValue(nativeColor) << 2;
        if ((g & 0x4) != 0)
            g |= 0x3; // Copy LSB
        int b = NativeColorBValue(nativeColor) << 3;
        if ((b & 0x8) != 0)
            b |= 0x7; // Copy LSB
        return ColorFromRGB(r, g, b);
    }
    __inline static CLR_UINT32 ConvertColorToNative(CLR_UINT32 color)
    {
        return NativeColorFromRGB(ColorRValue(color) >> 3, ColorGValue(color) >> 2, ColorBValue(color) >> 3);
    }

    __inline static GFX_Pen ConvertPenToNative(const GFX_Pen &pen)
    {
        GFX_Pen nativePen;
        nativePen.thickness = pen.thickness;
        nativePen.color = ConvertColorToNative(pen.color);
        return nativePen;
    }

    __inline static GFX_Brush ConvertBrushToNative(const GFX_Brush &brush)
    {
        GFX_Brush nativeBrush;
        nativeBrush.gradientStartX = brush.gradientStartX;
        nativeBrush.gradientStartY = brush.gradientStartY;
        nativeBrush.gradientStartColor = ConvertColorToNative(brush.gradientStartColor);
        nativeBrush.gradientEndX = brush.gradientEndX;
        nativeBrush.gradientEndY = brush.gradientEndY;
        nativeBrush.gradientEndColor = ConvertColorToNative(brush.gradientEndColor);
        nativeBrush.opacity = brush.opacity;
        return nativeBrush;
    }

    typedef void (*EllipseCallback)(const PAL_GFX_Bitmap &, int, int, void *);

    static void EllipseAlgorithm(
        const PAL_GFX_Bitmap &bitmap,
        int radiusX,
        int radiusY,
        void *params,
        EllipseCallback ellipseCallback);

    static void Draw4PointsEllipse(const PAL_GFX_Bitmap &bitmap, int offsetX, int offsetY, void *params);
    static void Draw4PointsRoundedRect(const PAL_GFX_Bitmap &bitmap, int offsetX, int offsetY, void *params);
    static void Fill4PointLinesRoundedRect(const PAL_GFX_Bitmap &bitmap, int offsetX, int offsetY, void *params);
    static void GradientFill4PointLinesRoundedRect(
        const PAL_GFX_Bitmap &bitmap,
        int offsetX,
        int offsetY,
        void *params);
};

// The PAL Graphics API uses the 24bit BGR color space, the one that's used for the
// CLR. It is the responsibility of whoever is implementing the PAL to deal with color conversion
// as neither CLR or TinyCore understands any color space other than this default one.
// For opacity, the valid value are from 0 (c_OpacityTransparent) to 256 (c_OpacityOpaque).

//_____________________________________
//   Gesture support
//_____________________________________

struct GestureDriver
{
    static const int c_IgnoreCount = 2;

  private:
    static bool s_initialized;

    static PalEventListener m_gestureListener;
    static HAL_COMPLETION m_gestureCompletion;
    static CLR_UINT32 m_index;
    static CLR_UINT32 m_currentState;
    static CLR_UINT16 m_lastx;
    static CLR_UINT16 m_lasty;
    static CLR_UINT16 m_startx;
    static CLR_UINT16 m_starty;

    static CLR_UINT32 m_stateIgnoreIndex;
    static CLR_UINT32 m_stateIgnoreHead;
    static CLR_UINT32 m_stateIgnoreTail;
    static CLR_UINT32 m_stateIgnoreBuffer[c_IgnoreCount];

  public:
    static HRESULT Initialize();
    static HRESULT Uninitialize();
    static bool ProcessPoint(CLR_UINT32 flags, CLR_UINT16 source, CLR_UINT16 x, CLR_UINT16 y, CLR_INT64 time);
    static void ResetRecognition();
    static void EventListener(uint32_t e, uint32_t param);
    static void GestureContinuationRoutine(void *arg);
};
// Bitmap decoder
typedef CLR_UINT32 COLORREF;
enum BmpEncodingType
{
    BmpUnknown = 0,
    Bmp16Bit_565 = 1,
    Bmp24Bit_RGB = 2,
    Bmp8Bit_Indexed = 3,
    Bmp32Bit_ARGB = 4,
};
struct BmpDecoder
{
    int width;
    int height;
    BmpEncodingType encodingType;
    HRESULT BmpInitOutput(const CLR_UINT8 *src, CLR_UINT32 srcSize);
    HRESULT BmpStartOutput(CLR_GFX_Bitmap *bitmap);
    static CLR_UINT32 BmpOutputHelper(int x, int y, CLR_UINT32 flags, CLR_UINT16 &opacity, void *param);

  private:
    CLR_RT_ByteArrayReader source;
    const CLR_UINT8 *palette;
    CLR_UINT8 paletteDepth;
    bool isTopDown;
};
struct BITMAPFILEHEADER
{
    CLR_UINT16 bfType;
    CLR_UINT32 bfSize;
    CLR_UINT16 bfReserved1;
    CLR_UINT16 bfReserved2;
    CLR_UINT32 bfOffBits;
} __attribute__((packed));
struct BITMAPINFOHEADER
{
    CLR_UINT32 biSize;
    CLR_INT32 biWidth;
    CLR_INT32 biHeight;
    CLR_UINT16 biPlanes;
    CLR_UINT16 biBitCount;
    CLR_UINT32 biCompression;
    CLR_UINT32 biSizeImage;
    CLR_INT32 biXPelsPerMeter;
    CLR_INT32 biYPelsPerMeter;
    CLR_UINT32 biClrUsed;
    CLR_UINT32 biClrImportant;
} __attribute__((packed));
struct BmpOutputHelperParam
{
    CLR_RT_ByteArrayReader *source;
    BmpEncodingType encodingType;
    CLR_UINT32 srcWidthInBytes;
    CLR_UINT8 *srcRGB;
    const CLR_UINT8 *palette;
    CLR_UINT8 paletteDepth;
};

#endif // GRAPHICS_H


text:
package com.intellij.openapi.externalSystem.model.project;

import javax.annotation.Nonnull;

/**
 * @author Vladislav.Soroka
 * @since 11/27/13
 */
public interface Identifiable {

  @Nonnull
  String getId();
}

redpajama_set_name: RedPajamaGithub


text:
class LayerLoading : public cocos2d::Layer
{
public:
	// there's no 'id' in cpp, so we recommend returning the class instance pointer
	static cocos2d::Scene* createScene();

	// Here's a difference. Method 'init' in cocos2d-x returns bool, instead of returning 'id' in cocos2d-iphone
	virtual bool init();

	virtual void update(float dt);
	// implement the "static create()" method manually
	CREATE_FUNC(LayerLoading);
};

#endif // __Layer_Function_H__


text:
package com.swall.enteach.services;

import android.content.Context;
import android.os.Bundle;
import android.util.Log;
import com.android.volley.*;
import com.android.volley.toolbox.JsonObjectRequest;
import org.json.JSONObject;

/**
 * Created by pxz on 13-12-13.
 */
public class UploadService extends ActionService {
    final String UPLOAD_URL = "http://localhost:8999/upload/";

    public UploadService(Context context,ServiceManager manager) {
        super(context, manager);
    }

    @Override
    public void doAction(int action, Bundle data, ActionListener callback) {
        switch (action){
            case ServiceManager.Constants.ACTION_UPLOAD_TEXT:
                uploadText(data,callback);
                break;
        }
    }

    private void uploadText(Bundle data, ActionListener callback) {
        RequestQueue rq = MyVolley.getRequestQueue();
        JsonObjectRequest jor = new JsonObjectRequest(
                Request.Method.POST,
                ServiceManager.Constants.getUpdatesUrl(data.getString("userName","xamn"),data),
                null,
                new Response.Listener<JSONObject>(){

                    @Override
                    public void onResponse(JSONObject response) {
                        Log.i("SWall", response.toString());
                    }
                },
                new Response.ErrorListener() {
                    @Override
                    public void onErrorResponse(VolleyError error) {

                    }
                }
        );

        rq.start();
    }

    @Override
    public int[] getActionList() {
        return new int[]{
                ServiceManager.Constants.ACTION_UPLOAD_PIC,
                ServiceManager.Constants.ACTION_UPLOAD_TEXT,
                ServiceManager.Constants.ACTION_UPLOAD_VIDEO
        };
    }

    private void doUpload(String postUrl,byte[] data){

    }
}


text:
package cn.tomsnail.dev.console.util;

import redis.clients.jedis.Jedis;

public class RedisUtil {

	public static void set(String key,String value,RedisConfig redisConfig){
		set(key,value,0,redisConfig);
	}

	public static void set(String key,String value,int timeout,RedisConfig redisConfig){
		Jedis jedis = getJedis(redisConfig);
		jedis.set(key, value);
		if(timeout>0){
			jedis.expire(key, timeout);
		}
		colse(jedis);
	}

	public static void hset(String mapName,String key,String value,RedisConfig redisConfig){
		hset(mapName,key,value,0,redisConfig);
	}

	public static void hset(String mapName,String key,String value,int timeout,RedisConfig redisConfig){
		Jedis jedis = getJedis(redisConfig);
		jedis.hset(mapName, key, value);
		if(timeout>0){
			jedis.expire(mapName, timeout);
		}
		colse(jedis);
	}

	public static String get(String key,RedisConfig redisConfig ){
		Jedis jedis = getJedis(redisConfig);
		String v = jedis.get(key);
		colse(jedis);
		return v;
	}

	private static Jedis getJedis(RedisConfig redisConfig ){
		if(redisConfig==null){
			throw new NullPointerException("RedisConfig is null");
		}
		Jedis jedis = new Jedis(redisConfig.getUrl(), redisConfig.getPort(), redisConfig.getMaxWaitMillis());
		return jedis;
	}

	private static void colse(Jedis jedis){
		if(jedis!=null){
			jedis.close();
		}
	}

}


text:
Newscoop Plugins Installer
==========================

Newscoop Plugins (based on Symfony Bundles) composer installer.


text:
package com.xj.scud.monitor;

import com.xj.scud.client.ClientConfig;
import com.xj.scud.client.ScudClientFactory;
import com.xj.scud.client.route.RouteEnum;
import com.xj.scud.commons.Config;
import com.xj.scud.core.network.SerializableEnum;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * Author: xiajun
 * Date: 2017/09/25 11:31
 */
public class MonitorHandlerImpl implements MonitorHandlerInterface {
    private final static Logger LOGGER = LoggerFactory.getLogger(MonitorHandlerImpl.class);
    private static MonitorHandlerInterface monitorHandler;

    public MonitorHandlerImpl() {
        if (monitorHandler == null) {
            synchronized (MonitorHandlerImpl.class) {
                if (monitorHandler == null) {
                    ClientConfig conf = new ClientConfig();
                    conf.setRoute(RouteEnum.RANDOM).setTimeout(2000).setInterfaze(MonitorHandlerInterface.class).setVersion("1.0")
                            .setType(SerializableEnum.PROTOBUF).setUseZk(true).setZkHost(Config.getValue("zk.host"));
                    monitorHandler = ScudClientFactory.getServiceConsumer(conf);
                }
            }
        }
    }

    @Override
    public void monitor(TopPercentile topPercentile) {
        if (monitorHandler != null) {
            try {
                monitorHandler.monitor(topPercentile);
            } catch (Exception e) {
                LOGGER.error("", e);
            }
        } else {
            LOGGER.error("Monitor handler exception, create instance fail.");
        }
    }
}


text:
package org.mgechev.elang.parser.expressions.symbols.builtinoperators;

import org.mgechev.elang.parser.expressions.symbols.Operator;
import org.mgechev.elang.parser.expressions.symbols.Value;

public class Equals extends Operator {

    public Equals() {
        super(0);
    }

    public Value<Boolean> evaluate() {
        return null;
    }
}


text:
package ie.cit.oossp.cookie;

import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class CookieExampleServlet extends HttpServlet {

	private static final long serialVersionUID = -4628573099634298659L;

	private String names[] = { "C", "C++", "Java", "C#", "Python" };
	private String isbn[] = { "0132261197", "0135289106", "0130125075", "1491927062", "1449355730" };

	public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		PrintWriter output;
		String language = request.getParameter("lang");

		Cookie c = new Cookie(language, getISBN(language));
		c.setMaxAge(60); // seconds until cookie removed
		response.addCookie(c); // must precede getWriter

		//response.setContentType("text/html");
		output = response.getWriter();

		// send HTML page to client
		output.println("<TITLE>");
		output.println("Cookies");
		output.println("</TITLE>");
		output.println("
Welcome to Cookies!
");
		output.println("
");
		output.println(language);
		output.println(" is a great language.");
		output.println("");
		output.close(); // close stream
	}

	public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		PrintWriter output;
		Cookie cookies[];

		cookies = request.getCookies(); // get client's cookies

		response.setContentType("text/html");
		output = response.getWriter();

		output.println("<TITLE>");
		output.println("Cookies II");
		output.println("</TITLE>");

		if (cookies != null && !cookies[0].getName().equals("JSESSIONID")) {
			output.println("
Recommendations
");
			// get the name of each cookie
			for (int i = 0; i < cookies.length; i++)
				if (!cookies[i].getName().equals("JSESSIONID"))
					output.println(cookies[i].getName() + " : Check out the book with this ISBN#: " + cookies[i].getValue() + "
");
		} else {
			output.println("
No Recommendations
");
			output.println("You did not select a language or");
			output.println("the cookies have expired.");
		}

		output.println("");
		output.close(); // close stream
	}

	private String getISBN(String lang) {
		for (int i = 0; i < names.length; ++i)
			if (lang.equals(names[i]))
				return isbn[i];

		return ""; // no matching string found
	}
}


text:
if(UNIX)
  set(CMAKE_C_OUTPUT_EXTENSION .o)
else()
  set(CMAKE_C_OUTPUT_EXTENSION .obj)
endif()

set(_INCLUDED_FILE 0)

# Load compiler-specific information.
if(CMAKE_C_COMPILER_ID)
  include(Compiler/${CMAKE_C_COMPILER_ID}-C OPTIONAL)
endif()

set(CMAKE_BASE_NAME)
get_filename_component(CMAKE_BASE_NAME ${CMAKE_C_COMPILER} NAME_WE)
if(CMAKE_COMPILER_IS_GNUCC)
  set(CMAKE_BASE_NAME gcc)
endif()

# load a hardware specific file, mostly useful for embedded compilers
if(CMAKE_SYSTEM_PROCESSOR)
  if(CMAKE_C_COMPILER_ID)
    include(Platform/${CMAKE_SYSTEM_NAME}-${CMAKE_C_COMPILER_ID}-C-${CMAKE_SYSTEM_PROCESSOR} OPTIONAL RESULT_VARIABLE _INCLUDED_FILE)
  endif()
  if (NOT _INCLUDED_FILE)
    include(Platform/${CMAKE_SYSTEM_NAME}-${CMAKE_BASE_NAME}-${CMAKE_SYSTEM_PROCESSOR} OPTIONAL)
  endif ()
endif()

# load the system- and compiler specific files
if(CMAKE_C_COMPILER_ID)
  include(Platform/${CMAKE_SYSTEM_NAME}-${CMAKE_C_COMPILER_ID}-C
    OPTIONAL RESULT_VARIABLE _INCLUDED_FILE)
endif()
if (NOT _INCLUDED_FILE)
  include(Platform/${CMAKE_SYSTEM_NAME}-${CMAKE_BASE_NAME}
    OPTIONAL RESULT_VARIABLE _INCLUDED_FILE)
endif ()
# We specify the compiler information in the system file for some
# platforms, but this language may not have been enabled when the file
# was first included.  Include it again to get the language info.
# Remove this when all compiler info is removed from system files.
if (NOT _INCLUDED_FILE)
  include(Platform/${CMAKE_SYSTEM_NAME} OPTIONAL)
endif ()

if(CMAKE_C_SIZEOF_DATA_PTR)
  foreach(f ${CMAKE_C_ABI_FILES})
    include(${f})
  endforeach()
  unset(CMAKE_C_ABI_FILES)
endif()

# This should be included before the _INIT variables are
# used to initialize the cache.  Since the rule variables
# have if blocks on them, users can still define them here.
# But, it should still be after the platform file so changes can
# be made to those values.

if(CMAKE_USER_MAKE_RULES_OVERRIDE)
  # Save the full path of the file so try_compile can use it.
  include(${CMAKE_USER_MAKE_RULES_OVERRIDE} RESULT_VARIABLE _override)
  set(CMAKE_USER_MAKE_RULES_OVERRIDE "${_override}")
endif()

if(CMAKE_USER_MAKE_RULES_OVERRIDE_C)
  # Save the full path of the file so try_compile can use it.
  include(${CMAKE_USER_MAKE_RULES_OVERRIDE_C} RESULT_VARIABLE _override)
  set(CMAKE_USER_MAKE_RULES_OVERRIDE_C "${_override}")
endif()

# for most systems a module is the same as a shared library
# so unless the variable CMAKE_MODULE_EXISTS is set just
# copy the values from the LIBRARY variables
if(NOT CMAKE_MODULE_EXISTS)
  set(CMAKE_SHARED_MODULE_C_FLAGS ${CMAKE_SHARED_LIBRARY_C_FLAGS})
  set(CMAKE_SHARED_MODULE_CREATE_C_FLAGS ${CMAKE_SHARED_LIBRARY_CREATE_C_FLAGS})
endif()

set(CMAKE_C_FLAGS_INIT "$ENV{CFLAGS} ${CMAKE_C_FLAGS_INIT}")
# avoid just having a space as the initial value for the cache
if(CMAKE_C_FLAGS_INIT STREQUAL " ")
  set(CMAKE_C_FLAGS_INIT)
endif()
set (CMAKE_C_FLAGS "${CMAKE_C_FLAGS_INIT}" CACHE STRING
     "Flags used by the compiler during all build types.")

if(NOT CMAKE_NOT_USING_CONFIG_FLAGS)
# default build type is none
  if(NOT CMAKE_NO_BUILD_TYPE)
    set (CMAKE_BUILD_TYPE ${CMAKE_BUILD_TYPE_INIT} CACHE STRING
      "Choose the type of build, options are: None(CMAKE_CXX_FLAGS or CMAKE_C_FLAGS used) Debug Release RelWithDebInfo MinSizeRel.")
  endif()
  set (CMAKE_C_FLAGS_DEBUG "${CMAKE_C_FLAGS_DEBUG_INIT}" CACHE STRING
    "Flags used by the compiler during debug builds.")
  set (CMAKE_C_FLAGS_MINSIZEREL "${CMAKE_C_FLAGS_MINSIZEREL_INIT}" CACHE STRING
    "Flags used by the compiler during release minsize builds.")
  set (CMAKE_C_FLAGS_RELEASE "${CMAKE_C_FLAGS_RELEASE_INIT}" CACHE STRING
    "Flags used by the compiler during release builds (/MD /Ob1 /Oi /Ot /Oy /Gs will produce slightly less optimized but smaller files).")
  set (CMAKE_C_FLAGS_RELWITHDEBINFO "${CMAKE_C_FLAGS_RELWITHDEBINFO_INIT}" CACHE STRING
    "Flags used by the compiler during Release with Debug Info builds.")
endif()

if(CMAKE_C_STANDARD_LIBRARIES_INIT)
  set(CMAKE_C_STANDARD_LIBRARIES "${CMAKE_C_STANDARD_LIBRARIES_INIT}"
    CACHE STRING "Libraries linked by defalut with all C applications.")
  mark_as_advanced(CMAKE_C_STANDARD_LIBRARIES)
endif()

include(CMakeCommonLanguageInclude)

# now define the following rule variables

# CMAKE_C_CREATE_SHARED_LIBRARY
# CMAKE_C_CREATE_SHARED_MODULE
# CMAKE_C_COMPILE_OBJECT
# CMAKE_C_LINK_EXECUTABLE

# variables supplied by the generator at use time
# <TARGET>
# <TARGET_BASE> the target without the suffix
# <OBJECTS>
# <OBJECT>
# <LINK_LIBRARIES>
# <FLAGS>
# <LINK_FLAGS>

# C compiler information
# <CMAKE_C_COMPILER>
# <CMAKE_SHARED_LIBRARY_CREATE_C_FLAGS>
# <CMAKE_SHARED_MODULE_CREATE_C_FLAGS>
# <CMAKE_C_LINK_FLAGS>

# Static library tools
# <CMAKE_AR>
# <CMAKE_RANLIB>

# create a C shared library
if(NOT CMAKE_C_CREATE_SHARED_LIBRARY)
  set(CMAKE_C_CREATE_SHARED_LIBRARY
      "<CMAKE_C_COMPILER> <CMAKE_SHARED_LIBRARY_C_FLAGS> <LANGUAGE_COMPILE_FLAGS> <LINK_FLAGS> <CMAKE_SHARED_LIBRARY_CREATE_C_FLAGS> <SONAME_FLAG><TARGET_SONAME> -o <TARGET> <OBJECTS> <LINK_LIBRARIES>")
endif()

# create a C shared module just copy the shared library rule
if(NOT CMAKE_C_CREATE_SHARED_MODULE)
  set(CMAKE_C_CREATE_SHARED_MODULE ${CMAKE_C_CREATE_SHARED_LIBRARY})
endif()

# Create a static archive incrementally for large object file counts.
# If CMAKE_C_CREATE_STATIC_LIBRARY is set it will override these.
if(NOT DEFINED CMAKE_C_ARCHIVE_CREATE)
  set(CMAKE_C_ARCHIVE_CREATE "<CMAKE_AR> cr <TARGET> <LINK_FLAGS> <OBJECTS>")
endif()
if(NOT DEFINED CMAKE_C_ARCHIVE_APPEND)
  set(CMAKE_C_ARCHIVE_APPEND "<CMAKE_AR> r  <TARGET> <LINK_FLAGS> <OBJECTS>")
endif()
if(NOT DEFINED CMAKE_C_ARCHIVE_FINISH)
  set(CMAKE_C_ARCHIVE_FINISH "<CMAKE_RANLIB> <TARGET>")
endif()

# compile a C file into an object file
if(NOT CMAKE_C_COMPILE_OBJECT)
  set(CMAKE_C_COMPILE_OBJECT
    "<CMAKE_C_COMPILER> <DEFINES> <FLAGS> -o <OBJECT>   -c <SOURCE>")
endif()

if(NOT CMAKE_C_LINK_EXECUTABLE)
  set(CMAKE_C_LINK_EXECUTABLE
    "<CMAKE_C_COMPILER> <FLAGS> <CMAKE_C_LINK_FLAGS> <LINK_FLAGS> <OBJECTS>  -o <TARGET> <LINK_LIBRARIES>")
endif()

if(NOT CMAKE_EXECUTABLE_RUNTIME_C_FLAG)
  set(CMAKE_EXECUTABLE_RUNTIME_C_FLAG ${CMAKE_SHARED_LIBRARY_RUNTIME_C_FLAG})
endif()

if(NOT CMAKE_EXECUTABLE_RUNTIME_C_FLAG_SEP)
  set(CMAKE_EXECUTABLE_RUNTIME_C_FLAG_SEP ${CMAKE_SHARED_LIBRARY_RUNTIME_C_FLAG_SEP})
endif()

if(NOT CMAKE_EXECUTABLE_RPATH_LINK_C_FLAG)
  set(CMAKE_EXECUTABLE_RPATH_LINK_C_FLAG ${CMAKE_SHARED_LIBRARY_RPATH_LINK_C_FLAG})
endif()

mark_as_advanced(
CMAKE_C_FLAGS
CMAKE_C_FLAGS_DEBUG
CMAKE_C_FLAGS_MINSIZEREL
CMAKE_C_FLAGS_RELEASE
CMAKE_C_FLAGS_RELWITHDEBINFO
)
set(CMAKE_C_INFORMATION_LOADED 1)


text:
<?php

namespace app\controllers;

use Yii;
use app\models\Goodgroup;
use app\models\GoodgroupSearch;
use yii\web\Controller;
use yii\web\NotFoundHttpException;
use yii\filters\VerbFilter;

/**
 * GoodgroupController implements the CRUD actions for Goodgroup model.
 */
class GoodgroupController extends Controller
{
    public function behaviors()
    {
        return [
            'verbs' => [
                'class' => VerbFilter::className(),
                'actions' => [
                    'delete' => ['post'],
                ],
            ],
        ];
    }

    /**
     * Lists all Goodgroup models.
     * @return mixed
     */
    public function actionIndex()
    {
        $searchModel = new GoodgroupSearch();
        $dataProvider = $searchModel->search(Yii::$app->request->queryParams);

        return $this->render('index', [
            'searchModel' => $searchModel,
            'dataProvider' => $dataProvider,
        ]);
    }

    /**
     * Displays a single Goodgroup model.
     * @param integer $id
     * @return mixed
     */
    public function actionView($id)
    {
        return $this->render('view', [
            'model' => $this->findModel($id),
        ]);
    }

    /**
     * Creates a new Goodgroup model.
     * If creation is successful, the browser will be redirected to the 'view' page.
     * @return mixed
     */
    public function actionCreate()
    {
        $model = new Goodgroup();

        if ($model->load(Yii::$app->request->post()) && $model->save()) {
            return $this->redirect(['view', 'id' => $model->gdgrp_id]);
        } else {
            return $this->render('create', [
                'model' => $model,
            ]);
        }
    }

    /**
     * Updates an existing Goodgroup model.
     * If update is successful, the browser will be redirected to the 'view' page.
     * @param integer $id
     * @return mixed
     */
    public function actionUpdate($id)
    {
        $model = $this->findModel($id);

        if ($model->load(Yii::$app->request->post()) && $model->save()) {
            return $this->redirect(['view', 'id' => $model->gdgrp_id]);
        } else {
            return $this->render('update', [
                'model' => $model,
            ]);
        }
    }

    /**
     * Deletes an existing Goodgroup model.
     * If deletion is successful, the browser will be redirected to the 'index' page.
     * @param integer $id
     * @return mixed
     */
    public function actionDelete($id)
    {
        $this->findModel($id)->delete();

        return $this->redirect(['index']);
    }

    /**
     * Finds the Goodgroup model based on its primary key value.
     * If the model is not found, a 404 HTTP exception will be thrown.
     * @param integer $id
     * @return Goodgroup the loaded model
     * @throws NotFoundHttpException if the model cannot be found
     */
    protected function findModel($id)
    {
        if (($model = Goodgroup::findOne($id)) !== null) {
            return $model;
        } else {
            throw new NotFoundHttpException('The requested page does not exist.');
        }
    }
}


text:
package com.intuit.karate.robot.win;

import java.util.HashMap;
import java.util.Map;

/**
 *
 * @author pthomas3
 */
public enum Pattern {

    Invoke(10000, IUIAutomationInvokePattern.class),
    Selection(10001),
    Value(10002, IUIAutomationValuePattern.class),
    RangeValue(10003),
    Scroll(10004, IUIAutomationScrollPattern.class),
    ExpandCollapse(10005),
    Grid(10006),
    GridItem(10007),
    MultipleView(10008),
    Window(10009, IUIAutomationWindowPattern.class),
    SelectionItem(10010, IUIAutomationSelectionItemPattern.class),
    Dock(10011),
    Table(10012),
    TableItem(10013),
    Text(10014),
    Toggle(10015),
    Transform(10016),
    ScrollItem(10017),
    LegacyIAccessible(10018),
    ItemContainer(10019),
    VirtualizedItem(10020),
    SynchronizedInput(10021),
    ObjectModel(10022),
    Annotation(10023),
    Text2(10024),
    Styles(10025),
    Spreadsheet(10026),
    SpreadsheetItem(10027),
    Transform2(10028),
    TextChild(10029),
    Drag(10030),
    DropTarget(10031),
    TextEdit(10032),
    CustomNavigation(10033);

    public final int value;
    public final Class type;

    private Pattern(int value) {
        this(value, null);
    }

    private Pattern(int value, Class type) {
        this.value = value;
        this.type = type;
    }

    private static final Map<String, Pattern> FROM_CLASS;
    private static final Map<String, Pattern> FROM_NAME;

    static {
        Pattern[] values = Pattern.values();
        FROM_CLASS = new HashMap(values.length);
        FROM_NAME = new HashMap(values.length);
        for (Pattern p : values) {
            if (p.type != null) {
                FROM_CLASS.put(p.type.getSimpleName(), p);
            }
            FROM_NAME.put(p.name().toLowerCase(), p);
        }
    }

    public static Pattern fromType(Class type) {
        return FROM_CLASS.get(type.getSimpleName());
    }

    public static Pattern fromName(String name) {
        return FROM_NAME.get(name.toLowerCase());
    }

}


text:
import { NgModule } from '@angular/core';
import { CommonModule } from '@angular/common';
import { TooltipDirective } from './tooltip';
import { TiplayerComponent } from './tiplayer';
import { OverlayModule } from '../overlay';

@NgModule({
    imports: [CommonModule, OverlayModule],
    declarations: [TooltipDirective, TiplayerComponent],
    exports: [TooltipDirective, TiplayerComponent],
    entryComponents: [TiplayerComponent]
})
export class TooltipModule { }


text: Migrate GitHub Stars and Following


text:
<?php

namespace Abc\DemoBundle\Listener;

use Abc\Bundle\SchedulerBundle\Event\SchedulerEvent;
use Abc\DemoBundle\Entity\Schedule;

/**
 * @author Hannes Schulz <hannes.schulz@aboutcoders.com>
 */
class DemoListener
{
    /**
     * @var array
     */
    protected $events = [];

    public function onSchedule(SchedulerEvent $event)
    {
        if($event->getSchedule() instanceof Schedule)
        {
            $this->events[] = $event;
        }
    }

    public function clear()
    {
        $this->events = array();
    }

    public function getEvents()
    {
        return $this->events;
    }
}


text:
<?xml version="1.0"?>
<project
	xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"
	xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
	<modelVersion>4.0.0</modelVersion>

	<!-- ##################################### -->
	<!-- Basics Maven Coordinates -->
	<!-- ##################################### -->
	<groupId>avonbo.snippets.java.ruleengine</groupId>
	<artifactId>eventbus</artifactId>
	<version>0.0.1</version>
	<packaging>jar</packaging>

	<parent>
		<groupId>avonbo.snippets.java</groupId>
		<artifactId>ruleengine</artifactId>
		<version>1.0.0</version>
	</parent>

	<!-- ##################################### -->
	<!-- Project Dependencies -->
	<!-- ##################################### -->
	<dependencies>
		<dependency>
			<groupId>com.lmax</groupId>
			<artifactId>disruptor</artifactId>
			<version>3.2.1</version>
		</dependency>
		<dependency>
			<groupId>org.mvel</groupId>
			<artifactId>mvel2</artifactId>
			<version>2.2.5.Final</version>
		</dependency>
		<dependency>
			<groupId>junit</groupId>
			<artifactId>junit</artifactId>
			<version>4.10</version>
			<scope>test</scope>
		</dependency>
	</dependencies>

	<build>
		<pluginManagement>
			<plugins>
				<!-- Compiler plugin enforces Java 1.6 compatibility and activates annotation
					processors -->
				<plugin>
					<artifactId>maven-compiler-plugin</artifactId>
					<version>2.3.2</version>
					<configuration>
						<source>1.8</source>
						<target>1.8</target>
					</configuration>
				</plugin>
			</plugins>
		</pluginManagement>
		<plugins>
			<plugin>
				<artifactId>maven-compiler-plugin</artifactId>
			</plugin>
			<plugin>
				<artifactId>maven-ejb-plugin</artifactId>
			</plugin>

		</plugins>
	</build>

</project>


text:
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.Text;
using PcapDotNet.Base;

namespace PcapDotNet.Packets.Http
{
    internal class HttpParser
    {
        public HttpParser(byte[] buffer)
            :this(buffer, 0, buffer.Length)
        {
        }

        public HttpParser(byte[] buffer, int offset, int length)
        {
            _buffer = buffer;
            _offset = offset;
            _totalLength = offset + length;
            Success = offset >= 0 && length >= 0 && offset + length <= buffer.Length;
        }

        public bool Success { get; private set; }

        public int Offset
        {
            get { return _offset; }
        }

        public HttpParser Token(out Datagram token)
        {
            if (!Success)
            {
                token = null;
                return this;
            }

            int tokenLength = Range.TakeWhile(value => value.IsToken()).Count();
            if (tokenLength == 0)
            {
                token = null;
                return Fail();
            }

            token = new Datagram(_buffer, _offset, tokenLength);
            _offset += token.Length;
            return this;
        }

        public HttpParser Token(out string token)
        {
            Datagram bytesToken;
            Token(out bytesToken);
            token = Success ? bytesToken.Decode(Encoding.ASCII) : null;
            return this;
        }

        public HttpParser Colon()
        {
            return Bytes(AsciiBytes.Colon);
        }

        public HttpParser Dot()
        {
            return Bytes(AsciiBytes.Dot);
        }

        public HttpParser Space()
        {
            return Bytes(AsciiBytes.Space);
        }

        public HttpParser SkipSpaces()
        {
            while (IsNext(AsciiBytes.Space))
                Skip(1);
            return this;
        }

        public HttpParser SkipLws()
        {
            while (true)
            {
                IEnumerable<byte> range = Range;
                byte first = range.FirstOrDefault();
                if (first.IsSpaceOrHorizontalTab()) // ( SP | HT )
                    ++_offset;
                else if (first == AsciiBytes.CarriageReturn) // CR
                {
                    range = range.Skip(1);
                    if (range.FirstOrDefault() != AsciiBytes.Linefeed) // CR without LF
                        break;

                    // CRLF
                    range = range.Skip(1);
                    if (!range.FirstOrDefault().IsSpaceOrHorizontalTab()) // CRLF without ( SP | HT )
                        break;

                    // CRLF ( SP | HT )
                    _offset += 3;
                }
                else
                    break;
            }

            return this;
        }

        public HttpParser FieldContent(out IEnumerable<byte> fieldContent)
        {
            int originalOffset = Offset;
            fieldContent = null;
            while (Success)
            {
                fieldContent = new Datagram(_buffer, originalOffset, Offset - originalOffset);

                if (IsNext(AsciiBytes.Space) || IsNext(AsciiBytes.CarriageReturn) || IsNext(AsciiBytes.HorizontalTab) || IsNext(AsciiBytes.Linefeed))
                    break;

                if (IsNext(AsciiBytes.DoubleQuotationMark))
                {
                    Datagram quotedString;
                    QuotedString(out quotedString);
                }
                else
                {
                    var text = Range.TakeWhile(value => value > 0x20 && value != AsciiBytes.DoubleQuotationMark);
                    if (!text.Any())
                        return Fail();
                    _offset += text.Count();
                }
            }

            return this;
        }

        public HttpParser FieldValue(out IEnumerable<byte> fieldValue)
        {
            if (!Success)
            {
                fieldValue = null;
                return this;
            }

            SkipLws();

            FieldContent(out fieldValue);
            if (!fieldValue.Any())
                return this;

            while (Success)
            {
                IEnumerable<byte> fieldContent;
                SkipLws();

                FieldContent(out fieldContent);
                if (!fieldContent.Any())
                    break;

                fieldValue = fieldValue.Concat(AsciiBytes.Space).Concat(fieldContent);
            }

            return this;
        }

        public HttpParser RequestUri(out string uri)
        {
            if (!Success)
            {
                uri = null;
                return this;
            }

            var range = Range;
            int numChars = range.TakeWhile(value => value > 32).Count();
            uri = EncodingExtensions.Iso88591.GetString(_buffer, _offset, numChars);
            _offset += numChars;
            return this;
        }

        public HttpParser Version(out HttpVersion version)
        {
            uint? major;
            uint? minor;
            Bytes(_httpSlash).DecimalNumber(out major).Dot().DecimalNumber(out minor);
            version = major != null && minor != null ? new HttpVersion(major.Value, minor.Value) : null;
            return this;
        }

        public HttpParser CarriageReturnLineFeed()
        {
            return Bytes(AsciiBytes.CarriageReturn, AsciiBytes.Linefeed);
        }

        public bool IsCarriageReturnLineFeed()
        {
            return IsNext(AsciiBytes.CarriageReturn) && IsNextNext(AsciiBytes.Linefeed);
        }

        public HttpParser DecimalNumber(int numDigits, out uint? number)
        {
            if (numDigits > 8 || numDigits < 0)
                throw new ArgumentOutOfRangeException("numDigits", numDigits, "Only between 0 and 8 digits are supported");

            if (!Success)
            {
                number = null;
                return this;
            }

            var digits = Range.Take(numDigits).TakeWhile(value => value.IsDigit());
            if (digits.Count() != numDigits)
            {
                number = null;
                return Fail();
            }
            number = digits.Select(value => (uint)(value - AsciiBytes.Zero)).Aggregate<uint, uint>(0, (accumulated, value) => 10 * accumulated + value);
            _offset += numDigits;
            return this;
        }

        public HttpParser DecimalNumber(out uint? number)
        {
            if (!Success)
            {
                number = null;
                return this;
            }

            var digits = Range.TakeWhile(value => value.IsDigit());
            if (!digits.Any())
            {
                number = null;
                return Fail();
            }

            int numDigits = digits.Count();
            int numInsignificantDigits = digits.TakeWhile(value => value == AsciiBytes.Zero).Count();
            if (numDigits - numInsignificantDigits > 9)
            {
                number = null;
                return Fail();
            }

            uint numberValue = digits.Select(value => (uint)(value - AsciiBytes.Zero)).Aggregate<uint, uint>(0, (accumulated, value) => 10 * accumulated + value);
            number = numberValue;
            _offset += numDigits;
            return this;
        }

        public HttpParser HexadecimalNumber(out uint? number)
        {
            if (!Success)
            {
                number = null;
                return this;
            }

            var digits = Range.TakeWhile(value => value.IsHexadecimalDigit());
            if (!digits.Any())
            {
                number = null;
                return Fail();
            }

            int numDigits = digits.Count();
            int numInsignificantDigits = digits.TakeWhile(value => value == AsciiBytes.Zero).Count();
            if (numDigits - numInsignificantDigits > 8)
            {
                number = null;
                return Fail();
            }
            uint numberValue = digits.Select(value => (uint)(value.ToHexadecimalValue())).Aggregate<uint, uint>(0, (accumulated, value) => 16 * accumulated + value);
            number = numberValue;
            _offset += numDigits;
            return this;
        }

        public HttpParser ReasonPhrase(out Datagram reasonPhrase)
        {
            if (!Success)
            {
                reasonPhrase = null;
                return this;
            }

            int count = 0;
            foreach (byte b in Range)
            {
                if (!b.IsControl() || b == AsciiBytes.HorizontalTab)
                    ++count;
                else
                    break;
            }
//            Console.WriteLine(count);
            int reasonPhraseLength = Range.TakeWhile(value => !value.IsControl() || value == AsciiBytes.HorizontalTab).Count();
            reasonPhrase = new Datagram(_buffer, _offset, reasonPhraseLength);
            _offset += reasonPhraseLength;
            return this;
        }

        public HttpParser QuotedString(out Datagram quotedString)
        {
            quotedString = null;
            int startOffset = _offset;

            // Parse first "
            if (!Bytes(AsciiBytes.DoubleQuotationMark).Success)
                return this;  // This cannot happen, since we call this method only when we have '"'.

            while (IsNext())
            {
                byte next = Next();

                // Parse last "
                if (next == AsciiBytes.DoubleQuotationMark)
                {
                    ++_offset;
                    quotedString = new Datagram(_buffer, startOffset, _offset - startOffset);
                    return this;
                }

                // Parse \char
                if (next == AsciiBytes.BackSlash && IsNextNext() && NextNext().IsChar())
                    _offset += 2;
                else
                {
                    // parse text
                    int original = _offset;
                    SkipLws();
                    if (original == _offset)
                    {
                        // text isn't LWS - parse a byte that isn't control
                        if (!next.IsControl())
                            ++_offset;
                        else
                            return Fail(); // illegal byte
                    }
                }
            }

            // no " found
            return Fail();
        }

        public HttpParser SkipChunkExtensions()
        {
            while (Success && IsNext(AsciiBytes.Semicolon))
            {
                Bytes(AsciiBytes.Semicolon);

                string chunkExtensionName;
                Token(out chunkExtensionName);
                if (IsNext(AsciiBytes.EqualsSign))
                {
                    Bytes(AsciiBytes.EqualsSign);

                    Datagram chunkExtensionValue;
                    if (IsNext(AsciiBytes.DoubleQuotationMark))
                        QuotedString(out chunkExtensionValue);
                    else
                        Token(out chunkExtensionValue);
                }
            }

            return this;
        }

        private bool IsNext()
        {
            return _offset < _totalLength;
        }

        private bool IsNext(byte next)
        {
            return (IsNext() && Next() == next);
        }

        private bool IsNextNext()
        {
            return _offset + 1 < _totalLength;
        }

        private bool IsNextNext(byte nextNext)
        {
            return (IsNextNext() && NextNext() == nextNext);
        }

        private byte Next()
        {
            return _buffer[_offset];
        }

        private byte NextNext()
        {
            return _buffer[_offset + 1];
        }

        private HttpParser Fail()
        {
            Success = false;
            return this;
        }

        private IEnumerable<byte> Range
        {
            get { return _buffer.Range(_offset, _totalLength - _offset); }
        }

        private HttpParser Bytes(byte value)
        {
            if (!Success)
                return this;

            var range = Range;
            if (!range.Any() || range.First() != value)
                return Fail();

            ++_offset;
            return this;
        }

        private HttpParser Bytes(params byte[] values)
        {
            if (!Success)
                return this;

            if (!Range.Take(values.Length).SequenceEqual(values))
                return Fail();

            _offset += values.Length;
            return this;
        }

        public HttpParser Skip(int count)
        {
            _offset += count;
            if (_offset > _totalLength)
                return Fail();
            return this;
        }

        private static readonly byte[] _httpSlash = Encoding.ASCII.GetBytes("HTTP/");

        private readonly byte[] _buffer;
        private int _offset;
        private readonly int _totalLength;
    }
}


text:
using Azure.ResourceManager.Core;

namespace Azure.ResourceManager.Models
{
    /// <summary> The KeyVaultProperties. </summary>
    [PropertyReferenceType]
    public partial class KeyVaultProperties
    {
        /// <summary> Initializes a new instance of KeyVaultProperties. </summary>
        [InitializationConstructor]
        public KeyVaultProperties()
        {
        }

        /// <summary> Initializes a new instance of KeyVaultProperties. </summary>
        /// <param name="keyIdentifier"> Key vault uri to access the encryption key. </param>
        /// <param name="identity"> The client ID of the identity which will be used to access key vault. </param>
        [SerializationConstructor]
        internal KeyVaultProperties(string keyIdentifier, string identity)
        {
            KeyIdentifier = keyIdentifier;
            Identity = identity;
        }

        /// <summary> Key vault uri to access the encryption key. </summary>
        public string KeyIdentifier { get; set; }
        /// <summary> The client ID of the identity which will be used to access key vault. </summary>
        public string Identity { get; set; }
    }
}


text:
<!--
  Licensed to the Apache Software Foundation (ASF) under one
  or more contributor license agreements.  See the NOTICE file
  distributed with this work for additional information
  regarding copyright ownership.  The ASF licenses this file
  to you 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.
-->

<workflow-app name="hs-total-002" xmlns="uri:oozie:workflow:0.4">
  <global>
            <configuration>
                <property>
                    <name>jobTracker</name>
                    <value>karma-dig-3.hdp.azure.karma.isi.edu:8050</value>
                </property>
            </configuration>
  </global>
    <start to="de_page_backpage"/>
    <action name="de_page_backpage">
        <map-reduce>
            <job-tracker>${jobTracker}</job-tracker>
            <name-node>${nameNode}</name-node>
            <configuration>
                <property>
                    <name>mapred.mapper.new-api</name>
                    <value>true</value>
                </property>
                <property>
                    <name>mapred.reducer.new-api</name>
                    <value>true</value>
                </property>
                <!-- <property> -->
                <!--     <name>mapreduce.job.map.class</name> -->
                <!--     <value>edu.isi.karma.mapreduce.driver.N3Mapper</value> -->
                <!-- </property> -->
                <!-- <property> -->
                <!--     <name>mapreduce.job.reduce.class</name> -->
                <!--     <value>edu.isi.karma.mapreduce.driver.N3Reducer</value> -->
                <!-- </property> -->
                <property>
                    <name>mapreduce.map.output.key.class</name>
                    <value>org.apache.hadoop.io.Text</value>
                </property>
                <property>
                    <name>mapreduce.map.output.value.class</name>
                    <value>org.apache.hadoop.io.Text</value>
                </property>
                <property>
                    <name>mapred.input.key.class</name>
                    <value>org.apache.hadoop.io.Text</value>
                </property>
                <property>
                    <name>mapred.input.value.class</name>
                    <value>org.apache.hadoop.io.Text</value>
                </property>
                <property>
                    <name>mapreduce.inputformat.class</name>
                    <value>org.apache.hadoop.mapreduce.lib.input.SequenceFileAsTextInputFormat</value>
                </property>
                <property>
                    <name>mapreduce.outputformat.class</name>
                    <value>org.apache.hadoop.mapreduce.lib.output.SequenceFileOutputFormat</value>
                </property>
                <!-- <property> -->
                <!--     <name>model.file</name> -->
                <!--     <value>people-model.ttl</value> -->
                <!-- </property> -->
                <property>
                    <name>mapred.input.dir</name>
                    <value>/user/philpot/hs-total-002_input</value>
                </property>
                <property>
                    <name>mapred.output.dir</name>
                    <value>/user/philpot/hs-total-003_output</value>
                </property>
            </configuration>
            <!-- <file>./people-model.ttl#people-model.ttl</file> -->
            <!-- <archive>./karma.zip#karma.zip</archive> -->
            <streaming>
                <mapper>python dig.extract.page.backpage</mapper>
                <reducer>org.apache.hadoop.mapred.lib.IdentityReducer</reducer>
            </streaming>
            <archive>./digvenv.zip#dig</archive>
        </map-reduce>
        <ok to="fork_backpage_data"/>
        <error to="kill"/>
    </action>
    <fork name="fork_backpage_data">
        <path start="de_entity_digtoken" />
        <path start="de_entity_phone" />
    </fork>
    <action name="de_entity_digtoken">
        <map-reduce>
            <job-tracker>${jobTracker}</job-tracker>
            <name-node>${nameNode}</name-node>
            <streaming>
                <mapper>python dig.extract.entity.digtoken</mapper>
                <reducer>org.apache.hadoop.mapred.lib.IdentityReducer</reducer>
            </streaming>
            <archive>/opt/dig/venv/digvenv.zip</archive>
        </map-reduce>
        <ok to="fork_digtoken_data"/>
        <error to="kill"/>
    </action>
    <fork name="fork_digtoken_data">
        <path start="de_entity_workingname_workingname" />
        <path start="de_entity_classifier_patscan" />
    </fork>
    <action name="de_entity_workingname_workingname">
        <map-reduce>
            <job-tracker>${jobTracker}</job-tracker>
            <name-node>${nameNode}</name-node>
            <streaming>
                <mapper>python dig.extract.entity.workingname.workingname</mapper>
                <reducer>org.apache.hadoop.mapred.lib.IdentityReducer</reducer>
            </streaming>
            <archive>/opt/dig/venv/digvenv.zip</archive>
        </map-reduce>
        <ok to="join-303"/>
        <error to="kill"/>
    </action>
    <action name="de_entity_classifier_patscan">
        <map-reduce>
            <job-tracker>${jobTracker}</job-tracker>
            <name-node>${nameNode}</name-node>
            <streaming>
                <mapper>python dig.extract.entity.classlfier.patscan -c "ageSelect" -c "agency" -c "briefDuration" -c "ethnicityNationality" -c "incall" -c "incalloutcall" -c "multiProvider" -c "notagency" -c "notincall" -c "notoutcall" -c "outcall" -c "providerYouth" -c "raceEthnicSelect" -c "spa"</mapper>
                <reducer>org.apache.hadoop.mapred.lib.IdentityReducer</reducer>
            </streaming>
            <archive>/opt/dig/venv/digvenv.zip</archive>
        </map-reduce>
        <ok to="join-303"/>
        <error to="kill"/>
    </action>
    <join name="join-303" to="join-300"/>
    <action name="de_entity_phone">
        <map-reduce>
            <job-tracker>${jobTracker}</job-tracker>
            <name-node>${nameNode}</name-node>
            <streaming>
                <mapper>python dig.extract.entity.phone</mapper>
                <reducer>org.apache.hadoop.mapred.lib.IdentityReducer</reducer>
            </streaming>
            <archive>/opt/dig/venv/digvenv.zip</archive>
        </map-reduce>
        <ok to="join-300"/>
        <error to="kill"/>
    </action>
    <join name="join-300" to="end"/>
    <kill name="kill">
        <message>Action failed, error message[${wf:errorMessage(wf:lastErrorNode())}]</message>
    </kill>
    <end name="end"/>
</workflow-app>


text:
jQuery(document).ready(function() {
    $('#advancedSearchBtn').on('click', function(e) {
        e.preventDefault();

        $('#basicSearch').fadeOut(400, function(){
            $('#advancedSearch').fadeIn();
        });

    });

    $('#simpleSearchBtn').on('click', function(e) {
        e.preventDefault();

        $('#advancedSearch').fadeOut(400, function(){
            $('#basicSearch').fadeIn();
        });

    });

    $('.form-search').on('submit', function(e) {
        e.preventDefault();

        $.ajax({
            type: "POST",
            url: $(this).attr('action'),
            data: $(this).serialize(),
            success: function(data)
            {
                $('#results_datagrid').html(data);
                if ($('.resetSearchBtn').css('display') == 'none') {
                    $('.resetSearchBtn').css({
                        opacity: 0,
                        display: 'inline-block'
                    }).animate({opacity:1},600);
                }

            }
        });
    });

    $('.resetSearchBtn button').on('click', function(e) {
        e.preventDefault();
        $.ajax({
            type: "POST",
            url: $('#formFilter').attr('action'),
            success: function(data)
            {
                $('#results_datagrid').html(data);
            }
        });
        $('.form-search').trigger("reset");
        $('.resetSearchBtn').css({
            opacity: 100,
            display: 'none'
        }).animate({opacity:1},600);
    });

    $('#results_datagrid').on('click', '.sortable, .pagerBtn', function(e) {
        e.preventDefault();
        var action = $(this).attr('href');

        $.ajax({
            type: "POST",
            url: action,
            data: $('.form-search:visible').serialize(),
            success: function(data)
            {
                $('#results_datagrid').html(data);
            }
        });
    });

    $('#results_datagrid').on('change', '#pagerDropdownInput',  function(e) {
        e.preventDefault();

        if ($.isNumeric($(this).val())) {
            var action = $('#formFilter').attr('action') + '?page='+$(this).val();

            $.ajax({
                type: "POST",
                url: action,
                data: $('.form-search:visible').serialize(),
                success: function(data)
                {
                    $('#results_datagrid').html(data);
                }
            });
        }
        else {
            $(this).val('NaN');
        }
    });

});


text:
package main

import (
	"time"

	"github.com/mxk/go-sqlite/sqlite3"
	"gopkg.in/go-playground/validator.v8"
)

type ReviewService struct {
	dbConn *sqlite3.Conn
}

func (rs ReviewService) Create(r *Review) error {
	r.TimeCreated = time.Now()
	r.Status = 1

	sql := "INSERT INTO review (isbn, rating, content, user_id, status, time_created) VALUES ($isbn, $rating, $content, $user_id, $status, $time_created)"
	args := sqlite3.NamedArgs{
		"$isbn":         r.Isbn,
		"$rating":       r.Rating,
		"$content":      r.Content,
		"$user_id":      r.UserId,
		"$status":       r.Status,
		"$time_created": r.TimeCreated,
	}

	return rs.dbConn.Exec(sql, args)
}

func (rs ReviewService) getReviewsByIsbn(isbn string) ReviewCollection {
	rc := ReviewCollection{}

	sql := "SELECT id, isbn, user_id,rating, content, status, time_created FROM review WHERE isbn = $isbn"
	args := sqlite3.NamedArgs{"$isbn": isbn}

	row := make(sqlite3.RowMap)
	for s, err := rs.dbConn.Query(sql, args); err == nil; err = s.Next() {
		var rowId int
		var rowIsbn string
		var rowUserId string
		var rowRating int
		var rowContent string
		var rowStatus int
		var rowTimeCreated time.Time

		s.Scan(rowId, rowIsbn, rowUserId, rowRating, rowContent, rowStatus, rowTimeCreated, row)

		r := Review{
			Id:          rowId,
			Isbn:        rowIsbn,
			UserId:      rowUserId,
			Status:      rowStatus,
			Rating:      rowRating,
			Content:     rowContent,
			TimeCreated: rowTimeCreated,
		}

		rc = append(rc, r)
	}

	return rc
}

func (rs ReviewService) Validate(r *Review) error {
	config := &validator.Config{TagName: "validate"}
	validate := validator.New(config)

	return validate.Struct(r)
}


text:
package org.jclouds.reflect;

import static com.google.common.base.Objects.equal;
import static com.google.common.base.Preconditions.checkNotNull;

import org.jclouds.javax.annotation.Nullable;

import com.google.common.annotations.Beta;
import com.google.common.base.Objects;
import com.google.common.base.Objects.ToStringHelper;
import com.google.common.base.Optional;

/**
 * Holds the context of a successful call to {@link com.google.common.reflect.Invokable#invoke(Object, Object...)}
 */
@Beta
public final class InvocationSuccess {
   public static InvocationSuccess create(Invocation invocation, @Nullable Object result) {
      return new InvocationSuccess(invocation, Optional.fromNullable(result));
   }

   private final Invocation invocation;
   private final Optional<Object> result;

   private InvocationSuccess(Invocation invocation, Optional<Object> result) {
      this.invocation = checkNotNull(invocation, "invocation");
      this.result = checkNotNull(result, "result");
   }

   /**
    * what was invocation
    */
   public Invocation getInvocation() {
      return invocation;
   }

   public Optional<Object> getResult() {
      return result;
   }

   @Override
   public boolean equals(Object o) {
      if (this == o)
         return true;
      if (o == null || getClass() != o.getClass())
         return false;
      InvocationSuccess that = InvocationSuccess.class.cast(o);
      return equal(this.invocation, that.invocation) && equal(this.result.orNull(), that.result.orNull());
   }

   @Override
   public int hashCode() {
      return Objects.hashCode(invocation, result.orNull());
   }

   @Override
   public String toString() {
      return string().toString();
   }

   protected ToStringHelper string() {
      return Objects.toStringHelper("").omitNullValues().add("invocation", invocation).add("result", result.orNull());
   }
}


text:
package me.blackphreak.dynamicdungeon.MapBuilding.Objects;

import java.util.AbstractMap;
import java.util.function.BiConsumer;

public abstract class DungeonObject {
    private String type;
    private String name; // custom name of this object
    private int x;
    private int y;
    private int z;

    public DungeonObject(String type, int x, int y, int z) {
        this.type = type;
        this.name = "";
        this.x = x;
        this.y = y;
        this.z = z;
    }

    public DungeonObject(String type, String name, int x, int y, int z) {
        this.type = type;
        this.name = name;
        this.x = x;
        this.y = y;
        this.z = z;
    }

    public abstract AbstractMap.SimpleEntry<String, BiConsumer<DungeonObject, Object>> getOperation();

    public void setX(int x) {
        this.x = x;
    }

    public void setY(int y) {
        this.y = y;
    }

    public void setZ(int z) {
        this.z = z;
    }

    public void setType(String type)
    {
        this.type = type;
    }

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

    public int getX() {
        return x;
    }

    public int getY() {
        return y;
    }

    public int getZ() {
        return z;
    }

    public String getType() {
        return type;
    }

    public String getName()
    {
        return name;
    }

    @Override
    public String toString() {
        String r = "";
        r += "X:" + x + "\n";
        r += "Y:" + y + "\n";
        r += "Z:" + z + "\n";
        return r;
    }
}


text:
NAME=sfl2img
CCSRCS=$(NAME).cpp

#
# Dependency libraries
#

PKG_LIBS=-lR3Surfels -lR3Shapes -lR2Shapes -lRNBasics -ljpeg -lpng

#
# R3 application makefile
#

include ../../makefiles/Makefile.apps


text:
package ramsql

import (
	"database/sql"
	"fmt"
	"io/ioutil"
	"os"
	"path"
	"strings"
)

// InitSchemas execute each query in provided sql file
// Expected sql file path into $GOPATH/src
func InitSchemas(db *sql.DB, sqlfile string) error {
	gopath := os.Getenv("GOPATH")

	content, err := ioutil.ReadFile(path.Join(gopath, "src", sqlfile))
	if err != nil {
		return err
	}

	queries := strings.Split(string(content), ";")

	for _, q := range queries {
		q = strings.Trim(q, "\n")

		if q == "" {
			continue
		}

		_, err := db.Exec(q)
		if err != nil {
			return fmt.Errorf("Query '%s': %s", q, err)
		}

	}

	return nil
}


text:
void LDL_AES_init(struct lora_aes_ctx *ctx, const void *key)
{
}

void LDL_AES_encrypt(const struct lora_aes_ctx *ctx, void *s)
{
}

void LDL_AES_decrypt(const struct lora_aes_ctx *ctx, void *s)
{
}


text:
package live_reload

type Events interface {
	// Called when a livereload is triggered
	ReloadTriggered(targets []string)
}


text:
These [RelaxNG][rng] grammar files for XSLT were downloaded from
[Norman Walsh's GitHub repository][ndw] and converted to `.rng` with
[`trang`][trang].

[ndw]: https://github.com/ndw/xslt-relax-ng
[rng]: http://relaxng.org/
[trang]: http://www.thaiopensource.com/relaxng/trang.html


text:
name             'ccache'
maintainer       'Travis CI GmbH'
maintainer_email 'support@travis-ci.com'
license          'MIT'
description      'Installs/Configures ccache'
long_description IO.read(File.join(File.dirname(__FILE__), 'README.md'))
version          '0.1.0'


text:
package org.cytargetlinker.app.internal.ui;

import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Component;
import java.awt.Dimension;
import java.awt.Point;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.swing.JButton;
import javax.swing.JCheckBox;
import javax.swing.JDialog;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JScrollPane;

import org.cytargetlinker.app.internal.CTLManager;
import org.cytargetlinker.app.internal.data.Direction;
import org.cytargetlinker.app.internal.tasks.ExtendNetworkTaskFactory;
import org.cytoscape.model.CyNetwork;
import org.cytoscape.work.TaskIterator;
import org.cytoscape.work.swing.DialogTaskManager;

import com.jgoodies.forms.builder.PanelBuilder;
import com.jgoodies.forms.layout.CellConstraints;
import com.jgoodies.forms.layout.FormLayout;

/**
 *
 * @author mkutmon
 * dialog to choose which RegINs should be used
 *
 */
public class LinksetSelectionDlg extends JDialog {

	private Map<String, File> map;
	private List<File> linkSets;
	private List<File> selectedLinkSets;
	private Map<String, JCheckBox> cbMap;
	private CTLManager manager;
	private CyNetwork network;
	private String idAttribute;
	private Direction direction;

	private CellConstraints cc;

	public LinksetSelectionDlg(CTLManager manager, CyNetwork network, String idAttribute, Direction direction, String lsDir) {
		super(manager.getApplicationFrame());
		cc = new CellConstraints();
		map = new HashMap<String, File>();
		this.manager = manager;
		this.network = network;
		this.idAttribute = idAttribute;
		this.direction = direction;
		selectedLinkSets = new ArrayList<File>();
		linkSets = new ArrayList<File>();

		for(File f : new File(lsDir).listFiles()) {
			if(f.getName().endsWith(".xgmml")) {
				linkSets.add(f);
				map.put(f.getName(), f);
			}
		}

		cbMap = new HashMap<String, JCheckBox>();

		this.add(getContent());
		locate();
		this.setResizable(false);
		this.pack();
	}

	private JPanel getContent() {
		JPanel panel = new JPanel();
		panel.setBackground(Color.WHITE);
		panel.setLayout(new BorderLayout(1,1));

		panel.add(getMainPanel(), BorderLayout.CENTER);
		panel.add(getCancelOkPanel(), BorderLayout.SOUTH);
		return panel;
	}

	private Component getMainPanel() {
		FormLayout layout = new FormLayout("10dlu, p, 5dlu, p, 10dlu", getRowLayout());
		PanelBuilder builder = new PanelBuilder(layout);
		builder.add(new JLabel("Linkset Files"), cc.xy(2, 2));
		builder.addSeparator("", cc.xyw(2, 3, 3));
		int i = 0;

		for(File f : linkSets) {
			builder.add(new JLabel(f.getName()), cc.xy(2, 2*i+5));
			JCheckBox box = new JCheckBox();
			box.setSelected(true);
			builder.add(box, cc.xy(4, 2*i+5));
			cbMap.put(f.getName(), box);
			i++;
		}

		JScrollPane pane = new JScrollPane(builder.getPanel());
		return pane;
	}

	private JPanel getCancelOkPanel() {
		FormLayout layout = new FormLayout("right:max(72dlu;p), 10dlu, 72dlu, 10dlu", "5dlu, p, 5dlu");
		PanelBuilder builder = new PanelBuilder(layout);
		builder.setDefaultDialogBorder();
		JButton button1 = new JButton("Cancel");
		button1.addActionListener(new ActionListener() {

			@Override
			public void actionPerformed(ActionEvent arg0) {
				dispose();
			}
		});

		builder.add(button1, cc.xy(1, 2));
		JButton button2 = new JButton("Ok");
		button2.addActionListener(new ActionListener() {

			@Override
			public void actionPerformed(ActionEvent e) {
				for(String str : cbMap.keySet()) {
					if(cbMap.get(str).isSelected()) {
						selectedLinkSets.add(map.get(str));
					}
				}
				dispose();
				{
					ExtendNetworkTaskFactory fact = new ExtendNetworkTaskFactory(manager);
					TaskIterator it = fact.createTaskIterator(network, selectedLinkSets, idAttribute, direction, true);
					manager.getService(DialogTaskManager.class).execute(it);
				}
			}
		});

		builder.add(button2, cc.xy(3, 2));
		return builder.getPanel();
	}

	private String getRowLayout() {
		String str = "10dlu, p, 15dlu, 5dlu";
		for(int i = 0; i < linkSets.size(); i++) {
			str = str + ",p,5dlu";
		}
		str = str + ",10dlu";
		return str;
	}

	private void locate() {
		int sizeX = 400;
		int sizeY = 400;
		this.setPreferredSize(new Dimension(sizeX, sizeY));

		Point cyLocation = manager.getApplicationFrame().getLocation();
		int cyHeight = manager.getApplicationFrame().getHeight();
		int cyWidth = manager.getApplicationFrame().getWidth();

		Point middle = new Point(cyLocation.x + (cyWidth / 2), cyLocation.y + (cyHeight / 2));

		int locX = middle.x - (sizeX / 2);
		int locY = middle.y - (sizeY / 2);
		this.setLocation(new Point(locX, locY));
	}
}


text:
var dotfile = require('../'),
  path = require('path'),
  assert = require('assert');

assert.equal(dotfile._version, require('../package').version);
assert.ok(dotfile._tilde);

var dotfiles = {
  foo_fff0z: dotfile('foo_fff0z'),
  bar_fff0z: dotfile('bar_fff0z'),
  baz_fff0z: dotfile('baz_fff0z', {
    dirname: path.join(dotfile._tilde, 'baz')
  })
};

var cfgs = {
  foo_fff0z: {
    a: [1, 2, 3],
    b: {
      c: {
        d: 'EEE!'
      }
    }
  },
  bar_fff0z: 'I AM A PONEYCORN!'
};

//
// for each dotfile being save
//
['foo_fff0z', 'bar_fff0z'].forEach(function (wat) {
  //
  // make sure there's no left overs
  // this can be cause when exceptions bubble up
  //
  dotfiles[wat].unlink(function (err) {
    //
    // files should not exist right now
    //
    dotfiles[wat].exists(function (yesno) {
      assert.equal(yesno, false);
      //
      // write the dotfile
      //
      dotfiles[wat].write(cfgs[wat], function (err) {
        assert.equal(err, null);
        //
        // read the dotfile
        //
        dotfiles[wat].read(function (err, fromdisk) {
          assert.equal(err, null);
          //
          // make sure what was written and read matches
          //
          assert.deepEqual(cfgs[wat], fromdisk);
          //
          // file should now exist
          //
          dotfiles[wat].exists(function (yesno) {
            assert.ok(yesno);
            //
            // unlink just to keep things tidy (redundant);
            //
            dotfiles[wat].unlink(function (err) {
              assert.ok(!err);
            });
          });
        });
      });
    });
  });
});

//
// this dot file exists to
// assert if the current dirname
// implementation is working
//
dotfiles.baz_fff0z.exists(function (yn) {
  assert.equal(yn, false);
  assert.equal(path.join(dotfile._tilde, 'baz', '.baz_fff0z.json'), dotfiles.baz_fff0z.filepath);
});

//
// ALL DONE
//
console.log('ok DINOSAURS!');