当前位置: 首页>>代码示例>>C++>>正文


C++ QByteArray::mid方法代码示例

本文整理汇总了C++中QByteArray::mid方法的典型用法代码示例。如果您正苦于以下问题:C++ QByteArray::mid方法的具体用法?C++ QByteArray::mid怎么用?C++ QByteArray::mid使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在QByteArray的用法示例。


在下文中一共展示了QByteArray::mid方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C++代码示例。

示例1: onServerDataEvent

void ProtocolController::onServerDataEvent(QByteArray &data)
{
    const QByteArray seperator("\r\n");

    if ( data.startsWith("MESSAGE:") ) {
        QByteArray preparedData = prepareRequest(data, QByteArrayLiteral("MESSAGE:"));

        if ( preparedData.size() > 0 ) {

            int seperatorIndex = preparedData.indexOf(seperator);

            QByteArray username = preparedData.left(seperatorIndex);
            QByteArray message = preparedData.mid(seperatorIndex + seperator.length());

            signalMessage(username, message);
        }
    }
    else if ( data.startsWith("STARTUP:") ) {
        QByteArray preparedData = prepareRequest(data, QByteArrayLiteral("STARTUP:"));

        if ( preparedData.size() > 0 ) {

            int seperatorIndex = preparedData.indexOf(seperator);

            QByteArray username = preparedData.left(seperatorIndex);
            QByteArray publicKey = preparedData.mid(seperatorIndex + seperator.length());

            signalStartup(username, publicKey);
        }
    }
    else if ( data.startsWith("ENCRYPT:") ) {
        QByteArray preparedData = prepareRequest(data, QByteArrayLiteral("ENCRYPT:"));

        if ( preparedData.size() > 0 ) {

            int seperatorIndex = preparedData.indexOf(seperator);

            QByteArray username = preparedData.left(seperatorIndex);
            QByteArray message = preparedData.mid(seperatorIndex + seperator.length());

            signalEncrypt(username, message);
        }
    }
    else if ( data.startsWith("IDENTITY-CHECK:") ) {
        QByteArray encryptedRandomString = stripRequest(data, QByteArrayLiteral("IDENTITY-CHECK:"));

        if ( encryptedRandomString.size() > 0 ) {
            signalIdentityCheck(encryptedRandomString);
        }
    }
    else if ( data.startsWith("AUTHENTICATION-ACCEPTED") ) {
        emit signalAuthenticationSucceded();
    }
    else if ( data.startsWith("NOTIFICATION:") ) {
        QByteArray notificationString = stripRequest(data, QByteArrayLiteral("NOTIFICATION:"));

        qDebug() << "Received notification: " << notificationString;

        if ( notificationString.startsWith("ONLINE") ) {
            int seperatorIndex = notificationString.indexOf(seperator);
            QByteArray username = notificationString.mid(seperatorIndex + seperator.length());

            qDebug() << "User " << username << " is online";

            emit signalUserOnline(username);
        }
    }
    else {
        qWarning() << "UNKNOWN ACTION";
        signalError(QByteArrayLiteral("UNKNOWN ACTION"));
    }
}
开发者ID:saeschdivara,项目名称:SecretWhisperer-Desktop-Client,代码行数:72,代码来源:protocolcontroller.cpp

示例2: preprocess

