Beispiel #1
0
void LoginHandler::handleHostMessage(const QString &message)
{
	Q_ASSERT(!_client->username().isEmpty());

	if(_server->sessionCount() >= _server->sessionLimit()) {
		send("ERROR CLOSED");
		_client->disconnectError("login error");
		return;
	}

	const QRegularExpression re("\\AHOST (\\*|[a-zA-Z0-9:-]{1,64}) (\\d+) (\\d+)\\s*(?:;(.+))?\\z");
	auto m = re.match(message);
	if(!m.hasMatch()) {
		send("ERROR SYNTAX");
		_client->disconnectError("login error");
		return;
	}

	QString sessionId = m.captured(1);
	int minorVersion = m.captured(2).toInt();
	int userId = m.captured(3).toInt();

	// Check if session ID is available
	if(sessionId == "*") {
		// Generated session ID
		sessionId = QUuid::createUuid().toString();
		sessionId = sessionId.mid(1, sessionId.length()-2); // strip the { and } chars
	}

	if(!_server->getSessionDescriptionById(sessionId).id.isEmpty()) {
		send("ERROR SESSIONIDINUSE");
		_client->disconnectError("login error");
		return;
	}

	QString password = m.captured(4);
	if(password != _server->hostPassword() && !_hostPrivilege) {
		send("ERROR BADPASS");
		_client->disconnectError("login error");
		return;
	}

	_client->setId(userId);

	// Mark login phase as complete. No more login messages will be sent to this user
	send(QString("OK %1 %2").arg(sessionId).arg(userId));
	_complete = true;

	// Create a new session
	SessionState *session = _server->createSession(sessionId, minorVersion, _client->username());

	session->joinUser(_client, true);

	deleteLater();
}
Beispiel #2
0
bool FloorCapVector::IsValid() const
{
    Q_D(const FloorCapVector);
    if (!AbstractBbgVect::IsValid(R"**(\[(?:(?:-?\d*\.?\d+)|(?:(?:-?\d*\.?\d+)?(?:,-?\d*\.?\d+)))\])**", false)) return false;
    QRegularExpression rx("\\[(-?\\d*\\.?\\d+),(-?\\d*\\.?\\d+)\\]");
    for (auto i = rx.globalMatch(d->m_Vector); i.hasNext();) {
        const auto singleMatch = i.next();
        if (singleMatch.captured(1).toDouble() > singleMatch.captured(2).toDouble())
            return false;
    }
    return true;
}
Beispiel #3
0
ParsedDetails HtmlApi::parseDetails(const QString &source, Site *site) const
{
	Q_UNUSED(site);
	ParsedDetails ret;

	// Pools
	if (contains("Regex/Pools"))
	{
		QRegularExpression rx(value("Regex/Pools"));
		auto matches = rx.globalMatch(source);
		while (matches.hasNext())
		{
			auto match = matches.next();
			QString previous = match.captured(1), id = match.captured(2), name = match.captured(3), next = match.captured(4);
			ret.pools.append(Pool(id.toInt(), name, 0, next.toInt(), previous.toInt()));
		}
	}

	// Tags
	QString rxtags;
	if (contains("Regex/ImageTags"))
	{ rxtags = value("Regex/ImageTags"); }
	else if (contains("Regex/Tags"))
	{ rxtags = value("Regex/Tags"); }
	if (!rxtags.isEmpty())
	{ ret.tags = Tag::FromRegexp(rxtags, source); }

	// Image url
	if (contains("Regex/ImageUrl"))
	{
		QRegularExpression rx(value("Regex/ImageUrl"));
		auto matches = rx.globalMatch(source);
		while (matches.hasNext())
		{
			auto match = matches.next();
			ret.imageUrl = match.captured(1).replace("&", "&");
		}
	}

	// Image date
	if (contains("Regex/ImageDate"))
	{
		QRegularExpression rx(value("Regex/ImageDate"));
		auto matches = rx.globalMatch(source);
		while (matches.hasNext())
		{
			auto match = matches.next();
			ret.createdAt = qDateTimeFromString(match.captured(1));
		}
	}

	return ret;
}
Beispiel #4
0
/**
 * Restores the database file from the backup file with
 * name <filename>.old.<extension> to filePath. This will
 * overwrite the existing file!
 *
 * @param filePath Path to the file to restore
 * @return true on success
 */
