IOReturn
SATSMARTUserClient::ReadLogAtAddress ( ATASMARTReadLogStruct * structIn,
                                      void * structOut,
                                      IOByteCount inStructSize,
                                      IOByteCount *outStructSize)
{
    
    IOReturn status                  = kIOReturnSuccess;
    IOSATCommand *                  command                 = NULL;
    IOMemoryDescriptor *    buffer                  = NULL;
    DEBUG_LOG("%s[%p]::%s %p(%ld) %p(%ld)\n", getClassName(), this, __FUNCTION__, structIn, (long)inStructSize, structOut, (long)(outStructSize));
    
    if ( inStructSize != sizeof ( ATASMARTReadLogStruct )  || !outStructSize || *outStructSize < 1) {
        return kIOReturnBadArgument;
    }
    
    fOutstandingCommands++;
    
    if ( isInactive ( ) )
    {
        
        status = kIOReturnNoDevice;
        goto ErrorExit;
        
    }
    
    fProvider->retain ( );
    
    command = AllocateCommand ( );
    if ( command == NULL )
    {
        
        status = kIOReturnNoResources;
        goto ReleaseProvider;
        
    }
    
    buffer = IOMemoryDescriptor::withAddress (structOut,  *outStructSize, kIODirectionIn);
    if ( buffer == NULL )
    {
        
        status = kIOReturnNoResources;
        goto ReleaseCommand;
        
    }
    
    status = buffer->prepare ( );
    DEBUG_LOG("%s[%p]::%s status %x\n", getClassName(), this, __FUNCTION__, status);
    if ( status != kIOReturnSuccess )
    {
        
        goto ReleaseBuffer;
        
    }
    
    command->setBuffer                      ( buffer );
    command->setByteCount           ( buffer->getLength());
    command->setFeatures            ( kFeaturesRegisterReadLogAtAddress );
    command->setOpcode                      ( kATAFnExecIO );
    command->setTimeoutMS           ( kATAThirtySecondTimeoutInMS );
    command->setSectorCount         ( structIn->numSectors );
    command->setSectorNumber        ( structIn->logAddress );
    command->setCylLo                       ( kSMARTMagicCylinderLoValue );
    command->setCylHi                       ( kSMARTMagicCylinderHiValue );
    command->setCommand                     ( kATAcmdSMART );
    command->setFlags                       ( mATAFlagIORead );
    
    status = SendSMARTCommand ( command );
    if ( status == kIOReturnIOError )
    {
        
        if ( command->getEndErrorReg ( ) & 0x04 )
        {
            
            ERROR_LOG ( "ReadLogAtAddress %d unsupported\n", structIn->logAddress );
            status = kIOReturnUnsupported;
            
        }
        
        if ( command->getEndErrorReg ( ) & 0x10 )
        {
            
            ERROR_LOG ( "ReadLogAtAddress %d unreadable\n", structIn->logAddress );
            status = kIOReturnNotReadable;
            
        }
        
    }
    
    *outStructSize = buffer->getLength();
    
    buffer->complete ( );
    
    
    
ReleaseBuffer:
    
    
    buffer->release ( );
    buffer = NULL;
    
    
ReleaseCommand:
    
    
    DeallocateCommand ( command );
    command = NULL;
    
    
ReleaseProvider:
    
    
    fProvider->release ( );
    
    
ErrorExit:
    
    
    fOutstandingCommands--;
    
    DEBUG_LOG("%s[%p]::%s result %d\n", getClassName(), this,  __FUNCTION__, status);
    return status;
    
}
Array FrameInjection::getStackFrame(bool withSelf, bool withThis) {
  Array frame = Array::Create();

  if (m_prev) {
    String file = m_prev->getFileName();
    if (!file.empty() && m_prev->m_line) {
      frame.set(s_file, file, true);
      frame.set(s_line, m_prev->m_line, true);
    }
  } else if (m_flags & PseudoMain) {
    // Stop at top, don't include top file
    return Array();
  }

  if (m_flags & PseudoMain) {
    frame.set(s_function, "include", true);
    frame.set(s_args, Array::Create(getFileName()), true);
  } else {
    const char *c = strstr(m_name, "::");
    const char *f = m_name;
    if (c) {
      f = c + 2;
      frame.set(s_class, getClassName()->copy(), true);
      if (ObjectData *obj = getObjectV()) {
        if (withThis) {
          frame.set(s_object, Object(obj), true);
        }
        frame.set(s_type, "->", true);
      } else {
        frame.set(s_type, "::", true);
      }
    }
    ASSERT(f);
    switch (f[0]) {
    case ParserBase::CharClosure:
      frame.set(s_function, s_closureBrackets, true);
      break;
    case ParserBase::CharContinuationFromClosure:
      frame.set(s_function, s_closureGenBrackets, true);
      break;
    default:
      if (const char *c = strstr(f, "$$")) {
        frame.set(s_function, String(f, c - f, CopyString), true);
      } else {
        if (isEvalFrame()) {
          frame.set(s_function, String(f, CopyString), true);
        } else {
          frame.set(s_function, f, true);
        }
      }
      break;
    }

    Array args = getArgs();
    if (!args.isNull()) {
      frame.set(s_args, args, true);
    } else {
      frame.set(s_args, Array::Create(), true);
    }
  }
  return frame;
}
Exemple #3
0
QString Namer::getClassName( const Schema::Attribute &attribute )
{
  return getClassName( attribute.name() );
}
Exemple #4
0
/*!
  Creates an implementation (cpp-file) for the form given in \a e.

  \sa createFormDecl(), createObjectImpl()
 */
