示例#1
0
int main()
{
   int x;
   forward(g, x);
}
示例#2
0
void next()
{
	pen_up();
	forward(55);
	pen_down();
}
示例#3
0
文件: relay.c 项目: a2/Soxy
void relay_udp(SOCKS_STATE *state)
{
  fd_set   rfds;
  int      nfds, sfd;
  struct   timeval tv;
  struct   timezone tz;
  ssize_t  wc;
  rlyinfo  ri;
  int      done;
  u_long   max_count = idle_timeout;
  u_long   timeout_count;
  struct sockaddr_storage ss;
  LOGINFO	li;

  memset(&ri, 0, sizeof(ri));
  memset(&li, 0, sizeof(li));
  ri.ss = (struct sockaddr *)&ss;
  ri.flags = 0;
  ri.nr = BUFSIZE-sizeof(UDPH);

  setsignal(SIGALRM, timeout);
  gettimeofday(&li.start, &tz);
  li.bc = li.upl = li.dnl = 0;
  timeout_count = 0;
  for (;;) {
    FD_ZERO(&rfds);
    FD_SET(state->s, &rfds); FD_SET(state->sr.udp->d, &rfds);
    nfds = MAX(state->s, state->sr.udp->d);
    if (state->r >= 0) {
      FD_SET(state->r, &rfds);
      nfds = MAX(nfds, state->r);
    }
    if (state->sr.udp->u >= 0) {
      FD_SET(state->sr.udp->u, &rfds);
      nfds = MAX(nfds, state->sr.udp->u);
    }

    done = 0;
    /* idle timeout related setting. */
    tv.tv_sec = 60; tv.tv_usec = 0;   /* unit = 1 minute. */
    tz.tz_minuteswest = 0; tz.tz_dsttime = 0;
    sfd = select(nfds+1, &rfds, 0, 0, &tv);
    if (sfd > 0) {
      /* UDP channels */
      /* in case of UDP, wc == 0 does not mean EOF (??) */
      if (FD_ISSET(state->sr.udp->d, &rfds)) {
	ri.from = state->sr.udp->d; ri.to = state->sr.udp->u;
	ri.dir = UP;
	if ((wc = forward_udp(&ri, state->sr.udp, state->rtbl.rl_meth)) < 0)
	  done++;
	else
    {
	  li.bc += wc; li.upl += wc;
      if (log_tmp_transfer_callback) log_tmp_transfer_callback(state->si, &li, wc, 0);
    }
	FD_CLR(state->sr.udp->d, &rfds);
      }
      if (state->sr.udp->u >= 0 && FD_ISSET(state->sr.udp->u, &rfds)) {
	ri.from = state->sr.udp->u; ri.to = state->sr.udp->d;
	ri.dir = DOWN;
	if ((wc = forward_udp(&ri, state->sr.udp, state->rtbl.rl_meth)) < 0)
	  done++;
	else
    {
	  li.bc += wc; li.dnl += wc;
      if (log_tmp_transfer_callback) log_tmp_transfer_callback(state->si, &li, wc, 0);
    }
	FD_CLR(state->sr.udp->d, &rfds);
      }
      /* packets on TCP channel may indicate
	 termination of UDP assoc.
      */
      if (FD_ISSET(state->s, &rfds)) {
	ri.from = state->s; ri.to = state->r; ri.flags = 0;
	if ((wc = forward(&ri)) <= 0)
	  done++;
	FD_CLR(state->s, &rfds);
      }
      if (FD_ISSET(state->r >= 0 && state->r, &rfds)) {
	ri.from = state->r; ri.to = state->s; ri.flags = 0;
	if ((wc = forward(&ri)) <= 0)
	  done++;
	FD_CLR(state->r, &rfds);
      }
      if (done > 0)
	break;
    } else if (sfd < 0) {
      if (errno != EINTR)
	break;
    } else { /* sfd == 0 */
      if (max_count != 0) {
	timeout_count++;
	if (timeout_count > max_count)
	  break;
      }
    }
  }

  gettimeofday(&li.end, &tz);
  /* getsockname for logging */
  state->sr.udp->si.myc.len = SS_LEN;
  getsockname(state->sr.udp->d,
	      &state->sr.udp->si.myc.addr.sa,
	      (socklen_t *)&state->sr.udp->si.myc.len);
  if (state->sr.udp->u >= 0) {
    state->sr.udp->si.mys.len = SS_LEN;
    getsockname(state->sr.udp->u,
		&state->sr.udp->si.mys.addr.sa,
		(socklen_t *)&state->sr.udp->si.mys.len);
  }

  log_transfer(&state->sr.udp->si, &li);

  close(state->s);
  if (state->r >= 0)
    close(state->r);
  close(state->sr.udp->d);
  if (state->sr.udp->u >= 0)
    close(state->sr.udp->u);
  if (state->sr.udp != NULL)
    free(state->sr.udp);
}
示例#4
0
 std::size_t operator()( const servus::uint128_t& in ) const
 {
     hash< uint64_t > forward;
     return forward( in.high() ^ in.low( ));
 }
