text:
// Copyright (c) 2010 The WebM project authors. All Rights Reserved.
//
// Use of this source code is governed by a BSD-style license
// that can be found in the LICENSE file in the root of the source
// tree. An additional intellectual property rights grant can be found
// in the file PATENTS.  All contributing project authors may
// be found in the AUTHORS file in the root of the source tree.

#include <strmif.h>
#include <uuids.h>
#include "webmoggsourcefilter.hpp"
#include "cenumpins.hpp"
#include "webmoggsourceoutpin.hpp"
#include "webmtypes.hpp"
#include "oggtrackaudio.hpp"
#include <new>
#include <cassert>
#include <vfwmsgs.h>
#include <process.h>
#include <limits>
#ifdef _DEBUG
#include "iidstr.hpp"
#include "odbgstream.hpp"
using std::endl;
#endif

using std::wstring;
using namespace oggparser;

namespace WebmOggSource
{

//const LONGLONG Filter::kNoSeek(std::numeric_limits<LONGLONG>::min());

HRESULT CreateInstance(
    IClassFactory* pClassFactory,
    IUnknown* pOuter,
    const IID& iid,
    void** ppv)
{
    if (ppv == 0)
        return E_POINTER;

    *ppv = 0;

    if ((pOuter != 0) && (iid != __uuidof(IUnknown)))
        return E_INVALIDARG;

    Filter* p = new (std::nothrow) Filter(pClassFactory, pOuter);

    if (p == 0)
        return E_OUTOFMEMORY;

    assert(p->m_nondelegating.m_cRef == 0);

    const HRESULT hr = p->m_nondelegating.QueryInterface(iid, ppv);

    if (SUCCEEDED(hr))
    {
        assert(*ppv);
        assert(p->m_nondelegating.m_cRef == 1);

        return S_OK;
    }

    assert(*ppv == 0);
    assert(p->m_nondelegating.m_cRef == 0);

    delete p;
    p = 0;

    return hr;
}

#pragma warning(disable:4355)  //'this' ptr in member init list
Filter::Filter(IClassFactory* pClassFactory, IUnknown* pOuter)
    : m_pClassFactory(pClassFactory),
      m_nondelegating(this),
      m_pOuter(pOuter ? pOuter : &m_nondelegating),
      m_state(State_Stopped),
      m_clock(0),
      //m_file
      m_stream(&m_file)
      //m_pSeekBase(0),
      //m_seekBase_ns(-1),
      //m_currTime(kNoSeek)
{
    m_pClassFactory->LockServer(TRUE);

    const HRESULT hr = CLockable::Init();
    hr;
    assert(SUCCEEDED(hr));

    m_info.pGraph = 0;
    m_info.achName[0] = L'\0';

#ifdef _DEBUG
    odbgstream os;
    os << "webmoggsrc::ctor" << endl;
#endif
}
#pragma warning(default:4355)

Filter::~Filter()
{
#ifdef _DEBUG
    odbgstream os;
    os << "webmoggsrc::dtor" << endl;
#endif

    while (!m_pins.empty())
    {
        Outpin* p = m_pins.back();
        assert(p);

        m_pins.pop_back();
        delete p;
    }

    //delete m_pStream;

    m_pClassFactory->LockServer(FALSE);
}

Filter::nondelegating_t::nondelegating_t(Filter* p)
    : m_pFilter(p),
      m_cRef(0)  //see CreateInstance
{
}

Filter::nondelegating_t::~nondelegating_t()
{
}

HRESULT Filter::nondelegating_t::QueryInterface(
    const IID& iid,
    void** ppv)
{
    if (ppv == 0)
        return E_POINTER;

    IUnknown*& pUnk = reinterpret_cast<IUnknown*&>(*ppv);

    if (iid == __uuidof(IUnknown))
    {
        pUnk = this;  //must be nondelegating
    }
    else if ((iid == __uuidof(IBaseFilter)) ||
             (iid == __uuidof(IMediaFilter)) ||
             (iid == __uuidof(IPersist)))
    {
        pUnk = static_cast<IBaseFilter*>(m_pFilter);
    }
    else if (iid == __uuidof(IFileSourceFilter))
    {
        pUnk = static_cast<IFileSourceFilter*>(m_pFilter);
    }
    else if (iid == __uuidof(IAMFilterMiscFlags))
    {
        pUnk = static_cast<IAMFilterMiscFlags*>(m_pFilter);
    }
    else
    {
#if 0
        wodbgstream os;
        os << "webmsource::filter::QI: iid=" << IIDStr(iid) << std::endl;
#endif
        pUnk = 0;
        return E_NOINTERFACE;
    }

    pUnk->AddRef();
    return S_OK;
}

ULONG Filter::nondelegating_t::AddRef()
{
    return InterlockedIncrement(&m_cRef);
}

ULONG Filter::nondelegating_t::Release()
{
    if (LONG n = InterlockedDecrement(&m_cRef))
        return n;

    delete m_pFilter;
    return 0;
}

HRESULT Filter::QueryInterface(const IID& iid, void** ppv)
{
    return m_pOuter->QueryInterface(iid, ppv);
}

ULONG Filter::AddRef()
{
    return m_pOuter->AddRef();
}

ULONG Filter::Release()
{
    return m_pOuter->Release();
}

HRESULT Filter::GetClassID(CLSID* p)
{
    if (p == 0)
        return E_POINTER;

    *p = WebmTypes::CLSID_WebmOggSource;
    return S_OK;
}

HRESULT Filter::Stop()
{
    //Stop is a synchronous operation: when it completes,
    //the filter is stopped.

    Lock lock;

    HRESULT hr = lock.Seize(this);

    if (FAILED(hr))
        return hr;

    switch (m_state)
    {
        case State_Paused:
        case State_Running:

            lock.Release();

            OnStop();

            hr = lock.Seize(this);
            assert(SUCCEEDED(hr));  //TODO

            break;

        case State_Stopped:
        default:
            break;
    }

    m_state = State_Stopped;
    return S_OK;
}

HRESULT Filter::Pause()
{
    //Unlike Stop(), Pause() can be asynchronous (that's why you have
    //GetState()).  We could use that here to build the samples index.

    Lock lock;

    HRESULT hr = lock.Seize(this);

    if (FAILED(hr))
        return hr;

    switch (m_state)
    {
        case State_Stopped:
            OnStart();
            break;

        case State_Running:
        case State_Paused:
        default:
            break;
    }

    m_state = State_Paused;
    return S_OK;
}

HRESULT Filter::Run(REFERENCE_TIME start)
{
    Lock lock;

    HRESULT hr = lock.Seize(this);

    if (FAILED(hr))
        return hr;

    switch (m_state)
    {
        case State_Stopped:
            OnStart();
            break;

        case State_Paused:
        case State_Running:
        default:
            break;
    }

    m_start = start;
    m_state = State_Running;

    return S_OK;
}

HRESULT Filter::GetState(
    DWORD /* timeout */ ,
    FILTER_STATE* p)
{
    if (p == 0)
        return E_POINTER;

    //What the GetState.timeout parameter refers to is not to locking
    //the filter, but rather to waiting to determine the current state.
    //A request to Stop is always synchronous (hence no timeout parameter),
    //but a request to Pause can be asynchronous, so the caller can say
    //how long he's willing to wait for the transition (to paused) to
    //complete.

    //TODO: implement a waiting scheme here.  We'll probably have to
    //use SignalObjectAndWait atomically release the mutex and then
    //wait for the condition variable to change.
    //if (hr == VFW_E_TIMEOUT)
    //    return VFW_S_STATE_INTERMEDIATE;

    Lock lock;

    const HRESULT hr = lock.Seize(this);

    //The lock is only used for synchronization.  If Seize fails,
    //it means there's a serious problem with the filter.

    if (FAILED(hr))
        return E_FAIL;

    *p = m_state;
    return S_OK;
}

HRESULT Filter::SetSyncSource(
    IReferenceClock* clock)
{
    Lock lock;

    HRESULT hr = lock.Seize(this);

    if (FAILED(hr))
        return hr;

    if (m_clock)
        m_clock->Release();

    m_clock = clock;

    if (m_clock)
        m_clock->AddRef();

    return S_OK;
}

HRESULT Filter::GetSyncSource(
    IReferenceClock** pclock)
{
    if (pclock == 0)
        return E_POINTER;

    Lock lock;

    HRESULT hr = lock.Seize(this);

    if (FAILED(hr))
        return hr;

    IReferenceClock*& clock = *pclock;

    clock = m_clock;

    if (clock)
        clock->AddRef();

    return S_OK;
}

HRESULT Filter::EnumPins(IEnumPins** pp)
{
    Lock lock;

    HRESULT hr = lock.Seize(this);

    if (FAILED(hr))
        return hr;

    if (m_pins.empty())
        return CEnumPins::CreateInstance(0, 0, pp);

    Outpin* const* const i = &m_pins[0];
    const ULONG n = static_cast<ULONG>(m_pins.size());

    return CEnumPins::CreateInstance<Outpin>(i, n, pp);
}

HRESULT Filter::FindPin(
    LPCWSTR id1,
    IPin** pp)
{
    if (pp == 0)
        return E_POINTER;

    IPin*& p = *pp;
    p = 0;

    if (id1 == 0)
        return E_INVALIDARG;

    typedef pins_t::const_iterator iter_t;

    iter_t i = m_pins.begin();
    const iter_t j = m_pins.end();

    while (i != j)
    {
        Pin* const pPin = *i++;

        const wstring& id2_ = pPin->m_id;
        const wchar_t* const id2 = id2_.c_str();

        if (wcscmp(id1, id2) == 0)  //case-sensitive
        {
            p = pPin;
            p->AddRef();

            return S_OK;
        }
    }

    return VFW_E_NOT_FOUND;
}

HRESULT Filter::QueryFilterInfo(FILTER_INFO* p)
{
    if (p == 0)
        return E_POINTER;

    Lock lock;

    HRESULT hr = lock.Seize(this);

    if (FAILED(hr))
        return hr;

    enum { size = sizeof(p->achName)/sizeof(WCHAR) };
    const errno_t e = wcscpy_s(p->achName, size, m_info.achName);
    e;
    assert(e == 0);

    p->pGraph = m_info.pGraph;

    if (p->pGraph)
        p->pGraph->AddRef();

    return S_OK;
}

HRESULT Filter::JoinFilterGraph(
    IFilterGraph *pGraph,
    LPCWSTR name)
{
    Lock lock;

    HRESULT hr = lock.Seize(this);

    if (FAILED(hr))
        return hr;

    //NOTE:
    //No, do not adjust reference counts here!
    //Read the docs for the reasons why.
    //ENDNOTE.

    m_info.pGraph = pGraph;

    if (name == 0)
        m_info.achName[0] = L'\0';
    else
    {
        enum { size = sizeof(m_info.achName)/sizeof(WCHAR) };
        //const errno_t e = wcscpy_s(m_info.achName, size, name);
        //e;
        //assert(e == 0);

        //if (wcslen(name) >= size)
        //    return E_INVALIDARG;

        const wchar_t* src = name;

        wchar_t* const dst_begin = m_info.achName;
        wchar_t* const dst_end = dst_begin + size - 1;

        wchar_t* dst = dst_begin;

        while ((dst < dst_end) && (*dst++ = *src++))
            ;

        *dst++ = L'\0';

        const size_t size_ = dst - dst_begin;
        size_;
        assert(size_ <= size);
    }

    return S_OK;
}

HRESULT Filter::QueryVendorInfo(LPWSTR* pstr)
{
    if (pstr == 0)
        return E_POINTER;

    wchar_t*& str = *pstr;

    str = 0;
    return E_NOTIMPL;
}

HRESULT Filter::Load(LPCOLESTR filename, const AM_MEDIA_TYPE* pmt)
{
    pmt;

    Lock lock;

    HRESULT hr = lock.Seize(this);

    if (FAILED(hr))
        return hr;

    if (m_file.IsOpen())
        return E_UNEXPECTED;

    //assert(m_pStream == 0);

    hr = m_file.Open(filename);

    if (FAILED(hr))
        return hr;

    //OggStream* pStream;

    //const long status = OggStream::Create(&m_file, pStream);

    //if (status < 0)  //error
    //    return E_FAIL;

    hr = OggInit();

    if (FAILED(hr))
    {
        m_file.Close();
        return hr;
    }

    m_filename = filename;
    //m_pStream = pStream;

    return S_OK;
}

HRESULT Filter::OggInit()
{
    assert(m_file.IsOpen());
    assert(m_pins.empty());

#if 0
    const ULONG n = pTracks->GetTracksCount();

    for (ULONG i = 0; i < n; ++i)
    {
        const Track* const pTrack = pTracks->GetTrackByIndex(i);

        if (pTrack == 0)
            continue;

        const long long type = pTrack->GetType();

        if (type == 1)  //video
        {
            typedef mkvparser::VideoTrack VT;
            const VT* const t = static_cast<const VT*>(pTrack);

            if (VideoStream* s = VideoStream::CreateInstance(t))
                CreateOutpin(s);
        }
        else if (type == 2)  //audio
        {
            typedef mkvparser::AudioTrack AT;
            const AT* const t = static_cast<const AT*>(pTrack);

            if (AudioStream* s = AudioStream::CreateInstance(t))
                CreateOutpin(s);
        }
    }

    if (m_pins.empty())
        return VFW_E_INVALID_FILE_FORMAT;  //TODO: better return value here?

    //m_pSeekBase = 0;
    //m_seekBase_ns = -1;
    //m_currTime = kNoSeek;

#else

    //TODO: for now, just hard-code a single Vorbis audio track, since that's
    //all our OggStream parser supports anyway.  If there's interest in
    //generalizing this component to work with an ogg container having
    //multiple tracks ("logical bitreams", in Ogg parlance), then we can just
    //add support for that later.

    //TODO: use logical bitstream id instead of hard-coding 1
    //OggTrackAudio* const pTrack = new OggTrackAudio(&m_stream, 1);

    OggTrackAudio* pTrack;

    HRESULT hr = OggTrackAudio::Create(&m_stream, pTrack);

    if (FAILED(hr))
        return hr;

    Outpin* const pOutpin = new Outpin(this, pTrack);

    m_pins.push_back(pOutpin);

#endif

    return S_OK;
}

#if 0  //TODO

void Filter::CreateOutpin(mkvparser::Stream* s)
{
    Outpin* const p = new (std::nothrow) Outpin(this, s);
    m_pins.push_back(p);
}

#endif  //TODO

HRESULT Filter::GetCurFile(LPOLESTR* pname, AM_MEDIA_TYPE* pmt)
{
    if (pmt)
        memset(pmt, 0, sizeof(AM_MEDIA_TYPE));  //TODO

    if (pname == 0)
        return E_POINTER;

    wchar_t*& name = *pname;
    name = 0;

    Lock lock;

    HRESULT hr = lock.Seize(this);

    if (FAILED(hr))
        return hr;

    if (!m_file.IsOpen())
        return S_FALSE;

    const size_t len = m_filename.length();
    const size_t size = len + 1;
    const size_t cb = size * sizeof(wchar_t);

    name = (wchar_t*)CoTaskMemAlloc(cb);

    if (name == 0)
        return E_OUTOFMEMORY;

    const errno_t e = wcscpy_s(name, size, m_filename.c_str());
    e;
    assert(e == 0);

    return S_OK;
}

ULONG Filter::GetMiscFlags()
{
    return AM_FILTER_MISC_FLAGS_IS_SOURCE;
}

void Filter::OnStart()
{
    typedef pins_t::iterator iter_t;

    iter_t i = m_pins.begin();
    const iter_t j = m_pins.end();

    while (i != j)
    {
        Outpin* const pPin = *i++;
        assert(pPin);

        pPin->Init();
    }

    //Init();
}

void Filter::OnStop()
{
    //Final();

    typedef pins_t::iterator iter_t;

    iter_t i = m_pins.begin();
    const iter_t j = m_pins.end();

    while (i != j)
    {
        Outpin* const pPin = *i++;
        assert(pPin);

        pPin->Final();
    }
}

#if 0

int Filter::GetConnectionCount() const
{
    //filter already locked by caller

    int n = 0;

    typedef pins_t::const_iterator iter_t;

    iter_t i = m_pins.begin();
    const iter_t j = m_pins.end();

    while (i != j)
    {
        const Outpin* const pin = *i++;
        assert(pin);

        if (pin->m_connection)
            ++n;
    }

    return n;
}

void Filter::SetCurrPosition(
    LONGLONG currTime,
    DWORD dwCurr,
    Outpin* pOutpin)
{
    assert(pOutpin);
    assert(pOutpin->m_connection);

    using namespace mkvparser;

    Stream* const pOutpinStream = pOutpin->m_pStream;
    const Track* const pOutpinTrack = pOutpinStream->m_pTrack;

    if (m_currTime == currTime)
    {
       const BlockEntry* pCurr;

        if (m_pSeekBase == 0)  //lazy init
            pCurr = 0;
        else if (m_pSeekBase->EOS())
            pCurr = pOutpinTrack->GetEOS();
        else
            pCurr = m_pSeekBase->GetEntry(pOutpinTrack, m_seekTime_ns);

        pOutpinStream->SetCurrPosition(m_seekBase_ns, pCurr);
        return;
    }

    m_currTime = currTime;
    const LONGLONG ns = pOutpinStream->GetSeekTime(currTime, dwCurr);

    long status = m_pSegment->LoadCluster();
    assert(status >= 0);  //TODO

    if (pOutpinTrack->GetType() == 1)  //video
    {
        const AM_MEDIA_TYPE& mt = pOutpin->m_connection_mtv[0];
        const BOOL bVideo = (mt.majortype == MEDIATYPE_Video);
        bVideo;
        assert(bVideo);

        if (const Cues* pCues = m_pSegment->GetCues())
        {
            const CuePoint* pCP;
            const CuePoint::TrackPosition* pTP;

            if (pCues->Find(ns, pOutpinTrack, pCP, pTP))
            {
                const BlockEntry* const pCurr = pCues->GetBlock(pCP, pTP);

                if ((pCurr != 0) && !pCurr->EOS())
                {
                    m_pSeekBase = pCurr->GetCluster();
                    m_seekBase_ns = pCurr->GetBlock()->GetTime(m_pSeekBase);
                    m_seekTime_ns = m_seekBase_ns;

                    pOutpinStream->SetCurrPosition(m_seekBase_ns, pCurr);
                    return;
                }
            }
        }

        const BlockEntry* pCurr;

        for (;;)
        {
            status = pOutpinTrack->Seek(ns, pCurr);

            if (status >= 0)
                break;

            assert(status == mkvparser::E_BUFFER_NOT_FULL);

            status = m_pSegment->LoadCluster();
            assert(status >= 0);
        }

        assert(pCurr);

        if (pCurr->EOS())  //pathological
        {
            m_pSeekBase = &m_pSegment->m_eos;
            m_seekBase_ns = -1;
            m_seekTime_ns = -1;
        }
        else
        {
            m_pSeekBase = pCurr->GetCluster();
            m_seekBase_ns = pCurr->GetBlock()->GetTime(m_pSeekBase);
            m_seekTime_ns = m_seekBase_ns;
        }

        pOutpinStream->SetCurrPosition(m_seekBase_ns, pCurr);
        return;
    }

    typedef pins_t::const_iterator iter_t;

    iter_t i = m_pins.begin();
    const iter_t j = m_pins.end();

    while (i != j)
    {
        const Outpin* const pin = *i++;
        assert(pin);

        if (pin->m_connection == 0)
            continue;

        const AM_MEDIA_TYPE& mt = pin->m_connection_mtv[0];
        const BOOL bVideo = (mt.majortype == MEDIATYPE_Video);

        if (!bVideo)
            continue;

        Stream* const pStream = pin->m_pStream;
        assert(pStream);
        assert(pStream != pOutpinStream);

        const Track* const pVideoTrack = pStream->m_pTrack;
        assert(pVideoTrack->GetType() == 1);  //video

        if (const Cues* pCues = m_pSegment->GetCues())
        {
            const CuePoint* pCP;
            const CuePoint::TrackPosition* pTP;

            if (pCues->Find(ns, pVideoTrack, pCP, pTP))
            {
                const BlockEntry* pCurr = pCues->GetBlock(pCP, pTP);

                if ((pCurr != 0) && !pCurr->EOS())
                {
                    m_pSeekBase = pCurr->GetCluster();
                    m_seekBase_ns = pCurr->GetBlock()->GetTime(m_pSeekBase);
                    m_seekTime_ns = m_seekBase_ns;  //to find same block later

                    pCurr = m_pSeekBase->GetEntry(pOutpinTrack, m_seekBase_ns);
                    assert(pCurr);

                    if (!pCurr->EOS())
                    {
                        const Block* const pBlock = pCurr->GetBlock();
                        assert(pBlock);

                        m_seekBase_ns = pBlock->GetTime(m_pSeekBase);
                    }

                    pOutpinStream->SetCurrPosition(m_seekBase_ns, pCurr);
                    return;
                }
            }
        }

        const BlockEntry* pCurr;

        for (;;)
        {
            status = pVideoTrack->Seek(ns, pCurr);

            if (status >= 0)
                break;

            assert(status == mkvparser::E_BUFFER_NOT_FULL);

            status = m_pSegment->LoadCluster();
            assert(status >= 0);
        }

        if (pCurr->EOS())  //pathological
        {
            m_pSeekBase = &m_pSegment->m_eos;
            m_seekBase_ns = -1;
            m_seekTime_ns = -1;

            pCurr = pOutpinTrack->GetEOS();
            pOutpinStream->SetCurrPosition(m_seekBase_ns, pCurr);
            return;
        }

        m_pSeekBase = pCurr->GetCluster();
        m_seekBase_ns = pCurr->GetBlock()->GetTime(m_pSeekBase);
        m_seekTime_ns = m_seekBase_ns;  //to find same block later

        pCurr = m_pSeekBase->GetEntry(pOutpinTrack, m_seekBase_ns);
        assert(pCurr);

        if (!pCurr->EOS())
            m_seekBase_ns = pCurr->GetBlock()->GetTime(m_pSeekBase);

        pOutpinStream->SetCurrPosition(m_seekBase_ns, pCurr);
        return;
    }

    const BlockEntry* pCurr;

    for (;;)
    {
        status = pOutpinTrack->Seek(ns, pCurr);

        if (status >= 0)
            break;

        assert(status == mkvparser::E_BUFFER_NOT_FULL);

        status = m_pSegment->LoadCluster();
        assert(status >= 0);
    }

    assert(pCurr);

    if (pCurr->EOS())  //pathological
    {
        m_pSeekBase = &m_pSegment->m_eos;
        m_seekBase_ns = -1;
        m_seekTime_ns = -1;
    }
    else
    {
        m_pSeekBase = pCurr->GetCluster();
        m_seekBase_ns = m_pSeekBase->GetFirstTime();
        m_seekTime_ns = ns;
    }

    pOutpinStream->SetCurrPosition(m_seekBase_ns, pCurr);
}

#endif  //TODO

} //end namespace WebmOggSource