bool Database::restoreDatabase(const QString& filePath)
{
    static auto re = QRegularExpression("^(.*?)(\\.[^.]+)?$");

    auto match = re.match(filePath);
    auto backupFilePath = match.captured(1) + ".old" + match.captured(2);
    // Only try to restore if the backup file actually exists
    if (QFile::exists(backupFilePath)) {
        QFile::remove(filePath);
        return QFile::copy(backupFilePath, filePath);
    }
    return false;
}
Beispiel #5
0
QString     Replacer::replaceParameters( const QString & text, const ReportPtr & report )
{
    auto newText = text;
    QRegularExpression expr( "(\\$P\\{\\w+\\})", QRegularExpression::CaseInsensitiveOption );
    auto iterator = expr.globalMatch( newText );
    while( iterator.hasNext() )
    {
        auto match = iterator.next();
        auto name = match.captured( 1 ).remove( 0, 3 ).remove( -1, 1 );
        auto parameter = report->getParameter( name );
        newText.replace( match.captured( 1 ), parameter.toString() ); //need fix for classname
    }

    return newText;
}
Beispiel #6
0
QString     Replacer::replaceField( const QString & text, const ReportPtr & report, int i )
{
    auto newText = text;
    QRegularExpression expr( "(\\$F\\{\\w+\\})", QRegularExpression::CaseInsensitiveOption );
    auto iterator = expr.globalMatch( newText );
    while( iterator.hasNext() )
    {
        auto match = iterator.next();
        auto name = match.captured( 1 ).remove( 0, 3 ).remove( -1, 1 );
        auto parameter = report->getField( name )->getData( i );
        newText.replace( match.captured( 1 ), parameter );
    }

    return newText;
}
Beispiel #7
0
static QString getXdgValue(const QString& contents, const QString& key, const QString& accessor = "")
{
    QString fullkey = accessor.length() ? key + "[" + accessor + "]" : key;
    QRegularExpression re("^" + fullkey + "=(.*)$", QRegularExpression::MultilineOption);
    auto match = re.match(contents);
    return match.hasMatch() ? match.captured(1) : "";
}
Beispiel #8
0
SignaturePad::SignaturePad(Container * parent) : ViewControl(parent)
{
	// create default view with Graphics2D graphics

	// replace this with logic to extract colors from control properties
	QVariantList backgroundColor;
	backgroundColor << COLOR_WHITE.red << COLOR_WHITE.green << COLOR_WHITE.blue << COLOR_WHITE.alpha;
	QVariantList strokeColor;
	strokeColor << COLOR_BLACK.red << COLOR_BLACK.green << COLOR_BLACK.blue << COLOR_BLACK.alpha;

	_signPad = new SketchPad();
	_signPad->setPosition(0, 0);
	_signPad->setSize(0, 0);
	_signPad->setZ(-1);

	_signPad->setBackgroundColor(backgroundColor);
	_signPad->setStrokeColor(strokeColor);
	_signPad->setStrokeWidth(10.0);
	_signPad->setTool("freedraw");
	_signPad->setEnabled(false);

	addView(_signPad);
	addViewToResize(_signPad);
	addTouchEventView(_signPad);

	QObject::connect(
			_signPad,
			SIGNAL(captured()),
			this,
			SLOT(onCaptured()));

	_saveFilename.clear();
}
Beispiel #9
0
bool Pursuer::feasibleState()
{
    bool cond1 = limitX.contains(currentState[x] + currentState[xp]);
    bool cond2 = cond1 && limitY.contains(currentState[y] + currentState[yp]);

    return cond2 && !captured();
}
Beispiel #10
0
QString LayerListModel::getAvailableLayerName(QString basename) const
{
	// Return a layer name of format "basename n" where n is one bigger than the
	// biggest suffix number of layers named "basename n".

	// First, strip suffix number from the basename (if it exists)

	QRegularExpression suffixNumRe("(\\d+)$");
	{
		auto m = suffixNumRe.match(basename);
		if(m.hasMatch()) {
			basename = basename.mid(0, m.capturedStart()).trimmed();
		}
	}

	// Find the biggest suffix in the layer stack
	int suffix = 0;
	for(const LayerListItem &l : _items) {
		auto m = suffixNumRe.match(l.title);
		if(m.hasMatch()) {
			if(l.title.startsWith(basename)) {
				suffix = qMax(suffix, m.captured(1).toInt());
			}
		}
	}

	// Make unique name
	return QString("%2 %1").arg(suffix+1).arg(basename);
}
Beispiel #11
0
void Pursuer::step(const DenseAction& action, DenseState& nextState,
                   Reward& reward)
{
    //action threshold
    double v = maxV.bound(action[0]);
    double omega = maxOmega.bound(action[1]);

    //Compute pursuer control using chicken pose prediction
    double omegar;
    double vr;
    computePursuerControl(vr, omegar);

    //Update pursuer state
    double xrabs, yrabs;
    updatePursuerPose(vr, omegar, xrabs, yrabs);

    //update chased position
    updateChasedPose(v, omega);

    //update pursuer relative position
    currentState[xp] = xrabs - currentState[x];
    currentState[yp] = yrabs - currentState[y];

    if (captured())
    {
        reward[0] = -100;
        currentState.setAbsorbing(true);
    }
    else
    {
        reward[0] = 1;
    }

    nextState = currentState;
}
Beispiel #12
0
void update()
{
	int nextfree = 0;
	DIR *dir;
	struct dirent *ent;
	dir = opendir(".");	
	while ((ent = readdir(dir)) != NULL) {
		struct stat st_,*st=&st_;
		stat(ent->d_name, st);
		if(S_ISREG(st->st_mode) && !captured(ent->d_name)) {
			printf("*** capturing entry: %s ***\n",ent->d_name);
			nextfree = find_next_free();
			if (nextfree == -1) {
				fprintf(stderr,"more than max files (%d) in folder, ignoring %s\n", MAX_ENTRIES, ent->d_name);
				break;
			}
				
			strcpy(entries[nextfree].filename ,ent->d_name);
			entries[nextfree].mtime = st->st_mtime;
			entries[nextfree].fh = fopen(ent->d_name,"r");
			fseek(entries[nextfree].fh,0,SEEK_END);
		}
	}
	closedir(dir);
}
Beispiel #13
0
QStringList KateProjectWorker::filesFromDarcs(const QDir &dir, bool recursive)
{
    QStringList files;

    const QString cmd = QStringLiteral("darcs");
    QString root;

    {
        QProcess darcs;
        darcs.setWorkingDirectory(dir.absolutePath());
        QStringList args;
        args << QStringLiteral("list") << QStringLiteral("repo");

        darcs.start(cmd, args);

        if (!darcs.waitForStarted() || !darcs.waitForFinished())
            return files;

        auto str = QString::fromLocal8Bit(darcs.readAllStandardOutput());
        QRegularExpression exp(QStringLiteral("Root: ([^\\n\\r]*)"));
        auto match = exp.match(str);

        if(!match.hasMatch())
            return files;

        root = match.captured(1);
    }

    QStringList relFiles;
    {
        QProcess darcs;
        QStringList args;
        darcs.setWorkingDirectory(dir.absolutePath());
        args << QStringLiteral("list") << QStringLiteral("files")
             << QStringLiteral("--no-directories") << QStringLiteral("--pending");

        darcs.start(cmd, args);

        if(!darcs.waitForStarted() || !darcs.waitForFinished())
            return files;

        relFiles = QString::fromLocal8Bit(darcs.readAllStandardOutput())
            .split(QRegularExpression(QStringLiteral("[\n\r]")), QString::SkipEmptyParts);
    }

    for (const QString &relFile: relFiles) {
        const QString path = dir.relativeFilePath(root + QStringLiteral("/") + relFile);

        if ((!recursive && (relFile.indexOf(QStringLiteral("/")) != -1)) ||
            (recursive && (relFile.indexOf(QStringLiteral("..")) == 0))
        ) {
            continue;
        }

        files.append(dir.absoluteFilePath(path));
    }

    return files;
}
Beispiel #14
0
void CaptureThread::run(){
    Pkt* pkt = NULL;
    while(!QThread::currentThread()->isInterruptionRequested()){
        pkt= nic->getNextPacket();
        if (pkt!=NULL)
            emit captured(pkt); // pkt可以携带设备信息,因此这里不再发送设备指针
    }
    qDebug("CaptureThread finished.");
}
Beispiel #15
0
bool FileImageSource::capture()
{
    if (!isInitialized)
        Initialize();
    bool isOk = readImage();
    if (isOk)
        emit captured(image);
    return isOk;
}
Beispiel #16
0
/**
 * Remove the old backup and replace it with a new one
 * backups are named <filename>.old.<extension>
 *
 * @param filePath Path to the file to backup
 * @return true on success
 */