示例#5
0
文件: mp1.cpp 项目: hznlp/pbmt
void MP1::
expectation(CorpusCache& cache){
    double& alpha=alpha_;
    double alphaCount=0;
    for(auto& sp: cache){
        vector<vector<double>> target_probs(sp.m,vector<double>(sp.l,0.0));
        alpha/=sp.n*sp.l;
        for(int j=0;j<sp.m;j++){
            for(int jlen=0;jlen<sp.l;jlen++){
                for(int i=0;i<sp.n;i++){
                    for(int ilen=0;ilen<sp.l;ilen++){
                        if(sp(i,ilen,j,jlen)!=(void*)0){
                            target_probs[j][jlen]+=
                            (sp(i,ilen,j,jlen)->prob*alpha);
                            if(sp(i,ilen,j,jlen)->prob>1){
                                cerr<<"wth prob>1 : "
                                <<sp(i,ilen,j,jlen)->prob<<endl;
                            }
                        }
                    }
                }
                //cout<<target_probs[j][jlen]<<" ";
            }
            //cout<<endl;
        }
        //cout<<endl;

        for(int j=0;j<sp.m;j++){
            for(int jlen=0;jlen<sp.l;jlen++){
                if(target_probs[j][jlen]>1)
                    cerr<<"error :"<<target_probs[j][jlen]<<endl;
                if(target_probs[j][0]==0){
                    target_probs[j][0]=1E-7;
                    //cerr<<"reset error target["<<j<<",0]"<<endl;
                }
            }
        }

        vector<LogProb> forward(sp.m,0.0),backward(sp.m,0.0);
        if(specs.logEM){
            for(auto& i:forward)i=-1E10;
            for(auto& i:backward)i=-1E10;
        }

        //forward[i] is the posterior probability of target words of 1...i+1
        for(int i=0;i<sp.l&&i<sp.m;i++)
            forward[i]=target_probs[0][i];
        for(int i=1;i<(int)forward.size();i++){
            for(int j=1;j<=sp.l&&i-j>=0;j++){
                forward[i]+=forward[i-j]*(LogProb)target_probs[i-j+1][j-1];

            }
        }

        //backward[i] is the posterior probability of target words of i+1...m

        for(int i=0;i<sp.l&&i<sp.m;i++)
            backward[sp.m-i-1]=target_probs[sp.m-i-1][i];
        for(int i=sp.m-2;i>=0;i--){
            for(int j=1;j<=sp.l&&i+j<sp.m;j++){
                backward[i]+=(LogProb)target_probs[i][j-1]*backward[i+j];
            }
        }

        //viterbi
        vector<pair<double,int> > viterbi(sp.m,pair<double,int>(0.0,0));
        for(int i=0;i<sp.l&&i<sp.m;i++)
            viterbi[i]=pair<double,int>(target_probs[0][i],-1);
        for(int i=1;i<(int)forward.size();i++){
            for(int j=1;j<=sp.l&&i-j>=0;j++){
                if(viterbi[i-j].first*target_probs[i-j+1][j-1]>viterbi[i].first)
                    viterbi[i]=
                    make_pair(viterbi[i-j].first*target_probs[i-j+1][j-1],i-j);
            }
        }

        int pos=sp.m-1;
        string sequence="";
        while(pos>=0){
            sequence=to_string(pos)+" "+sequence;
            pos=viterbi[pos].second;
        }
        //cout<<"best seg:"<<sequence<<endl;

        //make sure forward[sp.m-1]==backward[0];
        assert(backward[0]>(LogProb)0);
        if(abs(forward[sp.m-1]-backward[0])>=(LogProb)1e-5*backward[0])
            cerr<<forward[sp.m-1]<<", "<<backward[0]<<endl;
        assert(abs(forward[sp.m-1]-backward[0])<(LogProb)1e-5*backward[0]);
        //cerr<<"backward[0]:"<<backward[0]<<endl;
        //collect fractional count for each phrase pair
        //fraccount=forward[j]*backward[j+jlen]*p(t|s)/backward[0];

        for(int j=0;j<sp.m;j++){
            for(int jlen=0;jlen<sp.l&&j+jlen+1<=sp.m;jlen++){
                double segprob=0;
                LogProb before=1;
                LogProb after=1;
                if(j>0)before=forward[j-1];
                if(j+jlen+1<sp.m)after=backward[j+jlen+1];

                segprob=before*after*(LogProb)target_probs[j][jlen]
                        /backward[0];

                if(segprob>1||segprob<=0){
                    //cerr<<"segprob "<<segprob<<","<<j<<","<<jlen<<endl;
                }
                if(segprob<=0)continue;
                for(int i=0;i<sp.n;i++){
                    for(int ilen=0;ilen<sp.l&&ilen+i+1<=sp.n;ilen++){
                        if(sp(i,ilen,j,jlen)!=(void*)0){
                            double count=sp(i,ilen,j,jlen)->prob*segprob*alpha
                            /target_probs[j][jlen];
                            sp(i,ilen,j,jlen)->count+=count;
                            //cerr<<"before update"<<endl;
                            //sp(i,ilen,j,jlen)->fractype.print(cerr);
                            sp(i,ilen,j,jlen)->fractype.updateLog(count);
                            //cerr<<"after update"<<endl;
                            //sp(i,ilen,j,jlen)->fractype.print(cerr);
                            alphaCount+=count;
                            if(count>1+1e-5)
                                cerr<<i<<","<<ilen<<","<<j
                                <<","<<jlen<<" ["<<sp.m<<","<<sp.n<<"]"
                                <<",count "<<count
                                <<", target probs "
                                <<target_probs[j][jlen]<<endl;
                        }
                    }
                }
            }
        }
        alpha*=sp.n*sp.l;
    }
    //cerr<<alphaCount<<","<<cache.size()<<endl;
    alpha=alphaCount/(alphaCount+cache.size());
}
示例#6
0
static size_t ListScan(void *p) {
    List *list = p;
    list->term = forward(list->term);
    list->next = forward(list->next);
    return sizeof (List);
}
示例#7
0
void visitGCRoot(void **root, const void *meta) {
  forward((universal_t *)root);
}
示例#8
0
void QucsHelp::setupActions()
{
  QToolBar *toolbar = new QToolBar(this,"main_toolbar");

  this->addToolBar(toolbar);

  QMenuBar *bar = menuBar();

  const QKeySequence ks = QKeySequence();

  QAction *quitAction = new QAction(QIcon((":/bitmaps/quit.png")),
                                    tr("&Quit"), (const QKeySequence&)Qt::CTRL+Qt::Key_Q, this,"");
  QAction *backAction = new QAction(QIcon((":/bitmaps/back.png")),
                                    tr("&Back"), Qt::ALT+Qt::Key_Left, this,"");
  QAction *forwardAction = new QAction(QIcon((":/bitmaps/forward.png")),
                                       tr("&Forward"), Qt::ALT+Qt::Key_Right, this,"");
  QAction *homeAction = new QAction(QIcon((":/bitmaps/home.png")),
                                    tr("&Home"),Qt::CTRL+Qt::Key_H,this,"");
  previousAction = new QAction(QIcon((":/bitmaps/previous.png")),tr("&Previous"),
                               ks, this,"");
  nextAction = new QAction(QIcon((":/bitmaps/next.png")),
                           tr("&Next"), ks, this,"");
  viewBrowseDock = new QAction(tr("&Table of Contents"), 0, this,"");
  viewBrowseDock->setToggleAction(true);
  viewBrowseDock->setOn(true);
  viewBrowseDock->setStatusTip(tr("Enables/disables the table of contents"));
  viewBrowseDock->setWhatsThis(tr("Table of Contents\n\nEnables/disables the table of contents"));

  connect(quitAction,SIGNAL(activated()),qApp,SLOT(quit()));

  connect(backAction,SIGNAL(activated()),textBrowser,SLOT(backward()));
  connect(textBrowser,SIGNAL(backwardAvailable(bool)),backAction,SLOT(setEnabled(bool)));

  connect(forwardAction,SIGNAL(activated()),textBrowser,SLOT(forward()));
  connect(textBrowser,SIGNAL(forwardAvailable(bool)),forwardAction,SLOT(setEnabled(bool)));

  connect(homeAction,SIGNAL(activated()),textBrowser,SLOT(home()));
  connect(homeAction,SIGNAL(activated()),this,SLOT(gohome()));

  connect(textBrowser,SIGNAL(sourceChanged(const QUrl &)),this,SLOT(slotSourceChanged(const QUrl &)));
  connect(previousAction,SIGNAL(activated()),this,SLOT(previousLink()));
  connect(nextAction,SIGNAL(activated()),this,SLOT(nextLink()));
  connect(viewBrowseDock, SIGNAL(toggled(bool)), SLOT(slotToggleSidebar(bool)));

  backAction->addTo(toolbar);
  forwardAction->addTo(toolbar);
  toolbar->addSeparator();
  homeAction->addTo(toolbar);
  previousAction->addTo(toolbar);
  nextAction->addTo(toolbar);
  toolbar->addSeparator();
  quitAction->addTo(toolbar);

  QMenu *fileMenu = new QMenu(this);
  quitAction->addTo(fileMenu);

  QMenu *viewMenu = new QMenu(this);
  backAction->addTo(viewMenu);
  forwardAction->addTo(viewMenu);
  homeAction->addTo(viewMenu);
  previousAction->addTo(viewMenu);
  nextAction->addTo(viewMenu);
  viewMenu->insertSeparator();
  viewBrowseDock->addTo(viewMenu);

  QMenu *helpMenu = new QMenu(this);
  helpMenu->insertItem(tr("&About Qt"),qApp,SLOT(aboutQt()));

  bar->insertItem(tr("&File"), fileMenu );
  bar->insertItem(tr("&View"),viewMenu);
  bar->insertSeparator();
  bar->insertItem(tr("&Help"),helpMenu);
}
示例#9
0
Vec3 Camera::right(bool remove_y) {
	return Vec3::normalize(Vec3::cross(Vec3(0.0f, 1.0f, 0.0f), forward(remove_y)));	
}
示例#10
0
/** 
 * Injects customers into the network using forward.
 * The initial location of the customer is the source node.
 */