text:
:root {
  --theme-color: #283e4a;
  --theme-color2: #2f8033;
  --font-family: Arabic, sans-serif, Tahoma, serif;
  --font-weight: normal;
  --font-size: 14px;
  --line-height: 1.4;
  --float: left;
  --direction: ltr;
  --text-align: left;
  --color: #ffffff;
  --background-color: #607d8b;
  --box-shadow-color: #272727;
  --border: 1px solid #353535;
  --zoom: 90%;
  --user-select: text;

  --body-background: #607d8b;
  --body-margin-top: 70px;
  --body-margin-bottom: 200px;

  --h-font-weight: normal;

  --navbar-color: #fff;
  --navbar-span-color: #ffffff;
  --navbar-background-color: #283e4a;
  --navbar-box-shadow-color: #272727;
  --navbar-li-border-radius: 8px;
  --navbar-li-border: none;

  --tabs-color: #fff;
  --tabs-background-color: #283e4a;
  --tabs-background-color2: rgb(60, 85, 97);
  --tabs-header-width: 20%;
  --tabs-content-width: 80%;
  --tabs-header-link-color: #ffffff;
  --tabs-header-link-color2: #ffffff;
  --tabs-header-link-background: none;
  --tabs-header-link-border: none;
  --tabs-header-link-border-bottom: none;
  --tabs-header-link-radius: 4px;
  --tab-animation-name: animatetabs;
  --tab-animation-duration: 0.5s;

  --treeview-color: #ffffff;
  --treeview-color2: #ffffff;
  --treeview-background-color: none;
  --treeview-border-color: #000000;
  --treeview-background-color2: rgb(60, 85, 97);
  --treeview-display-color: #0000ff;

  --form-color: #ffffff;
  --form-background-color: none;
  --label-font-size: 12px;
  --label-font-weight: bold;
  --label-text-align: center;

  --input-color: #ffeb3b;
  --input-background-color: #3c5d6f;
  --input-height: 33px;
  --input-padding: 6px 12px;
  --input-font-size: 14px;
  --input-font-wight: bold;
  --input-border-radius: 4px;
  --input-border-width: 1px;
  --input-border-color: #272727;
  --input-focus-border-width: 2px;
  --input-focus-border-color: var(--input-color);

  --textarea-border-width: 1px;
  --select-appearance: menulist;
  --select-font-size: 14px;
  --select-color: #000000;
  --select-height: 33px;

  --btn-color: #ffffff;
  --btn-background: #283e4a;
  --btn-add-color: #ffffff;
  --btn-add-background-color: #118011;
  --btn-update-color: #ffffff;
  --btn-update-background-color: #117380;
  --btn-save-color: #ffffff;
  --btn-save-background-color: #117380;
  --btn-delete-color: #ffffff;
  --btn-delete-background-color: #801117;
  --btn-view-color: #ffffff;
  --btn-view-background-color: #451180;
  --btn-exit-color: #ffffff;
  --btn-exit-background-color: #811e1e;
  --btn-search-color: #ffffff;
  --btn-search-background-color: #243688;
  --btn-print-color: #ffffff;
  --btn-print-background-color: #000000;
  --btn-export-color: #000000;
  --btn-export-background-color: #ffffff;
  --btn-sgin-color: #283e4a;
  --btn-sgin-background-color: #ffffff;
  --btn-box-shadow-color: #272727;
  --btn-border-radius: 5px;

  --i-image-border: 2px dashed var(--modal-header-background-color);
  --i-image-view-border: 2px solid var(--modal-header-background-color);

  --fieldset-border: 2px solid #283e4a;
  --fieldset-background: none;
  --fieldset-margin: 10px;
  --fieldset-padding: 5px;
  --legend-color: #fff;
  --legend-text-shadow: none;
  --legend-font-size: 16px;
  --legend-font-weight: bold;
  --legend-border: none;

  --modal-background: rgba(0, 0, 0, 0.6);
  --modal-content-background: #607d8b;
  --modal-content-border: none;
  --modal-color: #000;
  --modal-animation-name: animatetop;
  --modal-animation-duration: 0.4s;
  --modal-header-color: #000000;
  --modal-footer-color: #000000;
  --modal-header-background-color: #283e4a;
  --modal-footer-background-color: #bbb;
  --modal-box-shadow-color: #000000;

  --table-color: #030303;
  --table-background-color: #ffffff;
  --table-border: 1px solid #bbb;
  --table-hover-background-color: yellow;
  --table-th-color: #fff;

  --help-height: 110px;
  --help-border: none;
  --help-border-radius: 10px;
  --help-background-color: #283e4a;
  --help-opacity: 1;
  --help-content-color: #ffffff;

  --main-menu-item-padding: 2px;
  --main-menu-item-border: 1px solid #ddd;
  --main-menu-item-border-radius: 0px;
  --main-menu-item-background-color: #283e4a;
  --main-menu-h2-color: #ffffff;
  --main-menu-p-color: #ffffff;

  --scrollbar-background-color: #272727;
  --scrollbar-color: #ffeb3b;
  --scrollbar-box-shadow-color: #4caf50;
}

