text:
void
Unicode2UTF(
    LPCWSTR wszSrc, // The string to convert.
  __out_ecount(cbDst)
    LPUTF8  szDst,  // Buffer for the output UTF8 string.
    int     cbDst)  // Size of the buffer for UTF8 string.
{
    int cchSrc = (int)wcslen(wszSrc);
    int cchRet;

    cchRet = WszWideCharToMultiByte(
        CP_UTF8,
        0,
        wszSrc,
        cchSrc + 1,
        szDst,
        cbDst,
        NULL,
        NULL);

    if (cchRet == 0)
    {
        _ASSERTE_MSG(FALSE, "Converting unicode string to UTF8 string failed!");
        szDst[0] = '\0';
    }
} // Unicode2UTF

HRESULT HENUMInternal::CreateSimpleEnum(
    DWORD           tkKind,             // kind of token that we are iterating
    ULONG           ridStart,           // starting rid
    ULONG           ridEnd,             // end rid
    HENUMInternal   **ppEnum)           // return the created HENUMInternal
{
    HENUMInternal   *pEnum;
    HRESULT         hr = NOERROR;

    // Don't create an empty enum.
    if (ridStart >= ridEnd)
    {
        *ppEnum = 0;
        goto ErrExit;
    }

    pEnum = new (nothrow) HENUMInternal;

    // check for out of memory error
    if (pEnum == NULL)
        IfFailGo( E_OUTOFMEMORY );

    memset(pEnum, 0, sizeof(HENUMInternal));
    pEnum->m_tkKind = tkKind;
    pEnum->m_EnumType = MDSimpleEnum;
    pEnum->u.m_ulStart = pEnum->u.m_ulCur = ridStart;
    pEnum->u.m_ulEnd = ridEnd;
    pEnum->m_ulCount = ridEnd - ridStart;

    *ppEnum = pEnum;
ErrExit:
    return hr;

}   // CreateSimpleEnum

//*****************************************************************************
// Helper function to destroy Enumerator
//*****************************************************************************
void HENUMInternal::DestroyEnum(
    HENUMInternal   *pmdEnum)
{
    if (pmdEnum == NULL)
        return;

    if (pmdEnum->m_EnumType == MDDynamicArrayEnum)
    {
        TOKENLIST       *pdalist;
        pdalist = (TOKENLIST *) &(pmdEnum->m_cursor);

        // clear the embedded dynamic array before we delete the enum
        pdalist->Clear();
    }
    delete pmdEnum;
}   // DestroyEnum

//*****************************************************************************
// Helper function to destroy Enumerator if the enumerator is empty
//*****************************************************************************
void HENUMInternal::DestroyEnumIfEmpty(
    HENUMInternal   **ppEnum)           // reset the enumerator pointer to NULL if empty
{

    if (*ppEnum == NULL)
        return;

    _ASSERTE((*ppEnum)->m_EnumType != MDCustomEnum);

    if ((*ppEnum)->m_ulCount == 0)
    {
        HENUMInternal::DestroyEnum(*ppEnum);
        *ppEnum = NULL;
    }
}   // DestroyEnumIfEmpty

void HENUMInternal::ClearEnum(
    HENUMInternal   *pmdEnum)
{
    if (pmdEnum == NULL)
        return;

    if (pmdEnum->m_EnumType == MDDynamicArrayEnum)
    {
        TOKENLIST       *pdalist;
        pdalist = (TOKENLIST *) &(pmdEnum->m_cursor);

        // clear the embedded dynamic array before we delete the enum
        pdalist->Clear();
    }
}   // ClearEnum

//*****************************************************************************
// Helper function to iterate the enum
//*****************************************************************************
bool HENUMInternal::EnumNext(
    HENUMInternal *phEnum,              // [IN] the enumerator to retrieve information
    mdToken     *ptk)                   // [OUT] token to scope the search
{
    _ASSERTE(phEnum && ptk);
    _ASSERTE(phEnum->m_EnumType != MDCustomEnum);

    if (phEnum->u.m_ulCur >= phEnum->u.m_ulEnd)
        return false;

    if ( phEnum->m_EnumType == MDSimpleEnum )
    {
        *ptk = phEnum->u.m_ulCur | phEnum->m_tkKind;
        phEnum->u.m_ulCur++;
    }
    else
    {
        TOKENLIST       *pdalist = (TOKENLIST *)&(phEnum->m_cursor);

        _ASSERTE( phEnum->m_EnumType == MDDynamicArrayEnum );
        *ptk = *( pdalist->Get(phEnum->u.m_ulCur++) );
    }
    return true;
}   // EnumNext

//*****************************************************************************
// Number of items in the enumerator.
//*****************************************************************************
HRESULT HENUMInternal::GetCount(
    HENUMInternal   *phEnum,            // [IN] the enumerator to retrieve information
    ULONG           *pCount)            // ]OUT] the index of the desired item
{
    // Check for empty enum.
    if (phEnum == 0)
        return S_FALSE;

    _ASSERTE(phEnum->m_EnumType != MDCustomEnum);

    *pCount = phEnum->u.m_ulEnd - phEnum->u.m_ulStart;
    return S_OK;
}

//*****************************************************************************
// Get a specific element.
//*****************************************************************************
HRESULT HENUMInternal::GetElement(
    HENUMInternal   *phEnum,            // [IN] the enumerator to retrieve information
    ULONG           ix,                 // ]IN] the index of the desired item
    mdToken         *ptk)               // [OUT] token to fill
{
    // Check for empty enum.
    if (phEnum == 0)
        return S_FALSE;

    if (ix > (phEnum->u.m_ulEnd - phEnum->u.m_ulStart))
        return S_FALSE;

    if ( phEnum->m_EnumType == MDSimpleEnum )
    {
        *ptk = (phEnum->u.m_ulStart + ix) | phEnum->m_tkKind;
    }
    else
    {
        TOKENLIST       *pdalist = (TOKENLIST *)&(phEnum->m_cursor);

        _ASSERTE( phEnum->m_EnumType == MDDynamicArrayEnum );
        *ptk = *( pdalist->Get(ix) );
    }

    return S_OK;
}

//*****************************************************************************
// Helper function to fill output token buffers given an enumerator
//*****************************************************************************
HRESULT HENUMInternal::EnumWithCount(
    HENUMInternal   *pEnum,             // enumerator
    ULONG           cMax,               // max tokens that caller wants
    mdToken         rTokens[],          // output buffer to fill the tokens
    ULONG           *pcTokens)          // number of tokens fill to the buffer upon return
{
    ULONG           cTokens;
    HRESULT         hr = NOERROR;

    // Check for empty enum.
    if (pEnum == 0)
    {
        if (pcTokens)
            *pcTokens = 0;
        return S_FALSE;
    }

    // we can only fill the minimun of what caller asked for or what we have left
    cTokens = min ( (pEnum->u.m_ulEnd - pEnum->u.m_ulCur), cMax);

    if (pEnum->m_EnumType == MDSimpleEnum)
    {

        // now fill the output
        for (ULONG i = 0; i < cTokens; i ++, pEnum->u.m_ulCur++)
        {
            rTokens[i] = TokenFromRid(pEnum->u.m_ulCur, pEnum->m_tkKind);
        }

    }
    else
    {
        // cannot be any other kind!
        _ASSERTE( pEnum->m_EnumType == MDDynamicArrayEnum );

        // get the embedded dynamic array
        TOKENLIST       *pdalist = (TOKENLIST *)&(pEnum->m_cursor);

        for (ULONG i = 0; i < cTokens; i ++, pEnum->u.m_ulCur++)
        {
            rTokens[i] = *( pdalist->Get(pEnum->u.m_ulCur) );
        }
    }

    if (pcTokens)
        *pcTokens = cTokens;

    if (cTokens == 0)
        hr = S_FALSE;
    return hr;
}   // EnumWithCount

//*****************************************************************************
// Helper function to fill output token buffers given an enumerator
// This is a variation that takes two output arrays.  The tokens in the
// enumerator are interleaved, one for each array.  This is currently used by
// EnumMethodImpl which needs to return two arrays.
//*****************************************************************************
HRESULT HENUMInternal::EnumWithCount(
    HENUMInternal   *pEnum,             // enumerator
    ULONG           cMax,               // max tokens that caller wants
    mdToken         rTokens1[],         // first output buffer to fill the tokens
    mdToken         rTokens2[],         // second output buffer to fill the tokens
    ULONG           *pcTokens)          // number of tokens fill to each buffer upon return
{
    ULONG           cTokens;
    HRESULT         hr = NOERROR;

    // cannot be any other kind!
    _ASSERTE( pEnum->m_EnumType == MDDynamicArrayEnum );

    // Check for empty enum.
    if (pEnum == 0)
    {
        if (pcTokens)
            *pcTokens = 0;
        return S_FALSE;
    }

    // Number of tokens must always be a multiple of 2.
    _ASSERTE(! ((pEnum->u.m_ulEnd - pEnum->u.m_ulCur) % 2) );

    // we can only fill the minimun of what caller asked for or what we have left
    cTokens = min ( (pEnum->u.m_ulEnd - pEnum->u.m_ulCur), cMax * 2);

    // get the embedded dynamic array
    TOKENLIST       *pdalist = (TOKENLIST *)&(pEnum->m_cursor);

    for (ULONG i = 0; i < (cTokens / 2); i++)
    {
        rTokens1[i] = *( pdalist->Get(pEnum->u.m_ulCur++) );
        rTokens2[i] = *( pdalist->Get(pEnum->u.m_ulCur++) );
    }

    if (pcTokens)
        *pcTokens = cTokens / 2;

    if (cTokens == 0)
        hr = S_FALSE;
    return hr;
}   // EnumWithCount

//*****************************************************************************
// Helper function to create HENUMInternal
//*****************************************************************************
HRESULT HENUMInternal::CreateDynamicArrayEnum(
    DWORD           tkKind,             // kind of token that we are iterating
    HENUMInternal   **ppEnum)           // return the created HENUMInternal
{
    HENUMInternal   *pEnum;
    HRESULT         hr = NOERROR;
    TOKENLIST       *pdalist;

    pEnum = new (nothrow) HENUMInternal;

    // check for out of memory error
    if (pEnum == NULL)
        IfFailGo( E_OUTOFMEMORY );

    memset(pEnum, 0, sizeof(HENUMInternal));
    pEnum->m_tkKind = tkKind;
    pEnum->m_EnumType = MDDynamicArrayEnum;

    // run the constructor in place
    pdalist = (TOKENLIST *) &(pEnum->m_cursor);
    ::new (pdalist) TOKENLIST;

    *ppEnum = pEnum;
ErrExit:
    return hr;

}   // _CreateDynamicArrayEnum

//*****************************************************************************
// Helper function to init HENUMInternal
//*****************************************************************************
void HENUMInternal::InitDynamicArrayEnum(
    HENUMInternal   *pEnum)             // HENUMInternal to be initialized
{
    TOKENLIST       *pdalist;

    memset(pEnum, 0, sizeof(HENUMInternal));
    pEnum->m_EnumType = MDDynamicArrayEnum;
    pEnum->m_tkKind = (DWORD) -1;

    // run the constructor in place
    pdalist = (TOKENLIST *) &(pEnum->m_cursor);
    ::new (pdalist) TOKENLIST;
}   // CreateDynamicArrayEnum

//*****************************************************************************
// Helper function to init HENUMInternal
//*****************************************************************************
void HENUMInternal::InitSimpleEnum(
    DWORD           tkKind,             // kind of token that we are iterating
    ULONG           ridStart,           // starting rid
    ULONG           ridEnd,             // end rid
    HENUMInternal   *pEnum)             // HENUMInternal to be initialized
{
    pEnum->m_EnumType = MDSimpleEnum;
    pEnum->m_tkKind = tkKind;
    pEnum->u.m_ulStart = pEnum->u.m_ulCur = ridStart;
    pEnum->u.m_ulEnd = ridEnd;
    pEnum->m_ulCount = ridEnd - ridStart;

}   // InitSimpleEnum