void Ui3Reader::createFormImpl(const QDomElement &e)
{
    QDomElement n;
    QDomNodeList nl;
    int i;
    QString objClass = getClassName(e);
    if (objClass.isEmpty())
        return;
    QString objName = getObjectName(e);

    // generate local and local includes required
    QStringList globalIncludes, localIncludes;
    QStringList::Iterator it;

    QMap<QString, CustomInclude> customWidgetIncludes;

    // find additional slots and functions
    QStringList extraFuncts;
    QStringList extraFunctTyp;
    QStringList extraFunctSpecifier;

    nl = e.parentNode().toElement().elementsByTagName(QLatin1String("slot"));
    for (i = 0; i < (int) nl.length(); i++) {
        n = nl.item(i).toElement();
        if (n.parentNode().toElement().tagName() != QLatin1String("slots")
             && n.parentNode().toElement().tagName() != QLatin1String("connections"))
            continue;
        if (n.attribute(QLatin1String("language"), QLatin1String("C++")) != QLatin1String("C++"))
            continue;
        QString functionName = n.firstChild().toText().data().trimmed();
        if (functionName.endsWith(QLatin1Char(';')))
            functionName.chop(1);
        extraFuncts += functionName;
        extraFunctTyp += n.attribute(QLatin1String("returnType"), QLatin1String("void"));
        extraFunctSpecifier += n.attribute(QLatin1String("specifier"), QLatin1String("virtual"));
    }

    nl = e.parentNode().toElement().elementsByTagName(QLatin1String("function"));
    for (i = 0; i < (int) nl.length(); i++) {
        n = nl.item(i).toElement();
        if (n.parentNode().toElement().tagName() != QLatin1String("functions"))
            continue;
        if (n.attribute(QLatin1String("language"), QLatin1String("C++")) != QLatin1String("C++"))
            continue;
        QString functionName = n.firstChild().toText().data().trimmed();
        if (functionName.endsWith(QLatin1Char(';')))
            functionName.chop(1);
        extraFuncts += functionName;
        extraFunctTyp += n.attribute(QLatin1String("returnType"), QLatin1String("void"));
        extraFunctSpecifier += n.attribute(QLatin1String("specifier"), QLatin1String("virtual"));
    }

    // additional includes (local or global) and forward declaractions
    nl = e.parentNode().toElement().elementsByTagName(QLatin1String("include"));
    for (i = 0; i < (int) nl.length(); i++) {
        QDomElement n2 = nl.item(i).toElement();
        QString s = n2.firstChild().toText().data();
        if (n2.attribute(QLatin1String("location")) != QLatin1String("local")) {
            if (s.right(5) == QLatin1String(".ui.h") && !QFile::exists(s))
                continue;
            if (n2.attribute(QLatin1String("impldecl"), QLatin1String("in implementation")) != QLatin1String("in implementation"))
                continue;
            globalIncludes += s;
        }
    }

    registerDatabases(e);
    dbConnections = unique(dbConnections);
    bool dbForm = false;
    if (dbForms[QLatin1String("(default)")].count())
        dbForm = true;
    bool subDbForms = false;
    for (it = dbConnections.begin(); it != dbConnections.end(); ++it) {
        if (!(*it).isEmpty()  && (*it) != QLatin1String("(default)")) {
            if (dbForms[(*it)].count()) {
                subDbForms = true;
                break;
            }
        }
    }

    // do the local includes afterwards, since global includes have priority on clashes
    for (i = 0; i < (int) nl.length(); i++) {
        QDomElement n2 = nl.item(i).toElement();
        QString s = n2.firstChild().toText().data();
        if (n2.attribute(QLatin1String("location")) == QLatin1String("local") && !globalIncludes.contains(s)) {
            if (s.right(5) == QLatin1String(".ui.h") && !QFile::exists(s))
                continue;
            if (n2.attribute(QLatin1String("impldecl"), QLatin1String("in implementation")) != QLatin1String("in implementation"))
                continue;
            localIncludes += s;
        }
    }

    // additional custom widget headers
    nl = e.parentNode().toElement().elementsByTagName(QLatin1String("header"));
    for (i = 0; i < (int) nl.length(); i++) {
        QDomElement n2 = nl.item(i).toElement();
        QString s = n2.firstChild().toText().data();
        if (n2.attribute(QLatin1String("location")) != QLatin1String("local"))
            globalIncludes += s;
        else
            localIncludes += s;
    }

    out << "#include <qvariant.h>" << endl; // first for gcc 2.7.2

    globalIncludes = unique(globalIncludes);
    for (it = globalIncludes.begin(); it != globalIncludes.end(); ++it) {
        if (!(*it).isEmpty())
            out << "#include <" << fixHeaderName(*it) << '>' << endl;
    }

    if (externPixmaps) {
        out << "#include <qimage.h>" << endl;
        out << "#include <qpixmap.h>" << endl << endl;
    }

    /*
      Put local includes after all global includes
    */
    localIncludes = unique(localIncludes);
    for (it = localIncludes.begin(); it != localIncludes.end(); ++it) {
        if (!(*it).isEmpty() && *it != QFileInfo(fileName + QLatin1String(".h")).fileName())
            out << "#include \"" << fixHeaderName(*it) << '\"' << endl;
    }

    QString uiDotH = fileName + QLatin1String(".h");
    if (QFile::exists(uiDotH)) {
        if (!outputFileName.isEmpty())
            uiDotH = QString::fromUtf8(combinePath(uiDotH.ascii(), outputFileName.ascii()));
        out << "#include \"" << uiDotH << '\"' << endl;
        writeFunctImpl = false;
    }

    // register the object and unify its name
    objName = registerObject(objName);

    if (externPixmaps) {
        pixmapLoaderFunction = QLatin1String("QPixmap::fromMimeSource");
    }

    // constructor
    if (objClass == QLatin1String("QDialog") || objClass == QLatin1String("QWizard")) {
        out << "/*" << endl;
        out << " *  Constructs a " << nameOfClass << " as a child of 'parent', with the" << endl;
        out << " *  name 'name' and widget flags set to 'f'." << endl;
        out << " *" << endl;
        out << " *  The " << objClass.mid(1).toLower() << " will by default be modeless, unless you set 'modal' to" << endl;
        out << " *  true to construct a modal " << objClass.mid(1).toLower() << '.' << endl;
        out << " */" << endl;
        out << nameOfClass << "::" << bareNameOfClass << "(QWidget* parent, const char* name, bool modal, Qt::WindowFlags fl)" << endl;
        out << "    : " << objClass << "(parent, name, modal, fl)";
    } else if (objClass == QLatin1String("QWidget"))  {
        out << "/*" << endl;
        out << " *  Constructs a " << nameOfClass << " as a child of 'parent', with the" << endl;
        out << " *  name 'name' and widget flags set to 'f'." << endl;
        out << " */" << endl;
        out << nameOfClass << "::" << bareNameOfClass << "(QWidget* parent, const char* name, Qt::WindowFlags fl)" << endl;
        out << "    : " << objClass << "(parent, name, fl)";
    } else if (objClass == QLatin1String("QMainWindow") || objClass == QLatin1String("Q3MainWindow")) {
        out << "/*" << endl;
        out << " *  Constructs a " << nameOfClass << " as a child of 'parent', with the" << endl;
        out << " *  name 'name' and widget flags set to 'f'." << endl;
        out << " *" << endl;
        out << " */" << endl;
        out << nameOfClass << "::" << bareNameOfClass << "(QWidget* parent, const char* name, Qt::WindowFlags fl)" << endl;
        out << "    : " << objClass << "(parent, name, fl)";
        isMainWindow = true;
    } else {
        out << "/*" << endl;
        out << " *  Constructs a " << nameOfClass << " which is a child of 'parent', with the" << endl;
        out << " *  name 'name'.' " << endl;
        out << " */" << endl;
        out << nameOfClass << "::" << bareNameOfClass << "(QWidget* parent, const char* name)" << endl;
        out << "    : " << objClass << "(parent, name)";
    }

    out << endl;

    out << '{' << endl;

//
// setup the gui
//
    out << indent << "setupUi(this);" << endl << endl;


    if (isMainWindow)
        out << indent << "(void)statusBar();" << endl;

    // database support
    dbConnections = unique(dbConnections);
    if (dbConnections.count())
        out << endl;
    for (it = dbConnections.begin(); it != dbConnections.end(); ++it) {
        if (!(*it).isEmpty() && (*it) != QLatin1String("(default)")) {
            out << indent << (*it) << "Connection = QSqlDatabase::database(\"" <<(*it) << "\");" << endl;
        }
    }

    nl = e.parentNode().toElement().elementsByTagName(QLatin1String("widget"));
    for (i = 1; i < (int) nl.length(); i++) { // start at 1, 0 is the toplevel widget
        n = nl.item(i).toElement();
        QString s = getClassName(n);
        if ((dbForm || subDbForms) && (s == QLatin1String("QDataBrowser") || s == QLatin1String("QDataView"))) {
            QString objName = getObjectName(n);
            QString tab = getDatabaseInfo(n, QLatin1String("table"));
            QString con = getDatabaseInfo(n, QLatin1String("connection"));
            out << indent << "QSqlForm* " << objName << "Form = new QSqlForm(this);" << endl;
            out << indent << objName << "Form->setObjectName(\"" << objName << "Form\");" << endl;
            QDomElement n2;
            for (n2 = n.firstChild().toElement(); !n2.isNull(); n2 = n2.nextSibling().toElement())
                createFormImpl(n2, objName, con, tab);
            out << indent << objName << "->setForm(" << objName << "Form);" << endl;
        }
    }

    if (extraFuncts.contains(QLatin1String("init()")))
        out << indent << "init();" << endl;

    // end of constructor
    out << '}' << endl;
    out << endl;

    // destructor
    out << "/*" << endl;
    out << " *  Destroys the object and frees any allocated resources" << endl;
    out << " */" << endl;
    out << nameOfClass << "::~" << bareNameOfClass << "()" << endl;
    out << '{' << endl;
    if (extraFuncts.contains(QLatin1String("destroy()")))
        out << indent << "destroy();" << endl;
    out << indent << "// no need to delete child widgets, Qt does it all for us" << endl;
    out << '}' << endl;
    out << endl;

    // handle application events if required
    bool needFontEventHandler = false;
    bool needSqlTableEventHandler = false;
    bool needSqlDataBrowserEventHandler = false;
    nl = e.elementsByTagName(QLatin1String("widget"));
    for (i = 0; i < (int) nl.length(); i++) {
        if (!DomTool::propertiesOfType(nl.item(i).toElement() , QLatin1String("font")).isEmpty())
            needFontEventHandler = true;
        QString s = getClassName(nl.item(i).toElement());
        if (s == QLatin1String("QDataTable") || s == QLatin1String("QDataBrowser")) {
            if (!isFrameworkCodeGenerated(nl.item(i).toElement()))
                 continue;
            if (s == QLatin1String("QDataTable"))
                needSqlTableEventHandler = true;
            if (s == QLatin1String("QDataBrowser"))
                needSqlDataBrowserEventHandler = true;
        }
        if (needFontEventHandler && needSqlTableEventHandler && needSqlDataBrowserEventHandler)
            break;
    }

    out << "/*" << endl;
    out << " *  Sets the strings of the subwidgets using the current" << endl;
    out << " *  language." << endl;
    out << " */" << endl;
    out << "void " << nameOfClass << "::languageChange()" << endl;
    out << '{' << endl;
    out << "    retranslateUi(this);" << endl;
    out << '}' << endl;
    out << endl;

    // create stubs for additional slots if necessary
    if (!extraFuncts.isEmpty() && writeFunctImpl) {
        it = extraFuncts.begin();
        QStringList::Iterator it2 = extraFunctTyp.begin();
        QStringList::Iterator it3 = extraFunctSpecifier.begin();
        while (it != extraFuncts.end()) {
            QString type = fixDeclaration(*it2);
            if (type.isEmpty())
                type = QLatin1String("void");
            type = type.simplified();
            QString fname = fixDeclaration(Parser::cleanArgs(*it));
            if (!(*it3).startsWith(QLatin1String("pure"))) { // "pure virtual" or "pureVirtual"
                out << type << ' ' << nameOfClass << "::" << fname << endl;
                out << '{' << endl;
                if (*it != QLatin1String("init()") && *it != QLatin1String("destroy()")) {
                    QRegExp numeric(QLatin1String("^(?:signed|unsigned|u?char|u?short|u?int"
                                     "|u?long|Q_U?INT(?:8|16|32)|Q_U?LONG|float"
                                     "|double)$"));
                    QString retVal;

                    /*
                      We return some kind of dummy value to shut the
                      compiler up.

                      1.  If the type is 'void', we return nothing.

                      2.  If the type is 'bool', we return 'false'.

                      3.  If the type is 'unsigned long' or
                          'quint16' or 'double' or similar, we
                          return '0'.

                      4.  If the type is 'Foo *', we return '0'.

                      5.  If the type is 'Foo &', we create a static
                          variable of type 'Foo' and return it.

                      6.  If the type is 'Foo', we assume there's a
                          default constructor and use it.
                    */
                    if (type != QLatin1String("void")) {
                        QStringList toks = type.split(QLatin1String(" "));
                        bool isBasicNumericType =
                                (toks.filter(numeric).count() == toks.count());

                        if (type == QLatin1String("bool")) {
                            retVal = QLatin1String("false");
                        } else if (isBasicNumericType || type.endsWith(QLatin1Char('*'))) {
                            retVal = QLatin1String("0");
                        } else if (type.endsWith(QLatin1Char('&'))) {
                            do {
                                type.chop(1);
                            } while (type.endsWith(QLatin1Char(' ')));
                            retVal = QLatin1String("uic_temp_var");
                            out << indent << "static " << type << ' ' << retVal << ';' << endl;
                        } else {
                            retVal = type + QLatin1String("()");
                        }
                    }

                    out << indent << "qWarning(\"" << nameOfClass << "::" << fname << ": Not implemented yet\");" << endl;
                    if (!retVal.isEmpty())
                        out << indent << "return " << retVal << ';' << endl;
                }
                out << '}' << endl;
                out << endl;
            }
            ++it;
            ++it2;
            ++it3;
        }
    }
}
Exemple #5
0
template <typename PointInT, typename PointOutT> void
pcl::MovingLeastSquares<PointInT, PointOutT>::process (PointCloudOut &output)
{
  // Check if normals have to be computed/saved
  if (compute_normals_)
  {
    normals_.reset (new NormalCloud);
    // Copy the header
    normals_->header = input_->header;
    // Clear the fields in case the method exits before computation
    normals_->width = normals_->height = 0;
    normals_->points.clear ();
  }


  // Copy the header
  output.header = input_->header;
  output.width = output.height = 0;
  output.points.clear ();

  if (search_radius_ <= 0 || sqr_gauss_param_ <= 0)
  {
    PCL_ERROR ("[pcl::%s::process] Invalid search radius (%f) or Gaussian parameter (%f)!\n", getClassName ().c_str (), search_radius_, sqr_gauss_param_);
    return;
  }

  // Check if distinct_cloud_ was set
  if (upsample_method_ == DISTINCT_CLOUD && !distinct_cloud_)
  {
    PCL_ERROR ("[pcl::%s::process] Upsample method was set to DISTINCT_CLOUD, but no distinct cloud was specified.\n", getClassName ().c_str ());
    return;
  }

  if (!initCompute ())
    return;


  // Initialize the spatial locator
  if (!tree_)
  {
    KdTreePtr tree;
    if (input_->isOrganized ())
      tree.reset (new pcl::search::OrganizedNeighbor<PointInT> ());
    else
      tree.reset (new pcl::search::KdTree<PointInT> (false));
    setSearchMethod (tree);
  }

  // Send the surface dataset to the spatial locator
  tree_->setInputCloud (input_, indices_);

  switch (upsample_method_)
  {
    // Initialize random number generator if necessary
    case (RANDOM_UNIFORM_DENSITY):
      {
      boost::mt19937 *rng = new boost::mt19937 (static_cast<unsigned int>(std::time(0)));
      float tmp = static_cast<float> (search_radius_ / 2.0f);
      boost::uniform_real<float> *uniform_distrib = new boost::uniform_real<float> (-tmp, tmp);
      rng_uniform_distribution_ = new boost::variate_generator<boost::mt19937, boost::uniform_real<float> > (*rng, *uniform_distrib);
      break;
      }
    case (VOXEL_GRID_DILATION):
    case (DISTINCT_CLOUD):
      {
      mls_results_.resize (input_->size ());
      break;
      }
    default:
      break;
  }

  // Perform the actual surface reconstruction
  performProcessing (output);

  if (compute_normals_)
  {
    normals_->height = 1;
    normals_->width = static_cast<uint32_t> (normals_->size ());

    // TODO!!! MODIFY TO PER-CLOUD COPYING - much faster than per-point
    for (unsigned int i = 0; i < output.size (); ++i)
    {
      typedef typename pcl::traits::fieldList<PointOutT>::type FieldList;
      pcl::for_each_type<FieldList> (SetIfFieldExists<PointOutT, float> (output.points[i], "normal_x", normals_->points[i].normal_x));
      pcl::for_each_type<FieldList> (SetIfFieldExists<PointOutT, float> (output.points[i], "normal_y", normals_->points[i].normal_y));
      pcl::for_each_type<FieldList> (SetIfFieldExists<PointOutT, float> (output.points[i], "normal_z", normals_->points[i].normal_z));
      pcl::for_each_type<FieldList> (SetIfFieldExists<PointOutT, float> (output.points[i], "curvature", normals_->points[i].curvature));
    }

  }

  // Set proper widths and heights for the clouds
  output.height = 1;
  output.width = static_cast<uint32_t> (output.size ());

  deinitCompute ();
}
Exemple #6
0
void VisletFactory::destroyVislet(Vislet*) const
	{
	Misc::throwStdErr("Cannot destroy vislet of abstract class %s",getClassName());
	}
