Exemplo n.º 1
0
void CDataParser::WriteSerial( CWinSerialPort *pSerial, char cCmd[ ], int nCmdLen )
{
    ControlSerialPort( pSerial, true );

    QByteArray byCmd;
    byCmd.append( cCmd, nCmdLen );

    CSerialEvent* pEvent = new CSerialEvent( QEvent::User );
    bool bWineSerial = ( pSerial == pWineSerialPort );
    pEvent->SetSerialData( byCmd,  bWineSerial ? 1 : 0 );
    QApplication::postEvent( &g_serialThread, pEvent );

    return;

    int nCount = byCmd.count( );
    Win_QextSerialPort& rawSerial = pSerial->GetRawSerialPort( );

    if ( rawSerial.isWritable( ) ) {
        bool bRet = ( nCount == rawSerial.write( byCmd ) );
        rawSerial.flush( );
#ifndef QT_NO_DEBUG
        QString strData( byCmd.toHex( ) );
        qDebug( ) << "Write Serial Port Cmd : " << strData << endl;
#endif

       Sleep( 300 );
    }
}
Exemplo n.º 2
0
bool CWriteThread::WriteData( CWinSerialPort* pWinPort, QByteArray &byData )
{
    bool bRet = false;
    if ( NULL == pWinPort  ) {
        return bRet;
    }

    int nCount = byData.count( );
    Win_QextSerialPort& rawSerial = pWinPort->GetRawSerialPort( );

    if ( rawSerial.isWritable( ) ) {
        bRet = ( nCount == rawSerial.write( byData ) );
        rawSerial.flush( );
#ifndef QT_NO_DEBUG
        QString strData( byData.toHex( ) );
        qDebug( ) << "Write Serial Port Cmd : " << strData << endl;
#endif
#if false
        int nDelay = 700;
        if ( 8 >= nCount ) {
            nDelay = 100;
        } else if ( 8 < nCount && 16 >= nCount ) {
            nDelay = 200;
        } else {
            nDelay = 300;
        }
#endif

       Sleep( 300 );
    }

    return bRet;
}
Exemplo n.º 3
0
void CLog::LogString(int logLevel, std::string&& logString)
{
  CSingleLock waitLock(g_logState.critSec);
  std::string strData(logString);
  StringUtils::TrimRight(strData);
  if (!strData.empty())
  {
    if (g_logState.m_repeatLogLevel == logLevel && g_logState.m_repeatLine == strData)
    {
      g_logState.m_repeatCount++;
      return;
    }
    else if (g_logState.m_repeatCount)
    {
      std::string strData2 = StringUtils::Format("Previous line repeats %d times.",
                                                g_logState.m_repeatCount);
      PrintDebugString(strData2);
      WriteLogString(g_logState.m_repeatLogLevel, strData2);
      g_logState.m_repeatCount = 0;
    }

    g_logState.m_repeatLine = strData;
    g_logState.m_repeatLogLevel = logLevel;

    PrintDebugString(strData);

    WriteLogString(logLevel, strData);
  }
}
Exemplo n.º 4
0
std::string ByteStream::readString(int length){
	char* readData = new char[length + 1];
	mainStream.read(readData, length);
	std::string strData(readData, length);
	delete[] readData;
	return strData;
}
Exemplo n.º 5
0
HRESULT CMainFrameDropTarget::PasteText(CLIPFORMAT cfData, COleDataObject& data)
{
    HRESULT hrPasteResult = E_FAIL;
    HANDLE hMem;
    if ((hMem = data.GetGlobalData(cfData)) != NULL)
    {
        LPCSTR pszUrlA;
        if ((pszUrlA = (LPCSTR)GlobalLock(hMem)) != NULL)
        {
            // skip white space
            while (isspace((unsigned char)*pszUrlA))
                pszUrlA++;

            hrPasteResult = S_FALSE; // default: nothing was pasted
            if (_strnicmp(pszUrlA, "ed2k://|", 8) == 0)
            {
                CString strData(pszUrlA);
                int iPos = 0;
                CString str = strData.Tokenize(_T("\r\n"), iPos);
                while (!str.IsEmpty())
                {
                    theApp.emuledlg->ProcessED2KLink(str);
                    hrPasteResult = S_OK;
                    str = strData.Tokenize(_T("\r\n"), iPos);
                }
            }

            GlobalUnlock(hMem);
        }
        GlobalFree(hMem);
    }
    return hrPasteResult;
}
Exemplo n.º 6
0
		/*
		 *gets the xml, decode it and process it
		 */
		void Employee::doJob(uchar* data , HttpLineInterperter *resConfiguration)
		{
			//convert the bytes data into string
			//assuming the srcEncoding and encoding are the same type
			string strData((char *)data , resConfiguration->getContentLength());
			cout<<"GOT the XML:"<<endl;
			cout<<strData<<endl;
			JobXMLParser xmlDecoder(strData);
			xmlDecoder.parseXML();
			xmlDecoder.parseDocument();
			Job &job = xmlDecoder.getJob();
			cout<<"A"<<endl;
			this->socket_.close();
			this->connect();
			bool flag;
			flag = job.download(*(this) , resConfiguration);
			if (flag)
			{
				job.process();
				this->socket_.close();
				this->connect();
				job.upload(*(this) , resConfiguration);

			}
		}
