コード例 #1
0
void KCommonDecoration::menuButtonPressed()
{
    static QTime* t = NULL;
    static KCommonDecoration* lastClient = NULL;
    if (t == NULL)
        t = new QTime;
    bool dbl = (lastClient==this && t->elapsed() <= QApplication::doubleClickInterval());
    lastClient = this;
    t->start();
    if (!dbl || !decorationBehaviour(DB_MenuClose) ) {
        QRect menuRect = m_button[MenuButton]->rect();
        QPoint menutop = m_button[MenuButton]->mapToGlobal(menuRect.topLeft());
        QPoint menubottom = m_button[MenuButton]->mapToGlobal(menuRect.bottomRight())+QPoint(0,2);
        KDecorationFactory* f = factory();
        showWindowMenu(QRect(menutop, menubottom));
        if( !f->exists( this )) // 'this' was deleted
            return;
        m_button[MenuButton]->setDown(false);
    }
    else
        closing = true;
}
コード例 #2
0
bool pawsRadioButtonGroup::SetActive(const char* widgetName)
{
    bool okFlag = false;
    for(size_t x=0; x < children.GetSize(); x++)
    {
        csString factory(children[x]->GetType());
        if(factory == "pawsRadioButton")
        {
            pawsRadioButton* radButton = (pawsRadioButton*)children[x];
            if(strcmp(children[x]->GetName(), widgetName))
            {
                radButton->SetState(false);
            }
            else
            {
                okFlag = true;
                radButton->SetState(true);
            }
        }
    }
    return okFlag;
}
コード例 #3
0
static void test_factory(skiatest::Reporter* reporter, SkImageCache* cache, SkData* encodedData,
                       const SkBitmap& origBitmap) {
    SkBitmapFactory factory(&SkImageDecoder::DecodeMemoryToTarget);
    factory.setImageCache(cache);
    SkAutoTDelete<SkBitmap> bitmapFromFactory(SkNEW(SkBitmap));
    bool success = factory.installPixelRef(encodedData, bitmapFromFactory.get());
    // This assumes that if the encoder worked, the decoder should also work, so the above call
    // should not fail.
    REPORTER_ASSERT(reporter, success);
    assert_bounds_equal(reporter, origBitmap, *bitmapFromFactory.get());

    SkPixelRef* pixelRef = bitmapFromFactory->pixelRef();
    REPORTER_ASSERT(reporter, pixelRef != NULL);
    if (NULL == cache) {
        // This assumes that installPixelRef called lockPixels.
        REPORTER_ASSERT(reporter, bitmapFromFactory->readyToDraw());
    } else {
        // Lazy decoding
        REPORTER_ASSERT(reporter, !bitmapFromFactory->readyToDraw());
        SkLazyPixelRef* lazyRef = static_cast<SkLazyPixelRef*>(pixelRef);
        intptr_t cacheID = lazyRef->getCacheId();
        REPORTER_ASSERT(reporter, cache->getMemoryStatus(cacheID)
                                  != SkImageCache::kPinned_MemoryStatus);
        {
            SkAutoLockPixels alp(*bitmapFromFactory.get());
            REPORTER_ASSERT(reporter, bitmapFromFactory->readyToDraw());
            cacheID = lazyRef->getCacheId();
            REPORTER_ASSERT(reporter, cache->getMemoryStatus(cacheID)
                                      == SkImageCache::kPinned_MemoryStatus);
        }
        REPORTER_ASSERT(reporter, !bitmapFromFactory->readyToDraw());
        REPORTER_ASSERT(reporter, cache->getMemoryStatus(cacheID)
                                  != SkImageCache::kPinned_MemoryStatus);
        bitmapFromFactory.free();
        REPORTER_ASSERT(reporter, cache->getMemoryStatus(cacheID)
                                  == SkImageCache::kFreed_MemoryStatus);
    }
}
コード例 #4
0
ファイル: tSTK_IO.cpp プロジェクト: gitter-badger/quinoa
TEUCHOS_UNIT_TEST(tSTK_IO, exodus_factory_transient_fields)
{
   STK_ExodusReaderFactory factory("meshes/basic.gen");
   RCP<STK_Interface> mesh = factory.buildUncommitedMesh(MPI_COMM_WORLD);
   mesh->addSolutionField("u","block_1");
   mesh->addSolutionField("T","block_1");
   mesh->addSolutionField("T","block_2");
   factory.completeMeshConstruction(*mesh,MPI_COMM_WORLD);

   std::map<std::string,Teuchos::RCP<std::vector<std::size_t> > > localIds; 
   buildLocalIds(*mesh,localIds);

   FieldContainer vert0, vert1;
   out << "get vertices" << std::endl;
   mesh->getElementVertices(*localIds["block_1"],vert0);
   mesh->getElementVertices(*localIds["block_2"],vert1);

   FieldContainer ublock0, tblock0, tblock1;
   ublock0.resize(localIds["block_1"]->size(),4);
   tblock0.resize(localIds["block_1"]->size(),4);
   tblock1.resize(localIds["block_2"]->size(),4);

   mesh->setupTransientExodusFile("transient_exo.exo");

   out << "assigning 4.5" << std::endl;
   {
      assignBlock(ublock0,vert0,6.0);
      assignBlock(tblock0,vert0,7.0);
      assignBlock(tblock1,vert1,8.0);

      mesh->setSolutionFieldData("u","block_1",*localIds["block_1"],ublock0);
      mesh->setSolutionFieldData("T","block_1",*localIds["block_1"],tblock0);
      mesh->setSolutionFieldData("T","block_2",*localIds["block_2"],tblock1);
   }

   out << "write to exodus: 4.5" << std::endl;
   mesh->writeToExodus(4.5);
}
コード例 #5
0
int	main(int argc, char *argv[]) {
	int	c;
	while (EOF != (c = getopt(argc, argv, "d")))
		switch (c) {
		case 'd':
			debuglevel = LOG_DEBUG;
			break;
		}

	// create a Chart factory
	CatalogPtr 	catalog = CatalogFactory::get(CatalogFactory::Combined,
					"/usr/local/starcatalogs");
	TurbulencePointSpreadFunction   psf(2);
	ChartFactory    factory(catalog, psf, 14, 100);
	debug(LOG_DEBUG, DEBUG_LOG, 0, "chart factory created");

	// create an Image Normalizer
	ImageNormalizer normalizer(factory);

	// prepare the initial transformation
	Projection      projection(M_PI * 162 / 180, Point(838, 182), 0.98);
	debug(LOG_DEBUG, DEBUG_LOG, 0, "projection: %s",
	projection.toString().c_str());

	// get the image from the input file
	FITSin  in("andromeda-base.fits");
	ImagePtr        imageptr = in.read();

	// apply the normalizer to the 
	debug(LOG_DEBUG, DEBUG_LOG, 0, "apply normalizer");
	RaDec   center = normalizer(imageptr, projection);
	debug(LOG_DEBUG, DEBUG_LOG, 0, "true center: %s",
	center.toString().c_str());
	debug(LOG_DEBUG, DEBUG_LOG, 0, "transformation: %s",
	projection.toString().c_str());

	return EXIT_SUCCESS;
}
コード例 #6
0
  ProbabilisticModelPtr TrainVariableLengthMarkovChain::create( ProbabilisticModelParameters & parameters, const std::vector<std::string> & training_set, double & loglikelihood, int & sample_size) const {
        ProbabilisticModelParameterValuePtr alphabet_parameter =
                        parameters.getMandatoryParameterValue("alphabet");
        ProbabilisticModelParameterValuePtr delta_parameter =
                        parameters.getMandatoryParameterValue("cut");
        if ((alphabet_parameter == NULL)|| (delta_parameter == NULL)) {
                std::cerr << help() << std::endl;
                exit(-1);
        }
        AlphabetPtr alphabet = AlphabetPtr(new Alphabet());
        alphabet->initializeFromVector(alphabet_parameter->getStringVector());
        SequenceFactory factory(alphabet);
        SequenceEntryList sample_set;
        for(int i = 0; i < (int)sample_set.size(); i++) {
          Sequence s = factory.createSequence(training_set[i]);
          SequenceEntryPtr e =  SequenceEntryPtr  (new SequenceEntry(alphabet));
          e->setSequence(s);
          sample_set.push_back(e);
        }

        ContextTreePtr tree = ContextTreePtr(new ContextTree(alphabet));
        tree->initializeContextTreeRissanen(sample_set);
        tree->pruneTree(delta_parameter->getDouble());
        tree->removeContextNotUsed();
        tree->normalize();
        VariableLengthMarkovChainPtr m = VariableLengthMarkovChainPtr(
                        new VariableLengthMarkovChain(tree));
        m->setAlphabet(alphabet);
        loglikelihood = 0.0;
        sample_size = 0;
        for (int i = 0; i < (int) sample_set.size(); i++) {
                loglikelihood
                  += m->evaluate((sample_set[i]->getSequence()), 0, (sample_set[i]->getSequence()).size() - 1);
                sample_size += (sample_set[i]->getSequence()).size();
        }
        return m;

  }