Exemple #7
0
/*!
  Creates a declaration (header file) for the form given in \a e

  \sa createFormImpl()
*/
void Ui3Reader::createFormDecl(const QDomElement &e)
{
    QDomElement body = e;

    QDomElement n;
    QDomNodeList nl;
    int i;
    QString objClass = getClassName(e);
    if (objClass.isEmpty())
        return;
    QString objName = getObjectName(e);

    QStringList typeDefs;

    QMap<QString, CustomInclude> customWidgetIncludes;

    /*
      We are generating a few QImage members that are not strictly
      necessary in some cases. Ideally, we would use requiredImage,
      which is computed elsewhere, to keep the generated .h and .cpp
      files synchronized.
    */

    // at first the images
    QMap<QString, int> customWidgets;
    QStringList forwardDecl;
    QStringList forwardDecl2;
    for (n = e; !n.isNull(); n = n.nextSibling().toElement()) {
        if (n.tagName().toLower() == QLatin1String("customwidgets")) {
            QDomElement n2 = n.firstChild().toElement();
            while (!n2.isNull()) {
                if (n2.tagName().toLower() == QLatin1String("customwidget")) {
                    QDomElement n3 = n2.firstChild().toElement();
                    QString cl;
                    while (!n3.isNull()) {
                        QString tagName = n3.tagName().toLower();
                        if (tagName == QLatin1String("class")) {
                            cl = n3.firstChild().toText().data();
                            if (m_options & CustomWidgetForwardDeclarations)
                                forwardDecl << cl;
                            customWidgets.insert(cl, 0);
                        } else if (tagName == QLatin1String("header")) {
                            CustomInclude ci;
                            ci.header = n3.firstChild().toText().data();
                            ci.location = n3.attribute(QLatin1String("location"), QLatin1String("global"));
                            if (!ci.header.isEmpty())
                                forwardDecl.removeAll(cl);
                            customWidgetIncludes.insert(cl, ci);
                        }
                        n3 = n3.nextSibling().toElement();
                    }
                }
                n2 = n2.nextSibling().toElement();
            }
        }
    }

    // register the object and unify its name
    objName = registerObject(objName);
    QString protector = objName.toUpper() + QLatin1String("_H");
    protector.replace(QLatin1String("::"), QLatin1String("_"));
    out << "#ifndef " << protector << endl;
    out << "#define " << protector << endl;
    out << endl;

    out << "#include <qvariant.h>" << endl; // for broken HP-UX compilers

    QStringList globalIncludes, localIncludes;

    {
        QMap<QString, CustomInclude>::Iterator it = customWidgetIncludes.find(objClass);
        if (it != customWidgetIncludes.end()) {
            if ((*it).location == QLatin1String("global"))
                globalIncludes += (*it).header;
            else
                localIncludes += (*it).header;
        }
    }

    QStringList::ConstIterator it;

    globalIncludes = unique(globalIncludes);
    for (it = globalIncludes.constBegin(); it != globalIncludes.constEnd(); ++it) {
        if (!(*it).isEmpty()) {
            QString header = fixHeaderName(*it);
            out << "#include <" << header << '>' << endl;
        }
    }
    localIncludes = unique(localIncludes);
    for (it = localIncludes.constBegin(); it != localIncludes.constEnd(); ++it) {
        if (!(*it).isEmpty()) {
            QString header = fixHeaderName(*it);
            out << "#include \"" << header << '\"' << endl;
        }
    }
    out << endl;

    bool dbForm = false;
    registerDatabases(e);
    dbConnections = unique(dbConnections);
    if (dbForms[QLatin1String("(default)")].count())
        dbForm = true;
    bool subDbForms = false;
    for (it = dbConnections.constBegin(); it != dbConnections.constEnd(); ++it) {
        if (!(*it).isEmpty() && (*it) != QLatin1String("(default)")) {
            if (dbForms[(*it)].count()) {
                subDbForms = true;
                break;
            }
        }
    }

    // some typedefs, maybe
    typeDefs = unique(typeDefs);
    for (it = typeDefs.constBegin(); it != typeDefs.constEnd(); ++it) {
        if (!(*it).isEmpty())
            out << "typedef " << *it << ';' << endl;
    }

    nl = e.parentNode().toElement().elementsByTagName(QLatin1String("forward"));
    for (i = 0; i < (int) nl.length(); i++)
        forwardDecl2 << fixDeclaration(nl.item(i).toElement().firstChild().toText().data());

    forwardDecl = unique(forwardDecl);
    for (it = forwardDecl.constBegin(); it != forwardDecl.constEnd(); ++it) {
        if (!(*it).isEmpty() && (*it) != objClass) {
            QString forwardName = *it;
            QStringList forwardNamespaces = forwardName.split(QLatin1String("::"));
            forwardName = forwardNamespaces.last();
            forwardNamespaces.removeAt(forwardNamespaces.size()-1);

            QStringList::ConstIterator ns = forwardNamespaces.constBegin();
            while (ns != forwardNamespaces.constEnd()) {
                out << "namespace " << *ns << " {" << endl;
                ++ns;
            }
            out << "class " << forwardName << ';' << endl;
            for (int i = 0; i < (int) forwardNamespaces.count(); i++)
                out << '}' << endl;
        }
    }

    for (it = forwardDecl2.constBegin(); it != forwardDecl2.constEnd(); ++it) {
        QString fd = *it;
        fd = fd.trimmed();
        if (!fd.endsWith(QLatin1Char(';')))
            fd += QLatin1Char(';');
        out << fd << endl;
    }

    out << endl;

    Driver d;
    d.option().headerProtection = false;
    d.option().copyrightHeader = false;
    d.option().extractImages = m_extractImages;
    d.option().limitXPM_LineLength = (m_options & LimitXPM_LineLength) ? 1 : 0;
    d.option().qrcOutputFile = m_qrcOutputFile;
    d.option().implicitIncludes = (m_options & ImplicitIncludes) ? 1 : 0;
    if (trmacro.size())
        d.option().translateFunction = trmacro;
    DomUI *ui = generateUi4(e);
    d.uic(fileName, ui, &out);
    delete ui;

    createWrapperDeclContents(e);

    out << "#endif // " << protector << endl;
}
IOReturn
SATSMARTUserClient::ExecuteOfflineImmediate ( UInt32 extendedTest )
{
    
    IOReturn status  = kIOReturnSuccess;
    IOSATCommand *  command = NULL;
    DEBUG_LOG("%s[%p]::%s\n", getClassName(), this, __FUNCTION__);
    
    fOutstandingCommands++;
    
    if ( isInactive ( ) )
    {
        
        status = kIOReturnNoDevice;
        goto ErrorExit;
        
    }
    
    fProvider->retain ( );
    
    command = AllocateCommand ( );
    if ( command == NULL )
    {
        
        status = kIOReturnNoResources;
        goto ReleaseProvider;
        
    }
    
    command->setFeatures            ( kFeaturesRegisterExecuteOfflineImmed );
    command->setOpcode                      ( kATAFnExecIO );
    command->setTimeoutMS           ( kATAThirtySecondTimeoutInMS );
    command->setSectorNumber        ( ( extendedTest == 0 ) ? 0x01 : 0x02 );
    command->setCylLo                       ( kSMARTMagicCylinderLoValue );
    command->setCylHi                       ( kSMARTMagicCylinderHiValue );
    command->setCommand                     ( kATAcmdSMART );
    
    status = SendSMARTCommand ( command );
    if ( status == kIOReturnIOError )
    {
        
        if ( command->getEndErrorReg ( ) & 0x04 )
        {
            
            ERROR_LOG ( "Execute Offline Immediate unsupported\n" );
            status = kIOReturnUnsupported;
            
        }
        
    }
    
    DeallocateCommand ( command );
    command = NULL;
    
    
ReleaseProvider:
    
    
    fProvider->release ( );
    
    
ErrorExit:
    
    
    fOutstandingCommands--;
    
    DEBUG_LOG("%s[%p]::%s result %d\n", getClassName(), this,  __FUNCTION__, status);
    return status;
    
}
IOReturn
SATSMARTUserClient::ReadDataThresholds (UInt32 * dataOut,
                                        IOByteCount * outputSize)
{
    
    IOReturn status  = kIOReturnSuccess;
    IOSATCommand *                  command = NULL;
    IOMemoryDescriptor *    buffer  = NULL;
    DEBUG_LOG("%s[%p]::%s\n", getClassName(), this, __FUNCTION__);
    
    if (!dataOut || !outputSize || *outputSize != sizeof ( ATASMARTDataThresholds ) ) {
        return kIOReturnBadArgument;
    }
    
    fOutstandingCommands++;
    
    if ( isInactive ( ) )
    {
        
        status = kIOReturnNoDevice;
        goto ErrorExit;
        
    }
    
    fProvider->retain ( );
    
    command = AllocateCommand ( );
    if ( command == NULL )
    {
        
        status = kIOReturnNoResources;
        goto ReleaseProvider;
        
    }
    
    buffer = IOMemoryDescriptor::withAddress(dataOut, sizeof ( ATASMARTDataThresholds ), kIODirectionIn);
    
    if ( buffer == NULL )
    {
        
        status = kIOReturnNoResources;
        goto ReleaseCommand;
        
    }
    
    status = buffer->prepare ( );
    if ( status != kIOReturnSuccess )
    {
        
        goto ReleaseBuffer;
        
    }
    
    command->setBuffer                      ( buffer );
    command->setByteCount           ( sizeof ( ATASMARTDataThresholds ) );
    command->setFeatures            ( kFeaturesRegisterReadDataThresholds );
    command->setOpcode                      ( kATAFnExecIO );
    command->setTimeoutMS           ( kATAThirtySecondTimeoutInMS );
    command->setCylLo                       ( kSMARTMagicCylinderLoValue );
    command->setCylHi                       ( kSMARTMagicCylinderHiValue );
    command->setCommand                     ( kATAcmdSMART );
    command->setFlags                       ( mATAFlagIORead );
    
    status = SendSMARTCommand ( command );
    if ( status == kIOReturnIOError )
    {
        
        if ( command->getEndErrorReg ( ) & 0x04 )
        {
            
            ERROR_LOG ( "ReadDataThresholds unsupported\n" );
            status = kIOReturnUnsupported;
            
        }
        
        if ( command->getEndErrorReg ( ) & 0x10 )
        {
            
            ERROR_LOG ( "ReadDataThresholds Not readable\n" );
            status = kIOReturnNotReadable;
            
        }
        
    }
    
    *outputSize = buffer->getLength();
    
    buffer->complete ( );
    
    
ReleaseBuffer:
    
    
    buffer->release ( );
    buffer = NULL;
    
    
ReleaseCommand:
    
    
    DeallocateCommand ( command );
    command = NULL;
    
    
ReleaseProvider:
    
    
    fProvider->release ( );
    
    
ErrorExit:
    
    
    fOutstandingCommands--;
    
    DEBUG_LOG("%s[%p]::%s result %d\n", getClassName(), this,  __FUNCTION__, status);
    return status;
    
}
IOReturn
SATSMARTUserClient::EnableDisableAutoSave ( UInt32 enable )
{
    
    IOReturn status = kIOReturnSuccess;
    IOSATCommand *  command;
    DEBUG_LOG("%s[%p]::%s\n", getClassName(), this, __FUNCTION__);
    
    fOutstandingCommands++;
    
    if ( isInactive ( ) )
    {
        
        status = kIOReturnNoDevice;
        goto ErrorExit;
        
    }
    
    fProvider->retain ( );
    
    command = AllocateCommand ( );
    if ( command == NULL )
    {
        
        status = kIOReturnNoResources;
        goto ReleaseProvider;
        
    }
    
    if ( enable == 0 )
    {
        
        // They want to disable SMART autosave operations.
        command->setSectorCount ( kSMARTAutoSaveDisable );
        
    }
    
    else
    {
        
        // They want to enable SMART autosave operations.
        command->setSectorCount ( kSMARTAutoSaveEnable );
        
    }
    
    command->setFeatures    ( kFeaturesRegisterEnableDisableAutoSave );
    command->setOpcode              ( kATAFnExecIO );
    command->setTimeoutMS   ( kATAThirtySecondTimeoutInMS );
    command->setCylLo               ( kSMARTMagicCylinderLoValue );
    command->setCylHi               ( kSMARTMagicCylinderHiValue );
    command->setCommand             ( kATAcmdSMART );
    
    status = SendSMARTCommand ( command );
    if ( status == kIOReturnIOError )
    {
        
        if ( command->getEndErrorReg ( ) & 0x04 )
        {
            
            ERROR_LOG ( "Enable/Disable autosave unsupported\n" );
            status = kIOReturnUnsupported;
            
        }
        
    }
    
    DeallocateCommand ( command );
    command = NULL;
    
    
ReleaseProvider:
    
    
    fProvider->release ( );
    
    
ErrorExit:
    
    
    fOutstandingCommands--;
    
    DEBUG_LOG("%s[%p]::%s result %d\n", getClassName(), this,  __FUNCTION__, status);
    return status;
    
}
IOReturn
SATSMARTUserClient::ReturnStatus ( UInt32 * exceededCondition )
{
    
    IOReturn status  = kIOReturnSuccess;
    IOSATCommand *  command = NULL;
    UInt8 lbaMid  = kSMARTMagicCylinderLoValue;
    UInt8 lbaHigh = kSMARTMagicCylinderHiValue;
    DEBUG_LOG("%s[%p]::%s\n", getClassName(), this, __FUNCTION__);
    
    fOutstandingCommands++;
    
    if ( isInactive ( ) )
    {
        
        status = kIOReturnNoDevice;
        goto ErrorExit;
        
    }
    
    fProvider->retain ( );
    
    command = AllocateCommand ( );
    if ( command == NULL )
    {
        
        status = kIOReturnNoResources;
        goto ReleaseProvider;
        
    }
    
    command->setFeatures    ( kFeaturesRegisterReturnStatus );
    command->setOpcode              ( kATAFnExecIO );
    command->setTimeoutMS   ( kATAThirtySecondTimeoutInMS );
    command->setCylLo               ( lbaMid );
    command->setCylHi               ( lbaHigh );
    command->setCommand             ( kATAcmdSMART );
    command->setRegMask             ( ( ataRegMask ) ( mATACylinderHiValid | mATACylinderLoValid ) );
    command->setFlags               ( mATAFlagTFAccessResult );
    
    status = SendSMARTCommand ( command );
    
    lbaMid  = command->getCylLo ( );
    lbaHigh = command->getCylHi ( );
    
    if ( status == kIOReturnSuccess )
    {
        
        // Check if threshold exceeded
        if ( ( lbaMid == kSMARTReturnStatusValidLoValue ) &&
            ( lbaHigh == kSMARTReturnStatusValidHiValue ) )
        {
            *exceededCondition = 1;
        }
        
        else
        {
            *exceededCondition = 0;
        }
        
    }
    
    if ( status == kIOReturnIOError )
    {
        
        if ( command->getEndErrorReg ( ) & 0x04 )
        {
            
            ERROR_LOG ( "Return Status unsupported\n" );
            status = kIOReturnUnsupported;
            
        }
        
    }
    
    DeallocateCommand ( command );
    command = NULL;
    
    
ReleaseProvider:
    
    
    fProvider->release ( );
    
    
ErrorExit:
    
    
    fOutstandingCommands--;
    
    DEBUG_LOG("%s[%p]::%s result %d\n", getClassName(), this,  __FUNCTION__, status);
    return status;
    
}
bool
SATSMARTUserClient::start ( IOService * provider )
{
    IOWorkLoop *    workLoop = NULL;
    DEBUG_LOG("%s[%p]::%s\n", getClassName(), this, __FUNCTION__);
    
    if ( fProvider != NULL )
    {
        
        ERROR_LOG ( "fProvider != NULL, returning false\n" );
        return false;
        
    }
    
    fProvider = OSDynamicCast ( IOSATServices, provider );
    if ( fProvider == NULL )
    {
        
        ERROR_LOG ( "Provider not IOSATServices\n" );
        return false;
        
    }
    
    if ( !super::start ( provider ) )
    {
        
        ERROR_LOG ( "super rejected provider in start\n" );
        return false;
        
    }
    
    fCommandGate = IOCommandGate::commandGate ( this );
    if ( fCommandGate == NULL )
    {
        
        ERROR_LOG ( "Command gate creation failed\n" );
        return false;
        
    }
    
    workLoop = getWorkLoop ( );
    if ( workLoop == NULL )
    {
        
        ERROR_LOG ( "workLoop == NULL\n" );
        fCommandGate->release ( );
        fCommandGate = NULL;
        return false;
        
    }
    
    workLoop->addEventSource ( fCommandGate );
    
    if ( !fProvider->open ( this, kIOATASMARTUserClientAccessMask, 0 ) )
    {
        
        ERROR_LOG ( "Open failed\n" );
        fCommandGate->release ( );
        fCommandGate = NULL;
        return false;
        
    }
    
    fWorkLoop = workLoop;
    
    // Yes, we found an object to use as our interface
    return true;
    
}
IOReturn
SATSMARTUserClient::GetIdentifyData (UInt32 * dataOut,
				     IOByteCount * outputSize)
{
    
    IOReturn status                  = kIOReturnSuccess;
    IOSATCommand *                          command                 = NULL;
    IOMemoryDescriptor *      buffer                  = NULL;
    DEBUG_LOG("%s[%p]::%s %p(%ld)\n", getClassName(), this, __FUNCTION__, dataOut, (long)(outputSize));
    
    if (!dataOut || !outputSize || *outputSize < kATADefaultSectorSize ) {
        return kIOReturnBadArgument;
    }
    
    fOutstandingCommands++;
    
    if ( isInactive ( ) )
    {
        
        status = kIOReturnNoDevice;
        goto ErrorExit;
        
    }
    
    fProvider->retain ( );
    
    command = AllocateCommand ( );
    if ( command == NULL )
    {
        
        status = kIOReturnNoResources;
        goto ReleaseProvider;
        
    }
    
    buffer = IOMemoryDescriptor::withAddress(dataOut, kATADefaultSectorSize, kIODirectionIn);
    if ( buffer == NULL )
    {
        
        status = kIOReturnNoResources;
        goto ReleaseCommand;
        
    }
    
    status = buffer->prepare ( );
    if ( status != kIOReturnSuccess )
    {
        
        goto ReleaseBuffer;
        
    }
    
    command->setBuffer                              ( buffer );
    command->setByteCount                   ( kATADefaultSectorSize );
    command->setTransferChunkSize   ( kATADefaultSectorSize );
    command->setOpcode                              ( kATAFnExecIO );
    command->setTimeoutMS                   ( kATAThirtySecondTimeoutInMS );
    command->setCommand                             ( kATAcmdDriveIdentify );
    command->setFlags                               ( mATAFlagIORead );
    command->setRegMask                             ( ( ataRegMask ) ( mATAErrFeaturesValid | mATAStatusCmdValid ) );
    
    status = SendSMARTCommand ( command );
    if ( status == kIOReturnSuccess )
    {
        
#if defined(__BIG_ENDIAN__)
        UInt8 *         bufferToCopy = identifyDataPtr;
        
        // The identify device info needs to be byte-swapped on big-endian (ppc)
        // systems becuase it is data that is produced by the drive, read across a
        // 16-bit little-endian PCI interface, directly into a big-endian system.
        // Regular data doesn't need to be byte-swapped because it is written and
        // read from the host and is intrinsically byte-order correct.
        
        IOByteCount index;
        UInt8 temp;
        UInt8 *                 firstBytePtr;
        UInt8 *                 identifyDataPtr = ( UInt8 * )dataOut;
        
        for ( index = 0; index < buffer->getLength ( ); index += 2 )
        {
            
            firstBytePtr            = identifyDataPtr;                          // save pointer
            temp                            = *identifyDataPtr++;               // Save Byte0, point to Byte1
            *firstBytePtr           = *identifyDataPtr;                         // Byte0 = Byte1
            *identifyDataPtr++      = temp;                                             // Byte1 = Byte0
            
        }
        
#endif
        
        *outputSize = buffer->getLength ( );
        DEBUG_LOG("%s[%p]::%s cpy %p %p\n", getClassName(), this,  __FUNCTION__, (void*)*outputSize, (void*)buffer->getLength());
    }
    
    
ReleaseBufferPrepared:
    
    buffer->complete ( );
    
    
ReleaseBuffer:
    
    
    buffer->release ( );
    buffer = NULL;
    
    
ReleaseCommand:
    
    
    DeallocateCommand ( command );
    command = NULL;
    
    
ReleaseProvider:
    
    
    fProvider->release ( );
    
    
ErrorExit:
    
    
    fOutstandingCommands--;
    
    DEBUG_LOG("%s[%p]::%s result %x\n", getClassName(), this,  __FUNCTION__, status);
    return status;
    
}
IOReturn
SATSMARTUserClient::WriteLogAtAddress ( ATASMARTWriteLogStruct *        writeLogData,
                                       UInt32 inStructSize )
{
    
    IOReturn status                  = kIOReturnSuccess;
    IOSATCommand *                  command                 = NULL;
    IOMemoryDescriptor *    buffer                  = NULL;
    DEBUG_LOG("%s[%p]::%s\n", getClassName(), this, __FUNCTION__);
    
    if ( inStructSize != sizeof ( ATASMARTWriteLogStruct ) || writeLogData->numSectors > 16 || writeLogData->data_length > kSATMaxDataSize) {
        return kIOReturnBadArgument;
    }
    
    fOutstandingCommands++;
    
    if ( isInactive ( ) )
    {
        
        status = kIOReturnNoDevice;
        goto ErrorExit;
        
    }
    
    fProvider->retain ( );
    
    command = AllocateCommand ( );
    if ( command == NULL )
    {
        status = kIOReturnNoResources;
        goto ReleaseProvider;
    }
    
    //buffer = IOMemoryDescriptor::withAddress(writeLogData->buffer, writeLogData->bufferSize, kIODirectionOut);
    buffer = IOMemoryDescriptor::withAddressRange(writeLogData->data_pointer, writeLogData->data_length, kIODirectionOut, fTask);
    
    if ( buffer == NULL )
    {
        status = kIOReturnVMError;
        goto ReleaseCommand;
    }
    
    status = buffer->prepare ( );
    if ( status != kIOReturnSuccess )
    {
        goto ReleaseBuffer;
    }
    
    command->setBuffer                      ( buffer );
    command->setByteCount           ( writeLogData->data_length );
    command->setFeatures            ( kFeaturesRegisterWriteLogAtAddress );
    command->setOpcode                      ( kATAFnExecIO );
    command->setTimeoutMS           ( kATAThirtySecondTimeoutInMS );
    command->setSectorCount         ( writeLogData->numSectors );
    command->setSectorNumber        ( writeLogData->logAddress );
    command->setCylLo                       ( kSMARTMagicCylinderLoValue );
    command->setCylHi                       ( kSMARTMagicCylinderHiValue );
    command->setCommand                     ( kATAcmdSMART );
    command->setFlags                       ( mATAFlagIOWrite );
    
    status = SendSMARTCommand ( command );
    if ( status == kIOReturnIOError )
    {
        
        if ( command->getEndErrorReg ( ) & 0x04 )
        {
            
            ERROR_LOG ( "WriteLogAtAddress %d unsupported\n", writeLogData->logAddress );
            status = kIOReturnUnsupported;
            
        }
        
        if ( command->getEndErrorReg ( ) & 0x10 )
        {
            
            ERROR_LOG ( "WriteLogAtAddress %d unwriteable\n", writeLogData->logAddress );
            status = kIOReturnNotWritable;
            
        }
        
    }
    
    buffer->complete ( );
    
    
ReleaseBuffer:
    
    
    buffer->release ( );
    buffer = NULL;
    
    
ReleaseCommand:
    
    
    DeallocateCommand ( command );
    command = NULL;
    
    
ReleaseProvider:
    
    
    fProvider->release ( );
    
    
ErrorExit:
    
    
    fOutstandingCommands--;
    
    DEBUG_LOG("%s[%p]::%s result %d\n", getClassName(), this,  __FUNCTION__, status);
    return status;
    
}
Exemple #15
0
bool isPushButton(QObject *object)
{
    static const QString name("QPushButton");
    return (getClassName(object) == name);
}
Exemple #16
0
String CIMObjectPath::toString() const
{
    String objectName;

    // Get the host:

    if (_rep->_host.size())
    {
        objectName = "//";
        objectName.append(_rep->_host);
        objectName.append("/");
    }

    // Get the namespace (if we have a host name, we must write namespace):

    if (!_rep->_nameSpace.isNull() || _rep->_host.size())
    {
        objectName.append(_rep->_nameSpace.getString ());
        objectName.append(":");
    }

    // Get the class name:

    objectName.append(getClassName().getString ());

    //
    //  ATTN-CAKG-P2-20020726:  The following condition does not correctly
    //  distinguish instanceNames from classNames in every case
    //  The instanceName of a singleton instance of a keyless class has no
    //  key bindings
    //
    if (_rep->_keyBindings.size () != 0)
    {
        objectName.append('.');

        // Append each key-value pair:

        const Array<CIMKeyBinding>& keyBindings = getKeyBindings();

        for (Uint32 i = 0, n = keyBindings.size(); i < n; i++)
        {
            objectName.append(keyBindings[i].getName().getString ());
            objectName.append('=');

            const String& value = _escapeSpecialCharacters(
                keyBindings[i].getValue());

            CIMKeyBinding::Type type = keyBindings[i].getType();

            if (type == CIMKeyBinding::STRING || type == CIMKeyBinding::REFERENCE)
                objectName.append('"');

            objectName.append(value);

            if (type == CIMKeyBinding::STRING || type == CIMKeyBinding::REFERENCE)
                objectName.append('"');

            if (i + 1 != n)
                objectName.append(',');
        }
    }

    return objectName;
}
Exemple #17
0
 const TCHAR* RangeQuery::getQueryName() const{
   return getClassName();
 }