redpajama_set_name: RedPajamaGithub


text:
from pyjokes.jokes_en import jokes_en
from pyjokes.jokes_de import jokes_de
from pyjokes.jokes_es import jokes_es
from pyjokes.jokes_gl import jokes_gl
from pyjokes.jokes_eu import jokes_eu
from pyjokes.jokes_it import jokes_it

#test if joke is windows compatible
def _test_joke_win(joke):
    assert len(joke) <= len(joke.encode('iso-8859-1', 'ignore')) ##ascii don't support umlauts

def _test_default_locale(joke):
    import locale
    encod = locale.getdefaultlocale()[1]
    assert len(joke) <= len(joke.encode(encod, 'ignore'))

#unix is full compatible - no need of tests
def test_jokes_lengths():
    jokes_sets = [jokes_en, jokes_es, jokes_de, jokes_gl, jokes_eu, jokes_it]
    for jokes in jokes_sets:
        for j in jokes['all']:
            _test_default_locale(j)
            _test_joke_win(j)


text:
@interface AppDelegate : NSObject <CRApplicationDelegate>

@end


text:
require 'test_helper'

class ParserHelperTest < MiniTest::Unit::TestCase
  def setup
    @text = " [group gitosis]\n "
    @parser_helper = Parse::Conf::ParserHelper
  end

  def test_trim!
    obj = @parser_helper.new(@text)
    obj.trim!

    assert_equal "[group gitosis]", obj.string
  end

  def test_remove_ugly_symbol!
    obj = @parser_helper.new(@text)
    obj.remove_ugly_symbol!

    assert_equal " group gitosis\n ", obj.string
  end

  def test_trim_and_remove_ugly_symbol!
    assert_equal 'group gitosis', @parser_helper.trim_and_remove_ugly_symbol(@text)
  end
end


text:
using Nancy;
using Nancy.Bootstrapper;
using Nancy.Diagnostics;
using Nancy.TinyIoc;
using Newtonsoft.Json;

#if !DEBUG
using Nancy.Diagnostics;
#endif

namespace Oxide.PluginWebApi.Nancy
{
    public class ApiBootstrapper : DefaultNancyBootstrapper
    {
#if DEBUG
        protected override DiagnosticsConfiguration DiagnosticsConfiguration => new DiagnosticsConfiguration
        {
            Password = "debug"
        };
#endif

        protected override void RequestStartup(TinyIoCContainer container, IPipelines pipelines, NancyContext context)
        {
#if !DEBUG
            // Disable /_nancy diagnostics page.
            DiagnosticsHook.Disable(pipelines);
#endif

            StaticConfiguration.DisableErrorTraces = false;

            pipelines.AfterRequest.AddItemToEndOfPipeline(ctx =>
            {
                ctx.Response.WithHeader("Access-Control-Allow-Origin", "*")
                            .WithHeader("Access-Control-Allow-Methods", "POST,GET")
                            .WithHeader("Access-Control-Allow-Headers", "Accept,Origin,Content-Type");
            });
        }

        protected override void ConfigureApplicationContainer(TinyIoCContainer container)
        {
            base.ConfigureApplicationContainer(container);
            container.Register<JsonSerializer, ApiJsonSerializer>();
        }
    }
}


text:
@extends('mage2::admin.master')

@section('content')

Category Edit Form

            {!! Form::model($category,array('method' => 'PATCH', 'files' => true ,'url' => url('/admin/category',$category->id)) ) !!}

            @include('mage2::admin.category._edit')

            {!! Form::hidden('id') !!}

            {!! Form::close() !!}

@endsection


text:
package fastparsers.input

/**
 * Input on a array-like.
 *
 * Elem, Input, inputType and inputElemType must be set
 */
trait ArrayLikeInput extends ParseInput {

  import c.universe._

  private val inputpos = TermName(c.freshName("inputpos"))
  private val inputlength = TermName(c.freshName("inputsize"))

  def initInput(startpos: c.Tree, then: c.Tree) =
    q"""
      var $inputpos = $startpos
      val $inputlength = $inputValue.size
      $then
    """

  def currentInput = q"$inputValue($inputpos)"

  def advance = q"$inputpos = $inputpos + 1"

  def setpos(pos: c.Tree): c.Tree = q"$inputpos = $pos"

  def mark(code: c.Tree => c.Tree) = {
    val input_tmp = TermName(c.freshName)
    q"""
      val $input_tmp = $inputpos
      ${code(q"$inputpos = $input_tmp")}
     """
  }

  def isEOI = q"$inputpos >= $inputlength"

  def isNEOI = q"$inputpos < $inputlength"

  def pos = q"$inputpos"

  def inputsize = q"$inputlength"

  def slice(begin: c.Tree, end: c.Tree) = {
    q"$inputValue.slice($begin,$end)"
  }
}


text:
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
	<!-- This POM is just to trigger the Ant/Ivy sample from Maven and to test -->
	<modelVersion>4.0.0</modelVersion>
	<parent>
		<groupId>org.springframework.boot</groupId>
		<artifactId>spring-boot-samples</artifactId>
		<version>${revision}</version>
	</parent>
	<artifactId>spring-boot-sample-ant</artifactId>
	<name>Spring Boot Ant Sample</name>
	<description>Spring Boot Ant Sample</description>
	<properties>
		<main.basedir>${basedir}/../..</main.basedir>
		<ant.version>1.9.3</ant.version>
	</properties>
	<dependencies>
		<!-- Compile -->
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter</artifactId>
		</dependency>
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-loader</artifactId>
		</dependency>
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-test</artifactId>
		</dependency>
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-antlib</artifactId>
			<version>${project.version}</version>
		</dependency>
		<!-- Test -->
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-loader-tools</artifactId>
			<scope>test</scope>
		</dependency>
	</dependencies>
	<build>
		<plugins>
			<plugin>
				<groupId>org.apache.maven.plugins</groupId>
				<artifactId>maven-compiler-plugin</artifactId>
				<executions>
					<execution>
						<id>default-compile</id>
						<phase>none</phase>
					</execution>
				</executions>
			</plugin>
			<plugin>
				<groupId>org.apache.maven.plugins</groupId>
				<artifactId>maven-antrun-plugin</artifactId>
				<executions>
					<execution>
						<id>antbuild</id>
						<phase>package</phase>
						<configuration>
							<target>
								<property name="build.compiler" value="extJavac" />
								<ant dir="${basedir}" />
							</target>
						</configuration>
						<goals>
							<goal>run</goal>
						</goals>
					</execution>
				</executions>
				<dependencies>
					<dependency>
						<groupId>org.apache.ant</groupId>
						<artifactId>ant</artifactId>
						<version>${ant.version}</version>
					</dependency>
					<dependency>
						<groupId>org.apache.ivy</groupId>
						<artifactId>ivy</artifactId>
						<version>2.4.0</version>
					</dependency>
					<dependency>
						<groupId>org.springframework.boot</groupId>
						<artifactId>spring-boot-antlib</artifactId>
						<version>${revision}</version>
					</dependency>
				</dependencies>
			</plugin>
			<plugin>
				<groupId>org.apache.maven.plugins</groupId>
				<artifactId>maven-failsafe-plugin</artifactId>
				<executions>
					<execution>
						<goals>
							<goal>integration-test</goal>
							<goal>verify</goal>
						</goals>
					</execution>
				</executions>
			</plugin>
		</plugins>
	</build>
</project>


text:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE module PUBLIC "-//Google Inc.//DTD Google Web Toolkit trunk//EN" "http://google-web-toolkit.googlecode.com/svn/trunk/distro-source/core/src/gwt-module.dtd">
<module rename-to="html">
	<inherits name='com.badlogic.gdx.backends.gdx_backends_gwt' />
	<inherits name='com.kotcrab.vis.vis-ui' />

	<inherits name='Game' />
	<entry-point class='com.laststandstudio.concpet.client.HtmlLauncher' />

	<set-configuration-property name="gdx.assetpath" value="../core/assets" />
</module>


text:
let mirror;

function setup() {
    canvas = createCanvas(windowWidth, windowHeight);
    mirror = new Line();
}

function reflect(i, n) {
  return i.copy().add(n.copy().mult(i.copy().mult(2).dot(n) / pow(n.mag(), 2) * -1));
}