コード例 #7
0
ファイル: Acceptor.cpp プロジェクト: andrija-hers/quickfix
void Acceptor::initialize() throw ( ConfigError )
{
  std::set < SessionID > sessions = m_settings.getSessions();
  std::set < SessionID > ::iterator i;

  if ( !sessions.size() )
    throw ConfigError( "No sessions defined" );

  SessionFactory factory( m_application, m_messageStoreFactory,
                          m_pLogFactory );

  for ( i = sessions.begin(); i != sessions.end(); ++i )
  {
    if ( m_settings.get( *i ).getString( CONNECTION_TYPE ) == "acceptor" )
    {
      m_sessionIDs.insert( *i );
      m_sessions[ *i ] = factory.create( *i, m_settings.get( *i ) );
    }
  }

  if ( !m_sessions.size() )
    throw ConfigError( "No sessions defined for acceptor" );
}
コード例 #8
0
	// just like the Initiator::initialize function
	void AsioSocketInitiator::initialize()
	{
		std::set < SessionID > sessions = m_settings.getSessions();
		std::set < SessionID > ::iterator i;

		if ( !sessions.size() )
			throw ConfigError( "No sessions defined" );

		SessionFactory factory( m_application, m_messageStoreFactory,
			m_pLogFactory );

		for ( i = sessions.begin(); i != sessions.end(); ++i )
		{
			if ( m_settings.get( *i ).getString( m_connection_type_label ).compare ( m_initiator_label ) == 0 )
			{
				m_sessions[ *i ] = factory.create( *i, m_settings.get( *i ) );
				ConnectSession ( *i, m_settings.get( *i ) );
			}
		}

		if ( !m_sessions.size() )
			throw ConfigError( "No sessions defined for initiator" );
	}
コード例 #9
0
CoaSettingsWidgetChangeDebug::CoaSettingsWidgetChangeDebug(QWidget * const parent , Qt::WFlags f )
: CoaSettingsWidget (parent, f)
,actionModel(0)
{
   BEGIN;

   //Create the central form
   Q_INIT_RESOURCE(tools);
   CoaFormFactory factory(this);
   factory.formBuild(":/tools/settings/coachangedebug.ui");
   setIcon(":/tools/settings/icons/debug.png");

   initMainButtons();
   initDefaultModeButtons();

   loadModel();
   assert(actionModel);

   initTableView();
   setShortName( tr("Debug") );
   setGroupName( shortName() );

}
コード例 #10
0
ファイル: Web.cpp プロジェクト: lmurray/kwin
  void
