text:
#include "../../SDL_internal.h"

#if SDL_VIDEO_DRIVER_X11

#include "SDL.h"
#include "SDL_x11video.h"
#include "SDL_x11dyn.h"
#include "SDL_x11messagebox.h"

#include <X11/keysym.h>
#include <locale.h>

#define SDL_FORK_MESSAGEBOX 1
#define SDL_SET_LOCALE      1

#if SDL_FORK_MESSAGEBOX
#include <sys/types.h>
#include <sys/wait.h>
#include <unistd.h>
#include <errno.h>
#endif

#define MAX_BUTTONS             8       /* Maximum number of buttons supported */
#define MIN_BUTTON_WIDTH        64      /* Minimum button width */
#define MIN_DIALOG_WIDTH        200     /* Minimum dialog width */
#define MIN_DIALOG_HEIGHT       100     /* Minimum dialog height */

static const char g_MessageBoxFontLatin1[] = "-*-*-medium-r-normal--0-120-*-*-p-0-iso8859-1";
static const char g_MessageBoxFont[] = "-*-*-medium-r-normal--*-120-*-*-*-*-*-*";

static const SDL_MessageBoxColor g_default_colors[ SDL_MESSAGEBOX_COLOR_MAX ] = {
    { 56,  54,  53  }, /* SDL_MESSAGEBOX_COLOR_BACKGROUND, */
    { 209, 207, 205 }, /* SDL_MESSAGEBOX_COLOR_TEXT, */
    { 140, 135, 129 }, /* SDL_MESSAGEBOX_COLOR_BUTTON_BORDER, */
    { 105, 102, 99  }, /* SDL_MESSAGEBOX_COLOR_BUTTON_BACKGROUND, */
    { 205, 202, 53  }, /* SDL_MESSAGEBOX_COLOR_BUTTON_SELECTED, */
};

#define SDL_MAKE_RGB( _r, _g, _b )  ( ( ( Uint32 )( _r ) << 16 ) | \
                                      ( ( Uint32 )( _g ) << 8 ) |  \
                                      ( ( Uint32 )( _b ) ) )

typedef struct SDL_MessageBoxButtonDataX11 {
    int x, y;                           /* Text position */
    int length;                         /* Text length */
    int text_width;                     /* Text width */

    SDL_Rect rect;                      /* Rectangle for entire button */

    const SDL_MessageBoxButtonData *buttondata;   /* Button data from caller */
} SDL_MessageBoxButtonDataX11;

typedef struct TextLineData {
    int width;                          /* Width of this text line */
    int length;                         /* String length of this text line */
    const char *text;                   /* Text for this line */
} TextLineData;

typedef struct SDL_MessageBoxDataX11
{
    Display *display;
    int screen;
    Window window;
#if SDL_VIDEO_DRIVER_X11_XDBE
    XdbeBackBuffer buf;
    SDL_bool xdbe;                      /* Whether Xdbe is present or not */
#endif
    long event_mask;
    Atom wm_protocols;
    Atom wm_delete_message;

    int dialog_width;                   /* Dialog box width. */
    int dialog_height;                  /* Dialog box height. */

    XFontSet font_set;                  /* for UTF-8 systems */
    XFontStruct *font_struct;           /* Latin1 (ASCII) fallback. */
    int xtext, ytext;                   /* Text position to start drawing at. */
    int numlines;                       /* Count of Text lines. */
    int text_height;                    /* Height for text lines. */
    TextLineData *linedata;

    int *pbuttonid;                     /* Pointer to user return buttonid value. */

    int button_press_index;             /* Index into buttondata/buttonpos for button which is pressed (or -1). */
    int mouse_over_index;               /* Index into buttondata/buttonpos for button mouse is over (or -1). */

    int numbuttons;                     /* Count of buttons. */
    const SDL_MessageBoxButtonData *buttondata;
    SDL_MessageBoxButtonDataX11 buttonpos[ MAX_BUTTONS ];

    Uint32 color[ SDL_MESSAGEBOX_COLOR_MAX ];

    const SDL_MessageBoxData *messageboxdata;
} SDL_MessageBoxDataX11;

/* Maximum helper for ints. */
static SDL_INLINE int
IntMax( int a, int b )
{
    return ( a > b  ) ? a : b;
}

/* Return width and height for a string. */
static void
GetTextWidthHeight( SDL_MessageBoxDataX11 *data, const char *str, int nbytes, int *pwidth, int *pheight )
{
    if (SDL_X11_HAVE_UTF8) {
        XRectangle overall_ink, overall_logical;
        X11_Xutf8TextExtents(data->font_set, str, nbytes, &overall_ink, &overall_logical);
        *pwidth = overall_logical.width;
        *pheight = overall_logical.height;
    } else {
        XCharStruct text_structure;
        int font_direction, font_ascent, font_descent;
        X11_XTextExtents( data->font_struct, str, nbytes,
                      &font_direction, &font_ascent, &font_descent,
                      &text_structure );
        *pwidth = text_structure.width;
        *pheight = text_structure.ascent + text_structure.descent;
    }
}

/* Return index of button if position x,y is contained therein. */
static int
GetHitButtonIndex( SDL_MessageBoxDataX11 *data, int x, int y )
{
    int i;
    int numbuttons = data->numbuttons;
    SDL_MessageBoxButtonDataX11 *buttonpos = data->buttonpos;

    for ( i = 0; i < numbuttons; i++ ) {
        SDL_Rect *rect = &buttonpos[ i ].rect;

        if ( ( x >= rect->x ) &&
             ( x <= ( rect->x + rect->w ) ) &&
             ( y >= rect->y ) &&
             ( y <= ( rect->y + rect->h ) ) ) {
            return i;
        }
    }

    return -1;
}

/* Initialize SDL_MessageBoxData structure and Display, etc. */
static int
X11_MessageBoxInit( SDL_MessageBoxDataX11 *data, const SDL_MessageBoxData * messageboxdata, int * pbuttonid )
{
    int i;
    int numbuttons = messageboxdata->numbuttons;
    const SDL_MessageBoxButtonData *buttondata = messageboxdata->buttons;
    const SDL_MessageBoxColor *colorhints;

    if ( numbuttons > MAX_BUTTONS ) {
        return SDL_SetError("Too many buttons (%d max allowed)", MAX_BUTTONS);
    }

    data->dialog_width = MIN_DIALOG_WIDTH;
    data->dialog_height = MIN_DIALOG_HEIGHT;
    data->messageboxdata = messageboxdata;
    data->buttondata = buttondata;
    data->numbuttons = numbuttons;
    data->pbuttonid = pbuttonid;

    data->display = X11_XOpenDisplay( NULL );
    if ( !data->display ) {
        return SDL_SetError("Couldn't open X11 display");
    }

    if (SDL_X11_HAVE_UTF8) {
        char **missing = NULL;
        int num_missing = 0;
        data->font_set = X11_XCreateFontSet(data->display, g_MessageBoxFont,
                                        &missing, &num_missing, NULL);
        if ( missing != NULL ) {
            X11_XFreeStringList(missing);
        }
        if ( data->font_set == NULL ) {
            return SDL_SetError("Couldn't load font %s", g_MessageBoxFont);
        }
    } else {
        data->font_struct = X11_XLoadQueryFont( data->display, g_MessageBoxFontLatin1 );
        if ( data->font_struct == NULL ) {
            return SDL_SetError("Couldn't load font %s", g_MessageBoxFontLatin1);
        }
    }

    if ( messageboxdata->colorScheme ) {
        colorhints = messageboxdata->colorScheme->colors;
    } else {
        colorhints = g_default_colors;
    }

    /* Convert our SDL_MessageBoxColor r,g,b values to packed RGB format. */
    for ( i = 0; i < SDL_MESSAGEBOX_COLOR_MAX; i++ ) {
        data->color[ i ] = SDL_MAKE_RGB( colorhints[ i ].r, colorhints[ i ].g, colorhints[ i ].b );
    }

    return 0;
}

static int
CountLinesOfText(const char *text)
{
    int retval = 0;
    while (text && *text) {
        const char *lf = SDL_strchr(text, '\n');
        retval++;  /* even without an endline, this counts as a line. */
        text = lf ? lf + 1 : NULL;
    }
    return retval;
}

/* Calculate and initialize text and button locations. */
static int
X11_MessageBoxInitPositions( SDL_MessageBoxDataX11 *data )
{
    int i;
    int ybuttons;
    int text_width_max = 0;
    int button_text_height = 0;
    int button_width = MIN_BUTTON_WIDTH;
    const SDL_MessageBoxData *messageboxdata = data->messageboxdata;

    /* Go over text and break linefeeds into separate lines. */
    if ( messageboxdata->message[0] ) {
        const char *text = messageboxdata->message;
        const int linecount = CountLinesOfText(text);
        TextLineData *plinedata = (TextLineData *) SDL_malloc(sizeof (TextLineData) * linecount);

        if (!plinedata) {
            return SDL_OutOfMemory();
        }

        data->linedata = plinedata;
        data->numlines = linecount;

        for ( i = 0; i < linecount; i++, plinedata++ ) {
            const char *lf = SDL_strchr( text, '\n' );
            const int length = lf ? ( lf - text ) : SDL_strlen( text );
            int height;

            plinedata->text = text;

            GetTextWidthHeight( data, text, length, &plinedata->width, &height );

            /* Text and widths are the largest we've ever seen. */
            data->text_height = IntMax( data->text_height, height );
            text_width_max = IntMax( text_width_max, plinedata->width );

            plinedata->length = length;
            if (lf && (lf > text) && (lf[-1] == '\r')) {
                plinedata->length--;
            }

            text += length + 1;

            /* Break if there are no more linefeeds. */
            if ( !lf )
                break;
        }

        /* Bump up the text height slightly. */
        data->text_height += 2;
    }

    /* Loop through all buttons and calculate the button widths and height. */
    for ( i = 0; i < data->numbuttons; i++ ) {
        int height;

        data->buttonpos[ i ].buttondata = &data->buttondata[ i ];
        data->buttonpos[ i ].length = SDL_strlen( data->buttondata[ i ].text );

        GetTextWidthHeight( data, data->buttondata[ i ].text, SDL_strlen( data->buttondata[ i ].text ),
                            &data->buttonpos[ i ].text_width, &height );

        button_width = IntMax( button_width, data->buttonpos[ i ].text_width );
        button_text_height = IntMax( button_text_height, height );
    }

    if ( data->numlines ) {
        /* x,y for this line of text. */
        data->xtext = data->text_height;
        data->ytext = data->text_height + data->text_height;

        /* Bump button y down to bottom of text. */
        ybuttons = 3 * data->ytext / 2 + ( data->numlines - 1 ) * data->text_height;

        /* Bump the dialog box width and height up if needed. */
        data->dialog_width = IntMax( data->dialog_width, 2 * data->xtext + text_width_max );
        data->dialog_height = IntMax( data->dialog_height, ybuttons );
    } else {
        /* Button y starts at height of button text. */
        ybuttons = button_text_height;
    }

    if ( data->numbuttons ) {
        int x, y;
        int width_of_buttons;
        int button_spacing = button_text_height;
        int button_height = 2 * button_text_height;

        /* Bump button width up a bit. */
        button_width += button_text_height;

        /* Get width of all buttons lined up. */
        width_of_buttons = data->numbuttons * button_width + ( data->numbuttons - 1 ) * button_spacing;

        /* Bump up dialog width and height if buttons are wider than text. */
        data->dialog_width = IntMax( data->dialog_width, width_of_buttons + 2 * button_spacing );
        data->dialog_height = IntMax( data->dialog_height, ybuttons + 2 * button_height );

        /* Location for first button. */
        if ( messageboxdata->flags & SDL_MESSAGEBOX_BUTTONS_RIGHT_TO_LEFT ) {
            x = data->dialog_width - ( data->dialog_width - width_of_buttons ) / 2 - ( button_width + button_spacing );
        } else {
            x = ( data->dialog_width - width_of_buttons ) / 2;
        }
        y = ybuttons + ( data->dialog_height - ybuttons - button_height ) / 2;

        for ( i = 0; i < data->numbuttons; i++ ) {
            /* Button coordinates. */
            data->buttonpos[ i ].rect.x = x;
            data->buttonpos[ i ].rect.y = y;
            data->buttonpos[ i ].rect.w = button_width;
            data->buttonpos[ i ].rect.h = button_height;

            /* Button text coordinates. */
            data->buttonpos[ i ].x = x + ( button_width - data->buttonpos[ i ].text_width ) / 2;
            data->buttonpos[ i ].y = y + ( button_height - button_text_height - 1 ) / 2 + button_text_height;

            /* Scoot over for next button. */
            if ( messageboxdata->flags & SDL_MESSAGEBOX_BUTTONS_RIGHT_TO_LEFT ) {
                x -= button_width + button_spacing;
            } else {
                x += button_width + button_spacing;
            }
        }
    }

    return 0;
}