bool Database::backupDatabase(const QString& filePath)
{
    static auto re = QRegularExpression("(\\.[^.]+)$");

    auto match = re.match(filePath);
    auto backupFilePath = filePath;
    backupFilePath = backupFilePath.replace(re, "") + ".old" + match.captured(1);
    QFile::remove(backupFilePath);
    return QFile::copy(filePath, backupFilePath);
}
Beispiel #17
0
// ----------------------------------------------------------------------------
// Widget
// ----------------------------------------------------------------------------
Widget::Widget(QWidget *parent) :
  QWidget(parent),
  ui(new Ui::Widget)
{
  ui->setupUi(this);
  db_ = QSqlDatabase::addDatabase("QSQLITE");
  connect(&cs_, SIGNAL(captured(Cookies)), this, SLOT(processCookies(Cookies)), Qt::BlockingQueuedConnection);
  connect(&cs_, SIGNAL(closed()), this, SLOT(processClosed()), Qt::AutoConnection);
  loadControl();
  setControl();
}
Beispiel #18
0
std::vector<BankAccount> OfxParser::parse()
{
    std::vector<BankAccount> result;
    QTextStream stream(m_file);
    QString line;
    QRegularExpression newTagMatcher("^<(\\w+)>$");
    QRegularExpression endTagMatcher("^</(\\w+)>$");
    QRegularExpression dataTagMatcher("^<(\\w+)>(.*)$");

    QStringList tagList;
    QMap<QString, QString> dataMap;
    while (stream.readLineInto(&line)) {
        if (line.isEmpty())
            continue;
        auto match = newTagMatcher.match(line);
        if (match.hasMatch()) {
            if (!dataMap.isEmpty()) {
                parsedData(result, tagList.join('/'), dataMap);
                dataMap.clear();
            }
            tagList.append(match.captured(1));
            continue;
        }
        match = endTagMatcher.match(line);
        if (match.hasMatch()) {
            if (!dataMap.isEmpty()) {
                parsedData(result, tagList.join('/'), dataMap);
                dataMap.clear();
            }
            tagList.pop_back();
            continue;
        }
        match = dataTagMatcher.match(line);
        if (match.hasMatch()) {
            dataMap.insert(match.captured(1), match.captured(2));
            continue;
        }
        qFatal("Invalid content");
    }
    return result;
}
Beispiel #19
0
/*-----------------------------------------------------------------------------
Capture a screen shot and return it without saving it
-----------------------------------------------------------------------------*/
CapturedImage ScreenCapture::CaptureImage(HWND wnd, bool crop_viewport) {
	CapturedImage ret;
	if (wnd) {
		EnterCriticalSection(&cs);
		RECT * rect = NULL;
		if (crop_viewport && _viewport_set)
			rect = &_viewport;
		CapturedImage captured(wnd, rect);
		ret = captured;
		LeaveCriticalSection(&cs);
	}
	return ret;
}
Beispiel #20
0
QImage  Replacer::replaceFieldImage( const QString & text, const ReportPtr & report, int i )
{
    QRegularExpression expr( "(\\$F\\{\\w+\\})", QRegularExpression::CaseInsensitiveOption );
    auto iterator = expr.globalMatch( text );
    while( iterator.hasNext() )
    {
        auto match = iterator.next();
        auto name = match.captured( 1 ).remove( 0, 3 ).remove( -1, 1 );
        auto byteArray = report->getField( name )->getData< QByteArray >( i );
        auto image = QImage::fromData( byteArray );
        return image;
    }

    return QImage();
}
Beispiel #21
0
QByteArray LSHttpdRequest::extractOption(QByteArray headerValue, QByteArray optionTag)
{
    if(headerValue.isEmpty() || optionTag.isEmpty())
    {
        return QByteArray();
    }
    QString pattern = QStringLiteral("%1=\"([^\"]+)\"");
    QRegularExpression rx(pattern.arg(QString::fromLocal8Bit(optionTag)));
    auto rxMatch = rx.match(QString::fromLocal8Bit(headerValue));
    if(rxMatch.hasMatch())
    {
        return rxMatch.captured(1).toLocal8Bit();
    }
    return "";
}
Beispiel #22
0
Widget::Widget(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::Widget)
{
    ui->setupUi(this);

    QObject::connect(&scannerThread, SIGNAL(started()), &scanner, SLOT(start()));
    QObject::connect(&scannerThread, SIGNAL(finished()), &scanner, SLOT(stop()));

    QObject::connect(&scanner, SIGNAL(captured(CaptureInfo)), this, SLOT(setCaptureInfo(CaptureInfo)), Qt::BlockingQueuedConnection);

    QObject::connect(&channelThread, SIGNAL(started()), &timer, SLOT(start()));
    QObject::connect(&timer, SIGNAL(timeout()), this, SLOT(channelLoop()));
    QObject::connect(&channelThread, SIGNAL(finished()), &timer, SLOT(stop()));

}
Beispiel #23
0
Range::Range(const QString &input)
{
  static const QRegularExpression pattern(
    "\\A"
    "([\\+-]?\\d+)?"
    "(?:,([\\+-]?\\d+)?)?"
    "\\z"
  );

  const auto match = pattern.match(input);

  m_min = RangeComponent(match.captured(1));
  m_max = RangeComponent(match.captured(2));

  sort();
  rewind();
}
/**
 * @brief prepend the match string with specify symbol
 * @param input string need to prepend symbol
 * @param number_length the length of the number, will prepend symbol
 * if the length smaller than this number
 * @param symbol symbol prepand before the number
 * @return the name after alter
 * @example ex : number_length == 3, reg = (\\d+), symbol = '0'
 * then "1" == "001", "10" == "010"
 * ex : number_length == 2, reg = (\\d+), symbol = '0'
 * then "1" == "01", "10" == "10"
 */
