text:
static
VOID
VecsSrvFreeCertContainer(
    PVMAFD_CERT_CONTAINER pContainer,
    DWORD dwArraySize
    );
static
DWORD
VecsDbGetStoreCount(
    PVECS_DB_CONTEXT pDbContext,
    PDWORD pdwStoreCount
    );

static
BOOL
VecsDbIsRestrictedStore (
    PCWSTR pszStoreName
    );

DWORD
VecsDbCreateCertStore(
    PCWSTR pszStoreName,
    PCWSTR pszPassword
    )
{
    DWORD dwError = 0;
    PVECS_DB_CONTEXT pDbContext = NULL;
    sqlite3_stmt* pDbQuery = NULL;
    sqlite3_stmt* pDbQuerySize = NULL;
    DWORD dwSizeOfTable = 0;

    if (IsNullOrEmptyString(pszStoreName))
    {
        dwError = ERROR_INVALID_PARAMETER;
        BAIL_ON_VECS_ERROR(dwError);
    }

    dwError = VecsDbCreateContext(&pDbContext);
    BAIL_ON_VECS_ERROR(dwError);

   dwError = VecsDbGetStoreCount(pDbContext, &dwSizeOfTable);
   BAIL_ON_VECS_ERROR (dwError);

   if (dwSizeOfTable > STORE_TABLE_LIMIT)
   {
      dwError = ERROR_IMPLEMENTATION_LIMIT;
      BAIL_ON_VECS_ERROR (dwError);
   }

    if(!pDbContext->pCreateStoreTable)
    {
        CHAR szQuery[] =
                        "INSERT INTO StoreTable ("
                        " StoreName,"
                        " Password,"
                        " Salt)"
                        " VALUES( :storeName,"
                                    " :password,"
                                    " :salt);";
        dwError = sqlite3_prepare_v2(
                            pDbContext->pDb,
                            szQuery,
                            -1,
                            &pDbContext->pCreateStoreTable,
                            NULL);
        BAIL_ON_VECS_ERROR(dwError);
    }

    pDbQuery = pDbContext->pCreateStoreTable;

    if (!pDbContext->bInTx)
    {
        dwError = VecsDbBeginTransaction(pDbContext->pDb);
        BAIL_ON_VECS_ERROR(dwError);

        pDbContext->bInTx = TRUE;
    }

    dwError = VecsBindWideString(
                    pDbQuery,
                    ":storeName",
                    (PWSTR)pszStoreName
                    );
    BAIL_ON_VECS_ERROR(dwError);

    dwError = VecsBindWideString(
                    pDbQuery,
                    ":password",
                    (PWSTR)pszPassword
                    );
    BAIL_ON_VECS_ERROR(dwError);

    dwError = VecsBindWideString(
                    pDbQuery,
                    ":salt",
                    (PWSTR)NULL
                    );
    BAIL_ON_VECS_ERROR(dwError);

    dwError = VecsDbStepSql(pDbQuery);
    BAIL_ON_VECS_ERROR(dwError);

    dwError = VecsDbCommitTransaction(pDbContext->pDb);
    BAIL_ON_VECS_ERROR(dwError);

    pDbContext->bInTx = FALSE;

cleanup:

    if (pDbQuery)
    {
        sqlite3_reset(pDbQuery);
    }
    if (pDbQuerySize)
    {
        sqlite3_reset(pDbQuerySize);
    }
    if (pDbContext)
    {
        VecsDbReleaseContext(pDbContext);
    }

    return dwError;

error:

    if (pDbContext && pDbContext->bInTx)
    {
        VecsDbRollbackTransaction(pDbContext->pDb);
        pDbContext->bInTx = FALSE;
    }
    if (dwError == SQLITE_CONSTRAINT)
    {
        dwError = ERROR_ALREADY_EXISTS;
    }

    goto cleanup;
}

DWORD
VecsDbGetCertStore(
        PCWSTR pszStoreName,
        PCWSTR pszPassWord,
        PDWORD pdwStoreId
        )
{
   DWORD dwError = 0;
   PVECS_DB_CONTEXT pDbContext = NULL;
   sqlite3_stmt* pDbQuery = NULL;
   DWORD dwStoreId = 0;

   if (IsNullOrEmptyString(pszStoreName))
   {
       dwError = ERROR_INVALID_PARAMETER;
       BAIL_ON_VECS_ERROR(dwError);
   }

   dwError = VecsDbCreateContext(&pDbContext);
   BAIL_ON_VECS_ERROR(dwError);

   if(!pDbContext->pQueryStoreTable)
   {
       CHAR szQuery[] =
                       "SELECT  StoreID "
                       "FROM StoreTable "
                       "WHERE StoreName = :storeName";

       dwError = sqlite3_prepare_v2(
                           pDbContext->pDb,
                           szQuery,
                           -1,
                           &pDbContext->pQueryStoreTable,
                           NULL);
       BAIL_ON_VECS_ERROR(dwError);
   }

   pDbQuery = pDbContext->pQueryStoreTable;

   dwError = VecsBindWideString(
                   pDbQuery,
                   ":storeName",
                   (PWSTR)pszStoreName
                   );
   BAIL_ON_VECS_ERROR(dwError);

   dwError = VecsDbStepSql(pDbQuery);
   if (dwError == SQLITE_ROW)
   {
              dwError =  VecsDBGetColumnInt(
                          pDbQuery,
                          "StoreID",
                          &dwStoreId);
              BAIL_ON_VECS_ERROR(dwError);
   }
   else if (dwError == SQLITE_DONE)
   {
       dwError = ERROR_OBJECT_NOT_FOUND;
   }
   BAIL_ON_VECS_ERROR(dwError);

   if (dwStoreId == 0)
   {
       dwError = ERROR_OBJECT_NOT_FOUND;
       BAIL_ON_VECS_ERROR (dwError);
   }

   *pdwStoreId = dwStoreId;

cleanup:

   if (pDbQuery)
   {
       sqlite3_reset(pDbQuery);
   }
   if (pDbContext)
   {
        VecsDbReleaseContext(pDbContext);
   }

   return dwError;

error:

   goto cleanup;
}

DWORD
VecsDbGetCertStoreName(
        DWORD   dwStoreId,
        PWSTR*  ppwszStoreName
        )
{
   DWORD dwError = 0;
   PVECS_DB_CONTEXT pDbContext = NULL;
   sqlite3_stmt* pDbQuery = NULL;
   PWSTR pwszStoreName = NULL;

   if (!ppwszStoreName)
   {
       dwError = ERROR_INVALID_PARAMETER;
       BAIL_ON_VECS_ERROR(dwError);
   }

   dwError = VecsDbCreateContext(&pDbContext);
   BAIL_ON_VECS_ERROR(dwError);

   if(!pDbContext->pQueryStoreTable)
   {
       CHAR szQuery[] =
                       "SELECT  StoreName "
                       "FROM StoreTable "
                       "WHERE StoreID = :storeID";

       dwError = sqlite3_prepare_v2(
                           pDbContext->pDb,
                           szQuery,
                           -1,
                           &pDbContext->pQueryStoreTable,
                           NULL);
       BAIL_ON_VECS_ERROR(dwError);
   }

   pDbQuery = pDbContext->pQueryStoreTable;

   dwError = VecsBindDword(
                   pDbQuery,
                   ":storeID",
                   (DWORD)dwStoreId
                   );
   BAIL_ON_VECS_ERROR(dwError);

   dwError = VecsDbStepSql(pDbQuery);
   if (dwError == SQLITE_ROW)
   {
              dwError =  VecsDBGetColumnString(
                          pDbQuery,
                          "StoreName",
                          &pwszStoreName);
              BAIL_ON_VECS_ERROR(dwError);
   }
   else if (dwError == SQLITE_DONE)
   {
       dwError = ERROR_OBJECT_NOT_FOUND;
   }
   BAIL_ON_VECS_ERROR(dwError);

   if (dwStoreId == 0)
   {
       dwError = ERROR_OBJECT_NOT_FOUND;
       BAIL_ON_VECS_ERROR (dwError);
   }

   *ppwszStoreName = pwszStoreName;

cleanup:

   if (pDbQuery)
   {
       sqlite3_reset(pDbQuery);
   }
   if (pDbContext)
   {
        VecsDbReleaseContext(pDbContext);
   }

   return dwError;

error:
   VMAFD_SAFE_FREE_MEMORY(pwszStoreName);
   if (ppwszStoreName)
   {
       *ppwszStoreName = NULL;
   }

   goto cleanup;
}

DWORD
VecsDbEnumCertStore(
    PWSTR **ppszStoreNameArray,
    PDWORD pdwCount
    )
{
    DWORD dwError = 0;
    DWORD dwDbStatus = 0;
    PVECS_DB_CONTEXT pDbContext = NULL;
    sqlite3_stmt* pDbQuery = NULL;
    DWORD dwStoresReturned = 0;
    PWSTR *pszStoreNameArray = NULL;
    DWORD dwStoreTableSize = 0;

    dwError = VecsDbCreateContext(&pDbContext);
    BAIL_ON_VECS_ERROR(dwError);

    dwError = VecsDbGetStoreCount (pDbContext, &dwStoreTableSize);
    BAIL_ON_VECS_ERROR (dwError);

    if (dwStoreTableSize)
    {
      if(!pDbContext->pQueryStoreTable)
      {
          CHAR szQuery[] = "SELECT "
                                 " StoreID,"
                                 " StoreName"
                                 " FROM StoreTable"
                                 " ORDER BY StoreID"
                                 " LIMIT :count";

            dwError = sqlite3_prepare_v2(
                pDbContext->pDb,
                szQuery,
                -1,
                &pDbContext->pQueryStoreTable,
                NULL);
            BAIL_ON_VECS_ERROR(dwError);
      }

      pDbQuery = pDbContext->pQueryStoreTable;

      if (!pDbContext->bInTx)
      {
        dwError = VecsDbBeginTransaction(pDbContext->pDb);
        BAIL_ON_VECS_ERROR(dwError);

        pDbContext->bInTx = TRUE;
      }

      dwError = VecsBindDword(
                   pDbQuery,
                   ":count",
                   dwStoreTableSize
                   );
      BAIL_ON_VECS_ERROR(dwError);

      dwError = VecsAllocateMemory(
                    sizeof(PWSTR)*dwStoreTableSize,
                    (PVOID *)&pszStoreNameArray
                    );
      BAIL_ON_VECS_ERROR(dwError);

      do
      {
          dwDbStatus = VecsDbStepSql(pDbQuery);

          if (dwDbStatus == SQLITE_ROW)
          {
              dwError = VecsDBGetColumnString(
                          pDbQuery,
                          "StoreName",
                          &(pszStoreNameArray[dwStoresReturned]));
              BAIL_ON_VECS_ERROR(dwError);

              dwStoresReturned++;
          }
          else if (dwDbStatus != SQLITE_DONE)
          {
            dwError = dwDbStatus;
            BAIL_ON_VECS_ERROR(dwError);
          }
      } while (dwDbStatus == SQLITE_ROW);
      dwError = VecsDbCommitTransaction(pDbContext->pDb);
      BAIL_ON_VECS_ERROR(dwError);
    }

    pDbContext->bInTx = FALSE;

    *pdwCount = dwStoresReturned;
    *ppszStoreNameArray = pszStoreNameArray;

cleanup:

    if (pDbQuery)
    {
       sqlite3_reset(pDbQuery);
    }
    if (pDbContext)
    {
        VecsDbReleaseContext(pDbContext);
    }

    return dwError;

error:

    if (pDbContext && pDbContext->bInTx)
    {
       VecsDbRollbackTransaction(pDbContext->pDb);
       pDbContext->bInTx = FALSE;
    }
    if (ppszStoreNameArray)
    {
        *ppszStoreNameArray = NULL;
    }
    if (pdwCount)
    {
        *pdwCount = 0;
    }
    if (pszStoreNameArray)
    {
        VmAfdFreeStringArrayW (pszStoreNameArray, dwStoresReturned);
    }

    goto cleanup;
}