/* Free SDL_MessageBoxData data. */
static void
X11_MessageBoxShutdown( SDL_MessageBoxDataX11 *data )
{
    if ( data->font_set != NULL ) {
        X11_XFreeFontSet( data->display, data->font_set );
        data->font_set = NULL;
    }

    if ( data->font_struct != NULL ) {
        X11_XFreeFont( data->display, data->font_struct );
        data->font_struct = NULL;
    }

#if SDL_VIDEO_DRIVER_X11_XDBE
    if ( SDL_X11_HAVE_XDBE && data->xdbe ) {
        X11_XdbeDeallocateBackBufferName(data->display, data->buf);
    }
#endif

    if ( data->display ) {
        if ( data->window != None ) {
            X11_XWithdrawWindow( data->display, data->window, data->screen );
            X11_XDestroyWindow( data->display, data->window );
            data->window = None;
        }

        X11_XCloseDisplay( data->display );
        data->display = NULL;
    }

    SDL_free(data->linedata);
}

/* Create and set up our X11 dialog box indow. */
static int
X11_MessageBoxCreateWindow( SDL_MessageBoxDataX11 *data )
{
    int x, y;
    XSizeHints *sizehints;
    XSetWindowAttributes wnd_attr;
    Atom _NET_WM_WINDOW_TYPE, _NET_WM_WINDOW_TYPE_DIALOG;
    Display *display = data->display;
    SDL_WindowData *windowdata = NULL;
    const SDL_MessageBoxData *messageboxdata = data->messageboxdata;

    if ( messageboxdata->window ) {
        SDL_DisplayData *displaydata =
            (SDL_DisplayData *) SDL_GetDisplayForWindow(messageboxdata->window)->driverdata;
        windowdata = (SDL_WindowData *)messageboxdata->window->driverdata;
        data->screen = displaydata->screen;
    } else {
        data->screen = DefaultScreen( display );
    }

    data->event_mask = ExposureMask |
                       ButtonPressMask | ButtonReleaseMask | KeyPressMask | KeyReleaseMask |
                       StructureNotifyMask | FocusChangeMask | PointerMotionMask;
    wnd_attr.event_mask = data->event_mask;

    data->window = X11_XCreateWindow(
                       display, RootWindow(display, data->screen),
                       0, 0,
                       data->dialog_width, data->dialog_height,
                       0, CopyFromParent, InputOutput, CopyFromParent,
                       CWEventMask, &wnd_attr );
    if ( data->window == None ) {
        return SDL_SetError("Couldn't create X window");
    }

    if ( windowdata ) {
        Atom _NET_WM_STATE = X11_XInternAtom(display, "_NET_WM_STATE", False);
        Atom stateatoms[16];
        size_t statecount = 0;
        /* Set some message-boxy window states when attached to a parent window... */
        /* we skip the taskbar since this will pop to the front when the parent window is clicked in the taskbar, etc */
        stateatoms[statecount++] = X11_XInternAtom(display, "_NET_WM_STATE_SKIP_TASKBAR", False);
        stateatoms[statecount++] = X11_XInternAtom(display, "_NET_WM_STATE_SKIP_PAGER", False);
        stateatoms[statecount++] = X11_XInternAtom(display, "_NET_WM_STATE_FOCUSED", False);
        stateatoms[statecount++] = X11_XInternAtom(display, "_NET_WM_STATE_MODAL", False);
        SDL_assert(statecount <= SDL_arraysize(stateatoms));
        X11_XChangeProperty(display, data->window, _NET_WM_STATE, XA_ATOM, 32,
                            PropModeReplace, (unsigned char *)stateatoms, statecount);

        /* http://tronche.com/gui/x/icccm/sec-4.html#WM_TRANSIENT_FOR */
        X11_XSetTransientForHint( display, data->window, windowdata->xwindow );
    }

    SDL_X11_SetWindowTitle(display, data->window, (char*)messageboxdata->title);

    /* Let the window manager know this is a dialog box */
    _NET_WM_WINDOW_TYPE = X11_XInternAtom(display, "_NET_WM_WINDOW_TYPE", False);
    _NET_WM_WINDOW_TYPE_DIALOG = X11_XInternAtom(display, "_NET_WM_WINDOW_TYPE_DIALOG", False);
    X11_XChangeProperty(display, data->window, _NET_WM_WINDOW_TYPE, XA_ATOM, 32,
                    PropModeReplace,
                    (unsigned char *)&_NET_WM_WINDOW_TYPE_DIALOG, 1);

    /* Allow the window to be deleted by the window manager */
    data->wm_protocols = X11_XInternAtom( display, "WM_PROTOCOLS", False );
    data->wm_delete_message = X11_XInternAtom( display, "WM_DELETE_WINDOW", False );
    X11_XSetWMProtocols( display, data->window, &data->wm_delete_message, 1 );

    if ( windowdata ) {
        XWindowAttributes attrib;
        Window dummy;

        X11_XGetWindowAttributes(display, windowdata->xwindow, &attrib);
        x = attrib.x + ( attrib.width - data->dialog_width ) / 2;
        y = attrib.y + ( attrib.height - data->dialog_height ) / 3 ;
        X11_XTranslateCoordinates(display, windowdata->xwindow, RootWindow(display, data->screen), x, y, &x, &y, &dummy);
    } else {
        const SDL_VideoDevice *dev = SDL_GetVideoDevice();
        if ((dev) && (dev->displays) && (dev->num_displays > 0)) {
            const SDL_VideoDisplay *dpy = &dev->displays[0];
            const SDL_DisplayData *dpydata = (SDL_DisplayData *) dpy->driverdata;
            x = dpydata->x + (( dpy->current_mode.w - data->dialog_width ) / 2);
            y = dpydata->y + (( dpy->current_mode.h - data->dialog_height ) / 3);
        } else {   /* oh well. This will misposition on a multi-head setup. Init first next time. */
            x = ( DisplayWidth( display, data->screen ) - data->dialog_width ) / 2;
            y = ( DisplayHeight( display, data->screen ) - data->dialog_height ) / 3 ;
        }
    }
    X11_XMoveWindow( display, data->window, x, y );

    sizehints = X11_XAllocSizeHints();
    if ( sizehints ) {
        sizehints->flags = USPosition | USSize | PMaxSize | PMinSize;
        sizehints->x = x;
        sizehints->y = y;
        sizehints->width = data->dialog_width;
        sizehints->height = data->dialog_height;

        sizehints->min_width = sizehints->max_width = data->dialog_width;
        sizehints->min_height = sizehints->max_height = data->dialog_height;

        X11_XSetWMNormalHints( display, data->window, sizehints );

        X11_XFree( sizehints );
    }

    X11_XMapRaised( display, data->window );

#if SDL_VIDEO_DRIVER_X11_XDBE
    /* Initialise a back buffer for double buffering */
    if (SDL_X11_HAVE_XDBE) {
        int xdbe_major, xdbe_minor;
        if (X11_XdbeQueryExtension(display, &xdbe_major, &xdbe_minor) != 0) {
            data->xdbe = SDL_TRUE;
            data->buf = X11_XdbeAllocateBackBufferName(display, data->window, XdbeUndefined);
        } else {
            data->xdbe = SDL_FALSE;
        }
    }
#endif

    return 0;
}

/* Draw our message box. */
static void
X11_MessageBoxDraw( SDL_MessageBoxDataX11 *data, GC ctx )
{
    int i;
    Drawable window = data->window;
    Display *display = data->display;

#if SDL_VIDEO_DRIVER_X11_XDBE
    if (SDL_X11_HAVE_XDBE && data->xdbe) {
        window = data->buf;
        X11_XdbeBeginIdiom(data->display);
    }
#endif

    X11_XSetForeground( display, ctx, data->color[ SDL_MESSAGEBOX_COLOR_BACKGROUND ] );
    X11_XFillRectangle( display, window, ctx, 0, 0, data->dialog_width, data->dialog_height );

    X11_XSetForeground( display, ctx, data->color[ SDL_MESSAGEBOX_COLOR_TEXT ] );
    for ( i = 0; i < data->numlines; i++ ) {
        TextLineData *plinedata = &data->linedata[ i ];

        if (SDL_X11_HAVE_UTF8) {
            X11_Xutf8DrawString( display, window, data->font_set, ctx,
                             data->xtext, data->ytext + i * data->text_height,
                             plinedata->text, plinedata->length );
        } else {
            X11_XDrawString( display, window, ctx,
                         data->xtext, data->ytext + i * data->text_height,
                         plinedata->text, plinedata->length );
        }
    }

    for ( i = 0; i < data->numbuttons; i++ ) {
        SDL_MessageBoxButtonDataX11 *buttondatax11 = &data->buttonpos[ i ];
        const SDL_MessageBoxButtonData *buttondata = buttondatax11->buttondata;
        int border = ( buttondata->flags & SDL_MESSAGEBOX_BUTTON_RETURNKEY_DEFAULT ) ? 2 : 0;
        int offset = ( ( data->mouse_over_index == i ) && ( data->button_press_index == data->mouse_over_index ) ) ? 1 : 0;

        X11_XSetForeground( display, ctx, data->color[ SDL_MESSAGEBOX_COLOR_BUTTON_BACKGROUND ] );
        X11_XFillRectangle( display, window, ctx,
                        buttondatax11->rect.x - border, buttondatax11->rect.y - border,
                        buttondatax11->rect.w + 2 * border, buttondatax11->rect.h + 2 * border );

        X11_XSetForeground( display, ctx, data->color[ SDL_MESSAGEBOX_COLOR_BUTTON_BORDER ] );
        X11_XDrawRectangle( display, window, ctx,
                        buttondatax11->rect.x, buttondatax11->rect.y,
                        buttondatax11->rect.w, buttondatax11->rect.h );

        X11_XSetForeground( display, ctx, ( data->mouse_over_index == i ) ?
                        data->color[ SDL_MESSAGEBOX_COLOR_BUTTON_SELECTED ] :
                        data->color[ SDL_MESSAGEBOX_COLOR_TEXT ] );

        if (SDL_X11_HAVE_UTF8) {
            X11_Xutf8DrawString( display, window, data->font_set, ctx,
                             buttondatax11->x + offset,
                             buttondatax11->y + offset,
                             buttondata->text, buttondatax11->length );
        } else {
            X11_XDrawString( display, window, ctx,
                         buttondatax11->x + offset, buttondatax11->y + offset,
                         buttondata->text, buttondatax11->length );
        }
    }

#if SDL_VIDEO_DRIVER_X11_XDBE
    if (SDL_X11_HAVE_XDBE && data->xdbe) {
        XdbeSwapInfo swap_info;
        swap_info.swap_window = data->window;
        swap_info.swap_action = XdbeUndefined;
        X11_XdbeSwapBuffers(data->display, &swap_info, 1);
        X11_XdbeEndIdiom(data->display);
    }
#endif
}