Exemple #18
0
//////////////////////////////////////////////////////////////////////////////////////////////
// Compute a local Reference Frame for a 3D feature; the output is stored in the "rf" vector
template <typename PointInT, typename PointNT, typename PointOutT> float
pcl::SHOTEstimationBase<PointInT, PointNT, PointOutT>::getSHOTLocalRF (
  const pcl::PointCloud<PointInT> &cloud, const pcl::PointCloud<PointNT> &normals,
  const int index, const std::vector<int> &indices, const std::vector<float> &dists, 
  std::vector<Eigen::Vector4f, Eigen::aligned_allocator<Eigen::Vector4f> > &rf)
{
  if (rf.size () != 3)
    rf.resize (3);

  Eigen::Vector4f central_point = cloud.points[index].getVector4fMap ();
  // Allocate enough space
  Eigen::Vector4d *vij = new Eigen::Vector4d[indices.size ()];

  Eigen::Matrix3d cov_m = Eigen::Matrix3d::Zero ();

  double distance = 0.0;
  double sum = 0.0;

  int valid_nn_points = 0;

  for (size_t i_idx = 0; i_idx < indices.size (); ++i_idx)
  {
    if (indices[i_idx] == index)
      continue;

    Eigen::Vector4f pt = cloud.points[indices[i_idx]].getVector4fMap (); 
    // Difference between current point and origin
    vij[valid_nn_points] = (pt - central_point).cast<double> ();

    distance = search_radius_ - sqrt (dists[i_idx]);

    // Multiply vij * vij'
    cov_m += distance * (vij[valid_nn_points].head<3> () * vij[valid_nn_points].head<3> ().transpose ());

    sum += distance;
    valid_nn_points++;
  }

  if (valid_nn_points < 5)
  {
    PCL_ERROR ("[pcl::%s::getSHOTLocalRF] Warning! Neighborhood has less than 5 vertexes. Aborting Local RF computation of feature point with index %d\n", getClassName ().c_str (), index);
    rf[0].setZero ();
    rf[1].setZero ();
    rf[2].setZero ();

    rf[0][0] = 1;
    rf[1][1] = 1;
    rf[2][2] = 1;

    delete [] vij;

    return (std::numeric_limits<float>::max ());
  }

  cov_m /= sum;

  Eigen::SelfAdjointEigenSolver<Eigen::Matrix3d> solver (cov_m);

  // Disambiguation
  int plusNormal = 0, plusTangentDirection1=0;

  Eigen::Vector3d v1c = solver.eigenvectors ().col (0);
  Eigen::Vector3d v2c = solver.eigenvectors ().col (1);
  Eigen::Vector3d v3c = solver.eigenvectors ().col (2);

  double e1c = solver.eigenvalues ()[0];
  double e2c = solver.eigenvalues ()[1];
  double e3c = solver.eigenvalues ()[2];

  Eigen::Vector4d v1 = Eigen::Vector4d::Zero ();
  Eigen::Vector4d v3 = Eigen::Vector4d::Zero ();

  if (e1c > e2c)
  {
    if (e1c > e3c) // v1c > max(v2c,v3c)
    {
      v1.head<3> () = v1c;

      if (e2c > e3c)  // v1c > v2c > v3c
        v3.head<3> () = v3c;
      else // v1c > v3c > v2c
        v3.head<3> () = v2c;
    }
    else // v3c > v1c > v2c
    {
      v1.head<3> () = v3c;
      v3.head<3> () = v2c;
    }
  }
  else
  {
    if (e2c > e3c) // v2c > max(v1c,v3c)
    {
      v1.head<3> () = v2c;

      if (e1c > e3c)  // v2c > v1c > v3c
        v3.head<3> () = v3c;
      else // v2c > v3c > v1c
        v3.head<3> () = v1c;
    }
    else // v3c > v2c > v1c
    {
      v1.head<3> () = v3c;
      v3.head<3> () = v1c;
    }
  }

  for (int ne = 0; ne < valid_nn_points; ne++)
  {
    double dp = vij[ne].dot (v1);
    if (dp >= 0)
      plusTangentDirection1++;

    dp = vij[ne].dot (v3);
    if (dp >= 0)
      plusNormal++;
  }

  if (plusTangentDirection1 < valid_nn_points - plusTangentDirection1)
    v1 *= - 1;

  if (plusNormal < valid_nn_points - plusNormal)
    v3 *= - 1;

  rf[0] = v1.cast<float>();
  rf[2] = v3.cast<float>();
  rf[1] = rf[2].cross3 (rf[0]);
  rf[0][3] = 0; rf[1][3] = 0; rf[2][3] = 0;

  delete [] vij;

  return (0.0f);
}
Exemple #19
0
std::string PlanIterator::toString() const
{
  std::stringstream ss;
  ss << getId() << " = " << getClassName();
  return ss.str();
}
Exemple #20
0
      /* Returns a satTypeValueMap object, adding the new data generated when
       * calling this object.
       *
       * @param time      Epoch corresponding to the data.
       * @param gData     Data object holding the data.
       */
   satTypeValueMap& ComputeDOP::Process( const CommonTime& time,
                                         satTypeValueMap& gData)
      throw(ProcessingException)
   {

      try
      {

         bool valid1(false), valid2(false); 

            // First, let's define a set with XYZt unknowns
         TypeIDSet tempSet1;
         tempSet1.insert(TypeID::dx);
         tempSet1.insert(TypeID::dy);
         tempSet1.insert(TypeID::dz);
         tempSet1.insert(TypeID::cdt);

            // Second, let's define a set with NEUt unknowns
         TypeIDSet tempSet2;
         tempSet2.insert(TypeID::dLat);
         tempSet2.insert(TypeID::dLon);
         tempSet2.insert(TypeID::dH);
         tempSet2.insert(TypeID::cdt);

            // Then, generate the corresponding geometry/design matrices
         Matrix<double> dMatrix1(gData.getMatrixOfTypes(tempSet1));
         Matrix<double> dMatrix2(gData.getMatrixOfTypes(tempSet2));

            // Afterwards, compute the appropriate extra matrices
         Matrix<double> AT1(transpose(dMatrix1));
         Matrix<double> covM1(AT1 * dMatrix1);

         Matrix<double> AT2(transpose(dMatrix2));
         Matrix<double> covM2(AT2 * dMatrix2);

            // Let's try to invert AT*A matrices
         try
         {

            covM1 = inverseChol( covM1 );
            valid1 = true;

         }
         catch(...)
         {

            valid1 = false;
         }

         try
         {

            covM2 = inverseChol( covM2 );
            valid2 = true;

         }
         catch(...)
         {
            valid2 = false;
         }

         if( valid1 )
         {

            gdop = std::sqrt(covM1(0,0)+covM1(1,1)+covM1(2,2)+covM1(3,3));
            pdop = std::sqrt(covM1(0,0)+covM1(1,1)+covM1(2,2));
            tdop = std::sqrt(covM1(3,3));

         }
         else
         {
            gdop = -1.0;
            pdop = -1.0;
            tdop = -1.0;
         }

         if( valid2 )
         {
            hdop = std::sqrt(covM2(0,0)+covM2(1,1));
            vdop = std::sqrt(covM2(2,2));
         }
         else
         {
            hdop = -1.0;
            vdop = -1.0;
         }

         return gData;

      }
      catch(Exception& u)
      {
            // Throw an exception if something unexpected happens
         ProcessingException e( getClassName() + ":"
                                + u.what() );

         GPSTK_THROW(e);

      }

   }  // End of method 'ComputeDOP::Process()'
