text:
#include <Display.h>
#include <Utils.h>
#include <SDL.h>
#include <Surface.h>
#include <nme/NmeCffi.h>
#include <KeyCodes.h>
#include <map>
#include <Sound.h>

#ifdef NME_MIXER
#include <SDL_mixer.h>
#endif

namespace nme
{

static int sgDesktopWidth = 0;
static int sgDesktopHeight = 0;
static Rect sgWindowRect = Rect(0, 0, 0, 0);
static bool sgInitCalled = false;
static bool sgJoystickEnabled = false;
static int  sgShaderFlags = 0;
static bool sgIsOGL2 = false;

enum { NO_TOUCH = -1 };

int InitSDL()
{
   if (sgInitCalled)
      return 0;

   sgInitCalled = true;

   #ifdef NME_MIXER
   int audioFlag = SDL_INIT_AUDIO;
   #else
   int audioFlag = 0;
   #endif
   int err = SDL_Init(SDL_INIT_VIDEO | audioFlag | SDL_INIT_TIMER);

   if (err == 0 && SDL_InitSubSystem (SDL_INIT_JOYSTICK) == 0)
   {
      sgJoystickEnabled = true;
   }

   return err;
}

static void openAudio()
{
   gSDLAudioState = sdaOpen;

   #ifdef HX_WINDOWS
   int chunksize = 2048;
   #else
   int chunksize = 4096;
   #endif

   int frequency = 44100;
   //int frequency = MIX_DEFAULT_FREQUENCY //22050
   //The default frequency would have less latency, but is incompatible with the average MP3 file

   if (Mix_OpenAudio(frequency, MIX_DEFAULT_FORMAT, MIX_DEFAULT_CHANNELS, chunksize) != 0)
   {
      fprintf(stderr,"Could not open sound: %s\n", Mix_GetError());
      gSDLAudioState = sdaError;
   }
}

void InitSDLAudio()
{
   SDL_Init(SDL_INIT_AUDIO);
   openAudio();
}

class SDLSurf : public Surface
{
public:
   SDLSurf(SDL_Surface *inSurf,bool inDelete) : mSurf(inSurf)
   {
      mDelete = inDelete;
      mLockedForHitTest = false;
   }
   ~SDLSurf()
   {
      if (mDelete)
         SDL_FreeSurface(mSurf);
   }

   int Width() const { return mSurf->w; }
   int Height() const { return mSurf->h; }
   PixelFormat Format() const { return pfXRGB; }
   const uint8 *GetBase() const { return (const uint8 *)mSurf->pixels; }
   int GetStride() const { return mSurf->pitch; }

   void Clear(uint32 inColour,const Rect *inRect)
   {
      SDL_Rect r;
      SDL_Rect *rect_ptr = 0;
      if (inRect)
      {
         rect_ptr = &r;
         r.x = inRect->x;
         r.y = inRect->y;
         r.w = inRect->w;
         r.h = inRect->h;
      }

      SDL_FillRect(mSurf,rect_ptr,SDL_MapRGBA(mSurf->format,
            inColour>>16, inColour>>8, inColour, inColour>>24 )  );
   }

   uint8 *Edit(const Rect *inRect)
   {
      if (SDL_MUSTLOCK(mSurf))
         SDL_LockSurface(mSurf);

      return (uint8 *)mSurf->pixels;
   }
   void Commit()
   {
      if (SDL_MUSTLOCK(mSurf))
         SDL_UnlockSurface(mSurf);
   }

   RenderTarget BeginRender(const Rect &inRect,bool inForHitTest)
   {
      mLockedForHitTest = inForHitTest;
      if (SDL_MUSTLOCK(mSurf) && !mLockedForHitTest)
         SDL_LockSurface(mSurf);
      return RenderTarget(Rect(Width(),Height()), Format(),
         (uint8 *)mSurf->pixels, mSurf->pitch);
   }
   void EndRender()
   {
      if (SDL_MUSTLOCK(mSurf) && !mLockedForHitTest)
         SDL_UnlockSurface(mSurf);
   }

   void BlitTo(const RenderTarget &outTarget,
               const Rect &inSrcRect,int inPosX, int inPosY,
               BlendMode inBlend, const BitmapCache *inMask,
               uint32 inTint=0xffffff ) const
   {
   }
   void BlitChannel(const RenderTarget &outTarget, const Rect &inSrcRect,
                            int inPosX, int inPosY,
                            int inSrcChannel, int inDestChannel ) const
   {
   }

   void StretchTo(const RenderTarget &outTarget,
          const Rect &inSrcRect, const DRect &inDestRect) const
   {
   }

   SDL_Surface *mSurf;
   bool  mDelete;
   bool  mLockedForHitTest;
};

/*
SDL_Surface *SurfaceToSDL(Surface *inSurface)
{
   int swap =  (gC0IsRed!=(bool)(inSurface->Format()&pfSwapRB)) ? 0xff00ff : 0;
   return SDL_CreateRGBSurfaceFrom((void *)inSurface->Row(0),
             inSurface->Width(), inSurface->Height(),
             32, inSurface->Width()*4,
             0x00ff0000^swap, 0x0000ff00,
             0x000000ff^swap, 0xff000000 );
}
*/

SDL_Cursor *CreateCursor(const char *image[],int inHotX,int inHotY)
{
   int i, row, col;
   Uint8 data[4*32];
   Uint8 mask[4*32];

   i = -1;
   for ( row=0; row<32; ++row ) {
      for ( col=0; col<32; ++col ) {
         if ( col % 8 ) {
            data[i] <<= 1;
            mask[i] <<= 1;
         } else {
            ++i;
            data[i] = mask[i] = 0;
         }
         switch (image[row][col]) {
            case 'X':
               data[i] |= 0x01;
               mask[i] |= 0x01;
               break;
            case '.':
               mask[i] |= 0x01;
               break;
            case ' ':
               break;
         }
      }
   }
   return SDL_CreateCursor(data, mask, 32, 32, inHotX, inHotY);
}

SDL_Cursor *sDefaultCursor = 0;
SDL_Cursor *sTextCursor = 0;
SDL_Cursor *sHandCursor = 0;

class SDLStage : public Stage
{
public:
   SDLStage(SDL_Window *inWindow, SDL_Renderer *inRenderer, uint32 inWindowFlags, bool inIsOpenGL, int inWidth, int inHeight)
   {
      mWidth = inWidth;
      mHeight = inHeight;

      mIsOpenGL = inIsOpenGL;
      mSDLWindow = inWindow;
      mSDLRenderer = inRenderer;
      mWindowFlags = inWindowFlags;

      mShowCursor = true;
      mCurrentCursor = curPointer;

      mIsFullscreen = (mWindowFlags & SDL_WINDOW_FULLSCREEN || mWindowFlags & SDL_WINDOW_FULLSCREEN_DESKTOP);
      if (mIsFullscreen)
         displayState = sdsFullscreenInteractive;

      if (mIsOpenGL)
      {
         mOpenGLContext = HardwareRenderer::CreateOpenGL(0, 0, sgIsOGL2);
         mOpenGLContext->IncRef();
         //mOpenGLContext->SetWindowSize(inSurface->w, inSurface->h);
         mOpenGLContext->SetWindowSize(mWidth, mHeight);
         mPrimarySurface = new HardwareSurface(mOpenGLContext);
      }
      else
      {
         mOpenGLContext = 0;
         mSoftwareSurface = SDL_CreateRGBSurface(0, mWidth, mHeight, 32, 0xFF000000, 0x00FF0000, 0x0000FF00, 0x000000FF);
         if (!mSoftwareSurface)
         {
            fprintf(stderr, "Could not create SDL surface : %s\n", SDL_GetError());
         }
         mSoftwareTexture = SDL_CreateTexture(mSDLRenderer, SDL_PIXELFORMAT_ARGB8888, SDL_TEXTUREACCESS_STREAMING, mWidth, mHeight);
         mPrimarySurface = new SDLSurf(mSoftwareSurface, inIsOpenGL);
      }
      mPrimarySurface->IncRef();

      #if defined(WEBOS) || defined(BLACKBERRY)
      mMultiTouch = true;
      #else
      mMultiTouch = false;
      #endif
      mSingleTouchID = NO_TOUCH;
      mDX = 0;
      mDY = 0;

      mDownX = 0;
      mDownY = 0;
   }

   ~SDLStage()
   {
      SDL_SetWindowFullscreen(mSDLWindow, 0);
      if (!mIsOpenGL)
      {
         SDL_FreeSurface(mSoftwareSurface);
         SDL_DestroyTexture(mSoftwareTexture);
      }
      else
      {
         mOpenGLContext->DecRef();
      }
      mPrimarySurface->DecRef();
      SDL_DestroyRenderer(mSDLRenderer);
      SDL_DestroyWindow(mSDLWindow);
   }

   void Resize(int inWidth, int inHeight)
   {
      mWidth = inWidth;
      mHeight = inHeight;

      if (mIsOpenGL)
      {
         mOpenGLContext->SetWindowSize(inWidth, inHeight);
      }
      else
      {
         SDL_FreeSurface(mSoftwareSurface);
         SDL_DestroyTexture(mSoftwareTexture);

         mSoftwareSurface = SDL_CreateRGBSurface(0, mWidth, mHeight, 32, 0xFF000000, 0x00FF0000, 0x0000FF00, 0x000000FF);
         if (!mSoftwareSurface)
         {
            fprintf(stderr, "Could not create SDL surface : %s\n", SDL_GetError());
         }
         mSoftwareTexture = SDL_CreateTexture(mSDLRenderer, SDL_PIXELFORMAT_ARGB8888, SDL_TEXTUREACCESS_STREAMING, mWidth, mHeight);
         ((SDLSurf*)mPrimarySurface)->mSurf = mSoftwareSurface;
      }
   }

   void ResizeWindow(int inWidth, int inHeight)
   {
      if (mIsFullscreen)
      {
         SDL_DisplayMode mode;
         SDL_GetCurrentDisplayMode(0, &mode);

         mode.w = inWidth;
         mode.h = inHeight;

         SDL_SetWindowDisplayMode(mSDLWindow, &mode);
      }
      else
      {
         SDL_SetWindowSize(mSDLWindow, inWidth, inHeight);
      }
   }

   void SetFullscreen(bool inFullscreen)
   {
      if (inFullscreen != mIsFullscreen)
      {
         mIsFullscreen = inFullscreen;

         if (mIsFullscreen)
         {
            SDL_GetWindowPosition(mSDLWindow, &sgWindowRect.x, &sgWindowRect.y);
            SDL_GetWindowSize(mSDLWindow, &sgWindowRect.w, &sgWindowRect.h);

            //SDL_SetWindowSize(mSDLWindow, sgDesktopWidth, sgDesktopHeight);

            SDL_DisplayMode mode;
            SDL_GetCurrentDisplayMode(0, &mode);
            mode.w = sgDesktopWidth;
            mode.h = sgDesktopHeight;
            SDL_SetWindowDisplayMode(mSDLWindow, &mode);

            SDL_SetWindowFullscreen(mSDLWindow, SDL_WINDOW_FULLSCREEN /*SDL_WINDOW_FULLSCREEN_DESKTOP*/);
         }
         else
         {
            SDL_SetWindowFullscreen(mSDLWindow, 0);
            if (sgWindowRect.w && sgWindowRect.h)
            {
               SDL_SetWindowSize(mSDLWindow, sgWindowRect.w, sgWindowRect.h);
            }
            #ifndef HX_LINUX
            SDL_SetWindowPosition(mSDLWindow, sgWindowRect.x, sgWindowRect.y);
            #endif
         }
      }
   }

   bool isOpenGL() const { return mOpenGLContext; }

   void ProcessEvent(Event &inEvent)
   {
      #if defined(HX_WINDOWS) || defined(HX_LINUX)
      if (inEvent.type == etKeyUp && (inEvent.flags & efAltDown) && inEvent.value == keyF4)
      {
         inEvent.type = etQuit;
      }
      #endif

      #if defined(WEBOS) || defined(BLACKBERRY)
      if (inEvent.type == etMouseMove || inEvent.type == etMouseDown || inEvent.type == etMouseUp)
      {
         if (mSingleTouchID == NO_TOUCH || inEvent.value == mSingleTouchID || !mMultiTouch)
         inEvent.flags |= efPrimaryTouch;

         if (mMultiTouch)
         {
            switch(inEvent.type)
            {
               case etMouseDown: inEvent.type = etTouchBegin; break;
               case etMouseUp: inEvent.type = etTouchEnd; break;
               case etMouseMove: inEvent.type = etTouchMove; break;
            }

            if (inEvent.type == etTouchBegin)
            {
               mDownX = inEvent.x;
               mDownY = inEvent.y;
            }

            if (inEvent.type == etTouchEnd)
            {
               if (mSingleTouchID == inEvent.value)
                  mSingleTouchID = NO_TOUCH;
            }
         }
      }
      #endif

      HandleEvent(inEvent);
   }

   void Flip()
   {
      if (mIsOpenGL)
      {
         #ifdef RASPBERRYPI
         nmeEGLSwapBuffers();
         #else
         SDL_RenderPresent(mSDLRenderer);
         #endif
      }
      else
      {
         SDL_UpdateTexture(mSoftwareTexture, NULL, mSoftwareSurface->pixels, mSoftwareSurface->pitch);
         //SDL_RenderClear(mSDLRenderer);
         SDL_RenderCopy(mSDLRenderer, mSoftwareTexture, NULL, NULL);
         SDL_RenderPresent(mSDLRenderer);
      }
   }