static Bool
X11_MessageBoxEventTest(Display *display, XEvent *event, XPointer arg)
{
    const SDL_MessageBoxDataX11 *data = (const SDL_MessageBoxDataX11 *) arg;
    return ((event->xany.display == data->display) && (event->xany.window == data->window)) ? True : False;
}

/* Loop and handle message box event messages until something kills it. */
static int
X11_MessageBoxLoop( SDL_MessageBoxDataX11 *data )
{
    GC ctx;
    XGCValues ctx_vals;
    SDL_bool close_dialog = SDL_FALSE;
    SDL_bool has_focus = SDL_TRUE;
    KeySym last_key_pressed = XK_VoidSymbol;
    unsigned long gcflags = GCForeground | GCBackground;

    SDL_zero(ctx_vals);
    ctx_vals.foreground = data->color[ SDL_MESSAGEBOX_COLOR_BACKGROUND ];
    ctx_vals.background = data->color[ SDL_MESSAGEBOX_COLOR_BACKGROUND ];

    if (!SDL_X11_HAVE_UTF8) {
        gcflags |= GCFont;
        ctx_vals.font = data->font_struct->fid;
    }

    ctx = X11_XCreateGC( data->display, data->window, gcflags, &ctx_vals );
    if ( ctx == None ) {
        return SDL_SetError("Couldn't create graphics context");
    }

    data->button_press_index = -1;  /* Reset what button is currently depressed. */
    data->mouse_over_index = -1;    /* Reset what button the mouse is over. */

    while( !close_dialog ) {
        XEvent e;
        SDL_bool draw = SDL_TRUE;

        /* can't use XWindowEvent() because it can't handle ClientMessage events. */
        /* can't use XNextEvent() because we only want events for this window. */
        X11_XIfEvent( data->display, &e, X11_MessageBoxEventTest, (XPointer) data );

        /* If X11_XFilterEvent returns True, then some input method has filtered the
           event, and the client should discard the event. */
        if ( ( e.type != Expose ) && X11_XFilterEvent( &e, None ) )
            continue;

        switch( e.type ) {
        case Expose:
            if ( e.xexpose.count > 0 ) {
                draw = SDL_FALSE;
            }
            break;

        case FocusIn:
            /* Got focus. */
            has_focus = SDL_TRUE;
            break;

        case FocusOut:
            /* lost focus. Reset button and mouse info. */
            has_focus = SDL_FALSE;
            data->button_press_index = -1;
            data->mouse_over_index = -1;
            break;

        case MotionNotify:
            if ( has_focus ) {
                /* Mouse moved... */
                const int previndex = data->mouse_over_index;
                data->mouse_over_index = GetHitButtonIndex( data, e.xbutton.x, e.xbutton.y );
                if (data->mouse_over_index == previndex) {
                    draw = SDL_FALSE;
                }
            }
            break;

        case ClientMessage:
            if ( e.xclient.message_type == data->wm_protocols &&
                 e.xclient.format == 32 &&
                 e.xclient.data.l[ 0 ] == data->wm_delete_message ) {
                close_dialog = SDL_TRUE;
            }
            break;

        case KeyPress:
            /* Store key press - we make sure in key release that we got both. */
            last_key_pressed = X11_XLookupKeysym( &e.xkey, 0 );
            break;

        case KeyRelease: {
            Uint32 mask = 0;
            KeySym key = X11_XLookupKeysym( &e.xkey, 0 );

            /* If this is a key release for something we didn't get the key down for, then bail. */
            if ( key != last_key_pressed )
                break;

            if ( key == XK_Escape )
                mask = SDL_MESSAGEBOX_BUTTON_ESCAPEKEY_DEFAULT;
            else if ( ( key == XK_Return ) || ( key == XK_KP_Enter ) )
                mask = SDL_MESSAGEBOX_BUTTON_RETURNKEY_DEFAULT;

            if ( mask ) {
                int i;

                /* Look for first button with this mask set, and return it if found. */
                for ( i = 0; i < data->numbuttons; i++ ) {
                    SDL_MessageBoxButtonDataX11 *buttondatax11 = &data->buttonpos[ i ];

                    if ( buttondatax11->buttondata->flags & mask ) {
                        *data->pbuttonid = buttondatax11->buttondata->buttonid;
                        close_dialog = SDL_TRUE;
                        break;
                    }
                }
            }
            break;
        }

        case ButtonPress:
            data->button_press_index = -1;
            if ( e.xbutton.button == Button1 ) {
                /* Find index of button they clicked on. */
                data->button_press_index = GetHitButtonIndex( data, e.xbutton.x, e.xbutton.y );
            }
            break;

        case ButtonRelease:
            /* If button is released over the same button that was clicked down on, then return it. */
            if ( ( e.xbutton.button == Button1 ) && ( data->button_press_index >= 0 ) ) {
                int button = GetHitButtonIndex( data, e.xbutton.x, e.xbutton.y );

                if ( data->button_press_index == button ) {
                    SDL_MessageBoxButtonDataX11 *buttondatax11 = &data->buttonpos[ button ];

                    *data->pbuttonid = buttondatax11->buttondata->buttonid;
                    close_dialog = SDL_TRUE;
                }
            }
            data->button_press_index = -1;
            break;
        }

        if ( draw ) {
            /* Draw our dialog box. */
            X11_MessageBoxDraw( data, ctx );
        }
    }

    X11_XFreeGC( data->display, ctx );
    return 0;
}

static int
X11_ShowMessageBoxImpl(const SDL_MessageBoxData *messageboxdata, int *buttonid)
{
    int ret;
    SDL_MessageBoxDataX11 data;
#if SDL_SET_LOCALE
    char *origlocale;
#endif

    SDL_zero(data);

    if ( !SDL_X11_LoadSymbols() )
        return -1;

#if SDL_SET_LOCALE
    origlocale = setlocale(LC_ALL, NULL);
    if (origlocale != NULL) {
        origlocale = SDL_strdup(origlocale);
        if (origlocale == NULL) {
            return SDL_OutOfMemory();
        }
        setlocale(LC_ALL, "");
    }
#endif

    /* This code could get called from multiple threads maybe? */
    X11_XInitThreads();

    /* Initialize the return buttonid value to -1 (for error or dialogbox closed). */
    *buttonid = -1;

    /* Init and display the message box. */
    ret = X11_MessageBoxInit( &data, messageboxdata, buttonid );
    if ( ret != -1 ) {
        ret = X11_MessageBoxInitPositions( &data );
        if ( ret != -1 ) {
            ret = X11_MessageBoxCreateWindow( &data );
            if ( ret != -1 ) {
                ret = X11_MessageBoxLoop( &data );
            }
        }
    }

    X11_MessageBoxShutdown( &data );

#if SDL_SET_LOCALE
    if (origlocale) {
        setlocale(LC_ALL, origlocale);
        SDL_free(origlocale);
    }
#endif

    return ret;
}

/* Display an x11 message box. */
int
X11_ShowMessageBox(const SDL_MessageBoxData *messageboxdata, int *buttonid)
{
#if SDL_FORK_MESSAGEBOX
    /* Use a child process to protect against setlocale(). Annoying. */
    pid_t pid;
    int fds[2];
    int status = 0;

    if (pipe(fds) == -1) {
        return X11_ShowMessageBoxImpl(messageboxdata, buttonid); /* oh well. */
    }

    pid = fork();
    if (pid == -1) {  /* failed */
        close(fds[0]);
        close(fds[1]);
        return X11_ShowMessageBoxImpl(messageboxdata, buttonid); /* oh well. */
    } else if (pid == 0) {  /* we're the child */
        int exitcode = 0;
        close(fds[0]);
        status = X11_ShowMessageBoxImpl(messageboxdata, buttonid);
        if (write(fds[1], &status, sizeof (int)) != sizeof (int)) {
            exitcode = 1;
        } else if (write(fds[1], buttonid, sizeof (int)) != sizeof (int)) {
            exitcode = 1;
        }
        close(fds[1]);
        _exit(exitcode);  /* don't run atexit() stuff, static destructors, etc. */
    } else {  /* we're the parent */
        pid_t rc;
        close(fds[1]);
        do {
            rc = waitpid(pid, &status, 0);
        } while ((rc == -1) && (errno == EINTR));

        SDL_assert(rc == pid);  /* not sure what to do if this fails. */

        if ((rc == -1) || (!WIFEXITED(status)) || (WEXITSTATUS(status) != 0)) {
            status = SDL_SetError("msgbox child process failed");
        } else if ( (read(fds[0], &status, sizeof (int)) != sizeof (int)) ||
                    (read(fds[0], buttonid, sizeof (int)) != sizeof (int)) ) {
            status = SDL_SetError("read from msgbox child process failed");
            *buttonid = 0;
        }
        close(fds[0]);

        return status;
    }
#else
    return X11_ShowMessageBoxImpl(messageboxdata, buttonid);
#endif
}
#endif /* SDL_VIDEO_DRIVER_X11 */

/* vi: set ts=4 sw=4 expandtab: */


text:
/**
 * Test dependencies
 */
var assert = require('assert');
var httpHelper = require('./helpers/httpHelper.js');
var appHelper = require('./helpers/appHelper');
var util = require('util');

/**
 * Errors
 */
var Err = {
	badResponse: function(response) {
		return 'Wrong server response!  Response :::\n' + util.inspect(response.body);
	}
};