Exemplo n.º 7
0
	DataArray2D<std::string> TableauHtmlVersDataArray(const std::string &strSource)
	{
		int posDebutTableau=strSource.find("<table");
		int posFinTableau=strSource.find("</table>");

		int nbLigne=Utils::String::Count(strSource, "</tr>", posDebutTableau, posFinTableau);
		//int nbCellule=Utils::String::Count(strSource, "</td>", posDebutTableau, posFinTableau);

		StringArray ligneArray=Utils::String::GetArrayOfBetween(strSource, "<tr", "</tr>", posDebutTableau, posFinTableau);

		int nbColonne=0;
		for(unsigned int i=0; i<ligneArray.size(); i++)
		{
			int tempCol=Utils::String::Count(ligneArray.at(i), "</td>",0);
			nbColonne=(tempCol>nbColonne)?tempCol:nbColonne;
		}

		DataArray2D<std::string> tableauDeDonnnees(nbLigne, nbColonne);
		for(unsigned int i=0; i<ligneArray.size(); i++)
		{
			//todo: éviter de recalculer ! c'est des vecteur après tout ! (merge des deux boucles)
			StringArray colArray=Utils::String::GetArrayOfBetween(ligneArray.at(i), "<td", "</td>");
			for(unsigned int j=0; j<colArray.size(); j++)
			{
				std::string strData(Utils::Html::HtmlDecode(Utils::Html::RemoveHtmlTag("<td"+colArray.at(j)+"</td>"))); // Remove html crap and extract data
				tableauDeDonnnees.AjouterDonnees(i,j, strData);
			}
		}
		return tableauDeDonnnees;
	}
