Ejemplo n.º 1
0
void ConditionalDialog::slotOk()
{
    kDebug() << "slotOk";

    if (!checkInputData())
        return;

    kDebug() << "Input data is valid";

    QLinkedList<KCConditional> newList;

    KCConditional newCondition;

    if (getCondition(newCondition, m_dlg->m_condition_1, m_dlg->m_firstValue_1,
                     m_dlg->m_secondValue_1, m_dlg->m_style_1))
        newList.append(newCondition);

    if (getCondition(newCondition, m_dlg->m_condition_2, m_dlg->m_firstValue_2,
                     m_dlg->m_secondValue_2, m_dlg->m_style_2))
        newList.append(newCondition);

    if (getCondition(newCondition, m_dlg->m_condition_3, m_dlg->m_firstValue_3,
                     m_dlg->m_secondValue_3, m_dlg->m_style_3))
        newList.append(newCondition);

    kDebug() << "Setting conditional list";
    KCConditionCommand* manipulator = new KCConditionCommand();
    manipulator->setSheet(m_selection->activeSheet());
    manipulator->setConditionList(newList);
    manipulator->add(*m_selection);
    manipulator->execute(m_selection->canvas());

    accept();
}
Ejemplo n.º 2
0
void SeparateNodesExecutor::execute_server()
{

	int count, id;

	*stream >>count;

	Data::Graph* currentGraph = Manager::GraphManager::getInstance()->getActiveGraph();
	QMap<qlonglong, osg::ref_ptr<Data::Node> >* nodes = currentGraph -> getMetaNodes();

	QLinkedList<osg::ref_ptr<Data::Node> >* selectedNodes = new QLinkedList<osg::ref_ptr<Data::Node> >();

	for ( int i = 0; i < count; i++ ) {
		*stream >> id;
		if ( nodes->contains( id ) ) {
			selectedNodes->append( *nodes->find( id ) );
		}
	}

	Server* server = Server::getInstance();
	currentGraph->separateNodes( selectedNodes );

	server->sendSeparateNodes( selectedNodes );

	if ( ( ( QOSG::CoreWindow* )server->getCoreWindowReference() )->playing() ) {
		server->getLayoutThread()->play();
	}
	return;

}
Ejemplo n.º 3
0
/**
 * Produces an erase plan for clearing the entire device.
 *
 * Special care is taken to erase the Config Words page last, when writeConfig is
 * turned on and the device uses FLASH for Config Words.
 *
 * When writeConfig is false, care is taken to avoid erasing the Config Words page.
 *
 * This routine makes sure not to erase the Bootloader Block.
 *
 * All erases are listed in reverse address order. This forces the program to
 * erase all application code from the device before finally erasing the crucial
 * address 0 reset vector. With all application code erased, having a "GOTO BootloaderStart"
 * instruction at address 0 is no longer critical, as blank memory will provide "NOP"
 * executions all the way to the Bootloader Block. Thus, the Bootloader will be able to
 * execute when there is no application code programmed.
 */
void DeviceWritePlanner::planFlashErase(QLinkedList<Device::MemoryRange>& eraseList,
                                        unsigned int* existingData)
{
    Device::MemoryRange block;

    block.start = device->startFLASH;
    block.end = device->endFLASH;
    eraseList.clear();
    eraseList.append(block);
    if(device->family == Device::PIC32 && existingData == NULL)
    {
        return;
    }

    if(writeConfig)
    {
        eraseConfigPageLast(eraseList);
    }
    else
    {
        doNotEraseConfigPage(eraseList);
    }

    doNotEraseInterruptVectorTable(eraseList);

    doNotEraseBootBlock(eraseList);

    if(existingData != NULL)
    {
        // For differential bootloading:
        // Scan existingData to see if we can avoid erasing any pages.
        // Not explicitly required, but could occassionally reduce the
        // number of erase transactions.
    }
}
void ComplexNetworkConstructor::build() {

    unsigned int num = 1;
    while (reader.hasNext()) {
        QList<int> regionsIds;
        QLinkedList<FeatureAbstractPtr> features;
        SupervisedImage img = reader.readNext();
        if (num % 10 == 0)
            printf("Reading image(%u/%d): %s%s\n", num, reader.getTotal(), img.getImagePath().size() > 60 ? "..." : "",
                   img.getImagePath().right(60).toStdString().c_str());

        for (int idx = 0; idx < img.getRegions().size(); idx++) {
            Region r = img.getRegions().at(idx);
            for (QList<const FeatureFactoryAbstract *>::iterator i = extractors.begin(); i != extractors.end(); i++) {
                features.append(move((*i)->CreateFromRegion(&r)));
                regionsIds.append(idx);
            }
        }
        //printf("Nodes: %ld , Edges: %ld\n", cn.getNumNodes(), cn.getNumEdges());
        makeCoOccurrences(features, regionsIds);
        num++;
    }
    fflush(stdout);
    cn.refreshCache();
}
/** Atualiza os pesos as arestas de acordo com a Equação:
 * \f[ w_{i,j} = w_{i,j} + \alpha\left(\frac{\lambda}{\Delta t} - w_{i,j} \right)  \f]
 */
void ComplexNetworkConstructor::makeCoOccurrences(QLinkedList<FeatureAbstractPtr> &features, QList<int> &regionsIds) {

    QLinkedList<FeaturesComplexNetwork::Node> nodes;


    //Cria nós ou pesquisa existentes
    for (auto &f: features) {
        FeaturesComplexNetwork::Node id;
        if (!index.contains(f)) {
            FeatureAbstractPtr temp = f;
            id = cn.addNode(f);
            index.insert(temp, id);
        } else {
            id = index[f];
        }
        nodes.append(id);
    }

    unsigned int i = 0, j = 0;
    for (QLinkedList<FeaturesComplexNetwork::Node>::const_iterator it1 = nodes.begin(); it1 != nodes.end(); it1++) {
        j = i + 1;
        for (QLinkedList<FeaturesComplexNetwork::Node>::const_iterator it2 = it1 + 1; it2 != nodes.end(); it2++) {
            reinforceLink(*it1, *it2, regionsIds[i] == regionsIds[j]);
            if (*it2 != *it1)
                reinforceLink(*it2, *it1, regionsIds[i] == regionsIds[j]);
            this->time++;
            j++;
        }
        i++;
    }
}
Ejemplo n.º 6
0
void Layer::addFeaturePart( FeaturePart* fpart, const QString& labelText )
{
    double bmin[2];
    double bmax[2];
    fpart->getBoundingBox( bmin, bmax );

    // add to list of layer's feature parts
    featureParts->append( fpart );

    // add to r-tree for fast spatial access
    rtree->Insert( bmin, bmax, fpart );

    // add to hashtable with equally named feature parts
    if ( mMergeLines && !labelText.isEmpty() )
    {
        QHash< QString, QLinkedList<FeaturePart*>* >::const_iterator lstPtr = connectedHashtable->find( labelText );
        QLinkedList< FeaturePart*>* lst;
        if ( lstPtr == connectedHashtable->constEnd() )
        {
            // entry doesn't exist yet
            lst = new QLinkedList<FeaturePart*>;
            connectedHashtable->insert( labelText, lst );
            connectedTexts->append( labelText );
        }
        else
        {
            lst = *lstPtr;
        }
        lst->append( fpart ); // add to the list
    }
}
Ejemplo n.º 7
0
void Layer::addFeaturePart( FeaturePart* fpart, const QString& labelText )
{
  double bmin[2];
  double bmax[2];
  fpart->getBoundingBox( bmin, bmax );

  // add to list of layer's feature parts
  mFeatureParts << fpart;

  // add to r-tree for fast spatial access
  mFeatureIndex->Insert( bmin, bmax, fpart );

  // add to hashtable with equally named feature parts
  if ( mMergeLines && !labelText.isEmpty() )
  {
    QLinkedList< FeaturePart*>* lst;
    if ( !mConnectedHashtable.contains( labelText ) )
    {
      // entry doesn't exist yet
      lst = new QLinkedList<FeaturePart*>;
      mConnectedHashtable.insert( labelText, lst );
      mConnectedTexts << labelText;
    }
    else
    {
      lst = mConnectedHashtable.value( labelText );
    }
    lst->append( fpart ); // add to the list
  }
}
Ejemplo n.º 8
0
const QLinkedList< QPair<QVariant,QString> > NfcTarget::getContentList()
{
  QLinkedList< QPair<QVariant,QString> > ll;
  for(int i=0;i<_targetContent.size();i++) {
    ll.append ( QPair<QVariant,QString> ( _targetContent.at(i)->getId(),
      _targetContent.at(i)->getType() ) );
  }
  return ll;
}
Ejemplo n.º 9
0
QLinkedList<const GEOSGeometry *>* pal::Util::unmulti( const GEOSGeometry *the_geom )
{
  QLinkedList<const GEOSGeometry*> *queue = new QLinkedList<const GEOSGeometry*>;
  QLinkedList<const GEOSGeometry*> *final_queue = new QLinkedList<const GEOSGeometry*>;

  const GEOSGeometry *geom;

  queue->append( the_geom );
  int nGeom;
  int i;

  GEOSContextHandle_t geosctxt = geosContext();

  while ( !queue->isEmpty() )
  {
    geom = queue->takeFirst();
    int type = GEOSGeomTypeId_r( geosctxt, geom );
    switch ( type )
    {
      case GEOS_MULTIPOINT:
      case GEOS_MULTILINESTRING:
      case GEOS_MULTIPOLYGON:
        nGeom = GEOSGetNumGeometries_r( geosctxt, geom );
        for ( i = 0; i < nGeom; i++ )
        {
          queue->append( GEOSGetGeometryN_r( geosctxt, geom, i ) );
        }
        break;
      case GEOS_POINT:
      case GEOS_LINESTRING:
      case GEOS_POLYGON:
        final_queue->append( geom );
        break;
      default:
        QgsDebugMsg( QString( "unexpected geometry type:%1" ).arg( type ) );
        delete final_queue;
        delete queue;
        return nullptr;
    }
  }
  delete queue;

  return final_queue;
}
Ejemplo n.º 10
0
  QLinkedList<const GEOSGeometry *> *unmulti( const GEOSGeometry *the_geom )
  {
    QLinkedList<const GEOSGeometry*> *queue = new QLinkedList<const GEOSGeometry*>;
    QLinkedList<const GEOSGeometry*> *final_queue = new QLinkedList<const GEOSGeometry*>;

    const GEOSGeometry *geom;

    queue->append( the_geom );
    int nGeom;
    int i;

    while ( !queue->isEmpty() )
    {
      geom = queue->takeFirst();
      GEOSContextHandle_t geosctxt = geosContext();
      switch ( GEOSGeomTypeId_r( geosctxt, geom ) )
      {
        case GEOS_MULTIPOINT:
        case GEOS_MULTILINESTRING:
        case GEOS_MULTIPOLYGON:
          nGeom = GEOSGetNumGeometries_r( geosctxt, geom );
          for ( i = 0; i < nGeom; i++ )
          {
            queue->append( GEOSGetGeometryN_r( geosctxt, geom, i ) );
          }
          break;
        case GEOS_POINT:
        case GEOS_LINESTRING:
        case GEOS_POLYGON:
          final_queue->append( geom );
          break;
        default:
          delete final_queue;
          delete queue;
          return NULL;
      }
    }
    delete queue;

    return final_queue;
  }