describe('router :: ', function() {

	describe('API scaffold routes', function() {
		var appName = 'testApp';

		before(function(done) {
			appHelper.build(function(err) {
				// console.log('before chdir ' + appName + ', cwd was :: ' + process.cwd());
				process.chdir(appName);
				// console.log('after chdir ' + appName + ', new cwd is :: ' + process.cwd());
				if (err) return done(err);
				done();
			});
		});

		after(function() {
			// console.log('before `chdir ../`' + ', cwd was :: ' + process.cwd());
			process.chdir('../');
			// console.log('after `chdir ../`' + ', cwd was :: ' + process.cwd());
			appHelper.teardown();
		});

		describe('a get request to /:controller/create', function() {

			it('should return JSON for a newly created instance of the test model', function(done) {

				httpHelper.testRoute('get', {
					url: 'empty/create',
					json: true
				}, function(err, response) {
					if (err) return done(new Error(err));

					assert(response.body.id === 1, Err.badResponse(response));
					done();
				});
			});
		});

		describe('a post request to /:controller/create', function() {

			it('should return JSON for a newly created instance of the test model', function(done) {

				httpHelper.testRoute('post', {
					url: 'empty/create',
					json: true,
					body: {}
				}, function(err, response) {
					if (err) return done(new Error(err));

					assert(response.body.id === 2, Err.badResponse(response));
					done();
				});
			});
		});

		describe('a get request to /:controller', function() {

			it('should return JSON for all instances of the test model', function(done) {

				httpHelper.testRoute('get', {
					url: 'empty',
					json: true
				}, function(err, response) {
					if (err) return done(new Error(err));

					assert(response.body[0].id === 1, Err.badResponse(response));
					assert(response.body[1].id === 2, Err.badResponse(response));
					done();
				});
			});
		});

		describe('a get request to /:controller/:id', function() {

			it('should return JSON for the instance of the test model with the specified id', function(done) {

				httpHelper.testRoute('get', {
					url: 'empty/1',
					json: true
				}, function(err, response) {
					if (err) return done(new Error(err));

					assert(response.body.id === 1, Err.badResponse(response));
					done();
				});
			});
		});

		describe('a put request to /:controller/:id', function() {

			it('should return JSON for the updated instance of the test model', function(done) {

				httpHelper.testRoute('put', {
					url: 'empty/1?foo=bar',
					json: true
				}, function(err, response) {
					if (err) return done(new Error(err));

					assert(response.body.foo === 'bar', Err.badResponse(response));
					done();
				});
			});
		});

		describe('a delete request to /:controller/:id', function() {

			it('should return JSON for the destroyed instance of the test model', function(done) {

				httpHelper.testRoute('del', {
					url: 'empty/1',
					json: true
				}, function(err, response) {
					if (err) return done(new Error(err));

					assert(response.body.id === 1, Err.badResponse(response));
					done();
				});
			});
		});

		describe('with pluralize turned on', function() {

			before(function() {
				httpHelper.writeBlueprint({
					pluralize: true
				});
			});

			it('should bind blueprint actions to plural controller names', function(done) {
				httpHelper.testRoute('get', {
					url: 'empties',
					json: true
				}, function(err, response) {
					if (err) done(new Error(err));

					assert(response.body instanceof Array);
					done();
				});
			});

			it('should not bind blueprint actions to singular controller names', function(done) {
				httpHelper.testRoute('get', {
					url: 'empty',
					json: true
				}, function(err, response) {
					if (err) done(new Error(err));

					assert(response.body instanceof Object);
					assert(response.body.status === 404);
					done();
				});
			});
		});
	});

});

redpajama_set_name: RedPajamaGithub


text: All new Web Stuff I want to try


text:
<?php

namespace ISG\ProjectSubmissionAppBundle\Model;

use ISG\ProjectSubmissionAppBundle\Model\om\BaseRegister;

class Register extends BaseRegister
{
}


text:
<!DOCTYPE html>

    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0"/>
    <title>Code for America</title>
    <link rel="stylesheet" type="text/css" href="//cloud.typography.com/6304652/777902/css/fonts.css" />
    <link rel="stylesheet" href="/_style/css/main.css">
    <link rel="stylesheet" href="/_style/css/layout.css" media="all and (min-width: 40em)">
    <link href="/_style/css/prism.css" rel="stylesheet" />
    <link rel="shortcut icon" type="image/x-icon" href="/favicon.ico">
    <link rel="apple-touch-icon-precomposed" href="/_style/favicons/60x60/flag-red.png"/>

Blog

Library

<form class="search-global" id="search-global">
    <input type="search" id="search-global-input" class="search-global-input" autocomplete="off" placeholder="Search" name="search-global" />

    <button class="search-global-submit" id="search-global-submit" value="Search" type="submit" name="search-global">Search</button>
</form>

Home

apps

Apps & APIs

        Apps & APIs

Menu

            		Who we are

                    Governments

                	Citizens

                	Apps

Donate

Home

apps

Apps & APIs

Promptly

Overview

Text message notification system for benefits recipients, built for San Francisco.

http://promptly.io

Created by Fellows

Andy Hull

Marc Hérbert

Rebecca Ackerman

Jacob Solomon

Created for

Human Services Agency in collaboration with the mayor's office of civic innovation

Promptly text messages San Francisco Human Services Agency clients with important information to keep them enrolled in services.

Summary

Live	http://promptly.io

Video	http://www.youtube.com/watch?v=vnJIzYBdcVI

Codebase	https://github.com/codeforamerica/promptly

Environment	Ruby on Rails with Postgres and Twilio

Redeploy	Unsure

	    	Contact us to deploy this app

Many CalFresh (Food Stamps) recipients in San Francisco  discover that they've been disenrolled from benefits while trying to pay for their groceries. It's a stressful and embarrassing moment. What's worse, some of these same people have to reapply for services from scratch. Promptly stops this from happening by sending a text message to recipients before they're disenrolled.

Promptly was built for the San Francisco Human Service Agency by 2013 fellows in collaboration with the Human Service Agency and the Mayor's Office of Civic Innovation. Although Promptly was first used to keep people enrolled in CalFresh, the app is also a flexible tool to help schedule, monitor, and send text message notifications for any reason.

Users include small business owners who:

Don't have time to find and discover new tech

Find traditional tech training too  difficult or time consuming; and,

Want to find tools other business use and compare them

Interested in using Promptly? Check it out at promptly.io, fork it on GitHub or contact us for info.

<form class="search-global" id="search-global">
    <input type="search" id="search-global-input" class="search-global-input" autocomplete="off" placeholder="Search" name="search-global" />

    <button class="search-global-submit" id="search-global-submit" value="Search" type="submit" name="search-global">Search</button>
</form>

About

What we do

Annual report

Press

Supporters

Jobs

Contact

Who we are

Board

Team

Staff

City Partners

Brigade captains

Programs

Fellowship

Brigade

Startup

International

Peer Network

Donate

Financial Contributions

In-Kind Donations

Social

Facebook

Twitter

YouTube

GitHub

Tumblr

Flickr

RSS

            Code for America Labs, Inc is a non-partisan, non-political 501(c)(3) organization. Content is licensed through Creative Commons.


text:
<?php

namespace Kunstmaan\FormBundle\Tests\Entity;

use Kunstmaan\FormBundle\Entity\AbstractFormPage;

class FormPage extends AbstractFormPage
{
    public function getPossibleChildTypes()
    {
        return null;
    }

    public function getPagePartAdminConfigurations()
    {
        return [
            [
                'name'  => 'ContentPage',
                'class' => '{{ namespace }}\Entity\Pages\ContentPage'
            ],
            [
                'name'  => 'FormPage',
                'class' => '{{ namespace }}\Entity\Pages\FormPage'
            ]
        ];
    }

    public function getDefaultView()
    {
        return 'some.twig';
    }
}


text:
#ifndef _WS_H_
#define _WS_H_

#include<stdio.h>
#include<stdlib.h>
#include<unistd.h>
#include<string.h>
#include<ctype.h>
#include<setjmp.h>
#include<signal.h>
#include<sys/time.h>
#include<sys/types.h>
#include<sys/wait.h>
#include<sys/stat.h>
#include<fcntl.h>
#include<sys/mman.h>
#include<errno.h>
#include<math.h>
#include<pthread.h>
#include<semaphore.h>
#include<sys/socket.h>
#include<netdb.h>
#include<netinet/in.h>
#include<arpa/inet.h>

/* the number of work pthreads */
#define  NTHREADS        100
#define  SBUFSIZE        1024

#define  MAXLINE         8192
#define  RIO_BUFSIZE     8192
#define  LISTENQ         1024
#define  MAXBUF          8192

typedef struct sockaddr SA;

#endif


text:
// Copyright (c) Microsoft.  All Rights Reserved.  Licensed under the Apache License, Version 2.0.  See License.txt in the project root for license information.

using System.Runtime.InteropServices;
using Microsoft.CodeAnalysis.Editor;
using Microsoft.CodeAnalysis.Editor.Shared.Extensions;
using Microsoft.VisualStudio;
using Microsoft.VisualStudio.Editor;
using Microsoft.VisualStudio.OLE.Interop;
using Microsoft.VisualStudio.Text;
using Microsoft.VisualStudio.Text.Editor;
using Microsoft.VisualStudio.TextManager.Interop;
using Roslyn.Utilities;

namespace Microsoft.VisualStudio.LanguageServices.Implementation
{
    internal abstract partial class AbstractOleCommandTarget : IOleCommandTarget
    {
        private const VSConstants.VSStd2KCmdID CmdidToggleConsumeFirstMode = (VSConstants.VSStd2KCmdID)2303;
        private const VSConstants.VSStd2KCmdID CmdidNextHighlightedReference = (VSConstants.VSStd2KCmdID)2400;
        private const VSConstants.VSStd2KCmdID CmdidPreviousHighlightedReference = (VSConstants.VSStd2KCmdID)2401;
        private const VSConstants.VSStd2KCmdID CmdidContextMenuViewCallHierarchy = (VSConstants.VSStd2KCmdID)2301;

        private readonly IWpfTextView _wpfTextView;
        private readonly ICommandHandlerServiceFactory _commandHandlerServiceFactory;
        private readonly IVsEditorAdaptersFactoryService _editorAdaptersFactory;
        private readonly System.IServiceProvider _serviceProvider;

        /// <summary>
        /// This is set only during Exec. Currently, this is required to disambiguate the editor calls to
        /// <see cref="IVsTextViewFilter.GetPairExtents(int, int, TextSpan[])"/> between GotoBrace and GotoBraceExt commands.
        /// </summary>
        protected uint CurrentlyExecutingCommand { get; private set; }

        public AbstractOleCommandTarget(
            IWpfTextView wpfTextView,
            ICommandHandlerServiceFactory commandHandlerServiceFactory,
            IVsEditorAdaptersFactoryService editorAdaptersFactory,
            System.IServiceProvider serviceProvider)
        {
            Contract.ThrowIfNull(wpfTextView);
            Contract.ThrowIfNull(commandHandlerServiceFactory);
            Contract.ThrowIfNull(editorAdaptersFactory);
            Contract.ThrowIfNull(serviceProvider);

            _wpfTextView = wpfTextView;
            _commandHandlerServiceFactory = commandHandlerServiceFactory;
            _editorAdaptersFactory = editorAdaptersFactory;
            _serviceProvider = serviceProvider;
        }

        public IVsEditorAdaptersFactoryService EditorAdaptersFactory
        {
            get { return _editorAdaptersFactory; }
        }

        /// <summary>
        /// The IWpfTextView that this command filter is attached to.
        /// </summary>
        public IWpfTextView WpfTextView
        {
            get { return _wpfTextView; }
        }

        /// <summary>
        /// The command handler service to use for dispatching commands. This is set by
        /// the derived classes to this class.
        /// </summary>
        protected ICommandHandlerService CurrentHandlers { get; set; }

        /// <summary>
        /// The next command target in the chain. This is set by the derived implementation of this
        /// class.
        /// </summary>
        protected internal IOleCommandTarget NextCommandTarget { get; set; }

        protected internal void RefreshCommandFilters()
        {
            this.CurrentHandlers = _commandHandlerServiceFactory.GetService(WpfTextView);
        }

        internal AbstractOleCommandTarget AttachToVsTextView()
        {
            var vsTextView = _editorAdaptersFactory.GetViewAdapter(_wpfTextView);
            // Add command filter to IVsTextView. If something goes wrong, throw.
            var returnValue = vsTextView.AddCommandFilter(this, out var nextCommandTarget);
            Marshal.ThrowExceptionForHR(returnValue);
            Contract.ThrowIfNull(nextCommandTarget);

            CurrentHandlers = _commandHandlerServiceFactory.GetService(WpfTextView);
            NextCommandTarget = nextCommandTarget;

            return this;
        }

        protected virtual ITextBuffer GetSubjectBufferContainingCaret()
        {
            return _wpfTextView.GetBufferContainingCaret();
        }

