text:
namespace leveldb
{

namespace Win32
{

#define DISALLOW_COPY_AND_ASSIGN(TypeName) \
  TypeName(const TypeName&);               \
  void operator=(const TypeName&)

std::string GetCurrentDir();
std::wstring GetCurrentDirW();

static const std::string CurrentDir = GetCurrentDir();
static const std::wstring CurrentDirW = GetCurrentDirW();

std::string& ModifyPath(std::string& path);
std::wstring& ModifyPath(std::wstring& path);

std::string GetLastErrSz();
std::wstring GetLastErrSzW();

size_t GetPageSize();

typedef void (*ScheduleProc)(void*) ;

struct WorkItemWrapper
{
    WorkItemWrapper(ScheduleProc proc_,void* content_);
    ScheduleProc proc;
    void* pContent;
};

DWORD WINAPI WorkItemWrapperProc(LPVOID pContent);

class Win32SequentialFile : public SequentialFile
{
public:
    friend class Win32Env;
    virtual ~Win32SequentialFile();
    virtual Status Read(size_t n, Slice* result, char* scratch);
    virtual Status Skip(uint64_t n);
    BOOL isEnable();
private:
    BOOL _Init();
    void _CleanUp();
    Win32SequentialFile(const std::string& fname);
    std::string _filename;
    ::HANDLE _hFile;
    DISALLOW_COPY_AND_ASSIGN(Win32SequentialFile);
};

class Win32RandomAccessFile : public RandomAccessFile
{
public:
    friend class Win32Env;
    virtual ~Win32RandomAccessFile();
    virtual Status Read(uint64_t offset, size_t n, Slice* result,char* scratch) const;
    BOOL isEnable();
private:
    BOOL _Init(LPCWSTR path);
    void _CleanUp();
    Win32RandomAccessFile(const std::string& fname);
    HANDLE _hFile;
    const std::string _filename;
    DISALLOW_COPY_AND_ASSIGN(Win32RandomAccessFile);
};

class Win32MapFile : public WritableFile
{
public:
    Win32MapFile(const std::string& fname);

    ~Win32MapFile();
    virtual Status Append(const Slice& data);
    virtual Status Close();
    virtual Status Flush();
    virtual Status Sync();
    BOOL isEnable();
private:
    std::string _filename;
    HANDLE _hFile;
    size_t _page_size;
    size_t _map_size;       // How much extra memory to map at a time
    char* _base;            // The mapped region
    HANDLE _base_handle;
    char* _limit;           // Limit of the mapped region
    char* _dst;             // Where to write next  (in range [base_,limit_])
    char* _last_sync;       // Where have we synced up to
    uint64_t _file_offset;  // Offset of base_ in file
    //LARGE_INTEGER file_offset_;
    // Have we done an munmap of unsynced data?
    bool _pending_sync;

    // Roundup x to a multiple of y
    static size_t _Roundup(size_t x, size_t y);
    size_t _TruncateToPageBoundary(size_t s);
    bool _UnmapCurrentRegion();
    bool _MapNewRegion();
    DISALLOW_COPY_AND_ASSIGN(Win32MapFile);
    BOOL _Init(LPCWSTR Path);
};

class Win32FileLock : public FileLock
{
public:
    friend class Win32Env;
    virtual ~Win32FileLock();
    BOOL isEnable();
private:
    BOOL _Init(LPCWSTR path);
    void _CleanUp();
    Win32FileLock(const std::string& fname);
    HANDLE _hFile;
    std::string _filename;
    DISALLOW_COPY_AND_ASSIGN(Win32FileLock);
};

class Win32Logger : public Logger
{
public:
    friend class Win32Env;
    virtual ~Win32Logger();
    virtual void Logv(const char* format, va_list ap);
private:
    explicit Win32Logger(WritableFile* pFile);
    WritableFile* _pFileProxy;
    DISALLOW_COPY_AND_ASSIGN(Win32Logger);
};

class Win32Env : public Env
{
public:
    Win32Env();
    virtual ~Win32Env();
    virtual Status NewSequentialFile(const std::string& fname,
        SequentialFile** result);

    virtual Status NewRandomAccessFile(const std::string& fname,
        RandomAccessFile** result);
    virtual Status NewWritableFile(const std::string& fname,
        WritableFile** result);

    virtual bool FileExists(const std::string& fname);

    virtual Status GetChildren(const std::string& dir,
        std::vector<std::string>* result);

    virtual Status DeleteFile(const std::string& fname);

    virtual Status CreateDir(const std::string& dirname);

    virtual Status DeleteDir(const std::string& dirname);

    virtual Status GetFileSize(const std::string& fname, uint64_t* file_size);

    virtual Status RenameFile(const std::string& src,
        const std::string& target);

    virtual Status LockFile(const std::string& fname, FileLock** lock);

    virtual Status UnlockFile(FileLock* lock);

    virtual void Schedule(
        void (*function)(void* arg),
        void* arg);

    virtual void StartThread(void (*function)(void* arg), void* arg);

    virtual Status GetTestDirectory(std::string* path);

    //virtual void Logv(WritableFile* log, const char* format, va_list ap);

    virtual Status NewLogger(const std::string& fname, Logger** result);

    virtual uint64_t NowMicros();

