/// \brief		Unscented transform of process Sigma points
void UnscentedKalmanFilter::utf(vnl_matrix<double> X, vnl_vector<double> u,
	vnl_vector<double> &y, vnl_matrix<double> &Y, vnl_matrix<double> &P, vnl_matrix<double> &Y1)
{
	// determine number of sigma points
	unsigned int L = X.cols();
	// zero output matrices
	y.fill(0.0); Y.fill(0.0);

	// transform the sigma points and put them as columns in a matrix Y
	for( int k = 0; k < L; k++ )
	{
		vnl_vector<double> xk = X.get_column(k);
		vnl_vector<double> yk(N);
		f(xk,u,yk);
		Y.set_column(k,yk);
		// add each transformed point to the weighted mean
		y = y + Wm.get(0,k)*yk;
	}

	// create a matrix with each column being the weighted mean
	vnl_matrix<double> Ymean(N,L);
	for( int k = 0; k < L; k++ )
		Ymean.set_column(k,y);
	// set the matrix of difference vectors
	Y1 = Y-Ymean;
	// calculate the covariance matrix output
	vnl_matrix<double> WC(L,L,0.0);
	WC.set_diagonal(Wc.get_row(0));
	P = Y1*WC*Y1.transpose();
}
/// \brief		Update Kalman filter
void UnscentedKalmanFilter::updateUKF(vnl_vector<double> u, vnl_vector<double> z)
{
	// create Sigma points X for the current estimate distribution
	vnl_matrix<double> X(N,2*N+1);
	sigmas(x_hat, P_hat+Q, sqrt(C), X);
	
	vnl_matrix<double> Dbg;

	qDebug() << "X: "; 
	for( int i = 0; i<6; i++)
	{
		qDebug() << X(i,0) << " " << X(i,1) << " " << X(i,2) << " " << X(i,3) << " " << X(i,4) << " " << X(i,5) << " "
			<< X(i,6) << " " << X(i,7) << " " << X(i,8) << " " << X(i,9) << " " << X(i,10) << " " << X(i,11)
			<< " " << X(i,12);
	}

	// apply unscented transformation for process model 
	vnl_vector<double> x1(6);
	vnl_matrix<double> X1(N,2*N+1), P1(N,N), X2(N,2*N+1);
	utf(X, u, x1, X1, P1, X2);

	// apply unscented transformation for observation model
	vnl_vector<double> z1(M);
	vnl_matrix<double> Z1(M,2*M+1), P2(M,M), Z2(M,2*M+1);
	utg(X1, z1, Z1, P2, Z2);
	// define transformated cross-covariance
	vnl_matrix<double> WC(2*N+1,2*N+1,0.0);
	WC.set_diagonal(Wc.get_row(0));
	vnl_matrix<double> P12 = X2*WC*Z2.transpose();
	// perform state update
	K = P12*vnl_matrix_inverse<double>(P2);
	x_hat = x1 + K*(z-z1);
	// perform covariance update
	P_hat = P1 - K*P12.transpose();
}
Example #3
0
File: ogl.c Project: tcbabu/kglib
int kgSwapglBuffers(void *Gtmp) {
    Window glWin;
    DIG *G;
    Display *Dsp;
    G = (DIG *)Gtmp;
    Dsp = WC(G->D)->Dsp;
    glWin = *((Window *)(G->glWindow));
    if(G->glDouble)glXSwapBuffers(Dsp,glWin);
    else glFlush();
    return 1;
}
Example #4
0
File: ogl.c Project: tcbabu/kglib
int  kgInitglWindow(void* Gtmp) {
#if 0	
    int snglBuf[] ={GLX_RGBA,GLX_RED_SIZE,1,GLX_GREEN_SIZE,1,
	            GLX_BLUE_SIZE,1,GLX_DEPTH_SIZE,12,None};
    int dblBuf[] ={GLX_RGBA,GLX_RED_SIZE,1,GLX_GREEN_SIZE,1,
	            GLX_BLUE_SIZE,1,GLX_DEPTH_SIZE,12,GLX_DOUBLEBUFFER,None};
#endif
    DIG *G;
    int snglBuf[] = {GLX_RGBA, GLX_DEPTH_SIZE, 16, None};
    int dblBuf[] = {GLX_RGBA, GLX_DEPTH_SIZE, 16, GLX_DOUBLEBUFFER, None};
    XVisualInfo *vInfoMain;
    GLXContext *cMain;
    Window wMain,*sWin;
    int nvis,dummy;
    XVisualInfo  sampleVis;
    Display *xDisplay;
    int xScreen;
    DIALOG *D;
    kgWC *wc;
    G = (DIG *)Gtmp;
    D = (DIALOG *)G->D;
    wc = WC(D);
    xDisplay = wc->Dsp;
#if 1
    if(!glXQueryExtension(xDisplay, &dummy, &dummy)) {
      printf("X server has no OpenGL GLX extension\n");
      return 0;
    }
#endif
    xScreen = DefaultScreen(xDisplay);
    kgSubWindow(Gtmp);
    sWin = (Window *)G->glWindow;
    wMain = *sWin;
#if 0
    sampleVis.screen = xScreen;
    sampleVis.depth = DisplayPlanes(xDisplay,DefaultScreen(xDisplay));
    sampleVis.visual = XDefaultVisual(xDisplay,DefaultScreen(xDisplay));
    sampleVis.visualid = XVisualIDFromVisual(
         XDefaultVisual(xDisplay,DefaultScreen(xDisplay)));
    vInfoMain =  XGetVisualInfo(xDisplay,
       VisualIDMask|VisualScreenMask|VisualDepthMask,&sampleVis, &nvis);
#else
    vInfoMain =  glXChooseVisual(xDisplay,xScreen,dblBuf);
    if(vInfoMain == NULL) {
      vInfoMain =  glXChooseVisual(xDisplay,xScreen,snglBuf);
      if(vInfoMain == NULL) {
	      printf("No RGB Visual with Depth Buffer\n");
	      return GL_FALSE;
      }
      else { 
        G->glDouble=0;
	printf("RGB Visual with Depth Buffer(single)\n");
      }
	
    }
    else {
      G->glDouble=1;
      printf("RGB Visual with Depth Buffer(double)\n");
    }
    if(vInfoMain->class != TrueColor) {
	    printf("TrueColor visual required for this program\n");
	    exit(1);
    }
#endif
    cMain = (GLXContext *)malloc(sizeof(GLXContext));
    *cMain = glXCreateContext(xDisplay, vInfoMain, None,
			       GL_TRUE);
    if (!(*cMain)) {
	fprintf(stderr, "Can't create a context!\n");
	return GL_FALSE;
    }
    G->cMain = (void *) cMain;

    if (!glXMakeCurrent(xDisplay, wMain, *cMain)) {
	printf( "Can't make window current drawable!\n");
	return GL_FALSE;
    }
    XMapWindow(xDisplay, wMain);
    glViewport(0,0,(G->x2-G->x1+1),(G->y2-G->y1+1));

    return GL_TRUE;
}
Example #5
0
/*****************************************************

The suggested algorithm is:

   a)  If "RCPT To:" is one of "our" domains, local or a domain that
       we accept to forward to (alternate MX), then accept to Relay.

   b)  If SMTP_Caller is authorized, either its IP.src or its FQDN
       (depending on if you trust the DNS), then accept to Relay.

   c)  Else refuse to Relay.



  550 <*****@*****.**>... Denied due to spam list

*****************************************************/
BOOL CUT_SMTPThread::CheckRelay(LPCSTR /* szFrom */, LPCSTR szTo, LPCSTR /* szHost */)
{
	

	CUT_MailServer  *ptrMailServer  = ((CUT_SMTPServer *)m_winsockclass_this)->m_ptrMailServer;
	char szStrFromTempDomain[WSS_BUFFER_SIZE+1];
	char szStrToTempDomain[WSS_BUFFER_SIZE+1];


	if (szTo == NULL || szTo[0] == 0 || strlen(szTo) < 3)
		return FALSE;	
	

	// i am not going to relay to other server
	if (CUT_StrMethods::GetParseStringPieces  (szTo, "@") > 2) 
	{
		return FALSE;
	}
	
	
	if (CUT_StrMethods::ParseString (szTo, "@",1,szStrToTempDomain,WSS_BUFFER_SIZE) != CUT_SUCCESS) 
	{
		// this block should never be hit
		  return FALSE;					
	}


	// if the domain name of the to is local 
	// then return true
	// v4.2 using WC here - domains now held as _TCHAR
	if (ptrMailServer->Sys_IsDomainLocal(WC(szStrToTempDomain)))
	{
		char szLogLine[WSS_BUFFER_SIZE +  20];
		_snprintf(szLogLine,sizeof(szLogLine)-1, "RELAY CHECKED [%s]  %s",GetClientAddress(),szStrToTempDomain);
		ptrMailServer->OnStatus(szLogLine);
		return TRUE;
	}


		
	// now we have the address of the recepient 
	//  and the address of the sender and the address of the 
	// host machine
	// if the client address is in the allowed relay IP addresses 
	
	// if it does not exist then let see if it is part of relay IP addresses list
	// now lets see if the client is in the relay list
	// Get the list of Relay from the mail server
	if ( ptrMailServer->Sys_GetRelayAddressCount () <= 0)
		return TRUE; // the server is not set up to prevent relaying
	
	int peices = 0;
	char szClientAddress[32];
	in_addr inRangeStart, inRangeEnd ;
	in_addr	clientAddr;

	// first get the address of the connected client.
	strcpy(szClientAddress, GetClientAddress());

	// change the client address into a winsock 	
	clientAddr.S_un.S_addr  = inet_addr (szClientAddress);
	// v4.2 changed these to unsigned long to allow ranges up to 255.255.255
	unsigned long lstart = 0;
	unsigned long lend = 0;
	unsigned long lclient = 0;
	
	// v4.2 relays now held as _TCHAR so convert...
	char szAnsiRelay[MAX_PATH+1];
	for (int index = 0; index <  (int) ptrMailServer->Sys_GetRelayAddressCount (); index++)
	{
		// for each item 
		// check first if it contains -
		CUT_Str::cvtcpy(szAnsiRelay,MAX_PATH,ptrMailServer->Sys_GetRelayAddress (index));
		peices = CUT_StrMethods::GetParseStringPieces (szAnsiRelay,"-");
		// if peices are 0 or less then it is an internal error
		if (peices >1)
		{
			// parse the avilable list for  the range
			// get the first piece
			// v4.2 using AC here - relays now _TCHAR
			CUT_StrMethods::ParseString (szAnsiRelay, "-", 0, szStrFromTempDomain, WSS_BUFFER_SIZE);
			inRangeStart.S_un.S_addr  = inet_addr ( szStrFromTempDomain);
			// get the end piece
			// v4.2 using AC here - relays now _TCHAR
			CUT_StrMethods::ParseString (szAnsiRelay, "-",1,szStrToTempDomain,WSS_BUFFER_SIZE);
			inRangeEnd.S_un.S_addr  = inet_addr ( szStrToTempDomain);


			lstart = inRangeStart.S_un.S_un_b.s_b1 * 16777216 + 
				inRangeStart.S_un.S_un_b.s_b2 * 65536 +
				inRangeStart.S_un.S_un_b.s_b3 * 256 +
				inRangeStart.S_un.S_un_b.s_b4;

			lend = inRangeEnd.S_un.S_un_b.s_b1 * 16777216 + 
				inRangeEnd.S_un.S_un_b.s_b2 * 65536 +
				inRangeEnd.S_un.S_un_b.s_b3 * 256 +
				inRangeEnd.S_un.S_un_b.s_b4;

			lclient = clientAddr.S_un.S_un_b.s_b1 * 16777216 + 
				clientAddr.S_un.S_un_b.s_b2 * 65536 +
				clientAddr.S_un.S_un_b.s_b3 * 256 +
				clientAddr.S_un.S_un_b.s_b4;
				if (	( lend >= lclient ) && (lstart <= lclient)) 
				{
				char szLogLine[WSS_BUFFER_SIZE +  20];
				_snprintf(szLogLine,sizeof(szLogLine)-1, "IP RANGE OK %s < [%s] > %s",szStrFromTempDomain ,GetClientAddress() ,szStrToTempDomain );
				ptrMailServer->OnStatus(szLogLine);
				return TRUE;

				}
			
		}
		else
		if (_stricmp(szAnsiRelay,szClientAddress) == 0)
		{
			char szLogLine[WSS_BUFFER_SIZE +  20];
			_snprintf(szLogLine,sizeof(szLogLine)-1, "IP OK [%s] %s",GetClientAddress(),szStrToTempDomain);
			ptrMailServer->OnStatus(szLogLine);			
			return TRUE;
		}
	}
	// you may notice that I did not test the 
	// from if it is part of the domain
	// this is simply because the message data may contain diffrent from feild than the actual sender

	return FALSE; // nothing found
}
Example #6
0
int xmlParse(void* Pool,PXMLNode x,wchar_t *src,int flags)
{
  int sz=xstrlen(src);
  int i,st,n;
  wchar_t str[256];
  PXMLNode stack[256];
  int stackpos=0;
  PXMLNode p=x,c;
  PHashLink l;
  PXMLNode chlds=NULL;
  if(!sz)return 0;

  for(i=0;i<sz;i++)
  {
    if(xmlIsSpace(src[i]))continue;
    if(src[i]==L'<' && src[i+1]==L'!' && src[i+2]==L'-' && src[i+3]==L'-' && sz-i>4)
    {
      i+=4;
      st=i;
      while((src[i]!=L'-' || src[i+1]!=L'-' || src[i+2]!=L'>') && sz-i>3)i++;
      i+=2;
      if(sz-i<3)return 0;
      c=xmlNewChild(Pool,p,xmlComment);
      c->szCont=xstrndup(Pool,src+st,i-st-3);
      if(chlds)chlds->pNext=c;
      else p->pChildren=c;
      chlds=c;
      continue;
    }
    if(src[i]==L'<')
    {
      i++;
      if(src[i]==L'/')
      {
        i++;
        st=i;
        i=xmlGetWordEnd(src,i);
        if(i==-1)return 0;
        i=xmlSkipSpace(src,i);CHK;
        if(src[i]!=L'>')return 0;
        n=i-st;
        if(!xstrncmp(p->szName,src+st,n))return 0;
        //i++;
        p=p->pParent;
        if(p->eType==xmlRoot)return 1;
        stackpos--;
        chlds=stack[stackpos];
        continue;
      }
      if(WC(src[i]))
      {
        st=i;
        i=xmlGetWordEnd(src,i);CHK;
        c=xmlNewChild(Pool,p,xmlLeaf);
        if(p->eType!=xmlRoot)p->eType=xmlNode;
        n=i-st;
        if(n>255)n=255;
        xstrncpy(str,src+st,n);
        if(p->hChildren==NULL)p->hChildren=hashNew(Pool);
        l=hashAdd(p->hChildren,str,c);
        c->szName=l->szKey;
        if(chlds)chlds->pNext=c;
        else p->pChildren=c;
        chlds=c;
        i=xmlParseTag(Pool,c,&p,src,i);
        if(i==0)return 0;
        if(p==c)
        {
          stack[stackpos]=chlds;
          stackpos++;
          chlds=NULL;
        }
        i=xmlSkipSpace(src,i);CHK;
        st=i;
        i=xmlSkipTill(src,i,L'<');CHK;
        if(i>st)
        {
          p->szCont=xmlSubst(xstrndup(Pool,src+st,i-st));
        }
        i--;
        continue;
      }
      if(src[i]==L'!' || src[i]==L'?')
      {
        st=i+1;
        if(src[i+1]==L'[')
        {
          if(xstrncmp(src+i,L"![CDATA[",8))
          {
            const wchar_t *p=src+i+8;
            while((p=xstrchr(p,']')))
            {
              if(p[1]==L']' && p[2]==L'>')break;
            }
            if(p)i=(int)(p-src+2);
          }else i=xmlSkipTill(src,i,L'>');
        }else
        {
          i=xmlSkipTill(src,i,L'>');
        }
        if(i==-1)return 0;
        c=xmlNewChild(Pool,p,src[st-1]==L'!'?xmlExcl:xmlQuest);
        c->szCont=xstrndup(Pool,src+st,i-st);
        if(chlds)chlds->pNext=c;
        else p->pChildren=c;
        chlds=c;
        continue;
      }
    }else
    {
      st=i;
      i=xmlSkipTill(src,i,L'<');CHK;
      c=xmlNewChild(Pool,p,xmlContent);
      c->szCont=xmlSubst(xstrndup(Pool,src+st,i-st));
      if(chlds)chlds->pNext=c;
      else p->pChildren=c;
      chlds=c;
      i--;
    }
  }
  return 1;
}
Example #7
0
static int xmlGetWordEnd(wchar_t *str,int pos)
{
  while(WC(str[pos]))pos++;
  if(!str[pos])return -1;
  return pos;
}
Example #8
0
float leap_gesture_swipe_speed(leap_gesture_ref gesture)
{
    return WC(gesture).speed();
}
Example #9
0
int undo(Puzzle *puz, Solution *sol, int leave_branch)
{
    Hist *h;
    Clue *clue;
    Cell **line;
    dir_t k;
    int is_branch;
    line_t i;

    while (puz->nhist > 0)
    {
        h= HIST(puz, puz->nhist-1);

        /* Invalidate any saved positions for lines crossing undone cell.
         * We can't just have the fact that nhist < stamp mean the line is
         * invalid, because we might backtrack and then advance past stamp
         * again before we recheck the line.
         */
        for (k= 0; k < puz->nset; k++)
        {

            i= h->cell->line[k];
            clue= &(puz->clue[k][i]);
            line= sol->line[k][i];

            if ((VL && VU) || WL(*clue))
                printf("U: CHECK %s %d", CLUENAME(puz->type,k),i);

            left_undo(puz, clue, line, h->cell->index[k], h->bit);
            right_undo(puz, clue, line,  h->cell->index[k], h->bit);

            if ((VL && VU) || WL(*clue)) printf("\n");
        }

        is_branch= h->branch;

        if (!is_branch || !leave_branch)
        {
            /* If undoing a solved cell, decrement completion count */
            if (h->cell->n == 1) solved_a_cell(puz, h->cell, -1);

            /* Restore saved value */
            h->cell->n= h->n;
            fbit_cpy(h->cell->bit, h->bit);

            if (VU || WC(h->cell))
            {
                printf("U: UNDOING CELL ");
                for (k= 0; k < puz->nset; k++)
                    printf(" %d",h->cell->line[k]);
                printf(" TO ");
                dump_bits(stdout,puz,h->cell->bit);
                printf(" (%d)\n",h->cell->n);
            }

            puz->nhist--;
        }

        if (is_branch)
            return 0;
    }
    return 1;
}
Example #10
0
leap_pointable_ref leap_gesture_key_tap_copy_pointable(leap_gesture_ref gesture)
{
    return leap_pointable_new(WC(gesture).pointable());
}
Example #11
0
void leap_gesture_key_tap_direction(leap_gesture_ref gesture, leap_vector *out_result)
{
    *out_result = to_vector(WC(gesture).direction());
}
Example #12
0
void leap_gesture_screen_tap_position(leap_gesture_ref gesture, leap_vector *out_result)
{
    *out_result = to_vector(WC(gesture).position());
}
Example #13
0
float leap_gesture_circle_radius(leap_gesture_ref gesture)
{
    return WC(gesture).radius();
}
Example #14
0
float leap_gesture_circle_progress(leap_gesture_ref gesture)
{
    return WC(gesture).progress();
}
Example #15
0
void leap_gesture_circle_normal(leap_gesture_ref gesture, leap_vector *out_result)
{
    *out_result = to_vector(WC(gesture).normal());
}
Example #16
0
void leap_gesture_circle_center(leap_gesture_ref gesture, leap_vector *out_result)
{
    *out_result = to_vector(WC(gesture).center());
}
Example #17
0
int solve(Puzzle *puz, Solution *sol)
{
    Cell *cell;
    line_t besti, bestj;
    color_t bestc;
    int bestnleft;
    int rc;
    int sprint_clock= 0, plod_clock= PLOD_INIT;

    /* One color puzzles are already solved */
    if (puz->ncolor < 2)
    {
        puz->nsolved= puz->ncells;
        return 1;
    }

    /* Start bookkeeping, if we need it */
    if (mayprobe)
        probe_init(puz,sol);
    else
        bookkeeping_on(puz,sol);

    while (1)
    {
        /* Always start with logical solving */
        if (VA) printf("A: LINE SOLVING\n");
        rc= logic_solve(puz, sol, 0);

        if (rc > 0) return 1;   /* Exit if the puzzle is complete */

        if (rc == 0)
        {
            /* Logical solving has stalled. */

            if (VA)
            {
                printf("A: STUCK - Line solving failed\n");
                print_solution(stdout,puz,sol);
            }

            if (maycontradict)
            {
                /* Try a depth-limited search for logical contradictions */
                if (VA) printf("A: SEARCHING FOR CONTRADICTIONS\n");
                rc= contradict(puz,sol);

                if (rc > 0) return 1; /* puzzle complete - stop */

                if (rc < 0) continue; /* found some - resume logic solving */

                /* otherwise, try something else */
            }

            /* Stop if no guessing is allowed */
            if (!maybacktrack) return 1;

            if (hintlog)
            {
                printf("STARTING SEARCH: EXPLANATION SHUTTING DOWN...\n");
                hintlog= 0;
            }

            /* Shut down the exhaustive search once we start searching */
            if (maylinesolve) mayexhaust= 0;

            /* Turn on caching when we first start searching */
            if (maycache && !cachelines)
            {
                cachelines= 1;
                init_cache(puz);
            }

            if (mayprobe && (!mayguess || sprint_clock <= 0))
            {
                /* Do probing to find best guess to make */
                if (VA) printf("A: PROBING\n");
                rc= probe(puz, sol, &besti, &bestj, &bestc);

                if (rc > 0)
                    return 1; /* Stop if accidentally completed the puzzle */
                if (rc < 0)
                    continue; /* Resume logic solving if found contradiction */

                /* Otherwise, use the guess returned from the probe */
                cell= sol->line[0][besti][bestj];
                if (VA)
                {
                    printf("A: PROBING SELECTED ");
                    print_coord(stdout,puz,cell);
                    printf(" COLOR %d\n",bestc);
                }

                /* If a lot of probes have not been finding contradictions,
                 * consider triggering sprint mode
                 */
                if (mayguess && --plod_clock <= 0)
                {
                    float rate= probe_rate();
                    if (rate >= .12)
                    {
                        /* More than 10% have failed to find contradiction,
                         * so try heuristic searching for a while */
                        bookkeeping_on(puz,sol);
                        sprint_clock= SPRINT_LENGTH;
                        nsprint++;
                        /*printf("STARTING SPRINT - probe rate=%.4f\n",rate);*/
                    }
                    else
                    {
                        /* Success rate of probing is still high. Keep on
                         * trucking. */
                        plod_clock= PLOD_LENGTH;
                        nplod++;
                        /*printf("CONTINUING PLOD - probe rate=%.4f\n", rate);*/
                    }
                }
            }
            else
            {
                /* Old guessing algorithm.  Use heuristics to make a guess */
                cell= pick_a_cell(puz, sol);
                if (cell == NULL)
                    return 0;

                bestc= (*pick_color)(puz,sol,cell);
                if (VA || WC(cell->line[0],cell->line[1]))
                {
                    printf("A: GUESSING SELECTED ");
                    print_coord(stdout,puz,cell);
                    printf(" COLOR %d\n",bestc);
                }

                if (mayprobe && --sprint_clock <= 0)
                {
                    /* If we have reached the end of our sprint, try plodding
                     * again.  */
                    probe_init(puz,sol);
                    plod_clock= PLOD_LENGTH;
                    nplod++;
                    /*printf("ENDING SPRINT\n");*/
                }
            }
            guess_cell(puz, sol, cell, bestc);
            guesses++;
        }
        else
        {
            /* We have hit a contradiction - try backtracking */
            if (VA) printf("A: STUCK ON CONTRADICTION - BACKTRACKING\n");

            guesses++;

            /* Back up to last guess point, and invert that guess */
            if (backtrack(puz,sol))
                /* Nothing to backtrack to - puzzle has no solution */
                return 0;
            if (VB) print_solution(stdout,puz,sol);
            if (VB) dump_history(stdout, puz, VV);
        }
    }
}
Example #18
0
int
connect_socket(const char *host, unsigned short port, unsigned long to_us)
{
	int64_t tsend = to_us ? timestamp_us() + to_us : 0;
	struct addrinfo *ai_list = NULL;
	struct addrinfo hints;
	memset(&hints, 0, sizeof hints);
	hints.ai_family = PF_UNSPEC;
	hints.ai_socktype = SOCK_STREAM;
	hints.ai_protocol = 0;
	hints.ai_flags = AI_NUMERICSERV;
	char portstr[6];
	snprintf(portstr, sizeof portstr, "%hu", port);

	int r = getaddrinfo(host, portstr, &hints, &ai_list);

	if (r != 0) {
		W("%s", gai_strerror(r));
		return -1;
	}

	if (!ai_list) {
		W("result address list empty");
		return -1;
	}

	int sck = -1;
	for (struct addrinfo *ai = ai_list; ai; ai = ai->ai_next)
	{
		errno = 0;
		sck = socket(ai->ai_family, ai->ai_socktype, ai->ai_protocol);
		if (sck < 0) {
			WE("cannot create socket");
			continue;
		}
		
		errno = 0;
		if (fcntl(sck, F_SETFL, O_NONBLOCK) == -1) {
			WE("failed to enable nonblocking mode");
			close(sck);
			sck = -1;
			continue;
		}
		
		D("set to nonblocking mode, calling connect() now");
		errno = 0;
		int r = connect(sck, ai->ai_addr, ai->ai_addrlen);

		if (r == -1 && (errno != EINPROGRESS)) {
			WE("connect() failed");
			close(sck);
			sck = -1;
			continue;
		}

		int opt = 1;
		socklen_t optlen = sizeof opt;
		struct timeval tout;
		tout.tv_sec = 0;
		tout.tv_usec = 0;
		int64_t trem = 0;

		for(;;) {
			if (tsend)
			{
				trem = tsend - timestamp_us();
				if (trem <= 0) {
					W("timeout reached while in 3WHS");
					close(sck);
					sck = -1;
					goto outer_bot;
				}

				tconv(&tout, &trem, false);
			}

			fd_set fds;
			FD_ZERO(&fds);
			FD_SET(sck, &fds);

			errno = 0;
			r = select(sck+1, NULL, &fds, NULL, tsend ? &tout : NULL);
			if (r < 0)
			{
				WE("select() failed");
				close(sck);
				sck = -1;
				goto outer_bot;
			}
			if (r == 1) {
				D("select finished successfully");
				break;
			}
		}

		if (getsockopt(sck, SOL_SOCKET, SO_ERROR, &opt, &optlen) != 0) {
			W("getsockopt failed");
			close(sck);
			sck = -1;
			continue;
		}

		if (opt == 0) {
			D("socket connected, setting to blocking mode");
			errno = 0;
			if (fcntl(sck, F_SETFL, 0) == -1) {
				WE("failed to clear nonblocking mode");
				close(sck);
				sck = -1;
				continue;
			}

			break;
		} else {
			WC(opt, "could not connect socket (%d)", opt);
			close(sck);
			sck = -1;
			continue;
		}
outer_bot:;
	}

	freeaddrinfo(ai_list);

	return sck;
}
Example #19
0
int backtrack(Puzzle *puz, Solution *sol)
{
    Hist *h;
    //color_t z, oldn, newn;
    //dir_t k;

    if (VB) printf("B: BACKTRACKING TO LAST GUESS\n");

    /* Undo up to, but not including, the most recent branch point */
    if (undo(puz,sol, 1))
    {
        if (VB) printf("B: CANNOT BACKTRACK\n");
        return 1;
    }

    if (VB) print_solution(stdout,puz,sol);

    /* This will be the branch point since undo() backed us up to it */
    h= HIST(puz, puz->nhist-1);

    if (VB || WC(h->cell))
    {
        printf("B: LAST GUESS WAS ");
        print_coord(stdout,puz,h->cell);
        printf(" |");
        dump_bits(stdout,puz,h->bit);
        printf("| -> |");
        dump_bits(stdout,puz,h->cell->bit);
        printf("|\n");
    }

    /* If undoing a solved cell, uncount it */
    if (h->cell->n == 1) solved_a_cell(puz, h->cell, -1);

    /* Reset any bits previously set */
#ifdef LIMITCOLORS
    h->cell->bit[0]= ((~h->cell->bit[0]) & h->bit[0]);
#else
    for (z= 0; z < fbit_size; z++)
        h->cell->bit[z]= ((~h->cell->bit[z]) & h->bit[z]);
#endif
    h->cell->n= h->n - h->cell->n;  /* Since the bits set in h are always
				       a superset of those in h->cell,
				       this should always work */

    /* If inverted cell is solved, count it */
    if (h->cell->n == 1) solved_a_cell(puz, h->cell, 1);

    if (VB || WC(h->cell))
    {
        printf("B: INVERTING GUESS TO |");
        dump_bits(stdout,puz,h->cell->bit);
        printf("| (%d)\n",h->cell->n);
    }

    /* Now that we've backtracked to it and inverted it, it is no
     * longer a branch point.  If there is no previous history, delete
     * this node.  Otherwise, convert it into a non-branch point.
     * Next time we backtrack we will just delete it.
     */
    if (puz->nhist == 1)
        puz->nhist= 0;
    else
        h->branch= 0;

    /* Remove everything from the job list except the lines containing
     * the inverted cell.
     */
    if (maylinesolve)
    {
        flush_jobs(puz);
        add_jobs(puz, sol, -1, h->cell, 0, h->bit);
    }

    backtracks++;

    return 0;
}
Example #20
0
void leap_gesture_swipe_start_position(leap_gesture_ref gesture, leap_vector *out_result)
{
    *out_result = to_vector(WC(gesture).startPosition());
}