//*****************************************************************************
// Helper function to init HENUMInternal
//*****************************************************************************
HRESULT HENUMInternal::AddElementToEnum(
    HENUMInternal   *pEnum,             // return the created HENUMInternal
    mdToken         tk)                 // token value to be stored
{
    HRESULT         hr = NOERROR;
    TOKENLIST       *pdalist;
    mdToken         *ptk;

    pdalist = (TOKENLIST *) &(pEnum->m_cursor);

        {
        // TODO: Revisit this violation.
        CONTRACT_VIOLATION(ThrowsViolation);
    ptk = ((mdToken *)pdalist->Append());
        }
    if (ptk == NULL)
        IfFailGo( E_OUTOFMEMORY );
    *ptk = tk;

    // increase the count
    pEnum->m_ulCount++;
    pEnum->u.m_ulEnd++;
ErrExit:
    return hr;

}   // _AddElementToEnum

//*****************************************************************************
// find a token in the tokenmap.
//*****************************************************************************
MDTOKENMAP::~MDTOKENMAP()
{
    if (m_pMap)
        m_pMap->Release();
} // MDTOKENMAP::~MDTOKENMAP()

HRESULT MDTOKENMAP::Init(
    IUnknown    *pImport)               // The import that this map is for.
{
    HRESULT     hr;                     // A result.
    IMetaDataTables *pITables=0;        // Table information.
    ULONG       cRows;                  // Count of rows in a table.
    ULONG       cTotal;                 // Running total of rows in db.
    TOKENREC    *pRec;                  // A TOKENREC record.
    mdToken     tkTable;                // Token kind for a table.

    hr = pImport->QueryInterface(IID_IMetaDataTables, (void**)&pITables);
    if (hr == S_OK)
    {
        // Determine the size of each table.
        cTotal = 0;
        for (ULONG ixTbl=0; ixTbl<TBL_COUNT; ++ixTbl)
        {
            // Where does this table's data start.
            m_TableOffset[ixTbl] = cTotal;
            // See if this table has tokens.
            tkTable = CMiniMdRW::GetTokenForTable(ixTbl);
            if (tkTable == (ULONG) -1)
            {
                // It doesn't have tokens, so we won't see any tokens for the table.
            }
            else
            {   // It has tokens, so we may see a token for every row.
                pITables->GetTableInfo(ixTbl, 0, &cRows, 0,0,0);
                // Safe: cTotal += cRows
                if (!ClrSafeInt<ULONG>::addition(cTotal, cRows, cTotal))
                {
                    IfFailGo(COR_E_OVERFLOW);
                }
            }
        }
        m_TableOffset[TBL_COUNT] = cTotal;
        m_iCountIndexed = cTotal;
        // Attempt to allocate space for all of the possible remaps.
        if (!AllocateBlock(cTotal))
            IfFailGo(E_OUTOFMEMORY);
        // Note that no sorts are needed.
        m_sortKind = Indexed;
        // Initialize entries to "not found".
        for (ULONG i=0; i<cTotal; ++i)
        {
            pRec = Get(i);
            pRec->SetEmpty();
        }
    }
#if defined(_DEBUG)
    if (SUCCEEDED(pImport->QueryInterface(IID_IMetaDataImport, (void**)&m_pImport)))
    {
        // Ok, here's a pretty nasty workaround. We're going to make a big assumption here
        // that we're owned by the pImport, and so we don't need to keep a refcount
        // on the pImport object.
        //
        // If we did, we'd create a circular reference and neither this object nor
        // the RegMeta would be freed.
        m_pImport->Release();

    }

#endif

ErrExit:
    if (pITables)
        pITables->Release();
    return hr;
} // HRESULT MDTOKENMAP::Init()

HRESULT MDTOKENMAP::EmptyMap()
{
    int nCount = Count();
    for (int i=0; i<nCount; ++i)
    {
        Get(i)->SetEmpty();
    }

    return S_OK;
}// HRESULT MDTOKENMAP::Clear()

//*****************************************************************************
// find a token in the tokenmap.
//*****************************************************************************
bool MDTOKENMAP::Find(
    mdToken     tkFind,                 // [IN] the token value to find
    TOKENREC    **ppRec)                // [OUT] point to the record found in the dynamic array
{
    int         lo,mid,hi;              // binary search indices.
    TOKENREC    *pRec = NULL;

    if (m_sortKind == Indexed && TypeFromToken(tkFind) != mdtString)
    {
        // Get the entry.
        ULONG ixTbl = CMiniMdRW::GetTableForToken(tkFind);
        if(ixTbl == (ULONG) -1)
            return false;
        ULONG iRid = RidFromToken(tkFind);
        if((m_TableOffset[ixTbl] + iRid) > m_TableOffset[ixTbl+1])
            return false;
        pRec = Get(m_TableOffset[ixTbl] + iRid - 1);
        // See if it has been set.
        if (pRec->IsEmpty())
            return false;
        // Verify that it is what we think it is.
        _ASSERTE(pRec->m_tkFrom == tkFind);
        *ppRec = pRec;
        return true;
    }
    else
    {   // Shouldn't be any unsorted records, and table must be sorted in proper ordering.
        _ASSERTE( m_iCountTotal == m_iCountSorted &&
            (m_sortKind == SortByFromToken || m_sortKind == Indexed) );
        _ASSERTE( (m_iCountIndexed + m_iCountTotal) == (ULONG)Count() );

        // Start with entire table.
        lo = m_iCountIndexed;
        hi = Count() - 1;

        // While there are rows in the range...
        while (lo <= hi)
        {   // Look at the one in the middle.
            mid = (lo + hi) / 2;

            pRec = Get(mid);

            // If equal to the target, done.
            if (tkFind == pRec->m_tkFrom)
            {
                *ppRec = Get(mid);
                return true;
            }

            // If middle item is too small, search the top half.
            if (pRec->m_tkFrom < tkFind)
                lo = mid + 1;
            else // but if middle is to big, search bottom half.
                hi = mid - 1;
        }
    }

    // Didn't find anything that matched.
    return false;
} // bool MDTOKENMAP::Find()

//*****************************************************************************
// remap the token
//*****************************************************************************
HRESULT MDTOKENMAP::Remap(
    mdToken     tkFrom,
    mdToken     *ptkTo)
{
    HRESULT     hr = NOERROR;
    TOKENREC    *pRec;

    // Remap nil to same thing (helps because System.Object has no base class.)
    if (IsNilToken(tkFrom))
    {
        *ptkTo = tkFrom;
        return hr;
    }

    if ( Find(tkFrom, &pRec) )
    {
        *ptkTo = pRec->m_tkTo;
    }
    else
    {
        _ASSERTE( !" Bad lookup map!");
        hr = META_E_BADMETADATA;
    }
    return hr;
} // HRESULT MDTOKENMAP::Remap()

//*****************************************************************************
// find a token in the tokenmap.
//*****************************************************************************
HRESULT MDTOKENMAP::InsertNotFound(
    mdToken     tkFind,
    bool        fDuplicate,
    mdToken     tkTo,
    TOKENREC    **ppRec)
{
    HRESULT     hr = NOERROR;
    int         lo, mid, hi;                // binary search indices.
    TOKENREC    *pRec;

    // If possible, validate the input.
    _ASSERTE(!m_pImport || m_pImport->IsValidToken(tkFind));

    if (m_sortKind == Indexed && TypeFromToken(tkFind) != mdtString)
    {
        // Get the entry.
        ULONG ixTbl = CMiniMdRW::GetTableForToken(tkFind);
        _ASSERTE(ixTbl != (ULONG) -1);
        ULONG iRid = RidFromToken(tkFind);
        _ASSERTE((m_TableOffset[ixTbl] + iRid) <= m_TableOffset[ixTbl+1]);
        pRec = Get(m_TableOffset[ixTbl] + iRid - 1);
        // See if it has been set.
        if (!pRec->IsEmpty())
        {   // Verify that it is what we think it is.
            _ASSERTE(pRec->m_tkFrom == tkFind);
        }
        // Store the data.
        pRec->m_tkFrom = tkFind;
        pRec->m_isDuplicate = fDuplicate;
        pRec->m_tkTo = tkTo;
        pRec->m_isFoundInImport = false;
        // Return the result.
        *ppRec = pRec;
    }
    else
    {   // Shouldn't be any unsorted records, and table must be sorted in proper ordering.
        _ASSERTE( m_iCountTotal == m_iCountSorted &&
            (m_sortKind == SortByFromToken || m_sortKind == Indexed) );

        if ((Count() - m_iCountIndexed) > 0)
        {
            // Start with entire table.
            lo = m_iCountIndexed;
            hi = Count() - 1;

            // While there are rows in the range...
            while (lo < hi)
            {   // Look at the one in the middle.
                mid = (lo + hi) / 2;

                pRec = Get(mid);

                // If equal to the target, done.
                if (tkFind == pRec->m_tkFrom)
                {
                    *ppRec = Get(mid);
                    goto ErrExit;
                }

                // If middle item is too small, search the top half.
                if (pRec->m_tkFrom < tkFind)
                    lo = mid + 1;
                else // but if middle is to big, search bottom half.
                    hi = mid - 1;
            }
            _ASSERTE(hi <= lo);
            pRec = Get(lo);

            if (tkFind == pRec->m_tkFrom)
            {
                if (tkTo == pRec->m_tkTo && fDuplicate == pRec->m_isDuplicate)
                {
                    *ppRec = pRec;
                }
                else
                {
                    _ASSERTE(!"inconsistent token has been added to the table!");
                    IfFailGo( E_FAIL );
                }
            }

            if (tkFind < pRec->m_tkFrom)
            {
                // insert before lo;
                pRec = Insert(lo);
            }
            else
            {
                // insert after lo
                pRec = Insert(lo + 1);
            }
        }
        else
        {
            // table is empty
            pRec = Insert(m_iCountIndexed);
        }

        // If pRec == NULL, return E_OUTOFMEMORY
        IfNullGo(pRec);

        m_iCountTotal++;
        m_iCountSorted++;

        *ppRec = pRec;

        // initialize the record
        pRec->m_tkFrom = tkFind;
        pRec->m_isDuplicate = fDuplicate;
        pRec->m_tkTo = tkTo;
        pRec->m_isFoundInImport = false;
    }

ErrExit:
    return hr;
} // HRESULT MDTOKENMAP::InsertNotFound()

//*****************************************************************************
// find a "to" token in the tokenmap. Now that we are doing the ref to def optimization,
// we might have several from tokens map to the same to token. We need to return a range of index
// instead....
//*****************************************************************************
bool MDTOKENMAP::FindWithToToken(
    mdToken     tkFind,                 // [IN] the token value to find
    int         *piPosition)            // [OUT] return the first from-token that has the matching to-token
{
    int         lo, mid, hi;            // binary search indices.
    TOKENREC    *pRec;
    TOKENREC    *pRec2;

    // This makes sure that no insertions take place between calls to FindWithToToken.
    // We want to avoid repeated sorting of the table.
    _ASSERTE(m_sortKind != SortByToToken || m_iCountTotal == m_iCountSorted);

    // If the map is sorted with From tokens, change it to be sorted with To tokens.
    if (m_sortKind != SortByToToken)
        SortTokensByToToken();

    // Start with entire table.
    lo = 0;
    hi = Count() - 1;

    // While there are rows in the range...
    while (lo <= hi)
    {   // Look at the one in the middle.
        mid = (lo + hi) / 2;

        pRec = Get(mid);

        // If equal to the target, done.
        if (tkFind == pRec->m_tkTo)
        {
            for (int i = mid-1; i >= 0; i--)
            {
                pRec2 = Get(i);
                if (tkFind != pRec2->m_tkTo)
                {
                    *piPosition = i + 1;
                    return true;
                }
            }
            *piPosition = 0;
            return true;
        }

        // If middle item is too small, search the top half.
        if (pRec->m_tkTo < tkFind)
            lo = mid + 1;
        else // but if middle is to big, search bottom half.
            hi = mid - 1;
    }
    // Didn't find anything that matched.
    return false;
} // bool MDTOKENMAP::FindWithToToken()