    virtual void SleepForMicroseconds(int micros);
};

void ToWidePath(const std::string& value, std::wstring& target) {
	wchar_t buffer[MAX_PATH];
	MultiByteToWideChar(CP_ACP, 0, value.c_str(), -1, buffer, MAX_PATH);
	target = buffer;
}

void ToNarrowPath(const std::wstring& value, std::string& target) {
	char buffer[MAX_PATH];
	WideCharToMultiByte(CP_ACP, 0, value.c_str(), -1, buffer, MAX_PATH, NULL, NULL);
	target = buffer;
}

std::string GetCurrentDir()
{
    CHAR path[MAX_PATH];
    ::GetModuleFileNameA(::GetModuleHandleA(NULL),path,MAX_PATH);
    *strrchr(path,'\\') = 0;
    return std::string(path);
}

std::wstring GetCurrentDirW()
{
    WCHAR path[MAX_PATH];
    ::GetModuleFileNameW(::GetModuleHandleW(NULL),path,MAX_PATH);
    *wcsrchr(path,L'\\') = 0;
    return std::wstring(path);
}

std::string& ModifyPath(std::string& path)
{
    if(path[0] == '/' || path[0] == '\\'){
        path = CurrentDir + path;
    }
    std::replace(path.begin(),path.end(),'/','\\');

    return path;
}

std::wstring& ModifyPath(std::wstring& path)
{
    if(path[0] == L'/' || path[0] == L'\\'){
        path = CurrentDirW + path;
    }
    std::replace(path.begin(),path.end(),L'/',L'\\');
    return path;
}

std::string GetLastErrSz()
{
    LPWSTR lpMsgBuf;
    FormatMessageW(
        FORMAT_MESSAGE_ALLOCATE_BUFFER |
        FORMAT_MESSAGE_FROM_SYSTEM |
        FORMAT_MESSAGE_IGNORE_INSERTS,
        NULL,
        GetLastError(),
        0, // Default language
        (LPWSTR) &lpMsgBuf,
        0,
        NULL
        );
    std::string Err;
	ToNarrowPath(lpMsgBuf, Err);
    LocalFree( lpMsgBuf );
    return Err;
}

std::wstring GetLastErrSzW()
{
    LPVOID lpMsgBuf;
    FormatMessageW(
        FORMAT_MESSAGE_ALLOCATE_BUFFER |
        FORMAT_MESSAGE_FROM_SYSTEM |
        FORMAT_MESSAGE_IGNORE_INSERTS,
        NULL,
        GetLastError(),
        0, // Default language
        (LPWSTR) &lpMsgBuf,
        0,
        NULL
        );
    std::wstring Err = (LPCWSTR)lpMsgBuf;
    LocalFree(lpMsgBuf);
    return Err;
}

WorkItemWrapper::WorkItemWrapper( ScheduleProc proc_,void* content_ ) :
    proc(proc_),pContent(content_)
{

}

DWORD WINAPI WorkItemWrapperProc(LPVOID pContent)
{
    WorkItemWrapper* item = static_cast<WorkItemWrapper*>(pContent);
    ScheduleProc TempProc = item->proc;
    void* arg = item->pContent;
    delete item;
    TempProc(arg);
    return 0;
}

size_t GetPageSize()
{
    SYSTEM_INFO si;
    GetSystemInfo(&si);
    return std::max(si.dwPageSize,si.dwAllocationGranularity);
}

const size_t g_PageSize = GetPageSize();

Win32SequentialFile::Win32SequentialFile( const std::string& fname ) :
    _filename(fname),_hFile(NULL)
{
    _Init();
}

Win32SequentialFile::~Win32SequentialFile()
{
    _CleanUp();
}

Status Win32SequentialFile::Read( size_t n, Slice* result, char* scratch )
{
    Status sRet;
    DWORD hasRead = 0;
    if(_hFile && ReadFile(_hFile,scratch,n,&hasRead,NULL) ){
        *result = Slice(scratch,hasRead);
    } else {
        sRet = Status::IOError(_filename, Win32::GetLastErrSz() );
    }
    return sRet;
}

Status Win32SequentialFile::Skip( uint64_t n )
{
    Status sRet;
    LARGE_INTEGER Move,NowPointer;
    Move.QuadPart = n;
    if(!SetFilePointerEx(_hFile,Move,&NowPointer,FILE_CURRENT)){
        sRet = Status::IOError(_filename,Win32::GetLastErrSz());
    }
    return sRet;
}

BOOL Win32SequentialFile::isEnable()
{
    return _hFile ? TRUE : FALSE;
}

BOOL Win32SequentialFile::_Init()
{
	std::wstring path;
	ToWidePath(_filename, path);
	_hFile = CreateFileW(path.c_str(),
                         GENERIC_READ,
                         FILE_SHARE_READ,
                         NULL,
                         OPEN_EXISTING,
                         FILE_ATTRIBUTE_NORMAL,
                         NULL);
    return _hFile ? TRUE : FALSE;
}

void Win32SequentialFile::_CleanUp()
{
    if(_hFile){
        CloseHandle(_hFile);
        _hFile = NULL;
    }
}

Win32RandomAccessFile::Win32RandomAccessFile( const std::string& fname ) :
    _filename(fname),_hFile(NULL)
{
	std::wstring path;
	ToWidePath(fname, path);
    _Init( path.c_str() );
}

Win32RandomAccessFile::~Win32RandomAccessFile()
{
    _CleanUp();
}

Status Win32RandomAccessFile::Read(uint64_t offset,size_t n,Slice* result,char* scratch) const
{
    Status sRet;
    OVERLAPPED ol = {0};
    ZeroMemory(&ol,sizeof(ol));
    ol.Offset = (DWORD)offset;
    ol.OffsetHigh = (DWORD)(offset >> 32);
    DWORD hasRead = 0;
    if(!ReadFile(_hFile,scratch,n,&hasRead,&ol))
        sRet = Status::IOError(_filename,Win32::GetLastErrSz());
    else
        *result = Slice(scratch,hasRead);
    return sRet;
}

BOOL Win32RandomAccessFile::_Init( LPCWSTR path )
{
    BOOL bRet = FALSE;
    if(!_hFile)
        _hFile = ::CreateFileW(path,GENERIC_READ,FILE_SHARE_READ,NULL,OPEN_EXISTING,
        FILE_ATTRIBUTE_NORMAL | FILE_FLAG_RANDOM_ACCESS,NULL);
    if(!_hFile || _hFile == INVALID_HANDLE_VALUE )
        _hFile = NULL;
    else
        bRet = TRUE;
    return bRet;
}

BOOL Win32RandomAccessFile::isEnable()
{
    return _hFile ? TRUE : FALSE;
}

void Win32RandomAccessFile::_CleanUp()
{
    if(_hFile){
        ::CloseHandle(_hFile);
        _hFile = NULL;
    }
}

size_t Win32MapFile::_Roundup( size_t x, size_t y )
{
    return ((x + y - 1) / y) * y;
}

size_t Win32MapFile::_TruncateToPageBoundary( size_t s )
{
    s -= (s & (_page_size - 1));
    assert((s % _page_size) == 0);
    return s;
}

bool Win32MapFile::_UnmapCurrentRegion()
{
    bool result = true;
    if (_base != NULL) {
        if (_last_sync < _limit) {
            // Defer syncing this data until next Sync() call, if any
            _pending_sync = true;
        }
        if (!UnmapViewOfFile(_base) || !CloseHandle(_base_handle))
            result = false;
        _file_offset += _limit - _base;
        _base = NULL;
        _base_handle = NULL;
        _limit = NULL;
        _last_sync = NULL;
        _dst = NULL;
        // Increase the amount we map the next time, but capped at 1MB
        if (_map_size < (1<<20)) {
            _map_size *= 2;
        }
    }
    return result;
}

bool Win32MapFile::_MapNewRegion()
{
    assert(_base == NULL);
    //LONG newSizeHigh = (LONG)((file_offset_ + map_size_) >> 32);
    //LONG newSizeLow = (LONG)((file_offset_ + map_size_) & 0xFFFFFFFF);
    DWORD off_hi = (DWORD)(_file_offset >> 32);
    DWORD off_lo = (DWORD)(_file_offset & 0xFFFFFFFF);
    LARGE_INTEGER newSize;
    newSize.QuadPart = _file_offset + _map_size;
    SetFilePointerEx(_hFile, newSize, NULL, FILE_BEGIN);
    SetEndOfFile(_hFile);

    _base_handle = CreateFileMappingA(
        _hFile,
        NULL,
        PAGE_READWRITE,
        0,
        0,
        0);
    if (_base_handle != NULL) {
        _base = (char*) MapViewOfFile(_base_handle,
            FILE_MAP_ALL_ACCESS,
            off_hi,
            off_lo,
            _map_size);
        if (_base != NULL) {
            _limit = _base + _map_size;
            _dst = _base;
            _last_sync = _base;
            return true;
        }
    }
    return false;
}

Win32MapFile::Win32MapFile( const std::string& fname) :
    _filename(fname),
    _hFile(NULL),
    _page_size(Win32::g_PageSize),
    _map_size(_Roundup(65536, Win32::g_PageSize)),
    _base(NULL),
    _base_handle(NULL),
    _limit(NULL),
    _dst(NULL),
    _last_sync(NULL),
    _file_offset(0),
    _pending_sync(false)
{
	std::wstring path;
	ToWidePath(fname, path);
    _Init(path.c_str());
    assert((Win32::g_PageSize & (Win32::g_PageSize - 1)) == 0);
}

Status Win32MapFile::Append( const Slice& data )
{
    const char* src = data.data();
    size_t left = data.size();
    Status s;
    while (left > 0) {
        assert(_base <= _dst);
        assert(_dst <= _limit);
        size_t avail = _limit - _dst;
        if (avail == 0) {
            if (!_UnmapCurrentRegion() ||
                !_MapNewRegion()) {
                    return Status::IOError("WinMmapFile.Append::UnmapCurrentRegion or MapNewRegion: ", Win32::GetLastErrSz());
            }
        }
        size_t n = (left <= avail) ? left : avail;
        memcpy(_dst, src, n);
        _dst += n;
        src += n;
        left -= n;
    }
    return s;
}

Status Win32MapFile::Close()
{
    Status s;
    size_t unused = _limit - _dst;
    if (!_UnmapCurrentRegion()) {
        s = Status::IOError("WinMmapFile.Close::UnmapCurrentRegion: ",Win32::GetLastErrSz());
    } else if (unused > 0) {
        // Trim the extra space at the end of the file
        LARGE_INTEGER newSize;
        newSize.QuadPart = _file_offset - unused;
        if (!SetFilePointerEx(_hFile, newSize, NULL, FILE_BEGIN)) {
            s = Status::IOError("WinMmapFile.Close::SetFilePointer: ",Win32::GetLastErrSz());
        } else
            SetEndOfFile(_hFile);
    }
    if (!CloseHandle(_hFile)) {
        if (s.ok()) {
            s = Status::IOError("WinMmapFile.Close::CloseHandle: ", Win32::GetLastErrSz());
        }
    }
    _hFile = INVALID_HANDLE_VALUE;
    _base = NULL;
    _base_handle = NULL;
    _limit = NULL;

    return s;
}

Status Win32MapFile::Sync()
{
    Status s;
    if (_pending_sync) {
        // Some unmapped data was not synced
        _pending_sync = false;
        if (!FlushFileBuffers(_hFile)) {
            s = Status::IOError("WinMmapFile.Sync::FlushFileBuffers: ",Win32::GetLastErrSz());
        }
    }
    if (_dst > _last_sync) {
        // Find the beginnings of the pages that contain the first and last
        // bytes to be synced.
        size_t p1 = _TruncateToPageBoundary(_last_sync - _base);
        size_t p2 = _TruncateToPageBoundary(_dst - _base - 1);
        _last_sync = _dst;
        if (!FlushViewOfFile(_base + p1, p2 - p1 + _page_size)) {
            s = Status::IOError("WinMmapFile.Sync::FlushViewOfFile: ",Win32::GetLastErrSz());
        }
    }
    return s;
}

Status Win32MapFile::Flush()
{
    return Status::OK();
}

Win32MapFile::~Win32MapFile()
{
    if (_hFile != INVALID_HANDLE_VALUE) {
        Win32MapFile::Close();
    }
}

BOOL Win32MapFile::_Init( LPCWSTR Path )
{
    DWORD Flag = PathFileExistsW(Path) ? OPEN_EXISTING : CREATE_ALWAYS;
    _hFile = CreateFileW(Path,
                         GENERIC_READ | GENERIC_WRITE,
                         FILE_SHARE_READ|FILE_SHARE_DELETE|FILE_SHARE_WRITE,
                         NULL,
                         Flag,
                         FILE_ATTRIBUTE_NORMAL,
                         NULL);
    if(!_hFile || _hFile == INVALID_HANDLE_VALUE)
        return FALSE;
    else
        return TRUE;
}

BOOL Win32MapFile::isEnable()
{
    return _hFile ? TRUE : FALSE;
}

Win32FileLock::Win32FileLock( const std::string& fname ) :
    _hFile(NULL),_filename(fname)
{
	std::wstring path;
	ToWidePath(fname, path);
	_Init(path.c_str());
}

Win32FileLock::~Win32FileLock()
{
    _CleanUp();
}

BOOL Win32FileLock::_Init( LPCWSTR path )
{
    BOOL bRet = FALSE;
    if(!_hFile)
        _hFile = ::CreateFileW(path,0,0,NULL,CREATE_ALWAYS,FILE_ATTRIBUTE_NORMAL,NULL);
    if(!_hFile || _hFile == INVALID_HANDLE_VALUE ){
        _hFile = NULL;
    }
    else
        bRet = TRUE;
    return bRet;
}

void Win32FileLock::_CleanUp()
{
    ::CloseHandle(_hFile);
    _hFile = NULL;
}

BOOL Win32FileLock::isEnable()
{
    return _hFile ? TRUE : FALSE;
}

Win32Logger::Win32Logger(WritableFile* pFile) : _pFileProxy(pFile)
{
    assert(_pFileProxy);
}

Win32Logger::~Win32Logger()
{
    if(_pFileProxy)
        delete _pFileProxy;
}

void Win32Logger::Logv( const char* format, va_list ap )
{
    uint64_t thread_id = ::GetCurrentThreadId();

    // We try twice: the first time with a fixed-size stack allocated buffer,
    // and the second time with a much larger dynamically allocated buffer.
    char buffer[500];
    for (int iter = 0; iter < 2; iter++) {
        char* base;
        int bufsize;
        if (iter == 0) {
            bufsize = sizeof(buffer);
            base = buffer;
        } else {
            bufsize = 30000;
            base = new char[bufsize];
        }
        char* p = base;
        char* limit = base + bufsize;

        SYSTEMTIME st;
        GetLocalTime(&st);
        p += snprintf(p, limit - p,
            "%04d/%02d/%02d-%02d:%02d:%02d.%06d %llx ",
            int(st.wYear),
            int(st.wMonth),
            int(st.wDay),
            int(st.wHour),
            int(st.wMinute),
            int(st.wMinute),
            int(st.wMilliseconds),
            static_cast<long long unsigned int>(thread_id));

        // Print the message
        if (p < limit) {
            va_list backup_ap;
            va_copy(backup_ap, ap);
            p += vsnprintf(p, limit - p, format, backup_ap);
            va_end(backup_ap);
        }

        // Truncate to available space if necessary
        if (p >= limit) {
            if (iter == 0) {
                continue;       // Try again with larger buffer
            } else {
                p = limit - 1;
            }
        }

        // Add newline if necessary
        if (p == base || p[-1] != '\n') {
            *p++ = '\n';
        }

        assert(p <= limit);
        DWORD hasWritten = 0;
        if(_pFileProxy){
            _pFileProxy->Append(Slice(base, p - base));
            _pFileProxy->Flush();
        }
        if (base != buffer) {
            delete[] base;
        }
        break;
    }
}

bool Win32Env::FileExists(const std::string& fname)
{
	std::string path = fname;
    std::wstring wpath;
	ToWidePath(ModifyPath(path), wpath);
    return ::PathFileExistsW(wpath.c_str()) ? true : false;
}

Status Win32Env::GetChildren(const std::string& dir, std::vector<std::string>* result)
{
    Status sRet;
    ::WIN32_FIND_DATAW wfd;
    std::string path = dir;
    ModifyPath(path);
    path += "\\*.*";
	std::wstring wpath;
	ToWidePath(path, wpath);

	::HANDLE hFind = ::FindFirstFileW(wpath.c_str() ,&wfd);
    if(hFind && hFind != INVALID_HANDLE_VALUE){
        BOOL hasNext = TRUE;
        std::string child;
        while(hasNext){
            ToNarrowPath(wfd.cFileName, child);
            if(child != ".." && child != ".")  {
                result->push_back(child);
            }
            hasNext = ::FindNextFileW(hFind,&wfd);
        }
        ::FindClose(hFind);
    }
    else
        sRet = Status::IOError(dir,"Could not get children.");
    return sRet;
}

void Win32Env::SleepForMicroseconds( int micros )
{
    ::Sleep((micros + 999) /1000);
}

Status Win32Env::DeleteFile( const std::string& fname )
{
    Status sRet;
    std::string path = fname;
    std::wstring wpath;
	ToWidePath(ModifyPath(path), wpath);

    if(!::DeleteFileW(wpath.c_str())) {
        sRet = Status::IOError(path, "Could not delete file.");
    }
    return sRet;
}

Status Win32Env::GetFileSize( const std::string& fname, uint64_t* file_size )
{
    Status sRet;
    std::string path = fname;
    std::wstring wpath;
	ToWidePath(ModifyPath(path), wpath);

    HANDLE file = ::CreateFileW(wpath.c_str(),
        GENERIC_READ,FILE_SHARE_READ,NULL,OPEN_EXISTING,FILE_ATTRIBUTE_NORMAL,NULL);
    LARGE_INTEGER li;
    if(::GetFileSizeEx(file,&li)){
        *file_size = (uint64_t)li.QuadPart;
    }else
        sRet = Status::IOError(path,"Could not get the file size.");
    CloseHandle(file);
    return sRet;
}

Status Win32Env::RenameFile( const std::string& src, const std::string& target )
{
    Status sRet;
    std::string src_path = src;
    std::wstring wsrc_path;
	ToWidePath(ModifyPath(src_path), wsrc_path);
	std::string target_path = target;
    std::wstring wtarget_path;
	ToWidePath(ModifyPath(target_path), wtarget_path);

    if(!MoveFileW(wsrc_path.c_str(), wtarget_path.c_str() ) ){
        DWORD err = GetLastError();
        if(err == 0x000000b7){
            if(!::DeleteFileW(wtarget_path.c_str() ) )
                sRet = Status::IOError(src, "Could not rename file.");
			else if(!::MoveFileW(wsrc_path.c_str(),
                                 wtarget_path.c_str() ) )
                sRet = Status::IOError(src, "Could not rename file.");
        }
    }
    return sRet;
}

Status Win32Env::LockFile( const std::string& fname, FileLock** lock )
{
    Status sRet;
    std::string path = fname;
    ModifyPath(path);
    Win32FileLock* _lock = new Win32FileLock(path);
    if(!_lock->isEnable()){
        delete _lock;
        *lock = NULL;
        sRet = Status::IOError(path, "Could not lock file.");
    }
    else
        *lock = _lock;
    return sRet;
}

Status Win32Env::UnlockFile( FileLock* lock )
{
    Status sRet;
    delete lock;
    return sRet;
}

void Win32Env::Schedule( void (*function)(void* arg), void* arg )
{
    QueueUserWorkItem(Win32::WorkItemWrapperProc,
                      new Win32::WorkItemWrapper(function,arg),
                      WT_EXECUTEDEFAULT);
}

void Win32Env::StartThread( void (*function)(void* arg), void* arg )
{
    ::_beginthread(function,0,arg);
}

Status Win32Env::GetTestDirectory( std::string* path )
{
    Status sRet;
    WCHAR TempPath[MAX_PATH];
    ::GetTempPathW(MAX_PATH,TempPath);
	ToNarrowPath(TempPath, *path);
    path->append("leveldb\\test\\");
    ModifyPath(*path);
    return sRet;
}

uint64_t Win32Env::NowMicros()
{
#ifndef USE_VISTA_API
#define GetTickCount64 GetTickCount
#endif
    return (uint64_t)(GetTickCount64()*1000);
}

static Status CreateDirInner( const std::string& dirname )
{
    Status sRet;
    DWORD attr = ::GetFileAttributes(dirname.c_str());
    if (attr == INVALID_FILE_ATTRIBUTES) { // doesn't exist:
      std::size_t slash = dirname.find_last_of("\\");
      if (slash != std::string::npos){
	sRet = CreateDirInner(dirname.substr(0, slash));
	if (!sRet.ok()) return sRet;
      }
      BOOL result = ::CreateDirectory(dirname.c_str(), NULL);
      if (result == FALSE) {
	sRet = Status::IOError(dirname, "Could not create directory.");
	return sRet;
      }
    }
    return sRet;
}

Status Win32Env::CreateDir( const std::string& dirname )
{
    std::string path = dirname;
    if(path[path.length() - 1] != '\\'){
        path += '\\';
    }
    ModifyPath(path);

    return CreateDirInner(path);
}

Status Win32Env::DeleteDir( const std::string& dirname )
{
    Status sRet;
    std::wstring path;
	ToWidePath(dirname, path);
    ModifyPath(path);
    if(!::RemoveDirectoryW( path.c_str() ) ){
        sRet = Status::IOError(dirname, "Could not delete directory.");
    }
    return sRet;
}

Status Win32Env::NewSequentialFile( const std::string& fname, SequentialFile** result )
{
    Status sRet;
    std::string path = fname;
    ModifyPath(path);
    Win32SequentialFile* pFile = new Win32SequentialFile(path);
    if(pFile->isEnable()){
        *result = pFile;
    }else {
        delete pFile;
        sRet = Status::IOError(path, Win32::GetLastErrSz());
    }
    return sRet;
}

Status Win32Env::NewRandomAccessFile( const std::string& fname, RandomAccessFile** result )
{
    Status sRet;
    std::string path = fname;
    Win32RandomAccessFile* pFile = new Win32RandomAccessFile(ModifyPath(path));
    if(!pFile->isEnable()){
        delete pFile;
        *result = NULL;
        sRet = Status::IOError(path, Win32::GetLastErrSz());
    }else
        *result = pFile;
    return sRet;
}

Status Win32Env::NewLogger( const std::string& fname, Logger** result )
{
    Status sRet;
    std::string path = fname;
    Win32MapFile* pMapFile = new Win32MapFile(ModifyPath(path));
    if(!pMapFile->isEnable()){
        delete pMapFile;
        *result = NULL;
        sRet = Status::IOError(path,"could not create a logger.");
    }else
        *result = new Win32Logger(pMapFile);
    return sRet;
}

Status Win32Env::NewWritableFile( const std::string& fname, WritableFile** result )
{
    Status sRet;
    std::string path = fname;
    Win32MapFile* pFile = new Win32MapFile(ModifyPath(path));
    if(!pFile->isEnable()){
        *result = NULL;
        sRet = Status::IOError(fname,Win32::GetLastErrSz());
    }else
        *result = pFile;
    return sRet;
}

Win32Env::Win32Env()
{

}

Win32Env::~Win32Env()
{

}

}  // Win32 namespace

static port::OnceType once = LEVELDB_ONCE_INIT;
static Env* default_env;
static void InitDefaultEnv() { default_env = new Win32::Win32Env(); }

Env* Env::Default() {
  port::InitOnce(&once, InitDefaultEnv);
  return default_env;
}

}  // namespace leveldb