function draw() {
    clear();
    background(255, 235, 200);
    const boundary = {x: -width / 2, y: -height / 2, w: width, h: height};

    const mx = cos(frameCount / 120 * PI + PI * 0.251);
    const my = 1;
    mirror.fromTwoPoints({x:0, y: 0}, {x: mx, y: my});

    const ty = sin(frameCount / 90 * PI) * height / 4;
    const ray = new Line().fromTwoPoints({x: -width / 2, y:0}, {x: 0, y: ty});
    const rayVec = createVector(width / 2, ty).normalize();

    const intersection = mirror.getIntersectionPoint(ray);
    const normal = createVector(-my, mx);
    if (normal.dot(rayVec) > 0) { normal.mult(-1);}
    const reflectionVec = reflect(rayVec, normal);

    const rayHead = intersection.copy().add(rayVec.copy().mult(-32));
    const rayTail = intersection.copy().add(rayVec.copy().mult(-56));
    const normalHead = intersection.copy().add(normal.copy().mult(24));
    const reflectionHead = intersection.copy().add(reflectionVec.copy().mult(56));
    const reflectionTail = intersection.copy().add(reflectionVec.copy().mult(32));
    const reflectionLineEnd = intersection.copy().add(reflectionVec.copy().mult(width));

    push();

    fill(255); stroke(0); strokeWeight(1);
    translate(width / 2, height / 2);
    line(-width / 2, 0, intersection.x, intersection.y);
    line(intersection.x, intersection.y, reflectionLineEnd.x, reflectionLineEnd.y);

    strokeWeight(2);
    mirror.draw(boundary);
    drawArrow(intersection.x, intersection.y, normalHead.x, normalHead.y);
    strokeWeight(4);
    drawArrow(rayTail.x, rayTail.y, rayHead.x, rayHead.y);
    drawArrow(reflectionTail.x, reflectionTail.y, reflectionHead.x, reflectionHead.y);

    fill(0); noStroke(0);
    drawLabel(rayHead.x + rayVec.x * 16, rayHead.y + rayVec. y * 16, "i");
    drawLabel(reflectionHead.x + reflectionVec.x * 16, reflectionHead.y + reflectionVec.y * 16, "r");
    drawLabel(normalHead.x + normal.x * 16, normalHead.y + normal.y * 16, "n");

    pop();
}

/** Line **/

/** drawArrow **/

/** drawLabel **/


text:
window.addEventListener('mousedown', function(e) {
    document.body.classList.add('mouse-navigation');
    document.body.classList.remove('kbd-navigation');
});

window.addEventListener('keydown', function(e) {
    if (e.keyCode === 9) {
        document.body.classList.add('kbd-navigation');
        document.body.classList.remove('mouse-navigation');
    }
});

window.addEventListener('click', function(e) {
    if (e.target.tagName === 'A' && e.target.getAttribute('href') === '#') {
        e.preventDefault();
    }
});

window.onerror = function(message, source, line, col, error) {
    var text = error ? error.stack || error : message + ' (at ' + source + ':' + line + ':' + col + ')';
    errors.textContent += text + '\n';
    errors.style.display = '';
};

console.error = (function(old) {
    return function error() {
        errors.textContent += Array.prototype.slice.call(arguments).join(' ') + '\n';
        errors.style.display = '';
        old.apply(this, arguments);
    }
})(console.error);


text:
import BaseController from './controller.js'

class ApplicantsApplicantViewCtrl extends BaseController {
    constructor($scope, $injector, stateData) {
        super($scope, $injector);

		this.body = angular.element('body');
    }

    // Fired when custom html section is loaded
    includeContentLoaded() {

    }

    // Fired when custom html section loading failed
    includeContentError(e) {

    }

    // Fired when view content is loaded
	onShow($scope) {
		var that = this,
			applicantDS;

		this.scope = $scope;
		applicantDS = this.$ds.ApplicantDS;

		// Call SetUpAgeDataSource() when control is available.
		// Use of watch() is a common Angular approach
		// to wait for availability of the control.
		// onShow - it is too soon
		// kendoWidgetCreated - you need to identify the control
		// success of read() - control may still not be available

		$scope.$watch(function () {
			return angular.element("#AgeCB").data("kendoComboBox");
		}, function (newValue, oldValue) {
			if (newValue) {
				that.setUpAgeDataSource();
				that.updateNonModelControls();
			}
		});

		// Show progress indicator
		kendo.ui.progress(this.body, true);

		applicantDS.bind('change', function (e) {
			// For form, datasource pagesize is set to 1, so view returns single row
			// in current page
			var view = applicantDS.view(),
				that = this;
			if (view.length) {
				$scope.$applyAsync(function () {
					//console.log("In $applyAsync, got change " + view[0].Name);

					// On change, update model with row
						that.$viewModels.ApplicantDSModel = kendo.proxyModelSetters(view[0]);

					// Need to manually update controls with data from newly populated model
					that.updateNonModelControls();
				}.bind(this));
			}
		}.bind(this));
		applicantDS.read().done(function () {
			kendo.ui.progress(that.body, false);
			that.addMode = false;
		});
	}

	// Updates the corresponding DataSource row from model
	updateDataSourceRow(model) {
		var i,
			applicantDS = this.$ds.ApplicantDS,
			schema = applicantDS.transport.jsdo.getSchema(),
			dataItem = applicantDS.get(model.id);

		// Manually synchronize model with datasource.
		// Using schema instead of model, else issue overwriting dirty property
		for (i = 0; i < schema.length; i += 1) {
			dataItem.set(schema[i].name, model[schema[i].name]);
		}
	}

	// Updates the combobox control with data from model
	// manually, because a local datasource is used.
	updateNonModelControls() {
		var applicantModel = this.$viewModels.ApplicantDSModel,
			ageComboBox = angular.element("#AgeCB").data("kendoComboBox");

		// updateNonModelControls is called from a change event callback,
		// in some circumstances, the combobox might not be available
		if (ageComboBox) {
			ageComboBox.value(applicantModel.Age);
		}
	}

	// OnCreateClick() adds a new row to the datasource.
	// The add() returns its corresponding dataItem with default values.
	// Once the 'Save' btn is selected, the create operation will then
	// be sent to the backend.
	// The new record will not be in a sort position until a refresh occurs.
	// Navigation uses local paging and will not change sort order.
	onCreateClick() {
		var applicantDS = this.$ds.ApplicantDS;

		// Add new row to the datasource, then update the current page.
		// The add() fires the change event which updates the model with
		// current row (page).
		applicantDS.add({});
		applicantDS.page(applicantDS.totalPages());

		this.addMode = true;
		this.enableButtons(false, true);
	}

	onRemoveClick() {
		var that = this;

		function removeRow() {
			var applicantDS = that.$ds.ApplicantDS,
				applicantModel = that.$viewModels.ApplicantDSModel,
				promise;

			applicantDS.remove(applicantModel);

			// Now save changes to the backend
			promise = applicantDS.sync();
			promise.done(function (xhr) {
				var applicantDS = that.$ds.ApplicantDS;

				// Remove forces change event which updates
				// model, but if last row is deleted, then
				// current page needs to be updated
				if (applicantDS.page() > applicantDS.totalPages()) {
					applicantDS.page(applicantDS.totalPages());
				}
			});
			promise.fail(function (xhr) {
				var applicantDS = that.$ds.ApplicantDS,
					errors,

				errors = applicantDS.transport.jsdo.getErrors();
				for (i = 0; i < errors.length; i += 1) {
					console.log(errors[i].error);
				}
			}); // end promise.fail
		}

		this.scope.$emit('dialog', {
			title: "Are you sure you want to delete record?",
			hint: "The record will be permanently removed.",

			okButton: {
				handler: removeRow
			}
		});
	}

	// OnCancelClick() cancels a pending create or update operation
	onCancelClick($scope, customData) {
		var applicantModel = this.$viewModels.ApplicantDSModel,
			applicantDS = this.$ds.ApplicantDS;

		// The change to the datasource will force the change event
		// which will update model correctly
		if (applicantDS.hasChanges()) {
			if (this.addMode === true) {
				// Remove record just added to dataSource
				applicantDS.remove(applicantModel);
				this.addMode = false;
				// Focus is now on last row (created rows are appended at end)
				applicantDS.page(applicantDS.totalPages());
			} else {
				applicantDS.cancelChanges();
			}
		}

		this.enableButtons(true, true);
	}

	// This function calls the datasource.sync() function to send the
	// update or create operation to backend service.
	// For created rows, it first must synchronize model with datasource
	onSaveClick() {
		var that = this,
			promise,
			applicantModel = this.$viewModels.ApplicantDSModel,
			applicantDS = this.$ds.ApplicantDS;

		if (this.addMode) {
			// Manually synchronize model with datasource.
			this.updateDataSourceRow(applicantModel);
		}

		if (applicantDS.hasChanges()) {
			this.enableButtons(false, false);
			promise = applicantDS.sync();
			promise.done(function () {
				that.enableButtons(true, true);

				if (that.addMode === true) {
					that.addMode = false;
				}
			});
			promise.fail(function (xhr) {
				var applicantDS = that.$ds.ApplicantDS,
					errors,
					i;

				that.enableButtons(false, true);
				errors = applicantDS.transport.jsdo.getErrors();
				for (i = 0; i < errors.length; i += 1) {
					console.log(errors[i].error);
				}

				applicantDS.cancelChanges();
			}); // end promise.fail
		}
	}

	// When bEnable is false, all buttons except for the Save and Cancel
	//buttons should be disabled. In this scenario, user, for example,
	// just selected "Create", so must either hit "Save" to actually
	//create the record or "Cancel" to cancel add.
	// (We'll just leave Save and Cancel buttons as always enabled)
	enableButtons(bEnable, bSaveCancel) {
		var navToolBar = angular.element("#NavToolbar").data("kendoToolBar"),
			updToolBar = angular.element("#UpdToolbar").data("kendoToolBar");

		if (navToolBar && updToolBar) {
			navToolBar.enable("#FirstBtn", bEnable);
			navToolBar.enable("#PrevBtn", bEnable);
			navToolBar.enable("#NextBtn", bEnable);
			navToolBar.enable("#LastBtn", bEnable);

			updToolBar.enable("#NewBtn", bEnable);
			updToolBar.enable("#RemoveBtn", bEnable);

			updToolBar.enable("#SaveBtn", bSaveCancel);
			updToolBar.enable("#CancelBtn", bSaveCancel);
		}
	}

	onNavToolbarClick(e) {
		var that = this,
			applicantDS = this.$ds.ApplicantDS;

		if (applicantDS.hasChanges()) {
			this.scope.$emit('dialog', {
				title: "Changes detected",
				hint: "Are you sure you want to navigate without saving changes?",
				okButton: {
					handler: function () {
						that.$ds.ApplicantDS.cancelChanges();
						that.navigateTo(e.id);
					}
				}
			});
		} else {
			this.navigateTo(e.id);
		}
	}

	navigateTo(id) {
		var applicantDS = this.$ds.ApplicantDS,
			data = applicantDS.data(),
			scope = this.scope,
			// Note: The DataSource pageSize is 1
			currentPage = applicantDS.page();

		switch (id) {
		case "FirstBtn":
			if (applicantDS.totalPages() > 0) {
				applicantDS.page(1);
			}
			break;
		case "PrevBtn":
			if (currentPage > 1) {
				applicantDS.page(currentPage - 1);
			}
			break;
		case "NextBtn":
			if (currentPage < applicantDS.totalPages()) {
				applicantDS.page(currentPage + 1);
			}
			break;
		case "LastBtn":
			if (applicantDS.totalPages() > 0) {
				applicantDS.page(applicantDS.totalPages());
			}
			break;
		}
	}

	onCRUDToolbarClick(e) {
		var applicantDS = this.$ds.ApplicantDS,
			data = applicantDS.data();

		switch (e.id) {
		case "NewBtn":
			this.onCreateClick();
			break;

		case "RemoveBtn":
			this.onRemoveClick();
			break;

		case "SaveBtn":
			this.onSaveClick();
			break;

		case "CancelBtn":
			this.onCancelClick();
			break;

		}
	}