//*****************************************************************************
// output a remapped token
//*****************************************************************************
mdToken MDTOKENMAP::SafeRemap(
    mdToken     tkFrom)                 // [IN] the token value to find
{
    TOKENREC    *pRec;

    // If possible, validate the input.
    _ASSERTE(!m_pImport || m_pImport->IsValidToken(tkFrom));

    SortTokensByFromToken();

    if ( Find(tkFrom, &pRec) )
    {
        return pRec->m_tkTo;
    }

    return tkFrom;
} // mdToken MDTOKENMAP::SafeRemap()

//*****************************************************************************
// Sorting
//*****************************************************************************
void MDTOKENMAP::SortTokensByToToken()
{
    // Only sort if there are unsorted records or the sort kind changed.
    if (m_iCountSorted < m_iCountTotal || m_sortKind != SortByToToken)
    {
        // Sort the entire array.
        m_iCountTotal = Count();
        m_iCountIndexed = 0;
        SortRangeToToken(0, m_iCountTotal - 1);
        m_iCountSorted = m_iCountTotal;
        m_sortKind = SortByToToken;
    }
} // void MDTOKENMAP::SortTokensByToToken()

void MDTOKENMAP::SortRangeFromToken(
    int         iLeft,
    int         iRight)
{
    int         iLast;
    int         i;                      // loop variable.

    // if less than two elements you're done.
    if (iLeft >= iRight)
        return;

    // The mid-element is the pivot, move it to the left.
    Swap(iLeft, (iLeft+iRight)/2);
    iLast = iLeft;

    // move everything that is smaller than the pivot to the left.
    for(i = iLeft+1; i <= iRight; i++)
        if (CompareFromToken(i, iLeft) < 0)
            Swap(i, ++iLast);

    // Put the pivot to the point where it is in between smaller and larger elements.
    Swap(iLeft, iLast);

    // Sort the each partition.
    SortRangeFromToken(iLeft, iLast-1);
    SortRangeFromToken(iLast+1, iRight);
} // void MDTOKENMAP::SortRangeFromToken()

//*****************************************************************************
// Sorting
//*****************************************************************************
void MDTOKENMAP::SortRangeToToken(
    int         iLeft,
    int         iRight)
{
    int         iLast;
    int         i;                      // loop variable.

    // if less than two elements you're done.
    if (iLeft >= iRight)
        return;

    // The mid-element is the pivot, move it to the left.
    Swap(iLeft, (iLeft+iRight)/2);
    iLast = iLeft;

    // move everything that is smaller than the pivot to the left.
    for(i = iLeft+1; i <= iRight; i++)
        if (CompareToToken(i, iLeft) < 0)
            Swap(i, ++iLast);

    // Put the pivot to the point where it is in between smaller and larger elements.
    Swap(iLeft, iLast);

    // Sort the each partition.
    SortRangeToToken(iLeft, iLast-1);
    SortRangeToToken(iLast+1, iRight);
} // void MDTOKENMAP::SortRangeToToken()

//*****************************************************************************
// find a token in the tokenmap.
//*****************************************************************************
HRESULT MDTOKENMAP::AppendRecord(
    mdToken     tkFind,
    bool        fDuplicate,
    mdToken     tkTo,
    TOKENREC    **ppRec)
{
    HRESULT     hr = NOERROR;
    TOKENREC    *pRec;

    // If possible, validate the input.
    _ASSERTE(!m_pImport || m_pImport->IsValidToken(tkFind));

    // If the map is indexed, and this is a table token, update-in-place.
    if (m_sortKind == Indexed && TypeFromToken(tkFind) != mdtString)
    {
        // Get the entry.
        ULONG ixTbl = CMiniMdRW::GetTableForToken(tkFind);
        _ASSERTE(ixTbl != (ULONG) -1);
        ULONG iRid = RidFromToken(tkFind);
        _ASSERTE((m_TableOffset[ixTbl] + iRid) <= m_TableOffset[ixTbl+1]);
        pRec = Get(m_TableOffset[ixTbl] + iRid - 1);
        // See if it has been set.
        if (!pRec->IsEmpty())
        {   // Verify that it is what we think it is.
            _ASSERTE(pRec->m_tkFrom == tkFind);
        }
    }
    else
    {
        pRec = Append();
        IfNullGo(pRec);

        // number of entries increased but not the sorted entry
        m_iCountTotal++;
    }

    // Store the data.
    pRec->m_tkFrom = tkFind;
    pRec->m_isDuplicate = fDuplicate;
    pRec->m_tkTo = tkTo;
    pRec->m_isFoundInImport = false;
    *ppRec = pRec;

ErrExit:
    return hr;
} // HRESULT MDTOKENMAP::AppendRecord()

//*********************************************************************************************************
//
// Merge Token manager's constructor
//
//*********************************************************************************************************
MergeTokenManager::MergeTokenManager(MDTOKENMAP *pTkMapList, IUnknown *pHandler)
{
    m_cRef = 1;
    m_pTkMapList = pTkMapList;
    m_pDefaultHostRemap = NULL;
    if (pHandler)
        pHandler->QueryInterface(IID_IMapToken, (void **) &m_pDefaultHostRemap);
} // TokenManager::TokenManager()

//*********************************************************************************************************
//
// Merge Token manager's destructor
//
//*********************************************************************************************************
MergeTokenManager::~MergeTokenManager()
{
    if (m_pDefaultHostRemap)
        m_pDefaultHostRemap->Release();
}   // TokenManager::~TokenManager()

ULONG MergeTokenManager::AddRef()
{
    return InterlockedIncrement(&m_cRef);
}   // TokenManager::AddRef()

ULONG MergeTokenManager::Release()
{
    ULONG   cRef = InterlockedDecrement(&m_cRef);
    if (!cRef)
        delete this;
    return (cRef);
}   // TokenManager::Release()

HRESULT MergeTokenManager::QueryInterface(REFIID riid, void **ppUnk)
{
    *ppUnk = 0;

    if (riid == IID_IMapToken)
        *ppUnk = (IUnknown *) (IMapToken *) this;
    else
        return (E_NOINTERFACE);
    AddRef();
    return (S_OK);
}   // TokenManager::QueryInterface

//*********************************************************************************************************
//
// Token manager keep tracks a list of tokenmaps. Each tokenmap corresponding
// to an imported scope. Note that with this, we do have problem in how to
// tell linker regarding the token movement when the token is added by Define
// rather than merge. This should be fixed with new merge implementation.
// The tkImp is the old tokens in the emit scope, tkEmit is the new token in the
// emit scope. We need to find the token from an import scope that is resolved
// to the tkImp. We then need to tell linker about this token movement.
// If we don't find any import scope which generates the tkImp token, that is
// this tkImp is generated by calling DefinXXX directly on the final merged scope.
// Then we use the default host remap to send the notification.
//
//*********************************************************************************************************
HRESULT MergeTokenManager::Map(mdToken  tkImp, mdToken tkEmit)
{
    HRESULT     hr = NOERROR;
    MDTOKENMAP  *pTkMapList = m_pTkMapList;
    bool        fFoundInImport = false;
    int         iPosition;
    TOKENREC    *pRec;

    _ASSERTE(m_pTkMapList);
    while ( pTkMapList )
    {
        // FindWithToToken will return the first match with the To token.
        // pTkMapList is sorted with To token. It might contain several From tokens
        // that map to the To token due to ref to def optimiation. Make sure that
        // all notification is sent to all of these From tokens.
        //
        if ( pTkMapList->FindWithToToken(tkImp, &iPosition) )
        {
            // make sure that we don't walk over the last entry
            while (iPosition < pTkMapList->Count())
            {
                pRec = pTkMapList->Get(iPosition);
                if (pRec->m_tkTo != tkImp)
                {
                    // we are done!
                    break;
                }

                // more matching record...
                fFoundInImport = true;
                if (pTkMapList->m_pMap)
                    hr = pTkMapList->m_pMap->Map(pRec->m_tkFrom, tkEmit);
                _ASSERTE(SUCCEEDED(hr));
                IfFailGo( hr );
                iPosition++;
            }
        }
        pTkMapList = pTkMapList->m_pNextMap;
    }

    if (fFoundInImport == false && m_pDefaultHostRemap)
    {
        // use the default remap to send the notification
        IfFailGo( m_pDefaultHostRemap->Map(tkImp, tkEmit) );
    }
ErrExit:
    return hr;
}

//*********************************************************************************************************
//
// CMapToken's constructor
//
//*********************************************************************************************************
CMapToken::CMapToken()
{
    m_cRef = 1;
    m_pTKMap = NULL;
    m_isSorted = true;
} // TokenManager::TokenManager()

//*********************************************************************************************************
//
// CMapToken's destructor
//
//*********************************************************************************************************
CMapToken::~CMapToken()
{
    delete m_pTKMap;
}   // CMapToken::~CMapToken()

ULONG CMapToken::AddRef()
{
    return InterlockedIncrement(&m_cRef);
}   // CMapToken::AddRef()

ULONG CMapToken::Release()
{
    ULONG   cRef = InterlockedDecrement(&m_cRef);
    if (!cRef)
        delete this;
    return (cRef);
}   // CMapToken::Release()

HRESULT CMapToken::QueryInterface(REFIID riid, void **ppUnk)
{
    *ppUnk = 0;

    if (riid == IID_IMapToken)
        *ppUnk = (IUnknown *) (IMapToken *) this;
    else
        return (E_NOINTERFACE);
    AddRef();
    return (S_OK);
}   // CMapToken::QueryInterface

//*********************************************************************************************************
//
// Track the token mapping
//
//*********************************************************************************************************
HRESULT CMapToken::Map(
    mdToken     tkFrom,
    mdToken     tkTo)
{
    HRESULT     hr = NOERROR;
    TOKENREC    *pTkRec;

    if (m_pTKMap == NULL)
        m_pTKMap = new (nothrow) MDTOKENMAP;

    IfNullGo( m_pTKMap );

    IfFailGo( m_pTKMap->AppendRecord(tkFrom, false, tkTo, &pTkRec) );
    _ASSERTE( pTkRec );

    m_isSorted = false;
ErrExit:
    return hr;
}

//*********************************************************************************************************
//
// return what tkFrom is mapped to ptkTo. If there is no remap
// (ie the token from is filtered out by the filter mechanism, it will return false.
//
//*********************************************************************************************************
bool    CMapToken::Find(
    mdToken     tkFrom,
    TOKENREC    **pRecTo)
{
    TOKENREC    *pRec;
    bool        bRet;
    if ( m_isSorted == false )
    {
        // sort the map
        m_pTKMap->SortTokensByFromToken();
        m_isSorted = true;
    }

    bRet =  m_pTKMap->Find(tkFrom, &pRec) ;
    if (bRet)
    {
        _ASSERTE(pRecTo);
        *pRecTo = pRec;
    }
    else
    {
        pRec = NULL;
    }
    return bRet;
}