DWORD
VecsDbDeleteCertStore(
    PCWSTR pwszStoreName
    )
{
    DWORD dwError = 0;
    PVECS_DB_CONTEXT pDbContext = NULL;
    sqlite3_stmt* pDbQuery = NULL;
    DWORD dwStoreId = 0;

    if (IsNullOrEmptyString(pwszStoreName))
    {
        dwError = ERROR_INVALID_PARAMETER;
        BAIL_ON_VECS_ERROR(dwError);
    }

    if (VecsDbIsRestrictedStore (pwszStoreName))
    {
        dwError = ERROR_ACCESS_DENIED;
        BAIL_ON_VECS_ERROR (dwError);
    }

    dwError = VecsDbGetCertStore(pwszStoreName, NULL , &dwStoreId);
    BAIL_ON_VECS_ERROR(dwError);

    dwError = VecsDbCreateContext(&pDbContext);
    BAIL_ON_VECS_ERROR(dwError);

    if (!pDbContext->pDeleteStore)
    {
        CHAR szQuery[] = "DELETE FROM StoreTable WHERE StoreName = :storeName";

        dwError = sqlite3_prepare_v2(
                            pDbContext->pDb,
                            szQuery,
                            -1,
                            &pDbContext->pDeleteStore,
                            NULL);
        BAIL_ON_VECS_ERROR(dwError);
    }

    pDbQuery = pDbContext->pDeleteStore;

    if (!pDbContext->bInTx)
    {
        dwError = VecsDbBeginTransaction(pDbContext->pDb);
        BAIL_ON_VECS_ERROR(dwError);

        pDbContext->bInTx = TRUE;
    }

    dwError = VecsBindWideString(
                    pDbQuery,
                    ":storeName",
                    (PWSTR)pwszStoreName
                    );
    BAIL_ON_VECS_ERROR(dwError);

    dwError = VecsDbStepSql(pDbQuery);
    BAIL_ON_VECS_ERROR(dwError);

    dwError = VecsDbCommitTransaction(pDbContext->pDb);
    BAIL_ON_VECS_ERROR(dwError);

    pDbContext->bInTx = FALSE;

cleanup:

    if (pDbQuery)
    {
        sqlite3_reset(pDbQuery);
    }
    if (pDbContext)
    {
        VecsDbReleaseContext(pDbContext);
    }

    return dwError;

error:

    if (pDbContext && pDbContext->bInTx)
    {
        VecsDbRollbackTransaction(pDbContext->pDb);
        pDbContext->bInTx = FALSE;
    }

    goto cleanup;
}

DWORD
VecsDbAddCert(
        DWORD dwStoreId,
        CERT_ENTRY_TYPE entryType,
        PWSTR pszAliasName,
        PWSTR pszCertificate,
        PWSTR pszPrivateKey,
        PWSTR pszPassWord,
        BOOLEAN bAutoRefresh
        )
{
   DWORD dwError = 0;
   PVECS_DB_CONTEXT pDbContext = NULL;
   sqlite3_stmt* pDbQuery = NULL;
   size_t nCertSize = 0;
   size_t nPrivateKeySize = 0;
   DWORD dwCertSize = 0;
   DWORD dwPrivateKeySize = 0;

   if (IsNullOrEmptyString(pszAliasName))
   {
       dwError = ERROR_INVALID_PARAMETER;
       BAIL_ON_VECS_ERROR(dwError);
   }

   if (pszCertificate)
   {
      dwError = VmAfdGetStringLengthW(
                    (PCWSTR)pszCertificate,
                    &nCertSize
                    );
      BAIL_ON_VECS_ERROR (dwError);
      dwCertSize = (nCertSize +1)* sizeof(WCHAR);
   }

   if (pszPrivateKey)
   {
      dwError = VmAfdGetStringLengthW(
                    (PCWSTR)pszPrivateKey,
                    &nPrivateKeySize
                    );
      BAIL_ON_VECS_ERROR (dwError);
      dwPrivateKeySize = (nPrivateKeySize+1)* sizeof(WCHAR);
   }

   dwError = VecsDbCreateContext(&pDbContext);
   BAIL_ON_VECS_ERROR(dwError);

   if(!pDbContext->pAddCertQuery)
   {
       CHAR szQuery[] =
                      "INSERT INTO CertTable ("
                      " Alias,"
                      " CertSize,"
                      " CertBlob,"
                      " Password,"
                      " EntryType,"
                      " KeySize,"
                      " PrivateKey,"
                      " StoreID,"
                      " AutoRefresh)"
                      " VALUES( :alias,"
                            " :certsize,"
                            " :certblob,"
                            " :password,"
                            " :entrytype,"
                            " :keysize,"
                            " :privatekey,"
                            " :storeid,"
                            " :autorefresh);";

       dwError = sqlite3_prepare_v2(
                           pDbContext->pDb,
                           szQuery,
                           -1,
                           &pDbContext->pAddCertQuery,
                           NULL);
       BAIL_ON_VECS_ERROR(dwError);
   }

   pDbQuery = pDbContext->pAddCertQuery;

   if (!pDbContext->bInTx)
   {
       dwError = VecsDbBeginTransaction(pDbContext->pDb);
       BAIL_ON_VECS_ERROR(dwError);

       pDbContext->bInTx = TRUE;
   }

   dwError = VecsBindWideString(
                   pDbQuery,
                   ":alias",
                   pszAliasName
                   );
   BAIL_ON_VECS_ERROR(dwError);

   dwError = VecsBindBlob(
                  pDbQuery,
                  ":certblob",
                  (PBYTE)pszCertificate,
                  dwCertSize
                  );
   BAIL_ON_VECS_ERROR (dwError);

   dwError = VecsBindDword(
                  pDbQuery,
                  ":certsize",
                  dwCertSize
                  );
   BAIL_ON_VECS_ERROR (dwError);

   dwError = VecsBindWideString(
                  pDbQuery,
                  ":password",
                  pszPassWord
                  );
   BAIL_ON_VECS_ERROR (dwError);

   dwError = VecsBindDword(
                  pDbQuery,
                  ":entrytype",
                  entryType
                  );
   BAIL_ON_VECS_ERROR (dwError);

   dwError = VecsBindBlob(
                  pDbQuery,
                  ":privatekey",
                  (PBYTE)pszPrivateKey,
                  dwPrivateKeySize
                  );
   BAIL_ON_VECS_ERROR (dwError);

   dwError = VecsBindDword(
                  pDbQuery,
                  ":keysize",
                  dwPrivateKeySize
                  );
   BAIL_ON_VECS_ERROR (dwError);

   dwError = VecsBindDword(
                  pDbQuery,
                  ":storeid",
                  dwStoreId
                  );
   BAIL_ON_VECS_ERROR (dwError);

   dwError = VecsBindDword(
                  pDbQuery,
                  ":autorefresh",
                  bAutoRefresh
                  );
   BAIL_ON_VECS_ERROR (dwError);

   dwError = VecsDbStepSql(pDbQuery);
   BAIL_ON_VECS_ERROR (dwError);

   dwError = VecsDbCommitTransaction(pDbContext->pDb);
   BAIL_ON_VECS_ERROR(dwError);

   pDbContext->bInTx = FALSE;

cleanup:

   if (pDbQuery)
   {
       sqlite3_reset(pDbQuery);
   }
   if (pDbContext)
   {
      VecsDbReleaseContext (pDbContext);
   }

   return dwError;

error:

   if (pDbContext && pDbContext->bInTx)
   {
       VecsDbRollbackTransaction(pDbContext->pDb);
       pDbContext->bInTx = FALSE;
   }

   if (dwError == SQLITE_CONSTRAINT)
   {
      dwError = ERROR_ALREADY_EXISTS;
   }

   goto cleanup;
}

DWORD
VecsDbGetEntryByAliasInfoLevel1(
    DWORD dwStoreId,
    PWSTR pszAliasName,
    PVMAFD_CERT_ARRAY *ppCertContainer
    )
{
    DWORD dwError = 0;
    PVECS_DB_CONTEXT pDbContext = NULL;
    sqlite3_stmt* pDbQuery = NULL;
    PVMAFD_CERT_CONTAINER pEntry = NULL;
    PVMAFD_CERT_ARRAY pCertContainer = NULL;
    DWORD dwCount = 0;

    if (IsNullOrEmptyString(pszAliasName) ||
        !ppCertContainer)
    {
       dwError = ERROR_INVALID_PARAMETER;
       BAIL_ON_VECS_ERROR(dwError);
    }

    dwError = VecsDbCreateContext(&pDbContext);
    BAIL_ON_VECS_ERROR(dwError);

    if(!pDbContext->pGetCertFromAliasQuery)
    {
       CHAR szQuery[] =
                       "SELECT  *"
                       " FROM CertTable"
                       " WHERE StoreID = :storeid"
                       " AND Alias = :alias";

       dwError = sqlite3_prepare_v2(
                           pDbContext->pDb,
                           szQuery,
                           -1,
                           &pDbContext->pGetCertFromAliasQuery,
                           NULL);
       BAIL_ON_VECS_ERROR(dwError);
    }

    pDbQuery = pDbContext->pGetCertFromAliasQuery;

    dwError = VecsBindDword(
                   pDbQuery,
                   ":storeid",
                   dwStoreId
                   );
    BAIL_ON_VECS_ERROR(dwError);

    dwError = VecsBindWideString(
                   pDbQuery,
                   ":alias",
                   pszAliasName
                   );
    BAIL_ON_VECS_ERROR(dwError);

    dwError = VecsDbStepSql(pDbQuery);
    if (dwError == SQLITE_ROW)
    {
        dwError = VmAfdAllocateMemory(
                        sizeof (VMAFD_CERT_CONTAINER),
                        (PVOID *) &pEntry
                        );
        BAIL_ON_VECS_ERROR (dwError);

        dwError = VecsDBGetColumnInt(
                        pDbQuery,
                        "EntryType",
                        &(pEntry[dwCount].dwStoreType)
                        );
        BAIL_ON_VECS_ERROR (dwError);

        dwError = VecsDBGetColumnString(
                        pDbQuery,
                        "Alias",
                        &(pEntry[dwCount].pAlias)
                        );
        BAIL_ON_VECS_ERROR (dwError);

        dwError = VecsDBGetColumnInt (
                        pDbQuery,
                        "Date",
                        &(pEntry[dwCount].dwDate));
        BAIL_ON_VECS_ERROR (dwError);

        dwCount++;
    }
    else if (dwError == SQLITE_DONE)
    {
       dwError = ERROR_OBJECT_NOT_FOUND;
    }

    if (!dwCount)
    {
        dwError = ERROR_OBJECT_NOT_FOUND;
    }
    BAIL_ON_VECS_ERROR(dwError);

    dwError = VmAfdAllocateMemory (
                    sizeof (VMAFD_CERT_ARRAY),
                    (PVOID *) &pCertContainer
                    );
    BAIL_ON_VECS_ERROR (dwError);

    pCertContainer->dwCount = dwCount;
    pCertContainer->certificates = pEntry;

    *ppCertContainer = pCertContainer;
cleanup:

    if (pDbQuery)
    {
       sqlite3_reset(pDbQuery);
    }
    if (pDbContext)
    {
        VecsDbReleaseContext (pDbContext);
    }

    return dwError;

error:
    if (ppCertContainer)
    {
      *ppCertContainer = NULL;
    }
    if (pCertContainer)
    {
        VMAFD_SAFE_FREE_MEMORY(pCertContainer);
    }
    if (pEntry)
    {
        VecsSrvFreeCertContainer(pEntry, dwCount);
    }

    goto cleanup;
}