Exemple #21
0
void Ui3Reader::createWrapperDeclContents(const QDomElement &e)
{
    QString objClass = getClassName(e);
    if (objClass.isEmpty())
        return;

    QDomNodeList nl;
    QString exportMacro;
    int i;
    QDomElement n;
    QStringList::ConstIterator it;
    nl = e.parentNode().toElement().elementsByTagName(QLatin1String("exportmacro"));
    if (nl.length() == 1)
        exportMacro = nl.item(0).firstChild().toText().data();

    QStringList::ConstIterator ns = namespaces.constBegin();
    while (ns != namespaces.constEnd()) {
        out << "namespace " << *ns << " {" << endl;
        ++ns;
    }

    out << "class ";
    if (!exportMacro.isEmpty())
        out << exportMacro << ' ';
    out << bareNameOfClass << " : public " << objClass << ", public Ui::" << bareNameOfClass << endl << '{' << endl;

    /* qmake ignore Q_OBJECT */
    out << "    Q_OBJECT" << endl;
    out << endl;
    out << "public:" << endl;

    // constructor
    if (objClass == QLatin1String("QDialog") || objClass == QLatin1String("QWizard")) {
        out << "    " << bareNameOfClass << "(QWidget* parent = 0, const char* name = 0, bool modal = false, Qt::WindowFlags fl = 0);" << endl;
    } else if (objClass == QLatin1String("QWidget")) {
        out << "    " << bareNameOfClass << "(QWidget* parent = 0, const char* name = 0, Qt::WindowFlags fl = 0);" << endl;
    } else if (objClass == QLatin1String("QMainWindow") || objClass == QLatin1String("Q3MainWindow")) {
        out << "    " << bareNameOfClass << "(QWidget* parent = 0, const char* name = 0, Qt::WindowFlags fl = Qt::WType_TopLevel);" << endl;
        isMainWindow = true;
    } else {
        out << "    " << bareNameOfClass << "(QWidget* parent = 0, const char* name = 0);" << endl;
    }

    // destructor
    out << "    ~" << bareNameOfClass << "();" << endl;
    out << endl;

    // database connections
    dbConnections = unique(dbConnections);
    bool hadOutput = false;
    for (it = dbConnections.constBegin(); it != dbConnections.constEnd(); ++it) {
        if (!(*it).isEmpty()) {
            // only need pointers to non-default connections
            if ((*it) != QLatin1String("(default)") && !(*it).isEmpty()) {
                out << indent << "QSqlDatabase* " << *it << "Connection;" << endl;
                hadOutput = true;
            }
        }
    }
    if (hadOutput)
        out << endl;

    QStringList publicSlots, protectedSlots, privateSlots;
    QStringList publicSlotTypes, protectedSlotTypes, privateSlotTypes;
    QStringList publicSlotSpecifier, protectedSlotSpecifier, privateSlotSpecifier;

    nl = e.parentNode().toElement().elementsByTagName(QLatin1String("slot"));
    for (i = 0; i < (int) nl.length(); i++) {
        n = nl.item(i).toElement();
        if (n.parentNode().toElement().tagName() != QLatin1String("slots")
             && n.parentNode().toElement().tagName() != QLatin1String("connections"))
            continue;
        if (n.attribute(QLatin1String("language"), QLatin1String("C++")) != QLatin1String("C++"))
            continue;
        QString returnType = n.attribute(QLatin1String("returnType"), QLatin1String("void"));
        QString functionName = n.firstChild().toText().data().trimmed();
        if (functionName.endsWith(QLatin1Char(';')))
            functionName.chop(1);
        QString specifier = n.attribute(QLatin1String("specifier"));
        QString access = n.attribute(QLatin1String("access"));
        if (access == QLatin1String(QLatin1String("protected"))) {
            protectedSlots += functionName;
            protectedSlotTypes += returnType;
            protectedSlotSpecifier += specifier;
        } else if (access == QLatin1String("private")) {
            privateSlots += functionName;
            privateSlotTypes += returnType;
            privateSlotSpecifier += specifier;
        } else {
            publicSlots += functionName;
            publicSlotTypes += returnType;
            publicSlotSpecifier += specifier;
        }
    }

    QStringList publicFuncts, protectedFuncts, privateFuncts;
    QStringList publicFunctRetTyp, protectedFunctRetTyp, privateFunctRetTyp;
    QStringList publicFunctSpec, protectedFunctSpec, privateFunctSpec;

    nl = e.parentNode().toElement().elementsByTagName(QLatin1String("function"));
    for (i = 0; i < (int) nl.length(); i++) {
        n = nl.item(i).toElement();
        if (n.parentNode().toElement().tagName() != QLatin1String("functions"))
            continue;
        if (n.attribute(QLatin1String("language"), QLatin1String("C++")) != QLatin1String("C++"))
            continue;
        QString returnType = n.attribute(QLatin1String("returnType"), QLatin1String("void"));
        QString functionName = n.firstChild().toText().data().trimmed();
        if (functionName.endsWith(QLatin1Char(';')))
            functionName.chop(1);
        QString specifier = n.attribute(QLatin1String("specifier"));
        QString access = n.attribute(QLatin1String("access"));
        if (access == QLatin1String("protected")) {
            protectedFuncts += functionName;
            protectedFunctRetTyp += returnType;
            protectedFunctSpec += specifier;
        } else if (access == QLatin1String("private")) {
            privateFuncts += functionName;
            privateFunctRetTyp += returnType;
            privateFunctSpec += specifier;
        } else {
            publicFuncts += functionName;
            publicFunctRetTyp += returnType;
            publicFunctSpec += specifier;
        }
    }

    QStringList publicVars, protectedVars, privateVars;
    nl = e.parentNode().toElement().elementsByTagName(QLatin1String("variable"));
    for (i = 0; i < (int)nl.length(); i++) {
        n = nl.item(i).toElement();
        // Because of compatibility the next lines have to be commented out.
        // Someday it should be uncommented.
        //if (n.parentNode().toElement().tagName() != QLatin1String("variables"))
        //    continue;
        QString access = n.attribute(QLatin1String("access"), QLatin1String("protected"));
        QString var = fixDeclaration(n.firstChild().toText().data().trimmed());
        if (!var.endsWith(QLatin1Char(';')))
            var += QLatin1Char(';');
        if (access == QLatin1String("public"))
            publicVars += var;
        else if (access == QLatin1String("private"))
            privateVars += var;
        else
            protectedVars += var;
    }

    if (!publicVars.isEmpty()) {
        for (it = publicVars.constBegin(); it != publicVars.constEnd(); ++it)
            out << indent << *it << endl;
        out << endl;
    }
    if (!publicFuncts.isEmpty())
        writeFunctionsDecl(publicFuncts, publicFunctRetTyp, publicFunctSpec);

    if (!publicSlots.isEmpty()) {
        out << "public slots:" << endl;
        if (!publicSlots.isEmpty())
            writeFunctionsDecl(publicSlots, publicSlotTypes, publicSlotSpecifier);
    }

    // find signals
    QStringList extraSignals;
    nl = e.parentNode().toElement().elementsByTagName(QLatin1String("signal"));
    for (i = 0; i < (int) nl.length(); i++) {
        n = nl.item(i).toElement();
        if (n.parentNode().toElement().tagName() != QLatin1String("signals")
             && n.parentNode().toElement().tagName() != QLatin1String("connections"))
            continue;
        if (n.attribute(QLatin1String("language"), QLatin1String("C++")) != QLatin1String("C++"))
            continue;
        QString sigName = n.firstChild().toText().data().trimmed();
        if (sigName.endsWith(QLatin1Char(';')))
            sigName = sigName.left(sigName.length() - 1);
        extraSignals += fixDeclaration(sigName);
    }

    // create signals
    if (!extraSignals.isEmpty()) {
        out << "signals:" << endl;
        for (it = extraSignals.constBegin(); it != extraSignals.constEnd(); ++it)
            out << "    void " << (*it) << ';' << endl;
        out << endl;
    }

    if (!protectedVars.isEmpty()) {
        out << "protected:" << endl;
        for (it = protectedVars.constBegin(); it != protectedVars.constEnd(); ++it)
            out << indent << *it << endl;
        out << endl;
    }

    if (!protectedFuncts.isEmpty()) {
        if (protectedVars.isEmpty())
            out << "protected:" << endl;

        writeFunctionsDecl(protectedFuncts, protectedFunctRetTyp, protectedFunctSpec);
    }

    out << "protected slots:" << endl;
    out << "    virtual void languageChange();" << endl;

    if (!protectedSlots.isEmpty()) {
        out << endl;
        writeFunctionsDecl(protectedSlots, protectedSlotTypes, protectedSlotSpecifier);
    }
    out << endl;

    // create all private stuff
    if (!privateFuncts.isEmpty() || !privateVars.isEmpty()) {
        out << "private:" << endl;
        if (!privateVars.isEmpty()) {
            for (it = privateVars.constBegin(); it != privateVars.constEnd(); ++it)
                out << indent << *it << endl;
            out << endl;
        }
        if (!privateFuncts.isEmpty())
            writeFunctionsDecl(privateFuncts, privateFunctRetTyp, privateFunctSpec);
    }

    if (!privateSlots.isEmpty()) {
        out << "private slots:" << endl;
        writeFunctionsDecl(privateSlots, privateSlotTypes, privateSlotSpecifier);
    }

    out << "};" << endl;
    for (i = 0; i < (int) namespaces.count(); i++)
        out << '}' << endl;

    out << endl;
}
MusicVideoTableWidget::~MusicVideoTableWidget()
{
    M_CONNECTION_PTR->poolDisConnect(getClassName());
    clearAllItems();
}
Exemple #23
0
int annTrain::train(std::string imagesDir, int networkInputSize, float testRatio)
{

    std::cout << "Reading training set..." << std::endl;
    uint64 start = ofGetElapsedTimeMillis();
    std::vector<std::string> files = getFilesInDirectory(imagesDir);
    std::random_shuffle(files.begin(), files.end());
    
    cv::Mat img;
    
    for (auto it = files.begin(); it != files.end(); ++it)
    {
        std::string filename = *it;
        //std::cout << "Reading image " << filename << "..." << std::endl;
        img = cv::imread(filename, 0);

        if (img.empty())
        {
            std::cerr << "WARNING: Could not read image." << std::endl;
            continue;
        }
        std::string classname = getClassName(filename);
        cv::Mat descriptors = getDescriptors(img);
        processClassAndDesc(classname, descriptors);
    }
    
    std::cout << " Seconds : " << (ofGetElapsedTimeMillis() - start) / 1000.0 << std::endl;
    
    std::cout << "Creating vocabulary..." << std::endl;
    start = ofGetElapsedTimeMillis();
    cv::Mat labels;
    cv::Mat vocabulary;
    // Use k-means to find k centroids (the words of our vocabulary)
    cv::kmeans(descriptorsSet, networkInputSize, labels, cv::TermCriteria(cv::TermCriteria::EPS + cv::TermCriteria::MAX_ITER, 10, 0.01), 1, cv::KMEANS_PP_CENTERS, vocabulary);
    // No need to keep it on memory anymore
    descriptorsSet.release();
    std::cout << " Seconds : " << (ofGetElapsedTimeMillis() - start) / 1000.0 << std::endl;
    
    // Convert a set of local features for each image in a single descriptors
    // using the bag of words technique
    std::cout << "Getting histograms of visual words..." << std::endl;
    int* ptrLabels = (int*)(labels.data);
    int size = labels.rows * labels.cols;
    for (int i = 0; i < size; i++)
    {
        int label = *ptrLabels++;
        ImageData* data = descriptorsMetadata[i];
        data->bowFeatures.at<float>(label)++;
    }
    
    // Filling matrixes to be used by the neural network
    std::cout << "Preparing neural network..." << std::endl;
    std::set<ImageData*> uniqueMetadata(descriptorsMetadata.begin(), descriptorsMetadata.end());
    for (auto it = uniqueMetadata.begin(); it != uniqueMetadata.end(); )
    {
        ImageData* data = *it;
        cv::Mat normalizedHist;
        cv::normalize(data->bowFeatures, normalizedHist, 0, data->bowFeatures.rows, cv::NORM_MINMAX, -1, cv::Mat());
        trainSamples.push_back(normalizedHist);
        trainResponses.push_back(getClassCode(classes, data->classname));
        delete *it; // clear memory
        it++;
    }
    descriptorsMetadata.clear();
    
    // Training neural network
    std::cout << "Training neural network..." << std::endl;
    start = ofGetElapsedTimeMillis();
    mlp = getTrainedNeuralNetwork(trainSamples, trainResponses);
    std::cout << " Seconds : " << (ofGetElapsedTimeMillis() - start) / 1000.0 << std::endl;
    
    // We can clear memory now
    trainSamples.release();
    trainResponses.release();
    
    // Train FLANN
    std::cout << "Training FLANN..." << std::endl;
    start = ofGetElapsedTimeMillis();
    
    flann = cv::Ptr<cv::FlannBasedMatcher>(new cv::FlannBasedMatcher());
    
    flann->add(vocabulary);
    flann->train();
    std::cout << " Seconds : " << (ofGetElapsedTimeMillis() - start) / 1000.0 << std::endl;
    
    // Reading test set
    std::cout << "Reading test set..." << std::endl;
    start = ofGetElapsedTimeMillis();
    readImagesToTest(files.begin() + (size_t)(files.size() * testRatio), files.end());
    std::cout << " Seconds : " << (ofGetElapsedTimeMillis() - start) / 1000.0 << std::endl;
    
    // Get confusion matrix of the test set
    std::vector<std::vector<int> > confusionMatrix = getConfusionMatrix();
    
    // how accurate is our model
    std::cout << "Confusion matrix " << std::endl;
    printConfusionMatrix(confusionMatrix, classes);
    std::cout << "Accuracy " << getAccuracy(confusionMatrix) << std::endl;
    
    // now save everything
    std::cout << "saving models" << std::endl;
    saveModels(vocabulary, classes);
    
    return 0;
}
Exemple #24
0
bool isLineEdit(QObject *object)
{
    static const QString name("QLineEdit");
    return (getClassName(object) == name);
}
Exemple #25
0
/* Returns a reference to a satTypeValueMap object after differencing
 * data type values given in 'diffTypes' field with respect to
 * reference station data in 'refData' field.
 *
 * @param gData      Data object holding the data.
 */