   void GetMouse()
   {

   }

   void SetCursor(Cursor inCursor)
   {
      if (sDefaultCursor==0)
         sDefaultCursor = SDL_GetCursor();

      mCurrentCursor = inCursor;

      if (inCursor==curNone || !mShowCursor)
         SDL_ShowCursor(false);
      else
      {
         SDL_ShowCursor(true);

         if (inCursor==curPointer)
            SDL_SetCursor(sDefaultCursor);
         else if (inCursor==curHand)
         {
            if (!sHandCursor)
               sHandCursor = CreateCursor(sHandCursorData,13,1);
            SDL_SetCursor(sHandCursor);
         }
         else
         {
         // TODO: Rotated
         if (sTextCursor==0)
            sTextCursor = CreateCursor(sTextCursorData,2,13);
         SDL_SetCursor(sTextCursor);
         }
      }
   }

   void ShowCursor(bool inShow)
   {
      if (inShow!=mShowCursor)
      {
         mShowCursor = inShow;
         this->SetCursor(mCurrentCursor);
      }
   }

    void ConstrainCursorToWindowFrame(bool inLock)
    {
        if (inLock != mLockCursor)
        {
           mLockCursor = inLock;
           SDL_SetRelativeMouseMode( inLock ? SDL_FALSE : SDL_TRUE );
        }
    }

      //Note that this fires a mouse event, see the SDL_WarpMouseInWindow docs
    void SetCursorPositionInWindow(int inX, int inY)
    {
      SDL_WarpMouseInWindow( mSDLWindow, inX, inY );
    }

      //Note that this fires a mouse event, see the SDL_WarpMouseInWindow docs
    void SetStageWindowPosition(int inX, int inY)
    {
      SDL_SetWindowPosition( mSDLWindow, inX, inY );
    }

   void EnablePopupKeyboard(bool enabled)
   {

   }

   bool getMultitouchSupported()
   {
      #if defined(WEBOS) || defined(BLACKBERRY)
      return true;
      #else
      return false;
      #endif
   }

   void setMultitouchActive(bool inActive) { mMultiTouch = inActive; }

   bool getMultitouchActive()
   {
      #if defined(WEBOS) || defined(BLACKBERRY)
      return mMultiTouch;
      #else
      return false;
      #endif
   }

   bool mMultiTouch;
   int  mSingleTouchID;

   double mDX;
   double mDY;

   double mDownX;
   double mDownY;

   Surface *GetPrimarySurface()
   {
      return mPrimarySurface;
   }

   HardwareRenderer *mOpenGLContext;
   SDL_Window *mSDLWindow;
   SDL_Renderer *mSDLRenderer;
   Surface     *mPrimarySurface;
   SDL_Surface *mSoftwareSurface;
   SDL_Texture *mSoftwareTexture;
   double       mFrameRate;
   bool         mIsOpenGL;
   Cursor       mCurrentCursor;
   bool         mShowCursor;
   bool            mLockCursor;
   bool         mIsFullscreen;
   unsigned int mWindowFlags;
   int          mWidth;
   int          mHeight;
};

class SDLFrame : public Frame
{
public:
   SDLFrame(SDL_Window *inWindow, SDL_Renderer *inRenderer, uint32 inWindowFlags, bool inIsOpenGL, int inWidth, int inHeight)
   {
      mWindowFlags = inWindowFlags;
      mIsOpenGL = inIsOpenGL;
      mStage = new SDLStage(inWindow, inRenderer, mWindowFlags, inIsOpenGL, inWidth, inHeight);
      mStage->IncRef();
   }

   ~SDLFrame()
   {
      mStage->DecRef();
   }

   void ProcessEvent(Event &inEvent)
   {
      mStage->ProcessEvent(inEvent);
   }

   void Resize(int inWidth, int inHeight)
   {
      mStage->Resize(inWidth, inHeight);
   }

   // --- Frame Interface ----------------------------------------------------

   void SetTitle()
   {

   }

   void SetIcon()
   {

   }

   Stage *GetStage()
   {
      return mStage;
   }

   SDLStage *mStage;
   bool mIsOpenGL;
   uint32 mWindowFlags;