DWORD
VecsDbGetEntryByAliasInfoLevel2(
    DWORD dwStoreId,
    PWSTR pszAliasName,
    PVMAFD_CERT_ARRAY *ppCertContainer
    )
{
    DWORD dwError = 0;
    PVECS_DB_CONTEXT pDbContext = NULL;
    sqlite3_stmt* pDbQuery = NULL;
    PVMAFD_CERT_CONTAINER pEntry = NULL;
    PVMAFD_CERT_ARRAY pCertContainer = NULL;
    DWORD dwCount = 0;
    PBYTE pCertBlob = NULL;
    DWORD dwCertSize = 0;

    if (IsNullOrEmptyString(pszAliasName) ||
        !ppCertContainer)
    {
       dwError = ERROR_INVALID_PARAMETER;
       BAIL_ON_VECS_ERROR(dwError);
    }

    dwError = VecsDbCreateContext(&pDbContext);
    BAIL_ON_VECS_ERROR(dwError);

    if(!pDbContext->pGetCertFromAliasQuery)
    {
       CHAR szQuery[] =
                       "SELECT  *"
                       " FROM CertTable"
                       " WHERE StoreID = :storeid"
                       " AND Alias = :alias";

       dwError = sqlite3_prepare_v2(
                           pDbContext->pDb,
                           szQuery,
                           -1,
                           &pDbContext->pGetCertFromAliasQuery,
                           NULL);
       BAIL_ON_VECS_ERROR(dwError);
    }

    pDbQuery = pDbContext->pGetCertFromAliasQuery;

    dwError = VecsBindDword(
                   pDbQuery,
                   ":storeid",
                   dwStoreId
                   );
    BAIL_ON_VECS_ERROR(dwError);

    dwError = VecsBindWideString(
                   pDbQuery,
                   ":alias",
                   pszAliasName
                   );
    BAIL_ON_VECS_ERROR(dwError);

    dwError = VecsDbStepSql(pDbQuery);
    if (dwError == SQLITE_ROW)
    {
        dwError = VmAfdAllocateMemory(
                        sizeof (VMAFD_CERT_CONTAINER),
                        (PVOID *) &pEntry
                        );
        BAIL_ON_VECS_ERROR (dwError);

        dwError =  VecsDBGetColumnBlob(
                          pDbQuery,
                          "CertBlob",
                          &pCertBlob,
                          &dwCertSize);
        BAIL_ON_VECS_ERROR (dwError);

        if (pCertBlob)
        {

            dwError = VmAfdAllocateStringW(
                              (PWSTR)pCertBlob,
                              &(pEntry[dwCount].pCert)
                              );
            BAIL_ON_VECS_ERROR (dwError);
        }

        dwError = VecsDBGetColumnInt(
                        pDbQuery,
                        "EntryType",
                        &(pEntry[dwCount].dwStoreType)
                        );
        BAIL_ON_VECS_ERROR (dwError);

        dwError = VecsDBGetColumnString(
                        pDbQuery,
                        "Alias",
                        &(pEntry[dwCount].pAlias)
                        );
        BAIL_ON_VECS_ERROR (dwError);

        dwError = VecsDBGetColumnInt (
                    pDbQuery,
                    "Date",
                    &(pEntry[dwCount].dwDate));
        dwCount++;
    }
    else if (dwError == SQLITE_DONE)
    {
       dwError = ERROR_OBJECT_NOT_FOUND;
    }

    if (!dwCount)
    {
        dwError = ERROR_OBJECT_NOT_FOUND;
    }
    BAIL_ON_VECS_ERROR(dwError);

    dwError = VmAfdAllocateMemory (
                    sizeof (VMAFD_CERT_ARRAY),
                    (PVOID *) &pCertContainer
                    );
    BAIL_ON_VECS_ERROR (dwError);

    pCertContainer->dwCount = dwCount;
    pCertContainer->certificates = pEntry;

    *ppCertContainer = pCertContainer;
cleanup:

    if (pDbQuery)
    {
       sqlite3_reset(pDbQuery);
    }
    if (pDbContext)
    {
        VecsDbReleaseContext (pDbContext);
    }

    VMAFD_SAFE_FREE_MEMORY (pCertBlob);

    return dwError;
error:
    if (ppCertContainer)
    {
      *ppCertContainer = NULL;
    }
    if (pCertContainer)
    {
        VMAFD_SAFE_FREE_MEMORY(pCertContainer);
    }
    if (pEntry)
    {
        VecsSrvFreeCertContainer(pEntry, dwCount);
    }

    goto cleanup;
}

DWORD
VecsDbGetEntryTypeByAlias(
    DWORD dwStoreId,
    PWSTR pszAliasName,
    CERT_ENTRY_TYPE *pEntryType
    )
{
    DWORD dwError = 0;
    PVECS_DB_CONTEXT pDbContext = NULL;
    sqlite3_stmt* pDbQuery = NULL;
    CERT_ENTRY_TYPE entryType = CERT_ENTRY_TYPE_UNKNOWN;

    if (IsNullOrEmptyString(pszAliasName) ||
        !pEntryType
       )
    {
       dwError = ERROR_INVALID_PARAMETER;
       BAIL_ON_VECS_ERROR(dwError);
    }

    dwError = VecsDbCreateContext(&pDbContext);
    BAIL_ON_VECS_ERROR(dwError);

    if(!pDbContext->pQueryTypeByAlias)
    {
       CHAR szQuery[] =
                       "SELECT  EntryType"
                       " FROM CertTable"
                       " WHERE StoreID = :storeid"
                       " AND Alias = :alias";

       dwError = sqlite3_prepare_v2(
                           pDbContext->pDb,
                           szQuery,
                           -1,
                           &pDbContext->pQueryTypeByAlias,
                           NULL);
       BAIL_ON_VECS_ERROR(dwError);
    }

    pDbQuery = pDbContext->pQueryTypeByAlias;

    dwError = VecsBindDword(
                   pDbQuery,
                   ":storeid",
                   dwStoreId
                   );
    BAIL_ON_VECS_ERROR(dwError);

    dwError = VecsBindWideString(
                   pDbQuery,
                   ":alias",
                   pszAliasName
                   );
    BAIL_ON_VECS_ERROR(dwError);

    dwError = VecsDbStepSql(pDbQuery);
    if (dwError == SQLITE_ROW)
    {
              dwError =  VecsDBGetColumnInt(
                          pDbQuery,
                          "EntryType",
                          &entryType
                          );
              BAIL_ON_VECS_ERROR(dwError);

    }
    else if (dwError == SQLITE_DONE)
    {
       dwError = ERROR_OBJECT_NOT_FOUND;
    }
    BAIL_ON_VECS_ERROR(dwError);

    if (entryType == CERT_ENTRY_TYPE_UNKNOWN)
    {
       dwError = ERROR_OBJECT_NOT_FOUND;
       BAIL_ON_VECS_ERROR (dwError);
    }

    *pEntryType = entryType;

cleanup:
    if (pDbQuery)
    {
       sqlite3_reset(pDbQuery);
    }
    if (pDbContext)
    {
        VecsDbReleaseContext (pDbContext);
    }

    return dwError;

error:
    if (pEntryType)
    {
        *pEntryType = CERT_ENTRY_TYPE_UNKNOWN;
    }

    goto cleanup;
}

DWORD
VecsDbGetEntryDateByAlias(
    DWORD dwStoreId,
    PWSTR pszAliasName,
    PDWORD pdwDate
    )
{
    DWORD dwError = 0;
    PVECS_DB_CONTEXT pDbContext = NULL;
    sqlite3_stmt* pDbQuery = NULL;
    DWORD dwDate = 0;

    if (IsNullOrEmptyString(pszAliasName) ||
        !pdwDate
       )
    {
       dwError = ERROR_INVALID_PARAMETER;
       BAIL_ON_VECS_ERROR(dwError);
    }

    dwError = VecsDbCreateContext(&pDbContext);
    BAIL_ON_VECS_ERROR(dwError);

    if(!pDbContext->pQueryDateByAlias)
    {
       CHAR szQuery[] =
                       "SELECT  Date"
                       " FROM CertTable"
                       " WHERE StoreID = :storeid"
                       " AND Alias = :alias";

       dwError = sqlite3_prepare_v2(
                           pDbContext->pDb,
                           szQuery,
                           -1,
                           &pDbContext->pQueryDateByAlias,
                           NULL);
       BAIL_ON_VECS_ERROR(dwError);
    }

    pDbQuery = pDbContext->pQueryDateByAlias;

    dwError = VecsBindDword(
                   pDbQuery,
                   ":storeid",
                   dwStoreId
                   );
    BAIL_ON_VECS_ERROR(dwError);

    dwError = VecsBindWideString(
                   pDbQuery,
                   ":alias",
                   pszAliasName
                   );
    BAIL_ON_VECS_ERROR(dwError);

    dwError = VecsDbStepSql(pDbQuery);
    if (dwError == SQLITE_ROW)
    {
              dwError = VecsDBGetColumnInt(
                              pDbQuery,
                              "Date",
                              &dwDate
                              );
              BAIL_ON_VECS_ERROR (dwError);

    }
    else if (dwError == SQLITE_DONE)
    {
       dwError = ERROR_OBJECT_NOT_FOUND;
    }
    BAIL_ON_VECS_ERROR(dwError);

    if (dwDate == 0)
    {
       dwError = ERROR_OBJECT_NOT_FOUND;
       BAIL_ON_VECS_ERROR (dwError);
    }

    *pdwDate = dwDate;

cleanup:
    if (pDbQuery)
    {
       sqlite3_reset(pDbQuery);
    }
    if (pDbContext)
    {
        VecsDbReleaseContext (pDbContext);
    }

    return dwError;

error:
    if (pdwDate)
    {
        *pdwDate = 0;
    }

    goto cleanup;
}

DWORD
VecsDbGetCertificateByAlias(
    DWORD dwStoreId,
    PWSTR pszAliasName,
    PWSTR *ppszCertificate
    )
{
    DWORD dwError = 0;
    PVECS_DB_CONTEXT pDbContext = NULL;
    sqlite3_stmt* pDbQuery = NULL;
    PBYTE pCertBlob = NULL;
    DWORD dwCertSize = 0;

    if (IsNullOrEmptyString(pszAliasName) ||
        !ppszCertificate)
    {
       dwError = ERROR_INVALID_PARAMETER;
       BAIL_ON_VECS_ERROR(dwError);
    }

    dwError = VecsDbCreateContext(&pDbContext);
    BAIL_ON_VECS_ERROR(dwError);

    if(!pDbContext->pGetCertFromAliasQuery)
    {
       CHAR szQuery[] =
                       "SELECT  CertBlob"
                       " FROM CertTable"
                       " WHERE StoreID = :storeid"
                       " AND Alias = :alias";

       dwError = sqlite3_prepare_v2(
                           pDbContext->pDb,
                           szQuery,
                           -1,
                           &pDbContext->pGetCertFromAliasQuery,
                           NULL);
       BAIL_ON_VECS_ERROR(dwError);
    }

    pDbQuery = pDbContext->pGetCertFromAliasQuery;

    dwError = VecsBindDword(
                   pDbQuery,
                   ":storeid",
                   dwStoreId
                   );
    BAIL_ON_VECS_ERROR(dwError);

    dwError = VecsBindWideString(
                   pDbQuery,
                   ":alias",
                   pszAliasName
                   );
    BAIL_ON_VECS_ERROR(dwError);

    dwError = VecsDbStepSql(pDbQuery);
    if (dwError == SQLITE_ROW)
    {
              dwError =  VecsDBGetColumnBlob(
                          pDbQuery,
                          "CertBlob",
                          &pCertBlob,
                          &dwCertSize);
              BAIL_ON_VECS_ERROR(dwError);

              if (dwCertSize == 0)
              {
                dwError = ERROR_OBJECT_NOT_FOUND;
                BAIL_ON_VECS_ERROR (dwError);
              }

    }
    else if (dwError == SQLITE_DONE)
    {
       dwError = ERROR_OBJECT_NOT_FOUND;
    }
    BAIL_ON_VECS_ERROR(dwError);

    if (pCertBlob == NULL)
    {
       dwError = ERROR_OBJECT_NOT_FOUND;
       BAIL_ON_VECS_ERROR (dwError);
    }

    dwError = VmAfdAllocateStringW((PWSTR)pCertBlob, ppszCertificate);
    BAIL_ON_VECS_ERROR (dwError);

cleanup:

    if (pDbQuery)
    {
       sqlite3_reset(pDbQuery);
    }
    VMAFD_SAFE_FREE_MEMORY (pCertBlob);
    if (pDbContext)
    {
        VecsDbReleaseContext (pDbContext);
    }

    return dwError;

error:
    if (ppszCertificate)
    {
      *ppszCertificate = NULL;
    }

    goto cleanup;
}