	// For the age comboBox, we are creating a local datasource, and
	// associating it with the comboBox control
	setUpAgeDataSource(view, curRow) {
		var ageComboBox = angular.element("#AgeCB").data("kendoComboBox"),
			dataSource,
			that = this;

		if (ageComboBox) {
			dataSource = new kendo.data.DataSource(
				{data : [25, 30, 35, 40, 45, 50, 55, 60, 65, 70, 75]}
			);
			ageComboBox.setDataSource(dataSource);
		} else {
			console.log("ERROR in SetUpAgeDataSource: AgeCB is not available");
		}
	}

	onChangeAge($scope, customData) {
		var applicantModel = this.$viewModels.ApplicantDSModel,
			age = parseInt($scope.sender.value());

		if (age) {
			applicantModel.Age = age;
		}
	}

}

ApplicantsApplicantViewCtrl.$inject = ['$scope', '$injector', 'stateData'];

export default ApplicantsApplicantViewCtrl


text:
                Casino
                <button class="navbar-toggle" type="button" data-toggle="collapse" data-target="#navbar-main">

                </button>

                        News

                        User Details

                        Balance

                        Games

                         Login

Login

Registration

Send feedback

Logout

        <alert></alert>
        <router-outlet></router-outlet>


text:
import uuid
from msrest.pipeline import ClientRawResponse

from .. import models

class SignedInUserOperations(object):
    """SignedInUserOperations operations.

    :param client: Client for service requests.
    :param config: Configuration of service client.
    :param serializer: An object model serializer.
    :param deserializer: An object model deserializer.
    :ivar api_version: Client API version. Constant value: "1.6".
    """

    models = models

    def __init__(self, client, config, serializer, deserializer):

        self._client = client
        self._serialize = serializer
        self._deserialize = deserializer
        self.api_version = "1.6"

        self.config = config

    def get(
            self, custom_headers=None, raw=False, **operation_config):
        """Gets the details for the currently logged-in user.

        :param dict custom_headers: headers that will be added to the request
        :param bool raw: returns the direct response alongside the
         deserialized response
        :param operation_config: :ref:`Operation configuration
         overrides<msrest:optionsforoperations>`.
        :return: User or ClientRawResponse if raw=true
        :rtype: ~azure.graphrbac.models.User or
         ~msrest.pipeline.ClientRawResponse
        :raises:
         :class:`GraphErrorException<azure.graphrbac.models.GraphErrorException>`
        """
        # Construct URL
        url = self.get.metadata['url']
        path_format_arguments = {
            'tenantID': self._serialize.url("self.config.tenant_id", self.config.tenant_id, 'str')
        }
        url = self._client.format_url(url, **path_format_arguments)

        # Construct parameters
        query_parameters = {}
        query_parameters['api-version'] = self._serialize.query("self.api_version", self.api_version, 'str')

        # Construct headers
        header_parameters = {}
        header_parameters['Accept'] = 'application/json'
        if self.config.generate_client_request_id:
            header_parameters['x-ms-client-request-id'] = str(uuid.uuid1())
        if custom_headers:
            header_parameters.update(custom_headers)
        if self.config.accept_language is not None:
            header_parameters['accept-language'] = self._serialize.header("self.config.accept_language", self.config.accept_language, 'str')

        # Construct and send request
        request = self._client.get(url, query_parameters, header_parameters)
        response = self._client.send(request, stream=False, **operation_config)

        if response.status_code not in [200]:
            raise models.GraphErrorException(self._deserialize, response)

        deserialized = None

        if response.status_code == 200:
            deserialized = self._deserialize('User', response)

        if raw:
            client_raw_response = ClientRawResponse(deserialized, response)
            return client_raw_response

        return deserialized
    get.metadata = {'url': '/{tenantID}/me'}

    def list_owned_objects(
            self, custom_headers=None, raw=False, **operation_config):
        """Get the list of directory objects that are owned by the user.

        :param dict custom_headers: headers that will be added to the request
        :param bool raw: returns the direct response alongside the
         deserialized response
        :param operation_config: :ref:`Operation configuration
         overrides<msrest:optionsforoperations>`.
        :return: An iterator like instance of DirectoryObject
        :rtype:
         ~azure.graphrbac.models.DirectoryObjectPaged[~azure.graphrbac.models.DirectoryObject]
        :raises:
         :class:`GraphErrorException<azure.graphrbac.models.GraphErrorException>`
        """
        def internal_paging(next_link=None, raw=False):

            if not next_link:
                # Construct URL
                url = self.list_owned_objects.metadata['url']
                path_format_arguments = {
                    'tenantID': self._serialize.url("self.config.tenant_id", self.config.tenant_id, 'str')
                }
                url = self._client.format_url(url, **path_format_arguments)

                # Construct parameters
                query_parameters = {}
                query_parameters['api-version'] = self._serialize.query("self.api_version", self.api_version, 'str')

            else:
                url = '/{tenantID}/{nextLink}'
                path_format_arguments = {
                    'nextLink': self._serialize.url("next_link", next_link, 'str', skip_quote=True),
                    'tenantID': self._serialize.url("self.config.tenant_id", self.config.tenant_id, 'str')
                }
                url = self._client.format_url(url, **path_format_arguments)
                query_parameters = {}
                query_parameters['api-version'] = self._serialize.query("self.api_version", self.api_version, 'str')

            # Construct headers
            header_parameters = {}
            header_parameters['Accept'] = 'application/json'
            if self.config.generate_client_request_id:
                header_parameters['x-ms-client-request-id'] = str(uuid.uuid1())
            if custom_headers:
                header_parameters.update(custom_headers)
            if self.config.accept_language is not None:
                header_parameters['accept-language'] = self._serialize.header("self.config.accept_language", self.config.accept_language, 'str')

            # Construct and send request
            request = self._client.get(url, query_parameters, header_parameters)
            response = self._client.send(request, stream=False, **operation_config)

            if response.status_code not in [200]:
                raise models.GraphErrorException(self._deserialize, response)

            return response

        # Deserialize response
        deserialized = models.DirectoryObjectPaged(internal_paging, self._deserialize.dependencies)

        if raw:
            header_dict = {}
            client_raw_response = models.DirectoryObjectPaged(internal_paging, self._deserialize.dependencies, header_dict)
            return client_raw_response

        return deserialized
    list_owned_objects.metadata = {'url': '/{tenantID}/me/ownedObjects'}


text:
<ion-content padding>

These are your total steps walked today. Check if you reached yor goal or not!

</ion-content>


text:
1. Close your IDE.
2. [Figure out where your configuration lives][webstorm-2] (_IDE Settings_ section)
3. Navigate to `your-config-dir/codestyles`. If this directory doesn't exist,
   create it in the WebStorm config settings directory
4. Create a `Standard.xml` file:
  ```xml
    <code_scheme name="Standard">
      <JSCodeStyleSettings>
        <option name="USE_SEMICOLON_AFTER_STATEMENT" value="false" />
        <option name="USE_DOUBLE_QUOTES" value="false" />
        <option name="SPACES_WITHIN_OBJECT_LITERAL_BRACES" value="true" />
        <option name="SPACES_WITHIN_IMPORTS" value="true" />
      </JSCodeStyleSettings>
      <XML>
        <option name="XML_LEGACY_SETTINGS_IMPORTED" value="true" />
      </XML>
      <codeStyleSettings language="JavaScript">
        <option name="KEEP_BLANK_LINES_IN_CODE" value="1" />
        <option name="SPACE_WITHIN_BRACKETS" value="true" />
        <option name="SPACE_BEFORE_METHOD_PARENTHESES" value="true" />
        <option name="KEEP_SIMPLE_BLOCKS_IN_ONE_LINE" value="true" />
        <option name="KEEP_SIMPLE_METHODS_IN_ONE_LINE" value="true" />
        <indentOptions>
          <option name="INDENT_SIZE" value="2" />
          <option name="CONTINUATION_INDENT_SIZE" value="2" />
          <option name="TAB_SIZE" value="2" />
        </indentOptions>
      </codeStyleSettings>
    </code_scheme>
  ```

5. You may install dependencies and config globally or locally and with support of ES7 or without it
  - **Local** install:
    - `npm install --save-dev eslint-config-standard eslint-config-standard-jsx eslint-plugin-promise eslint-plugin-react eslint-plugin-standard`
    - `echo '{"extends": ["standard", "standard-jsx"]}' > .eslintrc`
  - **Global** install:
    - `npm install --global eslint-config-standard eslint-config-standard-jsx eslint-plugin-promise eslint-plugin-react eslint-plugin-standard`
    - `echo '{"extends": ["standard", "standard-jsx"]}' > ~/.eslintrc`

  Be aware: The second command above will overwrite an existing `.eslintrc` if one exists.

  If you choose global install, the first command may require you to use `sudo`. If
  it does require sudo, that means you do not have permission to write to the
  directories that npm uses to store global packages. `Standard` will work, but if
  you would like to fix it, [read this article][npm-article].

6. Start up the IDE and open a _Settings_/_Preferences_ screen (choose between project and default settings accordingly to your preference)
7. Under `Editor > Code Style > JavaScript` change `Scheme` to `Standard`
8. Under `Editor > Inspections > JavaScript > Code style issues` untick `Unterminated statement`
9. Under `Languages & Frameworks > JavaScript > Code Quality Tools > ESLint` just select `Enable`. If you didn't install `ESLint` before and you don't have it in your dependencies - that's all. If you do - be sure to use `ESLint package` of the same version as current version of `standard` is using. Or just remove your old one - you probably won't need it anymore

---

If you're a Webstorm or PhpStorm user, [vote for `standard` to be one of the default styles][webstorm-3]
built into the app.

[npm-article]: https://docs.npmjs.com/getting-started/fixing-npm-permissions
[webstorm-1]: https://www.jetbrains.com/webstorm/
[webstorm-2]: https://www.jetbrains.com/help/phpstorm/2016.1/directories-used-by-phpstorm-to-store-settings-caches-plugins-and-logs.html?origin=old_help#d66583e60
[webstorm-3]: https://youtrack.jetbrains.com/issue/WEB-17331


text:
import remote
import unittest

class testRemote(unittest.TestCase):
    def setUp(self):
        self.con = remote.remote(host="localhost", user='', pswd='')

    def tearDown(self):
        self.con.logout()

    def testRemote1LoginSimple(self):
        msg = "Unable to login"
        self.assertTrue(self.con.login(), msg)

    def testRemote1LoginMultiPass(self):
        msg = "Unable to login with passwd array"
        self.assertTrue(self.con.login(pswd=['']), msg)

    def testRemote1LoginMultiTtl(self):
        msg = "Unable to login with timeout array"
        self.assertTrue(self.con.login(timeout=[15,10,5]), msg)

    def testRemote1LoginMultiPassTtl(self):
        msg = "Unable to login with passwd, timeout array"
        self.assertTrue(self.con.login(pswd=[''], timeout=[15,10,5]), msg)

    def testRemote1LoginHostDosntExist(self):
        msg = "Expected graceful failure of bad hostname"
        self.assertFalse(self.con.login(host="thishostdosntexist"), msg)

    def testRemote1LoginHostDosntExistMultiTtl(self):
        msg = "Expected graceful failure of bad hostname"
        self.assertFalse(self.con.login(host="thishostdosntexist", timeout=[5,4,3,2,1]), msg)

    def testRemote1LoginBadPassSimple(self):
        msg = "Expected graceful failure of bad password"
        pswd = "mamba"
        self.assertFalse(self.con.login(pswd=pswd), msg)

    def testRemote1LoginBadPassMulti(self):
        msg = "Expected graceful failure of bad password list"
        pswd = ["mamba", "tucow", "rose"]
        self.assertFalse(self.con.login(pswd=pswd), msg)

    def testRemote1LoginBadPassMultiTtl(self):
        msg = "Expected graceful failure of bas pswd with ttl array"
        pswd = ["mamba", "tucow", "rose"]
        self.assertFalse(self.con.login(pswd=pswd, timeout=[5,4,3,2,1]), msg)

    def testRemote5GetoutputPwd(self):
        cmd = "pwd"
        msg = "Unable to get pwd output"
        result = self.con.login()
        if (not result):
            raise Error, "Unable to login, test can't continue"
        self.assertTrue(self.con.getoutput(cmd), msg)

    def testRemote6Getrhel(self):
        msg = "Unable to stat /etc/redhat-release"
        result = self.con.login()
        if (not result):
            raise Error, "Unable to login, test can't continue"
        self.assertTrue(self.con.getrhel(), msg)

    def testRemote6Getuname(self):
        msg = "Unable to get output from uname -a"
        result = self.con.login()
        if (not result):
            raise Error, "Unable to login, test can't continue"
        self.assertTrue(self.con.getuname(), msg)

    def testRemote6run(self):
        msg = "Unable to get output and $?"
        cmd = "touch /tmp"
        result = self.con.login()
        if (not result):
            raise Error, "Unable to login, test can't continue"
        self.assertEqual(self.con.run(cmd), (self.con.getoutput(cmd),0), msg)