QString prepend_symbol_on_match(QString const &input, int number_length,
                                QRegularExpression const &reg,
                                QChar symbol)
{    
    auto new_file_name = input;
    auto match = reg.match(new_file_name);

    if(match.hasMatch()){
        auto const Captured = match.captured(0);
        if(Captured.size() < number_length){
            new_file_name.insert(match.capturedStart(0),
                                 QString(number_length - match.capturedLength(1),
                                         symbol));
        }
    }

    return new_file_name;
}
Beispiel #25
0
KTextEditor::Cursor KTextEditorHelpers::extractCursor(const QString& input, int* pathLength)
{
    static const QRegularExpression pattern(QStringLiteral(":(\\d+)(?::(\\d+))?$"));
    const auto match = pattern.match(input);
    if (!match.hasMatch()) {
        if (pathLength)
            *pathLength = input.length();
        return KTextEditor::Cursor::invalid();
    }

    int line = match.capturedRef(1).toInt() - 1;
    // don't use an invalid column when the line is valid
    int column = qMax(0, match.captured(2).toInt() - 1);

    if (pathLength)
        *pathLength = match.capturedStart(0);
    return {line, column};
}
//--------------------------------------------------------------
void testApp::findOrigin() {
  int width = ofGetScreenWidth();
  int height = ofGetScreenHeight();
  unsigned char *data = pixelsBelowWindow(0, 0, width, height);
  ofImage banner;
  banner.loadImage("banner.png");
  float start = ofGetElapsedTimef();
  cv::Mat captured(height, width, CV_8UC4, data, 0);
  cv::Mat screen(height, width, CV_8UC3);
  int fromTo[] = {1,0, 2,1, 3,2};
  mixChannels(&captured, 1, &screen, 1, fromTo, 3);
  cv::Mat temp_img = ofxCv::toCv(banner);
  cv::Mat result_img;
  cv::matchTemplate(screen, temp_img, result_img, CV_TM_CCOEFF_NORMED);
  cv::Point max_pt;
  double maxVal;
  cv::minMaxLoc(result_img, NULL, &maxVal, NULL, &max_pt);
  cout << "(" << max_pt.x << ", " << max_pt.y << "), score=" << maxVal << ", time=" << (ofGetElapsedTimef() - start) << endl;
  if (maxVal > 0.9) {
    origin.x = max_pt.x + 20;
    origin.y = max_pt.y + 115 + 63;
    
#if 0
    for (int y = 0; y < 8; y++) {
      for (int x = 0; x < 8; x++) {
        cv::Mat name = screen(cv::Rect(origin.x + x * 50, origin.y + y * 50, 46, 46)).clone();
        ofImage nameko;
        ofxCv::toOf(name, nameko);
        nameko.reloadTexture();
        char filename[256];
        sprintf(filename, "nameko/%06x.png", nameko.getColor(23, 2).getHex());
        ofFile file(filename);
        if (!file.exists()) {
          nameko.saveImage(file);
        }
      }
    }
#endif

    ofSetWindowPosition(origin.x - ofGetWindowWidth() - 25, origin.y - 1);
  }
}
const QString clearHTMLTags(const QString &text)
{
    const QRegularExpression regex("<(\\w+)[^>]*>([^<]*)</\\1>");

    QString ret = text;
    do
    {
        const auto match = regex.match(ret);
        if (!match.isValid() || !match.hasMatch())
            break;

        const int start = match.capturedStart();
        const int len = match.capturedLength();
        const QString &cap = match.captured(2);

        ret.replace(start, len, cap);
    } while (true);

    return ret;
}
Beispiel #28
0
QString Mrl::displayName() const {
	if (isLocalFile())
		return fileName();
	QString disc;
	if (isDvd())
		disc = qApp->translate("Mrl", "DVD");
	else if (isBluray())
		disc = qApp->translate("Mrl", "Blu-ray");
	if (disc.isEmpty())
		return location();
	auto dev = device();
	if (dev.isEmpty())
		return disc;
	if (!dev.startsWith(_L("/dev/"))) {
		QRegularExpression regex("/([^/]+)/*$");
		auto match = regex.match(dev);
		if (match.hasMatch())
			dev = match.captured(1);
	}
	return disc % _L(" (") % dev % _L(')');
}
Beispiel #29
0
void GCapture::run() {
  qDebug() << "stt"; // gilgil temp 2015.10.28
  while (active()) {
    GPacket packet;
    packet.clear();
    packet.capture = this;
    Result res = read(&packet);
    if (res == TimeOut) continue;
    if (res == Eof || res == Fail) break;
    if (autoParse_) packet.parse();
    emit captured(&packet);
    if (this->pathType() == InPath) {
      res = relay(&packet);
      if (res != Ok) {
        qWarning() << "relay return %d" << (int)res; // gilgil temp 2015.10.29
      }
    }
  }
  qDebug() << "end"; // gilgil temp 2015.10.28
  emit closed();
}
Beispiel #30
0
ParsedTags HtmlApi::parseTags(const QString &source, Site *site) const
{
	ParsedTags ret;
	QMap<int, TagType> tagTypes = site->tagDatabase()->tagTypes();

	// Read tags
	QRegularExpression rx(value("Regex/TagApi"), QRegularExpression::DotMatchesEverythingOption);
	auto matches = rx.globalMatch(source);
	while (matches.hasNext())
	{
		auto match = matches.next();

		// Parse result using the regex
		QMap<QString, QString> d;
		for (const QString &group : rx.namedCaptureGroups())
		{
			if (group.isEmpty())
				continue;

			QString val = match.captured(group);
			if (!val.isEmpty())
			{ d[group] = val.trimmed(); }
		}

		// Map variables
		int id = d.contains("id") ? d["id"].toInt() : 0;
		QString name = d["tag"];
		int count = d.contains("count") ? d["count"].toInt() : 0;
		int typeId = d.contains("typeId") ? d["typeId"].toInt() : -1;
		QString ttype = d["type"];

		TagType tagType = !ttype.isEmpty() ? TagType(ttype) : (tagTypes.contains(typeId) ? tagTypes[typeId] : TagType("unknown"));
		ret.tags.append(Tag(id, name, tagType, count));
	}

	return ret;
}