QString Transfer::statusString() const { switch (status()) { case Paused: return tr("Paused"); case Canceled: return tr("Canceled"); case Failed: return tr("Failed: %1").arg(errorString()); case Completed: return tr("Completed"); case Queued: return tr("Queued"); case Connecting: return tr("Connecting"); case Downloading: return tr("Downloading"); case Uploading: return tr("Uploading"); case ExecutingCustomCommand: return tr("Executing custom command"); default: return QString(); } }
bool AgarServer::setupNetworking() { /****************Networking Setup*********************/ //based on max number of players and threads we determine the number of //connections each thread manages int numPerThread = Config::gameMaxPlayers/Config::maxConnectionThreads; if(numPerThread == 0){ numPerThread = 1; } for(int i=0;i<Config::maxConnectionThreads;i++){ createAgarThread(numPerThread); } //listen on port 57488 for whatever reason if(!listen(QHostAddress::Any,port)){ qCritical("Error listening: %s",errorString().toUtf8().constData()); return false; } qDebug("Listening on %i.",port); return true; }
//==================================== // Constructor... //------------------------------------ SaXImportSysp::SaXImportSysp (int section) { // .../ //! An object of this type is used to create a SYSP based //! SaX import. Refering to the given section ID the correct //! sysp.pl options are set. // ---- mOptions.append ((const char*)"-q"); switch (section) { case SYSP_MOUSE: mSectionName = "Mouse"; mOptions.append ((const char*)"mouse"); break; case SYSP_KEYBOARD: mSectionName = "Keyboard"; mOptions.append ((const char*)"keyboard"); break; case SYSP_CARD: mSectionName = "Card"; mOptions.append ((const char*)"server"); break; case SYSP_DESKTOP: mSectionName = "Desktop"; mOptions.append ((const char*)"xstuff"); break; case SYSP_3D: mSectionName = "3D"; mOptions.append ((const char*)"3d"); break; default: excImportSectionFailed(); qError (errorString(),EXC_IMPORTSECTIONFAILED); mSectionName = "Undefined"; break; } mSection = section; }
void DialogNewCamera::listCameras(std::function<void(const QJsonArray &arr)> dataCb) { QString url = listUrl; url += QStringLiteral("&_sid=%1").arg(apiSid); QUrl u(url); QNetworkRequest request(u); request.setHeader(QNetworkRequest::ContentTypeHeader, "application/json"); auto reply = nm->get(request); connect(reply, &QNetworkReply::finished, [=]() { reply->deleteLater(); if (reply->error() != QNetworkReply::NoError) { QMessageBox::warning(this, tr("Calaos Installer"), reply->errorString()); dataCb({}); return; } QByteArray bytes = reply->readAll(); bool err; QJsonObject jdata = parseResult(bytes, err); if (err) QMessageBox::warning(this, tr("Calaos Installer"), tr("Failed to list cameras")); if (err || !jdata["cameras"].isArray()) { dataCb({}); return; } dataCb(jdata["cameras"].toArray()); }); }
// ------------------------------------------------------------------- StringArray PosixRegEx::grep(const StringArray &src, int eflags) { if( !compiled) { BLOCXX_THROW(RegExCompileException, "Regular expression is not compiled"); } m_ecode = REG_NOERROR; m_error.erase(); StringArray out; if( !src.empty()) { StringArray::const_iterator i=src.begin(); for( ; i != src.end(); ++i) { int ret = ::regexec(&m_regex, i->c_str(), 0, NULL, eflags); if( ret == REG_NOERROR) { out.push_back(*i); } else if(ret != REG_NOMATCH) { m_ecode = ret; m_error = getError(&m_regex, m_ecode); BLOCXX_THROW_ERR(RegExExecuteException, errorString().c_str(), m_ecode); } } } return out; }
/** * This function is used for activating the socket listener. * @param filename Full path to a file to be used as the socket. * @param perm Permissions to be used on the socket. * @return Returns true on success, otherwise returns an error. */ ReturnValue QtRpc::ServerProtocolListenerSocket::listen(QString filename, SocketPermission perm) { //Remove old socket if it exists if (QFile::exists(filename)) { if (!QFile::remove(filename)) { qWarning() << "Unable to remove old socket file" << filename; } } //listen on the socket if (!QLocalServer::listen(filename)) { //an error occured return(ReturnValue(1, errorString())); } //set up permissions switch (perm) { case Owner: QFile::setPermissions(filename, QFile::ReadOwner | QFile::WriteOwner | QFile::ExeOwner); break; case Group: QFile::setPermissions(filename, QFile::ReadOwner | QFile::WriteOwner | QFile::ExeOwner | QFile::ReadGroup | QFile::WriteGroup | QFile::ExeGroup); break; case Everyone: QFile::setPermissions(filename, QFile::ReadOwner | QFile::WriteOwner | QFile::ExeOwner | QFile::ReadGroup | QFile::WriteGroup | QFile::ExeGroup | QFile::ReadOther | QFile::WriteOther | QFile::ExeOther); break; } return ReturnValue(true); }
//==================================== // addInputDevice //------------------------------------ int SaXManipulateDevices::addInputDevice (const char* fashion) { // .../ //! add a new input device at the end of the current input //! device list. The new input device ID is returned. pointer //! input devices are following the odd order (1,3,5,7...) //! whereas keyboard input devices use the even order (0,2,4,6...) // ---- if (! inputHandlingAllowed) { return -1; } //==================================== // check fashion string... //------------------------------------ QString inputFashion (fashion); if ( (inputFashion != SAX_INPUT_TOUCHPANEL) && (inputFashion != SAX_INPUT_TABLET) && (inputFashion != SAX_INPUT_PEN) && (inputFashion != SAX_INPUT_ERASER) && (inputFashion != SAX_INPUT_MOUSE) && (inputFashion != SAX_INPUT_VNC) && (inputFashion != SAX_INPUT_KEYBOARD) ) { excWrongInputFashion (fashion); qError (errorString(),EXC_WRONGINPUTFASHION); return -1; } //==================================== // determine new input device ID... //------------------------------------ QString baseID ("Mouse"); QString baseDriver ("mouse"); if (fashion == SAX_INPUT_VNC) { baseDriver = "rfbmouse"; } QDict<QString>* data = mInput->getTablePointer (0); int newID = mInput->getCount (true) * 2 + 1; if ((data) && (! data->isEmpty())) { baseDriver ="kbd"; if (fashion == SAX_INPUT_VNC) { baseDriver = "rfbkeyb"; } baseID = "Keyboard"; newID = mInput->getCount (true) * 2; } if (! mInput -> addID (newID)) { return -1; } //==================================== // add new input device section... //------------------------------------ QString newIDstring; newIDstring.sprintf ("%d",newID); mInput -> setItem ("Identifier",baseID + "[" + newIDstring + "]"); mInput -> setItem ("InputFashion",fashion); //==================================== // set some defaults... //------------------------------------ mInput -> setItem ("Driver",baseDriver); //==================================== // update server layout //------------------------------------ if (baseID == "Mouse") { QString inputDevice; QTextOStream (&inputDevice) << mLayout -> getItem ("InputDevice") << ",Mouse[" << newIDstring << "]"; mLayout -> setItem ("InputDevice",inputDevice); } if (baseID == "Keyboard") { QString inputDevice; QTextOStream (&inputDevice) << mLayout -> getItem ("Keyboard") << ",Keyboard[" << newIDstring << "]"; mLayout -> setItem ("Keyboard",inputDevice); } return mInput -> getCurrentID(); }
bool TSReader::read(Translator &translator) { STRING(both); STRING(byte); STRING(comment); STRING(context); STRING(defaultcodec); STRING(encoding); STRING(extracomment); STRING(filename); STRING(id); STRING(language); STRING(line); STRING(location); STRING(message); STRING(name); STRING(numerus); STRING(numerusform); STRING(obsolete); STRING(oldcomment); STRING(oldsource); STRING(source); STRING(sourcelanguage); STRING(translation); STRING(translatorcomment); STRING(true); STRING(TS); STRING(type); STRING(unfinished); STRING(userdata); STRING(utf8); STRING(value); //STRING(version); STRING(yes); static const QString strextrans(QLatin1String("extra-")); static const QString strUtf8(QLatin1String("UTF-8")); while (!atEnd()) { readNext(); if (isStartDocument()) { // <!DOCTYPE TS> //qDebug() << attributes(); } else if (isEndDocument()) { // <!DOCTYPE TS> //qDebug() << attributes(); } else if (isDTD()) { // <!DOCTYPE TS> //qDebug() << tokenString(); } else if (elementStarts(strTS)) { // <TS> //qDebug() << "TS " << attributes(); QHash<QString, int> currentLine; QString currentFile; QXmlStreamAttributes atts = attributes(); //QString version = atts.value(strversion).toString(); translator.setLanguageCode(atts.value(strlanguage).toString()); translator.setSourceLanguageCode(atts.value(strsourcelanguage).toString()); while (!atEnd()) { readNext(); if (isEndElement()) { // </TS> found, finish local loop break; } else if (isWhiteSpace()) { // ignore these, just whitespace } else if (elementStarts(strdefaultcodec)) { // <defaultcodec> const QString &codec = readElementText(); if (!codec.isEmpty()) translator.setCodecName(codec.toLatin1()); // </defaultcodec> } else if (isStartElement() && name().toString().startsWith(strextrans)) { // <extra-...> QString tag = name().toString(); translator.setExtra(tag.mid(6), readContents()); // </extra-...> } else if (elementStarts(strcontext)) { // <context> QString context; while (!atEnd()) { readNext(); if (isEndElement()) { // </context> found, finish local loop break; } else if (isWhiteSpace()) { // ignore these, just whitespace } else if (elementStarts(strname)) { // <name> context = readElementText(); // </name> } else if (elementStarts(strmessage)) { // <message> TranslatorMessage::References refs; QString currentMsgFile = currentFile; TranslatorMessage msg; msg.setId(attributes().value(strid).toString()); msg.setContext(context); msg.setType(TranslatorMessage::Finished); msg.setPlural(attributes().value(strnumerus) == stryes); const QStringRef &utf8Attr = attributes().value(strutf8); msg.setNonUtf8(utf8Attr == strboth); msg.setUtf8(msg.isNonUtf8() || utf8Attr == strtrue || attributes().value(strencoding) == strUtf8); while (!atEnd()) { readNext(); if (isEndElement()) { // </message> found, finish local loop msg.setReferences(refs); translator.append(msg); break; } else if (isWhiteSpace()) { // ignore these, just whitespace } else if (elementStarts(strsource)) { // <source>...</source> msg.setSourceText(readContents()); } else if (elementStarts(stroldsource)) { // <oldsource>...</oldsource> msg.setOldSourceText(readContents()); } else if (elementStarts(stroldcomment)) { // <oldcomment>...</oldcomment> msg.setOldComment(readContents()); } else if (elementStarts(strextracomment)) { // <extracomment>...</extracomment> msg.setExtraComment(readContents()); } else if (elementStarts(strtranslatorcomment)) { // <translatorcomment>...</translatorcomment> msg.setTranslatorComment(readContents()); } else if (elementStarts(strlocation)) { // <location/> QXmlStreamAttributes atts = attributes(); QString fileName = atts.value(strfilename).toString(); if (fileName.isEmpty()) { fileName = currentMsgFile; } else { if (refs.isEmpty()) currentFile = fileName; currentMsgFile = fileName; } const QString lin = atts.value(strline).toString(); if (lin.isEmpty()) { translator.setLocationsType(Translator::RelativeLocations); refs.append(TranslatorMessage::Reference(fileName, -1)); } else { bool bOK; int lineNo = lin.toInt(&bOK); if (bOK) { if (lin.startsWith(QLatin1Char('+')) || lin.startsWith(QLatin1Char('-'))) { lineNo = (currentLine[fileName] += lineNo); translator.setLocationsType(Translator::RelativeLocations); } else { translator.setLocationsType(Translator::AbsoluteLocations); } refs.append(TranslatorMessage::Reference(fileName, lineNo)); } } readContents(); } else if (elementStarts(strcomment)) { // <comment>...</comment> msg.setComment(readContents()); } else if (elementStarts(struserdata)) { // <userdata>...</userdata> msg.setUserData(readContents()); } else if (elementStarts(strtranslation)) { // <translation> QXmlStreamAttributes atts = attributes(); QStringRef type = atts.value(strtype); if (type == strunfinished) msg.setType(TranslatorMessage::Unfinished); else if (type == strobsolete) msg.setType(TranslatorMessage::Obsolete); if (msg.isPlural()) { QStringList translations; while (!atEnd()) { readNext(); if (isEndElement()) { break; } else if (isWhiteSpace()) { // ignore these, just whitespace } else if (elementStarts(strnumerusform)) { translations.append(readTransContents()); } else { handleError(); break; } } msg.setTranslations(translations); } else { msg.setTranslation(readTransContents()); } // </translation> } else if (isStartElement() && name().toString().startsWith(strextrans)) { // <extra-...> QString tag = name().toString(); msg.setExtra(tag.mid(6), readContents()); // </extra-...> } else { handleError(); } } // </message> } else { handleError(); } } // </context> } else { handleError(); } } // </TS> } else { handleError(); } } if (hasError()) { m_cd.appendError(errorString()); return false; } return true; }
int main (int argc, char **argv) { std::string brokers = "localhost"; std::string errstr; std::vector<std::string> topics; std::string conf_file; std::string mode = "P"; int throughput = 0; int32_t partition = RdKafka::Topic::PARTITION_UA; bool do_conf_dump = false; MyHashPartitionerCb hash_partitioner; /* * Create configuration objects */ RdKafka::Conf *conf = RdKafka::Conf::create(RdKafka::Conf::CONF_GLOBAL); RdKafka::Conf *tconf = RdKafka::Conf::create(RdKafka::Conf::CONF_TOPIC); { char hostname[128]; gethostname(hostname, sizeof(hostname)-1); conf->set("client.id", std::string("rdkafka@") + hostname, errstr); } conf->set("debug", "cgrp,topic", errstr); for (int i = 1 ; i < argc ; i++) { const char *name = argv[i]; const char *val = i+1 < argc ? argv[i+1] : NULL; if (val && !strncmp(val, "--", 2)) val = NULL; std::cout << now() << ": argument: " << name << " " << (val?val:"") << std::endl; if (val) { if (!strcmp(name, "--topic")) topics.push_back(val); else if (!strcmp(name, "--broker-list")) brokers = val; else if (!strcmp(name, "--max-messages")) state.maxMessages = atoi(val); else if (!strcmp(name, "--throughput")) throughput = atoi(val); else if (!strcmp(name, "--producer.config") || !strcmp(name, "--consumer.config")) read_conf_file(val); else if (!strcmp(name, "--group-id")) conf->set("group.id", val, errstr); else if (!strcmp(name, "--session-timeout")) conf->set("session.timeout.ms", val, errstr); else if (!strcmp(name, "--reset-policy")) { if (tconf->set("auto.offset.reset", val, errstr)) { std::cerr << now() << ": " << errstr << std::endl; exit(1); } } else if (!strcmp(name, "--debug")) { conf->set("debug", val, errstr); } else { std::cerr << now() << ": Unknown option " << name << std::endl; exit(1); } i++; } else { if (!strcmp(name, "--consumer")) mode = "C"; else if (!strcmp(name, "--producer")) mode = "P"; else if (!strcmp(name, "--enable-autocommit")) { state.consumer.useAutoCommit = true; conf->set("enable.auto.commit", "true", errstr); } else { std::cerr << now() << ": Unknown option or missing argument to " << name << std::endl; exit(1); } } } if (topics.empty() || brokers.empty()) { std::cerr << now() << ": Missing --topic and --broker-list" << std::endl; exit(1); } /* * Set configuration properties */ conf->set("metadata.broker.list", brokers, errstr); ExampleEventCb ex_event_cb; conf->set("event_cb", &ex_event_cb, errstr); if (do_conf_dump) { int pass; for (pass = 0 ; pass < 2 ; pass++) { std::list<std::string> *dump; if (pass == 0) { dump = conf->dump(); std::cerr << now() << ": # Global config" << std::endl; } else { dump = tconf->dump(); std::cerr << now() << ": # Topic config" << std::endl; } for (std::list<std::string>::iterator it = dump->begin(); it != dump->end(); ) { std::cerr << *it << " = "; it++; std::cerr << *it << std::endl; it++; } std::cerr << std::endl; } exit(0); } signal(SIGINT, sigterm); signal(SIGTERM, sigterm); signal(SIGALRM, sigwatchdog); if (mode == "P") { /* * Producer mode */ ExampleDeliveryReportCb ex_dr_cb; /* Set delivery report callback */ conf->set("dr_cb", &ex_dr_cb, errstr); /* * Create producer using accumulated global configuration. */ RdKafka::Producer *producer = RdKafka::Producer::create(conf, errstr); if (!producer) { std::cerr << now() << ": Failed to create producer: " << errstr << std::endl; exit(1); } std::cerr << now() << ": % Created producer " << producer->name() << std::endl; /* * Create topic handle. */ RdKafka::Topic *topic = RdKafka::Topic::create(producer, topics[0], tconf, errstr); if (!topic) { std::cerr << now() << ": Failed to create topic: " << errstr << std::endl; exit(1); } static const int delay_us = throughput ? 1000000/throughput : 0; if (state.maxMessages == -1) state.maxMessages = 1000000; /* Avoid infinite produce */ for (int i = 0 ; run && i < state.maxMessages ; i++) { /* * Produce message */ std::ostringstream msg; msg << i; RdKafka::ErrorCode resp = producer->produce(topic, partition, RdKafka::Producer::RK_MSG_COPY /* Copy payload */, const_cast<char *>(msg.str().c_str()), msg.str().size(), NULL, NULL); if (resp != RdKafka::ERR_NO_ERROR) { errorString("producer_send_error", RdKafka::err2str(resp), topic->name(), NULL, msg.str()); state.producer.numErr++; } else { std::cerr << now() << ": % Produced message (" << msg.str().size() << " bytes)" << std::endl; state.producer.numSent++; } producer->poll(delay_us / 1000); watchdog_kick(); } run = true; while (run && producer->outq_len() > 0) { std::cerr << now() << ": Waiting for " << producer->outq_len() << std::endl; producer->poll(50); watchdog_kick(); } std::cerr << now() << ": " << state.producer.numAcked << "/" << state.producer.numSent << "/" << state.maxMessages << " msgs acked/sent/max, " << state.producer.numErr << " errored" << std::endl; delete topic; delete producer; } else if (mode == "C") { /* * Consumer mode */ tconf->set("auto.offset.reset", "smallest", errstr); /* Set default topic config */ conf->set("default_topic_conf", tconf, errstr); ExampleRebalanceCb ex_rebalance_cb; conf->set("rebalance_cb", &ex_rebalance_cb, errstr); ExampleOffsetCommitCb ex_offset_commit_cb; conf->set("offset_commit_cb", &ex_offset_commit_cb, errstr); /* * Create consumer using accumulated global configuration. */ consumer = RdKafka::KafkaConsumer::create(conf, errstr); if (!consumer) { std::cerr << now() << ": Failed to create consumer: " << errstr << std::endl; exit(1); } std::cerr << now() << ": % Created consumer " << consumer->name() << std::endl; /* * Subscribe to topic(s) */ RdKafka::ErrorCode resp = consumer->subscribe(topics); if (resp != RdKafka::ERR_NO_ERROR) { std::cerr << now() << ": Failed to subscribe to " << topics.size() << " topics: " << RdKafka::err2str(resp) << std::endl; exit(1); } /* * Consume messages */ while (run) { RdKafka::Message *msg = consumer->consume(500); msg_consume(consumer, msg, NULL); delete msg; watchdog_kick(); } /* Final commit */ do_commit(consumer, 1); /* * Stop consumer */ consumer->close(); delete consumer; } /* * Wait for RdKafka to decommission. * This is not strictly needed (when check outq_len() above), but * allows RdKafka to clean up all its resources before the application * exits so that memory profilers such as valgrind wont complain about * memory leaks. */ RdKafka::wait_destroyed(5000); std::cerr << now() << ": EXITING WITH RETURN VALUE 0" << std::endl; return 0; }
void QMLManager::loadDivesWithValidCredentials() { QString url; timestamp_t currentDiveTimestamp = selectedDiveTimestamp(); if (getCloudURL(url)) { QString errorString(get_error_string()); appendTextToLog(errorString); setStartPageText(RED_FONT + tr("Cloud storage error: %1").arg(errorString) + END_FONT); revertToNoCloudIfNeeded(); return; } QByteArray fileNamePrt = QFile::encodeName(url); git_repository *git; const char *branch; int error; if (check_git_sha(fileNamePrt.data(), &git, &branch) == 0) { qDebug() << "local cache was current, no need to modify dive list"; appendTextToLog("Cloud sync shows local cache was current"); goto successful_exit; } appendTextToLog("Cloud sync brought newer data, reloading the dive list"); clear_dive_file_data(); if (git != dummy_git_repository) { appendTextToLog(QString("have repository and branch %1").arg(branch)); error = git_load_dives(git, branch); } else { appendTextToLog(QString("didn't receive valid git repo, try again")); error = parse_file(fileNamePrt.data()); } setAccessingCloud(-1); if (!error) { report_error("filename is now %s", fileNamePrt.data()); const char *error_string = get_error_string(); appendTextToLog(error_string); set_filename(fileNamePrt.data(), true); } else { report_error("failed to open file %s", fileNamePrt.data()); QString errorString(get_error_string()); appendTextToLog(errorString); revertToNoCloudIfNeeded(); return; } consumeFinishedLoad(currentDiveTimestamp); successful_exit: alreadySaving = false; setLoadFromCloud(true); // if we came from local storage mode, let's merge the local data into the local cache // for the remote data - which then later gets merged with the remote data if necessary if (oldStatus() == NOCLOUD) { git_storage_update_progress(false, "import dives from nocloud local storage"); dive_table.preexisting = dive_table.nr; mergeLocalRepo(); DiveListModel::instance()->clear(); DiveListModel::instance()->addAllDives(); appendTextToLog(QStringLiteral("%1 dives loaded after importing nocloud local storage").arg(dive_table.nr)); saveChangesLocal(); if (syncToCloud() == false) { appendTextToLog(QStringLiteral("taking things back offline now that storage is synced")); prefs.git_local_only = syncToCloud(); } } setAccessingCloud(-1); // if we got here just for an initial connection to the cloud, reset to offline if (currentGitLocalOnly) { currentGitLocalOnly = false; prefs.git_local_only = true; } return; }
QList<QCharsetMatch> QCharsetDetector::detectAll() { Q_D(QCharsetDetector); clearError(); // get list of matches from ICU: qint32 matchesFound; const UCharsetMatch **uCharsetMatch = ucsdet_detectAll(d->_uCharsetDetector, &matchesFound, &(d->_status)); if(hasError()) { qWarning() << __PRETTY_FUNCTION__ << errorString(); return QList<QCharsetMatch>(); } // sometimes the number of matches found by ucsdet_detectAll() // maybe 0 (matchesFound == 0) but d->_status has no error. Do not // return here with an error if this happens because the fine // tuning below may add more matches. Better check whether no // matches were found at all *after* the fine tuning. // fill list of matches into a QList<QCharsetMatch>: QList<QCharsetMatch> qCharsetMatchList; for (qint32 i = 0; i < matchesFound; ++i) { QCharsetMatch qCharsetMatch; qCharsetMatch.setName( QString::fromLatin1(ucsdet_getName(uCharsetMatch[i], &(d->_status)))); if(hasError()) { qWarning() << __PRETTY_FUNCTION__ << errorString(); return QList<QCharsetMatch>(); } qCharsetMatch.setConfidence( static_cast<qint32>(ucsdet_getConfidence (uCharsetMatch[i], &(d->_status)))); if(hasError()) { qWarning() << __PRETTY_FUNCTION__ << errorString(); return QList<QCharsetMatch>(); } qCharsetMatch.setLanguage( QString::fromLatin1(ucsdet_getLanguage(uCharsetMatch[i], &(d->_status)))); if(hasError()) { qWarning() << __PRETTY_FUNCTION__ << errorString(); return QList<QCharsetMatch>(); } qCharsetMatchList << qCharsetMatch; } if(d->_allDetectableCharsets.isEmpty()) getAllDetectableCharsets(); // libicu sometimes does not detect single byte encodings at all // even if they can encode the input without error. This seems to // contradict the documentation on // http://icu-project.org/apiref/icu4c/ucsdet_8h.html which says: // // A confidence value of ten does have a general meaning - it is // used for charsets that can represent the input data, but for // which there is no other indication that suggests that the // charset is the correct one. Pure 7 bit ASCII data, for example, // is compatible with a great many charsets, most of which will // appear as possible matches with a confidence of 10. // // But if such a single byte encoding has been set as the declared // encoding, it should at least be tried, therefore add it here to // the list of matches with the confidence value of 10. If it // cannot encode the complete input, the iteration over the list // of matches will detect that and remove it again. if(!d->_declaredEncoding.isEmpty() && (d->_declaredEncoding.startsWith(QLatin1String("ISO-8859-")) || d->_declaredEncoding.startsWith(QLatin1String("windows-12")) || d->_declaredEncoding.startsWith(QLatin1String("KOI8")))) qCharsetMatchList << QCharsetMatch(d->_declaredEncoding, QString(), 10); // Similar as for declaredEncoding, when declaredLocale is used // and it is a locale where the legacy encoding is a single byte // encoding, it should at least be tried, therefore add the legacy // single byte encoding for the declared locale here. If it // cannot encode the complete input, it will be removed again // later. Multibyte encodings like Shift_JIS, EUC-JP, Big5, // etc. ... do not need to be added, contrary to the single byte // encodings I could find no case where the matches returned by // libicu did omit a multibyte encoding when it should have been // included. if(!d->_declaredLocale.isEmpty()) { QString language = d->_declaredLocale.left(2); if(language == QLatin1String("ru")) { qCharsetMatchList << QCharsetMatch(QLatin1String("KOI8-R"), language, 10); qCharsetMatchList << QCharsetMatch(QLatin1String("windows-1251"), language, 10); qCharsetMatchList << QCharsetMatch(QLatin1String("ISO-8859-5"), language, 10); } else if(language == QLatin1String("tr")) qCharsetMatchList << QCharsetMatch(QLatin1String("ISO-8859-9"), language, 10); else if(language == QLatin1String("el")) qCharsetMatchList << QCharsetMatch(QLatin1String("ISO-8859-7"), language, 10); else if(language == QLatin1String("en") || language == QLatin1String("da") || language == QLatin1String("de") || language == QLatin1String("es") || language == QLatin1String("fi") || language == QLatin1String("fr") || language == QLatin1String("it") || language == QLatin1String("nl") || language == QLatin1String("no") || language == QLatin1String("nn") || language == QLatin1String("nb") || language == QLatin1String("pt") || language == QLatin1String("sv")) qCharsetMatchList << QCharsetMatch(QLatin1String("ISO-8859-1"), language, 10); else if(language == QLatin1String("cs") || language == QLatin1String("hu") || language == QLatin1String("pl") || language == QLatin1String("ro")) qCharsetMatchList << QCharsetMatch(QLatin1String("ISO-8859-1"), language, 10); else if(language == QLatin1String("ar") || language == QLatin1String("fa") || language == QLatin1String("ur")) qCharsetMatchList << QCharsetMatch(QLatin1String("ISO-8859-6"), language, 10); else if(language == QLatin1String("he")) qCharsetMatchList << QCharsetMatch(QLatin1String("ISO-8859-8"), language, 10); } // iterate over the detected matches and do some fine tuning: bool sortNeeded = false; qint32 koi8rConfidence = 0; qint32 iso88595Confidence = 0; qint32 windows1251Confidence = 0; QList<QCharsetMatch>::iterator it = qCharsetMatchList.begin(); while(it != qCharsetMatchList.end()) { if((*it).name() == QLatin1String("KOI8-R")) koi8rConfidence += (*it).confidence(); if((*it).name() == QLatin1String("ISO-8859-5")) iso88595Confidence += (*it).confidence(); if((*it).name() == QLatin1String("windows-1251")) windows1251Confidence += (*it).confidence(); if((*it).name() == QLatin1String("ISO-2022-JP")) { // non-Japanese text in ISO-2022-JP encoding is possible // but very unlikely: (*it).setLanguage(QLatin1String("ja")); } if((*it).name() == QLatin1String("UTF-8") && (*it).confidence() >= 80 && (*it).confidence() < 99) { // Actually libicu currently only returns confidence // values of 100, 80, 25, and 10 for UTF-8. A value of 80 // can mean two things: // // 1) (hasBOM && numValid > numInvalid*10) // 2) (numValid > 0 && numInvalid == 0) // // If it is case 1), the match will be removed anyway by // the check below which tests whether the complete input // can be encoded. I.e. we don’t need to care about this. // // If it is case 2) *and* the check below whether the // complete input can be encoded does not remove it, we // have valid UTF-8 and it is very unlikely that it is // anything else, therefore I think the confidence of 80 // is too low and should be increased. // With a confidence of only 80, a longer ASCII text with // less than 4 UTF-8 characters will detect as ISO-8859-1 // which is most certainly wrong. (*it).setConfidence(99); sortNeeded = true; } if(!d->_declaredEncoding.isEmpty() && (*it).name() == d->_declaredEncoding && (*it).confidence() == 10) { // A confidence value of 10 means the charset can // represent the input data, but there is no other // indication that suggests that the charset is the // correct one. But if the user has set this to be the // declared encoding, it should be preferred over the // other encodings which also got confidence 10 (there are // often many with confidence 10). Do not increase the // confidence too much though in order not to override // real evidence that the input does really use something // different than the declared encoding. (*it).setConfidence(40); sortNeeded = true; } if(!d->_declaredLocale.isEmpty() && d->_declaredLocale.startsWith((*it).language()) && (*it).confidence() == 10) { // A confidence value of 10 means the charset can // represent the input data, but there is no other // indication that suggests that the charset is the // correct one. But if the detected language for this // charset matches the language declared by the user, this // charset should be preferred over the others which also // got confidence 10 (there are often many with confidence // 10). Do not increase the confidence too much though in // order not to override real evidence that the input does // really use something different than the declared // encoding. Use a slightly lower value than for the // declared encoding. Setting the declared encoding // is more precise and should have somewhat higher priority if (d->_declaredLocale.startsWith(QLatin1String("ru"))) { // Treat the Russian setDeclaredLocale("ru") case a // bit different than the single byte encodings for // other languages: Only increase the weight of // Russian encodings if setDeclaredLocale("ru") has // been used if libicu has really detected the same // Russian encoding as well. libicu usually detects // these Russian encodings with very low confidences < // 10 for short input. But if we are already pretty // sure that it is Russian because of // setDeclaredLocale("ru"), then these low confidences // detected by libicu seem to be useful to distinguish // between the different Russian legacy encodings. // // If the setDeclareLocale("ru") has been used, the // accumulated confidence for the Russian single byte // encoding is 10 (because of setDeclaredLocale("ru")) // plus whatever libicu has detected. If libicu has // not detected anything, the accumulated confidence // is exactly 10 here and there is no way to // distinguish between the Russian legacy // encodings. Therefore, don’t increase the confidence // if the accumulated confidence is not > 10. // // But if libicu has detected something with small // confidence, the accumulated confidence is 10 plus // something small. In that case, adding something // around 20 seems to work reasonably well. // // I add 20 to the confidence for KOI8-R and // ISO-8859-5 but 21 to the confidence for // windows-1251 to prefer windows-1251 a little bit // over ISO-8859-5. if((*it).name() == QLatin1String("KOI8-R") && koi8rConfidence > 10 && koi8rConfidence < 30) (*it).setConfidence(20 + koi8rConfidence); else if((*it).name() == QLatin1String("ISO-8859-5") && iso88595Confidence > 10 && iso88595Confidence < 30) (*it).setConfidence(20 + iso88595Confidence); else if((*it).name() == QLatin1String("windows-1251") && windows1251Confidence > 10 && windows1251Confidence < 30) (*it).setConfidence(21 + windows1251Confidence); } else if ((d->_declaredLocale.contains(QLatin1String("TW")) || d->_declaredLocale.contains(QLatin1String("HK")) || d->_declaredLocale.contains(QLatin1String("MO"))) && (*it).name() == QLatin1String("Big5")) { // Traditional Chinese, Big5 more likely (*it).setConfidence(39); } else if ((d->_declaredLocale.contains(QLatin1String("CN")) || d->_declaredLocale.contains(QLatin1String("SG")) || d->_declaredLocale == QLatin1String("zh")) && (*it).name() == QLatin1String("GB18030")) { // Simplified Chinese, GB18030/GB2312 more likely. // Simplified Chinese is also assumed if only “zh” // is set. If the variant is unknown, simplified // Chinese seems a bit more likely. On top of that, // the settings application sets only “zh” for // simplified Chinese and the translations for // simplified Chinese are also in files like // “foo_zh.qm” which makes simplified Chinese more // likely when only “zh” is set on the device (see // also NB#242154). (*it).setConfidence(39); } else { (*it).setConfidence(38); } sortNeeded = true; } if(!d->_allDetectableCharsets.contains((*it).name())) { // remove matches for charsets not supported by QTextCodec // then it is probably some weird charset we cannot use anyway it = qCharsetMatchList.erase(it); } else { // test whether the complete input text can be encoded // using this match, if not remove the match clearError(); text(*it); if(hasError()) { // qMailLog(Messaging) << __PRETTY_FUNCTION__ // << "removing match" << (*it).name() // << "because it cannot encode the complete input" // << errorString(); it = qCharsetMatchList.erase(it); clearError(); } else ++it; } } // sort the list of matches again if confidences have been changed: if(sortNeeded) std::sort(qCharsetMatchList.begin(), qCharsetMatchList.end(), std::greater<QCharsetMatch>()); if(qCharsetMatchList.isEmpty()) { // is there any better status to describe this case? d->_status = U_CE_NOT_FOUND_ERROR; qWarning() << __PRETTY_FUNCTION__ << "number of matches found=0" << errorString(); return QList<QCharsetMatch>(); } return qCharsetMatchList; }
void CL::check_error(const cl_int &err, const char * context) { if(err != CL_SUCCESS) { fprintf(stderr,"[OpenCL] %s: %s\n", context, errorString(err)); util_abort(); } }
// TODO: Instead of doing all in this slot, we should iteratively parse in readyRead(). This // would allow us to be more asynchronous in processing while data is coming from the network, // not all in one big blob at the end. bool LsColJob::finished() { qCInfo(lcLsColJob) << "LSCOL of" << reply()->request().url() << "FINISHED WITH STATUS" << reply()->error() << (reply()->error() == QNetworkReply::NoError ? QLatin1String("") : errorString()); QString contentType = reply()->header(QNetworkRequest::ContentTypeHeader).toString(); int httpCode = reply()->attribute(QNetworkRequest::HttpStatusCodeAttribute).toInt(); if (httpCode == 207 && contentType.contains("application/xml; charset=utf-8")) { LsColXMLParser parser; connect(&parser, &LsColXMLParser::directoryListingSubfolders, this, &LsColJob::directoryListingSubfolders); connect(&parser, &LsColXMLParser::directoryListingIterated, this, &LsColJob::directoryListingIterated); connect(&parser, &LsColXMLParser::finishedWithError, this, &LsColJob::finishedWithError); connect(&parser, &LsColXMLParser::finishedWithoutError, this, &LsColJob::finishedWithoutError); QString expectedPath = reply()->request().url().path(); // something like "/owncloud/remote.php/webdav/folder" if (!parser.parse(reply()->readAll(), &_sizes, expectedPath)) { // XML parse error emit finishedWithError(reply()); } } else if (httpCode == 207) { // wrong content type emit finishedWithError(reply()); } else { // wrong HTTP code or any other network error emit finishedWithError(reply()); } return true; }
bool MkColJob::finished() { qCInfo(lcMkColJob) << "MKCOL of" << reply()->request().url() << "FINISHED WITH STATUS" << reply()->error() << (reply()->error() == QNetworkReply::NoError ? QLatin1String("") : errorString()); emit finished(reply()->error()); return true; }
OpenNI2Interface::OpenNI2Interface(int inWidth, int inHeight, int fps) : width(inWidth), height(inHeight), fps(fps), initSuccessful(true) { //Setup openni::Status rc = openni::STATUS_OK; const char * deviceURI = openni::ANY_DEVICE; rc = openni::OpenNI::initialize(); std::string errorString(openni::OpenNI::getExtendedError()); if(errorString.length() > 0) { errorText.append(errorString); initSuccessful = false; } else { rc = device.open(deviceURI); if (rc != openni::STATUS_OK) { errorText.append(openni::OpenNI::getExtendedError()); openni::OpenNI::shutdown(); initSuccessful = false; } else { openni::VideoMode depthMode; depthMode.setFps(fps); depthMode.setPixelFormat(openni::PIXEL_FORMAT_DEPTH_1_MM); depthMode.setResolution(width, height); openni::VideoMode colorMode; colorMode.setFps(fps); colorMode.setPixelFormat(openni::PIXEL_FORMAT_RGB888); colorMode.setResolution(width, height); rc = depthStream.create(device, openni::SENSOR_DEPTH); if (rc == openni::STATUS_OK) { depthStream.setVideoMode(depthMode); rc = depthStream.start(); if (rc != openni::STATUS_OK) { errorText.append(openni::OpenNI::getExtendedError()); depthStream.destroy(); initSuccessful = false; } } else { errorText.append(openni::OpenNI::getExtendedError()); initSuccessful = false; } rc = rgbStream.create(device, openni::SENSOR_COLOR); if (rc == openni::STATUS_OK) { rgbStream.setVideoMode(colorMode); rc = rgbStream.start(); if (rc != openni::STATUS_OK) { errorText.append(openni::OpenNI::getExtendedError()); rgbStream.destroy(); initSuccessful = false; } } else { errorText.append(openni::OpenNI::getExtendedError()); initSuccessful = false; } if (!depthStream.isValid() || !rgbStream.isValid()) { errorText.append(openni::OpenNI::getExtendedError()); openni::OpenNI::shutdown(); initSuccessful = false; } if(initSuccessful) { //For printing out formatMap[openni::PIXEL_FORMAT_DEPTH_1_MM] = "1mm"; formatMap[openni::PIXEL_FORMAT_DEPTH_100_UM] = "100um"; formatMap[openni::PIXEL_FORMAT_SHIFT_9_2] = "Shift 9 2"; formatMap[openni::PIXEL_FORMAT_SHIFT_9_3] = "Shift 9 3"; formatMap[openni::PIXEL_FORMAT_RGB888] = "RGB888"; formatMap[openni::PIXEL_FORMAT_YUV422] = "YUV422"; formatMap[openni::PIXEL_FORMAT_GRAY8] = "GRAY8"; formatMap[openni::PIXEL_FORMAT_GRAY16] = "GRAY16"; formatMap[openni::PIXEL_FORMAT_JPEG] = "JPEG"; assert(findMode(width, height, fps) && "Sorry, mode not supported!"); latestDepthIndex.assignValue(-1); latestRgbIndex.assignValue(-1); for(int i = 0; i < numBuffers; i++) { uint8_t * newImage = (uint8_t *)calloc(width * height * 3, sizeof(uint8_t)); rgbBuffers[i] = std::pair<uint8_t *, int64_t>(newImage, 0); } for(int i = 0; i < numBuffers; i++) { uint8_t * newDepth = (uint8_t *)calloc(width * height * 2, sizeof(uint8_t)); uint8_t * newImage = (uint8_t *)calloc(width * height * 3, sizeof(uint8_t)); frameBuffers[i] = std::pair<std::pair<uint8_t *, uint8_t *>, int64_t>(std::pair<uint8_t *, uint8_t *>(newDepth, newImage), 0); } rgbCallback = new RGBCallback(lastRgbTime, latestRgbIndex, rgbBuffers); depthCallback = new DepthCallback(lastDepthTime, latestDepthIndex, latestRgbIndex, rgbBuffers, frameBuffers); depthStream.setMirroringEnabled(false); rgbStream.setMirroringEnabled(false); device.setDepthColorSyncEnabled(true); device.setImageRegistrationMode(openni::IMAGE_REGISTRATION_DEPTH_TO_COLOR); setAutoExposure(true); setAutoWhiteBalance(true); rgbStream.addNewFrameListener(rgbCallback); depthStream.addNewFrameListener(depthCallback); } } } }
int Audio::loadOggStream(Path path){ int result; AudioSource* source=new AudioSource; source->type=AUDIO_OGG; source->filename=path; source->stream=true; ALenum error=alGetError(); if(!(source->oggFile = fopen(path.getAbsolute().c_str(), "rb"))){ console().write("Could not open Ogg file."); return -1; } if((result = ov_open(source->oggFile, &source->oggStream, NULL, 0)) < 0) { fclose(source->oggFile); console().write("Could not open Ogg stream. " + errorString(result)); return -1; } source->vorbisInfo = ov_info(&source->oggStream, -1); source->vorbisComment = ov_comment(&source->oggStream, -1); source->freq = source->vorbisInfo->rate; if(source->vorbisInfo->channels == 1){ source->format = AL_FORMAT_MONO16; source->stereo=false; }else{ source->format = AL_FORMAT_STEREO16; source->stereo=true; } source->lengthSeconds=ov_time_total(&source->oggStream,-1); error=alGetError(); alGenBuffers(2, source->buffers); alGenSources(1, &source->source); error=alGetError(); if(error==AL_OUT_OF_MEMORY || error==AL_INVALID_VALUE){ //there's not more resources for sources source->alSourceSet=false; }else if(error!=AL_NO_ERROR){ return -1; }else{ source->alSourceSet=true; alSources.pushBack(source->source); source->sourceIndex=sources.size()-1; alSourcePriority.pushBack(0); while(alSourceUsedBy.size()<=sources.size()){ //note, we haven't actually added this source to the sources list yet, thus the weird index alSourceUsedBy.pushBack(); } alSourceUsedBy[alSources.size()-1]=sources.size(); source->alSourceIndex=alSources.size()-1; } error=alGetError(); if(error == AL_NO_ERROR){ sources.pushBack(source); source->sourceIndex=sources.size()-1; return sources.size()-1; }else{ logs().audio.write("[AudioObject] Error 2 loading file:"+source->filename.getRelative()); console().write(String("audio wav error: error '")+String(alGetString(error))+"' loading file '"+source->filename.getRelative()+"'"); return -1; } }
CL::CL() { cl_int err; std::vector<cl::Platform> platforms; if(cl::Platform::get(&platforms) == CL_INVALID_VALUE) { fprintf(stderr, "[OpenCL] No platforms available\n"); util_abort(); } platform_ = platforms[0]; //Just select the first platform std::string name, version, extensions; platform_.getInfo(CL_PLATFORM_NAME, &name); platform_.getInfo(CL_PLATFORM_VERSION, &version); platform_.getInfo(CL_PLATFORM_EXTENSIONS, &extensions); fprintf(verbose, "[OpenCL] Platform: %s %s\n" " Extensions: %s\n", name.c_str(), version.c_str() ,extensions.c_str()); #if defined (__APPLE__) || defined(MACOSX) CGLContextObj kCGLContext = CGLGetCurrentContext(); CGLShareGroupObj kCGLShareGroup = CGLGetShareGroup(kCGLContext); cl_context_properties properties[] = { CL_CONTEXT_PROPERTY_USE_CGL_SHAREGROUP_APPLE, (cl_context_properties)kCGLShareGroup, 0 }; #elif defined WIN32 HGLRC current_context = wglGetCurrentContext(); HDC current_dc = wglGetCurrentDC(); if(current_dc == NULL || current_context == NULL) { fprintf(stderr,"[OpenCL] No OpenGL context active\n"); util_abort(); } cl_context_properties properties[] = { CL_CONTEXT_PLATFORM, (cl_context_properties)platform_(), CL_WGL_HDC_KHR, (intptr_t) current_dc, CL_GL_CONTEXT_KHR, (intptr_t) current_context, 0 }; #else if(glXGetCurrentContext() == NULL) { fprintf(stderr, "[OpenCL] glXGetCurrentContex() return NULL. Make sure to create OpenGL context before create the CL-context\n"); util_abort(); } cl_context_properties properties[] = { CL_GL_CONTEXT_KHR, (cl_context_properties)glXGetCurrentContext(), CL_GLX_DISPLAY_KHR, (cl_context_properties)glXGetCurrentDisplay(), CL_CONTEXT_PLATFORM, (cl_context_properties)(platform_)(), 0 }; #endif static CL_API_ENTRY cl_int (CL_API_CALL *clGetGLContextInfoKHR)(const cl_context_properties *properties, cl_gl_context_info param_name, size_t param_value_size, void *param_value, size_t *param_value_size_ret)=NULL; clGetGLContextInfoKHR = (clGetGLContextInfoKHR_fn) clGetExtensionFunctionAddress("clGetGLContextInfoKHR"); cl_device_id devices[32]; size_t deviceSize = 0; err = clGetGLContextInfoKHR(properties, CL_DEVICES_FOR_GL_CONTEXT_KHR, 32 * sizeof(cl_device_id), devices, &deviceSize); if(deviceSize == 0) { fprintf(stderr, "[OpenCL] Interop not possible\n"); util_abort(); } cl_bool image_support, available; size_t max_width, max_height; cl_uint num_cores, frequency; cl_device_type _type; std::string type; fprintf(verbose, "[OpenCL] Available devices: \n"); for(int i=0; i< (deviceSize / sizeof(cl_device_id)); ++i) { cl::Device device(devices[i]); device.getInfo(CL_DEVICE_VENDOR, &name); device.getInfo(CL_DEVICE_VERSION, &version); device.getInfo(CL_DEVICE_EXTENSIONS, &extensions); device.getInfo(CL_DEVICE_AVAILABLE, &available); device.getInfo(CL_DEVICE_IMAGE_SUPPORT, &image_support); device.getInfo(CL_DEVICE_IMAGE2D_MAX_WIDTH, &max_width); device.getInfo(CL_DEVICE_IMAGE2D_MAX_HEIGHT, &max_height); device.getInfo( CL_DEVICE_MAX_COMPUTE_UNITS , &num_cores); device.getInfo(CL_DEVICE_MAX_CLOCK_FREQUENCY, &frequency); device.getInfo(CL_DEVICE_TYPE, &_type); switch(_type) { case CL_DEVICE_TYPE_GPU: type = "GPU"; break; case CL_DEVICE_TYPE_CPU: type = "CPU"; break; case CL_DEVICE_TYPE_ACCELERATOR: type = "Accelerator"; break; } fprintf(verbose, "[OpenCL] Device (%p): %s %s (%s)\n" " Cores: %u, Frequency: %u MHz, Available: %s," " Image support: %s, max size: %lux%lu\n" " Extensions: %s\n --- \n", (device)(), name.c_str(), version.c_str(), type.c_str(), num_cores, frequency,available?"YES":"NO",image_support?"YES":"NO", max_width, max_height, extensions.c_str()); devices_.push_back(device); } fprintf(verbose, "\n-------------------\n"); cl_device_id device_id; context_ = cl::Context(devices_, properties, &CL::cl_error_callback, nullptr, &err); if(err != CL_SUCCESS) { fprintf(stderr, "[OpenCL] Failed to create context: %s\n", errorString(err)); util_abort(); } err = clGetGLContextInfoKHR(properties, CL_CURRENT_DEVICE_FOR_GL_CONTEXT_KHR, sizeof(device_id), &device_id, NULL); if(err != CL_SUCCESS) { fprintf(stderr, "[OpenCL] Failed to get current device for context: %s\n", errorString(err)); util_abort(); } context_device_ = cl::Device(device_id); context_device_.getInfo(CL_DEVICE_VENDOR, &name); context_device_.getInfo(CL_DEVICE_VERSION, &version); fprintf(verbose, "[OpenCL] Context Device (%p): %s %s\n",(context_device_)(), name.c_str(), version.c_str()); queue_ = cl::CommandQueue(context_, context_device_, 0, &err); if(err != CL_SUCCESS) { fprintf(stderr, "[OpenCL] Failed to create a command queue: %s\n", errorString(err)); util_abort(); } }
bool PropfindJob::finished() { qCInfo(lcPropfindJob) << "PROPFIND of" << reply()->request().url() << "FINISHED WITH STATUS" << reply()->error() << (reply()->error() == QNetworkReply::NoError ? QLatin1String("") : errorString()); int http_result_code = reply()->attribute(QNetworkRequest::HttpStatusCodeAttribute).toInt(); if (http_result_code == 207) { // Parse DAV response QXmlStreamReader reader(reply()); reader.addExtraNamespaceDeclaration(QXmlStreamNamespaceDeclaration("d", "DAV:")); QVariantMap items; // introduced to nesting is ignored QStack<QString> curElement; while (!reader.atEnd()) { QXmlStreamReader::TokenType type = reader.readNext(); if (type == QXmlStreamReader::StartElement) { if (!curElement.isEmpty() && curElement.top() == QLatin1String("prop")) { items.insert(reader.name().toString(), reader.readElementText(QXmlStreamReader::SkipChildElements)); } else { curElement.push(reader.name().toString()); } } if (type == QXmlStreamReader::EndElement) { if (curElement.top() == reader.name()) { curElement.pop(); } } } if (reader.hasError()) { qCWarning(lcPropfindJob) << "XML parser error: " << reader.errorString(); emit finishedWithError(reply()); } else { emit result(items); } } else { qCWarning(lcPropfindJob) << "*not* successful, http result code is" << http_result_code << (http_result_code == 302 ? reply()->header(QNetworkRequest::LocationHeader).toString() : QLatin1String("")); emit finishedWithError(reply()); } return true; }
void MainWindow::on_connectAction_triggered(bool connect) { if(connect) { if(_serialPort->open(QIODevice::ReadWrite)) { // TODO hardcoded settings if(!_serialPort->setRate(SerialPort::Rate115200) || !_serialPort->setDataBits(SerialPort::Data8) || !_serialPort->setParity(SerialPort::NoParity) || !_serialPort->setFlowControl(SerialPort::NoFlowControl) || !_serialPort->setStopBits(SerialPort::TwoStop)) { _serialPort->close(); QMessageBox::critical(this, "Logger", "Can't configure serial port, reason: " + errorString()); } } else { QMessageBox::critical(this, "Logger", "Serial port connection failed, reason: " + errorString(), QMessageBox::Ok); } } else { _serialPort->close(); } updateStatus(); }
bool ProppatchJob::finished() { qCInfo(lcProppatchJob) << "PROPPATCH of" << reply()->request().url() << "FINISHED WITH STATUS" << reply()->error() << (reply()->error() == QNetworkReply::NoError ? QLatin1String("") : errorString()); int http_result_code = reply()->attribute(QNetworkRequest::HttpStatusCodeAttribute).toInt(); if (http_result_code == 207) { emit success(); } else { qCWarning(lcProppatchJob) << "*not* successful, http result code is" << http_result_code << (http_result_code == 302 ? reply()->header(QNetworkRequest::LocationHeader).toString() : QLatin1String("")); emit finishedWithError(); } return true; }
Map::Map(const QString &filename) : d(new MapPrivate) { QFile file(filename); if (!file.open(QIODevice::ReadOnly)) { setError(1, QString("Could not open %1 for reading: %2") .arg(filename) .arg(file.errorString()) ); return; } QByteArray rawJson = file.readAll(); QJsonParseError error; QJsonDocument doc = QJsonDocument::fromJson(rawJson, &error); if (error.error != QJsonParseError::NoError) { setError(1, QString("Failed to load imagemap %1, error %2 on offset %3") .arg(filename) .arg(error.errorString()) .arg(error.offset)); return; } QVariantMap result = doc.toVariant().toMap(); if (result.isEmpty()) { setError(1, QString("Empty Map %1").arg(filename)); return; } QString basepath = QFileInfo(filename).absolutePath(); QVariantMap imagemaps = result["images"].toMap(); for (QVariantMap::iterator files = imagemaps.begin(); files != imagemaps.end(); ++files) { QString filename = basepath + "/" + files.key() ; QVariantMap fileOpts = files.value().toMap(); // Load the image container. Container* container; if (filename.endsWith(".svg")) { container = ContainerSVG::create(this, filename); } else { container = ContainerImage::create(this, filename); } if (errorCode() != 0) { setError(1, QString("Failed to load image %1: %2") .arg(filename) .arg(errorString())); return; } // Create the list of images. if (fileOpts.contains("full")) { QVariantMap value = fileOpts["full"].toMap(); if (value.isEmpty()) { wzLog(LOG_IM) << "Image" << filename << "is empty!"; } else { Image myImage; // Add the first found image. myImage.type = FixedType; myImage.xPosition = 0; myImage.yPosition = 0; myImage.size = QSize(value.begin().value().toList()[0].toInt(), value.begin().value().toList()[1].toInt()); myImage.container = container; d->m_images.insert(value.begin().key(), myImage); } } if (fileOpts.contains("fixed")) { QVariantMap value = fileOpts["fixed"].toMap(); for (QVariantMap::iterator images = value.begin(); images != value.end(); ++images) { QVariantList imgdefList = images.value().toList(); Image myImage; myImage.type = FixedType; myImage.xPosition = imgdefList[0].toInt(); myImage.yPosition = imgdefList[1].toInt(); myImage.size = QSize(imgdefList[2].toInt(), imgdefList[3].toInt()); myImage.container = container; d->m_images.insert(images.key(), myImage); } } if (filename.endsWith(".svg") && fileOpts.contains("named")) { QVariantMap value = fileOpts["named"].toMap(); for (QVariantMap::iterator images = value.begin(); images != value.end(); ++images) { Image myImage; myImage.type = NamedType; myImage.name = images.value().toString(); myImage.container = container; d->m_images.insert(images.key(), myImage); } } if (fileOpts.contains("cache")) { container->setCache(fileOpts["cache"].toBool()); } } // for files }
bool RequestEtagJob::finished() { qCInfo(lcEtagJob) << "Request Etag of" << reply()->request().url() << "FINISHED WITH STATUS" << reply()->error() << (reply()->error() == QNetworkReply::NoError ? QLatin1String("") : errorString()); if (reply()->attribute(QNetworkRequest::HttpStatusCodeAttribute) == 207) { // Parse DAV response QXmlStreamReader reader(reply()); reader.addExtraNamespaceDeclaration(QXmlStreamNamespaceDeclaration("d", "DAV:")); QString etag; while (!reader.atEnd()) { QXmlStreamReader::TokenType type = reader.readNext(); if (type == QXmlStreamReader::StartElement && reader.namespaceUri() == QLatin1String("DAV:")) { QString name = reader.name().toString(); if (name == QLatin1String("getetag")) { etag += reader.readElementText(); } } } emit etagRetreived(etag); } return true; }
void QWSServerSocket::init(const QString &file) { #ifndef QT_NO_SXE QByteArray fn = file.toLocal8Bit(); bool result = QUnixSocketServer::listen( fn ); if ( !result ) { QUnixSocketServer::ServerError err = serverError(); switch ( err ) { case InvalidPath: qWarning("QWSServerSocket:: invalid path %s", qPrintable(file)); break; case ResourceError: case BindError: case ListenError: qWarning("QWSServerSocket:: could not listen on path %s", qPrintable(file)); break; default: break; } } #else int backlog = 16; //##### // create socket int s = ::socket(PF_LOCAL, SOCK_STREAM, 0); if (s == -1) { perror("QWSServerSocket::init"); qWarning("QWSServerSocket: unable to create socket."); return; } QByteArray fn = file.toLocal8Bit(); unlink(fn.constData()); // doesn't have to succeed // bind socket struct sockaddr_un a; memset(&a, 0, sizeof(a)); a.sun_family = PF_LOCAL; strncpy(a.sun_path, fn.constData(), sizeof(a.sun_path) - 1); int r = ::bind(s, (struct sockaddr*)&a, SUN_LEN(&a)); if (r < 0) { perror("QWSServerSocket::init"); qWarning("QWSServerSocket: could not bind to file %s", fn.constData()); ::close(s); return; } if (chmod(fn.constData(), 0600) < 0) { perror("QWSServerSocket::init"); qWarning("Could not set permissions of %s", fn.constData()); ::close(s); return; } // listen if (::listen(s, backlog) == 0) { if (!setSocketDescriptor(s)) qWarning( "QWSServerSocket could not set descriptor %d : %s", s, errorString().toLatin1().constData()); } else { perror("QWSServerSocket::init"); qWarning("QWSServerSocket: could not listen to file %s", fn.constData()); ::close(s); } #endif }
cHTTPTrackerServer::cHTTPTrackerServer(int port) { if (!listen(QHostAddress::Any,port)){ qCritical() << "http server start error: " << errorString(); } }
void CNetSock::SockError(QAbstractSocket::SocketError err) { ForceClose(errorString()); }
// Initialization function for the OpenCL platform and all OpenCL resources // required by this program. void initOpenCL() { int errcode = 0; unsigned int i, j; cl_platform_id platformId; numDevices = 0; cl_device_id deviceIds[8]; // Initialize the OpenCL platform itself clGetPlatformIDs(1, &platformId, NULL); clGetDeviceIDs(platformId, CL_DEVICE_TYPE_GPU, 8, &deviceIds[0], &numDevices); contexts = (cl_context **) calloc(sizeof(cl_context *), numDevices); commandQueues = (cl_command_queue **) calloc(sizeof(cl_command_queue*), numDevices); saxpyProgram = (cl_program **) calloc(sizeof(cl_program *), numDevices); globalWorkSize[0] = numberElems / (numDevices * numOverlap); input1 = (cl_mem **) calloc(sizeof(cl_mem *), numDevices); input2 = (cl_mem **) calloc(sizeof(cl_mem *), numDevices); output = (cl_mem **) calloc(sizeof(cl_mem *), numDevices); saxpyKernel = (cl_kernel **) calloc(sizeof(cl_kernel *), numDevices); // Create the resources for each GPU for(i = 0; i < numDevices; i++) { contexts[i] = (cl_context *) calloc(sizeof(cl_context), numOverlap); commandQueues[i] = (cl_command_queue *) calloc(sizeof(cl_command_queue), numOverlap); saxpyProgram[i] = (cl_program *) calloc(sizeof(cl_program), numOverlap); input1[i] = (cl_mem *) calloc(sizeof(cl_mem), numOverlap); input2[i] = (cl_mem *) calloc(sizeof(cl_mem), numOverlap); output[i] = (cl_mem *) calloc(sizeof(cl_mem), numOverlap); saxpyKernel[i] = (cl_kernel *) calloc(sizeof(cl_kernel), numDevices); // Create resources within each GPU for(j = 0; j < numOverlap; j++) { contexts[i][j] = clCreateContext(0, 1, &deviceIds[i], NULL, NULL, &errcode); // Create a command queue so that the host can issue orders to the device commandQueues[i][j] = clCreateCommandQueue(contexts[i][j], deviceIds[i], 0, &errcode); // Create buffer objects for X matrix input1[i][j] = clCreateBuffer(contexts[i][j], CL_MEM_READ_WRITE, sizeof(cl_float) * globalWorkSize[0], NULL, &errcode); if(errcode != 0) { std::cerr << "CreateBuffer (X): " << errorString(errcode) << std::endl; } // Create buffer objects for Y Matrix input2[i][j] = clCreateBuffer(contexts[i][j], CL_MEM_READ_WRITE, sizeof(cl_float) * globalWorkSize[0], NULL, &errcode); if(errcode != 0) { std::cerr << "CreateBuffer (Y): " << errorString(errcode) << std::endl; } // Create buffer objects for the output output[i][j] = clCreateBuffer(contexts[i][j], CL_MEM_READ_WRITE, sizeof(cl_float) * globalWorkSize[0], NULL, &errcode); if(errcode != 0) { std::cerr << "CreateBuffer (output): " << errorString(errcode) << std::endl; } // Load and build OpenCL kernels saxpyProgram[i][j] = programFromSource(kernelFile, contexts[i][j]); errcode = clBuildProgram(saxpyProgram[i][j], 0, NULL, NULL, NULL, NULL); if(errcode != 0) { char buildlog[16000]; clGetProgramBuildInfo(saxpyProgram[i][j], deviceIds[i], CL_PROGRAM_BUILD_LOG, sizeof(buildlog), buildlog, NULL); std::cerr << "Error in clBuildProgram " << buildlog << std::endl; exit(1); } // Create the kernel object saxpyKernel[i][j] = clCreateKernel(saxpyProgram[i][j], "saxpy", &errcode); if(errcode != 0) { std::cerr << "Error creating kernel: " << errorString(errcode) << std::endl; } } } }
String Sound_Renderer_AL::errorString() { if(Sound_Renderer_AL::alGetError()) return errorString(Sound_Renderer_AL::alGetError()()); else return "OpenAL not initialized"; }
static int statDir(const char *file, struct stat *sb, uint64_t *winattr) { WIN32_FIND_DATAW info_w; // window's file info WIN32_FIND_DATAA info_a; // window's file info // cache some common vars to make code more transparent DWORD *pdwFileAttributes; DWORD *pnFileSizeHigh; DWORD *pnFileSizeLow; DWORD *pdwReserved0; FILETIME *pftLastAccessTime; FILETIME *pftLastWriteTime; FILETIME *pftCreationTime; /* Oh, cool, another exception: Microsoft doesn't let us do FindFile operations on a Drive, so simply fake root attibutes. */ if(file[1]==':' && !file[2]) { time_t now=time(NULL); sb->st_mode=S_IFDIR; sb->st_mode|=S_IREAD|S_IEXEC|S_IWRITE; sb->st_ctime=now; sb->st_mtime=now; sb->st_atime=now; sb->st_rdev=0; return 0; } HANDLE h=INVALID_HANDLE_VALUE; // use unicode if(p_FindFirstFileW) { char *pwszBuf=sm_get_pool_memory(PM_FNAME); make_win32_path_UTF8_2_wchar(&pwszBuf, file); h=p_FindFirstFileW((LPCWSTR)pwszBuf, &info_w); sm_free_pool_memory(pwszBuf); pdwFileAttributes=&info_w.dwFileAttributes; pdwReserved0 =&info_w.dwReserved0; pnFileSizeHigh =&info_w.nFileSizeHigh; pnFileSizeLow =&info_w.nFileSizeLow; pftLastAccessTime=&info_w.ftLastAccessTime; pftLastWriteTime =&info_w.ftLastWriteTime; pftCreationTime =&info_w.ftCreationTime; // use ASCII } else if (p_FindFirstFileA) { h=p_FindFirstFileA(file, &info_a); pdwFileAttributes=&info_a.dwFileAttributes; pdwReserved0 =&info_a.dwReserved0; pnFileSizeHigh =&info_a.nFileSizeHigh; pnFileSizeLow =&info_a.nFileSizeLow; pftLastAccessTime=&info_a.ftLastAccessTime; pftLastWriteTime =&info_a.ftLastWriteTime; pftCreationTime =&info_a.ftCreationTime; } if(h==INVALID_HANDLE_VALUE) { const char *err = errorString(); /* Note, in creating leading paths, it is normal that the file does not exist. */ LocalFree((void *)err); errno=b_errno_win32; return -1; } else FindClose(h); *winattr=(int64_t)*pdwFileAttributes; /* Graham says: all the following stuff seems rather complicated. It is probably not all needed anymore, since I have added *winattr above, which bacula did not do. One reason for keeping it is that some of the values get converted to unix-style permissions that show up in the long list functionality. I think I would prefer to remove it all at some point. */ sb->st_mode = 0777; // start with everything if(*pdwFileAttributes & FILE_ATTRIBUTE_READONLY) sb->st_mode &= ~(S_IRUSR|S_IRGRP|S_IROTH); if(*pdwFileAttributes & FILE_ATTRIBUTE_SYSTEM) sb->st_mode &= ~S_IRWXO; // remove everything for other if(*pdwFileAttributes & FILE_ATTRIBUTE_HIDDEN) sb->st_mode |= S_ISVTX; // use sticky bit -> hidden sb->st_mode |= S_IFDIR; /* Store reparse/mount point info in st_rdev. Note a Win32 reparse point (junction point) is like a link though it can have many properties (directory link, soft link, hard link, HSM, ... A mount point is a reparse point where another volume is mounted, so it is like a Unix mount point (change of filesystem). */ if(*pdwFileAttributes & FILE_ATTRIBUTE_REPARSE_POINT) sb->st_rdev=WIN32_MOUNT_POINT; else sb->st_rdev=0; if((*pdwFileAttributes & FILE_ATTRIBUTE_REPARSE_POINT) && (*pdwReserved0 & IO_REPARSE_TAG_MOUNT_POINT)) { sb->st_rdev=WIN32_MOUNT_POINT; /* Now to find out if the directory is a mount point or a reparse point, we must do a song and a dance. Explicitly open the file to read the reparse point, then call DeviceIoControl to find out if it points to a Volume or to a directory. */ h=INVALID_HANDLE_VALUE; if(p_GetFileAttributesW) { char *pwszBuf=sm_get_pool_memory(PM_FNAME); make_win32_path_UTF8_2_wchar(&pwszBuf, file); if(p_CreateFileW) { h=CreateFileW((LPCWSTR)pwszBuf, GENERIC_READ, FILE_SHARE_READ, NULL, OPEN_EXISTING, FILE_FLAG_BACKUP_SEMANTICS | FILE_FLAG_OPEN_REPARSE_POINT, NULL); } sm_free_pool_memory(pwszBuf); } else if(p_GetFileAttributesA) { h=CreateFileA(file, GENERIC_READ, FILE_SHARE_READ, NULL, OPEN_EXISTING, FILE_FLAG_BACKUP_SEMANTICS | FILE_FLAG_OPEN_REPARSE_POINT, NULL); } if(h!=INVALID_HANDLE_VALUE) { char dummy[1000]; REPARSE_DATA_BUFFER *rdb=(REPARSE_DATA_BUFFER *)dummy; rdb->ReparseTag=IO_REPARSE_TAG_MOUNT_POINT; DWORD bytes; bool ok; ok=DeviceIoControl(h, FSCTL_GET_REPARSE_POINT, NULL, 0, // in buffer, bytes (LPVOID)rdb, (DWORD)sizeof(dummy), // out buffer, btyes (LPDWORD)&bytes, (LPOVERLAPPED)0); if(ok) { char *utf8=sm_get_pool_memory(PM_NAME); wchar_2_UTF8(utf8, (wchar_t *) rdb->SymbolicLinkReparseBuffer.PathBuffer); if(!strncasecmp(utf8, "\\??\\volume{", 11)) sb->st_rdev=WIN32_MOUNT_POINT; else // Points to a directory so we ignore it. sb->st_rdev=WIN32_JUNCTION_POINT; sm_free_pool_memory(utf8); } CloseHandle(h); } } sb->st_size=*pnFileSizeHigh; sb->st_size<<=32; sb->st_size|=*pnFileSizeLow; sb->st_blksize=4096; sb->st_blocks=(uint32_t)(sb->st_size+4095)/4096; sb->st_atime=cvt_ftime_to_utime(*pftLastAccessTime); sb->st_mtime=cvt_ftime_to_utime(*pftLastWriteTime); sb->st_ctime=cvt_ftime_to_utime(*pftCreationTime); return 0; }
//==================================== // removeInputDevice //------------------------------------ int SaXManipulateDevices::removeInputDevice (int id) { // .../ //! remove the input device of the given id (id) and return the //! previous input device id. The current input device id is set //! to this previous input device id. If the input device does //! not exist or the input device id is the core (0|1) mouse or //! keyboard the method will return (-1) // ---- if (! inputHandlingAllowed) { return -1; } //==================================== // don't allow removing the core entry //------------------------------------ if (id <= 1) { excInvalidArgument (id); qError (errorString(),EXC_INVALIDARGUMENT); return -1; } //==================================== // remove input devices... //------------------------------------ if (! mInput->delID (id)) { return -1; } //==================================== // select previous input device //------------------------------------ for (int i=1;i<=2;i++) { QDict<QString>* data = mInput->getTablePointer (i); if ((data) && (! data->isEmpty())) { mInput->setID (i); break; } } //==================================== // check input device type //------------------------------------ bool isMouse = true; QString baseItem ("InputDevice"); QString baseID ("Mouse"); if (mInput->getCurrentID() % 2 == 0) { isMouse = false; baseItem = "Keyboard"; baseID = "Keyboard"; } //==================================== // update server layout //------------------------------------ QString result; QString IDstring; IDstring.sprintf ("%d",id); QString deviceList = mLayout -> getItem (baseItem); QStringList optlist = QStringList::split ( ",", deviceList ); for ( QStringList::Iterator in = optlist.begin(); in != optlist.end(); ++in ) { QString item (*in); if (item == QString(baseID + "["+IDstring+"]")) { continue; } QRegExp identifier ("\\[(.+)\\]"); int pos = identifier.search (item); if (pos >= 0) { int curID = identifier.cap(1).toInt(); if ( curID > id ) { QString newMK; newMK.sprintf ("%s[%d],",baseID.ascii(),curID - 2); result.append ( newMK ); } else { result.append (item+","); } } } result.remove (result.length()-1,result.length()); mLayout -> setItem (baseItem,result); return mInput -> getCurrentID(); }
void CGroupClient::errorHandler ( QAbstractSocket::SocketError socketError ) { CGroupCommunicator *comm = dynamic_cast<CGroupCommunicator *>( parent() ); comm->errorInConnection(this, errorString() ); }