QString WallpapersWideProvider::GetRandomPage(const QString &url)
{
    // get first page
    QByteArray data = Utils::GetDataFromUrl(url, "wallpaperswide.com", "http://wallpaperswide.com");
    QString strData(data);

    // find number of pages
    int numberOfPages = 0;
    QRegExp rxPageNumber("/page/(\\d+)\">");
    int pos = 0;
    while ((pos = rxPageNumber.indexIn(strData, pos)) != -1)
    {
        int page = rxPageNumber.cap(1).toInt();
        if (page > numberOfPages) numberOfPages = page;
        pos += rxPageNumber.matchedLength();
    }

    // get random page
    if (numberOfPages > 0)
    {
        int randomPage = (_randomGenerator.get() % numberOfPages) + 1;
        QString randomUrl = url;
        randomUrl.remove(".html");
        randomUrl.append("/page/");
        randomUrl.append(QString::number(randomPage));

        data = Utils::GetDataFromUrl(randomUrl, "wallpaperswide.com", "http://wallpaperswide.com");
        strData = QString::fromUtf8(data.data());
    }

    return strData;
}
Exemplo n.º 9
0
double GetDoubleData( char* psData, int nSize, int nDotPos )
{
	CString strData( psData, nSize );
	// 소숫점이 찍히지 않은 데이터이므로 nDotPos 위치에 점을 찍는다.
	strData.Insert( strData.GetLength() - nDotPos, '.' );

	return atof(strData);
}
Exemplo n.º 10
0
CString GetDispData( TCHAR* psData, int nSize, int nType, int nDotPos )
{
	CString strData( psData, nSize );

	// Raw 데이터를 보여주지 않을때는 SPACE, 숫자앞의 0, 그리고 소숫점을 추가한다.
	if( g_bShowRaw == FALSE )
	{
		//-----------------------------------------------------------------------
		// 문자열 : 뒷부분의 Space 제거
		if( nType == DATA_TYPE_STRING )
		{
			strData.TrimRight();
		}

		//-----------------------------------------------------------------------
		// 정수 : 앞의 0 을 제거. 쉽게 하기 위해 정수로 변환후 다시 문자로 변환
		else if( nType == DATA_TYPE_LONG )
		{
			CString strTemp;
			strTemp.Format( "%d", atoi( strData ) );
			strData = strTemp;
		}

		//-----------------------------------------------------------------------
		// 실수 : 앞의 0 을 제거. 쉽게 하기 위해 실수로 변환후 다시 nDotPos 만큼 표시
		else if( nType == DATA_TYPE_FLOAT )
		{
			// 소숫점이 찍히지 않은 데이터이므로 nDotPos 위치에 점을 찍는다.
			strData.Insert( strData.GetLength() - nDotPos, '.' );

			// 소숫점 이하를 nDotPos 만큼 표시하기 위해 format을 만든다.
			CString strFormat;
			strFormat.Format( "%%.%df", nDotPos );
			CString strTemp;
			strTemp.Format( strFormat, atof( strData ) );
			strData = strTemp;
		}

		//-----------------------------------------------------------------------
		// 실수 : 앞의 0 을 제거. 쉽게 하기 위해 실수로 변환후 다시 nDotPos 만큼 표시
		else if( nType == DATA_TYPE_FLOAT_DOT )
		{
			// 소숫점이 찍혀있다
			int nFind = strData.Find( "." );
			nDotPos = strData.GetLength() - nFind - 1;

			// 소숫점 이하를 nDotPos 만큼 표시하기 위해 format을 만든다.
			CString strFormat;
			strFormat.Format( "%%.%df", nDotPos );
			CString strTemp;
			strTemp.Format( strFormat, atof( strData ) );
			strData = strTemp;
		}
	}

	return strData;
}
Exemplo n.º 11
0
// static
bool OTKeyring::KWallet_RetrieveSecret(const OTString& strUser,
                                       OTPassword& thePassword,
                                       const std::string& str_display)
{
    OT_ASSERT(strUser.Exists());

    KWallet::Wallet* pWallet = OTKeyring::OpenKWallet();

    if (nullptr != pWallet) {
        const QString qstrKey(strUser.Get());
        QString qstrPwd;

        // Get the password
        //
        if (pWallet->readPassword(qstrKey, qstrPwd) == 0) {
            const std::string str_password =
                qstrPwd.toStdString(); // todo security: notice str_password
                                       // isn't zero'd here.

            OTString strData(str_password);
            OTASCIIArmor ascData;

            const bool bLoaded =
                strData.Exists() && ascData.LoadFromString(strData);
            strData.zeroMemory();

            if (!bLoaded)
                otErr << __FUNCTION__ << ": Failed trying to decode secret "
                                         "from KWallet contents.\n";
            else {
                OTData thePayload(ascData);
                ascData.zeroMemory();
                if (thePayload.IsEmpty())
                    otErr << __FUNCTION__ << ": Failed trying to decode secret "
                                             "OTData from OTASCIIArmor from "
                                             "KWallet contents.\n";
                else {
                    thePassword.setMemory(thePayload.GetPayloadPointer(),
                                          thePayload.GetSize());
                    thePayload.zeroMemory(); // for security.
                    return true;
                }
            }
        }
        else
            otErr << __FUNCITON__
                  << ": Failed trying to retrieve secret from KWallet.\n";
    }

    // Not an error: what if it just hasn't been set there yet?
    //
    otWarn << "OTKeyring::KWallet_RetrieveSecret: No secret found.\n";

    return false;
}
Exemplo n.º 12
0
/*
   SaveForbid - принудительно запретить запись добавляемой строки.
                Используется на панели плагина
*/
void History::AddToHistory(const string& Str, history_record_type Type, const GUID* Guid, const wchar_t *File, const wchar_t *Data, bool SaveForbid)
{
	_ASSERTE(this!=NULL);
	if (!m_EnableAdd || SaveForbid)
		return;

	if (Global->CtrlObject->Macro.IsExecuting() && Global->CtrlObject->Macro.IsHistoryDisable((int)m_TypeHistory))
		return;

	if (m_TypeHistory!=HISTORYTYPE_DIALOG && (m_TypeHistory!=HISTORYTYPE_FOLDER || !Guid || *Guid == FarGuid) && Str.empty())
		return;

	bool Lock = false;
	string strName(Str),strGuid,strFile(NullToEmpty(File)),strData(NullToEmpty(Data));
	if(Guid) strGuid=GuidToStr(*Guid);

	unsigned __int64 DeleteId = 0;

	const bool ignore_data = m_TypeHistory == HISTORYTYPE_CMD;

	if (m_RemoveDups) // удалять дубликаты?
	{
		DWORD index=0;
		string strHName,strHGuid,strHFile,strHData;
		history_record_type HType;
		bool HLock;
		unsigned __int64 id;
		unsigned __int64 Time;
		while (HistoryCfgRef()->Enum(index++,m_TypeHistory,m_HistoryName,&id,strHName,&HType,&HLock,&Time,strHGuid,strHFile,strHData))
		{
			if (EqualType(Type,HType))
			{
				typedef int (*CompareFunction)(const string&, const string&);
				CompareFunction CaseSensitive = StrCmp, CaseInsensitive = StrCmpI;
				CompareFunction CmpFunction = (m_RemoveDups == 2 ? CaseInsensitive : CaseSensitive);

				if (!CmpFunction(strName, strHName) &&
					!CmpFunction(strGuid, strHGuid) &&
					!CmpFunction(strFile, strHFile) &&
					(ignore_data || !CmpFunction(strData, strHData)))
				{
					Lock = Lock || HLock;
					DeleteId = id;
					break;
				}
			}
		}
	}

	HistoryCfgRef()->DeleteAndAddAsync(DeleteId, m_TypeHistory, m_HistoryName, strName, Type, Lock, strGuid, strFile, strData);  //Async - should never be used in a transaction

	ResetPosition();
}
Exemplo n.º 13
0
bool CWin32InterfaceForCLog::WriteStringToLog(const std::string& logString)
{
    if (m_hFile == INVALID_HANDLE_VALUE)
        return false;

    std::string strData(logString);
    StringUtils::Replace(strData, "\n", "\r\n");
    strData += "\r\n";

    DWORD written;
    const bool ret = (WriteFile(m_hFile, strData.c_str(), strData.length(), &written, NULL) != 0) && written == strData.length();

    return ret;
}
Exemplo n.º 14
0
IniFileSections
parseIniFile (std::string const& strInput, const bool bTrim)
{
    std::string strData (strInput);
    std::vector<std::string> vLines;
    IniFileSections secResult;

    // Convert DOS format to unix.
    boost::algorithm::replace_all (strData, "\r\n", "\n");

    // Convert MacOS format to unix.
    boost::algorithm::replace_all (strData, "\r", "\n");

    boost::algorithm::split (vLines, strData,
        boost::algorithm::is_any_of ("\n"));

    // Set the default Section name.
    std::string strSection  = SECTION_DEFAULT_NAME;

    // Initialize the default Section.
    secResult[strSection]   = IniFileSections::mapped_type ();

    // Parse each line.
    for (auto& strValue : vLines)
    {
        if (strValue.empty () || strValue[0] == '#')
        {
            // Blank line or comment, do nothing.
        }
        else if (strValue[0] == '[' && strValue[strValue.length () - 1] == ']')
        {
            // New Section.
            strSection              = strValue.substr (1, strValue.length () - 2);
            secResult.emplace(strSection, IniFileSections::mapped_type{});
        }
        else
        {
            // Another line for Section.
            if (bTrim)
                boost::algorithm::trim (strValue);

            if (!strValue.empty ())
                secResult[strSection].push_back (strValue);
        }
    }

    return secResult;
}
Exemplo n.º 15
0
void EffectRack::startDrag(int idx)
{
    FILE* tmp = tmpfile();
    if (tmp == 0)
    {
        fprintf(stderr, "EffectRack::startDrag fopen failed: %s\n",
                strerror(errno));
        return;
    }
    Xml xml(tmp);
    Pipeline* pipe = track->efxPipe();
    if (pipe)
    {
        int size = pipe->size();
        if (idx < size)
        {
            xml.header();
            xml.tag(0, "oom version=\"2.0\"");
            (*pipe)[idx]->writeConfiguration(1, xml);
            xml.tag(0, "/oom");
        }
        else
        {
            //printf("no plugin!\n");
            return;
        }
    }
    else
    {
        //printf("no pipe!\n");
        return;
    }

    QString xmlconf;
    xml.dump(xmlconf);

    QByteArray data(xmlconf.toLatin1().constData());
    QString strData(data);
    //qDebug("EffectRack::startDrag: Generated Drag Copy data:\n%s",strData.toUtf8().constData());
    QMimeData* md = new QMimeData();

    md->setData("text/x-oom-plugin", data);

    QDrag* drag = new QDrag(this);
    drag->setMimeData(md);

    drag->exec(Qt::CopyAction);
}
Exemplo n.º 16
0
 inline void decodeTypedElements( Text *, T *, DataPtr &data, T *t, int nCount)
 {
     if (data.length() == 0)
     {
         RCF_THROW(RCF::Exception(RCF::SfError_DataFormat));
     }
     std::string strData(reinterpret_cast<char *>(data.get()), data.length());
     std::istringstream istr(strData);
     istr >> t[0];
     for (int i=1; i<nCount; i++)
     {
         char ch;
         istr.get(ch);
         RCF_ASSERT( ch == chSeparator );
         istr >> t[i];
     }
 }
