本文整理汇总了C++中QByteArray类的典型用法代码示例。如果您正苦于以下问题:C++ QByteArray类的具体用法?C++ QByteArray怎么用?C++ QByteArray使用的例子?那么, 这里精选的类代码示例或许可以为您提供帮助。
在下文中一共展示了QByteArray类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C++代码示例。
示例1: helpUrl
bool QgsHelp::urlExists( const QString &url )
{
QUrl helpUrl( url );
QTcpSocket socket;
QgsSettings settings;
bool proxyEnabled = settings.value( QStringLiteral( "proxy/proxyEnabled" ), false ).toBool();
if ( proxyEnabled )
{
QNetworkProxy proxy;
QString proxyHost = settings.value( QStringLiteral( "proxy/proxyHost" ), QString() ).toString();
int proxyPort = settings.value( QStringLiteral( "proxy/proxyPort" ), QString() ).toString().toInt();
QString proxyUser = settings.value( QStringLiteral( "proxy/proxyUser" ), QString() ).toString();
QString proxyPassword = settings.value( QStringLiteral( "proxy/proxyPassword" ), QString() ).toString();
QString proxyTypeString = settings.value( QStringLiteral( "proxy/proxyType" ), QString() ).toString();
if ( proxyTypeString == QLatin1String( "DefaultProxy" ) )
{
QList<QNetworkProxy> proxies = QNetworkProxyFactory::systemProxyForQuery();
if ( !proxies.isEmpty() )
{
proxy = proxies.first();
}
}
else
{
QNetworkProxy::ProxyType proxyType = QNetworkProxy::DefaultProxy;
if ( proxyTypeString == QLatin1String( "Socks5Proxy" ) )
{
proxyType = QNetworkProxy::Socks5Proxy;
}
else if ( proxyTypeString == QLatin1String( "HttpProxy" ) )
{
proxyType = QNetworkProxy::HttpProxy;
}
else if ( proxyTypeString == QLatin1String( "HttpCachingProxy" ) )
{
proxyType = QNetworkProxy::HttpCachingProxy;
}
else if ( proxyTypeString == QLatin1String( "FtpCachingProxy" ) )
{
proxyType = QNetworkProxy::FtpCachingProxy;
}
proxy = QNetworkProxy( proxyType, proxyHost, proxyPort, proxyUser, proxyPassword );
}
socket.setProxy( proxy );
}
socket.connectToHost( helpUrl.host(), 80 );
if ( socket.waitForConnected() )
{
socket.write( "HEAD " + helpUrl.path().toUtf8() + " HTTP/1.1\r\n"
"Host: " + helpUrl.host().toUtf8() + "\r\n\r\n" );
if ( socket.waitForReadyRead() )
{
QByteArray bytes = socket.readAll();
if ( bytes.contains( "200 OK" ) || bytes.contains( "302 Found" ) || bytes.contains( "301 Moved" ) )
{
return true;
}
}
}
return false;
}
示例2: atexit
//
// Load OpenSSL's list of root certificate authorities
//
void PaymentServer::LoadRootCAs(X509_STORE* _store)
{
if (PaymentServer::certStore == NULL)
atexit(PaymentServer::freeCertStore);
else
freeCertStore();
// Unit tests mostly use this, to pass in fake root CAs:
if (_store)
{
PaymentServer::certStore = _store;
return;
}
// Normal execution, use either -rootcertificates or system certs:
PaymentServer::certStore = X509_STORE_new();
// Note: use "-system-" default here so that users can pass -rootcertificates=""
// and get 'I don't like X.509 certificates, don't trust anybody' behavior:
QString certFile = QString::fromStdString(GetArg("-rootcertificates", "-system-"));
if (certFile.isEmpty())
return; // Empty store
QList<QSslCertificate> certList;
if (certFile != "-system-")
{
certList = QSslCertificate::fromPath(certFile);
// Use those certificates when fetching payment requests, too:
QSslSocket::setDefaultCaCertificates(certList);
}
else
certList = QSslSocket::systemCaCertificates ();
int nRootCerts = 0;
const QDateTime currentTime = QDateTime::currentDateTime();
foreach (const QSslCertificate& cert, certList)
{
if (currentTime < cert.effectiveDate() || currentTime > cert.expiryDate()) {
ReportInvalidCertificate(cert);
continue;
}
#if QT_VERSION >= 0x050000
if (cert.isBlacklisted()) {
ReportInvalidCertificate(cert);
continue;
}
#endif
QByteArray certData = cert.toDer();
const unsigned char *data = (const unsigned char *)certData.data();
X509* x509 = d2i_X509(0, &data, certData.size());
if (x509 && X509_STORE_add_cert(PaymentServer::certStore, x509))
{
// Note: X509_STORE_free will free the X509* objects when
// the PaymentServer is destroyed
++nRootCerts;
}
else
{
ReportInvalidCertificate(cert);
continue;
}
}
qDebug() << "PaymentServer::LoadRootCAs : Loaded " << nRootCerts << " root certificates";
// Project for another day:
// Fetch certificate revocation lists, and add them to certStore.
// Issues to consider:
// performance (start a thread to fetch in background?)
// privacy (fetch through tor/proxy so IP address isn't revealed)
// would it be easier to just use a compiled-in blacklist?
// or use Qt's blacklist?
// "certificate stapling" with server-side caching is more efficient
}
示例3: update_CFB
QByteArray AES::update_CFB(const QByteArray &input, bool _encode)
{
uint8_t *in = (uint8_t*)(input.data());
uint8_t *iv = reinterpret_cast<uint8_t *>(aes_iv.data());
uint8_t *key = reinterpret_cast<uint8_t *>(aes_key.data());
QByteArray output;
uint _size = input.size();
int STATE_SIZE = 16;
int offset = 0;
switch(keyLength)
{
default:
case B128: Nk = 4; Nr = 10; break;
case B192: Nk = 6; Nr = 12; break;
case B256: Nk = 8; Nr = 14; break;
}
uint8_t *w = new uint8_t[ Nb * (Nr + 1) * 4 ];
key_expansion(key, w);
uint8_t out[16];
uint8_t xor_out[16];
// for encode
memcpy(xor_out, iv, sizeof(uint8_t) * STATE_SIZE);
while(offset + STATE_SIZE <= _size)
{
if(_encode)
{
cipher(xor_out, out, w);
XOR(out, in, STATE_SIZE, xor_out);
output.append(reinterpret_cast<const char *>(xor_out), STATE_SIZE);
in += STATE_SIZE;
offset += STATE_SIZE;
}else{
if(offset == 0)
{
cipher(iv, out, w);
XOR(out, in, STATE_SIZE, xor_out);
output.append(reinterpret_cast<const char *>(xor_out), STATE_SIZE);
offset += STATE_SIZE;
}
else
{
cipher(in, out, w);
in += STATE_SIZE;
XOR(out, in, STATE_SIZE, xor_out);
output.append(reinterpret_cast<const char *>(xor_out), STATE_SIZE);
offset += STATE_SIZE;
}
}
}
// cipher remains
int remains = _size - offset;
if(_encode){
cipher(xor_out, out, w);
XOR(out, in , remains , xor_out);
output.append(reinterpret_cast<const char*>(xor_out), remains);
}else{
if(offset == 0)
{
cipher(iv, out, w);
XOR(out, in, remains, xor_out);
output.append(reinterpret_cast<const char*>(xor_out), remains);
}else
{
cipher(in ,out ,w);
in += STATE_SIZE;
XOR(out, in , remains, xor_out);
output.append(reinterpret_cast<const char*>(xor_out), remains);
}
}
delete [] w;
output.resize(_size);
return output;
}
示例4: QDialog
//.........这里部分代码省略.........
if (xstart == -std::numeric_limits<double>::infinity()) {
xstart = std::min(0., xend - 1.);
}
if (xend == std::numeric_limits<double>::infinity()) {
xend = std::max(xstart + 1., 1.);
}
_mainLayout = new QVBoxLayout(this);
_mainLayout->setContentsMargins(0, TO_DPIX(3), 0, 0);
_mainLayout->setSpacing(TO_DPIX(2));
setLayout(_mainLayout);
//////File
_fileContainer = new QWidget(this);
_fileLayout = new QHBoxLayout(_fileContainer);
_fileLabel = new Label(tr("File:"), _fileContainer);
_fileLayout->addWidget(_fileLabel);
_fileLineEdit = new LineEdit(_fileContainer);
_fileLineEdit->setPlaceholderText( tr("File path...") );
_fileLineEdit->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Fixed);
_fileLayout->addWidget(_fileLineEdit);
_fileBrowseButton = new Button(_fileContainer);
QPixmap pix;
appPTR->getIcon(NATRON_PIXMAP_OPEN_FILE, &pix);
_fileBrowseButton->setIcon( QIcon(pix) );
QObject::connect( _fileBrowseButton, SIGNAL(clicked()), this, SLOT(open_file()) );
_fileLayout->addWidget(_fileBrowseButton);
_mainLayout->addWidget(_fileContainer);
//////x start value
_startContainer = new QWidget(this);
_startLayout = new QHBoxLayout(_startContainer);
_startLabel = new Label(tr("X start value:"), _startContainer);
_startLayout->addWidget(_startLabel);
_startLineEdit = new LineEdit(_startContainer);
_startLineEdit->setText(QString::number(xstart,'g',10));
_startLineEdit->setToolTip( NATRON_NAMESPACE::convertFromPlainText(tr("The X of the first value in the ASCII file. This can be a python expression."), NATRON_NAMESPACE::WhiteSpaceNormal) );
_startLayout->addWidget(_startLineEdit);
_mainLayout->addWidget(_startContainer);
//////x increment
_incrContainer = new QWidget(this);
_incrLayout = new QHBoxLayout(_incrContainer);
_incrLabel = new Label(tr("X increment:"), _incrContainer);
_incrLayout->addWidget(_incrLabel);
_incrLineEdit = new LineEdit(_incrContainer);
if (xstart == 0. && xend == 1.) {
_incrLineEdit->setText(QString::fromUtf8("1./255"));
} else {
_incrLineEdit->setText(QString::number(1));
}
_incrLineEdit->setToolTip( NATRON_NAMESPACE::convertFromPlainText(tr("The X increment between two consecutive values. This can be a python expression."), NATRON_NAMESPACE::WhiteSpaceNormal) );
_incrLayout->addWidget(_incrLineEdit);
_mainLayout->addWidget(_incrContainer);
//////x end value
if (isExportDialog) {
_endContainer = new QWidget(this);
_endLayout = new QHBoxLayout(_endContainer);
_endLabel = new Label(tr("X end value:"), _endContainer);
_endLabel->setFont( QApplication::font() ); // necessary, or the labels will get the default font size
_endLayout->addWidget(_endLabel);
_endLineEdit = new LineEdit(_endContainer);
_endLineEdit->setText(QString::number(xend,'g',10));
_incrLineEdit->setToolTip( NATRON_NAMESPACE::convertFromPlainText(tr("The X of the last value in the ASCII file. This can be a python expression."), NATRON_NAMESPACE::WhiteSpaceNormal) );
_endLayout->addWidget(_endLineEdit);
_mainLayout->addWidget(_endContainer);
}
////curves columns
for (U32 i = 0; i < curves.size(); ++i) {
CurveColumn column;
column._curve = curves[i];
column._curveContainer = new QWidget(this);
column._curveLayout = new QHBoxLayout(column._curveContainer);
column._curveLabel = new Label( tr("%1 column:").arg( curves[i]->getName() ) );
column._curveLabel->setFont( QApplication::font() ); // necessary, or the labels will get the default font size
column._curveLayout->addWidget(column._curveLabel);
column._curveSpinBox = new SpinBox(column._curveContainer, SpinBox::eSpinBoxTypeInt);
column._curveSpinBox->setValue( (double)i + 1. );
column._curveLayout->addWidget(column._curveSpinBox);
_curveColumns.push_back(column);
_mainLayout->addWidget(column._curveContainer);
}
/////buttons
_buttonBox = new DialogButtonBox(QDialogButtonBox::StandardButtons(QDialogButtonBox::Ok | QDialogButtonBox::Cancel), Qt::Horizontal, this);
QObject::connect( _buttonBox, SIGNAL(rejected()), this, SLOT(reject()) );
QObject::connect( _buttonBox, SIGNAL(accepted()), this, SLOT(accept()) );
_mainLayout->addWidget(_buttonBox);
QSettings settings( QString::fromUtf8(NATRON_ORGANIZATION_NAME), QString::fromUtf8(NATRON_APPLICATION_NAME) );
QByteArray state;
if (isExportDialog) {
state = settings.value( QLatin1String("CurveWidgetExportDialog") ).toByteArray();
} else {
state = settings.value( QLatin1String("CurveWidgetImportDialog") ).toByteArray();
}
if ( !state.isEmpty() ) {
restoreState(state);
}
}
示例5: Q_Q
/*!
\internal
*/
bool QFSFileEnginePrivate::nativeOpen(QIODevice::OpenMode openMode)
{
Q_Q(QFSFileEngine);
if (openMode & QIODevice::Unbuffered) {
int flags = openModeToOpenFlags(openMode);
// Try to open the file in unbuffered mode.
do {
fd = QT_OPEN(fileEntry.nativeFilePath().constData(), flags, 0666);
} while (fd == -1 && errno == EINTR);
// On failure, return and report the error.
if (fd == -1) {
q->setError(errno == EMFILE ? QFile::ResourceError : QFile::OpenError,
qt_error_string(errno));
return false;
}
if (!(openMode & QIODevice::WriteOnly)) {
// we don't need this check if we tried to open for writing because then
// we had received EISDIR anyway.
if (QFileSystemEngine::fillMetaData(fd, metaData)
&& metaData.isDirectory()) {
q->setError(QFile::OpenError, msgOpenDirectory());
QT_CLOSE(fd);
return false;
}
}
// Seek to the end when in Append mode.
if (flags & QFile::Append) {
int ret;
do {
ret = QT_LSEEK(fd, 0, SEEK_END);
} while (ret == -1 && errno == EINTR);
if (ret == -1) {
q->setError(errno == EMFILE ? QFile::ResourceError : QFile::OpenError,
qt_error_string(int(errno)));
return false;
}
}
fh = 0;
} else {
QByteArray fopenMode = openModeToFopenMode(openMode, fileEntry, metaData);
// Try to open the file in buffered mode.
do {
fh = QT_FOPEN(fileEntry.nativeFilePath().constData(), fopenMode.constData());
} while (!fh && errno == EINTR);
// On failure, return and report the error.
if (!fh) {
q->setError(errno == EMFILE ? QFile::ResourceError : QFile::OpenError,
qt_error_string(int(errno)));
return false;
}
if (!(openMode & QIODevice::WriteOnly)) {
// we don't need this check if we tried to open for writing because then
// we had received EISDIR anyway.
if (QFileSystemEngine::fillMetaData(QT_FILENO(fh), metaData)
&& metaData.isDirectory()) {
q->setError(QFile::OpenError, msgOpenDirectory());
fclose(fh);
return false;
}
}
setCloseOnExec(fileno(fh)); // ignore failure
// Seek to the end when in Append mode.
if (openMode & QIODevice::Append) {
int ret;
do {
ret = QT_FSEEK(fh, 0, SEEK_END);
} while (ret == -1 && errno == EINTR);
if (ret == -1) {
q->setError(errno == EMFILE ? QFile::ResourceError : QFile::OpenError,
qt_error_string(int(errno)));
return false;
}
}
fd = -1;
}
closeFileHandle = true;
return true;
}
示例6: QueryResult
void WLQuery::Process()
{
if (!Configuration::HuggleConfiguration->GlobalConfig_Whitelist.size())
{
// there is no whitelist in config for this wiki
Syslog::HuggleLogs->ErrorLog("Unable to process WL request, there is no whitelist server defined");
this->Result = new QueryResult();
this->Result->ErrorMessage = "Invalid URL";
this->Result->Failed = true;
this->Status = Huggle::StatusInError;
return;
}
this->StartTime = QDateTime::currentDateTime();
this->Status = StatusProcessing;
this->Result = new QueryResult();
QUrl url(Configuration::HuggleConfiguration->GlobalConfig_Whitelist
+ "?action=read&wp="
+ Configuration::HuggleConfiguration->Project->WhiteList);
switch (this->Type)
{
case WLQueryType_ReadWL:
break;
case WLQueryType_SuspWL:
url = QUrl(Configuration::HuggleConfiguration->GlobalConfig_Whitelist +
"susp.php?action=insert&" + this->Parameters);
break;
case WLQueryType_WriteWL:
url = QUrl(Configuration::HuggleConfiguration->GlobalConfig_Whitelist + "?action=save&user=" +
QUrl::toPercentEncoding("huggle_" + Configuration::HuggleConfiguration->SystemConfig_Username) +
"&wp=" + Configuration::HuggleConfiguration->Project->WhiteList);
break;
}
QString params = "";
QByteArray data;
if (this->Type == WLQueryType_WriteWL)
{
QString whitelist = "";
int p = 0;
while (p < Configuration::HuggleConfiguration->NewWhitelist.count())
{
if (Configuration::HuggleConfiguration->NewWhitelist.at(p) != "")
{
whitelist += Configuration::HuggleConfiguration->NewWhitelist.at(p) + "|";
}
p++;
}
if (whitelist.endsWith("|"))
{
whitelist = whitelist.mid(0, whitelist.length() - 1);
}
whitelist += "||EOW||";
params = "wl=" + QUrl::toPercentEncoding(whitelist);
data = params.toUtf8();
long size = (long)data.size();
Syslog::HuggleLogs->DebugLog("Sending whitelist data of size: " + QString::number(size) + " byte");
}
QNetworkRequest request(url);
if (this->Type == WLQueryType_ReadWL)
{
this->r = Query::NetworkManager->get(request);
} else
{
request.setHeader(QNetworkRequest::ContentTypeHeader, "application/x-www-form-urlencoded");
this->r = Query::NetworkManager->post(request, data);
}
QObject::connect(this->r, SIGNAL(downloadProgress(qint64,qint64)), this, SLOT(WriteProgress(qint64,qint64)));
QObject::connect(this->r, SIGNAL(uploadProgress(qint64,qint64)), this, SLOT(WriteProgress(qint64,qint64)));
QObject::connect(this->r, SIGNAL(finished()), this, SLOT(Finished()));
QObject::connect(this->r, SIGNAL(readyRead()), this, SLOT(ReadData()));
}
示例7: while
void KJavaAppletServer::slotJavaRequest( const QByteArray& qb )
{
// qb should be one command only without the length string,
// we parse out the command and it's meaning here...
QString cmd;
QStringList args;
int index = 0;
const int qb_size = qb.size();
//get the command code
const char cmd_code = qb[ index++ ];
++index; //skip the next sep
//get contextID
QString contextID;
while( qb[index] != 0 && index < qb_size )
{
contextID += qb[ index++ ];
}
bool ok;
const int ID_num = contextID.toInt( &ok ); // context id or kio job id
/*if (d->locked_context > -1 &&
ID_num != d->locked_context &&
(cmd_code == KJAS_JAVASCRIPT_EVENT ||
cmd_code == KJAS_APPLET_STATE ||
cmd_code == KJAS_APPLET_FAILED))
{
/ * Don't allow requests from other contexts if we're waiting
* on a return value that can trigger JavaScript events
* /
d->java_requests.push_back(qb);
return;
}*/
++index; //skip the sep
if (cmd_code == KJAS_PUT_DATA) {
// rest of the data is for kio put
if (ok) {
KIOJobMap::iterator it = d->kiojobs.find( ID_num );
if (ok && it != d->kiojobs.end()) {
QByteArray qba;
qba = QByteArray::fromRawData(qb.data() + index, qb.size() - index - 1);
it.value()->data(qba);
qba = QByteArray::fromRawData(qb.data() + index, qb.size() - index - 1);
}
kDebug(6100) << "PutData(" << ID_num << ") size=" << qb.size() - index;
} else
kError(6100) << "PutData error " << ok << endl;
return;
}
//now parse out the arguments
while( index < qb_size )
{
int sep_pos = qb.indexOf( (char) 0, index );
if (sep_pos < 0) {
kError(6100) << "Missing separation byte" << endl;
sep_pos = qb_size;
}
//kDebug(6100) << "KJavaAppletServer::slotJavaRequest: "<< QString::fromLocal8Bit( qb.data() + index, sep_pos - index );
args.append( QString::fromLocal8Bit( qb.data() + index, sep_pos - index ) );
index = sep_pos + 1; //skip the sep
}
//here I should find the context and call the method directly
//instead of emitting signals
switch( cmd_code )
{
case KJAS_SHOW_DOCUMENT:
cmd = QLatin1String( "showdocument" );
break;
case KJAS_SHOW_URLINFRAME:
cmd = QLatin1String( "showurlinframe" );
break;
case KJAS_SHOW_STATUS:
cmd = QLatin1String( "showstatus" );
break;
case KJAS_RESIZE_APPLET:
cmd = QLatin1String( "resizeapplet" );
break;
case KJAS_GET_URLDATA:
if (ok && !args.empty() ) {
d->kiojobs.insert(ID_num, new KJavaDownloader(ID_num, args.first()));
kDebug(6100) << "GetURLData(" << ID_num << ") url=" << args.first();
} else
kError(6100) << "GetURLData error " << ok << " args:" << args.size() << endl;
return;
case KJAS_PUT_URLDATA:
if (ok && !args.empty()) {
KJavaUploader* const job = new KJavaUploader(ID_num, args.first());
d->kiojobs.insert(ID_num, job);
job->start();
kDebug(6100) << "PutURLData(" << ID_num << ") url=" << args.first();
} else
kError(6100) << "PutURLData error " << ok << " args:" << args.size() << endl;
return;
case KJAS_DATA_COMMAND:
if (ok && !args.empty()) {
//.........这里部分代码省略.........
示例8: qDebug
QString chromaprinter::calcFingerPrint(SoundSourceProxy& soundSource){
soundSource.open();
m_SampleRate = soundSource.getSampleRate();
unsigned int length = soundSource.length();
if (m_SampleRate == 0 ){
qDebug() << "Skipping invalid file:" << soundSource.getFilename();
return QString();
}
// this is worth 2min of audio, multiply by 2 because we have 2 channels
// AcoustID only stores a fingerprint for the first two minutes of a song
// on their server so we need only a fingerprint of the first two minutes
// --kain88 July 2012
m_NumSamples = 120*2*m_SampleRate;
// check that the song is actually longer then the amount of audio we use
if (m_NumSamples > length) {
m_NumSamples = length;
}
SAMPLE *pData = new SAMPLE[m_NumSamples];
QTime timerReadingFile;
timerReadingFile.start();
unsigned int read = soundSource.read(m_NumSamples, pData);
if (read!=m_NumSamples) {
qDebug() << "oh that's embarrasing I couldn't read the track";
return QString();
}
qDebug("reading file took: %d ms" , timerReadingFile.elapsed());
ChromaprintContext* ctx = chromaprint_new(CHROMAPRINT_ALGORITHM_DEFAULT);
// we have 2 channels in mixxx always
chromaprint_start(ctx, m_SampleRate, 2);
QTime timerGeneratingFingerPrint;
timerGeneratingFingerPrint.start();
int success = chromaprint_feed(ctx, pData, m_NumSamples);
if (!success) {
qDebug() << "could not generate fingerprint";
delete pData;
return QString();
}
chromaprint_finish(ctx);
void* fprint = NULL;
int size = 0;
int ret = chromaprint_get_raw_fingerprint(ctx, &fprint, &size);
QByteArray fingerprint;
if (ret == 1) {
void* encoded = NULL;
int encoded_size = 0;
chromaprint_encode_fingerprint(fprint, size,
CHROMAPRINT_ALGORITHM_DEFAULT,
&encoded,
&encoded_size, 1);
fingerprint.append(reinterpret_cast<char*>(encoded), encoded_size);
chromaprint_dealloc(fprint);
chromaprint_dealloc(encoded);
}
chromaprint_free(ctx);
delete pData;
qDebug("generating fingerprint took: %d ms" , timerGeneratingFingerPrint.elapsed());
return fingerprint;
}
示例9: progress
void
DownloadJob::onDownloadProgress( qint64 rcvd, qint64 total )
{
if ( m_reply == 0 )
return;
if ( rcvd >= m_fileSize && m_fileSize > 0 )
{
m_finished = true;
}
if ( state() == Paused )
return;
m_rcvdSize = rcvd;
m_fileSize = total;
qint64 now = QDateTime::currentDateTime().toMSecsSinceEpoch();
if ( ( now - 50 > m_rcvdStamp ) || ( rcvd == total ) )
{
m_rcvdStamp = now;
if ( ( m_rcvdSize - 16384 > m_rcvdEmit ) || ( rcvd == total ) )
{
m_rcvdEmit = m_rcvdSize;
emit progress( progressPercentage() );
}
}
if ( !m_file )
return;
if ( !m_file->isOpen() )
{
if ( m_tryResuming && checkForResumedFile() )
return;
if ( !m_file->open( QIODevice::WriteOnly ) )
{
tLog() << Q_FUNC_INFO << "Failed opening file:" << m_file->fileName();
setState( Failed );
return;
}
}
QByteArray data = m_reply->readAll();
if ( data.isEmpty() )
return;
if ( m_file->write( data ) < 0 )
{
tLog() << Q_FUNC_INFO << "Failed writing to file:" << data.length();
onDownloadError( QNetworkReply::UnknownContentError );
return;
}
if ( m_rcvdSize >= m_fileSize && m_fileSize > 0 )
{
onDownloadFinished();
}
else if ( m_reply->isFinished() && m_reply->bytesAvailable() == 0 )
{
if ( ( m_fileSize > 0 && m_rcvdSize < m_fileSize ) || m_rcvdSize == 0 )
{
onDownloadError( QNetworkReply::UnknownContentError );
return;
}
}
}
示例10: readClient
void ServerSocketInterface::readClient()
{
QByteArray data = socket->readAll();
servatrice->incRxBytes(data.size());
inputBuffer.append(data);
do {
if (!messageInProgress) {
if (inputBuffer.size() >= 4) {
messageLength = (((quint32) (unsigned char) inputBuffer[0]) << 24)
+ (((quint32) (unsigned char) inputBuffer[1]) << 16)
+ (((quint32) (unsigned char) inputBuffer[2]) << 8)
+ ((quint32) (unsigned char) inputBuffer[3]);
inputBuffer.remove(0, 4);
messageInProgress = true;
} else
return;
}
if (inputBuffer.size() < messageLength)
return;
CommandContainer newCommandContainer;
try {
newCommandContainer.ParseFromArray(inputBuffer.data(), messageLength);
}
catch(std::exception &e) {
qDebug() << "Caught std::exception in" << __FILE__ << __LINE__ <<
#ifdef _MSC_VER // Visual Studio
__FUNCTION__;
#else
__PRETTY_FUNCTION__;
#endif
qDebug() << "Exception:" << e.what();
qDebug() << "Message coming from:" << getAddress();
qDebug() << "Message length:" << messageLength;
qDebug() << "Message content:" << inputBuffer.toHex();
}
catch(...) {
qDebug() << "Unhandled exception in" << __FILE__ << __LINE__ <<
#ifdef _MSC_VER // Visual Studio
__FUNCTION__;
#else
__PRETTY_FUNCTION__;
#endif
qDebug() << "Message coming from:" << getAddress();
}
inputBuffer.remove(0, messageLength);
messageInProgress = false;
// dirty hack to make v13 client display the correct error message
if (handshakeStarted)
processCommandContainer(newCommandContainer);
else if (!newCommandContainer.has_cmd_id()) {
handshakeStarted = true;
if (!initSession())
prepareDestroy();
}
// end of hack
} while (!inputBuffer.isEmpty());
}
示例11: getActualPositions
//! Returns a collection of information of the players, enemies, eggs and collectables that are sent periodically to the client.
QByteArray* LogicEngine::getActualPositions()
{
QByteArray* positions = new QByteArray;
positions->append( (char) level->getEnemies()->size() );
for(int i = 0; i < level->getEnemies()->size(); i++)
{
// ID
positions->append( '\0' ); // ID ANCORA DA FARE
// X COORDINATE
int x = level->getEnemies()->at(i)->getX();
int t1 = x / (256);
int t2 = x % (256);
positions->append( (char) t1 );
positions->append( (char) t2 );
// Y COORDINATE
x = level->getEnemies()->at(i)->getY();
t1 = x / 256;
t2 = x % 256;
positions->append( (char) t1 );
positions->append( (char) t2 );
// REST
positions->append( (char) level->getEnemies()->at(i)->getDirectionX() );
positions->append( (char) level->getEnemies()->at(i)->getDirectionY() );
positions->append( (char) level->getEnemies()->at(i)->isVisible() );
}
int players = 0;
for(int i = 0; i < clientList->size(); i++)
{
if(clientList->at(i)->player != NULL)
players++;
}
positions->append( (char) players );
for(int i = 0; i < clientList->size(); i++)
{
if(clientList->at(i)->player == NULL)
continue;
// ID
positions->append( (char) clientList->at(i)->id );
// X COORDINATE
int x = clientList->at(i)->player->getX();
int t1 = x / 256;
int t2 = x % 256;
positions->append( (char) t1 );
positions->append( (char) t2 );
// Y COORDINATE
x = clientList->at(i)->player->getY();
if(x < 0)
{
x *= -1;
x += 1000;
}
t1 = x / 256;
t2 = x % 256;
positions->append( (char) t1 );
positions->append( (char) t2 );
// REST
int dirX = 0;
if (clientList->at(i)->player->getVelocityX() != 0){
dirX = clientList->at(i)->player->getDirectionX();
}
positions->append( (char) dirX );
positions->append( (char) clientList->at(i)->player->getDirectionY() );
positions->append( (char) clientList->at(i)->player->getLife() );
// Points
x = clientList->at(i)->player->getPoints();
t1 = x / 256;
t2 = x % 256;
positions->append( (char) t1 );
positions->append( (char) t2 );
positions->append( (char) clientList->at(i)->player->getEggs() );
//.........这里部分代码省略.........
示例12: runTimingTests
//.........这里部分代码省略.........
qCDebug(interfaceapp, "usleep(1000) ms: %f", (double)(elapsedUsecs / 1000.0f));
startTime.start();
usleep(15000);
elapsedUsecs = (float)startTime.nsecsElapsed() * NSEC_TO_USEC;
qCDebug(interfaceapp, "usleep(15000) ms: %f", (double)(elapsedUsecs / 1000.0f));
// Random number generation
startTime.start();
for (int i = 0; i < numTests; i++) {
iResults[i] = rand();
}
elapsedUsecs = (float)startTime.nsecsElapsed() * NSEC_TO_USEC;
qCDebug(interfaceapp, "rand() stored in array usecs: %f, first result:%d",
(double)(elapsedUsecs / numTests), iResults[0]);
// Random number generation using randFloat()
startTime.start();
for (int i = 0; i < numTests; i++) {
fResults[i] = randFloat();
}
elapsedUsecs = (float)startTime.nsecsElapsed() * NSEC_TO_USEC;
qCDebug(interfaceapp, "randFloat() stored in array usecs: %f, first result: %f",
(double)(elapsedUsecs / numTests), (double)(fResults[0]));
free(iResults);
free(fResults);
// PowF function
fTest = 1145323.2342f;
startTime.start();
for (int i = 0; i < numTests; i++) {
fTest = powf(fTest, 0.5f);
}
elapsedUsecs = (float)startTime.nsecsElapsed() * NSEC_TO_USEC;
qCDebug(interfaceapp, "powf(f, 0.5) usecs: %f", (double)(elapsedUsecs / (float) numTests));
// Vector Math
float distance;
glm::vec3 pointA(randVector()), pointB(randVector());
startTime.start();
for (int i = 0; i < numTests; i++) {
//glm::vec3 temp = pointA - pointB;
//float distanceSquared = glm::dot(temp, temp);
distance = glm::distance(pointA, pointB);
}
elapsedUsecs = (float)startTime.nsecsElapsed() * NSEC_TO_USEC;
qCDebug(interfaceapp, "vector math usecs: %f [%f usecs total for %d tests], last result:%f",
(double)(elapsedUsecs / (float) numTests), (double)elapsedUsecs, numTests, (double)distance);
// Vec3 test
glm::vec3 vecA(randVector()), vecB(randVector());
float result;
startTime.start();
for (int i = 0; i < numTests; i++) {
glm::vec3 temp = vecA-vecB;
result = glm::dot(temp,temp);
}
elapsedUsecs = (float)startTime.nsecsElapsed() * NSEC_TO_USEC;
qCDebug(interfaceapp, "vec3 assign and dot() usecs: %f, last result:%f",
(double)(elapsedUsecs / numTests), (double)result);
quint64 BYTE_CODE_MAX_TEST_VALUE = 99999999;
quint64 BYTE_CODE_TESTS_SKIP = 999;
QByteArray extraJunk;
const int EXTRA_JUNK_SIZE = 200;
extraJunk.append((unsigned char)255);
for (int i = 0; i < EXTRA_JUNK_SIZE; i++) {
extraJunk.append(QString("junk"));
}
{
startTime.start();
quint64 tests = 0;
quint64 failed = 0;
for (quint64 value = 0; value < BYTE_CODE_MAX_TEST_VALUE; value += BYTE_CODE_TESTS_SKIP) {
quint64 valueA = value; // usecTimestampNow();
ByteCountCoded<quint64> codedValueA = valueA;
QByteArray codedValueABuffer = codedValueA;
codedValueABuffer.append(extraJunk);
ByteCountCoded<quint64> decodedValueA;
decodedValueA.decode(codedValueABuffer);
quint64 valueADecoded = decodedValueA;
tests++;
if (valueA != valueADecoded) {
qDebug() << "FAILED! value:" << valueA << "decoded:" << valueADecoded;
failed++;
}
}
elapsedUsecs = (float)startTime.nsecsElapsed() * NSEC_TO_USEC;
qCDebug(interfaceapp) << "ByteCountCoded<quint64> usecs: " << elapsedUsecs
<< "per test:" << (double) (elapsedUsecs / tests)
<< "tests:" << tests
<< "failed:" << failed;
}
}
示例13: QByteArray
void XByteArray::setData(QByteArray data)
{
_data = data;
_changedData = QByteArray(data.length(), char(0));
}
示例14: fileInfo
void FileWatcher::saveFile(QString file) {
QFileInfo fileInfo(file);
// If we have a dbi import file
QLOG_DEBUG() << fileInfo.dir().absolutePath() + QDir::separator();
QLOG_DEBUG() << global.fileManager.getDbiDirPath();
if ((fileInfo.dir().absolutePath() + QDir::separator()) == global.fileManager.getDbiDirPath()) {
BatchImport importer;
importer.import(file);
emit(nnexImported());
QFile f(file);
f.remove();
return;
}
// If we have a user-import file
QFile f(file);
f.open(QIODevice::ReadOnly);
QByteArray data = f.readAll();
f.close();
if (f.size() == 0)
return;
Note newNote;
NoteTable ntable(global.db);
ConfigStore cs(global.db);
qint32 lid = cs.incrementLidCounter();
QCryptographicHash md5hash(QCryptographicHash::Md5);
QByteArray hash = md5hash.hash(data, QCryptographicHash::Md5);
// * Start setting up the new note
newNote.guid = QString::number(lid);
newNote.title = file;
NotebookTable bookTable(global.db);
QString notebook;
bookTable.getGuid(notebook, notebookLid);
newNote.notebookGuid = notebook;
QString newNoteBody = QString("<?xml version=\"1.0\" encoding=\"UTF-8\"?>")+
QString("<!DOCTYPE en-note SYSTEM \"http://xml.evernote.com/pub/enml2.dtd\">")+
QString("<en-note style=\"word-wrap: break-word; -webkit-nbsp-mode: space; -webkit-line-break: after-white-space;\">");
MimeReference mimeRef;
QString mime = mimeRef.getMimeFromFileName(file);
QString enMedia =QString("<en-media hash=\"") +hash.toHex() +QString("\" border=\"0\"")
+QString(" type=\"" +mime +"\" ")
+QString("/>");
newNoteBody.append(enMedia + QString("</en-note>"));
newNote.content = newNoteBody;
newNote.active = true;
newNote.created = QDateTime::currentMSecsSinceEpoch();;
newNote.updated = newNote.created;
newNote.updateSequenceNum = 0;
NoteAttributes na;
na.sourceURL = "file://" + file;
newNote.attributes = na;
qint32 noteLid = lid;
ntable.add(lid, newNote, true);
QString noteGuid = ntable.getGuid(lid);
lid = cs.incrementLidCounter();
// Start creating the new resource
Resource newRes;
Data d;
d.body = data;
d.bodyHash = hash;
d.size = data.size();
newRes.data = d;
newRes.mime = mime;
ResourceAttributes ra;
ra.fileName = file;
if (mime.startsWith("image", Qt::CaseInsensitive) || mime.endsWith("pdf", Qt::CaseInsensitive))
ra.attachment = false;
else
ra.attachment = true;
newRes.active = true;
newRes.guid = QString::number(lid);
newRes.noteGuid = noteGuid;
newRes.updateSequenceNum = 0;
ResourceTable restable(global.db);
restable.add(lid, newRes, true, noteLid);
emit(fileImported(noteLid, lid));
if (scanType == FileWatcher::ImportDelete) {
QLOG_DEBUG() << f.remove();
}
}
示例15: qDebug
//
// Update Headpose in Game.
//
void FTNServer::sendHeadposeToGame() {
int no_bytes;
QHostAddress sender;
quint16 senderPort;
//
// Create UDP-sockets if they don't exist already.
// They must be created here, because they must be in the Tracker thread (Tracker::run())
//
if (inSocket == 0) {
qDebug() << "FTNServer::sendHeadposeToGame creating sockets";
inSocket = new QUdpSocket();
// Connect the inSocket to the port, to receive messages
if (!inSocket->bind(QHostAddress::Any, destPort+1)) {
qDebug() << "FTNServer::writePendingDatagrams says: unable to bind inSocket!";
delete inSocket;
inSocket = 0;
}
}
if (outSocket == 0) {
outSocket = new QUdpSocket();
}
//
// Copy the Raw measurements directly to the client.
//
TestData.x = virtPosX;
TestData.y = virtPosY;
TestData.z = virtPosZ;
TestData.pitch = virtRotX;
TestData.yaw = virtRotY;
TestData.roll = virtRotZ;
//
// Try to send an UDP-message to the receiver
//
//! [1]
no_bytes = outSocket->writeDatagram((const char *) &TestData, sizeof( TestData ), destIP, destPort);
if ( no_bytes > 0) {
// qDebug() << "FTNServer::writePendingDatagrams says: bytes send =" << no_bytes << sizeof( double );
}
else {
qDebug() << "FTNServer::writePendingDatagrams says: nothing sent!";
}
//
// Receiver may send data, so we must read that here.
//
if (inSocket != 0) {
while (inSocket->hasPendingDatagrams()) {
QByteArray datagram;
datagram.resize(inSocket->pendingDatagramSize());
inSocket->readDatagram( (char * ) &cmd, sizeof(cmd), &sender, &senderPort);
fg_cmd = cmd; // Let's just accept that command for now...
if ( cmd > 0 ) {
qDebug() << "FTNServer::sendHeadposeToGame hasPendingDatagrams, cmd = " << cmd;
headTracker->handleGameCommand ( cmd ); // Send it upstream, for the Tracker to handle
}
}
}
}