WebClient::init()
{
  // title height
  const int textVMargin   = 2;
  QFontMetrics fm(options()->font(isActive(), isToolWindow()));

  // border size
  switch(options()->preferredBorderSize( factory())) {
    case BorderLarge:
      borderSize_ = 8;
      break;
    case BorderVeryLarge:
      borderSize_ = 12;
      break;
    case BorderHuge:
      borderSize_ = 18;
      break;
    case BorderVeryHuge:
      borderSize_ = 27;
      break;
    case BorderOversized:
      borderSize_ = 40;
      break;
    case BorderNormal:
    default:
      borderSize_ = 4;
  }
  titleHeight_ = qMax(qMax(14, fm.height() + textVMargin * 2), borderSize_);
  if (0 != titleHeight_ % 2)
    titleHeight_ += 1;

  KConfig c("kwinwebrc");
  shape_ = c.group("General").readEntry("Shape", true);

  KCommonDecoration::init();
}
コード例 #11
0
bool MultipleDocumentsReadingModeSelectorController::mergeDocumentOption(const FormatDetectionResult& formatResult, QMap<QString, qint64>* headerSequenceLengths){
    QVariantMap docHints = formatResult.rawDataCheckResult.properties;
    if(formatResult.format == NULL){
        return false;
    }
    if(formatResult.format->getFormatId() == BaseDocumentFormats::PLAIN_GENBANK){
        if(docHints.value(RawDataCheckResult_Sequence) == false){
            static const int MAX_LINE = 8192;
            char buff[MAX_LINE + 1] = {0};

            QScopedPointer<LocalFileAdapterFactory> factory( new LocalFileAdapterFactory());
            QScopedPointer<IOAdapter> io(factory->createIOAdapter());
            if(!io->open(formatResult.url, IOAdapterMode_Read)){
                return false;
            }
            bool terminatorFound = false;
            io->readLine(buff, MAX_LINE, &terminatorFound);
            if(!terminatorFound){
                return false;
            }
            QString line = QString(QByteArray(buff));
            QStringList words = line.split(QRegExp("\\s"), QString::SkipEmptyParts);
            if(words.size() < 3){ // origin len not defined
                return false;
            }
            bool isLenDefined = false;
            qint64 seqLen = words[2].toLongLong(&isLenDefined); 
            
            if(!isLenDefined || seqLen <= 0){
                return false;
            }
            (*headerSequenceLengths)[formatResult.url.getURLString()] = seqLen;
            return true;
        }
    }
    return docHints.value(RawDataCheckResult_Sequence).toBool();
}
コード例 #12
0
CoaToolsSqlBrowser::CoaToolsSqlBrowser()
: CoaToolWindow("CoaToolsSqlBrowser", 0)
, m_isValid(false)
, m_sqlEdit(0)
, m_table(0)
, m_connectionWidget(0)
, m_submitButton(0)
, m_clearButton(0)
{
   BEGIN;

   //Create the central form
   Q_INIT_RESOURCE(tools);
   CoaFormFactory factory(this);
   m_isValid = factory.formBuild(":/tools/sqlbrowser/coasqlbrowser.ui");
   if (m_isValid == true) {
      m_isValid = setInternalGuiPointers();
   }
   setWindowTitle(tr("COA SQL Browser"));

   if (m_isValid == true) {
      if (CoaSqlDatabase::drivers().isEmpty())
         QMessageBox::information(this, tr("No database drivers found"),
                                       tr("This Tools needs Coa SQL Database drivers. Please check your installation!"));
      else {
         QMetaObject::invokeMethod(this, "addConnection", Qt::QueuedConnection);
         QMetaObject::invokeMethod(this, "connectSignals", Qt::QueuedConnection);
      }
      emit statusMessage(tr("Ready."));
   } else {
      emit statusMessage(tr("Error while loading"));
   }


   REGISTERSINGLETON("CoaToolsSqlBrowser");
   readSettings();
}
コード例 #13
0
ファイル: testfactory2.C プロジェクト: svarshavchik/libcxx
static void testfactory2()
{
	std::cout << "Test factory 2" << std::endl;

	{
		std::pair<LIBCXX_NAMESPACE::fd, LIBCXX_NAMESPACE::fd>
			p=LIBCXX_NAMESPACE::fd::base::pipe();

		r=p.first;
		w=p.second;
	}

	typedef LIBCXX_NAMESPACE::eventfactory<std::string, int > factory_t;

	{
		factory_t factory(factory_t::create());

		LIBCXX_NAMESPACE::ptr<inteventhandlerObj>
			ev=LIBCXX_NAMESPACE::ptr<inteventhandlerObj>::create();

		LIBCXX_NAMESPACE::eventregistrationptr er=
			factory->registerHandler("foo", ev);

		std::cout << "Starting subthread" << std::endl;

		LIBCXX_NAMESPACE::run(LIBCXX_NAMESPACE::ref<myThread>
				    ::create(&er));

		char buffer[1];

		r->read(buffer, 1);
		std::cout << "Write side of the pipe is closed"
			  << std::endl;
		factory->event("foo", 1);
	}
	std::cout << "Factory destroyed" << std::endl;
}
コード例 #14
0
    void TestReadOnlyDistributedVector()
    {
        DistributedVectorFactory factory(10);
        Vec petsc_vec = factory.CreateVec();

        {
            DistributedVector distributed_vector = factory.CreateDistributedVector(petsc_vec);
            for (DistributedVector::Iterator index = distributed_vector.Begin();
                    index!= distributed_vector.End();
                    ++index)
            {
                distributed_vector[index] = (double) PetscTools::GetMyRank();
            }
       }

#if (PETSC_VERSION_MAJOR == 3 && PETSC_VERSION_MINOR >= 6) //PETSc 3.6 or later
        // Lock the vector so that modern PETSc (3.6) won't want to change it
        EXCEPT_IF_NOT(VecLockPush(petsc_vec) == 0);
#endif
        {
            DistributedVector distributed_vector_read = factory.CreateDistributedVector(petsc_vec, true);

            for (DistributedVector::Iterator index = distributed_vector_read.Begin();
                    index!= distributed_vector_read.End();
                    ++index)
            {
                TS_ASSERT_EQUALS(distributed_vector_read[index], (double) PetscTools::GetMyRank());
                distributed_vector_read[index] = 2.0;
            }
        }
#if (PETSC_VERSION_MAJOR == 3 && PETSC_VERSION_MINOR >= 6) //PETSc 3.6 or later
        // Take the lock back
        EXCEPT_IF_NOT(VecLockPop(petsc_vec) == 0);
#endif

        PetscTools::Destroy(petsc_vec);
    }