//*********************************************************************************************************
//
// This function returns true if tkFrom is resolved to a def token. Otherwise, it returns
// false.
//
//*********************************************************************************************************
bool TokenRemapManager::ResolveRefToDef(
    mdToken tkRef,                      // [IN] ref token
    mdToken *ptkDef)                    // [OUT] def token that it resolves to. If it does not resolve to a def
                                        // token, it will return the tkRef token here.
{
    mdToken     tkTo;

    _ASSERTE(ptkDef);

    if (TypeFromToken(tkRef) == mdtTypeRef)
    {
        tkTo = m_TypeRefToTypeDefMap[RidFromToken(tkRef)];
    }
    else
    {
        _ASSERTE( TypeFromToken(tkRef) == mdtMemberRef );
        tkTo = m_MemberRefToMemberDefMap[RidFromToken(tkRef)];
    }
    if (RidFromToken(tkTo) == mdTokenNil)
    {
        *ptkDef = tkRef;
        return false;
    }
    *ptkDef = tkTo;
    return true;
}   // ResolveRefToDef

//*********************************************************************************************************
//
// Destructor
//
//*********************************************************************************************************
TokenRemapManager::~TokenRemapManager()
{
    m_TypeRefToTypeDefMap.Clear();
    m_MemberRefToMemberDefMap.Clear();
}   // ~TokenRemapManager

//*********************************************************************************************************
//
// Initialize the size of Ref to Def optimization table. We will grow the tables in this function.
// We also initialize the table entries to zero.
//
//*********************************************************************************************************
HRESULT TokenRemapManager::ClearAndEnsureCapacity(
    ULONG       cTypeRef,
    ULONG       cMemberRef)
{
    HRESULT     hr = NOERROR;
    if ( ((ULONG) (m_TypeRefToTypeDefMap.Count())) < (cTypeRef + 1) )
    {
        if ( m_TypeRefToTypeDefMap.AllocateBlock(cTypeRef + 1 - m_TypeRefToTypeDefMap.Count() ) == 0 )
            IfFailGo( E_OUTOFMEMORY );
    }
    memset( m_TypeRefToTypeDefMap.Get(0), 0, (cTypeRef + 1) * sizeof(mdToken) );

    if ( ((ULONG) (m_MemberRefToMemberDefMap.Count())) < (cMemberRef + 1) )
    {
        if ( m_MemberRefToMemberDefMap.AllocateBlock(cMemberRef + 1 - m_MemberRefToMemberDefMap.Count() ) == 0 )
            IfFailGo( E_OUTOFMEMORY );
    }
    memset( m_MemberRefToMemberDefMap.Get(0), 0, (cMemberRef + 1) * sizeof(mdToken) );

ErrExit:
    return hr;
} // HRESULT TokenRemapManager::ClearAndEnsureCapacity()

//*********************************************************************************************************
//
// Constructor
//
//*********************************************************************************************************
CMDSemReadWrite::CMDSemReadWrite(
    UTSemReadWrite * pSem)
{
    m_fLockedForRead = false;
    m_fLockedForWrite = false;
    m_pSem = pSem;
} // CMDSemReadWrite::CMDSemReadWrite

//*********************************************************************************************************
//
// Destructor
//
//*********************************************************************************************************
CMDSemReadWrite::~CMDSemReadWrite()
{
    _ASSERTE(!m_fLockedForRead || !m_fLockedForWrite);
    if (m_pSem == NULL)
    {
        return;
    }
    if (m_fLockedForRead)
    {
        LOG((LF_METADATA, LL_EVERYTHING, "UnlockRead called from CSemReadWrite::~CSemReadWrite \n"));
        m_pSem->UnlockRead();
    }
    if (m_fLockedForWrite)
    {
        LOG((LF_METADATA, LL_EVERYTHING, "UnlockWrite called from CSemReadWrite::~CSemReadWrite \n"));
        m_pSem->UnlockWrite();
    }
} // CMDSemReadWrite::~CMDSemReadWrite

//*********************************************************************************************************
//
// Used to obtain the read lock
//
//*********************************************************************************************************
HRESULT CMDSemReadWrite::LockRead()
{
    HRESULT hr = S_OK;

    _ASSERTE(!m_fLockedForRead && !m_fLockedForWrite);

    if (m_pSem == NULL)
    {
        INDEBUG(m_fLockedForRead = true);
        return hr;
    }

    LOG((LF_METADATA, LL_EVERYTHING, "LockRead called from CSemReadWrite::LockRead \n"));
    IfFailRet(m_pSem->LockRead());
    m_fLockedForRead = true;

    return hr;
} // CMDSemReadWrite::LockRead

//*********************************************************************************************************
//
// Used to obtain the read lock
//
//*********************************************************************************************************
HRESULT CMDSemReadWrite::LockWrite()
{
    HRESULT hr = S_OK;

    _ASSERTE(!m_fLockedForRead && !m_fLockedForWrite);

    if (m_pSem == NULL)
    {
        INDEBUG(m_fLockedForWrite = true);
        return hr;
    }

    LOG((LF_METADATA, LL_EVERYTHING, "LockWrite called from CSemReadWrite::LockWrite \n"));
    IfFailRet(m_pSem->LockWrite());
    m_fLockedForWrite = true;

    return hr;
}

//*********************************************************************************************************
//
// Convert a read lock to a write lock
//
//*********************************************************************************************************
HRESULT CMDSemReadWrite::ConvertReadLockToWriteLock()
{
    _ASSERTE(!m_fLockedForWrite);

    HRESULT hr = S_OK;

    if (m_pSem == NULL)
    {
        INDEBUG(m_fLockedForRead = false);
        INDEBUG(m_fLockedForWrite = true);
        return hr;
    }

    if (m_fLockedForRead)
    {
        LOG((LF_METADATA, LL_EVERYTHING, "UnlockRead called from CSemReadWrite::ConvertReadLockToWriteLock \n"));
        m_pSem->UnlockRead();
        m_fLockedForRead = false;
    }
    LOG((LF_METADATA, LL_EVERYTHING, "LockWrite called from  CSemReadWrite::ConvertReadLockToWriteLock\n"));
    IfFailRet(m_pSem->LockWrite());
    m_fLockedForWrite = true;

    return hr;
} // CMDSemReadWrite::ConvertReadLockToWriteLock

//*********************************************************************************************************
//
// Unlocking for write
//
//*********************************************************************************************************
void CMDSemReadWrite::UnlockWrite()
{
    _ASSERTE(!m_fLockedForRead);

    if (m_pSem == NULL)
    {
        INDEBUG(m_fLockedForWrite = false);
        return;
    }
    if (m_fLockedForWrite)
    {
        LOG((LF_METADATA, LL_EVERYTHING, "UnlockWrite called from CSemReadWrite::UnlockWrite \n"));
        m_pSem->UnlockWrite();
        m_fLockedForWrite = false;
    }
} // CMDSemReadWrite::UnlockWrite


text:
<!DOCTYPE html>

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

    Lorem ipsum dolor ssit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.
    Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.

    Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.
    Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.

redpajama_set_name: RedPajamaGithub


text:
using System;
using System.Collections.Generic;
using System.Xml.Serialization;
using System.Text;

using Amazon.Runtime;

namespace Amazon.ElasticTranscoder.Model
{
    /// <summary>
    /// Returns information about the  DeletePresetResult response and response metadata.
    /// </summary>
    public class DeletePresetResponse : AmazonWebServiceResponse
    {
        private DeletePresetResult deletePresetResult;

        /// <summary>
        /// Gets and sets the DeletePresetResult property.
        ///
        /// </summary>
        public DeletePresetResult DeletePresetResult
        {
            get
            {
                if(this.deletePresetResult == null)
                {
                    this.deletePresetResult = new DeletePresetResult();
                }

                return this.deletePresetResult;
            }
            set { this.deletePresetResult = value; }
        }
    }
}


text:
@interface PXCanvas (ImportingExporting)

+ (id)canvasWithContentsOfFile:(NSString *)aFile;

- (id)initWithContentsOfFile:(NSString *)aFile;
- (id)initWithImage:(NSImage *)anImage;

- (NSData *)imageDataWithType:(NSBitmapImageFileType)storageType properties:(NSDictionary *)properties;

- (void)replaceActiveLayerWithImage:(NSImage *)anImage;

- (NSBitmapImageRep *)imageRep; // suitable for drawing to the screen

@end


text:
<?php
if(!defined('IN_MANAGER_MODE') || IN_MANAGER_MODE != 'true') exit();

if (!$modx->hasPermission('edit_module')) {
	$e->setError(3);
	$e->dumpError();
}

if (isset($_REQUEST['id']))
        $id = (int)$_REQUEST['id'];
else    $id = 0;

// Get table names (alphabetical)
$tbl_site_module_depobj = $modx->getFullTableName('site_module_depobj');
$tbl_site_plugins       = $modx->getFullTableName('site_plugins');
$tbl_site_snippets      = $modx->getFullTableName('site_snippets');

// initialize page view state - the $_PAGE object
$modx->manager->initPageViewState();

// check to see the  editor isn't locked
$rs = $modx->db->select('internalKey, username','[+prefix+]active_users',"action=108 AND id='{$id}'");
$limit = $modx->db->getRecordCount($rs);
if($limit>1) {
	while($lock = $modx->db->getRow($rs))
	{
		if($lock['internalKey']!=$modx->getLoginUserID())
		{
			$msg = sprintf($_lang['lock_msg'], $lock['username'], $_lang['modules']);
			$e->setError(5, $msg);
			$e->dumpError();
		}
	}
}
// end check for lock

// make sure the id's a number
if(!is_numeric($id)) {
	echo "Passed ID is not a valid number!";
	exit;
}

// take action
switch ($_REQUEST['op']) {
	case 'add':
		$opids = explode(',',$_REQUEST['newids']);
		if (count($opids)>0){
			// 1-snips, 2-tpls, 3-tvs, 4-chunks, 5-plugins, 6-docs
			$rt = strtolower($_REQUEST["rt"]);
			if ($rt == 'chunk') $type = 10;
			if ($rt == 'doc')   $type = 20;
			if ($rt == 'plug')  $type = 30;
			if ($rt == 'snip')  $type = 40;
			if ($rt == 'tpl')   $type = 50;
			if ($rt == 'tv')    $type = 60;
			$v = array();
			foreach($opids as $opid)
			{
				$opid = intval($opid);
				$v[] = "('{$id}','{$opid}','{$type}')";
			}
			$values = join(',', $v);
			$del_opids = join(',', $opids);
			$modx->db->delete($tbl_site_module_depobj, "module='{$id}' AND resource IN ({$del_opids}) AND type='{$type}'");
			$ds = $modx->db->query("INSERT INTO {$tbl_site_module_depobj} (module, resource, type) VALUES {$values}");
			if(!$ds){
				echo '';
			}
		}
		break;
	case 'del':
		$opids = $_REQUEST['depid'];
		for($i=0;$i<count($opids);$i++) {
			$opids[$i]=intval($opids[$i]); // convert ids to numbers
		}
		// get resources that needs to be removed
		$ds = $modx->db->query("SELECT * FROM ".$tbl_site_module_depobj." WHERE id IN (".implode(",",$opids).")");
		if ($ds) {
			// loop through resources and look for plugins and snippets
			$i=0; $plids=array(); $snid=array();
			while ($row=$modx->db->getRow($ds)){
				if($row['type']=='30') $plids[$i]=$row['resource'];
				if($row['type']=='40') $snids[$i]=$row['resource'];
			}
			// get guid
			$ds = $modx->db->select('*', '[+prefix+]site_modules', "id='{$id}'");
			if($ds) {
				$row = $modx->db->getRow($ds);
				$guid = $row['guid'];
			}
			// reset moduleguid for deleted resources
			if (($cp=count($plids)) || ($cs=count($snids)))
			{
				$plids = join(',', $plids);
				$snids = join(',', $snids);
				if ($cp) $modx->db->update("moduleguid=''", $tbl_site_plugins,  "id IN ({$plids}) AND moduleguid='{$guid}'");
				if ($cs) $modx->db->update("moduleguid=''", $tbl_site_snippets, "id IN ({$snids}) AND moduleguid='{$guid}'");
				// reset cache
				$modx->clearCache();
			}
		}
		$opids = join(',', $opids);
		$modx->db->delete($tbl_site_module_depobj,"id IN ({$opids})");
		break;
}

