本文整理汇总了C++中QByteArray::resize方法的典型用法代码示例。如果您正苦于以下问题:C++ QByteArray::resize方法的具体用法?C++ QByteArray::resize怎么用?C++ QByteArray::resize使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类QByteArray
的用法示例。
在下文中一共展示了QByteArray::resize方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C++代码示例。
示例1: fieldData
QVariant MacProtocol::fieldData(int index, FieldAttrib attrib,
int streamIndex) const
{
switch (index)
{
case mac_dstAddr:
{
int u;
quint64 dstMac = 0;
switch (data.dst_mac_mode())
{
case OstProto::Mac::e_mm_fixed:
dstMac = data.dst_mac();
break;
case OstProto::Mac::e_mm_inc:
u = (streamIndex % data.dst_mac_count()) *
data.dst_mac_step();
dstMac = data.dst_mac() + u;
break;
case OstProto::Mac::e_mm_dec:
u = (streamIndex % data.dst_mac_count()) *
data.dst_mac_step();
dstMac = data.dst_mac() - u;
break;
case OstProto::Mac::e_mm_resolve:
if (forResolve_)
dstMac = 0;
else {
forResolve_ = true;
dstMac = mpStream->neighborMacAddress(streamIndex);
forResolve_ = false;
}
break;
default:
qWarning("Unhandled dstMac_mode %d", data.dst_mac_mode());
}
switch(attrib)
{
case FieldName:
return QString("Desination");
case FieldValue:
return dstMac;
case FieldTextValue:
return uintToMacStr(dstMac);
case FieldFrameValue:
{
QByteArray fv;
fv.resize(8);
qToBigEndian(dstMac, (uchar*) fv.data());
fv.remove(0, 2);
return fv;
}
default:
break;
}
break;
}
case mac_srcAddr:
{
int u;
quint64 srcMac = 0;
switch (data.src_mac_mode())
{
case OstProto::Mac::e_mm_fixed:
srcMac = data.src_mac();
break;
case OstProto::Mac::e_mm_inc:
u = (streamIndex % data.src_mac_count()) *
data.src_mac_step();
srcMac = data.src_mac() + u;
break;
case OstProto::Mac::e_mm_dec:
u = (streamIndex % data.src_mac_count()) *
data.src_mac_step();
srcMac = data.src_mac() - u;
break;
case OstProto::Mac::e_mm_resolve:
if (forResolve_)
srcMac = 0;
else {
forResolve_ = true;
srcMac = mpStream->deviceMacAddress(streamIndex);
forResolve_ = false;
}
break;
default:
qWarning("Unhandled srcMac_mode %d", data.src_mac_mode());
}
switch(attrib)
{
case FieldName:
return QString("Source");
case FieldValue:
return srcMac;
case FieldTextValue:
return uintToMacStr(srcMac);
//.........这里部分代码省略.........
示例2: endQuote
//.........这里部分代码省略.........
QString tmp = *it;
// escape a single " because the arguments will be parsed
tmp.replace( QLatin1Char('\"'), QLatin1String("\\\"") );
if ( tmp.isEmpty() || tmp.contains( QLatin1Char(' ') ) || tmp.contains( QLatin1Char('\t') ) ) {
// The argument must not end with a \ since this would be interpreted
// as escaping the quote -- rather put the \ behind the quote: e.g.
// rather use "foo"\ than "foo\"
QString endQuote( QLatin1String("\"") );
int i = tmp.length();
while ( i>0 && tmp.at( i-1 ) == QLatin1Char('\\') ) {
--i;
endQuote += QLatin1Char('\\');
}
args += QLatin1String(" \"") + tmp.left( i ) + endQuote;
} else {
args += QLatin1Char(' ') + tmp;
}
}
#if defined(QT_Q3PROCESS_DEBUG)
qDebug( "Q3Process::start(): args [%s]", args.latin1() );
#endif
// CreateProcess()
bool success;
d->newPid();
STARTUPINFOW startupInfo = {
sizeof( STARTUPINFO ), 0, 0, 0,
(ulong)CW_USEDEFAULT, (ulong)CW_USEDEFAULT, (ulong)CW_USEDEFAULT, (ulong)CW_USEDEFAULT,
0, 0, 0,
STARTF_USESTDHANDLES,
0, 0, 0,
d->pipeStdin[0], d->pipeStdout[1], d->pipeStderr[1]
};
wchar_t *applicationName;
if ( appName.isNull() )
applicationName = 0;
else
applicationName = _wcsdup( (wchar_t*)appName.utf16() );
wchar_t *commandLine = _wcsdup( (wchar_t*)args.utf16() );
QByteArray envlist;
if ( env != 0 ) {
int pos = 0;
// add PATH if necessary (for DLL loading)
QByteArray path = qgetenv( "PATH" );
if ( env->grep( QRegExp(QLatin1String("^PATH="),FALSE) ).empty() && !path.isNull() ) {
QString tmp = QString::fromLatin1("PATH=%1").arg(QLatin1String(path.constData()));
uint tmpSize = sizeof(wchar_t) * (tmp.length() + 1);
envlist.resize( envlist.size() + tmpSize );
memcpy( envlist.data() + pos, tmp.utf16(), tmpSize );
pos += tmpSize;
}
// add the user environment
for ( QStringList::Iterator it = env->begin(); it != env->end(); it++ ) {
QString tmp = *it;
uint tmpSize = sizeof(wchar_t) * (tmp.length() + 1);
envlist.resize( envlist.size() + tmpSize );
memcpy( envlist.data() + pos, tmp.utf16(), tmpSize );
pos += tmpSize;
}
// add the 2 terminating 0 (actually 4, just to be on the safe side)
envlist.resize( envlist.size()+4 );
envlist[pos++] = 0;
envlist[pos++] = 0;
envlist[pos++] = 0;
envlist[pos++] = 0;
}
success = CreateProcess( applicationName, commandLine,
0, 0, TRUE, ( comms == 0 ? CREATE_NEW_CONSOLE : CREATE_NO_WINDOW )
#ifndef Q_OS_WINCE
| CREATE_UNICODE_ENVIRONMENT
#endif
, env == 0 ? 0 : envlist.data(),
(wchar_t*)QDir::toNativeSeparators(workingDir.absPath()).utf16(),
&startupInfo, d->pid );
free( applicationName );
free( commandLine );
if ( !success ) {
d->deletePid();
return false;
}
#ifndef Q_OS_WINCE
if ( comms & Stdin )
CloseHandle( d->pipeStdin[0] );
if ( comms & Stdout )
CloseHandle( d->pipeStdout[1] );
if ( (comms & Stderr) && !(comms & DupStderr) )
CloseHandle( d->pipeStderr[1] );
#endif
if ( ioRedirection || notifyOnExit ) {
d->lookup->start( 100 );
}
// cleanup and return
return true;
}
示例3: addGlyphs
void QPF::addGlyphs(QFontEngine *fe, const QList<CharacterRange> &ranges)
{
const quint16 glyphCount = fe->glyphCount();
QByteArray gmap;
gmap.resize(glyphCount * sizeof(quint32));
gmap.fill(char(0xff));
//qDebug() << "glyphCount" << glyphCount;
QByteArray glyphs;
if (options & RenderGlyphs) {
// this is only a rough estimation
glyphs.reserve(glyphCount
* (sizeof(QFontEngineQPF::Glyph)
+ qRound(fe->maxCharWidth() * (fe->ascent() + fe->descent()).toReal())));
QGlyphLayoutArray<10> layout;
foreach (CharacterRange range, ranges) {
if (debugVerbosity > 2)
qDebug() << "rendering range from" << range.start << "to" << range.end;
for (uint uc = range.start; uc <= range.end; ++uc) {
QChar ch(uc);
int nglyphs = 10;
if (!fe->stringToCMap(&ch, 1, &layout, &nglyphs, /*flags*/ 0))
continue;
if (nglyphs != 1)
continue;
const quint32 glyphIndex = layout.glyphs[0];
if (!glyphIndex)
continue;
Q_ASSERT(glyphIndex < glyphCount);
QImage img = fe->alphaMapForGlyph(glyphIndex).convertToFormat(QImage::Format_Indexed8);
glyph_metrics_t metrics = fe->boundingBox(glyphIndex);
const quint32 oldSize = glyphs.size();
glyphs.resize(glyphs.size() + sizeof(QFontEngineQPF::Glyph) + img.byteCount());
uchar *data = reinterpret_cast<uchar *>(glyphs.data() + oldSize);
uchar *gmapPtr = reinterpret_cast<uchar *>(gmap.data() + glyphIndex * sizeof(quint32));
qToBigEndian(oldSize, gmapPtr);
QFontEngineQPF::Glyph *glyph = reinterpret_cast<QFontEngineQPF::Glyph *>(data);
glyph->width = img.width();
glyph->height = img.height();
glyph->bytesPerLine = img.bytesPerLine();
glyph->x = qRound(metrics.x);
glyph->y = qRound(metrics.y);
glyph->advance = qRound(metrics.xoff);
data += sizeof(QFontEngineQPF::Glyph);
if (debugVerbosity && uc >= 'A' && uc <= 'z' || debugVerbosity > 1) {
qDebug() << "adding glyph with index" << glyphIndex << " uc =" << char(uc) << ":\n"
<< " glyph->x =" << glyph->x << "rounded from" << metrics.x << "\n"
<< " glyph->y =" << glyph->y << "rounded from" << metrics.y << "\n"
<< " width =" << glyph->width << "height =" << glyph->height
<< " advance =" << glyph->advance << "rounded from" << metrics.xoff
;
}
memcpy(data, img.bits(), img.byteCount());
}
}
}
示例4: sizeof
void QgsSimpleLine3DSymbolHandler::makeEntity( Qt3DCore::QEntity *parent, const Qgs3DRenderContext &context, LineData &out, bool selected )
{
if ( out.indexes.isEmpty() )
return;
// material (only ambient color is used for the color)
Qt3DExtras::QPhongMaterial *mat = _material( mSymbol );
if ( selected )
{
// update the material with selection colors
mat->setAmbient( context.map().selectionColor() );
}
// geometry renderer
QByteArray vertexBufferData;
vertexBufferData.resize( out.vertices.size() * 3 * sizeof( float ) );
float *rawVertexArray = reinterpret_cast<float *>( vertexBufferData.data() );
int idx = 0;
for ( const auto &v : qgis::as_const( out.vertices ) )
{
rawVertexArray[idx++] = v.x();
rawVertexArray[idx++] = v.y();
rawVertexArray[idx++] = v.z();
}
QByteArray indexBufferData;
indexBufferData.resize( out.indexes.size() * sizeof( int ) );
unsigned int *rawIndexArray = reinterpret_cast<unsigned int *>( indexBufferData.data() );
idx = 0;
for ( unsigned int indexVal : qgis::as_const( out.indexes ) )
{
rawIndexArray[idx++] = indexVal;
}
Qt3DCore::QEntity *entity = new Qt3DCore::QEntity;
Qt3DRender::QBuffer *vertexBuffer = new Qt3DRender::QBuffer( Qt3DRender::QBuffer::VertexBuffer, entity );
vertexBuffer->setData( vertexBufferData );
Qt3DRender::QBuffer *indexBuffer = new Qt3DRender::QBuffer( Qt3DRender::QBuffer::IndexBuffer, entity );
indexBuffer->setData( indexBufferData );
Qt3DRender::QAttribute *positionAttribute = new Qt3DRender::QAttribute( entity );
positionAttribute->setAttributeType( Qt3DRender::QAttribute::VertexAttribute );
positionAttribute->setBuffer( vertexBuffer );
positionAttribute->setVertexBaseType( Qt3DRender::QAttribute::Float );
positionAttribute->setVertexSize( 3 );
positionAttribute->setName( Qt3DRender::QAttribute::defaultPositionAttributeName() );
Qt3DRender::QAttribute *indexAttribute = new Qt3DRender::QAttribute( entity );
indexAttribute->setAttributeType( Qt3DRender::QAttribute::IndexAttribute );
indexAttribute->setBuffer( indexBuffer );
indexAttribute->setVertexBaseType( Qt3DRender::QAttribute::UnsignedInt );
Qt3DRender::QGeometry *geom = new Qt3DRender::QGeometry;
geom->addAttribute( positionAttribute );
geom->addAttribute( indexAttribute );
Qt3DRender::QGeometryRenderer *renderer = new Qt3DRender::QGeometryRenderer;
renderer->setPrimitiveType( Qt3DRender::QGeometryRenderer::LineStrip );
renderer->setGeometry( geom );
renderer->setVertexCount( out.vertices.count() );
renderer->setPrimitiveRestartEnabled( true );
renderer->setRestartIndexValue( 0 );
// make entity
entity->addComponent( renderer );
entity->addComponent( mat );
entity->setParent( parent );
}
示例5: unpackUpdate
void PsUpdateDownloader::unpackUpdate() {
QByteArray packed;
if (!outputFile.open(QIODevice::ReadOnly)) {
LOG(("Update Error: cant read updates file!"));
return fatalFail();
}
#ifdef Q_OS_WIN // use Lzma SDK for win
const int32 hSigLen = 128, hShaLen = 20, hPropsLen = LZMA_PROPS_SIZE, hOriginalSizeLen = sizeof(int32), hSize = hSigLen + hShaLen + hPropsLen + hOriginalSizeLen; // header
#else
const int32 hSigLen = 128, hShaLen = 20, hPropsLen = 0, hOriginalSizeLen = sizeof(int32), hSize = hSigLen + hShaLen + hOriginalSizeLen; // header
#endif
QByteArray compressed = outputFile.readAll();
int32 compressedLen = compressed.size() - hSize;
if (compressedLen <= 0) {
LOG(("Update Error: bad compressed size: %1").arg(compressed.size()));
return fatalFail();
}
outputFile.close();
QString tempDirPath = cWorkingDir() + qsl("tupdates/temp"), readyDirPath = cWorkingDir() + qsl("tupdates/ready");
deleteDir(tempDirPath);
deleteDir(readyDirPath);
QDir tempDir(tempDirPath), readyDir(readyDirPath);
if (tempDir.exists() || readyDir.exists()) {
LOG(("Update Error: cant clear tupdates/temp or tupdates/ready dir!"));
return fatalFail();
}
uchar sha1Buffer[20];
bool goodSha1 = !memcmp(compressed.constData() + hSigLen, hashSha1(compressed.constData() + hSigLen + hShaLen, compressedLen + hPropsLen + hOriginalSizeLen, sha1Buffer), hShaLen);
if (!goodSha1) {
LOG(("Update Error: bad SHA1 hash of update file!"));
return fatalFail();
}
RSA *pbKey = PEM_read_bio_RSAPublicKey(BIO_new_mem_buf(const_cast<char*>(UpdatesPublicKey), -1), 0, 0, 0);
if (!pbKey) {
LOG(("Update Error: cant read public rsa key!"));
return fatalFail();
}
if (RSA_verify(NID_sha1, (const uchar*)(compressed.constData() + hSigLen), hShaLen, (const uchar*)(compressed.constData()), hSigLen, pbKey) != 1) { // verify signature
RSA_free(pbKey);
LOG(("Update Error: bad RSA signature of update file!"));
return fatalFail();
}
RSA_free(pbKey);
QByteArray uncompressed;
int32 uncompressedLen;
memcpy(&uncompressedLen, compressed.constData() + hSigLen + hShaLen + hPropsLen, hOriginalSizeLen);
uncompressed.resize(uncompressedLen);
size_t resultLen = uncompressed.size();
#ifdef Q_OS_WIN // use Lzma SDK for win
SizeT srcLen = compressedLen;
int uncompressRes = LzmaUncompress((uchar*)uncompressed.data(), &resultLen, (const uchar*)(compressed.constData() + hSize), &srcLen, (const uchar*)(compressed.constData() + hSigLen + hShaLen), LZMA_PROPS_SIZE);
if (uncompressRes != SZ_OK) {
LOG(("Update Error: could not uncompress lzma, code: %1").arg(uncompressRes));
return fatalFail();
}
#else
lzma_stream stream = LZMA_STREAM_INIT;
lzma_ret ret = lzma_stream_decoder(&stream, UINT64_MAX, LZMA_CONCATENATED);
if (ret != LZMA_OK) {
const char *msg;
switch (ret) {
case LZMA_MEM_ERROR: msg = "Memory allocation failed"; break;
case LZMA_OPTIONS_ERROR: msg = "Specified preset is not supported"; break;
case LZMA_UNSUPPORTED_CHECK: msg = "Specified integrity check is not supported"; break;
default: msg = "Unknown error, possibly a bug"; break;
}
LOG(("Error initializing the decoder: %1 (error code %2)").arg(msg).arg(ret));
return fatalFail();
}
stream.avail_in = compressedLen;
stream.next_in = (uint8_t*)(compressed.constData() + hSize);
stream.avail_out = resultLen;
stream.next_out = (uint8_t*)uncompressed.data();
lzma_ret res = lzma_code(&stream, LZMA_FINISH);
if (stream.avail_in) {
LOG(("Error in decompression, %1 bytes left in _in of %2 whole.").arg(stream.avail_in).arg(compressedLen));
return fatalFail();
} else if (stream.avail_out) {
LOG(("Error in decompression, %1 bytes free left in _out of %2 whole.").arg(stream.avail_out).arg(resultLen));
return fatalFail();
}
lzma_end(&stream);
if (res != LZMA_OK && res != LZMA_STREAM_END) {
const char *msg;
switch (res) {
case LZMA_MEM_ERROR: msg = "Memory allocation failed"; break;
case LZMA_FORMAT_ERROR: msg = "The input data is not in the .xz format"; break;
case LZMA_OPTIONS_ERROR: msg = "Unsupported compression options"; break;
case LZMA_DATA_ERROR: msg = "Compressed file is corrupt"; break;
case LZMA_BUF_ERROR: msg = "Compressed data is truncated or otherwise corrupt"; break;
//.........这里部分代码省略.........
示例6: addLocalFile
bool KArchive::addLocalFile( const QString& fileName, const QString& destName )
{
QFileInfo fileInfo( fileName );
if ( !fileInfo.isFile() && !fileInfo.isSymLink() )
{
kWarning() << fileName << "doesn't exist or is not a regular file.";
return false;
}
KDE_struct_stat fi;
if (KDE::lstat(fileName,&fi) == -1) {
kWarning() << "stat'ing" << fileName
<< "failed:" << strerror(errno);
return false;
}
if (fileInfo.isSymLink()) {
QString symLinkTarget;
// Do NOT use fileInfo.readLink() for unix symlinks!
// It returns the -full- path to the target, while we want the target string "as is".
#if defined(Q_OS_UNIX) && !defined(Q_OS_OS2EMX)
const QByteArray encodedFileName = QFile::encodeName(fileName);
QByteArray s;
#if defined(PATH_MAX)
s.resize(PATH_MAX+1);
#else
int path_max = pathconf(encodedFileName.data(), _PC_PATH_MAX);
if (path_max <= 0) {
path_max = 4096;
}
s.resize(path_max);
#endif
int len = readlink(encodedFileName.data(), s.data(), s.size() - 1);
if ( len >= 0 ) {
s[len] = '\0';
symLinkTarget = QFile::decodeName(s);
}
#endif
if (symLinkTarget.isEmpty()) // Mac or Windows
symLinkTarget = fileInfo.symLinkTarget();
return writeSymLink(destName, symLinkTarget, fileInfo.owner(),
fileInfo.group(), fi.st_mode, fi.st_atime, fi.st_mtime,
fi.st_ctime);
}/*end if*/
qint64 size = fileInfo.size();
// the file must be opened before prepareWriting is called, otherwise
// if the opening fails, no content will follow the already written
// header and the tar file is effectively f*cked up
QFile file( fileName );
if ( !file.open( QIODevice::ReadOnly ) )
{
kWarning() << "couldn't open file " << fileName;
return false;
}
if ( !prepareWriting( destName, fileInfo.owner(), fileInfo.group(), size,
fi.st_mode, fi.st_atime, fi.st_mtime, fi.st_ctime ) )
{
kWarning() << " prepareWriting" << destName << "failed";
return false;
}
// Read and write data in chunks to minimize memory usage
QByteArray array;
array.resize( int( qMin( qint64( 1024 * 1024 ), size ) ) );
qint64 n;
qint64 total = 0;
while ( ( n = file.read( array.data(), array.size() ) ) > 0 )
{
if ( !writeData( array.data(), n ) )
{
kWarning() << "writeData failed";
return false;
}
total += n;
}
Q_ASSERT( total == size );
if ( !finishWriting( size ) )
{
kWarning() << "finishWriting failed";
return false;
}
return true;
}
示例7: ProcessData
void CNetRender::ProcessData(QTcpSocket *socket, sMessage *inMsg)
{
// beware: payload points to char, first cast to target type pointer, then dereference
// *(qint32*)msg->payload
//------------------------- CLIENT ------------------------
if(IsClient())
{
switch ((netCommand)inMsg->command)
{
case netRender_VERSION:
{
sMessage outMsg;
if(*(qint32*)inMsg->payload.data() == version)
{
WriteLog("NetRender - version matches (" + QString::number(version) + "), connection established");
if(systemData.noGui)
{
QTextStream out(stdout);
out << "NetRender - version matches (" + QString::number(version) + "), connection established\n";
}
// server version matches, send worker count
outMsg.command = netRender_WORKER;
QDataStream stream(&outMsg.payload, QIODevice::WriteOnly);
stream << workerCount;
QString machineName = QHostInfo::localHostName();
stream << (qint32)machineName.toUtf8().size();
stream.writeRawData(machineName.toUtf8().data(), machineName.toUtf8().size());
status = netRender_READY;
emit NewStatusClient();
}
else
{
qWarning() << "CNetRender - version mismatch! client version: " << version << ", server: " << *(qint32*)inMsg->payload.data();
outMsg.command = netRender_BAD;
}
SendData(clientSocket, outMsg);
break;
}
case netRender_STOP:
{
status = netRender_READY;
gMainInterface->stopRequest = true;
emit NotifyStatus();
WriteLog("CNetRender - STOP");
break;
}
case netRender_STATUS:
{
emit NotifyStatus();
break;
}
case netRender_JOB:
{
if (inMsg->id == actualId)
{
WriteLog("NetRender - received new job");
QDataStream stream(&inMsg->payload, QIODevice::ReadOnly);
QByteArray buffer;
qint32 size;
status = netRender_WORKING;
emit NotifyStatus();
// read settings
stream >> size;
buffer.resize(size);
stream.readRawData(buffer.data(), size);
settingsText = QString::fromUtf8(buffer.data(), buffer.size());
// read textures
for (int i = 0; i < textures.textureList.size(); i++)
{
stream >> size;
if (size > 0)
{
buffer.resize(size);
stream.readRawData(buffer.data(), size);
textures.textureList[i]->FromQByteArray(buffer);
}
}
cSettings parSettings(cSettings::formatCondensedText);
parSettings.BeQuiet(true);
parSettings.LoadFromString(settingsText);
parSettings.Decode(gPar, gParFractal);
if(!systemData.noGui)
{
gMainInterface->SynchronizeInterface(gPar, gParFractal, cInterface::write);
gMainInterface->StartRender(true);
}
else
{
//in noGui mode it must be started as separate thread to be able to process event loop
gMainInterface->headless = new cHeadless;
QThread *thread = new QThread; //deleted by deleteLater()
gMainInterface->headless->moveToThread(thread);
//.........这里部分代码省略.........
示例8: readPendingDatagrams
void AssignmentClient::readPendingDatagrams() {
NodeList* nodeList = NodeList::getInstance();
QByteArray receivedPacket;
HifiSockAddr senderSockAddr;
while (nodeList->getNodeSocket().hasPendingDatagrams()) {
receivedPacket.resize(nodeList->getNodeSocket().pendingDatagramSize());
nodeList->getNodeSocket().readDatagram(receivedPacket.data(), receivedPacket.size(),
senderSockAddr.getAddressPointer(), senderSockAddr.getPortPointer());
if (packetVersionMatch(receivedPacket)) {
if (_currentAssignment) {
// have the threaded current assignment handle this datagram
QMetaObject::invokeMethod(_currentAssignment, "processDatagram", Qt::QueuedConnection,
Q_ARG(QByteArray, receivedPacket),
Q_ARG(HifiSockAddr, senderSockAddr));
} else if (packetTypeForPacket(receivedPacket) == PacketTypeCreateAssignment) {
if (_currentAssignment) {
qDebug() << "Dropping received assignment since we are currently running one.";
} else {
// construct the deployed assignment from the packet data
_currentAssignment = AssignmentFactory::unpackAssignment(receivedPacket);
if (_currentAssignment) {
qDebug() << "Received an assignment -" << *_currentAssignment;
// switch our nodelist domain IP and port to whoever sent us the assignment
nodeList->setDomainSockAddr(senderSockAddr);
nodeList->setOwnerUUID(_currentAssignment->getUUID());
qDebug() << "Destination IP for assignment is" << nodeList->getDomainIP().toString();
// start the deployed assignment
QThread* workerThread = new QThread(this);
connect(workerThread, SIGNAL(started()), _currentAssignment, SLOT(run()));
connect(_currentAssignment, SIGNAL(finished()), this, SLOT(assignmentCompleted()));
connect(_currentAssignment, SIGNAL(finished()), workerThread, SLOT(quit()));
connect(_currentAssignment, SIGNAL(finished()), _currentAssignment, SLOT(deleteLater()));
connect(workerThread, SIGNAL(finished()), workerThread, SLOT(deleteLater()));
_currentAssignment->moveToThread(workerThread);
// move the NodeList to the thread used for the _current assignment
nodeList->moveToThread(workerThread);
// Starts an event loop, and emits workerThread->started()
workerThread->start();
} else {
qDebug() << "Received an assignment that could not be unpacked. Re-requesting.";
}
}
} else {
// have the NodeList attempt to handle it
nodeList->processNodeData(senderSockAddr, receivedPacket);
}
}
}
}
示例9: QUdpSocket
/**
* @brief SingleApplication::SingleApplication
* Constructor. Checks and fires up LocalServer or closes the program
* if another instance already exists
* @param argc
* @param argv
*/
SingleApplication::SingleApplication(QStringList &args)
{
_shouldContinue = false; // By default this is not the main process
socket = new QUdpSocket();
QUdpSocket acceptor;
acceptor.bind(QHostAddress::LocalHost, 58488, QUdpSocket::ReuseAddressHint|QUdpSocket::ShareAddress);
// Attempt to connect to the LocalServer
socket->connectToHost(QHostAddress::LocalHost, 58487);
QString isServerRuns;
if(socket->waitForConnected(100))
{
socket->write(QString("CMD:Is editor running?").toUtf8());
socket->flush();
if(acceptor.waitForReadyRead(100))
{
//QByteArray dataGram;//Yes, I'm runs!
QByteArray datagram;
datagram.resize(acceptor.pendingDatagramSize());
QHostAddress sender;
quint16 senderPort;
acceptor.readDatagram(datagram.data(), datagram.size(), &sender, &senderPort);
if(QString::fromUtf8(datagram)=="Yes, I'm runs!")
{
isServerRuns="Yes!";
}
}
}
if(args.contains("--force-run", Qt::CaseInsensitive))
{
isServerRuns.clear();
args.removeAll("--force-run");
}
_arguments = args;
if(!isServerRuns.isEmpty())
{
QString str = QString("CMD:showUp");
QByteArray bytes;
for(int i=1; i<_arguments.size(); i++)
{
str.append(QString("\n%1").arg(_arguments[i]));
}
bytes = str.toUtf8();
socket->write(bytes);
socket->flush();
QThread::msleep(100);
socket->close();
}
else
{
// The attempt was insuccessful, so we continue the program
_shouldContinue = true;
server = new LocalServer();
server->start();
QObject::connect(server, SIGNAL(showUp()), this, SLOT(slotShowUp()));
QObject::connect(server, SIGNAL(dataReceived(QString)), this, SLOT(slotOpenFile(QString)));
QObject::connect(server, SIGNAL(acceptedCommand(QString)), this, SLOT(slotAcceptedCommand(QString)));
QObject::connect(this, SIGNAL(stopServer()), server, SLOT(stopServer()));
}
}
示例10: ReadPacket
CQueryHit* CQueryHit::ReadPacket(G2Packet *pPacket, QSharedPointer<QueryHitInfo> pHitInfo)
{
if( !pPacket->m_bCompound )
return 0;
pPacket->m_nPosition = 0; // reset packet position
bool bHaveHits = false;
bool bFirstHit = true;
CQueryHit* pThisHit = new CQueryHit();
try
{
char szType[9], szTypeX[9];
quint32 nLength = 0, nLengthX = 0, nNext = 0, nNextX = 0;
bool bCompound = false;
while( pPacket->ReadPacket(&szType[0], nLength, &bCompound) )
{
nNext = pPacket->m_nPosition + nLength;
if( strcmp("H", szType) == 0 && bCompound )
{
CQueryHit* pHit = (bFirstHit ? pThisHit : new CQueryHit());
if( !bFirstHit )
{
CQueryHit* pPrevHit = pThisHit;
while( pPrevHit->m_pNext != 0 )
{
pPrevHit = pPrevHit->m_pNext;
}
pPrevHit->m_pNext = pHit;
}
bool bHaveSize = false;
QByteArray baTemp;
bool bHaveDN = false;
bool bHaveURN = false;
while( pPacket->m_nPosition < nNext && pPacket->ReadPacket(&szTypeX[0], nLengthX))
{
nNextX = pPacket->m_nPosition + nLengthX;
if( strcmp("URN", szTypeX) == 0 )
{
QString sURN;
char hashBuff[256];
sURN = pPacket->ReadString();
if( nLengthX >= 44u && sURN.compare("bp") == 0 )
{
pPacket->Read(&hashBuff[0], CSHA1::ByteCount());
if( pHit->m_oSha1.FromRawData(&hashBuff[0], CSHA1::ByteCount()) )
{
bHaveURN = true;
}
else
{
pHit->m_oSha1.Clear();
}
}
else if( nLengthX >= CSHA1::ByteCount() + 5u && sURN.compare("sha1") == 0 )
{
pPacket->Read(&hashBuff[0], CSHA1::ByteCount());
if( pHit->m_oSha1.FromRawData(&hashBuff[0], CSHA1::ByteCount()) )
{
bHaveURN = true;
}
else
{
pHit->m_oSha1.Clear();
}
}
}
else if( strcmp("URL", szTypeX) == 0 && nLengthX )
{
// if url empty - try uri-res resolver or a node do not have this object
// bez sensu...
pHit->m_sURL = pPacket->ReadString();
}
else if( strcmp("DN", szTypeX) == 0 )
{
if( bHaveSize )
{
pHit->m_sDescriptiveName = pPacket->ReadString(nLengthX);
}
else if( nLengthX > 4 )
{
baTemp.resize(4);
pPacket->Read(baTemp.data(), 4);
pHit->m_sDescriptiveName = pPacket->ReadString(nLengthX - 4);
}
bHaveDN = true;
}
else if( strcmp("MD", szTypeX) == 0 )
//.........这里部分代码省略.........
示例11: compact
bool MailFolder::compact(unsigned level)
{
// sync first so that you are sure the database is ok
sync();
if ( level ) {
qDebug("Folder compressing isn't yet available.");
}
QCString mboxInfo;
mboxInfo = "From - " + QDateTime::currentDateTime().toString() + "\r\n";
QFile descriptorFile( getDescriptorFileName() );
if ( !descriptorFile.open(IO_ReadOnly) )
return false;
QFile newDescriptorFile( getDescriptorFileName()+"new" );
if ( !newDescriptorFile.open(IO_WriteOnly) )
return false;
QFile messageFile( getMessagesFileName() );
if ( !messageFile.open(IO_ReadOnly) )
return false;
QFile newMessageFile( getMessagesFileName()+"new" );
if ( !newMessageFile.open(IO_WriteOnly) )
return false;
IndexClass * index = 0L;
QByteArray buffer;
for (QDictIterator<IndexClass> it(indexCollection); it.current(); ++it) {
index = it.current();
if ( !index->getDescriptorLength() ||
!index->getUniblockLength() ) {
qDebug("The index file seems to be broken :(");
indexCollection.remove( index->getID() );
continue;
}
// read the descriptor
buffer.resize( index->getDescriptorLength() );
descriptorFile.at( index->getDescriptorOffset() );
descriptorFile.readBlock(buffer.data(), buffer.size());
// write the descriptor
index->setDescriptorOffset( newDescriptorFile.at() );
newDescriptorFile.writeBlock( buffer );
// read the message
buffer.resize( index->getUniblockLength() );
messageFile.at( index->getUniblockOffset() );
messageFile.readBlock(buffer.data(), buffer.size());
// write the message
// The MBOX line isn't right but the line isn't used too.
// So, I decided to just store only the current date.
newMessageFile.writeBlock((const char *)mboxInfo, mboxInfo.length());
index->setUniblockOffset(newMessageFile.at(), true);
newMessageFile.writeBlock( buffer );
newMessageFile.writeBlock("\r\n", 2);
}
descriptorFile.close();
newDescriptorFile.close();
messageFile.close();
newMessageFile.close();
buffer.truncate(0);
// replace the old files
descriptorFile.remove();
messageFile.remove();
QDir folder( getStorageDevice() );
folder.rename( newDescriptorFile.name(), getDescriptorFileName(), true );
folder.rename( newMessageFile.name(), getMessagesFileName(), true );
saveIndex();
return true;
}
示例12: wrapInFunction
void wrapInFunction()
{
//! [0]
QByteArray ba("Hello");
//! [0]
//! [1]
QByteArray ba;
ba.resize(5);
ba[0] = 0x3c;
ba[1] = 0xb8;
ba[2] = 0x64;
ba[3] = 0x18;
ba[4] = 0xca;
//! [1]
//! [2]
for (int i = 0; i < ba.size(); ++i) {
if (ba.at(i) >= 'a' && ba.at(i) <= 'f')
cout << "Found character in range [a-f]" << endl;
}
//! [2]
//! [3]
QByteArray x("and");
x.prepend("rock "); // x == "rock and"
x.append(" roll"); // x == "rock and roll"
x.replace(5, 3, "&"); // x == "rock & roll"
//! [3]
//! [4]
QByteArray ba("We must be <b>bold</b>, very <b>bold</b>");
int j = 0;
while ((j = ba.indexOf("<b>", j)) != -1) {
cout << "Found <b> tag at index position " << j << endl;
++j;
}
//! [4]
//! [5]
QByteArray().isNull(); // returns true
QByteArray().isEmpty(); // returns true
QByteArray("").isNull(); // returns false
QByteArray("").isEmpty(); // returns true
QByteArray("abc").isNull(); // returns false
QByteArray("abc").isEmpty(); // returns false
//! [5]
//! [6]
QByteArray ba("Hello");
int n = ba.size(); // n == 5
ba.data()[0]; // returns 'H'
ba.data()[4]; // returns 'o'
ba.data()[5]; // returns '\0'
//! [6]
//! [7]
QByteArray().isEmpty(); // returns true
QByteArray("").isEmpty(); // returns true
QByteArray("abc").isEmpty(); // returns false
//! [7]
//! [8]
QByteArray ba("Hello world");
char *data = ba.data();
while (*data) {
cout << "[" << *data << "]" << endl;
++data;
}
//! [8]
//! [9]
QByteArray ba;
for (int i = 0; i < 10; ++i)
ba[i] = 'A' + i;
// ba == "ABCDEFGHIJ"
//! [9]
//! [10]
QByteArray ba("Stockholm");
ba.truncate(5); // ba == "Stock"
//! [10]
//! [11]
QByteArray ba("STARTTLS\r\n");
ba.chop(2); // ba == "STARTTLS"
//.........这里部分代码省略.........
示例13: buildIndex
void CSwordModuleInfo::buildIndex() {
m_cancelIndexing = false;
try {
//Without this we don't get strongs, lemmas, etc
backend()->setFilterOptions ( CBTConfig::getFilterOptionDefaults() );
//make sure we reset all important filter options which influcence the plain filters.
// turn on these options, they are needed for the EntryAttributes population
backend()->setOption( CSwordModuleInfo::strongNumbers, true );
backend()->setOption( CSwordModuleInfo::morphTags, true );
backend()->setOption( CSwordModuleInfo::footnotes, true );
backend()->setOption( CSwordModuleInfo::headings, true );
// we don't want the following in the text, the do not carry searchable information
backend()->setOption( CSwordModuleInfo::morphSegmentation, false );
backend()->setOption( CSwordModuleInfo::scriptureReferences, false );
backend()->setOption( CSwordModuleInfo::redLetterWords, false );
// do not use any stop words
const TCHAR* stop_words[] = { NULL };
lucene::analysis::standard::StandardAnalyzer an( (const TCHAR**)stop_words );
QString index = getModuleStandardIndexLocation();
QDir dir("/");
dir.mkpath( getGlobalBaseIndexLocation() );
dir.mkpath( getModuleBaseIndexLocation() );
dir.mkpath( getModuleStandardIndexLocation() );
if (lucene::index::IndexReader::indexExists(index.toAscii().constData())) {
if (lucene::index::IndexReader::isLocked(index.toAscii().constData()) ) {
lucene::index::IndexReader::unlock(index.toAscii().constData());
}
}
boost::scoped_ptr<lucene::index::IndexWriter> writer( new lucene::index::IndexWriter(index.toAscii().constData(), &an, true) ); //always create a new index
writer->setMaxFieldLength(BT_MAX_LUCENE_FIELD_LENGTH);
writer->setUseCompoundFile(true); //merge segments into a single file
writer->setMinMergeDocs(1000);
*m_module = sword::TOP;
unsigned long verseLowIndex = m_module->Index();
*m_module = sword::BOTTOM;
unsigned long verseHighIndex = m_module->Index();
//verseLowIndex is not 0 in all cases (i.e. NT-only modules)
unsigned long verseIndex = verseLowIndex + 1;
unsigned long verseSpan = verseHighIndex - verseLowIndex;
//Index() is not implemented properly for lexicons, so we use a
//workaround.
if (type() == CSwordModuleInfo::Lexicon) {
verseIndex = 0;
verseLowIndex = 0;
verseSpan = ((CSwordLexiconModuleInfo*)this)->entries()->size();
}
emit indexingProgress(0);
sword::SWKey* key = m_module->getKey();
//VerseKey for bibles
sword::VerseKey* vk = dynamic_cast<sword::VerseKey*>(key);
if (vk) {
// we have to be sure to insert the english key into the index, otherwise we'd be in trouble if the language changes
vk->setLocale("en_US");
//If we have a verse based module, we want to include the pre-chapter etc. headings in the search
vk->Headings(1);
}
//holds UTF-8 data and is faster than QString.
QByteArray textBuffer;
// we start with the first module entry, key is automatically updated
// because key is a pointer to the modules key
m_module->setSkipConsecutiveLinks(true);
wchar_t wcharBuffer[BT_MAX_LUCENE_FIELD_LENGTH + 1];
for (*m_module = sword::TOP; !(m_module->Error()) && !m_cancelIndexing; (*m_module)++) {
// Also index Chapter 0 and Verse 0, because they might have information in the entry attributes
// We used to just put their content into the textBuffer and continue to the next verse, but
// with entry attributes this doesn't work any more.
// Hits in the search dialog will show up as 1:1 (instead of 0)
boost::scoped_ptr<lucene::document::Document> doc(new lucene::document::Document());
//index the key
lucene_utf8towcs(wcharBuffer, key->getText(), BT_MAX_LUCENE_FIELD_LENGTH);
//doc->add(*lucene::document::Field::UnIndexed((const TCHAR*)_T("key"), (const TCHAR*)wcharBuffer));
doc->add(*(new lucene::document::Field((const TCHAR*)_T("key"), (const TCHAR*)wcharBuffer, lucene::document::Field::STORE_YES | lucene::document::Field::INDEX_NO)));
// index the main text
//at this point we have to make sure we disabled the strongs and the other options
//so the plain filters won't include the numbers somehow.
lucene_utf8towcs(wcharBuffer, (const char*) textBuffer.append(m_module->StripText()), BT_MAX_LUCENE_FIELD_LENGTH);
doc->add(*(new lucene::document::Field((const TCHAR*)_T("content"), (const TCHAR*)wcharBuffer, lucene::document::Field::STORE_NO | lucene::document::Field::INDEX_TOKENIZED)));
textBuffer.resize(0); //clean up
//.........这里部分代码省略.........
示例14: broadcastAvatarData
// NOTE: some additional optimizations to consider.
// 1) use the view frustum to cull those avatars that are out of view. Since avatar data doesn't need to be present
// if the avatar is not in view or in the keyhole.
void AvatarMixer::broadcastAvatarData() {
int idleTime = QDateTime::currentMSecsSinceEpoch() - _lastFrameTimestamp;
++_numStatFrames;
const float STRUGGLE_TRIGGER_SLEEP_PERCENTAGE_THRESHOLD = 0.10f;
const float BACK_OFF_TRIGGER_SLEEP_PERCENTAGE_THRESHOLD = 0.20f;
const float RATIO_BACK_OFF = 0.02f;
const int TRAILING_AVERAGE_FRAMES = 100;
int framesSinceCutoffEvent = TRAILING_AVERAGE_FRAMES;
const float CURRENT_FRAME_RATIO = 1.0f / TRAILING_AVERAGE_FRAMES;
const float PREVIOUS_FRAMES_RATIO = 1.0f - CURRENT_FRAME_RATIO;
_trailingSleepRatio = (PREVIOUS_FRAMES_RATIO * _trailingSleepRatio)
+ (idleTime * CURRENT_FRAME_RATIO / (float) AVATAR_DATA_SEND_INTERVAL_MSECS);
float lastCutoffRatio = _performanceThrottlingRatio;
bool hasRatioChanged = false;
if (framesSinceCutoffEvent >= TRAILING_AVERAGE_FRAMES) {
if (_trailingSleepRatio <= STRUGGLE_TRIGGER_SLEEP_PERCENTAGE_THRESHOLD) {
// we're struggling - change our min required loudness to reduce some load
_performanceThrottlingRatio = _performanceThrottlingRatio + (0.5f * (1.0f - _performanceThrottlingRatio));
qDebug() << "Mixer is struggling, sleeping" << _trailingSleepRatio * 100 << "% of frame time. Old cutoff was"
<< lastCutoffRatio << "and is now" << _performanceThrottlingRatio;
hasRatioChanged = true;
} else if (_trailingSleepRatio >= BACK_OFF_TRIGGER_SLEEP_PERCENTAGE_THRESHOLD && _performanceThrottlingRatio != 0) {
// we've recovered and can back off the required loudness
_performanceThrottlingRatio = _performanceThrottlingRatio - RATIO_BACK_OFF;
if (_performanceThrottlingRatio < 0) {
_performanceThrottlingRatio = 0;
}
qDebug() << "Mixer is recovering, sleeping" << _trailingSleepRatio * 100 << "% of frame time. Old cutoff was"
<< lastCutoffRatio << "and is now" << _performanceThrottlingRatio;
hasRatioChanged = true;
}
if (hasRatioChanged) {
framesSinceCutoffEvent = 0;
}
}
if (!hasRatioChanged) {
++framesSinceCutoffEvent;
}
static QByteArray mixedAvatarByteArray;
int numPacketHeaderBytes = populatePacketHeader(mixedAvatarByteArray, PacketTypeBulkAvatarData);
NodeList* nodeList = NodeList::getInstance();
AvatarMixerClientData* nodeData = NULL;
AvatarMixerClientData* otherNodeData = NULL;
foreach (const SharedNodePointer& node, nodeList->getNodeHash()) {
if (node->getLinkedData() && node->getType() == NodeType::Agent && node->getActiveSocket()
&& (nodeData = reinterpret_cast<AvatarMixerClientData*>(node->getLinkedData()))->getMutex().tryLock()) {
++_sumListeners;
// reset packet pointers for this node
mixedAvatarByteArray.resize(numPacketHeaderBytes);
AvatarData& avatar = nodeData->getAvatar();
glm::vec3 myPosition = avatar.getPosition();
// this is an AGENT we have received head data from
// send back a packet with other active node data to this node
foreach (const SharedNodePointer& otherNode, nodeList->getNodeHash()) {
if (otherNode->getLinkedData() && otherNode->getUUID() != node->getUUID()
&& (otherNodeData = reinterpret_cast<AvatarMixerClientData*>(otherNode->getLinkedData()))->getMutex().tryLock()) {
AvatarMixerClientData* otherNodeData = reinterpret_cast<AvatarMixerClientData*>(otherNode->getLinkedData());
AvatarData& otherAvatar = otherNodeData->getAvatar();
glm::vec3 otherPosition = otherAvatar.getPosition();
float distanceToAvatar = glm::length(myPosition - otherPosition);
// The full rate distance is the distance at which EVERY update will be sent for this avatar
// at a distance of twice the full rate distance, there will be a 50% chance of sending this avatar's update
const float FULL_RATE_DISTANCE = 2.0f;
// Decide whether to send this avatar's data based on it's distance from us
if ((_performanceThrottlingRatio == 0 || randFloat() < (1.0f - _performanceThrottlingRatio))
&& (distanceToAvatar == 0.0f || randFloat() < FULL_RATE_DISTANCE / distanceToAvatar)) {
QByteArray avatarByteArray;
avatarByteArray.append(otherNode->getUUID().toRfc4122());
avatarByteArray.append(otherAvatar.toByteArray());
if (avatarByteArray.size() + mixedAvatarByteArray.size() > MAX_PACKET_SIZE) {
nodeList->writeDatagram(mixedAvatarByteArray, node);
//.........这里部分代码省略.........
示例15: ProcessData
void SSDP::ProcessData( MSocketDevice *pSocket )
{
long nBytes = 0;
long nRead = 0;
while ((nBytes = pSocket->bytesAvailable()) > 0)
{
QByteArray buffer;
buffer.resize(nBytes);
nRead = pSocket->readBlock( buffer.data(), nBytes );
QHostAddress peerAddress = pSocket->peerAddress();
quint16 peerPort = pSocket->peerPort ();
// ------------------------------------------------------------------
QString str = QString(buffer.constData());
QStringList lines = str.split("\r\n", QString::SkipEmptyParts);
QString sRequestLine = lines.size() ? lines[0] : "";
lines.pop_front();
// ------------------------------------------------------------------
// Parse request Type
// ------------------------------------------------------------------
VERBOSE(VB_UPNP+VB_EXTRA,
QString( "SSDP::ProcessData - requestLine: %1" )
.arg( sRequestLine ));
SSDPRequestType eType = ProcessRequestLine( sRequestLine );
// ------------------------------------------------------------------
// Read Headers into map
// ------------------------------------------------------------------
QStringMap headers;
for ( QStringList::Iterator it = lines.begin();
it != lines.end(); ++it )
{
QString sLine = *it;
QString sName = sLine.section( ':', 0, 0 ).trimmed();
QString sValue = sLine.section( ':', 1 );
sValue.truncate( sValue.length() ); //-2
if ((sName.length() != 0) && (sValue.length() !=0))
headers.insert( sName.toLower(), sValue.trimmed() );
}
// pSocket->SetDestAddress( peerAddress, peerPort );
// --------------------------------------------------------------
// See if this is a valid request
// --------------------------------------------------------------
switch( eType )
{
case SSDP_MSearch:
{
// ----------------------------------------------------------
// If we haven't enabled notifications yet, then we don't
// want to answer search requests.
// ----------------------------------------------------------
if (m_pNotifyTask != NULL)
ProcessSearchRequest( headers, peerAddress, peerPort );
break;
}
case SSDP_MSearchResp:
ProcessSearchResponse( headers);
break;
case SSDP_Notify:
ProcessNotify( headers );
break;
case SSDP_Unknown:
default:
VERBOSE(VB_UPNP, "SSPD::ProcessData - Unknown request Type.");
break;
}
}
}