   double mAccX;
   double mAccY;
   double mAccZ;
};

// --- When using the simple window class -----------------------------------------------

extern "C" void MacBoot( /*void (*)()*/ );

SDLFrame *sgSDLFrame = 0;
#ifndef EMSCRIPTEN
SDL_Joystick *sgJoystick = 0;
#endif

void AddModStates(int &ioFlags,int inState = -1)
{
   int state = inState==-1 ? SDL_GetModState() : inState;
   if (state & KMOD_SHIFT) ioFlags |= efShiftDown;
   if (state & KMOD_CTRL) ioFlags |= efCtrlDown;
   if (state & KMOD_ALT) ioFlags |= efAltDown;
   if (state & KMOD_GUI) ioFlags |= efCommandDown;

   int m = SDL_GetMouseState(0,0);
   if ( m & SDL_BUTTON(1) ) ioFlags |= efLeftDown;
   if ( m & SDL_BUTTON(2) ) ioFlags |= efMiddleDown;
   if ( m & SDL_BUTTON(3) ) ioFlags |= efRightDown;

   ioFlags |= efPrimaryTouch;
   ioFlags |= efNoNativeClick;
}

#define SDL_TRANS(x) case SDLK_##x: return key##x;
#define SDL_TRANS_TO(x, y) case SDLK_##x: return key##y;

int SDLKeyToFlash(int inKey,bool &outRight)
{
   outRight = (inKey==SDLK_RSHIFT || inKey==SDLK_RCTRL ||
               inKey==SDLK_RALT || inKey==SDLK_RGUI);
   if (inKey>=keyA && inKey<=keyZ){
      return inKey;
   }
   if (inKey>=keyA+32 && inKey<=keyZ+32){
      return inKey - 32;
   }
   if (inKey>=SDLK_0 && inKey<=SDLK_9)
      return inKey - SDLK_0 + keyNUMBER_0;

   if (inKey>=SDLK_F1 && inKey<=SDLK_F12)
      return inKey - SDLK_F1 + keyF1;

   switch(inKey)
   {
      case SDLK_RALT:
      case SDLK_LALT:
         return keyALTERNATE;
      case SDLK_RSHIFT:
      case SDLK_LSHIFT:
         return keySHIFT;
      case SDLK_RCTRL:
      case SDLK_LCTRL:
         return keyCONTROL;
      case SDLK_LGUI:
      case SDLK_RGUI:
         return keyCOMMAND;

      case SDLK_CAPSLOCK: return keyCAPS_LOCK;
      case SDLK_PAGEDOWN: return keyPAGE_DOWN;
      case SDLK_PAGEUP: return keyPAGE_UP;
      case SDLK_EQUALS: return keyEQUAL;
      case SDLK_RETURN:
      case SDLK_KP_ENTER:
         return keyENTER;

      SDL_TRANS(BACKQUOTE)
      SDL_TRANS(BACKSLASH)
      SDL_TRANS(BACKSPACE)
      SDL_TRANS(COMMA)
      SDL_TRANS(DELETE)
      SDL_TRANS(DOWN)
      SDL_TRANS(END)
      SDL_TRANS(ESCAPE)
      SDL_TRANS(HOME)
      SDL_TRANS(INSERT)
      SDL_TRANS(LEFT)
      SDL_TRANS(LEFTBRACKET)
      SDL_TRANS(MINUS)
      SDL_TRANS(PERIOD)
      SDL_TRANS(QUOTE)
      SDL_TRANS(RIGHT)
      SDL_TRANS(RIGHTBRACKET)
      SDL_TRANS(SEMICOLON)
      SDL_TRANS(SLASH)
      SDL_TRANS(SPACE)
      SDL_TRANS(TAB)
      SDL_TRANS(UP)
      SDL_TRANS(F13)
      SDL_TRANS(F14)
      SDL_TRANS(F15)
      SDL_TRANS_TO(KP_0, NUMPAD_0)
      SDL_TRANS_TO(KP_1, NUMPAD_1)
      SDL_TRANS_TO(KP_2, NUMPAD_2)
      SDL_TRANS_TO(KP_3, NUMPAD_3)
      SDL_TRANS_TO(KP_4, NUMPAD_4)
      SDL_TRANS_TO(KP_5, NUMPAD_5)
      SDL_TRANS_TO(KP_6, NUMPAD_6)
      SDL_TRANS_TO(KP_7, NUMPAD_7)
      SDL_TRANS_TO(KP_8, NUMPAD_8)
      SDL_TRANS_TO(KP_9, NUMPAD_9)
      SDL_TRANS_TO(KP_PLUS, NUMPAD_ADD)
      SDL_TRANS_TO(KP_DECIMAL, NUMPAD_DECIMAL)
      SDL_TRANS_TO(KP_PERIOD, NUMPAD_DECIMAL)
      SDL_TRANS_TO(KP_DIVIDE, NUMPAD_DIVIDE)
      //SDL_TRANS_TO(KP_ENTER, NUMPAD_ENTER)
      SDL_TRANS_TO(KP_MULTIPLY, NUMPAD_MULTIPLY)
      SDL_TRANS_TO(KP_MINUS, NUMPAD_SUBTRACT)
   }

   return inKey;
}

void AddCharCode(Event &key)
{
   bool shift = (key.flags & efShiftDown);
   bool foundCode = true;

   if (!shift)
   {
      switch (key.value)
      {
         case 8:
         case 13:
         case 27:
         case 32:
            key.code = key.value;
            break;
         case 186:
            key.code = 59;
            break;
         case 187:
            key.code = 61;
            break;
         case 188:
         case 189:
         case 190:
         case 191:
            key.code = key.value - 144;
            break;
         case 192:
            key.code = 96;
            break;
         case 219:
         case 220:
         case 221:
            key.code = key.value - 128;
            break;
         case 222:
            key.code = 39;
            break;
         default:
            foundCode = false;
            break;
      }

      if (!foundCode)
      {
         if (key.value >= 48 && key.value <= 57)
         {
            key.code = key.value;
            foundCode = true;
         }
         else if (key.value >= 65 && key.value <= 90)
         {
            key.code = key.value + 32;
            foundCode = true;
         }
      }
   }
   else
   {
      switch (key.value)
      {
         case 48:
            key.code = 41;
            break;
         case 49:
            key.code = 33;
            break;
         case 50:
            key.code = 64;
            break;
         case 51:
         case 52:
         case 53:
            key.code = key.value - 16;
            break;
         case 54:
            key.code = 94;
            break;
         case 55:
            key.code = 38;
            break;
         case 56:
            key.code = 42;
            break;
         case 57:
            key.code = 40;
            break;
         case 186:
            key.code = 58;
            break;
         case 187:
            key.code = 43;
            break;
         case 188:
            key.code = 60;
            break;
         case 189:
            key.code = 95;
            break;
         case 190:
            key.code = 62;
            break;
         case 191:
            key.code = 63;
            break;
         case 192:
            key.code = 126;
            break;
         case 219:
         case 220:
         case 221:
            key.code = key.value - 96;
            break;
         case 222:
            key.code = 34;
            break;
         default:
            foundCode = false;
            break;
      }

      if (!foundCode)
      {
         if (key.value >= 65 && key.value <= 90)
         {
            key.code = key.value;
            foundCode = true;
         }
      }
   }

   if (!foundCode)
   {
      if (key.value >= 96 && key.value <= 105)
      {
         key.code = key.value - 48;
      }
      else if (key.value >= 106 && key.value <= 111)
      {
         key.code = key.value - 64;
      }
      else if (key.value == 46)
      {
         key.code = 127;
      }
      else if (key.value == 13)
      {
         key.code = 13;
      }
      else if (key.value == 8)
      {
         key.code = keyBACKSPACE;
      }
      else
      {
         key.code = 0;
      }
   }
}

std::map<int,wchar_t> sLastUnicode;

void ProcessEvent(SDL_Event &inEvent)
{
   switch(inEvent.type)
   {
      case SDL_QUIT:
      {
         Event close(etQuit);
         sgSDLFrame->ProcessEvent(close);
         break;
      }
      case SDL_WINDOWEVENT:
      {
         switch (inEvent.window.event)
         {
            case SDL_WINDOWEVENT_SHOWN:
            {
               Event activate(etActivate);
               sgSDLFrame->ProcessEvent(activate);
               break;
            }
            case SDL_WINDOWEVENT_HIDDEN:
            {
               Event deactivate(etDeactivate);
               sgSDLFrame->ProcessEvent(deactivate);
               break;
            }
            case SDL_WINDOWEVENT_EXPOSED:
            {
               Event poll(etPoll);
               sgSDLFrame->ProcessEvent(poll);
               break;
            }
            //case SDL_WINDOWEVENT_MOVED: break;
            //case SDL_WINDOWEVENT_RESIZED: break;
            case SDL_WINDOWEVENT_SIZE_CHANGED:
            {
               Event resize(etResize, inEvent.window.data1, inEvent.window.data2);
               sgSDLFrame->Resize(inEvent.window.data1, inEvent.window.data2);
               sgSDLFrame->ProcessEvent(resize);
               break;
            }
            //case SDL_WINDOWEVENT_MINIMIZED: break;
            //case SDL_WINDOWEVENT_MAXIMIZED: break;
            //case SDL_WINDOWEVENT_RESTORED: break;
            //case SDL_WINDOWEVENT_ENTER: break;
            //case SDL_WINDOWEVENT_LEAVE: break;
            case SDL_WINDOWEVENT_FOCUS_GAINED:
            {
               Event inputFocus(etGotInputFocus);
               sgSDLFrame->ProcessEvent(inputFocus);
               break;
            }
            case SDL_WINDOWEVENT_FOCUS_LOST:
            {
               Event inputFocus(etLostInputFocus);
               sgSDLFrame->ProcessEvent(inputFocus);
               break;
            }
            case SDL_WINDOWEVENT_CLOSE:
            {
               //Event deactivate(etDeactivate);
               //sgSDLFrame->ProcessEvent(deactivate);

               //Event kill(etDestroyHandler);
               //sgSDLFrame->ProcessEvent(kill);
               break;
            }
            default: break;
         }
      }
      case SDL_MOUSEMOTION:
      {
         Event mouse(etMouseMove, inEvent.motion.x, inEvent.motion.y);
         #if defined(WEBOS) || defined(BLACKBERRY)
         mouse.value = inEvent.motion.which;
         mouse.flags |= efLeftDown;
         #else
         AddModStates(mouse.flags);
         #endif
         sgSDLFrame->ProcessEvent(mouse);
         break;
      }
      case SDL_MOUSEBUTTONDOWN:
      {
         Event mouse(etMouseDown, inEvent.button.x, inEvent.button.y, inEvent.button.button - 1);
         #if defined(WEBOS) || defined(BLACKBERRY)
         mouse.value = inEvent.motion.which;
         mouse.flags |= efLeftDown;
         #else
         AddModStates(mouse.flags);
         #endif
         sgSDLFrame->ProcessEvent(mouse);
         break;
      }
      case SDL_MOUSEBUTTONUP:
      {
         Event mouse(etMouseUp, inEvent.button.x, inEvent.button.y, inEvent.button.button - 1);
         #if defined(WEBOS) || defined(BLACKBERRY)
         mouse.value = inEvent.motion.which;
         #else
         AddModStates(mouse.flags);
         #endif
         sgSDLFrame->ProcessEvent(mouse);
         break;
      }
      case SDL_MOUSEWHEEL:
      {
            //previous behavior in nme was 3 for down, 4 for up
         int event_dir = (inEvent.wheel.y > 0) ? 3 : 4;
            //space to get the current mouse position, to make sure the values are sane
         int _x = 0;
         int _y = 0;
            //fetch the mouse position
         SDL_GetMouseState(&_x,&_y);
            //create the event
         Event mouse(etMouseUp, _x, _y, event_dir);
            //add flags for modifier keys
         AddModStates(mouse.flags);
            //and done.
         sgSDLFrame->ProcessEvent(mouse);
      }
      case SDL_KEYDOWN:
      case SDL_KEYUP:
      {
         Event key(inEvent.type == SDL_KEYDOWN ? etKeyDown : etKeyUp );
         bool right;
         key.value = SDLKeyToFlash(inEvent.key.keysym.sym, right);
         /*if (inEvent.type == SDL_KEYDOWN)
         {
            //key.code = key.value==keyBACKSPACE ? keyBACKSPACE : inEvent.key.keysym.unicode;
            key.code = inEvent.key.keysym.scancode;
            sLastUnicode[inEvent.key.keysym.scancode] = key.code;
         }
         else
            // SDL does not provide unicode on key up, so remember it,
            //  keyed by scancode
            key.code = sLastUnicode[inEvent.key.keysym.scancode];*/
         //key.code = 0;
         AddModStates(key.flags, inEvent.key.keysym.mod);
         if (right)
            key.flags |= efLocationRight;

         // SDL2 does not expose char codes in key events (due to the more advanced
         // Unicode event API), so we'll add some ASCII assumptions to return something
         AddCharCode(key);
         sgSDLFrame->ProcessEvent(key);
         break;
      }
      case SDL_JOYAXISMOTION:
      {
         Event joystick(etJoyAxisMove);
         joystick.id = inEvent.jaxis.which;
         joystick.code = inEvent.jaxis.axis;
         joystick.value = inEvent.jaxis.value;
         sgSDLFrame->ProcessEvent(joystick);
         break;
      }
      case SDL_JOYBALLMOTION:
      {
         Event joystick(etJoyBallMove, inEvent.jball.xrel, inEvent.jball.yrel);
         joystick.id = inEvent.jball.which;
         joystick.code = inEvent.jball.ball;
         sgSDLFrame->ProcessEvent(joystick);
         break;
      }
      case SDL_JOYBUTTONDOWN:
      {
         Event joystick(etJoyButtonDown);
         joystick.id = inEvent.jbutton.which;
         joystick.code = inEvent.jbutton.button;
         sgSDLFrame->ProcessEvent(joystick);
         break;
      }
      case SDL_JOYBUTTONUP:
      {
         Event joystick(etJoyButtonUp);
         joystick.id = inEvent.jbutton.which;
         joystick.code = inEvent.jbutton.button;
         sgSDLFrame->ProcessEvent(joystick);
         break;
      }
      case SDL_JOYHATMOTION:
      {
         Event joystick(etJoyHatMove);
         joystick.id = inEvent.jhat.which;
         joystick.code = inEvent.jhat.hat;
         joystick.value = inEvent.jhat.value;
         sgSDLFrame->ProcessEvent(joystick);
         break;
      }
   }
};

void CreateMainFrame(FrameCreationCallback inOnFrame, int inWidth, int inHeight, unsigned int inFlags, const char *inTitle, Surface *inIcon)
{
   bool fullscreen = (inFlags & wfFullScreen) != 0;
   bool opengl = (inFlags & wfHardware) != 0;
   bool resizable = (inFlags & wfResizable) != 0;
   bool borderless = (inFlags & wfBorderless) != 0;
   bool vsync = (inFlags & wfVSync) != 0;

   #ifdef HX_LINUX
   if (opengl)
   {
      if (!InitOGLFunctions())
        opengl = false;
   }
   #endif

   sgShaderFlags = (inFlags & (wfAllowShaders|wfRequireShaders) );

   //Rect r(100,100,inWidth,inHeight);

   int err = InitSDL();
   if (err == -1)
   {
      fprintf(stderr,"Could not initialize SDL : %s\n", SDL_GetError());
      inOnFrame(0);
   }

   //SDL_EnableUNICODE(1);
   //SDL_EnableKeyRepeat(500,30);

   #ifdef NME_MIXER
   openAudio();
   #endif

   if (SDL_GetNumVideoDisplays() > 0)
   {
      SDL_DisplayMode currentMode;
      SDL_GetDesktopDisplayMode(0, &currentMode);
      sgDesktopWidth = currentMode.w;
      sgDesktopHeight = currentMode.h;
   }

   int windowFlags = 0;

   if (opengl) windowFlags |= SDL_WINDOW_OPENGL;
   if (resizable) windowFlags |= SDL_WINDOW_RESIZABLE;
   if (borderless) windowFlags |= SDL_WINDOW_BORDERLESS;
   if (fullscreen) windowFlags |= SDL_WINDOW_FULLSCREEN; //SDL_WINDOW_FULLSCREEN_DESKTOP;

   if (opengl)
   {
      SDL_GL_SetAttribute(SDL_GL_RED_SIZE, 8);
      SDL_GL_SetAttribute(SDL_GL_GREEN_SIZE, 8);
      SDL_GL_SetAttribute(SDL_GL_BLUE_SIZE, 8);

      if (inFlags & wfDepthBuffer)
         SDL_GL_SetAttribute(SDL_GL_DEPTH_SIZE, 32 - (inFlags & wfStencilBuffer) ? 8 : 0);

      if (inFlags & wfStencilBuffer)
         SDL_GL_SetAttribute(SDL_GL_STENCIL_SIZE, 8);

      SDL_GL_SetAttribute(SDL_GL_DOUBLEBUFFER, 1);

      if (inFlags & wfHW_AA_HIRES)
      {
         SDL_GL_SetAttribute(SDL_GL_MULTISAMPLEBUFFERS, true);
         SDL_GL_SetAttribute(SDL_GL_MULTISAMPLESAMPLES, 4);
      }
      else if (inFlags & wfHW_AA)
      {
         SDL_GL_SetAttribute(SDL_GL_MULTISAMPLEBUFFERS, true);
         SDL_GL_SetAttribute(SDL_GL_MULTISAMPLESAMPLES, 2);
      }
   }

   #ifdef HX_LINUX
   int setWidth = inWidth;
   int setHeight = inHeight;
   #else
   int setWidth = fullscreen ? sgDesktopWidth : inWidth;
   int setHeight = fullscreen ? sgDesktopHeight : inHeight;
   #endif

   SDL_Window *window = SDL_CreateWindow (inTitle, SDL_WINDOWPOS_UNDEFINED, SDL_WINDOWPOS_UNDEFINED, setWidth, setHeight, windowFlags);

   if (!window) return;
   windowFlags = SDL_GetWindowFlags (window);

   if (fullscreen) {

      sgWindowRect = Rect(SDL_WINDOWPOS_CENTERED, SDL_WINDOWPOS_CENTERED, inWidth, inHeight);

   }

   int renderFlags = 0;

   if (opengl) renderFlags |= SDL_RENDERER_ACCELERATED;
   if (vsync) renderFlags |= SDL_RENDERER_PRESENTVSYNC;

   SDL_Renderer *renderer = SDL_CreateRenderer (window, -1, renderFlags);

   if (!renderer && opengl) {

      opengl = false;
      renderFlags &= ~SDL_RENDERER_ACCELERATED;

      renderer = SDL_CreateRenderer (window, -1, renderFlags);

   }

   if (!renderer) return;

   if (opengl) {

      sgIsOGL2 = (inFlags & (wfAllowShaders | wfRequireShaders));

   }

/*#if defined(IPHONE) || defined(BLACKBERRY) || defined(EMSCRIPTEN)
   sdl_flags |= SDL_NOFRAME;
#else
   if (inIcon)
   {
      SDL_Surface *sdl = SurfaceToSDL(inIcon);
      SDL_WM_SetIcon( sdl, NULL );
   }
#endif

   #if defined (HX_WINDOWS) || defined (HX_LINUX)
   //SDL_WM_SetCaption( inTitle, 0 );
   #endif

   SDL_Surface* screen = 0;
   bool is_opengl = false;
   sgIsOGL2 = false;

   #ifdef RASPBERRYPI
   bool nmeEgl = true;
   #else
   bool nmeEgl = false;
   #endif

   if (opengl && !nmeEgl)
   {
      int  aa_tries = (inFlags & wfHW_AA) ? ( (inFlags & wfHW_AA_HIRES) ? 2 : 1 ) : 0;

      //int bpp = info->vfmt->BitsPerPixel;
      int startingPass = 0;

      // Try for 24:8  depth:stencil
      if (inFlags & wfStencilBuffer)
         startingPass = 1;

      #if defined (WEBOS) || defined (BLACKBERRY) || defined(EMSCRIPTEN)
      // Start at 16 bits...
      startingPass = 2;
      #endif

      // No need to loop over depth
      if (!(inFlags & wfDepthBuffer))
         startingPass = 2;

      int oglLevelPasses = 1;

      #if !defined(NME_FORCE_GLES1) && (defined(WEBOS) || defined(BLACKBERRY) || defined(EMSCRIPTEN))
      // Try 2 then 1 ?
      if ( (inFlags & wfAllowShaders) && !(inFlags & wfRequireShaders) )
         oglLevelPasses = 2;
      #endif

      // Find config...

      for(int oglPass = 0; oglPass< oglLevelPasses && !is_opengl; oglPass++)
      {
         #ifdef NME_FORCE_GLES1
         int level = 1;
         #else
         int level = (inFlags & wfRequireShaders) ? 2 : (inFlags & wfAllowShaders) ? 2-oglPass : 1;
         #endif

         for(int depthPass=startingPass;depthPass<3 && !is_opengl;depthPass++)
         {
            // Initialize the display
            for(int aa_pass = aa_tries; aa_pass>=0 && !is_opengl; --aa_pass)
            {
               SDL_GL_SetAttribute(SDL_GL_RED_SIZE,  8 );
               SDL_GL_SetAttribute(SDL_GL_GREEN_SIZE,8 );
               SDL_GL_SetAttribute(SDL_GL_BLUE_SIZE, 8 );

               #if defined(WEBOS) || defined(BLACKBERRY) || defined(EMSCRIPTEN)
               SDL_GL_SetAttribute(SDL_GL_CONTEXT_MAJOR_VERSION, level);
               #endif
               // try 32 24 or 16 bit depth...
               if (inFlags & wfDepthBuffer)
                  SDL_GL_SetAttribute(SDL_GL_DEPTH_SIZE,  32 - depthPass*8 );

               if (inFlags & wfStencilBuffer)
                  SDL_GL_SetAttribute(SDL_GL_STENCIL_SIZE, 8 );

               SDL_GL_SetAttribute(SDL_GL_DOUBLEBUFFER, 1);

               if (aa_tries > 0)
               {
                  SDL_GL_SetAttribute(SDL_GL_MULTISAMPLEBUFFERS, aa_pass>0);
                  SDL_GL_SetAttribute(SDL_GL_MULTISAMPLESAMPLES,  1<<aa_pass );
               }

               #ifndef EMSCRIPTEN
               if ( inFlags & wfVSync )
               {
                  SDL_GL_SetAttribute(SDL_GL_SWAP_CONTROL, 1);
               }
               #endif

               sdl_flags |= SDL_OPENGL;

               //if (!(screen = SDL_SetVideoMode( use_w, use_h, 32, sdl_flags)))
               if (!(screen = SDL_CreateWindow(inTitle, SDL_WINDOWPOS_UNDEFINED, SDL_WINDOWPOS_UNDEFINED, use_w, use_h, sdl_flags)))
               {
                  if (depthPass==2 && aa_pass==0 && oglPass==oglLevelPasses-1)
                  {
                     sdl_flags &= ~SDL_OPENGL;
                     fprintf(stderr, "Couldn't set OpenGL mode32: %s\n", SDL_GetError());
                  }
               }
               else
               {
                  is_opengl = true;
                  #if defined(WEBOS) || defined(BLACKBERRY) || defined(EMSCRIPTEN)
                  sgIsOGL2 = level==2;
                  #else
                  // TODO: check extensions support
                  sgIsOGL2 = (inFlags & (wfAllowShaders | wfRequireShaders) );
                  #endif
                  break;
               }
            }
         }
      }
   }

   if (!screen)
   {
      if (!opengl || !nmeEgl)
         sdl_flags |= SDL_DOUBLEBUF;

      //screen = SDL_SetVideoMode( use_w, use_h, 32, sdl_flags );
      screen = SDL_CreateWindow(inTitle, SDL_WINDOWPOS_UNDEFINED, SDL_WINDOWPOS_UNDEFINED, use_w, use_h, sdl_flags);
      if (!screen)
      {
         fprintf(stderr, "Couldn't set video mode: %s\n", SDL_GetError());
         inOnFrame(0);
         gSDLIsInit = false;
         return;
      }
   }

   #ifdef RASPBERRYPI
   if (opengl)
   {
      sgIsOGL2 = (inFlags & (wfAllowShaders | wfRequireShaders) );

      use_w = screen->w;
      use_h = screen->h;
      bool ok = nmeEGLCreate( 0, use_w, use_h,
                        sgIsOGL2,
                        (inFlags & wfDepthBuffer) ? 16 : 0,
                        (inFlags & wfStencilBuffer) ? 8 : 0,
                        0 );
      if (ok)
         is_opengl = true;
   }
   #endif

   HintColourOrder( is_opengl || screen->format->Rmask==0xff );
*/

   int numJoysticks = SDL_NumJoysticks();

   if (sgJoystickEnabled && numJoysticks > 0)
   {
      for (int i = 0; i < numJoysticks; i++)
      {
         sgJoystick = SDL_JoystickOpen(i);
      }
      SDL_JoystickEventState(SDL_TRUE);
   }

   int width, height;
   if (windowFlags & SDL_WINDOW_FULLSCREEN || windowFlags & SDL_WINDOW_FULLSCREEN_DESKTOP)
   {
      //SDL_DisplayMode mode;
      //SDL_GetCurrentDisplayMode(0, &mode);
      //width = mode.w;
      //height = mode.h;
      width = sgDesktopWidth;
      height = sgDesktopHeight;
   }
   else
   {
      SDL_GetWindowSize(window, &width, &height);
   }

   sgSDLFrame = new SDLFrame(window, renderer, windowFlags, opengl, width, height);
   inOnFrame(sgSDLFrame);
   StartAnimation();
}

bool sgDead = false;

void SetIcon(const char *path)
{

}

QuickVec<int>* CapabilitiesGetScreenResolutions()
{
   InitSDL();
   QuickVec<int> *out = new QuickVec<int>();

   int numModes = SDL_GetNumDisplayModes(0);
   SDL_DisplayMode mode;

   for (int i = 0; i < numModes; i++)
   {
      SDL_GetDisplayMode(0, i, &mode);
      out->push_back(mode.w);
      out->push_back(mode.h);
   }

   return out;
}

double CapabilitiesGetScreenResolutionX()
{
   InitSDL();
   return sgDesktopWidth;
}

double CapabilitiesGetScreenResolutionY()
{
   InitSDL();
   return sgDesktopHeight;
}

void PauseAnimation() {}
void ResumeAnimation() {}

void StopAnimation()
{
   #ifdef NME_MIXER
   if (gSDLAudioState==sdaOpen)
   {
      gSDLAudioState = sdaClosed;
      Mix_CloseAudio();
   }
   #endif
   sgDead = true;
}

static SDL_TimerID sgTimerID = 0;
bool sgTimerActive = false;

Uint32 OnTimer(Uint32 interval, void *)
{
   // Ping off an event - any event will force the frame check.
   SDL_Event event;
   SDL_UserEvent userevent;
   /* In this example, our callback pushes an SDL_USEREVENT event
   into the queue, and causes ourself to be called again at the
   same interval: */
   userevent.type = SDL_USEREVENT;
   userevent.code = 0;
   userevent.data1 = NULL;
   userevent.data2 = NULL;
   event.type = SDL_USEREVENT;
   event.user = userevent;
   sgTimerActive = false;
   sgTimerID = 0;
   SDL_PushEvent(&event);
   return 0;
}

#ifndef SDL_NOEVENT
#define SDL_NOEVENT -1;
#endif

void StartAnimation()
{
   SDL_Event event;
   bool firstTime = true;
   while(!sgDead)
   {
      event.type = SDL_NOEVENT;
      while (!sgDead && (firstTime || SDL_WaitEvent(&event)))
      {
         firstTime = false;
         if (sgTimerActive && sgTimerID)
         {
            SDL_RemoveTimer(sgTimerID);
            sgTimerActive = false;
            sgTimerID = 0;
         }

         ProcessEvent(event);
         if (sgDead) break;
         event.type = SDL_NOEVENT;

         while (SDL_PollEvent(&event))
         {
            ProcessEvent (event);
            if (sgDead) break;
            event.type = -1;
         }

         Event poll(etPoll);
         sgSDLFrame->ProcessEvent(poll);

         if (sgDead) break;

         double next = sgSDLFrame->GetStage()->GetNextWake() - GetTimeStamp();

         if (next > 0.001)
         {
            int snooze = next*1000.0;
            sgTimerActive = true;
            sgTimerID = SDL_AddTimer(snooze, OnTimer, 0);
         }
         else
         {
            OnTimer(0, 0);
         }
      }
   }

   Event deactivate(etDeactivate);
   sgSDLFrame->ProcessEvent(deactivate);

   Event kill(etDestroyHandler);
   sgSDLFrame->ProcessEvent(kill);
   SDL_Quit();
}

}