def suite():
    suite = unittest.TestSuite()
    suite.addTest(unittest.makeSuite(testRemote))
    return suite

if __name__ == '__main__':

    #suiteFew = unittest.TestSuite()
    #suiteFew = suiteFew.addTest(testRemote("testRemoteLoginSimple"))
    #unittest.TextTestRunner(verbosity=2).run(suiteFew)
    results = unittest.TextTestRunner(verbosity=2).run(suite())


text:
#ifndef _MAGICKCORE_MAGICK_H
#define _MAGICKCORE_MAGICK_H

#if defined(__cplusplus) || defined(c_plusplus)
extern "C" {
#endif

typedef enum
{
  UndefinedFormatType,
  ImplicitFormatType,
  ExplicitFormatType
} MagickFormatType;

typedef enum
{
  NoThreadSupport = 0x0000,
  DecoderThreadSupport = 0x0001,
  EncoderThreadSupport = 0x0002
} MagickThreadSupport;

typedef Image
  *DecodeImageHandler(const ImageInfo *,ExceptionInfo *);

typedef MagickBooleanType
  EncodeImageHandler(const ImageInfo *,Image *);

typedef MagickBooleanType
  IsImageFormatHandler(const unsigned char *,const size_t);

typedef struct _MagickInfo
{
  char
    *name,
    *description,
    *version,
    *note,
    *module;

  ImageInfo
    *image_info;

  DecodeImageHandler
    *decoder;

  EncodeImageHandler
    *encoder;

  IsImageFormatHandler
    *magick;

  void
    *client_data;

  MagickBooleanType
    adjoin,
    raw,
    endian_support,
    blob_support,
    seekable_stream;

  MagickFormatType
    format_type;

  MagickStatusType
    thread_support;

  MagickBooleanType
    stealth;

  struct _MagickInfo
    *previous,
    *next;  /* deprecated, use GetMagickInfoList() */

  unsigned long
    signature;
} MagickInfo;

extern MagickExport char
  **GetMagickList(const char *,unsigned long *,ExceptionInfo *);

extern MagickExport const char
  *GetMagickDescription(const MagickInfo *);

extern MagickExport DecodeImageHandler
  *GetImageDecoder(const MagickInfo *);

extern MagickExport EncodeImageHandler
  *GetImageEncoder(const MagickInfo *);

extern MagickExport MagickBooleanType
  GetImageMagick(const unsigned char *,const size_t,char *),
  GetMagickAdjoin(const MagickInfo *),
  GetMagickBlobSupport(const MagickInfo *),
  GetMagickEndianSupport(const MagickInfo *),
  GetMagickRawSupport(const MagickInfo *),
  GetMagickSeekableStream(const MagickInfo *),
  IsMagickInstantiated(void),
  UnregisterMagickInfo(const char *);

extern const MagickExport MagickInfo
  *GetMagickInfo(const char *,ExceptionInfo *),
  **GetMagickInfoList(const char *,unsigned long *,ExceptionInfo *);

extern MagickExport MagickInfo
  *RegisterMagickInfo(MagickInfo *),
  *SetMagickInfo(const char *);

extern MagickExport MagickStatusType
  GetMagickThreadSupport(const MagickInfo *);

extern MagickExport void
  DestroyMagickList(void),
  MagickCoreGenesis(const char *,const MagickBooleanType),
  MagickCoreTerminus(void);

#if defined(__cplusplus) || defined(c_plusplus)
}
#endif

#endif


text:
package org.gradle.api.internal.artifacts.transform;

import org.gradle.api.artifacts.transform.TransformAction;
import org.gradle.api.internal.tasks.properties.InspectionScheme;
import org.gradle.api.internal.tasks.properties.TypeMetadataStore;
import org.gradle.api.internal.tasks.properties.TypeScheme;
import org.gradle.internal.instantiation.InstantiationScheme;

public class ArtifactTransformActionScheme implements TypeScheme {
    private final InstantiationScheme instantiationScheme;
    private final InspectionScheme inspectionScheme;
    private final InstantiationScheme legacyInstantiationScheme;

    public ArtifactTransformActionScheme(InstantiationScheme instantiationScheme, InspectionScheme inspectionScheme, InstantiationScheme legacyInstantiationScheme) {
        this.instantiationScheme = instantiationScheme;
        this.inspectionScheme = inspectionScheme;
        this.legacyInstantiationScheme = legacyInstantiationScheme;
    }

    @Override
    public TypeMetadataStore getMetadataStore() {
        return inspectionScheme.getMetadataStore();
    }

    @Override
    public boolean appliesTo(Class<?> type) {
        return TransformAction.class.isAssignableFrom(type);
    }

    public InspectionScheme getInspectionScheme() {
        return inspectionScheme;
    }

    public InstantiationScheme getInstantiationScheme() {
        return instantiationScheme;
    }

    public InstantiationScheme getLegacyInstantiationScheme() {
        return legacyInstantiationScheme;
    }
}


text:
<?php
/* Ported from Head First Design Patters Examples: http://www.headfirstlabs.com/books/hfdp/
 * Decorator Pattern - Attach additional responsibilities to an object dynamically.
 * Decorators provide a flexible alternative to subclassing for extending functionality.
 */

abstract class Beverage
{
    protected $description = "Unknown Beverage";
    public function getDescription(){ return $this->description; }
    protected abstract function cost();
}

abstract class CondimentDecorator extends Beverage
{
    // In PHP, abstract methods are implicitly passed to their child
    // http://stackoverflow.com/questions/17525620/php-fatal-error-cant-inherit-abstract-function
}

class Espresso extends Beverage{
    public function __construct() { $this->description = "Espresso"; }
    public function cost() { return 1.99; }
}

class HouseBlend extends Beverage{
    public function __construct() { $this->description = "House Blend Coffee"; }
    public function cost() { return .89; }
}

class DarkRoast extends Beverage{
    public function __construct() { $this->description = "Dark Roast"; }
    public function cost() { return .99; }
}

class Decaf extends Beverage{
    public function __construct() { $this->description = "Decaf Coffee"; }
    public function cost() { return 1.05; }
}

class Mocha extends CondimentDecorator{
    private $beverage;

    public function __construct($b) { $this->beverage = $b; }
    public function getDescription() { return $this->beverage->getDescription() . ", Mocha"; }
    public function cost() { return .2 + $this->beverage->cost(); }
}

class Soy extends CondimentDecorator{
    private $beverage;
    public function __construct($b) { $this->beverage = $b; }
    public function getDescription() { return $this->beverage->getDescription() . ", Soy"; }
    public function cost() { return .15 + $this->beverage->cost(); }
}

class Whip extends CondimentDecorator{
    private $beverage;
    public function __construct($b) { $this->beverage = $b; }
    public function getDescription() { return $this->beverage->getDescription() . ", Whip"; }
    public function cost() { return .1 + $this->beverage->cost(); }
}

$beverage = new Espresso();
print $beverage->getDescription() . " $" . $beverage->cost() . "\n";

$beverage2 = new DarkRoast();
$beverage2 = new Mocha($beverage2);
$beverage2 = new Mocha($beverage2);
$beverage2 = new Whip($beverage2);
print $beverage2->getDescription() . " $" . $beverage2->cost() . "\n";

$beverage3 = new HouseBlend();
$beverage3 = new Soy($beverage3);
$beverage3 = new Mocha($beverage3);
$beverage3 = new Whip($beverage3);
print $beverage3->getDescription() . " $" . $beverage3->cost() . "\n";


text:
using std::vector;

#include "cache_replacement_policy.h"

class RoundRobinReplacementPolicy : public CacheReplacementPolicy
{
public:
   RoundRobinReplacementPolicy(UInt32 cache_size, UInt32 associativity, UInt32 cache_line_size);
   ~RoundRobinReplacementPolicy();

   UInt32 getReplacementWay(CacheLineInfo** cache_line_info_array, UInt32 set_num);
   void update(CacheLineInfo** cache_line_info_array, UInt32 set_num, UInt32 accessed_way);

private:
   vector<UInt32> _replacement_index_vec;
};


text:
Decompiling the game
====================

Fortunately, this game can easily be extracted and decompiled. This makes modding much easier--if it was hard, there probably would be no modding framework.

Prerequisites
-------------

You will need a working Python 2 installation. To check, open up a Powershell, command prompt, terminal, or equivalent and execute ``python --version``.

If you get an error such as

    'python' is not recognized as an internal or external command, operable program or batch file

then you have improperly installed Python.

If you get an output that starts with ``Python 3``, you have installed the incorrect version of Python.

If you get an output that starts with ``Python 2``, you have installed the correct version of Python.

Getting media and compiled source code
--------------------------------------

*This assumes you know the basics of command line, such as changing directories.*

* Open up a Powershell, command prompt, terminal, or equivalent
* Make a new folder anywhere and change directories to the new folder
* Copy the archive.rpa from the game directory in the installation folder into the new folder
* Download rpatool_ and extract the file ``rpatool`` into the new folder
* Run ``python rpatool -x archive.rpa``. It might take a while

After the command is executed, a whole plethora of files and folders are made in the new folder. For now, ignore all files with the .rpyc file extension.

Some notable folders include:

+-----------------+-----------------------------------------------------------------+
|     Location    |                             Purpose                             |
+=================+=================================================================+
| achievements    | Contains all the achievement icons                              |
+-----------------+-----------------------------------------------------------------+
| bg              | Contains all the backgrounds                                    |
+-----------------+-----------------------------------------------------------------+
| bg/in           | Contains backgrounds that take place inside                     |
+-----------------+-----------------------------------------------------------------+
| bg/in/apts      | Contains apartment backgrounds                                  |
+-----------------+-----------------------------------------------------------------+
| bg/in/facility  | Contains backgrounds that take place in the production facility |
+-----------------+-----------------------------------------------------------------+
| bg/out          | Contains backgrounds that take place outside                    |
+-----------------+-----------------------------------------------------------------+
| bg/out/facility | Contains backgrounds that is right outside the facility         |
+-----------------+-----------------------------------------------------------------+
| bg/out/np       | Contains backgrounds that take at night time                    |
+-----------------+-----------------------------------------------------------------+
| bg/out/town     | Contains backgrounds of various places in the town              |
+-----------------+-----------------------------------------------------------------+
| cg              | Contains all the characters' CGs among other stuff              |
+-----------------+-----------------------------------------------------------------+
| cg/extra        | Contains all the cards and image gallery photos                 |
+-----------------+-----------------------------------------------------------------+
| cg/lorem        | Contains extra pictures of Lorem and Ispum                      |
+-----------------+-----------------------------------------------------------------+
| cr              | Contains all the characters expressions                         |
+-----------------+-----------------------------------------------------------------+
| fx              | Contains the sound effects                                      |
+-----------------+-----------------------------------------------------------------+
| mx              | Contains all the music the game has to offer                    |
+-----------------+-----------------------------------------------------------------+
| se/sounds       | Contains more sound effects                                     |
+-----------------+-----------------------------------------------------------------+
| sy              | Never before seen photos!                                       |
+-----------------+-----------------------------------------------------------------+

Getting the source code
-----------------------

