示例#1
0
文件: dice.c 项目: plurSKI/diceFinder
int main()
{
   int i[6], j[6];
   t(i,0,1,18,j);
   return 0;
}
示例#2
0
文件: cloner.cpp 项目: danpe91/mongo
        void operator()( DBClientCursorBatchIterator &i ) {
            Lock::GlobalWrite lk;
            if ( context ) {
                context->relocked();
            }

            while( i.moreInCurrentBatch() ) {
                if ( n % 128 == 127 /*yield some*/ ) {
                    time_t now = time(0);
                    if( now - lastLog >= 60 ) { 
                        // report progress
                        if( lastLog )
                            log() << "clone " << to_collection << ' ' << n << endl;
                        lastLog = now;
                    }
                    mayInterrupt( _mayBeInterrupted );
                    dbtempreleaseif t( _mayYield );
                }

                BSONObj tmp = i.nextSafe();

                /* assure object is valid.  note this will slow us down a little. */
                if ( !tmp.valid() ) {
                    stringstream ss;
                    ss << "Cloner: skipping corrupt object from " << from_collection;
                    BSONElement e = tmp.firstElement();
                    try {
                        e.validate();
                        ss << " firstElement: " << e;
                    }
                    catch( ... ) {
                        ss << " firstElement corrupt";
                    }
                    out() << ss.str() << endl;
                    continue;
                }

                ++n;

                BSONObj js = tmp;
                if ( isindex ) {
                    verify( strstr(from_collection, "system.indexes") );
                    js = fixindex(tmp);
                    storedForLater->push_back( js.getOwned() );
                    continue;
                }

                try {
                    theDataFileMgr.insertWithObjMod(to_collection, js);
                    if ( logForRepl )
                        logOp("i", to_collection, js);

                    getDur().commitIfNeeded();
                }
                catch( UserException& e ) {
                    error() << "error: exception cloning object in " << from_collection << ' ' << e.what() << " obj:" << js.toString() << '\n';
                    throw;
                }

                RARELY if ( time( 0 ) - saveLast > 60 ) {
                    log() << n << " objects cloned so far from collection " << from_collection << endl;
                    saveLast = time( 0 );
                }
            }
        }
