inline void SqlTranslator::Visit(const OrExpression& expression) { const auto& leftExpression = *expression.GetLeftExpression(); leftExpression.Apply(*this); auto leftQuery = GetQuery(); const auto& rightExpression = *expression.GetRightExpression(); rightExpression.Apply(*this); auto rightQuery = GetQuery(); GetQuery() = "(" + leftQuery + " OR " + rightQuery + ")"; }
inline void SqlTranslator::Visit(const ConstantExpression& expression) { const Value& value = expression.GetValue(); if(value->GetType()->GetNativeType() == typeid(bool)) { if(value->GetValue<bool>()) { GetQuery() += "true"; } else { GetQuery() += "false"; } } else if(value->GetType()->GetNativeType() == typeid(char)) { GetQuery() += "\'"; GetQuery() += value->GetValue<char>(); GetQuery() += + "\'"; } else if(value->GetType()->GetNativeType() == typeid(int)) { GetQuery() += boost::lexical_cast<std::string>(value->GetValue<int>()); } else if(value->GetType()->GetNativeType() == typeid(double)) { GetQuery() += boost::lexical_cast<std::string>(value->GetValue<double>()); } else if(value->GetType()->GetNativeType() == typeid(std::string)) { GetQuery() += "\"" + value->GetValue<std::string>() + "\""; } else if(value->GetType()->GetNativeType() == typeid(boost::posix_time::ptime)) { std::uint64_t timestamp = MySql::ToMySqlTimestamp( value->GetValue<boost::posix_time::ptime>()); GetQuery() += boost::lexical_cast<std::string>(timestamp); } }
bool CMySQL_LangCmd::Send() { if (mysql_real_query (&m_Connect->m_MySQL, GetQuery().data(), GetQuery().length()) != 0) { DATABASE_DRIVER_WARNING( "Failed: mysql_real_query", 800003 ); } GetBindParamsImpl().LockBinding(); my_ulonglong nof_Rows = mysql_affected_rows(&this->m_Connect->m_MySQL); // There is not too much sence in comparing unsigned value with -1. // m_HasMoreResults = nof_Rows == -1 || nof_Rows > 0; m_HasMoreResults = nof_Rows > 0; return true; }
/// If this virtual method is overwritten in a derived class, it typically /// first calls the corresponding method of the base class. bool CbirRandom::Initialize(const Query *q, const string& s, CbirAlgorithm::QueryData*& qd) const { string hdr = "CbirRandom::Initialize() : "; if (!CbirAlgorithm::Initialize(q, s, qd)) return ShowError(hdr+"CbirAlgorithm::Initialize() failed"); // After calling CbirAlgorithm::Initialize() we should have a valid Query // pointer named qd->query: cout << TimeStamp() << hdr << "query's identity is \"" << GetQuery(qd)->Identity() << "\"" << endl; cout << TimeStamp() << hdr << "query's target type is \"" << TargetTypeString(GetQuery(qd)->Target()) << "\"" << endl; return true; }
nsresult nsMailboxUrl::ParseSearchPart() { nsAutoCString searchPart; nsresult rv = GetQuery(searchPart); // add code to this function to decompose everything past the '?'..... if (NS_SUCCEEDED(rv) && !searchPart.IsEmpty()) { // the action for this mailbox must be a display message... char * msgPart = extractAttributeValue(searchPart.get(), "part="); if (msgPart) // if we have a part in the url then we must be fetching just the part. m_mailboxAction = nsIMailboxUrl::ActionFetchPart; else m_mailboxAction = nsIMailboxUrl::ActionFetchMessage; char * messageKey = extractAttributeValue(searchPart.get(), "number="); m_messageID = extractAttributeValue(searchPart.get(),"messageid="); if (messageKey) m_messageKey = (nsMsgKey) ParseUint64Str(messageKey); // convert to a uint32_t... PR_Free(msgPart); PR_Free(messageKey); } else m_mailboxAction = nsIMailboxUrl::ActionParseMailbox; return rv; }
QList<QVariant> FirefoxProfileSelectPage::GetBookmarks () { QString sql ("SELECT bm.title, pl.url FROM moz_bookmarks bm, moz_places pl " "WHERE bm.parent NOT IN (SELECT ann.item_id FROM moz_items_annos " "ann, moz_bookmarks bm WHERE ann.item_id IN (SELECT item_id FROM " "moz_items_annos WHERE anno_attribute_id = (SELECT id FROM " "moz_anno_attributes WHERE name='livemark/feedURI')) AND " "ann.anno_attribute_id <> 3 AND ann.anno_attribute_id <> 7 AND bm.id" "= ann.item_id) AND bm.fk IS NOT NULL AND bm.fk IN (SELECT id " "FROM moz_places WHERE url LIKE 'http%' OR url LIKE 'ftp%' OR url " "like 'file%') AND bm.id > 100 AND bm.fk = pl.id AND bm.title NOT NULL"); QSqlQuery bookmarksQuery = GetQuery (sql); if (bookmarksQuery.isValid ()) { QList<QVariant> bookmarks; QString tagsSql_p1 ("SELECT title from moz_bookmarks WHERE id IN (" "SELECT bm.parent FROM moz_bookmarks bm, moz_places pl " " WHERE pl.url='"); QString tagsSql_p2 ("' AND bm.title IS NULL AND bm.fk = pl.id)"); QMap<QString, QVariant> record; do { QString tagsSql = tagsSql_p1 + bookmarksQuery.value (1).toString () + tagsSql_p2; QSqlQuery tagsQuery = GetQuery (tagsSql); QStringList tags; do { QString tag = tagsQuery.value (0).toString (); if (!tag.isEmpty ()) tags << tag; } while (tagsQuery.next ()); record ["Tags"] = tags; record ["Title"] = bookmarksQuery.value (0).toString (); record ["URL"] = bookmarksQuery.value (1).toString (); bookmarks.push_back (record); } while (bookmarksQuery.next ()); return bookmarks; } return QList<QVariant> (); }
void CAsyncWriter::OnInvokeBackground( ) { sBindParameter* pStreamParam = GetQuery( )->GetStreamParameter( ); size_t nRemaining = pStreamParam->m_nColumnSize - pStreamParam->m_nDataWritten; if( nRemaining < m_nLength ) { m_nLength = nRemaining; } if( !GetQuery( )->GetStatement( ).PutData( m_pBuffer, m_nLength ) ) { m_bHasError = true; } pStreamParam->m_nDataWritten += m_nLength; }
void CAsyncWriter::OnCompleteForeground( ) { Isolate* isolate = Isolate::GetCurrent( ); HandleScope scope( isolate ); Local< Function > callback = node::PersistentToLocal( isolate, m_fnCallback ); const unsigned argc = 1; Local< Value > argv[ argc ] = { Boolean::New( isolate, m_bHasError ) }; node::MakeCallback( isolate, Object::New( isolate ), callback, argc, argv ); sBindParameter* pStreamParam = GetQuery( )->GetStreamParameter( ); if( pStreamParam->m_nDataWritten == pStreamParam->m_nColumnSize ) { GetQuery( )->RunOperation( ); //> leaks } }
nsresult nsNntpUrl::DetermineNewsAction() { nsAutoCString path; nsresult rv = nsMsgMailNewsUrl::GetPathQueryRef(path); NS_ENSURE_SUCCESS(rv, rv); nsAutoCString query; rv = GetQuery(query); NS_ENSURE_SUCCESS(rv, rv); if (query.EqualsLiteral("cancel")) { m_newsAction = nsINntpUrl::ActionCancelArticle; return NS_OK; } if (query.EqualsLiteral("list-ids")) { m_newsAction = nsINntpUrl::ActionListIds; return NS_OK; } if (query.EqualsLiteral("newgroups")) { m_newsAction = nsINntpUrl::ActionListNewGroups; return NS_OK; } if (StringBeginsWith(query, NS_LITERAL_CSTRING("search"))) { m_newsAction = nsINntpUrl::ActionSearch; return NS_OK; } if (StringBeginsWith(query, NS_LITERAL_CSTRING("part=")) || query.Find("&part=") > 0) { // news://news.mozilla.org:119/3B98D201.3020100%40cs.com?part=1 // news://news.mozilla.org:119/b58dme%24aia2%40ripley.netscape.com?header=print&part=1.2&type=image/jpeg&filename=Pole.jpg m_newsAction = nsINntpUrl::ActionFetchPart; return NS_OK; } if (!m_messageID.IsEmpty() || m_key != nsMsgKey_None) { m_newsAction = nsINntpUrl::ActionFetchArticle; return NS_OK; } if (m_group.Find("*") >= 0) { // If the group is a wildmat, list groups instead of grabbing a group. m_newsAction = nsINntpUrl::ActionListGroups; return NS_OK; } if (!m_group.IsEmpty()) { m_newsAction = nsINntpUrl::ActionGetNewNews; return NS_OK; } // At this point, we have a URI that contains neither a query, a group, nor a // message ID. Ergo, we don't know what it is. m_newsAction = nsINntpUrl::ActionUnknown; return NS_OK; }
inline void SqlTranslator::Visit(const FunctionExpression& expression) { if(expression.GetName() == ADDITION_NAME) { if(expression.GetParameters().size() != 2) { BOOST_THROW_EXCEPTION(ExpressionTranslationException( "Invalid parameters.")); } const auto& leftExpression = *expression.GetParameters()[0]; leftExpression.Apply(*this); auto leftQuery = GetQuery(); const auto& rightExpression = *expression.GetParameters()[1]; rightExpression.Apply(*this); auto rightQuery = GetQuery(); GetQuery() = "(" + leftQuery + " + " + rightQuery + ")"; } else if(expression.GetName() == EQUALS_NAME) { if(expression.GetParameters().size() != 2) { BOOST_THROW_EXCEPTION(ExpressionTranslationException( "Invalid parameters.")); } const auto& leftExpression = *expression.GetParameters()[0]; leftExpression.Apply(*this); auto leftQuery = GetQuery(); const auto& rightExpression = *expression.GetParameters()[1]; rightExpression.Apply(*this); auto rightQuery = GetQuery(); GetQuery() = "(" + leftQuery + " = " + rightQuery + ")"; } else { BOOST_THROW_EXCEPTION(ExpressionTranslationException( "Function not supported.")); } }
void CADORecordset::dump_com_error(_com_error &e) { TCHAR ErrorStr[1024]; _bstr_t bstrSource(e.Source()); _bstr_t bstrDescription(e.Description()); swprintf(ErrorStr,sizeof(ErrorStr)/sizeof(ErrorStr[0]), _T("CADORecordset Error\r\nCode = %08lx\r\nCode meaning = %s\r\nSource = %s\r\nDescription = %s\r\n"), e.Error(), e.ErrorMessage(), (LPCTSTR)bstrSource, (LPCTSTR)bstrDescription ); m_strLastError = _T("Query = ") + GetQuery() + _T('\r\n') + ErrorStr; m_dwLastError = e.Error(); }
void sPerfMonGpu::Leave(const sPerfMonSection *s) { if(this && Current) { RecordQuery *q = Current->Queries.AddMany(1); q->PatchTime = int(Current->Data.GetCount()); q->Query = GetQuery(); q->Query->Issue(Adapter->ImmediateContext); Record *r = Current->Data.AddMany(1); r->Kind = RK_Leave; r->Section = s; r->Time = 0; } }
CDBParams& CODBC_RPCCmd::GetBindParams(void) { if (m_InParams.get() == NULL) { m_InParams.reset(new impl::CRowInfo_SP_SQL_Server( GetQuery(), GetConnImpl(), GetBindParamsImpl() ) ); } return *m_InParams; }
void CADORecordset::dump_com_error(_com_error &e) { CString ErrorStr; _bstr_t bstrSource(e.Source()); _bstr_t bstrDescription(e.Description()); ErrorStr.Format( "CADORecordset Error\n\tCode = %08lx\n\tCode meaning = %s\n\tSource = %s\n\tDescription = %s\n", e.Error(), e.ErrorMessage(), (LPCSTR)bstrSource, (LPCSTR)bstrDescription ); ErrorStr.Format( "Error Code = %08lx\n\t %s\n", e.Error(), (LPCSTR)bstrDescription ); m_strLastError = _T("Query = " + GetQuery() + " " + (LPCSTR)bstrDescription); m_dwLastError = e.Error(); #ifdef _DEBUG AfxMessageBox( ErrorStr, MB_OK | MB_ICONERROR ); #endif throw CADOException(e.Error(), m_strLastError); }
long CStaffTable::Find(tTableMap& data, const tDATA& filter) { long res = UDF_E_FAIL; do { std::string szQuery; std::string szFilter; sql::ResultSet* qRes = NULL; if(! m_pConnection) { res = UDF_E_NOCONNECTION; break; } szFilter = GetFilterString(filter); szQuery = GetQuery(TABLE, szFilter); qRes = m_pConnection->ExecuteQuery(szQuery); if(!qRes) { res = UDF_E_EXECUTE_QUERY_FAILED; break; } data.clear(); while( qRes && qRes->next()) { tDATA el = {0}; el.id = qRes->getUInt("id"); el.roleId = qRes->getUInt("role_id"); el.name = qRes->getString("name"); el.login = qRes->getString("login"); el.pass = qRes->getString("pass"); data.insert(make_pair(el.id, el)); } res = UDF_OK; }while(0); return res; }
void CADORecordset::dump_com_error(_com_error &e) { CString ErrorStr; _bstr_t bstrSource(e.Source()); _bstr_t bstrDescription(e.Description()); ErrorStr.Format( _T("CADORecordset Error\n\tCode = %08lx\n\tCode meaning = %s\n\tSource = %s\n\tDescription = %s\n"), e.Error(), e.ErrorMessage(), (LPCSTR)bstrSource, (LPCSTR)bstrDescription ); m_strLastError = _T("Query = " + GetQuery() + '\n' + ErrorStr); m_dwLastError = e.Error(); #ifdef _DEBUG AfxMessageBox( ErrorStr, MB_OK | MB_ICONERROR ); #else g_log.Trace(LOGL_HIG, LOGC_ERROR, __TFILE__, __LINE__, bstrDescription) ; #endif throw CADOException(e.Error(), e.Description()); }
long CChampionshipToursTable::Find(tTableMap& data, const tDATA& filter) { long res = UDF_E_FAIL; do { std::string szQuery; std::string szFilter; sql::ResultSet* qRes = NULL; if(! m_pConnection) { res = UDF_E_NOCONNECTION; break; } szFilter = GetFilterString(filter); szQuery = GetQuery(TABLE, szFilter); qRes = m_pConnection->ExecuteQuery(szQuery); if(!qRes) { res = UDF_E_EXECUTE_QUERY_FAILED; break; } data.clear(); while( qRes && qRes->next()) { tDATA el = {0}; el.id = qRes->getUInt(1); el.csCatId = qRes->getUInt(2); el.typeId = qRes->getUInt(3); el.limit = qRes->getInt(4); data.insert(make_pair(el.id, el)); } res = UDF_OK; }while(0); return res; }
QList<QVariant> FirefoxProfileSelectPage::GetHistory () { QString sql ("SELECT moz_places.url, moz_places.title, moz_historyvisits.visit_date " "FROM moz_historyvisits, moz_places WHERE moz_places.id = moz_historyvisits.place_id"); QSqlQuery query = GetQuery (sql); if (query.isValid ()) { QList<QVariant> history; do { QMap<QString, QVariant> record; record ["URL"] = query.value (0).toString (); record ["Title"] = query.value (1).toString (); record ["DateTime"] = QDateTime::fromTime_t (query.value (2).toLongLong () / 1000000); history.push_back (record); } while (query.next ()); return history; } return QList<QVariant> (); }
/*************************************************************************** * COLLI_colli_reply_handler * ***************************************************************************/ void COLLI_colli_reply_handler(TCX_REF_PTR ref, COLLI_colli_reply_ptr data) { int i,count=0; for ( i=0 ; i<NumberOfColliReplyModules ; i++) { if ( RMR[ColliAutoReplyList[i]].ModuleStatus == ACTIVE ) { if ( ( COLLI_REPLIES % RMR[ColliAutoReplyList[i]].colli )==0) { if ( verbose_on == 1 ) fprintf (stderr,">"); tcxSendMsg ( RMR[ColliAutoReplyList[i]].module, "COLLI_colli_reply", data ); count++; } } } for ( i=0 ; i<MaxNumberOfModules ; i++ ) { if ( RMR[i].colli == 0 ) /* final security */ { if ( GetQuery ( i , COLLI_QUERY ) > 0 ) { if ( verbose_on == 1 ) fprintf (stderr,"\nSending COLLI REPLY to %d",i ); tcxSendMsg ( RMR[i].module, "COLLI_colli_reply", data ); DecreaseQuery ( i , COLLI_QUERY ); } } } COLLI_REPLIES++; if ( verbose_on == 1 ) fprintf (stderr,"C%d",count); tcxFree ( "COLLI_colli_reply" , data ); }
DWORD CHttpServer::HttpExtensionProc(EXTENSION_CONTROL_BLOCK *pECB) { DWORD dwRet = HSE_STATUS_SUCCESS; BOOL bDefault = FALSE; LPTSTR pszPostBuffer = NULL; LPTSTR pszQuery; LPTSTR pszCommand = NULL; int nMethodRet; LPTSTR pstrLastChar; DWORD cbStream = 0; BYTE* pbStream = NULL; CHttpServerContext ctxtCall(pECB); pECB->dwHttpStatusCode = 0; ISAPIASSERT(NULL != pServer); if (pServer == NULL) { dwRet = HSE_STATUS_ERROR; goto CleanUp; } // get the query if (_tcsicmp(pECB->lpszMethod, szGet) == 0) { pszQuery = pECB->lpszQueryString; } else if (_tcsicmp(pECB->lpszMethod, szPost) == 0) { pszCommand = pECB->lpszQueryString; pszPostBuffer = new TCHAR[pECB->cbAvailable + 1]; pszQuery = GetQuery(&ctxtCall, pszPostBuffer, pECB->cbAvailable); } else { ISAPITRACE1("Error: Unrecognized method: %s\n", pECB->lpszMethod); dwRet = HSE_STATUS_ERROR; goto CleanUp; } // trim junk that some browsers put at the very end pstrLastChar = pszQuery + _tcslen(pszQuery) -1; while ((*pstrLastChar == ' ' || *pstrLastChar == '\n' || *pstrLastChar == '\r') && pstrLastChar > pszQuery) { *pstrLastChar-- = '\0'; } // do something about it if (!pServer->InitInstance(&ctxtCall)) dwRet = HSE_STATUS_ERROR; else { pECB->dwHttpStatusCode = HTTP_STATUS_OK; try { nMethodRet = pServer->CallFunction(&ctxtCall, pszQuery, pszCommand); } catch (...) { ISAPITRACE1("Error: command %s caused an unhandled exception!\n", pszQuery); nMethodRet = callNoStackSpace; } // was an error caused by trying to dispatch? if (nMethodRet != callOK && pECB->dwHttpStatusCode == HTTP_STATUS_OK) { dwRet = HSE_STATUS_ERROR; switch (nMethodRet) { case callNoStream: pECB->dwHttpStatusCode = HTTP_STATUS_NO_CONTENT; break; case callParamRequired: case callBadParamCount: case callBadParam: pECB->dwHttpStatusCode = HTTP_STATUS_BAD_REQUEST; break; case callBadCommand: pECB->dwHttpStatusCode = HTTP_STATUS_NOT_IMPLEMENTED; break; case callNoStackSpace: default: pECB->dwHttpStatusCode = HTTP_STATUS_SERVER_ERROR; break; } } // if there was no error or the user said they handled // the error, prepare to spit out the generated HTML if (nMethodRet == callOK || OnParseError(&ctxtCall, nMethodRet) == TRUE) { cbStream = ctxtCall.m_pStream->GetStreamSize(); pbStream = ctxtCall.m_pStream->Detach(); } } CleanUp: // if there was an error, return an appropriate status TCHAR szResponse[64]; BuildStatusCode(szResponse, pECB->dwHttpStatusCode); DWORD dwSize = cbStream - ctxtCall.m_dwEndOfHeaders; BYTE* pbContent = NULL; BYTE cSaved; if (pbStream != NULL) { cSaved = pbStream[ctxtCall.m_dwEndOfHeaders]; pbStream[ctxtCall.m_dwEndOfHeaders] = '\0'; pbContent = &pbStream[ctxtCall.m_dwEndOfHeaders]; } if (!ctxtCall.ServerSupportFunction( HSE_REQ_SEND_RESPONSE_HEADER, szResponse, 0, (LPDWORD) pbStream)) { pECB->dwHttpStatusCode = HTTP_STATUS_SERVER_ERROR; dwRet = HSE_STATUS_ERROR; #ifdef _DEBUG DWORD dwCause = ::GetLastError(); ISAPITRACE1("Error: Unable to write headers: %8.8X!\n", dwCause); #endif } else { if (pbContent != NULL) { // write a newline to separate content from headers *pbContent = cSaved; DWORD dwNewLineSize = 2; if (!ctxtCall.WriteClient(_T("\r\n"), &dwNewLineSize, 0) || !ctxtCall.WriteClient(pbContent, &dwSize, 0)) { dwRet = HSE_STATUS_ERROR; pECB->dwHttpStatusCode = HTTP_STATUS_SERVER_ERROR; ISAPITRACE("Error: Unable to write content body!\n"); } } else ISAPITRACE("Error: No body content!\n"); } if (pbStream != NULL) ctxtCall.m_pStream->Free(pbStream); if (dwRet == HSE_STATUS_SUCCESS) pECB->dwHttpStatusCode = HTTP_STATUS_OK; if (pszPostBuffer != NULL) delete [] pszPostBuffer; return dwRet; }
/// This virtual method really needs to be overwritten in a derived /// class. ObjectList CbirRandom::CbirRound(CbirAlgorithm::QueryData *qd, const ObjectList& seen, size_t maxq) const { string hdr = "CbirRandom::CbirRound() : "; bool do_debug = debug_stages || debug; CbirRandom::QueryData *qde = CastData(qd); // This is called only for CbirAlgorithm::CbirRound()'s logging ability // it will return an empty list which is NOT an indication of a failure CbirAlgorithm::CbirRound(qde, seen, maxq); if (do_debug) cout << TimeStamp() << hdr << "starting with " << seen.size() << " object already seen" << endl; const Query::algorithm_data *lower = GetQuery(qd)->LowerAlgorithm(qd, 0, false); set<size_t> lowerset; if (lower) { for (size_t i=0; i<lower->result.size(); i++) if (lower->result[i].Retained()) lowerset.insert(lower->result[i].Index()); if (do_debug) cout << TimeStamp() << hdr << "lower algorithm [" << lower->fullname << "] returns " << lowerset.size() << "/" << lower->result.size() << " objects" << endl; } size_t nobj = qde->GetMaxQuestions(maxq), nobjeff = nobj-lowerset.size(); if (nobj<lowerset.size()) { ShowError(hdr+"nobj<lowerset.size()"); nobjeff = 0; } // This simple algorithm just returns nobj number of yet unseen // objects. The objects need to be of the same target_type as // requested by the Query object. ObjectList list; if (lower) for (size_t i=0; i<lower->result.size(); i++) if (lower->result[i].Retained()) list.push_back(Object(database, lower->result[i].Index(), select_question)); stringstream nobjstrss; nobjstrss << nobj << "-" << lowerset.size() << "=" << nobjeff; string nobjstr = nobjstrss.str(); bool old_and_slow = database->Size()<4000000; if (old_and_slow) { vector<size_t> idx; for (size_t i=0; i<database->Size(); i++) if (database->ObjectsTargetTypeContains(i, GetQuery(qde)->Target()) && GetQuery(qde)->CanBeShownRestricted(i, true) && (lowerset.empty() || lowerset.find(i)==lowerset.end())) idx.push_back(i); if (do_debug) cout << TimeStamp() << hdr << "selecting " << nobjstr << " random objects of type \"" << TargetTypeString(GetQuery(qde)->Target()) << "\" out of " << idx.size() << " unseen&unselected ones with seed " << qde->seed << endl; RandVar rndvar(qde->seed); while (!idx.empty() && (nobj==0 || list.size()<nobj)) { size_t rnd = (size_t)rndvar.RandomInt(idx.size()); list.push_back(Object(database, idx[rnd], select_question)); idx.erase(idx.begin()+rnd); } } else { if (do_debug) cout << TimeStamp() << hdr << "selecting " << nobjstr << " random objects of type \"" << TargetTypeString(GetQuery(qde)->Target()) << "\" out of " << "UNKNOWN NUMBER OF" << " unseen&unselected ones with seed " << qde->seed << endl; RandVar rndvar(qde->seed); while (list.size()<nobj) { size_t i = (size_t)rndvar.RandomInt(database->Size()); if (database->ObjectsTargetTypeContains(i, GetQuery(qde)->Target()) && GetQuery(qde)->CanBeShownRestricted(i, true) && (lowerset.empty() || lowerset.find(i)==lowerset.end())) list.push_back(Object(database, i, select_question)); } } if (do_debug||debug_lists) cout << TimeStamp() << hdr << "returning " << list.size() << " objects" << endl; return list; }
INT32 SNTPClient::Connect() { SOCK_SOCKET timeSocket = SOCK_SOCKET_ERROR; INT32 sockErr = 0; UINT32 usedServer = 0; // look up outstdanding queries for this set of servers OutstandingQuery* query = FindOutstandingConnection(m_ipAddressPrimary, m_ipAddressAlternate); if(query != NULL) { // // signal failed queries // if(query->IsOld()) { query->Dispose(); query = NULL; } else { // // resume old connection // timeSocket = query->GetSocket(); } } if(timeSocket == SOCK_SOCKET_ERROR) { // // new connection // timeSocket = SOCK_socket(SOCK_AF_INET, SOCK_SOCK_DGRAM, SOCK_IPPROTO_UDP); if(timeSocket == SOCK_SOCKET_ERROR) { sockErr = SOCK_getlasterror(); return (sockErr == 0 ? HAL_TIMESERVICE_ERROR : sockErr); } SOCK_sockaddr addr; SOCK_sockaddr_in* dst = (SOCK_sockaddr_in*)&addr; memset(dst, 0, sizeof(SOCK_sockaddr_in)); dst->sin_family = SOCK_AF_INET; dst->sin_port = SOCK_htons(123); dst->sin_addr.S_un.S_addr = SOCK_htonl(m_ipAddressPrimary); usedServer = m_ipAddressPrimary; if(SOCK_connect(timeSocket, &addr, sizeof(addr)) == SOCK_SOCKET_ERROR && SOCK_getlasterror() != SOCK_EWOULDBLOCK) { if(m_ipAddressAlternate != 0) { usedServer = m_ipAddressAlternate; dst->sin_addr.S_un.S_addr = SOCK_htonl(m_ipAddressAlternate); if(SOCK_connect(timeSocket, &addr, sizeof(addr)) == SOCK_SOCKET_ERROR && SOCK_getlasterror() != SOCK_EWOULDBLOCK) { sockErr = SOCK_getlasterror(); SOCK_close(timeSocket); return (sockErr == 0 ? HAL_TIMESERVICE_ERROR : sockErr); } } else { sockErr = SOCK_getlasterror(); SOCK_close(timeSocket); return (sockErr == 0 ? HAL_TIMESERVICE_ERROR : sockErr); } } Initialize(); int sent = SOCK_send(timeSocket, (char*)SNTPData, sizeof(SNTPData), 0); if(sent != sizeof(SNTPData)) { sockErr = SOCK_getlasterror(); SOCK_close(timeSocket); return (sockErr == 0 ? HAL_TIMESERVICE_ERROR : sockErr); } } // retry 10 times every time we stop by INT32 retry = 10; INT32 bytesToRead = c_SNTPDataLength; char* buf = (char*)SNTPData; while(retry-- > 0) { int read = SOCK_recv(timeSocket, buf, bytesToRead, 0); if(read < 0 && (sockErr = SOCK_getlasterror()) != SOCK_EWOULDBLOCK) { SOCK_close(timeSocket); return (sockErr == 0 ? HAL_TIMESERVICE_ERROR : sockErr); } else if(read > 0) { bytesToRead -= read; if(bytesToRead <= 0) { break; } buf += read; // incase we start receiving data towards the end // of the retry limit. retry++; } } // if we could not finish reading, then cache and retry later // if we read a part of answer, then declare failure // in the future we could try and cope with this problem if(bytesToRead == c_SNTPDataLength) { // // if this is a new connection, get a slot // if(query == NULL) { query = GetQuery(usedServer, timeSocket); } return HAL_TIMESERVICE_WANT_READ_WRITE; } else if(bytesToRead > 0 && bytesToRead < c_SNTPDataLength) { if(query != NULL) query->Dispose(); return HAL_TIMESERVICE_WANT_READ_WRITE; } else { if(query != NULL) { query->Dispose(); query = NULL; } else { if( timeSocket != SOCK_SOCKET_ERROR ) { SOCK_close(timeSocket); timeSocket = SOCK_SOCKET_ERROR; } } } DestinationTimestamp = Time_GetUtcTime(); if( !IsResponseValid() ) { if(query != NULL) { query->Dispose(); query = NULL; } else { if( timeSocket != SOCK_SOCKET_ERROR ) { SOCK_close(timeSocket); timeSocket = SOCK_SOCKET_ERROR; } } return HAL_TIMESERVICE_ERROR; } return HAL_TIMESERVICE_SUCCESS; }
inline void SqlTranslator::Visit(const ParameterExpression& expression) { GetQuery() = m_parameter; }
void Report::Export() { query->exec(GetQuery()); logRep->setQuery(query); logRep->makeReport(); }
QString FirefoxProfileSelectPage::GetImportOpmlFile () { QString rssSql ("SELECT ann.id, ann.item_id, ann.anno_attribute_id, ann.content," "bm.title FROM moz_items_annos ann,moz_bookmarks bm WHERE ann.item_id" " IN (SELECT item_id FROM moz_items_annos WHERE anno_attribute_id = (SELECT" " id FROM moz_anno_attributes WHERE name = 'livemark/feedURI')) AND (" "ann.anno_attribute_id = 4 OR ann.anno_attribute_id = 5) AND " "bm.id = ann.item_id"); QSqlQuery rssQuery = GetQuery (rssSql); if (rssQuery.isValid ()) { QSqlQuery query (*DB_); query.exec ("SELECT id FROM moz_anno_attributes WHERE name='livemark/siteURI'"); query.next (); int site = query.value (0).toInt (); query.exec ("SELECT id FROM moz_anno_attributes WHERE name='livemark/feedURI'"); query.next (); int feed = query.value (0).toInt (); QList<QVariant> opmlData; int prevItemId = -1; QMap<QString, QVariant> omplLine; do { if (rssQuery.value (2).toInt () == site) omplLine ["SiteUrl"] = rssQuery.value (3).toString (); if (rssQuery.value (2).toInt () == feed) omplLine ["FeedUrl"] = rssQuery.value (3).toString (); if (prevItemId == rssQuery.value (1).toInt ()) opmlData.push_back (omplLine); else { prevItemId = rssQuery.value (1).toInt (); omplLine ["Title"] = rssQuery.value (4).toString (); } } while (rssQuery.next ()); QFile file ("firefox.opml"); if (file.open (QIODevice::WriteOnly)) { QXmlStreamWriter streamWriter (&file); streamWriter.setAutoFormatting (true); streamWriter.writeStartDocument (); streamWriter.writeStartElement ("opml"); streamWriter.writeAttribute ("version", "1.0"); streamWriter.writeStartElement ("head"); streamWriter.writeStartElement ("text"); streamWriter.writeEndElement (); streamWriter.writeEndElement (); streamWriter.writeStartElement ("body"); streamWriter.writeStartElement ("outline"); streamWriter.writeAttribute ("text", "Live Bookmarks"); Q_FOREACH (const QVariant& hRowVar, opmlData) { streamWriter.writeStartElement ("outline"); QMap<QString, QVariant> hRow = hRowVar.toMap (); QXmlStreamAttributes attr; attr.append ("title", hRow ["Title"].toString ()); attr.append ("htmlUrl", hRow ["SiteUrl"].toString ()); attr.append ("xmlUrl", hRow ["FeedUrl"].toString ()); attr.append ("text", hRow ["Title"].toString ()); streamWriter.writeAttributes (attr); streamWriter.writeEndElement (); }
bool CODBC_RPCCmd::Send() { Cancel(); SetHasFailed(false); m_HasStatus = false; // make a language command string main_exec_query("declare @STpROCrETURNsTATUS int;\nexec @STpROCrETURNsTATUS="); main_exec_query += GetQuery(); string param_result_query; CMemPot bindGuard; string q_str; if(GetBindParamsImpl().NofParams() > 0) { SQLLEN* indicator = (SQLLEN*) bindGuard.Alloc(GetBindParamsImpl().NofParams() * sizeof(SQLLEN)); if (!x_AssignParams(q_str, main_exec_query, param_result_query, bindGuard, indicator)) { ResetParams(); SetHasFailed(); string err_message = "Cannot assign params." + GetDbgInfo(); DATABASE_DRIVER_ERROR( err_message, 420003 ); } } if(NeedToRecompile()) main_exec_query += " with recompile"; q_str += main_exec_query + ";\nselect STpROCrETURNsTATUS=@STpROCrETURNsTATUS"; if(!param_result_query.empty()) { q_str += ";\nselect " + param_result_query; } switch(SQLExecDirect(GetHandle(), CODBCString(q_str, GetClientEncoding()), SQL_NTS)) { case SQL_SUCCESS: m_HasMoreResults = true; break; case SQL_NO_DATA: m_HasMoreResults = true; /* this is a bug in SQLExecDirect it returns SQL_NO_DATA if status result is the only result of RPC */ m_RowCount = 0; break; case SQL_ERROR: ReportErrors(); ResetParams(); SetHasFailed(); { string err_message = "SQLExecDirect failed." + GetDbgInfo(); DATABASE_DRIVER_ERROR( err_message, 420001 ); } case SQL_SUCCESS_WITH_INFO: ReportErrors(); m_HasMoreResults = true; break; case SQL_STILL_EXECUTING: ReportErrors(); ResetParams(); SetHasFailed(); { string err_message = "Some other query is executing on this connection." + GetDbgInfo(); DATABASE_DRIVER_ERROR( err_message, 420002 ); } case SQL_INVALID_HANDLE: SetHasFailed(); { string err_message = "The statement handler is invalid (memory corruption suspected)." + GetDbgInfo(); DATABASE_DRIVER_ERROR( err_message, 420004 ); } default: ReportErrors(); ResetParams(); SetHasFailed(); { string err_message = "Unexpected error." + GetDbgInfo(); DATABASE_DRIVER_ERROR( err_message, 420005 ); } } SetWasSent(); return true; }
bool CTL_BCPInCmd::Send(void) { unsigned int i; CS_INT datalen = 0; size_t len = 0; char buff[2048]; CheckIsDead(); if ( !WasSent() ) { // we need to init the bcp CheckSFB(blk_init(x_GetSybaseCmd(), CS_BLK_IN, (CS_CHAR*) GetQuery().data(), GetQuery().size()), "blk_init failed", 123001); SetWasSent(); // check what needs to be default CS_DATAFMT fmt; for (i = 0; i < GetBindParamsImpl().NofParams(); i++) { if (GetBindParamsImpl().GetParamStatus(i) != 0) { continue; } SetHasFailed((Check(blk_describe(x_GetSybaseCmd(), i + 1, &fmt)) != CS_SUCCEED)); CHECK_DRIVER_ERROR( HasFailed(), "blk_describe failed (check the number of " "columns in a table)." + GetDbgInfo(), 123002 ); } } SetHasFailed(!x_AssignParams()); CHECK_DRIVER_ERROR( HasFailed(), "Cannot assign the params." + GetDbgInfo(), 123004 ); switch ( Check(blk_rowxfer(x_GetSybaseCmd())) ) { case CS_BLK_HAS_TEXT: for (i = 0; i < GetBindParamsImpl().NofParams(); i++) { if (GetBindParamsImpl().GetParamStatus(i) == 0) continue; CDB_Object& param = *GetBindParamsImpl().GetParam(i); if (param.IsNULL()) { continue; } else if (param.GetType() == eDB_Text || param.GetType() == eDB_Image) { CDB_Stream& par = dynamic_cast<CDB_Stream&> (param); for (datalen = (CS_INT) par.Size(); datalen > 0; datalen -= (CS_INT) len) { len = par.Read(buff, sizeof(buff)); SetHasFailed((Check(blk_textxfer(x_GetSybaseCmd(), (CS_BYTE*) buff, (CS_INT) len, 0) ) == CS_FAIL)); CHECK_DRIVER_ERROR( HasFailed(), "blk_textxfer failed for the text/image field." + GetDbgInfo(), 123005 ); } } } case CS_SUCCEED: ++m_RowCount; return true; default: SetHasFailed(); CHECK_DRIVER_ERROR( HasFailed(), "blk_rowxfer failed." + GetDbgInfo(), 123007 ); } return false; }
SU_PSSMInput::SU_PSSMInput(const BlockMultipleAlignment *b) : bma(b) { // TRACE_MESSAGE("Creating SU_PSSMInput structure"); // encode master masterLength = bma->GetMaster()->Length(); masterNCBIStdaa = new unsigned char[masterLength]; for (unsigned int i=0; i<masterLength; ++i) masterNCBIStdaa[i] = LookupNCBIStdaaNumberFromCharacter(bma->GetMaster()->m_sequenceString[i]); // create PSIMsa PSIMsaDimensions dim; dim.query_length = bma->GetMaster()->Length(); dim.num_seqs = bma->NRows() - 1; // not including master data = PSIMsaNew(&dim); FillInAlignmentData(bma, data); // set up PSIDiagnosticsRequest diag.information_content = false; diag.residue_frequencies = false; diag.weighted_residue_frequencies = false; diag.frequency_ratios = true; // true to match cdtree diag.gapless_column_weights = false; // create PSIBlastOptions PSIBlastOptionsNew(&options); options->nsg_compatibility_mode = false; // false for now, since we're not using a consensus double infoContent = CalculateInformationContent(data, false); if (infoContent > 84 ) options->pseudo_count = 10; else if (infoContent > 55 ) options->pseudo_count = 7; else if (infoContent > 43 ) options->pseudo_count = 5; else if (infoContent > 41.5) options->pseudo_count = 4; else if (infoContent > 40 ) options->pseudo_count = 3; else if (infoContent > 39 ) options->pseudo_count = 2; else options->pseudo_count = 1; #ifdef DEBUG_PSSM CNcbiOfstream ofs("psimsa.txt", IOS_BASE::out | IOS_BASE::app); if (ofs) { // diag.residue_frequencies = true; ofs << "information content: " << setprecision(6) << infoContent << '\n' << "pseudocount: " << options->pseudo_count << '\n' << "query length: " << GetQueryLength() << '\n' << "query: "; for (unsigned int i=0; i<GetQueryLength(); ++i) ofs << LookupCharacterFromNCBIStdaaNumber(GetQuery()[i]); ofs << "\nmatrix name: " << GetMatrixName() << '\n' << "options->pseudo_count: " << options->pseudo_count << '\n' << "options->inclusion_ethresh: " << options->inclusion_ethresh << '\n' << "options->use_best_alignment: " << (int) options->use_best_alignment << '\n' << "options->nsg_compatibility_mode: " << (int) options->nsg_compatibility_mode << '\n' << "options->impala_scaling_factor: " << options->impala_scaling_factor << '\n' << "diag->information_content: " << (int) GetDiagnosticsRequest()->information_content << '\n' << "diag->residue_frequencies: " << (int) GetDiagnosticsRequest()->residue_frequencies << '\n' << "diag->weighted_residue_frequencies: " << (int) GetDiagnosticsRequest()->weighted_residue_frequencies << '\n' << "diag->frequency_ratios: " << (int) GetDiagnosticsRequest()->frequency_ratios << '\n' << "diag->gapless_column_weights: " << (int) GetDiagnosticsRequest()->gapless_column_weights << '\n' << "num_seqs: " << data->dimensions->num_seqs << ", query_length: " << data->dimensions->query_length << '\n'; for (unsigned int row=0; row<=data->dimensions->num_seqs; ++row) { for (unsigned int column=0; column<data->dimensions->query_length; ++column) ofs << LookupCharacterFromNCBIStdaaNumber(data->data[row][column].letter); ofs << '\n'; } for (unsigned int row=0; row<=data->dimensions->num_seqs; ++row) { for (unsigned int column=0; column<data->dimensions->query_length; ++column) ofs << (data->data[row][column].is_aligned ? 'A' : 'U'); ofs << '\n'; } } #endif }
OGRFeature *OGRIDBLayer::GetNextRawFeature() { if( GetQuery() == NULL ) return NULL; /* -------------------------------------------------------------------- */ /* If we are marked to restart then do so, and fetch a record. */ /* -------------------------------------------------------------------- */ ITRow * row = poCurr->NextRow(); if ( ! row ) { delete poCurr; poCurr = NULL; return NULL; } iNextShapeId++; m_nFeaturesRead++; /* -------------------------------------------------------------------- */ /* Create a feature from the current result. */ /* -------------------------------------------------------------------- */ int iField; OGRFeature *poFeature = new OGRFeature( poFeatureDefn ); const ITTypeInfo * poRowType = poCurr->RowType(); int nFieldCount = poRowType->ColumnCount(); for ( iField = 0; iField < nFieldCount; iField++ ) { /* -------------------------------------------------------------------- */ /* Handle FID column */ /* -------------------------------------------------------------------- */ if ( pszFIDColumn != NULL && EQUAL( poRowType->ColumnName( iField ), pszFIDColumn ) ) poFeature->SetFID( atoi( row->Column( iField )->Printable() ) ); /* -------------------------------------------------------------------- */ /* Handle geometry */ /* -------------------------------------------------------------------- */ if( pszGeomColumn != NULL && EQUAL( poRowType->ColumnName( iField ), pszGeomColumn ) ) { OGRGeometry *poGeom = NULL; OGRErr eErr = OGRERR_NONE; ITValue * v = row->Column( iField ); if( ! v->IsNull() && ! bGeomColumnWKB ) { const char *pszGeomText = v->Printable(); if ( pszGeomText != NULL ) eErr = OGRGeometryFactory::createFromWkt((char **) &pszGeomText, poSRS, &poGeom); } else if( ! v->IsNull() && bGeomColumnWKB ) { ITDatum *rv = 0; if ( v->QueryInterface( ITDatumIID, (void **) &rv ) == IT_QUERYINTERFACE_SUCCESS ) { int nLength = rv->DataLength(); unsigned char * wkb = (unsigned char *)rv->Data(); eErr = OGRGeometryFactory::createFromWkb( wkb, poSRS, &poGeom, nLength); rv->Release(); } } v->Release(); if ( eErr != OGRERR_NONE ) { const char *pszMessage; switch ( eErr ) { case OGRERR_NOT_ENOUGH_DATA: pszMessage = "Not enough data to deserialize"; break; case OGRERR_UNSUPPORTED_GEOMETRY_TYPE: pszMessage = "Unsupported geometry type"; break; case OGRERR_CORRUPT_DATA: pszMessage = "Corrupt data"; default: pszMessage = "Unrecognized error"; } CPLError(CE_Failure, CPLE_AppDefined, "GetNextRawFeature(): %s", pszMessage); } if( poGeom != NULL ) { poFeature->SetGeometryDirectly( poGeom ); } continue; } /* -------------------------------------------------------------------- */ /* Transfer regular data fields. */ /* -------------------------------------------------------------------- */ int iOGRField = poFeatureDefn->GetFieldIndex( poRowType->ColumnName( iField ) ); if( iOGRField < 0 ) continue; const char * pszColData = row->Column( iField )->Printable(); if( ! pszColData ) continue; if( poFeatureDefn->GetFieldDefn(iOGRField)->GetType() == OFTBinary ) poFeature->SetField( iOGRField, poRowType->ColumnType( iField )->Size(), (GByte *) pszColData ); else poFeature->SetField( iOGRField, pszColData ); } row->Release(); return poFeature; }
string CModularWebController::HandleWebRequest(const SWebRequest &Request) { if(Request.s_Uri == "/modularapi/patches/get") { // return json for patches auto Tmp = PatchesToJson(m_ModularController->GetPatchManager()); return Tmp; } else if(Request.s_Uri == "/Patches") { std::string Command = GetQuery("Command", Request); std::string SelectedPatchName = GetQuery("SelectedPatch", Request); std::string NewPatchName = GetQuery("PatchName", Request); if(Command=="Load") { if(!SelectedPatchName.empty()) { m_ModularController->LoadPatch(SelectedPatchName); } } else if(Command=="Save") { if(!SelectedPatchName.empty()) { //Save current patch as SelectedPatchName m_ModularController->SavePatch(SelectedPatchName); } } else if(Command=="Clear") { RemoveAll(); } else if(Command=="SaveAs") { if(!NewPatchName.empty()) { //Save current patch as NewPatchName (if it is not empty) m_ModularController->SavePatch(NewPatchName); // UpdatePatchesPage(m_ModularController->GetPatchManager(), *m_WebPageManager); } } } else if(Request.s_Uri == "/ModuleCreation") { std::string Command = GetQuery("Command", Request); std::string ModuleType = GetQuery("SelectedModule", Request); if(Command=="Create" && !ModuleType.empty()) { Create(ModuleType, "");//auto name creation } } else if(Request.s_Uri == "/Connections") { UpdateConnectionsPage(m_ModularController->GetModuleManager(), *m_WebPageManager); } else if(Request.s_Uri == "/Modules") { std::string Command = GetQuery("Command", Request); std::string SelectedModule = GetQuery("SelectedModule", Request); if(Command=="RemoveAll") { RemoveAll(); } else if(Command=="DefaultAll") { m_ModularController->Default(); } else if(Command=="Default") { // TODO defaults on selected module only } else if(Command=="Remove") { if(!SelectedModule.empty()) { m_ModularController->Remove(SelectedModule); } } else if(Command=="Edit") { // Queries are of the form // ParameterName = string value // in order to correctly apply the parameter, first retrieve the current // then update current (which knows the correct type) from string value // then apply it for(auto itQuery : Request.s_Query) { if(itQuery.first!="Command" && itQuery.first!="SelectedModule") { SCmdStackItem Item = m_ModularController->GetCommandStackController().GetCurrent(itQuery.first); Item.ValueFromString(itQuery.second); m_ModularController->GetCommandStackController().Handle(Item); } } } UpdateModuleWebPages(); } return m_WebPageManager->GetPage(Request.s_Uri); }