Ejemplo n.º 11
0
QLinkedList<QString> CSV_Helper::Get_CSV_Elements_From_Line_As_Linked_List(const QString &line) {
    QLinkedList<QString> elements;
    QString currentElement = QString();
    bool insideQuotes = false;
    bool lastWasComma = false;
    for (int i = 0; i < line.length(); ++i) {
        lastWasComma = false;
        if (line[i] == '\"') {
            insideQuotes = !insideQuotes;
        } else if (!insideQuotes && line[i] == ',') {
            elements.append(currentElement);
            currentElement = "";
            lastWasComma = true;
        } else {
            currentElement += line[i];
        }
    }
    if (lastWasComma || !currentElement.isEmpty()) elements.append(currentElement);

    return elements;
}
Ejemplo n.º 12
0
void fcfs::schedule_processess(QLinkedList<process> &timeline){
    int i;
    QVector<process> processes = list;
    //Arrange processes according to arrival time
    qSort(processes.begin(), processes.end(), less_than_arrival_time_based);
    for (i = 0; i < number_of_processes; i++){
        process current_process = processes.at(i);
        if (current_process.get_burst_time() != 0){
            timeline.append(current_process);
        }
    }
}
Ejemplo n.º 13
0
int main(int argc, char *argv[])
{
    QCoreApplication a(argc, argv);

    QLinkedList<QString> linkList;
    linkList.append("Bangaluru");
    linkList.append("Mumbai");
    linkList.append("Delhi");
    linkList.append("Gandhinagara");

    qDebug() << "1-Number of Items =" << linkList.count();

    QLinkedList<QString>::iterator j = qFind(linkList.begin(),linkList.end(),"Varanasi");
    linkList.insert(j,"Bhopal");

    QLinkedList<QString>::iterator i;
    for (i = linkList.begin(); i != linkList.end(); ++i)
         qDebug() << *i << endl;

    qDebug() << "2-Number of Items =" << linkList.count();

    return a.exec();
}
Ejemplo n.º 14
0
void tst_ExceptionSafety::exceptionLinkedList() {

    {
        QLinkedList<FlexibleThrowerSmall> list;
        QLinkedList<FlexibleThrowerSmall> list2;
        QLinkedList<FlexibleThrowerSmall> list3;

        for( int i = 0; i<10; i++ )
            list.append( FlexibleThrowerSmall(i) );

        try {
            throwType = ThrowAtCopy;
            list.append( FlexibleThrowerSmall(10));
        } catch (...) {
        }
        QCOMPARE( list.size(), 10 );

        try {
            throwType = ThrowAtCopy;
            list.prepend( FlexibleThrowerSmall(10));
        } catch (...) {
        }
        QCOMPARE( list.first().value(), 0 );
        QCOMPARE( list.size(), 10 );

        try {
            throwType = ThrowAtCopy;
            list3 = list;
            list3.append( FlexibleThrowerSmall(11) );
        } catch (...) {
        }
        QCOMPARE( list.first().value(), 0 );
        QCOMPARE( list.size(), 10 );
        QCOMPARE( list3.size(), 10 );
    }
    QCOMPARE(objCounter, 0 ); // check that every object has been freed
}
Ejemplo n.º 15
0
void testQLinkedList()
{
#if 1
    QLinkedList<int> li;
    QLinkedList<uint> lu;

    for (int i = 0; i != 3; ++i)
        li.append(i);
    li.append(102);


    lu.append(102);
    lu.append(102);
    lu.append(102);

    QLinkedList<Foo *> lpi;
    lpi.append(new Foo(1));
    lpi.append(0);
    lpi.append(new Foo(3));

    QLinkedList<qulonglong> l;
    l.append(42);
    l.append(43);
    l.append(44);
    l.append(45);

    QLinkedList<Foo> f;
    f.append(Foo(1));
    f.append(Foo(2));
#endif
    QLinkedList<std::string> v;
    v.push_back("aa");
    v.push_back("bb");
    v.push_back("cc");
    v.push_back("dd");
 }
Ejemplo n.º 16
0
/*!
 * Memory ranges used by the bootloader firmware are excluded from the verify list.
 *
 * If the Write Config option is disabled, the FLASH Erase Block containing config
 * words is excluded from the verify list. (only for devices that store config bits in
 * FLASH memory).
 */