#endif // defined(LEVELDB_PLATFORM_WINDOWS)


text:
@implementation BookmarkObject

@synthesize name = _name;
@synthesize url = _url;

- (id) initWithName:(NSString *)aName andURL:(NSURL *)aUrl {
    if (self = [super init]) {
        self.name = aName;
        self.url = aUrl;
    }
    return self;
}

- (id) initWithCoder: (NSCoder *)coder {
      self = [self init];
    if (self != nil)
    {
        self.name = [coder decodeObjectForKey: @"name"];
        self.url = [coder decodeObjectForKey: @"url"];
    }
    return self;
}

- (void) encodeWithCoder: (NSCoder *)coder {
    [coder encodeObject:_name forKey:@"name"];
    [coder encodeObject:_url forKey:@"url"];
}

- (void) dealloc {
    self.name = nil;
    self.url = nil;
    [super dealloc];
}

@end

redpajama_set_name: RedPajamaGithub


text:
<?php

$app->add(new Sentinel\Middleware\ResponseHeaders());


text:
var companyList = require('../../../fixtures/v4/company-list/company-list.json')
var filteredCompanyLists = require('../../../fixtures/v4/company-list/filtered-company-lists.json')
var companyLists = require('../../../fixtures/v4/company-list/company-lists.json')
var companyListsDB = require('../../../fixtures/v4/company-list/company-lists-db.json')
var multipleItemCompanyList = require('../../../fixtures/v4/company-list/single-list-with-multiple-items.json')
var errorOnDeleteCompanyList = require('../../../fixtures/v4/company-list/single-list-with-error-on-delete.json')

const LAMBDA_COMPANY_ID = '0fb3379c-341c-4da4-b825-bf8d47b26baa'

exports.companyList = function (req, res) {
  res.json(companyList)
}

exports.getCompanyLists = function (req, res) {
  if (req.query.items__company_id == LAMBDA_COMPANY_ID) {
    return res.json(filteredCompanyLists)
  }
  return res.json(companyLists)
}

exports.getCompanyList = function (req, res) {
  if (req.params.listId === multipleItemCompanyList.id) {
    res.json(multipleItemCompanyList)
    return
  }

  if (req.params.listId === errorOnDeleteCompanyList.id) {
    res.json(errorOnDeleteCompanyList)
    return
  }

  res.sendStatus(404)
}

exports.getCompanyListItems = function (req, res) {
  return res.json(
    companyListsDB[req.params.listId] || {
      count: 0,
      next: null,
      previous: null,
      results: [],
    }
  )
}

exports.createCompanyList = function (req, res) {
  res.sendStatus(201)
}

exports.deleteCompanyList = function (req, res) {
  if (req.params.listId === multipleItemCompanyList.id) {
    res.sendStatus(204)
    return
  }

  res.sendStatus(404)
}

exports.editCompanyList = function (req, res) {
  if (req.params.listId === multipleItemCompanyList.id) {
    res.sendStatus(204)
    return
  }

  res.sendStatus(404)
}

exports.addCompanyToList = function (req, res) {
  res.sendStatus(204)
}

exports.removeCompanyFromList = function (req, res) {
  res.sendStatus(204)
}


text: /Applications/LibreOffice.app/Contents/MacOS/python calc_view.py &


text:
package example.service;

import example.repo.Customer247Repository;

import org.springframework.stereotype.Service;

@Service
public class Customer247Service {
	public Customer247Service(Customer247Repository repo) {}
}


text:
layout: page
title: Administration
---

# Administration

## Keeping Up to Date
See [Updating](updating.md).

## Viewing Activity
Monitor your system via the [Waiting For Caller (WFC)](../modding/wfc.md) screen and learn how to [monitoring logs](../troubleshooting/monitoring-logs.md).

## Managing Users
User management is currently handled via the [oputil CLI](oputil.md).

## Backing Up Your System
It is *highly* recommended to perform **regular backups** of your system. Nothing is worse than spending a lot of time setting up a system only to have to go away unexpectedly!

