示例#1
0
std::pair<int, Quad> Decode::operator()(const std::vector<unsigned char> &bits, const Quad &corners)
{
    auto result = doDecode(bits, corners);
#ifdef HAS_INVERTED_TAGS
    if (result.first == INVALID_TAG) {
        //flip the bits, in case this tag is inverted
        std::vector<unsigned char> flippedBits(bits.size());
        std::transform(bits.begin(), bits.end(), flippedBits.begin(), [](const unsigned char& c) {
                return 1 - c;
            });
        result = doDecode(flippedBits, corners);
    }
#endif
    return result;
}
示例#2
0
static jobject nativeDecodeByteArray(
  JNIEnv* env,
  jclass clazz,
  jbyteArray array,
  jint offset,
  jint length,
  jobject bitmapOptions,
  jfloat scale,
  jbyteArray inTempStorage) {

    // get image into decoded heap
    jbyte* data = env->GetByteArrayElements(array, nullptr);
    if (env->ExceptionCheck() == JNI_TRUE) {
      env->ReleaseByteArrayElements(inTempStorage, data, JNI_ABORT);
      RETURN_NULL_IF_EXCEPTION(env);
    }
    if (data == nullptr || offset + length > env->GetArrayLength(array)) {
      env->ReleaseByteArrayElements(array, data, JNI_ABORT);
      RETURN_NULL_IF_EXCEPTION(env);
    }
    jobject bitmap = doDecode(env, reinterpret_cast<uint8_t*>(data) + offset, length, bitmapOptions, scale);
    env->ReleaseByteArrayElements(array, data, JNI_ABORT);
    RETURN_NULL_IF_EXCEPTION(env);

    return bitmap;
}
示例#3
0
BitmapGlue*
BitmapFactoryGlue::decodeByteArray(const NativeArray<uint8_t>& data, int offset, int length, Options& options)
{
	/*  If optionsShareable() we could decide to just wrap the java array and
	    share it, but that means adding a globalref to the java array object
	    and managing its lifetime. For now we just always copy the array's data
	    if optionsPurgeable(), unless we're just decoding bounds.
	*/
	bool purgeable = options.isPurgeable && !options.justDecodeBounds;
	SkStream* stream = new SkMemoryStream(data.ptr(offset,length), length, purgeable);
	SkAutoUnref aur(stream);
	return doDecode(stream, options, purgeable);
}
示例#4
0
void calculateFitness(struct Chromosome *pop){
	int calcPath[2*(1+GENETIC_PURSUERS+GENETIC_STEPS*GENETIC_PURSUERS)]; // Temporary variable for path
	calcPath[0]=GENETIC_PURSUERS; // Number of pursuers
	calcPath[1]=GENETIC_STEPS; // Number of steps
	doDecode(&(*pop), calcPath); // Decode allele to positions
	int temp = calculateStates(calcPath); // Calculate states
	(*pop).chrSteps = temp; // Write number of steps to individual
	if(temp>=0)
		(*pop).inS4 = 0; // If number of steps was positive, no nodes were in state 4
	else
		(*pop).inS4 = getS4(); // Write number of nodes in state 4
	//(*pop).fitnessScore = 1000/(1+(*pop).inS4+abs((*pop).chrSteps)); // Set fitness to 1000/(1+S4+steps), 1000 to scale fitness, 1+ to avoid division by 0.
	(*pop).fitnessScore = (ROWS*COLS+GENETIC_STEPS-(*pop).inS4-abs((*pop).chrSteps)); // Better fitness function? Nr of nodes in S123 + nr of steps not used.
}
示例#5
0
static jobject nativeDecodeStream(
  JNIEnv* env,
  jclass clazz,
  jobject is,
  jobject bitmapOptions,
  jfloat scale,
  jbyteArray inTempStorage) {
  auto encoded_image = readStreamFully(env, is, inTempStorage);
  if (!encoded_image.empty()) {
    return doDecode(env, encoded_image.data(), encoded_image.size(), bitmapOptions, scale);
  }
  return {};

}
示例#6
0
BitmapGlue*
BitmapFactoryGlue::nativeDecodeAsset(Asset& asset, SkIRect padding, Options& options)
{
	SkStream* stream;
	bool forcePurgeable = options.isPurgeable;
	if (forcePurgeable) {
		// if we could "ref/reopen" the asset, we may not need to copy it here
		// and we could assume optionsShareable, since assets are always RO
		stream = copyAssetToStream(asset);
		if (NULL == stream) {
			return NULL;
		}
	} else {
		// since we know we'll be done with the asset when we return, we can
		// just use a simple wrapper
		stream = new AssetStreamAdaptor(asset);
	}
	SkAutoUnref aur(stream);
	return doDecode(stream, options, true, forcePurgeable);
}
示例#7
0
int
main (int argc, char **argv)
{
    int		 retval = 0;  /* 0 - test succeeded.  -1 - test failed */
    SECStatus	 rv;
    PLOptState	*optstate;
    char	*program_name;
    char  *input_file = NULL; 	/* read encrypted data from here (or create) */
    char  *output_file = NULL;	/* write new encrypted data here */
    char  *log_file = NULL;	/* write new encrypted data here */
    FILE	*inFile = stdin;
    FILE	*outFile = stdout;
    FILE	*logFile = NULL;
    PLOptStatus optstatus;
    secuPWData  pwdata = { PW_NONE, NULL };


    program_name = PL_strrchr(argv[0], '/');
    program_name = program_name ? (program_name + 1) : argv[0];

    optstate = PL_CreateOptState (argc, argv, "Hd:f:i:o:l:p:?");
    if (optstate == NULL) {
	SECU_PrintError (program_name, "PL_CreateOptState failed");
	return 1;
    }

    while ((optstatus = PL_GetNextOpt(optstate)) == PL_OPT_OK) {
	switch (optstate->option) {
	  case '?':
	    short_usage (program_name);
	    return 1;

	  case 'H':
	    long_usage (program_name);
	    return 1;

	  case 'd':
	    SECU_ConfigDirectory(optstate->value);
	    break;

          case 'i':
            input_file = PL_strdup(optstate->value);
            break;

          case 'o':
            output_file = PL_strdup(optstate->value);
            break;

          case 'l':
            log_file = PL_strdup(optstate->value);
            break;

          case 'f':
            pwdata.source = PW_FROMFILE;
            pwdata.data = PL_strdup(optstate->value);
            break;

          case 'p':
            pwdata.source = PW_PLAINTEXT;
            pwdata.data = PL_strdup(optstate->value);
            break;

	}
    }
    PL_DestroyOptState(optstate);
    if (optstatus == PL_OPT_BAD) {
	short_usage (program_name);
	return 1;
    }

    if (input_file) {
        inFile = fopen(input_file,"r");
        if (inFile == NULL) {
	    perror(input_file);
	    return 1;
        }
        PR_Free(input_file);
    }
    if (output_file) {
        outFile = fopen(output_file,"w+");
        if (outFile == NULL) {
	    perror(output_file);
	    return 1;
        }
        PR_Free(output_file);
    }
    if (log_file) {
	if (log_file[0] == '-')
	    logFile = stderr;
	else
	    logFile = fopen(log_file,"w+");
	if (logFile == NULL) {
	    perror(log_file);
	    return 1;
	}
        PR_Free(log_file);
    }

    /*
     * Initialize the Security libraries.
     */
    PK11_SetPasswordFunc(SECU_GetModulePassword);
    rv = NSS_Init(SECU_ConfigDirectory(NULL));
    if (rv != SECSuccess) {
	SECU_PrintError (program_name, "NSS_Init failed");
	retval = 1;
	goto prdone;
    }

    /* Get the encrypted result, either from the input file
     * or from encrypting the plaintext value
     */
    while (fgets(dataString, sizeof dataString, inFile)) {
	unsigned char c = dataString[0];

	if (c == 'M' && isBase64(dataString)) {
	    doDecrypt(dataString, outFile, logFile, &pwdata);
        } else if (c == '~' && isBase64(dataString + 1)) {
	    doDecode(dataString, outFile, logFile);
	} else {
	    fputs(dataString, outFile);
	}
    }
    if (pwdata.data)
    	PR_Free(pwdata.data);

    fclose(outFile);
    fclose(inFile);
    if (logFile && logFile != stderr) {
	fclose(logFile);
    }

    if (NSS_Shutdown() != SECSuccess) {
	SECU_PrintError (program_name, "NSS_Shutdown failed");
        exit(1);
    }

prdone:
    PR_Cleanup ();
    return retval;
}
示例#8
0
void MSFTime::stateChange()  // interrupt routine called on every state change
{

   byte val = digitalRead(mInputPin);


  if( val == oldVal )
    return;
    
  oldVal = val;

  long millisNow = millis();

  if( mLedPin != 255 )
    digitalWrite(mLedPin, val);

  // see here:
  // http://www.pvelectronics.co.uk/rftime/msf/MSF_Time_Date_Code.pdf
  // for an explanation of the format

  // Carrier goes off for 100, 200, 300, or 500 mS during every second

  // Our input is inverted by our receiver, so val != 0 when carrier is off

    if (val != 0) // carrier is off, start timing
    {
      
      if( millisNow - mOnStartMillis < PULSE_IGNORE_WIDTH)
      {
        // ignore this transition plus the previous one
         #ifdef EXTRA_DEBUG
        Serial.print("Ignoring on pulse len ");
        Serial.println(millisNow - mOnStartMillis);
        #endif
        
        mOnStartMillis = mPrevOnStartMillis;
       
        return;
      }
      
      mPrevOffStartMillis = mOffStartMillis;
      mOffStartMillis = millisNow;

      mOnWidth = mOffStartMillis - mOnStartMillis;
      return; 
    }

    
    if( millisNow - mOffStartMillis < PULSE_IGNORE_WIDTH)
    {
       #ifdef EXTRA_DEBUG
        Serial.print("Ignoring off pulse len ");
        Serial.println(millisNow - mOffStartMillis);
        #endif
      // ignore this transition plus the previous one
      mOffStartMillis = mPrevOffStartMillis;
      return;
    }
    
        mPrevOnStartMillis = mOnStartMillis;
    mOnStartMillis = millisNow;
  
    long offWidth = millisNow - mOffStartMillis - PULSE_OFF_OFFSET;


    /* check the width of the off-pulse; according to the specifications, a
     * pulse must be 0.1 or 0.2 or 0.3 or 0.5 seconds
     */

    boolean is500 = abs(offWidth-500) < PULSE_MARGIN;
    boolean is300 = abs(offWidth-300) < PULSE_MARGIN;
    boolean is200 = abs(offWidth-200) < PULSE_MARGIN;
    boolean is100 = abs(offWidth-100) < PULSE_MARGIN;

    long onWidth = mOnWidth;

    boolean onWas100 =  (onWidth > 5) && (onWidth < 200);

    boolean onWasNormal = (onWidth > 400) && (onWidth < (900 + PULSE_MARGIN));

    
    #ifdef EXTRA_DEBUG
    Serial.print("Sum ");
    Serial.print(offWidth + onWidth);
    Serial.print("  offWidth ");
    Serial.print(offWidth);
    Serial.print("  onWidth ");
    Serial.print(onWidth);

    Serial.print("  mBitIndex ");
    Serial.println((int)mBitIndex);
    #endif


    if( (onWasNormal || onWas100) && (is100 || is200 || is300 || is500 ))
    {
      mGoodPulses++;
    }
    else
    {
      #ifdef EXTRA_DEBUG
      Serial.println("Bad pulse!!!!!! ");
      #endif
      mGoodPulses = 0;
    }
    
    /*
    Cases:
    a 500mS carrier-off marks the start of a minute
    a 300mS carrier-off means bits 1 1
    a 200mS carrier-off means bits 1 0
    a 100mS carrier-off followed by a 900mS carrier-on means bits 0 0
    a 100mS carrier-off followed by a 100mS carrier-on followed by a 100mS carrier-off means bits 0 1
    */

    if( is500 ) // minute marker
    {
      if( mIsReading )
        doDecode();

      mIsReading = true; // and get ready to read the next minute's worth
      mBitIndex = 1;  // the NPL docs number bits from 1, so we will too
    }
    else
    if( mIsReading )
    {
      if( mBitIndex < 60 && onWasNormal && (is100 || is200 || is300 )) // we got a sensible pair of bits, 00 or 01 or 11
      {
        if( is100 )
        {
           setBit( mABits, mBitIndex, 0 );
           setBit( mBBits, mBitIndex++, 0 );
        }
        if( is200 )
        {
           setBit( mABits, mBitIndex, 1 );
           setBit( mBBits, mBitIndex++, 0 );
        }
        if( is300 )
        {
           setBit( mABits, mBitIndex, 1 );
           setBit( mBBits, mBitIndex++, 1 );
        }

        #ifdef EXTRA_DEBUG
          if( getBit( mABits, mBitIndex - 1 ))
             Serial.println("  A = 1");
          else
             Serial.println("  A = 0");

          if( getBit( mBBits, mBitIndex - 1 ))
             Serial.println("  B = 1");
          else
             Serial.println("  B = 0");
         #endif


      }
      else if( mBitIndex < 60 && onWas100 && is100 && mBitIndex > 0 ) // tricky - we got a second bit for the preceding pair
      {
        setBit( mBBits, mBitIndex - 1, 1 );

        #ifdef EXTRA_DEBUG
            if( getBit( mBBits, mBitIndex - 1 ))
             Serial.println("  B = 1");
          else
             Serial.println("  B = 0");
         #endif
       }
      else // bad pulse, give up
      {
        #ifdef DEBUG
        if( mIsReading || ! (is100 || is200 || is300 || is500))
        {
          Serial.println("Bad pulse len");
          Serial.print("  offWidth ");
          Serial.println(offWidth);
          Serial.print("  onWidth ");
          Serial.println(onWidth);
          Serial.print("  mBitIndex ");
          Serial.println((int)mBitIndex);
        }
        #endif

        mIsReading = false;
        mBitIndex = 0;
      }
    }
}
示例#9
0
/*** Algorithm ***/
void genAlg(int *solution) { // Main call function for Genetic Algorithm
	int currentGeneration=0, currentPopulation=0;
	int isSolved = 0;
	int k,i,j;
	int isChanged = 1;
	for(;GENETIC_POPULATION_SIZE<GENETIC_POPULATION_MAX_SIZE;GENETIC_POPULATION_SIZE+=GENETIC_INCREMENT_POPULATION){
		for(i = GENETIC_POPULATION_SIZE; i < GENETIC_POPULATION_SIZE+GENETIC_INCREMENT_POPULATION; i++){ // Reset all genes.
			for(j = 0; j < GENETIC_PURSUERS; j++)
				for(k=0;k<GENETIC_STEPS;k++)
					Population[i].gene[j].allele[k] = 4;
			Population[i].inS4=999; // Reset fitness value (S4), just set to high value
			Population[i].chrSteps=999; // Reset fitness value (steps), set to high value
			Population[i].fitnessScore = 1; // Low value = bad solution, must be positive
			for(j = 0; j < GENETIC_PURSUERS; j++)
				for(k = 0; k < 2; k++)
					Population[i].gene[j].start[k] = Population[0].gene[j].start[k];
			int GeneNr=0;
			for(GeneNr = 0; GeneNr < GENETIC_PURSUERS; GeneNr++){ // For each Gene
				getRandom(&(Population[i].gene[GeneNr]),0); // Generate a random step sequence
			}
		}
		if(isChanged == 1){
			i = 0;
			isChanged = 0;
		}
		else{
			i = GENETIC_POPULATION_SIZE;
		}
		for(; i < GENETIC_POPULATION_SIZE+GENETIC_INCREMENT_POPULATION; i++){ // Calculate fitness for population
			calculateFitness(&Population[i]);
			if(Population[i].inS4 == 0){
				isSolved = 1;
				if(Population[i].chrSteps < GENETIC_STEPS){
					isChanged = 1;
					GENETIC_STEPS = Population[i].chrSteps;
				}
			}
		}
		if(isSolved==1 && GENETIC_POPULATION_SIZE>GENETIC_MIN_POP_SIZE)
			break;
	}
	printf("genAlg\n");
	printf("**** Genetic Algorithm info ****\n");
	printf("Population size:\t%d\n", GENETIC_POPULATION_SIZE);
	printf("Pursuers:\t\t%d\n", GENETIC_PURSUERS);
	printf("Maximum steps:\t\t%d\n", GENETIC_STEPS);
	printf("Maximum generations:\t%d\n", GENETIC_GENERATIONS);
	printf("Convergence %%:\t\t%d\n", abs(GENETIC_CONVERGENCE_PERCENT*100));
	printf("Mutation %%:\t\t%d\n", abs(GENETIC_MUTATION_PROBABILITY*100));
	sortPopulation(Population, GENETIC_POPULATION_SIZE); // Sort the population after fitness
	for(currentGeneration = 0; currentGeneration < GENETIC_GENERATIONS; currentGeneration++){
		/*** New generation ***/
		/*
		calculateFitness(&Population[0]);
		printStates();
		printf("Generation %d\n", currentGeneration);
		*/
		addToNewPopulation(Population[0]); // Elite selection
		addToNewPopulation(Population[1]); // Elite selection
		while(NewPopLocation < GENETIC_POPULATION_SIZE)
			doReproduce(); // Reproduction
		sortPopulation(New_Population, GENETIC_POPULATION_SIZE); // Sort the new population after fitness
		/*** Swap populations ***/
		int i;
		for(i = 0; i < GENETIC_POPULATION_SIZE;i++)
			Population[i] = New_Population[i]; // Overwrite old population with new
		memcpy(Population, New_Population, sizeof New_Population);
		/*
		if(currentGeneration%1==0){
			printf("Best Fitness: %f, States: %d, steps: %d\n", Population[0].fitnessScore, Population[0].inS4, Population[0].chrSteps);
			printf("Compare Fitness (%d): %f, States: %d, steps: %d\n", abs(GENETIC_POPULATION_SIZE*GENETIC_CONVERGENCE_PERCENT), Population[abs(GENETIC_POPULATION_SIZE*GENETIC_CONVERGENCE_PERCENT)].fitnessScore, Population[abs(GENETIC_POPULATION_SIZE*GENETIC_CONVERGENCE_PERCENT)].inS4, Population[abs(GENETIC_POPULATION_SIZE*GENETIC_CONVERGENCE_PERCENT)].chrSteps);
			printf("Worst Fitness (%d): %f, States: %d, steps: %d\n", GENETIC_POPULATION_SIZE, Population[GENETIC_POPULATION_SIZE-1].fitnessScore, Population[GENETIC_POPULATION_SIZE-1].inS4, Population[GENETIC_POPULATION_SIZE-1].chrSteps);
		}
		*/
		if(Population[0].inS4 == 0 && Population[abs(GENETIC_POPULATION_SIZE*GENETIC_CONVERGENCE_PERCENT)].inS4 == 0) // If a complete solution has been found, check if convergence level is reached
				if((Population[0].chrSteps==Population[abs(GENETIC_POPULATION_SIZE*GENETIC_CONVERGENCE_PERCENT)].chrSteps)) // If 90% of the population has the same number of steps, no need to continue to do more generations.
					if(Population[0].fitnessScore==Population[abs(GENETIC_POPULATION_SIZE*GENETIC_CONVERGENCE_PERCENT)].fitnessScore) // Redundant check, check fitness score
						break;
		NewPopLocation=0;
	}
	printf("%d generations used.\n", currentGeneration);
	printf("Best Fitness: %f, States: %d, steps: %d\n", Population[0].fitnessScore, Population[0].inS4, Population[0].chrSteps);
	printf("Compare Fitness: %f, States: %d, steps: %d\n", Population[abs(GENETIC_POPULATION_SIZE*GENETIC_CONVERGENCE_PERCENT)].fitnessScore, Population[abs(GENETIC_POPULATION_SIZE*GENETIC_CONVERGENCE_PERCENT)].inS4, Population[abs(GENETIC_POPULATION_SIZE*GENETIC_CONVERGENCE_PERCENT)].chrSteps);
	printf("Worst Fitness: %f, States: %d, steps: %d\n", Population[GENETIC_POPULATION_SIZE-1].fitnessScore, Population[GENETIC_POPULATION_SIZE-1].inS4, Population[GENETIC_POPULATION_SIZE-1].chrSteps);
	solution[0]=GENETIC_PURSUERS; // Write number of pursuers to solution
	solution[1]=GENETIC_STEPS; // Write maximum number of steps to solution
	if(Population[0].chrSteps<=MAX_SIZE_SOLUTION){
		doDecode(&Population[0], solution); // Decode solution to positions
		solution[1]=calculateStates(solution); // Calculate states, and update steps to minimum
	}
	else
		solution[1]=Population[0].chrSteps; // If the solution was to long, or not found, no need to return path
	/*** Free allocated memory ***/
	free(Population);
	free(New_Population);
	/*** Free memory for NodeMatrix ***/
	for(i = 0; i < ROWS;i++)
		free(NodeMatrix[i]);
	free(NodeMatrix);
	return;
}