text:
import QSlideItem from './QSlideItem.js'

export {
  QSlideItem
}

redpajama_set_name: RedPajamaGithub


text:
OSVR Core System

Maintained at https://github.com/OSVR/OSVR-Core

For details, see http://osvr.github.io

For support, see http://support.osvr.com

This is the code and libraries to use when developing with OSVR.

For developing plugins, you’ll use the @ref PluginKit library.

For developing applications using the framework, you’ll use the @ref ClientKit library.

Binary Snapshot Documentation

If you’re looking at this file in a binary build of OSVR-Core, please seen the BINARY_README file for more targeted information, as this main README file is focused on the source tree.

Source Documentation

See the HACKING file for some development guidelines for working on this code base itself.

If you’re looking at the source tree, not a binary snapshot, you may be interested in build docs. You may also be interested in binary snapshots at http://osvr.github.io .

License and Vendored Projects

This project: Licensed under the Apache License, Version 2.0.

/cmake - Git subtree from https://github.com/rpavlik/cmake-modules used at compile-time only. Primarily BSL 1.0, some items under the license used by CMake (BSD-style)

/vendor/com_smart_pointer - Header (for integrating boost::intrusive_ptr with MS COM) extracted from the following project and file: https://github.com/rengeln/nyx/blob/master/src/Prefix.h, modified as needed for compatibility. MIT license.

/vendor/discount-windows-bins - Submodule containing source, build script, and Windows binaries for the “Discount” Markdown processor, used only during the build process on Windows. Upstream at https://github.com/Orc/discount. 3-clause BSD license.

/vendor/eigen-3.2.7 - Unpacked release from http://eigen.tuxfamily.org/ - header-only library under the MPL2 (a file-level copyleft, compatible with proprietary software), define EIGEN_MPL2_ONLY to exclude modules with other license from the build (done in OSVR-Core build system).

/vendor/FloatExceptions - Code for development use only, usage should not be committed or merged into master. MIT licensed.

/vendor/gtest-1.7.0 - Unpacked source from https://code.google.com/p/googletest/ - 3-clause BSD license. Used only for building/running tests.

/vendor/jenkins-ctest-plugin - Git submodule from https://github.com/rpavlik/jenkins-ctest-plugin, used only for building/running tests and CI. MIT license.

/vendor/libcxx-backports - C++11/14 standard library functionality backported into headers using the implementations from the libc++ project at http://libcxx.llvm.org/. Dual licensed under the MIT and the “BSD-like” UIUC license.

/vendor/UIforETWbins - Distributed binary releases of UIforETW https://github.com/google/UIforETW extracted to a Git repo (submodule) unmodified. Apache License, Version 2.0.

/vendor/util-headers - subset of headers installed from https://github.com/rpavlik/util-headers. BSL 1.0.

/vendor/vrpn - Git submodule, accessed from https://github.com/vrpn/vrpn. BSL 1.0. Contains optional recursive submodules HIDAPI and libjsoncpp.


text:
package org.nick.wwwjdic.widgets;

import java.util.List;

import org.nick.wwwjdic.BuildConfig;
import org.nick.wwwjdic.KanjiEntryDetail;
import org.nick.wwwjdic.R;
import org.nick.wwwjdic.WwwjdicPreferences;
import org.nick.wwwjdic.model.KanjiEntry;

import android.annotation.TargetApi;
import android.app.AlarmManager;
import android.app.PendingIntent;
import android.appwidget.AppWidgetManager;
import android.appwidget.AppWidgetProvider;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Build;
import android.os.Bundle;
import android.util.Log;
import android.util.TypedValue;
import android.view.View;
import android.widget.RemoteViews;

import androidx.core.content.ContextCompat;

public class KodWidgetProvider extends AppWidgetProvider {

    private static final String TAG = KodWidgetProvider.class.getSimpleName();

    @Override
    public void onUpdate(Context context, AppWidgetManager appWidgetManager,
                         int[] appWidgetIds) {
        if (BuildConfig.DEBUG) {
            Log.d(TAG, "KOD widget udpate");
        }

        ContextCompat.startForegroundService(context, new Intent(context, GetKanjiService.class));
    }

    @SuppressWarnings("deprecation")
    @Override
    public void onReceive(Context context, Intent intent) {
        Log.d(TAG, "onReceive: " + intent);
        // v1.5 fix that doesn't call onDelete Action
        final String action = intent.getAction();
        if (BuildConfig.DEBUG) {
            Log.d(TAG, "KOD widget onReceive: " + action);
        }
        if (AppWidgetManager.ACTION_APPWIDGET_DELETED.equals(action)) {
            final int appWidgetId = intent.getExtras().getInt(
                    AppWidgetManager.EXTRA_APPWIDGET_ID,
                    AppWidgetManager.INVALID_APPWIDGET_ID);
            if (appWidgetId != AppWidgetManager.INVALID_APPWIDGET_ID) {
                this.onDeleted(context, new int[]{appWidgetId});
            }
        } else if (ConnectivityManager.CONNECTIVITY_ACTION.equals(action)) {
            Bundle extras = intent.getExtras();
            // only on IS04 2.2.2?
            if (extras == null) {
                return;
            }
            boolean noConnectivity = extras.getBoolean(
                    ConnectivityManager.EXTRA_NO_CONNECTIVITY, false);
            Log.d(TAG, "CONNECTIVITY_ACTION::noConnectivity : "
                    + noConnectivity);
            if (noConnectivity) {
                return;
            }

            NetworkInfo ni = extras.getParcelable(ConnectivityManager.EXTRA_NETWORK_INFO);
            if (ni !=null && ni.isConnected()) {
                if (BuildConfig.DEBUG) {
                    Log.d(TAG, ni.getTypeName() + " is connecting");
                }
                if (WwwjdicPreferences.getLastKodUpdateError(context) != 0) {
                    if (BuildConfig.DEBUG) {
                        Log.d(TAG,
                                "KOD widget is in error state, trying to update...");
                    }
                    ContextCompat.startForegroundService(context,
                            new Intent(context, GetKanjiService.class));
                }
            }
        } else {
            super.onReceive(context, intent);
        }
    }