示例#3
0
int main(int argc, char** argv) {
    if(argc < 3)
        return 1;
    HPDDM::MatrixCSR<K>* A = nullptr;
    {
        auto tBegin = std::chrono::steady_clock::now();
        std::ifstream t(argv[1]);
        A = new HPDDM::MatrixCSR<K>(t);
        if(A->_n <= 0) {
            delete A;
            return 1;
        }
        auto tEnd = std::chrono::steady_clock::now();
        std::cout << "// left-hand side matrix read from file in " << std::chrono::duration<double, std::ratio<1>>(tEnd - tBegin).count() << " second(s)\n";
    }
    HPDDM::MatrixCSR<K>* B = nullptr;
    {
        auto tBegin = std::chrono::steady_clock::now();
        std::ifstream t(argv[2]);
        B = new HPDDM::MatrixCSR<K>(t);
        if(B->_n <= 0) {
            delete B;
            delete A;
            return 1;
        }
        auto tEnd = std::chrono::steady_clock::now();
        std::cout << "// right-hand side matrix read from file in " << std::chrono::duration<double, std::ratio<1>>(tEnd - tBegin).count() << " second(s)\n";

    }
    {
        MPI_Init(&argc, &argv);
        int size;
        MPI_Comm_size(MPI_COMM_WORLD, &size);
        if(size > 1) {
            delete B;
            delete A;
            MPI_Finalize();
            return 1;
        }
#ifdef _OPENMP
        int th = omp_get_max_threads();
#else
        int th = 1;
#endif
        std::cout << "// " << size << " MPI process" << (size > 1 ? "es" : "") << " x " << th << " thread" << (th > 1 ? "s" : "") << " = " << (size * th) << " worker" << (size * th > 1 ? "s" : "") << std::endl;
    }
    HPDDM::Option& opt = *HPDDM::Option::get();
    opt.parse(argc, argv, false, {
        std::forward_as_tuple("warm_up=<2>", "Number of fake runs to prime the pump.", HPDDM::Option::Arg::integer),
        std::forward_as_tuple("trials=<5>", "Number of trial runs to time.", HPDDM::Option::Arg::integer),
    });
    std::streamsize old = std::cout.precision();
    EIGENSOLVER<K>* S = new EIGENSOLVER<K>(A->_n, HPDDM::Option::get()->val("geneo_nu", 20));
    std::cout << std::scientific;
    K** ev;
    for(unsigned int begin = 0, end = opt.app()["warm_up"]; begin < end; ++begin) {
        S->template solve<SUBDOMAIN>(A, B, ev, MPI_COMM_SELF);
        if(*ev)
            delete [] *ev;
        delete [] ev;
        delete S;
        S = new EIGENSOLVER<K>(A->_n, HPDDM::Option::get()->val("geneo_nu", 20));
    }
    for(unsigned int begin = 0, end = opt.app()["trials"]; begin < end; ++begin) {
        auto tBegin = std::chrono::steady_clock::now();
        S->template solve<SUBDOMAIN>(A, B, ev, MPI_COMM_SELF);
        auto tEnd = std::chrono::steady_clock::now();
        std::cout << std::setw(10) << std::setprecision(5) << std::chrono::duration<double, std::milli>(tEnd - tBegin).count() << "\n";
        if(*ev)
            delete [] *ev;
        delete [] ev;
        delete S;
        S = new EIGENSOLVER<K>(A->_n, HPDDM::Option::get()->val("geneo_nu", 20));
    }
    std::cout.unsetf(std::ios_base::scientific);
    std::cout.precision(old);
    delete S;
    MPI_Finalize();
    delete B;
    delete A;
    return 0;
}
示例#4
0
int main()
{
	t("%.50g", 100000000000000.5, "100000000000000.5");
	t("%.50g", 987654321098765.0, "987654321098765");
	return t_status;
}
示例#5
0
void draw(const Eigen::Quaternionf &q, const Eigen::Vector3f &translation, const cv::Scalar &color, std::list<cv::Point2f> &tail, bool draw_tail = true)
{

  // Project z axis to ground plane
  Eigen::Vector3f z(0.0, 0.0, 1.0);
  z = q.matrix() * z + translation;  

  // Metric dimension in 3D coordinate frame
  float d_x = 15.24;        // In meter
  float d_y = 28.6512;      // In meter
  
  // Convert to image coordinate  
  float s_x = img_draw.cols;
  float s_y = img_draw.rows;

  float o_x = s_x - translation(1) / d_y * s_x;
  float o_y = s_y - translation(0) / d_x * s_y;

  float p_x = s_x - z(1) / d_y * s_x;
  float p_y = s_y - z(0) / d_x * s_y;

  float s = sqrt((p_x - o_x) * (p_x - o_x) + (p_y - o_y) * (p_y - o_y));

  float u = (p_x - o_x) / s;
  float v = (p_y - o_y) / s;

  float theta = atan2(v, u);

  // 2D rotation matrix and translation
  Eigen::Rotation2Df rot(theta);
  Eigen::Vector2f t(o_x, o_y);

  // Camera cone
  std::vector<Eigen::Vector2f> camera;
  float l = 5;
  Eigen::Vector2f o = rot * Eigen::Vector2f(0.0, 0.0) + t;
  Eigen::Vector2f a = rot * Eigen::Vector2f(3 * l, -3 * l) + t;
  Eigen::Vector2f b = rot * Eigen::Vector2f(3 * l, 3 * l) + t;

  if (tail.size() == 250)
    tail.pop_front();

  tail.push_back(cv::Point2f(o(0), o(1)));

  cv::circle(img_draw, cv::Point2f(o_x, o_y), 3, color);
  cv::line(img_draw, cv::Point2f(o(0), o(1)), cv::Point2f(a(0), a(1)), color, 2, CV_AA);
  cv::line(img_draw, cv::Point2f(o(0), o(1)), cv::Point2f(b(0), b(1)), color, 2, CV_AA);
  cv::line(img_draw, cv::Point2f(a(0), a(1)), cv::Point2f(b(0), b(1)), color, 2, CV_AA);

  if (true == draw_tail)
  {
   cv::Point2f p1, p2;
   for (std::list<cv::Point2f>::iterator iter = tail.begin(); iter != tail.end(); ++iter)
   {
      if (iter == tail.begin())
      {
        p1 = *iter;
       continue;
     }
      p2 = *iter;  
      cv::line(img_draw, p1, p2, color, 2, CV_AA);
     p1 = p2;
  }
  }
}
示例#6
0
PrintcapEntry* ApsHandler::createEntry(KMPrinter *prt)
{
	TQString	prot = prt->deviceProtocol();
	if (prot != "parallel" && prot != "lpd" && prot != "smb" && prot != "ncp")
	{
		manager()->setErrorMsg(i18n("Unsupported backend: %1.").arg(prot));
		return NULL;
	}
	TQString	path = sysconfDir() + "/" + prt->printerName();
	if (!TDEStandardDirs::makeDir(path, 0755))
	{
		manager()->setErrorMsg(i18n("Unable to create directory %1.").arg(path));
		return NULL;
	}
	if (prot == "smb" || prot == "ncp")
	{
		// either "smb" or "ncp"
		TQFile::remove(path + "/smbclient.conf");
		TQFile::remove(path + "/netware.conf");
		TQFile	f;
		if (prot == "smb")
		{
			f.setName(path + "/smbclient.conf");
			if (f.open(IO_WriteOnly))
			{
				TQTextStream	t(&f);
				TQString work, server, printer, user, passwd;
				if ( splitSmbURI( prt->device(), work, server, printer, user, passwd ) )
				{
					if (work.isEmpty())
					{
						manager()->setErrorMsg(i18n("Missing element: %1.").arg("Workgroup"));
						return NULL;
					}
					t << "SMB_SERVER='" << server << "'" << endl;
					t << "SMB_PRINTER='" << printer << "'" << endl;
					t << "SMB_IP=''" << endl;
					t << "SMB_WORKGROUP='" << work << "'" << endl;
					t << "SMB_BUFFER=1400" << endl;
					t << "SMB_FLAGS='-N'" << endl;
					if (!user.isEmpty())
					{
						t << "SMB_USER='******'" << endl;
						t << "SMB_PASSWD='" << passwd << "'" << endl;
					}
				}
				else
				{
					manager()->setErrorMsg( i18n( "Invalid printer backend specification: %1" ).arg( prt->device() ) );
					return NULL;
				}
			}
			else
			{
				manager()->setErrorMsg(i18n("Unable to create the file %1.").arg(f.name()));
				return NULL;
			}
		}
		else
		{
			f.setName(path + "/netware.conf");
			if (f.open(IO_WriteOnly))
			{
				TQString work, server, printer, user, passwd;
				TQString uri = prt->device();
				uri.replace( 0, 3, "smb" );
				if ( splitSmbURI( uri, work, server, printer, user, passwd ) )
				{
					TQTextStream	t(&f);
					t << "NCP_SERVER='" << server << "'" << endl;
					t << "NCP_PRINTER='" << printer << "'" << endl;
					if (!user.isEmpty())
					{
						t << "NCP_USER='******'" << endl;
						t << "NCP_PASSWD='" << passwd << "'" << endl;
					}
				}
				else
				{
					manager()->setErrorMsg( i18n( "Invalid printer backend specification: %1" ).arg( prt->device() ) );
					return NULL;
				}
			}
			else
			{
				manager()->setErrorMsg(i18n("Unable to create the file %1.").arg(f.name()));
				return NULL;
			}
		}
		// change file permissions
		::chmod(TQFile::encodeName(f.name()).data(), S_IRUSR|S_IWUSR);
	}
	PrintcapEntry	*entry = LprHandler::createEntry(prt);
	if (!entry)
	{
		entry = new PrintcapEntry;
		entry->addField("lp", Field::String, "/dev/null");
	}
	TQString	sd = LprSettings::self()->baseSpoolDir() + "/" + prt->printerName();
	entry->addField("af", Field::String, sd + "/acct");
	entry->addField("lf", Field::String, sd + "/log");
	entry->addField("if", Field::String, sysconfDir() + "/basedir/bin/apsfilter");
	entry->comment = TQString::fromLatin1("# APS%1_BEGIN:printer%2").arg(m_counter).arg(m_counter);
	entry->postcomment = TQString::fromLatin1("# APS%1_END").arg(m_counter);
	m_counter++;
	return entry;
}
示例#7
0
static void
hc_prepare_commit_conflict(void)
{
	void *env = sp_env();
	t( env != NULL );
	t( sp_setstring(env, "sophia.path", st_r.conf->sophia_dir, 0) == 0 );
	t( sp_setint(env, "scheduler.threads", 0) == 0 );
	t( sp_setstring(env, "log.path", st_r.conf->log_dir, 0) == 0 );
	t( sp_setstring(env, "db", "test", 0) == 0 );
	t( sp_setstring(env, "db.test.path", st_r.conf->db_dir, 0) == 0 );
	t( sp_setstring(env, "db.test.index.key", "u32", 0) == 0 );
	t( sp_setint(env, "db.test.sync", 0) == 0 );
	t( sp_open(env) == 0 );
	void *db = sp_getobject(env, "db.test");

	int key = 7;

	int rc;
	void *a = sp_begin(env);
	t( a != NULL );

	void *o = sp_object(db);
	t( o != NULL );
	t( sp_setstring(o, "key", &key, sizeof(key)) == 0 );
	t( sp_set(a, o) == 0 );
	t( sp_setint(a, "half_commit", 1) == 0 );
	rc = sp_prepare(a);
	t( rc == 0 );

	void *b = sp_begin(env);
	t( b != NULL );
	o = sp_object(db);
	t( o != NULL );
	t( sp_setstring(o, "key", &key, sizeof(key)) == 0 );
	t( sp_set(b, o) == 0 );
	t( sp_setint(b, "half_commit", 1) == 0 );
	rc = sp_prepare(b); /* this should fail in default conditions */
	t( rc == 0 );

	rc = sp_commit(a);
	t( rc == 0 );
	rc = sp_commit(b);
	t( rc == 0 );

	t( sp_destroy(env) == 0 );
}
示例#8
0
文件: 190.C 项目: JackDrogon/Study
 menu()
{
 int x;
  do{
       {
	clrscr();
	design();
	t();
	textcolor(WHITE);
	gotoxy(24,3);
	cprintf("\xDB\xDB\xDB\xDB\xB2  SAM'S DEPARTMANTAL STORE  \xB2\xDB\xDB\xDB\xDB");
	gotoxy(3,4);
	cprintf("--------------------------------------------------------------------------");
	gotoxy(35,5);
	cprintf("MAIN MENU");
	gotoxy(26,8);
	cprintf(" 1  -   INFORMATION ABOUT PRODUCTS            ");
	gotoxy(26,9);
	cprintf(" 2  -   ENTER  PURCHASE  RECORDS            ");
	gotoxy(26,10);
	cprintf(" 3  -   ENTER PRODUCTS TO BE SALE           ");
	gotoxy(26,11);
	cprintf(" 4  -   SEARCH FOR RECORD                     ");
	gotoxy(26,12);
	cprintf(" 5  -   DELETE RECORD FROM STORE DATABASE     ");
	gotoxy(26,13);
	cprintf(" 6  -   VIEW SALES , PURCHASE & PROFIT REPORT ");
	gotoxy(26,14);
	cprintf(" 7  -   PRINT RECORDS                         ");
	gotoxy(26,15);
	cprintf(" 8  -   BAR  GRAPH OF QUANTITY / PROFIT       ");
	gotoxy(26,16);
	cprintf(" 9  -   RETRIEVE INFORMATION         ");
	gotoxy(26,17);
	cprintf(" H  -   HELP                                  ");
	gotoxy(26,18);
	cprintf(" E  -   EXIT                                  ");
	gotoxy(26,23);
	cprintf("ENTER YOUR CHOICE :: ");
	gotoxy(47,23);
	x=toupper(getch());
	switch(x)
	{
	case '1':
	infor();
	break;

	case '2':
	entry();
	break;

	case '3':
	edit();
	break;

	case '4':
	search();
	break;

	case '5':
	del();
	break;

	case '6':
	report2();
	break;

	case '7':
	print();
	break;

	case 'h': case'H':
	help();
	break;

	case'8':
	graph1();
	break;

	case '9':
	display();
	break;

	case 'e': case 'E':
	exit(0);
	break;

	default:
	clrscr();
	design();
	gotoxy(17,12);
	printf("\a\xDB\xB2  WRONG ENTRY : PRESS ANY KEY AND TRY AGAIN");
	getche();
	}
      }
    }while((x!='e')||(x!='E'));
return x;
}
示例#9
0
文件: matrix3.cpp 项目: Ajdorr/ajLib
Vector3 Vector3::operator*(const float a){
  Vector3 t(v[0]*a, v[1]*a, v[2]*a);

  return t;
}
示例#10
0
SumFileManagerIfc::CHECK_FILE_RET SumFileMd5Manager::hasCheckSum(FileInfo *file)
{
    Q_ASSERT(file);
    if(!file)
    {
        return SumFileManagerIfc::ACCESS_ERROR;
    }

    InfoParent *parent = file->getParent();
    Q_ASSERT(parent);
    if(!parent)
    {
        return SumFileManagerIfc::ACCESS_ERROR;
    }

    InfoBase *pb = parent->getInfoBase();
    Q_ASSERT(pb);
    if(!pb)
    {
        return SumFileManagerIfc::ACCESS_ERROR;
    }

    const WorkerSettings::OUTPUT_SELECTION where = pWorkerSettings->getOutputDirSelection();

    switch(where)
    {
        case WorkerSettings::AS_INPUT :
        {
            QDir d(QDir::cleanPath(pWorkerSettings->getInputDir()+"/"+pb->getSubPath()));
            if(!d.exists() || !d.isReadable())
            {
                return SumFileManagerIfc::FILE_NOT_FOUND;
            }
            TwoColumnSumFile t(d.filePath(SUM_FILENAME), theFileLock, pDataCache, theErrorErrorCollector, CHECKSUM_LEN, FILE_SPARATOR);
            if(!t.isValid())
            {
                return SumFileManagerIfc::PARSING_ERROR;
            }
            return t.readCheckSum(file->getName()).isEmpty() ?
                        SumFileManagerIfc::FILE_NOT_FOUND :
                        SumFileManagerIfc::FILE_FOUND;
        }
        case WorkerSettings::OTHER_DIR :
        {
            QDir d(QDir::cleanPath(pWorkerSettings->getOutputDir()+"/"+pb->getSubPath()));
            if(!d.exists() || !d.isReadable())
            {
                return SumFileManagerIfc::FILE_NOT_FOUND;
            }
            TwoColumnSumFile t(d.filePath(SUM_FILENAME), theFileLock, pDataCache, theErrorErrorCollector, CHECKSUM_LEN, FILE_SPARATOR);
            if(!t.isValid())
            {
                return SumFileManagerIfc::PARSING_ERROR;
            }
            return t.readCheckSum(file->getName()).isEmpty() ?
                        SumFileManagerIfc::FILE_NOT_FOUND :
                        SumFileManagerIfc::FILE_FOUND;
        }
        default: Q_ASSERT(false);
                 return SumFileManagerIfc::ACCESS_ERROR;
    }
}
示例#11
0
文件: 190.C 项目: JackDrogon/Study
void entry()
{
   char ch;
  clrscr();

	   ptr=fopen("shop.dat","a+b");
  ch='y';
  while(ch=='y')
 {
  clrscr();
  design();
  textcolor(14);
  t();
  gotoxy(14,3);
  cprintf("\xDB\xDB\xDB\xDB\xDB\xB2  PURSHASE  \xB2\xDB\xDB\xDB\xDB\xDB ");
   {


     gotoxy(7,5);
    cprintf("\xDB\xDB\xB2  ENTER PRODUCT ID  : ");
     ventry(temp.id,1);
     flushall();
     gotoxy(7,7);
     cprintf("\xDB\xDB\xB2  ENTER DESCRIPTION : ");
     ventry(temp.desc,0);
     flushall();
    gotoxy(7,9);
     cprintf("\xDB\xDB\xB2  ENTER RACK NO     : ");
     ventry(a,1);
    temp.rack= atoi(a);

     flushall();
     gotoxy(7,11);
     cprintf("\xDB\xDB\xB2  ENTER CABNIT NO   : ");
     ventry(a,1);
    temp.cabnit= atoi(a);

    flushall();
    gotoxy(7,13);
     cprintf("\xDB\xDB\xB2  ENTER UNIT COST  :$ ");
     ventry(a,1);
    temp.unit= atof(a);
     flushall();

     gotoxy(7,15);
     cprintf("\xDB\xDB\xB2  ENTER SALE PRICE :$ ");
     ventry(a,1);
    temp.sale= atof(a);
     flushall();

     gotoxy(7,17);
     cprintf("\xDB\xDB\xB2  ENTER  QUANTITY  :  ");
     ventry(a,1);
    temp.quantity= atoi(a);
     flushall();

     gotoxy(7,18);
     cprintf("=====================================");
     temp.total=temp.quantity*temp.sale;

     textcolor(10);
     gotoxy(10,20);
     cprintf("\xB2\xDB\xB2  TOTAL PRICE = $ %.2f",temp.total);
     temp.cost=(temp.unit*temp.quantity);
     gotoxy(40,20);
     cprintf("\xDB\xB2  TOTAL COST = $ %.2f",temp.cost);

     }
  fwrite(&temp,sizeof(temp),1,ptr);
  textcolor(10);
  gotoxy(10,23);
  cprintf("More entries  [y/n]");
  ch=getche();
 }
fclose(ptr);

}
示例#12
0
SumFileManagerIfc::CHECK_FILE_RET SumFileMd5Manager::startCheckSumWrite(FileInfo *file, const QSharedPointer<CheckSumIfc> &checksum)
{
    Q_ASSERT(file);
    if(!file)
    {
        return SumFileManagerIfc::FILE_NOT_FOUND;
    }

    QSharedPointer<MemoryStoredCheckSum> m = checksum.dynamicCast<MemoryStoredCheckSum>();
    if(m.isNull())
    {
        return SumFileManagerIfc::ACCESS_ERROR;
    }

    InfoParent *parent = file->getParent();
    Q_ASSERT(parent);
    if(!parent)
    {
        return SumFileManagerIfc::FILE_NOT_FOUND;
    }

    InfoBase *pb = parent->getInfoBase();
    Q_ASSERT(pb);
    if(!pb)
    {
        return SumFileManagerIfc::FILE_NOT_FOUND;
    }

    const WorkerSettings::OUTPUT_SELECTION where = pWorkerSettings->getOutputDirSelection();

    switch(where)
    {
        case WorkerSettings::AS_INPUT :
        {
            QDir d(pWorkerSettings->getInputDir());
            if(!d.exists() || !d.isReadable())
            {
                return SumFileManagerIfc::FILE_NOT_FOUND;
            }
            d = QDir::cleanPath(pWorkerSettings->getInputDir()+"/"+pb->getSubPath());
            TwoColumnSumFile t(d.filePath(SUM_FILENAME), theFileLock, pDataCache, theErrorErrorCollector, CHECKSUM_LEN, FILE_SPARATOR);
            if(t.writeCheckSum(file->getName(), m->toByteArray(), WRITE_SPARATOR))
            {
                return SumFileManagerIfc::FILE_FOUND;
            }
            else
            {
                return SumFileManagerIfc::ACCESS_ERROR;
            }
        }
        case WorkerSettings::OTHER_DIR :
        {
            QDir d(pWorkerSettings->getOutputDir());
            if(!d.exists() || !d.isReadable())
            {
                return SumFileManagerIfc::FILE_NOT_FOUND;
            }
            d = QDir::cleanPath(pWorkerSettings->getOutputDir()+"/"+pb->getSubPath());
            TwoColumnSumFile t(d.filePath(SUM_FILENAME), theFileLock, pDataCache, theErrorErrorCollector, CHECKSUM_LEN, FILE_SPARATOR);
            if(t.writeCheckSum(file->getName(), m->toByteArray(), WRITE_SPARATOR))
            {
                return SumFileManagerIfc::FILE_FOUND;
            }
            else
            {
                return SumFileManagerIfc::ACCESS_ERROR;
            }
        }
        default: Q_ASSERT(false);
            return SumFileManagerIfc::ACCESS_ERROR;
    }
}
示例#13
0
QSharedPointer<CheckSumIfc> SumFileMd5Manager::readCheckSum(FileInfo *file)
{
    Q_ASSERT(file);
    if(!file)
    {
        return QSharedPointer<CheckSumIfc>();
    }

    InfoParent *parent = file->getParent();
    Q_ASSERT(parent);
    if(!parent)
    {
        return QSharedPointer<CheckSumIfc>();
    }

    InfoBase *pb = parent->getInfoBase();
    Q_ASSERT(pb);
    if(!pb)
    {
        return QSharedPointer<CheckSumIfc>();
    }

    const WorkerSettings::OUTPUT_SELECTION where = pWorkerSettings->getOutputDirSelection();

    switch(where)
    {
        case WorkerSettings::AS_INPUT    :
        {
            QDir d(QDir::cleanPath(pWorkerSettings->getInputDir()+"/"+pb->getSubPath()));
            if(!d.exists() || !d.isReadable())
            {
                theErrorErrorCollector->addError(QString("Check sum path not found: ")+d.absolutePath());
                return QSharedPointer<CheckSumIfc>();
            }
            TwoColumnSumFile t(d.filePath(SUM_FILENAME), theFileLock, pDataCache, theErrorErrorCollector, CHECKSUM_LEN, FILE_SPARATOR);
            if(!t.isValid())
            {
                return QSharedPointer<CheckSumIfc>();
            }
            QByteArray b = t.readCheckSum(file->getName());
            if(b.isEmpty())
            {
                return QSharedPointer<CheckSumIfc>();
            }
            return QSharedPointer<CheckSumIfc>(new MemoryStoredCheckSum(b));
        }
        case WorkerSettings::OTHER_DIR :
        {
            QDir d(QDir::cleanPath(pWorkerSettings->getOutputDir()+"/"+pb->getSubPath()));
            if(!d.exists() || !d.isReadable())
            {
                theErrorErrorCollector->addError(QString("Check sum path not found: ")+d.absolutePath());
                return QSharedPointer<CheckSumIfc>();
            }
            TwoColumnSumFile t(d.filePath(SUM_FILENAME), theFileLock, pDataCache, theErrorErrorCollector, CHECKSUM_LEN, FILE_SPARATOR);
            if(!t.isValid())
            {
                return QSharedPointer<CheckSumIfc>();
            }
            QByteArray b = t.readCheckSum(file->getName());
            if(b.isEmpty())
            {
                return QSharedPointer<CheckSumIfc>();
            }
            return QSharedPointer<CheckSumIfc>(new MemoryStoredCheckSum(b));
        }
        default: Q_ASSERT(false);
            return QSharedPointer<CheckSumIfc>();
    }
}
示例#14
0
typet dplib_convt::gen_array_index_type()
{
  typet t(ID_signedbv);
  t.set(ID_width, 32);
  return t;
}
示例#15
0
ptime TimeBoost::GetPTimeFromMS(millis_t aTimeMS)
{
	ptime t(msEpochDate, milliseconds(aTimeMS));
	return t;
}
示例#16
0
int P4d::performWebifRequests()
{
   tableJobs->clear();

   for (int f = selectPendingJobs->find(); f; f = selectPendingJobs->fetch())
   {
      int start = time(0);
      int addr = tableJobs->getIntValue("ADDRESS");
      const char* command = tableJobs->getStrValue("COMMAND");
      const char* data = tableJobs->getStrValue("DATA");
      int jobId = tableJobs->getIntValue("ID");

      tableJobs->find();
      tableJobs->setValue("DONEAT", time(0));
      tableJobs->setValue("STATE", "D");

      tell(eloAlways, "Processing WEBIF job %d '%s:0x%04x/%s'",
           jobId, command, addr, data);

      if (strcasecmp(command, "test-mail") == 0)
      {
         char* subject = strdup(data);
         char* body = 0;

         if ((body = strchr(subject, ':')))
         {
            *body = 0; body++;

            tell(eloDetail, "Test mail requested with: '%s/%s'", subject, body);

            if (isEmpty(mailScript))
               tableJobs->setValue("RESULT", "fail:missing mailscript");
            else if (!fileExists(mailScript))
               tableJobs->setValue("RESULT", "fail:mail-script not found");
            else if (isEmpty(stateMailTo))
               tableJobs->setValue("RESULT", "fail:missing-receiver");
            else if (sendMail(stateMailTo, subject, body, "text/plain") != success)
               tableJobs->setValue("RESULT", "fail:mail-sended");
            else
               tableJobs->setValue("RESULT", "success:mail-sended");
         }
      }

      else if (strcasecmp(command, "check-login") == 0)
      {
         char* webUser = 0;
         char* webPass = 0;
         md5Buf defaultPwd;

         createMd5("p4-3200", defaultPwd);

         getConfigItem("user", webUser, "p4");
         getConfigItem("passwd", webPass, defaultPwd);

         char* user = strdup(data);
         char* pwd = 0;

         if ((pwd = strchr(user, ':')))
         {
            *pwd = 0; pwd++;

            tell(eloDetail, "%s/%s", pwd, webPass);

            if (strcmp(webUser, user) == 0 && strcmp(pwd, webPass) == 0)
               tableJobs->setValue("RESULT", "success:login-confirmed");
            else
               tableJobs->setValue("RESULT", "fail:login-denied");
         }

         free(webPass);
         free(webUser);
         free(user);
      }

      else if (strcasecmp(command, "update-schemacfg") == 0)
      {
         updateSchemaConfTable();
         tableJobs->setValue("RESULT", "success:done");
      }

      else if (strcasecmp(command, "write-config") == 0)
      {
         char* name = strdup(data);
         char* value = 0;

         if ((value = strchr(name, ':')))
         {
            *value = 0; value++;

            setConfigItem(name, value);

            tableJobs->setValue("RESULT", "success:stored");
         }

         free(name);

         // read the config from table to apply changes

         readConfiguration();
      }

      else if (strcasecmp(command, "read-config") == 0)
      {
         char* name = strdup(data);
         char* buf = 0;
         char* value = 0;
         char* def = 0;

         if ((def = strchr(name, ':')))
         {
            *def = 0;
            def++;
         }

         getConfigItem(name, value, def ? def : "");

         asprintf(&buf, "success:%s", value);
         tableJobs->setValue("RESULT", buf);

         free(name);
         free(buf);
         free(value);
      }

      else if (strcasecmp(command, "getp") == 0)
      {
         tableMenu->clear();
         tableMenu->setValue("ID", addr);

         if (tableMenu->find())
         {
            int type = tableMenu->getIntValue("TYPE");
            unsigned int paddr = tableMenu->getIntValue("ADDRESS");

            ConfigParameter p(paddr);

            if (request->getParameter(&p) == success)
            {
               char* buf = 0;
               cRetBuf value = ConfigParameter::toNice(p.value, type);

               // special for time min/max/default

               if (type == mstParZeit)
                  ;  // #TODO

               asprintf(&buf, "success#%s#%s#%d#%d#%d#%d", *value, type == 0x0a ? "Uhr" : p.unit,
                        p.def, p.min, p.max, p.digits);
               tableJobs->setValue("RESULT", buf);

               free(buf);
            }
         }
      }

      else if (strcasecmp(command, "setp") == 0)
      {
         int status;

         tableMenu->clear();
         tableMenu->setValue("ID", addr);

         if (tableMenu->find())
         {
            int type = tableMenu->getIntValue("TYPE");
            int paddr = tableMenu->getIntValue("ADDRESS");

            ConfigParameter p(paddr);

            // Set Value

            if (ConfigParameter::toValue(data, type, p.value) == success)
            {
               tell(eloAlways, "Storing value '%s/%d' for parameter at address 0x%x", data, p.value, paddr);

               if ((status = request->setParameter(&p)) == success)
               {
                  char* buf = 0;
                  cRetBuf value = ConfigParameter::toNice(p.value, type);

                  // store job result

                  asprintf(&buf, "success#%s#%s#%d#%d#%d#%d", *value, p.unit,
                           p.def, p.min, p.max, p.digits);
                  tableJobs->setValue("RESULT", buf);
                  free(buf);

                  // update menu table

                  tableMenu->setValue("VALUE", value);
                  tableMenu->setValue("UNIT", p.unit);
                  tableMenu->update();
               }
               else
               {
                  tell(eloAlways, "Set of parameter failed, error %d", status);

                  if (status == P4Request::wrnNonUpdate)
                     tableJobs->setValue("RESULT", "fail#no update");
                  else if (status == P4Request::wrnOutOfRange)
                     tableJobs->setValue("RESULT", "fail#out of range");
                  else
                     tableJobs->setValue("RESULT", "fail#communication error");
               }
            }
            else
            {
               tell(eloAlways, "Set of parameter failed, wrong format");
               tableJobs->setValue("RESULT", "fail#format error");
            }
         }
         else
         {
            tell(eloAlways, "Set of parameter failed, id 0x%x not found", addr);
            tableJobs->setValue("RESULT", "fail#id not found");
         }
      }

      else if (strcasecmp(command, "gettrp") == 0)
      {
         // first update the time range data
         //  s3200 support no single request of a time range parameter

         // don't update since it takes to long (assume table is up to date)
         // updateTimeRangeData();

         // now read it from the table

         tableTimeRanges->clear();
         tableTimeRanges->setValue("ADDRESS", addr);

         if (tableTimeRanges->find())
         {
            char* buf = 0;
            char fName[10+TB];
            char tName[10+TB];
            int n = atoi(data);

            sprintf(fName, "FROM%d", n);
            sprintf(tName, "TO%d", n);

            asprintf(&buf, "success#%s#%s#%s",
                     tableTimeRanges->getStrValue(fName),
                     tableTimeRanges->getStrValue(tName),
                     "Zeitraum");
            tableJobs->setValue("RESULT", buf);

            free(buf);
         }
      }

      else if (strcasecmp(command, "settrp") == 0)
      {
         int status = success;
         Fs::TimeRanges t(addr);
         char fName[10+TB];
         char tName[10+TB];
         int rangeNo;
         char valueFrom[100+TB];
         char valueTo[100+TB];

         // parse rangeNo and value from data

         if (sscanf(data, "%d#%[^#]#%[^#]", &rangeNo, valueFrom, valueTo) != 3)
         {
            tell(eloAlways, "Parsing of '%s' failed", data);
            status = fail;
         }

         rangeNo--;

         // get actual values from table

         tableTimeRanges->clear();
         tableTimeRanges->setValue("ADDRESS", addr);

         if (status == success && tableTimeRanges->find())
         {
            for (int n = 0; n < 4; n++)
            {
               sprintf(fName, "FROM%d", n+1);
               sprintf(tName, "TO%d", n+1);

               status += t.setTimeRange(n, tableTimeRanges->getStrValue(fName), tableTimeRanges->getStrValue(tName));
            }

            // override the 'rangeNo' with new value

            status += t.setTimeRange(rangeNo, valueFrom, valueTo);

            if (status == success)
            {
               tell(eloAlways, "Storing '%s' for time range '%d' of parameter 0x%x", t.getTimeRange(rangeNo), rangeNo+1, t.address);

               if ((status = request->setTimeRanges(&t)) == success)
               {
                  char* buf = 0;

                  // store job result

                  asprintf(&buf, "success#%s#%s#%s", t.getTimeRangeFrom(rangeNo), t.getTimeRangeTo(rangeNo), "Zeitbereich");
                  tableJobs->setValue("RESULT", buf);
                  free(buf);

                  // update time range table

                  sprintf(fName, "FROM%d", rangeNo+1);
                  sprintf(tName, "TO%d", rangeNo+1);
                  tableTimeRanges->setValue(fName, t.getTimeRangeFrom(rangeNo));
                  tableTimeRanges->setValue(tName, t.getTimeRangeTo(rangeNo));
                  tableTimeRanges->update();
               }
               else
               {
                  tell(eloAlways, "Set of time range parameter failed, error %d", status);

                  if (status == P4Request::wrnNonUpdate)
                     tableJobs->setValue("RESULT", "fail#no update");
                  else if (status == P4Request::wrnOutOfRange)
                     tableJobs->setValue("RESULT", "fail#out of range");
                  else
                     tableJobs->setValue("RESULT", "fail#communication error");
               }
            }
            else
            {
               tell(eloAlways, "Set of time range parameter failed, wrong format");
               tableJobs->setValue("RESULT", "fail#format error");
            }
         }
         else
         {
            tell(eloAlways, "Set of time range parameter failed, addr 0x%x for '%s' not found", addr, data);
            tableJobs->setValue("RESULT", "fail#id not found");
         }
      }

      else if (strcasecmp(command, "getv") == 0)
      {
         Value v(addr);

         tableValueFacts->clear();
         tableValueFacts->setValue("TYPE", "VA");
         tableValueFacts->setValue("ADDRESS", addr);

         if (tableValueFacts->find())
         {
            double factor = tableValueFacts->getIntValue("FACTOR");
            const char* unit = tableValueFacts->getStrValue("UNIT");

            if (request->getValue(&v) == success)
            {
               char* buf = 0;

               asprintf(&buf, "success:%.2f%s", v.value / factor, unit);
               tableJobs->setValue("RESULT", buf);
               free(buf);
            }
         }
      }

      else if (strcasecmp(command, "initmenu") == 0)
      {
         initMenu();
         tableJobs->setValue("RESULT", "success:done");
      }

      else if (strcasecmp(command, "updatehm") == 0)
      {
         if (hmSyncSysVars() == success)
            tableJobs->setValue("RESULT", "success:done");
         else
            tableJobs->setValue("RESULT", "fail:error");
      }

      else if (strcasecmp(command, "p4d-state") == 0)
      {
         struct tm tim = {0};

         double averages[3];
         char dt[10];
         char d[100];
         char* buf;

         memset(averages, 0, sizeof(averages));
         localtime_r(&nextAt, &tim);
         strftime(dt, 10, "%H:%M:%S", &tim);
         toElapsed(time(0)-startedAt, d);

         getloadavg(averages, 3);

         asprintf(&buf, "success:%s#%s#%s#%3.2f %3.2f %3.2f",
                  dt, VERSION, d, averages[0], averages[1], averages[2]);

         tableJobs->setValue("RESULT", buf);
         free(buf);
      }

      else if (strcasecmp(command, "s3200-state") == 0)
      {
         struct tm tim = {0};
         char date[100];
         char* buf = 0;

         localtime_r(&currentState.time, &tim);
         strftime(date, 100, "%A, %d. %b. %G %H:%M:%S", &tim);

         asprintf(&buf, "success:%s#%d#%s#%s", date,
                  currentState.state, currentState.stateinfo,
                  currentState.modeinfo);

         tableJobs->setValue("RESULT", buf);
         free(buf);
      }

      else if (strcasecmp(command, "initvaluefacts") == 0)
      {
         updateValueFacts();
         tableJobs->setValue("RESULT", "success:done");
      }

      else if (strcasecmp(command, "updatemenu") == 0)
      {
         tableMenu->clear();

         for (int f = selectAllMenuItems->find(); f; f = selectAllMenuItems->fetch())
         {
            int type = tableMenu->getIntValue("TYPE");
            int paddr = tableMenu->getIntValue("ADDRESS");

            if (type == 0x07 || type == 0x08 || type == 0x0a ||
                type == 0x40 || type == 0x39 || type == 0x32)
            {
               Fs::ConfigParameter p(paddr);

               if (request->getParameter(&p) == success)
               {
                  cRetBuf value = ConfigParameter::toNice(p.value, type);

                  if (tableMenu->find())
                  {
                     tableMenu->setValue("VALUE", value);
                     tableMenu->setValue("UNIT", p.unit);
                     tableMenu->update();
                  }
               }
            }

            else if (type == mstFirmware)
            {
               Fs::Status s;

               if (request->getStatus(&s) == success)
               {
                  if (tableMenu->find())
                  {
                     tableMenu->setValue("VALUE", s.version);
                     tableMenu->setValue("UNIT", "");
                     tableMenu->update();
                  }
               }
            }

            else if (type == mstDigOut || type == mstDigIn || type == mstAnlOut)
            {
               int status;
               Fs::IoValue v(paddr);

               if (type == mstDigOut)
                  status = request->getDigitalOut(&v);
               else if (type == mstDigIn)
                  status = request->getDigitalIn(&v);
               else
                  status = request->getAnalogOut(&v);

               if (status == success)
               {
                  char* buf = 0;

                  if (type == mstAnlOut)
                  {
                     if (v.mode == 0xff)
                        asprintf(&buf, "%d (A)", v.state);
                     else
                        asprintf(&buf, "%d (%d)", v.state, v.mode);
                  }
                  else
                     asprintf(&buf, "%s (%c)", v.state ? "on" : "off", v.mode);

                  if (tableMenu->find())
                  {
                     tableMenu->setValue("VALUE", buf);
                     tableMenu->setValue("UNIT", "");
                     tableMenu->update();
                  }

                  free(buf);
               }
            }

            else if (type == mstMesswert || type == mstMesswert1)
            {
               int status;
               Fs::Value v(paddr);

               tableValueFacts->clear();
               tableValueFacts->setValue("TYPE", "VA");
               tableValueFacts->setValue("ADDRESS", paddr);

               if (tableValueFacts->find())
               {
                  double factor = tableValueFacts->getIntValue("FACTOR");
                  const char* unit = tableValueFacts->getStrValue("UNIT");

                  status = request->getValue(&v);

                  if (status == success)
                  {
                     char* buf = 0;
                     asprintf(&buf, "%.2f", v.value / factor);

                     if (tableMenu->find())
                     {
                        tableMenu->setValue("VALUE", buf);

                        if (strcmp(unit, "°") == 0)
                           tableMenu->setValue("UNIT", "°C");
                        else
                           tableMenu->setValue("UNIT", unit);

                        tableMenu->update();
                     }

                     free(buf);
                  }
               }
            }
         }

         selectAllMenuItems->freeResult();

         updateTimeRangeData();

         tableJobs->setValue("RESULT", "success:done");
      }

      else
      {
         tell(eloAlways, "Warning: Ignoring unknown job '%s'", command);
         tableJobs->setValue("RESULT", "fail:unknown command");
      }

      tableJobs->store();

      tell(eloAlways, "Processing WEBIF job %d done with '%s' after %ld seconds",
           jobId, tableJobs->getStrValue("RESULT"),
           time(0) - start);
   }

   selectPendingJobs->freeResult();

   return success;
}
示例#17
0
boost::thread make_thread_return_local(boost::thread::id* the_id)
{
    boost::thread t(do_nothing,the_id);
    return boost::move(t);
}
 void NodeSender::start() {
   boost::thread t(boost::bind(&boost::asio::io_service::run,&io_service_));
 }