void Preprocessor::preprocess(const QByteArray &filename, Symbols &preprocessed)
{
    currentFilenames.push(filename);
    preprocessed.reserve(preprocessed.size() + symbols.size());
    while (hasNext()) {
        Token token = next();

        switch (token) {
        case PP_INCLUDE:
        {
            int lineNum = symbol().lineNum;
            QByteArray include;
            bool local = false;
            if (test(PP_STRING_LITERAL)) {
                local = lexem().startsWith('\"');
                include = unquotedLexem();
            } else
                continue;
            until(PP_NEWLINE);

            // #### stringery
            QFileInfo fi;
            if (local)
                fi.setFile(QFileInfo(QString::fromLocal8Bit(filename)).dir(), QString::fromLocal8Bit(include));
            for (int j = 0; j < Preprocessor::includes.size() && !fi.exists(); ++j) {
                const IncludePath &p = Preprocessor::includes.at(j);
                if (p.isFrameworkPath) {
                    const int slashPos = include.indexOf('/');
                    if (slashPos == -1)
                        continue;
                    QByteArray frameworkCandidate = include.left(slashPos);
                    frameworkCandidate.append(".framework/Headers/");
                    fi.setFile(QString::fromLocal8Bit(p.path + '/' + frameworkCandidate), QString::fromLocal8Bit(include.mid(slashPos + 1)));
                } else {
                    fi.setFile(QString::fromLocal8Bit(p.path), QString::fromLocal8Bit(include));
                }
                // try again, maybe there's a file later in the include paths with the same name
                // (186067)
                if (fi.isDir()) {
                    fi = QFileInfo();
                    continue;
                }
            }

            if (!fi.exists() || fi.isDir())
                continue;
            include = fi.canonicalFilePath().toLocal8Bit();

            if (Preprocessor::preprocessedIncludes.contains(include))
                continue;
            Preprocessor::preprocessedIncludes.insert(include);

            QFile file(QString::fromLocal8Bit(include));
            if (!file.open(QFile::ReadOnly))
                continue;

            QByteArray input = file.readAll();
            file.close();
            if (input.isEmpty())
                continue;

            Symbols saveSymbols = symbols;
            int saveIndex = index;

            // phase 1: get rid of backslash-newlines
            input = cleaned(input);

            // phase 2: tokenize for the preprocessor
            symbols = tokenize(input);
            input.clear();

            index = 0;

            // phase 3: preprocess conditions and substitute macros
            preprocessed += Symbol(0, MOC_INCLUDE_BEGIN, include);
            preprocess(include, preprocessed);
            preprocessed += Symbol(lineNum, MOC_INCLUDE_END, include);

            symbols = saveSymbols;
            index = saveIndex;
            continue;
        }
        case PP_DEFINE:
        {
            next(IDENTIFIER);
            QByteArray name = lexem();
            int start = index;
            until(PP_NEWLINE);
            Macro macro;
            macro.symbols.reserve(index - start - 1);
            for (int i = start; i < index - 1; ++i)
                macro.symbols += symbols.at(i);
            macros.insert(name, macro);
            continue;
        }
        case PP_UNDEF: {
            next(IDENTIFIER);
            QByteArray name = lexem();
            until(PP_NEWLINE);
            macros.remove(name);
//.........这里部分代码省略.........
开发者ID:husninazer,项目名称:qt,代码行数:101,代码来源:preprocessor.cpp

示例3: compileProperty

bool QDeclarativeListModelParser::compileProperty(const QDeclarativeCustomParserProperty &prop, QList<ListInstruction> &instr, QByteArray &data)
{
    QList<QVariant> values = prop.assignedValues();
    for(int ii = 0; ii < values.count(); ++ii) {
        const QVariant &value = values.at(ii);

        if(value.userType() == qMetaTypeId<QDeclarativeCustomParserNode>()) {
            QDeclarativeCustomParserNode node =
                qvariant_cast<QDeclarativeCustomParserNode>(value);

            if (node.name() != listElementTypeName) {
                const QMetaObject *mo = resolveType(node.name());
                if (mo != &QDeclarativeListElement::staticMetaObject) {
                    error(node, QDeclarativeListModel::tr("ListElement: cannot contain nested elements"));
                    return false;
                }
                listElementTypeName = node.name(); // cache right name for next time
            }

            {
            ListInstruction li;
            li.type = ListInstruction::Push;
            li.dataIdx = -1;
            instr << li;
            }

            QList<QDeclarativeCustomParserProperty> props = node.properties();
            for(int jj = 0; jj < props.count(); ++jj) {
                const QDeclarativeCustomParserProperty &nodeProp = props.at(jj);
                if (nodeProp.name().isEmpty()) {
                    error(nodeProp, QDeclarativeListModel::tr("ListElement: cannot contain nested elements"));
                    return false;
                }
                if (nodeProp.name() == "id") {
                    error(nodeProp, QDeclarativeListModel::tr("ListElement: cannot use reserved \"id\" property"));
                    return false;
                }

                ListInstruction li;
                int ref = data.count();
                data.append(nodeProp.name());
                data.append('\0');
                li.type = ListInstruction::Set;
                li.dataIdx = ref;
                instr << li;

                if(!compileProperty(nodeProp, instr, data))
                    return false;

                li.type = ListInstruction::Pop;
                li.dataIdx = -1;
                instr << li;
            }

            {
            ListInstruction li;
            li.type = ListInstruction::Pop;
            li.dataIdx = -1;
            instr << li;
            }

        } else {

            QDeclarativeParser::Variant variant =
                qvariant_cast<QDeclarativeParser::Variant>(value);

            int ref = data.count();

            QByteArray d;
            d += char(variant.type()); // type tag
            if (variant.isString()) {
                d += variant.asString().toUtf8();
            } else if (variant.isNumber()) {
                double temp = variant.asNumber();
                d += QByteArray( reinterpret_cast<const char*>(&temp), sizeof(double));
            } else if (variant.isBoolean()) {
                d += char(variant.asBoolean());
            } else if (variant.isScript()) {
                if (definesEmptyList(variant.asScript())) {
                    d[0] = char(QDeclarativeParser::Variant::Invalid); // marks empty list
                } else {
                    QByteArray script = variant.asScript().toUtf8();
                    int v = evaluateEnum(script);
                    if (v<0) {
                        if (script.startsWith("QT_TR_NOOP(\"") && script.endsWith("\")")) {
                            d[0] = char(QDeclarativeParser::Variant::String);
                            d += script.mid(12,script.length()-14);
                        } else {
                            error(prop, QDeclarativeListModel::tr("ListElement: cannot use script for property value"));
                            return false;
                        }
                    } else {
                        d[0] = char(QDeclarativeParser::Variant::Number);
                        double temp = v;
                        d += QByteArray( reinterpret_cast<const char*>(&temp), sizeof(double));
                    }
                }
            }
            d.append('\0');
            data.append(d);
//.........这里部分代码省略.........
开发者ID:Drakey83,项目名称:steamlink-sdk,代码行数:101,代码来源:qdeclarativelistmodel.cpp

示例4: parseData

int InboundAudioStream::parseData(const QByteArray& packet) {

    PacketType packetType = packetTypeForPacket(packet);
    QUuid senderUUID = uuidFromPacketHeader(packet);

    // parse header 
    int numBytesHeader = numBytesForPacketHeader(packet);
    const char* sequenceAt = packet.constData() + numBytesHeader;
    int readBytes = numBytesHeader;

    // parse sequence number and track it
    quint16 sequence = *(reinterpret_cast<const quint16*>(sequenceAt));
    readBytes += sizeof(quint16);
    SequenceNumberStats::ArrivalInfo arrivalInfo = _incomingSequenceNumberStats.sequenceNumberReceived(sequence, senderUUID);

    frameReceivedUpdateTimingStats();

    // TODO: handle generalized silent packet here?????

    // parse the info after the seq number and before the audio data.(the stream properties)
    int numAudioSamples;
    readBytes += parseStreamProperties(packetType, packet.mid(readBytes), numAudioSamples);

    // handle this packet based on its arrival status.
    // For now, late packets are ignored.  It may be good in the future to insert the late audio frame
    // into the ring buffer to fill in the missing frame if it hasn't been mixed yet.
    switch (arrivalInfo._status) {
        case SequenceNumberStats::Early: {
            int packetsDropped = arrivalInfo._seqDiffFromExpected;
            writeSamplesForDroppedPackets(packetsDropped * numAudioSamples);
            // fall through to OnTime case
        }
        case SequenceNumberStats::OnTime: {
            readBytes += parseAudioData(packetType, packet.mid(readBytes), numAudioSamples);
            break;
        }
        default: {
            break;
        }
    }

    int framesAvailable = _ringBuffer.framesAvailable();
    // if this stream was starved, check if we're still starved.
    if (_isStarved && framesAvailable >= _desiredJitterBufferFrames) {
        _isStarved = false;
    }
    // if the ringbuffer exceeds the desired size by more than the threshold specified,
    // drop the oldest frames so the ringbuffer is down to the desired size.
    if (framesAvailable > _desiredJitterBufferFrames + _maxFramesOverDesired) {
        int framesToDrop = framesAvailable - (_desiredJitterBufferFrames + DESIRED_JITTER_BUFFER_FRAMES_PADDING);
        _ringBuffer.shiftReadPosition(framesToDrop * _ringBuffer.getNumFrameSamples());
        
        _framesAvailableStat.reset();
        _currentJitterBufferFrames = 0;

        _oldFramesDropped += framesToDrop;
    }

    framesAvailableChanged();

    return readBytes;
}
开发者ID:WatcomHecht,项目名称:hifi,代码行数:62,代码来源:InboundAudioStream.cpp

示例5: setupLocaleMapper

/* the next two functions are implicitely thread safe,
   as they are only called by setup() which uses a mutex.
*/
static void setupLocaleMapper()
{
#if defined(Q_OS_WIN32) || defined(Q_OS_WINCE)
    localeMapper = QTextCodec::codecForName("System");
#else

#ifndef QT_NO_ICONV
    localeMapper = QTextCodec::codecForName("System");
#endif

#if defined (_XOPEN_UNIX) && !defined(Q_OS_QNX) && !defined(Q_OS_OSF)
    if (!localeMapper) {
        char *charset = nl_langinfo (CODESET);
        if (charset)
            localeMapper = QTextCodec::codecForName(charset);
    }
#endif

    if (!localeMapper) {
        // Very poorly defined and followed standards causes lots of
        // code to try to get all the cases... This logic is
        // duplicated in QIconvCodec, so if you change it here, change
        // it there too.

        // Try to determine locale codeset from locale name assigned to
        // LC_CTYPE category.

        // First part is getting that locale name.  First try setlocale() which
        // definitely knows it, but since we cannot fully trust it, get ready
        // to fall back to environment variables.
#if !defined(QT_NO_SETLOCALE)
        const QByteArray ctype = setlocale(LC_CTYPE, 0);
#else
        const QByteArray ctype;
#endif

        // Get the first nonempty value from $LC_ALL, $LC_CTYPE, and $LANG
        // environment variables.
        QByteArray lang = qgetenv("LC_ALL");
        if (lang.isEmpty() || lang == "C") {
            lang = qgetenv("LC_CTYPE");
        }
        if (lang.isEmpty() || lang == "C") {
            lang = qgetenv("LANG");
        }

        // Now try these in order:
        // 1. CODESET from ctype if it contains a .CODESET part (e.g. en_US.ISO8859-15)
        // 2. CODESET from lang if it contains a .CODESET part
        // 3. ctype (maybe the locale is named "ISO-8859-1" or something)
        // 4. locale (ditto)
        // 5. check for "@euro"
        // 6. guess locale from ctype unless ctype is "C"
        // 7. guess locale from lang

        // 1. CODESET from ctype if it contains a .CODESET part (e.g. en_US.ISO8859-15)
        int indexOfDot = ctype.indexOf('.');
        if (indexOfDot != -1)
            localeMapper = checkForCodec( ctype.mid(indexOfDot + 1) );

        // 2. CODESET from lang if it contains a .CODESET part
        if (!localeMapper) {
            indexOfDot = lang.indexOf('.');
            if (indexOfDot != -1)
                localeMapper = checkForCodec( lang.mid(indexOfDot + 1) );
        }

        // 3. ctype (maybe the locale is named "ISO-8859-1" or something)
        if (!localeMapper && !ctype.isEmpty() && ctype != "C")
            localeMapper = checkForCodec(ctype);

        // 4. locale (ditto)
        if (!localeMapper && !lang.isEmpty())
            localeMapper = checkForCodec(lang);

        // 5. "@euro"
        if ((!localeMapper && ctype.contains("@euro")) || lang.contains("@euro"))
            localeMapper = checkForCodec("ISO 8859-15");

        // 6. guess locale from ctype unless ctype is "C"
        // 7. guess locale from lang
        const QByteArray &try_by_name = (!ctype.isEmpty() && ctype != "C") ? lang : ctype;

        // Now do the guessing.
        if (!lang.isEmpty() && !localeMapper && !try_by_name.isEmpty()) {
            if (try_locale_list(iso8859_15locales, lang))
                localeMapper = QTextCodec::codecForName("ISO 8859-15");
            else if (try_locale_list(iso8859_2locales, lang))
                localeMapper = QTextCodec::codecForName("ISO 8859-2");
            else if (try_locale_list(iso8859_3locales, lang))
                localeMapper = QTextCodec::codecForName("ISO 8859-3");
            else if (try_locale_list(iso8859_4locales, lang))
                localeMapper = QTextCodec::codecForName("ISO 8859-4");
            else if (try_locale_list(iso8859_5locales, lang))
                localeMapper = QTextCodec::codecForName("ISO 8859-5");
            else if (try_locale_list(iso8859_6locales, lang))
                localeMapper = QTextCodec::codecForName("ISO 8859-6");
//.........这里部分代码省略.........
开发者ID:venkatarajasekhar,项目名称:ECE497,代码行数:101,代码来源:qtextcodec.cpp

示例6: populateSettings

    void populateSettings(const QByteArray &xSettings)
    {
        if (xSettings.length() < 12)
            return;
        char byteOrder = xSettings.at(0);
        if (byteOrder != LSBFirst && byteOrder != MSBFirst) {
            qWarning("%s ByteOrder byte %d not 0 or 1", Q_FUNC_INFO , byteOrder);
            return;
        }

#define ADJUST_BO(b, t, x) \
        ((b == LSBFirst) ?                          \
         qFromLittleEndian<t>((const uchar *)(x)) : \
         qFromBigEndian<t>((const uchar *)(x)))
#define VALIDATE_LENGTH(x)    \
        if ((size_t)xSettings.length() < (offset + local_offset + 12 + x)) { \
            qWarning("%s Length %d runs past end of data", Q_FUNC_INFO , x); \
            return;                                                     \
        }

        uint number_of_settings = ADJUST_BO(byteOrder, quint32, xSettings.mid(8,4).constData());
        const char *data = xSettings.constData() + 12;
        size_t offset = 0;
        for (uint i = 0; i < number_of_settings; i++) {
            int local_offset = 0;
            VALIDATE_LENGTH(2);
            XSettingsType type = static_cast<XSettingsType>(*reinterpret_cast<const quint8 *>(data + offset));
            local_offset += 2;

            VALIDATE_LENGTH(2);
            quint16 name_len = ADJUST_BO(byteOrder, quint16, data + offset + local_offset);
            local_offset += 2;

            VALIDATE_LENGTH(name_len);
            QByteArray name(data + offset + local_offset, name_len);
            local_offset += round_to_nearest_multiple_of_4(name_len);

            VALIDATE_LENGTH(4);
            int last_change_serial = ADJUST_BO(byteOrder, qint32, data + offset + local_offset);
            Q_UNUSED(last_change_serial);
            local_offset += 4;

            QVariant value;
            if (type == XSettingsTypeString) {
                VALIDATE_LENGTH(4);
                int value_length = ADJUST_BO(byteOrder, qint32, data + offset + local_offset);
                local_offset+=4;
                VALIDATE_LENGTH(value_length);
                QByteArray value_string(data + offset + local_offset, value_length);
                value.setValue(value_string);
                local_offset += round_to_nearest_multiple_of_4(value_length);
            } else if (type == XSettingsTypeInteger) {
                VALIDATE_LENGTH(4);
                int value_length = ADJUST_BO(byteOrder, qint32, data + offset + local_offset);
                local_offset += 4;
                value.setValue(value_length);
            } else if (type == XSettingsTypeColor) {
                VALIDATE_LENGTH(2*4);
                quint16 red = ADJUST_BO(byteOrder, quint16, data + offset + local_offset);
                local_offset += 2;
                quint16 green = ADJUST_BO(byteOrder, quint16, data + offset + local_offset);
                local_offset += 2;
                quint16 blue = ADJUST_BO(byteOrder, quint16, data + offset + local_offset);
                local_offset += 2;
                quint16 alpha= ADJUST_BO(byteOrder, quint16, data + offset + local_offset);
                local_offset += 2;
                QColor color_value(red,green,blue,alpha);
                value.setValue(color_value);
            }
            offset += local_offset;
            settings[name].updateValue(screen,name,value,last_change_serial);
        }

    }
开发者ID:venkatarajasekhar,项目名称:Qt,代码行数:74,代码来源:qxcbxsettings.cpp

示例7: processHeaderData

	bool processHeaderData(const QByteArray &headerData)
	{
		QList<QByteArray> lines;
		int at = 0;
		while(at < headerData.size())
		{
			int end = headerData.indexOf("\n", at);
			assert(end != -1);

			if(end > at && headerData[end - 1] == '\r')
				lines += headerData.mid(at, end - at - 1);
			else
				lines += headerData.mid(at, end - at);
			at = end + 1;
		}

		if(lines.isEmpty())
			return false;

		QByteArray requestLine = lines[0];

		at = requestLine.indexOf(' ');
		if(at == -1)
			return false;

		method = QString::fromLatin1(requestLine.mid(0, at));
		if(method.isEmpty())
			return false;

		++at;
		int end = requestLine.indexOf(' ', at);
		if(end == -1)
			return false;

		uri = requestLine.mid(at, end - at);

		QByteArray versionStr = requestLine.mid(end + 1);
		if(versionStr == "HTTP/1.0")
			version1dot0 = true;

		for(int n = 1; n < lines.count(); ++n)
		{
			const QByteArray &line = lines[n];
			end = line.indexOf(':');
			if(end == -1)
				continue;

			// skip first space
			at = end + 1;
			if(at < line.length() && line[at] == ' ')
				++at;

			QByteArray name = line.mid(0, end);
			QByteArray val = line.mid(at);

			reqHeaders += HttpHeader(name, val);
		}

		//log_debug("httpserver: IN method=[%s] uri=[%s] 1.1=%s", qPrintable(method), uri.data(), version1dot0 ? "no" : "yes");
		//foreach(const HttpHeader &h, reqHeaders)
		//	log_debug("httpserver:   [%s] [%s]", h.first.data(), h.second.data());
		log_debug("httpserver: IN %s %s", qPrintable(method), uri.data());

		return true;
	}
开发者ID:welll,项目名称:pushpin,代码行数:65,代码来源:httpserver.cpp

示例8: file

Quest::Quest(QString path, Player *Owner)
{
    QFile file(path);
    if (!file.open(QFile::ReadOnly))
    {
        app.logError(QObject::tr("Error reading quest DB"));
        app.stopGameServer();
        throw std::exception();
    }

    QList<QString> lines = QString(file.readAll().replace('\r',"")).split('\n');

    owner = Owner;
    commands = new QList<QList<QString> >;
    name = new QString();
    descr = new QString();
    npc = new Pony(nullptr); // A NPC doesn't have an owner player !
    npc->id = 0;
    npc->netviewId = 0;
    id = 0;
    state = 0;
    eip = 0;

    // Parse the metadata, add everything else as quest commands
    for (int i=0; i<lines.size(); i++)
    {
        QList<QString> line = lines[i].split(" ", QString::SkipEmptyParts);
        if (!line.size() || lines[i][0]=='#')
            continue;
        if (line[0] == "name")
            if (line.size()>=2)
                npc->name = lines[i].mid(line[0].size()+1);
            else throw QString(QObject::tr("Quest::Quest: Error reading name, quest %1").arg(path));
        else if (line[0] == "scene")
            if (line.size()>=2)
                npc->sceneName = lines[i].mid(line[0].size()+1).toLower();
            else throw QString(QObject::tr("Quest::Quest: Error reading scene, quest %1").arg(path));
        else if (line[0] == "ponyData")
        {
            if (line.size()==2)
            {
                QByteArray ponyData = QByteArray::fromBase64(line[1].toLatin1());
                // Read the ponyData
                unsigned strlen;
                unsigned lensize=0;
                {
                    unsigned char num3; int num=0, num2=0;
                    do {
                        num3 = ponyData[lensize]; lensize++;
                        num |= (num3 & 0x7f) << num2;
                        num2 += 7;
                    } while ((num3 & 0x80) != 0);
                    strlen = (uint) num;
                }
                int nameSize = strlen + lensize;
                int ponyDataSize = ponyData.size() - nameSize;
                if (ponyDataSize == 43)
                {
                    app.logMessage(QString("Quest::Quest: PonyData of quest %1 is in old format, converting")
                                   .arg(path));
                    ponyData += uint32ToData(0); // Member ID
                    ponyData.insert(nameSize+17+3,ponyData.mid(nameSize+17,3)); // Hair color 2 (copy of color 1)
                }
                npc->ponyData = ponyData;
            }
            else throw QString(QObject::tr("Quest::Quest: Error reading ponyData, quest %1").arg(path));
        }
        else if (line[0] == "pos")
            if (line.size()==4)
            {
                bool ok1, ok2, ok3;
                npc->pos = UVector(line[1].toFloat(&ok1), line[2].toFloat(&ok2),
                                    line[3].toFloat(&ok3));
                if (!(ok1 && ok2 && ok3))
                    throw QString(QObject::tr("Quest::Quest: Error reading pos, quest %1").arg(path));
            }
            else throw QString(QObject::tr("Quest::Quest: Error reading pos, quest %1").arg(path));
        else if (line[0] == "rot")
            if (line.size()==5)
            {
                bool ok1, ok2, ok3, ok4;
                npc->rot = UQuaternion(line[1].toFloat(&ok1), line[2].toFloat(&ok2),
                                        line[3].toFloat(&ok3), line[4].toFloat(&ok4));
                if (!(ok1 && ok2 && ok3 && ok4))
                    throw QString(QObject::tr("Quest::Quest: Error reading rot, quest %1").arg(path));
            }
            else throw QString(QObject::tr("Quest::Quest: Error reading rot, quest %1").arg(path));
        else if (line[0] == "wear")
        {
            for (int i=1; i<line.size(); i++)
            {
                bool ok;
                int itemId = line[i].toInt(&ok);
                if (!ok)
                    throw QString(QObject::tr("Quest::Quest: Error reading wear, quest %1").arg(path));
                WearableItem item;
                item.id = itemId;
                item.index = wearablePositionsToSlot(wearablePositionsMap[itemId]);
                npc->worn << item;
            }
//.........这里部分代码省略.........
开发者ID:AmesianX,项目名称:LoE-PrivateServer,代码行数:101,代码来源:quest.cpp

示例9: readSerialized

void SettingsSerializer::readSerialized()
{
    QFile f(path);
    if (!f.open(QIODevice::ReadOnly))
    {
        qWarning() << "Couldn't open file";
        return;
    }
    QByteArray data = f.readAll();
    f.close();

    // Decrypt
    if (tox_is_data_encrypted((uint8_t*)data.data()))
    {
        if (password.isEmpty())
        {
            qCritical() << "The settings file is encrypted, but we don't have a password!";
            return;
        }

        Core* core = Nexus::getCore();

        uint8_t salt[TOX_PASS_SALT_LENGTH];
        tox_get_salt(reinterpret_cast<uint8_t *>(data.data()), salt);
        auto passkey = core->createPasskey(password, salt);

        data = core->decryptData(data, *passkey);
        if (data.isEmpty())
        {
            qCritical() << "Failed to decrypt the settings file";
            return;
        }
    }
    else
    {
        if (!password.isEmpty())
            qWarning() << "We have a password, but the settings file is not encrypted";
    }

    if (memcmp(data.data(), magic, 4))
    {
        qWarning() << "Bad magic!";
        return;
    }
    data = data.mid(4);

    QDataStream stream(&data, QIODevice::ReadOnly);
    stream.setVersion(QDataStream::Qt_5_0);

    while (!stream.atEnd())
    {
        RecordTag tag;
        readStream(stream, tag);
        if (tag == RecordTag::Value)
        {
            QByteArray key;
            QByteArray value;
            readStream(stream, key);
            readStream(stream, value);
            setValue(QString::fromUtf8(key), QVariant(QString::fromUtf8(value)));
        }
        else if (tag == RecordTag::GroupStart)
        {
            QByteArray prefix;
            readStream(stream, prefix);
            beginGroup(QString::fromUtf8(prefix));
        }
        else if (tag == RecordTag::ArrayStart)
        {
            QByteArray prefix;
            readStream(stream, prefix);
            beginReadArray(QString::fromUtf8(prefix));
            QByteArray sizeData;
            readStream(stream, sizeData);
            if (sizeData.isEmpty())
            {
                qWarning("The personal save file is corrupted!");
                return;
            }
            quint64 size = dataToVUint(sizeData);
            arrays[array].size = max(size, arrays[array].size);
        }
        else if (tag == RecordTag::ArrayValue)
        {
            QByteArray indexData;
            readStream(stream, indexData);
            if (indexData.isEmpty())
            {
                qWarning("The personal save file is corrupted!");
                return;
            }
            quint64 index = dataToVUint(indexData);
            setArrayIndex(index);
            QByteArray key;
            QByteArray value;
            readStream(stream, key);
            readStream(stream, value);
            setValue(QString::fromUtf8(key), QVariant(QString::fromUtf8(value)));
        }
        else if (tag == RecordTag::ArrayEnd)
//.........这里部分代码省略.........
开发者ID:proton-byte,项目名称:qTox,代码行数:101,代码来源:settingsserializer.cpp

示例10: radioData

void DevicePluginElro::radioData(const QList<int> &rawData)
{    
    // filter right here a wrong signal length
    if (rawData.length() != 49) {
        return;
    }

    int delay = rawData.first()/31;
    QByteArray binCode;
    
    // average 314
    if (delay > 290 && delay < 400) {
        // go trough all 48 timings (without sync signal)
        for (int i = 1; i <= 48; i+=2 ) {
            int div;
            int divNext;
            
            // if short
            if (rawData.at(i) <= 700) {
                div = 1;
            } else {
                div = 3;
            }
            // if long
            if (rawData.at(i+1) < 700) {
                divNext = 1;
            } else {
                divNext = 3;
            }

             //      _
             //     | |___   = 0 -> in 4 delays => 1000
             //         _
             //     ___| |   = 1 -> in 4 delays => 0001

            if (div == 1 && divNext == 3) {
                binCode.append('0');
            } else if(div == 3 && divNext == 1) {
                binCode.append('1');
            } else {
                return;
            }
        }
    } else {
        return;
    }

    qCDebug(dcElro) << "Understands this protocol: " << binCode;

    if (binCode.left(20) == "00000100000000000001") {
        if (binCode.right(4) == "0100") {
            qCDebug(dcElro) << "Motion Detector OFF";
        } else {
            qCDebug(dcElro) << "Motion Detector ON";
        }
    }

    // get the channel of the remote signal (5 channels, true=1, false=0)
    QList<bool> group;
    for (int i = 1; i < 10; i+=2) {
        if (binCode.at(i-1) == '0' && binCode.at(i) == '1') {
            group << false;
        } else if(binCode.at(i-1) == '0' && binCode.at(i) == '0') {
            group << true;
        } else {
            return;
        }
    }
    
    // get the button letter
    QString button;
    QByteArray buttonCode = binCode.mid(10,10);

    if (buttonCode == "0001010101") {
        button = "A";
    } else if (buttonCode == "0100010101") {
        button = "B";
    } else if (buttonCode == "0101000101") {
        button = "C";
    } else if(buttonCode == "0101010001") {
        button = "D";
    } else if(buttonCode == "0101010100") {
        button = "E";
    } else {
        return;
    }

    // get power status -> On = 0100, Off = 0001
    bool power;
    if (binCode.right(4).toInt(0,2) == 1) {
        power = true;
    } else if(binCode.right(4).toInt(0,2) == 4) {
        power = false;
    } else {
        return;
    }

    qCDebug(dcElro) << group << buttonCode << power;
}
开发者ID:lampi87,项目名称:guh,代码行数:99,代码来源:devicepluginelro.cpp

示例11: refreshModStatus

void Profile::refreshModStatus()
{
  QFile file(getModlistFileName());
  if (!file.open(QIODevice::ReadOnly)) {
    throw MyException(tr("\"%1\" is missing or inaccessible").arg(getModlistFileName()));
  }

  bool modStatusModified = false;
  m_ModStatus.clear();
  m_ModStatus.resize(ModInfo::getNumMods());

  std::set<QString> namesRead;

  // load mods from file and update enabled state and priority for them
  int index = 0;
  while (!file.atEnd()) {
    QByteArray line = file.readLine().trimmed();
    bool enabled = true;
    QString modName;
    if (line.length() == 0) {
      // empty line
      continue;
    } else if (line.at(0) == '#') {
      // comment line
      continue;
    } else if (line.at(0) == '-') {
      enabled = false;
      modName = QString::fromUtf8(line.mid(1).trimmed().constData());
    } else if ((line.at(0) == '+')
               || (line.at(0) == '*')) {
      modName = QString::fromUtf8(line.mid(1).trimmed().constData());
    } else {
      modName = QString::fromUtf8(line.trimmed().constData());
    }
    if (modName.size() > 0) {
      QString lookupName = modName;
      if (namesRead.find(lookupName) != namesRead.end()) {
        continue;
      } else {
        namesRead.insert(lookupName);
      }
      unsigned int modIndex = ModInfo::getIndex(lookupName);
      if (modIndex != UINT_MAX) {
        ModInfo::Ptr info = ModInfo::getByIndex(modIndex);
        if ((modIndex < m_ModStatus.size())
            && (info->getFixedPriority() == INT_MIN)) {
          m_ModStatus[modIndex].m_Enabled = enabled;
          if (m_ModStatus[modIndex].m_Priority == -1) {
            if (static_cast<size_t>(index) >= m_ModStatus.size()) {
              throw MyException(tr("invalid index %1").arg(index));
            }
            m_ModStatus[modIndex].m_Priority = index++;
          }
        } else {
          qWarning("no mod state for \"%s\" (profile \"%s\")",
                   qPrintable(modName), m_Directory.path().toUtf8().constData());
          // need to rewrite the modlist to fix this
          modStatusModified = true;
        }
      } else {
        qDebug("mod \"%s\" (profile \"%s\") not found",
               qPrintable(modName), m_Directory.path().toUtf8().constData());
        // need to rewrite the modlist to fix this
        modStatusModified = true;
      }
    }
  }

  int numKnownMods = index;

  int topInsert = 0;

  // invert priority order to match that of the pluginlist. Also
  // give priorities to mods not referenced in the profile
  for (size_t i = 0; i < m_ModStatus.size(); ++i) {
    ModInfo::Ptr modInfo = ModInfo::getByIndex(i);
    if (modInfo->alwaysEnabled()) {
      m_ModStatus[i].m_Enabled = true;
    }

    if (modInfo->getFixedPriority() == INT_MAX) {
      continue;
    }

    if (m_ModStatus[i].m_Priority != -1) {
      m_ModStatus[i].m_Priority = numKnownMods - m_ModStatus[i].m_Priority - 1;
    } else {
      if (static_cast<size_t>(index) >= m_ModStatus.size()) {
        throw MyException(tr("invalid index %1").arg(index));
      }
      if (modInfo->hasFlag(ModInfo::FLAG_FOREIGN)) {
        m_ModStatus[i].m_Priority = --topInsert;
      } else {
        m_ModStatus[i].m_Priority = index++;
      }
      // also, mark the mod-list as changed
      modStatusModified = true;
    }
  }
  // to support insertion of new mods at the top we may now have mods with negative priority. shift them all up
//.........这里部分代码省略.........
开发者ID:RevReese,项目名称:modorganizer,代码行数:101,代码来源:profile.cpp

示例12: stunHash

void stunHash()
{
    QString m_localUser = "XiSh";
    QString m_remoteUser = "B23U";
    QString m_remotePassword = "EXlVjyYgSRcC4OAxMSYDFF";

    QByteArray username = QString("%1:%2").arg(m_remoteUser, m_localUser).toUtf8();
    quint16 usernameSize = username.size();
    username += QByteArray::fromHex("e1c318");
//    username += QByteArray(4 * ((usernameSize + 3) / 4) - usernameSize, 0);
    quint32 priority = 1862270975;
    QByteArray unknown(8, 0);
    QByteArray key = m_remotePassword.toUtf8();

    QByteArray buffer;
    QDataStream stream(&buffer, QIODevice::WriteOnly);
    quint16 type = BindingRequest;
    quint16 length = 0;
    QByteArray id = QByteArray::fromHex("93be62deb6e5418f9f87b68b");
    stream << type;
    stream << length;
    stream << MAGIC_COOKIE;
    stream.writeRawData(id.data(), id.size());

    stream << quint16(Priority);
    stream << quint16(sizeof(priority));
    stream << priority;

    stream << quint16(Unknown);
    stream << quint16(unknown.size());
    stream.writeRawData(unknown.data(), unknown.size());

    stream << quint16(Username);
    stream << usernameSize;
    stream.writeRawData(username.data(), username.size());

    // integrity
    length = buffer.size() - 20 + 24;
    qint64 pos = stream.device()->pos();
    stream.device()->seek(2);
    stream << length;
    stream.device()->seek(pos);

    QByteArray integrity = QXmppUtils::generateHmacSha1(key, buffer);
    qDebug() << "integrity" << integrity.toHex();
    stream << quint16(MessageIntegrity);
    stream << quint16(integrity.size());
    stream.writeRawData(integrity.data(), integrity.size());

    // fingerprint
    length = buffer.size() - 20 + 8;
    pos = stream.device()->pos();
    stream.device()->seek(2);
    stream << length;
    stream.device()->seek(pos);

    quint32 fingerprint = QXmppUtils::generateCrc32(buffer) ^ 0x5354554eL;
    qDebug() << "fingerprint" << fingerprint;
    stream << quint16(Fingerprint);
    stream << quint16(sizeof(fingerprint));
    stream << fingerprint;

    // output
    buffer.prepend(QByteArray(10, 0));
    for (int i = 0; i < buffer.size(); i += 16)
    {
        QByteArray chunk = buffer.mid(i, 16);
        QString str;
        for (int j = 0; j < 16; j += 1)
            str += chunk.mid(j, 1).toHex() + " ";
        qDebug() << str;
    }

}
开发者ID:jlaine,项目名称:wilink,代码行数:74,代码来源:hasher.cpp

示例13: tcpProcessPendingDatagrams


//.........这里部分代码省略.........
                data = removeHTTPHeader(data, "Connection:");
                data = removeHTTPHeader(data, "Vary:");
                data = removeHTTPHeader(data, "X-Powered-By:");
                data = removeHTTPHeader(data, "accept-encoding:");
                data = removeHTTPHeader(data, "if-modified-since:");

                if (data.size() >= length) // Wait until we have all the data, then process it all
                {
                    data.truncate(length);
                    tcpProcessData(data, socket);
                    *recvBuffer = recvBuffer->right(recvBuffer->size() - recvBuffer->indexOf(data) - data.size());
                    if (recvBuffer->isEmpty())
                        return;
                    nTries=0;
                }
            }
        }
        else if (recvBuffer->contains("\r\n\r\n")) // POST or GET request, without a Content-Length header
        {
            QByteArray data = *recvBuffer;
            data = data.left(data.indexOf("\r\n\r\n")+4);
            int dataSize = data.size();
#if DEBUG_LOG
            logMessage(tr("Got non-content length request:")+data);
#endif

            int i1=0;
            do
            {
                i1 = data.indexOf("GET");
                if (i1 != -1)
                {
                    int i2 = data.indexOf("HTTP")-1;
                    QString path = data.mid(i1 + 4, i2-i1-4);
                    if (path == "/log") // GET /log
                    {
                        data = removeHTTPHeader(data, "POST ");
                        data = removeHTTPHeader(data, "GET ");
                        data = removeHTTPHeader(data, "if-modified-since:");
                        data = removeHTTPHeader(data, "accept-encoding:");
                        data = removeHTTPHeader(data, "host:");
                        if (!enableGetlog)
                            continue;
                        QFile head(QString(NETDATAPATH)+"/dataTextHeader.bin");
                        head.open(QIODevice::ReadOnly);
                        if (!head.isOpen())
                        {
                            logError(tr("Can't open header : ","The header is a file")+head.errorString());
                            continue;
                        }
                        QByteArray logData = ui->log->toPlainText().toLatin1();
                        socket->write(head.readAll());
                        socket->write(QString("Content-Length: "+QString().setNum(logData.size())+"\r\n\r\n").toLocal8Bit());
                        socket->write(logData);
                        head.close();
                        logMessage(tr("Sent log to %1").arg(socket->peerAddress().toString()));
                        continue;
                    }
                    // Other GETs (not getlog)
                    data = removeHTTPHeader(data, "POST ");
                    data = removeHTTPHeader(data, "GET ");
                    logMessage(tr("TCP: Replying to HTTP GET %1").arg(path));
                    QFile head(QString(NETDATAPATH)+"/dataHeader.bin");
                    QFile res("data/"+path);
                    head.open(QIODevice::ReadOnly);
                    if (!head.isOpen())
开发者ID:DanielOaks,项目名称:LoE-PrivateServer,代码行数:67,代码来源:tcp.cpp

示例14: if

// This function goes through the entire byte array
// and tries to see whether this is a valid UTF-8 sequence.
// If it's valid, this is probably a UTF-8 string.
bool HTMLEncodingResolver::IsValidUtf8(const QByteArray &string)
{
    // This is an implementation of the Perl code written here:
    //   http://www.w3.org/International/questions/qa-forms-utf-8
    //
    // Basically, UTF-8 has a very specific byte-pattern. This function
    // checks if the sent byte-sequence conforms to this pattern.
    // If it does, chances are *very* high that this is UTF-8.
    //
    // This function is written to be fast, not pretty.
    if (string.isNull()) {
        return false;
    }

    int index = 0;

    while (index < string.size()) {
        QByteArray dword = string.mid(index, 4);

        if (dword.size() < 4) {
            dword = dword.leftJustified(4, '\0');
        }

        const unsigned char *bytes = (const unsigned char *) dword.constData();

        // ASCII
        if (bytes[0] == 0x09 ||
            bytes[0] == 0x0A ||
            bytes[0] == 0x0D ||
            (0x20 <= bytes[0] && bytes[0] <= 0x7E)
           ) {
            index += 1;
        }
        // non-overlong 2-byte
        else if ((0xC2 <= bytes[0] && bytes[0] <= 0xDF) &&
                 (0x80 <= bytes[1] && bytes[1] <= 0xBF)
                ) {
            index += 2;
        } else if ((bytes[0] == 0xE0                         &&              // excluding overlongs
                    (0xA0 <= bytes[1] && bytes[1] <= 0xBF) &&
                    (0x80 <= bytes[2] && bytes[2] <= 0xBF)) ||
                   (((0xE1 <= bytes[0] && bytes[0] <= 0xEC) ||               // straight 3-byte
                     bytes[0] == 0xEE                         ||
                     bytes[0] == 0xEF) &&
                    (0x80 <= bytes[1] && bytes[1] <= 0xBF)   &&
                    (0x80 <= bytes[2] && bytes[2] <= 0xBF)) ||
                   (bytes[0] == 0xED                         &&              // excluding surrogates
                    (0x80 <= bytes[1] && bytes[1] <= 0x9F) &&
                    (0x80 <= bytes[2] && bytes[2] <= 0xBF))
                  ) {
            index += 3;
        } else if ((bytes[0] == 0xF0                         &&              // planes 1-3
                    (0x90 <= bytes[1] && bytes[1] <= 0xBF) &&
                    (0x80 <= bytes[2] && bytes[2] <= 0xBF) &&
                    (0x80 <= bytes[3] && bytes[3] <= 0xBF)) ||
                   ((0xF1 <= bytes[0] && bytes[0] <= 0xF3) &&              // planes 4-15
                    (0x80 <= bytes[1] && bytes[1] <= 0xBF) &&
                    (0x80 <= bytes[2] && bytes[2] <= 0xBF) &&
                    (0x80 <= bytes[3] && bytes[3] <= 0xBF)) ||
                   (bytes[0] == 0xF4                         &&            // plane 16
                    (0x80 <= bytes[1] && bytes[1] <= 0x8F) &&
                    (0x80 <= bytes[2] && bytes[2] <= 0xBF) &&
                    (0x80 <= bytes[3] && bytes[3] <= 0xBF))
                  ) {
            index += 4;
        } else {
            return false;
        }
    }

    return true;
}
开发者ID:AmesianX,项目名称:Sigil,代码行数:75,代码来源:HTMLEncodingResolver.cpp

示例15: fopen

Segment *SegmentNoaa::ReadSegmentInMemory()
{
    FILE*   f;
    BZFILE* b;
    int     nBuf;
    char    buf[ 11090 * 2 ];
    int     bzerror;

    quint16 val1_ch[5], val2_ch[5],tot_ch[5];
    QByteArray picture_line;

    int heightinsegment = 0;

    f = fopen ( this->fileInfo.absoluteFilePath().toLatin1(), "rb" );
    if ( !f ) {
        qDebug() << QString("file %1 not found ! ").arg(this->fileInfo.absoluteFilePath());
        segmentok = false;
        return this;
    }

    qDebug() << "Bz2 file " + this->fileInfo.absoluteFilePath() + " is open";

    if((b = BZ2_bzopen(this->fileInfo.absoluteFilePath().toLatin1(),"rb"))==NULL)
    {
        segmentok = false;
        qDebug() << "error in BZ2_bzopen";
    }

    bzerror = BZ_OK;
    while ( bzerror == BZ_OK )
    {
      nBuf = BZ2_bzRead ( &bzerror, b, buf, 11090 * 2 );
      if ( bzerror == BZ_OK || bzerror == BZ_STREAM_END)
      {
          QByteArray data = QByteArray::fromRawData(buf, sizeof(buf));
          picture_line = data.mid( 1500, 20480 );

          if ((data.at(0) & 0xFF) == 0x02 && (data.at(1) & 0xFF) == 0x84
              && (data.at(2) & 0xFF) == 0x01 && (data.at(3) & 0xFF) == 0x6f
              && (data.at(4) & 0xFF) == 0x03 && (data.at(5) & 0xFF) == 0x5c
              && (data.at(6) & 0xFF) == 0x01 && (data.at(7) & 0xFF) == 0x9d
              && (data.at(8) & 0xFF) == 0x02 && (data.at(9) & 0xFF) == 0x0f
              && (data.at(10) & 0xFF) == 0x00 && (data.at(11) & 0xFF) == 0x95)
          {

              for (int i=0, j = 0; i < 20471; i+=10, j++)
              {
                  for(int k = 0, l = 0; k < 5; k++)
                  {
                    val1_ch[k] = 0xFF & picture_line.at(i+l);
                    l++;
                    val2_ch[k] = 0xFF & picture_line.at(i+l);
                    l++;
                    tot_ch[k] = (val1_ch[k] <<= 8) | val2_ch[k];
                    *(this->ptrbaChannel[k].data() + heightinsegment * 2048 + j) = tot_ch[k];

                  }

                  for(int k = 0 ; k < 5; k++)
                  {
                      if (tot_ch[k] < stat_min_ch[k] )
                          stat_min_ch[k] = tot_ch[k];
                      if (tot_ch[k] > stat_max_ch[k] )
                          stat_max_ch[k] = tot_ch[k];
                  }
              }
              heightinsegment++;
          }
      }
    }

    //NbrOfLines = heightinsegment;
    BZ2_bzclose ( b );
    fclose(f);

    return this;

}
开发者ID:hvanruys,项目名称:EUMETCastView,代码行数:78,代码来源:segmentnoaa.cpp


注:本文中的QByteArray::mid方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。