        protected virtual ITextView ConvertTextView()
        {
            return _wpfTextView;
        }
    }
}


text:
package com.google.javascript.jscomp.ant;

import com.google.common.collect.Lists;
import com.google.javascript.jscomp.CommandLineRunner;
import com.google.javascript.jscomp.CompilationLevel;
import com.google.javascript.jscomp.Compiler;
import com.google.javascript.jscomp.CompilerOptions;
import com.google.javascript.jscomp.JSSourceFile;
import com.google.javascript.jscomp.MessageFormatter;
import com.google.javascript.jscomp.Result;
import com.google.javascript.jscomp.WarningLevel;

import org.apache.tools.ant.BuildException;
import org.apache.tools.ant.Project;
import org.apache.tools.ant.Task;
import org.apache.tools.ant.types.FileList;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.nio.charset.Charset;
import java.util.Date;
import java.util.List;
import java.util.logging.Level;

/**
 * This class implements a simple Ant task to do almost the same as
 * CommandLineRunner.
 *
 * Most of the public methods of this class are entry points for the
 * Ant code to hook into.
 *
 */
public final class CompileTask
    extends Task {
  private WarningLevel warningLevel;
  private boolean debugOptions;
  private String encoding = "UTF-8";
  private String outputEncoding = "UTF-8";
  private CompilationLevel compilationLevel;
  private boolean customExternsOnly;
  private boolean manageDependencies;
  private boolean prettyPrint;
  private boolean printInputDelimiter;
  private boolean generateExports;
  private File outputFile;
  private final List<FileList> externFileLists;
  private final List<FileList> sourceFileLists;

  public CompileTask() {
    this.warningLevel = WarningLevel.DEFAULT;
    this.debugOptions = false;
    this.compilationLevel = CompilationLevel.SIMPLE_OPTIMIZATIONS;
    this.customExternsOnly = false;
    this.manageDependencies = false;
    this.prettyPrint = false;
    this.printInputDelimiter = false;
    this.generateExports = false;
    this.externFileLists = Lists.newLinkedList();
    this.sourceFileLists = Lists.newLinkedList();
  }

  /**
   * Set the warning level.
   * @param value The warning level by string name. (default, quiet, verbose).
   */
  public void setWarning(String value) {
    if ("default".equalsIgnoreCase(value)) {
      this.warningLevel = WarningLevel.DEFAULT;
    } else if ("quiet".equalsIgnoreCase(value)) {
      this.warningLevel = WarningLevel.QUIET;
    } else if ("verbose".equalsIgnoreCase(value)) {
      this.warningLevel = WarningLevel.VERBOSE;
    } else {
      throw new BuildException(
          "Unrecognized 'warning' option value (" + value + ")");
    }
  }

  /**
   * Enable debugging options.
   * @param value True if debug mode is enabled.
   */
  public void setDebug(boolean value) {
    this.debugOptions = value;
  }

  /**
   * Set the compilation level.
   * @param value The optimization level by string name.
   *     (whitespace, simple, advanced).
   */
  public void setCompilationLevel(String value) {
    if ("simple".equalsIgnoreCase(value)) {
      this.compilationLevel = CompilationLevel.SIMPLE_OPTIMIZATIONS;
    } else if ("advanced".equalsIgnoreCase(value)) {
      this.compilationLevel = CompilationLevel.ADVANCED_OPTIMIZATIONS;
    } else if ("whitespace".equalsIgnoreCase(value)) {
      this.compilationLevel = CompilationLevel.WHITESPACE_ONLY;
    } else {
      throw new BuildException(
          "Unrecognized 'compilation' option value (" + value + ")");
    }
  }

  public void setManageDependencies(boolean value) {
    this.manageDependencies = value;
  }

  /**
   * Use only custom externs.
   */
  public void setCustomExternsOnly(boolean value) {
    this.customExternsOnly = value;
  }

  /**
   * Set output file.
   */
  public void setOutput(File value) {
    this.outputFile = value;
  }

  /**
   * Set input file encoding
   */
  public void setEncoding(String encoding) {
    this.encoding = encoding;
  }

  /**
   * Set output file encoding
   */
  public void setOutputEncoding(String outputEncoding) {
    this.outputEncoding = outputEncoding;
  }

  /**
   * Set pretty print formatting option
   */
  public void setPrettyPrint(boolean pretty) {
    this.prettyPrint = pretty;
  }

  /**
   * Set print input delimitter formatting option
   */
  public void setPrintInputDelimiter(boolean print) {
    this.printInputDelimiter = print;
  }

  /**
   * Set generateExports option
   */
  public void setGenerateExports(boolean generateExports) {
   this.generateExports = generateExports;
  }

  /**
   * Sets the externs file.
   */
  public void addExterns(FileList list) {
    this.externFileLists.add(list);
  }

  /**
   * Sets the source files.
   */
  public void addSources(FileList list) {
    this.sourceFileLists.add(list);
  }

  public void execute() {
    if (this.outputFile == null) {
      throw new BuildException("outputFile attribute must be set");
    }

    Compiler.setLoggingLevel(Level.OFF);

    CompilerOptions options = createCompilerOptions();
    Compiler compiler = createCompiler(options);

    JSSourceFile[] externs = findExternFiles();
    JSSourceFile[] sources = findSourceFiles();

    if (isStale()) {
      log("Compiling " + sources.length + " file(s) with " +
          externs.length + " extern(s)");

      Result result = compiler.compile(externs, sources, options);
      if (result.success) {
        writeResult(compiler.toSource());
      } else {
        throw new BuildException("Compilation failed.");
      }
    } else {
      log("None of the files changed. Compilation skipped.");
    }
  }

  private CompilerOptions createCompilerOptions() {
    CompilerOptions options = new CompilerOptions();

    this.compilationLevel.setOptionsForCompilationLevel(options);
    if (this.debugOptions) {
      this.compilationLevel.setDebugOptionsForCompilationLevel(options);
    }

    options.prettyPrint = this.prettyPrint;
    options.printInputDelimiter = this.printInputDelimiter;
    options.generateExports = this.generateExports;

    this.warningLevel.setOptionsForWarningLevel(options);
    options.setManageClosureDependencies(manageDependencies);
    return options;
  }

  private Compiler createCompiler(CompilerOptions options) {
    Compiler compiler = new Compiler();
    MessageFormatter formatter =
        options.errorFormat.toFormatter(compiler, false);
    AntErrorManager errorManager = new AntErrorManager(formatter, this);
    compiler.setErrorManager(errorManager);
    return compiler;
  }

  private JSSourceFile[] findExternFiles() {
    List<JSSourceFile> files = Lists.newLinkedList();
    if (!this.customExternsOnly) {
      files.addAll(getDefaultExterns());
    }

    for (FileList list : this.externFileLists) {
      files.addAll(findJavaScriptFiles(list));
    }

    return files.toArray(new JSSourceFile[files.size()]);
  }

  private JSSourceFile[] findSourceFiles() {
    List<JSSourceFile> files = Lists.newLinkedList();

    for (FileList list : this.sourceFileLists) {
      files.addAll(findJavaScriptFiles(list));
    }

    return files.toArray(new JSSourceFile[files.size()]);
  }

  /**
   * Translates an Ant file list into the file format that the compiler
   * expects.
   */
  private List<JSSourceFile> findJavaScriptFiles(FileList fileList) {
    List<JSSourceFile> files = Lists.newLinkedList();
    File baseDir = fileList.getDir(getProject());

    for (String included : fileList.getFiles(getProject())) {
      files.add(JSSourceFile.fromFile(new File(baseDir, included),
          Charset.forName(encoding)));
    }

    return files;
  }

  /**
   * Gets the default externs set.
   *
   * Adapted from {@link CommandLineRunner}.
   */
  private List<JSSourceFile> getDefaultExterns() {
    try {
      return CommandLineRunner.getDefaultExterns();
    } catch (IOException e) {
      throw new BuildException(e);
    }
  }

  private void writeResult(String source) {
    if (this.outputFile.getParentFile().mkdirs()) {
      log("Created missing parent directory " +
          this.outputFile.getParentFile(), Project.MSG_DEBUG);
    }

    try {
      OutputStreamWriter out = new OutputStreamWriter(
          new FileOutputStream(this.outputFile), outputEncoding);
      out.append(source);
      out.flush();
      out.close();
    } catch (IOException e) {
      throw new BuildException(e);
    }

    log("Compiled javascript written to " + this.outputFile.getAbsolutePath(),
        Project.MSG_DEBUG);
  }

  /**
   * Determine if compilation must actually happen, i.e. if any input file
   * (extern or source) has changed after the outputFile was last modified.
   *
   * @return true if compilation should happen
   */
  private boolean isStale() {
    long lastRun = outputFile.lastModified();
    long sourcesLastModified = getLastModifiedTime(this.sourceFileLists);
    long externsLastModified = getLastModifiedTime(this.externFileLists);

    return lastRun <= sourcesLastModified || lastRun <= externsLastModified;
  }

  private long getLastModifiedTime(List<FileList> fileLists) {
    long lastModified = 0;
    for (FileList list : fileLists) {
      for (String fileName : list.getFiles(this.getProject())) {
        File path = list.getDir(this.getProject());
        File file = new File(path, fileName);
        long fileLastModified = file.lastModified();
        // If the file is absent, we don't know if it changed (maybe
        // was deleted), so assume it has just changed.
        if (fileLastModified == 0) {
          fileLastModified = new Date().getTime();
        }
        lastModified = Math.max(fileLastModified, lastModified);
      }
    }
    return lastModified;
  }
}


text:
package org.indiarose.lib;

/*
 * This work is licensed under the Creative Commons Attribution-NonCommercial-ShareAlike 4.0 International License.
 * To view a copy of this license, visit http://creativecommons.org/licenses/by-nc-sa/4.0/.
 */

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

import org.indiarose.lib.model.Indiagram;

import android.os.Environment;
import android.text.TextUtils;
import android.util.Log;

/**
 * Class to manage all path relative system.
 * @author Julien Mialon <mialon.julien@gmail.com>
 */
public class PathData
{
	/**
	 * The root path to all India Rose relative data.
	 */
	public static final String ROOT_PATH = Environment.getExternalStorageDirectory().getPath() + "/IndiaRose/";

	/**
	 * Path to xml storage directory.
	 */
	public static final String XML_DIRECTORY = ROOT_PATH + "xml/";
	/**
	 * Path to the image storage directory.
	 */
	public static final String IMAGE_DIRECTORY = ROOT_PATH + "image/";
	/**
	 * Name of the directory of the image took with camera.
	 */
	public static final String USER_IMAGE_DIRECTORY = ""; //TODO : "0x2Acamera/";
	/**
	 * Path to the sound storage directory.
	 */
	public static final String SOUND_DIRECTORY = ROOT_PATH + "sound/";
	/**
	 * Name of the directory of the sound recorded using microphone.
	 */
	public static final String USER_SOUND_DIRECTORY = ""; //TODO : "0x2Amicro/";
	/**
	 * Path to temp directory.
	 */
	public static final String TMP_DIRECTORY = ROOT_PATH + "temp/";
	/**
	 * Path to the internal app data directory.
	 */
	public static final String APP_DIRECTORY = ROOT_PATH + "app/";