示例#19
0
static void
hc_prepare_commit(void)
{
	void *env = sp_env();
	t( env != NULL );
	t( sp_setstring(env, "sophia.path", st_r.conf->sophia_dir, 0) == 0 );
	t( sp_setint(env, "scheduler.threads", 0) == 0 );
	t( sp_setstring(env, "log.path", st_r.conf->log_dir, 0) == 0 );
	t( sp_setstring(env, "db", "test", 0) == 0 );
	t( sp_setstring(env, "db.test.path", st_r.conf->db_dir, 0) == 0 );
	t( sp_setstring(env, "db.test.index.key", "u32", 0) == 0 );
	t( sp_setint(env, "db.test.sync", 0) == 0 );
	t( sp_open(env) == 0 );
	void *db = sp_getobject(env, "db.test");

	int rc;
	void *tx = sp_begin(env);
	t( tx != NULL );

	int key = 7;
	void *o = sp_object(db);
	t( o != NULL );
	t( sp_setstring(o, "key", &key, sizeof(key)) == 0 );
	t( sp_setstring(o, "value", &key, sizeof(key)) == 0 );
	t( sp_set(tx, o) == 0 );
	o = sp_object(db);
	t( sp_setstring(o, "key", &key, sizeof(key)) == 0 );
	o = sp_get(tx, o);
	t( o != NULL );
	t( *(int*)sp_getstring(o, "value", NULL) == key );
	sp_destroy(o);

	t( sp_setint(tx, "half_commit", 1) == 0 );
	rc = sp_prepare(tx);
	t( rc == 0 );
	rc = sp_commit(tx);
	t( rc == 0 );

	t( sp_destroy(env) == 0 );
}
示例#20
0
pstring  ppreprocessor::process_line(const pstring &line)
{
	pstring lt = line.replace("\t"," ").trim();
	pstringbuffer ret;
	m_lineno++;
	// FIXME ... revise and extend macro handling
	if (lt.startsWith("#"))
	{
		std::vector<pstring> lti(psplit(lt, " ", true));
		if (lti[0].equals("#if"))
		{
			m_level++;
			std::size_t start = 0;
			lt = replace_macros(lt);
			std::vector<pstring> t(psplit(lt.substr(3).replace(" ",""), m_expr_sep));
			int val = static_cast<int>(expr(t, start, 0));
			if (val == 0)
				m_ifflag |= (1 << m_level);
		}
		else if (lti[0].equals("#ifdef"))
		{
			m_level++;
			if (get_define(lti[1]) == nullptr)
				m_ifflag |= (1 << m_level);
		}
		else if (lti[0].equals("#ifndef"))
		{
			m_level++;
			if (get_define(lti[1]) != nullptr)
				m_ifflag |= (1 << m_level);
		}
		else if (lti[0].equals("#else"))
		{
			m_ifflag ^= (1 << m_level);
		}
		else if (lti[0].equals("#endif"))
		{
			m_ifflag &= ~(1 << m_level);
			m_level--;
		}
		else if (lti[0].equals("#include"))
		{
			// ignore
		}
		else if (lti[0].equals("#pragma"))
		{
			if (m_ifflag == 0 && lti.size() > 3 && lti[1].equals("NETLIST"))
			{
				if (lti[2].equals("warning"))
					error("NETLIST: " + catremainder(lti, 3, " "));
			}
		}
		else if (lti[0].equals("#define"))
		{
			if (m_ifflag == 0)
			{
				if (lti.size() != 3)
					error("PREPRO: only simple defines allowed: " + line);
				m_defines.insert({lti[1], define_t(lti[1], lti[2])});
			}
		}
		else
			error(pfmt("unknown directive on line {1}: {2}")(m_lineno)(line));
	}
	else
	{
		lt = replace_macros(lt);
		if (m_ifflag == 0)
		{
			ret.cat(lt);
		}
	}
	return ret;
}
示例#21
0
// Calucuate a size and alignment for some type.
std::pair<size_t, unsigned int> TypeStore::calc_type_size(VMemory::Accessor& memory,
                                                          vaddr_t type) {
  std::unique_ptr<TypeStore> t(TypeStore::read(memory, type));

  return std::make_pair(t->size, t->alignment);
}
示例#22
0
void m(void)
{
    t(i);
}
示例#23
0
Spectrum AggregateVolume::tau(const Ray &ray, float step, float offset) const {
    Spectrum t(0.);
    for (uint32_t i = 0; i < regions.size(); ++i)
        t += regions[i]->tau(ray, step, offset);
    return t;
}
示例#24
0
文件: unit.c 项目: 117311730/PHP
int run_test(int (*t)(void)) {
  t();
  printf(".");
}
示例#25
0
文件: test.cpp 项目: rowoflo/hubo
void huboArmTrans(Eigen::Isometry3d &B, Vector6d &q, int side,  const Eigen::Isometry3d &endEffector, int fromFrame, int toFrame)
{
    // Declarations
    Eigen::Isometry3d neck, hand, T;
    Eigen::MatrixXd limits(6,2);
    Vector6d offset; offset.setZero();
    
    // Parameters
    double l1 = 214.5/1000.0;
    double l2 = 179.14/1000.0;
    double l3 = 181.59/1000.0;
    double l4 = 4.75*25.4/1000.0;
    
    Vector6d t, f, r, d;
    t <<  M_PI/2, -M_PI/2,  M_PI/2,       0,       0,  M_PI/2;
    f <<  M_PI/2,  M_PI/2, -M_PI/2,  M_PI/2, -M_PI/2,       0;
    r <<       0,       0,       0,       0,       0,      l4;
    d <<       0,       0,     -l2,       0,     -l3,       0;

    limits <<
        H_Arm_Ctrl[side].joint[0].po_smin, H_Arm_Ctrl[side].joint[0].pos_max,
        H_Arm_Ctrl[side].joint[1].pos_min, H_Arm_Ctrl[side].joint[1].pos_max,
        H_Arm_Ctrl[side].joint[2].pos_min, H_Arm_Ctrl[side].joint[2].pos_max,
        H_Arm_Ctrl[side].joint[3].pos_min, H_Arm_Ctrl[side].joint[3].pos_max,
        H_Arm_Ctrl[side].joint[4].pos_min, H_Arm_Ctrl[side].joint[4].pos_max,
        H_Arm_Ctrl[side].joint[5].pos_min, H_Arm_Ctrl[side].joint[5].pos_max;

    
    if (side == RIGHT) {
        neck(0,0) = 1; neck(0,1) =  0; neck(0,2) = 0; neck(0,3) =   0;
        neck(1,0) = 0; neck(1,1) =  0; neck(1,2) = 1; neck(1,3) = -l1;
        neck(2,0) = 0; neck(2,1) = -1; neck(2,2) = 0; neck(2,3) =   0;
        neck(3,0) = 0; neck(3,1) =  0; neck(3,2) = 0; neck(3,3) =   1;
        
/*
        limits <<
        -2,   2,
        -2,  .3,
        -2,   2,
        -2,   0.01,
        -2,   2,
        -1.4, 1.2;
*/        
        // Set offsets
        offset(1) = limits(1,1); // Note: I think this might be backwards
//        offset(1) = -limits(1,1);
        
    } else {
        // Transformation from Neck frame to left shoulder pitch frame
        neck(0,0) = 1; neck(0,1) =  0; neck(0,2) = 0; neck(0,3) =   0;
        neck(1,0) = 0; neck(1,1) =  0; neck(1,2) = 1; neck(1,3) =  l1;
        neck(2,0) = 0; neck(2,1) = -1; neck(2,2) = 0; neck(2,3) =   0;
        neck(3,0) = 0; neck(3,1) =  0; neck(3,2) = 0; neck(3,3) =   1;
/*        
        limits <<
        -2,   2,
        -.3,   2,
        -2,   2,
        -2,   0.01,
        -2,   2,
        -1.4, 1.2;
*/        
        // Set offsets
        offset(1) = limits(1,0); // Note: I think this might be backwards
//        offset(1) = -limits(1,0);
    }
     
    // Calculate forward kinematics
    if (fromFrame == -1) {
      B = neck;
      fromFrame = 0;
    } else {
      B = Isometry3d:Identity();
    }
    for (int i = fromFrame; i < std::min(toFrame,6); i++) {
        DH2HG(T, t(i)+q(i)-offset(i), f(i), r(i), d(i));
        B = B*T;
    }
    if (fromFrame == 7) {
      B = B*endEffector;
    }
    
}
示例#26
0
Term Polynomial::removetip() {
  Term t(*begin());
  d_terms.pop_front();
  d_numberOfTerms--;
  return t;
};
示例#27
0
void quotRemainder128(const BigReal &x, const BigReal &y, BigInt *quotient, BigReal *remainder) {
  DEFINEMETHODNAME;
  if(y.isZero()) {
    throwBigRealInvalidArgumentException(method, _T("Division by zero"));
  }
  if(quotient == remainder) { // also takes care of the stupid situation where both are NULL
    throwBigRealInvalidArgumentException(method, _T("quotient is the same variable as remainder"));
  }
  if(quotient == &x || quotient == &y) {
    throwBigRealInvalidArgumentException(method, _T("quotient cannot be the same variable as x or y"));
  }
  if(remainder == &x || remainder == &y) {
    throwBigRealInvalidArgumentException(method, _T("remainder cannot be the same variable as x or y"));
  }

  if(x.isZero()) {
    if(quotient ) quotient->setToZero();
    if(remainder) remainder->setToZero();
    return;
  }

  const int cmpAbs = compareAbs(x, y);
  if(cmpAbs < 0) {
    if(remainder) *remainder = x;
    if(quotient)  quotient->setToZero();
    return;
  } else if(cmpAbs == 0) {
    if(remainder) remainder->setToZero();
    if(quotient) {
      *quotient = quotient->getDigitPool()->get1();
    }
    return;
  }

  // x != 0 && y != 0 && |x| > |y|

  if(BigReal::isPow10(y)) {
    BigReal tmp(x);
    const BRExpoType yp10 = BigReal::getExpo10(y);
    tmp.multPow10(-yp10);
    tmp.fractionate(quotient, remainder);
    if(remainder) {
      remainder->multPow10(yp10);
    }
    if(quotient) {
      quotient->setPositive();
    }
    return;
  }

  const bool yNegative = y.isNegative();
  ((BigReal&)y).setPositive(); // cheating. We set it back agin

  DigitPool *pool = x.getDigitPool();

  BigReal z(x, pool);
  z.setPositive();

  BRExpoType             scale;
  _uint128               yFirst;
  y.getFirst128(yFirst, MAXDIGITS_DIVISOR128, &scale);
  const int              yDigits      = BigReal::getDecimalDigitCount64(yFirst);

  BigReal q(pool), t(pool), tmp(pool);
  while(compareAbs(z, y) >= 0) {
    t.approxQuot128Abs(z, yFirst, scale).m_negative = z.m_negative;
    q += t;
    z -= BigReal::product(tmp, t, y, pool->get0(),0);
  }

  if(!z.isNegative()) {
    if(isInteger(q)) {
      if(quotient)  *quotient  = q;
      if(remainder) *remainder = z;
    } else {
      q.fractionate(quotient, &t);
      z += t * y;
      if(compareAbs(z, y) >= 0) {
        if(quotient)  ++(*quotient);
        if(remainder) *remainder = z - y;
      } else {
        if(remainder) *remainder = z;
      }
    }
  } else { // z < 0
    if(isInteger(q)) {
      if(quotient)  {
        *quotient = q;
        --(*quotient);
      }
      if(remainder) {
        *remainder = z + y;
      }
    } else {
      if(!remainder) { // quotient != NULL
        q.fractionate(quotient, &t);
        z += t * y;
        if(z.isNegative()) {
          --(*quotient);
        }
      } else { // remainder != NULL. quotient might be NULL
        q.fractionate(quotient, &t);
        *remainder = z + t * y;
        if(remainder->isNegative()) {
          *remainder += y;
          if(quotient) {
            --(*quotient);
          }
        }
      }
    }
  }

  if(remainder) {
    remainder->m_negative = x.m_negative;
  }
  ((BigReal&)y).m_negative = yNegative;
}
示例#28
0
void TimeBoost::SetToNow()
{
	ptime t(microsec_clock::universal_time());
	mTime = t;
}
// decode a given message
BOOL LLTemplateMessageReader::decodeData(const U8* buffer, const LLHost& sender )
{
	llassert( mReceiveSize >= 0 );
	llassert( mCurrentRMessageTemplate);
	llassert( !mCurrentRMessageData );
	delete mCurrentRMessageData; // just to make sure

	// The offset tells us how may bytes to skip after the end of the
	// message name.
	U8 offset = buffer[PHL_OFFSET];
	S32 decode_pos = LL_PACKET_ID_SIZE + (S32)(mCurrentRMessageTemplate->mFrequency) + offset;

	// create base working data set
	mCurrentRMessageData = new LLMsgData(mCurrentRMessageTemplate->mName);
	
	// loop through the template building the data structure as we go
	LLMessageTemplate::message_block_map_t::const_iterator iter;
	for(iter = mCurrentRMessageTemplate->mMemberBlocks.begin();
		iter != mCurrentRMessageTemplate->mMemberBlocks.end();
		++iter)
	{
		LLMessageBlock* mbci = *iter;
		U8	repeat_number;
		S32	i;

		// how many of this block?

		if (mbci->mType == MBT_SINGLE)
		{
			// just one
			repeat_number = 1;
		}
		else if (mbci->mType == MBT_MULTIPLE)
		{
			// a known number
			repeat_number = mbci->mNumber;
		}
		else if (mbci->mType == MBT_VARIABLE)
		{
			// need to read the number from the message
			// repeat number is a single byte
			if (decode_pos >= mReceiveSize)
			{
				// commented out - hetgrid says that missing variable blocks
				// at end of message are legal
				// logRanOffEndOfPacket(sender, decode_pos, 1);

				// default to 0 repeats
				repeat_number = 0;
			}
			else
			{
				repeat_number = buffer[decode_pos];
				decode_pos++;
			}
		}
		else
		{
			llerrs << "Unknown block type" << llendl;
			return FALSE;
		}

		LLMsgBlkData* cur_data_block = NULL;

		// now loop through the block
		for (i = 0; i < repeat_number; i++)
		{
			if (i)
			{
				// build new name to prevent collisions
				// TODO: This should really change to a vector
				cur_data_block = new LLMsgBlkData(mbci->mName, repeat_number);
				cur_data_block->mName = mbci->mName + i;
			}
			else
			{
				cur_data_block = new LLMsgBlkData(mbci->mName, repeat_number);
			}

			// add the block to the message
			mCurrentRMessageData->addBlock(cur_data_block);

			// now read the variables
			for (LLMessageBlock::message_variable_map_t::const_iterator iter = 
					 mbci->mMemberVariables.begin();
				 iter != mbci->mMemberVariables.end(); iter++)
			{
				const LLMessageVariable& mvci = **iter;

				// ok, build out the variables
				// add variable block
				cur_data_block->addVariable(mvci.getName(), mvci.getType());

				// what type of variable?
				if (mvci.getType() == MVT_VARIABLE)
				{
					// variable, get the number of bytes to read from the template
					S32 data_size = mvci.getSize();
					U8 tsizeb = 0;
					U16 tsizeh = 0;
					U32 tsize = 0;

					if ((decode_pos + data_size) > mReceiveSize)
					{
						logRanOffEndOfPacket(sender, decode_pos, data_size);

						// default to 0 length variable blocks
						tsize = 0;
					}
					else
					{
						switch(data_size)
						{
						case 1:
							htonmemcpy(&tsizeb, &buffer[decode_pos], MVT_U8, 1);
							tsize = tsizeb;
							break;
						case 2:
							htonmemcpy(&tsizeh, &buffer[decode_pos], MVT_U16, 2);
							tsize = tsizeh;
							break;
						case 4:
							htonmemcpy(&tsize, &buffer[decode_pos], MVT_U32, 4);
							break;
						default:
							llerrs << "Attempting to read variable field with unknown size of " << data_size << llendl;
							break;
						}
					}
					decode_pos += data_size;

					cur_data_block->addData(mvci.getName(), &buffer[decode_pos], tsize, mvci.getType());
					decode_pos += tsize;
				}
				else
				{
					// fixed!
					// so, copy data pointer and set data size to fixed size
					if ((decode_pos + mvci.getSize()) > mReceiveSize)
					{
						logRanOffEndOfPacket(sender, decode_pos, mvci.getSize());

						// default to 0s.
						U32 size = mvci.getSize();
						std::vector<U8> data(size);
						memset(&(data[0]), 0, size);
						cur_data_block->addData(mvci.getName(), &(data[0]), 
												size, mvci.getType());
					}
					else
					{
						cur_data_block->addData(mvci.getName(), 
												&buffer[decode_pos], 
												mvci.getSize(), 
												mvci.getType());
					}
					decode_pos += mvci.getSize();
				}
			}
		}
	}

	if (mCurrentRMessageData->mMemberBlocks.empty()
		&& !mCurrentRMessageTemplate->mMemberBlocks.empty())
	{
		lldebugs << "Empty message '" << mCurrentRMessageTemplate->mName << "' (no blocks)" << llendl;
		return FALSE;
	}

	{
		static LLTimer decode_timer;

		if(LLMessageReader::getTimeDecodes() || gMessageSystem->getTimingCallback())
		{
			decode_timer.reset();
		}

		{
			LLFastTimer t(LLFastTimer::FTM_PROCESS_MESSAGES);
			if( !mCurrentRMessageTemplate->callHandlerFunc(gMessageSystem) )
			{
				llwarns << "Message from " << sender << " with no handler function received: " << mCurrentRMessageTemplate->mName << llendl;
			}
		}

		if(LLMessageReader::getTimeDecodes() || gMessageSystem->getTimingCallback())
		{
			F32 decode_time = decode_timer.getElapsedTimeF32();

			if (gMessageSystem->getTimingCallback())
			{
				(gMessageSystem->getTimingCallback())(mCurrentRMessageTemplate->mName,
								decode_time,
								gMessageSystem->getTimingCallbackData());
			}

			if (LLMessageReader::getTimeDecodes())
			{
				mCurrentRMessageTemplate->mDecodeTimeThisFrame += decode_time;

				mCurrentRMessageTemplate->mTotalDecoded++;
				mCurrentRMessageTemplate->mTotalDecodeTime += decode_time;

				if( mCurrentRMessageTemplate->mMaxDecodeTimePerMsg < decode_time )
				{
					mCurrentRMessageTemplate->mMaxDecodeTimePerMsg = decode_time;
				}


				if(decode_time > LLMessageReader::getTimeDecodesSpamThreshold())
				{
					lldebugs << "--------- Message " << mCurrentRMessageTemplate->mName << " decode took " << decode_time << " seconds. (" <<
						mCurrentRMessageTemplate->mMaxDecodeTimePerMsg << " max, " <<
						(mCurrentRMessageTemplate->mTotalDecodeTime / mCurrentRMessageTemplate->mTotalDecoded) << " avg)" << llendl;
				}
			}
		}
	}
	return TRUE;
}
/*
    Set up the layout.
*/
void QTabWidget::setUpLayout( bool onlyCheck )
{
    if ( onlyCheck && !d->dirty )
	return; // nothing to do

    if ( !isVisible() ) {
	d->dirty = TRUE;
	return; // we'll do it later
    }

    QSize t( 0, d->stack->frameWidth() );
    if ( d->tabs->isVisibleTo(this) )
	t = d->tabs->sizeHint();
    int lcw = 0;
    if ( d->leftCornerWidget && d->leftCornerWidget->isVisible()  ) {
	QSize sz = d->leftCornerWidget->sizeHint();
	d->leftCornerWidget->resize(sz);
	lcw = sz.width();
	if ( t.height() > lcw )
	    lcw = t.height();
     }
    int rcw = 0;
    if ( d->rightCornerWidget && d->rightCornerWidget->isVisible() ) {
	QSize sz = d->rightCornerWidget->sizeHint();
	d->rightCornerWidget->resize(sz);
	rcw = sz.width();
	if ( t.height() > rcw )
	    rcw = t.height();
    }
    int tw = width() - lcw - rcw;
    if ( t.width() > tw )
	t.setWidth( tw );
    int lw = d->stack->lineWidth();
    bool reverse = QApplication::reverseLayout();
    int tabx, taby, stacky, exty, exth, overlap;

    exth = style().pixelMetric( QStyle::PM_TabBarBaseHeight, this );
    overlap = style().pixelMetric( QStyle::PM_TabBarBaseOverlap, this );

    if ( reverse )
	tabx = QMIN( width() - t.width(), width() - t.width() - lw + 2 ) - lcw;
    else
	tabx = QMAX( 0, lw - 2 ) + lcw;
    if ( d->pos == Bottom ) {
	taby = height() - t.height() - lw;
	stacky = 0;
	exty = taby - (exth - overlap);
    } else { // Top
	taby = 0;
	stacky = t.height()-lw + (exth - overlap);
	exty = taby + t.height() - overlap;
    }

    // do alignment
    int alignment = style().styleHint( QStyle::SH_TabBar_Alignment, this );
    if ( alignment != AlignLeft && t.width() < width() ) {
	if ( alignment == AlignHCenter )
	    tabx += (width()-lcw-rcw)/2 - t.width()/2;
	else if ( alignment == AlignRight )
	    tabx += width() - t.width() - rcw;
    }

    d->tabs->setGeometry( tabx, taby, t.width(), t.height() );
    d->tabBase->setGeometry( 0, exty, width(), exth );
    if ( exth == 0 )
	d->tabBase->hide();
    else
	d->tabBase->show();

    d->stack->setGeometry( 0, stacky, width(), height() - (exth-overlap) -
			   t.height()+QMAX(0, lw-2));

    d->dirty = FALSE;

    // move cornerwidgets
    if ( d->leftCornerWidget ) {
	int y = ( t.height() / 2 ) - ( d->leftCornerWidget->height() / 2 );
	int x = ( reverse ? width() - lcw + y : y );
	d->leftCornerWidget->move( x, y + taby );
    }
    if ( d->rightCornerWidget ) {
	int y = ( t.height() / 2 ) - ( d->rightCornerWidget->height() / 2 );

    if ( !onlyCheck )
	update();
    updateGeometry();
    if ( autoMask() )
	updateMask();
	int x = ( reverse ? y : width() - rcw + y );
	d->rightCornerWidget->move( x, y + taby );
    }
}