// load record
$rs = $modx->db->select('*','[+prefix+]site_modules',"id='{$id}'");
$limit = $modx->db->getRecordCount($rs);
if($limit>1) {
	echo "
Multiple modules sharing same unique id. Please contact the Site Administrator.
";
	exit;
}
elseif($limit<1) {
	echo "
Module not found for id '$id'.
";
	exit;
}
$content = $modx->db->getRow($rs);
$_SESSION['itemname']=$content['name'];
if($content['locked']==1 && $_SESSION['mgrRole']!=1) {
	$e->setError(3);
	$e->dumpError();
}

?>

<form name="mutate" method="post" action="index.php">
<input type="hidden" name="a" value="113" />
<input type="hidden" name="op" value="" />
<input type="hidden" name="rt" value="" />
<input type="hidden" name="newids" value="" />
<input type="hidden" name="id" value="<?php echo $content['id'];?>" />

<?php echo $_lang['module_resource_title']; ?>

<img src="<?php echo $_style["icons_cancel"]?>" /> <?php echo $_lang['cancel']; ?>

<?php echo $content["name"]." - ".$_lang['module_resource_title']; ?>

<img src="<?php echo $_style["icons_modules"] ?>" alt="" align="left" /><?php echo $_lang['module_resource_msg']; ?>

<img src="<?php echo $_style["icons_add"] ?>" /> <?php echo $_lang['add_snippet']; ?>

<img src="<?php echo $_style["icons_add"] ?>" /> <?php echo $_lang['add_plugin']; ?>

		<?php
			$sql = "SELECT smd.id,COALESCE(ss.name,sp.name) as 'name'," .
					"CASE smd.type " .
					" WHEN 30 THEN 'Plugin' " .
					" WHEN 40 THEN 'Snippet' " .
					"END as 'type' " .
					"FROM ".$tbl_site_module_depobj." smd ".
					"LEFT JOIN ".$tbl_site_plugins." sp ON sp.id = smd.resource AND smd.type = '30' ".
					"LEFT JOIN ".$tbl_site_snippets." ss ON ss.id = smd.resource AND smd.type = '40' ".
					"WHERE smd.module=$id ORDER BY smd.type,name ";
			$ds = $modx->db->query($sql);
			if (!$ds){
				echo "An error occured while loading module dependencies.";
			}
			else {
				include_once(MODX_CORE_PATH . 'controls/datagrid.class.php');
				$grd = new DataGrid('',$ds,0); // set page size to 0 t show all items
				$grd->noRecordMsg = $_lang["no_records_found"];
				$grd->cssClass="grid";
				$grd->columnHeaderClass="gridHeader";
				$grd->itemClass="gridItem";
				$grd->altItemClass="gridAltItem";
				$grd->columns=$_lang["element_name"]." ,".$_lang["type"];
				$grd->colTypes = "template:<input type='checkbox' name='depid[]' value='[+id+]'> [+value+]";
				$grd->fields="name,type";
				$grd->colWidths='200';
				echo $grd->render();
			}
		?>

<img src="<?php echo $_style["icons_delete_document"]?>" /> <?php echo $_lang['remove']; ?>

<input type="submit" name="save" style="display:none">
</form>


text:
package middleware

import (
	"net/http"
	"net/http/httptest"

	"encoding/json"

	"github.com/gin-gonic/gin"
	. "github.com/onsi/ginkgo"
	. "github.com/onsi/gomega"

	"github.com/VirrageS/chirp/backend/config"
	"github.com/VirrageS/chirp/backend/token"
)

// From Go documentation of httptest.NewRequest():
// 192.0.2.0/24 is "TEST-NET" in RFC 5737 for use solely in
// documentation and example source code and should not be
// used publicly.
const (
	testIP    = "192.0.2.1"
	testAgent = "test/1.0"
)

var _ = Describe("TokenAuthenticator", func() {
	var (
		router *gin.Engine
	)

	BeforeEach(func() {
		gin.SetMode(gin.TestMode)

		conf := config.New()
		tokenManager := token.NewManager(conf.Token)
		router = gin.New()
		router.Use(ErrorHandler())
		router.Use(TokenAuthenticator(tokenManager))
	})

	It("should allow to make normal response when jwt token is okay", func() {
		correctJWT := "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ1c2VySUQiOjEsImFsbG93ZWRJUCI6IjE5Mi4wLjIuMSIsImFsbG93ZWRVc2VyQWdlbnQiOiJ0ZXN0LzEuMCIsImV4cCI6NDEwMjQ0NDgwMH0.OO-BsNijn7kIG1G2QUhNPibdTZF2Q9ezpHSQ6JJ_AwE"

		router.POST("/test", func(c *gin.Context) {
			c.String(http.StatusOK, "%d", c.MustGet("userID").(int64))
		})

		w := httptest.NewRecorder()
		req := httptest.NewRequest("POST", "/test", nil)
		req.Header.Set("Authorization", "Bearer "+correctJWT)
		req.Header.Set("X-Real-Ip", testIP)
		req.Header.Set("User-Agent", testAgent)

		router.ServeHTTP(w, req)

		Expect(w.Code).To(Equal(http.StatusOK))
		Expect(w.Body.String()).To(Equal("1"))
	})

	It("should allow to make normal response when X-Real-IP header is not provided, but RemoteAddr is", func() {
		noUserIDToken := "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ1c2VySUQiOjEsImFsbG93ZWRJUCI6IjE5Mi4wLjIuMSIsImFsbG93ZWRVc2VyQWdlbnQiOiJ0ZXN0LzEuMCIsImV4cCI6NDEwMjQ0NDgwMH0.OO-BsNijn7kIG1G2QUhNPibdTZF2Q9ezpHSQ6JJ_AwE"
		router.POST("/test", func(c *gin.Context) {
			c.String(http.StatusOK, "%d", c.MustGet("userID").(int64))
		})

		w := httptest.NewRecorder()
		req := httptest.NewRequest("POST", "/test", nil)
		req.Header.Set("Authorization", "Bearer "+noUserIDToken)
		req.Header.Set("X-Real-Ip", testIP)
		req.Header.Set("User-Agent", testAgent)

		router.ServeHTTP(w, req)

		Expect(w.Code).To(Equal(http.StatusOK))
		Expect(w.Body.String()).To(Equal("1"))
	})

	It("should return status unauthorized when token has unsupported signing method", func() {
		unsupportedSigningMethodToken := "eyJ0eXAiOiJKV1QiLCJhbGciOiJSUzI1NiJ9.eyJ1c2VySUQiOjEsImV4cCI6NDEwMjQ0NDgwMH0.DqWD84gFXT2reQB064MourQ5RT4lhXreEhEEcibWSZQ"

		router.POST("/test", func(c *gin.Context) {
			c.String(http.StatusOK, "%d", c.MustGet("userID").(int64))
		})

		w := httptest.NewRecorder()
		req := httptest.NewRequest("POST", "/test", nil)
		req.Header.Set("Authorization", "Bearer "+unsupportedSigningMethodToken)
		req.Header.Set("X-Real-Ip", testIP)
		req.Header.Set("User-Agent", testAgent)

		router.ServeHTTP(w, req)

		var response errorResponse
		json.NewDecoder(w.Body).Decode(&response)

		Expect(w.Code).To(Equal(http.StatusUnauthorized))
		Expect(response).To(Equal(errorResponse{[]string{"Invalid authentication token."}}))
	})

	It("shoud return status unauthorized when token has wrong signature", func() {
		wrongSignatureToken := "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ1c2VySUQiOjEsImFsbG93ZWRJUCI6IjE5Mi4wLjIuMSIsImFsbG93ZWRVc2VyQWdlbnQiOiJ0ZXN0LzEuMCIsImV4cCI6NDEwMjQ0NDgwMH0.uFkBc1pQDK_YL8y1tbllqkrmnjk3gG_h8Bi_B45LFdY"

		router.POST("/test", func(c *gin.Context) {
			c.String(http.StatusOK, "%d", c.MustGet("userID").(int64))
		})

		w := httptest.NewRecorder()
		req := httptest.NewRequest("POST", "/test", nil)
		req.Header.Set("Authorization", "Bearer "+wrongSignatureToken)
		req.Header.Set("X-Real-Ip", testIP)
		req.Header.Set("User-Agent", testAgent)

		router.ServeHTTP(w, req)

		var response errorResponse
		json.NewDecoder(w.Body).Decode(&response)

		Expect(w.Code).To(Equal(http.StatusUnauthorized))
		Expect(response).To(Equal(errorResponse{[]string{"Invalid authentication token."}}))
	})

	It("should return status unauthorized when token is expired", func() {
		expiredToken := "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ1c2VySUQiOjEsImFsbG93ZWRJUCI6IjE5Mi4wLjIuMSIsImFsbG93ZWRVc2VyQWdlbnQiOiJ0ZXN0LzEuMCIsImV4cCI6OTQ2Njg0ODAwfQ.CGy0aYslZYNIz_CI5n9XjAsxBkulotkaEfbsR11WM5s"
		router.POST("/test", func(c *gin.Context) {
			c.String(http.StatusOK, "%d", c.MustGet("userID").(int64))
		})

		w := httptest.NewRecorder()
		req := httptest.NewRequest("POST", "/test", nil)
		req.Header.Set("Authorization", "Bearer "+expiredToken)
		req.Header.Set("X-Real-Ip", testIP)
		req.Header.Set("User-Agent", testAgent)

		router.ServeHTTP(w, req)

		var response errorResponse
		json.NewDecoder(w.Body).Decode(&response)

		Expect(w.Code).To(Equal(http.StatusUnauthorized))
		Expect(response).To(Equal(errorResponse{[]string{"Token has expired."}}))
	})

	// Test the case when token does not contain 'exp' field. This is incorrect and should be rejected.
	It("should return status unauthorized when token does not contain `exp` field", func() {
		expiredToken := "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ1c2VySUQiOjEsImFsbG93ZWRVc2VyQWdlbnQiOiJ0ZXN0LzEuMCIsImFsbG93ZWRJUCI6IjE5Mi4wLjIuMSJ9.vxk2n-A27G72Miu9geKKVjxKF5vE4Gfc88jzyLDiEW0"
		router.POST("/test", func(c *gin.Context) {
			c.String(http.StatusOK, "%d", c.MustGet("userID").(int64))
		})

		w := httptest.NewRecorder()
		req := httptest.NewRequest("POST", "/test", nil)
		req.Header.Set("Authorization", "Bearer "+expiredToken)
		req.Header.Set("X-Real-Ip", testIP)
		req.Header.Set("User-Agent", testAgent)

		router.ServeHTTP(w, req)

		var response errorResponse
		json.NewDecoder(w.Body).Decode(&response)

		Expect(w.Code).To(Equal(http.StatusUnauthorized))
		Expect(response).To(Equal(errorResponse{[]string{"Token has expired."}}))
	})

	// Test the case when token does not contain 'userID' field. This is incorrect and should be rejected.
	It("should return status unauthorized when token does not cotain `userID` field", func() {
		noUserIDToken := "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJhbGxvd2VkSVAiOiIxOTIuMC4yLjEiLCJhbGxvd2VkVXNlckFnZW50IjoidGVzdC8xLjAiLCJleHAiOjQxMDI0NDQ4MDB9.uxEGCy4krGYUZ00TLojsIVYUUY5mpzJ9VDh9DhwMhpE"
		router.POST("/test", func(c *gin.Context) {
			c.String(http.StatusOK, "%d", c.MustGet("userID").(int64))
		})

		w := httptest.NewRecorder()
		req := httptest.NewRequest("POST", "/test", nil)
		req.Header.Set("Authorization", "Bearer "+noUserIDToken)
		req.Header.Set("X-Real-Ip", testIP)
		req.Header.Set("User-Agent", testAgent)

		router.ServeHTTP(w, req)

		var response errorResponse
		json.NewDecoder(w.Body).Decode(&response)

		Expect(w.Code).To(Equal(http.StatusUnauthorized))
		Expect(response).To(Equal(errorResponse{[]string{"Token does not contain required data."}}))
	})

	It("should return status unauthorized when request is sent with X-Real-IP header that does not match `allowedIP`", func() {
		noUserIDToken := "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ1c2VySUQiOjEsImFsbG93ZWRJUCI6IjEyNy4wLjAuMSIsImFsbG93ZWRVc2VyQWdlbnQiOiJ0ZXN0LzEuMCIsImV4cCI6NDEwMjQ0NDgwMH0.AC_FQLzE660E7RWrq6BiRUloINb6Iaydqi6i3oK3E8M"
		router.POST("/test", func(c *gin.Context) {
			c.String(http.StatusOK, "%d", c.MustGet("userID").(int64))
		})

		w := httptest.NewRecorder()
		req := httptest.NewRequest("POST", "/test", nil)
		req.Header.Set("Authorization", "Bearer "+noUserIDToken)
		req.Header.Set("X-Real-Ip", "1.2.3.4:1234")
		req.Header.Set("User-Agent", testAgent)
		req.RemoteAddr = "" // just to make sure it checks X-Real-IP

		router.ServeHTTP(w, req)

		var response errorResponse
		json.NewDecoder(w.Body).Decode(&response)

		Expect(w.Code).To(Equal(http.StatusUnauthorized))
		Expect(response).To(Equal(errorResponse{[]string{"Token is not allowed to be used from this IP."}}))
	})

	It("should return status unauthorized when request is sent without X-Real-IP header but with RemoteAddr that does not match `allowedIp`", func() {
		noUserIDToken := "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ1c2VySUQiOjEsImFsbG93ZWRJUCI6IjEyNy4wLjAuMSIsImFsbG93ZWRVc2VyQWdlbnQiOiJ0ZXN0LzEuMCIsImV4cCI6NDEwMjQ0NDgwMH0.AC_FQLzE660E7RWrq6BiRUloINb6Iaydqi6i3oK3E8M"
		router.POST("/test", func(c *gin.Context) {
			c.String(http.StatusOK, "%d", c.MustGet("userID").(int64))
		})

		w := httptest.NewRecorder()
		req := httptest.NewRequest("POST", "/test", nil)
		req.Header.Set("Authorization", "Bearer "+noUserIDToken)
		req.Header.Set("User-Agent", testAgent)
		req.RemoteAddr = "1.2.3.4:1234"

		router.ServeHTTP(w, req)

		var response errorResponse
		json.NewDecoder(w.Body).Decode(&response)

		Expect(w.Code).To(Equal(http.StatusUnauthorized))
		Expect(response).To(Equal(errorResponse{[]string{"Token is not allowed to be used from this IP."}}))
	})

	// Not sure if this can ever happen
	It("should return status unauthorized when both X-Real-IP header and RemoteAddr are not provided", func() {
		noUserIDToken := "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ1c2VySUQiOjEsImFsbG93ZWRJUCI6IjE5Mi4wLjIuMSIsImFsbG93ZWRVc2VyQWdlbnQiOiJ0ZXN0LzEuMCIsImV4cCI6NDEwMjQ0NDgwMH0.OO-BsNijn7kIG1G2QUhNPibdTZF2Q9ezpHSQ6JJ_AwE"
		router.POST("/test", func(c *gin.Context) {
			c.String(http.StatusOK, "%d", c.MustGet("userID").(int64))
		})

		w := httptest.NewRecorder()
		req := httptest.NewRequest("POST", "/test", nil)
		req.Header.Set("Authorization", "Bearer "+noUserIDToken)
		req.Header.Set("User-Agent", testAgent)
		req.RemoteAddr = ""

		router.ServeHTTP(w, req)

		var response errorResponse
		json.NewDecoder(w.Body).Decode(&response)

		Expect(w.Code).To(Equal(http.StatusUnauthorized))
		Expect(response).To(Equal(errorResponse{[]string{"Malformed request: no client IP was provided."}}))
	})

	It("should return status unauthorized when User-Agent header is not provided.", func() {
		noUserIDToken := "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ1c2VySUQiOjEsImFsbG93ZWRJUCI6IjE5Mi4wLjIuMSIsImFsbG93ZWRVc2VyQWdlbnQiOiJ0ZXN0LzEuMCIsImV4cCI6NDEwMjQ0NDgwMH0.OO-BsNijn7kIG1G2QUhNPibdTZF2Q9ezpHSQ6JJ_AwE"
		router.POST("/test", func(c *gin.Context) {
			c.String(http.StatusOK, "%d", c.MustGet("userID").(int64))
		})

		w := httptest.NewRecorder()
		req := httptest.NewRequest("POST", "/test", nil)
		req.Header.Set("Authorization", "Bearer "+noUserIDToken)
		req.Header.Set("X-Real-Ip", testIP)

		router.ServeHTTP(w, req)

		var response errorResponse
		json.NewDecoder(w.Body).Decode(&response)

		Expect(w.Code).To(Equal(http.StatusUnauthorized))
		Expect(response).To(Equal(errorResponse{[]string{"Malformed request: no User-Agent header."}}))
	})

	It("should return status unauthorized when User-Agent header is not provided.", func() {
		noUserIDToken := "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ1c2VySUQiOjEsImFsbG93ZWRJUCI6IjE5Mi4wLjIuMSIsImFsbG93ZWRVc2VyQWdlbnQiOiJ0ZXN0LzEuMCIsImV4cCI6NDEwMjQ0NDgwMH0.OO-BsNijn7kIG1G2QUhNPibdTZF2Q9ezpHSQ6JJ_AwE"
		router.POST("/test", func(c *gin.Context) {
			c.String(http.StatusOK, "%d", c.MustGet("userID").(int64))
		})

		w := httptest.NewRecorder()
		req := httptest.NewRequest("POST", "/test", nil)
		req.Header.Set("Authorization", "Bearer "+noUserIDToken)
		req.Header.Set("X-Real-Ip", testIP)
		req.Header.Set("User-Agent", "badAgent/1.0")

		router.ServeHTTP(w, req)

		var response errorResponse
		json.NewDecoder(w.Body).Decode(&response)

		Expect(w.Code).To(Equal(http.StatusUnauthorized))
		Expect(response).To(Equal(errorResponse{[]string{"Token is not allowed to be used from this User-Agent."}}))
	})
})