コード例 #15
0
ファイル: KoDockerManager.cpp プロジェクト: KDE/koffice
void KoDockerManager::newOptionWidgets(const QMap<QString, QWidget *> &optionWidgetMap)
{
    d->removeDockers();

    // Now show new active dockers (maybe even create) and show in docker menu
    QMap<QString, QWidget*>::ConstIterator iter = optionWidgetMap.constBegin();
    for (;iter != optionWidgetMap.constEnd(); ++iter) {
        const QString name = iter.value()->objectName();
        if (name.isEmpty()) {
            kError(30004) << "tooldocker widget have no name " << iter.key();
            Q_ASSERT(!name.isEmpty());
            continue; // skip this docker in release build when assert don't crash
        }

        KoToolDocker *td = d->toolDockerMap.value(name);
        if (!td) {
            ToolDockerFactory factory(name);
            td = qobject_cast<KoToolDocker*>(d->mainWindow->createDockWidget(&factory));
            Q_ASSERT(td);
            d->toolDockerMap[name] = td;
            d->toolDockerVisibilityMap[name] =  true;
        }
        td->setEnabled(true);
        td->setWindowTitle(iter.key());
        td->newOptionWidget(iter.value());
        d->mainWindow->restoreDockWidget(td);
        //kDebug() << name << " " << d->toolDockerVisibilityMap[name];
        td->setVisible(d->toolDockerVisibilityMap[name]);
        //kDebug() << td->isVisible();
        td->toggleViewAction()->setVisible(true);
        d->activeToolDockerMap[name] = td;
        if (d->toolDockerRaisedMap.value(name)) {
            td->raise();
        }
    }
}
コード例 #16
0
cloth::Solver* ClothingScene::getClothSolver(bool useCuda)
{
	ClothFactory factory(NULL, NULL);
#ifdef PX_WINDOWS
	if (useCuda)
	{
		factory = mGpuFactory;
	}
	else
#else
	PX_UNUSED(useCuda);
#endif
	{
		factory = mCpuFactory;
	}

	PX_ASSERT(factory.factory != NULL);
	if (factory.factory != NULL)
	{
		return mSimulationTask->getSolver(factory);
	}

	return NULL;
}
コード例 #17
0
ファイル: at.cpp プロジェクト: filgood/fixfeed
int main( int argc, char** argv )
{
  std::string file;

  if ( getopt( argc, argv, "+f:" ) == 'f' )
    file = optarg;
  else
  {
    std::cout << "usage: " << argv[ 0 ]
    << " -f FILE" << std::endl;
    return 1;
  }

  try
  {
    FIX::SessionSettings settings( file );
    Application application;
    FIX::FileStoreFactory factory( "store" );

    AcceptorPtr pAcceptor;
    pAcceptor = std::auto_ptr < FIX::Acceptor >
                      ( new FIX::SocketAcceptor
                        ( application, factory, settings ) );

    pAcceptor->start();
    while ( true ) FIX::process_sleep( 1 );
    pAcceptor->stop();
  }
  catch ( std::exception & e )
  {
    std::cout << e.what();
    return 2;
  }

  return 0;
}
コード例 #18
0
ファイル: frame_consumer.cpp プロジェクト: yakatape/Server
safe_ptr<core::frame_consumer> create_consumer(const std::vector<std::wstring>& params)
{
	if(params.empty())
		BOOST_THROW_EXCEPTION(invalid_argument() << arg_name_info("params") << arg_value_info(""));
	
	auto consumer = frame_consumer::empty();
	std::any_of(g_factories.begin(), g_factories.end(), [&](const consumer_factory_t& factory) -> bool
		{
			try
			{
				consumer = factory(params);
			}
			catch(...)
			{
				CASPAR_LOG_CURRENT_EXCEPTION();
			}
			return consumer != frame_consumer::empty();
		});

	if(consumer == frame_consumer::empty())
		BOOST_THROW_EXCEPTION(file_not_found() << msg_info("No match found for supplied commands. Check syntax."));

	return consumer;
}
コード例 #19
0
TemporaryRef<PathBuilder>
DrawTargetD2D1::CreatePathBuilder(FillRule aFillRule) const
{
  RefPtr<ID2D1PathGeometry> path;
  HRESULT hr = factory()->CreatePathGeometry(byRef(path));

  if (FAILED(hr)) {
    gfxWarning() << *this << ": Failed to create Direct2D Path Geometry. Code: " << hr;
    return nullptr;
  }

  RefPtr<ID2D1GeometrySink> sink;
  hr = path->Open(byRef(sink));
  if (FAILED(hr)) {
    gfxWarning() << *this << ": Failed to access Direct2D Path Geometry. Code: " << hr;
    return nullptr;
  }

  if (aFillRule == FillRule::FILL_WINDING) {
    sink->SetFillMode(D2D1_FILL_MODE_WINDING);
  }

  return new PathBuilderD2D(sink, path, aFillRule);
}
コード例 #20
0
    void Test1()
    {
        const unsigned SIZE = 1000;
        const unsigned REPETITIONS = 10;

        // Create a distibuted vector
        DistributedVectorFactory factory(SIZE);

        Vec petsc_vec = factory.CreateVec();
        DistributedVector distributed_vector = factory.CreateDistributedVector(petsc_vec);
        for (DistributedVector::Iterator index = distributed_vector.Begin();
             index!= distributed_vector.End();
             ++index)
        {
            distributed_vector[index] = -(double)(index.Local*index.Global);
        }
        distributed_vector.Restore();

        // Set up a parallel writer
        ParallelColumnDataWriter parallel_writer("TestParallelWriterPerformance","ParallelColumnWriter");
        unsigned time_var_id = parallel_writer.DefineUnlimitedDimension("Time","msecs");
        parallel_writer.DefineFixedDimension("Node","dimensionless", SIZE);
        unsigned var1_id = parallel_writer.DefineVariable("Var1","LightYears");
        parallel_writer.EndDefineMode();

        // Write multiple times
        for (unsigned i=0; i<REPETITIONS; i++)
        {
            double time = (double)i;
            parallel_writer.PutVariable(time_var_id, time);
            parallel_writer.PutVector(var1_id, petsc_vec);
            parallel_writer.AdvanceAlongUnlimitedDimension();
        }

        PetscTools::Destroy(petsc_vec);
    }