satTypeValueMap& DoubleOp::Process(satTypeValueMap& gData)
throw(ProcessingException)
{

    try
    {
        // First, we get difference data between two stations
        sdStations.Process(gData);

        // Second, we should check if the elevation of the ref satellite
        // is useable, if not, pick up a new ref satellite with the highest
        // elevation
        bool lookHigestElevation = true;

        if(refSatID.isValid())
        {
            satTypeValueMap::iterator it = gData.find(refSatID);
            if(it!=gData.end())
            {
                double elev = gData(it->first)(TypeID::elevation);
                if(elev > refSatMinElev) lookHigestElevation = false;
            }
        }

        if(lookHigestElevation)
        {
            double maxElevation(0.0);

            // Loop through all satellites in reference station data set,
            // looking for reference satellite
            satTypeValueMap::iterator it;
            for (it = gData.begin(); it != gData.end(); ++it)
            {

                // The satellite with the highest elevation will usually be
                // the reference satellite
                if ( gData((*it).first)(TypeID::elevation) > maxElevation )
                {

                    refSatID = (*it).first;
                    maxElevation = gData((*it).first)(TypeID::elevation);
                }

            }  // end for

        }  // End 'if(lookHigestElevation)'

        // At last, We get the final DD data
        sdSatellites.setRefSat(refSatID);
        sdSatellites.Process(gData);

        return gData;

    }
    catch(Exception& u)
    {
        // Throw an exception if something unexpected happens
        ProcessingException e( getClassName() + ":"
                               + StringUtils::asString( getIndex() ) + ":"
                               + u.what() );

        GPSTK_THROW(e);

    }

}  // End of method 'DoubleOp::Process()'
Exemple #26
0
bool isGroupBox(QObject *object)
{
    static const QString name("QGroupBox");
    return (getClassName(object) == name);
}
Exemple #27
0
template <typename PointT> void
pcl16::VoxelGrid<PointT>::applyFilter (PointCloud &output)
{
  // Has the input dataset been set already?
  if (!input_)
  {
    PCL16_WARN ("[pcl16::%s::applyFilter] No input dataset given!\n", getClassName ().c_str ());
    output.width = output.height = 0;
    output.points.clear ();
    return;
  }

  // Copy the header (and thus the frame_id) + allocate enough space for points
  output.height       = 1;                    // downsampling breaks the organized structure
  output.is_dense     = true;                 // we filter out invalid points

  Eigen::Vector4f min_p, max_p;
  // Get the minimum and maximum dimensions
  if (!filter_field_name_.empty ()) // If we don't want to process the entire cloud...
    getMinMax3D<PointT>(input_, filter_field_name_, static_cast<float> (filter_limit_min_), static_cast<float> (filter_limit_max_), min_p, max_p, filter_limit_negative_);
  else
    getMinMax3D<PointT>(*input_, min_p, max_p);

  // Compute the minimum and maximum bounding box values
  min_b_[0] = static_cast<int> (floor (min_p[0] * inverse_leaf_size_[0]));
  max_b_[0] = static_cast<int> (floor (max_p[0] * inverse_leaf_size_[0]));
  min_b_[1] = static_cast<int> (floor (min_p[1] * inverse_leaf_size_[1]));
  max_b_[1] = static_cast<int> (floor (max_p[1] * inverse_leaf_size_[1]));
  min_b_[2] = static_cast<int> (floor (min_p[2] * inverse_leaf_size_[2]));
  max_b_[2] = static_cast<int> (floor (max_p[2] * inverse_leaf_size_[2]));

  // Compute the number of divisions needed along all axis
  div_b_ = max_b_ - min_b_ + Eigen::Vector4i::Ones ();
  div_b_[3] = 0;

  // Set up the division multiplier
  divb_mul_ = Eigen::Vector4i (1, div_b_[0], div_b_[0] * div_b_[1], 0);

  int centroid_size = 4;
  if (downsample_all_data_)
    centroid_size = boost::mpl::size<FieldList>::value;

  // ---[ RGB special case
  std::vector<sensor_msgs::PointField> fields;
  int rgba_index = -1;
  rgba_index = pcl16::getFieldIndex (*input_, "rgb", fields);
  if (rgba_index == -1)
    rgba_index = pcl16::getFieldIndex (*input_, "rgba", fields);
  if (rgba_index >= 0)
  {
    rgba_index = fields[rgba_index].offset;
    centroid_size += 3;
  }

  std::vector<cloud_point_index_idx> index_vector;
  index_vector.reserve(input_->points.size());

  // If we don't want to process the entire cloud, but rather filter points far away from the viewpoint first...
  if (!filter_field_name_.empty ())
  {
    // Get the distance field index
    std::vector<sensor_msgs::PointField> fields;
    int distance_idx = pcl16::getFieldIndex (*input_, filter_field_name_, fields);
    if (distance_idx == -1)
      PCL16_WARN ("[pcl16::%s::applyFilter] Invalid filter field name. Index is %d.\n", getClassName ().c_str (), distance_idx);

    // First pass: go over all points and insert them into the index_vector vector
    // with calculated idx. Points with the same idx value will contribute to the
    // same point of resulting CloudPoint
    for (unsigned int cp = 0; cp < static_cast<unsigned int> (input_->points.size ()); ++cp)
    {
      if (!input_->is_dense)
        // Check if the point is invalid
        if (!pcl_isfinite (input_->points[cp].x) || 
            !pcl_isfinite (input_->points[cp].y) || 
            !pcl_isfinite (input_->points[cp].z))
          continue;

      // Get the distance value
      const uint8_t* pt_data = reinterpret_cast<const uint8_t*> (&input_->points[cp]);
      float distance_value = 0;
      memcpy (&distance_value, pt_data + fields[distance_idx].offset, sizeof (float));

      if (filter_limit_negative_)
      {
        // Use a threshold for cutting out points which inside the interval
        if ((distance_value < filter_limit_max_) && (distance_value > filter_limit_min_))
          continue;
      }
      else
      {
        // Use a threshold for cutting out points which are too close/far away
        if ((distance_value > filter_limit_max_) || (distance_value < filter_limit_min_))
          continue;
      }
      
      int ijk0 = static_cast<int> (floor (input_->points[cp].x * inverse_leaf_size_[0]) - min_b_[0]);
      int ijk1 = static_cast<int> (floor (input_->points[cp].y * inverse_leaf_size_[1]) - min_b_[1]);
      int ijk2 = static_cast<int> (floor (input_->points[cp].z * inverse_leaf_size_[2]) - min_b_[2]);

      // Compute the centroid leaf index
      int idx = ijk0 * divb_mul_[0] + ijk1 * divb_mul_[1] + ijk2 * divb_mul_[2];
      index_vector.push_back (cloud_point_index_idx (static_cast<unsigned int> (idx), cp));
    }
  }
  // No distance filtering, process all data
  else
  {
    // First pass: go over all points and insert them into the index_vector vector
    // with calculated idx. Points with the same idx value will contribute to the
    // same point of resulting CloudPoint
    for (unsigned int cp = 0; cp < static_cast<unsigned int> (input_->points.size ()); ++cp)
    {
      if (!input_->is_dense)
        // Check if the point is invalid
        if (!pcl_isfinite (input_->points[cp].x) || 
            !pcl_isfinite (input_->points[cp].y) || 
            !pcl_isfinite (input_->points[cp].z))
          continue;

      int ijk0 = static_cast<int> (floor (input_->points[cp].x * inverse_leaf_size_[0]) - min_b_[0]);
      int ijk1 = static_cast<int> (floor (input_->points[cp].y * inverse_leaf_size_[1]) - min_b_[1]);
      int ijk2 = static_cast<int> (floor (input_->points[cp].z * inverse_leaf_size_[2]) - min_b_[2]);

      // Compute the centroid leaf index
      int idx = ijk0 * divb_mul_[0] + ijk1 * divb_mul_[1] + ijk2 * divb_mul_[2];
      index_vector.push_back (cloud_point_index_idx (static_cast<unsigned int> (idx), cp));
    }
  }

  // Second pass: sort the index_vector vector using value representing target cell as index
  // in effect all points belonging to the same output cell will be next to each other
  std::sort (index_vector.begin (), index_vector.end (), std::less<cloud_point_index_idx> ());

  // Third pass: count output cells
  // we need to skip all the same, adjacenent idx values
  unsigned int total = 0;
  unsigned int index = 0;
  while (index < index_vector.size ()) 
  {
    unsigned int i = index + 1;
    while (i < index_vector.size () && index_vector[i].idx == index_vector[index].idx) 
      ++i;
    ++total;
    index = i;
  }

  // Fourth pass: compute centroids, insert them into their final position
  output.points.resize (total);
  if (save_leaf_layout_)
  {
    try
    { 
      // Resizing won't reset old elements to -1.  If leaf_layout_ has been used previously, it needs to be re-initialized to -1
      uint32_t new_layout_size = div_b_[0]*div_b_[1]*div_b_[2];
      //This is the number of elements that need to be re-initialized to -1
      uint32_t reinit_size = std::min (static_cast<unsigned int> (new_layout_size), static_cast<unsigned int> (leaf_layout_.size()));
      for (uint32_t i = 0; i < reinit_size; i++)
      {
        leaf_layout_[i] = -1;
      }        
      leaf_layout_.resize (new_layout_size, -1);           
    }
    catch (std::bad_alloc&)
    {
      throw PCLException("VoxelGrid bin size is too low; impossible to allocate memory for layout", 
        "voxel_grid.hpp", "applyFilter");	
    }
    catch (std::length_error&)
    {
      throw PCLException("VoxelGrid bin size is too low; impossible to allocate memory for layout", 
        "voxel_grid.hpp", "applyFilter");	
    }
  }
  
  index = 0;
  Eigen::VectorXf centroid = Eigen::VectorXf::Zero (centroid_size);
  Eigen::VectorXf temporary = Eigen::VectorXf::Zero (centroid_size);

  for (unsigned int cp = 0; cp < index_vector.size ();)
  {
    // calculate centroid - sum values from all input points, that have the same idx value in index_vector array
    if (!downsample_all_data_) 
    {
      centroid[0] = input_->points[index_vector[cp].cloud_point_index].x;
      centroid[1] = input_->points[index_vector[cp].cloud_point_index].y;
      centroid[2] = input_->points[index_vector[cp].cloud_point_index].z;
    }
    else 
    {
      // ---[ RGB special case
      if (rgba_index >= 0)
      {
        // Fill r/g/b data, assuming that the order is BGRA
        pcl16::RGB rgb;
        memcpy (&rgb, reinterpret_cast<const char*> (&input_->points[index_vector[cp].cloud_point_index]) + rgba_index, sizeof (RGB));
        centroid[centroid_size-3] = rgb.r;
        centroid[centroid_size-2] = rgb.g;
        centroid[centroid_size-1] = rgb.b;
      }
      pcl16::for_each_type <FieldList> (NdCopyPointEigenFunctor <PointT> (input_->points[index_vector[cp].cloud_point_index], centroid));
    }

    unsigned int i = cp + 1;
    //++Kadir
    std::vector<int> tmp;
		tmp.push_back (index_vector[cp].cloud_point_index);
    //--Kadir
    while (i < index_vector.size () && index_vector[i].idx == index_vector[cp].idx) 
    {
      //++Kadir
//        map_gid_2_pc_indices_[index_vector[i].idx].push_back(index_vector[i].cloud_point_index);
      tmp.push_back (index_vector[i].cloud_point_index);
      //--Kadir    
      if (!downsample_all_data_) 
      {
        centroid[0] += input_->points[index_vector[i].cloud_point_index].x;
        centroid[1] += input_->points[index_vector[i].cloud_point_index].y;
        centroid[2] += input_->points[index_vector[i].cloud_point_index].z;
      }
      else 
      {
        // ---[ RGB special case
        if (rgba_index >= 0)
        {
          // Fill r/g/b data, assuming that the order is BGRA
          pcl16::RGB rgb;
          memcpy (&rgb, reinterpret_cast<const char*> (&input_->points[index_vector[i].cloud_point_index]) + rgba_index, sizeof (RGB));
          temporary[centroid_size-3] = rgb.r;
          temporary[centroid_size-2] = rgb.g;
          temporary[centroid_size-1] = rgb.b;
        }
        pcl16::for_each_type <FieldList> (NdCopyPointEigenFunctor <PointT> (input_->points[index_vector[i].cloud_point_index], temporary));
        centroid += temporary;
      }
      ++i;
    }
    map_gid_2_pc_indices_[index] = tmp;        

    // index is centroid final position in resulting PointCloud
    if (save_leaf_layout_)
      leaf_layout_[index_vector[cp].idx] = index;

    centroid /= static_cast<float> (i - cp);

    // store centroid
    // Do we need to process all the fields?
    if (!downsample_all_data_) 
    {
      output.points[index].x = centroid[0];
      output.points[index].y = centroid[1];
      output.points[index].z = centroid[2];
    }
    else 
    {
      pcl16::for_each_type<FieldList> (pcl16::NdCopyEigenPointFunctor <PointT> (centroid, output.points[index]));
      // ---[ RGB special case
      if (rgba_index >= 0) 
      {
        // pack r/g/b into rgb
        float r = centroid[centroid_size-3], g = centroid[centroid_size-2], b = centroid[centroid_size-1];
        int rgb = (static_cast<int> (r) << 16) | (static_cast<int> (g) << 8) | static_cast<int> (b);
        memcpy (reinterpret_cast<char*> (&output.points[index]) + rgba_index, &rgb, sizeof (float));
      }
    }
    cp = i;
    ++index;
  }
  output.width = static_cast<uint32_t> (output.points.size ());
}
Exemple #28
0
bool isLabel(QObject *object)
{
    static const QString name("QLabel");
    return (getClassName(object) == name);
}
Exemple #29
0
QString Namer::getClassName( const Schema::Element &element )
{
  return getClassName( element.name() );
}
DXInputSystem::~DXInputSystem( void )
{
	Log::Info(getClassName(), "Shutting Down");

	Log::Info(getClassName(), "Finished");
}