Source code is the human-readable version of the game. All dialog options, games, and spoilers are in these files.
However, the code is compiled into Ren'Py compiled files. They have an extension of .rpyc.
To get the source code, we need to decompile the game. The source code has an extension of .rpy

* Download _unrpyc and extract the zip file into the new folder
* Run ``python unrpyc.py .``
* *Optional:* Remove the .rpyc files

.. _rpatool: https://github.com/Shizmob/rpatool/archive/master.zip
.. _unrpyc: https://github.com/CensoredUsername/unrpyc/archive/master.zip


text:
<?php

namespace Ergast\Exception;

/**
 * @author Brieuc Thomas <tbrieuc@gmail.com>
 */
class InvalidArgumentException extends \InvalidArgumentException implements ExceptionInterface
{
}


text:
package com.citrix.netscaler.nitro.resource.config.appqoe;

import com.citrix.netscaler.nitro.resource.base.*;
import com.citrix.netscaler.nitro.service.nitro_service;
import com.citrix.netscaler.nitro.service.options;
import com.citrix.netscaler.nitro.util.*;
import com.citrix.netscaler.nitro.exception.nitro_exception;

class appqoepolicy_response extends base_response
{
	public appqoepolicy[] appqoepolicy;
}
/**
* Configuration for AppQoS policy resource.
*/

public class appqoepolicy extends base_resource
{
	private String name;
	private String rule;
	private String action;

	//------- Read only Parameter ---------;

	private Long hits;
	private Long __count;

	/**
	*

	* .
 Minimum length =  1
	*

	*/
	public void set_name(String name) throws Exception{
		this.name = name;
	}

	/**
	*

	* .
 Minimum length =  1
	*

	*/
	public String get_name() throws Exception {
		return this.name;
	}

	/**
	*

	* Expression or name of a named expression, against which the request is evaluated. The policy is applied if the rule evaluates to true.
	*

	*/
	public void set_rule(String rule) throws Exception{
		this.rule = rule;
	}

	/**
	*

	* Expression or name of a named expression, against which the request is evaluated. The policy is applied if the rule evaluates to true.
	*

	*/
	public String get_rule() throws Exception {
		return this.rule;
	}

	/**
	*

	* Configured AppQoE action to trigger.
 Minimum length =  1
	*

	*/
	public void set_action(String action) throws Exception{
		this.action = action;
	}

	/**
	*

	* Configured AppQoE action to trigger.
 Minimum length =  1
	*

	*/
	public String get_action() throws Exception {
		return this.action;
	}

	/**
	*

	* Number of hits.
	*

	*/
	public Long get_hits() throws Exception {
		return this.hits;
	}

	/**
	*

	* converts nitro response into object and returns the object array in case of get request.
	*

	*/
	protected base_resource[] get_nitro_response(nitro_service service, String response) throws Exception{
		appqoepolicy_response result = (appqoepolicy_response) service.get_payload_formatter().string_to_resource(appqoepolicy_response.class, response);
		if(result.errorcode != 0) {
			if (result.errorcode == 444) {
				service.clear_session();
			}
			if(result.severity != null)
			{
				if (result.severity.equals("ERROR"))
					throw new nitro_exception(result.message,result.errorcode);
			}
			else
			{
				throw new nitro_exception(result.message,result.errorcode);
			}
		}
		return result.appqoepolicy;
	}

	/**
	*

	* Returns the value of object identifier argument
	*

	*/

	protected String get_object_name() {
		return this.name;
	}

	/**
	* Use this API to add appqoepolicy.
	*/
	public static base_response add(nitro_service client, appqoepolicy resource) throws Exception {
		appqoepolicy addresource = new appqoepolicy();
		addresource.name = resource.name;
		addresource.rule = resource.rule;
		addresource.action = resource.action;
		return addresource.add_resource(client);
	}

	/**
	* Use this API to add appqoepolicy resources.
	*/
	public static base_responses add(nitro_service client, appqoepolicy resources[]) throws Exception {
		base_responses result = null;
		if (resources != null && resources.length > 0) {
			appqoepolicy addresources[] = new appqoepolicy[resources.length];
			for (int i=0;i<resources.length;i++){
				addresources[i] = new appqoepolicy();
				addresources[i].name = resources[i].name;
				addresources[i].rule = resources[i].rule;
				addresources[i].action = resources[i].action;
			}
			result = add_bulk_request(client, addresources);
		}
		return result;
	}

	/**
	* Use this API to delete appqoepolicy of given name.
	*/
	public static base_response delete(nitro_service client, String name) throws Exception {
		appqoepolicy deleteresource = new appqoepolicy();
		deleteresource.name = name;
		return deleteresource.delete_resource(client);
	}

	/**
	* Use this API to delete appqoepolicy.
	*/
	public static base_response delete(nitro_service client, appqoepolicy resource) throws Exception {
		appqoepolicy deleteresource = new appqoepolicy();
		deleteresource.name = resource.name;
		return deleteresource.delete_resource(client);
	}

	/**
	* Use this API to delete appqoepolicy resources of given names.
	*/
	public static base_responses delete(nitro_service client, String name[]) throws Exception {
		base_responses result = null;
		if (name != null && name.length > 0) {
			appqoepolicy deleteresources[] = new appqoepolicy[name.length];
			for (int i=0;i<name.length;i++){
				deleteresources[i] = new appqoepolicy();
				deleteresources[i].name = name[i];
			}
			result = delete_bulk_request(client, deleteresources);
		}
		return result;
	}

	/**
	* Use this API to delete appqoepolicy resources.
	*/
	public static base_responses delete(nitro_service client, appqoepolicy resources[]) throws Exception {
		base_responses result = null;
		if (resources != null && resources.length > 0) {
			appqoepolicy deleteresources[] = new appqoepolicy[resources.length];
			for (int i=0;i<resources.length;i++){
				deleteresources[i] = new appqoepolicy();
				deleteresources[i].name = resources[i].name;
			}
			result = delete_bulk_request(client, deleteresources);
		}
		return result;
	}

	/**
	* Use this API to update appqoepolicy.
	*/
	public static base_response update(nitro_service client, appqoepolicy resource) throws Exception {
		appqoepolicy updateresource = new appqoepolicy();
		updateresource.name = resource.name;
		updateresource.rule = resource.rule;
		updateresource.action = resource.action;
		return updateresource.update_resource(client);
	}

	/**
	* Use this API to update appqoepolicy resources.
	*/
	public static base_responses update(nitro_service client, appqoepolicy resources[]) throws Exception {
		base_responses result = null;
		if (resources != null && resources.length > 0) {
			appqoepolicy updateresources[] = new appqoepolicy[resources.length];
			for (int i=0;i<resources.length;i++){
				updateresources[i] = new appqoepolicy();
				updateresources[i].name = resources[i].name;
				updateresources[i].rule = resources[i].rule;
				updateresources[i].action = resources[i].action;
			}
			result = update_bulk_request(client, updateresources);
		}
		return result;
	}

	/**
	* Use this API to fetch all the appqoepolicy resources that are configured on netscaler.
	*/
	public static appqoepolicy[] get(nitro_service service) throws Exception{
		appqoepolicy obj = new appqoepolicy();
		appqoepolicy[] response = (appqoepolicy[])obj.get_resources(service);
		return response;
	}
	/**
	* Use this API to fetch all the appqoepolicy resources that are configured on netscaler.
	*/
	public static appqoepolicy[] get(nitro_service service, options option) throws Exception{
		appqoepolicy obj = new appqoepolicy();
		appqoepolicy[] response = (appqoepolicy[])obj.get_resources(service,option);
		return response;
	}
	/**
	* Use this API to fetch appqoepolicy resource of given name .
	*/
	public static appqoepolicy get(nitro_service service, String name) throws Exception{
		appqoepolicy obj = new appqoepolicy();
		obj.set_name(name);
		appqoepolicy response = (appqoepolicy) obj.get_resource(service);
		return response;
	}

	/**
	* Use this API to fetch appqoepolicy resources of given names .
	*/
	public static appqoepolicy[] get(nitro_service service, String name[]) throws Exception{
		if (name !=null && name.length>0) {
			appqoepolicy response[] = new appqoepolicy[name.length];
			appqoepolicy obj[] = new appqoepolicy[name.length];
			for (int i=0;i<name.length;i++) {
				obj[i] = new appqoepolicy();
				obj[i].set_name(name[i]);
				response[i] = (appqoepolicy) obj[i].get_resource(service);
			}
			return response;
		}
		return null;
	}
	/**
	* Use this API to fetch filtered set of appqoepolicy resources.
	* filter string should be in JSON format.eg: "port:80,servicetype:HTTP".
	*/
	public static appqoepolicy[] get_filtered(nitro_service service, String filter) throws Exception{
		appqoepolicy obj = new appqoepolicy();
		options option = new options();
		option.set_filter(filter);
		appqoepolicy[] response = (appqoepolicy[]) obj.getfiltered(service, option);
		return response;
	}

	/**
	* Use this API to fetch filtered set of appqoepolicy resources.
	* set the filter parameter values in filtervalue object.
	*/
	public static appqoepolicy[] get_filtered(nitro_service service, filtervalue[] filter) throws Exception{
		appqoepolicy obj = new appqoepolicy();
		options option = new options();
		option.set_filter(filter);
		appqoepolicy[] response = (appqoepolicy[]) obj.getfiltered(service, option);
		return response;
	}

	/**
	* Use this API to count the appqoepolicy resources configured on NetScaler.
	*/
	public static long count(nitro_service service) throws Exception{
		appqoepolicy obj = new appqoepolicy();
		options option = new options();
		option.set_count(true);
		appqoepolicy[] response = (appqoepolicy[])obj.get_resources(service, option);
		if (response != null) {
			return response[0].__count;
		}
		return 0;
	}

	/**
	* Use this API to count filtered the set of appqoepolicy resources.
	* filter string should be in JSON format.eg: "port:80,servicetype:HTTP".
	*/
	public static long count_filtered(nitro_service service, String filter) throws Exception{
		appqoepolicy obj = new appqoepolicy();
		options option = new options();
		option.set_count(true);
		option.set_filter(filter);
		appqoepolicy[] response = (appqoepolicy[]) obj.getfiltered(service, option);
		if (response != null) {
			return response[0].__count;
		}
		return 0;
	}

	/**
	* Use this API to count the filtered set of appqoepolicy resources.
	* set the filter parameter values in filtervalue object.
	*/
	public static long count_filtered(nitro_service service, filtervalue[] filter) throws Exception{
		appqoepolicy obj = new appqoepolicy();
		options option = new options();
		option.set_count(true);
		option.set_filter(filter);
		appqoepolicy[] response = (appqoepolicy[]) obj.getfiltered(service, option);
		if (response != null) {
			return response[0].__count;
		}
		return 0;
	}

}


text:
from questionanswering import bidictionnary
import re
def process(question, query_builder):
    mapped_question = next(question)
    if ('unemployment' in mapped_question) & ('rate' in mapped_question):
        unemployment_rate = extract_unemployment_rate(mapped_question)
        for rate in unemployment_rate:
            if re.match('^[^.]*$', rate):
                query_builder.with_category_data('unemployment rate', ' '.join(unemployment_rate) + '.*')
            else:
                query_builder.with_category_data('unemployment rate', ' '.join(unemployment_rate))
    yield mapped_question

def extract_unemployment_rate(mappedSentence):
    reverse_dict = bidictionnary.Bidict(mappedSentence)
    return reverse_dict.keys_with_values(['CD'])


text:
__author__ = 'phithon'
import tornado.web
from controller.base import BaseHandler
from tornado import gen
from util.function import not_need_login

class IndexHandler(BaseHandler):

    @not_need_login
    def prepare(self):
        BaseHandler.prepare(self)

    @tornado.web.asynchronous
    @gen.coroutine
    def get(self, *args, **kwargs):
        self.render("index.html")