コード例 #21
0
ファイル: test_Matrix.cpp プロジェクト: 00liujj/trilinos
int test_Matrix::test3()
{
#ifdef HAVE_FEI_FETI
  testData* testdata = new testData(localProc_, numProcs_);
  std::vector<int>& idTypes = testdata->idTypes;
  std::vector<int>& ids = testdata->ids;

  fei::SharedPtr<FiniteElementData> fedata(new FETI_DP_FiniteElementData(comm_));

  std::string paramstr("debugOutput .");
  char* param = const_cast<char*>(paramstr.c_str());

  CHK_ERR( fedata->parameters(1, &param) );

  fei::SharedPtr<fei::Factory> factory(new snl_fei::Factory(fedata, idTypes[0]));

  fei::SharedPtr<fei::VectorSpace> vectorSpacePtr =
    test_VectorSpace::create_VectorSpace(comm_,
					 testdata, localProc_, numProcs_,
					 false, false, "U_FEMat", factory);

  fei::SharedPtr<fei::MatrixGraph> matrixGraphPtr =
    test_MatrixGraph::create_MatrixGraph(testdata, localProc_, numProcs_,
					 false, false, "U_FEMat", vectorSpacePtr,
					 factory);

  CHK_ERR( matrixGraphPtr->initComplete() );

  fei::SharedPtr<fei::Vector> vec_fed = factory->createVector(vectorSpacePtr);

  fei::SharedPtr<fei::Matrix> mat_fed = factory->createMatrix(matrixGraphPtr);

  fei::Matrix_Impl<FiniteElementData>* smat2 = 
    dynamic_cast<fei::Matrix_Impl<FiniteElementData>*>(mat_fed.get());
  if (smat2 == NULL) {
    ERReturn(-1);
  }

  int blockID=0;
  int numIndices = matrixGraphPtr->getConnectivityNumIndices(blockID);

  std::vector<int> indicesArray(numIndices);
  int* indicesPtr = &indicesArray[0];

  int checkNumIndices = 0;
  CHK_ERR( matrixGraphPtr->getConnectivityIndices(blockID, 0,
					     numIndices, indicesPtr,
					     checkNumIndices) );

  std::vector<double> data(ids.size(), 1.0);
  double* dptr = &data[0];
  std::vector<double*> coefPtrs(ids.size(), dptr);

  CHK_ERR( mat_fed->sumIn(blockID, 0, &coefPtrs[0]) );

  CHK_ERR( vec_fed->sumIn(blockID, 0, &data[0]) );

  CHK_ERR( mat_fed->gatherFromOverlap() );

  CHK_ERR( fedata->loadComplete() );


  delete testdata;

  MPI_Barrier(comm_);

#endif  //HAVE_FEI_FETI

  return(0);
}
コード例 #22
0
ファイル: EBLevelAdvect.cpp プロジェクト: rsnemmen/Chombo
void
EBLevelAdvect::
advectToFacesBCG(LevelData< EBFluxFAB >&                         a_extrapState,
                 const LevelData< EBCellFAB >&                   a_consState,
                 const LevelData< EBCellFAB >&                   a_normalVel,
                 const LevelData< EBFluxFAB >&                   a_advectionVel,
                 const LevelData< EBCellFAB >*                   a_consStateCoarseOld,
                 const LevelData< EBCellFAB >*                   a_consStateCoarseNew,
                 const LevelData< EBCellFAB >*                   a_normalVelCoarseOld,
                 const LevelData< EBCellFAB >*                   a_normalVelCoarseNew,
                 const Real&                                     a_timeCoarseOld,
                 const Real&                                     a_timeCoarseNew,
                 const Real&                                     a_timeFine,
                 const Real&                                     a_dt,
                 const LevelData<EBCellFAB>* const               a_source,
                 const LevelData<EBCellFAB>* const               a_sourceCoarOld,
                 const LevelData<EBCellFAB>* const               a_sourceCoarNew)
{
  CH_TIME("EBLevelAdvect::advectToFacesBCG (level)");
  CH_assert(isDefined());

  //create temp data with the correct number of ghost cells
  IntVect ivGhost = m_nGhost*IntVect::Unit;
  Interval consInterv(0, m_nVar-1);
  Interval intervSD(0, SpaceDim-1);

  // LevelData<EBCellFAB>& consTemp = (LevelData<EBCellFAB>&) a_consState;
  // LevelData<EBCellFAB>& veloTemp = (LevelData<EBCellFAB>&) a_normalVel;

  EBCellFactory factory(m_thisEBISL);
  LevelData<EBCellFAB> consTemp(m_thisGrids, m_nVar, ivGhost, factory);
  LevelData<EBCellFAB> veloTemp(m_thisGrids, SpaceDim, ivGhost, factory);
  for (DataIterator dit = m_thisGrids.dataIterator(); dit.ok(); ++dit)
    {
      consTemp[dit()].setVal(0.);
    }

  a_consState.copyTo(consInterv, consTemp, consInterv);
  a_normalVel.copyTo(intervSD, veloTemp, intervSD);
  // Fill ghost cells using fillInterp, and copyTo.
  if (m_hasCoarser)
    {
      CH_TIME("fillPatch");
      m_fillPatch.interpolate(consTemp,
                              *a_consStateCoarseOld,
                              *a_consStateCoarseNew,
                              a_timeCoarseOld,
                              a_timeCoarseNew,
                              a_timeFine,
                              consInterv);

      m_fillPatchVel.interpolate(veloTemp,
                                 *a_normalVelCoarseOld,
                                 *a_normalVelCoarseNew,
                                 a_timeCoarseOld,
                                 a_timeCoarseNew,
                                 a_timeFine,
                                 intervSD);
    }
  // Exchange all the data between grids
  {
    CH_TIME("initial_exchange");
    consTemp.exchange(consInterv);
    veloTemp.exchange(intervSD);
  }

  LevelData<EBCellFAB>* srcTmpPtr = NULL;
  if (a_source != NULL)
    {
      // srcTmpPtr = (LevelData<EBCellFAB>*) a_source;

      srcTmpPtr = new LevelData<EBCellFAB>(m_thisGrids, m_nVar, ivGhost, factory);
      for (DataIterator dit = m_thisGrids.dataIterator(); dit.ok(); ++dit)
        {
          (*srcTmpPtr)[dit()].setVal(0.);
        }
      a_source->copyTo(consInterv, *srcTmpPtr, consInterv);

      if ( (a_sourceCoarOld != NULL) &&
           (a_sourceCoarNew != NULL) &&
           (m_hasCoarser) )
        {
          CH_TIME("fillPatch");

          m_fillPatch.interpolate(*srcTmpPtr,
                                  *a_sourceCoarOld,
                                  *a_sourceCoarNew,
                                  a_timeCoarseOld,
                                  a_timeCoarseNew,
                                  a_timeFine,
                                  consInterv);
          {
            CH_TIME("initial_exchange");
            srcTmpPtr->exchange(consInterv);
          }
        }
    }

  {
    CH_TIME("advectToFaces");
    int ibox = 0;
    for (DataIterator dit = m_thisGrids.dataIterator(); dit.ok(); ++dit)
      {
        const Box& cellBox = m_thisGrids.get(dit());
        const EBISBox& ebisBox = m_thisEBISL[dit()];
        if (!ebisBox.isAllCovered())
          {
            //the viscous term goes into here
            EBCellFAB dummy;
            EBCellFAB* srcPtr = &dummy;
            if (srcTmpPtr != NULL)
              {
                srcPtr = (EBCellFAB*)(&((*srcTmpPtr)[dit()]));
              }

            const EBCellFAB& source = *srcPtr;
            //unused in this case
            BaseIVFAB<Real> boundaryPrim;
            bool doBoundaryPrim = false;

            EBFluxFAB& extrapFAB  = a_extrapState[dit()];
            advectToFacesBCG(extrapFAB,
                             boundaryPrim,
                             consTemp[dit()],
                             veloTemp[dit()],
                             a_advectionVel[dit()],
                             cellBox,
                             ebisBox,
                             a_dt,
                             a_timeFine,
                             source,
                             dit(),
                             doBoundaryPrim);



            ibox++;
          }
      }
  }
  if (srcTmpPtr != NULL)
    {
      delete srcTmpPtr;
    }
}
コード例 #23
0
ファイル: flyweight_core.hpp プロジェクト: LeWoY/MAMEHub
 static const entry_type& entry(const base_handle_type& h)
 {
   return factory().entry(h);
 }