DWORD
VecsDbGetPrivateKeyByAlias(
    DWORD dwStoreId,
    PWSTR pszAliasName,
    PWSTR pszPassword,
    PWSTR *ppszPrivateKey
    )
{
    DWORD dwError = 0;
    PVECS_DB_CONTEXT pDbContext = NULL;
    sqlite3_stmt* pDbQuery = NULL;
    PBYTE pPrivateKeyBlob = NULL;
    DWORD dwPrivateKeySize = 0;

    if (IsNullOrEmptyString(pszAliasName) ||
        !ppszPrivateKey)
    {
       dwError = ERROR_INVALID_PARAMETER;
       BAIL_ON_VECS_ERROR(dwError);
    }

    dwError = VecsDbCreateContext(&pDbContext);
    BAIL_ON_VECS_ERROR(dwError);

    if(!pDbContext->pGetPKeyFromAlias)
    {
       CHAR szQuery[] =
                       "SELECT  PrivateKey"
                       " FROM CertTable"
                       " WHERE StoreID = :storeid"
                       " AND Alias = :alias";

       dwError = sqlite3_prepare_v2(
                           pDbContext->pDb,
                           szQuery,
                           -1,
                           &pDbContext->pGetPKeyFromAlias,
                           NULL);
       BAIL_ON_VECS_ERROR(dwError);
    }

    pDbQuery = pDbContext->pGetPKeyFromAlias;

    dwError = VecsBindDword(
                   pDbQuery,
                   ":storeid",
                   dwStoreId
                   );
    BAIL_ON_VECS_ERROR(dwError);

    dwError = VecsBindWideString(
                   pDbQuery,
                   ":alias",
                   pszAliasName
                   );
    BAIL_ON_VECS_ERROR(dwError);

    dwError = VecsDbStepSql(pDbQuery);
    if (dwError == SQLITE_ROW)
    {
              dwError =  VecsDBGetColumnBlob(
                          pDbQuery,
                          "PrivateKey",
                          &pPrivateKeyBlob,
                          &dwPrivateKeySize
                          );
              BAIL_ON_VECS_ERROR(dwError);

              if (dwPrivateKeySize == 0)
              {
                  dwError = ERROR_OBJECT_NOT_FOUND;
                  BAIL_ON_VECS_ERROR (dwError);
              }

    }
    else if (dwError == SQLITE_DONE)
    {
       dwError = ERROR_OBJECT_NOT_FOUND;
    }
    BAIL_ON_VECS_ERROR(dwError);

    if (pPrivateKeyBlob == NULL)
    {
      dwError = ERROR_OBJECT_NOT_FOUND;
      BAIL_ON_VECS_ERROR (dwError);
    }

    dwError = VmAfdAllocateStringW((PWSTR)pPrivateKeyBlob, ppszPrivateKey);
    BAIL_ON_VECS_ERROR (dwError);

cleanup:

    if (pDbQuery)
    {
       sqlite3_reset(pDbQuery);
    }
    VMAFD_SAFE_FREE_MEMORY (pPrivateKeyBlob);
    if (pDbContext)
    {
        VecsDbReleaseContext(pDbContext);
    }

    return dwError;

error:
    if (ppszPrivateKey)
    {
      *ppszPrivateKey = NULL;
    }

    goto cleanup;
}

DWORD
VecsDbGetEntriesCount(
    DWORD dwStoreId,
    PDWORD pdwSize
    )
{
    DWORD dwError = 0;
    PVECS_DB_CONTEXT pDbContext = NULL;
    sqlite3_stmt* pDbQuery = NULL;
    DWORD dwCertsReturned = 0;

    dwError = VecsDbCreateContext(&pDbContext);
    BAIL_ON_VECS_ERROR(dwError);

    if(!pDbContext->pQueryCertificatesPaged)
    {
         CHAR szQuery[] = "SELECT COUNT(*)"
                                 " FROM CertTable"
                                 " WHERE StoreID = :storeid";

          dwError = sqlite3_prepare_v2(
                pDbContext->pDb,
                szQuery,
                -1,
                &pDbContext->pQueryCertificatesPaged,
                NULL);
          BAIL_ON_VECS_ERROR(dwError);
    }

    pDbQuery = pDbContext->pQueryCertificatesPaged;

    dwError = VecsBindDword(
                   pDbQuery,
                   ":storeid",
                   dwStoreId
                   );
    BAIL_ON_VECS_ERROR(dwError);

    dwError = VecsDbStepSql(pDbQuery);

    if (dwError == SQLITE_ROW)
    {
        dwCertsReturned = sqlite3_column_int(pDbQuery, 0);
        dwError = 0;
    }
    BAIL_ON_VECS_ERROR (dwError);

    *pdwSize = dwCertsReturned;
cleanup:

    if (pDbQuery)
    {
       sqlite3_reset(pDbQuery);
    }
    if (pDbContext)
    {
        VecsDbReleaseContext(pDbContext);
    }

    return dwError;

error:
    if (pdwSize)
    {
        *pdwSize = 0;
    }

    goto cleanup;
}

DWORD
VecsDbEnumInfoLevel1(
    DWORD dwStoreId,
    DWORD dwIndex,
    DWORD dwLimit,
    PVMAFD_CERT_ARRAY *ppCertContainer
    )
{
    DWORD dwError = 0;
    DWORD dwDbStatus = 0;
    PVECS_DB_CONTEXT pDbContext = NULL;
    sqlite3_stmt* pDbQuery = NULL;
    DWORD dwCertsReturned = 0;
    PVMAFD_CERT_ARRAY pCertContainer = NULL;
    PVMAFD_CERT_CONTAINER pContainer = NULL;

    dwError = VecsDbCreateContext(&pDbContext);
    BAIL_ON_VECS_ERROR(dwError);

    if(!pDbContext->pQueryInfoLevel1)
    {
         CHAR szQuery[] = "SELECT "
                                 " ID,"
                                 " Alias,"
                                 " EntryType,"
                                 " Date"
                                 " FROM CertTable"
                                 " WHERE StoreID = :storeid"
                                 " ORDER BY ID"
                                 " LIMIT :count OFFSET :skip";

          dwError = sqlite3_prepare_v2(
                pDbContext->pDb,
                szQuery,
                -1,
                &pDbContext->pQueryInfoLevel1,
                NULL);
          BAIL_ON_VECS_ERROR(dwError);
     }

    pDbQuery = pDbContext->pQueryInfoLevel1;

    if (!pDbContext->bInTx)
    {
       dwError = VecsDbBeginTransaction(pDbContext->pDb);
       BAIL_ON_VECS_ERROR(dwError);

       pDbContext->bInTx = TRUE;
    }

    dwError = VecsBindDword(
                   pDbQuery,
                   ":storeid",
                   dwStoreId
                   );
    BAIL_ON_VECS_ERROR(dwError);

    dwError = VecsBindDword(
                   pDbQuery,
                   ":count",
                   dwLimit
                   );
    BAIL_ON_VECS_ERROR(dwError);

    dwError = VecsBindDword(
                   pDbQuery,
                   ":skip",
                   dwIndex
                   );
    BAIL_ON_VECS_ERROR(dwError);

    dwError = VecsAllocateMemory(
                    sizeof(VMAFD_CERT_CONTAINER)*dwLimit,
                    (PVOID *)&pContainer
                    );
    BAIL_ON_VECS_ERROR(dwError);

    do
    {
        dwDbStatus = VecsDbStepSql(pDbQuery);

        if (dwDbStatus == SQLITE_ROW)
        {
              dwError = VecsDBGetColumnString(
                          pDbQuery,
                          "Alias",
                          &(pContainer[dwCertsReturned].pAlias));
              BAIL_ON_VECS_ERROR(dwError);

              dwError = VecsDBGetColumnInt(
                            pDbQuery,
                            "EntryType",
                            &(pContainer[dwCertsReturned].dwStoreType));
              BAIL_ON_VECS_ERROR (dwError);

              dwError = VecsDBGetColumnInt (
                            pDbQuery,
                            "Date",
                            &(pContainer[dwCertsReturned].dwDate));
              BAIL_ON_VECS_ERROR (dwError);

              dwCertsReturned++;
        }
        else if (dwDbStatus != SQLITE_DONE)
        {
            dwError = dwDbStatus;
            BAIL_ON_VECS_ERROR(dwError);
        }
    } while (dwDbStatus == SQLITE_ROW);

    dwError = VecsDbCommitTransaction(pDbContext->pDb);
    BAIL_ON_VECS_ERROR(dwError);

    pDbContext->bInTx = FALSE;

    dwError = VecsAllocateMemory(
                    sizeof(VMAFD_CERT_ARRAY),
                    (PVOID *) &pCertContainer);
    BAIL_ON_VECS_ERROR (dwError);

    pCertContainer->dwCount = dwCertsReturned;
    pCertContainer->certificates = pContainer;

    *ppCertContainer = pCertContainer;

cleanup:

    if (pDbQuery)
    {
       sqlite3_reset(pDbQuery);
    }
    if (pDbContext)
    {
        VecsDbReleaseContext(pDbContext);
    }

    return dwError;

error:

    if (pDbContext && pDbContext->bInTx)
    {
       VecsDbRollbackTransaction(pDbContext->pDb);
       pDbContext->bInTx = FALSE;
    }
    if (ppCertContainer)
    {
        *ppCertContainer = NULL;
    }
    if (pCertContainer)
    {
        VMAFD_SAFE_FREE_MEMORY(pCertContainer);
    }
    if (pContainer)
    {
        VecsSrvFreeCertContainer(pContainer,dwCertsReturned);
    }

    goto cleanup;
}

DWORD
VecsDbEnumInfoLevel2(
    DWORD dwStoreId,
    DWORD dwIndex,
    DWORD dwLimit,
    PVMAFD_CERT_ARRAY *ppCertContainer
    )
{
    DWORD dwError = 0;
    DWORD dwDbStatus = 0;
    PVECS_DB_CONTEXT pDbContext = NULL;
    sqlite3_stmt* pDbQuery = NULL;
    DWORD dwCertsReturned = 0;
    PVMAFD_CERT_ARRAY pCertContainer = NULL;
    PVMAFD_CERT_CONTAINER pContainer = NULL;
    PBYTE pCertBlob = NULL;
    DWORD dwCertSize = 0;

    dwError = VecsDbCreateContext(&pDbContext);
    BAIL_ON_VECS_ERROR(dwError);

    if(!pDbContext->pQueryInfoLevel2)
    {
         CHAR szQuery[] = "SELECT "
                                 " ID,"
                                 " Alias,"
                                 " CertBlob,"
                                 " EntryType,"
                                 " AutoRefresh,"
                                 " Date"
                                 " FROM CertTable"
                                 " WHERE StoreID = :storeid"
                                 " ORDER BY ID"
                                 " LIMIT :count OFFSET :skip";

          dwError = sqlite3_prepare_v2(
                pDbContext->pDb,
                szQuery,
                -1,
                &pDbContext->pQueryInfoLevel2,
                NULL);
          BAIL_ON_VECS_ERROR(dwError);
      }

    pDbQuery = pDbContext->pQueryInfoLevel2;

    if (!pDbContext->bInTx)
    {
       dwError = VecsDbBeginTransaction(pDbContext->pDb);
       BAIL_ON_VECS_ERROR(dwError);

       pDbContext->bInTx = TRUE;
    }

    dwError = VecsBindDword(
                   pDbQuery,
                   ":storeid",
                   dwStoreId
                   );
    BAIL_ON_VECS_ERROR(dwError);

    dwError = VecsBindDword(
                   pDbQuery,
                   ":count",
                   dwLimit
                   );
    BAIL_ON_VECS_ERROR(dwError);

    dwError = VecsBindDword(
                   pDbQuery,
                   ":skip",
                   dwIndex
                   );
    BAIL_ON_VECS_ERROR(dwError);

    dwError = VecsAllocateMemory(
                    sizeof(VMAFD_CERT_CONTAINER)*dwLimit,
                    (PVOID *)&pContainer
                    );
    BAIL_ON_VECS_ERROR(dwError);

    do
    {
        dwDbStatus = VecsDbStepSql(pDbQuery);

        if (dwDbStatus == SQLITE_ROW)
        {
              dwError =  VecsDBGetColumnBlob(
                          pDbQuery,
                          "CertBlob",
                          &pCertBlob,
                          &dwCertSize);
              BAIL_ON_VECS_ERROR (dwError);

              if (pCertBlob)
              {

                  dwError = VmAfdAllocateStringW(
                              (PWSTR)pCertBlob,
                              &(pContainer[dwCertsReturned].pCert)
                              );
                  BAIL_ON_VECS_ERROR (dwError);
              }

              VMAFD_SAFE_FREE_MEMORY (pCertBlob);

              dwError = VecsDBGetColumnString(
                          pDbQuery,
                          "Alias",
                          &(pContainer[dwCertsReturned].pAlias));
              BAIL_ON_VECS_ERROR(dwError);

              dwError = VecsDBGetColumnInt(
                            pDbQuery,
                            "EntryType",
                            &(pContainer[dwCertsReturned].dwStoreType));
              BAIL_ON_VECS_ERROR (dwError);

              dwError = VecsDBGetColumnInt(
                            pDbQuery,
                            "AutoRefresh",
                            &(pContainer[dwCertsReturned].dwAutoRefresh));
              BAIL_ON_VECS_ERROR (dwError);

              dwError = VecsDBGetColumnInt (
                            pDbQuery,
                            "Date",
                            &(pContainer[dwCertsReturned].dwDate));
              BAIL_ON_VECS_ERROR (dwError);

              dwCertsReturned++;
        }
        else if (dwDbStatus != SQLITE_DONE)
        {
            dwError = dwDbStatus;
            BAIL_ON_VECS_ERROR(dwError);
        }
    } while (dwDbStatus == SQLITE_ROW);

    dwError = VecsDbCommitTransaction(pDbContext->pDb);
    BAIL_ON_VECS_ERROR(dwError);

    pDbContext->bInTx = FALSE;

    dwError = VecsAllocateMemory(
                    sizeof(VMAFD_CERT_ARRAY),
                    (PVOID *) &pCertContainer);
    BAIL_ON_VECS_ERROR (dwError);

    pCertContainer->dwCount = dwCertsReturned;
    pCertContainer->certificates = pContainer;

    *ppCertContainer = pCertContainer;

cleanup:

    if (pDbQuery)
    {
       sqlite3_reset(pDbQuery);
    }
    if (pDbContext)
    {
        VecsDbReleaseContext (pDbContext);
    }

    return dwError;

error:

    if (pDbContext && pDbContext->bInTx)
    {
       VecsDbRollbackTransaction(pDbContext->pDb);
       pDbContext->bInTx = FALSE;
    }
    if (ppCertContainer)
    {
        *ppCertContainer = NULL;
    }
    if (pCertContainer)
    {
        VMAFD_SAFE_FREE_MEMORY(pCertContainer);
    }
    if (pContainer)
    {
        VecsSrvFreeCertContainer(pContainer,dwCertsReturned);
    }
    VMAFD_SAFE_FREE_MEMORY (pCertBlob);

    goto cleanup;
}