Exemplo n.º 17
0
void _stdcall OnNotifyKLineData( char * caStockNo, char * caData )
{
	if( m_nType == 3 )
	{
		CString strStockNo(caStockNo);
		CString strData(caData);

		CString strMsg;
		strMsg.Format(_T("%s %s"),strStockNo,strData);

		
		BSTR bstrMsg = strMsg.AllocSysString();

		SendMessage(FindWindow(NULL,_T("QuoteTester")),WM_DATA,m_nType,(int)bstrMsg);
		
		SysFreeString(bstrMsg);
	}
}
Exemplo n.º 18
0
PIN_KeyboardKeyComboSet* PIN_KeyboardManager::BuildComboSet(PIN_String comboData)
{
    std::string strData(comboData);

    std::string::const_iterator start, end;
    start = strData.begin();
    end = strData.end();
    boost::match_results<std::string::const_iterator> what;
    boost::match_flag_type flags = boost::match_default;

    PIN_KeyboardKeyComboSet* newSet = new PIN_KeyboardKeyComboSet();
    std::string strComboString("");

    while(regex_search(start, end, what, _keyListRegex, flags))
    {
        std::string strX  = what[0].str();

        SDL_Scancode code = SDL_GetScancodeFromName(strX.c_str());

        strComboString+=std::string(start,what[0].first) + PIN_KEYFORMAT;
        newSet->ComboKeys.push_back(code);

        // update search position:
        start = what[0].second;
        // update flags:
        flags |= boost::match_prev_avail;
        flags |= boost::match_not_bob;
    }
    strComboString+=std::string(start,end);

    newSet->ComboString = new char[PIN_MAXBUFFER_SIZE];
    memset(newSet->ComboString,0,PIN_MAXBUFFER_SIZE);
    strcat(newSet->ComboString,strComboString.c_str());

    if(newSet->ComboKeys.size() > 0)
    {
        return newSet;
    }
    else
    {
        return NULL;
    }
}
Exemplo n.º 19
0
String File::GetContents(std::fstream & fileStream)
{
	assert(fileStream.is_open());
	fileStream.seekg( 0, std::ios::beg);
	int start  = (int) fileStream.tellg();
	fileStream.seekg( 0, std::ios::end );
	int fileSize = (int) fileStream.tellg();
	// Empty file?
	if (fileSize == 0)
		return String();
	assert(fileSize);
	char * data = new char [fileSize+2];
	memset(data, 0, fileSize+1);
	fileStream.seekg( 0, std::ios::beg);
	fileStream.read((char*) data, fileSize);
	String strData(data);
	delete[] data;
	return strData;
}
Exemplo n.º 20
0
static int curl_trace(CURL *curl, curl_infotype type, char *data, size_t size, void *opaque)
{
    const char *text = "";
    switch (type) {
        case CURLINFO_TEXT:         text = "== Info"; break;
        case CURLINFO_HEADER_IN:    text = "<= Recv headers"; break;
        case CURLINFO_HEADER_OUT:   text = "=> Send headers"; break;
        case CURLINFO_DATA_IN:      text = "<= Recv data"; break;
        case CURLINFO_DATA_OUT:     text = "=> Send data"; break;
        case CURLINFO_SSL_DATA_IN:  text = "<= Recv SSL data"; break;
        case CURLINFO_SSL_DATA_OUT: text = "=> Send SSL data"; break;
        default:
            RAWLOG_INFO1("!! Unknown type of curl trace: %d", (int)type);
            return 0;
    }
    
    String strData(data, size);
    RAWLOG_INFO3("%s (%d bytes): %s", text, size, strData.c_str());
    return 0;
}
Exemplo n.º 21
0
TEST_F(CmMessageBlockTest, FillIovTest)
{
    char szBuff[512] = { 0 };
    m_pMsgBlock = new CCmMessageBlock(512, szBuff,0,0);

    ASSERT_TRUE(NULL != m_pMsgBlock);

    char szData[] = "hello, world!!!";
    DWORD dwDataLen = strlen(szData);

    EXPECT_TRUE(CM_OK == m_pMsgBlock->Write(szData, dwDataLen));

    iovec aIov[1];
    DWORD aMax = 1;

    DWORD dwFilled = m_pMsgBlock->FillIov(aIov, aMax);
    EXPECT_EQ(aMax, dwFilled);

    CCmString strData((const char*)aIov[0].iov_base);
    EXPECT_STREQ(szData, strData.c_str());
}
Exemplo n.º 22
0
 static CString LegalizePath(const CString &strPath)
 {
     CString strOriginPath = strPath;
     CString strData(strOriginPath);
     CString strFolderPath;
     CString strDstPath;
     while (1)
     {
         strFolderPath = GetRootPath(strData);
         if (strFolderPath == _T(".."))
             strDstPath = GetParsentFolder(strDstPath);
         else
             strDstPath.Append(strFolderPath);
         PathAddBackslash(strDstPath);
         strData = strData.Mid(strFolderPath.GetLength());
         strData.TrimLeft(L"\\");
         if (strData.IsEmpty())
             break;
     }
     return strDstPath;
 }