void Source::injectCustomer() {
	Customer *c =  buildCustomer() ;
	c->setLocation( this ) ;
	forward( c ) ;
}
示例#11
0
void forward_mm(unsigned int DistanceInMM)
{
 forward();
 linear_distance_mm(DistanceInMM);
}
示例#12
0
int webPage::qt_metacall(QMetaObject::Call _c, int _id, void **_a)
{
    _id = QMainWindow::qt_metacall(_c, _id, _a);
    if (_id < 0)
        return _id;
    if (_c == QMetaObject::InvokeMetaMethod) {
        switch (_id) {
        case 0: loading((*reinterpret_cast< QString(*)>(_a[1]))); break;
        case 1: isLoading((*reinterpret_cast< QPixmap(*)>(_a[1]))); break;
        case 2: titleChanged((*reinterpret_cast< QString(*)>(_a[1]))); break;
        case 3: pageChanged((*reinterpret_cast< QString(*)>(_a[1])),(*reinterpret_cast< QString(*)>(_a[2]))); break;
        case 4: showSources((*reinterpret_cast< QString(*)>(_a[1]))); break;
        case 5: speedDial(); break;
        case 6: needPrint((*reinterpret_cast< QPrinter*(*)>(_a[1]))); break;
        case 7: openTab((*reinterpret_cast< webPage*(*)>(_a[1]))); break;
        case 8: setFullScreen((*reinterpret_cast< bool(*)>(_a[1]))); break;
        case 9: startLoading(); break;
        case 10: finishLoading((*reinterpret_cast< bool(*)>(_a[1]))); break;
        case 11: changeTitle((*reinterpret_cast< QString(*)>(_a[1]))); break;
        case 12: changeUrl((*reinterpret_cast< QUrl(*)>(_a[1]))); break;
        case 13: goToHome(); break;
        case 14: loadUrl(); break;
        case 15: loadUrl((*reinterpret_cast< QUrl(*)>(_a[1]))); break;
        case 16: loadUrl((*reinterpret_cast< QString(*)>(_a[1]))); break;
        case 17: addToBookMark(); break;
        case 18: downloadFile((*reinterpret_cast< const QNetworkRequest(*)>(_a[1]))); break;
        case 19: downloadFile((*reinterpret_cast< QNetworkReply*(*)>(_a[1]))); break;
        case 20: loadBookMark(); break;
        case 21: showBookMark(); break;
        case 22: sources(); break;
        case 23: defineHome(); break;
        case 24: findNext(); break;
        case 25: findPrevious(); break;
        case 26: print(); break;
        case 27: createNewPage((*reinterpret_cast< WebView*(*)>(_a[1]))); break;
        case 28: createNewPage(); break;
        case 29: updateIcon(); break;
        case 30: copy(); break;
        case 31: authentification((*reinterpret_cast< QNetworkReply*(*)>(_a[1])),(*reinterpret_cast< QAuthenticator*(*)>(_a[2]))); break;
        case 32: inspectPage(); break;
        case 33: goToDial(); break;
        case 34: updateUrlIcon((*reinterpret_cast< QPixmap(*)>(_a[1]))); break;
        case 35: updateBookMark(); break;
        case 36: updateOptions(); break;
        case 37: showBar(); break;
        case 38: showPage(); break;
        case 39: showDial(); break;
        case 40: inCache(); break;
        case 41: showConsole(); break;
        case 42: zoomIn(); break;
        case 43: zoomOut(); break;
        case 44: restoreZoom(); break;
        case 45: savePage(); break;
        case 46: back(); break;
        case 47: forward(); break;
        default: ;
        }
        _id -= 48;
    }
    return _id;
}
示例#13
0
HelpWindow::HelpWindow( const QString & home_, const QString & _path, QWidget * parent )
    : QMainWindow( parent ), pathCombo( 0 ), selectedURL()
{
    setWindowIcon( QPixmap( RingDir + "xdrawchem-icon.png" ) );

    browser = new QTextBrowser( this );

//    browser->setSearchPaths( _path );
    browser->setFrameStyle( QFrame::Panel | QFrame::Sunken );
    connect( browser, SIGNAL( sourceChanged( const QUrl & ) ), this, SLOT( sourceChanged( const QUrl & ) ) );

    setCentralWidget( browser );

    if ( !home_.isEmpty() )
        browser->setSource( home_ );

    connect( browser, SIGNAL( highlighted( const QString & ) ), statusBar(), SLOT( showMessage( const QString & ) ) );

    resize( 640, 700 );

    QMenu *file = new QMenu( tr( "&File" ), this );

    file->addAction( tr( "&Print" ), this, SLOT( print() ), Qt::CTRL + Qt::Key_P );
    file->addSeparator();
    file->addAction( tr( "&Close" ), this, SLOT( close() ), Qt::CTRL + Qt::Key_W );

    // The same three icons are used twice each.
    QIcon icon_back( QPixmap( RingDir + "back.xpm" ) );
    QIcon icon_forward( QPixmap( RingDir + "forward.xpm" ) );
    QIcon icon_home( QPixmap( RingDir + "home.xpm" ) );

    QMenu *go = new QMenu( tr( "&Go" ), this );

    backwardAction = go->addAction( icon_back, tr( "&Backward" ), browser, SLOT( backward() ), Qt::CTRL + Qt::Key_Left );
    forwardAction = go->addAction( icon_forward, tr( "&Forward" ), browser, SLOT( forward() ), Qt::CTRL + Qt::Key_Right );
    homeAction = go->addAction( icon_home, tr( "&Home" ), browser, SLOT( home() ) );

    QMenu *help = new QMenu( tr( "&Help" ), this );

    help->addAction( tr( "&About ..." ), this, SLOT( about() ) );

    menuBar()->addMenu( file );
    menuBar()->addMenu( go );
    menuBar()->addMenu( help );

    forwardAction->setEnabled( FALSE );
    backwardAction->setEnabled( FALSE );

    connect( browser, SIGNAL( backwardAvailable( bool ) ), SLOT( setBackwardAvailable( bool ) ) );
    connect( browser, SIGNAL( forwardAvailable( bool ) ), SLOT( setForwardAvailable( bool ) ) );


    QToolBar *toolbar = new QToolBar( this );

    addToolBar( Qt::TopToolBarArea, toolbar );
//    QToolButton *button;

    toolbar->addAction( backwardAction );
    toolbar->addAction( forwardAction );
    toolbar->addAction( homeAction );

    toolbar->addSeparator();

    pathCombo = new QComboBox( toolbar );
    pathCombo->setSizePolicy( QSizePolicy( QSizePolicy::Expanding, QSizePolicy::Minimum ) );
    connect( pathCombo, SIGNAL( activated( const QString & ) ), SLOT( pathSelected( const QString & ) ) );

    toolbar->addWidget( pathCombo );
    pathCombo->addItem( home_ );
    browser->setFocus();

}
示例#14
0
void ConvexHullDistanceDemo::updateCamera() {
#else
void updateCamera() {
#endif



	glMatrixMode(GL_PROJECTION);
	glLoadIdentity();
	btScalar rele = 0;
	btScalar razi = 0;
	btVector3 m_cameraUp(0,1,0);
	btScalar m_cameraDistance = 10.f;
	btVector3 m_cameraPosition;
	

	btVector3 m_cameraTargetPosition = (tr[0].getOrigin()+tr[1].getOrigin())*0.5;


	btQuaternion rot(m_cameraUp,razi);


	int m_forwardAxis = 2;

	btVector3 eyePos(0,0,0);
	eyePos[m_forwardAxis] = -m_cameraDistance;

	btVector3 forward(eyePos[0],eyePos[1],eyePos[2]);
	if (forward.length2() < SIMD_EPSILON)
	{
		forward.setValue(1.f,0.f,0.f);
	}
	btVector3 right = m_cameraUp.cross(forward);
	btQuaternion roll(right,-rele);

	eyePos = btMatrix3x3(rot) * btMatrix3x3(roll) * eyePos;

	m_cameraPosition[0] = eyePos.getX();
	m_cameraPosition[1] = eyePos.getY();
	m_cameraPosition[2] = eyePos.getZ();
	m_cameraPosition += m_cameraTargetPosition;

	if (m_glutScreenWidth == 0 && m_glutScreenHeight == 0)
		return;

	btScalar aspect;
	btVector3 extents;

	if (m_glutScreenWidth > m_glutScreenHeight) 
	{
		aspect = m_glutScreenWidth / (btScalar)m_glutScreenHeight;
		extents.setValue(aspect * 1.0f, 1.0f,0);
	} else 
	{
		aspect = m_glutScreenHeight / (btScalar)m_glutScreenWidth;
		extents.setValue(1.0f, aspect*1.f,0);
	}

	
	if (m_ortho)
	{
		// reset matrix
		glLoadIdentity();
		
		
		extents *= m_cameraDistance;
		btVector3 lower = m_cameraTargetPosition - extents;
		btVector3 upper = m_cameraTargetPosition + extents;
		//gluOrtho2D(lower.x, upper.x, lower.y, upper.y);
		glOrtho(lower.getX(), upper.getX(), lower.getY(), upper.getY(),-1000,1000);
		
		glMatrixMode(GL_MODELVIEW);
		glLoadIdentity();
		//glTranslatef(100,210,0);
	} else
	{
		if (m_glutScreenWidth > m_glutScreenHeight) 
		{
//			glFrustum (-aspect, aspect, -1.0, 1.0, 1.0, 10000.0);
			glFrustum (-aspect * m_frustumZNear, aspect * m_frustumZNear, -m_frustumZNear, m_frustumZNear, m_frustumZNear, m_frustumZFar);
		} else 
		{
//			glFrustum (-1.0, 1.0, -aspect, aspect, 1.0, 10000.0);
			glFrustum (-aspect * m_frustumZNear, aspect * m_frustumZNear, -m_frustumZNear, m_frustumZNear, m_frustumZNear, m_frustumZFar);
		}
		glMatrixMode(GL_MODELVIEW);
		glLoadIdentity();
		gluLookAt(m_cameraPosition[0], m_cameraPosition[1], m_cameraPosition[2], 
			m_cameraTargetPosition[0], m_cameraTargetPosition[1], m_cameraTargetPosition[2], 
			m_cameraUp.getX(),m_cameraUp.getY(),m_cameraUp.getZ());
	}

}
示例#15
0
void turtle_t::exec(turtle_com_t *com)
{
  if (com->cname==F)
    {
      turtle_fwd_t* fcom = dynamic_cast<turtle_fwd_t*>(com);
      if (fcom) forward(fcom->dist);
    }
  else if (com->cname==B)
    {
      turtle_bck_t* bcom = dynamic_cast<turtle_bck_t*>(com);
      if (bcom) back(bcom->dist);
    }
  else if (com->cname==L)
    {
      turtle_lft_t* lcom = dynamic_cast<turtle_lft_t*>(com);
      if (lcom) turn_left(lcom->angl);
    }
  else if (com->cname==R)
    {
      turtle_rht_t* rcom = dynamic_cast<turtle_rht_t*>(com);
      if (rcom) turn_right(rcom->angl);
    }
  else if (com->cname==MF)
    {
      turtle_mfwd_t* mfcom = dynamic_cast<turtle_mfwd_t*>(com);
      if (mfcom) forward_move(mfcom->dist);
    }
  else if (com->cname==MB)
    {
      turtle_mbck_t* mbcom = dynamic_cast<turtle_mbck_t*>(com);
      if (mbcom) backward_move(mbcom->dist);
    }
  else if (com->cname==CLS)
    {
      turtle_cls_t* clscom = dynamic_cast<turtle_cls_t*>(com);
      if (clscom) clear();
    }
  else if (com->cname==RESET)
    {
      turtle_rst_t* rstcom = dynamic_cast<turtle_rst_t*>(com);
      if (rstcom) reset();
    }
  else if (com->cname==COL)
    {
      turtle_col_t* colcom = dynamic_cast<turtle_col_t*>(com);
      if (colcom) set_col(colcom->r, colcom->g, colcom->b);
    }
  else if (com->cname==BGCOL)
    {
      turtle_bgcol_t* bgcolcom = dynamic_cast<turtle_bgcol_t*>(com);
      if (bgcolcom) set_bgcol(bgcolcom->r, bgcolcom->g, bgcolcom->b);
    }
  else if (com->cname==SCALE)
    {
      turtle_scale_t* scalecom = dynamic_cast<turtle_scale_t*>(com);
      if (scalecom) scale(scalecom->s);
    }
  else if (com->cname==REPEAT)
    {
      turtle_rep_t *repcom = dynamic_cast<turtle_rep_t*>(com);

      if (repcom)
	{
	  unsigned int times = repcom->times;
	  turtle_com_list_t sublist = repcom->replist;
	  repeat(times, sublist);
	}
     }
  else if ((com->cname==ENDREP) || (com->cname==END) || (com->cname==BEGIN)) 
    {
      //These commands are place holders and used for program structure
      //But no execution is necessary - generate a NoOP
      ;
    }
  else
    {
      std::cerr<<"Unknown Command: Ignoring"<<std::endl;
      exit(-1);
    }
}
示例#16
0
Vec3 Camera::up() {
	return Vec3::normalize(Vec3::cross(forward(), right()));
}
//-----------------------------------------------------------------------------
// Strider muzzle flashes
//-----------------------------------------------------------------------------
void QUA_MuzzleFlash_Strider(ClientEntityHandle_t hEntity, int attachmentIndex)
{
	VPROF_BUDGET( "QUA_MuzzleFlash_Strider", VPROF_BUDGETGROUP_PARTICLE_RENDERING );

	matrix3x4_t	matAttachment;
	// If the client hasn't seen this entity yet, bail.
	if (!FX_GetAttachmentTransform(hEntity, attachmentIndex, matAttachment))
		return;

	CSmartPtr<CLocalSpaceEmitter> pSimple = CLocalSpaceEmitter::Create("QUA_MuzzleFlash_Strider", hEntity, attachmentIndex);

	SimpleParticle *pParticle;
	Vector			forward(1,0,0), offset; //NOTENOTE: All coords are in local space

	float flScale = random->RandomFloat( 3.0f, 4.0f );

	float burstSpeed = random->RandomFloat( 400.0f, 600.0f );

#define	FRONT_LENGTH 12

	// Front flash
	for ( int i = 1; i < FRONT_LENGTH; i++ )
	{
		offset = (forward * (i*2.0f*flScale));

		pParticle = (SimpleParticle *) pSimple->AddParticle( sizeof( SimpleParticle ), pSimple->GetPMaterial( VarArgs( "effects/combinemuzzle%d", random->RandomInt(1,2) ) ), offset );
			
		if ( pParticle == NULL )
			return;

		pParticle->m_flLifetime		= 0.0f;
		pParticle->m_flDieTime		= 0.1f;

		pParticle->m_vecVelocity = forward * burstSpeed;

		pParticle->m_uchColor[0]	= 255;
		pParticle->m_uchColor[1]	= 255;
		pParticle->m_uchColor[2]	= 255;

		pParticle->m_uchStartAlpha	= 255.0f;
		pParticle->m_uchEndAlpha	= 0;

		pParticle->m_uchStartSize	= ( (random->RandomFloat( 6.0f, 8.0f ) * (FRONT_LENGTH-(i))/(FRONT_LENGTH*0.75f)) * flScale );
		pParticle->m_uchEndSize		= pParticle->m_uchStartSize;
		pParticle->m_flRoll			= random->RandomInt( 0, 360 );
		pParticle->m_flRollDelta	= 0.0f;
	}
	
	Vector right(0,1,0), up(0,0,1);
	Vector dir = right - up;

#define	SIDE_LENGTH	8

	burstSpeed = random->RandomFloat( 400.0f, 600.0f );

	// Diagonal flash
	for ( int i = 1; i < SIDE_LENGTH; i++ )
	{
		offset = (dir * (i*flScale));

		pParticle = (SimpleParticle *) pSimple->AddParticle( sizeof( SimpleParticle ), pSimple->GetPMaterial( VarArgs( "effects/combinemuzzle%d", random->RandomInt(1,2) ) ), offset );
			
		if ( pParticle == NULL )
			return;

		pParticle->m_flLifetime		= 0.0f;
		pParticle->m_flDieTime		= 0.2f;

		pParticle->m_vecVelocity = dir * burstSpeed * 0.25f;

		pParticle->m_uchColor[0]	= 255;
		pParticle->m_uchColor[1]	= 255;
		pParticle->m_uchColor[2]	= 255;

		pParticle->m_uchStartAlpha	= 255;
		pParticle->m_uchEndAlpha	= 0;

		pParticle->m_uchStartSize	= ( (random->RandomFloat( 2.0f, 4.0f ) * (SIDE_LENGTH-(i))/(SIDE_LENGTH*0.5f)) * flScale );
		pParticle->m_uchEndSize		= pParticle->m_uchStartSize;
		pParticle->m_flRoll			= random->RandomInt( 0, 360 );
		pParticle->m_flRollDelta	= 0.0f;
	}

	dir = right + up;
	burstSpeed = random->RandomFloat( 400.0f, 600.0f );

	// Diagonal flash
	for ( int i = 1; i < SIDE_LENGTH; i++ )
	{
		offset = (-dir * (i*flScale));

		pParticle = (SimpleParticle *) pSimple->AddParticle( sizeof( SimpleParticle ), pSimple->GetPMaterial( VarArgs( "effects/combinemuzzle%d", random->RandomInt(1,2) ) ), offset );
			
		if ( pParticle == NULL )
			return;

		pParticle->m_flLifetime		= 0.0f;
		pParticle->m_flDieTime		= 0.2f;

		pParticle->m_vecVelocity = dir * -burstSpeed * 0.25f;

		pParticle->m_uchColor[0]	= 255;
		pParticle->m_uchColor[1]	= 255;
		pParticle->m_uchColor[2]	= 255;

		pParticle->m_uchStartAlpha	= 255;
		pParticle->m_uchEndAlpha	= 0;

		pParticle->m_uchStartSize	= ( (random->RandomFloat( 2.0f, 4.0f ) * (SIDE_LENGTH-(i))/(SIDE_LENGTH*0.5f)) * flScale );
		pParticle->m_uchEndSize		= pParticle->m_uchStartSize;
		pParticle->m_flRoll			= random->RandomInt( 0, 360 );
		pParticle->m_flRollDelta	= 0.0f;
	}

	dir = up;
	burstSpeed = random->RandomFloat( 400.0f, 600.0f );

	// Top flash
	for ( int i = 1; i < SIDE_LENGTH; i++ )
	{
		offset = (dir * (i*flScale));

		pParticle = (SimpleParticle *) pSimple->AddParticle( sizeof( SimpleParticle ), pSimple->GetPMaterial( VarArgs( "effects/combinemuzzle%d", random->RandomInt(1,2) ) ), offset );
			
		if ( pParticle == NULL )
			return;

		pParticle->m_flLifetime		= 0.0f;
		pParticle->m_flDieTime		= 0.2f;

		pParticle->m_vecVelocity = dir * burstSpeed * 0.25f;

		pParticle->m_uchColor[0]	= 255;
		pParticle->m_uchColor[1]	= 255;
		pParticle->m_uchColor[2]	= 255;

		pParticle->m_uchStartAlpha	= 255;
		pParticle->m_uchEndAlpha	= 0;

		pParticle->m_uchStartSize	= ( (random->RandomFloat( 2.0f, 4.0f ) * (SIDE_LENGTH-(i))/(SIDE_LENGTH*0.5f)) * flScale );
		pParticle->m_uchEndSize		= pParticle->m_uchStartSize;
		pParticle->m_flRoll			= random->RandomInt( 0, 360 );
		pParticle->m_flRollDelta	= 0.0f;
	}

	pParticle = (SimpleParticle *) pSimple->AddParticle( sizeof( SimpleParticle ), pSimple->GetPMaterial( "effects/strider_muzzle" ), vec3_origin );
		
	if ( pParticle == NULL )
		return;

	pParticle->m_flLifetime		= 0.0f;
	pParticle->m_flDieTime		= random->RandomFloat( 0.3f, 0.4f );

	pParticle->m_vecVelocity.Init();

	pParticle->m_uchColor[0]	= 255;
	pParticle->m_uchColor[1]	= 255;
	pParticle->m_uchColor[2]	= 255;

	pParticle->m_uchStartAlpha	= 255;
	pParticle->m_uchEndAlpha	= 0;

	pParticle->m_uchStartSize	= flScale * random->RandomFloat( 12.0f, 16.0f );
	pParticle->m_uchEndSize		= 0.0f;
	pParticle->m_flRoll			= random->RandomInt( 0, 360 );
	pParticle->m_flRollDelta	= 0.0f;

	Vector		origin;
	MatrixGetColumn( matAttachment, 3, &origin );

	int entityIndex = ClientEntityList().HandleToEntIndex(hEntity);
	if (entityIndex >= 0)
	{
		dlight_t *el = effects->CL_AllocElight(LIGHT_INDEX_MUZZLEFLASH + entityIndex);

		el->origin = origin;

		el->color.r = 64;
		el->color.g = 128;
		el->color.b = 255;
		el->color.exponent = 5;

		el->radius = random->RandomInt(100, 150);
		el->decay = el->radius / 0.05f;
		el->die = gpGlobals->curtime + 0.1f;
	}
}
示例#18
0
void MyTextBrowser::moveContent(int pos)
{
  if(pos >= '\t' || pos < 0)
  {
     activateWindow();
     char text[16];
     text[0] = pos & 0x0ff;
     text[1] = '\0';
     int modifiers = pos & 0x07fffff00;
     int key = pos & 0x0ff;
     if     ((pos & 0x0ff) == '\t') key = Qt::Key_Tab;
     else if((pos & 0x0ff) == 0x0d) key = Qt::Key_Return;
     QKeyEvent pressEvent(  QEvent::KeyPress,   (Qt::Key) key, (Qt::KeyboardModifiers) modifiers, text);
     QKeyEvent releaseEvent(QEvent::KeyRelease, (Qt::Key) key, (Qt::KeyboardModifiers) modifiers, text);
     if((pos & 0x0ff) == '\t') QWidget::setFocus(Qt::TabFocusReason);
     keyPressEvent(&pressEvent);
     keyReleaseEvent(&releaseEvent);
     return;
  }
#ifdef MY_NO_WEBKIT
  char buf[MAX_PRINTF_LENGTH];
  QString myurl;

  if(opt.arg_debug) printf("moveContent(%d)\n", pos);
  if     (pos == 0 && homeIsSet) 
  { 
    myurl = home; 
    setSource(QUrl(home)); 
  }
  else if(pos == 1)              
  { 
    forward();
    myurl = source().path();
  }  
  else if(pos == 2) 
  {
    backward();
    myurl = source().path();
  }  
  else if(pos == 3) 
  {
    reload();
    myurl = source().path();
  }  
#else
  char buf[MAX_PRINTF_LENGTH];
  QString myurl;
/*v5diff
  QWebHistory *hist;

  if(opt.arg_debug) printf("moveContent(%d)\n", pos);
  if     (pos == 0 && homeIsSet) 
  { 
    myurl = home; 
    load(home); 
  }
  else if(pos == 1)              
  { 
    hist = history();
    if(hist != NULL && hist->canGoForward()) myurl = hist->forwardItem().url().toString(); 
    forward();
  }  
  else if(pos == 2) 
  {
    hist = history();
    if(hist != NULL && hist->canGoBack()) myurl = hist->backItem().url().toString(); 
    back();
  }  
  else if(pos == 3) 
  {
    hist = history();
    if(hist != NULL) myurl = hist->currentItem().url().toString(); 
    reload();
  }
*/  
#endif

  if(myurl.isEmpty()) return;
  if(opt.arg_debug) printf("moveContent(%s)\n", (const char *) myurl.toUtf8());
  if(myurl.length()+40 > MAX_PRINTF_LENGTH) return;
  sprintf(buf,"text(%d,\"%s\")\n", id,decode(myurl));
  tcp_send(s,buf,strlen(buf));
}
示例#19
0
void draw_my_name()
{
	pen_colour(BLACK);
	pen_down();
	turn(RIGHT);
	forward(100);
	turn(LEFT);
	forward(200);
	turn(LEFT);
	forward(100);
	pen_up();
	forward(-50);
	turn(LEFT);
	pen_down();
	forward(200);
	pen_up();
	
	turn(LEFT);
	forward(100);
	turn(LEFT);
	forward(100);
	turn(180);
	
	pen_down();
	forward(100);
	turn(LEFT);
	forward(50);
	turn(LEFT);
	forward(100);
	pen_up();
	
	turn(RIGHT);
	forward(50);
	
	pen_down();
	forward(50);
	turn(RIGHT);
	forward(100);
	turn(RIGHT);
	forward(50);
	turn(RIGHT);
	forward(50);
	turn(RIGHT);
	forward(50);
	pen_up();
	
	forward(50);
	turn(RIGHT);
	forward(50);
	turn(180);
	
	pen_down();
	forward(100);
	turn(RIGHT);
	forward(50);
	turn(RIGHT);
	forward(100);
	pen_up();
}
示例#20
0
/******************************************************************
*
*  Basic copying collection (modified cheney algorithm)
*
******************************************************************/
void gc_copy(GCGenHeap fromHeap, GCGenHeap toHeap) {

#ifdef DEBUG_GC
  printf("gc: llvm root chain=%zu\n", (uintptr_t)llvm_gc_root_chain);
  if (llvm_gc_root_chain) {
    printf("gc: llvm root chain base stack num roots = %d\n",
           llvm_gc_root_chain->Map->NumRoots);
  }
  print_heap_region();
#endif


  uintptr_t *scan = 0;
  if (reserve == toHeap) {
    scan = heap->end_old;
  } else {
    scan = heap->start;
  }


  // forward global roots
  for (int i = 0; i < MJCglobal_roots_size; i++) {

    if (is_heap_pointer(MJCglobal_roots[i], fromHeap)) {
#ifdef DEBUG_GC
      printf("gc: forwarding global root object at %zu\n",
             (uintptr_t)(MJCglobal_roots[i]));
#endif

      MJCglobal_roots[i] = forward(MJCglobal_roots[i], fromHeap, toHeap);
    } else {
#ifdef DEBUG_GC
      printf("gc:  global root not forwarded (wrong heap gen or type): %zu\n",
             (uintptr_t)(MJCglobal_roots[i]));
#endif
    }

  }

  /* only need to evaluate assignment sets during minor collection */
  if (nursery == fromHeap) {
    for (GlobalRootEntry *assignpos =  MJC_gc_assignment_chain; assignpos != NULL;
         assignpos = (GlobalRootEntry*)assignpos->next) {

      if (is_heap_pointer(*assignpos->root, fromHeap)) {
#ifdef DEBUG_GC
        printf("gc: forwarding assignment root object at %zu\n",
               (uintptr_t)(*assignpos->root));
#endif

        *(assignpos->root) = forward(*assignpos->root, fromHeap, toHeap);
      } else {
#ifdef DEBUG_GC
        printf("gc:  assignment not forwarded (wrong heap gen or type): %zu\n",
               (uintptr_t)(*assignpos->root));
#endif
      }
    }
  }

  // forward roots
  for (StackEntry *rootpos =  llvm_gc_root_chain; rootpos != NULL;
       rootpos = (StackEntry*)rootpos->Next) {

    for (int i = 0; i < rootpos->Map->NumRoots; i++) {

      if (is_heap_pointer((uintptr_t *)(rootpos->Roots[i]), fromHeap)) {
#ifdef DEBUG_GC
        printf("gc: forwarding root object at %zu\n", (uintptr_t)rootpos->Roots[i]);
#endif

        rootpos->Roots[i] = forward((uintptr_t*)rootpos->Roots[i], fromHeap, toHeap);
      } else {
#ifdef DEBUG_GC
        printf("gc: root not forwarded (wrong heap gen or type): %zu\n",
               (uintptr_t)rootpos->Roots[i]);
#endif
      }
    }
  }

  //printf("heap before scan\n");
  //print_heap();

  uintptr_t *free = 0;
  if (reserve == toHeap) {
    free = heap->reserve_avail;
  } else {
    free = heap->old_avail;
  }


  // scan the tospace (make sure to increment by size)
  while (scan < free) {

    if (is_heap_pointer((uintptr_t*)*scan, fromHeap)) {

#ifdef DEBUG_GC
      printf("gc: forwarding scanned object at %zu\n", (uintptr_t)*scan);
#endif

      // forward the object pointed to by scan
      *scan = (uintptr_t)forward((void *)(*scan), fromHeap, toHeap);

      // update free
      if (reserve == toHeap) {
        free = heap->reserve_avail;
      } else {
        free = heap->old_avail;
      }
    }

    scan++;
  }
}
示例#21
0
bumpptr_t coq_gc(void) {
  struct timespec before;
  clock_gettime(CLOCK_PROCESS_CPUTIME_ID, &before);

  universal_t *tospace = (curbot == tobot) ? frombot : tobot;
  if (mprotect((void *)tospace,heapsize,PROT_READ|PROT_WRITE) != 0)
    fprintf(stderr, "Warning: failed to unprotect unused space\n");

  /* initialize the queue in tospace */
  queueptr = (curbot == frombot) ? tobot : frombot;
  endptr = queueptr;

  if (debug) {
    fprintf(stderr, "Starting gc collection... ");
  }

  /* Call forward on the roots */
  visitGCRoots(&visitGCRoot);

  /* iterate the worklist until we're done copying */
  while (queueptr < endptr) {
    universal_t *objref = queueptr+1;
    assert(is_rec(objref)); /* all heap allocations are records */
    queueptr += rec_len(objref) + 1;
    do {
      forward(objref++);
    } while (objref < queueptr);
  }

  if (debug) {
    fprintf(stderr, "done.\n");
  }

  /* Protect the not in use space to detect errors */
  if (mprotect((void *)curbot,heapsize,PROT_NONE) != 0) {
    fprintf(stderr, "Warning: failed to mprotect unused space\n");
  }

  /* Swap spaces and return the new bump pointers */
  if (curtop == fromtop) {
    curbot = tobot;
    curtop = totop;
  } else {
    curbot = frombot;
    curtop = fromtop;
  }
  assert(curbot <= endptr && endptr <= curtop);

  /* Statistics */
  struct timespec after;
  clock_gettime(CLOCK_PROCESS_CPUTIME_ID, &after);
  struct timespec diff;
  if ((after.tv_nsec-before.tv_nsec)<0) {
    diff.tv_sec = after.tv_sec-before.tv_sec-1;
    diff.tv_nsec = 1000000000+after.tv_nsec-before.tv_nsec;
  } else {
    diff.tv_sec = after.tv_sec-before.tv_sec;
    diff.tv_nsec = after.tv_nsec-before.tv_nsec;
  }
  collections++;
  collectionTime.tv_sec += diff.tv_sec;
  collectionTime.tv_nsec += diff.tv_nsec;
  if (collectionTime.tv_nsec >= 1000000000) {
    collectionTime.tv_nsec -= 1000000000;
    collectionTime.tv_sec += 1;
  }

  /* allocation starts at the end of the queue */
  return (bumpptr_t) { .base = endptr, .limit = curtop };
}
void Kinematics::init(){
    recomputeGeometry();
    if (sys.state != STATE_OLD_SETTINGS){
      forward(leftAxis.read(), rightAxis.read(), &sys.xPosition, &sys.yPosition, sys.xPosition, sys.yPosition);
    }
}
示例#23
0
void BtApplication::updateCamera() {


	glMatrixMode(GL_PROJECTION);
	glLoadIdentity();
	btScalar rele = m_ele * btScalar(0.01745329251994329547);// rads per deg
	btScalar razi = m_azi * btScalar(0.01745329251994329547);// rads per deg


	btQuaternion rot(m_cameraUp,razi);


	btVector3 eyePos(0,0,0);
	eyePos[m_forwardAxis] = -m_cameraDistance;

	btVector3 forward(eyePos[0],eyePos[1],eyePos[2]);
	if (forward.length2() < SIMD_EPSILON)
	{
		forward.setValue(1.f,0.f,0.f);
	}
	btVector3 right = m_cameraUp.cross(forward);
	btQuaternion roll(right,-rele);

	eyePos = btMatrix3x3(rot) * btMatrix3x3(roll) * eyePos;

	m_cameraPosition[0] = eyePos.getX();
	m_cameraPosition[1] = eyePos.getY();
	m_cameraPosition[2] = eyePos.getZ();
	m_cameraPosition += m_cameraTargetPosition;

	if (m_glutScreenWidth == 0 && m_glutScreenHeight == 0)
		return;

	btScalar aspect;
	btVector3 extents;

	aspect = m_glutScreenWidth / (btScalar)m_glutScreenHeight;
	extents.setValue(aspect * 1.0f, 1.0f,0);
	
	
	if (m_ortho)
	{
		// reset matrix
		glLoadIdentity();
		
		
		extents *= m_cameraDistance;
		btVector3 lower = m_cameraTargetPosition - extents;
		btVector3 upper = m_cameraTargetPosition + extents;
		//gluOrtho2D(lower.x, upper.x, lower.y, upper.y);
		glOrtho(lower.getX(), upper.getX(), lower.getY(), upper.getY(),-1000,1000);
		
		glMatrixMode(GL_MODELVIEW);
		glLoadIdentity();
		//glTranslatef(100,210,0);
	} else
	{
//		glFrustum (-aspect, aspect, -1.0, 1.0, 1.0, 10000.0);
		glFrustum (-aspect * m_frustumZNear, aspect * m_frustumZNear, -m_frustumZNear, m_frustumZNear, m_frustumZNear, m_frustumZFar);
		glMatrixMode(GL_MODELVIEW);
		glLoadIdentity();
		gluLookAt(m_cameraPosition[0], m_cameraPosition[1], m_cameraPosition[2], 
			m_cameraTargetPosition[0], m_cameraTargetPosition[1], m_cameraTargetPosition[2], 
			m_cameraUp.getX(),m_cameraUp.getY(),m_cameraUp.getZ());
	}

}
示例#24
0
GlobalActions::GlobalActions(QObject *parent) : QObject(parent)
{
    TRACE_OBJ

    // TODO: Put resource path in misc class
    QString resourcePath = QLatin1String(":/trolltech/assistant/images/");
#ifdef Q_OS_MAC
    resourcePath.append(QLatin1String("mac"));
#else
    resourcePath.append(QLatin1String("win"));
#endif
    CentralWidget *centralWidget = CentralWidget::instance();

    m_backAction = new QAction(tr("&Back"), parent);
    m_backAction->setEnabled(false);
    m_backAction->setShortcuts(QKeySequence::Back);
    m_backAction->setIcon(QIcon(resourcePath + QLatin1String("/previous.png")));
    connect(m_backAction, SIGNAL(triggered()), centralWidget, SLOT(backward()));
    m_actionList << m_backAction;

    m_nextAction = new QAction(tr("&Forward"), parent);
    m_nextAction->setPriority(QAction::LowPriority);
    m_nextAction->setEnabled(false);
    m_nextAction->setShortcuts(QKeySequence::Forward);
    m_nextAction->setIcon(QIcon(resourcePath + QLatin1String("/next.png")));
    connect(m_nextAction, SIGNAL(triggered()), centralWidget, SLOT(forward()));
    m_actionList << m_nextAction;

    setupNavigationMenus(m_backAction, m_nextAction, centralWidget);

    m_homeAction = new QAction(tr("&Home"), parent);
    m_homeAction->setShortcut(tr("ALT+Home"));
    m_homeAction->setIcon(QIcon(resourcePath + QLatin1String("/home.png")));
    connect(m_homeAction, SIGNAL(triggered()), centralWidget, SLOT(home()));
    m_actionList << m_homeAction;

    QAction *separator = new QAction(parent);
    separator->setSeparator(true);
    m_actionList << separator;

    m_zoomInAction = new QAction(tr("Zoom &in"), parent);
    m_zoomInAction->setPriority(QAction::LowPriority);
    m_zoomInAction->setIcon(QIcon(resourcePath + QLatin1String("/zoomin.png")));
    m_zoomInAction->setShortcut(QKeySequence::ZoomIn);
    connect(m_zoomInAction, SIGNAL(triggered()), centralWidget, SLOT(zoomIn()));
    m_actionList << m_zoomInAction;

    m_zoomOutAction = new QAction(tr("Zoom &out"), parent);
    m_zoomOutAction->setPriority(QAction::LowPriority);
    m_zoomOutAction->setIcon(QIcon(resourcePath + QLatin1String("/zoomout.png")));
    m_zoomOutAction->setShortcut(QKeySequence::ZoomOut);
    connect(m_zoomOutAction, SIGNAL(triggered()), centralWidget, SLOT(zoomOut()));
    m_actionList << m_zoomOutAction;

    separator = new QAction(parent);
    separator->setSeparator(true);
    m_actionList << separator;

    m_copyAction = new QAction(tr("&Copy selected Text"), parent);
    m_copyAction->setPriority(QAction::LowPriority);
    m_copyAction->setIconText("&Copy");
    m_copyAction->setIcon(QIcon(resourcePath + QLatin1String("/editcopy.png")));
    m_copyAction->setShortcuts(QKeySequence::Copy);
    m_copyAction->setEnabled(false);
    connect(m_copyAction, SIGNAL(triggered()), centralWidget, SLOT(copy()));
    m_actionList << m_copyAction;

    m_printAction = new QAction(tr("&Print..."), parent);
    m_printAction->setPriority(QAction::LowPriority);
    m_printAction->setIcon(QIcon(resourcePath + QLatin1String("/print.png")));
    m_printAction->setShortcut(QKeySequence::Print);
    connect(m_printAction, SIGNAL(triggered()), centralWidget, SLOT(print()));
    m_actionList << m_printAction;

    m_findAction = new QAction(tr("&Find in Text..."), parent);
    m_findAction->setIconText(tr("&Find"));
    m_findAction->setIcon(QIcon(resourcePath + QLatin1String("/find.png")));
    m_findAction->setShortcuts(QKeySequence::Find);
    connect(m_findAction, SIGNAL(triggered()), centralWidget, SLOT(showTextSearch()));
    m_actionList << m_findAction;

#ifdef Q_WS_X11
    m_backAction->setIcon(QIcon::fromTheme("go-previous" , m_backAction->icon()));
    m_nextAction->setIcon(QIcon::fromTheme("go-next" , m_nextAction->icon()));
    m_zoomInAction->setIcon(QIcon::fromTheme("zoom-in" , m_zoomInAction->icon()));
    m_zoomOutAction->setIcon(QIcon::fromTheme("zoom-out" , m_zoomOutAction->icon()));
    m_copyAction->setIcon(QIcon::fromTheme("edit-copy" , m_copyAction->icon()));
    m_findAction->setIcon(QIcon::fromTheme("edit-find" , m_findAction->icon()));
    m_homeAction->setIcon(QIcon::fromTheme("go-home" , m_homeAction->icon()));
    m_printAction->setIcon(QIcon::fromTheme("document-print" , m_printAction->icon()));
#endif
}
示例#25
0
文件: camera.hpp 项目: Tomius/vkEarth
 virtual vec3 right() const override {
   return glm::normalize(glm::cross(forward(), up()));
 }
示例#26
0
文件: tail.c 项目: coyizumi/cs111
int
main(int argc, char *argv[])
{
	struct stat sb;
	const char *fn;
	FILE *fp;
	off_t off;
	enum STYLE style;
	int i, ch, first;
	file_info_t *file;
	char *p;

	/*
	 * Tail's options are weird.  First, -n10 is the same as -n-10, not
	 * -n+10.  Second, the number options are 1 based and not offsets,
	 * so -n+1 is the first line, and -c-1 is the last byte.  Third, the
	 * number options for the -r option specify the number of things that
	 * get displayed, not the starting point in the file.  The one major
	 * incompatibility in this version as compared to historical versions
	 * is that the 'r' option couldn't be modified by the -lbc options,
	 * i.e. it was always done in lines.  This version treats -rc as a
	 * number of characters in reverse order.  Finally, the default for
	 * -r is the entire file, not 10 lines.
	 */
#define	ARG(units, forward, backward) {					\
	if (style)							\
		usage();						\
	off = strtoll(optarg, &p, 10) * (units);                        \
	if (*p)								\
		errx(1, "illegal offset -- %s", optarg);		\
	switch(optarg[0]) {						\
	case '+':							\
		if (off)						\
			off -= (units);					\
			style = (forward);				\
		break;							\
	case '-':							\
		off = -off;						\
		/* FALLTHROUGH */					\
	default:							\
		style = (backward);					\
		break;							\
	}								\
}

	obsolete(argv);
	style = NOTSET;
	off = 0;
	while ((ch = getopt(argc, argv, "Fb:c:fn:qr")) != -1)
		switch(ch) {
		case 'F':	/* -F is superset of (and implies) -f */
			Fflag = fflag = 1;
			break;
		case 'b':
			ARG(512, FBYTES, RBYTES);
			break;
		case 'c':
			ARG(1, FBYTES, RBYTES);
			break;
		case 'f':
			fflag = 1;
			break;
		case 'n':
			ARG(1, FLINES, RLINES);
			break;
		case 'q':
			qflag = 1;
			break;
		case 'r':
			rflag = 1;
			break;
		case '?':
		default:
			usage();
		}
	argc -= optind;
	argv += optind;

	no_files = argc ? argc : 1;

	/*
	 * If displaying in reverse, don't permit follow option, and convert
	 * style values.
	 */
	if (rflag) {
		if (fflag)
			usage();
		if (style == FBYTES)
			style = RBYTES;
		else if (style == FLINES)
			style = RLINES;
	}

	/*
	 * If style not specified, the default is the whole file for -r, and
	 * the last 10 lines if not -r.
	 */
	if (style == NOTSET) {
		if (rflag) {
			off = 0;
			style = REVERSE;
		} else {
			off = 10;
			style = RLINES;
		}
	}

	if (*argv && fflag) {
		files = (struct file_info *) malloc(no_files *
		    sizeof(struct file_info));
		if (!files)
			err(1, "Couldn't malloc space for file descriptors.");

		for (file = files; (fn = *argv++); file++) {
			file->file_name = strdup(fn);
			if (! file->file_name)
				errx(1, "Couldn't malloc space for file name.");
			if ((file->fp = fopen(file->file_name, "r")) == NULL ||
			    fstat(fileno(file->fp), &file->st)) {
				if (file->fp != NULL) {
					fclose(file->fp);
					file->fp = NULL;
				}
				if (!Fflag || errno != ENOENT)
					ierr(file->file_name);
			}
		}
		follow(files, style, off);
		for (i = 0, file = files; i < no_files; i++, file++) {
		    free(file->file_name);
		}
		free(files);
	} else if (*argv) {
		for (first = 1; (fn = *argv++);) {
			if ((fp = fopen(fn, "r")) == NULL ||
			    fstat(fileno(fp), &sb)) {
				ierr(fn);
				continue;
			}
			if (argc > 1 && !qflag) {
				printfn(fn, !first);
				first = 0;
			}

			if (rflag)
				reverse(fp, fn, style, off, &sb);
			else
				forward(fp, fn, style, off, &sb);
		}
	} else {
		fn = "stdin";

		if (fstat(fileno(stdin), &sb)) {
			ierr(fn);
			exit(1);
		}

		/*
		 * Determine if input is a pipe.  4.4BSD will set the SOCKET
		 * bit in the st_mode field for pipes.  Fix this then.
		 */
		if (lseek(fileno(stdin), (off_t)0, SEEK_CUR) == -1 &&
		    errno == ESPIPE) {
			errno = 0;
			fflag = 0;		/* POSIX.2 requires this. */
		}

		if (rflag)
			reverse(stdin, fn, style, off, &sb);
		else
			forward(stdin, fn, style, off, &sb);
	}
	exit(rval);
}
示例#27
0
文件: relay.c 项目: a2/Soxy
void relay_tcp(SOCKS_STATE *state)
{
  fd_set   rfds, xfds;
  int      nfds, sfd;
  struct   timeval tv;
  struct   timezone tz;
  ssize_t  wc;
  rlyinfo  ri;
  int      done;
  u_long   max_count = idle_timeout;
  u_long   timeout_count;
  LOGINFO	li;

  memset(&ri, 0, sizeof(ri));
  memset(&li, 0, sizeof(li));
  ri.ss = (struct sockaddr *)NULL;
  ri.len = 0;
  ri.nr = BUFSIZE;

  nfds = MAX(state->r, state->s);
  setsignal(SIGALRM, timeout);
  gettimeofday(&li.start, &tz);
  li.bc = li.upl = li.dnl = 0;
  ri.flags = 0; timeout_count = 0;
  for (;;) {
    FD_ZERO(&rfds);
    FD_SET(state->s, &rfds); FD_SET(state->r, &rfds);
    if (ri.flags == 0) {
      FD_ZERO(&xfds);
      FD_SET(state->s, &xfds); FD_SET(state->r, &xfds);
    }
    done = 0;
    /* idle timeout related setting. */
    tv.tv_sec = 60; tv.tv_usec = 0;   /* unit = 1 minute. */
    tz.tz_minuteswest = 0; tz.tz_dsttime = 0;
    sfd = select(nfds+1, &rfds, 0, &xfds, &tv);
    if (sfd > 0) {
      if (FD_ISSET(state->r, &rfds)) {
	ri.from = state->r; ri.to = state->s; ri.flags = 0;
	if ((wc = forward(&ri)) <= 0)
	  done++;
	else
    {
	  li.bc += wc; li.dnl += wc;
      if (log_tmp_transfer_callback) log_tmp_transfer_callback(state->si, &li, wc, 0);
    }
	FD_CLR(state->r, &rfds);
      }
      if (FD_ISSET(state->r, &xfds)) {
	ri.from = state->r; ri.to = state->s; ri.flags = MSG_OOB;
	if ((wc = forward(&ri)) <= 0)
	  done++;
	else
    {
	  li.bc += wc; li.dnl += wc;
      if (log_tmp_transfer_callback) log_tmp_transfer_callback(state->si, &li, wc, 0);
    }
	FD_CLR(state->r, &xfds);
      }
      if (FD_ISSET(state->s, &rfds)) {
	ri.from = state->s; ri.to = state->r; ri.flags = 0;
	if ((wc = forward(&ri)) <= 0)
	  done++;
	else
    {
	  li.bc += wc; li.upl += wc;
      if (log_tmp_transfer_callback) log_tmp_transfer_callback(state->si, &li, wc, 0);
    }
	FD_CLR(state->s, &rfds);
      }
      if (FD_ISSET(state->s, &xfds)) {
	ri.from = state->s; ri.to = state->r; ri.flags = MSG_OOB;
	if ((wc = forward(&ri)) <= 0)
	  done++;
	else
    {
	  li.bc += wc; li.upl += wc;
      if (log_tmp_transfer_callback) log_tmp_transfer_callback(state->si, &li, wc, 0);
    }
	FD_CLR(state->s, &xfds);
      }
      if (done > 0)
	break;
    } else if (sfd < 0) {
      if (errno != EINTR)
	break;
    } else { /* sfd == 0 */
      if (max_count != 0) {
	timeout_count++;
	if (timeout_count > max_count)
	  break;
      }
    }
  }
  gettimeofday(&li.end, &tz);
  log_transfer(state->si, &li);

  close(state->r);
  close(state->s);
}
示例#28
0
void HMM<Distribution>::Train(const std::vector<arma::mat>& dataSeq)
{
  // We should allow a guess at the transition and emission matrices.
  double loglik = 0;
  double oldLoglik = 0;

  // Maximum iterations?
  size_t iterations = 1000;

  // Find length of all sequences and ensure they are the correct size.
  size_t totalLength = 0;
  for (size_t seq = 0; seq < dataSeq.size(); seq++)
  {
    totalLength += dataSeq[seq].n_cols;

    if (dataSeq[seq].n_rows != dimensionality)
      Log::Fatal << "HMM::Train(): data sequence " << seq << " has "
          << "dimensionality " << dataSeq[seq].n_rows << " (expected "
          << dimensionality << " dimensions)." << std::endl;
  }

  // These are used later for training of each distribution.  We initialize it
  // all now so we don't have to do any allocation later on.
  std::vector<arma::vec> emissionProb(transition.n_cols,
      arma::vec(totalLength));
  arma::mat emissionList(dimensionality, totalLength);

  // This should be the Baum-Welch algorithm (EM for HMM estimation). This
  // follows the procedure outlined in Elliot, Aggoun, and Moore's book "Hidden
  // Markov Models: Estimation and Control", pp. 36-40.
  for (size_t iter = 0; iter < iterations; iter++)
  {
    // Clear new transition matrix and emission probabilities.
    arma::mat newTransition(transition.n_rows, transition.n_cols);
    newTransition.zeros();

    // Reset log likelihood.
    loglik = 0;

    // Sum over time.
    size_t sumTime = 0;

    // Loop over each sequence.
    for (size_t seq = 0; seq < dataSeq.size(); seq++)
    {
      arma::mat stateProb;
      arma::mat forward;
      arma::mat backward;
      arma::vec scales;

      // Add the log-likelihood of this sequence.  This is the E-step.
      loglik += Estimate(dataSeq[seq], stateProb, forward, backward, scales);

      // Now re-estimate the parameters.  This is the M-step.
      //   T_ij = sum_d ((1 / P(seq[d])) sum_t (f(i, t) T_ij E_i(seq[d][t]) b(i,
      //           t + 1)))
      //   E_ij = sum_d ((1 / P(seq[d])) sum_{t | seq[d][t] = j} f(i, t) b(i, t)
      // We store the new estimates in a different matrix.
      for (size_t t = 0; t < dataSeq[seq].n_cols; t++)
      {
        for (size_t j = 0; j < transition.n_cols; j++)
        {
          if (t < dataSeq[seq].n_cols - 1)
          {
            // Estimate of T_ij (probability of transition from state j to state
            // i).  We postpone multiplication of the old T_ij until later.
            for (size_t i = 0; i < transition.n_rows; i++)
              newTransition(i, j) += forward(j, t) * backward(i, t + 1) *
                  emission[i].Probability(dataSeq[seq].unsafe_col(t + 1)) /
                  scales[t + 1];
          }

          // Add to list of emission observations, for Distribution::Estimate().
          emissionList.col(sumTime) = dataSeq[seq].col(t);
          emissionProb[j][sumTime] = stateProb(j, t);
        }
        sumTime++;
      }
    }

    // Assign the new transition matrix.  We use %= (element-wise
    // multiplication) because every element of the new transition matrix must
    // still be multiplied by the old elements (this is the multiplication we
    // earlier postponed).
    transition %= newTransition;

    // Now we normalize the transition matrix.
    for (size_t i = 0; i < transition.n_cols; i++)
      transition.col(i) /= accu(transition.col(i));

    // Now estimate emission probabilities.
    for (size_t state = 0; state < transition.n_cols; state++)
      emission[state].Estimate(emissionList, emissionProb[state]);

    Log::Debug << "Iteration " << iter << ": log-likelihood " << loglik
        << std::endl;

    if (std::abs(oldLoglik - loglik) < tolerance)
    {
      Log::Debug << "Converged after " << iter << " iterations." << std::endl;
      break;
    }

    oldLoglik = loglik;
  }
}
//-----------------------------------------------------------------------------
// Airboat muzzle flashes
//-----------------------------------------------------------------------------
void MuzzleFlash_Airboat( ClientEntityHandle_t hEntity, int attachmentIndex )
{
	VPROF_BUDGET( "MuzzleFlash_Airboat", VPROF_BUDGETGROUP_PARTICLE_RENDERING );

	CSmartPtr<CLocalSpaceEmitter> pSimple = CLocalSpaceEmitter::Create( "MuzzleFlash", hEntity, attachmentIndex );

	SimpleParticle *pParticle;
	Vector			forward(1,0,0), offset; //NOTENOTE: All coords are in local space

	float flScale = random->RandomFloat( 0.75f, IsXbox() ? 2.0f : 2.5f );

	PMaterialHandle pMuzzle[2];
	pMuzzle[0] = pSimple->GetPMaterial( "effects/combinemuzzle1" );
	pMuzzle[1] = pSimple->GetPMaterial( "effects/combinemuzzle2" );

	// Flash
	for ( int i = 1; i < 7; i++ )
	{
		offset = (forward * (i*6.0f*flScale));

		pParticle = (SimpleParticle *) pSimple->AddParticle( sizeof( SimpleParticle ), pMuzzle[random->RandomInt(0,1)], offset );
			
		if ( pParticle == NULL )
			return;

		pParticle->m_flLifetime		= 0.0f;
		pParticle->m_flDieTime		= IsXbox() ? 0.0001f : 0.01f;

		pParticle->m_vecVelocity.Init();

		pParticle->m_uchColor[0]	= 255;
		pParticle->m_uchColor[1]	= 255;
		pParticle->m_uchColor[2]	= 255;

		pParticle->m_uchStartAlpha	= 255;
		pParticle->m_uchEndAlpha	= 128;

		pParticle->m_uchStartSize	= ( (random->RandomFloat( 6.0f, 8.0f ) * (9-(i))/7) * flScale );
		pParticle->m_uchEndSize		= pParticle->m_uchStartSize;
		pParticle->m_flRoll			= random->RandomInt( 0, 360 );
		pParticle->m_flRollDelta	= 0.0f;
	}

	// Tack on the smoke
	pParticle = (SimpleParticle *) pSimple->AddParticle( sizeof( SimpleParticle ), pSimple->GetPMaterial( "sprites/ar2_muzzle1" ), vec3_origin );
		
	if ( pParticle == NULL )
		return;

	pParticle->m_flLifetime		= 0.0f;
	pParticle->m_flDieTime		= 0.05f;

	pParticle->m_vecVelocity.Init();

	pParticle->m_uchColor[0]	= 255;
	pParticle->m_uchColor[1]	= 255;
	pParticle->m_uchColor[2]	= 255;

	pParticle->m_uchStartAlpha	= 255;
	pParticle->m_uchEndAlpha	= 128;

	pParticle->m_uchStartSize	= random->RandomFloat( 16.0f, 24.0f );
	pParticle->m_uchEndSize		= pParticle->m_uchStartSize;
	
	float spokePos = random->RandomInt( 0, 5 );

	pParticle->m_flRoll			= (360.0/6.0f)*spokePos;
	pParticle->m_flRollDelta	= 0.0f;
	
#ifndef _XBOX
	// Grab the origin out of the transform for the attachment
	if ( muzzleflash_light.GetInt() )
	{
		// If the client hasn't seen this entity yet, bail.
		matrix3x4_t	matAttachment;
		if ( FX_GetAttachmentTransform( hEntity, attachmentIndex, matAttachment ) )
		{
			Vector		origin;
			MatrixGetColumn( matAttachment, 3, &origin );
			CreateMuzzleflashELight( origin, 5, 64, 128, hEntity );
		}
	}
#endif
}
示例#30
0
void
forwardall(DATA_TYPE *mat, int *permutations, DATA_TYPE *rhs_copy,
        DATA_TYPE *rhs)
{
  int colcnt; /* number of columns stored for BLAS 3 ops */

  int col_len,row_len,rows_used,cols_used;
  int *sav_pivot_ptr;


  DATA_TYPE *sav_col_ptr,*sav_row_ptr,*sav_piv_row_ptr;
  DATA_TYPE *cur_col1_row_ptr;
  DATA_TYPE *temp_row_ptr;
  DATA_TYPE *act_col_ptr,*act_row_ptr;


  int numprocs;

  MPI_Comm_size(MPI_COMM_WORLD,&numprocs);
  if ( (numprocs/nprocs_row) * nprocs_row != numprocs )
  {
     if (me == 0)
     {
       printf("nprocs_row must go into numprocs perfectly!\n");
       printf("Try a different value of nprocs_row.\n");
     }
     MPI_Barrier(MPI_COMM_WORLD);
     exit(0);
  }
  colcnt = 0;           /* number of column's currently saved for update */
  col_len = my_rows;    /* length of column in remaining local matrix */
  sav_col_ptr = col1;   /* location to store next active column */
  act_col_ptr = col1;   /* location of matrix of columns being saved for dgemm update */

  row_len = my_cols + my_rhs;  /* length of row in local matrix including
			          rhs's*/

  rows_used = 0;      /* haven't used any local rows yet */
  cols_used = 0;
  cur_col1_row_ptr = col1;  /* location of first row in col1 matrix */
  act_row_ptr = row1; /* location of matrix of rows being saved for dgemm
			 update */

  sav_piv_row_ptr = row1; /* location for next row being saved for dgemm
	                 update */

  temp_row_ptr = row3; /* location for pivot row while being sent and
		         before transposing */

  sav_row_ptr = row2;  /* location to save current row and send to
			 owner of pivot row */

  sav_pivot_ptr = pivot_vec; /* location to store name of pivot row */


  exchange_pivots(permutations);
  permute_mat(mat,permutations);
  permute_rhs(rhs,permutations);
  forward(mat, rhs);
  MPI_Barrier(MPI_COMM_WORLD);

}/* End of function forwardall */