コード例 #24
0
static already_AddRefed<TextureClient>
TexClientFromReadback(SharedSurface* src, ISurfaceAllocator* allocator,
                      TextureFlags baseFlags, LayersBackend layersBackend)
{
  auto backendType = gfx::BackendType::CAIRO;
  TexClientFactory factory(allocator, src->mHasAlpha, src->mSize, backendType,
                           baseFlags, layersBackend);

  RefPtr<TextureClient> texClient;

  {
    gl::ScopedReadbackFB autoReadback(src);

    // We have a source FB, now we need a format.
    GLenum destFormat = LOCAL_GL_BGRA;
    GLenum destType = LOCAL_GL_UNSIGNED_BYTE;
    GLenum readFormat;
    GLenum readType;

    // We actually don't care if they match, since we can handle
    // any read{Format,Type} we get.
    auto gl = src->mGL;
    GetActualReadFormats(gl, destFormat, destType, &readFormat, &readType);

    MOZ_ASSERT(readFormat == LOCAL_GL_RGBA ||
               readFormat == LOCAL_GL_BGRA);
    MOZ_ASSERT(readType == LOCAL_GL_UNSIGNED_BYTE);

    // With a format and type, we can create texClient.
    if (readFormat == LOCAL_GL_BGRA &&
        readType == LOCAL_GL_UNSIGNED_BYTE)
    {
      // 0xAARRGGBB
      // In Lendian: [BB, GG, RR, AA]
      texClient = factory.CreateB8G8R8AX8();

    } else if (readFormat == LOCAL_GL_RGBA &&
               readType == LOCAL_GL_UNSIGNED_BYTE)
    {
      // [RR, GG, BB, AA]
      texClient = factory.CreateR8G8B8AX8();
    } else {
      MOZ_CRASH("GFX: Bad `read{Format,Type}`.");
    }

    MOZ_ASSERT(texClient);
    if (!texClient)
        return nullptr;

    // With a texClient, we can lock for writing.
    TextureClientAutoLock autoLock(texClient, OpenMode::OPEN_WRITE);
    DebugOnly<bool> succeeded = autoLock.Succeeded();
    MOZ_ASSERT(succeeded, "texture should have locked");

    MappedTextureData mapped;
    texClient->BorrowMappedData(mapped);

    // ReadPixels from the current FB into mapped.data.
    auto width = src->mSize.width;
    auto height = src->mSize.height;

    {
      ScopedPackAlignment autoAlign(gl, 4);

      MOZ_ASSERT(mapped.stride/4 == mapped.size.width);
      gl->raw_fReadPixels(0, 0, width, height, readFormat, readType, mapped.data);
    }

    // RB_SWAPPED doesn't work with D3D11. (bug 1051010)
    // RB_SWAPPED doesn't work with Basic. (bug ???????)
    // RB_SWAPPED doesn't work with D3D9. (bug ???????)
    bool layersNeedsManualSwap = layersBackend == LayersBackend::LAYERS_BASIC ||
                                 layersBackend == LayersBackend::LAYERS_D3D9 ||
                                 layersBackend == LayersBackend::LAYERS_D3D11;
    if (texClient->HasFlags(TextureFlags::RB_SWAPPED) &&
        layersNeedsManualSwap)
    {
      size_t pixels = width * height;
      uint8_t* itr = mapped.data;
      for (size_t i = 0; i < pixels; i++) {
        SwapRB_R8G8B8A8(itr);
        itr += 4;
      }

      texClient->RemoveFlags(TextureFlags::RB_SWAPPED);
    }
  }

  return texClient.forget();
}
コード例 #25
0
ファイル: ExportCmd.cpp プロジェクト: ryutaro765/Alembic
//-*****************************************************************************
MStatus AbcExportSelected( const Parameters &iConfig )
{
    // Abc::Init();
    
    //-*************************************************************************
    // CREATE SELECTION LIST
    //-*************************************************************************
    MSelectionList slist;
    MGlobal::getActiveSelectionList( slist );
    if ( slist.length() == 0 )
    {
        MGlobal::displayError( "Nothing selected." );
        return MS::kFailure;
    }

    //-*************************************************************************
    // CREATE THE ARCHIVE
    //-*************************************************************************
    if ( iConfig.fileName == "UNSPECIFIED_FILE_NAME.abc" ||
         iConfig.fileName == "" )
    {
        MGlobal::displayError( "No filename specified." );
        return MStatus::kFailure;
    }
        
    // Create the time sampling.
    Abc::TimeSamplingType tSmpType;
    if ( iConfig.endFrame > iConfig.startFrame )
    {
        tSmpType = Abc::TimeSamplingType(
                
            // Increment, in seconds, between samples.
            ( Abc::chrono_t )
            MTime( 1.0, MTime::uiUnit() ).as( MTime::kSeconds ) );
    }

    // Get FPS
    Abc::chrono_t fps =
        MTime( 1.0, MTime::kSeconds ).as( MTime::uiUnit() );
        
    Top top( iConfig.fileName, tSmpType, fps );
        
    std::cout << "AlembicSimpleAbcExport: Opened Alembic Archive: "
              << top.getName()
              << " for writing." << std::endl;
        
    // Build comments
    std::string comments = "AlembicSimpleAbcExport v0.1.1";
    comments += "\n";
    MString exportedFromStr =
        "(Exported from " + MFileIO::currentFile() + ")";
    comments += exportedFromStr.asChar();
    comments += "\n";
    // top.setComments( comments );


    //-*********************************************************************
    // BUILD TREE OF NODE:OBJECT PAIRS TO EXPORT
    //-*********************************************************************
    
    // Create the factory
    Factory factory( iConfig );
    
    for ( MItSelectionList liter( slist ); !liter.isDone(); liter.next() )
    {
        MDagPath dagPath;
        MObject component;
        liter.getDagPath( dagPath, component );
            
        // This will skip nodes we've already visited. HAVE NO
        // FEAR.
        factory.makeTree( top, dagPath, 1000000, tSmpType );
    }
    std::cout << "AlembicSimpleAbcExport: Created DAG Tree to export."
              << std::endl;

    //-*********************************************************************
    // EXPORT SAMPLES PER FRAME
    //-*********************************************************************
    
    // Loop over time
    MComputation computation;
    computation.beginComputation();
    for ( int frame = iConfig.startFrame;
          frame <= iConfig.endFrame; ++frame )
    {   
        // Get a time.
        MTime thisTime( ( double )frame, MTime::uiUnit() );
            
        // Set the time.
        MAnimControl::setCurrentTime( thisTime );
            
        // Get the chrono and the index
        Abc::index_t frameIndex =
            ( Abc::index_t )( frame - iConfig.startFrame );
        Abc::chrono_t frameTime =
            ( Abc::chrono_t )thisTime.as( MTime::kSeconds );
        
        // Is this necessary to force an eval?  Sometimes?
        // MGlobal::viewFrame( t );
        // M3dView currentView = M3dView::active3dView();
        // currentView.refresh( true, true, true );
            
        // Write the frame.
        top.writeSample( Abc::OSampleSelector( frameIndex, frameTime ) );
        std::cout << "AlembicSimpleAbcExport: Wrote frame: "
                  << frame << std::endl;
            
        if ( computation.isInterruptRequested() )
        {
            break;
        }
    }
        
    top.close();
    computation.endComputation();
    // H5close();

    std::cout << "AlembicSimpleAbcExport: Closed Archive." << std::endl;
    return MS::kSuccess;
}
コード例 #26
0
ファイル: MHL7Compare.cpp プロジェクト: nagyistge/mesa
int
MHL7Compare::compare(const MString& existFile, const MString& newFile, int logLevel) 
{
  mLogLevel = logLevel;
  MHL7Factory factory(mBase, mDefinition);

  MHL7Msg* msgExisting = factory.readFromFile(existFile);
  MHL7Msg* msgNew = factory.readFromFile(newFile);

  mMsgExist = msgExisting->getNativeMsg();
  mMsgNew   = msgNew->getNativeMsg();

  compareHL7();

  delete msgExisting;
  delete msgNew;

  return 0;

#if 0
  int baseLen = mBase.size()+1;
  int defLen = mDefinition.size()+1;
  char hl7Base[1024];
  char hl7Definition[30];
  mBase.safeExport(hl7Base, sizeof(hl7Base)-1);
  mDefinition.safeExport(hl7Definition, sizeof(hl7Definition)-1);
 
  if ( !existFile.size() || !newFile.size()) {
    cout << "File Names not properly specified" << endl;
    return -1;
  }

  cout << "Comparing Files: " << existFile << " and " << newFile << endl;

  int fd = 0;
  MString file(existFile);
  char *FullName = file.strData();

  fd = ::open(FullName, O_RDONLY);
  if (fd < 0) {
    cout << "Cannot open file: " << FullName << endl;
    delete [] FullName;
    return -1;
  } 

  // both file extensions should be in "v##" format where ## denotes the version number. e.g ".v22"
//   char *ver = strchr(FullName, '.');
//   if (!ver)
//   {
//     memset(FullName, 0, existFile.size());
//     strcpy(FullName, ".ihe");
//     ver = hl7Definition;
//   }
  
  mFlavorExist = HL7Init(hl7Base, hl7Definition);
  delete [] FullName;
  if (!mFlavorExist) {
    cout << "HL7Init Failed for the Existing Message" << endl;
    return -1;
  }
  mMsgExist = HL7Alloca(mFlavorExist);
  if (!mMsgExist) {
    cout << "HL7Alloca Failed for the Existing Message" << endl;
    HL7Drop(mFlavorExist);
    return -1;
  }
  
  char wire[16384];
  memset(wire, 0, sizeof(wire));
  int bytes = read(fd, wire, sizeof(wire));
  wire[bytes] = 0;

  close (fd);

  while (wire[strlen(wire)-1] != 13)
    wire[strlen(wire)-1] = 0;

  int iResult = HL7ReadMesg(mMsgExist, wire, strlen(wire));
  if (iResult != HL7_OK) {
    cout << "MHL7Compare: Failed to read the Existing message" << endl;
    cout << HL7ErrTxt(mMsgExist, iResult) << endl;
    HL7Free(mMsgExist);
    HL7Drop(mFlavorExist);
    mMsgExist = NULL;
    mFlavorExist = NULL;
    return -1;
  }

  // now read the new file
  fd = 0;
  file = newFile;
  FullName = file.strData();

  fd = open(FullName, O_RDONLY);
  if (fd < 0) {
    cout << "Cannot open file: " << FullName << endl;
    delete [] FullName;
    return -1;
  } 

  // file extension should be in "v##" format where ## denotes the version number. e.g ".v22"

//   ver = strchr(FullName, '.');
//   if (!ver)
//   {
//     memset(FullName, 0, existFile.size());
//     strcpy(FullName, ".ihe");
//     ver = FullName;
//   }

  // ver = hl7Definition;

  mFlavorNew = HL7Init(hl7Base, hl7Definition);
  delete [] FullName;
  if (!mFlavorNew)
  {
    cout << "HL7Init Failed for the New Message" << endl;
    HL7Free(mMsgExist);
    HL7Drop(mFlavorExist);
    return -1;
  }
  mMsgNew = HL7Alloca(mFlavorNew);
  if (!mMsgNew)
  {
    cout << "HL7Alloca Failed for the New Message" << endl;
    HL7Drop(mFlavorNew);
    HL7Free(mMsgExist);
    HL7Drop(mFlavorExist);
    return -1;
  }
  
  memset(wire, 0, sizeof(wire));
  bytes = read(fd, wire, sizeof(wire));
  wire[bytes] = 0;

  close (fd);

  while (wire[strlen(wire)-1] != 13)
    wire[strlen(wire)-1] = 0;

  iResult = HL7ReadMesg(mMsgNew, wire, strlen(wire));
  if (iResult != HL7_OK)
  {
    cout << "MHL7Compare: Failed to read the New message" << endl;
    cout << HL7ErrTxt(mMsgNew, iResult) << endl;
    HL7Free(mMsgExist);
    HL7Drop(mFlavorExist);
    mMsgExist = NULL;
    mFlavorExist = NULL;
    HL7Free(mMsgNew);
    HL7Drop(mFlavorNew);
    mMsgNew = NULL;
    mFlavorNew = NULL;
    return -1;
  }

  // now that we have allocated both messages, compare them
  compareHL7();
#endif
}
コード例 #27
0
ファイル: kcmstyle.cpp プロジェクト: Fat-Zer/tdebase
void KCMStyle::styleSpecificConfig()
{
	TQString libname = styleEntries[currentStyle()]->configPage;

	// Use KLibLoader to get the library, handling
	// any errors that arise
	KLibLoader* loader = KLibLoader::self();

	KLibrary* library = loader->library( TQFile::encodeName(libname) );
	if (!library)
	{
		KMessageBox::detailedError(this,
			i18n("There was an error loading the configuration dialog for this style."),
			loader->lastErrorMessage(),
			i18n("Unable to Load Dialog"));
		return;
	}

	void* allocPtr = library->symbol("allocate_tdestyle_config");

	if (!allocPtr)
	{
		KMessageBox::detailedError(this,
			i18n("There was an error loading the configuration dialog for this style."),
			loader->lastErrorMessage(),
			i18n("Unable to Load Dialog"));
		return;
	}

	//Create the container dialog
	StyleConfigDialog* dial = new StyleConfigDialog(this, styleEntries[currentStyle()]->name);
	dial->enableButtonSeparator(true);

	typedef TQWidget*(* factoryRoutine)( TQWidget* parent );

	//Get the factory, and make the widget.
	factoryRoutine factory      = (factoryRoutine)(allocPtr); //Grmbl. So here I am on my
	//"never use C casts" moralizing streak, and I find that one can't go void* -> function ptr
	//even with a reinterpret_cast.

	TQWidget*       pluginConfig = factory( dial );

	//Insert it in...
	dial->setMainWidget( pluginConfig );

	//..and connect it to the wrapper
	connect(pluginConfig, TQT_SIGNAL(changed(bool)), dial, TQT_SLOT(setDirty(bool)));
	connect(dial, TQT_SIGNAL(defaults()), pluginConfig, TQT_SLOT(defaults()));
	connect(dial, TQT_SIGNAL(save()), pluginConfig, TQT_SLOT(save()));

	if (dial->exec() == TQDialog::Accepted  && dial->isDirty() ) {
		// Force re-rendering of the preview, to apply settings
		switchStyle(currentStyle(), true);

		//For now, ask all TDE apps to recreate their styles to apply the setitngs
		KIPC::sendMessageAll(KIPC::StyleChanged);

		// We call setStyleDirty here to make sure we force style re-creation
		setStyleDirty();
	}

	delete dial;
}
コード例 #28
0
    void Test1dApd() throw(Exception)
    {
        HeartConfig::Instance()->SetPrintingTimeStep(1.0);
        HeartConfig::Instance()->SetSimulationDuration(400); //ms

        DistributedTetrahedralMesh<1,1> mesh;
        mesh.ConstructRegularSlabMesh(0.01, 1.0); // h=0.01cm, width=1cm

        PlaneStimulusCellFactory<CellLuoRudy1991FromCellML, 1> cell_factory(-600.0*1000);

        //////////////////////////////////////////////////////////////////////////
        // run original simulation - no adaptivity, dt=0.01 all the way through
        //////////////////////////////////////////////////////////////////////////
        HeartConfig::Instance()->SetOutputDirectory("MonoWithTimeAdaptivity1dLong/OrigNoAdapt");
        MonodomainProblem<1> problem(&cell_factory);
        problem.SetMesh(&mesh);

        problem.Initialise();
        problem.Solve();

        HeartEventHandler::Headings();
        HeartEventHandler::Report();

        //////////////////////////////////////////////////////////////////////////
        // run adaptive simulation - dt=0.01 for first 2ms, then dt=1
        //////////////////////////////////////////////////////////////////////////
        HeartConfig::Instance()->SetOutputDirectory("MonoWithTimeAdaptivity1dLong/SimpleAdapt");
        MonodomainProblem<1> adaptive_problem(&cell_factory);
        adaptive_problem.SetMesh(&mesh);

        FixedTimeAdaptivityController controller(25);
        adaptive_problem.SetUseTimeAdaptivityController(true, &controller);
        adaptive_problem.Initialise();
        adaptive_problem.Solve();

        HeartEventHandler::Headings();
        HeartEventHandler::Report();

        Hdf5DataReader reader_no_adapt("MonoWithTimeAdaptivity1dLong/OrigNoAdapt","SimulationResults");
        Hdf5DataReader reader_adapt("MonoWithTimeAdaptivity1dLong/SimpleAdapt","SimulationResults");

        unsigned num_timesteps = reader_no_adapt.GetUnlimitedDimensionValues().size();
        assert(num_timesteps == reader_adapt.GetUnlimitedDimensionValues().size());

        DistributedVectorFactory factory(mesh.GetNumNodes());
        Vec voltage_no_adapt = factory.CreateVec();
        Vec voltage_adapt = factory.CreateVec();

        Vec difference;
        VecDuplicate(voltage_adapt, &difference);

        for (unsigned timestep=0; timestep<num_timesteps; timestep++)
        {
            reader_no_adapt.GetVariableOverNodes(voltage_no_adapt, "V", timestep);
            reader_adapt.GetVariableOverNodes(voltage_adapt, "V", timestep);

            PetscVecTools::WAXPY(difference, -1.0, voltage_adapt, voltage_no_adapt);
            double l_inf_norm;
            VecNorm(difference, NORM_INFINITY, &l_inf_norm);

            //std::cout << l_inf_norm << "\n";
            if (timestep < 25)
            {
                TS_ASSERT_DELTA(l_inf_norm, 0.0, 1e-10); // first 25 ms, there should be no difference
            }
            else
            {
                TS_ASSERT_DELTA(l_inf_norm, 0.0, 2.25); // the difference is at most ~2mv, which occurs during the downstroke
            }
        }

        PetscTools::Destroy(voltage_no_adapt);
        PetscTools::Destroy(voltage_adapt);
    }