Exemplo n.º 23
0
static size_t write_callback(void *ptr, size_t size, size_t nmemb, void *userp)
{
    BtcRpcPacket *pooh = (BtcRpcPacket *)userp;

    int newSize = size * nmemb;

    if(size < 1)
        return 0;

    const char *charBuf = static_cast<const char*>(ptr);
    std::vector<char> data(charBuf, charBuf + newSize);
    std::string strData(data.begin(), data.end());

    if (pooh->AddData(strData))
    {
        return newSize;
    }
    else
    {
        return 0;
    }

    //int newLength = pooh->size + size * nmemb;

    //if(pooh->data == NULL)
    //    pooh->data = (char*)realloc(pooh->data, newLength + 1);

    //if(pooh->data == NULL)
    //{
    //    std::printf("realloc failed when reading data from bitcoin-qt\n");
    //    std::cout.flush();
    //    return 0;
    //}

    //memcpy(pooh->data + pooh->size, ptr, size * nmemb);
    //pooh->data[newLength] = '\0';
    //pooh->size = newLength;

    //return size * nmemb;
}
Exemplo n.º 24
0
bool CLog::WriteLogString(int logLevel, const std::string& logString)
{
  static const char* prefixFormat = "%02d:%02d:%02d.%03d T:%" PRIu64" %7s: ";

  std::string strData(logString);
  /* fixup newline alignment, number of spaces should equal prefix length */
  StringUtils::Replace(strData, "\n", "\n                                            ");

  int hour, minute, second;
  double millisecond;
  g_logState.m_platform.GetCurrentLocalTime(hour, minute, second, millisecond);

  strData = StringUtils::Format(prefixFormat,
                                  hour,
                                  minute,
                                  second,
                                  static_cast<int>(millisecond),
                                  (uint64_t)CThread::GetDisplayThreadId(CThread::GetCurrentThreadId()),
                                  levelNames[logLevel]) + strData;

  return g_logState.m_platform.WriteStringToLog(strData);
}
Exemplo n.º 25
0
  boost::any   DDLIndexPopulator::convertData(const erydbSystemCatalog::ColType&  colType, const execplan::ColumnResult* cr, int idx )
  {
    uint64_t data = cr->GetData(idx);  
    switch( colType.colDataType )
    {
      case erydbSystemCatalog::BIT: 
      case execplan::erydbSystemCatalog::TINYINT:    return  *reinterpret_cast<char*>(&data);
      case execplan::erydbSystemCatalog::SMALLINT:   return  *reinterpret_cast<short*>(&data);
      case execplan::erydbSystemCatalog::DATE:	// @bug 375
      case execplan::erydbSystemCatalog::MEDINT:
      case execplan::erydbSystemCatalog::INT:        return  *reinterpret_cast<int*>(&data);
      case execplan::erydbSystemCatalog::DATETIME: 	// @bug 375
      case execplan::erydbSystemCatalog::BIGINT:     return  *reinterpret_cast<long long*>(&data);
      case execplan::erydbSystemCatalog::DECIMAL:  
      {
	  if (colType.colWidth <= erydbSystemCatalog::FOUR_BYTE) return  *reinterpret_cast<short*>(&data);

	  else if (colType.colWidth <= 9)              return  *reinterpret_cast<int*>(&data);

	  else                                         return  *reinterpret_cast<long long*>(&data);
       }

      case execplan::erydbSystemCatalog::FLOAT:      return  *reinterpret_cast<float*>(&data);
      case execplan::erydbSystemCatalog::DOUBLE:     return  *reinterpret_cast<double*>(&data);
      case execplan::erydbSystemCatalog::CHAR:      
      case execplan::erydbSystemCatalog::VARCHAR:   
      {
	  string  strData(cr->GetStringData(idx) );  
	  return  *reinterpret_cast<string*>(&strData);
      }
      default: break;
    }
    logError("Invalid column type");
    throw std::runtime_error("Invalid data");

    return *reinterpret_cast<long long*>(&data);
     
  }