void DeviceVerifyPlanner::planFlashVerify(QLinkedList<Device::MemoryRange>& verifyList, int start, int end)
{
    Device::MemoryRange block;

    block.start = start;
    block.end = end;
    verifyList.clear();
    verifyList.append(block);

    if(!writeConfig)
    {
        doNotVerifyConfigPage(verifyList);
    }

    doNotVerifyBootBlock(verifyList);
}
Ejemplo n.º 17
0
//static
QLinkedList<QFileInfo> CoverArtUtils::findPossibleCoversInFolder(const QString& folder) {
    // Search for image files in the track directory.
    QRegExp coverArtFilenames(supportedCoverArtExtensionsRegex(),
                              Qt::CaseInsensitive);
    QDirIterator it(folder,
                    QDir::Dirs | QDir::Files | QDir::NoDotAndDotDot);
    QFile currentFile;
    QFileInfo currentFileInfo;
    QLinkedList<QFileInfo> possibleCovers;
    while (it.hasNext()) {
        it.next();
        currentFileInfo = it.fileInfo();
        if (currentFileInfo.isFile() &&
            coverArtFilenames.indexIn(currentFileInfo.fileName()) != -1) {
            possibleCovers.append(currentFileInfo);
        }
    }
    return possibleCovers;
}
Ejemplo n.º 18
0
void AssignLayers::run(Graph &graph)
{
    emit setStatusMsg("Assigning layers...");

    // copy the nodes to a linked list
    QLinkedList<AbstractNode*> vertices;
    for(AbstractNode* v : graph.getNodes()) {
        vertices.append(v);
    }

    QSet<AbstractNode*> U;
    QSet<AbstractNode*> Z;
    QList<QList<AbstractNode*>> layers;

    //add the first layer
    int currentLayer = 0;
    layers.append(QList<AbstractNode*>());
    while(!vertices.isEmpty()) {
        AbstractNode* selected = nullptr;
        for(AbstractNode* v : vertices) {
            if(Z.contains(v->getPredecessors().toSet())) {
                selected = v;
                break;
            }
        }

        if(selected != nullptr) {
            selected->setLayer(currentLayer);
            layers.last().append(selected);
            U.insert(selected);
            vertices.removeOne(selected);
        } else {
            currentLayer++;
            layers.append(QList<AbstractNode*>());
            Z.unite(U);
        }
    }

    graph.setLayers(layers);
    graph.repaintLayers();
    emit setStatusMsg("Assigning layers... Done!");
}
Ejemplo n.º 19
0
void PluckerGenerator::generatePixmap( Okular::PixmapRequest * request )
{
    const QSizeF size = mPages[ request->pageNumber() ]->size();

    QPixmap *pixmap = new QPixmap( request->width(), request->height() );
    pixmap->fill( Qt::white );

    QPainter p;
    p.begin( pixmap );

    qreal width = request->width();
    qreal height = request->height();

    p.scale( width / (qreal)size.width(), height / (qreal)size.height() );
    mPages[ request->pageNumber() ]->drawContents( &p );
    p.end();

    request->page()->setPixmap( request->id(), pixmap );


    if ( !mLinkAdded.contains( request->pageNumber() ) ) {
        QLinkedList<Okular::ObjectRect*> objects;
        for ( int i = 0; i < mLinks.count(); ++i ) {
            if ( mLinks[ i ].page == request->pageNumber() ) {
                QTextDocument *document = mPages[ request->pageNumber() ];

                QRectF rect;
                calculateBoundingRect( document, mLinks[ i ].start,
                                       mLinks[ i ].end, rect );

                objects.append( new Okular::ObjectRect( rect.left(), rect.top(), rect.right(), rect.bottom(), false, Okular::ObjectRect::Action, mLinks[ i ].link ) );
            }
        }

        if ( !objects.isEmpty() )
            request->page()->setObjectRects( objects );

        mLinkAdded.insert( request->pageNumber() );
    }

    signalPixmapRequestDone( request );
}
Ejemplo n.º 20
0
void AddMetaNodeExecutor::execute_server()
{

	int count, id;
	QString name, edgeName;
	float x, y, z;

	*stream >> name;

	Data::Graph* currentGraph = Manager::GraphManager::getInstance()->getActiveGraph();
	QMap<qlonglong, osg::ref_ptr<Data::Node> >* nodes = currentGraph -> getNodes();

	*stream >> x >> y >> z;

	osg::ref_ptr<Data::Node> metaNode = currentGraph->addNode( name, currentGraph->getNodeMetaType(), osg::Vec3( x,y,z ) );

	*stream >> edgeName;
	*stream >> count;
	QLinkedList<osg::ref_ptr<Data::Node> >* selectedNodes = new QLinkedList<osg::ref_ptr<Data::Node> >();

	for ( int i = 0; i < count; i++ ) {
		*stream >> id;
		if ( nodes->contains( id ) ) {
			currentGraph->addEdge( edgeName, *nodes->find( id ), metaNode, currentGraph->getEdgeMetaType(), true );
			selectedNodes->append( *nodes->find( id ) );
		}
	}

	Server* server = Server::getInstance();
	server->sendAddMetaNode( metaNode,selectedNodes,edgeName,osg::Vec3( x,y,z ) );

	if ( ( ( QOSG::CoreWindow* )server->getCoreWindowReference() )->playing() ) {
		server->getLayoutThread()->play();
	}


}
Ejemplo n.º 21
0
std::unique_ptr<Problem> Pal::extract( const QgsRectangle &extent, const QgsGeometry &mapBoundary )
{
  // to store obstacles
  RTree<FeaturePart *, double, 2, double> *obstacles = new RTree<FeaturePart *, double, 2, double>();

  std::unique_ptr< Problem > prob = qgis::make_unique< Problem >();

  int i, j;

  double bbx[4];
  double bby[4];

  double amin[2];
  double amax[2];

  int max_p = 0;

  LabelPosition *lp = nullptr;

  bbx[0] = bbx[3] = amin[0] = prob->bbox[0] = extent.xMinimum();
  bby[0] = bby[1] = amin[1] = prob->bbox[1] = extent.yMinimum();
  bbx[1] = bbx[2] = amax[0] = prob->bbox[2] = extent.xMaximum();
  bby[2] = bby[3] = amax[1] = prob->bbox[3] = extent.yMaximum();

  prob->pal = this;

  QLinkedList<Feats *> *fFeats = new QLinkedList<Feats *>;

  FeatCallBackCtx context;

  // prepare map boundary
  geos::unique_ptr mapBoundaryGeos( QgsGeos::asGeos( mapBoundary ) );
  geos::prepared_unique_ptr mapBoundaryPrepared( GEOSPrepare_r( QgsGeos::getGEOSHandler(), mapBoundaryGeos.get() ) );

  context.fFeats = fFeats;
  context.obstacles = obstacles;
  context.candidates = prob->candidates;
  context.mapBoundary = mapBoundaryPrepared.get();

  ObstacleCallBackCtx obstacleContext;
  obstacleContext.obstacles = obstacles;
  obstacleContext.obstacleCount = 0;

  // first step : extract features from layers

  int previousFeatureCount = 0;
  int previousObstacleCount = 0;

  QStringList layersWithFeaturesInBBox;

  mMutex.lock();
  const auto constMLayers = mLayers;
  for ( Layer *layer : constMLayers )
  {
    if ( !layer )
    {
      // invalid layer name
      continue;
    }

    // only select those who are active
    if ( !layer->active() )
      continue;

    // check for connected features with the same label text and join them
    if ( layer->mergeConnectedLines() )
      layer->joinConnectedFeatures();

    layer->chopFeaturesAtRepeatDistance();

    layer->mMutex.lock();

    // find features within bounding box and generate candidates list
    context.layer = layer;
    layer->mFeatureIndex->Search( amin, amax, extractFeatCallback, static_cast< void * >( &context ) );
    // find obstacles within bounding box
    layer->mObstacleIndex->Search( amin, amax, extractObstaclesCallback, static_cast< void * >( &obstacleContext ) );

    layer->mMutex.unlock();

    if ( context.fFeats->size() - previousFeatureCount > 0 || obstacleContext.obstacleCount > previousObstacleCount )
    {
      layersWithFeaturesInBBox << layer->name();
    }
    previousFeatureCount = context.fFeats->size();
    previousObstacleCount = obstacleContext.obstacleCount;
  }
  mMutex.unlock();

  prob->nbLabelledLayers = layersWithFeaturesInBBox.size();
  prob->labelledLayersName = layersWithFeaturesInBBox;

  if ( fFeats->isEmpty() )
  {
    delete fFeats;
    delete obstacles;
    return nullptr;
  }

  prob->nbft = fFeats->size();
  prob->nblp = 0;
  prob->featNbLp = new int [prob->nbft];
  prob->featStartId = new int [prob->nbft];
  prob->inactiveCost = new double[prob->nbft];

  Feats *feat = nullptr;

  // Filtering label positions against obstacles
  amin[0] = amin[1] = std::numeric_limits<double>::lowest();
  amax[0] = amax[1] = std::numeric_limits<double>::max();
  FilterContext filterCtx;
  filterCtx.cdtsIndex = prob->candidates;
  filterCtx.pal = this;
  obstacles->Search( amin, amax, filteringCallback, static_cast< void * >( &filterCtx ) );

  if ( isCanceled() )
  {
    const auto constFFeats = *fFeats;
    for ( Feats *feat : constFFeats )
    {
      qDeleteAll( feat->lPos );
      feat->lPos.clear();
    }

    qDeleteAll( *fFeats );
    delete fFeats;
    delete obstacles;
    return nullptr;
  }

  int idlp = 0;
  for ( i = 0; i < prob->nbft; i++ ) /* foreach feature into prob */
  {
    feat = fFeats->takeFirst();

    prob->featStartId[i] = idlp;
    prob->inactiveCost[i] = std::pow( 2, 10 - 10 * feat->priority );

    switch ( feat->feature->getGeosType() )
    {
      case GEOS_POINT:
        max_p = point_p;
        break;
      case GEOS_LINESTRING:
        max_p = line_p;
        break;
      case GEOS_POLYGON:
        max_p = poly_p;
        break;
    }

    // sort candidates by cost, skip less interesting ones, calculate polygon costs (if using polygons)
    max_p = CostCalculator::finalizeCandidatesCosts( feat, max_p, obstacles, bbx, bby );

    // only keep the 'max_p' best candidates
    while ( feat->lPos.count() > max_p )
    {
      // TODO remove from index
      feat->lPos.last()->removeFromIndex( prob->candidates );
      delete feat->lPos.takeLast();
    }

    // update problem's # candidate
    prob->featNbLp[i] = feat->lPos.count();
    prob->nblp += feat->lPos.count();

    // add all candidates into a rtree (to speed up conflicts searching)
    for ( j = 0; j < feat->lPos.count(); j++, idlp++ )
    {
      lp = feat->lPos.at( j );
      //lp->insertIntoIndex(prob->candidates);
      lp->setProblemIds( i, idlp ); // bugfix #1 (maxence 10/23/2008)
    }
    fFeats->append( feat );
  }

  int nbOverlaps = 0;

  while ( !fFeats->isEmpty() ) // foreach feature
  {
    if ( isCanceled() )
    {
      const auto constFFeats = *fFeats;
      for ( Feats *feat : constFFeats )
      {
        qDeleteAll( feat->lPos );
        feat->lPos.clear();
      }

      qDeleteAll( *fFeats );
      delete fFeats;
      delete obstacles;
      return nullptr;
    }

    feat = fFeats->takeFirst();
    while ( !feat->lPos.isEmpty() ) // foreach label candidate
    {
      lp = feat->lPos.takeFirst();
      lp->resetNumOverlaps();

      // make sure that candidate's cost is less than 1
      lp->validateCost();

      prob->addCandidatePosition( lp );
      //prob->feat[idlp] = j;

      lp->getBoundingBox( amin, amax );

      // lookup for overlapping candidate
      prob->candidates->Search( amin, amax, LabelPosition::countOverlapCallback, static_cast< void * >( lp ) );

      nbOverlaps += lp->getNumOverlaps();
    }
    delete feat;
  }
  delete fFeats;

  //delete candidates;
  delete obstacles;

  nbOverlaps /= 2;
  prob->all_nblp = prob->nblp;
  prob->nbOverlap = nbOverlaps;

  return prob;
}
Ejemplo n.º 22
0
void Layer::chopFeaturesAtRepeatDistance()
{
  GEOSContextHandle_t geosctxt = geosContext();
  QLinkedList<FeaturePart*> newFeatureParts;
  while ( !mFeatureParts.isEmpty() )
  {
    FeaturePart* fpart = mFeatureParts.takeFirst();
    const GEOSGeometry* geom = fpart->geos();
    double chopInterval = fpart->repeatDistance();
    if ( chopInterval != 0. && GEOSGeomTypeId_r( geosctxt, geom ) == GEOS_LINESTRING )
    {
      chopInterval *= ceil( fpart->getLabelWidth() / fpart->repeatDistance() );

      double bmin[2], bmax[2];
      fpart->getBoundingBox( bmin, bmax );
      mFeatureIndex->Remove( bmin, bmax, fpart );

      const GEOSCoordSequence *cs = GEOSGeom_getCoordSeq_r( geosctxt, geom );

      // get number of points
      unsigned int n;
      GEOSCoordSeq_getSize_r( geosctxt, cs, &n );

      // Read points
      std::vector<Point> points( n );
      for ( unsigned int i = 0; i < n; ++i )
      {
        GEOSCoordSeq_getX_r( geosctxt, cs, i, &points[i].x );
        GEOSCoordSeq_getY_r( geosctxt, cs, i, &points[i].y );
      }

      // Cumulative length vector
      std::vector<double> len( n, 0 );
      for ( unsigned int i = 1; i < n; ++i )
      {
        double dx = points[i].x - points[i - 1].x;
        double dy = points[i].y - points[i - 1].y;
        len[i] = len[i - 1] + std::sqrt( dx * dx + dy * dy );
      }

      // Walk along line
      unsigned int cur = 0;
      double lambda = 0;
      QVector<Point> part;
      for ( ;; )
      {
        lambda += chopInterval;
        for ( ; cur < n && lambda > len[cur]; ++cur )
        {
          part.push_back( points[cur] );
        }
        if ( cur >= n )
        {
          break;
        }
        double c = ( lambda - len[cur - 1] ) / ( len[cur] - len[cur - 1] );
        Point p;
        p.x = points[cur - 1].x + c * ( points[cur].x - points[cur - 1].x );
        p.y = points[cur - 1].y + c * ( points[cur].y - points[cur - 1].y );
        part.push_back( p );
        GEOSCoordSequence* cooSeq = GEOSCoordSeq_create_r( geosctxt, part.size(), 2 );
        for ( int i = 0; i < part.size(); ++i )
        {
          GEOSCoordSeq_setX_r( geosctxt, cooSeq, i, part[i].x );
          GEOSCoordSeq_setY_r( geosctxt, cooSeq, i, part[i].y );
        }

        GEOSGeometry* newgeom = GEOSGeom_createLineString_r( geosctxt, cooSeq );
        FeaturePart* newfpart = new FeaturePart( fpart->feature(), newgeom );
        newFeatureParts.append( newfpart );
        newfpart->getBoundingBox( bmin, bmax );
        mFeatureIndex->Insert( bmin, bmax, newfpart );
        part.clear();
        part.push_back( p );
      }
      // Create final part
      part.push_back( points[n - 1] );
      GEOSCoordSequence* cooSeq = GEOSCoordSeq_create_r( geosctxt, part.size(), 2 );
      for ( int i = 0; i < part.size(); ++i )
      {
        GEOSCoordSeq_setX_r( geosctxt, cooSeq, i, part[i].x );
        GEOSCoordSeq_setY_r( geosctxt, cooSeq, i, part[i].y );
      }

      GEOSGeometry* newgeom = GEOSGeom_createLineString_r( geosctxt, cooSeq );
      FeaturePart* newfpart = new FeaturePart( fpart->feature(), newgeom );
      newFeatureParts.append( newfpart );
      newfpart->getBoundingBox( bmin, bmax );
      mFeatureIndex->Insert( bmin, bmax, newfpart );
      delete fpart;
    }
    else
    {
      newFeatureParts.append( fpart );
    }
  }

  mFeatureParts = newFeatureParts;
}
Ejemplo n.º 23
0
TEST_F(CoverArtUtilTest, searchImage) {
    // creating a temp track directory
    QString trackdir(QDir::tempPath() % "/TrackDir");
    ASSERT_FALSE(QDir().exists(trackdir)); // it must start empty
    ASSERT_TRUE(QDir().mkpath(trackdir));

    TrackPointer pTrack(Track::newTemporary(kTrackLocationTest));
    SoundSourceProxy(pTrack).loadTrackMetadata();
    QLinkedList<QFileInfo> covers;
    CoverArt res;
    // looking for cover in an empty directory
    res = CoverArtUtils::selectCoverArtForTrack(pTrack.data(), covers);
    CoverArt expected;
    expected.info.source = CoverInfo::GUESSED;
    EXPECT_EQ(expected, res);

    // Looking for a track with embedded cover.
    pTrack = TrackPointer(Track::newTemporary(kTrackLocationTest));
    SoundSourceProxy(pTrack).loadTrackMetadataAndCoverArt();
    expected = CoverArt();
    expected.image = pTrack->getCoverArt().image;
    expected.info.type = CoverInfo::METADATA;
    expected.info.source = CoverInfo::GUESSED;
    expected.info.coverLocation = QString();
    expected.info.hash = CoverArtUtils::calculateHash(expected.image);
    EXPECT_EQ(expected, pTrack->getCoverArt());

    const char* format("jpg");
    const QString qFormat(format);

    // Since we already parsed this image from the matadata in
    // kTrackLocationTest, hang on to it since we use it as a template for
    // stuff below.
    const QImage img = expected.image;


    QString trackBaseName = "cover-test";
    QString trackAlbum = "album_name";

    // Search Strategy
    // 0. If we have just one file, we will get it.
    // 1. %track-file-base%.jpg in the track directory for %track-file-base%.mp3
    // 2. %album%.jpg
    // 3. cover.jpg
    // 4. front.jpg
    // 5. album.jpg
    // 6. folder.jpg
    // 7. if just one file exists take that otherwise none.

    // All the following expect the same image/hash to be selected.
    expected.image = img;
    expected.info.hash = CoverArtUtils::calculateHash(expected.image);

    // All the following expect FILE and GUESSED.
    expected.info.type = CoverInfo::FILE;
    expected.info.source = CoverInfo::GUESSED;

    // 0. saving just one cover in our temp track dir
    QString cLoc_foo = QString(trackdir % "/" % "foo." % qFormat);
    EXPECT_TRUE(img.save(cLoc_foo, format));

    // looking for cover in an directory with one image will select that one.
    expected.image = QImage(cLoc_foo);
    expected.info.coverLocation = "foo.jpg";
    expected.info.hash = CoverArtUtils::calculateHash(expected.image);
    covers << QFileInfo(cLoc_foo);
    res = CoverArtUtils::selectCoverArtForTrack(trackBaseName, trackAlbum,
                                                covers);
    EXPECT_EQ(expected, res);
    QFile::remove(cLoc_foo);

    QStringList extraCovers;
    // adding some extra images (bigger) just to populate the track dir.
    QString cLoc_big1 = QString(trackdir % "/" % "big1." % qFormat);
    EXPECT_TRUE(img.scaled(1000,1000).save(cLoc_big1, format));
    extraCovers << cLoc_big1;
    QString cLoc_big2 = QString(trackdir % "/" % "big2." % qFormat);
    EXPECT_TRUE(img.scaled(900,900).save(cLoc_big2, format));
    extraCovers << cLoc_big2;
    QString cLoc_big3 = QString(trackdir % "/" % "big3." % qFormat);
    EXPECT_TRUE(img.scaled(800,800).save(cLoc_big3, format));
    extraCovers << cLoc_big3;

    // saving more covers using the preferred names in the right order
    QLinkedList<QFileInfo> prefCovers;
    // 1. track_filename.jpg
    QString cLoc_filename = QString(trackdir % "/cover-test." % qFormat);
    EXPECT_TRUE(img.scaled(500,500).save(cLoc_filename, format));
    prefCovers << QFileInfo(cLoc_filename);
    // 2. album_name.jpg
    QString cLoc_albumName = QString(trackdir % "/album_name." % qFormat);
    EXPECT_TRUE(img.scaled(500,500).save(cLoc_albumName, format));
    prefCovers << QFileInfo(cLoc_albumName);
    // 3. cover.jpg
    QString cLoc_cover = QString(trackdir % "/" % "cover." % qFormat);
    EXPECT_TRUE(img.scaled(400,400).save(cLoc_cover, format));
    prefCovers << QFileInfo(cLoc_cover);
    // 4. front.jpg
    QString cLoc_front = QString(trackdir % "/" % "front." % qFormat);
    EXPECT_TRUE(img.scaled(300,300).save(cLoc_front, format));
    prefCovers << QFileInfo(cLoc_front);
    // 5. album.jpg
    QString cLoc_album = QString(trackdir % "/" % "album." % qFormat);
    EXPECT_TRUE(img.scaled(100,100).save(cLoc_album, format));
    prefCovers << QFileInfo(cLoc_album);
    // 6. folder.jpg
    QString cLoc_folder = QString(trackdir % "/" % "folder." % qFormat);
    EXPECT_TRUE(img.scaled(100,100).save(cLoc_folder, format));
    prefCovers << QFileInfo(cLoc_folder);
    // 8. other1.jpg
    QString cLoc_other1 = QString(trackdir % "/" % "other1." % qFormat);
    EXPECT_TRUE(img.scaled(10,10).save(cLoc_other1, format));
    prefCovers << QFileInfo(cLoc_other1);
    // 7. other2.jpg
    QString cLoc_other2 = QString(trackdir % "/" % "other2." % qFormat);
    EXPECT_TRUE(img.scaled(10,10).save(cLoc_other2, format));
    prefCovers << QFileInfo(cLoc_other2);

    // we must find covers in the right order
    EXPECT_EQ(8, prefCovers.size());

    // Remove the covers one by one from the front, checking that each one is
    // selected as we remove the previously-most-preferable cover.
    while (!prefCovers.isEmpty()) {
        QFileInfo cover = prefCovers.first();

        // We expect no cover selected for other1 since there are 2 covers,
        // neither of which match our preferred cover names. other2 will be
        // selected once we get to it since it is the only cover available.
        if (cover.baseName() == "other1") {
            expected.image = QImage();
            expected.info.type = CoverInfo::NONE;
            expected.info.coverLocation = QString();
            expected.info.hash = 0;
        } else {
            expected.image = QImage(cover.filePath());
            expected.info.type = CoverInfo::FILE;
            expected.info.coverLocation = cover.fileName();
            expected.info.hash = CoverArtUtils::calculateHash(expected.image);
        }
        res = CoverArtUtils::selectCoverArtForTrack(trackBaseName, trackAlbum,
                                                    prefCovers);
        EXPECT_QSTRING_EQ(expected.info.coverLocation, res.info.coverLocation);
        EXPECT_QSTRING_EQ(expected.info.hash, res.info.hash);
        EXPECT_EQ(expected, res);

        QFile::remove(cover.filePath());
        prefCovers.pop_front();
    }

    //
    // Additional tests
    //

    // what is chosen when cover.jpg and cover.JPG exists?
    // (it must always prefer the lighter cover)
    QString cLoc_coverJPG = trackdir % "/" % "cover." % "JPG";
    EXPECT_TRUE(img.scaled(200,200).save(cLoc_coverJPG, "JPG"));
    prefCovers.append(QFileInfo(cLoc_coverJPG));
    QString cLoc_coverjpg = trackdir % "/" % "cover." % "jpg";
    EXPECT_TRUE(img.scaled(400,400).save(cLoc_coverjpg, "jpg"));
    prefCovers.append(QFileInfo(cLoc_coverjpg));
    extraCovers << cLoc_coverJPG << cLoc_coverjpg;

    res = CoverArtUtils::selectCoverArtForTrack(trackBaseName, trackAlbum,
                                                prefCovers);
    expected.image = QImage(cLoc_coverJPG);
    expected.info.hash = CoverArtUtils::calculateHash(expected.image);
    expected.info.coverLocation = "cover.JPG";
    EXPECT_EQ(expected, res);

    // As we are looking for %album%.jpg and %base_track.jpg%,
    // we need to check if everything works with UTF8 chars.
    trackBaseName = QString::fromUtf8("track_ðÑöæäî");
    trackAlbum = QString::fromUtf8("öæäîðÑ_album");

    prefCovers.clear();

    // 2. album_name.jpg
    cLoc_albumName = QString(trackdir % "/" % trackAlbum % "." % qFormat);
    EXPECT_TRUE(img.save(cLoc_albumName, format));
    prefCovers.append(QFileInfo(cLoc_albumName));
    res = CoverArtUtils::selectCoverArtForTrack(trackBaseName, trackAlbum,
                                                prefCovers);
    expected.image = QImage(cLoc_albumName);
    expected.info.hash = CoverArtUtils::calculateHash(expected.image);
    expected.info.coverLocation = trackAlbum % ".jpg";
    EXPECT_EQ(expected, res);

    // 1. track_filename.jpg
    cLoc_filename = QString(trackdir % "/" % trackBaseName % "." % qFormat);
    EXPECT_TRUE(img.save(cLoc_filename, format));
    prefCovers.append(QFileInfo(cLoc_filename));
    res = CoverArtUtils::selectCoverArtForTrack(trackBaseName, trackAlbum,
                                                prefCovers);
    expected.image = QImage(cLoc_filename);
    expected.info.hash = CoverArtUtils::calculateHash(expected.image);
    expected.info.coverLocation = trackBaseName % ".jpg";
    EXPECT_EQ(expected, res);

    QFile::remove(cLoc_filename);
    QFile::remove(cLoc_albumName);

    // cleaning temp dir
    foreach (QString loc, extraCovers) {
        QFile::remove(loc);
    }
Ejemplo n.º 24
0
bool KNMusicPlaylistiTunesXMLParser::write(KNMusicPlaylistModel *playlist,
                                           const QString &filePath)
{
    //Generate the plist document.
    QDomDocument plistDocument;
    //Initial the plist element.
    QDomElement plistRoot=plistDocument.createElement("plist");
    plistRoot.setAttribute("version", "1.0");
    plistDocument.appendChild(plistRoot);

    //Initial the dict element.
    QDomElement dictElement=plistDocument.createElement("dict");
    plistRoot.appendChild(dictElement);
    appendDictValue(plistDocument, dictElement, "Major Version", 1);
    appendDictValue(plistDocument, dictElement, "Minor Version", 1);
    appendDictValue(plistDocument, dictElement, "Date",
                    QDateTime::currentDateTime());
    appendDictValue(plistDocument, dictElement, "Features", 5);
    appendDictValue(plistDocument, dictElement, "Show Content Ratings", true);

    //Generate database and song index list.
    QHash<QString, int> filePathIndex;
    QLinkedList<int> playlistIndexList;
    //Add paths to hash keys.
    for(int i=0; i<playlist->rowCount(); i++)
    {
        //Get current path.
        QString currentPath=playlist->rowProperty(i, FilePathRole).toString();
        //Check the path in the index hash.
        int currentIndex=filePathIndex.value(currentPath, -1);
        //If we never insert this path to the index,
        if(currentIndex==-1)
        {
            //Get the new index.
            currentIndex=i;
            //Insert the path to the hash.
            filePathIndex.insert(currentPath, currentIndex);
        }
        //Append the list.
        playlistIndexList.append(currentIndex);
    }

    //Output the database info to dict.
    //Initial the elements.
    QDomElement tracksKey=plistDocument.createElement("key"),
                tracksDict=plistDocument.createElement("dict");
    QDomText tracksKeyValue=plistDocument.createTextNode("Tracks");
    tracksKey.appendChild(tracksKeyValue);
    //Add to dict elements.
    dictElement.appendChild(tracksKey);
    dictElement.appendChild(tracksDict);
    //Write database info.
    QList<int> songIndexList=filePathIndex.values();
    while(!songIndexList.isEmpty())
    {
        int currentRow=songIndexList.takeFirst(),
                trackID=currentRow+100;
        //Generate current row key and dict.
        QDomElement trackKey=plistDocument.createElement("key"),
                    trackDict=plistDocument.createElement("dict");
        //Generate the track key value.
        QDomText trackKeyValue=
                plistDocument.createTextNode(QString::number(trackID));
        trackKey.appendChild(trackKeyValue);
        //Get the detail info.
        const KNMusicDetailInfo detailInfo=playlist->rowDetailInfo(currentRow);
        //Generate the dict.
        appendDictValue(plistDocument, trackDict, "Track ID",
                        trackID);
        appendDictValue(plistDocument, trackDict, "Name",
                        detailInfo.textLists[Name]);
        appendDictValue(plistDocument, trackDict, "Artist",
                        detailInfo.textLists[Artist]);
        appendDictValue(plistDocument, trackDict, "Album Artist",
                        detailInfo.textLists[AlbumArtist]);
        appendDictValue(plistDocument, trackDict, "Genre",
                        detailInfo.textLists[Genre]);
        appendDictValue(plistDocument, trackDict, "Kind",
                        detailInfo.textLists[Kind]);
        appendDictValue(plistDocument, trackDict, "Size",
                        detailInfo.size);
        appendDictValue(plistDocument, trackDict, "Total Time",
                        detailInfo.duration);
        appendDictValue(plistDocument, trackDict, "Track Number",
                        detailInfo.textLists[TrackNumber].toString().toInt());
        appendDictValue(plistDocument, trackDict, "Track Count",
                        detailInfo.textLists[TrackCount].toString().toInt());
        appendDictValue(plistDocument, trackDict, "Year",
                        detailInfo.textLists[Year].toString().toInt());
        appendDictValue(plistDocument, trackDict, "Date Modified",
                        detailInfo.dateModified);
        appendDictValue(plistDocument, trackDict, "Date Added",
                        detailInfo.dateAdded);
        appendDictValue(plistDocument, trackDict, "Bit Rate",
                        detailInfo.bitRate);
        appendDictValue(plistDocument, trackDict, "Sample Rate",
                        detailInfo.samplingRate);
        appendDictValue(plistDocument, trackDict, "Track Type", "File");
        QString fileLocate=QUrl::fromLocalFile(detailInfo.filePath).toString();
#ifdef Q_OS_WIN
        fileLocate.insert(7, "localhost");
#endif
        appendDictValue(plistDocument, trackDict, "Location",
                        QString(QUrl::toPercentEncoding(fileLocate, "/:")));
        appendDictValue(plistDocument, trackDict, "File Folder Count", -1);
        appendDictValue(plistDocument, trackDict, "Library Folder Count", -1);
        //Add the key and dict to track.
        tracksDict.appendChild(trackKey);
        tracksDict.appendChild(trackDict);
    }

    //Output the playlist info to dict.
    QDomElement playlistKey=plistDocument.createElement("key"),
            playlistArray=plistDocument.createElement("array");
    QDomText playlistKeyValue=plistDocument.createTextNode("Playlists");
    playlistKey.appendChild(playlistKeyValue);
    //Add the key and array to dict element.
    dictElement.appendChild(playlistKey);
    dictElement.appendChild(playlistArray);
    //Generate current playlist information.
    QDomElement playlistDict=plistDocument.createElement("dict");
    playlistArray.appendChild(playlistDict);
    //Set playlist information to the dict.
    appendDictValue(plistDocument, playlistDict, "Name", playlist->title());
    appendDictValue(plistDocument, playlistDict, "Playlist ID", "99");
    appendDictValue(plistDocument, playlistDict, "All Items", true);
    //Generate playlist items array.
    QDomElement playlistItemsKey=plistDocument.createElement("key"),
                playlistItemsArray=plistDocument.createElement("array");
    QDomText playlistItemsKeyValue=
                plistDocument.createTextNode("Playlist Items");
    playlistItemsKey.appendChild(playlistItemsKeyValue);
    //Add to current playlist dict.
    playlistDict.appendChild(playlistItemsKey);
    playlistDict.appendChild(playlistItemsArray);
    //Generate Track ID dicts.
    while(!playlistIndexList.isEmpty())
    {
        QDomElement currentTrackDict=plistDocument.createElement("dict");
        appendDictValue(plistDocument,
                        currentTrackDict,
                        "Track ID",
                        100+playlistIndexList.takeFirst());
        //Add the dict to the array.
        playlistItemsArray.appendChild(currentTrackDict);
    }
    return writeContent(filePath,
                        "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<!DOCTYPE "
                        "plist PUBLIC \"-//Apple Computer//DTD PLIST 1.0//EN\""
                        " \"http://www.apple.com/DTDs/PropertyList-1.0.dtd\">\n"
                        + plistDocument.toString(4));
}
Ejemplo n.º 25
0
void MainWindow::on_actionShortcuts_triggered() {

	QTableWidget* scTable = new QTableWidget();

	scTable->setRowCount(0);
	scTable->setColumnCount(2);

	scTable->setHorizontalHeaderItem(0, new QTableWidgetItem("Shortcut"));
	scTable->setHorizontalHeaderItem(1, new QTableWidgetItem("Description"));
	scTable->verticalHeader()->hide();


	QLinkedList<QPair<QString, QString>> scList;

	//read from file in resources and add to linked list
	QFile shortcutFile(":Shortcuts/resources/shortcuts.txt");

	if (!shortcutFile.open(QIODevice::ReadOnly | QIODevice::Text))
		return;

	QString line;
	while (!shortcutFile.atEnd()) {
		QTextStream stream(&shortcutFile);
		while (!stream.atEnd()) {
			line = stream.readLine();
			QStringList shortCutAndDescription = line.split(':');
			if (shortCutAndDescription.size() == 2) {
				scList.append(QPair<QString, QString>(shortCutAndDescription[0], shortCutAndDescription[1]));
			}
		}

	}

	QLinkedList<QPair<QString, QString>>::const_iterator sc;
	for (sc = scList.constBegin(); sc != scList.constEnd(); ++sc) {
		scTable->insertRow(scTable->rowCount());


		QTableWidgetItem* scKey = new QTableWidgetItem(sc->first);
		QTableWidgetItem* scKeyInfo = new QTableWidgetItem(sc->second);
		scKey->setFlags(Qt::NoItemFlags | Qt::ItemIsEnabled | Qt::ItemIsSelectable);
		scKeyInfo->setFlags(Qt::NoItemFlags | Qt::ItemIsEnabled | Qt::ItemIsSelectable);

		scTable->setItem(scTable->rowCount() - 1, 0, scKey);
		scTable->setItem(scTable->rowCount() - 1, 1, scKeyInfo);
	}


	//scTable->horizontalHeader()->setStretchLastSection( true ); 
	scTable->horizontalHeader()->setSectionResizeMode(QHeaderView::Stretch);

	QWidget* outerWidget = new QWidget();
	outerWidget->setWindowTitle("Shortcuts");
	outerWidget->resize(scTable->size());
	QVBoxLayout* vLayout = new QVBoxLayout();

	vLayout->addWidget(scTable);

	outerWidget->setLayout(vLayout);


	outerWidget->show();
}
Ejemplo n.º 26
0
/*!
 * \internal this function locks the lockregistry and checks if there is a collision between the process locks
 * \internal if there is no collision it inserts the lock into the registry and returns
 * \internal return true for success
 */
bool QxtFileLockRegistry::registerLock(QxtFileLock * lock)
{
    QMutexLocker locker(&this->registryMutex);

    QFile *fileToLock = lock ->file();

    if (fileToLock)
    {
        struct stat fileInfo;
        if (fstat(fileToLock->handle(), &fileInfo) < 0)
            return false;

        int newLockStart = lock ->offset();
        int newLockEnd = lock ->offset() + lock ->length();

        QMutableLinkedListIterator< QPointer<QxtFileLock> >iterator(this->procLocks);

        while (iterator.hasNext())
        {
            QPointer<QxtFileLock> currLock = iterator.next();
            if (currLock && currLock->file() && currLock->file()->isOpen())
            {
                struct stat currFileInfo;

                /*first check if the current lock is on the same file*/
                if (fstat(currLock->file()->handle(), &currFileInfo) < 0)
                {
                    /*that should never happen because a closing file should remove all locks*/
                    Q_ASSERT(false);
                    continue;
                }

                if (currFileInfo.st_dev == fileInfo.st_dev && currFileInfo.st_ino == fileInfo.st_ino)
                {
                    /*same file, check if our locks are in conflict*/
                    int currLockStart = currLock->offset();
                    int currLockEnd = currLock->offset() + currLock->length();

                    /*do we have to check for threads here?*/
                    if (newLockEnd >= currLockStart  && newLockStart <= currLockEnd)
                    {
                        //qDebug() << "we may have a collision";
                        //qDebug() << newLockEnd << " >= " << currLockStart << "  &&  " << newLockStart << " <= " << currLockEnd;

                        /*same lock region if one of both locks are exclusive we have a collision*/
                        if (lock ->mode() == QxtFileLock::WriteLockWait || lock ->mode() == QxtFileLock::WriteLock ||
                                currLock->mode() == QxtFileLock::WriteLockWait || currLock->mode() == QxtFileLock::WriteLock)
                        {
                            /*FIXED BUG #6 test rw_same() passes on Unix
                              keeping the old code for a while
                              */
                            return false;
#if 0
                           //qDebug() << "Okay if this is not the same thread using the same handle there is a collision";
                            /*the same thread  can lock the same region with the same handle*/

                            //qDebug() << "! (" << lock ->thread() << " == " << currLock->thread() << " && " << lock ->file()->handle() << " == " << currLock->file()->handle() << ")";

                            if (!(lock ->thread() == currLock->thread() && lock ->file()->handle() == currLock->file()->handle()))
                            {
                                qDebug() << "Collision";
                                return false;
                            }
#endif
                        }
                    }
                }
            }
            else //remove dead locks
                iterator.remove();
        }
        //qDebug() << "The lock is okay";
        /*here we can insert the lock into the list and return*/
        procLocks.append(QPointer<QxtFileLock>(lock));
        return true;

    }

    return false;
}
Ejemplo n.º 27
0
void LCSprinter::printLCS(uint index)
{
    //fprintf(stderr,"%2d. %2d. %2d. %2d\n",(uint)(*b)[index],nT,index%nT, index);
    if (index % nT == 0 || index < nT)
    {
    // original LCS algo does not have to deal with ins before first common
        uint bound = index%nT;
        for (index=0; index<bound; ++index)
        {
            resultString.append(addMarkerStart);
            resultString.append(*it2);
            ++it2;
            if (haveSpaces)
            {
                resultString.append(*it2Space);
                ++it2Space;
            }
            resultString.append(addMarkerEnd);
        }

        return;
    }

    if (ARROW_UP_LEFT == b->at(index))
    {
        printLCS(index-nT-1);
        if (it1!=s1.constEnd())
        {
            //kWarning() << "upleft '" << *it1 <<"'";
            //kWarning() << "upleft 1s" << *it1Space;
            //kWarning() << "upleft 2s" << *it2Space;
            if (haveSpaces)
            {
                if((*it1)==(*it2))//case and accels
                    resultString.append(*it1);
                else
                {
                    QStringList word1=prepareForInternalDiff(*it1);
                    QStringList word2=prepareForInternalDiff(*it2);

                    QStringList empty;
                    resultString.append(calcLCS(word1,word2,empty,empty).join(QString()));
                }

                if((*it1Space)==(*it2Space))
                    resultString.append(*it1Space);
                else
                {
                    QStringList word1=prepareForInternalDiff(*it1Space);
                    QStringList word2=prepareForInternalDiff(*it2Space);

                    QStringList empty;
                    //empty=calcLCS(word1,word2,empty,empty);
//???this is not really good if we use diff result in autosubst

                    empty=calcLCS(word2,word1,empty,empty);
                    empty.replaceInStrings("KBABELADD>","KBABELTMP>");
                    empty.replaceInStrings("KBABELDEL>","KBABELADD>");
                    empty.replaceInStrings("KBABELTMP>","KBABELDEL>");

                    resultString.append(empty.join(QString()));
                }
                ++it1Space;
                ++it2Space;
                //kWarning() << " common " << *it1;
            }
            else
                resultString.append(*it1);//we may guess that this is a batch job, i.e. TM search
            ++it1;
            ++it2;
        }
    }
    else if (ARROW_UP == b->at(index))
    {
        printLCS(index-nT);
//         if (it1!=s1.end())
        {
            //kWarning()<<"APPENDDEL "<<*it1;
            //kWarning()<<"APPENDDEL "<<*it1Space;
            resultString.append(delMarkerStart);
            resultString.append(*it1);
            ++it1;
            if (haveSpaces)
            {
                resultString.append(*it1Space);
                ++it1Space;
            }
            resultString.append(delMarkerEnd);
        }
    }
    else
    {
        printLCS(index-1);
        resultString.append(addMarkerStart);
        resultString.append(*it2);
        ++it2;
        if (haveSpaces)
        {
            //kWarning() << "add2 " << *it2;
            resultString.append(*it2Space);
            ++it2Space;
        }
        resultString.append(addMarkerEnd);
    }
}
Ejemplo n.º 28
0
/*!
 * @desc collects groups of concurrent items in the offset range
 */
QList< QLinkedList<QxtScheduleInternalItem *> > QxtScheduleViewPrivate::findConcurrentItems(const int from, const int to) const
{
    QList< QLinkedList<QxtScheduleInternalItem *> > allConcurrentItems;

    QList<QxtScheduleInternalItem *> allItemsSorted = m_Items;
    
    if(m_Items.size() == 0)
        return allConcurrentItems;
    
    qSort(allItemsSorted.begin(), allItemsSorted.end(), qxtScheduleItemLessThan);

    int startItem = 0;
    int endItem = allItemsSorted.size() - 1;

    //find the startitem that interferes with our range
    for (int i = 0; i < allItemsSorted.size(); i++)
    {
        if (i > 0)
        {
            if (!(allItemsSorted.at(i - 1)->visualEndTableOffset() >=  allItemsSorted.at(i)->visualStartTableOffset()
                    && allItemsSorted.at(i - 1)->visualStartTableOffset() <=  allItemsSorted.at(i)->visualEndTableOffset()))
                startItem = i;
        }

        if (allItemsSorted.at(i)->visualEndTableOffset() >= from && allItemsSorted.at(i)->visualStartTableOffset() <= to)
            break;
    }

    //find the last item that interferes with our range
    for (int i = allItemsSorted.size() - 1; i >= 0 ; i--)
    {
        if (i < allItemsSorted.size() - 1)
        {
            if (!(allItemsSorted.at(i + 1)->visualEndTableOffset() >=  allItemsSorted.at(i)->visualStartTableOffset()
                    && allItemsSorted.at(i + 1)->visualStartTableOffset() <=  allItemsSorted.at(i)->visualEndTableOffset()))
                endItem = i;
        }

        if (allItemsSorted.at(i)->visualEndTableOffset() >= from && allItemsSorted.at(i)->visualStartTableOffset() <= to)
            break;
    }

    int startOffset = allItemsSorted.at(startItem)->visualStartTableOffset();
    int endOffset = allItemsSorted.at(endItem)->visualEndTableOffset();

    /*now we have to populate a list with all items that interfere with our range */
    QLinkedList<QxtScheduleInternalItem *> concurrentItems;
    for (int iAllItemLoop = startItem; iAllItemLoop <= endItem; iAllItemLoop++)
    {
        int tempStartOffset = allItemsSorted.at(iAllItemLoop)->visualStartTableOffset();
        int tempEndOffset = allItemsSorted.at(iAllItemLoop)->visualEndTableOffset();

        if (tempEndOffset >= startOffset && tempStartOffset <= endOffset)
        {

            if (concurrentItems.size() >= 1)
            {
                bool bAppend = false;
                /*check all items in the list if the current items interfers although the items are ordered by startIndex
                *we can loose some of them if the endTime of the last Item is before the endTime of the pre last item
                */

                for (QLinkedList<QxtScheduleInternalItem *>::iterator it = concurrentItems.begin(); it != concurrentItems.end(); ++it)
                {
                    int lastStartOffset = (*it)->visualStartTableOffset();
                    int lastEndOffset   = (*it)->visualEndTableOffset();

                    if (tempEndOffset >= lastStartOffset && tempStartOffset <= lastEndOffset)
                    {
                        bAppend = true;
                        break;
                    }
                }

                if (bAppend)
                {
                    concurrentItems.append(allItemsSorted.at(iAllItemLoop));
                }
                else
                {
                    allConcurrentItems.append(concurrentItems);
                    concurrentItems.clear();
                    concurrentItems.append(allItemsSorted.at(iAllItemLoop));
                }
            }
            else
                concurrentItems.append(allItemsSorted.at(iAllItemLoop));

            if (tempStartOffset < startOffset)
                startOffset = tempStartOffset;

            if (tempEndOffset > endOffset)
                endOffset = tempEndOffset;
        }
    }
    if (concurrentItems.size() > 0)
        allConcurrentItems.append(concurrentItems);

    return allConcurrentItems;
}
Ejemplo n.º 29
0
/**
 * Produces FLASH erase and write plans for optimally programming application code into
 * a device.
 *
 * This routine assumes that pages filled with blank or "NOP" instructions (0xFFFF) do
 * not need to be erased nor written. For most applications, this will be sufficient,
 * providing extremely fast programming.
 *
 * To guarantee clean memory, perform a Verify After Write CRC check on each Erase
 * Block. This will find any leftover junk data from older firmware that can be erased.
 */
void DeviceWritePlanner::planFlashWrite(QLinkedList<Device::MemoryRange>& eraseList,
                                        QLinkedList<Device::MemoryRange>& writeList,
                                        unsigned int start, unsigned int end,
                                        unsigned int* data, unsigned int* existingData)
{
    unsigned int address = start;
    Device::MemoryRange block;

    while(address < end)
    {
        address = skipEmptyFlashPages(address, data);
        block.start = address;
        if(address >= end)
        {
            break;
        }

        address = findEndFlashWrite(address, data);
        if(address >= end)
        {
            address = end;
        }
        block.end = address;

        if(device->family == Device::PIC16 && !device->hasEraseFlashCommand())
        {
            // Certain PIC16 devices (such as PIC16F882) have a peculiar automatic erase
            // during write feature. To make that work, writes must be expanded to align
            // with Erase Block boundaries.
            block.start -= (block.start % device->eraseBlockSizeFLASH);
            if(block.end % device->eraseBlockSizeFLASH)
            {
                block.end += device->eraseBlockSizeFLASH - (block.end % device->eraseBlockSizeFLASH);
                address = block.end;
            }
        }
        writeList.append(block);

        address++;
    }

    if(existingData == NULL && device->family == Device::PIC32)
    {
        // Because PIC32 has Bulk Erase available for bootloader use,
        // it's faster to simply erase the entire FLASH memory space
        // than erasing specific erase blocks using an erase plan.
        block.start = device->startFLASH;
        block.end = device->endFLASH;
        eraseList.append(block);
    }
    else
    {
        if(existingData != NULL)
        {
            QLinkedList<Device::MemoryRange>::iterator it;
            for(it = writeList.begin(); it != writeList.end(); ++it)
            {
                qDebug("unpruned write(%X to %X)", it->start, it->end);
            }
            doNotWriteExistingData(writeList, start, end, data, existingData);
            for(it = writeList.begin(); it != writeList.end(); ++it)
            {
                qDebug("pruned write(%X to %X)", it->start, it->end);
            }
        }

        if(!writeList.isEmpty())
        {
            if(device->hasEraseFlashCommand())
            {
                flashEraseList(eraseList, writeList, data, existingData);
            }

            EraseAppCheckFirst(eraseList);
            WriteAppCheckLast(writeList);

            if(writeConfig)
            {
                eraseConfigPageLast(eraseList);
                writeConfigPageFirst(writeList);
                doNotEraseBootBlock(eraseList);     // needed in case boot block resides on config page
            }
            else
            {
                doNotEraseConfigPage(eraseList);
            }

            doNotEraseInterruptVectorTable(eraseList);
        }
    }

    packetSizeWriteList(writeList);
}
Ejemplo n.º 30
0
void PointSet::splitPolygons( QLinkedList<PointSet *> &shapes_toProcess,
                              QLinkedList<PointSet *> &shapes_final,
                              double xrm, double yrm )
{
  int i, j;

  int nbp;
  double *x = nullptr;
  double *y = nullptr;

  int *pts = nullptr;

  int *cHull = nullptr;
  int cHullSize;

  double cp;
  double bestcp = 0;

  double bestArea = 0;
  double area;

  double base;
  double b, c;
  double s;

  int ihs;
  int ihn;

  int ips;
  int ipn;

  int holeS = -1;  // hole start and end points
  int holeE = -1;

  int retainedPt = -1;
  int pt = 0;

  double labelArea = xrm * yrm;

  PointSet *shape = nullptr;

  while ( !shapes_toProcess.isEmpty() )
  {
    shape = shapes_toProcess.takeFirst();

    x = shape->x;
    y = shape->y;
    nbp = shape->nbPoints;
    pts = new int[nbp];

    for ( i = 0; i < nbp; i++ )
    {
      pts[i] = i;
    }

    // conpute convex hull
    shape->cHullSize = GeomFunction::convexHullId( pts, x, y, nbp, shape->cHull );

    cHull = shape->cHull;
    cHullSize = shape->cHullSize;

    bestArea = 0;
    retainedPt = -1;

    // lookup for a hole
    for ( ihs = 0; ihs < cHullSize; ihs++ )
    {
      // ihs->ihn => cHull'seg
      ihn = ( ihs + 1 ) % cHullSize;

      ips = cHull[ihs];
      ipn = ( ips + 1 ) % nbp;
      if ( ipn != cHull[ihn] ) // next point on shape is not the next point on cHull => there is a hole here !
      {
        bestcp = 0;
        pt = -1;
        // lookup for the deepest point in the hole
        for ( i = ips; i != cHull[ihn]; i = ( i + 1 ) % nbp )
        {
          cp = std::fabs( GeomFunction::cross_product( x[cHull[ihs]], y[cHull[ihs]],
                          x[cHull[ihn]], y[cHull[ihn]],
                          x[i], y[i] ) );
          if ( cp - bestcp > EPSILON )
          {
            bestcp = cp;
            pt = i;
          }
        }

        if ( pt  != -1 )
        {
          // compute the ihs->ihn->pt triangle's area
          base = GeomFunction::dist_euc2d( x[cHull[ihs]], y[cHull[ihs]],
                                           x[cHull[ihn]], y[cHull[ihn]] );

          b = GeomFunction::dist_euc2d( x[cHull[ihs]], y[cHull[ihs]],
                                        x[pt], y[pt] );

          c = GeomFunction::dist_euc2d( x[cHull[ihn]], y[cHull[ihn]],
                                        x[pt], y[pt] );

          s = ( base + b + c ) / 2; // s = half perimeter
          area = s * ( s - base ) * ( s - b ) * ( s - c );
          if ( area < 0 )
            area = -area;

          // retain the biggest area
          if ( area - bestArea > EPSILON )
          {
            bestArea = area;
            retainedPt = pt;
            holeS = ihs;
            holeE = ihn;
          }
        }
      }
    }

    // we have a hole, its area, and the deppest point in hole
    // we're going to find the second point to cup the shape
    // holeS = hole starting point
    // holeE = hole ending point
    // retainedPt = deppest point in hole
    // bestArea = area of triangle HoleS->holeE->retainedPoint
    bestArea = std::sqrt( bestArea );
    double cx, cy, dx, dy, ex, ey, fx, fy, seg_length, ptx = 0, pty = 0, fptx = 0, fpty = 0;
    int ps = -1, pe = -1, fps = -1, fpe = -1;
    if ( retainedPt >= 0 && bestArea > labelArea ) // there is a hole so we'll cut the shape in two new shape (only if hole area is bigger than twice labelArea)
    {
      c = std::numeric_limits<double>::max();

      // iterate on all shape points except points which are in the hole
      bool isValid;
      int k, l;
      for ( i = ( cHull[holeE] + 1 ) % nbp; i != ( cHull[holeS] - 1 + nbp ) % nbp; i = j )
      {
        j = ( i + 1 ) % nbp; // i->j is shape segment not in hole

        // compute distance between retainedPoint and segment
        // whether perpendicular distance (if retaindPoint is fronting segment i->j)
        // or distance between retainedPt and i or j (choose the nearest)
        seg_length = GeomFunction::dist_euc2d( x[i], y[i], x[j], y[j] );
        cx = ( x[i] + x[j] ) / 2.0;
        cy = ( y[i] + y[j] ) / 2.0;
        dx = cy - y[i];
        dy = cx - x[i];

        ex = cx - dx;
        ey = cy + dy;
        fx = cx + dx;
        fy = cy - dy;

        if ( seg_length < EPSILON || std::fabs( ( b = GeomFunction::cross_product( ex, ey, fx, fy, x[retainedPt], y[retainedPt] ) / ( seg_length ) ) ) > ( seg_length / 2 ) )   // retainedPt is not fronting i->j
        {
          if ( ( ex = GeomFunction::dist_euc2d_sq( x[i], y[i], x[retainedPt], y[retainedPt] ) ) < ( ey = GeomFunction::dist_euc2d_sq( x[j], y[j], x[retainedPt], y[retainedPt] ) ) )
          {
            b = ex;
            ps = i;
            pe = i;
          }
          else
          {
            b = ey;
            ps = j;
            pe = j;
          }
        }
        else   // point fronting i->j => compute pependicular distance  => create a new point
        {
          b = GeomFunction::cross_product( x[i], y[i], x[j], y[j], x[retainedPt], y[retainedPt] ) / seg_length;
          b *= b;
          ps = i;
          pe = j;

          if ( !GeomFunction::computeLineIntersection( x[i], y[i], x[j], y[j], x[retainedPt], y[retainedPt], x[retainedPt] - dx, y[retainedPt] + dy, &ptx, &pty ) )
          {
            //error - it should intersect the line
          }
        }

        isValid = true;
        double pointX, pointY;
        if ( ps == pe )
        {
          pointX = x[pe];
          pointY = y[pe];
        }
        else
        {
          pointX = ptx;
          pointY = pty;
        }

        for ( k = cHull[holeS]; k != cHull[holeE]; k = ( k + 1 ) % nbp )
        {
          l = ( k + 1 ) % nbp;
          if ( GeomFunction::isSegIntersects( x[retainedPt], y[retainedPt], pointX, pointY, x[k], y[k], x[l], y[l] ) )
          {
            isValid = false;
            break;
          }
        }


        if ( isValid && b < c )
        {
          c = b;
          fps = ps;
          fpe = pe;
          fptx = ptx;
          fpty = pty;
        }
      }  // for point which are not in hole

      // we will cut the shapeu in two new shapes, one from [retainedPoint] to [newPoint] and one form [newPoint] to [retainedPoint]
      int imin = retainedPt;
      int imax = ( ( ( fps < retainedPt && fpe < retainedPt ) || ( fps > retainedPt && fpe > retainedPt ) ) ? std::min( fps, fpe ) : std::max( fps, fpe ) );

      int nbPtSh1, nbPtSh2; // how many points in new shapes ?
      if ( imax > imin )
        nbPtSh1 = imax - imin + 1 + ( fpe != fps );
      else
        nbPtSh1 = imax + nbp - imin + 1 + ( fpe != fps );

      if ( ( imax == fps ? fpe : fps ) < imin )
        nbPtSh2 = imin - ( imax == fps ? fpe : fps ) + 1 + ( fpe != fps );
      else
        nbPtSh2 = imin + nbp - ( imax == fps ? fpe : fps ) + 1 + ( fpe != fps );

      if ( retainedPt == -1 || fps == -1 || fpe == -1 )
      {
        if ( shape->parent )
          delete shape;
      }
      // check for useless spliting
      else if ( imax == imin || nbPtSh1 <= 2 || nbPtSh2 <= 2 || nbPtSh1 == nbp  || nbPtSh2 == nbp )
      {
        shapes_final.append( shape );
      }
      else
      {

        PointSet *newShape = shape->extractShape( nbPtSh1, imin, imax, fps, fpe, fptx, fpty );

        if ( shape->parent )
          newShape->parent = shape->parent;
        else
          newShape->parent = shape;

        shapes_toProcess.append( newShape );

        if ( imax == fps )
          imax = fpe;
        else
          imax = fps;

        newShape = shape->extractShape( nbPtSh2, imax, imin, fps, fpe, fptx, fpty );

        if ( shape->parent )
          newShape->parent = shape->parent;
        else
          newShape->parent = shape;

        shapes_toProcess.append( newShape );

        if ( shape->parent )
          delete shape;
      }
    }
    else
    {
      shapes_final.append( shape );
    }
    delete[] pts;
  }
}