Example #1
0
void ccDBRoot::redrawCCObject(ccHObject* anObject)
{
    assert(anObject);

    anObject->redrawDisplay();
}
Example #2
0
bool CSock::Ioctl(long cmd,u_long FAR* argp)
{
	assert(IsCreate());
	if(!IsCreate()) return false;
	return SOCKET_ERROR != ::ioctlsocket(_s,cmd,argp);
}
Example #3
0
/**
 * Resize the given framebuffer's renderbuffers to the new width and height.
 * This should only be used for window-system framebuffers, not
 * user-created renderbuffers (i.e. made with GL_EXT_framebuffer_object).
 * This will typically be called via ctx->Driver.ResizeBuffers() or directly
 * from a device driver.
 *
 * \note it's possible for ctx to be null since a window can be resized
 * without a currently bound rendering context.
 */
void
_mesa_resize_framebuffer(GLcontext *ctx, struct gl_framebuffer *fb,
                         GLuint width, GLuint height)
{
   GLuint i;

   /* XXX I think we could check if the size is not changing
    * and return early.
    */

   /* For window system framebuffers, Name is zero */
   assert(fb->Name == 0);

   for (i = 0; i < BUFFER_COUNT; i++) {
      struct gl_renderbuffer_attachment *att = &fb->Attachment[i];
      if (att->Type == GL_RENDERBUFFER_EXT && att->Renderbuffer) {
         struct gl_renderbuffer *rb = att->Renderbuffer;
         /* only resize if size is changing */
         if (rb->Width != width || rb->Height != height) {
            /* could just as well pass rb->_ActualFormat here */
            if (rb->AllocStorage(ctx, rb, rb->InternalFormat, width, height)) {
               ASSERT(rb->Width == width);
               ASSERT(rb->Height == height);
            }
            else {
               _mesa_error(ctx, GL_OUT_OF_MEMORY, "Resizing framebuffer");
               /* no return */
            }
         }
      }
   }

   if (fb->_DepthBuffer) {
      struct gl_renderbuffer *rb = fb->_DepthBuffer;
      if (rb->Width != width || rb->Height != height) {
         if (!rb->AllocStorage(ctx, rb, rb->InternalFormat, width, height)) {
            _mesa_error(ctx, GL_OUT_OF_MEMORY, "Resizing framebuffer");
         }
      }
   }

   if (fb->_StencilBuffer) {
      struct gl_renderbuffer *rb = fb->_StencilBuffer;
      if (rb->Width != width || rb->Height != height) {
         if (!rb->AllocStorage(ctx, rb, rb->InternalFormat, width, height)) {
            _mesa_error(ctx, GL_OUT_OF_MEMORY, "Resizing framebuffer");
         }
      }
   }

   fb->Width = width;
   fb->Height = height;

   if (ctx) {
      /* update scissor / window bounds */
      _mesa_update_draw_buffer_bounds(ctx);
      /* Signal new buffer state so that swrast will update its clipping
       * info (the CLIP_BIT flag).
       */
      ctx->NewState |= _NEW_BUFFERS;
   }
}
SequenceOverlapPairVector KmerOverlaps::retrieveMatches(const std::string& query, size_t k, 
                                                        int min_overlap, double min_identity,
                                                        int bandwidth, const BWTIndexSet& indices)
{
    PROFILE_FUNC("OverlapHaplotypeBuilder::retrieveMatches")
    assert(indices.pBWT != NULL);
    assert(indices.pSSA != NULL);

    static size_t n_calls = 0;
    static size_t n_candidates = 0;
    static size_t n_output = 0;
    static double t_time = 0;
    Timer timer("test", true);

    n_calls++;

    int64_t max_interval_size = 200;
    SequenceOverlapPairVector overlap_vector;

    // Use the FM-index to look up intervals for each kmer of the read. Each index
    // in the interval is stored individually in the KmerMatchMap. We then
    // backtrack to map these kmer indices to read IDs. As reads can share
    // multiple kmers, we use the map to avoid redundant lookups.
    // There is likely a faster algorithm which performs direct decompression
    // of the read sequences without having to expand the intervals to individual
    // indices. The current algorithm suffices for now.
    KmerMatchMap prematchMap;
    size_t num_kmers = query.size() - k + 1;
    for(size_t i = 0; i < num_kmers; ++i)
    {
        std::string kmer = query.substr(i, k);
        BWTInterval interval = BWTAlgorithms::findInterval(indices, kmer);
        if(interval.isValid() && interval.size() < max_interval_size) 
        {
            for(int64_t j = interval.lower; j <= interval.upper; ++j)
            {
                KmerMatch match = { i, static_cast<size_t>(j), false };
                prematchMap.insert(std::make_pair(match, false));
            }
        }

        kmer = reverseComplement(kmer);
        interval = BWTAlgorithms::findInterval(indices, kmer);
        if(interval.isValid() && interval.size() < max_interval_size) 
        {
            for(int64_t j = interval.lower; j <= interval.upper; ++j)
            {
                KmerMatch match = { i, static_cast<size_t>(j), true };
                prematchMap.insert(std::make_pair(match, false));
            }
        }
    }

    // Backtrack through the kmer indices to turn them into read indices.
    // This mirrors the calcSA function in SampledSuffixArray except we mark each entry
    // as visited once it is processed.
    KmerMatchSet matches;
    for(KmerMatchMap::iterator iter = prematchMap.begin(); iter != prematchMap.end(); ++iter)
    {
        // This index has been visited
        if(iter->second)
            continue;

        // Mark this as visited
        iter->second = true;

        // Backtrack the index until we hit the starting symbol
        KmerMatch out_match = iter->first;
        while(1) 
        {
            char b = indices.pBWT->getChar(out_match.index);
            out_match.index = indices.pBWT->getPC(b) + indices.pBWT->getOcc(b, out_match.index - 1);

            // Check if the hash indicates we have visited this index. If so, stop the backtrack
            KmerMatchMap::iterator find_iter = prematchMap.find(out_match);
            if(find_iter != prematchMap.end())
            {
                // We have processed this index already
                if(find_iter->second)
                    break;
                else
                    find_iter->second = true;
            }

            if(b == '$')
            {
                // We've found the lexicographic index for this read. Turn it into a proper ID
                out_match.index = indices.pSSA->lookupLexoRank(out_match.index);
                matches.insert(out_match);
                break;
            }
        }
    }

    // Refine the matches by computing proper overlaps between the sequences
    // Use the overlaps that meet the thresholds to build a multiple alignment
    for(KmerMatchSet::iterator iter = matches.begin(); iter != matches.end(); ++iter)
    {
		
        std::string match_sequence = BWTAlgorithms::extractString(indices.pBWT, iter->index);
        if(iter->is_reverse)
            match_sequence = reverseComplement(match_sequence);
        
        // Ignore identical matches
        if(match_sequence == query)
            continue;

        // Compute the overlap. If the kmer match occurs a single time in each sequence we use
        // the banded extension overlap strategy. Otherwise we use the slow O(M*N) overlapper.
        SequenceOverlap overlap;
        std::string match_kmer = query.substr(iter->position, k);
        size_t pos_0 = query.find(match_kmer);
        size_t pos_1 = match_sequence.find(match_kmer);
        assert(pos_0 != std::string::npos && pos_1 != std::string::npos);

        // Check for secondary occurrences
        if(query.find(match_kmer, pos_0 + 1) != std::string::npos || 
           match_sequence.find(match_kmer, pos_1 + 1) != std::string::npos) {
            // One of the reads has a second occurrence of the kmer. Use
            // the slow overlapper.
            overlap = Overlapper::computeOverlap(query, match_sequence);
        } else {
            overlap = Overlapper::extendMatch(query, match_sequence, pos_0, pos_1, bandwidth);
        }
		
		
        n_candidates += 1;
        bool bPassedOverlap = overlap.getOverlapLength() >= min_overlap;
        bool bPassedIdentity = overlap.getPercentIdentity() / 100 >= min_identity;

        if(bPassedOverlap && bPassedIdentity)
        {
            SequenceOverlapPair op;
            op.sequence[0] = query;
            op.sequence[1] = match_sequence;
            op.overlap = overlap;
            op.is_reversed = iter->is_reverse;
            overlap_vector.push_back(op);
            n_output += 1;
        }
    }

    t_time += timer.getElapsedCPUTime();

    if(Verbosity::Instance().getPrintLevel() > 6 && n_calls % 100 == 0)
        printf("[kmer overlaps] n: %zu candidates: %zu valid: %zu (%.2lf) time: %.2lfs\n", 
            n_calls, n_candidates, n_output, (double)n_output / n_candidates, t_time);
    return overlap_vector;
}
Example #5
0
int CSock::Recv(char* buf,size_t cnt)
{
	assert(IsCreate());
	return ::recv(_s,buf,cnt,0);
}
Example #6
0
void TNonblockingIOThread::createNotificationPipe() {
  if (evutil_socketpair(AF_LOCAL, SOCK_STREAM, 0, notificationPipeFDs_) == -1) {
    GlobalOutput.perror("TNonblockingServer::createNotificationPipe ", EVUTIL_SOCKET_ERROR());
    throw TException("can't create notification pipe");
  }
  if (evutil_make_socket_nonblocking(notificationPipeFDs_[0]) < 0
      || evutil_make_socket_nonblocking(notificationPipeFDs_[1]) < 0) {
    ::THRIFT_CLOSESOCKET(notificationPipeFDs_[0]);
    ::THRIFT_CLOSESOCKET(notificationPipeFDs_[1]);
    throw TException("TNonblockingServer::createNotificationPipe() THRIFT_O_NONBLOCK");
  }
  for (int i = 0; i < 2; ++i) {
#if LIBEVENT_VERSION_NUMBER < 0x02000000
    int flags;
    if ((flags = THRIFT_FCNTL(notificationPipeFDs_[i], F_GETFD, 0)) < 0
        || THRIFT_FCNTL(notificationPipeFDs_[i], F_SETFD, flags | FD_CLOEXEC) < 0) {
#else
    if (evutil_make_socket_closeonexec(notificationPipeFDs_[i]) < 0) {
#endif
      ::THRIFT_CLOSESOCKET(notificationPipeFDs_[0]);
      ::THRIFT_CLOSESOCKET(notificationPipeFDs_[1]);
      throw TException(
          "TNonblockingServer::createNotificationPipe() "
          "FD_CLOEXEC");
    }
  }
}

/**
 * Register the core libevent events onto the proper base.
 */
void TNonblockingIOThread::registerEvents() {
  threadId_ = Thread::get_current();

  assert(eventBase_ == 0);
  eventBase_ = getServer()->getUserEventBase();
  if (eventBase_ == NULL) {
    eventBase_ = event_base_new();
    ownEventBase_ = true;
  }

  // Print some libevent stats
  if (number_ == 0) {
    GlobalOutput.printf("TNonblockingServer: using libevent %s method %s",
                        event_get_version(),
                        event_base_get_method(eventBase_));
  }

  if (listenSocket_ >= 0) {
    // Register the server event
    event_set(&serverEvent_,
              listenSocket_,
              EV_READ | EV_PERSIST,
              TNonblockingIOThread::listenHandler,
              server_);
    event_base_set(eventBase_, &serverEvent_);

    // Add the event and start up the server
    if (-1 == event_add(&serverEvent_, 0)) {
      throw TException(
          "TNonblockingServer::serve(): "
          "event_add() failed on server listen event");
    }
    GlobalOutput.printf("TNonblocking: IO thread #%d registered for listen.", number_);
  }

  createNotificationPipe();

  // Create an event to be notified when a task finishes
  event_set(&notificationEvent_,
            getNotificationRecvFD(),
            EV_READ | EV_PERSIST,
            TNonblockingIOThread::notifyHandler,
            this);

  // Attach to the base
  event_base_set(eventBase_, &notificationEvent_);

  // Add the event and start up the server
  if (-1 == event_add(&notificationEvent_, 0)) {
    throw TException(
        "TNonblockingServer::serve(): "
        "event_add() failed on task-done notification event");
  }
  GlobalOutput.printf("TNonblocking: IO thread #%d registered for notify.", number_);
}
SequenceOverlapPairVector KmerOverlaps::PacBioRetrieveMatches(const std::string& query, size_t k, 
                                                        int min_overlap, double min_identity,
                                                        int bandwidth, const BWTIndexSet& indices,
														KmerDistribution& kd, int round)
{
    PROFILE_FUNC("OverlapHaplotypeBuilder::PacBioRetrieveMatches")
    assert(indices.pBWT != NULL);
    assert(indices.pSSA != NULL);
	
	//size_t numStringCount[query.size()+1] = 0;
	
	int64_t intervalSum = 0;
    static size_t n_calls = 0;
    static size_t n_candidates = 0;
    static size_t n_output = 0;
    static double t_time = 0;
	size_t count = 0;
	size_t numKmer = 0;
	size_t numRepeatKmer = 0;
	size_t totalKmer = 0;
	size_t numNoSeedRead = 0;
	size_t repeatCutoff = kd.getRepeatKmerCutoff();
	size_t errorCutoff = kd.getMedian() - kd.getSdv();
    Timer timer("test", true);
	
    n_calls++;
	//std::cout<<"PacBioRetrieveMatches\n";
	std::cout<<"\tk :\t"<<k<<"\n";
    SequenceOverlapPairVector overlap_vector;
	std::vector<long> identityVector(100);
	for(int j = 0;j < identityVector.size(); j++)
		identityVector[j] = 0;
		
    // Use the FM-index to look up intervals for each kmer of the read. Each index
    // in the interval is stored individually in the KmerMatchMap. We then
    // backtrack to map these kmer indices to read IDs. As reads can share
    // multiple kmers, we use the map to avoid redundant lookups.
    // There is likely a faster algorithm which performs direct decompression
    // of the read sequences without having to expand the intervals to individual
    // indices. The current algorithm suffices for now.
    KmerMatchMap prematchMap;
    size_t num_kmers = query.size() - k + 1;
	clock_t search_seeds_s = clock(), search_seeds_e;
    
	
	for(size_t i = 0; i < num_kmers; i++)
    {
        std::string kmer = query.substr(i, k);
        BWTInterval interval = BWTAlgorithms::findInterval(indices, kmer);
		if(interval.upper - interval.lower < errorCutoff)
			numNoSeedRead++;
		if((interval.upper - interval.lower) > 20 && (interval.upper - interval.lower) < repeatCutoff)
		{
			numKmer++;
			totalKmer++;
		}
		
		//To avoid the repeat region
		/*if((interval.upper - interval.lower) > repeatCutoff)
		{	
			numRepeatKmer++;
			totalKmer++;
			continue;
		}
		else
			interval.upper = ((interval.upper - interval.lower)>20)?interval.lower + 20 : interval.upper;*/
		
        if(interval.isValid() && interval.size()) 
        {
			//std::cout<<"\tinterval size : "<<interval.upper - interval.lower<<std::endl;
            for(int64_t j = interval.lower; j <= interval.upper; ++j)
            {
                KmerMatch match = { i, static_cast<size_t>(j), false };
                prematchMap.insert(std::make_pair(match, false));
            }
			intervalSum += interval.upper - interval.lower;
			count++;
        }

        kmer = reverseComplement(kmer);
        interval = BWTAlgorithms::findInterval(indices, kmer);
		interval.upper = ((interval.upper - interval.lower)>20)?interval.lower + 20 : interval.upper;
        if(interval.isValid() && interval.size())
        {
            for(int64_t j = interval.lower; j <= interval.upper; ++j)
            {
                KmerMatch match = { i, static_cast<size_t>(j), true };
                prematchMap.insert(std::make_pair(match, false));
            }
			intervalSum += interval.upper - interval.lower;
			count++;
        }
    }
	if(numNoSeedRead == num_kmers)
		std::cout<<"\tnoSeedRead : 1"<<std::endl;
	std::cout<<"\tnumber of kmer : "<<numKmer<<std::endl;
	std::cout<<"\tnumber of RepeatKmer : "<<numRepeatKmer<<std::endl;
	std::cout<<"\tnumber of totalkmer : "<<totalKmer<<std::endl;
	
	
    // Backtrack through the kmer indices to turn them into read indices.
    // This mirrors the calcSA function in SampledSuffixArray except we mark each entry
    // as visited once it is processed.
	//std::cout<<"\tintervalSum : "<<intervalSum<<std::endl;
	//std::cout<<"\tintervalCount : "<<count<<std::endl;
	std::cout<<"\tprematchMap :\t"<<prematchMap.size()<<std::endl;
    KmerMatchSet matches;
    for(KmerMatchMap::iterator iter = prematchMap.begin(); iter != prematchMap.end(); ++iter)
    {
		//std::cout<<"iter->first.position : "<<iter->first.position<<std::endl;
        // This index has been visited
        if(iter->second)
            continue;

        // Mark this as visited
        iter->second = true;

        // Backtrack the index until we hit the starting symbol
        KmerMatch out_match = iter->first;
        while(1) 
        {
            char b = indices.pBWT->getChar(out_match.index);
            out_match.index = indices.pBWT->getPC(b) + indices.pBWT->getOcc(b, out_match.index - 1);

            // Check if the hash indicates we have visited this index. If so, stop the backtrack
            KmerMatchMap::iterator find_iter = prematchMap.find(out_match);
            if(find_iter != prematchMap.end())
            {
                // We have processed this index already
                if(find_iter->second)
                    break;
                else
                    find_iter->second = true;
            }

            if(b == '$')
            {
                // We've found the lexicographic index for this read. Turn it into a proper ID
                out_match.index = indices.pSSA->lookupLexoRank(out_match.index);
				//std::cout<<"out_match.position"<<out_match.position<<std::endl;
                matches.insert(out_match);
                break;
            }
        }
    }
	search_seeds_e = clock();
	std::cout<<"\tmatchset :\t"<<matches.size()<<"\n";
    // Refine the matches by computing proper overlaps between the sequences
    // Use the overlaps that meet the thresholds to build a multiple alignment
	clock_t  extrac_s, extrac_e;
	clock_t  overlapE_s, overlapE_e;
	clock_t  overlapC_s, overlapC_e;
	double extrac_sum = 0.0;
	double overlapE_sum = 0.0, overlapC_sum = 0.0;
	int compute_count = 0,extend_count = 0;
	size_t acNumber = 0;
    for(KmerMatchSet::iterator iter = matches.begin(); iter != matches.end(); ++iter)
    {
		extrac_s = clock();
        std::string match_sequence;// = BWTAlgorithms::extractString(indices.pBWT, iter->index);
		
		if(indices.pReadTable != NULL)
            match_sequence = indices.pReadTable->getRead(iter->index).seq.toString();
		/*else
			match_sequence = BWTAlgorithms::extractString(indices.pBWT, iter->index);*/
		
		extrac_e = clock();
		extrac_sum += (double)extrac_e - extrac_s;
        
		if(iter->is_reverse)
            match_sequence = reverseComplement(match_sequence);
        
        // Ignore identical matches
        if(match_sequence == query)
            continue;

        // Compute the overlap. If the kmer match occurs a single time in each sequence we use
        // the banded extension overlap strategy. Otherwise we use the slow O(M*N) overlapper.
        SequenceOverlap overlap;
        std::string match_kmer = query.substr(iter->position, k);
        size_t pos_0 = iter->position;//query.find(match_kmer);
        size_t pos_1 = match_sequence.find(match_kmer);
        assert(pos_0 != std::string::npos && pos_1 != std::string::npos);

		//Timer* sTimer = new Timer("seeds overlap");
        // Check for secondary occurrences
        /*if(query.find(match_kmer, pos_0 + 1) != std::string::npos || 
           match_sequence.find(match_kmer, pos_1 + 1) != std::string::npos) {
            // One of the reads has a second occurrence of the kmer. Use
            // the slow overlapper.
			overlapC_s = clock();
			compute_count++;
            overlap = Overlapper::computeOverlap(query, match_sequence);
			overlapC_e = clock();
			overlapC_sum += (double)overlapC_e - overlapC_s;
        } 
	
		else {*/
			overlapE_s = clock();
			extend_count++;
            overlap = Overlapper::PacBioExtendMatch(query, match_sequence, pos_0, pos_1, bandwidth);
			overlapE_e = clock();
			overlapE_sum += (double)overlapE_e - overlapE_s;
		//}
	
		//delete sTimer;
        n_candidates += 1;
        bool bPassedOverlap = overlap.getOverlapLength() >= min_overlap;
        bool bPassedIdentity = overlap.getPercentIdentity()  >= min_identity;
		identityVector[(int)overlap.getPercentIdentity()] += 1;
		//overlap.printTotal_columns();
		//overlap.printEdit_distance();
		//std::cout<<"min_overlap == "<<overlap.getOverlapLength()<<"\n";
		//std::cout<<"overlap.getOverlapLength() / 100 == "<<overlap.getOverlapLength() / 100<<"\n";
		//std::cout<<"min_identity == "<<min_identity<<"\n";
		//std::cout<<"bPassedOverlap == "<<bPassedOverlap<<"\n";
		//std::cout<<"bPassedIdentity == "<<bPassedIdentity<<"\n";
		//std::cout<<match_sequence<<"\n";
        if(bPassedOverlap && bPassedIdentity)
        {
            SequenceOverlapPair op;
            op.sequence[0] = query;
            op.sequence[1] = match_sequence;
            op.overlap = overlap;
            op.is_reversed = iter->is_reverse;
            overlap_vector.push_back(op);
            n_output += 1;
			acNumber += 1;
			//numStringCount
        } 
    }
	
	std::cout<<"\tacceptable number of seeds == "<<acNumber<<"\n";
	std::cout<<"\tsearch seeds time : "<<(double)(search_seeds_e - search_seeds_s)/CLOCKS_PER_SEC<<std::endl;
	std::cout<<"\textract time : "<<extrac_sum/CLOCKS_PER_SEC<<std::endl;
	//std::cout<<"\tcompute_count : "<<compute_count<<std::endl;
	//std::cout<<"\tbanded_count : "<<extend_count<<std::endl;
	//std::cout<<"\tcompute overlap time : "<<overlapC_sum/CLOCKS_PER_SEC<<std::endl;
	//std::cout<<"\tbanded overlap time : "<<overlapE_sum/CLOCKS_PER_SEC<<std::endl;
	/*------------------output-identity------------------------------------
	double mean = 0.0, temp_mean = 0.0,temp = 0.0;
	for(int i = 0; i < 100; i++)
	{	//count*identity
		mean+=identityVector[i]*i;
		temp+=identityVector[i];
	}
	mean=mean/temp;
	
	for(int i = 0; i < 100; i++)
		//count*identity^2
		temp_mean+=identityVector[i]*pow(i,2);
	std::cout<<"-----------outputIdentity------------"<<std::endl;
	std::cout<<"\tround "<<round;
	std::cout<<"\tmean identity :\t"<<mean<<std::endl;
	std::cout<<"\tSD identity :\t"<<sqrt(temp_mean/temp - pow(mean,2))<<std::endl;
	std::cout<<"-------------------------------------\n"<<std::endl;
	/*---------------------------------------------------------------------*/
	
    t_time += timer.getElapsedCPUTime();

    if(Verbosity::Instance().getPrintLevel() > 6 && n_calls % 100 == 0)
        printf("[kmer overlaps] n: %zu candidates: %zu valid: %zu (%.2lf) time: %.2lfs\n", 
            n_calls, n_candidates, n_output, (double)n_output / n_candidates, t_time);
    return overlap_vector;
}
void display(void) {
    struct timeval time1, time2;
    double total_time, rate, pixel_rate;
    const unsigned pixel_size = formats[cur_format].num_comp * types[cur_type].byte_size / types[cur_type].num_comp;
    const unsigned buf_size = align_size(screen_width * pixel_size, ALIGNMENT) * screen_height;
    unsigned char* buf = (unsigned char*) malloc(buf_size);
    assert(buf);

    if (stabilizing_rounds) 
        printf("Stabilizing round %i\n", stabilizing_rounds);
    
    glPixelStorei(GL_PACK_ALIGNMENT, ALIGNMENT);
    gettimeofday(&time1, NULL);
    for (int i = 0; i < NUM_READBACKS; ++i) {
        glReadPixels(0, 0, screen_width, screen_height, formats[cur_format].format, types[cur_type].type, buf);
    }
    gettimeofday(&time2, NULL);

    total_time = (time2.tv_sec + 1e-6 * time2.tv_usec - time1.tv_sec - 1e-6 * time1.tv_usec);
    rate = 1e-6 * NUM_READBACKS * buf_size / total_time;
    pixel_rate = 1e-6 * NUM_READBACKS * screen_width * screen_height / total_time;
    
    if (stabilizing_rounds) {
        --stabilizing_rounds;
        
    } else {
        results[cur_type * NUM_FORMATS + cur_format].type = cur_type;
        results[cur_type * NUM_FORMATS + cur_format].format = cur_format;
        results[cur_type * NUM_FORMATS + cur_format].rate = rate;
        results[cur_type * NUM_FORMATS + cur_format].pixel_rate = pixel_rate;
        
        printf("%s %s %g MB/s %g Mp/s\n", 
               formats[cur_format].desc, types[cur_type].desc, rate, pixel_rate);
        
        /* Find the next type that is compatible with the current format */
        do {
            ++cur_type;
        } while (!compatible(formats[cur_format], types[cur_type]) && cur_type < NUM_TYPES);
        
        /* Go to the next type/format */
        if (cur_type == NUM_TYPES) {
            cur_type = 0;
            
            if (++cur_format == NUM_FORMATS) {
                
                printf("\nSorted by data rate:\n");
                qsort(results, NUM_FORMATS * NUM_TYPES, sizeof(result_t), compare_data_rate);
                for (int i = 0; i < NUM_FORMATS * NUM_TYPES; ++i) {
                    if (results[i].rate >= 0) 
                        printf("%s %s %g MB/s\n", 
                               formats[results[i].format].desc, 
                               types[results[i].type].desc, 
                               results[i].rate);
                }
                
                printf("\nSorted by pixel rate:\n");
                qsort(results, NUM_FORMATS * NUM_TYPES, sizeof(result_t), compare_pixel_rate);
                for (int i = 0; i < NUM_FORMATS * NUM_TYPES; ++i) {
                    if (results[i].rate >= 0) 
                        printf("%s %s %g Mp/s\n", 
                               formats[results[i].format].desc, 
                               types[results[i].type].desc, 
                               results[i].pixel_rate);
                }
                
                exit(0);
            }
        }
    }
    
    free(buf);
    
    glutReportErrors();
    glutPostRedisplay();
}
Example #9
0
 T & operator [](size_t i) const
 {
     assert(i < m_size);
     return m_p[i];
 }
 static intx allocate_prefetch_style() {
   assert(AllocatePrefetchStyle >= 0, "AllocatePrefetchStyle should be positive");
   // Return 0 if AllocatePrefetchDistance was not defined.
   return AllocatePrefetchDistance > 0 ? AllocatePrefetchStyle : 0;
 }
ModelElement* MagnetMover::Copy () const
{
	// Not sure what to do here!
	assert(false);
	return 0;
}
Example #12
0
bool ObjReader::Read(const std::string & filename)
{
	std::ifstream file(filename);

	if (! file.good())
		return false;

	std::vector<Vector3> points;
	std::vector<Vector3> normals;
	std::vector<std::tuple<Face, Face, Face>> faces;

	while (file)
	{
		std::string line;
		std::getline(file, line);

		if (line[0] == '#')
			continue;

		if (line.empty())
			continue;

		std::vector<std::string> parts = Split(line, ' ');

		if (parts[0] == "v")
		{
			if (parts.size() != 4)
				return false;

			points.emplace_back(std::stof(parts[1]), std::stof(parts[2]), std::stof(parts[3]));
		}
		else if (parts[0] == "vn")
		{
			if (parts.size() != 4)
				return false;

			Vector3 normal(std::stof(parts[1]), std::stof(parts[2]), std::stof(parts[3]));
			normal.Normalize();

			normals.emplace_back(normal);
		}
		else if (parts[0] == "f")
		{
			if (parts.size() != 4)
				return false;

			faces.emplace_back(parts[1], parts[2], parts[3]);
		}
		// Ignore
		else if (parts[0] == "mtllib" || parts[0] == "usemtl" || parts[0] == "vt" ||
			parts[0] == "g" || parts[0] == "s" || parts[0] == "o")
		{
			continue;
		}
		else
		{
			return false;
		}
	}

	if (normals.empty())
	{
		const std::size_t size = points.size();

		for (std::size_t i = 0; i < size; ++i)
		{
			Vector3 normal;

			const std::size_t index = normals.size();

			for (auto && face : faces)
			{
				Face & f1 = std::get<0>(face);
				Face & f2 = std::get<1>(face);
				Face & f3 = std::get<2>(face);

				if (f1.point == i || f2.point == i ||f3.point == i)
				{
					geometry::Triangle triangle(points[f1.point], points[f2.point], points[f3.point]);
					normal += triangle.Normal();

					if (f1.point == i)
						f1.normal = index;

					if (f2.point == i)
						f2.normal = index;

					if (f3.point == i)
						f3.normal = index;
				}
			}

			normals.push_back(normal.NormalizedCopy());
		}
	}

	std::vector<geometry::Triangle> triangles;

	for (auto && face : faces)
	{
		Face f1 = std::get<0>(face);
		Face f2 = std::get<1>(face);
		Face f3 = std::get<2>(face);

		assert(f1.normal != Face::None);
		assert(f2.normal != Face::None);
		assert(f3.normal != Face::None);

		triangles.emplace_back(points[f1.point], points[f2.point], points[f3.point],
			normals[f1.normal], normals[f2.normal], normals[f3.normal]);
	}

	m_model.reset(new ObjModel(std::move(triangles)));

	return true;
}
Example #13
0
/*
 * local version of a security handle allocator.  Logically sets
 * up a network "connection".
 */
static void
local_connect(
    const char *	hostname,
    char *		(*conf_fn)(char *, void *),
    void		(*fn)(void *, security_handle_t *, security_status_t),
    void *		arg,
    void *		datap)
{
    struct sec_handle *rh;
    char *amandad_path=NULL;
    char *client_username=NULL;
    char myhostname[MAX_HOSTNAME_LENGTH+1];

    assert(fn != NULL);
    assert(hostname != NULL);

    auth_debug(1, _("local: local_connect: %s\n"), hostname);

    rh = g_new0(struct sec_handle, 1);
    security_handleinit(&rh->sech, &local_security_driver);
    rh->hostname = NULL;
    rh->rs = NULL;
    rh->ev_timeout = NULL;
    rh->rc = NULL;

    if (gethostname(myhostname, MAX_HOSTNAME_LENGTH) == -1) {
	security_seterror(&rh->sech, _("gethostname failed"));
	(*fn)(arg, &rh->sech, S_ERROR);
	return;
    }
    myhostname[sizeof(myhostname)-1] = '\0';

    if (strcmp(hostname, myhostname) != 0 &&
	match("^localhost(\\.localdomain)?$", hostname) == 0) {
	security_seterror(&rh->sech,
	    _("%s: is not local"), hostname);
	(*fn)(arg, &rh->sech, S_ERROR);
	return;
    }
    rh->hostname = g_strdup(hostname);
    rh->rs = tcpma_stream_client(rh, newhandle++);

    if (rh->rs == NULL)
	goto error;

    amfree(rh->hostname);
    rh->hostname = g_strdup(rh->rs->rc->hostname);

    /*
     * We need to open a new connection.
     *
     * XXX need to eventually limit number of outgoing connections here.
     */
    if(conf_fn) {
	amandad_path    = conf_fn("amandad_path", datap);
	client_username = conf_fn("client_username", datap);
    }
    if(rh->rc->read == -1) {
	if (runlocal(rh->rs->rc, amandad_path, client_username) < 0) {
	    security_seterror(&rh->sech, _("can't connect to %s: %s"),
			      hostname, rh->rs->rc->errmsg);
	    goto error;
	}
	rh->rc->refcnt++;
    }

    /*
     * The socket will be opened async so hosts that are down won't
     * block everything.  We need to register a write event
     * so we will know when the socket comes alive.
     *
     * Overload rh->rs->ev_read to provide a write event handle.
     * We also register a timeout.
     */
    rh->fn.connect = fn;
    rh->arg = arg;
    rh->rs->ev_read = event_register((event_id_t)rh->rs->rc->write, EV_WRITEFD,
	sec_connect_callback, rh);
    rh->ev_timeout = event_register((event_id_t)CONNECT_TIMEOUT, EV_TIME,
	sec_connect_timeout, rh);

    return;

error:
    (*fn)(arg, &rh->sech, S_ERROR);
    amfree(rh->hostname);
}
Example #14
0
bool ccDBRoot::dropMimeData(const QMimeData* data, Qt::DropAction action, int destRow, int destColumn, const QModelIndex& destParent)
{
	if (action != Qt::MoveAction)
         return false;

	//default mime type for QAbstractItemModel items)
	if (!data->hasFormat("application/x-qabstractitemmodeldatalist"))
		return false;

	//new parent (can't be a leaf object!)
	ccHObject *newParent = destParent.isValid() ? static_cast<ccHObject*>(destParent.internalPointer()) : m_treeRoot;
	if (newParent && newParent->isLeaf())
		return false;

	//decode data
	QByteArray encoded = data->data("application/x-qabstractitemmodeldatalist");
	QDataStream stream(&encoded, QIODevice::ReadOnly);
	while (!stream.atEnd())
	{
		//decode current item index data (row, col, data 'roles' map)
		int srcRow, srcCol;
		QMap<int, QVariant> roleDataMap;
		stream >> srcRow >> srcCol >> roleDataMap;
		if (!roleDataMap.contains(Qt::UserRole))
			continue;

		//selected item
		int uniqueID = roleDataMap.value(Qt::UserRole).toInt();
		ccHObject *item = m_treeRoot->find(uniqueID);
		if (!item)
			continue;
		//ccConsole::Print(QString("[Drag & Drop] Source: %1").arg(item->getName()));

		//old parent
		ccHObject* oldParent = item->getParent();
		//ccConsole::Print(QString("[Drag & Drop] Parent: %1").arg(oldParent ? oldParent->getName() : "none")));

		//let's check if we can actually move the entity
		if (oldParent)
		{
			if (item->isKindOf(CC_POINT_CLOUD))
			{
				//point cloud == mesh vertices?
				if (oldParent->isKindOf(CC_MESH) && static_cast<ccGenericMesh*>(oldParent)->getAssociatedCloud() == item)
					if (oldParent != newParent)
					{
						ccConsole::Error("Vertices can't leave their parent mesh!");
						return false;
					}
			}
			else if (item->isKindOf(CC_MESH))
			{
				//a mesh can't leave it's mesh group
				if (oldParent->isA(CC_MESH_GROUP) && static_cast<ccGenericMesh*>(item)->getAssociatedCloud() == static_cast<ccGenericMesh*>(oldParent)->getAssociatedCloud())
				{
					if (oldParent != newParent)
					{
						ccConsole::Error("Sub-meshes can't leave their mesh group!");
						return false;
					}
				}
				//a mesh can't leave it's associated cloud
				else if (oldParent->isKindOf(CC_POINT_CLOUD) &&  static_cast<ccGenericMesh*>(item)->getAssociatedCloud() == oldParent)
				{
					if (oldParent != newParent)
					{
						ccConsole::Error("Sub-meshes can't leave their associated cloud!");
						return false;
					}
				}
				//a mesh can't be inserted in a mesh group
				else if (newParent->isA(CC_MESH_GROUP) && static_cast<ccGenericMesh*>(item)->getAssociatedCloud() != static_cast<ccGenericMesh*>(newParent)->getAssociatedCloud())
				{
					ccConsole::Error("Outside meshes can't be added to mesh groups!");
					return false;
				}

			}
			else if (/*item->isKindOf(CC_PRIMITIVE) || */item->isKindOf(CC_IMAGE))
			{
				if (oldParent != newParent)
				{
					ccConsole::Error("This kind of entity can't leave their parent!");
					return false;
				}
			}
		}

		//special case: moving an item inside the same 'parent'
		if (oldParent && newParent == oldParent)
		{
			int oldRow = newParent->getChildIndex(item);
			if (destRow<0)
			{
				assert(newParent->getChildrenNumber()>0);
				destRow = (int)newParent->getChildrenNumber()-1;
			}
			else if (oldRow<destRow)
			{
				assert(destRow>0);
				--destRow;
			}
			else if (oldRow==destRow)
				return false; //nothing to do
		}

		//remove link from old parent
		bool fatherDependant = false;
		if (item->getFlagState(CC_FATHER_DEPENDANT))
		{
			fatherDependant = true;
			item->setFlagState(CC_FATHER_DEPENDANT,false);
		}

		//remove item from current position
		removeElement(item);

		//sets new parent
		assert(newParent);
		newParent->addChild(item,fatherDependant,destRow);

		if (newParent->getDisplay() == 0)
			newParent->setDisplay(item->getDisplay());
		else if (item->getDisplay() == 0)
			item->setDisplay(newParent->getDisplay());

		//add item back
		addElement(item,false);
	}

	return true;
}
Example #15
0
void TNonblockingServer::expireClose(boost::shared_ptr<Runnable> task) {
  TConnection* connection = static_cast<TConnection::Task*>(task.get())->getTConnection();
  assert(connection && connection->getServer() && connection->getState() == APP_WAIT_TASK);
  connection->forceClose();
}
Example #16
0
 R * get() const
 {
     assert(sizeof(R) == sizeof(T));
     return reinterpret_cast<R *>(m_p);
 }
Example #17
0
void TNonblockingServer::registerEvents(event_base* user_event_base) {
  userEventBase_ = user_event_base;

  // init listen socket
  if (serverSocket_ == THRIFT_INVALID_SOCKET)
    createAndListenOnSocket();

  // set up the IO threads
  assert(ioThreads_.empty());
  if (!numIOThreads_) {
    numIOThreads_ = DEFAULT_IO_THREADS;
  }
  // User-provided event-base doesn't works for multi-threaded servers
  assert(numIOThreads_ == 1 || !userEventBase_);

  for (uint32_t id = 0; id < numIOThreads_; ++id) {
    // the first IO thread also does the listening on server socket
    THRIFT_SOCKET listenFd = (id == 0 ? serverSocket_ : THRIFT_INVALID_SOCKET);

    shared_ptr<TNonblockingIOThread> thread(
        new TNonblockingIOThread(this, id, listenFd, useHighPriorityIOThreads_));
    ioThreads_.push_back(thread);
  }

  // Notify handler of the preServe event
  if (eventHandler_) {
    eventHandler_->preServe();
  }

  // Start all of our helper IO threads. Note that the threads run forever,
  // only terminating if stop() is called.
  assert(ioThreads_.size() == numIOThreads_);
  assert(ioThreads_.size() > 0);

  GlobalOutput.printf("TNonblockingServer: Serving on port %d, %d io threads.",
                      listenPort_,
                      ioThreads_.size());

  // Launch all the secondary IO threads in separate threads
  if (ioThreads_.size() > 1) {
    ioThreadFactory_.reset(new PlatformThreadFactory(
#if !USE_BOOST_THREAD && !USE_STD_THREAD
        PlatformThreadFactory::OTHER,  // scheduler
        PlatformThreadFactory::NORMAL, // priority
        1,                             // stack size (MB)
#endif
        false // detached
        ));

    assert(ioThreadFactory_.get());

    // intentionally starting at thread 1, not 0
    for (uint32_t i = 1; i < ioThreads_.size(); ++i) {
      shared_ptr<Thread> thread = ioThreadFactory_->newThread(ioThreads_[i]);
      ioThreads_[i]->setThread(thread);
      thread->start();
    }
  }

  // Register the events for the primary (listener) IO thread
  ioThreads_[0]->registerEvents();
}
Example #18
0
int main(int argc, char **argv) {
    int           procid, nproc, i, j, my_nelem;
    int           pollint = 0;
    double        time;
    MPI_Win       llist_win;
    llist_ptr_t   head_ptr, tail_ptr;

    MPI_Init(&argc, &argv);

    MPI_Comm_rank(MPI_COMM_WORLD, &procid);
    MPI_Comm_size(MPI_COMM_WORLD, &nproc);

    MPI_Win_create_dynamic(MPI_INFO_NULL, MPI_COMM_WORLD, &llist_win);

    /* Process 0 creates the head node */
    if (procid == 0)
        head_ptr.disp = alloc_elem(procid, llist_win);

    /* Broadcast the head pointer to everyone */
    head_ptr.rank = 0;
    MPI_Bcast(&head_ptr.disp, 1, MPI_AINT, 0, MPI_COMM_WORLD);
    tail_ptr = head_ptr;

    /* All processes append NUM_ELEMS elements to the list; rank 0 has already
     * appended an element. */
    if (procid == 0)
        i = 1;
    else
        i = 0;
    my_nelem = NUM_ELEMS/nproc;
    if (procid < NUM_ELEMS % nproc)
        my_nelem++;

    MPI_Barrier(MPI_COMM_WORLD);
    time = MPI_Wtime();

    for ( ; i < my_nelem; i++) {
        llist_ptr_t new_elem_ptr;
        int success = 0;

        /* Create a new list element and register it with the window */
        new_elem_ptr.rank = procid;
        new_elem_ptr.disp = alloc_elem(procid, llist_win);

        /* Append the new node to the list.  This might take multiple attempts if
           others have already appended and our tail pointer is stale. */
        do {
            int flag;

            /* The tail is at my left neighbor, append my element. */
            if (tail_ptr.rank == (procid + nproc-1) % nproc)
            {
                if (verbose)
                    printf("%d: Appending to <%d, %p>\n", procid, tail_ptr.rank, (void*) tail_ptr.disp);

                MPI_Win_lock(MPI_LOCK_EXCLUSIVE, tail_ptr.rank, 0, llist_win);
#if USE_ACC
                MPI_Accumulate(&new_elem_ptr, sizeof(llist_ptr_t), MPI_BYTE, tail_ptr.rank,
                               (MPI_Aint) &(((llist_elem_t*)tail_ptr.disp)->next), sizeof(llist_ptr_t),
                               MPI_BYTE, MPI_REPLACE, llist_win);
#else
                MPI_Put(&new_elem_ptr, sizeof(llist_ptr_t), MPI_BYTE, tail_ptr.rank,
                        (MPI_Aint) &(((llist_elem_t*)tail_ptr.disp)->next), sizeof(llist_ptr_t),
                        MPI_BYTE, llist_win);
#endif
                MPI_Win_unlock(tail_ptr.rank, llist_win);

                success = 1;
                tail_ptr = new_elem_ptr;
            }

            /* Otherwise, chase the tail. */
            else
            {
                llist_ptr_t next_tail_ptr;

                MPI_Win_lock(MPI_LOCK_EXCLUSIVE, tail_ptr.rank, 0, llist_win);
#if USE_ACC
                MPI_Get_accumulate( NULL, 0, MPI_DATATYPE_NULL, &next_tail_ptr,
                                    sizeof(llist_ptr_t), MPI_BYTE, tail_ptr.rank,
                                    (MPI_Aint) &(((llist_elem_t*)tail_ptr.disp)->next),
                                    sizeof(llist_ptr_t), MPI_BYTE, MPI_NO_OP, llist_win);
#else
                MPI_Get(&next_tail_ptr, sizeof(llist_ptr_t), MPI_BYTE, tail_ptr.rank,
                        (MPI_Aint) &(((llist_elem_t*)tail_ptr.disp)->next),
                        sizeof(llist_ptr_t), MPI_BYTE, llist_win);
#endif
                MPI_Win_unlock(tail_ptr.rank, llist_win);

                if (next_tail_ptr.rank != nil.rank) {
                    if (verbose)
                        printf("%d: Chasing to <%d, %p>\n", procid, next_tail_ptr.rank, (void*) next_tail_ptr.disp);
                    tail_ptr = next_tail_ptr;
                    pollint = MAX(MIN_NPROBE, pollint/2);
                }
                else {
                    for (j = 0; j < pollint; j++)
                        MPI_Iprobe(MPI_ANY_SOURCE, MPI_ANY_TAG, MPI_COMM_WORLD, &flag, MPI_STATUS_IGNORE);

                    pollint = MIN(MAX_NPROBE, pollint*2);
                }
            }
        } while (!success);
    }

    MPI_Barrier(MPI_COMM_WORLD);
    time = MPI_Wtime() - time;

    /* Traverse the list and verify that all processes inserted exactly the correct
       number of elements. */
    if (procid == 0) {
        int  errors    = 0;
        int *counts, count = 0;

        counts = (int*) malloc(sizeof(int) * nproc);
        assert(counts != NULL);

        for (i = 0; i < nproc; i++)
            counts[i] = 0;

        tail_ptr = head_ptr;

        MPI_Win_lock_all(0, llist_win);

        /* Walk the list and tally up the number of elements inserted by each rank */
        while (tail_ptr.disp != nil.disp) {
            llist_elem_t elem;

            MPI_Get(&elem, sizeof(llist_elem_t), MPI_BYTE,
                    tail_ptr.rank, tail_ptr.disp, sizeof(llist_elem_t), MPI_BYTE, llist_win);

            MPI_Win_flush(tail_ptr.rank, llist_win);

            tail_ptr = elem.next;

            assert(elem.value >= 0 && elem.value < nproc);
            counts[elem.value]++;
            count++;

            if (verbose) {
                int last_elem = tail_ptr.disp == nil.disp;
                printf("%2d%s", elem.value, last_elem ? "" : " -> ");
                if (count % ELEM_PER_ROW == 0 && !last_elem)
                    printf("\n");
            }
        }

        MPI_Win_unlock_all(llist_win);

        if (verbose)
          printf("\n\n");

        /* Verify the counts we collected */
        for (i = 0; i < nproc; i++) {
            int expected;

            expected = NUM_ELEMS/nproc;
            if (i < NUM_ELEMS % nproc)
                expected++;

            if (counts[i] != expected) {
                printf("Error: Rank %d inserted %d elements, expected %d\n", i, counts[i], expected);
                errors++;
            }
        }

        printf("%s\n", errors == 0 ? " No Errors" : "FAIL");
        free(counts);
    }

    if (print_perf) {
        double max_time;

        MPI_Reduce(&time, &max_time, 1, MPI_DOUBLE, MPI_SUM, 0, MPI_COMM_WORLD);

        if (procid == 0) {
            printf("Total time = %0.2f sec, elem/sec = %0.2f, sec/elem = %0.2f usec\n", max_time, NUM_ELEMS/max_time, max_time/NUM_ELEMS*1.0e6);
        }
    }

    MPI_Win_free(&llist_win);

    /* Free all the elements in the list */
    for ( ; my_elems_count > 0; my_elems_count--)
        MPI_Free_mem(my_elems[my_elems_count-1]);

    MPI_Finalize();
    return 0;
}
Example #19
0
/**
 * Server socket had something happen.  We accept all waiting client
 * connections on fd and assign TConnection objects to handle those requests.
 */
void TNonblockingServer::handleEvent(THRIFT_SOCKET fd, short which) {
  (void)which;
  // Make sure that libevent didn't mess up the socket handles
  assert(fd == serverSocket_);

  // Server socket accepted a new connection
  socklen_t addrLen;
  sockaddr_storage addrStorage;
  sockaddr* addrp = (sockaddr*)&addrStorage;
  addrLen = sizeof(addrStorage);

  // Going to accept a new client socket
  THRIFT_SOCKET clientSocket;

  // Accept as many new clients as possible, even though libevent signaled only
  // one, this helps us to avoid having to go back into the libevent engine so
  // many times
  while ((clientSocket = ::accept(fd, addrp, &addrLen)) != -1) {
    // If we're overloaded, take action here
    if (overloadAction_ != T_OVERLOAD_NO_ACTION && serverOverloaded()) {
      Guard g(connMutex_);
      nConnectionsDropped_++;
      nTotalConnectionsDropped_++;
      if (overloadAction_ == T_OVERLOAD_CLOSE_ON_ACCEPT) {
        ::THRIFT_CLOSESOCKET(clientSocket);
        return;
      } else if (overloadAction_ == T_OVERLOAD_DRAIN_TASK_QUEUE) {
        if (!drainPendingTask()) {
          // Nothing left to discard, so we drop connection instead.
          ::THRIFT_CLOSESOCKET(clientSocket);
          return;
        }
      }
    }

    // Explicitly set this socket to NONBLOCK mode
    int flags;
    if ((flags = THRIFT_FCNTL(clientSocket, THRIFT_F_GETFL, 0)) < 0
        || THRIFT_FCNTL(clientSocket, THRIFT_F_SETFL, flags | THRIFT_O_NONBLOCK) < 0) {
      GlobalOutput.perror("thriftServerEventHandler: set THRIFT_O_NONBLOCK (THRIFT_FCNTL) ",
                          THRIFT_GET_SOCKET_ERROR);
      ::THRIFT_CLOSESOCKET(clientSocket);
      return;
    }

    // Create a new TConnection for this client socket.
    TConnection* clientConnection = createConnection(clientSocket, addrp, addrLen);

    // Fail fast if we could not create a TConnection object
    if (clientConnection == NULL) {
      GlobalOutput.printf("thriftServerEventHandler: failed TConnection factory");
      ::THRIFT_CLOSESOCKET(clientSocket);
      return;
    }

    /*
     * Either notify the ioThread that is assigned this connection to
     * start processing, or if it is us, we'll just ask this
     * connection to do its initial state change here.
     *
     * (We need to avoid writing to our own notification pipe, to
     * avoid possible deadlocks if the pipe is full.)
     *
     * The IO thread #0 is the only one that handles these listen
     * events, so unless the connection has been assigned to thread #0
     * we know it's not on our thread.
     */
    if (clientConnection->getIOThreadNumber() == 0) {
      clientConnection->transition();
    } else {
      if (!clientConnection->notifyIOThread()) {
        GlobalOutput.perror("[ERROR] notifyIOThread failed on fresh connection, closing", errno);
        returnConnection(clientConnection);
      }
    }

    // addrLen is written by the accept() call, so needs to be set before the next call.
    addrLen = sizeof(addrStorage);
  }

  // Done looping accept, now we have to make sure the error is due to
  // blocking. Any other error is a problem
  if (THRIFT_GET_SOCKET_ERROR != THRIFT_EAGAIN && THRIFT_GET_SOCKET_ERROR != THRIFT_EWOULDBLOCK) {
    GlobalOutput.perror("thriftServerEventHandler: accept() ", THRIFT_GET_SOCKET_ERROR);
  }
}
Example #20
0
int main(int argc, char **argv)
{
    int i, j = 1024 * 1024 * 1;
    char *buffer = malloc(8 * j + 4);
#ifndef BENCH
    has_t* h = has_hash_new(64);
    has_t* vals = has_new(j);
#else
    has_t* h = has_hash_new(j);
#endif
    double t1, t2;

    t1 = epoch_double();
    for(i = 0; i < j; i++) {
        sprintf(buffer + i * 8, "%08x", i);
#ifndef BENCH
        has_string_init(&(vals[i]), buffer + i * 8, 8, false);
#endif
    }
    t2 = epoch_double();
    printf("Init: %f\n", t2 - t1);
    
    t1 = epoch_double();
    for(i = 0; i < j; i++) {
#ifndef BENCH
        has_hash_set(h, buffer + i * 8, 8, &(vals[i]));
#else
        has_hash_set(h, buffer + i * 8, 8, NULL);
#endif
    }
    t2 = epoch_double();
    printf("Adding: %f\n", t2 - t1);

    t1 = epoch_double();
    for(i = 0; i < j; i++) {
        assert(has_hash_get(h, buffer + i * 8, 8));
    }
    t2 = epoch_double();
    printf("Looking up: %f\n", t2 - t1);

    t1 = epoch_double();
    for(i = 0; i < j; i++) {
        has_hash_remove(h, buffer + i * 8, 8);
    }
    t2 = epoch_double();
    printf("Individual removal: %f\n", t2 - t1);

    t1 = epoch_double();
    for(i = 0; i < j; i++) {
#ifndef BENCH
        has_hash_set(h, buffer + i * 8, 8, &(vals[i]));
#else
        has_hash_set(h, buffer + i * 8, 8, NULL);
#endif
    }
    t2 = epoch_double();
    printf("Adding: %f\n", t2 - t1);

    t1 = epoch_double();
    for(i = 0; i < j; i++) {
#ifndef BENCH
        has_hash_set(h, buffer + i * 8, 8, &(vals[i]));
#else
        has_hash_set(h, buffer + i * 8, 8, NULL);
#endif
    }
    t2 = epoch_double();
    printf("Adding again: %f\n", t2 - t1);

    t1 = epoch_double();
    has_free(h);
    t2 = epoch_double();
    printf("Deleting: %f\n", t2 - t1);

#ifndef BENCH
    free(vals);
#endif
    free(buffer);
    return 0;
}
void _approximateSeededMatch(const std::string& in_query,
                             int min_overlap, 
                             double min_identity,
                             int bandwidth, 
                             int max_interval,
                             bool do_reverse,
                             const BWTIndexSet& indices,
                             SequenceOverlapPairVector& out_vector)
{
    Timer timer("test", true);
    assert(indices.pBWT != NULL);
    assert(indices.pSSA != NULL);
    assert(indices.pCache != NULL);

    static size_t n_calls = 0;
    static size_t n_candidates = 0;
    static size_t n_output = 0;
    static double t_time = 0;

    n_calls++;

    int target_seed_length = 41;
    int seed_stride = target_seed_length / 2;
    size_t d = 1;

    SequenceOverlapPairVector overlap_vector;

    std::string strand_query = do_reverse ? reverseComplement(in_query) : in_query;

    // Initialize seeds 
    int seed_end = strand_query.size();
    int q = indices.pCache->getCachedLength();

    std::queue<ApproxSeed> seeds;

    while(seed_end > target_seed_length)
    {
        // For the last q bases of the seed, create all strings within edit distance d
        std::string qmer = strand_query.substr(seed_end - q, q);
        assert((int)qmer.size() == q);
        // 0-distance seed
        ApproxSeed seed;
        seed.query_index = seed_end - q;
        seed.interval = indices.pCache->lookup(qmer.c_str());
        seed.length = q;
        seeds.push(seed);

        for(int i = 0; i < q; ++i)
        {
            // Switch base to other 3 symbols
            char o = qmer[i];
            for(size_t j = 0; j < 4; ++j)
            {
                char b = "ACGT"[j];
                if(b != o)
                {
                    qmer[i] = b;
                    ApproxSeed seed;
                    seed.query_index = seed_end - q;
                    seed.interval = indices.pCache->lookup(qmer.c_str());
                    seed.length = q;
                    seed.edits.push_back(SeedEdit(i + seed.query_index, b));
                    seeds.push(seed);
                }
            }
            qmer[i] = o;
        }
        seed_end -= seed_stride;
    }
    
    // Extend seeds
    std::vector<ApproxSeed> finished_seeds;
    while(!seeds.empty())
    {
        ApproxSeed& seed = seeds.front();

        // query_index is the index of the last base
        // in the seed. get the next base
        char qb = strand_query[seed.query_index - 1];

        // Branch to inexact match
        if(seed.edits.size() < d)
        {
            for(size_t j = 0; j < 4; ++j)
            {
                char b = "ACGT"[j];
                if(b != qb)
                {
                    ApproxSeed new_seed;
                    new_seed.query_index = seed.query_index - 1;
                    new_seed.interval = seed.interval;
                    BWTAlgorithms::updateInterval(new_seed.interval, b, indices.pBWT);
                    if(new_seed.interval.isValid())
                    {
                        new_seed.length = seed.length + 1;
                        new_seed.edits = seed.edits;
                        new_seed.edits.push_back(SeedEdit(new_seed.query_index, b));

                        if(new_seed.length < target_seed_length && new_seed.query_index > 0)
                            seeds.push(new_seed);
                        else
                            finished_seeds.push_back(new_seed);
                    }
                }
            }
        }
            
        // Extend with the actual query base without branching
        seed.query_index = seed.query_index - 1;
        seed.length += 1;
        BWTAlgorithms::updateInterval(seed.interval, qb, indices.pBWT);
        if(!seed.interval.isValid() || seed.length >= target_seed_length || seed.query_index == 0)
        {
            if(seed.interval.isValid())
                finished_seeds.push_back(seed);
            seeds.pop();
        }
    }
    
    std::set<size_t> rank_set;
    
    for(size_t i = 0; i < finished_seeds.size(); ++i)
    {
        if(finished_seeds[i].interval.size() > max_interval)
            continue;

        //std::cout << finished_seeds[i] << "\n";
        std::string query_seed = strand_query.substr(finished_seeds[i].query_index, target_seed_length);
        std::string match_seed = query_seed;

        // Apply edits to the new sequence
        for(size_t j = 0; j < finished_seeds[i].edits.size(); ++j)
            match_seed[finished_seeds[i].edits[j].index - finished_seeds[i].query_index] = finished_seeds[i].edits[j].base;

        // Flip the seeds to match the strand of the query
        if(do_reverse)
        {
            query_seed = reverseComplement(query_seed);
            match_seed = reverseComplement(match_seed);
        }

        // Extract the prefix of every occurrence of this seed
        RankedPrefixVector extensions = BWTAlgorithms::extractRankedPrefixes(indices.pBWT, finished_seeds[i].interval);

        // Extend the seeds to the full-length string
        for(size_t j = 0; j < extensions.size(); ++j)
        {
            size_t rank = extensions[j].rank;

            // The second element of the returned pair is
            // false if the set already contains this rank
            if(!rank_set.insert(rank).second)
                continue;

            // Extract the reminder of the read
            std::string& prefix = extensions[j].prefix;
            int64_t start_index_of_read = indices.pSSA->lookupLexoRank(rank);
            std::string suffix = BWTAlgorithms::extractUntilInterval(indices.pBWT, 
                                                                     start_index_of_read, 
                                                                     finished_seeds[i].interval);

            std::string match_sequence = prefix + suffix;

            // Ignore identical matches
            if(match_sequence == strand_query)
                continue;

            // Change strands
            if(do_reverse)
                match_sequence = reverseComplement(match_sequence);

            // Compute the overlap
            SequenceOverlap overlap;
            size_t pos_0 = in_query.find(query_seed);
            size_t pos_1 = match_sequence.find(match_seed);
            assert(pos_0 != std::string::npos);
            assert(pos_1 != std::string::npos);

            if(in_query.find(query_seed, pos_0 + 1) != std::string::npos || 
               match_sequence.find(match_seed, pos_1 + 1) != std::string::npos) {
                // One of the reads has a second occurrence of the kmer. Use
                // the slow overlapper.
                overlap = Overlapper::computeOverlap(in_query, match_sequence);
            } else {
                overlap = Overlapper::extendMatch(in_query, match_sequence, pos_0, pos_1, bandwidth);
            }

            n_candidates += 1;
            bool bPassedOverlap = overlap.getOverlapLength() >= min_overlap;
            bool bPassedIdentity = overlap.getPercentIdentity() / 100 >= min_identity;

            if(bPassedOverlap && bPassedIdentity)
            {
                //printf("Rank\t%zu\t%zu\t%s\t%.2lf\t%d\n", n_calls,
                //    rank, match_sequence.c_str(), overlap.getPercentIdentity(), overlap.getOverlapLength());
                
                SequenceOverlapPair op;
                op.sequence[0] = in_query;
                op.sequence[1] = match_sequence;
                op.overlap = overlap;
                op.is_reversed = do_reverse;
                out_vector.push_back(op);
                n_output += 1;
            }                
        }
    }
    t_time += timer.getElapsedCPUTime();
    
    if(Verbosity::Instance().getPrintLevel() > 6 && n_calls % 100 == 0)
        printf("[approx seeds] n: %zu candidates: %zu valid: %zu (%.2lf) time: %.2lfs\n", 
            n_calls, n_candidates, n_output, (double)n_output / n_candidates, t_time);
}
 //-----------------------------------------------------------------------
 std::string getAccountAddressAsStr(uint64_t prefix, const AccountPublicAddress& adr) {
   BinaryArray ba;
   bool r = toBinaryArray(adr, ba);
   assert(r);
   return Tools::Base58::encode_addr(prefix, Common::asString(ba));
 }
Example #23
0
token_t akl_lex(struct akl_io_device *dev)
{
    int ch;
    /* We should take care of the '+', '++',
      and etc. style functions. Moreover the
      positive and negative numbers must also work:
      '(++ +5)' should be valid. */
    char op = 0;
    if (!buffer)
        init_buffer();

    assert(dev);
    while ((ch = akl_io_getc(dev))) {
        /* We should avoid the interpretation of the Unix shebang */
        if (dev->iod_char_count == 1 && ch == '#') {
            while ((ch = akl_io_getc(dev)) && ch != '\n') 
                ;
        }
        if (ch == EOF) {
           return tEOF;
        } else if (ch == '\n') {
           dev->iod_line_count++;
           dev->iod_char_count = 0;
        } else if (ch == '+' || ch == '-') {
            if (op != 0) {
                if (op == '+')
                    strcpy(buffer, "++");
                else
                    strcpy(buffer, "--");
                op = 0;
                return tATOM;
            }
            op = ch;
        } else if (isdigit(ch)) {
            akl_io_ungetc(ch, dev);
            copy_number(dev, op);
            op = 0;
            return tNUMBER;
        } else if (ch == ' ' || ch == '\n') {
            dev->iod_column = dev->iod_char_count+1;
            if (op != 0) {
                if (op == '+')
                    strcpy(buffer, "+");
                else
                    strcpy(buffer, "-");
                op = 0;
                return tATOM;
            } else {
                continue;
            }
        } else if (ch == '"') {
            ch = akl_io_getc(dev);
            if (ch == '"')
                return tNIL;
            akl_io_ungetc(ch, dev);
            copy_string(dev); 
            return tSTRING;
        } else if (ch == '(') {
            dev->iod_column = dev->iod_char_count+1;
            ch = akl_io_getc(dev);
            if (ch == ')')
                return tNIL;
            akl_io_ungetc(ch, dev);
            return tLBRACE;
        } else if (ch == ')') {
            return tRBRACE;
        } else if (ch == '\'' || ch == ':') {
            return tQUOTE;
        } else if (ch == ';') {
            while ((ch = akl_io_getc(dev)) != '\n') {
                if (akl_io_eof(dev))
                    return tEOF;
            }
        } else if (isalpha(ch) || ispunct(ch)) {
            akl_io_ungetc(ch, dev);
            copy_atom(dev);
            if ((strcasecmp(buffer, "NIL")) == 0)
                return tNIL;
            else if ((strcasecmp(buffer, "T")) == 0)
                return tTRUE;
            else
                return tATOM;
        } else {
            continue;
        }
    }
    return tEOF;
}
int main(int argc, char*argv[])
{
    // options
    unsigned int num_channels=6;    // number of channels (must be even)
    unsigned int m=4;               // filter delay
    unsigned int num_symbols=4*m;   // number of symbols

    // validate input
    if (num_channels%2) {
        fprintf(stderr,"error: %s, number of channels must be even\n", argv[0]);
        exit(1);
    }

    // derived values
    unsigned int num_samples = num_channels * num_symbols;

    unsigned int i;
    unsigned int j;

    // generate filter
    // NOTE : these coefficients can be random; the purpose of this
    //        exercise is to demonstrate mathematical equivalence
#if 0
    unsigned int h_len = 2*m*num_channels;
    float h[h_len];
    for (i=0; i<h_len; i++) h[i] = randnf();
#else
    unsigned int h_len = 2*m*num_channels+1;
    float h[h_len];
    // NOTE: 81.29528 dB > beta = 8.00000 (6 channels, m=4)
    liquid_firdes_kaiser(h_len, 1.0f/(float)num_channels, 81.29528f, 0.0f, h);
#endif
    // normalize
    float hsum = 0.0f;
    for (i=0; i<h_len; i++) hsum += h[i];
    for (i=0; i<h_len; i++) h[i] = h[i] * num_channels / hsum;

    // sub-sampled filters for M=6 channels, m=4, beta=8.0
    //  -3.2069e-19  -6.7542e-04  -1.3201e-03   2.2878e-18   3.7613e-03   5.8033e-03
    //  -7.2899e-18  -1.2305e-02  -1.7147e-02   1.6510e-17   3.1187e-02   4.0974e-02
    //  -3.0032e-17  -6.8026e-02  -8.6399e-02   4.6273e-17   1.3732e-01   1.7307e-01
    //  -6.2097e-17  -2.8265e-01  -3.7403e-01   7.3699e-17   8.0663e-01   1.6438e+00
    //   2.0001e+00   1.6438e+00   8.0663e-01   7.3699e-17  -3.7403e-01  -2.8265e-01
    //  -6.2097e-17   1.7307e-01   1.3732e-01   4.6273e-17  -8.6399e-02  -6.8026e-02
    //  -3.0032e-17   4.0974e-02   3.1187e-02   1.6510e-17  -1.7147e-02  -1.2305e-02
    //  -7.2899e-18   5.8033e-03   3.7613e-03   2.2878e-18  -1.3201e-03  -6.7542e-04

    // create filterbank manually
    dotprod_crcf dp[num_channels];  // vector dot products
    windowcf w[num_channels];       // window buffers

#if DEBUG
    // print coefficients
    printf("h_prototype:\n");
    for (i=0; i<h_len; i++)
        printf("  h[%3u] = %12.8f\n", i, h[i]);
#endif

    // create objects
    unsigned int h_sub_len = 2*m;
    float h_sub[h_sub_len];
    for (i=0; i<num_channels; i++) {
        // sub-sample prototype filter
#if 0
        for (j=0; j<h_sub_len; j++)
            h_sub[j] = h[j*num_channels+i];
#else
        // load coefficients in reverse order
        for (j=0; j<h_sub_len; j++)
            h_sub[h_sub_len-j-1] = h[j*num_channels+i];
#endif

        // create window buffer and dotprod objects
        dp[i] = dotprod_crcf_create(h_sub, h_sub_len);
        w[i]  = windowcf_create(h_sub_len);

#if DEBUG
        printf("h_sub[%u] : \n", i);
        for (j=0; j<h_sub_len; j++)
            printf("  h[%3u] = %12.8f\n", j, h_sub[j]);
#endif
    }

    // generate DFT object
    float complex x[num_channels];  // time-domain buffer
    float complex X[num_channels];  // freq-domain buffer
#if 1
    fftplan fft = fft_create_plan(num_channels, X, x, LIQUID_FFT_BACKWARD, 0);
#else
    fftplan fft = fft_create_plan(num_channels, X, x, LIQUID_FFT_FORWARD, 0);
#endif

    float complex y[num_samples];                   // time-domain input
    float complex Y0[2*num_symbols][num_channels];  // channelizer output
    float complex Y1[2*num_symbols][num_channels];  // conventional output

    // generate input sequence
    for (i=0; i<num_samples; i++) {
        //y[i] = randnf() * cexpf(_Complex_I*randf()*2*M_PI);
        y[i] = (i==0) ? 1.0f : 0.0f;
        y[i] = cexpf(_Complex_I*sqrtf(2.0f)*i*i);
        printf("y[%3u] = %12.8f + %12.8fj\n", i, crealf(y[i]), cimagf(y[i]));
    }

    // 
    // run analysis filter bank
    //
#if 0
    unsigned int filter_index = 0;
#else
    unsigned int filter_index = num_channels/2-1;
#endif
    float complex y_hat;    // input sample
    float complex * r;      // buffer read pointer
    int toggle = 0;         // flag indicating buffer/filter alignment

    //
    for (i=0; i<2*num_symbols; i++) {

        // load buffers in blocks of num_channels/2
        for (j=0; j<num_channels/2; j++) {
            // grab sample
            y_hat = y[i*num_channels/2 + j];

            // push sample into buffer at filter index
            windowcf_push(w[filter_index], y_hat);

            // decrement filter index
            filter_index = (filter_index + num_channels - 1) % num_channels;
            //filter_index = (filter_index + 1) % num_channels;
        }

        // execute filter outputs
        // reversing order of output (not sure why this is necessary)
        unsigned int offset = toggle ? num_channels/2 : 0;
        toggle = 1-toggle;
        for (j=0; j<num_channels; j++) {
            unsigned int buffer_index  = (offset+j)%num_channels;
            unsigned int dotprod_index = j;

            windowcf_read(w[buffer_index], &r);
            //dotprod_crcf_execute(dp[dotprod_index], r, &X[num_channels-j-1]);
            dotprod_crcf_execute(dp[dotprod_index], r, &X[buffer_index]);
        }

        printf("***** i = %u\n", i);
        for (j=0; j<num_channels; j++)
            printf("  v2[%4u] = %12.8f + %12.8fj\n", j, crealf(X[j]), cimagf(X[j]));
        // execute DFT, store result in buffer 'x'
        fft_execute(fft);
        // scale fft output
        for (j=0; j<num_channels; j++)
            x[j] *= 1.0f / (num_channels);

        // move to output array
        for (j=0; j<num_channels; j++)
            Y0[i][j] = x[j];
    }
    // destroy objects
    for (i=0; i<num_channels; i++) {
        dotprod_crcf_destroy(dp[i]);
        windowcf_destroy(w[i]);
    }
    fft_destroy_plan(fft);


    // 
    // run traditional down-converter (inefficient)
    //
    // generate filter object
    firfilt_crcf f = firfilt_crcf_create(h, h_len);

    float dphi; // carrier frequency
    unsigned int n=0;
    for (i=0; i<num_channels; i++) {

        // reset filter
        firfilt_crcf_clear(f);

        // set center frequency
        dphi = 2.0f * M_PI * (float)i / (float)num_channels;

        // reset symbol counter
        n=0;

        for (j=0; j<num_samples; j++) {
            // push down-converted sample into filter
            firfilt_crcf_push(f, y[j]*cexpf(-_Complex_I*j*dphi));

            // compute output at the appropriate sample time
            assert(n<2*num_symbols);
            if ( ((j+1)%(num_channels/2))==0 ) {
                firfilt_crcf_execute(f, &Y1[n][i]);
                n++;
            }
        }
        assert(n==2*num_symbols);

    }
    firfilt_crcf_destroy(f);

    // print filterbank channelizer
    printf("\n");
    printf("filterbank channelizer:\n");
    for (i=0; i<2*num_symbols; i++) {
        printf("%2u:", i);
        for (j=0; j<num_channels; j++) {
            printf("%6.3f+%6.3fj, ", crealf(Y0[i][j]), cimagf(Y0[i][j]));
        }
        printf("\n");
    }

#if 0
    // print traditional channelizer
    printf("\n");
    printf("traditional channelizer:\n");
    for (i=0; i<2*num_symbols; i++) {
        printf("%2u:", i);
        for (j=0; j<num_channels; j++) {
            printf("%6.3f+%6.3fj, ", crealf(Y1[i][j]), cimagf(Y1[i][j]));
        }
        printf("\n");
    }

    // 
    // compare results
    // 
    float mse[num_channels];
    float complex d;
    for (i=0; i<num_channels; i++) {
        mse[i] = 0.0f;
        for (j=0; j<2*num_symbols; j++) {
            d = Y0[j][i] - Y1[j][i];
            mse[i] += crealf(d*conjf(d));
        }

        mse[i] /= num_symbols;
    }
    printf("\n");
    printf(" e:");
    for (i=0; i<num_channels; i++)
        printf("%12.4e    ", sqrt(mse[i]));
    printf("\n");
#endif

    printf("done.\n");
    return 0;

}
Example #25
0
int CSock::RecvFrom(char* buf,size_t cnt,CSockAddr* pRemoteaddr)
{
	assert(IsCreate());
	assert(pRemoteaddr);   
	return ::recvfrom(_s,buf,cnt,0,(sockaddr*)pRemoteaddr,(pRemoteaddr ? &pRemoteaddr->addlen : NULL));
}
Example #26
0
bool persist_file_context::clear_var(const std::string &global, bool immediate)
{
	config bak;
	config bactive;
	if (immediate) {
		bak = cfg_;
		config *node = get_node(bak, namespace_);
		if (node)
			bactive = node->child_or_add("variables");
		load();
	}
	config *active = get_node(cfg_, namespace_);
	if (active == NULL)
		return false;

	bool ret = active->has_child("variables");
	if (ret) {
		config &cfg = active->child("variables");
		bool exists = cfg.has_attribute(global);
		if (!exists) {
			if (cfg.has_child(global)) {
				exists = true;
				std::string::const_iterator index_start = std::find(global.begin(),global.end(),'[');
				if (index_start != global.end())
				{
					const std::string::const_iterator index_end = std::find(global.begin(),global.end(),']');
					const std::string index_str(index_start+1,index_end);
					size_t index = static_cast<size_t>(lexical_cast_default<int>(index_str));
					cfg.remove_child(global,index);
					if (immediate) bactive.remove_child(global,index);
				} else {
					cfg.clear_children(global);
					if (immediate) bactive.clear_children(global);
				}
			}
		}
		if (exists) {
			cfg.remove_attribute(global);
			if (immediate) bactive.remove_attribute(global);
			if (cfg.empty()) {
				active->clear_children("variables");
				active->remove_attribute("variables");
				name_space working = namespace_;
				while ((active->empty()) && (!working.lineage_.empty())) {
					name_space prev = working.prev();
					active = get_node(cfg_, prev);
					active->clear_children(working.node_);
					if (active->has_child("variables") && active->child("variables").empty()) {
						active->clear_children("variables");
						active->remove_attribute("variables");
					}
					working = prev;
				}
			}

			if (!in_transaction_)
				ret = save_context();
			else if (immediate) {
				ret = save_context();
				cfg_ = bak;
				active = get_node(cfg_, namespace_);
				if (active != NULL) {
					active->clear_children("variables");
					active->remove_attribute("variables");
					if (!bactive.empty())
						active->add_child("variables",bactive);
				}
			} else {
				ret = true;
			}
		} else {
			if (immediate) {
				cfg_ = bak;
				config *active = get_node(cfg_, namespace_);
				if (active != NULL) {
					active->clear_children("variables");
					active->remove_attribute("variables");
					if (!bactive.empty())
						active->add_child("variables",bactive);
				}
			}
			ret = exists;
		}
	}

	// TODO: figure out when this is the case and adjust the next loop
	//       condition accordingly. -- shadowm
	assert(active);

	while (active && active->empty() && !namespace_.lineage_.empty()) {
		name_space prev = namespace_.prev();
		active = get_node(cfg_, prev);
		if (active == NULL) {
			break;
		}
		active->clear_children(namespace_.node_);
		if (active->has_child("variables") && active->child("variables").empty()) {
			active->clear_children("variables");
			active->remove_attribute("variables");
		}
		namespace_ = prev;
	}
	return ret;
}
/**
 * Allocates a shared memory segment.
 *
 * @param  n  Size (in bytes) of chunk to allocate.
 * @return Id of shared memory chunk.
 */
int AllocateSharedMemory(int n)
{
    assert(n > 0); // Idiot-proof the call.
    return shmget(IPC_PRIVATE, n, IPC_CREAT | SHM_R | SHM_W);
}
Example #28
0
void cvComputeRQDecomposition(CvMat *matrixM, CvMat *matrixR, CvMat *matrixQ, CvMat *matrixQx, CvMat *matrixQy, CvMat *matrixQz, CvPoint3D64f *eulerAngles)
{
	
	CvMat *tmpMatrix1 = 0;
	CvMat *tmpMatrix2 = 0;
	CvMat *tmpMatrixM = 0;
	CvMat *tmpMatrixR = 0;
	CvMat *tmpMatrixQ = 0;
	CvMat *tmpMatrixQx = 0;
	CvMat *tmpMatrixQy = 0;
	CvMat *tmpMatrixQz = 0;
	double tmpEulerAngleX, tmpEulerAngleY, tmpEulerAngleZ;
	
	CV_FUNCNAME("cvRQDecomp3x3");
    __CV_BEGIN__;
	
	/* Validate parameters. */
	if(matrixM == 0 || matrixR == 0 || matrixQ == 0)
		CV_ERROR(CV_StsNullPtr, "Some of parameters is a NULL pointer!");
	
	if(!CV_IS_MAT(matrixM) || !CV_IS_MAT(matrixR) || !CV_IS_MAT(matrixQ))
		CV_ERROR(CV_StsUnsupportedFormat, "Input parameters must be a matrices!");
	
	if(matrixM->cols != 3 || matrixM->rows != 3 || matrixR->cols != 3 || matrixR->rows != 3 || matrixQ->cols != 3 || matrixQ->rows != 3)
		CV_ERROR(CV_StsUnmatchedSizes, "Size of matrices must be 3x3!");
	
	CV_CALL(tmpMatrix1 = cvCreateMat(3, 3, CV_64F));
	CV_CALL(tmpMatrix2 = cvCreateMat(3, 3, CV_64F));
	CV_CALL(tmpMatrixM = cvCreateMat(3, 3, CV_64F));
	CV_CALL(tmpMatrixR = cvCreateMat(3, 3, CV_64F));
	CV_CALL(tmpMatrixQ = cvCreateMat(3, 3, CV_64F));
	CV_CALL(tmpMatrixQx = cvCreateMat(3, 3, CV_64F));
	CV_CALL(tmpMatrixQy = cvCreateMat(3, 3, CV_64F));
	CV_CALL(tmpMatrixQz = cvCreateMat(3, 3, CV_64F));
	
	cvCopy(matrixM, tmpMatrixM);
	
	/* Find Givens rotation Q_x for x axis. */
	/*
	      ( 1  0  0 )
	 Qx = ( 0  c -s ), cos = -m33/sqrt(m32^2 + m33^2), cos = m32/sqrt(m32^2 + m33^2)
		  ( 0  s  c )
	 */
	
	double x, y, z, c, s;
	x = cvmGet(tmpMatrixM, 2, 1);
	y = cvmGet(tmpMatrixM, 2, 2);
	z = x * x + y * y;
	assert(z != 0); // Prevent division by zero.
	c = -y / sqrt(z);
	s = x / sqrt(z);
	
	cvSetIdentity(tmpMatrixQx);
	cvmSet(tmpMatrixQx, 1, 1, c);
	cvmSet(tmpMatrixQx, 1, 2, -s);
	cvmSet(tmpMatrixQx, 2, 1, s);
	cvmSet(tmpMatrixQx, 2, 2, c);
	
	tmpEulerAngleX = acos(c) * 180.0 / CV_PI;
	
	/* Multiply M on the right by Q_x. */
	
	cvMatMul(tmpMatrixM, tmpMatrixQx, tmpMatrixR);
	cvCopy(tmpMatrixR, tmpMatrixM);
	
	assert(cvmGet(tmpMatrixM, 2, 1) < CV_VERYSMALLDOUBLE && cvmGet(tmpMatrixM, 2, 1) > -CV_VERYSMALLDOUBLE); // Should actually be zero.
	
	if(cvmGet(tmpMatrixM, 2, 1) != 0.0)
		cvmSet(tmpMatrixM, 2, 1, 0.0); // Rectify arithmetic precision error.
	
	/* Find Givens rotation for y axis. */
	/*
	      ( c  0  s )
	 Qy = ( 0  1  0 ), cos = m33/sqrt(m31^2 + m33^2), cos = m31/sqrt(m31^2 + m33^2)
	      (-s  0  c )
	 */
	
	x = cvmGet(tmpMatrixM, 2, 0);
	y = cvmGet(tmpMatrixM, 2, 2);
	z = x * x + y * y;
	assert(z != 0); // Prevent division by zero.
	c = y / sqrt(z);
	s = x / sqrt(z);
	
	cvSetIdentity(tmpMatrixQy);
	cvmSet(tmpMatrixQy, 0, 0, c);
	cvmSet(tmpMatrixQy, 0, 2, s);
	cvmSet(tmpMatrixQy, 2, 0, -s);
	cvmSet(tmpMatrixQy, 2, 2, c);
	
	tmpEulerAngleY = acos(c) * 180.0 / CV_PI;
	
	/* Multiply M*Q_x on the right by Q_y. */
	
	cvMatMul(tmpMatrixM, tmpMatrixQy, tmpMatrixR);
	cvCopy(tmpMatrixR, tmpMatrixM);
	
	assert(cvmGet(tmpMatrixM, 2, 0) < CV_VERYSMALLDOUBLE && cvmGet(tmpMatrixM, 2, 0) > -CV_VERYSMALLDOUBLE); // Should actually be zero.
	
	if(cvmGet(tmpMatrixM, 2, 0) != 0.0)
		cvmSet(tmpMatrixM, 2, 0, 0.0); // Rectify arithmetic precision error.
	
	/* Find Givens rotation for z axis. */
	/*
	      ( c -s  0 )
	 Qz = ( s  c  0 ), cos = -m22/sqrt(m21^2 + m22^2), cos = m21/sqrt(m21^2 + m22^2)
	      ( 0  0  1 )
	 */
	
	x = cvmGet(tmpMatrixM, 1, 0);
	y = cvmGet(tmpMatrixM, 1, 1);
	z = x * x + y * y;
	assert(z != 0); // Prevent division by zero.
	c = -y / sqrt(z);
	s = x / sqrt(z);
	
	cvSetIdentity(tmpMatrixQz);
	cvmSet(tmpMatrixQz, 0, 0, c);
	cvmSet(tmpMatrixQz, 0, 1, -s);
	cvmSet(tmpMatrixQz, 1, 0, s);
	cvmSet(tmpMatrixQz, 1, 1, c);
	
	tmpEulerAngleZ = acos(c) * 180.0 / CV_PI;
	
	/* Multiply M*Q_x*Q_y on the right by Q_z. */
	
	cvMatMul(tmpMatrixM, tmpMatrixQz, tmpMatrixR);
	
	assert(cvmGet(tmpMatrixR, 1, 0) < CV_VERYSMALLDOUBLE && cvmGet(tmpMatrixR, 1, 0) > -CV_VERYSMALLDOUBLE); // Should actually be zero.
	
	if(cvmGet(tmpMatrixR, 1, 0) != 0.0)
		cvmSet(tmpMatrixR, 1, 0, 0.0); // Rectify arithmetic precision error.
	
	/* Calulate orthogonal matrix. */
	/*
	 Q = QzT * QyT * QxT
	 */
	
	cvTranspose(tmpMatrixQz, tmpMatrix1);
	cvTranspose(tmpMatrixQy, tmpMatrix2);
	cvMatMul(tmpMatrix1, tmpMatrix2, tmpMatrixQ);
	cvCopy(tmpMatrixQ, tmpMatrix1);
	cvTranspose(tmpMatrixQx, tmpMatrix2);
	cvMatMul(tmpMatrix1, tmpMatrix2, tmpMatrixQ);
	
	/* Solve decomposition ambiguity. */
	/*
	 Diagonal entries of R should be positive, so swap signs if necessary.
	 */
	
	if(cvmGet(tmpMatrixR, 0, 0) < 0.0) {
		cvmSet(tmpMatrixR, 0, 0, -1.0 * cvmGet(tmpMatrixR, 0, 0));
		cvmSet(tmpMatrixQ, 0, 0, -1.0 * cvmGet(tmpMatrixQ, 0, 0));
		cvmSet(tmpMatrixQ, 0, 1, -1.0 * cvmGet(tmpMatrixQ, 0, 1));
		cvmSet(tmpMatrixQ, 0, 2, -1.0 * cvmGet(tmpMatrixQ, 0, 2));
	}
	if(cvmGet(tmpMatrixR, 1, 1) < 0.0) {
		cvmSet(tmpMatrixR, 0, 1, -1.0 * cvmGet(tmpMatrixR, 0, 1));
		cvmSet(tmpMatrixR, 1, 1, -1.0 * cvmGet(tmpMatrixR, 1, 1));
		cvmSet(tmpMatrixQ, 1, 0, -1.0 * cvmGet(tmpMatrixQ, 1, 0));
		cvmSet(tmpMatrixQ, 1, 1, -1.0 * cvmGet(tmpMatrixQ, 1, 1));
		cvmSet(tmpMatrixQ, 1, 2, -1.0 * cvmGet(tmpMatrixQ, 1, 2));
	}

	/* Enforce det(Q) = 1 */ 
	if (cvDet(tmpMatrixQ) < 0) 
	{
		for (int i = 0; i < 3; i++) 
		{
			for (int j = 0; j < 3; j++) 
			{
				cvmSet(tmpMatrixQ, j, i, -cvmGet(tmpMatrixQ, j, i)); 
			}
		}
	}
	
	/* Save R and Q matrices. */
	
	cvCopy(tmpMatrixR, matrixR);
	cvCopy(tmpMatrixQ, matrixQ);
	
	if(matrixQx && CV_IS_MAT(matrixQx) && matrixQx->cols == 3 || matrixQx->rows == 3)
		cvCopy(tmpMatrixQx, matrixQx);
	if(matrixQy && CV_IS_MAT(matrixQy) && matrixQy->cols == 3 || matrixQy->rows == 3)
		cvCopy(tmpMatrixQy, matrixQy);
	if(matrixQz && CV_IS_MAT(matrixQz) && matrixQz->cols == 3 || matrixQz->rows == 3)
		cvCopy(tmpMatrixQz, matrixQz);
	
	/* Save Euler angles. */
	
	if(eulerAngles)
		*eulerAngles = cvPoint3D64f(tmpEulerAngleX, tmpEulerAngleY, tmpEulerAngleZ);
	
	__CV_END__;
	
	cvReleaseMat(&tmpMatrix1);
	cvReleaseMat(&tmpMatrix2);
	cvReleaseMat(&tmpMatrixM);
	cvReleaseMat(&tmpMatrixR);
	cvReleaseMat(&tmpMatrixQ);
	cvReleaseMat(&tmpMatrixQx);
	cvReleaseMat(&tmpMatrixQy);
	cvReleaseMat(&tmpMatrixQz);

}
Example #29
0
// create OFDM flexible framing generator object
//  _M          :   number of subcarriers, >10 typical
//  _cp_len     :   cyclic prefix length
//  _taper_len  :   taper length (OFDM symbol overlap)
//  _p          :   subcarrier allocation (null, pilot, data), [size: _M x 1]
//  _fgprops    :   frame properties (modulation scheme, etc.)
ofdmflexframegen ofdmflexframegen_create(unsigned int              _M,
                                         unsigned int              _cp_len,
                                         unsigned int              _taper_len,
                                         unsigned char *           _p,
                                         ofdmflexframegenprops_s * _fgprops)
{
    // validate input
    if (_M < 2) {
        fprintf(stderr,"error: ofdmflexframegen_create(), number of subcarriers must be at least 2\n");
        exit(1);
    } else if (_M % 2) {
        fprintf(stderr,"error: ofdmflexframegen_create(), number of subcarriers must be even\n");
        exit(1);
    }

    ofdmflexframegen q = (ofdmflexframegen) malloc(sizeof(struct ofdmflexframegen_s));
    q->M         = _M;          // number of subcarriers
    q->cp_len    = _cp_len;     // cyclic prefix length
    q->taper_len = _taper_len;  // taper length

    // allocate memory for transform buffers
    q->X = (float complex*) malloc((q->M)*sizeof(float complex));

    // allocate memory for subcarrier allocation IDs
    q->p = (unsigned char*) malloc((q->M)*sizeof(unsigned char));
    if (_p == NULL) {
        // initialize default subcarrier allocation
        ofdmframe_init_default_sctype(q->M, q->p);
    } else {
        // copy user-defined subcarrier allocation
        memmove(q->p, _p, q->M*sizeof(unsigned char));
    }

    // validate and count subcarrier allocation
    ofdmframe_validate_sctype(q->p, q->M, &q->M_null, &q->M_pilot, &q->M_data);

    // create internal OFDM frame generator object
    q->fg = ofdmframegen_create(q->M, q->cp_len, q->taper_len, q->p);

    // create header objects
    q->mod_header = modem_create(OFDMFLEXFRAME_H_MOD);
    q->p_header   = packetizer_create(OFDMFLEXFRAME_H_DEC,
                                      OFDMFLEXFRAME_H_CRC,
                                      OFDMFLEXFRAME_H_FEC,
                                      LIQUID_FEC_NONE);
    assert(packetizer_get_enc_msg_len(q->p_header)==OFDMFLEXFRAME_H_ENC);

    // compute number of header symbols
    div_t d = div(OFDMFLEXFRAME_H_SYM, q->M_data);
    q->num_symbols_header = d.quot + (d.rem ? 1 : 0);

    // initial memory allocation for payload
    q->payload_dec_len = 1;
    q->p_payload = packetizer_create(q->payload_dec_len,
                                     LIQUID_CRC_NONE,
                                     LIQUID_FEC_NONE,
                                     LIQUID_FEC_NONE);
    q->payload_enc_len = packetizer_get_enc_msg_len(q->p_payload);
    q->payload_enc = (unsigned char*) malloc(q->payload_enc_len*sizeof(unsigned char));

    q->payload_mod_len = 1;
    q->payload_mod = (unsigned char*) malloc(q->payload_mod_len*sizeof(unsigned char));

    // create payload modem (initially QPSK, overridden by properties)
    q->mod_payload = modem_create(LIQUID_MODEM_QPSK);

    // initialize properties
    ofdmflexframegen_setprops(q, _fgprops);

    // reset
    ofdmflexframegen_reset(q);

    // return pointer to main object
    return q;
}
Example #30
0
ccDBRoot::ccDBRoot(ccCustomQTreeView* dbTreeWidget, QTreeView* propertiesTreeWidget, QObject* parent) : QAbstractItemModel(parent)
{
    m_treeRoot = new ccHObject("DB Tree");

    //DB Tree
    assert(dbTreeWidget);
    m_dbTreeWidget = dbTreeWidget;
    m_dbTreeWidget->setModel(this);
    m_dbTreeWidget->header()->hide();

	//drag & drop support
	m_dbTreeWidget->setDragEnabled(true);
	m_dbTreeWidget->setAcceptDrops(true);
	//m_dbTreeWidget->viewport()->setAcceptDrops(true);
	m_dbTreeWidget->setDropIndicatorShown(true);
	m_dbTreeWidget->setDragDropMode(QAbstractItemView::InternalMove);
	setSupportedDragActions(Qt::MoveAction);
    /*//already done in ui file!
    m_dbTreeWidget->setEditTriggers(QAbstractItemView::EditKeyPressed);
    m_dbTreeWidget->setDragDropMode(QAbstractItemView::InternalMove);
    m_dbTreeWidget->setSelectionMode(QAbstractItemView::ExtendedSelection);
    m_dbTreeWidget->setUniformRowHeights(true);
    //*/

	//context menu on DB tree elements
	m_dbTreeWidget->setContextMenuPolicy(Qt::CustomContextMenu);
	m_expandBranch = new QAction("Expand branch",this);
	m_collapseBranch = new QAction("Collapse branch",this);
	m_sortSiblingsType = new QAction("Sort siblings by type",this);
	m_sortSiblingsAZ = new QAction("Sort siblings by name (A-Z)",this);
	m_sortSiblingsZA = new QAction("Sort siblings by name (Z-A)",this);
	m_deleteSelectedEntities = new QAction("Delete",this);
	m_toggleSelectedEntities = new QAction("Toggle",this);
	m_toggleSelectedEntitiesVisibility = new QAction("Toggle visibility",this);
	m_toggleSelectedEntitiesColor = new QAction("Toggle color",this);
	m_toggleSelectedEntitiesNormals = new QAction("Toggle normals",this);
	m_toggleSelectedEntitiesSF = new QAction("Toggle SF",this);
	m_addEmptyGroup = new QAction("Add empty group",this);

	m_contextMenuPos = QPoint(-1,-1);

	//connect custom context menu actions
	connect(m_dbTreeWidget,						SIGNAL(customContextMenuRequested(const QPoint&)),	this, SLOT(showContextMenu(const QPoint&)));
	connect(m_expandBranch,						SIGNAL(triggered()),								this, SLOT(expandBranch()));
	connect(m_collapseBranch,					SIGNAL(triggered()),								this, SLOT(collapseBranch()));
	connect(m_sortSiblingsAZ,					SIGNAL(triggered()),								this, SLOT(sortSiblingsAZ()));
	connect(m_sortSiblingsZA,					SIGNAL(triggered()),								this, SLOT(sortSiblingsZA()));
	connect(m_sortSiblingsType,					SIGNAL(triggered()),								this, SLOT(sortSiblingsType()));
	connect(m_deleteSelectedEntities,			SIGNAL(triggered()),								this, SLOT(deleteSelectedEntities()));
	connect(m_toggleSelectedEntities,			SIGNAL(triggered()),								this, SLOT(toggleSelectedEntities()));
	connect(m_toggleSelectedEntitiesVisibility,	SIGNAL(triggered()),								this, SLOT(toggleSelectedEntitiesVisibility()));
	connect(m_toggleSelectedEntitiesColor,		SIGNAL(triggered()),								this, SLOT(toggleSelectedEntitiesColor()));
	connect(m_toggleSelectedEntitiesNormals,	SIGNAL(triggered()),								this, SLOT(toggleSelectedEntitiesNormals()));
	connect(m_toggleSelectedEntitiesSF,			SIGNAL(triggered()),								this, SLOT(toggleSelectedEntitiesSF()));
	connect(m_addEmptyGroup,					SIGNAL(triggered()),								this, SLOT(addEmptyGroup()));
	

    //other DB tree signals/slots connection
    connect(m_dbTreeWidget->selectionModel(), SIGNAL(selectionChanged(const QItemSelection&, const QItemSelection&)), this, SLOT(changeSelection(const QItemSelection&, const QItemSelection&)));

    //Properties Tree
    assert(propertiesTreeWidget);
    m_propertiesTreeWidget = propertiesTreeWidget;
    m_propertiesModel = new QStandardItemModel(0, 2, parent);
    /*//already done in ui file!
    m_propertiesTreeWidget->header()->hide();
    m_propertiesTreeWidget->setSelectionMode(QAbstractItemView::NoSelection);
    m_propertiesTreeWidget->setAllColumnsShowFocus(true);
    //*/
    m_ccPropDelegate = new ccPropertiesTreeDelegate(m_propertiesModel, m_propertiesTreeWidget);
    m_propertiesTreeWidget->setItemDelegate(m_ccPropDelegate);
    m_propertiesTreeWidget->setModel(m_propertiesModel);
    m_propertiesTreeWidget->setEnabled(false);

    //Properties tree signals/slots connection
    connect(m_ccPropDelegate, SIGNAL(ccObjectPropertiesChanged(ccHObject*)), this, SLOT(updateCCObject(ccHObject*)));
    connect(m_ccPropDelegate, SIGNAL(ccObjectAppearanceChanged(ccHObject*)), this, SLOT(redrawCCObject(ccHObject*)));
    connect(m_ccPropDelegate, SIGNAL(ccObjectAndChildrenAppearanceChanged(ccHObject*)), this, SLOT(redrawCCObjectAndChildren(ccHObject*)));
}