Beispiel #1
0
Kb::~Kb(){
    // Save settings first
    save();

    // remove the notify channel from the list of notifyPaths.
    ///< \todo I don't think, that notifypaths is used somewhere. So why do we have it?
    /// If we do not need it, searching for an ununsed notify channel can easy be refactored to a private member function.
    notifyPaths.remove(macroPath);

    // Kill notification thread and remove node
    activeDevices.remove(this);
    if(!isOpen()){
        terminate();
        wait(1000);
        return;
    }
    if(notifyNumber > 0)
        cmd.write(QString("idle\nnotifyoff %1\n").arg(notifyNumber).toLatin1());
    cmd.flush();
    terminate();
    wait(1000);
    cmd.close();
}
Beispiel #2
0
QSet<int> SuGame::getRowOfFiled_(std::vector<SuFieldCell> &field, int y)
{
    QSet<int> row;

    int beginIndex = y * LEN_SIDE_OF_FIELD;

    for(int i = 0; i < LEN_SIDE_OF_FIELD; i++)
    {
        row.insert(field.at(beginIndex + i).value);
    }

    row.remove(0);

    return row;
}
Beispiel #3
0
void NewGameDialog::configureBlackEngine()
{
	EngineConfigurationDialog dlg(EngineConfigurationDialog::ConfigureEngine, this);

	int i = selectedEngineIndex(Chess::Side::Black);
	const EngineConfiguration& config = m_engineManager->engineAt(i);
	dlg.applyEngineInformation(config);

	QSet<QString> names = m_engineManager->engineNames();
	names.remove(config.name());
	dlg.setReservedNames(names);

	if (dlg.exec() == QDialog::Accepted)
		m_engineManager->updateEngineAt(i, dlg.engineConfiguration());
}
static QString updateVariable(const QString &varStr, const QString &varsToAdd,
                              const QString &varsToRemove)
{
    QSet<QString> var = parseVariable(varStr);

    QSet<QString> ss = parseVariable(varsToAdd);
    foreach (QString s, ss)
        var << s;

    ss = parseVariable(varsToRemove);
    foreach (QString s, ss)
        var.remove(s);

    QStringList sl = QStringList::fromSet(var);
    return sl.join(QLatin1String(" "));
}
void ShrinkToFitShapeContainer::unwrapShape(KoShape *shape)
{
    Q_ASSERT(shape->parent() == this);

    removeShape(shape);
    shape->setParent(parent());

    QSet<KoShape*> delegates = toolDelegates();
    delegates.remove(shape);
    setToolDelegates(delegates);

    shape->setPosition(position());
    shape->setSize(size());
    shape->rotate(rotation());
    shape->setSelectable(true);
}
Beispiel #6
0
QList<const UserBaseInformations*> FreeUser::Search(QMap<QString,AUser*>::const_iterator begin,QMap<QString,AUser*>::const_iterator end, const UserBaseInformations &inf) const
{
    QSet<const UserBaseInformations*> nameSet;
    QSet<const UserBaseInformations*> emailSet;
    QSet<const UserBaseInformations*> resultSet;
    bool set = false;

    if(inf.GetName() != "")
    {

        for(QMap<QString,AUser*>::const_iterator it = begin;it != end ;it++)
        {
            if((*it)->Profile->GetName() == inf.GetName())
                nameSet.insert((*it)->Profile);
        }

        if(!set)
        {
            set = true;
            resultSet = nameSet;
        }
    }

    if(inf.GetEmail() != "")
    {
        for(QMap<QString,AUser*>::const_iterator it = begin;it != end ;it++)
        {
            if((*it)->Profile->GetEmail() == inf.GetEmail())
                emailSet.insert((*it)->Profile);
        }

        if(!set)
        {
            set = true;
            resultSet = emailSet;
        }
    }

    if(inf.GetName()!="")
        resultSet.intersect(nameSet);
    if(inf.GetEmail()!= "")
        resultSet.intersect(emailSet);

    //rimuovo se presente me stesso
    resultSet.remove(this->Profile);
    return QList<const UserBaseInformations*>::fromSet(resultSet);
}
Beispiel #7
0
void QtPropertyDataDavaKeyedArcive::ChildsSync()
{
    QSet<QtPropertyData *> dataToRemove;

    // at first step of sync we mark (placing to vector) items to remove
    for(int i = 0; i < ChildCount(); ++i)
    {
        QPair<QString, QtPropertyData *> pair = ChildGet(i);
        if(NULL != pair.second)
        {
            dataToRemove.insert(pair.second);
        }
    }

    // as second step we go throught keyed archive and add new data items,
    // and remove deleting mark from items that are still in archive
    if(NULL != curArchive)
    {
        DAVA::Map<DAVA::String, DAVA::VariantType*> data = curArchive->GetArchieveData();
        DAVA::Map<DAVA::String, DAVA::VariantType*>::iterator i = data.begin();

        for(; i != data.end(); ++i)
        {
            QtPropertyData *childData = ChildGet(i->first.c_str());

            // this key already in items list
            if(NULL != childData)
            {
                // remove deleting mark
                dataToRemove.remove(childData);
            }
            // create new child data
            else
            {
                ChildCreate(i->first.c_str(), i->second);
            }
        }
    }

    // delete all marked items
    QSetIterator<QtPropertyData *> it(dataToRemove);
    while(it.hasNext())
    {
        ChildRemove(it.next());
    }
}
  void verify(QList<TestContext*> allContexts) {

    {
      DUChainReadLocker lock(DUChain::lock());
      QCOMPARE(m_context->importedParentContexts().count(), imports.count());
    }
    //Compute a closure of all children, and verify that they are imported.
    QSet<TestContext*> collected;
    collectImports(collected);
    collected.remove(this);

    DUChainReadLocker lock(DUChain::lock());
    foreach(TestContext* context, collected) {
      QVERIFY(m_context->imports(context->m_context, CursorInRevision::invalid()));
#ifdef TEST_NORMAL_IMPORTS
      QVERIFY(m_normalContext->imports(context->m_normalContext));
#endif
    }
Beispiel #9
0
void WindowsModel::updateWinList ()
{
    auto& w = Util::XWrapper::Instance ();

    QSet<Window> known;
    for (const auto& info : Windows_)
        known << info.WID_;

    auto current = w.GetWindows ();
    current.erase (std::remove_if (current.begin (), current.end (),
    [this, &w] (Window wid) {
        return !w.ShouldShow (wid);
    }), current.end ());

    for (auto i = current.begin (); i != current.end (); )
    {
        if (known.remove (*i))
            i = current.erase (i);
        else
            ++i;
    }

    for (auto wid : known)
    {
        const auto pos = std::find_if (Windows_.begin (), Windows_.end (),
        [&wid] (const WinInfo& info) {
            return info.WID_ == wid;
        });
        const auto dist = std::distance (Windows_.begin (), pos);
        beginRemoveRows ({}, dist, dist);
        Windows_.erase (pos);
        endRemoveRows ();

        ImageProvider_->RemoveIcon (QString::number (wid));
    }

    if (!current.isEmpty ())
    {
        beginInsertRows ({}, Windows_.size (), Windows_.size () + current.size () - 1);
        for (auto wid : current)
            AddWindow (wid, w);
        endInsertRows ();
    }
}
void OptionsDialog::editKeyword(QListWidgetItem *item)
{
    Keyword keyword;
    keyword.name = item->text();
    keyword.iconResource = item->data(Qt::UserRole).toString();
    keyword.color = item->backgroundColor();

    QSet<QString> keywordNamesButThis = keywordNames();
    keywordNamesButThis.remove(keyword.name);

    KeywordDialog *keywordDialog = new KeywordDialog(keyword, keywordNamesButThis, this);
    if (keywordDialog->exec() == QDialog::Accepted) {
        keyword = keywordDialog->keyword();
        item->setIcon(QIcon(keyword.iconResource));
        item->setText(keyword.name);
        item->setData(Qt::UserRole, keyword.iconResource);
        item->setBackgroundColor(keyword.color);
    }
}
Beispiel #11
0
QSet<int> SuGame::getBlockOfField_(std::vector<SuFieldCell> &field, int x, int y)
{
    QSet<int> block;

    int beginCol = (x / 3) * 3;
    int beginRow = (y / 3) * 3;

    for(int row = 0; row < 3; row++)
    {
        for(int col = 0; col < 3; col++)
        {
            block.insert(field[(beginRow + row) * LEN_SIDE_OF_FIELD + beginCol + col].value);
        }
    }

    block.remove(0);

    return block;
}
Beispiel #12
0
Kb::~Kb(){
    activeDevices.remove(this);
    if(!isOpen()){
        terminate();
        wait(1000);
        return;
    }
    // Kill notification thread and remove node
    if(notifyNumber > 0)
        cmd.write(QString("idle\nnotifyoff %1\n").arg(notifyNumber).toLatin1());
    cmd.flush();
    terminate();
    wait(1000);
    // Reset to hardware profile
    if(_hwProfile){
        _currentProfile = _hwProfile;
        hwSave();
    }
    cmd.close();
}
Beispiel #13
0
QcepObject::~QcepObject()
{
#ifndef QT_NO_DEBUG
  QThread *currTh = QThread::currentThread();
  QThread *objTh  = thread();

  if (objTh && currTh != objTh) {
    printf("Deleting object from different thread %s (%s, %s)\n",
           qPrintable(objectName()),
           qPrintable(currTh ? currTh->objectName() : "null"),
           qPrintable(objTh ? objTh->objectName() : "null"));
  }
#endif

  s_ObjectDeleteCount.fetchAndAddOrdered(1);

#ifndef QT_NO_DEBUG
  s_Allocated.remove(this);
#endif
}
Beispiel #14
0
void ObjectSelectionTool::mouseReleased(QGraphicsSceneMouseEvent *event)
{
    if (event->button() != Qt::LeftButton)
        return;

    switch (mMode) {
    case NoMode:
        if (mClickedObjectItem) {
            QSet<MapObjectItem*> selection = mapScene()->selectedObjectItems();
            const Qt::KeyboardModifiers modifiers = event->modifiers();
            if (modifiers & (Qt::ShiftModifier | Qt::ControlModifier)) {
                if (selection.contains(mClickedObjectItem))
                    selection.remove(mClickedObjectItem);
                else
                    selection.insert(mClickedObjectItem);
            } else {
                selection.clear();
                selection.insert(mClickedObjectItem);
            }
            mapScene()->setSelectedObjectItems(selection);
        } else {
            mapScene()->setSelectedObjectItems(QSet<MapObjectItem*>());
        }
        break;
    case Selecting:
        updateSelection(event->scenePos(), event->modifiers());
        mapScene()->removeItem(mSelectionRectangle);
        mMode = NoMode;
        break;
    case Moving:
        finishMoving(event->scenePos());
        break;
    case Rotating:
        finishRotating(event->scenePos());
        break;
    }

    mMousePressed = false;
    mClickedObjectItem = 0;
    mClickedCornerHandle = 0;
}
void QGeoTiledMappingManagerEngine::deregisterMap(QGeoTiledMapData *map)
{
    d_ptr->tileMaps_.remove(map);
    d_ptr->mapHash_.remove(map);

    QHash<QGeoTileSpec, QSet<QGeoTiledMapData *> > newTileHash = d_ptr->tileHash_;
    typedef QHash<QGeoTileSpec, QSet<QGeoTiledMapData *> >::const_iterator h_iter;
    h_iter hi = d_ptr->tileHash_.constBegin();
    h_iter hend = d_ptr->tileHash_.constEnd();
    for (; hi != hend; ++hi) {
        QSet<QGeoTiledMapData *> maps = hi.value();
        if (maps.contains(map)) {
            maps.remove(map);
            if (maps.isEmpty())
                newTileHash.remove(hi.key());
            else
                newTileHash.insert(hi.key(), maps);
        }
    }
    d_ptr->tileHash_ = newTileHash;
}
Beispiel #16
0
void tst_QSet::reserve()
{
    QSet<int> set;
    int n = set.capacity();
    QVERIFY(n == 0);

    set.reserve(1000);
    QVERIFY(set.capacity() >= 1000);

    for (int i = 0; i < 500; ++i)
        set.insert(i);

    QVERIFY(set.capacity() >= 1000);

    for (int j = 0; j < 500; ++j)
        set.remove(j);

    QVERIFY(set.capacity() >= 1000);

    set.clear();
    QVERIFY(set.capacity() == 0);
}
void EngineManagementWidget::configureEngine(const QModelIndex& index)
{
	// Map the index from the filtered model to the original model
	int row = m_filteredModel->mapToSource(index).row();
	const EngineConfiguration& config = m_engineManager->engineAt(row);

	QSet<QString> names = m_engineManager->engineNames();
	names.remove(config.name());

	auto dlg = new EngineConfigurationDialog(
		EngineConfigurationDialog::ConfigureEngine, this);
	dlg->setAttribute(Qt::WA_DeleteOnClose);
	dlg->applyEngineInformation(config);
	dlg->setReservedNames(names);

	connect(dlg, &EngineConfigurationDialog::accepted, [=]()
	{
		m_engineManager->updateEngineAt(row, dlg->engineConfiguration());
		m_hasChanged = true;
	});
	dlg->open();
}
Beispiel #18
0
void Qt4SimulatorTarget::createApplicationProFiles()
{
    removeUnconfiguredCustomExectutableRunConfigurations();

    // We use the list twice
    QList<Qt4ProFileNode *> profiles = qt4Project()->applicationProFiles();
    QSet<QString> paths;
    foreach (Qt4ProFileNode *pro, profiles)
        paths << pro->path();

    foreach (ProjectExplorer::RunConfiguration *rc, runConfigurations())
        if (Qt4RunConfiguration *qt4rc = qobject_cast<Qt4RunConfiguration *>(rc))
            paths.remove(qt4rc->proFilePath());

    // Only add new runconfigurations if there are none.
    foreach (const QString &path, paths)
        addRunConfiguration(new Qt4RunConfiguration(this, path));

    // Oh still none? Add a custom executable runconfiguration
    if (runConfigurations().isEmpty()) {
        addRunConfiguration(new ProjectExplorer::CustomExecutableRunConfiguration(this));
    }
}
Beispiel #19
0
void setSelect(QSet<T> &set, bool b, const U &val) {
   if (b) set.insert(val); else set.remove(val);
}
Beispiel #20
0
void LibraryModel::SongsDeleted(const SongList& songs) {
  // Delete the actual song nodes first, keeping track of each parent so we
  // might check to see if they're empty later.
  QSet<LibraryItem*> parents;
  for (const Song& song : songs) {
    if (song_nodes_.contains(song.id())) {
      LibraryItem* node = song_nodes_[song.id()];

      if (node->parent != root_) parents << node->parent;

      beginRemoveRows(ItemToIndex(node->parent), node->row, node->row);
      node->parent->Delete(node->row);
      song_nodes_.remove(song.id());
      endRemoveRows();
    } else {
      // If we get here it means some of the songs we want to delete haven't
      // been lazy-loaded yet.  This is bad, because it would mean that to
      // clean up empty parents we would need to lazy-load them all
      // individually to see if they're empty.  This can take a very long time,
      // so better to just reset the model and be done with it.
      Reset();
      return;
    }
  }

  // Now delete empty parents
  QSet<QString> divider_keys;
  while (!parents.isEmpty()) {
    // Since we are going to remove elements from the container, we
    // need a copy to iterate over. If we iterate over the original,
    // the behavior will be undefined.
    QSet<LibraryItem*> parents_copy = parents;
    for (LibraryItem* node : parents_copy) {
      parents.remove(node);
      if (node->children.count() != 0) continue;

      // Consider its parent for the next round
      if (node->parent != root_) parents << node->parent;

      // Maybe consider its divider node
      if (node->container_level == 0)
        divider_keys << DividerKey(group_by_[0], node);

      // Special case the Various Artists node
      if (IsCompilationArtistNode(node))
        node->parent->compilation_artist_node_ = nullptr;
      else
        container_nodes_[node->container_level].remove(node->key);

      // It was empty - delete it
      beginRemoveRows(ItemToIndex(node->parent), node->row, node->row);
      node->parent->Delete(node->row);
      endRemoveRows();
    }
  }

  // Delete empty dividers
  for (const QString& divider_key : divider_keys) {
    if (!divider_nodes_.contains(divider_key)) continue;

    // Look to see if there are any other items still under this divider
    bool found = false;
    for (LibraryItem* node : container_nodes_[0].values()) {
      if (DividerKey(group_by_[0], node) == divider_key) {
        found = true;
        break;
      }
    }

    if (found) continue;

    // Remove the divider
    int row = divider_nodes_[divider_key]->row;
    beginRemoveRows(ItemToIndex(root_), row, row);
    root_->Delete(row);
    endRemoveRows();
    divider_nodes_.remove(divider_key);
  }
}
Beispiel #21
0
void GenericProjectNode::refresh(QSet<QString> oldFileList)
{
    if (oldFileList.isEmpty()) {
        // Only do this once
        FileNode *projectFilesNode = new FileNode(m_project->filesFileName(),
                                                  ProjectFileType,
                                                  /* generated = */ false);

        FileNode *projectIncludesNode = new FileNode(m_project->includesFileName(),
                                                     ProjectFileType,
                                                     /* generated = */ false);

        FileNode *projectConfigNode = new FileNode(m_project->configFileName(),
                                                   ProjectFileType,
                                                   /* generated = */ false);

        addFileNodes(QList<FileNode *>()
                     << projectFilesNode
                     << projectIncludesNode
                     << projectConfigNode,
                     this);
    }

    // Do those separately
    oldFileList.remove(m_project->filesFileName());
    oldFileList.remove(m_project->includesFileName());
    oldFileList.remove(m_project->configFileName());

    QSet<QString> newFileList = m_project->files().toSet();
    newFileList.remove(m_project->filesFileName());
    newFileList.remove(m_project->includesFileName());
    newFileList.remove(m_project->configFileName());

    QSet<QString> removed = oldFileList;
    removed.subtract(newFileList);
    QSet<QString> added = newFileList;
    added.subtract(oldFileList);

    QString baseDir = QFileInfo(path()).absolutePath();
    QHash<QString, QStringList> filesInPaths = sortFilesIntoPaths(baseDir, added);
    foreach (const QString &filePath, filesInPaths.keys()) {
        QStringList components = filePath.split(QLatin1Char('/'));
        FolderNode *folder = findFolderByName(components, components.size());
        if (!folder)
            folder = createFolderByName(components, components.size());

        QList<FileNode *> fileNodes;
        foreach (const QString &file, filesInPaths.value(filePath)) {
            FileType fileType = SourceType; // ### FIXME
            FileNode *fileNode = new FileNode(file, fileType, /*generated = */ false);
            fileNodes.append(fileNode);
        }

        addFileNodes(fileNodes, folder);
    }

    filesInPaths = sortFilesIntoPaths(baseDir, removed);
    foreach (const QString &filePath, filesInPaths.keys()) {
        QStringList components = filePath.split(QLatin1Char('/'));
        FolderNode *folder = findFolderByName(components, components.size());

        QList<FileNode *> fileNodes;
        foreach (const QString &file, filesInPaths.value(filePath)) {
            foreach (FileNode *fn, folder->fileNodes())
                if (fn->path() == file)
                    fileNodes.append(fn);
        }

        removeFileNodes(fileNodes, folder);
    }

    foreach (FolderNode *fn, subFolderNodes())
        removeEmptySubFolders(this, fn);

}
void NetworkAccessManager::HandleDownload(QObject *object){
#ifdef WEBENGINEVIEW
    static QSet<QObject*> set;
    if(set.contains(object)) return;
    set << object;
    connect(object, &QObject::destroyed, [object](){ set.remove(object);});

    Application::AskDownloadPolicyIfNeed();

    DownloadItem *item = new DownloadItem(object);
    QWebEngineDownloadItem *orig_item = qobject_cast<QWebEngineDownloadItem*>(object);

    QString dir = Application::GetDownloadDirectory();
    QString filename;
    QString mime;
    QUrl url;
    if(orig_item){
        if(WebEngineView *w = qobject_cast<WebEngineView*>(Application::CurrentWidget())){
            if(TreeBank *tb = w->GetTreeBank()) tb->GoBackOrCloseForDownload(w);
        }
        filename = orig_item->path();
        mime = orig_item->mimeType();
        url = orig_item->url();
    } else {
        if(QuickWebEngineView *w = qobject_cast<QuickWebEngineView*>(Application::CurrentWidget())){
            if(TreeBank *tb = w->GetTreeBank()) tb->GoBackOrCloseForDownload(w);
        }
        filename = object->property("path").toString();
        mime = object->property("mimeType").toString();
        url = object->property("url").toUrl();
    }

    filename = filename.isEmpty() ? dir
        : dir + filename.split(QStringLiteral("/")).last();

    if(filename.isEmpty() ||
       Application::GetDownloadPolicy() == Application::Undefined_ ||
       Application::GetDownloadPolicy() == Application::AskForEachDownload){

        QString filter;

        QMimeDatabase db;
        QMimeType mimeType = db.mimeTypeForName(mime);
        if(!mimeType.isValid() || mimeType.isDefault()) mimeType = db.mimeTypeForFile(filename);
        if(!mimeType.isValid() || mimeType.isDefault()) mimeType = db.mimeTypeForUrl(url);

        if(mimeType.isValid() && !mimeType.isDefault()) filter = mimeType.filterString();

        filename = ModalDialog::GetSaveFileName_(QString(), filename, filter);
    }

    if(filename.isEmpty()){
        QMetaObject::invokeMethod(object, "cancel");
        item->deleteLater();
        return;
    }

    item->SetPath(filename);
    if(orig_item){
        orig_item->setPath(filename);
    } else {
        object->setProperty("path", filename);
    }
    QMetaObject::invokeMethod(object, "accept");
    MainWindow *win = Application::GetCurrentWindow();
    if(win && win->GetTreeBank()->GetNotifier())
        win->GetTreeBank()->GetNotifier()->RegisterDownload(item);

    QStringList path = filename.split(QStringLiteral("/"));
    path.removeLast();
    Application::SetDownloadDirectory(path.join(QStringLiteral("/")) + QStringLiteral("/"));
#else
    Q_UNUSED(object);
#endif
}
Beispiel #23
0
KbLight::~KbLight(){
    activeLights.remove(this);
}
Beispiel #24
0
QList<const UserBaseInformations*> ExecutiveUser::Search(QMap<QString,AUser*>::const_iterator begin,QMap<QString,AUser*>::const_iterator end, const UserBaseInformations &inf) const
{
    //prima parte di codice
    QSet<const UserBaseInformations*> nameSet;
    QSet<const UserBaseInformations*> emailSet;
    QSet<const UserBaseInformations*> surnameSet;
    QSet<const UserBaseInformations*> ageSet;
    QSet<const UserBaseInformations*> genderSet;
    QSet<const UserBaseInformations*> countrySet;
    QSet<const UserBaseInformations*> citySet;
    QSet<const UserBaseInformations*> streetSet;
    bool set = false;
    QSet<const UserBaseInformations*> resultSet;

    if(inf.GetName() != "")
    {

        for(QMap<QString,AUser*>::const_iterator it = begin;it != end ;it++)
        {
            if((*it)->Profile->GetName() == inf.GetName())
                nameSet.insert((*it)->Profile);
        }

        if(!set)
        {
            set = true;
            resultSet = nameSet;
        }
    }

    if(inf.GetEmail() != "")
    {
        for(QMap<QString,AUser*>::const_iterator it = begin;it != end ;it++)
        {
            if((*it)->Profile->GetEmail() == inf.GetEmail())
                emailSet.insert((*it)->Profile);
        }

        if(!set)
        {
            set = true;
            resultSet = emailSet;
        }
    }

    if(inf.GetSurname() != "")
    {
        for(QMap<QString,AUser*>::const_iterator it = begin;it != end ;it++)
        {
            if((*it)->Profile->GetSurname() == inf.GetSurname())
                surnameSet.insert((*it)->Profile);
        }
        if(!set)
        {
            set = true;
            resultSet = surnameSet;
        }
    }

    if(inf.GetAge() != 0)
    {
        for(QMap<QString,AUser*>::const_iterator it = begin;it != end ;it++)
        {
            if((*it)->Profile->GetAge() == inf.GetAge())
                ageSet.insert((*it)->Profile);
        }
        if(!set)
        {
            set = true;
            resultSet = ageSet;
        }
    }

    if(inf.GetGender() != 0)
    {
        for(QMap<QString,AUser*>::const_iterator it = begin;it != end ;it++)
        {
            if((*it)->Profile->GetGender() == inf.GetGender())
                genderSet.insert((*it)->Profile);
        }

        if(!set)
        {
            set = true;
            resultSet = genderSet;
        }
    }

    if(inf.GetCountry() != 0)
    {
        for(QMap<QString,AUser*>::const_iterator it = begin;it != end ;it++)
        {
            if((*it)->Profile->GetCountry() == inf.GetCountry())
                countrySet.insert((*it)->Profile);
        }

        if(!set)
        {
            set = true;
            resultSet = countrySet;
        }
    }

    if(inf.GetCity() != 0)
    {
        for(QMap<QString,AUser*>::const_iterator it = begin;it != end ;it++)
        {
            if((*it)->Profile->GetCity() == inf.GetCity())
                citySet.insert((*it)->Profile);
        }

        if(!set)
        {
            set = true;
            resultSet = citySet;
        }
    }

    if(inf.GetStreet() != 0)
    {
        for(QMap<QString,AUser*>::const_iterator it = begin;it != end ;it++)
        {
            if((*it)->Profile->GetStreet() == inf.GetStreet())
                streetSet.insert((*it)->Profile);
        }

        if(!set)
        {
            set = true;
            resultSet = streetSet;
        }
    }





    if(inf.GetName()!="")
        resultSet.intersect(nameSet);
    if(inf.GetEmail()!= "")
        resultSet.intersect(emailSet);
    if(inf.GetSurname()!="")
        resultSet.intersect(surnameSet);
    if(inf.GetAge()!= 0)
        resultSet.intersect(ageSet);
    if(inf.GetGender() != 0)
        resultSet.intersect(genderSet);
    if(inf.GetCountry()!="")
        resultSet.intersect(countrySet);
    if(inf.GetCity()!= 0)
        resultSet.intersect(citySet);
    if(inf.GetStreet() != 0)
        resultSet.intersect(streetSet);

    //rimuovo se presente me stesso
    resultSet.remove(this->Profile);
    return QList<const UserBaseInformations*>::fromSet(resultSet);
}
long long pathNumber(int x, int y, int depth) {
	long long result = 0;

	if (depth == 0)
		return 1;

	// try upper cell
	if (!alreadySeenCell.contains(
				QPair<int, int>(x, y - 1)
				)
	)
	{
		alreadySeenCell.insert(
				QPair<int, int>(x, y - 1)
				);
		result += pathNumber(x, y - 1, depth - 1);
		alreadySeenCell.remove(
				QPair<int, int>(x, y - 1)
				);
	}
		

	// try lower cell
	if (!alreadySeenCell.contains(
				QPair<int, int>(x, y + 1)
				)
	)
	{
		alreadySeenCell.insert(
				QPair<int, int>(x, y + 1)
				);
		result += pathNumber(x, y + 1, depth - 1);
		alreadySeenCell.remove(
				QPair<int, int>(x, y + 1)
				);
	}

	// try left cell
	if (!alreadySeenCell.contains(
				QPair<int, int>(x - 1, y)
				)
	)
	{
		alreadySeenCell.insert(
				QPair<int, int>(x - 1, y)
				);
		result += pathNumber(x - 1, y, depth - 1);
		alreadySeenCell.remove(
				QPair<int, int>(x - 1, y)
				);
	}

	// try right cell
	if (!alreadySeenCell.contains(
				QPair<int, int>(x + 1, y)
				)
	)
	{
		alreadySeenCell.insert(
				QPair<int, int>(x + 1, y)
				);
		result += pathNumber(x + 1, y, depth - 1);
		alreadySeenCell.remove(
				QPair<int, int>(x + 1, y)
				);
	}

	return result;
}
Beispiel #26
0
bool CmdExorcise::exec(CmdHelper* ch)
{
  if(!init(ch)) return false;

  mCmd->regStdOpts("del-omen save-omen");

  if(mCmd->isMissingParms())
  {
    mCmd->inOptBrief("del-omen", "[<Devil>]", "Delete the config file and home directory of <Devil>");
    mCmd->inOptBrief("save-omen", "Don't delete the config file and home directory of <Devil>");

    if(mCmd->printThisWay("[<Devil>]")) return true;

    mCmd->printComment(tr(
      "Switch in any case back to the productive version by restoring the "
      "productive user config file and delete (if given) the development "
      "schema <Devil>. At default is the devil config file and home directory saved."));
    mCmd->printNote(tr(
      "You could set in your productive config file 'DeleteDevilConfig=true' to auto "
      "remove the devil config file and home directory. See doc/config-file.txt."));
    mCmd->printForInst("mylastidea", tr(
      "Remove the DB schema but keep the config file and home directory."));
    mCmd->printForInst("--del-omen mygoodidea", tr(
      "Only delete the config file and home directory, keep the DB untouched."));
    mCmd->printForInst("mybadidea --del-omen", tr(
      "Delete DB schema, config file and home directory."));
    mCmd->aided();
    return true;
  }

  QString configFile  = mRcFile->fileName();
  QString devil       = FTool::makeValidWord(mRcFile->getST("Devil"));
  QString killDevil   = FTool::makeValidWord(mCmd->argStr(1, ""));
  QString devilFile   = configFile + ".Devil." + devil;
  QString proFile     = configFile + ".Productive";
  bool    configSaved = false;

  if(!devil.isEmpty())
  {
    verbose(FUNC, tr("I renunciate the devil '%1'").arg(devil));

    QFile::remove(devilFile);
    QFile::rename(configFile, devilFile);

    configSaved = true;

    if(QFile::exists(proFile))
    {
      QFile::rename(proFile, configFile);

      mRcFile->sync();
      mRcFile->remove("Devil"); // Be sure we are no longer devilish
      mRcFile->checkFiluHome();
      verbose(FUNC, tr("Productive config file restored."));
    }
    else
    {
      mRcFile->checkConfigFile();
      mRcFile->checkFiluHome();
    }

    verbose(FUNC, tr("SqlPath is now: %1").arg(mRcFile->getPath("SqlPath")));
    verbose(FUNC, tr("ProviderPath is now: %1").arg(mRcFile->getPath("ProviderPath")));
    mFilu->closeDB();
    mFilu->openDB();
  }

  QString user = qgetenv("USER");

  mFilu->setSqlParm(":username", user);
  QSqlQuery* query = mFilu->execSql("GetDevils");

  QSet<QString> devils;
  const QString devilPrefix = QString("user_%1_").arg(user);
  while(query->next())
  {
    QString devil = query->value(0).toString();
    devil.remove(devilPrefix);
    devils.insert(devil);
  }

  if(     (mCmd->has("del-omen") or mRcFile->getBL("DeleteDevilConfig"))
      and !mCmd->has("save-omen") )
  {
    QString devil = killDevil.isEmpty() ? mCmd->optStr("del-omen") : killDevil;
    devilFile = configFile + ".Devil." + devil;

    if(!devil.isEmpty())
    {
      if(QFile::exists(devilFile))
      {
        FTool::removeDir(SettingsFile(devilFile).getPath("FiluHome"));
        verbose(FUNC, tr("FiluHome of devil '%1' removed.").arg(devil));

        QFile::remove(devilFile);
        verbose(FUNC, tr("Config file for devil '%1' removed.").arg(devil));
        configSaved = false;
      }
      else
      {
        error(FUNC, tr("No config file for devil '%1' found to remove.").arg(devil));
      }
    }
  }

  const QString filuDevil = "%1_%2_%3";
  const QString userDevil = "user_%1_%2";

//   Out commentetd because I run in my own trap.
//   It is not possible to execute a SQL more than one time with static
//   parameters. What we need is a "execute once" function wich release the SQL
//   after executen, or a "release <sql>" function, or a "execStatic" function
//   wich works with normal setSqlParm() but does not use query-bind() but
//   replace the paramater by his own
//   if("+++" == killDevil) // Exorcise all devils
//   {
//     foreach(const QString& d, devils)
//     {
//       verbose(FUNC, tr("Devil '%1'.").arg(d));
//       mFilu->setStaticSqlParm(":filuDevil", filuDevil.arg(mRcFile->getST("FiluSchema"), user, d));
//       mFilu->setStaticSqlParm(":userDevil", userDevil.arg(user, d));
//       mFilu->execSql("BackToHell");
//
// //       devils.remove(d);
//
//       if(!mFilu->hasError())
//       {
//         verbose(FUNC, tr("Devil '%1' is banned back to hell.").arg(d));
//       }
//       else
//       {
//         return;
//       }
//     }
//
//     devils.clear();
//   }
//   else

  if(!killDevil.isEmpty())
  {
    if(devils.contains(killDevil))
    {
      mFilu->setStaticSqlParm(":filuDevil", filuDevil.arg("filu", user, killDevil));
      mFilu->setStaticSqlParm(":userDevil", userDevil.arg(user, killDevil));
      mFilu->execSql("BackToHell");

      devils.remove(killDevil);

      if(!mFilu->hasError())
      {
        verbose(FUNC, tr("Devil '%1' is banned back to hell.").arg(killDevil));
      }
    }
    else
    {
      error(FUNC, tr("No devil '%1' is amongst us.").arg(killDevil));
    }
  }
  else if(configSaved)
  {
    verbose(FUNC, tr("Config file for devil '%1' saved.").arg(devil));
  }

  if(verboseLevel(eInfo))
  {
    if(!devils.size())
    {
      verbose(FUNC, tr("No devils out of hell."));
    }
    else if(devils.size() == 1)
    {
      verbose(FUNC, tr("The devil is still amongst us:"));
      verbose(FUNC, QString("  %1").arg(devils.toList().at(0)));
    }
    else
    {
      verbose(FUNC, tr("These devils are still amongst us:"));
      foreach(const QString& d, devils) verbose(FUNC, QString("  %1").arg(d));
    }

    // FIXME: Looks ugly, find and print omen in a  more nicely way
    QString path = mRcFile->fileName();
    path.remove(QRegExp("[\\w\\.]+$"));
    QDirIterator dirIterator(path);
    bool infoTxt = false;
    while(dirIterator.hasNext())
    {
      dirIterator.next();
      QString omen = dirIterator.fileName();
      if(!omen.startsWith("Filu.conf.Devil.")) continue;

      omen.remove("Filu.conf.Devil.");
      if(devils.contains(omen)) continue;
      if(!infoTxt)
      {
        verbose(FUNC, tr("There are devil omen:"));
        infoTxt = true;
      }
      verbose(FUNC, QString("  %1").arg(omen));
    }
  }

  return !hasError();
}
Beispiel #27
0
void RateController::transfer()
{
    transferScheduled = false;
    if (sockets.isEmpty())
        return;

    int msecs = 1000;
    if (!stopWatch.isNull())
        msecs = qMin(msecs, stopWatch.elapsed());

    qint64 bytesToWrite = (upLimit * msecs) / 1000;
    qint64 bytesToRead = (downLimit * msecs) / 1000;
    if (bytesToWrite == 0 && bytesToRead == 0) {
        scheduleTransfer();
        return;
    }

    QSet<PeerWireClient *> pendingSockets;
    foreach (PeerWireClient *client, sockets) {
        if (client->canTransferMore())
            pendingSockets << client;
    }
    if (pendingSockets.isEmpty())
        return;

    stopWatch.start();

    bool canTransferMore;
    do {
        canTransferMore = false;
        qint64 writeChunk = qMax<qint64>(1, bytesToWrite / pendingSockets.size());
        qint64 readChunk = qMax<qint64>(1, bytesToRead / pendingSockets.size());

        QSetIterator<PeerWireClient *> it(pendingSockets);
        while (it.hasNext() && (bytesToWrite > 0 || bytesToRead > 0)) {
            PeerWireClient *socket = it.next();
            if (socket->state() != QAbstractSocket::ConnectedState) {
                pendingSockets.remove(socket);
                continue;
            }

            bool dataTransferred = false;
            qint64 available = qMin<qint64>(socket->socketBytesAvailable(), readChunk);
            if (available > 0) {
                qint64 readBytes = socket->readFromSocket(qMin<qint64>(available, bytesToRead));
                if (readBytes > 0) {
                    bytesToRead -= readBytes;
                    dataTransferred = true;
                }
            }

            if (upLimit * 2 > socket->bytesToWrite()) {
                qint64 chunkSize = qMin<qint64>(writeChunk, bytesToWrite);
                qint64 toWrite = qMin(upLimit * 2 - socket->bytesToWrite(), chunkSize);
                if (toWrite > 0) {
                    qint64 writtenBytes = socket->writeToSocket(toWrite);
                    if (writtenBytes > 0) {
                        bytesToWrite -= writtenBytes;
                        dataTransferred = true;
                    }
                }
            }

            if (dataTransferred && socket->canTransferMore())
                canTransferMore = true;
            else
                pendingSockets.remove(socket);
        }
    } while (canTransferMore && (bytesToWrite > 0 || bytesToRead > 0) && !pendingSockets.isEmpty());

    if (canTransferMore || bytesToWrite == 0 || bytesToRead == 0)
        scheduleTransfer();
}
Beispiel #28
0
// Component type is the one passed inside QML (registered name)
MetaComponent * MetaComponent::create(const QString &componentType, QObject *parent)
{
    // 1. Try to get the C++ metatype registered from the QML name
    // Right now, we run through all registered QML modules, and get the correct one.
    // If several are found, we break. Not the nicest, but we can do something better later.
    QList<QQmlType *> types = QQmlMetaType::qmlTypes();
    QList<QByteArray> found;
    foreach (const QQmlType *type, types) {
        if (type->elementName() == componentType) {
            found.append(type->typeName());
        }
    }

    if (found.isEmpty()) {
        qWarning() << "No QML component were registered with name" << componentType;
        return 0;
    }

    if (found.count() > 1) {
        qWarning() << "Several QML components were registered with name" << componentType;
        return 0;
    }

    QByteArray cppTypeByteArray = found.first();
    cppTypeByteArray.append("*");
    const char *cppType = QMetaObject::normalizedType(cppTypeByteArray).constData();


    // 2. Try to get the Phonebot MetaData
    int componentTypeIndex = QMetaType::type(cppType);
    if (componentTypeIndex == QMetaType::UnknownType) {
        qWarning() << "Cannot get Phonebot metadata from" << componentType << ":"
                   << "Cannot find Qt metatype for" << cppType
                   << "It might not be registered via qmlRegisterType.";
        return 0;
    }

    const QMetaObject *componentMeta = QMetaType::metaObjectForType(componentTypeIndex);
    int metaClassInfoIndex = componentMeta->indexOfClassInfo("meta");
    if (metaClassInfoIndex == -1) {
        qWarning() << "Cannot get Phonebot metadata from" << componentType << ":"
                   << cppType << "don't have a Phonebot metatype."
                   << "Did you forgot PHONEBOT_METADATA macro ?";
        return 0;
    }

    QMetaClassInfo metaClassInfo = componentMeta->classInfo(metaClassInfoIndex);
    QByteArray metaNameByteArray (metaClassInfo.value());
    metaNameByteArray.append("*");
    const char *metaName = QMetaObject::normalizedType(metaNameByteArray).constData();

    int metaTypeIndex = QMetaType::type(metaName);
    if (metaTypeIndex == QMetaType::UnknownType) {
        qWarning() << "Cannot get Phonebot metadata from" << componentType << ":"
                   << "Cannot find Qt metatype for Phonebot metatype" << metaName
                   << "It might not be registered via qDeclareMetaType.";
        return 0;
    }

    // Check if it inherits from AbstractMetaData
    bool ok = false;
    const QMetaObject *componentMetaMeta = QMetaType::metaObjectForType(metaTypeIndex);
    const QMetaObject *super = componentMetaMeta;
    while (super) {
        if (!ok) {
            ok =  (super->className() == AbstractMetaData::staticMetaObject.className());
        }
        super = super->superClass();
    }

    if (!ok) {
        qWarning() << "Cannot get Phonebot metadata from" << componentType << ":"
                   << "Phonebot metatype class" << metaName << "don't inherit from"
                   << AbstractMetaData::staticMetaObject.className();
        return 0;
    }

    // Construct
    QObject *meta = componentMetaMeta->newInstance();
    if (!meta) {
        qWarning() << "Cannot get Phonebot metadata from" << componentType << ":"
                   << "Phonebot metatype class " << metaName
                   << "don't have an invokable constructor and cannot be created.";
        return 0;
    }
    AbstractMetaData *castedMeta = qobject_cast<AbstractMetaData *>(meta);
    Q_ASSERT(castedMeta);

    QSet<QString> properties;
    for (int i = componentMeta->propertyOffset(); i < componentMeta->propertyCount(); ++i) {
        properties.insert(componentMeta->property(i).name());
    }

    QStringList removedProperties;
    foreach (const QString &property, properties) {
        if (!castedMeta->property(property)) {
            qWarning() << property << "do not have metadata registered";
        }
    }

    foreach (const QString &property, removedProperties) {
        properties.remove(property);
    }
Beispiel #29
0
highScoreManager::~highScoreManager()
{
	s_allHSM.remove(this);
}
void QgsMapRendererParallelJob::renderLayerStatic( LayerRenderJob& job )
{
  if ( job.context.renderingStopped() )
    return;

  if ( job.cached )
    return;

#ifdef QGISDEBUG
  static QSet<QString> running;
  static QMultiMap<int, QString> elapsed;

  QSettings settings;
  bool log = settings.value( "/Map/logCanvasRefreshEvent", false ).toBool();

  QTime t;
  t.start();
  QgsDebugMsg( QString( "job %1 start" ).arg( reinterpret_cast< ulong >( &job ), 0, 16 ) );
  if ( log )
  {
    QgsMessageLog::logMessage( tr( "Layer %1 job started" ).arg( job.layerId ), tr( "Rendering" ) );
    Q_ASSERT( !running.contains( job.layerId ) );
    running << job.layerId;
  }
#endif

  try
  {
    job.renderer->render();
  }
  catch ( QgsException & e )
  {
    QgsDebugMsg( "Caught unhandled QgsException: " + e.what() );
  }
  catch ( std::exception & e )
  {
    QgsDebugMsg( "Caught unhandled std::exception: " + QString::fromAscii( e.what() ) );
  }
  catch ( ... )
  {
    QgsDebugMsg( "Caught unhandled unknown exception" );
  }

#ifdef QGISDEBUG
  int tt = t.elapsed();

  QgsDebugMsg( QString( "job %1 end [%2 ms]" ).arg( reinterpret_cast< ulong >( &job ), 0, 16 ).arg( tt ) );

  if ( log )
  {
    running.remove( job.layerId );
    elapsed.insert( tt, job.layerId );

    QgsMessageLog::logMessage( tr( "Layer %1 job ended (%2 ms; still running:%3)" ).arg( job.layerId ).arg( tt ).arg( QStringList( running.values() ).join( ", " ) ), tr( "Rendering" ) );
    if ( running.isEmpty() )
    {
      QList<int> tt( elapsed.keys() );
      qSort( tt.begin(), tt.end(), qGreater<int>() );
      Q_FOREACH ( int t, tt )
      {
        QgsMessageLog::logMessage( tr( "%1 ms: %2" ).arg( t ).arg( QStringList( elapsed.values( t ) ).join( ", " ) ), tr( "Rendering" ) );
      }
      QgsMessageLog::logMessage( "---", tr( "Rendering" ) );
      elapsed.clear();
    }