    @Override
    public void onDeleted(Context context, int[] appWidgetIds) {
        if (BuildConfig.DEBUG) {
            Log.d(TAG, "onDeleted");
        }

        AppWidgetManager manager = AppWidgetManager.getInstance(context);
        ComponentName thisWidget = new ComponentName(context,
                KodWidgetProvider.class);
        int[] thisWidgetIds = manager.getAppWidgetIds(thisWidget);
        if (BuildConfig.DEBUG) {
            Log.d(TAG, "widget IDs: " + thisWidgetIds.length);
        }

        if (thisWidgetIds.length == 0) {
            if (BuildConfig.DEBUG) {
                Log.d(TAG, "we are the last widget, cleaning up");

                Log.d(TAG, "stopping update service...");
            }
            boolean stopped = context.stopService(new Intent(context,
                    GetKanjiService.class));
            if (BuildConfig.DEBUG) {
                Log.d(TAG, "stopped: " + stopped);

                Log.d(TAG, "cancelling update timer...");
            }
            AlarmManager alarmManager = (AlarmManager) context
                    .getSystemService(Context.ALARM_SERVICE);
            Intent updateIntent = new Intent(context, GetKanjiService.class);
            PendingIntent pendingIntent = PendingIntent.getService(context, 0,
                    updateIntent, 0);
            alarmManager.cancel(pendingIntent);

            ConnectivityMonitor.stop(context);
        }
    }

    @Override
    public void onAppWidgetOptionsChanged(Context context,
                                          AppWidgetManager appWidgetManager, int appWidgetId,
                                          Bundle newOptions) {
        if (BuildConfig.DEBUG) {
            Log.d(TAG, "onAppWidgetOptionsChanged " + appWidgetId);
            Log.d(TAG, "newOptions: " + newOptions);
        }
        for (String key : newOptions.keySet()) {
            Log.d(TAG, key + "=" + newOptions.get(key));
        }

        RemoteViews views = null;
        boolean showReadingAndMeaning = WwwjdicPreferences
                .isKodShowReading(context);
        views = currentRemoveViews(context, showReadingAndMeaning);

        float textSize = getKodTextSize(context, newOptions, appWidgetId,
                showReadingAndMeaning);
        float detailsTextSize = getDetailsTextSize(context, newOptions,
                appWidgetId);
        if (BuildConfig.DEBUG) {
            Log.d(TAG, "text size: " + textSize + "sp");
            Log.d(TAG, "details text size: " + detailsTextSize + "sp");
        }

        setTextSizes(views, textSize, detailsTextSize, showReadingAndMeaning);

        appWidgetManager.updateAppWidget(appWidgetId, views);
    }

    static RemoteViews currentRemoveViews(Context context,
                                          boolean showReadingAndMeaning) {
        boolean transparent = WwwjdicPreferences.isKodTransparentBg(context);

        if (showReadingAndMeaning) {
            return new RemoteViews(context.getPackageName(),
                    transparent ? R.layout.kod_widget_details_transparent
                            : R.layout.kod_widget_details);
        }

        return new RemoteViews(context.getPackageName(),
                transparent ? R.layout.kod_widget_transparent
                        : R.layout.kod_widget);
    }

    static float getKodTextSize(Context ctx, Bundle options, int id,
                                boolean showMeaning) {
        float ratio = showMeaning ? getDetailedKodTextSizeRatio(ctx)
                : getKodTextSizeRatio(ctx);

        return getTextSize(ctx, options, id, ratio);
    }

    private static float getDetailedKodTextSizeRatio(Context ctx) {
        int ratio = ctx.getResources().getInteger(
                R.integer.kod_detailed_text_size_ratio);

        return ratio / 100.0f;
    }

    private static float getKodTextSizeRatio(Context ctx) {
        int ratio = ctx.getResources()
                .getInteger(R.integer.kod_text_size_ratio);

        return ratio / 100.0f;
    }

    static float getDetailsTextSize(Context ctx, Bundle options, int id) {
        return getTextSize(ctx, options, id, getKodDetailsTextSizeRatio(ctx));
    }

    private static float getKodDetailsTextSizeRatio(Context ctx) {
        int ratio = ctx.getResources().getInteger(
                R.integer.kod_details_text_size_ratio);

        return ratio / 100.0f;
    }

    @TargetApi(Build.VERSION_CODES.JELLY_BEAN)
    static float getTextSize(Context ctx, Bundle options, int id, float scale) {
        AppWidgetManager widgetManager = AppWidgetManager.getInstance(ctx);
        if (options == null) {
            options = widgetManager.getAppWidgetOptions(id);
        }

        if (options != null) {
            int appWidgetMaxWidth = options
                    .getInt(AppWidgetManager.OPTION_APPWIDGET_MAX_WIDTH);
            int appWidgetMaxHeight = options
                    .getInt(AppWidgetManager.OPTION_APPWIDGET_MAX_HEIGHT);
            float candidateHeight = (float) (scale * appWidgetMaxHeight);
            float candidateWidth = (float) (scale * appWidgetMaxWidth);

            return Math.min(candidateHeight, candidateWidth);
        }

        return 1;
    }

    @TargetApi(Build.VERSION_CODES.JELLY_BEAN)
    static void setTextSizes(RemoteViews views,
                             float textSize, float detailsTextSize,
                             boolean showReadingAndMeaning) {
        if (textSize == 0 || detailsTextSize == 0) {
            return;
        }

        views.setTextViewTextSize(R.id.kod_text, TypedValue.COMPLEX_UNIT_SP,
                textSize);
        views.setTextViewTextSize(R.id.kod_header_text,
                TypedValue.COMPLEX_UNIT_SP, detailsTextSize);
        if (showReadingAndMeaning) {
            views.setTextViewTextSize(R.id.kod_reading,
                    TypedValue.COMPLEX_UNIT_SP, detailsTextSize);
            views.setTextViewTextSize(R.id.kod_meaning,
                    TypedValue.COMPLEX_UNIT_SP, detailsTextSize);
        }
    }

    protected static void setKodWidgetTextSizes(Context context,
                                                RemoteViews views, int widgetId,
                                                boolean showReadingAndMeaning) {
        float textSize = getKodTextSize(context, null, widgetId,
                showReadingAndMeaning);
        float detailsTextSize = getDetailsTextSize(context, null, widgetId);
        if (BuildConfig.DEBUG) {
            Log.d(TAG, "text size: " + textSize + "sp");
            Log.d(TAG, "details text size: " + detailsTextSize + "sp");
        }
        if (textSize > 0 && detailsTextSize > 0) {
            setTextSizes(views, textSize, detailsTextSize, showReadingAndMeaning);
        }
    }

    public static void showError(Context context, RemoteViews views) {
        views.setViewVisibility(R.id.kod_message_text, View.VISIBLE);
        views.setTextViewText(R.id.kod_message_text, context.getResources()
                .getString(R.string.error));
        views.setViewVisibility(R.id.widget, View.GONE);

        Intent updateIntent = new Intent(context, GetKanjiService.class);
        PendingIntent pendingIntent = PendingIntent.getService(context, 0,
                updateIntent, PendingIntent.FLAG_UPDATE_CURRENT);
        views.setOnClickPendingIntent(R.id.kod_message_text, pendingIntent);
    }

    public static void showLoading(Context context, RemoteViews views) {
        views.setTextViewText(R.id.kod_message_text, context.getResources()
                .getString(R.string.widget_loading));
        views.setViewVisibility(R.id.kod_message_text, View.VISIBLE);
        views.setViewVisibility(R.id.widget, View.GONE);
    }

    public static void clearLoading(RemoteViews views) {
        views.setViewVisibility(R.id.kod_message_text, View.GONE);
        views.setViewVisibility(R.id.widget, View.VISIBLE);
    }

    public static void showKanji(Context context, RemoteViews views,
                                 boolean showReadingAndMeaning, List<KanjiEntry> entries,
                                 int widgetId) {
        KanjiEntry entry = entries.get(0);
        String kod = entry.getHeadword();
        if (BuildConfig.DEBUG) {
            Log.d(TAG, "KOD: " + kod);
        }
        Intent intent = new Intent(context, KanjiEntryDetail.class);
        intent.putExtra(KanjiEntryDetail.EXTRA_KANJI_ENTRY, entries.get(0));
        intent.putExtra(KanjiEntryDetail.EXTRA_KOD_WIDGET_CLICK, true);
        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK
                | Intent.FLAG_ACTIVITY_CLEAR_TOP);
        PendingIntent pendingIntent = PendingIntent.getActivity(context, 0,
                intent, PendingIntent.FLAG_UPDATE_CURRENT);

        views.setTextViewText(R.id.kod_text, kod);
        if (showReadingAndMeaning) {
            views.setTextViewText(R.id.kod_reading, entry.getReading());
            views.setTextViewText(R.id.kod_meaning, entry.getMeaningsAsString());
        }
        setKodWidgetTextSizes(context, views, widgetId, showReadingAndMeaning);

        views.setOnClickPendingIntent(R.id.widget, pendingIntent);
        KodWidgetProvider.clearLoading(views);
    }
}


text:
Plugin.define "GoServe" do
author "Brendan Coles <bcoles@gmail.com>" # 2011-05-31
version "0.2"
description "GoServe - A Web and Gopher Server for OS/2. SRE-http is a highly configurable http server which requires GoServe"
website "http://www2.hursley.ibm.com/goserve"

# More Info #
# SRE-http is a highly configurable http/1.1 web server for OS/2. To use the SRE-http web server, you will need GoServe (a free, IBM EWS, OS/2 Internet server). - Homepage: http://www.srehttp.org/server/
# ShodanHQ results as at 2011-05-31 #
# 32 for GoServe
# 14 for GoServe -OS

matches [
	# HTTP Server Header
	{ :regexp=>/^GoServe/, :search=>"headers[server]" },

	# Version Detection
	{ :version=>/^GoServe\/([^\s]+)$/, :search=>"headers[server]" },

	# Version Detection
	{ :version=>/^GoServe for OS\/2, version ([^\s^;]+); SRE-http [\d\.]+$/, :search=>"headers[server]" },

	# Module Detection
	{ :module=>/^GoServe for OS\/2, version [^\s^;]+; (SRE-http [\d\.]+)$/, :search=>"headers[server]" },
]

end


text:
<!DOCTYPE html>

    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">

    <meta name="description" content="Documentation for peano">

    <meta name="author" content="Chris MacMackin" >
    <link rel="icon" href="../favicon.png">

    <title>kdtree – peano </title>

    <link href="../css/bootstrap.min.css" rel="stylesheet">
    <link href="../css/pygments.css" rel="stylesheet">
    <link href="../css/font-awesome.min.css" rel="stylesheet">
    <link href="../css/local.css" rel="stylesheet">

    <link  href="../tipuesearch/tipuesearch.css" rel="stylesheet">

          <button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#navbar" aria-expanded="false" aria-controls="navbar">
            Toggle navigation

          </button>
          peano

Source Files

Modules

Procedures

Derived Types

        <form action="../search.html" class="navbar-form navbar-right" role="search">

          <input type="text" class="form-control" placeholder="Search" name="q" id="tipue_search_input" autocomplete="off" required>

        </form>

kdtree
    Derived Type

 Source File

kdtree.f90

kd_tree

kdtree

Variables

      set

      root

      dim

      num

All Derived Types

      kdbox

      kdnode

      kdtree

Represents the kdtree itself

Components

Type	Visibility

Attributes		Name		Initial

  real,

  public,
  pointer	::
  set(:,:)	=> 	null()
The input (sorted, row-major) data set associated with this kd tree

  type(kdnode),

  public,
  pointer	::
  root	=> 	null()
The root node of the kd tree

  integer,

  public
  	::
  dim	 =	0
The rank of the data set's domain

  integer,

  public
  	::
  num	 =	0
The rank of the data set's range

© 2015 peano was written by Vincent San Miguel.

Documentation generated by FORD.


text:
using Esri.ArcGISRuntime.Controls;
using Esri.ArcGISRuntime.Data;
using Esri.ArcGISRuntime.Layers;
using Esri.ArcGISRuntime.Security;
using System;
using System.Globalization;
using System.Linq;
using Windows.UI.Popups;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;

namespace ArcGISRuntime.Samples.Store.Samples
{
	/// <summary>
	/// Demonstrates how editing of features can be restricted by ownership-based access defined in the service.
	/// </summary>
	/// <title>Ownership-based Editing</title>
	/// <category>Editing</category>
	public partial class OwnershipBasedEditing : Page
	{
		public OwnershipBasedEditing()
		{
			InitializeComponent();
		}

		/// <summary>
		/// Removes credential used to access the service and adds a new instance of layer to trigger another challenge.
		/// </summary>
		private void SignOut()
		{
			AddButton.IsEnabled = false;
			var layer = MyMapView.Map.Layers["Marine"] as FeatureLayer;
			if (layer == null) return;
			var table = (ServiceFeatureTable)layer.FeatureTable;
			var credential = IdentityManager.Current.FindCredential(table.ServiceUri);
			if (credential != null)
			{
				IdentityManager.Current.RemoveCredential(credential);
				MyMapView.Map.Layers.Remove(layer);
				MyMapView.Map.Layers.Add(new FeatureLayer(new Uri(table.ServiceUri)) { ID = layer.ID });
			}
		}

		/// <summary>
		/// Signs out from current login so sample can trigger credential challenge.
		/// </summary>
		private void SignOutButton_Click(object sender, RoutedEventArgs e)
		{
			SignOut();
		}