	/**
	 * Path to the settings file.
	 */
	public static final String SETTINGS_FILE = APP_DIRECTORY + "settings.xml";
	/**
	 * Path to the application data file.
	 */
	public static final String APPDATA_FILE = APP_DIRECTORY + "appdata.xml";
	/**
	 * Path to the home category xml file.
	 */
	public static final String HOME_FILE = "../app/home.xml";
	/**
	 * Path to the changelog xml file.
	 */
	public static final String CHANGELOG_FILE = APP_DIRECTORY + "changelog.xml";
	/**
	 * Path to the next arrow xml file describing this indiagram.
	 */
	public static final String NEXTARROW_FILE = "rightarrow.xml";
	/**
	 * Path to the play button xml file describing this indiagram.
	 */
	public static final String PLAYBUTTON_FILE = "playbutton.xml";
	/**
	 * Initialize all path. If one does not exists, create all.
	 */
	public static void Initialize()
	{
		ArrayList<File> files = new ArrayList<File>();
		files.add(new File(ROOT_PATH));
		files.add(new File(XML_DIRECTORY));
		files.add(new File(IMAGE_DIRECTORY));
		files.add(new File(IMAGE_DIRECTORY + USER_IMAGE_DIRECTORY));
		files.add(new File(SOUND_DIRECTORY));
		files.add(new File(SOUND_DIRECTORY + USER_SOUND_DIRECTORY));
		files.add(new File(TMP_DIRECTORY));
		files.add(new File(APP_DIRECTORY));

		for(int i = 0 ; i < files.size() ; ++i)
		{
			if(!files.get(i).exists())
			{
				if(!files.get(i).mkdir())
				{
					Log.e("PathData", "Unable to create " + files.get(i).getPath());
				}
			}
		}
	}

	/**
	 * Check if the app directory exists.
	 * @return true if exists.
	 */
	public static boolean IsAppDirectoryExists()
	{
		File rootPath = new File(ROOT_PATH);
		return rootPath.exists();
	}

	public static void clearTempDirectory()
	{
		File tmp = new File(TMP_DIRECTORY);
		if(tmp.exists())
		{
			for(String s : tmp.list())
			{
				File f = new File(s);
				deleteFile(f);
			}
		}
	}

	public static void deleteFile(File f)
	{
		if (f.isDirectory())
	        for (File child : f.listFiles())
	        	deleteFile(child);

	    f.delete();
	}

	/*
	public static String getDirectoryCategoryPath(Category _item)
	{
		return getDirectoryCategoryPath(_item, "");
	}

	public static String getDirectoryCategoryPath(Category _item, String _prefix)
	{
		String catName = getIndiagramPath(_item, _prefix);
		String catPath = catName.substring(0, catName.length() - ".xml".length()) + "/";

		File cat = new File(PathData.XML_DIRECTORY + catPath);
		if(!cat.exists())
		{
			cat.mkdirs();
		}

		return catPath;
	}
	*/

