Exemple #1
0
/*
 * Command line options
 */
void handle_opts(int argc, char* argv[], Command_line_opts *opts, Detector_settings *sett) {

  opts->hemi=0;
  opts->wd=NULL;
  opts->trl=20;
  // The default option for FFT interpolation is zero-padding
  opts->fftinterp=FFT;

  strcpy (opts->prefix, TOSTR(PREFIX));
  strcpy (opts->dtaprefix, TOSTR(DTAPREFIX));
  opts->label[0] = '\0';
  opts->range[0] = '\0';

  // Initial value of starting frequency
  // set to a negative quantity. If this is not
  // changed by the command line value
  // fpo is calculated from the band number b.
  sett->fpo = -1;

  // Default choice of the detector is Virgo:
  strcpy(opts->ifo_choice, "V1");



  opts->help_flag=0;
  opts->white_flag=0;
  opts->s0_flag=0;
  opts->checkp_flag=0;

  /*
    ############ Reading arguments ################
  */
  static int help_flag=0, white_flag=0, s0_flag=0, checkp_flag=1;


  while (1) {
    static struct option long_options[] = {
      {"help", no_argument, 			&help_flag, 1},
      {"whitenoise", no_argument, 	&white_flag, 1},
      {"nospindown", no_argument, 	&s0_flag, 1},
      {"nocheckpoint", no_argument, &checkp_flag, 0},
      // frame number
      {"ident", required_argument, 0, 'i'},
      // frequency band number
      {"band", required_argument, 0, 'b'},
      // output directory
      {"output", required_argument, 0, 'o'},
      // input data directory
      {"data", required_argument, 0, 'd'},
      // non-standard label for naming files
      {"label", required_argument, 0, 'l'},
      // narrower grid range parameter file
      {"range", required_argument, 0, 'r'},
      // change directory parameter
      {"cwd", required_argument, 0, 'c'},
      // interpolation method
      {"int/fft", required_argument, 0, 'f'},
      // interpolation method
      {"threshold", required_argument, 0, 't'},
      // hemisphere
      {"hemisphere", required_argument, 0, 'h'},
      // detector
      {"detector", required_argument, 0, 'a'},
      // fpo value
      {"fpo value", required_argument, 0, 'p'},
      {0, 0, 0, 0}
    };

    if (help_flag) {

      printf("*** Continuous GW search code using the F-statistic ***\n");
      printf("Usage: ./search -[switch1] <value1> -[switch2] <value2> ...\n") ;
      printf("Switches are:\n\n");
      printf("-d	Data directory (default is .)\n");
      printf("-o	Output directory (default is ./candidates)\n");
      printf("-i	Frame number\n");
      printf("-b	Band number\n");
      printf("-l	Custom label for the input and output files\n");
      printf("-r	File with grid range or pulsar position\n");
      printf("-c	Change to directory <dir>\n");
      printf("-f	Intepolation method (FFT [default] or INT)\n");
      printf("-t	Threshold for the F-statistic (default is 20)\n");
      printf("-h	Hemisphere (default is 0 - does both)\n");
      printf("-a	Detector (L1, H1 or V1); default is V1\n");
      printf("-p	fpo (starting frequency) value\n\n");
      printf("Also:\n\n");
      printf("--whitenoise	white Gaussian noise assumed\n");
      printf("--nospindown	spindowns neglected\n");
      printf("--nocheckpoint	state file won't be created (no checkpointing)\n");
      printf("--help		This help\n");

      exit (0);
    }

    int option_index = 0;
    int c = getopt_long (argc, argv, "i:b:o:d:l:r:c:t:f:h:a:p:", long_options, &option_index);
    if (c == -1)
      break;

    switch (c) {
    case 'i':
      opts->ident = atoi (optarg);
      break;
    case 'f':
      if(!strcmp(optarg, "INT")) opts->fftinterp=INT;
      break;
    case 't':
      opts->trl = atof(optarg);
      break;
    case 'h':
      opts->hemi = atof(optarg);
      break;
    case 'b':
      opts->band = atoi (optarg);
      break;
    case 'o':
      strcpy (opts->prefix, optarg);
      break;
    case 'd':
      strcpy (opts->dtaprefix, optarg);
      break;
    case 'l':
      opts->label[0] = '_';
      strcpy (1+opts->label, optarg);
      break;
    case 'r':
      strcpy (opts->range, optarg);
      break;
    case 'c':
      opts->wd = (char *) malloc (1+strlen(optarg));
      strcpy (opts->wd, optarg);
      break;
    case 'p':
      sett->fpo = atof(optarg);
      break;
    case 'a':
      strcpy (opts->ifo_choice, optarg);
      break;
    case '?':
      break;
    default:
      break ;
    } /* switch c */
  } /* while 1 */

  opts->white_flag = white_flag;
  opts->s0_flag = s0_flag;
  opts->checkp_flag = checkp_flag;

  printf ("Data directory is %s\n", opts->dtaprefix);
  printf ("Output directory is %s\n", opts->prefix);
  printf ("Frame number is %d\n", opts->ident);
  printf ("Band number is %d\n", opts->band);

  if (opts->white_flag)
    printf ("Assuming white Gaussian noise\n");
  if (opts->fftinterp==INT)
    printf ("Using fftinterp=INT (FFT interpolation by interbinning)\n");
  else
    printf ("Using fftinterp=FFT (FFT interpolation by zero-padding)\n");
  if(opts->trl!=20)
    printf ("Threshold for the F-statistic is %f\n", opts->trl);
  if(opts->hemi)
    printf ("Search for hemisphere %d\n", opts->hemi);
  if (opts->s0_flag)
    printf ("Assuming s_1 = 0.\n");
  if (strlen(opts->label))
    printf ("Using '%s' as data label\n", opts->label);
  if (strlen(opts->range))
    printf ("Obtaining grid range from '%s'\n", opts->range);
  if (opts->wd) {
    printf ("Changing working directory to %s\n", opts->wd);
    if (chdir(opts->wd)) {
      perror (opts->wd);
      abort ();
    }
  }

  /*
    ############ End reading arguments ################
  */


  // Starting band frequency:
  // fpo_val is optionally read from the command line
  // Its initial value is set to -1
  if(!(sett->fpo >= 0))
    // The usual definition:
    sett->fpo = 100. + 0.96875 * opts->band;

  printf("The reference frequency (fpo) is %f\n", sett->fpo);

}
Exemple #2
0
void test4 ( ) {
#define TXT_NUMBITS (128)
#define VAL_MINBYTES (PT_BITLEN_TO_BYTELEN(16))
#define VAL_MAXBYTES (PT_BITLEN_TO_BYTELEN(TXT_NUMBITS))
#define VAL_VARBYTES (VAL_MAXBYTES - VAL_MINBYTES)

	char* keysTxt = malloc ( PT_BITLEN_TO_BYTELEN(TXT_NUMBITS) * NUMELEMENTSTXT );
	uint64_t *valsTxt = malloc ( PT_BITLEN_TO_BYTELEN(64) * NUMELEMENTSTXT );

	t = clock ( );
	uint32_t lenBytes;
	char* pKey = keysTxt;
	for ( i = 0; i < NUMELEMENTSTXT ; ++i ) {
		// at least 16 bits, at most 128 bits of non-null bytes
		lenBytes = ( xorshift32 ( ) % ( VAL_VARBYTES + 1 ) ) + VAL_MINBYTES;
		for ( k = 0; k < lenBytes ; ++k ) {
			*pKey = (char) ( ( ( xorshift32 ( ) & ( TXT_NUMBITS - 1 ) ) + 32 ) & ( 0xFF ) );
			pKey++;
		}
		for ( ; k < PT_BITLEN_TO_BYTELEN( TXT_NUMBITS ) ; ++k ) {
			*pKey++ = 0;
		}
	}
	t = clock ( ) - t;
	printf ( "TreeTxt : Creating " TOSTR(NUMELEMENTSTXT)" random keys took %f seconds\n", (float) t / CLOCKS_PER_SEC );
	if ( pKey != ( keysTxt + PT_BITLEN_TO_BYTELEN(TXT_NUMBITS) * NUMELEMENTSTXT ) ) {
		printf ( "TreeTxt: Overwrote key array!" );
	}
	/*
	 char* ptKey2 = keysTxt;
	 for ( i = 0; i < 10 ; ++i ) {
	 printf ( "\t%u: %s\n", i, ptKey2 );
	 ptKey2 += PREFIX_TREE_BITLEN_TO_BYTELEN( 128 );
	 }
	 */

	pt_index treeTxt;
	pt_index_init ( &treeTxt, TXT_NUMBITS, 64 );

	t = clock ( );
	pKey = keysTxt;
	uint64_t *pValOrg = valsTxt;
	for ( i = 0; i < NUMELEMENTSTXT ; ++i ) {
		*pValOrg = xorshift64 ( );
		pt_add ( &treeTxt, pKey, pValOrg ); // I know that this will be stored inline

		pKey += PT_BITLEN_TO_BYTELEN( TXT_NUMBITS );
		++pValOrg;
	}
	t = clock ( ) - t;
	printf ( "TreeTxt : Inserting " TOSTR(NUMELEMENTSTXT)" keys took %f seconds\n", (float) t / CLOCKS_PER_SEC );

	t = clock ( );
	uint32_t numBadValues = 0;
	uint32_t numNullPointers = 0;
	pKey = keysTxt;
	pValOrg = valsTxt;
	for ( i = 0; i < NUMELEMENTSTXT ; ++i ) {
		pVal = pt_find ( &treeTxt, pKey );
		numNullPointers += ( pVal == NULL );
		numBadValues += ( pVal == NULL ) || ( memcmp ( pVal, pValOrg, PT_BITLEN_TO_BYTELEN( TXT_NUMBITS ) ) != 0 );

		pKey += PT_BITLEN_TO_BYTELEN( TXT_NUMBITS );
		++pValOrg;
	}
	numBadValues -= numNullPointers;
	t = clock ( ) - t;
	printf ( "TreeTxt : Verifying " TOSTR(NUMELEMENTS)" keys took %f seconds. %u bad values found. %u null pointers.\n", (float) t / CLOCKS_PER_SEC, numBadValues, numNullPointers );

	free ( keysTxt );
	free ( valsTxt );
	keysTxt = NULL;
	valsTxt = NULL;
}
Exemple #3
0
void handle_opts(
  Search_settings *sett, 
  Command_line_opts *opts,
	int argc, 
	char* argv[]) {
	
  opts->hemi=0;
  opts->wd=NULL;
  opts->trl=20;
  opts->fftinterp=INT;
	
  strcpy (opts->prefix, TOSTR(PREFIX));
  strcpy (opts->dtaprefix, TOSTR(DTAPREFIX));
  opts->label[0]  = '\0';
  opts->addsig[0] = '\0';
	
  // Initial value of starting frequency set to a negative quantity. 
  // If this is not changed by the command line value, fpo is calculated 
  // from the band number b (fpo = fpo = 100. + 0.96875*b)
  sett->fpo = -1;

  // Default initial value of the data sampling time 
  sett->dt = 0.5; 

  opts->help_flag=0;
  opts->white_flag=0;
  opts->s0_flag=0;
  opts->checkp_flag=0;

  static int help_flag=0, white_flag=0, s0_flag=0, checkp_flag=1;

  // Reading arguments 

  while (1) {
    static struct option long_options[] = {
      {"help", no_argument, 			&help_flag, 1},
      {"whitenoise", no_argument, 	&white_flag, 1},
      {"nospindown", no_argument, 	&s0_flag, 1},
      {"nocheckpoint", no_argument, &checkp_flag, 0},
      // frame number
      {"ident", required_argument, 0, 'i'},
      // frequency band number
      {"band", required_argument, 0, 'b'},
      // output directory
      {"output", required_argument, 0, 'o'},
      // input data directory
      {"data", required_argument, 0, 'd'},
      // non-standard label for naming files
      {"label", required_argument, 0, 'l'},
      // Spotlight grid range parameter file
      {"spotlight", required_argument, 0, 'r'},
      // change directory parameter
      {"cwd", required_argument, 0, 'c'},
      // interpolation method
      {"threshold", required_argument, 0, 't'},
      // hemisphere
      {"hemisphere", required_argument, 0, 'h'},
      // fpo value
      {"fpo", required_argument, 0, 'p'},
      // add signal parameters
      {"addsig", required_argument, 0, 'x'},
      // data sampling time 
      {"dt", required_argument, 0, 's'},
      {0, 0, 0, 0}
    };

    if (help_flag) {

      printf("polgraw-allsky CGW search code using the F-statistic\n");
      printf("Usage: ./search -[switch1] <value1> -[switch2] <value2> ...\n") ;
      printf("Switches are:\n\n");
      printf("-d, -data         Data directory (default is .)\n");
      printf("-o, -output       Output directory (default is ./candidates)\n");
      printf("-i, -ident        Frame number\n");
      printf("-b, -band         Band number\n");
      printf("-l, -label        Custom label for the input and output files\n");
      printf("-r, -spotlight    Spotlight search file with sky and spindown grid points\n");
      printf("-c, -cwd          Change to directory <dir>\n");
      printf("-t, -threshold    Threshold for the F-statistic (default is 20)\n");
      printf("-h, -hemisphere   Hemisphere (default is 0 - does both)\n");
      printf("-p, -fpo          Reference band frequency fpo value\n");
      printf("-s, -dt           Data sampling time dt (default value: 0.5)\n");
      printf("-x, -addsig       Add signal with parameters from <file>\n\n");

      printf("Also:\n\n");
      printf("--whitenoise      White Gaussian noise assumed\n");
      printf("--nospindown      Spindowns neglected\n");
      printf("--nocheckpoint    State file won't be created (no checkpointing)\n");
      printf("--help		This help\n");

      exit (0);
    }

    int option_index = 0;
    int c = getopt_long_only (argc, argv, "i:b:o:d:l:r:c:t:h:p:x:s:", long_options, &option_index);
    if (c == -1)
      break;

    switch (c) {
    case 'i':
      opts->ident = atoi(optarg);
      break;
    case 't':
      opts->trl = atof(optarg);
      break;
    case 'h':
      opts->hemi = atof(optarg);
      break;
    case 'b':
      opts->band = atoi(optarg);
      break;
    case 'o':
      strcpy(opts->prefix, optarg);
      break;
    case 'd':
      strcpy(opts->dtaprefix, optarg);
      break;
    case 'l':
      opts->label[0] = '_';
      strcpy(1+opts->label, optarg);
      break;
    case 'r':
      strcpy(opts->spotlight, optarg);
      break;
    case 'c':
      opts->wd = (char *) malloc (1+strlen(optarg));
      strcpy(opts->wd, optarg);
      break;
    case 'p':
      sett->fpo = atof(optarg);
      break;
    case 'x':
      strcpy(opts->addsig, optarg);
      break;
    case 's':
      sett->dt = atof(optarg);
      break;
    case '?':
      break;
    default:
      break ;
    } /* switch c */
  } /* while 1 */

  opts->white_flag = white_flag;
  opts->s0_flag = s0_flag;
  opts->checkp_flag = checkp_flag;	
	
  printf("Input data directory is %s\n", opts->dtaprefix);
  printf("Output directory is %s\n", opts->prefix);
  printf("Frame and band numbers are %d and %d\n", opts->ident, opts->band);

  // Starting band frequency:
  // fpo_val is optionally read from the command line
  // Its initial value is set to -1
  if(!(sett->fpo >= 0))
    // The usual definition (multiplying the offset by B=1/(2dt) ):
    sett->fpo = 100. + 0.96875*opts->band*(0.5/sett->dt);

  printf("The reference frequency fpo is %f\n", sett->fpo);
  printf("The data sampling time dt is  %f\n", sett->dt); 

  if (opts->white_flag)
    printf ("Assuming white Gaussian noise\n");

  // For legacy: FFT is now the only option 
  printf ("Using fftinterp=FFT (FFT interpolation by zero-padding)\n");

  if(opts->trl!=20)
    printf ("Threshold for the F-statistic is %lf\n", opts->trl);
  if(opts->hemi)
    printf ("Search for hemisphere %d\n", opts->hemi);
  if (opts->s0_flag)
    printf ("Assuming s_1 = 0.\n");
  if (strlen(opts->label))
    printf ("Using '%s' as data label\n", opts->label);

  if (strlen(opts->spotlight))
    printf("Obtaining spotlight grid points from '%s'\n", opts->spotlight);
  else { 
    printf("No spotlight grid range file provided! Exiting...\n");   
    abort(); 
  }

  if (strlen(opts->addsig))
    printf ("Adding signal from '%s'\n", opts->addsig);
  if (opts->wd) {
    printf ("Changing working directory to %s\n", opts->wd);
    if (chdir(opts->wd)) { perror (opts->wd); abort (); }
  }

} // end of command line options handling 
Exemple #4
0
/* zipfile.replaceFile(nameInArchive, name, offset, len) */
Handle<Value> ZipFile::Replace_File(const Arguments& args)
{
    ZipFile* zf = ObjectWrap::Unwrap<ZipFile>(args.This());

    struct zip_source *source;

    if (zf->Busy())
      return ThrowException(Exception::Error(String::New("Zipfile already in use..")));

    if (!args[0]->IsString())
      return ThrowException(Exception::TypeError(
                 String::New("Argument must be a file name.")));
    std::string archive_file = TOSTR(args[0]);

    std::string name;
    if (args[1]->IsUndefined())
      name = archive_file;
    else
      if (!args[1]->IsString())
        return ThrowException(Exception::TypeError(
                   String::New("Argument must be a file name.")));
      name = TOSTR(args[1]);

    zip_int64_t off;
    if (args[2]->IsUndefined())
      off = 0;
    else
      off = args[2]->Int32Value();
    
    zip_int64_t len; 
    if (args[3]->IsUndefined()) 
      len = -1; 
    else 
      len = args[3]->Int32Value();

    int idx = -1;
    
    std::vector<std::string>::iterator it = std::find(zf->names.begin(), zf->names.end(), archive_file);
    if (it!=zf->names.end()) {
        idx = distance(zf->names.begin(), it);
    }

    if (idx == -1) {
        std::stringstream s;
        s << "No file found by the name of: '" << archive_file << "\n";
        return ThrowException(Exception::Error(String::New(s.str().c_str())));
    }

    source = zip_source_file(zf->archive, name.c_str(), off, len);
    if (source == NULL) {
      std::stringstream s;
      s << "Error while replacing file " << name << " in zip archive: " << zip_strerror(zf->archive) << "\n";
      return ThrowException(Exception::Error(String::New(s.str().c_str())));
    }

    int ret = zip_replace(zf->archive, idx, source);        
    if (ret < 0) {
      zip_source_free(source);
      std::stringstream s;
      s << "Error while replacing file " << name << " in zip archive: " << zip_strerror(zf->archive) << "\n";
      return ThrowException(Exception::Error(String::New(s.str().c_str())));
    }

    return Undefined();
}
/**
  @brief Finds the Rois in the thermal image in CV_8UC1 format.
  First, the edges of the thermal image are detected.
  Then, keypoints of blobs are detected in the above image.
  Finally, the potential Rois outline is found, along with the bounding
  boxes of those outlines.
  @param[in] thermalImage [const cv::Mat&] The thermal
  image in CV_8UC1 format.
  @return RoisConveyor The struct that contains the rois found.
 **/