DWORD
VecsDbDeleteCert(
    DWORD dwStoreId,
    PWSTR pszAliasName
    )
{
    DWORD dwError = 0;
    DWORD dwDbStatus = 0;
    PVECS_DB_CONTEXT pDbContext = NULL;
    sqlite3_stmt* pDbQuery = NULL;

    if (IsNullOrEmptyString(pszAliasName))
    {
        dwError = ERROR_INVALID_PARAMETER;
        BAIL_ON_VECS_ERROR (dwError);
    }

    dwError = VecsDbCreateContext(&pDbContext);
    BAIL_ON_VECS_ERROR(dwError);

    if(!pDbContext->pDelCertQuery)
    {
         CHAR szQuery[] = "DELETE"
                                 " FROM"
                                 " CertTable"
                                 " WHERE StoreID = :storeid"
                                 " AND Alias = :alias;";

          dwError = sqlite3_prepare_v2(
                pDbContext->pDb,
                szQuery,
                -1,
                &pDbContext->pDelCertQuery,
                NULL);
          BAIL_ON_VECS_ERROR(dwError);
      }

    pDbQuery = pDbContext->pDelCertQuery;

    if (!pDbContext->bInTx)
    {
       dwError = VecsDbBeginTransaction(pDbContext->pDb);
       BAIL_ON_VECS_ERROR(dwError);

       pDbContext->bInTx = TRUE;
    }

    dwError = VecsBindDword(
                   pDbQuery,
                   ":storeid",
                   dwStoreId
                   );
    BAIL_ON_VECS_ERROR(dwError);

    dwError = VecsBindWideString(
                   pDbQuery,
                   ":alias",
                   pszAliasName
                   );
    BAIL_ON_VECS_ERROR(dwError);

    dwDbStatus = VecsDbStepSql(pDbQuery);
    BAIL_ON_VECS_ERROR (dwDbStatus);

    dwError = VecsDbCommitTransaction(pDbContext->pDb);
    BAIL_ON_VECS_ERROR(dwError);

    pDbContext->bInTx = FALSE;

cleanup:

    if (pDbQuery)
    {
       sqlite3_reset(pDbQuery);
    }
    if (pDbContext)
    {
        VecsDbReleaseContext (pDbContext);
    }

    return dwError;

error:

    if (pDbContext && pDbContext->bInTx)
    {
       VecsDbRollbackTransaction(pDbContext->pDb);
       pDbContext->bInTx = FALSE;
    }

    goto cleanup;
}

DWORD
VecsDbSetEntryDwordAttributeByAlias(
    DWORD dwStoreId,
    PWSTR pszAliasName,
    PSTR  pszAttributeName,
    DWORD dwValue
    )
{
    DWORD dwError = 0;
    PVECS_DB_CONTEXT pDbContext = NULL;
    sqlite3_stmt* pDbQuery = NULL;
    PSTR pszQuery = NULL;

    if (IsNullOrEmptyString(pszAliasName)
        || IsNullOrEmptyString(pszAttributeName))
    {
       dwError = ERROR_INVALID_PARAMETER;
       BAIL_ON_VECS_ERROR(dwError);
    }

    dwError = VecsDbCreateContext(&pDbContext);
    BAIL_ON_VECS_ERROR(dwError);

    if(!pDbContext->pUpdateCertAttrQuery)
    {
       CHAR szQuery[] =
                       "UPDATE CertTable"
                       " SET %s = :value"
                       " WHERE StoreID = :storeid"
                       " AND Alias = :alias";
       dwError = VmAfdAllocateStringPrintf(
           &pszQuery, szQuery, pszAttributeName);
       BAIL_ON_VECS_ERROR(dwError);

       dwError = sqlite3_prepare_v2(
                           pDbContext->pDb,
                           pszQuery,
                           -1,
                           &pDbContext->pUpdateCertAttrQuery,
                           NULL);
       BAIL_ON_VECS_ERROR(dwError);
    }

    pDbQuery = pDbContext->pUpdateCertAttrQuery;

    dwError = VecsBindDword(
                   pDbQuery,
                   ":storeid",
                   dwStoreId
                   );
    BAIL_ON_VECS_ERROR(dwError);

    dwError = VecsBindWideString(
                   pDbQuery,
                   ":alias",
                   pszAliasName
                   );
    BAIL_ON_VECS_ERROR(dwError);

    dwError = VecsBindDword(
                   pDbQuery,
                   ":value",
                   dwValue
                   );
    BAIL_ON_VECS_ERROR(dwError);

    dwError = VecsDbStepSql(pDbQuery);
    BAIL_ON_VECS_ERROR(dwError);

cleanup:
    VMAFD_SAFE_FREE_STRINGA(pszQuery);
    if (pDbQuery)
    {
       sqlite3_reset(pDbQuery);
    }
    if (pDbContext)
    {
        VecsDbReleaseContext (pDbContext);
    }

    return dwError;

error:
    goto cleanup;
}

static
VOID
VecsSrvFreeCertContainer(
    PVMAFD_CERT_CONTAINER pContainer,
    DWORD dwArraySize
    )
{
    if (pContainer)
    {
        DWORD dwIndex = 0;
        for (;dwIndex<dwArraySize; dwIndex++)
        {
            PVMAFD_CERT_CONTAINER pTemp = &pContainer[dwIndex];
            VMAFD_SAFE_FREE_MEMORY(pTemp->pCert);
            VMAFD_SAFE_FREE_MEMORY(pTemp->pAlias);
            VMAFD_SAFE_FREE_MEMORY(pTemp->pPassword);
            VMAFD_SAFE_FREE_MEMORY(pTemp->pPrivateKey);
        }
        VmAfdFreeMemory (pContainer);
    }
}

static
DWORD
VecsDbGetStoreCount(
    PVECS_DB_CONTEXT pDbContext,
    PDWORD pdwStoreCount
    )
{
    DWORD dwError = 0;
    sqlite3_stmt* pDbQuery = NULL;
    DWORD dwStoreCount = 0;

    char szQuery[] = "SELECT COUNT(*)"
                     " FROM StoreTable";

    if (!pDbContext || !pdwStoreCount)
    {
        dwError = ERROR_INVALID_PARAMETER;
        BAIL_ON_VECS_ERROR (dwError);
    }

    dwError = sqlite3_prepare_v2(
                pDbContext->pDb,
                szQuery,
                -1,
                &pDbQuery,
                NULL);
    BAIL_ON_VECS_ERROR(dwError);

    dwError = VecsDbStepSql(pDbQuery);
    if (dwError == SQLITE_ROW)
    {
        dwError = 0;
        dwStoreCount = sqlite3_column_int(pDbQuery, 0);
    }
    BAIL_ON_VECS_ERROR (dwError);

    *pdwStoreCount = dwStoreCount;
cleanup:
    if (pDbQuery)
    {
      sqlite3_finalize (pDbQuery);
    }

    return dwError;
error:
    if (pdwStoreCount)
    {
        *pdwStoreCount = 0;
    }

    goto cleanup;
}

static
BOOL
VecsDbIsRestrictedStore (
    PCWSTR pszStoreName
    )
{
    BOOL bIsRestricted = FALSE;
    WCHAR wszSystemStoreName[] = SYSTEM_CERT_STORE_NAME_W;
    WCHAR wszTrustedRootsStoreName[] = TRUSTED_ROOTS_STORE_NAME_W;
    WCHAR wszCRLStoreName[] = CRL_STORE_NAME_W;

    if (VmAfdStringIsEqualW(
                  pszStoreName,
                  &wszSystemStoreName[0],
                  0
                  )
       )
    {
        bIsRestricted = TRUE;
    }

    else if (VmAfdStringIsEqualW (
                            pszStoreName,
                            &wszTrustedRootsStoreName[0],
                            0
                            )
              )
    {
        bIsRestricted = TRUE;
    }

    else if (VmAfdStringIsEqualW(
                            pszStoreName,
                            &wszCRLStoreName[0],
                            0
                            )
            )
    {
        bIsRestricted = TRUE;
    }

    return bIsRestricted;
}


text:
<!DOCTYPE HTML>

<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>${content_ext.title} - ${site.site_name}</title>
<meta content="${content_tag}" http-equiv="keywords" />
<meta content="${content_ext.description!}" http-equiv="description" />

<link href="${baseRes!}/css/html5.css" rel="stylesheet" type="text/css"/>