	/**
	 * Function to retrieve the path to an Indiagram file.
	 * @param _item : the indiagram to have path.
	 * @return the path to xml file.
	 * TODO integrate pack management with PACK_ instead of USER_
	 */
	public static String getIndiagramPath(Indiagram _item)
	{
		if(TextUtils.isEmpty(_item.filePath))
		{
			String directory = PathData.XML_DIRECTORY;
			String filename = "USER_";
			for(int i = 0 ; i < _item.text.length() ; ++i)
			{
				char c = _item.text.charAt(i);
				if((c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') || (c >= '0' && c <= '9'))
				{
					filename += c;
				}
			}

			File f = new File(directory + filename + ".xml");
			int index = 1;
			while(f.exists())
			{
				index++;
				f = new File(directory + filename + "_" + index + ".xml");
			}
			if(index > 1)
			{
				_item.filePath = filename + "_" + index + ".xml";
			}
			else
			{
				_item.filePath = filename + ".xml";
			}
		}
		return _item.filePath;
	}

	/*
	public static String getCompleteIndiagramPath(Indiagram _item)
	{
		return PathData.IMAGE_DIRECTORY + _item.imagePath;
	}
	*/
}


text:
if (typeof define !== 'function') { var define = require('amdefine')(module) }
define( function(require,exports,module){

    var $         = require('jquery');
    var t          = require('../templates');
    var RefBinder = require('ref-binder');
    var View      = require('backbone').View;
    var self;

    var UploadImageView = module.exports = View.extend({

        events: {
            //'click #upload_image_button': 'uploadImage',
            'dragover #dragzone'        : 'onFileDrag',
            'dragleave #dragzone'       : 'onFileDragLeave',
            'drop #dragzone'            : 'onFileDrop',
            'change #image_file'        : 'fileSelected',
        },

        initialize: function(o) {
            this.models   = new RefBinder(this);
            this.cell     = o.cell;
            this.table    = o.table;
            self        = this;
        },

        render: function(){
            $('#es-modal-box').html(t.upload_image_dialog({sheet_id: this.table.getSheet().id}));
            $('#upload_image_button').on('click',this.uploadImage);
            $('#es-modal-overlay').show();
        },

        uploadImage: function(){
            $( '#upload_image_form' )
                .submit( function( e ) {
                    $.ajax( {
                        url: '/ethersheet/upload/image',
                        type: 'POST',
                        data: new FormData( this ),
                        processData: false,
                        contentType: false,
                        success : function(data) {
                            //udate cell value
                            self.cell.val(e.data);
                            self.table.getSheet().updateCell(self.cell.data('row_id'), self.cell.data('col_id'), data.image_url);
                            //dismiss dialog and menu
                            self.cell.on('mouseover', function(e){self.table.showCellPreview(e)});

                            $('#es-modal-overlay').hide();
                            $(".es-overlay").remove();
                        },
                        error : function(data){
                            alert(data.statusText + ": the file size must be less than 3Mb");
                            $('#es-modal-overlay').hide();
                            $(".es-overlay").remove();
                        }
                    } );
                    e.preventDefault();
                } );
        },

        onFileDrag: function(e){
            e.stopPropagation();
            e.preventDefault();
            $("#dragzone").addClass("ondrag");
        },

        onFileDragLeave : function(e){
            $("#dragzone").removeClass("ondrag");
        },

        onFileDrop: function(e){
            e.preventDefault();
            $("#dragzone").removeClass("ondrag");

            var files;
            if(_.isUndefined(e.dataTransfer))
               files = e.originalEvent.dataTransfer.files;
            else
               files = e.dataTransfer.files;
            $("#image_file")[0].files = files;
            this.showImagePreview(files[0]);

        },

        fileSelected : function(){
            this.showImagePreview($("#image_file")[0].files[0])
        },

        showImagePreview: function(img){
            $("#dragzone-caption").html("");
            if(!_.isUndefined(typeof FileReader)){
                var fs = new FileReader();
                fs.onload = function(e){
                    $("#dragzone").html('<img src="' + e.target.result  + '" />');
                };
                fs.readAsDataURL(img);
            }else{
                $("#dragzone-caption").html(files[0].name);
            }
        }

    })
});


text:
package models.query

import org.joda.time.LocalDate
import org.joda.time.format.ISODateTimeFormat
import scalikejdbc._

import scala.util.Try

/**
 * Date: 14/11/27.
 */
case class Period(from: Option[LocalDate], to: Option[LocalDate], default: Boolean) {
  import Period._
  import util.MFGDateUtil._

  def where(target: SQLSyntax): SQLSyntax = whereOpt(target).getOrElse(sqls"true")
  def whereOpt(target: SQLSyntax): Option[SQLSyntax] = {
    val x = from.map { it => sqls.gt(target, it.toDate.getTime) }
    val y = to.map { it => sqls.lt(target, it.toDate.getTime) }
    sqls.toAndConditionOpt(x, y)
  }

  def fromStr = from.getOrElse(DefaultStart).toString(ISODateTimeFormat.date())
  def toStr = to.getOrElse(LocalDate.now(Tokyo)).toString(ISODateTimeFormat.date())
}

object Period {
  lazy val DefaultStart = new LocalDate(2014, 1, 1)

  def fromStr(from: String, to: String): Period = {
    val fromDate = Try { LocalDate.parse(from, ISODateTimeFormat.date()) }
    val toDate = Try { LocalDate.parse(to, ISODateTimeFormat.date()) }
    Period(fromDate.toOption, toDate.toOption, fromDate.isFailure && toDate.isFailure)
  }
}


text:
module ImpactTravel
  class SessionsController < ImpactTravel::ApplicationController
    layout "impact_travel/login"
    before_action :redirect_logged_in_subscriber, except: [:destroy]

    def create
      create_session || redirect_to(
        new_session_path, notice: I18n.t("session.invalid")
      )
    end

    def destroy
      destroy_user_sessions
      redirect_to(landing_path, notice: I18n.t("session.destroyed"))
    end

    private

    def login
      @login = Login.new(login_params)
    end

    def create_session
      if login.authenticate
        sign_in(@login.subscriber)
        redirect_to(home_path, notice: I18n.t("session.created"))
      end
    end

    def destroy_user_sessions
      session[:auth_token] = nil
      session[:subscription_status] = nil
    end

    def login_params
      params.require(:login).permit(:name, :password)
    end
  end
end


text:
@interface IQCheckmarkView : UIView

@end


text:
class DecoyDuck : public Duck {
public:
    DecoyDuck();

    void display();
};

#endif


text:
<resources>

    <!-- Base application theme. -->
    <style name="AppTheme" parent="Theme.AppCompat.Light.DarkActionBar">
        <item name="actionBarStyle">@style/MyActionBar</item>
    </style>

    <!-- ActionBar styles -->
    <style name="MyActionBar" parent="@style/Widget.AppCompat.Light.ActionBar.Solid.Inverse">
        <item name="android:background">@color/md_red_500</item>
        <item name="background">@color/md_red_500</item>
    </style>

    <!-- Song info text fields -->
    <style name="LyricInfo" parent="@android:style/TextAppearance.Medium">
        <item name="android:layout_width">match_parent</item>
        <item name="android:layout_height">0dp</item>
        <item name="android:paddingTop">4dp</item>
        <item name="android:layout_weight">1</item>
        <item name="android:textColor">#333333</item>
        <item name="android:singleLine">true</item>
        <item name="android:textSize">16sp</item>
        <item name="android:gravity">center_vertical</item>
    </style>

    <!-- Translucent Theme -->
    <style name="TranslucentTheme">
        <item name="android:windowNoTitle">true</item>
        <item name="android:windowBackground">@android:color/transparent</item>
        <item name="android:colorBackgroundCacheHint">@null</item>
        <item name="android:windowIsTranslucent">true</item>
        <item name="android:windowAnimationStyle">@android:style/Animation</item>
    </style>

</resources>


text:
require "appitude/version"

require 'jquery-rails'
require 'coffee-script'
require 'backbone-rails'

module Appitude

  class Engine < Rails::Engine
  end

end


text:
package org.assertj.core.api.recursive.comparison;

import static org.assertj.core.api.Assertions.catchThrowable;
import static org.assertj.core.api.BDDAssertions.then;
import static org.assertj.core.test.AlwaysEqualComparator.alwaysEqual;

import java.util.Comparator;
import java.util.function.BiPredicate;
import java.util.regex.Pattern;

import org.apache.commons.lang3.RandomUtils;
import org.assertj.core.test.AlwaysEqualComparator;
import org.junit.jupiter.api.Test;

class RecursiveComparisonConfiguration_builder_Test {

  @Test
  void should_set_ignoreAllActualNullFields() {
    // GIVEN
    boolean value = RandomUtils.nextBoolean();
    // WHEN
    RecursiveComparisonConfiguration configuration = RecursiveComparisonConfiguration.builder()
                                                                                .withIgnoreAllActualNullFields(value)
                                                                                .build();
    // THEN
    then(configuration.getIgnoreAllActualNullFields()).isEqualTo(value);
  }

  @Test
  void should_set_ignoreAllActualEmptyOptionalFields() {
    // GIVEN
    boolean value = RandomUtils.nextBoolean();
    // WHEN
    RecursiveComparisonConfiguration configuration = RecursiveComparisonConfiguration.builder()
                                                                                .withIgnoreAllActualEmptyOptionalFields(value)
                                                                                .build();
    // THEN
    then(configuration.getIgnoreAllActualEmptyOptionalFields()).isEqualTo(value);
  }

  @Test
  void should_set_ignoreAllExpectedNullFields() {
    // GIVEN
    boolean value = RandomUtils.nextBoolean();
    // WHEN
    RecursiveComparisonConfiguration configuration = RecursiveComparisonConfiguration.builder()
                                                                                .withIgnoreAllExpectedNullFields(value)
                                                                                .build();
    // THEN
    then(configuration.getIgnoreAllExpectedNullFields()).isEqualTo(value);
  }

  @Test
  void should_set_ignoreAllOverriddenEquals() {
    // GIVEN
    boolean value = RandomUtils.nextBoolean();
    // WHEN
    RecursiveComparisonConfiguration configuration = RecursiveComparisonConfiguration.builder()
                                                                                .withIgnoreAllOverriddenEquals(value)
                                                                                .build();
    // THEN
    then(configuration.getIgnoreAllOverriddenEquals()).isEqualTo(value);
  }

  @Test
  void should_set_ignoreCollectionOrder() {
    // GIVEN
    boolean value = RandomUtils.nextBoolean();
    // WHEN
    RecursiveComparisonConfiguration configuration = RecursiveComparisonConfiguration.builder()
                                                                                .withIgnoreCollectionOrder(value)
                                                                                .build();
    // THEN
    then(configuration.getIgnoreCollectionOrder()).isEqualTo(value);
  }

  @Test
  void should_set_ignoreCollectionOrderInFields() {
    // GIVEN
    String[] values = { "foo", "bar" };
    // WHEN
    RecursiveComparisonConfiguration configuration = RecursiveComparisonConfiguration.builder()
                                                                                .withIgnoredCollectionOrderInFields(values)
                                                                                .build();
    // THEN
    then(configuration.getIgnoredCollectionOrderInFields()).containsExactly(values);
  }

  @Test
  void should_set_ignoreCollectionOrderInFieldsMatchingRegexes() {
    // GIVEN
    String[] values = { "foo", "bar" };
    // WHEN
    RecursiveComparisonConfiguration configuration = RecursiveComparisonConfiguration.builder()
                                                                                .withIgnoredCollectionOrderInFieldsMatchingRegexes(values)
                                                                                .build();
    // THEN
    then(configuration.getIgnoredCollectionOrderInFieldsMatchingRegexes()).extracting(Pattern::pattern)
                                                                          .containsExactly(values);
  }

  @Test
  void should_set_ignoredFields() {
    // GIVEN
    String[] values = { "foo", "bar" };
    // WHEN
    RecursiveComparisonConfiguration configuration = RecursiveComparisonConfiguration.builder()
                                                                                .withIgnoredFields(values)
                                                                                .build();
    // THEN
    then(configuration.getIgnoredFields()).containsExactly(values);
  }

  @Test
  void should_set_ignoredFieldsRegexes() {
    // GIVEN
    String[] values = { "foo", "bar" };
    // WHEN
    RecursiveComparisonConfiguration configuration = RecursiveComparisonConfiguration.builder()
                                                                                .withIgnoredFieldsMatchingRegexes(values)
                                                                                .build();
    // THEN
    then(configuration.getIgnoredFieldsRegexes()).extracting(Pattern::pattern)
                                                 .containsExactly(values);
  }

  @Test
  void should_set_ignoredOverriddenEqualsForFields() {
    // GIVEN
    String[] values = { "foo", "bar" };
    // WHEN
    RecursiveComparisonConfiguration configuration = RecursiveComparisonConfiguration.builder()
                                                                                .withIgnoredOverriddenEqualsForFields(values)
                                                                                .build();
    // THEN
    then(configuration.getIgnoredOverriddenEqualsForFields()).containsExactly(values);
  }

  @Test
  void should_set_ignoredOverriddenEqualsForTypes() {
    // GIVEN
    Class<?>[] values = { String.class, Long.class, int.class };
    // WHEN
    RecursiveComparisonConfiguration configuration = RecursiveComparisonConfiguration.builder()
                                                                                .withIgnoredOverriddenEqualsForTypes(values)
                                                                                .build();
    // THEN
    then(configuration.getIgnoredOverriddenEqualsForTypes()).containsExactly(String.class, Long.class, int.class);
  }

  @Test
  void should_set_ignoredOverriddenEqualsRegexes() {
    // GIVEN
    String[] values = { "foo", "bar" };
    // WHEN
    RecursiveComparisonConfiguration configuration = RecursiveComparisonConfiguration.builder()
                                                                                .withIgnoredOverriddenEqualsForFieldsMatchingRegexes(values)
                                                                                .build();
    // THEN
    then(configuration.getIgnoredOverriddenEqualsForFieldsMatchingRegexes()).extracting(Pattern::pattern)
                                                                            .containsExactly(values);
  }

  @Test
  void should_set_strictTypeCheckingMode() {
    // GIVEN
    boolean value = RandomUtils.nextBoolean();
    // WHEN
    RecursiveComparisonConfiguration configuration = RecursiveComparisonConfiguration.builder()
                                                                                .withStrictTypeChecking(value)
                                                                                .build();
    // THEN
    then(configuration.isInStrictTypeCheckingMode()).isEqualTo(value);
  }

  @Test
  void should_set_ignoredTypes() {
    // GIVEN
    Class<?>[] values = { String.class, Long.class, Object.class, int.class };
    // WHEN
    RecursiveComparisonConfiguration configuration = RecursiveComparisonConfiguration.builder()
                                                                                .withIgnoredFieldsOfTypes(values)
                                                                                .build();
    // THEN
    then(configuration.getIgnoredTypes()).containsExactly(String.class, Long.class, Object.class, Integer.class);
  }

  @Test
  void should_set_comparatorForField() {
    // GIVEN
    String fooLocation = "foo";
    String barLocation = "foo.bar";
    AlwaysEqualComparator<?> alwaysEqualComparator = alwaysEqual();
    // WHEN
    RecursiveComparisonConfiguration configuration = RecursiveComparisonConfiguration.builder()
                                                                                .withComparatorForFields(alwaysEqualComparator,
                                                                                fooLocation,
                                                                                barLocation)
                                                                                .build();
    // THEN
    then(configuration.hasComparatorForField(fooLocation)).isTrue();
    then(configuration.getComparatorForField(fooLocation)).isSameAs(alwaysEqualComparator);
    then(configuration.hasComparatorForField(barLocation)).isTrue();
    then(configuration.getComparatorForField(barLocation)).isSameAs(alwaysEqualComparator);
  }

  @Test
  void should_throw_NPE_if_given_comparator_for_fields_is_null() {
    // GIVEN
    Comparator<Integer> integerComparator = null;
    // WHEN
    Throwable throwable = catchThrowable(() -> RecursiveComparisonConfiguration.builder()
                                                                               .withComparatorForFields(integerComparator,
                                                                                "age"));
    // THEN
    then(throwable).isInstanceOf(NullPointerException.class)
                   .hasMessage("Expecting a non null Comparator");
  }

  @Test
  void should_throw_NPE_if_given_comparator_for_type_is_null() {
    // GIVEN
    Comparator<Integer> integerComparator = null;
    // WHEN
    Throwable throwable = catchThrowable(() -> RecursiveComparisonConfiguration.builder()
                                                                               .withComparatorForType(integerComparator,
                                                                                Integer.class));
    // THEN
    then(throwable).isInstanceOf(NullPointerException.class)
                   .hasMessage("Expecting a non null Comparator");
  }

  @Test
  void should_throw_NPE_if_given_BiPredicate_for_type_is_null() {
    // GIVEN
    BiPredicate<String, String> stringEquals = null;
    // WHEN
    Throwable throwable = catchThrowable(() -> RecursiveComparisonConfiguration.builder().withEqualsForType(stringEquals,
                                                                                String.class));
    // THEN
    then(throwable).isInstanceOf(NullPointerException.class)
                   .hasMessage("Expecting a non null BiPredicate");
  }

  @Test
  void should_throw_NPE_if_given_BiPredicate_for_fields_is_null() {
    // GIVEN
    BiPredicate<String, String> stringEquals = null;
    // WHEN
    Throwable throwable = catchThrowable(() -> RecursiveComparisonConfiguration.builder().withEqualsForFields(stringEquals,
                                                                                "id"));
    // THEN
    then(throwable).isInstanceOf(NullPointerException.class)
                   .hasMessage("Expecting a non null BiPredicate");
  }

  @Test
  void should_set_equalsForField() {
    // GIVEN
    String nameLocation = "name";
    String titleLocation = "title";
    BiPredicate<String, String> stringEquals = (String s1, String s2) -> s1.equalsIgnoreCase(s2);
    // WHEN
    RecursiveComparisonConfiguration configuration = RecursiveComparisonConfiguration.builder()
                                                                                .withEqualsForFields(stringEquals,
                                                                                nameLocation,
                                                                                titleLocation)
                                                                                .build();
    // THEN
    then(configuration.hasComparatorForField(nameLocation)).isTrue();
    then(configuration.hasComparatorForField(titleLocation)).isTrue();
  }

  @Test
  void should_set_comparatorForType() {
    // GIVEN
    AlwaysEqualComparator<String> alwaysEqualComparator = alwaysEqual();
    // WHEN
    RecursiveComparisonConfiguration configuration = RecursiveComparisonConfiguration.builder()
                                                                                .withComparatorForType(alwaysEqualComparator,
                                                                                String.class)
                                                                                .build();
    // THEN
    then(configuration.hasComparatorForType(String.class)).isTrue();
    then(configuration.getComparatorForType(String.class)).isSameAs(alwaysEqualComparator);
  }

  @Test
  void should_set_equalsForType() {
    // GIVEN
    BiPredicate<String, String> stringEquals = (String s1, String s2) -> s1.equalsIgnoreCase(s2);

    // WHEN
    RecursiveComparisonConfiguration configuration = RecursiveComparisonConfiguration.builder()
                                                                                .withEqualsForType(stringEquals,
                                                                                String.class)
                                                                                .build();
    // THEN
    then(configuration.hasComparatorForType(String.class)).isTrue();
  }
}


text:
<!DOCTYPE html>

	<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
	<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1.0, user-scalable=no">
	<meta http-equiv="X-UA-Compatible" content="IE=edge">
	<meta name="msapplication-tap-highlight" content="no">

	<link rel="apple-touch-icon" sizes="57x57" href="<?php echo base_url('assets/favicon/apple-icon-57x57.png')?>">
	<link rel="apple-touch-icon" sizes="60x60" href="<?php echo base_url('assets/favicon/apple-icon-60x60.png')?>">
	<link rel="apple-touch-icon" sizes="72x72" href="<?php echo base_url('assets/favicon/apple-icon-72x72.png')?>">
	<link rel="apple-touch-icon" sizes="76x76" href="<?php echo base_url('assets/favicon/apple-icon-76x76.png')?>">
	<link rel="apple-touch-icon" sizes="114x114" href="<?php echo base_url('assets/favicon/apple-icon-114x114.png')?>">
	<link rel="apple-touch-icon" sizes="120x120" href="<?php echo base_url('assets/favicon/apple-icon-120x120.png')?>">
	<link rel="apple-touch-icon" sizes="144x144" href="<?php echo base_url('assets/favicon/apple-icon-144x144.png')?>">
	<link rel="apple-touch-icon" sizes="152x152" href="<?php echo base_url('assets/favicon/apple-icon-152x152.png')?>">
	<link rel="apple-touch-icon" sizes="180x180" href="<?php echo base_url('assets/favicon/apple-icon-180x180.png')?>">
	<link rel="icon" type="image/png" sizes="192x192"  href="<?php echo base_url('assets/favicon/android-icon-192x192.png')?>">
	<link rel="icon" type="image/png" sizes="32x32" href="<?php echo base_url('assets/favicon/favicon-32x32.png')?>">
	<link rel="icon" type="image/png" sizes="96x96" href="<?php echo base_url('assets/favicon/favicon-96x96.png')?>">
	<link rel="icon" type="image/png" sizes="16x16" href="<?php echo base_url('assets/favicon/favicon-16x16.png')?>">
	<link rel="manifest" href="<?php echo base_url('assets/favicon/favicon-32x32.png')?>/manifest.json">
	<meta name="msapplication-TileColor" content="#ffffff">
	<meta name="msapplication-TileImage" content="<?php echo base_url('assets/favicon/ms-icon-144x144.png')?>">
	<meta name="theme-color" content="#ffffff">

	<link rel="stylesheet" type="text/css" href="<?php echo base_url();?>assets/materialize/crop/imgareaselect-default.css" />
	<link href="<?php echo base_url('assets/jquery-ui/jquery-ui.css')?>" rel="stylesheet" type="text/css" />
	<link rel="icon" href="<?php echo base_url('assets/images/favicon-32x32.png')?>" sizes="32x32">
	<link rel="apple-touch-icon-precomposed" href="<?php echo base_url('assets/images/favicon/apple-touch-icon-152x152.png')?>">
	<meta name="msapplication-TileColor" content="#00bcd4">
	<meta name="msapplication-TileImage" content="<?php echo base_url('assets/images/favicon/mstile-144x144.png')?>">

	<link href="<?php echo base_url('assets/materialize/mat/css/materialize.css')?>" type="text/css" rel="stylesheet" media="screen,projection">
	<link href="<?php echo base_url('assets/materialize/mat/css/style.css')?>" type="text/css" rel="stylesheet" media="screen,projection">
	<link href="<?php echo base_url('assets/materialize/mat/css/custom-style.css')?>" type="text/css" rel="stylesheet" media="screen,projection">

	<link href="<?php echo base_url('assets/materialize/mat/js/plugins/perfect-scrollbar/perfect-scrollbar.css')?>" type="text/css" rel="stylesheet" media="screen,projection">
	<link href="<?php echo base_url('assets/materialize/mat/js/plugins/jvectormap/jquery-jvectormap.css')?>" type="text/css?>" rel="stylesheet" media="screen,projection">
	<link href="<?php echo base_url('assets/materialize/mat/js/plugins/fullcalendar/css/fullcalendar.min.css')?>" type="text/css" rel="stylesheet" media="screen,projection">
	<link href="<?php echo base_url('assets/materialize/mat/js/plugins/data-tables/css/jquery.dataTables.min.css')?>" type="text/css" rel="stylesheet" media="screen,projection">

<a href="<?php echo base_url('admin');?>" class="brand-logo darken-1">Conference

<a href="<?php echo base_url('/admin')?>" class="waves-effect waves-cyan">Home

								Conferences

<a href="<?php echo base_url('admin/all_conferences')?>">All Conferences

<a href="<?php echo base_url('admin/add_conference')?>">Add Conference

<a href="<?php echo base_url('/admin/all_managers') ?>" class="waves-effect waves-cyan">All Managers

								 Users management

<a href="<?php echo base_url('admin/create_user')?>" class="waves-effect waves-cyan">
											Create User

<a href="<?php echo base_url('admin/edit_user')?>" class="waves-effect waves-cyan">
											Edit User

<a href="<?php echo base_url('/admin/upload_stud_list_view')?>" class="waves-effect waves-cyan">
											Upload Student List

<a href="<?php echo base_url('/admin/send_activation')?>" class="waves-effect waves-cyan">
											Send Activation


text:
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
Hola Mundo...
</body>
</html>


text:
from __future__ import absolute_import

from release import setup
import sys

install_requires = ['cryptography>=1.2', 'six']
if sys.version_info < (3, 4):
    install_requires.append('enum34')

setup(
    name='python-u2flib-server',
    author='Dain Nilsson',
    author_email='dain@yubico.com',
    description='Python based U2F server library',
    maintainer='Yubico Open Source Maintainers',
    maintainer_email='ossmaint@yubico.com',
    url='https://github.com/Yubico/python-u2flib-server',
    install_requires=install_requires,
    test_suite='test',
    tests_require=[],
    extras_require={
        'u2f_server': ['WebOb'],
    },
    classifiers=[
        'License :: OSI Approved :: BSD License',
        'Operating System :: OS Independent',
        'Development Status :: 5 - Production/Stable',
        'Intended Audience :: Developers',
        'Intended Audience :: System Administrators',
        'Programming Language :: Python :: 2',
        'Programming Language :: Python :: 2.6',
        'Programming Language :: Python :: 2.7',
        'Programming Language :: Python :: 3',
        'Programming Language :: Python :: 3.3',
        'Programming Language :: Python :: 3.4',
        'Programming Language :: Python :: 3.5',
        'Programming Language :: Python :: Implementation :: PyPy',
        'Topic :: Internet',
        'Topic :: Security :: Cryptography',
        'Topic :: Software Development :: Libraries :: Python Modules',
    ]
)


text:
  var experimentalUsbNatives = requireNative('experimental_usb');
  var GetNextUsbEventId = experimentalUsbNatives.GetNextUsbEventId;

  var chromeHidden = requireNative('chrome_hidden').GetChromeHidden();
  var sendRequest = require('sendRequest').sendRequest;
  var lazyBG = requireNative('lazy_background_page');

  chromeHidden.registerCustomHook('experimental.usb', function(api) {
      var apiFunctions = api.apiFunctions;

      apiFunctions.setHandleRequest('findDevice', function() {
          var args = arguments;
          if (args[2] && args[2].onEvent) {
            var id = GetNextUsbEventId();
            args[2].srcId = id;
            chromeHidden.usb.handlers[id] = args[2].onEvent;
            lazyBG.IncrementKeepaliveCount();
          }
          sendRequest(this.name, args, this.definition.parameters);
          return id;
        });

      chromeHidden.usb = {};
      chromeHidden.usb.handlers = {};
      chrome.experimental.usb.onEvent.addListener(function(event) {
          var eventHandler = chromeHidden.usb.handlers[event.srcId];
          if (eventHandler) {
            switch (event.type) {
              case 'transferComplete':
                eventHandler({resultCode: event.resultCode, data: event.data});
                break;
              default:
                console.error('Unexpected UsbEvent, type ' + event.type);
                break;
            }
          }
        });
    });


text:
#!/usr/bin/env node

/**
 * @file compare.js
 * A basic script that runs the solution for each problem in each language.
 * Some organization is assumed.  Solution scripts will be organized by language
 * and named with the number of the problem that the script solves (no leading 0s).
 */

var exec = require('child_process').exec
  , _ = require('underscore')
  , async = require('async')
  , AsciiTable = require('ascii-table')

/**
 * SET THESE AS NEEDED
 */
var languages = ['node', 'python']
var problems = _.range(1,11)

var extensions = {
    node: 'js',
    python: 'py'
};

/**
 * END SET VARIABLES
 */

var results = {}
var timeReggy = /real\s+(\d+\.\d+)/

async.each(languages, function(language, languageCb){
    results[language] = {}
    async.each(problems, function(problem, problemCb){
        var execString = 'time -p ./'+language+'/'+problem+'.'+extensions[language]
        exec(execString, function(err, stdout, stderr){
            if(err){
                results[language][problem] = ''
                return problemCb();
            }
            results[language][problem] = timeReggy.exec(stderr.toString())[1];
            return problemCb()
        })
    }, function(err){
        return languageCb()
    })
}, function(err){
    var table = new AsciiTable('Euler Problem Times')
    table.setHeading(['problem'].concat(languages))
    _.each(problems, function(problem){
        var row = [problem]
        _.each(languages, function(language){
            row.push(results[language][problem])
        })
        table.addRow(row)
    })
    console.log(table.toString())
})


text:
package models;

public class Node {
    public int level;
    public String imgSrc;
    public boolean hasForm;

    public Node(int level, String img, boolean flag) {
        this.level = level;
	this.imgSrc = img;
	this.hasForm = flag;
    }

    public Node(int level, String img) {
        this.level = level;
	this.imgSrc = img;
	this.hasForm = false;
    }

    public Node(String img) {
	this.level = 1;
	this.imgSrc = img;
	this.hasForm = false;
    }

    public void setImgSrc(String imgSrc) {
	this.imgSrc = imgSrc;
    }

    public String getImgSrc() {
	return this.imgSrc;
    }

    public void setLevel(int level) {
	this.level = level;
    }

    public int getLevel() {
        return this.level;
    }
}


text:
This is a tool for signing your Haskell packages with GPG. It makes it
easy to sign & upload signatures of packages to the
[sig-archive](https://github.com/commercialhaskell/sig-archive)
repository.

# Install

    cabal update
    cabal install sig-tool
    sig --help

# Signing Your Package

You can sign your own package & upload the signature to the
sig-service.  Try it!

First you need to make sure you have a valid GPG key with which to
sign packages.  Refer to the
[Debian Guide](https://wiki.debian.org/Keysigning) on key-signing
again if you don't.

Next you'll need a haskell package to sign. Grab one of your own
from hackage.  Then build sdist with the following commands:

    cabal check && cabal sdist

After you have a tarball on disk you can sign & upload the signature. Try this:

    sig sdist dist/mypackage-3.1.7.0.tar.gz

# Signing Your Entire Package Tree At Once

You can sign all of the versions of all of your packages at once with
the \`hackage\` command.

    sig hackage <hackage-username>


text:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="@color/transparent">

    <VideoView
        android:id="@+id/recipients_videoView"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        android:layout_alignParentTop="true"
        android:layout_alignParentBottom="true"
        android:layout_alignParentStart="true"
        android:layout_alignParentEnd="true"/>

    <ImageView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:contentDescription="@string/cancel"
        android:id="@+id/cancel_post"
        android:src="@drawable/ic_close_box_outline_white_24dp"
        android:layout_alignParentStart="true"
        android:layout_alignParentTop="true"
        android:layout_marginStart="8dp"/>

    <EditText
        android:layout_width="match_parent"
        android:layout_height="45dp"
        android:id="@+id/caption"
        android:textAlignment="center"
        android:visibility="gone"
        android:layout_centerInParent="true"
        android:hint="@string/comment_box_label"
        android:background="@drawable/rounded_edit_text"
        style="@style/Widget.AppCompat.EditText"
        android:textColorHint="@color/textColorPrimary"
        android:textSize="18sp"
        android:textColor="@color/black"/>

    <Button
        android:layout_width="match_parent"
        android:layout_height="45dp"
        android:layout_margin="@dimen/activity_horizontal_margin"
        android:layout_alignParentBottom="true"
        android:id="@+id/share_round_button"
        android:text="@string/share_around"
        android:textColor="@color/black"
        android:background="@drawable/around_button_selector"/>

</RelativeLayout>