RoisConveyor RoiDetector::findRois(const cv::Mat& thermalImage)
{
#ifdef DEBUG_TIME
    Timer::start("findRois", "inputThermalImageCallback");
#endif

#ifdef DEBUG_SHOW
    std::vector<cv::Mat> imgs;
    std::vector<std::string> msgs;
    if (Parameters::Debug::show_find_rois)  // Debug
    {
        std::string msg = LPATH(STR(__FILE__)) + STR(" ") + TOSTR(__LINE__);
        msg += " : Thermal image";
        msgs.push_back(msg);
        cv::Mat tmp = Visualization::scaleImageForVisualization(
                          thermalImage, Parameters::Image::scale_method);
        imgs.push_back(tmp);
    }
#endif

    // Detect edges in the thermal image
    cv::Mat thermalImageEdges;
    EdgeDetection::computeThermalEdges(thermalImage,
                                       &thermalImageEdges);

#ifdef DEBUG_SHOW
    if (Parameters::Debug::show_find_rois)  // Debug
    {
        std::string msg = LPATH(STR(__FILE__)) + STR(" ") + TOSTR(__LINE__);
        msg += STR(" : Edges after denoise");
        msgs.push_back(msg);
        cv::Mat tmp;
        thermalImageEdges.copyTo(tmp);
        imgs.push_back(tmp);
    }
#endif

    // Find blobs in the edges image. Each blob is represented as
    // a keypoint which is the center of the blob found
    std::vector<cv::KeyPoint> keyPoints;
    BlobDetection::detectBlobs(thermalImageEdges, &keyPoints);

#ifdef DEBUG_SHOW
    if (Parameters::Debug::show_find_rois)  // Debug
    {
        std::string msg = LPATH(STR(__FILE__)) + STR(" ") + TOSTR(__LINE__);
        msg += STR(" : Initial keypoints");
        msgs.push_back(msg);
        imgs.push_back(
            Visualization::showKeypoints(msg, thermalImageEdges, -1,
                                         keyPoints));
    }
#endif

    // The final vectors of keypoints, rectangles and blobs' outlines.
    RoisConveyor conveyor;

    /**
      Get me blobs that their center point is inside the image,
      their bounding box is also entirely inside the image, and their area is
      greater than Parameters::bounding_box_min_area_threshold.
      Each keypoint is associated with exactly one rectangle.
      The end product here is a set of keypoints, a set of rectangles that
      enclose them and a set of the outlines of the blobs found, all tightly
      packed in the conveyor struct.
     **/
    RoiFilters::validateBlobs(
        keyPoints,
        &thermalImageEdges,
        Parameters::Outline::outline_detection_method,
        &conveyor);

#ifdef DEBUG_SHOW
    if (Parameters::Debug::show_find_rois)  // Debug
    {
        std::string msg = LPATH(STR(__FILE__)) + STR(" ") + TOSTR(__LINE__);
        msg += STR(" : Blobs");
        msgs.push_back(msg);
        imgs.push_back(
            Visualization::showRois(
                msg,
                thermalImage,
                conveyor,
                -1,
                std::vector<std::string>()));
    }
#endif

#ifdef DEBUG_SHOW
    if (Parameters::Debug::show_find_rois)  // Debug
    {
        // A vector of keypoints
        std::vector<cv::KeyPoint> keypointsVector;

        for (int i = 0; i < conveyor.size(); i++)
        {
            keypointsVector.push_back(conveyor.rois[i].keypoint);
        }

        std::string msg = LPATH(STR(__FILE__)) + STR(" ") + TOSTR(__LINE__);
        msg += STR(" : Keypoints found from this process");
        msgs.push_back(msg);
        imgs.push_back(
            Visualization::showKeypoints(
                msg,
                thermalImage,
                -1,
                keypointsVector));
    }
    if (Parameters::Debug::show_find_rois)
    {
        Visualization::multipleShow("Thermal node", imgs, msgs,
                                    Parameters::Debug::show_find_rois_size, 1);
    }
#endif

#ifdef DEBUG_TIME
    Timer::tick("findRois");
#endif

    return conveyor;
}
Exemple #6
0
Handle<Value> ZipFile::readFileSync(const Arguments& args)
{
    HandleScope scope;

    if (args.Length() != 1 || !args[0]->IsString())
        return ThrowException(Exception::TypeError(
          String::New("first argument must be a file name inside the zip")));

    std::string name = TOSTR(args[0]);
  
    // TODO - enforce valid index
    ZipFile* zf = ObjectWrap::Unwrap<ZipFile>(args.This());

    if (zf->Busy())
      return ThrowException(Exception::Error(String::New("Zipfile already in use..")));

    struct zip_file *zf_ptr;

    int idx = -1;
    
    std::vector<std::string>::iterator it = std::find(zf->names.begin(), zf->names.end(), name);
    if (it!=zf->names.end()) {
        idx = distance(zf->names.begin(), it);
    }

    if (idx == -1) {
        std::stringstream s;
        s << "No file found by the name of: '" << name << "\n";
        return ThrowException(Exception::Error(String::New(s.str().c_str())));
    }

    if ((zf_ptr=zip_fopen_index(zf->archive, idx, 0)) == NULL) {
        zip_fclose(zf_ptr);
        std::stringstream s;
        s << "cannot open file #" << idx << " in " << name << ": archive error: " << zip_strerror(zf->archive) << "\n";
        return ThrowException(Exception::Error(String::New(s.str().c_str())));
    }

    struct zip_stat st;
    zip_stat_index(zf->archive, idx, 0, &st);
  
    std::vector<unsigned char> data;
    data.clear();
    data.resize( st.size );
    
    int result =  0;
    result = (int)zip_fread( zf_ptr, reinterpret_cast<void*> (&data[0]), data.size() );

    if (result < 0) {
        zip_fclose(zf_ptr);
        std::stringstream s;
        s << "error reading file #" << idx << " in " << name << ": archive error: " << zip_file_strerror(zf_ptr) << "\n";
        return ThrowException(Exception::Error(String::New(s.str().c_str())));
    }

    #if NODE_VERSION_AT_LEAST(0,3,0)
        node::Buffer *retbuf = Buffer::New((char *)&data[0],data.size());
    #else
        node::Buffer *retbuf = Buffer::New(data.size());
        std::memcpy(retbuf->data(), (char *)&data[0], data.size());
    #endif
    
    zip_fclose(zf_ptr);
    return scope.Close(retbuf->handle_);
}
Exemple #7
0
void run_test (intT, thr_args_base::tag_t tag)
{
    static const char* const tname = rw_any_t (intT ()).type_name ();

    if (!rw_enabled (tname)) {
        rw_note (0, 0, 0, "%s test disabled", tname);
        return;
    }

#ifdef _RWSTD_REENTRANT

    static const char* const fun = "__rw_atomic_exchange";

    rw_info (0, 0, 0, "__rw::%s (%s&, %2$s): %d iterations in %d threads",
             fun, tname, rw_opt_nloops, rw_opt_nthreads);

    rw_thread_t tid [MAX_THREADS];

    typedef thr_args<intT> Args;

    Args::nthreads_   = unsigned (rw_opt_nthreads);
    Args::type_tag_   = tag;
    Args::nincr_      = unsigned (rw_opt_nloops);
    Args::shared_ [0] = intT (1);
    Args::shared_ [1] = intT (1);

    _RWSTD_ASSERT (Args::nthreads_ < sizeof tid / sizeof *tid);

    Args args [sizeof tid / sizeof *tid];

    for (unsigned long i = 0; i != Args::nthreads_; ++i) {

        args [i].threadno_ = i;
        args [i].niter_    = 0;
        args [i].nxchg_    = 0;

        rw_fatal (0 == rw_thread_create (tid + i, 0, thread_routine, args + i),
                  0, __LINE__, "thread_create() failed");
    }
            
    for (unsigned long i = 0; i != Args::nthreads_; ++i) {

        rw_error (0 == rw_thread_join (tid [i], 0), 0, __LINE__,
                  "thread_join() failed");

        if (args [i].niter_) {
            // compute the percantage of thread iterations that resulted
            // in increments of one of the shared variables
            const unsigned long incrpcnt =
                (100U * Args::nincr_) / args [i].niter_;

            printf ("thread %lu performed %lu exchanges in %lu iterations "
                    "(%lu%% increments)\n",
                    args [i].threadno_, args [i].nxchg_,
                    args [i].niter_, incrpcnt);
        }
    }

    // compute the expected result, "skipping" zeros by incrementing
    // expect twice when it overflows and wraps around to 0 (zero is
    // used as the lock variable in thread_routine() above)
    intT expect = intT (1);

    const unsigned long nincr = (Args::nthreads_ * Args::nincr_) / 2U;
        
    for (unsigned long i = 0; i != nincr; ++i) {
        if (intT () == ++expect)
            ++expect;
    }

    // verify that the final value of the variables shared among all
    // threads equals the number of increments performed by the threads
    rw_assert (Args::shared_ [0] == expect, 0, __LINE__,
               "1. %s (%s&, %2$s); %s == %s failed",
               fun, tname, TOSTR (Args::shared_ [0]), TOSTR (expect));

    rw_assert (Args::shared_ [1] == expect, 0, __LINE__,
               "2. %s (%s&, %2$s); %s == %s failed",
               fun, tname, TOSTR (Args::shared_ [1]), TOSTR (expect));

#else   // if !defined (_RWSTD_REENTRANT)

    _RWSTD_UNUSED (tag);

#endif   // _RWSTD_REENTRANT
}
Handle<Value> Grid::New(const Arguments& args)
{
    HandleScope scope;
    if (!args.IsConstructCall())
        return ThrowException(String::New("Cannot call constructor as function, you need to use 'new' keyword"));

    if (args[0]->IsExternal())
    {
        //std::clog << "external!\n";
        Local<External> ext = Local<External>::Cast(args[0]);
        void* ptr = ext->Value();
        Grid* g =  static_cast<Grid*>(ptr);
        g->Wrap(args.This());
        return args.This();
    }

    if (args.Length() >= 2)
    {
        if (!args[0]->IsNumber() || !args[1]->IsNumber())
            return ThrowException(Exception::TypeError(
                                      String::New("Grid 'width' and 'height' must be a integers")));

        // defaults
        std::string key("__id__");
        unsigned int resolution = 1;

        if (args.Length() >= 3) {

            if (!args[2]->IsObject())
                return ThrowException(Exception::TypeError(
                                          String::New("optional third arg must be an options object")));
            Local<Object> options = args[2]->ToObject();

            if (options->Has(String::New("key"))) {
                Local<Value> bind_opt = options->Get(String::New("key"));
                if (!bind_opt->IsString())
                    return ThrowException(Exception::TypeError(
                                              String::New("optional arg 'key' must be an string")));

                key = TOSTR(bind_opt);
            }
            // TODO - remove, deprecated
            if (options->Has(String::New("resolution"))) {
                Local<Value> bind_opt = options->Get(String::New("resolution"));
                if (!bind_opt->IsNumber())
                    return ThrowException(Exception::TypeError(
                                              String::New("optional arg 'resolution' must be an string")));

                resolution = bind_opt->IntegerValue();
            }
        }

        Grid* g = new Grid(args[0]->IntegerValue(),args[1]->IntegerValue(),key,resolution);
        g->Wrap(args.This());
        return args.This();
    }
    else
    {
        return ThrowException(Exception::Error(
                                  String::New("please provide Grid width and height")));
    }
    return Undefined();
}
Handle<Value> Grid::encode(const Arguments& args) // format, resolution
{
    HandleScope scope;

    Grid* g = ObjectWrap::Unwrap<Grid>(args.This());

    // defaults
    std::string format("utf");
    unsigned int resolution = 4;
    bool add_features = true;

    // accept custom format
    if (args.Length() >= 1){
        if (!args[0]->IsString())
            return ThrowException(Exception::TypeError(
                                      String::New("first arg, 'format' must be a string")));
        format = TOSTR(args[0]);
    }

    // options hash
    if (args.Length() >= 2) {
        if (!args[1]->IsObject())
            return ThrowException(Exception::TypeError(
                                      String::New("optional second arg must be an options object")));

        Local<Object> options = args[1]->ToObject();

        if (options->Has(String::New("resolution")))
        {
            Local<Value> bind_opt = options->Get(String::New("resolution"));
            if (!bind_opt->IsNumber())
                return ThrowException(Exception::TypeError(
                                          String::New("'resolution' must be an Integer")));

            resolution = bind_opt->IntegerValue();
        }

        if (options->Has(String::New("features")))
        {
            Local<Value> bind_opt = options->Get(String::New("features"));
            if (!bind_opt->IsBoolean())
                return ThrowException(Exception::TypeError(
                                          String::New("'features' must be an Boolean")));

            add_features = bind_opt->BooleanValue();
        }
    }

    // ensure callback is a function
    if (!args[args.Length()-1]->IsFunction())
        return ThrowException(Exception::TypeError(
                                  String::New("last argument must be a callback function")));
    Local<Function> callback = Local<Function>::Cast(args[args.Length()-1]);

    encode_grid_baton_t *closure = new encode_grid_baton_t();
    closure->request.data = closure;
    closure->g = g;
    closure->format = format;
    closure->error = false;
    closure->resolution = resolution;
    closure->add_features = add_features;
    closure->cb = Persistent<Function>::New(Handle<Function>::Cast(callback));
    // todo - reserve lines size?
    uv_queue_work(uv_default_loop(), &closure->request, EIO_Encode, EIO_AfterEncode);
    uv_ref(uv_default_loop());
    g->Ref();
    return Undefined();
}
Handle<Value> Grid::encodeSync(const Arguments& args) // format, resolution
{
    HandleScope scope;

    Grid* g = ObjectWrap::Unwrap<Grid>(args.This());

    // defaults
    std::string format("utf");
    unsigned int resolution = 4;
    bool add_features = true;

    // accept custom format
    if (args.Length() >= 1){
        if (!args[0]->IsString())
            return ThrowException(Exception::TypeError(
                                      String::New("first arg, 'format' must be a string")));
        format = TOSTR(args[0]);
    }

    // options hash
    if (args.Length() >= 2) {
        if (!args[1]->IsObject())
            return ThrowException(Exception::TypeError(
                                      String::New("optional second arg must be an options object")));

        Local<Object> options = args[1]->ToObject();

        if (options->Has(String::New("resolution")))
        {
            Local<Value> bind_opt = options->Get(String::New("resolution"));
            if (!bind_opt->IsNumber())
                return ThrowException(Exception::TypeError(
                                          String::New("'resolution' must be an Integer")));

            resolution = bind_opt->IntegerValue();
        }

        if (options->Has(String::New("features")))
        {
            Local<Value> bind_opt = options->Get(String::New("features"));
            if (!bind_opt->IsBoolean())
                return ThrowException(Exception::TypeError(
                                          String::New("'features' must be an Boolean")));

            add_features = bind_opt->BooleanValue();
        }
    }

    try {

        boost::ptr_vector<uint16_t> lines;
        std::vector<mapnik::grid::lookup_type> key_order;
        node_mapnik::grid2utf<mapnik::grid>(*g->get(),lines,key_order,resolution);

        // convert key order to proper javascript array
        Local<Array> keys_a = Array::New(key_order.size());
        std::vector<std::string>::iterator it;
        unsigned int i;
        for (it = key_order.begin(), i = 0; it < key_order.end(); ++it, ++i)
        {
            keys_a->Set(i, String::New((*it).c_str()));
        }

        mapnik::grid const& grid_type = *g->get();

        // gather feature data
        Local<Object> feature_data = Object::New();
        if (add_features) {
            node_mapnik::write_features<mapnik::grid>(*g->get(),
                                                      feature_data,
                                                      key_order);
        }

        // Create the return hash.
        Local<Object> json = Object::New();
        Local<Array> grid_array = Array::New();
        unsigned array_size = static_cast<unsigned int>(grid_type.width()/resolution);
        for (unsigned j=0;j<lines.size();++j)
        {
            grid_array->Set(j,String::New(&lines[j],array_size));
        }
        json->Set(String::NewSymbol("grid"), grid_array);
        json->Set(String::NewSymbol("keys"), keys_a);
        json->Set(String::NewSymbol("data"), feature_data);
        return json;

    }
    catch (std::exception & ex)
    {
        return ThrowException(Exception::Error(
                                  String::New(ex.what())));
    }
}