In general, simply creating a copy/archive of your system is enough for the default configuration. If you have changed default paths to point outside of your main ENiGMA½ installation take special care to ensure these are preserved as well. Database files may be in a state of flux when simply copying files. See [Database Backups](#database-backups) below for details on consistent backups.

### Database Backups
[SQLite's CLI backup command](https://sqlite.org/cli.html#special_commands_to_sqlite3_dot_commands_) can be used for creating database backup files. This can be performed as an additional step to a full backup to ensure the database is backed up in a consistent state (whereas simply copying the files does not make any guarantees).

As an example, consider the following Bash script that creates foo.sqlite3.backup files:

```bash
for dbfile in /path/to/enigma-bbs/db/*.sqlite3; do
    sqlite3 $dbfile ".backup '/path/to/db_backup/$(basename $dbfile).backup'"
done
```

### Backup Tools
There are many backup solutions available across all platforms. Configuration of such tools is outside the scope of this documentation. With that said, the author has had great success with [Borg](https://www.borgbackup.org/).

## General Maintenance Tasks
### Vacuuming Database Files
SQLite database files become less performant over time and waste space. It is recommended to periodically vacuum your databases. Before proceeding, you should make a backup!

Example:
```bash
sqlite3 ./db/message.sqlite3 "vacuum;"
```


text:
<title>Phing API Documentation</title><meta http-equiv="Content-Type" content="text/html; charset=utf-8"></meta><link rel="stylesheet" href="css/jquery-ui.css" type="text/css"></link><link rel="stylesheet" href="css/docblox/jquery-ui-1.8.16.custom.css" type="text/css"></link><link rel="stylesheet" href="css/jquery.treeview.css" type="text/css"></link><link rel="stylesheet" href="css/theme.css" type="text/css"></link>

                The following actions are supported in this diagram:

Zoom, you can use the scrollwheel, or double-click,
                        to zoom in or out

Move, you can move around by dragging
                        the Diagram


text:
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace MyHoard.Models.Server
{
    public class ServerCollection
    {
        public string id { get; set; }
        public string name { get; set; }
        public string description { get; set; }
        public List<string> tags { get; set; }
        public int items_number { get; set; }
        public string created_date { get; set; }
        public string modified_date { get; set; }

        public DateTime CreatedDate()
        {
            DateTime d = DateTime.MinValue;
            DateTime.TryParse(created_date, out d);
            return d;
        }
        public DateTime ModifiedDate()
        {
            DateTime d = DateTime.MinValue;
            DateTime.TryParse(modified_date, out d);
            return d;
        }

    }
}


text:
TBD

---

## The Real Meat: Advanced Topics

   1. [Debugging your work - Episode 1: turning it *ON*](#error_handling)

   1. [Error handling](#error_handling)

      1. [Error handling in the lexer](#error_handling)
      1. [Error handling in the parser](#error_handling)
      1. [Loving Living Dangerously: Messing with the Error Recovery mechanisms](#error_handling)

   1. [Debugging your work - Episode 2: customizing the parser](#error_handling)

   1. [Debugging *their* work - Episode 1: improving your error diagnostics and reporting to the grammar user](#error_handling)

   1. [Performance Considerations: Speed is what I need!](#speed_is_what_I_need)

      1. [Don't skimp on your Theory pages! Giving it raw to your grammar spec](#cleaning_out)
      1. [Cleaning out the parser kernel](#cleaning_out)
      1. [Cleaning out the lexer kernel](#cleaning_out)

   1. [Performance Considerations: Compact **Size** is what I crave!](#right_I_like_em_tight)

      1. [Don't skimp on your Theory pages! Giving it raw to your grammar spec](#cleaning_out)
      1. [Cleaning out the parser kernel](#cleaning_out)
      1. [Cleaning out the lexer kernel](#cleaning_out)
      1. [If you must: writing a 100% custom lexer](#cleaning_out)

1. [Debugging *their* work - Episode 2: stepping through a parse](#error_handling)

---


text:
package com.microsoft.azure.management.edgegateway.v2019_03_01.implementation;

import com.microsoft.azure.arm.collection.InnerSupportsDelete;
import retrofit2.Retrofit;
import com.google.common.reflect.TypeToken;
import com.microsoft.azure.AzureServiceFuture;
import com.microsoft.azure.CloudException;
import com.microsoft.azure.ListOperationCallback;
import com.microsoft.azure.Page;
import com.microsoft.azure.PagedList;
import com.microsoft.rest.ServiceCallback;
import com.microsoft.rest.ServiceFuture;
import com.microsoft.rest.ServiceResponse;
import com.microsoft.rest.Validator;
import java.io.IOException;
import java.util.List;
import okhttp3.ResponseBody;
import retrofit2.http.Body;
import retrofit2.http.GET;
import retrofit2.http.Header;
import retrofit2.http.Headers;
import retrofit2.http.HTTP;
import retrofit2.http.Path;
import retrofit2.http.PUT;
import retrofit2.http.Query;
import retrofit2.http.Url;
import retrofit2.Response;
import rx.functions.Func1;
import rx.Observable;

/**
 * An instance of this class provides access to all the operations defined
 * in Orders.
 */
public class OrdersInner implements InnerSupportsDelete<Void> {
    /** The Retrofit service to perform REST calls. */
    private OrdersService service;
    /** The service client containing this operation class. */
    private DataBoxEdgeManagementClientImpl client;

    /**
     * Initializes an instance of OrdersInner.
     *
     * @param retrofit the Retrofit instance built from a Retrofit Builder.
     * @param client the instance of the service client containing this operation class.
     */
    public OrdersInner(Retrofit retrofit, DataBoxEdgeManagementClientImpl client) {
        this.service = retrofit.create(OrdersService.class);
        this.client = client;
    }

    /**
     * The interface defining all the services for Orders to be
     * used by Retrofit to perform actually REST calls.
     */
    interface OrdersService {
        @Headers({ "Content-Type: application/json; charset=utf-8", "x-ms-logging-context: com.microsoft.azure.management.edgegateway.v2019_03_01.Orders listByDataBoxEdgeDevice" })
        @GET("subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DataBoxEdge/dataBoxEdgeDevices/{deviceName}/orders")
        Observable<Response<ResponseBody>> listByDataBoxEdgeDevice(@Path("deviceName") String deviceName, @Path("subscriptionId") String subscriptionId, @Path("resourceGroupName") String resourceGroupName, @Query("api-version") String apiVersion, @Header("accept-language") String acceptLanguage, @Header("User-Agent") String userAgent);

        @Headers({ "Content-Type: application/json; charset=utf-8", "x-ms-logging-context: com.microsoft.azure.management.edgegateway.v2019_03_01.Orders get" })
        @GET("subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DataBoxEdge/dataBoxEdgeDevices/{deviceName}/orders/default")
        Observable<Response<ResponseBody>> get(@Path("deviceName") String deviceName, @Path("subscriptionId") String subscriptionId, @Path("resourceGroupName") String resourceGroupName, @Query("api-version") String apiVersion, @Header("accept-language") String acceptLanguage, @Header("User-Agent") String userAgent);

        @Headers({ "Content-Type: application/json; charset=utf-8", "x-ms-logging-context: com.microsoft.azure.management.edgegateway.v2019_03_01.Orders createOrUpdate" })
        @PUT("subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DataBoxEdge/dataBoxEdgeDevices/{deviceName}/orders/default")
        Observable<Response<ResponseBody>> createOrUpdate(@Path("deviceName") String deviceName, @Path("subscriptionId") String subscriptionId, @Path("resourceGroupName") String resourceGroupName, @Body OrderInner order, @Query("api-version") String apiVersion, @Header("accept-language") String acceptLanguage, @Header("User-Agent") String userAgent);

        @Headers({ "Content-Type: application/json; charset=utf-8", "x-ms-logging-context: com.microsoft.azure.management.edgegateway.v2019_03_01.Orders beginCreateOrUpdate" })
        @PUT("subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DataBoxEdge/dataBoxEdgeDevices/{deviceName}/orders/default")
        Observable<Response<ResponseBody>> beginCreateOrUpdate(@Path("deviceName") String deviceName, @Path("subscriptionId") String subscriptionId, @Path("resourceGroupName") String resourceGroupName, @Body OrderInner order, @Query("api-version") String apiVersion, @Header("accept-language") String acceptLanguage, @Header("User-Agent") String userAgent);

        @Headers({ "Content-Type: application/json; charset=utf-8", "x-ms-logging-context: com.microsoft.azure.management.edgegateway.v2019_03_01.Orders delete" })
        @HTTP(path = "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DataBoxEdge/dataBoxEdgeDevices/{deviceName}/orders/default", method = "DELETE", hasBody = true)
        Observable<Response<ResponseBody>> delete(@Path("deviceName") String deviceName, @Path("subscriptionId") String subscriptionId, @Path("resourceGroupName") String resourceGroupName, @Query("api-version") String apiVersion, @Header("accept-language") String acceptLanguage, @Header("User-Agent") String userAgent);

        @Headers({ "Content-Type: application/json; charset=utf-8", "x-ms-logging-context: com.microsoft.azure.management.edgegateway.v2019_03_01.Orders beginDelete" })
        @HTTP(path = "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DataBoxEdge/dataBoxEdgeDevices/{deviceName}/orders/default", method = "DELETE", hasBody = true)
        Observable<Response<ResponseBody>> beginDelete(@Path("deviceName") String deviceName, @Path("subscriptionId") String subscriptionId, @Path("resourceGroupName") String resourceGroupName, @Query("api-version") String apiVersion, @Header("accept-language") String acceptLanguage, @Header("User-Agent") String userAgent);

        @Headers({ "Content-Type: application/json; charset=utf-8", "x-ms-logging-context: com.microsoft.azure.management.edgegateway.v2019_03_01.Orders listByDataBoxEdgeDeviceNext" })
        @GET
        Observable<Response<ResponseBody>> listByDataBoxEdgeDeviceNext(@Url String nextUrl, @Header("accept-language") String acceptLanguage, @Header("User-Agent") String userAgent);

    }

    /**
     * Lists all the orders related to a data box edge/gateway device.
     *
     * @param deviceName The device name.
     * @param resourceGroupName The resource group name.
     * @throws IllegalArgumentException thrown if parameters fail the validation
     * @throws CloudException thrown if the request is rejected by server
     * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent
     * @return the PagedList<OrderInner> object if successful.
     */
    public PagedList<OrderInner> listByDataBoxEdgeDevice(final String deviceName, final String resourceGroupName) {
        ServiceResponse<Page<OrderInner>> response = listByDataBoxEdgeDeviceSinglePageAsync(deviceName, resourceGroupName).toBlocking().single();
        return new PagedList<OrderInner>(response.body()) {
            @Override
            public Page<OrderInner> nextPage(String nextPageLink) {
                return listByDataBoxEdgeDeviceNextSinglePageAsync(nextPageLink).toBlocking().single().body();
            }
        };
    }

    /**
     * Lists all the orders related to a data box edge/gateway device.
     *
     * @param deviceName The device name.
     * @param resourceGroupName The resource group name.
     * @param serviceCallback the async ServiceCallback to handle successful and failed responses.
     * @throws IllegalArgumentException thrown if parameters fail the validation
     * @return the {@link ServiceFuture} object
     */
    public ServiceFuture<List<OrderInner>> listByDataBoxEdgeDeviceAsync(final String deviceName, final String resourceGroupName, final ListOperationCallback<OrderInner> serviceCallback) {
        return AzureServiceFuture.fromPageResponse(
            listByDataBoxEdgeDeviceSinglePageAsync(deviceName, resourceGroupName),
            new Func1<String, Observable<ServiceResponse<Page<OrderInner>>>>() {
                @Override
                public Observable<ServiceResponse<Page<OrderInner>>> call(String nextPageLink) {
                    return listByDataBoxEdgeDeviceNextSinglePageAsync(nextPageLink);
                }
            },
            serviceCallback);
    }

    /**
     * Lists all the orders related to a data box edge/gateway device.
     *
     * @param deviceName The device name.
     * @param resourceGroupName The resource group name.
     * @throws IllegalArgumentException thrown if parameters fail the validation
     * @return the observable to the PagedList<OrderInner> object
     */
    public Observable<Page<OrderInner>> listByDataBoxEdgeDeviceAsync(final String deviceName, final String resourceGroupName) {
        return listByDataBoxEdgeDeviceWithServiceResponseAsync(deviceName, resourceGroupName)
            .map(new Func1<ServiceResponse<Page<OrderInner>>, Page<OrderInner>>() {
                @Override
                public Page<OrderInner> call(ServiceResponse<Page<OrderInner>> response) {
                    return response.body();
                }
            });
    }

    /**
     * Lists all the orders related to a data box edge/gateway device.
     *
     * @param deviceName The device name.
     * @param resourceGroupName The resource group name.
     * @throws IllegalArgumentException thrown if parameters fail the validation
     * @return the observable to the PagedList<OrderInner> object
     */
    public Observable<ServiceResponse<Page<OrderInner>>> listByDataBoxEdgeDeviceWithServiceResponseAsync(final String deviceName, final String resourceGroupName) {
        return listByDataBoxEdgeDeviceSinglePageAsync(deviceName, resourceGroupName)
            .concatMap(new Func1<ServiceResponse<Page<OrderInner>>, Observable<ServiceResponse<Page<OrderInner>>>>() {
                @Override
                public Observable<ServiceResponse<Page<OrderInner>>> call(ServiceResponse<Page<OrderInner>> page) {
                    String nextPageLink = page.body().nextPageLink();
                    if (nextPageLink == null) {
                        return Observable.just(page);
                    }
                    return Observable.just(page).concatWith(listByDataBoxEdgeDeviceNextWithServiceResponseAsync(nextPageLink));
                }
            });
    }

    /**
     * Lists all the orders related to a data box edge/gateway device.
     *
    ServiceResponse<PageImpl<OrderInner>> * @param deviceName The device name.
    ServiceResponse<PageImpl<OrderInner>> * @param resourceGroupName The resource group name.
     * @throws IllegalArgumentException thrown if parameters fail the validation
     * @return the PagedList<OrderInner> object wrapped in {@link ServiceResponse} if successful.
     */
    public Observable<ServiceResponse<Page<OrderInner>>> listByDataBoxEdgeDeviceSinglePageAsync(final String deviceName, final String resourceGroupName) {
        if (deviceName == null) {
            throw new IllegalArgumentException("Parameter deviceName is required and cannot be null.");
        }
        if (this.client.subscriptionId() == null) {
            throw new IllegalArgumentException("Parameter this.client.subscriptionId() is required and cannot be null.");
        }
        if (resourceGroupName == null) {
            throw new IllegalArgumentException("Parameter resourceGroupName is required and cannot be null.");
        }
        if (this.client.apiVersion() == null) {
            throw new IllegalArgumentException("Parameter this.client.apiVersion() is required and cannot be null.");
        }
        return service.listByDataBoxEdgeDevice(deviceName, this.client.subscriptionId(), resourceGroupName, this.client.apiVersion(), this.client.acceptLanguage(), this.client.userAgent())
            .flatMap(new Func1<Response<ResponseBody>, Observable<ServiceResponse<Page<OrderInner>>>>() {
                @Override
                public Observable<ServiceResponse<Page<OrderInner>>> call(Response<ResponseBody> response) {
                    try {
                        ServiceResponse<PageImpl<OrderInner>> result = listByDataBoxEdgeDeviceDelegate(response);
                        return Observable.just(new ServiceResponse<Page<OrderInner>>(result.body(), result.response()));
                    } catch (Throwable t) {
                        return Observable.error(t);
                    }
                }
            });
    }

    private ServiceResponse<PageImpl<OrderInner>> listByDataBoxEdgeDeviceDelegate(Response<ResponseBody> response) throws CloudException, IOException, IllegalArgumentException {
        return this.client.restClient().responseBuilderFactory().<PageImpl<OrderInner>, CloudException>newInstance(this.client.serializerAdapter())
                .register(200, new TypeToken<PageImpl<OrderInner>>() { }.getType())
                .registerError(CloudException.class)
                .build(response);
    }

    /**
     * Gets a specific order by name.
     *
     * @param deviceName The device name.
     * @param resourceGroupName The resource group name.
     * @throws IllegalArgumentException thrown if parameters fail the validation
     * @throws CloudException thrown if the request is rejected by server
     * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent
     * @return the OrderInner object if successful.
     */
    public OrderInner get(String deviceName, String resourceGroupName) {
        return getWithServiceResponseAsync(deviceName, resourceGroupName).toBlocking().single().body();
    }

    /**
     * Gets a specific order by name.
     *
     * @param deviceName The device name.
     * @param resourceGroupName The resource group name.
     * @param serviceCallback the async ServiceCallback to handle successful and failed responses.
     * @throws IllegalArgumentException thrown if parameters fail the validation
     * @return the {@link ServiceFuture} object
     */
    public ServiceFuture<OrderInner> getAsync(String deviceName, String resourceGroupName, final ServiceCallback<OrderInner> serviceCallback) {
        return ServiceFuture.fromResponse(getWithServiceResponseAsync(deviceName, resourceGroupName), serviceCallback);
    }

    /**
     * Gets a specific order by name.
     *
     * @param deviceName The device name.
     * @param resourceGroupName The resource group name.
     * @throws IllegalArgumentException thrown if parameters fail the validation
     * @return the observable to the OrderInner object
     */
    public Observable<OrderInner> getAsync(String deviceName, String resourceGroupName) {
        return getWithServiceResponseAsync(deviceName, resourceGroupName).map(new Func1<ServiceResponse<OrderInner>, OrderInner>() {
            @Override
            public OrderInner call(ServiceResponse<OrderInner> response) {
                return response.body();
            }
        });
    }

    /**
     * Gets a specific order by name.
     *
     * @param deviceName The device name.
     * @param resourceGroupName The resource group name.
     * @throws IllegalArgumentException thrown if parameters fail the validation
     * @return the observable to the OrderInner object
     */
    public Observable<ServiceResponse<OrderInner>> getWithServiceResponseAsync(String deviceName, String resourceGroupName) {
        if (deviceName == null) {
            throw new IllegalArgumentException("Parameter deviceName is required and cannot be null.");
        }
        if (this.client.subscriptionId() == null) {
            throw new IllegalArgumentException("Parameter this.client.subscriptionId() is required and cannot be null.");
        }
        if (resourceGroupName == null) {
            throw new IllegalArgumentException("Parameter resourceGroupName is required and cannot be null.");
        }
        if (this.client.apiVersion() == null) {
            throw new IllegalArgumentException("Parameter this.client.apiVersion() is required and cannot be null.");
        }
        return service.get(deviceName, this.client.subscriptionId(), resourceGroupName, this.client.apiVersion(), this.client.acceptLanguage(), this.client.userAgent())
            .flatMap(new Func1<Response<ResponseBody>, Observable<ServiceResponse<OrderInner>>>() {
                @Override
                public Observable<ServiceResponse<OrderInner>> call(Response<ResponseBody> response) {
                    try {
                        ServiceResponse<OrderInner> clientResponse = getDelegate(response);
                        return Observable.just(clientResponse);
                    } catch (Throwable t) {
                        return Observable.error(t);
                    }
                }
            });
    }

    private ServiceResponse<OrderInner> getDelegate(Response<ResponseBody> response) throws CloudException, IOException, IllegalArgumentException {
        return this.client.restClient().responseBuilderFactory().<OrderInner, CloudException>newInstance(this.client.serializerAdapter())
                .register(200, new TypeToken<OrderInner>() { }.getType())
                .registerError(CloudException.class)
                .build(response);
    }

    /**
     * Creates or updates an order.
     *
     * @param deviceName The device name.
     * @param resourceGroupName The resource group name.
     * @param order The order to be created or updated.
     * @throws IllegalArgumentException thrown if parameters fail the validation
     * @throws CloudException thrown if the request is rejected by server
     * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent
     * @return the OrderInner object if successful.
     */
    public OrderInner createOrUpdate(String deviceName, String resourceGroupName, OrderInner order) {
        return createOrUpdateWithServiceResponseAsync(deviceName, resourceGroupName, order).toBlocking().last().body();
    }

    /**
     * Creates or updates an order.
     *
     * @param deviceName The device name.
     * @param resourceGroupName The resource group name.
     * @param order The order to be created or updated.
     * @param serviceCallback the async ServiceCallback to handle successful and failed responses.
     * @throws IllegalArgumentException thrown if parameters fail the validation
     * @return the {@link ServiceFuture} object
     */
    public ServiceFuture<OrderInner> createOrUpdateAsync(String deviceName, String resourceGroupName, OrderInner order, final ServiceCallback<OrderInner> serviceCallback) {
        return ServiceFuture.fromResponse(createOrUpdateWithServiceResponseAsync(deviceName, resourceGroupName, order), serviceCallback);
    }

    /**
     * Creates or updates an order.
     *
     * @param deviceName The device name.
     * @param resourceGroupName The resource group name.
     * @param order The order to be created or updated.
     * @throws IllegalArgumentException thrown if parameters fail the validation
     * @return the observable for the request
     */
    public Observable<OrderInner> createOrUpdateAsync(String deviceName, String resourceGroupName, OrderInner order) {
        return createOrUpdateWithServiceResponseAsync(deviceName, resourceGroupName, order).map(new Func1<ServiceResponse<OrderInner>, OrderInner>() {
            @Override
            public OrderInner call(ServiceResponse<OrderInner> response) {
                return response.body();
            }
        });
    }

    /**
     * Creates or updates an order.
     *
     * @param deviceName The device name.
     * @param resourceGroupName The resource group name.
     * @param order The order to be created or updated.
     * @throws IllegalArgumentException thrown if parameters fail the validation
     * @return the observable for the request
     */
    public Observable<ServiceResponse<OrderInner>> createOrUpdateWithServiceResponseAsync(String deviceName, String resourceGroupName, OrderInner order) {
        if (deviceName == null) {
            throw new IllegalArgumentException("Parameter deviceName is required and cannot be null.");
        }
        if (this.client.subscriptionId() == null) {
            throw new IllegalArgumentException("Parameter this.client.subscriptionId() is required and cannot be null.");
        }
        if (resourceGroupName == null) {
            throw new IllegalArgumentException("Parameter resourceGroupName is required and cannot be null.");
        }
        if (order == null) {
            throw new IllegalArgumentException("Parameter order is required and cannot be null.");
        }
        if (this.client.apiVersion() == null) {
            throw new IllegalArgumentException("Parameter this.client.apiVersion() is required and cannot be null.");
        }
        Validator.validate(order);
        Observable<Response<ResponseBody>> observable = service.createOrUpdate(deviceName, this.client.subscriptionId(), resourceGroupName, order, this.client.apiVersion(), this.client.acceptLanguage(), this.client.userAgent());
        return client.getAzureClient().getPutOrPatchResultAsync(observable, new TypeToken<OrderInner>() { }.getType());
    }

    /**
     * Creates or updates an order.
     *
     * @param deviceName The device name.
     * @param resourceGroupName The resource group name.
     * @param order The order to be created or updated.
     * @throws IllegalArgumentException thrown if parameters fail the validation
     * @throws CloudException thrown if the request is rejected by server
     * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent
     * @return the OrderInner object if successful.
     */
    public OrderInner beginCreateOrUpdate(String deviceName, String resourceGroupName, OrderInner order) {
        return beginCreateOrUpdateWithServiceResponseAsync(deviceName, resourceGroupName, order).toBlocking().single().body();
    }

    /**
     * Creates or updates an order.
     *
     * @param deviceName The device name.
     * @param resourceGroupName The resource group name.
     * @param order The order to be created or updated.
     * @param serviceCallback the async ServiceCallback to handle successful and failed responses.
     * @throws IllegalArgumentException thrown if parameters fail the validation
     * @return the {@link ServiceFuture} object
     */
    public ServiceFuture<OrderInner> beginCreateOrUpdateAsync(String deviceName, String resourceGroupName, OrderInner order, final ServiceCallback<OrderInner> serviceCallback) {
        return ServiceFuture.fromResponse(beginCreateOrUpdateWithServiceResponseAsync(deviceName, resourceGroupName, order), serviceCallback);
    }

    /**
     * Creates or updates an order.
     *
     * @param deviceName The device name.
     * @param resourceGroupName The resource group name.
     * @param order The order to be created or updated.
     * @throws IllegalArgumentException thrown if parameters fail the validation
     * @return the observable to the OrderInner object
     */
    public Observable<OrderInner> beginCreateOrUpdateAsync(String deviceName, String resourceGroupName, OrderInner order) {
        return beginCreateOrUpdateWithServiceResponseAsync(deviceName, resourceGroupName, order).map(new Func1<ServiceResponse<OrderInner>, OrderInner>() {
            @Override
            public OrderInner call(ServiceResponse<OrderInner> response) {
                return response.body();
            }
        });
    }

    /**
     * Creates or updates an order.
     *
     * @param deviceName The device name.
     * @param resourceGroupName The resource group name.
     * @param order The order to be created or updated.
     * @throws IllegalArgumentException thrown if parameters fail the validation
     * @return the observable to the OrderInner object
     */
    public Observable<ServiceResponse<OrderInner>> beginCreateOrUpdateWithServiceResponseAsync(String deviceName, String resourceGroupName, OrderInner order) {
        if (deviceName == null) {
            throw new IllegalArgumentException("Parameter deviceName is required and cannot be null.");
        }
        if (this.client.subscriptionId() == null) {
            throw new IllegalArgumentException("Parameter this.client.subscriptionId() is required and cannot be null.");
        }
        if (resourceGroupName == null) {
            throw new IllegalArgumentException("Parameter resourceGroupName is required and cannot be null.");
        }
        if (order == null) {
            throw new IllegalArgumentException("Parameter order is required and cannot be null.");
        }
        if (this.client.apiVersion() == null) {
            throw new IllegalArgumentException("Parameter this.client.apiVersion() is required and cannot be null.");
        }
        Validator.validate(order);
        return service.beginCreateOrUpdate(deviceName, this.client.subscriptionId(), resourceGroupName, order, this.client.apiVersion(), this.client.acceptLanguage(), this.client.userAgent())
            .flatMap(new Func1<Response<ResponseBody>, Observable<ServiceResponse<OrderInner>>>() {
                @Override
                public Observable<ServiceResponse<OrderInner>> call(Response<ResponseBody> response) {
                    try {
                        ServiceResponse<OrderInner> clientResponse = beginCreateOrUpdateDelegate(response);
                        return Observable.just(clientResponse);
                    } catch (Throwable t) {
                        return Observable.error(t);
                    }
                }
            });
    }

    private ServiceResponse<OrderInner> beginCreateOrUpdateDelegate(Response<ResponseBody> response) throws CloudException, IOException, IllegalArgumentException {
        return this.client.restClient().responseBuilderFactory().<OrderInner, CloudException>newInstance(this.client.serializerAdapter())
                .register(200, new TypeToken<OrderInner>() { }.getType())
                .register(202, new TypeToken<Void>() { }.getType())
                .registerError(CloudException.class)
                .build(response);
    }

    /**
     * Deletes the order related to the device.
     *
     * @param deviceName The device name.
     * @param resourceGroupName The resource group name.
     * @throws IllegalArgumentException thrown if parameters fail the validation
     * @throws CloudException thrown if the request is rejected by server
     * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent
     */
    public void delete(String deviceName, String resourceGroupName) {
        deleteWithServiceResponseAsync(deviceName, resourceGroupName).toBlocking().last().body();
    }

    /**
     * Deletes the order related to the device.
     *
     * @param deviceName The device name.
     * @param resourceGroupName The resource group name.
     * @param serviceCallback the async ServiceCallback to handle successful and failed responses.
     * @throws IllegalArgumentException thrown if parameters fail the validation
     * @return the {@link ServiceFuture} object
     */
    public ServiceFuture<Void> deleteAsync(String deviceName, String resourceGroupName, final ServiceCallback<Void> serviceCallback) {
        return ServiceFuture.fromResponse(deleteWithServiceResponseAsync(deviceName, resourceGroupName), serviceCallback);
    }

    /**
     * Deletes the order related to the device.
     *
     * @param deviceName The device name.
     * @param resourceGroupName The resource group name.
     * @throws IllegalArgumentException thrown if parameters fail the validation
     * @return the observable for the request
     */
    public Observable<Void> deleteAsync(String deviceName, String resourceGroupName) {
        return deleteWithServiceResponseAsync(deviceName, resourceGroupName).map(new Func1<ServiceResponse<Void>, Void>() {
            @Override
            public Void call(ServiceResponse<Void> response) {
                return response.body();
            }
        });
    }

    /**
     * Deletes the order related to the device.
     *
     * @param deviceName The device name.
     * @param resourceGroupName The resource group name.
     * @throws IllegalArgumentException thrown if parameters fail the validation
     * @return the observable for the request
     */
    public Observable<ServiceResponse<Void>> deleteWithServiceResponseAsync(String deviceName, String resourceGroupName) {
        if (deviceName == null) {
            throw new IllegalArgumentException("Parameter deviceName is required and cannot be null.");
        }
        if (this.client.subscriptionId() == null) {
            throw new IllegalArgumentException("Parameter this.client.subscriptionId() is required and cannot be null.");
        }
        if (resourceGroupName == null) {
            throw new IllegalArgumentException("Parameter resourceGroupName is required and cannot be null.");
        }
        if (this.client.apiVersion() == null) {
            throw new IllegalArgumentException("Parameter this.client.apiVersion() is required and cannot be null.");
        }
        Observable<Response<ResponseBody>> observable = service.delete(deviceName, this.client.subscriptionId(), resourceGroupName, this.client.apiVersion(), this.client.acceptLanguage(), this.client.userAgent());
        return client.getAzureClient().getPostOrDeleteResultAsync(observable, new TypeToken<Void>() { }.getType());
    }

    /**
     * Deletes the order related to the device.
     *
     * @param deviceName The device name.
     * @param resourceGroupName The resource group name.
     * @throws IllegalArgumentException thrown if parameters fail the validation
     * @throws CloudException thrown if the request is rejected by server
     * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent
     */
    public void beginDelete(String deviceName, String resourceGroupName) {
        beginDeleteWithServiceResponseAsync(deviceName, resourceGroupName).toBlocking().single().body();
    }

    /**
     * Deletes the order related to the device.
     *
     * @param deviceName The device name.
     * @param resourceGroupName The resource group name.
     * @param serviceCallback the async ServiceCallback to handle successful and failed responses.
     * @throws IllegalArgumentException thrown if parameters fail the validation
     * @return the {@link ServiceFuture} object
     */
    public ServiceFuture<Void> beginDeleteAsync(String deviceName, String resourceGroupName, final ServiceCallback<Void> serviceCallback) {
        return ServiceFuture.fromResponse(beginDeleteWithServiceResponseAsync(deviceName, resourceGroupName), serviceCallback);
    }

    /**
     * Deletes the order related to the device.
     *
     * @param deviceName The device name.
     * @param resourceGroupName The resource group name.
     * @throws IllegalArgumentException thrown if parameters fail the validation
     * @return the {@link ServiceResponse} object if successful.
     */
    public Observable<Void> beginDeleteAsync(String deviceName, String resourceGroupName) {
        return beginDeleteWithServiceResponseAsync(deviceName, resourceGroupName).map(new Func1<ServiceResponse<Void>, Void>() {
            @Override
            public Void call(ServiceResponse<Void> response) {
                return response.body();
            }
        });
    }

    /**
     * Deletes the order related to the device.
     *
     * @param deviceName The device name.
     * @param resourceGroupName The resource group name.
     * @throws IllegalArgumentException thrown if parameters fail the validation
     * @return the {@link ServiceResponse} object if successful.
     */
    public Observable<ServiceResponse<Void>> beginDeleteWithServiceResponseAsync(String deviceName, String resourceGroupName) {
        if (deviceName == null) {
            throw new IllegalArgumentException("Parameter deviceName is required and cannot be null.");
        }
        if (this.client.subscriptionId() == null) {
            throw new IllegalArgumentException("Parameter this.client.subscriptionId() is required and cannot be null.");
        }
        if (resourceGroupName == null) {
            throw new IllegalArgumentException("Parameter resourceGroupName is required and cannot be null.");
        }
        if (this.client.apiVersion() == null) {
            throw new IllegalArgumentException("Parameter this.client.apiVersion() is required and cannot be null.");
        }
        return service.beginDelete(deviceName, this.client.subscriptionId(), resourceGroupName, this.client.apiVersion(), this.client.acceptLanguage(), this.client.userAgent())
            .flatMap(new Func1<Response<ResponseBody>, Observable<ServiceResponse<Void>>>() {
                @Override
                public Observable<ServiceResponse<Void>> call(Response<ResponseBody> response) {
                    try {
                        ServiceResponse<Void> clientResponse = beginDeleteDelegate(response);
                        return Observable.just(clientResponse);
                    } catch (Throwable t) {
                        return Observable.error(t);
                    }
                }
            });
    }

    private ServiceResponse<Void> beginDeleteDelegate(Response<ResponseBody> response) throws CloudException, IOException, IllegalArgumentException {
        return this.client.restClient().responseBuilderFactory().<Void, CloudException>newInstance(this.client.serializerAdapter())
                .register(200, new TypeToken<Void>() { }.getType())
                .register(202, new TypeToken<Void>() { }.getType())
                .register(204, new TypeToken<Void>() { }.getType())
                .registerError(CloudException.class)
                .build(response);
    }

    /**
     * Lists all the orders related to a data box edge/gateway device.
     *
     * @param nextPageLink The NextLink from the previous successful call to List operation.
     * @throws IllegalArgumentException thrown if parameters fail the validation
     * @throws CloudException thrown if the request is rejected by server
     * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent
     * @return the PagedList<OrderInner> object if successful.
     */
    public PagedList<OrderInner> listByDataBoxEdgeDeviceNext(final String nextPageLink) {
        ServiceResponse<Page<OrderInner>> response = listByDataBoxEdgeDeviceNextSinglePageAsync(nextPageLink).toBlocking().single();
        return new PagedList<OrderInner>(response.body()) {
            @Override
            public Page<OrderInner> nextPage(String nextPageLink) {
                return listByDataBoxEdgeDeviceNextSinglePageAsync(nextPageLink).toBlocking().single().body();
            }
        };
    }

    /**
     * Lists all the orders related to a data box edge/gateway device.
     *
     * @param nextPageLink The NextLink from the previous successful call to List operation.
     * @param serviceFuture the ServiceFuture object tracking the Retrofit calls
     * @param serviceCallback the async ServiceCallback to handle successful and failed responses.
     * @throws IllegalArgumentException thrown if parameters fail the validation
     * @return the {@link ServiceFuture} object
     */
    public ServiceFuture<List<OrderInner>> listByDataBoxEdgeDeviceNextAsync(final String nextPageLink, final ServiceFuture<List<OrderInner>> serviceFuture, final ListOperationCallback<OrderInner> serviceCallback) {
        return AzureServiceFuture.fromPageResponse(
            listByDataBoxEdgeDeviceNextSinglePageAsync(nextPageLink),
            new Func1<String, Observable<ServiceResponse<Page<OrderInner>>>>() {
                @Override
                public Observable<ServiceResponse<Page<OrderInner>>> call(String nextPageLink) {
                    return listByDataBoxEdgeDeviceNextSinglePageAsync(nextPageLink);
                }
            },
            serviceCallback);
    }

    /**
     * Lists all the orders related to a data box edge/gateway device.
     *
     * @param nextPageLink The NextLink from the previous successful call to List operation.
     * @throws IllegalArgumentException thrown if parameters fail the validation
     * @return the observable to the PagedList<OrderInner> object
     */
    public Observable<Page<OrderInner>> listByDataBoxEdgeDeviceNextAsync(final String nextPageLink) {
        return listByDataBoxEdgeDeviceNextWithServiceResponseAsync(nextPageLink)
            .map(new Func1<ServiceResponse<Page<OrderInner>>, Page<OrderInner>>() {
                @Override
                public Page<OrderInner> call(ServiceResponse<Page<OrderInner>> response) {
                    return response.body();
                }
            });
    }

    /**
     * Lists all the orders related to a data box edge/gateway device.
     *
     * @param nextPageLink The NextLink from the previous successful call to List operation.
     * @throws IllegalArgumentException thrown if parameters fail the validation
     * @return the observable to the PagedList<OrderInner> object
     */
    public Observable<ServiceResponse<Page<OrderInner>>> listByDataBoxEdgeDeviceNextWithServiceResponseAsync(final String nextPageLink) {
        return listByDataBoxEdgeDeviceNextSinglePageAsync(nextPageLink)
            .concatMap(new Func1<ServiceResponse<Page<OrderInner>>, Observable<ServiceResponse<Page<OrderInner>>>>() {
                @Override
                public Observable<ServiceResponse<Page<OrderInner>>> call(ServiceResponse<Page<OrderInner>> page) {
                    String nextPageLink = page.body().nextPageLink();
                    if (nextPageLink == null) {
                        return Observable.just(page);
                    }
                    return Observable.just(page).concatWith(listByDataBoxEdgeDeviceNextWithServiceResponseAsync(nextPageLink));
                }
            });
    }

    /**
     * Lists all the orders related to a data box edge/gateway device.
     *
    ServiceResponse<PageImpl<OrderInner>> * @param nextPageLink The NextLink from the previous successful call to List operation.
     * @throws IllegalArgumentException thrown if parameters fail the validation
     * @return the PagedList<OrderInner> object wrapped in {@link ServiceResponse} if successful.
     */
    public Observable<ServiceResponse<Page<OrderInner>>> listByDataBoxEdgeDeviceNextSinglePageAsync(final String nextPageLink) {
        if (nextPageLink == null) {
            throw new IllegalArgumentException("Parameter nextPageLink is required and cannot be null.");
        }
        String nextUrl = String.format("%s", nextPageLink);
        return service.listByDataBoxEdgeDeviceNext(nextUrl, this.client.acceptLanguage(), this.client.userAgent())
            .flatMap(new Func1<Response<ResponseBody>, Observable<ServiceResponse<Page<OrderInner>>>>() {
                @Override
                public Observable<ServiceResponse<Page<OrderInner>>> call(Response<ResponseBody> response) {
                    try {
                        ServiceResponse<PageImpl<OrderInner>> result = listByDataBoxEdgeDeviceNextDelegate(response);
                        return Observable.just(new ServiceResponse<Page<OrderInner>>(result.body(), result.response()));
                    } catch (Throwable t) {
                        return Observable.error(t);
                    }
                }
            });
    }

    private ServiceResponse<PageImpl<OrderInner>> listByDataBoxEdgeDeviceNextDelegate(Response<ResponseBody> response) throws CloudException, IOException, IllegalArgumentException {
        return this.client.restClient().responseBuilderFactory().<PageImpl<OrderInner>, CloudException>newInstance(this.client.serializerAdapter())
                .register(200, new TypeToken<PageImpl<OrderInner>>() { }.getType())
                .registerError(CloudException.class)
                .build(response);
    }

}


text:
layout: page
title: Boyd Chemical Show
date: 2016-05-24
author: Nancy Gillespie
tags: weekly links, java
status: published
summary: Maecenas hendrerit placerat ligula, vel dictum ante.
banner: images/banner/leisure-01.jpg
booking:
  startDate: 04/20/2019
  endDate: 04/25/2019
  ctyhocn: LAXHTHX
  groupCode: BCS
published: true
---
Aenean mollis augue at risus consectetur, id tincidunt magna vulputate. Suspendisse nibh est, lacinia eu ante et, consectetur sagittis ligula. Etiam vitae mollis ligula. Praesent ac pretium neque. Fusce faucibus est eu velit maximus, vitae pulvinar nulla vehicula. Aliquam ac tellus eros. Cras et turpis ac magna maximus mollis efficitur ac mauris. Nulla at faucibus velit, eu consequat est. Aenean nisl est, sollicitudin ac tortor eget, molestie finibus tortor. Quisque imperdiet leo nec quam sagittis, at venenatis massa commodo.

* Fusce semper nisl in scelerisque semper
* Nulla vitae ex tincidunt, bibendum arcu ut, maximus turpis
* Nulla in nisi et purus sodales finibus non tempor nibh.

Phasellus commodo ornare malesuada. Curabitur rutrum eros et convallis venenatis. Nulla ultrices tortor in dictum consequat. Class aptent taciti sociosqu ad litora torquent per conubia nostra, per inceptos himenaeos. Proin non ipsum non massa molestie consequat. Phasellus lacinia odio eu sodales semper. Fusce sit amet sem id velit finibus sagittis eu a tortor. Aenean in hendrerit risus, sed finibus turpis. Morbi faucibus, diam eget sodales egestas, enim eros scelerisque neque, sed porta velit quam in nunc. Pellentesque commodo odio orci, non pulvinar justo ullamcorper id. Nullam euismod fringilla ante non pharetra. Donec aliquet tincidunt sodales.
Morbi faucibus eu dolor at tristique. Maecenas porttitor quam diam, pharetra feugiat leo gravida varius. Sed venenatis lectus nec venenatis dignissim. Quisque ullamcorper mattis augue, id semper neque lobortis eget. Nunc tincidunt rutrum enim, at bibendum mauris vestibulum quis. Lorem ipsum dolor sit amet, consectetur adipiscing elit. Maecenas fringilla nulla elit, auctor pharetra nulla efficitur bibendum. Proin finibus magna sit amet tristique rutrum.


text:
require 'validator/utils'

describe Validator::Utils do
  describe '#clean_non_utf8_chars' do
  end
end


text:
<?php

namespace Mind\MediaBundle\Form\Type;

use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\OptionsResolver\OptionsResolverInterface;

class AbonnementDomaineType extends AbstractType
{
    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        $builder
            ->add('idUser', 'hidden')
            ->add('idDomaine', 'hidden')
        ;
    }

    public function setDefaultOptions(OptionsResolverInterface $resolver)
    {
        $resolver->setDefaults(array(
            'data_class' => 'Mind\MediaBundle\Entity\AbonnementDomaine'
        ));
    }

    public function getName()
    {
        return 'mind_mediabundle_abonnementdomainetype';
    }
}


text:
package org.rocko.demos.mvp.presenter;

/**
 * Created by Administrator on 2015/2/6.
 * 天气 Presenter接口
 */
public interface WeatherPresenter {
    /**
     * 获取天气的逻辑
     */
    void getWeather(String cityNO);

}


text:
// Copyright 2022 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

package org.chromium.chrome.browser.privacy_sandbox;

import androidx.annotation.IntDef;

import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;

/**
 * Indicates in which context the Privacy Sandbox dialog was launched.
 */
@IntDef({PrivacySandboxDialogLaunchContext.BROWSER_START,
        PrivacySandboxDialogLaunchContext.NEW_TAB_PAGE})
@Retention(RetentionPolicy.SOURCE)
public @interface PrivacySandboxDialogLaunchContext {
    /**
     * Corresponds to all the prompts shown on browser start.
     */
    int BROWSER_START = 0;
    /**
     * Corresponds to the bottom sheet notice on the NTP.
     */
    int NEW_TAB_PAGE = 1;
    int COUNT = 2;
}


text:
import json

from django.http import HttpResponse

def dynamic_api_one(request, dynamic_id):
    """
    Just an example api to check the dynamic part of the url is working correctly
    and is passed into the api function
    """

    return HttpResponse(json.dumps({"dynamicValue": dynamic_id}), content_type="application/json")

def dynamic_api_two(request, dynamic_id, dynamic_id_2):
    """
    Example api to check multiple dynamic values are passed through to the function correctly from a url
    """

    return HttpResponse(json.dumps({"dynamicValueOne": dynamic_id, "dynamicValueTwo": dynamic_id_2}), content_type="application/json")

def regular_api(request):
    """
    Example api for non dynamic urls
    """

    return HttpResponse(json.dumps({"message": "woohoo"}), content_type="application/json")


text:
<?xml version="1.0" encoding="ISO-8859-1"?>

<!DOCTYPE component SYSTEM "dtds/component.dtd">

<component name="ShipmentCharge">

	<entity>
		<property name="oid" type="String" key="true" hidden="true">
			<default-value-calculator class="org.openxava.calculators.UUIDCalculator" on-create="true"/>
		</property>
		<property name="mode" required="true">
			<valid-values>
				<valid-value value="slow"/>
				<valid-value value="medium"/>
				<valid-value value="fast"/>
			</valid-values>
		</property>
		<reference name="shipment"/>
		<property name="amount" stereotype="MONEY" required="true"/>

		<property name="slow" type="boolean">
			<calculator class="org.openxava.test.calculators.IsSlowCalculator" >
				<set property="mode"/>
			</calculator>
		</property>
	</entity>

	<view>
		<reference-view reference="shipment">
			<descriptions-list/>
		</reference-view>
	</view>

	<tab>
		<properties>mode, amount+, shipment.number, slow, shipment.description</properties>
	</tab>

	<entity-mapping table="XAVATEST@separator@SHIPMENTCHARGE">
		<property-mapping property="oid" column="ID"/>
		<!-- We don't use converter for 'mode', in this way:
			0 -> NO VALUE
			1 -> slow
			2 -> medium
			3 -> fast
		 -->
		<property-mapping property="mode" column="MODE"/>
		<reference-mapping reference="shipment">
			<reference-mapping-detail
				column="SHIPMENT_TYPE"
				referenced-model-property="type"
				cmp-type="String">
				<converter class="org.openxava.converters.ValidValuesLetterConverter">
					<set property="letters" value="IE"/>
				</converter>
			</reference-mapping-detail>
			<reference-mapping-detail
				column="MODE"
				referenced-model-property="mode"/>
			<reference-mapping-detail
				column="SHIPMENT_NUMBER"
				referenced-model-property="number"/>
		</reference-mapping>
		<property-mapping
			property="amount" column="TOTALAMOUNT"/>
	</entity-mapping>

</component>


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
K. norske vidensk. Selsk. Forh. 47 (1935)

#### Original name
Uromyces splendens A. Blytt

### Remarks
null


text:
package cz.muni.fi.pa165.methanolmanager.dal.repository;

import cz.muni.fi.pa165.methanolmanager.dal.DalConfig;
import cz.muni.fi.pa165.methanolmanager.dal.domain.Bottle;
import cz.muni.fi.pa165.methanolmanager.dal.domain.Make;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.boot.test.SpringApplicationConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;

import javax.inject.Inject;
import javax.transaction.Transactional;

import static org.hamcrest.Matchers.*;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertThat;

/*
 * @author Petr Barton
 */
@RunWith(SpringJUnit4ClassRunner.class)
@SpringApplicationConfiguration(classes = DalConfig.class)
@Transactional
public class MakeTest {

    @Inject
    BottleRepository bottleRepository;

    @Inject
    MakeRepository makeRepository;

    @Test
    public void testCreateMake() {
        Make makeBozkov = new Make();
        makeBozkov.setName("Bozkov");

        Bottle bottle1 = new Bottle();
        bottle1.setName("Tuzemsky");
        bottle1.setMake(makeBozkov);

        makeRepository.save(makeBozkov);
        bottleRepository.save(bottle1);

        assertEquals(bottleRepository.findAll().get(0).getMake(), makeBozkov);
    }

    @Test
    public void testDeleteMake() {
        Make makeFinlandia = new Make();
        makeFinlandia.setName("Finlandia");

        Make makeTullamoreDew = new Make();
        makeTullamoreDew.setName("Tullamore Dew");

        makeRepository.save(makeFinlandia);
        makeRepository.save(makeTullamoreDew);

        assertThat(makeRepository.findAll().size(), equalTo(2));

        Make deleteMake = makeRepository.findByName("Tullamore Dew");

        makeRepository.delete(deleteMake);

        assertThat(makeRepository.findAll().size(), equalTo(1));
        assertThat(makeRepository.findByName("Tullamore Dew"), nullValue());
    }
}


text:
/*
Theme Name:         Manz WP Theme
Theme URI:          https://jpcostallos.com
Description:        Manz classroom theme
Version:            1.0
Author:             JP Costallos
Author URI:         https://jpcostallos.com
Text Domain:        sage

License:            MIT License
License URI:        http://opensource.org/licenses/MIT
*/


text:
<!DOCTYPE html>

  <meta charset="utf-8">

  <meta name="viewport" content="width=device-width, initial-scale=1.0">

  <title>rl_coach.filters.observation.observation_crop_filter — Reinforcement Learning Coach 0.12.0 documentation</title>

  <link rel="stylesheet" href="../../../../_static/css/theme.css" type="text/css" />
  <link rel="stylesheet" href="../../../../_static/pygments.css" type="text/css" />
  <link rel="stylesheet" href="../../../../_static/css/custom.css" type="text/css" />
    <link rel="index" title="Index" href="../../../../genindex.html" />
    <link rel="search" title="Search" href="../../../../search.html" />
    <link href="../../../../_static/css/custom.css" rel="stylesheet" type="text/css">

             Reinforcement Learning Coach

  <form id="rtd-search-form" class="wy-form" action="../../../../search.html" method="get">
    <input type="text" name="q" placeholder="Search docs" />
    <input type="hidden" name="check_keywords" value="yes" />
    <input type="hidden" name="area" value="default" />
  </form>

Intro

Usage

Usage - Distributed Coach

Features

Selecting an Algorithm

Coach Dashboard

Design

Control Flow

Network Design

Distributed Coach - Horizontal Scale-Out

Contributing

Adding a New Agent

Adding a New Environment

Components

Agents

Architectures

Data Stores

Environments

Exploration Policies

Filters

Memories

Memory Backends

Orchestrators

Core Types

Spaces

Additional Parameters

          Reinforcement Learning Coach

Docs »

Module code »

rl_coach.filters.observation.observation_crop_filter

Source code for rl_coach.filters.observation.observation_crop_filter

#
# Copyright (c) 2017 Intel Corporation
#
# 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.
#
from typing import Union, Tuple

import numpy as np

from rl_coach.core_types import ObservationType
from rl_coach.filters.observation.observation_filter import ObservationFilter
from rl_coach.spaces import ObservationSpace

[docs]class ObservationCropFilter(ObservationFilter):
    """
    Crops the size of the observation to a given crop window. For example, in Atari, the
    observations are images with a shape of 210x160. Usually, we will want to crop the size of the observation to a
    square of 160x160 before rescaling them.
    """
    def __init__(self, crop_low: np.ndarray=None, crop_high: np.ndarray=None):
        """
        :param crop_low: a vector where each dimension describes the start index for cropping the observation in the
                         corresponding dimension. a negative value of -1 will be mapped to the max size
        :param crop_high: a vector where each dimension describes the end index for cropping the observation in the
                          corresponding dimension. a negative value of -1 will be mapped to the max size
        """
        super().__init__()
        if crop_low is None and crop_high is None:
            raise ValueError("At least one of crop_low and crop_high should be set to a real value. ")
        if crop_low is None:
            crop_low = np.array([0] * len(crop_high))
        if crop_high is None:
            crop_high = np.array([-1] * len(crop_low))

        self.crop_low = crop_low
        self.crop_high = crop_high

        for h, l in zip(crop_high, crop_low):
            if h < l and h != -1:
                raise ValueError("Some of the cropping low values are higher than cropping high values")
        if np.any(crop_high < -1) or np.any(crop_low < -1):
            raise ValueError("Cropping values cannot be negative")
        if crop_low.shape != crop_high.shape:
            raise ValueError("The low values and high values for cropping must have the same number of dimensions")
        if crop_low.dtype != int or crop_high.dtype != int:
            raise ValueError("The crop values should be int values, instead they are defined as: {} and {}"
                             .format(crop_low.dtype, crop_high.dtype))

    def _replace_negative_one_in_crop_size(self, crop_size: np.ndarray, observation_shape: Union[Tuple, np.ndarray]):
        # replace -1 with the max size
        crop_size = crop_size.copy()
        for i in range(len(observation_shape)):
            if crop_size[i] == -1:
                crop_size[i] = observation_shape[i]
        return crop_size

    def validate_input_observation_space(self, input_observation_space: ObservationSpace):
        crop_high = self._replace_negative_one_in_crop_size(self.crop_high, input_observation_space.shape)
        crop_low = self._replace_negative_one_in_crop_size(self.crop_low, input_observation_space.shape)
        if np.any(crop_high > input_observation_space.shape) or \
                np.any(crop_low > input_observation_space.shape):
            raise ValueError("The cropping values are outside of the observation space")
        if not input_observation_space.is_valid_index(crop_low) or \
                not input_observation_space.is_valid_index(crop_high - 1):
            raise ValueError("The cropping indices are outside of the observation space")

    def filter(self, observation: ObservationType, update_internal_state: bool=True) -> ObservationType:
        # replace -1 with the max size
        crop_high = self._replace_negative_one_in_crop_size(self.crop_high, observation.shape)
        crop_low = self._replace_negative_one_in_crop_size(self.crop_low, observation.shape)

        # crop
        indices = [slice(i, j) for i, j in zip(crop_low, crop_high)]
        observation = observation[indices]
        return observation

    def get_filtered_observation_space(self, input_observation_space: ObservationSpace) -> ObservationSpace:
        # replace -1 with the max size
        crop_high = self._replace_negative_one_in_crop_size(self.crop_high, input_observation_space.shape)
        crop_low = self._replace_negative_one_in_crop_size(self.crop_low, input_observation_space.shape)

        input_observation_space.shape = crop_high - crop_low
        return input_observation_space

        © Copyright 2018-2019, Intel AI Lab

  Built with Sphinx using a theme provided by Read the Docs.


text:
import org.jetbrains.annotations.Nullable;

public class Vocable {

    public enum Language {
        ENGLISH, GERMAN
    }

    private Vocable next;

    private Vocable prev;

    private Data data;

    public Vocable() {
        next = null;
        prev = null;
    }

    @Nullable
    public static Vocable fromString(String text) {
        String[] texts = text.split(";");
        if (texts.length < 2) {
            return null;
        }
        return new Vocable() {{
            setData(new Data() {{
                setEnglish(texts[0]);
                setGerman(texts[1]);
            }});
        }};
    }

    public void setNext(Vocable next) {
        this.next = next;
    }

    public void setPrev(Vocable prev) {
        this.prev = prev;
    }

    public void setData(Data data) {
        this.data = data;
    }

    @Nullable
    public Vocable getNext() {
        return next;
    }

    @Nullable
    public Vocable getPrev() {
        return prev;
    }

    public Data getData() {
        return data;
    }

    @Override
    public boolean equals(Object obj) {
        if (obj instanceof Vocable) {
            Vocable vocable = (Vocable) obj;
            return vocable.data.equals(this.data);
        }
        return false;
    }

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

    public static class Data {

        private String german;

        private String english;

        public Data() {
            english = null;
            german = null;
        }

        public void setEnglish(String english) {
            this.english = english;
        }

        public String getEnglish() {
            return english;
        }

        public void setGerman(String german) {
            this.german = german;
        }

        public String getGerman() {
            return german;
        }

        @Override
        public String toString() {
            return english + ";" + german;
        }

        @Override
        public boolean equals(Object obj) {
            if (obj instanceof Data) {
                Data data = (Data) obj;
                return data.german.equals(german) && data.english.equals(english);
            }
            return false;
        }
    }
}


text:
<!--
   Copyright 2015, Google, Inc.

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

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

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

	include_once("password/php/rules.php");

	$rules = new Rules();

	if (defined('STDIN') && array_key_exists(1, $argv)) {
	  	$candidate = $argv[1];
	} else {
		report(['pass'=>false,'message'=>$rules::FAIL_EMPTY]);
	}

	report($rules->validate($candidate));

	function report($result){
		echo json_encode($result);
		exit;
	}
?>


text: <scheme name="1" data="false"/>


text:
namespace SkiBrain.DataAccess
{
    using System;
    using System.Collections.Generic;

    public partial class MembershipType
    {
        public MembershipType()
        {
            this.Racers = new HashSet<Racer>();
        }

        public int Id { get; set; }
        public int TenantId { get; set; }
        public string Name { get; set; }
        public int RequiredVolunteerDays { get; set; }

        public virtual Tenant Tenant { get; set; }
        public virtual ICollection<Racer> Racers { get; set; }
    }
}


text:
package com.rx.common.injection.scope;

import javax.inject.Scope;

/**
 * Created by Shekar on 7/6/15.
 */

@Scope
public @interface ActivityScope {
}


text:
require 'spec_helper'

describe Viagogo::Public::API::Events do
  before do
    @client = Viagogo::Public::Client.new(:consumer_key => 'CK',
                                          :consumer_secret => 'CS',
                                          :access_token => 'AT',
                                          :access_token_secret => 'AS')
  end

  describe "#event" do
    it "makes HTTP get request" do
      stub_request(:any, /.*/).to_return(:body => "{}")
      @client.event 1
      expect(a_request(:get, /.*/)).to have_been_made
    end

    it "makes request for the correct resource" do
      expected_resource = 50
      expected_params = {:foo => "foo", :bar => "bar"}
      stub_get("/Public/Event/#{expected_resource}").
          with(:query => expected_params).
          to_return(:body => "{}")
      @client.event expected_resource, expected_params
      expect(a_get("/Public/Event/#{expected_resource}").with(:query => expected_params)).to have_been_made
    end

    it "returns Viagogo::Event created from the response" do
      stub_get("/Public/Event/1").to_return({:body => fixture("event.json")})
      expect(@client.event 1).to be_an_instance_of(Viagogo::Event)
    end
  end

  describe "#events_by_category" do
    it "makes HTTP get request" do
      stub_request(:any, /.*/).to_return(:body => "{}")
      @client.events_by_category 2
      expect(a_request(:get, /.*/)).to have_been_made
    end

    it "makes request for the correct resource" do
      expected_resource = "/Public/Event/ByCategory/50"
      expected_params = {:foo => "foo", :bar => "bar"}
      stub_get(expected_resource).with(:query => expected_params).to_return(:body => "{}")
      @client.events_by_category 50, expected_params
      expect(a_get(expected_resource).with(:query => expected_params)).to have_been_made
    end

    it "returns Viagogo::Page created from the response" do
      stub_request(:any, /.*/).to_return(:body => fixture("events.json"))
      expect(@client.events_by_category 20).to be_an_instance_of(Viagogo::Page)
    end
  end

  describe "#events_by_metro_area" do
    it "makes HTTP get request" do
      stub_request(:any, /.*/).to_return(:body => "{}")
      @client.events_by_metro_area 2
      expect(a_request(:get, /.*/)).to have_been_made
    end

    it "makes request for the correct resource" do
      expected_resource = "/Public/Event/ByMetroArea/50"
      expected_params = {:foo => "foo", :bar => "bar"}
      stub_get(expected_resource).with(:query => expected_params).to_return(:body => "{}")
      @client.events_by_metro_area 50, expected_params
      expect(a_get(expected_resource).with(:query => expected_params)).to have_been_made
    end

    it "returns Viagogo::Page created from the response" do
      stub_request(:any, /.*/).to_return(:body => fixture("events.json"))
      expect(@client.events_by_metro_area 20).to be_an_instance_of(Viagogo::Page)
    end
  end

  describe "#events_by_venue" do
    it "makes HTTP get request" do
      stub_request(:any, /.*/).to_return(:body => "{}")
      @client.events_by_venue 2
      expect(a_request(:get, /.*/)).to have_been_made
    end

    it "makes request for the correct resource" do
      expected_resource = "/Public/Event/ByVenue/50"
      expected_params = {:foo => "foo", :bar => "bar"}
      stub_get(expected_resource).with(:query => expected_params).to_return(:body => "{}")
      @client.events_by_venue 50, expected_params
      expect(a_get(expected_resource).with(:query => expected_params)).to have_been_made
    end

    it "returns Viagogo::Page created from the response" do
      stub_request(:any, /.*/).to_return(:body => fixture("events.json"))
      expect(@client.events_by_venue 20).to be_an_instance_of(Viagogo::Page)
    end
  end

  describe "#events_by_utc_start_date" do
    it "makes HTTP get request" do
      stub_request(:any, /.*/).to_return(:body => "{}")
      @client.events_by_utc_start_date 2000, 1, 1
      expect(a_request(:get, /.*/)).to have_been_made
    end

    it "makes request for the correct resource" do
      expected_resource = "/Public/Event/ByUtcStartDate/2003/3/15"
      expected_params = {:foo => "foo", :bar => "bar"}
      stub_get(expected_resource).with(:query => expected_params).to_return(:body => "{}")
      @client.events_by_utc_start_date 2003, 3, 15, expected_params
      expect(a_get(expected_resource).with(:query => expected_params)).to have_been_made
    end

    it "returns Viagogo::Page created from the response" do
      stub_request(:any, /.*/).to_return(:body => fixture("events.json"))
      expect(@client.events_by_utc_start_date 2011, 11, 11).to be_an_instance_of(Viagogo::Page)
    end
  end

  describe "#events_search" do
    it "makes HTTP get request" do
      stub_request(:any, /.*/).to_return(:body => "{}")
      @client.events_search "foo"
      expect(a_request(:get, /.*/)).to have_been_made
    end

    it "makes request for the correct resource" do
      expected_resource = "/Public/Event/Search"
      expected_params = {:searchText => "some query", :foo => "foo", :bar => "bar"}
      stub_get(expected_resource).with(:query => expected_params).to_return(:body => "{}")
      @client.events_search expected_params[:searchText], expected_params
      expect(a_get(expected_resource).with(:query => expected_params)).to have_been_made
    end

    it "returns Viagogo::Page created from the response" do
      stub_request(:any, /.*/).to_return(:body => fixture("events.json"))
      expect(@client.events_search "foo").to be_an_instance_of(Viagogo::Page)
    end
  end
end