class IndexInfoHandler(BaseHandler):

    @not_need_login
    def prepare(self):
        BaseHandler.prepare(self)

    @tornado.web.asynchronous
    @gen.coroutine
    def get(self, *args, **kwargs):
        self.write(self.index)

    index = { 'domain': 'jsgen.org',
  'beian': '',
  'title': 'jsGen',
  'url': 'http://www.jsgen.org',
  'logo': '/static/img/logo.png',
  'description': 'You can generate a beautiful website or blog with javascript!',
  'metatitle': 'jsGen',
  'metadesc': 'You can generate a beautiful website or blog with javascript!',
  'keywords': 'jsGen,Node.js,MongoDB',
  'date': 1452827445323,
  'onlineNum': 2,
  'onlineUsers': 2,
  'maxOnlineNum': 2,
  'maxOnlineTime': 1452836161181,
  'ArticleTagsMax': 5,
  'UserTagsMax': 10,
  'TitleMinLen': 12,
  'TitleMaxLen': 90,
  'SummaryMaxLen': 420,
  'ContentMinLen': 24,
  'ContentMaxLen': 20480,
  'UserNameMinLen': 5,
  'UserNameMaxLen': 15,
  'register': True,
  'upload': False,
  'cloudDomian': '',
  'tagsList': ['为什么','你','这么','叼'],
  'user': None }


text:
<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;

use App\Http\Requests;
use App\Http\Controllers\Controller;
use Omnipay\Omnipay;
use App\User;
use Session, Auth, Input, Redirect;

class PaymentController extends Controller
{

  protected $paypal_username = 'your_paypal_username';
  protected $paypal_password = 'your_paypal_password';
  protected $paypal_signature = 'your_paypal_signature';
  protected $paypal_testmode = true;

  public function postPayment()
  {
    $params = array(
    'cancelUrl' 	=> url() . '/deposit/cancel-deposit',
    'returnUrl' 	=> url() . '/deposit/payment-success',
    'name'		=> 'Deposit',
    'description' 	=> 'Deposit',
    'amount' 	=> Input::get('amount'),
    'currency' 	=> 'USD'
    );

    Session::put('params', $params);
    Session::save();

    $gateway = Omnipay::create('PayPal_Express');
    $gateway->setUsername(env('PAYPAL_USERNAME', $this->paypal_username));
    $gateway->setPassword(env('PAYPAL_PASSWORD', $this->paypal_password));
    $gateway->setSignature(env('PAYPAL_SIGNATURE', $this->paypal_signature));
    $gateway->setTestMode(env('PAYPAL_TESTMODE', $this->paypal_testmode));

    $response = $gateway->purchase($params)->send();

    if ($response->isSuccessful()) {
    //print_r($response);
    } elseif ($response->isRedirect()) {
    // redirect to offsite payment gateway
    $response->redirect();
    } else {
    // payment failed: display message to customer
    echo $response->getMessage();
    }
  }

  public function getSuccessPayment()
  {
    $gateway = Omnipay::create('PayPal_Express');
    $gateway->setUsername(env('PAYPAL_USERNAME', $this->paypal_username));
    $gateway->setPassword(env('PAYPAL_PASSWORD', $this->paypal_password));
    $gateway->setSignature(env('PAYPAL_SIGNATURE', $this->paypal_signature));
    $gateway->setTestMode(env('PAYPAL_TESTMODE', $this->paypal_testmode));

    $params = Session::get('params');

    $response = $gateway->completePurchase($params)->send();
    $paypalResponse = $response->getData(); // this is the raw response object

    if(isset($paypalResponse['PAYMENTINFO_0_ACK']) && $paypalResponse['PAYMENTINFO_0_ACK'] === 'Success') {

    $users = User::find(Auth::user()->id);
    $users->balance = Auth::user()->balance + $paypalResponse['PAYMENTINFO_0_AMT'];
    $users->save();
    // Response
    // print_r($paypalResponse);
    } else {
    //Failed transaction
    }
    Session::flash('message', 'You have successfully deposit');
    return Redirect::to('deposit');
  }

  public function cancelOrderPayment()
  {
    Session::flash('message', 'Deposit has been canceled');
    return Redirect::to('deposit');
  }
}


text:
URL normalisation for Express and Connect

## About

### Taking care of
* trailing slashes
* repeated slashes
* repeated question marks
* repeated ampersands
* repeated query strings
* case sensitivity

### Redirect example
```
request:  //sLuG??param=val&&param2=val2
response: /slug/?param=val&param2=val2
```

## Installation
```sh
$ npm install express-url
```

## Usage

### As middelware
```js
// Require module
var expurl = require('express-url');

// Process routes through middleware
app.use(expurl());
```

### Middelware options
```js
app.use(expurl({
    requestType: 'GET',
    redirectStatusCode: 302,
    lowercase: true,
    trailingSlash: true,
    repetedSlash: true,
    repeatedQuestionMark: true,
    repeatedAmpersand: true
}));
```

## Tests

```sh
$ npm install
$ cd node_modules/express-url
$ npm test
```

## Recommendations
* do not serve static files with node directly
* use case sensitive and strict routing

```js
app.set('case sensitive routing', true);
app.set('strict routing', true);
```


text:
<?php

namespace Equip\Resolver;

use Auryn\Injector;
use Relay\ResolverInterface;

class AurynResolver implements ResolverInterface
{
    /**
     * @var Injector
     */
    private $injector;

    public function __construct(Injector $injector)
    {
        $this->injector = $injector;
    }

    /**
     * Resolve a class spec into an object, if it is not already instantiated.
     *
     * @param string|object $specOrObject
     *
     * @return object
     */
    public function __invoke($specOrObject)
    {
        if (is_object($specOrObject)) {
            return $specOrObject;
        }

        return $this->injector->make($specOrObject);
    }
}


text:
package consulo.csharp.lang.psi.impl.source;

import javax.annotation.Nonnull;
import javax.annotation.Nullable;

import consulo.annotation.access.RequiredReadAction;
import consulo.csharp.lang.psi.CSharpElementVisitor;
import consulo.csharp.lang.psi.CSharpNullableType;
import consulo.csharp.lang.psi.CSharpStubElements;
import consulo.csharp.lang.psi.CSharpTokens;
import consulo.csharp.lang.psi.impl.CSharpNullableTypeUtil;
import consulo.dotnet.psi.DotNetType;
import consulo.dotnet.resolve.DotNetTypeRef;
import com.intellij.lang.ASTNode;
import com.intellij.psi.PsiElement;
import com.intellij.psi.stubs.EmptyStub;
import com.intellij.psi.stubs.IStubElementType;

/**
 * @author VISTALL
 * @since 17.04.14
 */
public class CSharpStubNullableTypeImpl extends CSharpStubTypeElementImpl<EmptyStub<CSharpNullableType>> implements CSharpNullableType
{
	public CSharpStubNullableTypeImpl(@Nonnull ASTNode node)
	{
		super(node);
	}

	public CSharpStubNullableTypeImpl(@Nonnull EmptyStub<CSharpNullableType> stub,
			@Nonnull IStubElementType<? extends EmptyStub<CSharpNullableType>, ?> nodeType)
	{
		super(stub, nodeType);
	}

	@Override
	public void accept(@Nonnull CSharpElementVisitor visitor)
	{
		visitor.visitNullableType(this);
	}

	@Override
	@Nonnull
	@RequiredReadAction
	public DotNetTypeRef toTypeRefImpl()
	{
		DotNetType innerType = getInnerType();
		if(innerType == null)
		{
			return DotNetTypeRef.ERROR_TYPE;
		}
		return CSharpNullableTypeUtil.box(innerType.toTypeRef());
	}

	@RequiredReadAction
	@Override
	@Nullable
	public DotNetType getInnerType()
	{
		return getStubOrPsiChildByIndex(CSharpStubElements.TYPE_SET, 0);
	}

	@RequiredReadAction
	@Override
	@Nonnull
	public PsiElement getQuestElement()
	{
		return findNotNullChildByType(CSharpTokens.QUEST);
	}
}


text:
@implementation NSDictionary(MPCaseInsensitive)

- (NSString *)caseInsensitiveKey:(NSString *)key {
    __block NSString *localKey = nil;

    @try {
        NSString *lowerCaseKey = [key lowercaseString];
        NSArray *keys = [self allKeys];
        [keys enumerateObjectsWithOptions:NSEnumerationConcurrent
                               usingBlock:^(NSString *aKey, NSUInteger idx, BOOL *stop) {
                                   if ([lowerCaseKey isEqualToString:[aKey lowercaseString]]) {
                                       localKey = aKey;
                                       *stop = YES;
                                   }
                               }];
    } @catch (NSException *exception) {
        MPILogError(@"Exception retrieving case insentitive key: %@", [exception reason]);
    }

    if (!localKey) {
        localKey = key;
    }

    return localKey;
}

- (id)valueForCaseInsensitiveKey:(NSString *)key {
    __block id value = nil;

    @try {
        NSString *lowerCaseKey = [key lowercaseString];
        NSArray *keys = [self allKeys];
        [keys enumerateObjectsWithOptions:NSEnumerationConcurrent
                               usingBlock:^(NSString *aKey, NSUInteger idx, BOOL *stop) {
                                   if ([lowerCaseKey isEqualToString:[aKey lowercaseString]]) {
                                       value = self[aKey];
                                       *stop = YES;
                                   }
                               }];
    } @catch (NSException *exception) {
        MPILogError(@"Exception retrieving case insentitive value: %@", [exception reason]);
    }

    return value;
}

- (NSDictionary<NSString *, NSString *> *)transformValuesToString {
    NSDictionary *originalDictionary = self;
    __block NSMutableDictionary<NSString *, NSString *> *transformedDictionary = [[NSMutableDictionary alloc] initWithCapacity:originalDictionary.count];
    Class NSStringClass = [NSString class];
    Class NSNumberClass = [NSNumber class];

    [originalDictionary enumerateKeysAndObjectsUsingBlock:^(id key, id obj, BOOL *stop) {
        if ([obj isKindOfClass:NSStringClass]) {
            transformedDictionary[key] = obj;
        } else if ([obj isKindOfClass:NSNumberClass]) {
            NSNumber *numberAttribute = (NSNumber *)obj;

            if (numberAttribute == (void *)kCFBooleanFalse || numberAttribute == (void *)kCFBooleanTrue) {
                transformedDictionary[key] = [numberAttribute boolValue] ? @"Y" : @"N";
            } else {
                transformedDictionary[key] = [numberAttribute stringValue];
            }
        } else if ([obj isKindOfClass:[NSDate class]]) {
            transformedDictionary[key] = [MPDateFormatter stringFromDateRFC3339:obj];
        } else if ([obj isKindOfClass:[NSData class]] && [(NSData *)obj length] > 0) {
            transformedDictionary[key] = [[NSString alloc] initWithData:obj encoding:NSUTF8StringEncoding];
        } else {
            MPILogError(@"Data type is not supported as an attribute value: %@ - %@", obj, [[obj class] description]);
            NSAssert([obj isKindOfClass:[NSString class]], @"Data type is not supported as an attribute value");
            return;
        }
    }];

    return (NSDictionary *)transformedDictionary;
}

@end


text:
import uuid

from nose.plugins.attrib import attr as tag

import murano.tests.functional.common.utils as common_utils
import murano.tests.functional.integration.integration_base as core

class MistralTest(core.MistralIntegration):

    @classmethod
    def setUpClass(cls):
        super(MistralTest, cls).setUpClass()

        try:
            # Upload the Murano test package.
            cls.upload_mistral_showcase_app()

        except Exception:
            cls.tearDownClass()
            raise

    @classmethod
    def tearDownClass(cls):
        with common_utils.ignored(Exception):
            cls.purge_environments()
        with common_utils.ignored(Exception):
            cls.purge_uploaded_packages()

    @tag('all', 'coverage')
    def test_deploy_package_success(self):
        # Test expects successful deployment and one output: input_1_value.

        # Create env json string.
        post_body = self._create_env_body()

        environment_name = 'Mistral_environment' + uuid.uuid4().hex[:5]

        # Deploy the environment.
        env = self.deploy_apps(environment_name, post_body)

        status = self.wait_for_final_status(env)

        self.assertIn("ready", status[0],
                      "Unexpected status : " + status[0])
        self.assertIn("input_1_value", status[1],
                      "Unexpected output value: " + status[1])


text:
<!DOCTYPE html>

<link rel="help" href="https://crbug.com/976397">