text:
<!doctype html>

		<meta charset="utf-8">

		<title>Red Hat Think G-Cloud 2014</title>

		<meta name="description" content="A presentation by Jeremy Brown for the Think G-Cloud 2014 conference entitled Agile, DevOps, Continuous Delivery and Lean - How do you tie it all together in GCloud?">
		<meta name="author" content="Jeremy Brown">

		<meta name="apple-mobile-web-app-capable" content="yes" />
		<meta name="apple-mobile-web-app-status-bar-style" content="black-translucent" />

		<meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no">

		<link rel="stylesheet" href="/css/reveal.css">
		<link rel="stylesheet" href="/content/common/css/redhat.css" id="theme">

		<link rel="stylesheet" href="/lib/css/zenburn.css">


text:
package gov.hhs.fha.nhinc.docretrieve.adapter.proxy;

import gov.hhs.fha.nhinc.aspect.AdapterDelegationEvent;
import gov.hhs.fha.nhinc.common.nhinccommon.AssertionType;
import gov.hhs.fha.nhinc.docretrieve.aspect.RetrieveDocumentSetRequestTypeDescriptionBuilder;
import gov.hhs.fha.nhinc.docretrieve.aspect.RetrieveDocumentSetResponseTypeDescriptionBuilder;
import gov.hhs.fha.nhinc.nhinclib.NhincConstants;
import gov.hhs.fha.nhinc.webserviceproxy.WebServiceProxyHelper;
import ihe.iti.xds_b._2007.RetrieveDocumentSetRequestType;
import java.lang.reflect.Method;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import org.junit.Test;
import static org.mockito.Matchers.anyString;
import static org.mockito.Matchers.eq;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;

/**
 * @author achidamb
 *
 */
public class AdapterDocRetrieveProxyWebServiceUnsecuredImplTest {

    @Test
    public void hasAdapterDelegationEvent() throws Exception {
        Class<AdapterDocRetrieveProxyWebServiceUnsecuredImpl> clazz =
            AdapterDocRetrieveProxyWebServiceUnsecuredImpl.class;
        Method method = clazz.getMethod("retrieveDocumentSet", RetrieveDocumentSetRequestType.class,
            AssertionType.class);
        AdapterDelegationEvent annotation = method.getAnnotation(AdapterDelegationEvent.class);
        assertNotNull(annotation);
        assertEquals(RetrieveDocumentSetRequestTypeDescriptionBuilder.class, annotation.beforeBuilder());
        assertEquals(RetrieveDocumentSetResponseTypeDescriptionBuilder.class, annotation.afterReturningBuilder());
        assertEquals("Retrieve Document", annotation.serviceType());
        assertEquals("", annotation.version());
    }

    @Test
    public void checkEndpointURLBasedOnImplementsSpecVersion() throws Exception {
        final String a0_URL = "a0 URL";
        final String a1_URL = "a1 URL";
        String url = null;

        WebServiceProxyHelper proxyMock = mock(WebServiceProxyHelper.class);
        when(proxyMock.getAdapterEndPointFromConnectionManager(anyString())).thenReturn(a1_URL);
        when(proxyMock.getEndPointFromConnectionManagerByAdapterAPILevel(anyString(), eq(NhincConstants.ADAPTER_API_LEVEL.LEVEL_a0))).thenReturn(a0_URL);
        when(proxyMock.getEndPointFromConnectionManagerByAdapterAPILevel(anyString(), eq(NhincConstants.ADAPTER_API_LEVEL.LEVEL_a1))).thenReturn(a1_URL);
        //check for bot secured and unsecured endpoints
        //instance of assertion type
        AssertionType assertion = new AssertionType();
        AdapterDocRetrieveProxyWebServiceUnsecuredImpl impl = new AdapterDocRetrieveProxyWebServiceUnsecuredImpl();
        impl.setoProxyHelper(proxyMock);

        //for 2010
        assertion.setImplementsSpecVersion(NhincConstants.UDDI_SPEC_VERSION.SPEC_2_0.toString());
        url = impl.getEndPointFromConnectionManagerByAdapterAPILevel(assertion, NhincConstants.ADAPTER_DOC_RETRIEVE_SERVICE_NAME);
        assertEquals(a0_URL, url);

        //for 2011
        assertion.setImplementsSpecVersion(NhincConstants.UDDI_SPEC_VERSION.SPEC_3_0.toString());
        url = impl.getEndPointFromConnectionManagerByAdapterAPILevel(assertion, NhincConstants.ADAPTER_DOC_RETRIEVE_SERVICE_NAME);
        assertEquals(a1_URL, url);

        //if ImplementsSpecVersion is null
        assertion.setImplementsSpecVersion(null);
        url = impl.getEndPointFromConnectionManagerByAdapterAPILevel(assertion, NhincConstants.ADAPTER_DOC_RETRIEVE_SERVICE_NAME);
        assertEquals(a1_URL, url);
    }
}