コード例 #29
0
ファイル: main.cpp プロジェクト: ghalfacree/RASDR
int main()
{
    // Here, you can change the board for which a case you want to construct.
    // Don't forget to change the #include statement above.
#if 1
    BoardDescription board = rasdr2Board();
    std::string name = "rasdr2"; // File name prefix
#else
    BoardDescription board = postsBoard();
    std::string name = "posts"; // File name prefix
#endif

    // Create a factory to build a case for this board.
    CaseFactory factory(board);

    // customize some parameters (note some of these should be in the board description)
    factory.screwHeadsOnSide = TopSide;
    factory.holesAddRadiusLoose = .1; // posts that have the recessed head (screwHeadsOnSide)
    factory.holesAddRadiusTight = .1; // posts that have the captive nut (not screwHeadsOnSide)
    factory.holesFloors = 12.7;       // NB: related to max z height of top forbidden areas (16.20 for rasdr2)
    factory.walls  = 3.0;
    factory.floors = 2.0;
    factory.cornerRadius = 1;         // NB: complex dependency on walls/floors; dont make this too big or be prepared to fiddle...
    factory.cornerFaces = 20; // should be >= 16.

    // Now we can fine-tune some dimension parameters for the case model. See the class CaseFactory for more options, such as wall thickness, screw hole radius etc.
    factory.smallerBottomHeight = .5; // We want the bottom part to be a bit less high (so the GPIO pin ends will be within the floor; this is just to demonstrate the power of the feature "forbidden areas")
    factory.printLayerHeight = .2;
    factory.printSafeBridgeLayerCount = 3;


    // Generate the models
    Component bottom = factory.constructBottom();
    Component top = factory.constructTop();


    // Write these models to SCAD files. We generate 3(4) files.
    // 1) Only the bottom:
    write(name + "-case-bottom.scad", bottom);
    // 2) Only the top:
    write(name + "-case-top.scad", top);
    // 3) Both parts side by side:
    double distance = 15; // in mm; give enough space to add 'pads' to hold the edges down
    double offset   = factory.outerDimensions().x + distance;
    bool adjacent_in_x = true;
    if( adjacent_in_x ) {
        write(name + "-case.scad", bottom + top.translatedCopy(offset, 0, 0));  // put offset into x or y based on above...
    } else {
        offset = factory.outerDimensions().y + distance; // choose .x or .y
        write(name + "-case.scad", bottom + top.translatedCopy(0, offset, 0));  // put offset into x or y based on above...
    }

    // Write an SCAD file for printing that has 'pads' to keep the rounded edges from curling
    if( factory.cornerRadius > 0.0 ) {
        double cr = factory.cornerRadius;
        double r = (distance - cr/2)/2;
        double x = factory.outerDimensions().x;
        double y = factory.outerDimensions().y;
        double w = factory.walls;
        double h = cr<2?cr/2:0.75;
        Component pad = Cylinder(r, h, 32, false);
        Component pads, part;

        double aa = 2*w-w+cr;               // adjust x
        double bb = ((cr>w)?cr-w:0)+cr/2;   // adjust for cr exceeding w
        double cc = -cr+cr/4;               // adjust y

        // pads based on 'bottom' dimensions
        pads =        pad.translatedCopy(x+r-aa, r-w, 0)    + pad.translatedCopy(x+r-aa, y-2*r, 0);     // EAST face
        pads = pads + pad.translatedCopy(-r-w+bb, r/2, 0)   + pad.translatedCopy(-r-w+bb, y-2*r, 0);    // WEST face
        pads = pads + pad.translatedCopy(r-w, -r-w+cr/2, 0) + pad.translatedCopy(x-2*r, -r-w+cr/2, 0);  // SOUTH face
        pads = pads + pad.translatedCopy(r-w, y+r-w+cc, 0)  + pad.translatedCopy(x-2*r, y+r-w+cc, 0);   // NORTH face

        if( adjacent_in_x ) {
            part = bottom + pads;
            part = part   + top.translatedCopy(offset-cr, 0, 0) + pads.translatedCopy(offset-cr, 0, 0);
        } else {
            part = bottom + pads;
            part = part   + top.translatedCopy(0, offset-cr, 0) + pads.translatedCopy(0, offset-cr, 0);
        }
        write(name + "-case-mfg.scad", part);
    }
    return 0;
}
コード例 #30
0
ファイル: KdeMainWindow.cpp プロジェクト: snowy97/marble
MainWindow::~MainWindow()
{
    factory()->removeClient( m_part );
    delete m_part;
}