		/// <summary>
		/// Updates login information based on credential.
		/// </summary>
		private void MyMapView_LayerLoaded(object sender, LayerLoadedEventArgs e)
		{
			if (e.LoadError != null || !(e.Layer is FeatureLayer))
				return;
			var layer = (FeatureLayer)e.Layer;
			var table = (ServiceFeatureTable)layer.FeatureTable;
			if (table.ServiceInfo != null)
			{
				AddButton.IsEnabled = true;
				var credential = IdentityManager.Current.FindCredential(table.ServiceUri);
				if (credential is TokenCredential)
					LoginInfo.Text = string.Format("Login '{0}' service as: {1}", table.ServiceInfo.Name, ((TokenCredential)credential).UserName);
			}
		}

		/// <summary>
		/// Signs out from current login so switching samples can trigger credential challenge.
		/// </summary>
		private void MyMapView_LayerUnloaded(object sender, LayerUnloadedEventArgs e)
		{
			if (!(e.Layer is FeatureLayer))
				return;
			SignOut();
		}

		/// <summary>
		/// Selects feature and checks whether update or delete is allowed.
		/// </summary>
		private async void MyMapView_MapViewTapped(object sender, MapViewInputEventArgs e)
		{
			// Ignore tap events while in edit mode so we do not interfere with add point.
			if (MyMapView.Editor.IsActive)
				return;
			var layer = MyMapView.Map.Layers["Marine"] as FeatureLayer;
			var table = (ArcGISFeatureTable)layer.FeatureTable;
			layer.ClearSelection();

			// Service metadata includes edit fields which can be used
			// to check ownership and/or tracking the last edit made.
			if (table.ServiceInfo == null || table.ServiceInfo.EditFieldsInfo == null)
				return;
			var creatorField = table.ServiceInfo.EditFieldsInfo.CreatorField;
			if (string.IsNullOrWhiteSpace(creatorField))
				return;

			string message = null;
			try
			{
				// Performs hit test on layer to select feature.
				var features = await layer.HitTestAsync(MyMapView, e.Position);
				if (features == null || !features.Any())
					return;
				var featureID = features.FirstOrDefault();
				layer.SelectFeatures(new long[] { featureID });
				var feature = (GeodatabaseFeature)await layer.FeatureTable.QueryAsync(featureID);

				// Displays feature attributes and editing restrictions.
				if (feature.Attributes.ContainsKey(table.ObjectIDField))
					message += string.Format("[{0}] : {1}\n", table.ObjectIDField, feature.Attributes[table.ObjectIDField]);
				if (feature.Attributes.ContainsKey(creatorField))
					message += string.Format("[{0}] : {1}\n", creatorField, feature.Attributes[creatorField]);
				// Checks whether service allows current user to add/update/delete attachment of feature.
				message += string.Format("Attachments\n\tCanAdd - {0}\n\tCanUpdate - {1}\n\tCanDelete - {2}\n",
					table.CanAddAttachment(feature), table.CanUpdateAttachment(feature), table.CanDeleteAttachment(feature));
				// Checks whether service allows current user to update feature's geometry or attributes; and delete feature.
				message += string.Format("Feature\n\tCanUpdateGeometry - {0}\n\tCanUpdate - {1}\n\tCanDelete - {2}\n",
					table.CanUpdateGeometry(feature), table.CanUpdateFeature(feature), table.CanDeleteFeature(feature));
			}
			catch (Exception ex)
			{
				message = ex.Message;
			}
			if (!string.IsNullOrWhiteSpace(message))
				await new MessageDialog(message).ShowAsync();
		}

		/// <summary>
		/// Adds a new turtle feature owned by current user.
		/// </summary>
		private async void AddButton_Click(object sender, RoutedEventArgs e)
		{
			var layer = MyMapView.Map.Layers["Marine"] as FeatureLayer;
			var table = (ArcGISFeatureTable)layer.FeatureTable;
			var typeID = (Int32)((Button)sender).Tag;
			string message = null;
			try
			{
				var mapPoint = await MyMapView.Editor.RequestPointAsync();
				var feature = new GeodatabaseFeature(table.Schema) { Geometry = mapPoint };
				if (table.ServiceInfo.Types == null)
					return;
				var featureType = table.ServiceInfo.Types.FirstOrDefault(t => Int32.Equals(Convert.ToInt32(t.ID, CultureInfo.InvariantCulture), typeID));
				if (featureType == null)
					return;
				var template = featureType.Templates.FirstOrDefault();
				if (template == null || template.Prototype == null || template.Prototype.Attributes == null)
					return;
				foreach (var item in template.Prototype.Attributes)
					feature.Attributes[item.Key] = item.Value;
				if (table.CanAddFeature(feature))
					await table.AddAsync(feature);
				if (table.HasEdits)
				{
					if (table is ServiceFeatureTable)
					{
						var serviceTable = (ServiceFeatureTable)table;
						// Pushes new feature back to the server.
						var result = await serviceTable.ApplyEditsAsync();
						if (result.AddResults == null || result.AddResults.Count < 1)
							return;
						var addResult = result.AddResults[0];
						if (addResult.Error != null)
							message = addResult.Error.Message;
					}
				}
			}
			catch (Exception ex)
			{
				message = ex.Message;
			}
			if (!string.IsNullOrWhiteSpace(message))
				await new MessageDialog(message).ShowAsync();
		}

		private void SignInButton_Click(object sender, RoutedEventArgs e)
		{
			// Add layer to map to trigger request for credentials.
			AddButton.IsEnabled = false;
			var layer = MyMapView.Map.Layers["Marine"] as FeatureLayer;
			if (layer == null) return;
			var table = (ServiceFeatureTable)layer.FeatureTable;
			MyMapView.Map.Layers.Remove(layer);
			MyMapView.Map.Layers.Add(new FeatureLayer(new Uri(table.ServiceUri)) { ID = layer.ID });

		}
	}
}


text:
'use strict';

require('../../../lib/common/init');

var assert = require('assert'),
    request = require('supertest'),
    danf = require('../../../lib/server/app')(require('../../fixture/http/danf'), null, {environment: 'test', verbosity: 0, cluster: null})
;

danf.buildServer(function(app) {
    describe('SessionHandler', function() {
        it('should allow to get and set cookies', function(done) {
            request(app)
                .get('/cookie')
                .expect(204)
                .end(function(err, res) {
                    if (err) {
                        if (res) {
                            console.log(res.text);
                        } else {
                            console.log(err);
                        }

                        throw err;
                    }

                    done();
                })
            ;
        })
    })
});


text:
enum {
SPORTH_FLOAT,
SPORTH_STRING,
SPORTH_IGNORE,
SPORTH_FUNC,
SPORTH_NOTOK,
SPORTH_OK,
SPORTH_WORD
};

#define SPORTH_FOFFSET 2
#define SPORTH_MAXCHAR 200
#define SPORTH_STACK_SIZE 32

typedef struct {
    float fval;
    char *sval;
    int type;
} sporth_stack_val;

typedef struct {
    int pos;
    uint32_t error;
    sporth_stack_val stack[SPORTH_STACK_SIZE];
} sporth_stack;

typedef struct sporth_entry {
    uint32_t val;
    char *key;
    struct sporth_entry *next;
} sporth_entry;

typedef struct {
    uint32_t count;
    sporth_entry root;
    sporth_entry *last;
} sporth_list ;

typedef struct {
    sporth_list list[256];
} sporth_htable;

typedef struct {
    const char *name;
    int (*func)(sporth_stack *, void *);
    void *ud;
} sporth_func;

typedef struct sporth_data {
    sporth_htable dict;
    uint32_t nfunc;
    sporth_func *flist;
    sporth_stack stack;
} sporth_data;

uint32_t sporth_hash(const char *str);
int sporth_search(sporth_htable *ht, const char *key, uint32_t *val);
int sporth_htable_add(sporth_htable *ht, const char *key, uint32_t val);
int sporth_htable_init(sporth_htable *ht);
int sporth_htable_destroy(sporth_htable *ht);

int sporth_stack_init(sporth_stack *stack);
int sporth_stack_push_float(sporth_stack *stack, float val);
int sporth_stack_push_string(sporth_stack *stack, char **str);
float sporth_stack_pop_float(sporth_stack *stack);
const char * sporth_stack_pop_string(sporth_stack *stack);
int sporth_check_args(sporth_stack *stack, const char *args);
int sporth_register_func(sporth_data *sporth, sporth_func *flist);
int sporth_exec(sporth_data *sporth, const char *keyword);
int sporth_init(sporth_data *sporth);
int sporth_destroy(sporth_data *sporth);

int sporth_gettype(sporth_data *sporth, char *str, int mode);
int sporth_parse(sporth_data *sporth, const char *filename);
char * sporth_tokenizer(const char *str,
        uint32_t size, uint32_t *pos);
int sporth_lexer(char *str, int32_t size);
sporth_stack_val * sporth_stack_get_last(sporth_stack *stack);

size_t sporth_getline(char **lineptr, size_t *n, FILE *stream);

void sporth_print(sporth_data *sporth, const char *fmt, ...);


text:
/**
 * Created by Shawn Liu on 15-5-22.
 */
var SeleniumHunInstance = require("./lib/SeleniumHubInstance");
var seleniumInstance = new SeleniumHunInstance();
var config = require("config").seleniumHub;
var Promise = require("bluebird");

exports.start = function () {
    return seleniumInstance.start(config.port)
        .then(function () {
            return Promise.map(config.phantom, function (port) {
                return seleniumInstance.registerNode(port, "phantomjs")
            })
        })
        .then(function () {
            return Promise.map(config.chrome, function (port) {
                return seleniumInstance.registerNode(port, "chrome");
            })
        })
        .then(function () {
            return seleniumInstance;
        })
}

exports.get = function () {
    return seleniumInstance;
}


text:
export default class TextElement {
  constructor(
    text          : string,
    rootContainer : IonizeContainer,
  ) {
    this.text = text;
  }

  commitUpdate(
    oldText       : string,
    newText       : string,
  ) {
    this.text = newText;
  }
}


text:
package com.amazonaws.services.elasticmapreduce.model.transform;

import java.util.Map;
import java.util.Map.Entry;

import com.amazonaws.services.elasticmapreduce.model.*;
import com.amazonaws.transform.SimpleTypeJsonUnmarshallers.*;
import com.amazonaws.transform.*;

import com.fasterxml.jackson.core.JsonToken;
import static com.fasterxml.jackson.core.JsonToken.*;

/**
 * StepDetail JSON Unmarshaller
 */
public class StepDetailJsonUnmarshaller implements
        Unmarshaller<StepDetail, JsonUnmarshallerContext> {

    public StepDetail unmarshall(JsonUnmarshallerContext context)
            throws Exception {
        StepDetail stepDetail = new StepDetail();

        int originalDepth = context.getCurrentDepth();
        String currentParentElement = context.getCurrentParentElement();
        int targetDepth = originalDepth + 1;

        JsonToken token = context.getCurrentToken();
        if (token == null)
            token = context.nextToken();
        if (token == VALUE_NULL)
            return null;

        while (true) {
            if (token == null)
                break;

            if (token == FIELD_NAME || token == START_OBJECT) {
                if (context.testExpression("StepConfig", targetDepth)) {
                    context.nextToken();
                    stepDetail.setStepConfig(StepConfigJsonUnmarshaller
                            .getInstance().unmarshall(context));
                }
                if (context
                        .testExpression("ExecutionStatusDetail", targetDepth)) {
                    context.nextToken();
                    stepDetail
                            .setExecutionStatusDetail(StepExecutionStatusDetailJsonUnmarshaller
                                    .getInstance().unmarshall(context));
                }
            } else if (token == END_ARRAY || token == END_OBJECT) {
                if (context.getLastParsedParentElement() == null
                        || context.getLastParsedParentElement().equals(
                                currentParentElement)) {
                    if (context.getCurrentDepth() <= originalDepth)
                        break;
                }
            }
            token = context.nextToken();
        }

        return stepDetail;
    }

    private static StepDetailJsonUnmarshaller instance;

    public static StepDetailJsonUnmarshaller getInstance() {
        if (instance == null)
            instance = new StepDetailJsonUnmarshaller();
        return instance;
    }
}


text:
<?php declare(strict_types=1);

namespace Smsapi\Client\Resource;

use ApiClients\Foundation\Resource\EmptyResourceInterface;

abstract class EmptyError implements ErrorInterface, EmptyResourceInterface
{
    /**
     * @return string
     */
    public function message() : string
    {
        return null;
    }

    /**
     * @return int
     */
    public function code() : int
    {
        return null;
    }
}


text:
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Google Chrome EULA</title>
<link rel="stylesheet" type="text/css" href="res://setup.exe/IDR_EULA_CSS.CSS" />

Google Chrome

        Navegue na Web com o Google Chrome
 Com o Google Chrome, o Web browser instalado no seu PC, utilizar a Internet é mais rápido, seguro e fácil.

  Para começar a utilizar o Google Chrome aceite os respectivos Termos de utilização:

  <form method="post" action="" onsubmit="checkAccept(this); return false;">

          <input type="checkbox" name="accept" id="accept" />

          Opcional: Ajude a melhorar o Google Chrome enviando automaticamente estatísticas de utilização e relatórios de falhas para a Google. Saiba mais

      <input type="submit" name="submit" value="Aceitar e instalar"  /> <input onClick="window.returnValue = 2; window.close();" type="button" name="cancel" value="Cancelar"  />

  </form>