text:
package org.metaborg.sdf2table.grammar.layoutconstraints.exceptions;

public class LayoutConstraintException extends Exception {

    private static final long serialVersionUID = 7161665365057577606L;

    public LayoutConstraintException(String msg) {
        super(msg);
    }

    public LayoutConstraintException(String msg, Throwable cause) {
        super(msg, cause);
    }
}


text:
namespace NewsSystem.Data.Migrations
{
    using System;
    using System.Data.Entity.Migrations;

    public partial class IsMain_IsTopMain_AddedForArticles : DbMigration
    {
        public override void Up()
        {
            AddColumn("dbo.Articles", "IsMain", c => c.Boolean(nullable: false));
            AddColumn("dbo.Articles", "IsTopMain", c => c.Boolean(nullable: false));
        }

        public override void Down()
        {
            DropColumn("dbo.Articles", "IsTopMain");
            DropColumn("dbo.Articles", "IsMain");
        }
    }
}


text:
using Permadelete.Helpers;
using Permadelete.Enums;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using DiskDetector;
namespace Permadelete.Services
{
    public sealed class ShredderService
    {
        #region Constructor
        private ShredderService()
        {

        }
        #endregion

        #region Fields
        private const int MAX_BUFFER_SIZE = Constants.MEGABYTE;
        private const int OBFUSCATE_ROUNDS = 5;

        Random _random = new Random();
        #endregion

        #region Properties
        // using Lazy<T> here makes the the field both lazily loaded and thread safe
        // more info: http://csharpindepth.com/Articles/General/Singleton.aspx
        private static Lazy<ShredderService> _instance = new Lazy<ShredderService>(() => new ShredderService());
        public static ShredderService Instance
        {
            get { return _instance.Value; }
        }
        #endregion

        #region Methods
        public async Task<bool> ShredItemAsync(string path, int passes, CancellationToken cancellationToken, IProgress<long> progress)
        {
            FileInfo file = null;
            DirectoryInfo folder = null;

            if (File.Exists(path))
                file = new FileInfo(path);
            else if (Directory.Exists(path))
                folder = new DirectoryInfo(path);
            else
                throw new ArgumentException($"This path does not exist: {path}");

            if (file != null)
                return await ShredFileAsync(file, passes, cancellationToken, progress).ConfigureAwait(false);

            if (cancellationToken != null)
                cancellationToken.ThrowIfCancellationRequested();

            if (folder != null)
                return await ShredFolderAsync(folder, passes, cancellationToken, progress).ConfigureAwait(false);

            return false;
        }

        public async Task<long> GetFolderSize(DirectoryInfo folder)
        {
            long length = 0;
            await Task.Run(async () =>
            {
                foreach (var item in folder.EnumerateFiles())
                {
                    length += item.Length;
                }

                foreach (var item in folder.EnumerateDirectories())
                {
                    length += await GetFolderSize(item);
                }
            });

            return length;
        }

        public async Task<bool> ShredFileAsync(FileInfo file, int passes, CancellationToken cancellationToken, IProgress<long> progress)
        {
            var totalBytes = file.Length * passes;

            var writeProgress = new Progress<long>();
            writeProgress.ProgressChanged += (sender, newBytes) =>
            {
                if (progress == null) return;
                progress.Report(newBytes);
            };

            // if the file was a syslink, then only remove the link not the contents.
            // and if the drive was an ssd, then there is no point in overwriting content
            // more info: https://samsclass.info/121/proj/ssd-evaporation.htm
            var driveName = Path.GetPathRoot(file.FullName);
            if ((file.Attributes & FileAttributes.ReparsePoint) == 0 && !DiskIsSSD(driveName))
            {
                file.Attributes = FileAttributes.Normal;
                file.Attributes = FileAttributes.NotContentIndexed;

                for (int i = 0; i < passes; i++)
                {
                    var result = await OverwriteFileAsync(file, cancellationToken, writeProgress).ConfigureAwait(false);
                    if (!result) return result;

                    if (cancellationToken != null) cancellationToken.ThrowIfCancellationRequested();
                }

                using (var stream = File.OpenWrite(file.FullName))
                {
                    stream.SetLength(0);
                }

                DestroyFileMetadata(file);
            }
            else
            {
                progress.Report(file.Length * passes);
            }

            file.Delete();

            return true;
        }

        public async Task<bool> ShredFolderAsync(DirectoryInfo folder, int passes, CancellationToken cancellationToken, IProgress<long> progress)
        {
            var totalLength = await GetFolderSize(folder);
            var everythingWasShredded = true;

            // if the folder was a syslink then only remove the link not the contents.
            if ((folder.Attributes & FileAttributes.ReparsePoint) == 0)
            {
                Progress<long> itemProgress;
                foreach (var info in folder.EnumerateFileSystemInfos())
                {
                    itemProgress = new Progress<long>();

                    if (cancellationToken != null)
                        cancellationToken.ThrowIfCancellationRequested();

                    var file = info as FileInfo;
                    var dir = info as DirectoryInfo;
                    long length = 0;

                    try
                    {
                        if (file != null)
                        {
                            length = file.Length;
                            itemProgress.ProgressChanged += (sender, newBytes) => progress.Report(newBytes);
                            var result = await ShredFileAsync(file, passes, cancellationToken, itemProgress).ConfigureAwait(false);

                            if (!result) return result;
                        }

                        if (dir != null)
                        {
                            length = await GetFolderSize(dir);
                            itemProgress.ProgressChanged += (sender, newBytes) => progress.Report(newBytes);
                            var result = await ShredFolderAsync(dir, passes, cancellationToken, itemProgress).ConfigureAwait(false);

                            if (!result) return result;
                        }
                    }
                    catch (Exception)
                    {
                        // if an exception was thrown, just skip this item
                        everythingWasShredded = false;
                        progress.Report((length));
                        continue;
                    }
                }
            }

            // if the folder was actually a logical drive (e.g. D:\)
            // don't even try to delete it
            if (everythingWasShredded && folder.Parent != null)
                folder.Delete();

            return everythingWasShredded;
        }

        public bool IsFileLocked(FileInfo file)
        {
            FileStream stream = null;

            try
            {
                stream = file.Open(FileMode.Open, FileAccess.Read, FileShare.None);
            }
            catch (IOException)
            {
                return true;
            }
            finally
            {
                if (stream != null) stream.Close();
            }

            return false;
        }
        #endregion

        #region Private Methods
        private async Task<bool> OverwriteFileAsync(FileInfo file, CancellationToken cancellationToken, IProgress<long> progress)
        {
            using (var stream = new FileStream(file.FullName, FileMode.Open, FileAccess.Write, FileShare.None))
            {
                var buffer = new byte[MAX_BUFFER_SIZE];
                for (int i = 0; i < MAX_BUFFER_SIZE; i++)
                {
                    buffer[i] = (byte)_random.Next(0, 255);
                }

                for (var length = file.Length; length > 0; length -= MAX_BUFFER_SIZE)
                {
                    int bytesToWrite = (length > MAX_BUFFER_SIZE) ? MAX_BUFFER_SIZE : (int)length;

                    await stream.WriteAsync(buffer, 0, bytesToWrite).ConfigureAwait(false);
                    await stream.FlushAsync().ConfigureAwait(false);

                    if (progress != null)
                        progress.Report(bytesToWrite);

                    if (cancellationToken != null)
                        cancellationToken.ThrowIfCancellationRequested();
                }
            }

            return true;
        }

        private bool DestroyFileMetadata(FileInfo file, FileSystemType fileSystemType = FileSystemType.Unknown)
        {
            if (!file.Exists)
                return false;

            var directoryName = Path.GetDirectoryName(file.FullName);

            // rename the file a few times to remove it from the file system table.
            for (var round = 0; round < OBFUSCATE_ROUNDS; round++)
            {
                var newPath = Path.Combine(directoryName, Path.GetRandomFileName());
                file.MoveTo(newPath);
            }

            var newTime = new DateTime(2000, 1, 1, 0, 0, 1);
            file.LastWriteTime = newTime;
            file.CreationTime = newTime;
            file.LastAccessTime = newTime;

            return true;
        }

        private bool DiskIsSSD(string driveName)
        {
            try
            {
                var result = Detector.DetectDrive(driveName);
                return result.HardwareType == DiskDetector.Models.HardwareType.Ssd;
            }
            catch
            {
                return false;
            }
        }
        #endregion
    }
}


text:
//
//  NSString+HTML.m
//  epub
//
//  Created by Chris Ridd on 24/01/2012.
//  Copyright (c) 2012 Chris Ridd. All rights reserved.
//

#import "NSString+HTML.h"

@implementation NSString (HTML)

/* Return an autoreleased version with HTML specials escaped. */
- (NSString *)stringByEscapingHTML
{
    NSMutableString *e = [self mutableCopy];
    [e replaceOccurrencesOfString:@"&" withString:@"&" options:0 range:NSMakeRange(0, [e length])];
    [e replaceOccurrencesOfString:@"<" withString:@"<" options:0 range:NSMakeRange(0, [e length])];
    [e replaceOccurrencesOfString:@">" withString:@">" options:0 range:NSMakeRange(0, [e length])];
    return [NSString stringWithString:e];
}

/* Return an autoreleased version with HTML/XML tags removed. */
- (NSString *)stringByStrippingHTML
{
    NSScanner *s = [NSScanner scannerWithString:self];
    [s setCharactersToBeSkipped:[NSCharacterSet characterSetWithCharactersInString:@""]];
    NSCharacterSet *pre = [[NSCharacterSet characterSetWithCharactersInString:@"<"] invertedSet];
    NSCharacterSet *end = [NSCharacterSet characterSetWithCharactersInString:@">"];
    NSCharacterSet *tag = [end invertedSet];

    NSMutableString *result = [[NSMutableString alloc] initWithCapacity:self.length];
    while ([s isAtEnd] == NO) {
        NSString *p = nil;
        if ([s scanCharactersFromSet:pre intoString:&p] == YES)
            [result appendString:p];
        [s scanCharactersFromSet:tag intoString:NULL];
        [s scanCharactersFromSet:end intoString:NULL];
    }
	return [NSString stringWithString:result];
}
@end


text:
package com.intellij.openapi.vcs.actions;

import com.intellij.openapi.application.ApplicationManager;
import com.intellij.openapi.application.ModalityState;
import com.intellij.openapi.diff.*;
import com.intellij.openapi.editor.Document;
import com.intellij.openapi.fileEditor.FileDocumentManager;
import com.intellij.openapi.progress.ProcessCanceledException;
import com.intellij.openapi.progress.ProgressIndicator;
import com.intellij.openapi.progress.ProgressManager;
import com.intellij.openapi.progress.Task;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.ui.Messages;
import com.intellij.openapi.util.Ref;
import com.intellij.openapi.vcs.AbstractVcsHelper;
import com.intellij.openapi.vcs.ProjectLevelVcsManager;
import com.intellij.openapi.vcs.VcsBundle;
import com.intellij.openapi.vcs.VcsException;
import com.intellij.openapi.vcs.changes.BackgroundFromStartOption;
import com.intellij.openapi.vcs.changes.BinaryContentRevision;
import com.intellij.openapi.vcs.changes.ContentRevision;
import com.intellij.openapi.vcs.diff.DiffProvider;
import com.intellij.openapi.vcs.diff.ItemLatestState;
import com.intellij.openapi.vcs.history.VcsRevisionNumber;
import com.intellij.openapi.vcs.impl.BackgroundableActionEnabledHandler;
import com.intellij.openapi.vcs.impl.ProjectLevelVcsManagerImpl;
import com.intellij.openapi.vcs.impl.VcsBackgroundableActions;
import com.intellij.openapi.vfs.VirtualFile;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;