Exemplo n.º 26
0
QString WallpapersWideProvider::GetBestImageUrl(WallpaperParameters parameters, QString imageName)
{
    QString resolutionsUrl = QString("http://wallpaperswide.com/") +
            imageName + QString(".html");
    QByteArray data = Utils::GetDataFromUrl(resolutionsUrl, "wallpaperswide.com", "http://wallpaperswide.com");
    QString strData(data);

    // remove 's' from end of the name ("-wallpapers")
    if (imageName.endsWith("wallpapers"))
    {
        imageName.remove(imageName.length() - 1, 1);
    }

    // iterate through resolutions
    QList<QSize> listOfResolutions;
    QRegExp rxResolution(QRegExp::escape(imageName) + "-(\\d+)x(\\d+).jpg\"");
    int pos = 0;
    while ((pos = rxResolution.indexIn(strData, pos)) != -1)
    {
        int width = rxResolution.cap(1).toInt();
        int height = rxResolution.cap(2).toInt();
        pos += rxResolution.matchedLength();

        listOfResolutions.push_back(QSize(width, height));
    }

    QSize bestResolution = Utils::ChooseBestResolution(listOfResolutions, parameters.prefferedWidth, parameters.prefferedHeight);

    return QString("http://wallpaperswide.com/download/") +
            imageName +
            QString("-") +
            QString::number(bestResolution.width()) +
            QString("x") +
            QString::number(bestResolution.height()) +
            QString(".jpg");
}
Exemplo n.º 27
0
CString GetStringData( char* psData, int nSize)
{
	CString strData(psData, nSize);
	strData.Trim();
	return strData;
}
Exemplo n.º 28
0
double GetDotDoubleData( char* psData, int nSize)
{
	CString strData( psData, nSize );
	return atof(strData);
}
Exemplo n.º 29
0
long GetLongData( char* psData, int nSize)
{
	CString strData( psData, nSize );
	return atoi( strData );
	
}
Exemplo n.º 30
0
// static
bool OTKeyring::Gnome_RetrieveSecret(const OTString& strUser,
                                     OTPassword& thePassword,
                                     const std::string& str_display)
{
    OT_ASSERT(strUser.Exists());

    GnomeKeyringResult theResult = GNOME_KEYRING_RESULT_IO_ERROR;
    gchar* gchar_p_password = nullptr;

    // if the password exists in the keyring, set it in
    // thePassword (output argument.)
    //
    int32_t nCount = -1;
    int64_t lSleep = 1;

    while ((GNOME_KEYRING_RESULT_OK != theResult)) {
        ++nCount; // 0 on first iteration.

        theResult = gnome_keyring_find_password_sync(
            GNOME_KEYRING_NETWORK_PASSWORD, &gchar_p_password, "user",
            strUser.Get(), "protocol", "opentxs", // todo: hardcoding.
            nullptr);

        if (GNOME_KEYRING_RESULT_OK == theResult) break;

        if (nCount > 2) // todo hardcoding.
            break;      // we try a few times -- not infinite times!

        OTString strGnomeError(gnome_keyring_result_to_message(theResult));

        //        OTString strGnomeError;
        //        switch (theResult) {
        //            case GNOME_KEYRING_RESULT_OK: strGnomeError
        // = "GNOME_KEYRING_RESULT_OK"; break;
        //            case GNOME_KEYRING_RESULT_DENIED: strGnomeError
        // = "GNOME_KEYRING_RESULT_DENIED"; break;
        //            case GNOME_KEYRING_RESULT_NO_KEYRING_DAEMON: strGnomeError
        // = "GNOME_KEYRING_RESULT_NO_KEYRING_DAEMON"; break;
        //            case GNOME_KEYRING_RESULT_ALREADY_UNLOCKED: strGnomeError
        // = "GNOME_KEYRING_RESULT_ALREADY_UNLOCKED"; break;
        //            case GNOME_KEYRING_RESULT_NO_SUCH_KEYRING: strGnomeError
        // = "GNOME_KEYRING_RESULT_NO_SUCH_KEYRING"; break;
        //            case GNOME_KEYRING_RESULT_BAD_ARGUMENTS: strGnomeError
        // = "GNOME_KEYRING_RESULT_BAD_ARGUMENTS"; break;
        //            case GNOME_KEYRING_RESULT_IO_ERROR: strGnomeError
        // = "GNOME_KEYRING_RESULT_IO_ERROR"; break;
        //            case GNOME_KEYRING_RESULT_CANCELLED: strGnomeError
        // = "GNOME_KEYRING_RESULT_CANCELLED"; break;
        //            case GNOME_KEYRING_RESULT_KEYRING_ALREADY_EXISTS:
        // strGnomeError = "GNOME_KEYRING_RESULT_KEYRING_ALREADY_EXISTS"; break;
        //            case GNOME_KEYRING_RESULT_NO_MATCH: strGnomeError
        // = "GNOME_KEYRING_RESULT_NO_MATCH"; break;
        //
        //            default:
        //                strGnomeError = "Unknown! Very strange!";
        //                break;
        //        }

        otErr << __FUNCTION__ << ": gnome_keyring_find_password_sync returned "
              << strGnomeError.Get() << '\n';
        otErr << "Remedy: Sleeping for " << lSleep
              << " seconds and then retrying (attempt " << (nCount + 2) << '\n';
        // on first iteration, nCount is 0, and this will say "attempt 2" aka
        // "second attempt," which is correct.

        sleep(lSleep);
        lSleep *= 2; // double it each time
    }

    if ((theResult == GNOME_KEYRING_RESULT_OK) &&
        (nullptr != gchar_p_password)) {
        size_t sizePassword =
            OTString::safe_strlen(gchar_p_password, MAX_STRING_LENGTH);

        if (sizePassword > 0) {
            OTString strData(gchar_p_password, sizePassword);

            gnome_keyring_free_password(gchar_p_password);
            gchar_p_password = nullptr;

            OTASCIIArmor ascData;
            const bool bLoaded =
                strData.Exists() && ascData.LoadFromString(strData);
            strData.zeroMemory();

            if (!bLoaded)
                otErr << __FUNCTION__ << ": Failed trying to decode secret "
                                         "from Gnome Keyring contents:\n\n"
                      << strData.Get() << "\n\n";
            else {
                OTData thePayload(ascData);
                ascData.zeroMemory();
                if (thePayload.IsEmpty())
                    otErr << __FUNCTION__ << ": Failed trying to decode secret "
                                             "OTData from OTASCIIArmor "
                          << "from Gnome Keyring contents:\n\n" << strData.Get()
                          << "\n\n";
                else {
                    thePassword.setMemory(thePayload.GetPayloadPointer(),
                                          thePayload.GetSize());
                    thePayload.zeroMemory(); // for security.
                    return true;
                }
                return false;
            }
        }
    }

    // Not an error: what if it just hasn't been set there yet?
    //
    otOut << "OTKeyring::Gnome_RetrieveSecret: "
          << "No secret found: gnome_keyring_find_password_sync: "
          << gnome_keyring_result_to_message(theResult) << '\n';

    return false;
}