text:
namespace search
{
ViewportSearchCallback::ViewportSearchCallback(Delegate & delegate, TOnResults onResults)
  : m_delegate(delegate)
  , m_onResults(move(onResults))
  , m_hotelsModeSet(false)
  , m_firstCall(true)
  , m_lastResultsSize(0)
{
}

void ViewportSearchCallback::operator()(Results const & results)
{
  ASSERT_LESS_OR_EQUAL(m_lastResultsSize, results.GetCount(), ());
  m_hotelsClassif.Add(results.begin() + m_lastResultsSize, results.end());
  m_lastResultsSize = results.GetCount();

  if (!m_hotelsModeSet && m_hotelsClassif.IsHotelResults())
  {
    m_delegate.SetHotelDisplacementMode();
    m_hotelsModeSet = true;
  }

  if (!results.IsEndMarker())
  {
    auto & delegate = m_delegate;
    bool const firstCall = m_firstCall;

    m_delegate.RunUITask([&delegate, firstCall, results]() {
      if (!delegate.IsViewportSearchActive())
        return;

      if (firstCall)
        delegate.ClearViewportSearchResults();

      delegate.ShowViewportSearchResults(results);
    });
  }

  if (m_onResults)
    m_onResults(results);

  m_firstCall = false;
}
}  // namespace search


text:
package org.wso2.siddhi.extension.map;

import org.wso2.siddhi.core.config.ExecutionPlanContext;
import org.wso2.siddhi.core.exception.ExecutionPlanRuntimeException;
import org.wso2.siddhi.core.executor.ExpressionExecutor;
import org.wso2.siddhi.core.executor.function.FunctionExecutor;
import org.wso2.siddhi.query.api.definition.Attribute;
import org.wso2.siddhi.query.api.exception.ExecutionPlanValidationException;

import java.util.Map;

/**
 * toXML(Map)
 * Returns the string representation of the map in XML format
 * Accept Type(s): (Map)
 * Return Type(s): String
 */
public class ToXMLFunctionExtension extends FunctionExecutor {
    private Attribute.Type returnType = Attribute.Type.STRING;

    @Override
    protected void init(ExpressionExecutor[] attributeExpressionExecutors, ExecutionPlanContext executionPlanContext) {
        if ((attributeExpressionExecutors.length) != 1) {
            throw new ExecutionPlanValidationException("Invalid no of arguments passed to map:toXML() function, " +
                    "required only 1, but found " + attributeExpressionExecutors.length);
        }
    }

    @Override
    protected Object execute(Object[] data) {
        return null;
    }

    @Override
    protected Object execute(Object data) {
        if (data instanceof Map) {
            Map<Object, Object> map = (Map<Object, Object>) data;
            return getXmlFromMap(map);
        } else {
            throw new ExecutionPlanRuntimeException("Data should be a string");
        }
    }

    private Object getXmlFromMap(Map<Object, Object> map) {
        String xmlValue = "";
        for (Map.Entry<Object, Object> mapEntry : map.entrySet()) {
            xmlValue += "<" + mapEntry.getKey().toString() + ">";
            if (mapEntry.getValue() instanceof Map) {
                xmlValue += getXmlFromMap((Map<Object, Object>) mapEntry.getValue());
            } else {
                xmlValue += mapEntry.getValue().toString();
            }
            xmlValue += "</" + mapEntry.getKey().toString() + ">";
        }
        return xmlValue;
    }

    @Override
    public void start() {
        //Nothing to start
    }

    @Override
    public void stop() {
        //Nothing to stop
    }

    @Override
    public Attribute.Type getReturnType() {
        return returnType;
    }

    @Override
    public Object[] currentState() {
        return null;    //No need to maintain a state.
    }

    @Override
    public void restoreState(Object[] state) {
        //Since there's no need to maintain a state, nothing needs to be done here.
    }
}


text:
package com.xzcen.modules.sys;

import java.util.UUID;

import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;

import com.xzcen.modules.sys.menu.entity.MenuType;
import com.xzcen.modules.sys.menu.repository.MenuManagement;

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = {"classpath*:../../main/resources/*.xml"})
public class MenuManagementTest {
	@Autowired MenuManagement menuManagement;
	MenuType menuType=new MenuType();

	@Test
	void menuTypeSave(){
		menuType.setMenuTypeName(UUID.randomUUID().toString());
		menuType.setIsSys("yes");
		menuType.setIsSysDefault("no");
		menuManagement.saveMenuType(menuType);
	}
}


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
Revis. gen. pl. (Leipzig) 3: 473 (1898)

#### Original name
Valsa aleurina Berk. & M.A. Curtis

### Remarks
null


text:
import os from 'os';
import path from 'path';

import { createWebpackDevServerDriver } from './driver/WebpackDevServerDriver';

describe('TypeScript Context Option', () => {
  it.each([
    { async: true, typescript: '~3.6.0' },
    { async: false, typescript: '~3.8.0' },
    { async: true, typescript: '~4.0.0' },
    { async: false, typescript: '~4.3.0' },
  ])('uses context and cwd to resolve project files for %p', async ({ async, typescript }) => {
    await sandbox.load(path.join(__dirname, 'fixtures/typescript-basic'));
    await sandbox.install('yarn', { typescript });
    await sandbox.patch(
      'webpack.config.js',
      '      async: false,',
      [
        `      async: ${JSON.stringify(async)},`,
        '      typescript: {',
        '        enabled: true,',
        '        configFile: path.resolve(__dirname, "build/tsconfig.json"),',
        '        context: __dirname,',
        '      },',
      ].join('\n')
    );

    // update sandbox to use context option
    await sandbox.remove('tsconfig.json');
    await sandbox.write(
      'build/tsconfig.json',
      JSON.stringify({
        compilerOptions: {
          target: 'es5',
          module: 'commonjs',
          lib: ['ES6', 'DOM'],
          moduleResolution: 'node',
          esModuleInterop: true,
          skipLibCheck: true,
          skipDefaultLibCheck: true,
          strict: true,
          baseUrl: './src',
          outDir: './dist',
        },
        include: ['./src'],
        exclude: ['node_modules'],
      })
    );
    await sandbox.patch(
      'webpack.config.js',
      "entry: './src/index.ts',",
      ["entry: './src/index.ts',", 'context: path.resolve(__dirname),'].join('\n')
    );
    await sandbox.patch(
      'webpack.config.js',
      '          transpileOnly: true,',
      [
        '          transpileOnly: true,',
        '          configFile: path.resolve(__dirname, "build/tsconfig.json"),',
        '          context: __dirname,',
      ].join('\n')
    );
    // create additional directory for cwd test
    await sandbox.write('foo/.gitignore', '');

    const driver = createWebpackDevServerDriver(
      sandbox.spawn(
        `../node_modules/.bin/webpack${
          os.platform() === 'win32' ? '.cmd' : ''
        } serve --mode=development --config=../webpack.config.js`,
        {
          cwd: path.join(sandbox.context, 'foo'),
        }
      ),
      async
    );

    // first compilation is successful
    await driver.waitForNoErrors();

    // then we introduce semantic error by removing "firstName" and "lastName" from the User model
    await sandbox.patch(
      'src/model/User.ts',
      ['  firstName?: string;', '  lastName?: string;'].join('\n'),
      ''
    );

    // we should receive 2 semantic errors
    const errors = await driver.waitForErrors();
    expect(errors).toEqual([
      [
        'ERROR in ../src/model/User.ts 11:16-25',
        "TS2339: Property 'firstName' does not exist on type 'User'.",
        '     9 |',
        '    10 | function getUserName(user: User): string {',
        "  > 11 |   return [user.firstName, user.lastName].filter((name) => name !== undefined).join(' ');",
        '       |                ^^^^^^^^^',
        '    12 | }',
        '    13 |',
        '    14 | export { User, getUserName };',
      ].join('\n'),
      [
        'ERROR in ../src/model/User.ts 11:32-40',
        "TS2339: Property 'lastName' does not exist on type 'User'.",
        '     9 |',
        '    10 | function getUserName(user: User): string {',
        "  > 11 |   return [user.firstName, user.lastName].filter((name) => name !== undefined).join(' ');",
        '       |                                ^^^^^^^^',
        '    12 | }',
        '    13 |',
        '    14 | export { User, getUserName };',
      ].join('\n'),
    ]);
  });
});


text:
// START OMIT
/***********************
 * Mission: Smallest multiple *
 ***********************
 *
 * What is the smallest positive number that is evenly divisible by all of the numbers from 1 to 20?
 *
 * Tip: 2520 is the smallest number that can be divided by each of the numbers from 1 to 10 without any remainder.
 *
 *
 */
package main

import (
  "fmt"
  "math"
)

func main() {
      divisorMax := 20
      math.Log(0)
      //implement generatePrimes
      p := generatePrimes(divisorMax)
      result := float64(1)

      // EDITABLE OMIT
      for i := 0; i < len(p); i++ {
        // Your code here
        // use math.Log &  math.Pow
      }

      fmt.Println(int64(result))
}

func generatePrimes(upperLimit int) (primes []int) {
  // Your code here
  return primes
}
// UNEDITABLE OMIT

// END OMIT


text:
<link rel="import" href="bower_components/polymer/polymer.html">

<dom-module id="simple-gallery" >

  <template>

 <button type="button" class="close" aria-hidden="true" on-click="close" >X</button>

                      <button id="previous" type="button" class="btn btn-default pull-left prev" on-click="prev">Previous</button>
                      <button id="next" type="button" class="btn btn-default next" on-click="next">Next</button>

  </template>
 </dom-module>


text:
@interface AppDelegate : NSObject <UIApplicationDelegate>
{
    NSTimer *mTimer;
    DemoApp demo;

    // Use of the CADisplayLink class is the preferred method for controlling your animation timing.
    // CADisplayLink will link to the main display and fire every vsync when added to a given run-loop.
    // The NSTimer class is used only as fallback when running on a pre 3.1 device where CADisplayLink
    // isn't available.
    id mDisplayLink;
    NSDate *mDate;
    double mLastFrameTime;
    double mStartTime;
    BOOL mDisplayLinkSupported;
}

- (void)go;
- (void)renderOneFrame:(id)sender;

@property (retain) NSTimer *mTimer;
@property (nonatomic) double mLastFrameTime;
@property (nonatomic) double mStartTime;

@end

@implementation AppDelegate

@synthesize mTimer;
@dynamic mLastFrameTime;
@dynamic mStartTime;

- (double)mLastFrameTime
{
    return mLastFrameTime;
}

- (void)setLastFrameTime:(double)frameInterval
{
    // Frame interval defines how many display frames must pass between each time the
    // display link fires. The display link will only fire 30 times a second when the
    // frame internal is two on a display that refreshes 60 times a second. The default
    // frame interval setting of one will fire 60 times a second when the display refreshes
    // at 60 times a second. A frame interval setting of less than one results in undefined
    // behavior.
    if (frameInterval >= 1)
    {
        mLastFrameTime = frameInterval;
    }
}

- (void)go {

    NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];
    mLastFrameTime = 1;
    mStartTime = 0;
    mTimer = nil;

    try {
        demo.startDemo();

        Ogre::Root::getSingleton().getRenderSystem()->_initRenderTargets();

        // Clear event times
		Ogre::Root::getSingleton().clearEventTimes();
    } catch( Ogre::Exception& e ) {
        std::cerr << "An exception has occurred: " <<
        e.getFullDescription().c_str() << std::endl;
    }

    if (mDisplayLinkSupported)
    {
        // CADisplayLink is API new to iPhone SDK 3.1. Compiling against earlier versions will result in a warning, but can be dismissed
        // if the system version runtime check for CADisplayLink exists in -initWithCoder:. The runtime check ensures this code will
        // not be called in system versions earlier than 3.1.
        mDate = [[NSDate alloc] init];
        mLastFrameTime = -[mDate timeIntervalSinceNow];

        mDisplayLink = [NSClassFromString(@"CADisplayLink") displayLinkWithTarget:self selector:@selector(renderOneFrame:)];
        [mDisplayLink setFrameInterval:mLastFrameTime];
        [mDisplayLink addToRunLoop:[NSRunLoop currentRunLoop] forMode:NSDefaultRunLoopMode];
    }
    else
    {
        mTimer = [NSTimer scheduledTimerWithTimeInterval:(NSTimeInterval)(1.0f / 60.0f) * mLastFrameTime
                                                  target:self
                                                selector:@selector(renderOneFrame:)
                                                userInfo:nil
                                                 repeats:YES];
    }
    [pool release];
}

- (void)applicationDidFinishLaunching:(UIApplication *)application
{
    // Hide the status bar
    [[UIApplication sharedApplication] setStatusBarHidden:YES];

    mDisplayLinkSupported = FALSE;
    mLastFrameTime = 1;
    mStartTime = 0;
    mTimer = nil;

    // A system version of 3.1 or greater is required to use CADisplayLink. The NSTimer
    // class is used as fallback when it isn't available.
#if USE_CADISPLAYLINK
    NSString *reqSysVer = @"3.1";
    NSString *currSysVer = [[UIDevice currentDevice] systemVersion];
    if ([currSysVer compare:reqSysVer options:NSNumericSearch] != NSOrderedAscending)
        mDisplayLinkSupported = TRUE;
#endif

    [self go];
}