import java.io.IOException;
import java.util.Arrays;

public abstract class DiffActionExecutor {
  protected final DiffProvider myDiffProvider;
  protected final VirtualFile mySelectedFile;
  protected final Project myProject;
  private final BackgroundableActionEnabledHandler myHandler;

  protected DiffActionExecutor(final DiffProvider diffProvider, final VirtualFile selectedFile, final Project project,
                               final VcsBackgroundableActions actionKey) {
    final ProjectLevelVcsManagerImpl vcsManager = (ProjectLevelVcsManagerImpl) ProjectLevelVcsManager.getInstance(project);
    myHandler = vcsManager.getBackgroundableActionHandler(actionKey);
    myDiffProvider = diffProvider;
    mySelectedFile = selectedFile;
    myProject = project;
  }

  @Nullable
  protected DiffContent createRemote(final VcsRevisionNumber revisionNumber) throws IOException, VcsException {
    final ContentRevision fileRevision = myDiffProvider.createFileContent(revisionNumber, mySelectedFile);
    if (fileRevision instanceof BinaryContentRevision) {
      final byte[] a = mySelectedFile.contentsToByteArray();
      final byte[] content = ((BinaryContentRevision)fileRevision).getBinaryContent();

      ApplicationManager.getApplication().invokeLater(new Runnable() {
        public void run() {
          if (Arrays.equals(a, content)) {
            Messages.showInfoMessage(VcsBundle.message("message.text.binary.versions.are.identical"), VcsBundle.message("message.title.diff"));
          } else {
            Messages.showInfoMessage(VcsBundle.message("message.text.binary.versions.are.different"), VcsBundle.message("message.title.diff"));
          }
        }
      }, ModalityState.NON_MODAL);
      return null;
    }

    if (fileRevision != null) {
      final String content = fileRevision.getContent();
      if (content == null) {
        throw new VcsException("Failed to load content");
      }
      return new SimpleContent(content, mySelectedFile.getFileType());
    }
    return null;
  }

  public void showDiff() {
    final Ref<VcsException> exceptionRef = new Ref<VcsException>();
    final Ref<SimpleDiffRequest> requestRef = new Ref<SimpleDiffRequest>();

    final Task.Backgroundable task = new Task.Backgroundable(myProject,
        VcsBundle.message("show.diff.progress.title.detailed", mySelectedFile.getPath()), true, BackgroundFromStartOption.getInstance()) {

      public void run(@NotNull ProgressIndicator indicator) {
        final VcsRevisionNumber revisionNumber = getRevisionNumber();
        try {
          if (revisionNumber == null) {
            return;
          }
          final DiffContent remote = createRemote(revisionNumber);
          if (remote == null) {
            return;
          }

          final SimpleDiffRequest request = new SimpleDiffRequest(myProject, mySelectedFile.getPresentableUrl());
          final Document document = FileDocumentManager.getInstance().getDocument(mySelectedFile);
          if (document == null) return;
          final DocumentContent content2 = new DocumentContent(myProject, document);

          final VcsRevisionNumber currentRevision = myDiffProvider.getCurrentRevision(mySelectedFile);

          if (revisionNumber.compareTo(currentRevision) > 0) {
            request.setContents(content2, remote);
            request.setContentTitles(VcsBundle.message("diff.title.local"), revisionNumber.asString());
          }
          else {
            request.setContents(remote, content2);
            request.setContentTitles(revisionNumber.asString(), VcsBundle.message("diff.title.local"));
          }

          request.addHint(DiffTool.HINT_SHOW_FRAME);
          requestRef.set(request);
        }
        catch (ProcessCanceledException e) {
          //ignore
        }
        catch (VcsException e) {
          exceptionRef.set(e);
        }
        catch (IOException e) {
          exceptionRef.set(new VcsException(e));
        }
      }

      @Override
      public void onCancel() {
        onSuccess();
      }

      @Override
      public void onSuccess() {
        myHandler.completed(VcsBackgroundableActions.keyFrom(mySelectedFile));

        if (! exceptionRef.isNull()) {
          AbstractVcsHelper.getInstance(myProject).showError(exceptionRef.get(), VcsBundle.message("message.title.diff"));
          return;
        }
        if (! requestRef.isNull()) {
          DiffManager.getInstance().getDiffTool().show(requestRef.get());
        }
      }
    };

    myHandler.register(VcsBackgroundableActions.keyFrom(mySelectedFile));
    ProgressManager.getInstance().run(task);
  }

  public static void showDiff(final DiffProvider diffProvider, final VcsRevisionNumber revisionNumber, final VirtualFile selectedFile,
                              final Project project, final VcsBackgroundableActions actionKey) {
    final DiffActionExecutor executor = new CompareToFixedExecutor(diffProvider, selectedFile, project, revisionNumber, actionKey);
    executor.showDiff();
  }

  @Nullable
  protected abstract VcsRevisionNumber getRevisionNumber();

  public static class CompareToFixedExecutor extends DiffActionExecutor {
    private final VcsRevisionNumber myNumber;

    public CompareToFixedExecutor(final DiffProvider diffProvider,
                                  final VirtualFile selectedFile, final Project project, final VcsRevisionNumber number,
                                  final VcsBackgroundableActions actionKey) {
      super(diffProvider, selectedFile, project, actionKey);
      myNumber = number;
    }

    protected VcsRevisionNumber getRevisionNumber() {
      return myNumber;
    }
  }

  public static class CompareToCurrentExecutor extends DiffActionExecutor {
    public CompareToCurrentExecutor(final DiffProvider diffProvider, final VirtualFile selectedFile, final Project project,
                                    final VcsBackgroundableActions actionKey) {
      super(diffProvider, selectedFile, project, actionKey);
    }

    @Nullable
    protected VcsRevisionNumber getRevisionNumber() {
      return myDiffProvider.getCurrentRevision(mySelectedFile);
    }
  }

  public static class DeletionAwareExecutor extends DiffActionExecutor {
    private boolean myFileStillExists;

    public DeletionAwareExecutor(final DiffProvider diffProvider,
                                 final VirtualFile selectedFile, final Project project, final VcsBackgroundableActions actionKey) {
      super(diffProvider, selectedFile, project, actionKey);
    }

    protected VcsRevisionNumber getRevisionNumber() {
      final ItemLatestState itemState = myDiffProvider.getLastRevision(mySelectedFile);
      if (itemState == null) {
        return null;
      }
      myFileStillExists = itemState.isItemExists();
      return itemState.getNumber();
    }

    @Override
    protected DiffContent createRemote(final VcsRevisionNumber revisionNumber) throws IOException, VcsException {
      if (myFileStillExists) {
        return super.createRemote(revisionNumber);
      } else {
        return new SimpleContent("", mySelectedFile.getFileType());
      }
    }
  }
}


text:
 <title>0x546F6D69</title>

Unnamed platformer strategy game

My next game project changed from platformer to strategy game. Better to do something you like, so there's a chance it will be finished one day :)

Style: medieval / fantasy boardgame look with pretty simple rules (like Warhammer etc.).

Game is in real-time and used can stop time to give commands to units.

UI is separated from Game Engine, so engine works with WinForms and XNA (XNA.Game replaces Game-class).

Have to find nice physics engine from somewhere. I don't have enough time to make my own (working one).

Architecture is almost ready (at least for now).

Getting good tips from Replica Island's architecture.

Google I/O 2009: Writing Real Time Games For Android.

	Full view of map

	GameState Update sequence at the moment:

	Notes:

	UI
	- User Interface
	Game
		- Main loop
	StateManager
		- Keep track in what state game is
	State
		- Game bahaviour logic
		- Decide what to do when updating and with inputs
	InputManager
		- Handle Input Queue
		- Execute InputActions
	InputAction
		- Move Camera, Zoom, Select etc.
		- DoAction does all the action
	ObjectManager
		- Creates and handles all GameObjects
		QuadTree
			- Keeps track of object locations
		GameObject
			- Objects you can see in the UI
				- Includes blocking objects, like houses, walls and trees.
			Character
			- Objects that participate in the "game"
				Behavior
					- What will AI character do
			Item
				- Objects Characters can use (weapons, armor etc.)
	CameraSystem
		- Keeps track of coordinates of what is shown in window
	GameArea
		- Info of full map

	----------------------------------------------------
	Game has different States:
	Init
		- Load all objects
	GameState
		- Game is running
	Pause
		- Game is paused
		- User can view map, give commands to GameObjects, but objects are not moving.
	End
		- Show statistics

	----------------------------------------------------
	On UserInput current state checks if input is allowed in this state and InputManager adds inputs to queues and returns those to State at Update.

	User can zoom in/out camera. Game will only draw object on view (using QuadTree).

	QuadTree is also used to check collisions and when calculating routes to target.

	These were amazing graphics for platformer.

	  <address>

		 11.4.2011

		 tomi.tuhkanen@iki.fi

	  </address>


text:
var Handlebars = require('./base');

// BEGIN(BROWSER)
(function() {

  Handlebars.AST = {};

  Handlebars.AST.ProgramNode = function(statements, inverse) {
    this.type = "program";
    this.statements = statements;
    if(inverse) { this.inverse = new Handlebars.AST.ProgramNode(inverse); }
  };

  Handlebars.AST.MustacheNode = function(params, hash, unescaped) {
    this.type = "mustache";
    this.id = params[0];
    this.params = params.slice(1);
    this.hash = hash;
    this.escaped = !unescaped;
  };

  Handlebars.AST.PartialNode = function(id, context) {
    this.type    = "partial";

    // TODO: disallow complex IDs

    this.id      = id;
    this.context = context;
  };

  var verifyMatch = function(open, close) {
    if(open.original !== close.original) {
      throw new Handlebars.Exception(open.original + " doesn't match " + close.original);
    }
  };

  Handlebars.AST.BlockNode = function(mustache, program, close) {
    verifyMatch(mustache.id, close);
    this.type = "block";
    this.mustache = mustache;
    this.program  = program;
  };

  Handlebars.AST.InverseNode = function(mustache, program, close) {
    verifyMatch(mustache.id, close);
    this.type = "inverse";
    this.mustache = mustache;
    this.program  = program;
  };

  Handlebars.AST.ContentNode = function(string) {
    this.type = "content";
    this.string = string;
  };

  Handlebars.AST.HashNode = function(pairs) {
    this.type = "hash";
    this.pairs = pairs;
  };

  Handlebars.AST.IdNode = function(parts) {
    this.type = "ID";
    this.original = parts.join(".");

    var dig = [], depth = 0;

    for(var i=0,l=parts.length; i<l; i++) {
      var part = parts[i];

      if(part === "..") { depth++; }
      else if(part === "." || part === "this") { this.isScoped = true; }
      else { dig.push(part); }
    }

    this.parts    = dig;
    this.string   = dig.join('.');
    this.depth    = depth;
    this.isSimple = (dig.length === 1) && (depth === 0);
  };

  Handlebars.AST.StringNode = function(string) {
    this.type = "STRING";
    this.string = string;
  };

  Handlebars.AST.IntegerNode = function(integer) {
    this.type = "INTEGER";
    this.integer = integer;
  };

  Handlebars.AST.BooleanNode = function(bool) {
    this.type = "BOOLEAN";
    this.bool = bool;
  };

  Handlebars.AST.CommentNode = function(comment) {
    this.type = "comment";
    this.comment = comment;
  };

})();
// END(BROWSER)