[#include "../include/页头顶栏.html"]
[#include "../include/标志和搜索.html"]

当前位置:首页 >
             [#list channelList as n]${n.name}[#if n_has_next] > [/#if][/#list] > 正文

${content_ext.title}

发布时间: ${content_ext.pub_time}   作者:${content_ext.author!'本站编辑'}   来源: ${content_ext.origin!'本站原创'}

            [#if pagination.firstPage]
            [#if content_ext.description??]

摘要: [@text_cut s=content_ext.description len='60' append='...'/]

            [/#if]
			[/#if]

			[#if content_ext.title_img??]

			[/#if]

			[#if content_ext.media_path?? && content_ext.media_type??]

[#if content_ext.media_type=='FLV'] <object height="400" width="600" codebase="http://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=7,0,19,0" classid="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000">
            <param name="movie" value="${baseRes!}/img/flvplayer.swf" />
            <param name="quality" value="high" />
            <param name="allowFullScreen" value="true" />
            <param name="FlashVars" value="vcastr_file=${content_ext.media_path!}&BufferTime=3" /><embed height="400" width="600" type="application/x-shockwave-flash" pluginspage="http://www.macromedia.com/go/getflashplayer" quality="high" flashvars="vcastr_file=${content_ext.media_path!}" allowfullscreen="true" src="${baseRes!}/img/flvplayer.swf"></embed></object>[#elseif content_ext.media_type=='FLASH'] <embed height="400" width="600" type="application/x-shockwave-flash" quality="high" src="${content_ext.media_path}" wmode="transparent" align="center"></embed>[#else] <embed height="400" width="600" type="video/x-ms-wmv" src="${content_ext.media_path}" console="cons" controls="ImageWindow" autostart="true"></embed>[/#if]

            [/#if]

${txt!}

[#include "../style_page/content.html"/]

			[#if (fileList?size>0)]

附件:

				[#list fileList as f]

				${f.filename!}

				[/#list]

			[/#if]
			[#--

上一篇:[@cms_content id=content.content_id next='1' channelId=content.channel_id][#if tag_bean??]${tag_bean.title}[#else]没有了[/#if][/@cms_content]

下一篇:[@cms_content id=content.content_id next='0' channelId=content.channel_id][#if tag_bean??]${tag_bean.title}[#else]没有了[/#if][/@cms_content]

			--]

	[#include "../include/页脚信息栏.html"/]

redpajama_set_name: RedPajamaGithub


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

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

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

package edu.berkeley.ground.api.models;

import com.fasterxml.jackson.databind.ObjectMapper;

import edu.berkeley.ground.api.versions.GroundType;
import io.dropwizard.jackson.Jackson;

import org.junit.Test;

import java.util.HashMap;
import java.util.Map;

import static io.dropwizard.testing.FixtureHelpers.fixture;
import static org.assertj.core.api.Assertions.assertThat;
import static org.junit.Assert.*;

public class StructureTest {
  private static final ObjectMapper MAPPER = Jackson.newObjectMapper();

  @Test
  public void serializesToJSON() throws Exception {
    Map<String, Tag> tagsMap = new HashMap<>();
    tagsMap.put("testtag", new Tag(1, "testtag", "tag", GroundType.STRING));

    Structure structure = new Structure(1, "test", tagsMap);
    final String expected = MAPPER.writeValueAsString(MAPPER.readValue(fixture("fixtures/models/structure.json"), Structure.class));

    assertThat(MAPPER.writeValueAsString(structure)).isEqualTo(expected);
  }

  @Test
  public void deserializesFromJSON() throws Exception {
    Map<String, Tag> tagsMap = new HashMap<>();
    tagsMap.put("testtag", new Tag(1, "testtag", "tag", GroundType.STRING));

    Structure structure = new Structure(1, "test", tagsMap);
    assertEquals(MAPPER.readValue(fixture("fixtures/models/structure.json"), Structure.class), structure);
  }
}


text:
package hoverctl_end_to_end

import (
	"github.com/SpectoLabs/hoverfly/functional-tests"
	. "github.com/onsi/ginkgo"
	. "github.com/onsi/gomega"
)

var _ = Describe("When I import with hoverctl", func() {

	Context("without providing a path to write to", func() {

		It("it should fail nicely", func() {
			output := functional_tests.Run(hoverctlBinary, "import")

			Expect(output).To(ContainSubstring("You have not provided a path to simulation"))
			Expect(output).To(ContainSubstring("Try hoverctl import --help for more information"))
		})
	})
})


text:
django-admin-tweaks
===================

Django admin tweaks such as thumbnails in list display and foreign key filtering links.

Current features:

* show a thumbnail of a django image field in the admin list view.
* show a color swatch of a char field hexidecimal ("#FF0000") or preset ("red") in list view.

## Installation

Either install directly:
`pip install git+https://github.com/RRMoelker/django-admin-tweaks.git#egg=admin_tweaks`

Or add the following line to your requirements file:
`-e git+https://github.com/RRMoelker/django-admin-tweaks.git#egg=admin_tweaks`

## Usage

1. Add `admin_tweaks` to your `INSTALLED_APPS`

2. Import `admin_tweaks.admin import ListTweakAdmin`
3. Let your modeladmin inherit from `ListTweakAdmin` instead of `admin.ModelAdmin`

### Thumbnail of image field
Creation of a thumbnail preview of an image field for each model. Thumbnailing is done using easy-thumbnails.

1. Add the model image field name to the `list_tweaks_icon` field, e.g.: `list_tweaks_icon = ['icon', ]`
2. Add 'admin_preview' thumnail alias to easythumnails aliases. e.g.:
```
THUMBNAIL_ALIASES = {
	'': {
		'admin_preview':		{'size': (50, 50), 		'crop': True},
	},
}
```

### Color swatch of char field
Showing a css color value directly in the list display for each model.

1. Add the character field name to the `list_tweaks_color` field, e.g.: `list_tweaks_color = ['color', ]`. An value for this field is `FF0000` or `red`.
2. Define the 'admin-tweaks-swatch' class in your admin pages css file, e.g.:
```
.admin-tweaks-swatch {
	width: 50px;
	height: 50px;
}
```

## Requirements
Django
django.contrib.admin
easy-thumbnails


text:
<TITLE>Review for Death of a Salesman (1985) (TV)</TITLE>
<LINK REL="STYLESHEET" TYPE="text/css" HREF="/ramr.css">

Death of a Salesman (1985) (TV)

reviewed by
Brian Koller

Death of a Salesman (1985)

Grade: 62

"Death of a Salesman" may be the Great American
Tragedy.  No matter how many other successful plays
Arthur Miller may have had, he will always be
remembered for bringing Willy Loman to life.
In 1984, Dustin Hoffman was cast as Willy in a
Broadway revival.  Most of the cast was retained
for a broadcast television production.  Volker
Schlondorff, whose entire previous career was
spent in Germany and France, became the director.

The story is depressing and even disturbing, as
it has the effect of challenging the viewer to
consider the value of his or her own life.  Willy
has spent his adult life as a struggling salesman,
and has lived under the delusion that he and his
family were destined for success, even greatness.
His wife Linda (Kate Reid) knows the truth, but
participates in his husband's delusions since
dreams are all that he has left.

But now Willy's dreams are shattered.  Prematurely
senile, he is fired from his longtime job and lives
on handouts from his old friend Charley (Charles
Durning).  Son Biff (John Malkovich) is jobless
and a kleptomaniac.  Son Happy (Stephen Lang) is
a cynical womanizer.  A broken man, Willy is
considering suicide.  As the story unfolds, it is
finally made clear why Biff has been such a failure,
with the blame seeping into Willy's life as well.

The play also ironically contrasts the parenting
skills of Willy and Charley.  Willy lives for his
two sons, and showers attention on them.  Charley
takes little interest in his nerdy son Bernard
(David S. Chandler), who nonetheless becomes an
important lawyer.

"Death of a Salesman" is not an enjoyable film
to watch.  The title gives away the ending, and
casts a gloomy pall over an already depressing
storyline.  If most folks live a life of quiet
desperation, Willy has graduated to the next
level.  While downbeat films have made great
cinema before (e.g. "The Lost Weekend"), it
doesn't happen here.

"Death of a Salesman" did well at the Golden Globes
(in the television movie category).  Hoffman won
Best Actor, while Malkovich and Reid were nominated
for their Supporting roles.  The film was also
nominated for Best Picture.  Hoffman and Malkovich
also won Emmy awards.

kollers@mpsi.net
http://members.tripod.com/~Brian_Koller/movies.html

The review above was posted to the
rec.arts.movies.reviews newsgroup (de.rec.film.kritiken for German reviews).

The Internet Movie Database accepts no responsibility for the contents of the
review and has no editorial control. Unless stated otherwise, the copyright
belongs to the author.

Please direct comments/criticisms of the review to relevant newsgroups.

Broken URLs inthe reviews are the responsibility of the author.

The formatting of the review is likely to differ from the original due
to ASCII to HTML conversion.

Related links: index of all rec.arts.movies.reviews reviews


text:
package org.kuali.rice.krms.impl.validation;

import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang.StringUtils;
import org.kuali.rice.core.api.exception.RiceIllegalArgumentException;
import org.kuali.rice.core.api.uif.RemotableAttributeField;
import org.kuali.rice.core.api.uif.RemotableRadioButtonGroup;
import org.kuali.rice.krms.api.repository.rule.RuleDefinition;
import org.kuali.rice.krms.api.repository.type.KrmsAttributeDefinition;
import org.kuali.rice.krms.api.repository.type.KrmsTypeAttribute;
import org.kuali.rice.krms.api.repository.type.KrmsTypeDefinition;
import org.kuali.rice.krms.api.repository.type.KrmsTypeRepositoryService;
import org.kuali.rice.krms.framework.engine.Rule;
import org.kuali.rice.krms.framework.type.ValidationActionType;
import org.kuali.rice.krms.framework.type.ValidationRuleType;
import org.kuali.rice.krms.framework.type.ValidationRuleTypeService;
import org.kuali.rice.krms.impl.provider.repository.RepositoryToEngineTranslator;
import org.kuali.rice.krms.impl.repository.KrmsRepositoryServiceLocator;
import org.kuali.rice.krms.impl.type.KrmsTypeServiceBase;

import javax.jws.WebParam;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;

/**
 * {@link ValidationRuleTypeService} implementation
 *
 * @author Kuali Rice Team (rice.collab@kuali.org)
 */
public final class ValidationRuleTypeServiceImpl extends KrmsTypeServiceBase implements ValidationRuleTypeService {

    private RepositoryToEngineTranslator translator;

    /**
     * private constructor to enforce use of static factory
     */
    private ValidationRuleTypeServiceImpl(){
        super();
    }

    /**
     * Factory method for getting a {@link ValidationRuleTypeService}
     * @return a {@link ValidationRuleTypeService} corresponding to the given {@link ValidationRuleType}.
     */
    public static ValidationRuleTypeService getInstance() {
        return new ValidationRuleTypeServiceImpl();
    }

    @Override
    public Rule loadRule(RuleDefinition validationRuleDefinition) {
        if (validationRuleDefinition == null) { throw new RiceIllegalArgumentException("validationRuleDefinition must not be null"); }
        if (validationRuleDefinition.getAttributes() == null) { throw new RiceIllegalArgumentException("validationRuleDefinition must not be null");}

        if (!validationRuleDefinition.getAttributes().containsKey(VALIDATIONS_RULE_TYPE_CODE_ATTRIBUTE)) {

            throw new RiceIllegalArgumentException("validationRuleDefinition does not contain an " +
                    VALIDATIONS_RULE_TYPE_CODE_ATTRIBUTE + " attribute");
        }
        String validationRuleTypeCode = validationRuleDefinition.getAttributes().get(VALIDATIONS_RULE_TYPE_CODE_ATTRIBUTE);

        if (StringUtils.isBlank(validationRuleTypeCode)) {
            throw new RiceIllegalArgumentException(VALIDATIONS_RULE_TYPE_CODE_ATTRIBUTE + " attribute must not be null or blank");
        }

        if (ValidationRuleType.VALID.getCode().equals(validationRuleTypeCode)) {
            return new ValidationRule(ValidationRuleType.VALID, validationRuleDefinition.getName(),
                    translator.translatePropositionDefinition(validationRuleDefinition.getProposition()),
                    translator.translateActionDefinitions(validationRuleDefinition.getActions()));
        }
        if (ValidationRuleType.INVALID.getCode().equals(validationRuleTypeCode)) {
            return new ValidationRule(ValidationRuleType.INVALID, validationRuleDefinition.getName(),
                    translator.translatePropositionDefinition(validationRuleDefinition.getProposition()),
                    translator.translateActionDefinitions(validationRuleDefinition.getActions()));
        }
        return null;
    }

    /**
     * @param translator the RepositoryToEngineTranslator to set
     */
    public void setRepositoryToEngineTranslator(RepositoryToEngineTranslator translator) {
        this.translator = translator;
    }

    /**
     *
     * @return List<RemotableAttributeField>
     * @throws RiceIllegalArgumentException
     */
    @Override
    public List<RemotableAttributeField> getAttributeFields(@WebParam(name = "krmsTypeId") String krmsTypeId) throws RiceIllegalArgumentException {
        Map<String, String> keyLabels = new TreeMap<String, String>();
        keyLabels.put(ValidationRuleType.VALID.getCode(), "Valid - action executed when false");
        keyLabels.put(ValidationRuleType.INVALID.getCode(), "Invalid - action executed when true");
        return getAttributeFields(krmsTypeId, keyLabels);
    }

    /**
     *
     * @param krmsTypeId
     * @param keyLabels Map<String, String> where the key is the VallidationRuleType code with the value being the UI Label.
     * @return List<RemotableAttributeField> for Validation Rules
     * @throws RiceIllegalArgumentException if krmsType is null (krmsTypeId lookup returns null)
     */
    private List<RemotableAttributeField> getAttributeFields(@WebParam(name = "krmsTypeId") String krmsTypeId, Map<String, String> keyLabels) throws RiceIllegalArgumentException {
        List<RemotableAttributeField> results = new ArrayList<RemotableAttributeField>();

        KrmsTypeDefinition krmsType =
                KrmsRepositoryServiceLocator.getKrmsTypeRepositoryService().getTypeById(krmsTypeId);

        if (krmsType == null) {
            throw new RiceIllegalArgumentException("krmsTypeId must be a valid id of a KRMS type");
        } else {
            List<KrmsTypeAttribute> typeAttributes = krmsType.getAttributes();
            Map<String, Integer> attribDefIdSequenceNumbers = new TreeMap<String, Integer>();
            Map<String, String> unsortedIdLables = new TreeMap<String, String>();
            if (!CollectionUtils.isEmpty(typeAttributes)) {
                // translate the attribute and store the sort code in our map
                KrmsTypeRepositoryService typeRepositoryService = KrmsRepositoryServiceLocator.getKrmsTypeRepositoryService();
                KrmsAttributeDefinition attributeDefinition = null;
                RadioButtonTypeServiceUtil util = new RadioButtonTypeServiceUtil();

                for (KrmsTypeAttribute typeAttribute : typeAttributes) {

                    attributeDefinition = typeRepositoryService.getAttributeDefinitionById(typeAttribute.getAttributeDefinitionId());

                    if (VALIDATIONS_RULE_TYPE_CODE_ATTRIBUTE.equals(attributeDefinition.getName())) {
                        RemotableAttributeField attributeField = util.translateTypeAttribute(attributeDefinition, keyLabels);
                        results.add(attributeField);
                    }
                }
            }
        }
        return results;
    }
}


text:
package com.all.core.common.services.reporting;

import static org.junit.Assert.*;
import static org.mockito.Mockito.*;

import java.io.File;
import java.io.FileInputStream;
import java.io.InputStreamReader;
import java.io.Reader;
import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import org.junit.Before;
import org.junit.Ignore;
import org.junit.Test;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.MockitoAnnotations;

import com.all.core.common.services.ApplicationConfig;
import com.all.core.common.services.reporting.FileStatExtractIterable;
import com.all.core.common.services.reporting.ReporterStatFileManager;
import com.all.shared.json.JsonConverter;
import com.all.shared.stats.AllStat;
import com.all.shared.stats.UserSessionStat;
import com.all.shared.stats.usage.UserActionStat;

public class TestReporterStatFileManager {
	@InjectMocks
	private ReporterStatFileManager fileManager;
	@Mock
	private ApplicationConfig config;

	@Before
	public void setup() {
		fileManager = new ReporterStatFileManager();
		MockitoAnnotations.initMocks(this);
	}

	@Test
	public void shouldSaveStats() throws Exception {
		File tempFile = File.createTempFile("abc", null);
		when(config.getAppFolder("reporting")).thenReturn(tempFile.getParentFile());
		List<AllStat> stats = new ArrayList<AllStat>();

		File savedStats = fileManager.saveStats(stats);
		savedStats.deleteOnExit();

		String fileContents = readFile(savedStats);
		String expectedJson = JsonConverter.toJson(stats);
		assertEquals(expectedJson, fileContents);
	}

	@SuppressWarnings("deprecation")
	@Test
	public void shouldSaveStatsWithMoreComplexThings() throws Exception {
		File tempFile = File.createTempFile("abc", null);
		when(config.getAppFolder("reporting")).thenReturn(tempFile.getParentFile());
		List<AllStat> stats = new ArrayList<AllStat>();
		stats.add(new UserActionStat());
		stats.add(new UserSessionStat());

		File savedStats = fileManager.saveStats(stats);
		savedStats.deleteOnExit();

		String fileContents = readFile(savedStats);
		String expectedJson = JsonConverter.toJson(stats);
		assertEquals(expectedJson, fileContents);
	}

	@SuppressWarnings("deprecation")
	@Test
	@Ignore("For safety, though it runs it may generate errors since its accessing the filesystem directories")
	public void UBERTEST() throws Exception {
		File tempFile = File.createTempFile("abc", null);
		File tempDir = new File(tempFile.getParent(), "tempTestUberTest");
		tempDir.mkdir();
		tempDir.deleteOnExit();
		when(config.getAppFolder("reporting")).thenReturn(tempDir);
		List<AllStat> stats = new ArrayList<AllStat>();
		stats.add(new UserActionStat());
		stats.add(new UserSessionStat());

		File savedStats = fileManager.saveStats(stats);
		savedStats.deleteOnExit();

		Iterable<List<AllStat>> load = fileManager.load();
		Iterator<List<AllStat>> iterator = load.iterator();
		assertTrue(iterator.hasNext());
		List<AllStat> next = iterator.next();
		assertNotNull(next);
		assertFalse(next.isEmpty());
		assertEquals(2, next.size());
		assertFalse(iterator.hasNext());
	}

	@SuppressWarnings("deprecation")
	@Test
	public void TestTheIteratorHandling() throws Exception {
		File tempFile = File.createTempFile("abc", null);
		when(config.getAppFolder("reporting")).thenReturn(tempFile.getParentFile());
		List<AllStat> stats = new ArrayList<AllStat>();
		stats.add(new UserActionStat());
		stats.add(new UserSessionStat());

		File savedStats = fileManager.saveStats(stats);
		savedStats.deleteOnExit();

		FileStatExtractIterable fileStatExtractIterable = new FileStatExtractIterable(new File[] { savedStats },
				Charset.forName("UTF-8"));
		Iterator<List<AllStat>> iterator = fileStatExtractIterable.iterator();
		assertTrue(iterator.hasNext());
		List<AllStat> next = iterator.next();
		assertNotNull(next);
		assertFalse(next.isEmpty());
		assertEquals(2, next.size());
		assertFalse(iterator.hasNext());

	}

	private String readFile(File savedStats) throws Exception {
		Reader reader = new InputStreamReader(new FileInputStream(savedStats), "UTF-8");
		StringBuilder text = new StringBuilder();
		int c = -1;
		while ((c = reader.read()) != -1) {
			text.append((char) c);
		}
		reader.close();
		return text.toString();
	}
}


text:
<?php

class Ffuenf_ProductAlertCleaner_Test_Helper_Data extends EcomDev_PHPUnit_Test_Case
{
    /**
     * @var Ffuenf_ProductAlertCleaner_Helper_Data
     */
    protected $_helper;

    public function setUp()
    {
        $this->_helper = new Ffuenf_ProductAlertCleaner_Helper_Data();
    }

    public function tearDown()
    {
        $this->_helper = null;
    }

    /**
     * Tests is extension active.
     *
     * @test
     * @covers Ffuenf_ProductAlertCleaner_Helper_Data::isExtensionActive
     */
    public function testIsExtensionActive()
    {
        $this->assertTrue(
            $this->_helper->isExtensionActive(),
            'Extension is not active please check config'
        );
    }
}


text:
<?xml version="1.0" encoding="utf-8"?>
<CrawlItem xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
  <Text>TOSTADA DE POLO je odlična! I hvala za gratis palačinku, baš super!</Text>
  <Rating>6</Rating>
  <Source>http://pauza.hr/menu/strossmayer</Source>
</CrawlItem>


text:
package quotidian.web

import com.handinteractive.mobile.UAgentInfo
import javax.servlet.http.{HttpServlet, HttpServletRequest => Request, HttpServletResponse => Response}
import quotidian.Logging
import scala.util.matching.Regex
import velocity.VelocityView

trait QcServlet extends HttpServlet {
	lazy val html = "templates/default.vm"
	lazy val json = "templates/default.json.vm"
	lazy val xml = "templates/default.xml.vm"
	lazy val plist = "templates/default.plist.vm"

	override def doGet(request:Request, response:Response) = handleRequest(request,response,processGet(_))
	override def doPost(request:Request, response:Response) = handleRequest(request,response,processPost(_))

	def processGet(http:HttpHelper) = Map[String,Any]()
	def processPost(http:HttpHelper) = Map[String,Any]()
	def handleRequest(request:Request,response:Response,processor:(HttpHelper) => Map[String,Any]) = {
		val http = new HttpHelper(request,response)
		val context = processor(http) + ("UserAgentInfo" -> new UAgentInfo(request))
		val view = new VelocityView(http.view)
		view.render(context,request,response)
	}

	private val uriRE = new Regex("(.*?)(xml|html|json|plist)?$","uri","format")
	private val dataRE = new Regex("(.*?)/([^/]*)$","path","data")

	class HttpHelper(val request:Request,val response:Response) extends Logging {
		// pretty impossible to not match this RE
		private val uriMatch = uriRE.findFirstMatchIn(request.getRequestURI).get
		private val uri = trim(uriMatch.group("uri"))
		private val format = uriMatch.group("format") match {
			case null => "html"
			case s:String => s
		}
		private val servletPath = request.getServletPath
		val (path,data) =
			if (servletPath == uri) {
				(uri,"")
			} else {
				(servletPath,uri.replace(servletPath + "/",""))
			}
		lazy val view = format match {
			case "xml" => xml
			case "json" => json
			case "plist" => plist
			case _ => html
		}

		def apply(param:String,default:String = "") = {
			val value = request.getParameter(param)
			if (value == null || value == "" || value == default) None else Some(value)
		}
		private def trim(str:String) =
			if (str.length > 0 && str.last == '/') {
				str.substring(0,str.length - 1)
			} else {
				str
			}
	}
}


text:
import bincalc

function_mapper = {
    int: bincalc.bytesToNumber,
    long: bincalc.bytesToNumber,
    unicode: bincalc.byteArrayToUnicode, # unicode(bytearray.decode("utf-8"))
    # str: does not need conversion, works directly
}

class BinaryDecoder:
    # final item dictionary. key:index, value:bytearray
    items = {}

    # Blueprint
    blueprint = None

    # Temporary storage of raw request
    byteArray = bytearray()

    def __init__(self):
        pass

    def __init__(self, blueprint):
        print "Blueprint:", blueprint
        self.loadBlueprint(blueprint)

    def loadBlueprint(self, blueprint):
        """ Map primitive functions to helper functions (decompressNumber, etc) """
        self.blueprint = {}
        for index in blueprint:
            function, key = blueprint[index]
            if function in function_mapper:
                function = function_mapper[function]
            self.blueprint[index] = (function, key)

    def readVarint(self):
        """
        Parse self.byteArray (pop from 0..n) to extract the current varint bytes.
        Returns the normal number.
        """
        number = 0
        round = 0
        while True:
            round += 1
            if round > 1:
                number <<= 7

            cur_byte = self.byteArray.pop(0)
            if cur_byte >> 7 == 1:
                number |= cur_byte & 127 # remove length-info bit
            else:
                # last varint byte because msb is 0. append and exit
                number |= cur_byte
                break

        return number

    def decode(self, byteArray):
        """
        Decodes a given binary request (bytearray), and extracts the content into a
        dictionary mapped to the original index keys. This function behaves differently
        with and without blueprints:

        No Blueprints:
        - values are bytearrays

        With Blueprints:
        - values are casted to their original data type
        """
        self.items = {}
        self.byteArray = byteArray
        self.byteArray.pop(0) # request start byte 0x00

        while len(self.byteArray) > 0:
           payload_length = self.readVarint()
           index = self.readVarint()
           payload = self.byteArray[:payload_length]
           self.byteArray[:payload_length] = []
           # If object blueprint available we can cast the bytearray now
           if self.blueprint:
               payload = self.blueprint[index][0](payload)
           self.items[index] = payload

        return self.items


text:
const Path = require('path');
const Mongoose = require('mongoose');
Mongoose.Promise = global.Promise;
const path = require('path');
const Config = require('config');

module.exports = {

  getFiles(path) {
    path = path[path.length - 1] !== '/' ? path + '/' : path;
    let files = [];
    try {
      files = require('fs').readdirSync(Path.resolve(__dirname, '../..', path));
    } catch (e) {
      console.log(e);
      process.exit();
    }
    return files.map((file) => {
      return Path.resolve(__dirname, '../..', path, file)
    });
  },

  addRoute(server) {
    this.getFiles('routes').forEach((routesFile) => {

      require(routesFile).forEach((route) => {
        server.route(route);
      });
    });
  },

  async addPolicies(server) {
    await server.register(require('hapi-auth-jwt2'));

    this.getFiles('policies').forEach((policyFile) => {

      let policy = require(policyFile);
      let name = path.basename(policyFile, '.js');
      let namePolicie = name.split('.')[0];

      server.auth.strategy(namePolicie, 'jwt', {
        key: Config.get('server.auth.secretKey'),
        validate: policy,
        verifyOptions: {algorithms: ['HS256']}
      });

    });
    server.auth.default('default', 'jwt');

  },

  addModels() {
    global.Models = {};

    this.getFiles('models').forEach((modelFile) => {

      let modelInterface = require(modelFile);
      let schema = Mongoose.Schema(modelInterface.schema, {versionKey: false});
      let name = path.basename(modelFile, '.js');

      if (modelInterface.statics) {
        for (let modelStatic in modelInterface.statics) {
          schema.statics[modelStatic] = modelInterface.statics[modelStatic];
        }
      }

      if (modelInterface.methods) {
        for (let modelMethod in modelInterface.methods) {
          schema.methods[modelMethod] = modelInterface.methods[modelMethod];
        }
      }

      if (modelInterface.onSchema) {
        for (let type in modelInterface.onSchema) {
          for (let func in modelInterface.onSchema[type]) {
            if (Array.isArray(modelInterface.onSchema[type][func])) {
              for (var i = 0; i < modelInterface.onSchema[type][func].length; i++) {
                schema[type](func, modelInterface.onSchema[type][func][i]);
              }
            } else {
              schema[type](func, modelInterface.onSchema[type][func]);
            }
          }
        }
      }

      let nameModel = name.split('.')[0];
      nameModel = nameModel.charAt(0).toUpperCase() + nameModel.slice(1);
      Models[nameModel] = Mongoose.model(nameModel, schema);
    });
  }
};


text:
package edu.stanford.math.plex4.homology.zigzag;

import java.util.HashMap;
import java.util.Map;

import edu.stanford.math.plex4.homology.barcodes.AnnotatedBarcodeCollection;
import edu.stanford.math.plex4.homology.barcodes.BarcodeCollection;
import edu.stanford.math.plex4.homology.barcodes.Interval;
import edu.stanford.math.plex4.homology.barcodes.PersistenceInvariantDescriptor;
import edu.stanford.math.primitivelib.utility.Infinity;

public class IntervalTracker<K, I extends Comparable<I>, G> implements AbstractPersistenceTracker<K, I, G> {

	protected final Map<K, IntervalDescriptor<I, G>> openIntervals = new HashMap<K, IntervalDescriptor<I, G>>();
	protected final AnnotatedBarcodeCollection<I, G> annotatedBarcodes = new AnnotatedBarcodeCollection<I, G>();

	protected boolean useLeftClosedIntervals = true;
	protected boolean useRightClosedIntervals = true;

	protected int maxDimension = Infinity.Int.getPositiveInfinity();

	public Map<K, IntervalDescriptor<I, G>> getActiveGenerators() {
		return this.openIntervals;
	}

	public AnnotatedBarcodeCollection<I, G> getInactiveGenerators() {
		return this.annotatedBarcodes;
	}

	public void setMaxDimension(int maxDimension) {
		this.maxDimension = maxDimension;
	}

	public void setUseLeftClosedIntervals(boolean value) {
		this.useLeftClosedIntervals = value;
	}

	public void setUseRightClosedIntervals(boolean value) {
		this.useRightClosedIntervals = value;
	}

	public boolean containsActiveInterval(K key) {
		return this.openIntervals.containsKey(key);
	}

	public void startInterval(K key, I startIndex, int dimension, G generator) {

		if (dimension > this.maxDimension) {
			return;
		}

		IntervalDescriptor<I, G> descriptor = new IntervalDescriptor<I, G>(startIndex, dimension, generator);
		this.openIntervals.put(key, descriptor);
	}

	public void endInterval(K key, I endIndex) {

		if (!this.openIntervals.containsKey(key)) {
			return;
		}

		IntervalDescriptor<I, G> descriptor = this.openIntervals.get(key);

		if (this.useLeftClosedIntervals && this.useRightClosedIntervals) {
			if (endIndex.compareTo(descriptor.start) >= 0) {
				this.annotatedBarcodes.addInterval(descriptor.dimension, Interval.makeInterval(descriptor.start, endIndex, this.useLeftClosedIntervals, this.useRightClosedIntervals, false, false), descriptor.generator);
			}
		} else {
			if (endIndex.compareTo(descriptor.start) > 0) {
				this.annotatedBarcodes.addInterval(descriptor.dimension, Interval.makeInterval(descriptor.start, endIndex, this.useLeftClosedIntervals, this.useRightClosedIntervals, false, false), descriptor.generator);
			}
		}

		this.openIntervals.remove(key);
	}

	public void endAllIntervals(I endIndex) {
		for (K key: this.openIntervals.keySet()) {
			if (!this.openIntervals.containsKey(key)) {
				continue;
			}

			IntervalDescriptor<I, G> descriptor = this.openIntervals.get(key);

			if (this.useLeftClosedIntervals && this.useRightClosedIntervals) {
				if (endIndex.compareTo(descriptor.start) >= 0) {
					this.annotatedBarcodes.addInterval(descriptor.dimension, Interval.makeInterval(descriptor.start, endIndex, this.useLeftClosedIntervals, this.useRightClosedIntervals, false, false), descriptor.generator);
				}
			} else {
				if (endIndex.compareTo(descriptor.start) > 0) {
					this.annotatedBarcodes.addInterval(descriptor.dimension, Interval.makeInterval(descriptor.start, endIndex, this.useLeftClosedIntervals, this.useRightClosedIntervals, false, false), descriptor.generator);
				}
			}
		}

		this.openIntervals.clear();
	}

	public AnnotatedBarcodeCollection<I, G> getAnnotatedBarcodes() {
		return (AnnotatedBarcodeCollection<I, G>) PersistenceInvariantDescriptor.union(this.getFiniteAnnotatedBarcodes(), this.getInfiniteAnnotatedBarcodes());
	}

	public AnnotatedBarcodeCollection<I, G> getInfiniteAnnotatedBarcodes() {
		AnnotatedBarcodeCollection<I, G> collection = new AnnotatedBarcodeCollection<I, G>();
		for (K key: this.openIntervals.keySet()) {
			IntervalDescriptor<I, G> descriptor = this.openIntervals.get(key);
			collection.addInterval(descriptor.dimension, Interval.makeInterval(descriptor.start, null, this.useLeftClosedIntervals, this.useRightClosedIntervals, false, true), descriptor.generator);
		}

		return collection;
	}

	public AnnotatedBarcodeCollection<I, G> getFiniteAnnotatedBarcodes() {
		return this.annotatedBarcodes;
	}

	public BarcodeCollection<I> getBarcodes() {
		return BarcodeCollection.forgetGeneratorType(this.getAnnotatedBarcodes());
	}

	public BarcodeCollection<I> getInfiniteBarcodes() {
		return BarcodeCollection.forgetGeneratorType(this.getInfiniteAnnotatedBarcodes());
	}

	public BarcodeCollection<I> getFiniteBarcodes() {
		return BarcodeCollection.forgetGeneratorType(this.getFiniteAnnotatedBarcodes());
	}

	@Override
	public String toString() {

		StringBuilder builder = new StringBuilder();

		for (K key: this.openIntervals.keySet()) {
			IntervalDescriptor<I, G> descriptor = this.openIntervals.get(key);
			builder.append(key.toString() + ": " + descriptor.toString());
			builder.append("\n");
		}

		builder.append(this.annotatedBarcodes.toString());

		return builder.toString();
	}

	/*
	public static <L, U, V> AnnotatedIntervalTracker<L, V> join(AnnotatedIntervalTracker<L, U> X, AnnotatedIntervalTracker<L, V> Z, Map<L, L> map, int ZIndex) {
		AnnotatedIntervalTracker<L, V> result = new AnnotatedIntervalTracker<L, V>();
		result.setUseRightClosedIntervals(true);
		Set<L> processedZIndices = new HashSet<L>();

		for (L X_key: X.openIntervals.keySet()) {
			IntervalDescriptor<Integer, U> X_descriptor = X.openIntervals.get(X_key);
			if (map.containsKey(X_key)) {
				L Z_key = map.get(X_key);
				IntervalDescriptor<Integer, V> Z_descriptor = Z.openIntervals.get(Z_key);

				result.startInterval(Z_key, X_descriptor.start, Z_descriptor.dimension, Z_descriptor.generator);

				processedZIndices.add(map.get(X_key));
			} else {
				result.startInterval(X_key, X_descriptor.start, X_descriptor.dimension, null);
				result.endInterval(X_key, ZIndex - 1);
			}
		}

		for (L Z_key: Z.openIntervals.keySet()) {
			if (processedZIndices.contains(Z_key)) {
				continue;
			}

			IntervalDescriptor<Integer, V> Z_descriptor = Z.openIntervals.get(Z_key);

			result.startInterval(Z_key, Z_descriptor.start, Z_descriptor.dimension, Z_descriptor.generator);
		}

		for (Entry<Integer, List<ObjectObjectPair<Interval<Integer>, U>>> barcode: X.annotatedBarcodes) {
			int dimension = barcode.getKey();
			for (ObjectObjectPair<Interval<Integer>, U> intervalPair: barcode.getValue()) {
				result.annotatedBarcodes.addInterval(dimension, intervalPair.getFirst(), null);
			}
		}

		return result;
	}
	*/
}


text:
package com.contactlab.api.ws;

import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlType;

/**
 *
Java class for getEmptyPushTemplateResponse complex type.
 *
 *
The following schema fragment specifies the expected content contained within this class.
 *
 *

 * <complexType name="getEmptyPushTemplateResponse">
 *   <complexContent>
 *     <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
 *       <sequence>
 *         <element name="return" type="{http://ws.api.contactlab.com/}pushTemplateEnvelope" minOccurs="0"/>
 *       </sequence>
 *     </restriction>
 *   </complexContent>
 * </complexType>
 *

 *
 *
 */
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "getEmptyPushTemplateResponse", propOrder = {
    "_return"
})
public class GetEmptyPushTemplateResponse {

    @XmlElement(name = "return")
    protected PushTemplateEnvelope _return;

    /**
     * Gets the value of the return property.
     *
     * @return
     *     possible object is
     *     {@link PushTemplateEnvelope }
     *
     */
    public PushTemplateEnvelope getReturn() {
        return _return;
    }

    /**
     * Sets the value of the return property.
     *
     * @param value
     *     allowed object is
     *     {@link PushTemplateEnvelope }
     *
     */
    public void setReturn(PushTemplateEnvelope value) {
        this._return = value;
    }

}


text:
Graph Converters
================

.. autoclass:: nnabla.experimental.graph_converters.GraphConverter
    :members:

.. autoclass:: nnabla.experimental.graph_converters.FunctionModifier
    :members:

Function Modifiers
------------------

.. autoclass:: nnabla.experimental.graph_converters.BatchNormalizationFoldingModifier

.. autoclass:: nnabla.experimental.graph_converters.AddBiasModifier

.. autoclass:: nnabla.experimental.graph_converters.BatchNormalizationFoldingModifierInner

.. autoclass:: nnabla.experimental.graph_converters.BatchNormalizationFoldingOppositeModifierInner

.. autoclass:: nnabla.experimental.graph_converters.BatchNormalizationSelfFoldingModifier

.. autoclass:: nnabla.experimental.graph_converters.FusedBatchNormalizationModifier

.. autoclass:: nnabla.experimental.graph_converters.UnfusedBatchNormalizationModifier

.. autoclass:: nnabla.experimental.graph_converters.ChannelLastModifier

.. autoclass:: nnabla.experimental.graph_converters.ChannelFirstModifier

.. autoclass:: nnabla.experimental.graph_converters.RemoveFunctionModifier

.. autoclass:: nnabla.experimental.graph_converters.BatchNormBatchStatModifier

.. autoclass:: nnabla.experimental.graph_converters.TestModeModifier

.. autoclass:: nnabla.experimental.graph_converters.IdentityModifier

.. autoclass:: nnabla.experimental.graph_converters.NoGradModifier

.. autoclass:: nnabla.experimental.graph_converters.PruningModifier

    .. automethod:: __init__

.. autoclass:: nnabla.experimental.graph_converters.QuantizeNonQNNToRecordingModifier

.. autoclass:: nnabla.experimental.graph_converters.QuantizeRecordingToTrainingModifier