- (void)applicationWillTerminate:(UIApplication *)application
{
    Ogre::Root::getSingleton().queueEndRendering();

    if (mDisplayLinkSupported)
    {
        [mDate release];
        mDate = nil;

        [mDisplayLink invalidate];
        mDisplayLink = nil;
    }
    else
    {
        [mTimer invalidate];
        mTimer = nil;
    }
    [[UIApplication sharedApplication] performSelector:@selector(terminate:) withObject:nil afterDelay:0.0];
}

- (void)applicationWillResignActive:(UIApplication *)application
{
    Ogre::Root::getSingleton().saveConfig();

    [[NSNotificationCenter defaultCenter] removeObserver:self];
}

- (void)applicationDidBecomeActive:(UIApplication *)application
{
}

- (void)renderOneFrame:(id)sender
{
    if(!OgreFramework::getSingletonPtr()->isOgreToBeShutDown() &&
       Ogre::Root::getSingletonPtr() && Ogre::Root::getSingleton().isInitialised())
    {
		if(OgreFramework::getSingletonPtr()->m_pRenderWnd->isActive())
		{
			mStartTime = OgreFramework::getSingletonPtr()->m_pTimer->getMillisecondsCPU();

			OgreFramework::getSingletonPtr()->m_pMouse->capture();

			OgreFramework::getSingletonPtr()->updateOgre(mLastFrameTime);
			OgreFramework::getSingletonPtr()->m_pRoot->renderOneFrame();

			mLastFrameTime = OgreFramework::getSingletonPtr()->m_pTimer->getMillisecondsCPU() - mStartTime;
		}
    }
    else
    {

	    if (mDisplayLinkSupported)
	    {
	        [mDate release];
	        mDate = nil;

	        [mDisplayLink invalidate];
	        mDisplayLink = nil;
	    }
	    else
	    {
	        [mTimer invalidate];
	        mTimer = nil;
	    }
        [[UIApplication sharedApplication] performSelector:@selector(terminate:) withObject:nil afterDelay:0.0];
    }
}

- (void)dealloc {
    if(mTimer)
    {
        [mTimer invalidate];
        mTimer = nil;
    }

    [super dealloc];
}

@end

#endif

#endif


text:
/*
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *	  http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.asual.summer.json;

import java.io.IOException;

import javax.inject.Named;

import org.codehaus.jackson.JsonGenerationException;
import org.codehaus.jackson.JsonParseException;
import org.codehaus.jackson.map.JsonMappingException;
import org.codehaus.jackson.map.ObjectMapper;

/**
 *
 * @author Rostislav Hristov
 *
 */
@Named
public class JsonUtils {

	private static ObjectMapper mapper = new ObjectMapper();

	public static String encode(Object obj) throws JsonGenerationException, JsonMappingException, IOException {
		return mapper.writeValueAsString(obj);
	}

	public static <T> T decode(String str, Class<T> clazz) throws JsonParseException, JsonMappingException, IOException {
		return mapper.readValue(str, clazz);
	}

}


text:
class CreateBanners < ActiveRecord::Migration[5.0]
  def change
    create_table :banners do |t|
      t.string :image
      t.string :group_id, limit: 20

      t.timestamps null: false
    end
  end
end


text:
/*=============================================================================
# Filename: LeafNode.h
# Author: syzz
# Mail: 1181955272@qq.com
# Last Modified: 2015-04-26 16:39
# Description: the leaf-node of a B+ tree
=============================================================================*/

#ifndef _KVSTORE_ISNODE_LEAFNODE_H
#define _KVSTORE_ISNODE_LEAFNODE_H

#include "Node.h"

class ISLeafNode: public ISNode
{
protected:
	ISNode* prev;	//LeafNode
	ISNode* next;
	Bstr* values;
	void AllocValues();
	//void FreeValues();
public:
	ISLeafNode();
	ISLeafNode(bool isVirtual);
	//LeafNode(Storage* TSM);
	void Virtual();
	void Normal();
	ISNode* getPrev() const;
	ISNode* getNext() const;
	const Bstr* getValue(int _index) const;
	bool setValue(const Bstr* _value, int _index, bool ifcopy = false);
	bool addValue(const Bstr* _value, int _index, bool ifcopy = false);
	bool subValue(int _index, bool ifdel = false);
	void setPrev(ISNode* _prev);
	void setNext(ISNode* _next);
	unsigned getSize() const;
	ISNode* split(ISNode* _father, int _index);
	ISNode* coalesce(ISNode* _father, int _index);
	void release();
	~ISLeafNode();
	void print(std::string s);			//DEBUG
	/*non-sense virtual function
	Node* getChild(int _index) const;
	bool addChild(Node* _child, int _index);
	bool subChild(int _index);
	*/
};
//BETTER: prev isn't a must, and reverse-range can be achieved using recursive-next

#endif


text:
class CreateRtppmSnapshots < ActiveRecord::Migration
  def change
    create_table :rtppm_snapshots do |t|
      t.json :raw_data
      t.datetime :imported_at

      t.timestamps
    end
  end
end


text:
Ionic OkCupid Side Menu
===================

A demo of how to achieve a side menu similar to that of the OkCupid App.
When the side menu is triggered, a ratio is returned via the `$ionicSideMenuDelegate.getOpenRatio()` provider method.
This ratio is then by a callback which is passed to the the animate ratio directive through
the `animate-ratio` ratio.

[Demo](http://codepen.io/loringdodge/pen/YXvGjX)

![Screenshot](screenshots/iphone.png)

## Usage

In your sidemenu:
```html
<button class="button-circle" animate-ratio="fadeIn">
  <i class="ion-ios-pulse-strong"></i>
</button>
```

In your parent controller:
```js
var transitionIn = function(ratio) {
  return Math.abs(ratio);
}

$scope.fadeIn = function(element, ratio) {
  element.style.transform = element.style.webkitTransform = 'scale(' + transitionIn(ratio) + ')';
  element.style.opacity = transitionIn(ratio);
}
```

## Directive Attributes

| Name                   | Scope  | Options| Action                                                        |
|------------------------|--------|--------|---------------------------------------------------------------|
| `animate-ratio`        | =      | fn     | Callback used to customize animation                          |


text:
/* @LICENSE(MUSLC_MIT) */

#include <unistd.h>
#include <errno.h>
#include <limits.h>
#include <string.h>
#include "internal/syscall.h"

char *getcwd(char *buf, size_t size)
{
	char tmp[PATH_MAX];
	if (!buf) buf = tmp, size = PATH_MAX;
	if (syscall(SYS_getcwd, buf, size) < 0) return 0;
	return buf == tmp ? strdup(buf) : buf;
}


text:
define("dojox/form/FileInput",["dojo/_base/declare","dojo/_base/kernel","dojo/_base/fx","dojo/dom-attr","dojo/dom-class","dojo/text!./resources/FileInput.html","dijit/form/_FormWidget","dijit/_Templated"],function(_1,_2,fx,_3,_4,_5,_6,_7){
_2.experimental("dojox.form.FileInput");
return _1("dojox.form.FileInput",_6,{label:"Browse ...",cancelText:"Cancel",name:"uploadFile",templateString:_5,startup:function(){
this._listener=this.connect(this.fileInput,"onchange","_matchValue");
this._keyListener=this.connect(this.fileInput,"onkeyup","_matchValue");
},postCreate:function(){
},_matchValue:function(){
this.inputNode.value=this.fileInput.value;
if(this.inputNode.value){
this.cancelNode.style.visibility="visible";
fx.fadeIn({node:this.cancelNode,duration:275}).play();
}
},setLabel:function(_8,_9){
this.titleNode.innerHTML=_8;
},reset:function(e){
this.disconnect(this._listener);
this.disconnect(this._keyListener);
if(this.fileInput){
this.domNode.removeChild(this.fileInput);
}
fx.fadeOut({node:this.cancelNode,duration:275}).play();
this.fileInput=document.createElement("input");
this.fileInput.setAttribute("type","file");
this.fileInput.setAttribute("id",this.id);
this.fileInput.setAttribute("name",this.name);
_4.add(this.fileInput,"dijitFileInputReal");
this.domNode.appendChild(this.fileInput);
this._keyListener=this.connect(this.fileInput,"onkeyup","_matchValue");
this._listener=this.connect(this.fileInput,"onchange","_matchValue");
this.inputNode.value="";
}});
});
require({cache:{"url:dojox/form/resources/FileInput.html":"
\n\t<input id=\"${id}\" class=\"dijitFileInputReal\" type=\"file\" dojoAttachPoint=\"fileInput\" name=\"${name}\" />\n\t
\n\t\t<input class=\"dijitFileInputVisible\" type=\"text\" dojoAttachPoint=\"focusNode, inputNode\" />\n\t\t
${label}
\n\t\t
${cancelText}
\n\t
\n
\n"}});


text:
export * from './decorator';
export * from './error';
export * from './guard';
export * from './interface';
export * from './metadata';
export * from './type';
export * from './util';


text:
#include <assert.h>
#include <string.h>
#include "pocl_cl.h"

CL_API_ENTRY cl_int CL_API_CALL
POname(clGetContextInfo)(cl_context context,
                 cl_context_info param_name,
                 size_t param_value_size,
                 void *param_value,
                 size_t *param_value_size_ret) CL_API_SUFFIX__VERSION_1_0
{
  size_t value_size;

  if (context == NULL)
    return CL_INVALID_CONTEXT;

  switch (param_name) {

  case CL_CONTEXT_DEVICES:
    {
      value_size = context->num_devices * sizeof(cl_device_id);
      if (param_value != NULL) {
        if (param_value_size < value_size)
          return CL_INVALID_VALUE;
        memcpy(param_value, context->devices, value_size);
      }
      if (param_value_size_ret != NULL)
        *param_value_size_ret = value_size;
      return CL_SUCCESS;
    }
  case CL_CONTEXT_NUM_DEVICES:
    {
      if (param_value_size < sizeof(size_t) && param_value != NULL)
        return CL_INVALID_VALUE;
      if (param_value != NULL )
        *((size_t*)param_value)=context->num_devices;
      if (param_value_size_ret != NULL)
        *param_value_size_ret=sizeof(size_t);
      return CL_SUCCESS;
    }
  default:
    break;
  }
  POCL_WARN_INCOMPLETE();
  return CL_INVALID_VALUE;
}
POsym(clGetContextInfo)


text:
package com.planet_ink.coffee_mud.Abilities.interfaces;
import com.planet_ink.coffee_mud.core.interfaces.*;
import com.planet_ink.coffee_mud.core.*;
import com.planet_ink.coffee_mud.core.collections.*;
import com.planet_ink.coffee_mud.Abilities.Misc.Amputation;
import com.planet_ink.coffee_mud.Abilities.interfaces.*;
import com.planet_ink.coffee_mud.Areas.interfaces.*;
import com.planet_ink.coffee_mud.Behaviors.interfaces.*;
import com.planet_ink.coffee_mud.CharClasses.interfaces.*;
import com.planet_ink.coffee_mud.Commands.interfaces.*;
import com.planet_ink.coffee_mud.Common.interfaces.*;
import com.planet_ink.coffee_mud.Exits.interfaces.*;
import com.planet_ink.coffee_mud.Items.interfaces.*;
import com.planet_ink.coffee_mud.Libraries.interfaces.*;
import com.planet_ink.coffee_mud.Locales.interfaces.*;
import com.planet_ink.coffee_mud.MOBS.interfaces.*;
import com.planet_ink.coffee_mud.Races.interfaces.*;

import java.util.*;

/**
 * This interface denotes an ability that also incidentally is capable
 * of generating objects, usually items.  This is probably a common
 * skill, but one could imagine an craftor also being a spell that
 * generates its own items.  Also the generation is an incidental
 * and internal aspect of the ability, these methods allow that
 * functionality to be exposed for archon use.
 */
public interface CraftorAbility extends Ability, RecipeDriven
{
	/**
	 * A list containing an entry for each craftable recipe
	 * both standard, and extra recipes from given mob
	 * Each craftable recipe is also a list of strings.
	 * @param mob the mob to check for extra recipes
	 * @return a vector of vectors
	 */
	public List<List<String>> fetchMyRecipes(final MOB mob);

	/**
	 * Returns a list of Integer objects where each Integer
	 * is a fully qualified RawMaterial code.
	 * @see com.planet_ink.coffee_mud.Items.interfaces.RawMaterial
	 * @return a vector of integers
	 */
	public List<Integer> myResources();

	/**
	 * Given a raw recipe, returns a description of the required components to build it.
	 * @param mob the potential builder
	 * @param recipe the raw recipe description
	 * @return a descriptive string
	 */
	public String getDecodedComponentsDescription(final MOB mob, final List<String> recipe);

	/**
	 * Class for generating filters of crafted items
	 * @author Bo Zimmerman
	 *
	 */
	public static class CraftorFilter
	{
		public int			minLevel	= 0;
		public int			maxLevel	= Integer.MAX_VALUE;
		public int			reqLevel	= -1;
		public int			minValue	= -1;
		public int			maxValue	= Integer.MAX_VALUE;
		public Class<?>[]	classes		= new Class<?>[0];
		public String		name		= "";
	}
}