Exemple #1
0
static TACommandVerdict lgamma_r_cmd(TAThread thread,TAInputStream stream)
{
    double x, res;
    int signp;

    x = readDouble(&stream);

    START_TARGET_OPERATION(thread);

    errno = 0;
    res = lgamma_r(x, &signp);

    END_TARGET_OPERATION(thread);

    writeInt(thread, errno);
    writeDouble(thread, res);
    writeInt(thread, signp);
    sendResponse(thread);

    return taDefaultVerdict;
}
Exemple #2
0
 void read(osgGA::GUIEventAdapter& event)
 {
     event.setEventType((osgGA::GUIEventAdapter::EventType)readUInt());
     event.setKey(readUInt());
     event.setButton(readUInt());
     int x = readInt();
     int y = readInt();
     int width = readUInt();
     int height = readUInt();
     event.setWindowRectangle(x,y,width,height);
     float xmin = readFloat();
     float ymin = readFloat();
     float xmax = readFloat();
     float ymax = readFloat();
     event.setInputRange(xmin,ymin,xmax,ymax);
     event.setX(readFloat());
     event.setY(readFloat());
     event.setButtonMask(readUInt());
     event.setModKeyMask(readUInt());
     event.setTime(readDouble());
 }
/**
 * Read an object of the type specified by the type char.
 * @param c type of argument to read
 * @return a Java representation of the argument
 */
QVariant OSCByteArrayToMsgConverter::readArgument(char ac)
{
    switch(ac)
    {
        case 'i' :
                return readInteger();
        case 'h' :
                return readBigInteger();
        case 'f' :
                return readFloat();
        case 'd' :
                return readDouble();
        case 's' :
                return readString();
        case 'c' :
                return readChar();
        case 'T' :
                return QVariant(TRUE);
        case 'F' :
                return QVariant(FALSE);
    }
    return QVariant();
}
Exemple #4
0
static TACommandVerdict cbrt_cmd(TAThread thread,TAInputStream stream)
{
    double x, res;

    // Prepare

    x = readDouble(&stream);
    
    START_TARGET_OPERATION(thread);
    
    // Execute

    res = cbrt(x);
    
    END_TARGET_OPERATION(thread);
    
    // Response
    
    writeDouble(thread, res);

    sendResponse(thread);
    return taDefaultVerdict;
}
 void ObjectDataInput::readInternal(int typeId, double *object) {
     *object = readDouble();
 }
Exemple #6
0
        void read(osg::Matrix& matrix)
        {
            matrix(0,0) = readDouble();
            matrix(0,1) = readDouble();
            matrix(0,2) = readDouble();
            matrix(0,3) = readDouble();

            matrix(1,0) = readDouble();
            matrix(1,1) = readDouble();
            matrix(1,2) = readDouble();
            matrix(1,3) = readDouble();

            matrix(2,0) = readDouble();
            matrix(2,1) = readDouble();
            matrix(2,2) = readDouble();
            matrix(2,3) = readDouble();

            matrix(3,0) = readDouble();
            matrix(3,1) = readDouble();
            matrix(3,2) = readDouble();
            matrix(3,3) = readDouble();

            osg::notify(osg::NOTICE)<<"readMatrix = "<<matrix<<std::endl;

        }
void ChanneledJsonDecompressor::read(dynamic* outObj) {
  uint8_t curType = readType();

  // Map
  if (inRange(curType, TYPE_SHORT_MAP_BASE, SHORT_TYPE_LENGTH)) {
    readMap(curType - TYPE_SHORT_MAP_BASE, outObj);
    return;
  }
  if (curType == TYPE_LONG_MAP) {
    int64_t mapLength = readVarInt(CHANNEL_MAPLEN);
    readMap(mapLength, outObj);
    return;
  }

  // Array
  if (inRange(curType, TYPE_SHORT_ARRAY_BASE, SHORT_TYPE_LENGTH)) {
    readArray(curType - TYPE_SHORT_ARRAY_BASE, outObj);
    return;
  }
  if (curType == TYPE_LONG_ARRAY) {
    int64_t arrayLength = readVarInt(CHANNEL_ARRAYLEN);
    readArray(arrayLength, outObj);
    return;
  }

  // String - different types
  if (curType == TYPE_MEMOISED_STRING) {
    int memoisedIdx = readVarInt(CHANNEL_MEMOSTRS);
    *outObj = memoStrings_[memoisedIdx];
    return;
  }

  if (inRange(curType, TYPE_SHORT_STRING_BASE, SHORT_TYPE_LENGTH)) {
    uint32_t stringLength = curType - TYPE_SHORT_STRING_BASE;
    readString(stringLength, CHANNEL_STRS, outObj);
    memoStrings_[memoStringsNext_] = outObj->asString();
    ++memoStringsNext_;
    return;
  }

  if (curType == TYPE_STRING_SIZE) {
    uint32_t stringLength = readVarInt(CHANNEL_STRLEN);
    readString(stringLength, CHANNEL_STRS, outObj);
    memoStrings_[memoStringsNext_] = outObj->asString();
    ++memoStringsNext_;
    return;
  }

  // Boolean
  if (curType == TYPE_BOOL_TRUE) {
    *outObj = true;
    return;
  }

  if (curType == TYPE_BOOL_FALSE) {
    *outObj = false;
    return;
  }

  // Integer
  if (inRange(curType, TYPE_SMALL_INT_BASE, SHORT_TYPE_LENGTH)) {
    *outObj = curType - TYPE_SMALL_INT_BASE;
    return;
  }

  if (curType == TYPE_LONG_INT) {
    *outObj = readVarInt(CHANNEL_INTS);
    return;
  }

  // None
  if (curType == TYPE_NONE) {
    *outObj = nullptr;
    return;
  }

  // Double
  if (curType == TYPE_DOUBLE) {
    readDouble(outObj);
    return;
  }

  //TODO(noamler) - unknown type error handling. Log?
  *outObj = nullptr;

}
Exemple #8
0
void SfzRegion::readOp(const QString& b, const QString& data)
      {
      int i = data.toInt();

      if (b == "amp_veltrack")
            readDouble(data, &amp_veltrack);
      else if (b == "ampeg_delay")
            readDouble(data, &ampeg_delay);
      else if (b == "ampeg_start")
            readDouble(data, &ampeg_start);
      else if (b == "ampeg_attack")
            readDouble(data, &ampeg_attack);
      else if (b == "ampeg_hold")
            readDouble(data, &ampeg_hold);
      else if (b == "ampeg_decay")
            readDouble(data, &ampeg_decay);
      else if (b == "ampeg_sustain")
            readDouble(data, &ampeg_sustain);
      else if (b == "ampeg_release")
            readDouble(data, &ampeg_release);
      else if (b == "sample") {
            sample = path + "/" + data;
            sample.replace("\\", "/");
            }
      else if (b == "key") {
            lokey = readKey(data);
            hikey = lokey;
            pitch_keycenter = lokey;
            }
      else if (b == "pitch_keytrack")
            ;
      else if (b == "trigger") {
            if (data == "attack")
                  trigger = Trigger::ATTACK;
            else if (data == "release")
                  trigger = Trigger::RELEASE;
            else if (data == "first")
                  trigger = Trigger::FIRST;
            else if (data == "legato")
                  trigger = Trigger::LEGATO;
            else
                  qDebug("SfzRegion: bad trigger value: %s", qPrintable(data));
            }
      else if (b == "loop_mode") {
            if (data == "no_loop")
                  loop_mode = LoopMode::NO_LOOP;
            else if (data == "one_shot")
                  loop_mode = LoopMode::ONE_SHOT;
            else if (data == "loop_continuous")
                  loop_mode = LoopMode::CONTINUOUS;
            else if (data == "loop_sustain")
                  loop_mode = LoopMode::SUSTAIN;
            if (loop_mode != LoopMode::ONE_SHOT)
                  qDebug("SfzRegion: loop_mode <%s>", qPrintable(data));
            }
      else if(b == "loop_start")
            readInt(data, &loopStart);
      else if(b == "loop_end")
            readInt(data, &loopEnd);
      else if (b.startsWith("on_locc")) {
            int idx = b.mid(7).toInt();
            if (idx >= 0 && idx < 128)
                  on_locc[idx] = i;
            }
      else if (b.startsWith("on_hicc")) {
            int idx = b.mid(7).toInt();
            if (idx >= 0 && idx < 128)
                  on_hicc[idx] = i;
            }
      else if (b.startsWith("locc")) {
            int idx = b.mid(7).toInt();
            if (idx >= 0 && idx < 128)
                  locc[idx] = i;
            }
      else if (b.startsWith("hicc")) {
            int idx = b.mid(7).toInt();
            if (idx >= 0 && idx < 128)
                  hicc[idx] = i;
            }
      else if (b == "off_mode") {
            if (data == "fast")
                  off_mode = OffMode::FAST;
            else if (data == "normal")
                  off_mode = OffMode::NORMAL;
            }
      else if (b == "tune")
            tune = i;
      else if (b == "rt_decay")
            readDouble(data, &rt_decay);
      else if (b == "hirand")
            readDouble(data, &hirand);
      else if (b == "lorand")
            readDouble(data, &lorand);
      else if (b == "volume")
            readDouble(data, &volume);
      else if (b == "pitch_keycenter")
            pitch_keycenter = readKey(data);
      else if (b == "lokey")
            lokey = readKey(data);
      else if (b == "hikey")
            hikey = readKey(data);
      else if (b == "lovel")
            lovel = i;
      else if (b == "hivel")
            hivel = i;
      else if (b == "off_by")
            off_by = i;
      else if (b == "group")
            group = i;
      else if (b == "lochan")
            lochan = i;
      else if (b == "hichan")
            hichan = i;
      else if (b == "note_offset")
            note_offset = i;
      else if (b == "octave_offset")
            octave_offset = i;
      else if (b == "seq_length")
            seq_length = i;
      else if (b == "seq_position")
            seq_position = i;
      else if (b == "transpose")
            transpose = i;
      else
            qDebug("SfzRegion: unknown opcode <%s>", qPrintable(b));
      }
Exemple #9
0
template <> double Reader::read<double>()
{
  return readDouble();
}
void GetSpeed(node_struct* node, char * sumo_id)
{
    commandGetVehicleVariable(sumo_id, VAR_SPEED);
    double speed_double = readDouble();
    node->mob->speed = speed_double;
}
int main (void)
{
	FILE *inputStream = NULL,			/* File pointer for input file */
		 *outputStream = NULL;			/* File pointer for output file */

	int studentId1 = 0,
		studentId2 = 0,
		studentId3 = 0,
		studentId4 = 0,
		studentId5 = 0;					/* 5 student IDs */

	int studentClassStanding1 = 0,
		studentClassStanding2 = 0,
		studentClassStanding3 = 0,
		studentClassStanding4 = 0,
		studentClassStanding5 = 0;		/* 5 student class standings */

	double studentGpa1 = 0.0,
		   studentGpa2 = 0.0,
		   studentGpa3 = 0.0,
		   studentGpa4 = 0.0,
		   studentGpa5 = 0.0;			/* 5 student GPAs */

	double studentAge1 = 0.0,
		   studentAge2 = 0.0,
		   studentAge3 = 0.0,
		   studentAge4 = 0.0,
		   studentAge5 = 0.0;			/* 5 student ages */

	double sumGpa = 0.0,				/* sum of the 5 student's GPA */
		   sumClassStanding = 0.0,		/* sum of the 5 student's class standing */
		   sumAge = 0.0;				/* sum of the 5 student's ages */

	double meanGpa = 0.0,				/* mean of the 5 student's GPA */
		   meanClassStanding = 0.0,		/* mean of the 5 student's class standing */
		   meanAge = 0.0;				/* mean of the 5 student's ages */

	double deviationGpa1 = 0.0,		
		   deviationGpa2 = 0.0,
		   deviationGpa3 = 0.0,
		   deviationGpa4 = 0.0,
		   deviationGpa5 = 0.0;			/* deviation of each student's GPA */

	double varianceGpa = 0.0,			/* variance of the 5 student's GPA */
		   standardDeviationGpa = 0.0,	/* standard variance of the 5 student's GPA */
		   maxStudentGpa = 0.0,			/* maximum number out of the 5 student's GPA */
		   minStudentGpa = 0.0;			/* minimum number out of the 5 student's GPA */


	/* Opens an input file "input.dat" for reading; */
	inputStream = openFileStream (INPUT_FILE, INPUT_FILE_MODE);

    /* Opens an output file "output.dat" for writing; */
	outputStream = openFileStream (OUTPUT_FILE, OUTPUT_FILE_MODE);

	/* Checks the condition if files were successfully opened.
	 * If either file didn't open, then an error message is prompted,
	 * otherwise program will continue to execute other operations. */
	if (inputStream == NULL || outputStream == NULL)
	{
		/* Files were not successfully opened and prompts user of the error.
		 * Program will not continue to execute the rest of the program. */
		printf ("Error: Not able to open files!\n");
	}
	else
	{
		/* Reads five records from the input file (input.dat); */
	
		/* Student 1 */
		studentId1 = readInteger (inputStream);
		studentGpa1 = readDouble (inputStream);
		studentClassStanding1 = readInteger (inputStream);
		studentAge1 = readDouble (inputStream);

		/* Student 2 */
		studentId2 = readInteger (inputStream);
		studentGpa2 = readDouble (inputStream);
		studentClassStanding2 = readInteger (inputStream);
		studentAge2 = readDouble (inputStream);

		/* Student 3 */
		studentId3 = readInteger (inputStream);
		studentGpa3 = readDouble (inputStream);
		studentClassStanding3 = readInteger (inputStream);
		studentAge3 = readDouble (inputStream);

		/* Student 4 */
		studentId4 = readInteger (inputStream);
		studentGpa4 = readDouble (inputStream);
		studentClassStanding4 = readInteger (inputStream);
		studentAge4 = readDouble (inputStream);

		/* Student 5 */
		studentId5 = readInteger (inputStream);
		studentGpa5 = readDouble (inputStream);
		studentClassStanding5 = readInteger (inputStream);
		studentAge5 = readDouble (inputStream);

		/* Calculates the sum of the GPAs; */
		sumGpa = calculateSum (studentGpa1, studentGpa2, 
							   studentGpa3, studentGpa4, 
							   studentGpa5);

		/* Calculates the sum of the class standings; */
		sumClassStanding = calculateSum (studentClassStanding1, studentClassStanding2, 
										 studentClassStanding3, studentClassStanding4, 
										 studentClassStanding5);

		/* Calculates the sum of the ages; */
		sumAge = calculateSum (studentAge1, studentAge2,
								studentAge3, studentAge4,
								studentAge5);

		/* Calculates the mean of the GPAs; */
		meanGpa = calculateMean (sumGpa, NUMBER_OF_STUDENTS);

		/* Calculates the mean of the class standings; */
		meanClassStanding = calculateMean (sumClassStanding, NUMBER_OF_STUDENTS);

		/* Calculates the mean of the ages; */
		meanAge = calculateMean (sumAge, NUMBER_OF_STUDENTS);
 
		/* Calculates the deviation of each GPA from the mean */
		deviationGpa1 = calculateDeviation (studentGpa1, meanGpa);
		deviationGpa2 = calculateDeviation (studentGpa2, meanGpa);
		deviationGpa3 = calculateDeviation (studentGpa3, meanGpa);
		deviationGpa4 = calculateDeviation (studentGpa4, meanGpa);
		deviationGpa5 = calculateDeviation (studentGpa5, meanGpa);

		/* Calculates the variance of the GPAs */
		varianceGpa = calculateVariance (deviationGpa1, deviationGpa2,
										 deviationGpa3, deviationGpa4,
										 deviationGpa5, NUMBER_OF_STUDENTS);

		/* Calculates the standard deviation of the GPAs; */
		standardDeviationGpa = calculateStandardDeviation (varianceGpa);
	
		/* Determines the min of the GPAs; */
		minStudentGpa = findMin (studentGpa1, studentGpa2, 
								 studentGpa3, studentGpa4, 
								 studentGpa5);	

		/* Determines the max of the GPAs; */
		maxStudentGpa = findMax (studentGpa1, studentGpa2, 
								 studentGpa3, studentGpa4, 
								 studentGpa5);

		/* Writing the result to the output file (output.dat) */
		printDouble (outputStream, meanGpa);
		printDouble (outputStream, meanClassStanding);
		printDouble (outputStream, meanAge);
		printDouble (outputStream, standardDeviationGpa);
		printDouble (outputStream, minStudentGpa);
		printDouble (outputStream, maxStudentGpa);

		/* Closes the input and output files (i.e. input.dat and output.dat) */
		closeFileStream (inputStream);
		closeFileStream (outputStream);
	}

	return 0;
}
Exemple #12
0
inline void nl_readDouble(char* x, int& y, NLdouble z)		{ readDouble(x, y, z); }
float SerialReceiver::readFloat(uint8_t itemNum) {
    return (float) readDouble(itemNum);
}
void InText::readFloat(float& d, PhysicalInStream& stream)
{
  double f;
  readDouble(f, stream);
  d = static_cast<float>(f);
}
Exemple #15
0
void RPCModel::ParseXML(const std::string &filename) 
{
    TiXmlDocument doc(filename);
    doc.LoadFile();

    TiXmlNode *root = doc.FirstChildElement("isd");
    TiXmlNode *image = root->FirstChildElement("RPB")->FirstChildElement("IMAGE");
    readDouble(image->FirstChildElement("SAMPOFFSET"), &rpcInfo.dfSAMP_OFF);
    readDouble(image->FirstChildElement("LINEOFFSET"), &rpcInfo.dfLINE_OFF);
    readDouble(image->FirstChildElement("SAMPSCALE"), &rpcInfo.dfSAMP_SCALE);
    readDouble(image->FirstChildElement("LINESCALE"), &rpcInfo.dfLINE_SCALE);
    readDouble(image->FirstChildElement("LONGOFFSET"), &rpcInfo.dfLONG_OFF);
    readDouble(image->FirstChildElement("LATOFFSET"), &rpcInfo.dfLAT_OFF);
    readDouble(image->FirstChildElement("HEIGHTOFFSET"), &rpcInfo.dfHEIGHT_OFF);
    readDouble(image->FirstChildElement("LONGSCALE"), &rpcInfo.dfLONG_SCALE);
    readDouble(image->FirstChildElement("LATSCALE"), &rpcInfo.dfLAT_SCALE);
    readDouble(image->FirstChildElement("HEIGHTSCALE"), &rpcInfo.dfHEIGHT_SCALE);

    readDouble(image->FirstChildElement("LINENUMCOEFList")->FirstChildElement("LINENUMCOEF"), rpcInfo.adfLINE_NUM_COEFF, 20);
    readDouble(image->FirstChildElement("LINEDENCOEFList")->FirstChildElement("LINEDENCOEF"), rpcInfo.adfLINE_DEN_COEFF, 20);
    readDouble(image->FirstChildElement("SAMPNUMCOEFList")->FirstChildElement("SAMPNUMCOEF"), rpcInfo.adfSAMP_NUM_COEFF, 20);
    readDouble(image->FirstChildElement("SAMPDENCOEFList")->FirstChildElement("SAMPDENCOEF"), rpcInfo.adfSAMP_DEN_COEFF, 20);

    TiXmlNode *bbox = root->FirstChildElement("IMD")->FirstChildElement("BAND_P");
    readDouble(bbox->FirstChildElement("ULLON"), &rpcInfo.dfMIN_LONG);
    readDouble(bbox->FirstChildElement("URLON"), &rpcInfo.dfMAX_LONG);
    readDouble(bbox->FirstChildElement("ULLAT"), &rpcInfo.dfMAX_LAT);
    readDouble(bbox->FirstChildElement("LLLAT"), &rpcInfo.dfMIN_LAT);

    TiXmlNode *addoffs = root->FirstChildElement("ADDOFFS");
    readDouble(addoffs->FirstChildElement("OFFSX"), &offsx);
    readDouble(addoffs->FirstChildElement("OFFSY"), &offsy);
}
void readDataFromFile( UDP req, char *filename )
{
   FILE *fp;
   char line[2048], *p1, *p2, *p3;
   int len, fldid, lineNum=1, fldtype;
   short  sVal;
   int    iVal;
   long   lVal;
   float  fVal;
   double dVal;

   fp = fopen( filename, "r" );
   if( fp == NULL )
   {
      printf( "open data file %s error : %s\n", filename, strerror(errno) );
      exit( 0 );
   }

   memset( line, 0, sizeof(line) );
   while( fgets( line, sizeof(line), fp ) != NULL )
   {
      fldid = (int)readLong(line);
      p2 = strchr( line, '=' );
      p1 = p2 + 1;
      while( *p1 == ' ' ) p1++;

      fldtype = readKeyword( &p1 );
      switch( fldtype )
      {
      case UDT_STRING:
         p2 = strchr( p1, '(' );
         if( p2 == NULL )
         {
            printf( "LINE %d Invalid format, expected char is (\n", lineNum );
            exit( 0 );
         }
         p1 = p2 + 1;
         p2 = strchr( p1, '"' );
         if( p2 == NULL )
         {
            printf( "LINE %d Invalid format, expected char is '\"' \n", lineNum );
            exit( 0 );
         }
         p3 = strchr( p2+1, '"' );
         if( p3 == NULL )
         {
            printf( "LINE %d Invalid format, not enought char '\"' \n", lineNum );
            exit( 0 );
         }
         len = p3-p2-1;
         p3 = strchr( p2+1, ')' );
         if( p3 == NULL )
         {
            printf( "LINE %d Invalid format, needed char is )\n", lineNum );
            exit( 0 );
         }
         UDO_AddField( req, fldid, UDT_STRING, p2+1, len );
         break;
      case UDT_SHORT:
         p2 = strchr( p1, '(' );
         if( p2 == NULL )
         {
            printf( "LINE %d Invalid format, expected char is (\n", lineNum );
            exit( 0 );
         }
         p3 = strchr( p2+1, ')' );
         if( p3 == NULL )
         {
            printf( "LINE %d Invalid format, needed char is )\n", lineNum );
            exit( 0 );
         }
         sVal = (short)readLong( p2+1 );
         UDO_AddField( req, fldid, UDT_SHORT, (char*)&sVal, len );
         break;
      case UDT_INT:
         p2 = strchr( p1, '(' );
         if( p2 == NULL )
         {
            printf( "LINE %d Invalid format, expected char is (\n", lineNum );
            exit( 0 );
         }
         p3 = strchr( p2+1, ')' );
         if( p3 == NULL )
         {
            printf( "LINE %d Invalid format, needed char is )\n", lineNum );
            exit( 0 );
         }
         iVal = (int)readLong( p2+1 );
         UDO_AddField( req, fldid, UDT_INT, (char*)&iVal, len );
         break;
      case UDT_LONG:
         p2 = strchr( p1, '(' );
         if( p2 == NULL )
         {
            printf( "LINE %d Invalid format, expected char is (\n", lineNum );
            exit( 0 );
         }
         p3 = strchr( p2+1, ')' );
         if( p3 == NULL )
         {
            printf( "LINE %d Invalid format, needed char is )\n", lineNum );
            exit( 0 );
         }
         lVal = readLong( p2+1 );
         UDO_AddField( req, fldid, UDT_LONG, (char*)&lVal, len );
         break;
      case UDT_FLOAT:
         p2 = strchr( p1, '(' );
         if( p2 == NULL )
         {
            printf( "LINE %d Invalid format, expected char is (\n", lineNum );
            exit( 0 );
         }
         p3 = strchr( p2+1, ')' );
         if( p3 == NULL )
         {
            printf( "LINE %d Invalid format, needed char is )\n", lineNum );
            exit( 0 );
         }
         fVal = (float)readDouble( p2+1 );
         UDO_AddField( req, fldid, UDT_FLOAT, (char*)&fVal, len );
         break;
      case UDT_DOUBLE:
         p2 = strchr( p1, '(' );
         if( p2 == NULL )
         {
            printf( "LINE %d Invalid format, expected char is (\n", lineNum );
            exit( 0 );
         }
         p3 = strchr( p2+1, ')' );
         if( p3 == NULL )
         {
            printf( "LINE %d Invalid format, needed char is )\n", lineNum );
            exit( 0 );
         }
         dVal = readDouble( p2+1 );
         UDO_AddField( req, fldid, UDT_DOUBLE, (char*)&dVal, len );
         break;
      default:
         printf( "LINE %d Invalid datatype\n", lineNum );
         exit( 0 );
      }
      memset( line, 0, sizeof(line) );
      lineNum++;
   }

   fclose( fp );
}
Exemple #17
0
// Returns a new reference.
static PyObject*
decode_val(DecodeBuffer* input, TType type, PyObject* typeargs, long string_limit, long container_limit) {
    switch (type) {

    case T_BOOL: {
        int8_t v = readByte(input);
        if (INT_CONV_ERROR_OCCURRED(v)) {
            return NULL;
        }

        switch (v) {
        case 0:
            Py_RETURN_FALSE;
        case 1:
            Py_RETURN_TRUE;
        // Don't laugh.  This is a potentially serious issue.
        default:
            PyErr_SetString(PyExc_TypeError, "boolean out of range");
            return NULL;
        }
        break;
    }
    case T_I08: {
        int8_t v = readByte(input);
        if (INT_CONV_ERROR_OCCURRED(v)) {
            return NULL;
        }

        return PyInt_FromLong(v);
    }
    case T_I16: {
        int16_t v = readI16(input);
        if (INT_CONV_ERROR_OCCURRED(v)) {
            return NULL;
        }
        return PyInt_FromLong(v);
    }
    case T_I32: {
        int32_t v = readI32(input);
        if (INT_CONV_ERROR_OCCURRED(v)) {
            return NULL;
        }
        return PyInt_FromLong(v);
    }

    case T_I64: {
        int64_t v = readI64(input);
        if (INT_CONV_ERROR_OCCURRED(v)) {
            return NULL;
        }
        // TODO(dreiss): Find out if we can take this fastpath always when
        //               sizeof(long) == sizeof(long long).
        if (CHECK_RANGE(v, LONG_MIN, LONG_MAX)) {
            return PyInt_FromLong((long) v);
        }

        return PyLong_FromLongLong(v);
    }

    case T_DOUBLE: {
        double v = readDouble(input);
        if (v == -1.0 && PyErr_Occurred()) {
            return false;
        }
        return PyFloat_FromDouble(v);
    }

    case T_STRING: {
        Py_ssize_t len = readI32(input);
        char* buf;
        if (!readBytes(input, &buf, len)) {
            return NULL;
        }
        if (!check_length_limit(len, string_limit)) {
            return NULL;
        }

        if (is_utf8(typeargs))
            return PyUnicode_DecodeUTF8(buf, len, 0);
        else
            return PyString_FromStringAndSize(buf, len);
    }

    case T_LIST:
    case T_SET: {
        SetListTypeArgs parsedargs;
        int32_t len;
        PyObject* ret = NULL;
        int i;
        bool use_tuple = false;

        if (!parse_set_list_args(&parsedargs, typeargs)) {
            return NULL;
        }

        if (!checkTypeByte(input, parsedargs.element_type)) {
            return NULL;
        }

        len = readI32(input);
        if (!check_length_limit(len, container_limit)) {
            return NULL;
        }

        use_tuple = type == T_LIST && parsedargs.immutable;
        ret = use_tuple ? PyTuple_New(len) : PyList_New(len);
        if (!ret) {
            return NULL;
        }

        for (i = 0; i < len; i++) {
            PyObject* item = decode_val(input, parsedargs.element_type, parsedargs.typeargs, string_limit, container_limit);
            if (!item) {
                Py_DECREF(ret);
                return NULL;
            }
            if (use_tuple) {
                PyTuple_SET_ITEM(ret, i, item);
            } else  {
                PyList_SET_ITEM(ret, i, item);
            }
        }

        // TODO(dreiss): Consider biting the bullet and making two separate cases
        //               for list and set, avoiding this post facto conversion.
        if (type == T_SET) {
            PyObject* setret;
            setret = parsedargs.immutable ? PyFrozenSet_New(ret) : PySet_New(ret);
            Py_DECREF(ret);
            return setret;
        }
        return ret;
    }

    case T_MAP: {
        int32_t len;
        int i;
        MapTypeArgs parsedargs;
        PyObject* ret = NULL;

        if (!parse_map_args(&parsedargs, typeargs)) {
            return NULL;
        }

        if (!checkTypeByte(input, parsedargs.ktag)) {
            return NULL;
        }
        if (!checkTypeByte(input, parsedargs.vtag)) {
            return NULL;
        }

        len = readI32(input);
        if (!check_length_limit(len, container_limit)) {
            return NULL;
        }

        ret = PyDict_New();
        if (!ret) {
            goto error;
        }

        for (i = 0; i < len; i++) {
            PyObject* k = NULL;
            PyObject* v = NULL;
            k = decode_val(input, parsedargs.ktag, parsedargs.ktypeargs, string_limit, container_limit);
            if (k == NULL) {
                goto loop_error;
            }
            v = decode_val(input, parsedargs.vtag, parsedargs.vtypeargs, string_limit, container_limit);
            if (v == NULL) {
                goto loop_error;
            }
            if (PyDict_SetItem(ret, k, v) == -1) {
                goto loop_error;
            }

            Py_DECREF(k);
            Py_DECREF(v);
            continue;

            // Yuck!  Destructors, anyone?
loop_error:
            Py_XDECREF(k);
            Py_XDECREF(v);
            goto error;
        }

        if (parsedargs.immutable) {
            PyObject* thrift = PyImport_ImportModule("thrift.Thrift");
            PyObject* cls = NULL;
            PyObject* arg = NULL;
            if (!thrift) {
                goto error;
            }
            cls = PyObject_GetAttrString(thrift, "TFrozenDict");
            if (!cls) {
                goto error;
            }
            arg = PyTuple_New(1);
            PyTuple_SET_ITEM(arg, 0, ret);
            return PyObject_CallObject(cls, arg);
        }

        return ret;

error:
        Py_XDECREF(ret);
        return NULL;
    }

    case T_STRUCT: {
        StructTypeArgs parsedargs;
        if (!parse_struct_args(&parsedargs, typeargs)) {
            return NULL;
        }

        return decode_struct(input, Py_None, parsedargs.klass, parsedargs.spec, string_limit, container_limit);
    }

    case T_STOP:
    case T_VOID:
    case T_UTF16:
    case T_UTF8:
    case T_U64:
    default:
        PyErr_SetString(PyExc_TypeError, "Unexpected TType");
        return NULL;
    }
}
Exemple #18
0
double SerialTunnel::readDouble() {
  double d = 0;
  readDouble(&d);
  return d;
}
Exemple #19
0
Waypoint* GTM::fetchNextWaypoint()
{
    /* Point to the actual waypoint offset */
    if ( VSIFSeekL(pGTMFile, actualWaypointOffset, SEEK_SET) != 0)
        return nullptr;

    const double latitude = readDouble(pGTMFile);
    const double longitude = readDouble(pGTMFile);

    char name[11];
    if ( !readFile( name, 1, 10 ) )
        return nullptr;

    /* Trim string name */
    {
        int i = 9;  // Used after for.
        for( ; i >= 0; --i)
        {
            if (name[i] != ' ')
            {
                name[i+1] = '\0';
                break;
            }
        }
        if (i < 0)
            name[0] = '\0';
    }

    /* Read String Length */
    const unsigned short stringSize = readUShort(pGTMFile);
    /* Read Comment String */
    char* comment = static_cast<char *>(
        VSI_MALLOC2_VERBOSE(sizeof(char), stringSize+1) );
    if( comment == nullptr )
        return nullptr;
    if ( stringSize != 0 && !readFile( comment, 1, sizeof(char)*stringSize ) )
    {
        CPLFree(comment);
        return nullptr;
    }
    comment[stringSize] = '\0';

    /* Read Icon */
    const unsigned short icon = readUShort(pGTMFile);

    /* Display number */
    readUChar(pGTMFile);

    /* Waypoint date */

    GIntBig wptdate = readInt(pGTMFile);
    if (wptdate != 0)
        wptdate += GTM_EPOCH;

    /* Rotation text angle */
    readUShort(pGTMFile);

    /* Altitude */
    const float altitude = readFloat(pGTMFile);

    Waypoint* poWaypoint = new Waypoint(latitude, longitude, altitude,
                                        name, comment, (int) icon, wptdate);

    /* Set actual waypoint offset to the next it there is one */
    ++waypointFetched;
    if (waypointFetched < nwpts)
    {
        actualWaypointOffset +=
            8 + 8 + 10 + 2 + stringSize + 2 + 1 + 4 + 2 + 4 + 2;
    }

    CPLFree(comment);
    return poWaypoint;
}
void
readSubspace (Subspace *s, const char* trainingFile, int quiet)
{
    int i, j, headerSize, rowDim, colDim;
    char junk[FILE_LINE_LENGTH], text[FILE_LINE_LENGTH];
    char** header;
    float ftemp;
    FILE* file;

    headerSize = 255;
    header = (char**) malloc (sizeof(char*) * headerSize);
    assert (header);
    for (i = 0; i < headerSize; i++) {
        header[i] = (char*) malloc(sizeof(char) * FILE_LINE_LENGTH);
        assert (header[i]);
    }

    file = fopen (trainingFile, "rb");

    if (!file) {
        printf("Error: could not open file <%s>\n", trainingFile);
        exit(1);
    }

    for (i = 0; i < headerSize; i++)
        fgets(header[i], FILE_LINE_LENGTH, file);

    if (!quiet) {
        printf("\nTraining Header File is:\n");
        for (i = 0; i < TRAINING_HEADER_ENTRIES; i++)
            printf("   Line %d: %s", i, header[i]);
    }

    sscanf(header[7], "%s%s%d", junk, junk, &s->basisDim);
    sscanf(header[4], "%s%*s%s", junk, text);

    if (strcmp(text, "NO") == 0)
        s->useLDA = 0;
    else
        s->useLDA = 1;


    /*START: Changed by Zeeshan: for LPP*/
    sscanf(header[10], "%s%*s%s", junk, text);

    if (strcmp(text, "NO") == 0)
        s->useLPP = 0;
    else
        s->useLPP = 1;

    sscanf(header[11], "%s%s%d", junk, junk, &s->neighbourCount);
    sscanf(header[12], "%s%*s%s", junk, text);
    s->lppDistance = strdup(text);
    sscanf(header[13], "%s%s%d", junk, junk, &s->lppKeepNVectors);
    sscanf(header[14], "%s%s%d", junk, junk, &s->useAdaptiveK);
    /*END: Changed by Zeeshan: for LPP*/

    /*START: 	Changed by Zeeshan: for ICA*/
    sscanf(header[15], "%s%*s%s", junk, text);

    if (strcmp(text, "NO") == 0)
        s->useICA = 0;
    else
        s->useICA = 1;

    sscanf(header[16], "%s%s%d", junk, junk, &s->blockSize);
    sscanf(header[17], "%s%s%e", junk, junk, &ftemp);
    s->learningRate = (double)ftemp;
    sscanf(header[18], "%s%s%d", junk, junk, &s->iterations);
    sscanf(header[19], "%s%s%d", junk, junk, &s->arch);
    /*END: 		Changed by Zeeshan: for ICA*/


    readInt (file,&rowDim);
    s->numPixels = rowDim;
    DEBUG_INT (3, "Vector size", rowDim);
    s->mean = makeMatrix(rowDim, 1);
    for (i = 0; i < (s->mean)->row_dim; i++) {
        readDouble (file, &ME(s->mean,i,0));
    }

    readInt (file,&rowDim);
    s->values = makeMatrix (rowDim, 1);
    for (i = 0; i < (s->values)->row_dim; i++) {
        readDouble (file, &ME(s->values,i,0));
    }

    rowDim = s->numPixels;
    readInt (file,&colDim);
    s->basis = makeMatrix (rowDim, colDim);
    for (i = 0; i < (s->basis)->col_dim; i++) {
        for (j = 0; j < (s->basis)->row_dim; j++) {
            readDouble (file, &ME(s->basis, j, i));
        }
    }

    if(s->useICA)
    {
        /*START: 	Changed by Zeeshan: for ICA*/
        readInt (file,&rowDim);
        readInt (file,&colDim);
        s->ica2Basis = makeMatrix (rowDim, colDim);
        for (i = 0; i < (s->ica2Basis)->col_dim; i++) {
            for (j = 0; j < (s->ica2Basis)->row_dim; j++) {
                readDouble (file, &ME(s->ica2Basis, j, i));
            }
        }
        /*END: 		Changed by Zeeshan: for ICA*/
    }
    fclose(file);
}
Exemple #21
0
template <> double Reader::read<double>(DECFILELINE)
{
  return readDouble(ARGFILELINE);
}
Exemple #22
0
        void initFileObject(lua_State* L)
        {
            luaL_newmetatable(L, meta<File>());
            // Duplicate the metatable on the stack.
            lua_pushvalue(L, -1);
            // metatable.__index = metatable
            lua_setfield(L, -2, "__index");

            // Put the members into the metatable.
            const luaL_Reg functions[] = {
                {"__gc", [](lua_State* L) { return script::wrapped<File>(L, 1)->gc(L); }},
                {"__index", [](lua_State* L) { return script::wrapped<File>(L, 1)->index(L); }},
                {"__newindex", [](lua_State* L) { return script::wrapped<File>(L, 1)->newindex(L); }},
                {"__tostring", [](lua_State* L) { return script::wrapped<File>(L, 1)->tostring(L); }},
                {"__pairs", [](lua_State* L) { return script::wrapped<File>(L, 1)->pairs(L); }},
                {"close", [](lua_State* L)
                {
                    auto file = script::ptr<File>(L, 1);
                    file->close();
                    return 0;
                }},
                {"readUnsigned8", [](lua_State* L)
                {
                    auto file = script::ptr<File>(L, 1);

                    uint8_t value;
                    if(file->readUnsigned8(value))
                    {
                        script::push(L, value);
                        return 1;
                    }
                    return 0;
                }},
                {"readUnsigned16", [](lua_State* L)
                {
                    auto file = script::ptr<File>(L, 1);

                    uint16_t value;
                    if(file->readUnsigned16(value))
                    {
                        script::push(L, value);
                        return 1;
                    }
                    return 0;
                }},
                {"readUnsigned32", [](lua_State* L)
                {
                    auto file = script::ptr<File>(L, 1);

                    uint32_t value;
                    if(file->readUnsigned32(value))
                    {
                        script::push(L, value);
                        return 1;
                    }
                    return 0;
                }},
                {"readInt8", [](lua_State* L)
                {
                    auto file = script::ptr<File>(L, 1);

                    int8_t value;
                    if(file->readInt8(value))
                    {
                        script::push(L, value);
                        return 1;
                    }
                    return 0;
                }},
                {"readInt16", [](lua_State* L)
                {
                    auto file = script::ptr<File>(L, 1);

                    int16_t value;
                    if(file->readInt16(value))
                    {
                        script::push(L, value);
                        return 1;
                    }
                    return 0;
                }},
                {"readInt32", [](lua_State* L)
                {
                    auto file = script::ptr<File>(L, 1);

                    int32_t value;
                    if(file->readInt32(value))
                    {
                        script::push(L, value);
                        return 1;
                    }
                    return 0;
                }},
                {"readFloat", [](lua_State* L)
                {
                    auto file = script::ptr<File>(L, 1);

                    float value;
                    if(file->readFloat(value))
                    {
                        script::push(L, value);
                        return 1;
                    }
                    return 0;
                }},
                {"readDouble", [](lua_State* L)
                {
                    auto file = script::ptr<File>(L, 1);

                    double value;
                    if(file->readDouble(value))
                    {
                        script::push(L, value);
                        return 1;
                    }
                    return 0;
                }},
                {"readString", [](lua_State* L)
                {
                    auto file = script::ptr<File>(L, 1);
                    auto blockSize = script::get<int>(L, 2);

                    std::string buffer(blockSize, 0);
                    if(file->readString(buffer))
                    {
                        lua_pushlstring(L, buffer.data(), buffer.size());
                        return 1;
                    }
                    return 0;
                }},
                {"readLine", [](lua_State* L)
                {
                    auto file = script::ptr<File>(L, 1);

                    std::string value;
                    if(file->readLine(value))
                    {
                        script::push(L, value.c_str());
                        return 1;
                    }
                    return 0;
                }},
                {"readFully", [](lua_State* L)
                {
                    auto file = script::ptr<File>(L, 1);

                    // Get current position.
                    auto pos = file->tell();
                    if(pos == -1)
                    {
                        return 0;
                    }

                    // Length to read = position of end - current.
                    auto length = 0;
                    if(!file->seek(pos, FileSeekMode::End))
                    {
                        return 0;
                    }
                    length = file->tell() - pos;
                    if(!file->seek(pos, FileSeekMode::Start))
                    {
                        return 0;
                    }

                    // Read the entire file into a string.
                    std::string buf(length, 0);
                    if(file->readString(buf))
                    {
                        lua_pushlstring(L, buf.data(), buf.size());
                        return 1;
                    }
                    return 0;
                }},
                {"writeUnsigned8", [](lua_State* L)
                {
                    auto file = script::ptr<File>(L, 1);
                    auto value = script::get<int>(L, 2);

                    script::push(L, file->writeUnsigned8(value));
                    return 1;
                }},
                {"writeUnsigned16", [](lua_State* L)
                {
                    auto file = script::ptr<File>(L, 1);
                    auto value = script::get<int>(L, 2);

                    script::push(L, file->writeUnsigned16(value));
                    return 1;
                }},
                {"writeUnsigned32", [](lua_State* L)
                {
                    auto file = script::ptr<File>(L, 1);
                    auto value = script::get<int>(L, 2);

                    script::push(L, file->writeUnsigned32(value));
                    return 1;
                }},
                {"writeInt8", [](lua_State* L)
                {
                    auto file = script::ptr<File>(L, 1);
                    auto value = script::get<int>(L, 2);

                    script::push(L, file->writeInt8(value));
                    return 1;
                }},
                {"writeInt16", [](lua_State* L)
                {
                    auto file = script::ptr<File>(L, 1);
                    auto value = script::get<int>(L, 2);

                    script::push(L, file->writeInt16(value));
                    return 1;
                }},
                {"writeInt32", [](lua_State* L)
                {
                    auto file = script::ptr<File>(L, 1);
                    auto value = script::get<int>(L, 2);

                    script::push(L, file->writeInt32(value));
                    return 1;
                }},
                {"writeFloat", [](lua_State* L)
                {
                    auto file = script::ptr<File>(L, 1);
                    auto value = script::get<double>(L, 2);

                    script::push(L, file->writeFloat((float) value));
                    return 1;
                }},
                {"writeDouble", [](lua_State* L)
                {
                    auto file = script::ptr<File>(L, 1);
                    auto value = script::get<double>(L, 2);

                    script::push(L, file->writeDouble(value));
                    return 1;
                }},
                {"writeString", [](lua_State* L)
                {
                    auto file = script::ptr<File>(L, 1);
                    size_t length = 0;
                    const char* buffer = luaL_checklstring(L, 2, &length);
                    std::string value(buffer, buffer + length);
                    script::push(L, file->writeString(value));
                    return 1;
                }},
                {"writeLine", [](lua_State* L)
                {
                    auto file = script::ptr<File>(L, 1);
                    size_t length = 0;
                    const char* buffer = luaL_checklstring(L, 2, &length);
                    std::string value(buffer, buffer + length);
                    script::push(L, file->writeLine(value));
                    return 1;
                }},
                {"tell", [](lua_State* L)
                {
                    auto file = script::ptr<File>(L, 1);
                    script::push(L, int(file->tell()));
                    return 1;
                }},
                {"seek", [](lua_State* L)
                {
                    auto file = script::ptr<File>(L, 1);
                    auto position = script::get<int>(L, 2);
                    auto mode = FileSeekMode(script::get<int>(L, 3));
                    script::push(L, file->seek(position, mode));
                    return 1;
                }},
                {"flush", [](lua_State* L)
                {
                    auto file = script::ptr<File>(L, 1);
                    file->flush();
                    return 0;
                }},
                {nullptr, nullptr},
            };
            luaL_setfuncs(L, functions, 0);

            lua_pop(L, 1);
                
            // Push plum namespace.
            lua_getglobal(L, "plum");

            // plum.File = <function create>
            script::push(L, "File");
            lua_pushcfunction(L, [](lua_State* L)
            {
                auto filename = script::get<const char*>(L, 1);
                auto mode = FileOpenMode(script::get<int>(L, 2));
                auto f = new File(filename, mode);
                // Failure.
                if(!f->isActive())
                {    
                    delete f;
                    return 0;
                }

                script::push(L, f, LUA_NOREF);
                return 1;
            });
            lua_settable(L, -3);

            // Pop plum namespace.
            lua_pop(L, 1);
        }
void  readRunoff()
//
//  Input:   none
//  Output:  none
//  Purpose: reads saved state of all subcatchments from a hot start file.
//
{
    int    i, j, k;
    double x[6];
    FILE*  f = Fhotstart1.file;

    for (i = 0; i < Nobjects[SUBCATCH]; i++)
    {
        // Ponded depths & runoff (4 elements)
        for (j = 0; j < 3; j++)
        {
            if ( !readDouble(&Subcatch[i].subArea[j].depth, f) ) return;
        }
        if ( !readDouble(&Subcatch[i].newRunoff, f) ) return;

        // Infiltration state (max. of 6 elements)
        for (j=0; j<6; j++) if ( !readDouble(&x[j], f) ) return;
        infil_setState(i, InfilModel, x);

        // Groundwater state (4 elements)
        if ( Subcatch[i].groundwater != NULL )
        {
            for (j=0; j<4; j++) if ( !readDouble(&x[j], f) ) return;
            gwater_setState(i, x);
        }

        // Snowpack state (5 elements for each of 3 snow surfaces)
        if ( Subcatch[i].snowpack != NULL )
        {
            for (j=0; j<3; j++) 
            {
                for (k=0; k<5; k++) if ( !readDouble(&x[k], f) ) return;
                snow_setState(i, j, x);
            }
        }

        // Water quality
        if ( Nobjects[POLLUT] > 0 ) 
        {
            // Runoff quality
            for (j=0; j<Nobjects[POLLUT]; j++)
                if ( ! readDouble(&Subcatch[i].newQual[j], f) ) return;

            // Ponded quality
            for (j=0; j<Nobjects[POLLUT]; j++)
                if ( !readDouble(&Subcatch[i].pondedQual[j], f) ) return;
            
            // Buildup and when streets were last swept
            for (k=0; k<Nobjects[LANDUSE]; k++)
            {
                for (j=0; j<Nobjects[POLLUT]; j++)
                {
                    if ( !readDouble(
                        &Subcatch[i].landFactor[k].buildup[j], f) ) return;
                }
                if ( !readDouble(&Subcatch[i].landFactor[k].lastSwept, f) )
                    return;
            }
        }
    }
}
void testFileMeasurePauli(){
	printf("\nTest file measurePauli:\n");
	
	FILE *fr;
	const int maxLineLength = 20000;
	char line[maxLineLength];
	int totalTests = 0, successTests = 0;

    time_t start_t, end_t;
    double diff_t;
    time(&start_t);

	fr = fopen("tests/tests-c/measurePauliTests.txt", "rt");
	
	while(1){
		struct StabilizerState state;
		int m, outk, outQ;
		double outResult;
		gsl_vector *zeta, *xi, *outh, *outD;
		gsl_matrix *outG, *outGbar, *outJ;
		
		//read n
		if(!readInt(fr, line, maxLineLength, &state.n)){
			break;
		}
		
		//read k
		if(!readInt(fr, line, maxLineLength, &state.k)){
			break;
		}
		
		//read Q
		if(!readInt(fr, line, maxLineLength, &state.Q)){
			break;
		}
		
		//read m
		if(!readInt(fr, line, maxLineLength, &m)){
			break;
		}
		
		//read h
		double vectorDatah[state.n];
		if(!readArray(fr, line, maxLineLength, vectorDatah)){
			break;
		}
		gsl_vector_view vectorViewh = gsl_vector_view_array(vectorDatah, state.n);
		state.h = &vectorViewh.vector;
		
		//read D
		double vectorDataD[state.n];
		if(!readArray(fr, line, maxLineLength, vectorDataD)){
			break;
		}
		gsl_vector_view vectorViewD = gsl_vector_view_array(vectorDataD, state.n);
		state.D = &vectorViewD.vector;
		
		//read zeta
		double vectorDatazeta[state.n];
		if(!readArray(fr, line, maxLineLength, vectorDatazeta)){
			break;
		}
		gsl_vector_view vectorViewzeta = gsl_vector_view_array(vectorDatazeta, state.n);
		zeta = &vectorViewzeta.vector;
		
		//read xi
		double vectorDataxi[state.n];
		if(!readArray(fr, line, maxLineLength, vectorDataxi)){
			break;
		}
		gsl_vector_view vectorViewxi = gsl_vector_view_array(vectorDataxi, state.n);
		xi = &vectorViewxi.vector;
		
		//read G
		double matrixDataG[state.n*state.n];
		if(!readArray(fr, line, maxLineLength, matrixDataG)){
			break;
		}
		gsl_matrix_view matrixViewG = gsl_matrix_view_array(matrixDataG, state.n, state.n);
		state.G = &matrixViewG.matrix;
		
		//read Gbar
		double matrixDataGbar[state.n*state.n];
		if(!readArray(fr, line, maxLineLength, matrixDataGbar)){
			break;
		}
		gsl_matrix_view matrixViewGbar = gsl_matrix_view_array(matrixDataGbar, state.n, state.n);
		state.Gbar = &matrixViewGbar.matrix;
		
		//read J
		double matrixDataJ[state.n*state.n];
		if(!readArray(fr, line, maxLineLength, matrixDataJ)){
			break;
		}
		gsl_matrix_view matrixViewJ = gsl_matrix_view_array(matrixDataJ, state.n, state.n);
		state.J = &matrixViewJ.matrix;
		
		//read outResult
		if(!readDouble(fr, line, maxLineLength, &outResult)){
			break;
		}
		
		//read outk
		if(!readInt(fr, line, maxLineLength, &outk)){
			break;
		}
		
		//read outQ
		if(!readInt(fr, line, maxLineLength, &outQ)){
			break;
		}
		
		//read outh
		double vectorDataouth[state.n];
		if(!readArray(fr, line, maxLineLength, vectorDataouth)){
			break;
		}
		gsl_vector_view vectorViewouth = gsl_vector_view_array(vectorDataouth, state.n);
		outh = &vectorViewouth.vector;
		
		//read outD
		double vectorDataoutD[state.n];
		if(!readArray(fr, line, maxLineLength, vectorDataoutD)){
			break;
		}
		gsl_vector_view vectorViewoutD = gsl_vector_view_array(vectorDataoutD, state.n);
		outD = &vectorViewoutD.vector;
		
		//read outG
		double matrixDataoutG[state.n*state.n];
		if(!readArray(fr, line, maxLineLength, matrixDataoutG)){
			break;
		}
		gsl_matrix_view matrixViewoutG = gsl_matrix_view_array(matrixDataoutG, state.n, state.n);
		outG = &matrixViewoutG.matrix;
		
		//read outGbar
		double matrixDataoutGbar[state.n*state.n];
		if(!readArray(fr, line, maxLineLength, matrixDataoutGbar)){
			break;
		}
		gsl_matrix_view matrixViewoutGbar = gsl_matrix_view_array(matrixDataoutGbar, state.n, state.n);
		outGbar = &matrixViewoutGbar.matrix;
		
		//read outJ
		double matrixDataoutJ[state.n*state.n];
		if(!readArray(fr, line, maxLineLength, matrixDataoutJ)){
			break;
		}
		gsl_matrix_view matrixViewoutJ = gsl_matrix_view_array(matrixDataoutJ, state.n, state.n);
		outJ = &matrixViewoutJ.matrix;
		
		double result = measurePauli(&state, m, zeta, xi);
		
		int isResultWorking = result - outResult < 0.0001 ? 1 : 0;
		int iskWorking = state.k == outk ? 1 : 0;
		int isQWorking = state.Q == outQ ? 1 : 0;
		int ishWorking = isVectorWorking(state.h, outh, state.k);
		int isDWorking = isVectorWorking(state.D, outD, state.k);
		int isGWorking = isMatrixWorking(state.G, outG, state.k);
		int isGbarWorking = isMatrixWorking(state.Gbar, outGbar, state.k);
		int isJWorking = isMatrixWorking(state.J, outJ, state.k);
		
		totalTests++;
		if(isResultWorking*iskWorking*isQWorking*ishWorking*isDWorking*isGWorking*isGbarWorking*isJWorking > 0){
			successTests++;
		}
		else{
			printf("%d %d %d %d %d %d %d %d ", isResultWorking, iskWorking, isQWorking, ishWorking, isDWorking, isGWorking, isGbarWorking, isJWorking);
			printf("Test number %d failed.\n", totalTests);
		}
	}
	
	fclose(fr);
	
	printf("%d out of %d tests successful.\n", successTests, totalTests);

    time(&end_t);
    diff_t = difftime(end_t, start_t);
    printf("Time elapsed: %f s\n", diff_t);

	printf("----------------------\n");
}
Exemple #25
0
status CAFFile::parseDescription(const Tag &, int64_t)
{
	double sampleRate;
	Tag formatID;
	uint32_t formatFlags;
	uint32_t bytesPerPacket;
	uint32_t framesPerPacket;
	uint32_t channelsPerFrame;
	uint32_t bitsPerChannel;
	if (!readDouble(&sampleRate) ||
		!readTag(&formatID) ||
		!readU32(&formatFlags) ||
		!readU32(&bytesPerPacket) ||
		!readU32(&framesPerPacket) ||
		!readU32(&channelsPerFrame) ||
		!readU32(&bitsPerChannel))
		return AF_FAIL;

	if (!channelsPerFrame)
	{
		_af_error(AF_BAD_CHANNELS, "invalid file with 0 channels");
		return AF_FAIL;
	}

	Track *track = getTrack();
	track->f.channelCount = channelsPerFrame;
	track->f.sampleWidth = bitsPerChannel;
	track->f.sampleRate = sampleRate;
	track->f.framesPerPacket = 1;

	if (formatID == "lpcm")
	{
		track->f.compressionType = AF_COMPRESSION_NONE;
		if (formatFlags & kCAFLinearPCMFormatFlagIsFloat)
		{
			if (bitsPerChannel != 32 && bitsPerChannel != 64)
			{
				_af_error(AF_BAD_WIDTH, "invalid bits per sample %d for floating-point audio data", bitsPerChannel);
				return AF_FAIL;
			}
			track->f.sampleFormat = bitsPerChannel == 32 ? AF_SAMPFMT_FLOAT :
				AF_SAMPFMT_DOUBLE;
		}
		else
		{
			track->f.sampleFormat = AF_SAMPFMT_TWOSCOMP;
		}
		track->f.byteOrder = (formatFlags & kCAFLinearPCMFormatFlagIsLittleEndian) ?
			AF_BYTEORDER_LITTLEENDIAN : AF_BYTEORDER_BIGENDIAN;

		if (_af_set_sample_format(&track->f, track->f.sampleFormat, track->f.sampleWidth) == AF_FAIL)
			return AF_FAIL;

		track->f.computeBytesPerPacketPCM();
		return AF_SUCCEED;
	}
	else if (formatID == "ulaw")
	{
		track->f.compressionType = AF_COMPRESSION_G711_ULAW;
		track->f.byteOrder = _AF_BYTEORDER_NATIVE;
		_af_set_sample_format(&track->f, AF_SAMPFMT_TWOSCOMP, 16);
		track->f.bytesPerPacket = channelsPerFrame;
		return AF_SUCCEED;
	}
	else if (formatID == "alaw")
	{
		track->f.compressionType = AF_COMPRESSION_G711_ALAW;
		track->f.byteOrder = _AF_BYTEORDER_NATIVE;
		_af_set_sample_format(&track->f, AF_SAMPFMT_TWOSCOMP, 16);
		track->f.bytesPerPacket = channelsPerFrame;
		return AF_SUCCEED;
	}
	else if (formatID == "ima4")
	{
		track->f.compressionType = AF_COMPRESSION_IMA;
		track->f.byteOrder = _AF_BYTEORDER_NATIVE;
		_af_set_sample_format(&track->f, AF_SAMPFMT_TWOSCOMP, 16);
		initIMACompressionParams();
		return AF_SUCCEED;
	}
	else
	{
		_af_error(AF_BAD_NOT_IMPLEMENTED, "Compression type %s not supported",
			formatID.name().c_str());
		return AF_FAIL;
	}
}
Exemple #26
0
int main(int argc, char *argv[]){

	//Load Road Network from File
	loadData(argv[1]);
	
	//时空数据文件
	FILE* st = fopen(argv[2],"rb");
	//结果
	FILE* result = fopen(argv[3],"w");
	
	FILE* fpp = fopen("./MMTCWhenAtTime.txt","w");
	int when = 13112826;
	
	FILE* loc = fopen("./5.txt","r");
	int tn;
	fscanf(loc,"%d",&tn);
	int i;
	for (i = 0; i < tn; ++i) {
		int d;
		fscanf(loc,"%d",&d);
		fscanf(loc,"%lf %lf",&query[d][0],&query[d][1]);
	}
	
	for (i = 0; i < 10000; ++i) {
		printf("%d\t",i);
		int src;
		long t = clock();
		int flag;
		int ans1;double ans2;
		for (src = 0; src < 1000; ++src) {
			int spNumber = readInt(st);
			//printf("%d\t",spNumber);
			int j;
			for (j = 1; j < spNumber; ++j) {
				path[j] = readInt(st);
				stamp[j] = readDouble(st);
			}
			
			double minp = 1e100;
			int p;
			double sideLen, roadLen;
			for (j = 1; j < spNumber; ++j) {
				double tS, tR;
				double tmp = nodeToEdgeDistanceAndNodeSide(query[i][0],query[i][1],path[j],&tS,&tR);
				if (tmp < minp) {
					minp = tmp;
					sideLen = tS;roadLen = tR;
					p = j;
				}
				if (tmp > 10*minp) break;
			}
			flag = 0;
			if (p < spNumber - 1 && (stamp[p] + (stamp[p+1] - stamp[p])*sideLen/roadLen) > 0) {
				flag = 1;
				ans1 = i;
				ans2 = stamp[p] + (stamp[p+1] - stamp[p])*sideLen/roadLen;
				//printf("%d %lf\n",i,stamp[p] + (stamp[p+1] - stamp[p])*sideLen/roadLen);
			}
		}
		if (flag) {
			fprintf(result,"%d %lf\n",ans1,ans2);
		}
		fprintf(fpp,"%ld\n",clock() - t);
	}
	
	fclose(fpp);
	fclose(loc);
	fclose(st);
	fclose(result);
	return 0;
}
Exemple #27
0
int Worker::handleRequest(queue<double> &inData) {
    double d;
    int status = readDouble(coordSocketFd, d);

    if (status == 0) {
        inData.push(d);
    }

    if (inData.size() >= 3) {
        int frameNumber = (int)inData.front();
        inData.pop();
        int column = (int)inData.front();
        inData.pop();
        int numWorkers = (int)inData.front();
        inData.pop();

        // cerr << "BEFORE " << mView << endl;
        // cerr << "FRAME NUMBER " << frameNumber << endl;

        for (list<Tween*>::iterator it = mTweens.begin(); it != mTweens.end(); it++) {
            Tween* tween = *it;
            tween->init();
            // cerr << "FRAME NUMBER1 " << frameNumber << endl;
                // cerr << "FRAME NUMBER2 " << frameNumber << endl;
            if (tween->type == Tween::TRANSLATE) {
                Vector3D translateDelta = tween->getTweenDelta(frameNumber);
                // cerr << "translateDelta " << translateDelta << endl;
                mEye = mEye + translateDelta;
            } else if (tween->type == Tween::ROTATE) {
                // cerr << "BEFORE " << mView << endl;
                Vector3D rotateDelta = tween->getTweenDelta(frameNumber);
                // cerr << "DELTA " << rotateDelta << endl;
                mView = mView + rotateDelta;
                mSide = mView.cross(mUp);
                // cerr << "AFTER " << mView << endl;
            }
        }


        WorkPool workPool;
        for (int i = column; i < this->width; i += numWorkers) {
            workPool.addJob(i);
        }

        pthread_mutex_t lock;
        pthread_mutex_init(&lock, NULL);

        struct worker_thread_args args;
        args.sendLock = &lock;
        args.workPool = &workPool;
        args.renderer = this->r;
        args.height = this->height;
        args.coordSocketFd = coordSocketFd;

        vector<pthread_t *> workerThreads;

        int numThreads = numCPUs;
        for (int i = 0; i < numThreads; i++) {
            pthread_t *thread = new pthread_t();
            pthread_create(thread, NULL, &testMethod, &args);
            workerThreads.push_back(thread);
        }
        for (int i = 0; i < numThreads; i++) {
            pthread_t *thread = workerThreads[i];
            pthread_join(*thread, NULL);
            delete thread;
        }

        return 1;
    }
    return status;
}
Exemple #28
0
int _tmain(int argc, NLchar **argv)
#endif
{
    NLbyte      buffer[NL_MAX_STRING_LENGTH];
    NLint       count = 0;
    NLbyte      b = (NLbyte)99;
    NLushort    s = 0x1122;
    NLulong     l = 0x11223344;
    NLfloat     f = 12.3141592651f;
    NLdouble    d = 123.12345678901234;
    NLchar      string[NL_MAX_STRING_LENGTH] = TEXT("Hello");
    NLbyte      block[] = {9,8,7,6,5,4,3,2,1,0};

    if(nlInit() == NL_FALSE)
        printErrorExit();

    nlEnable(NL_BIG_ENDIAN_DATA);
    _tprintf(TEXT("nl_big_endian_data = %d\n"), nlGetBoolean(NL_BIG_ENDIAN_DATA));
    _tprintf(TEXT("nlGetString(NL_VERSION) = %s\n\n"), nlGetString(NL_VERSION));
    _tprintf(TEXT("nlGetString(NL_NETWORK_TYPES) = %s\n\n"), nlGetString(NL_NETWORK_TYPES));

    if(nlSelectNetwork(NL_IP) == NL_FALSE)
        printErrorExit();

    _tprintf(TEXT("Short number: %#x, "), s);
    s = nlSwaps(s);
    _tprintf(TEXT("swapped: %#x, "), s);
    s = nlSwaps(s);
    _tprintf(TEXT("swapped back: %#x\n"), s);

    _tprintf(TEXT("Long number: %#lx, "), l);
    l = nlSwapl(l);
    _tprintf(TEXT("swapped: %#lx, "), l);
    l = nlSwapl(l);
    _tprintf(TEXT("swapped back: %#lx\n"), l);

    _tprintf(TEXT("Float number: %.10f, "), f);
    f = nlSwapf(f);
    _tprintf(TEXT("swapped: %.10f, "), f);
    f = nlSwapf(f);
    _tprintf(TEXT("swapped back: %.10f\n"), f);

    _tprintf(TEXT("Double number: %.14f, "), d);
    d = nlSwapd(d);
    _tprintf(TEXT("swapped: %.24f, "), d);
    d = nlSwapd(d);
    _tprintf(TEXT("swapped back: %.14f\n"), d);
    _tprintf(TEXT("\n"));

    _tprintf(TEXT("write byte %d to buffer\n"), b);
    _tprintf(TEXT("write short %#x to buffer\n"), s);
    _tprintf(TEXT("write long %#lx to buffer\n"), l);
    _tprintf(TEXT("write float %f to buffer\n"), f);
    _tprintf(TEXT("write double %.14f to buffer\n"), d);
    _tprintf(TEXT("write string %s to buffer\n"), string);
    _tprintf(TEXT("write block %d%d%d%d%d%d%d%d%d%d to buffer\n"), block[0]
            , block[1], block[2], block[3], block[4], block[5], block[6]
            , block[7], block[8], block[9]);
    _tprintf(TEXT("\n"));
    writeByte(buffer, count, b);
    writeShort(buffer, count, s);
    writeLong(buffer, count, l);
    writeFloat(buffer, count, f);
    writeDouble(buffer, count, d);
    writeString(buffer, count, string);
    writeBlock(buffer, count, block, 10);

    /* reset count to zero to read from start of buffer */
    count = 0;

    readByte(buffer, count, b);
    readShort(buffer, count, s);
    readLong(buffer, count, l);
    readFloat(buffer, count, f);
    readDouble(buffer, count, d);
    readString(buffer, count, string);
    readBlock(buffer, count, block, 10);
    _tprintf(TEXT("read byte %d from buffer\n"), b);
    _tprintf(TEXT("read short %#x from buffer\n"), s);
    _tprintf(TEXT("read long %#lx from buffer\n"), l);
    _tprintf(TEXT("read float %f from buffer\n"), f);
    _tprintf(TEXT("read double %.14f from buffer\n"), d);
    _tprintf(TEXT("read string %s from buffer\n"), string);
    _tprintf(TEXT("read block %d%d%d%d%d%d%d%d%d%d from buffer\n"), block[0]
            , block[1], block[2], block[3], block[4], block[5], block[6]
            , block[7], block[8], block[9]);

    nlShutdown();
    return 0;
}
void OGRXPlaneNavReader::ParseRecord( int nType )
{
    double dfVal = 0.0;
    double dfTrueHeading = 0.0;

    double dfLat = 0.0;
    double dfLon = 0.0;
    RET_IF_FAIL(readLatLon(&dfLat, &dfLon, 1));

    double dfElevation = 0.0;
    /* feet to meter */
    RET_IF_FAIL(readDoubleWithBoundsAndConversion(&dfElevation, 3, "elevation", FEET_TO_METER, -1000., 10000.));

    double dfFrequency = 0.0;
    RET_IF_FAIL(readDouble(&dfFrequency, 4, "frequency"));
    /* NDB frequencies are in kHz. Others must be divided by 100 */
    /* to get a frequency in MHz */
    if (nType != NAVAID_NDB)
        dfFrequency /= 100.;

    double dfRange = 0.0;
    /* nautical miles to kilometer */
    RET_IF_FAIL(readDouble(&dfRange, 5, "range"));
    dfRange *= NM_TO_KM;

    char* pszNavaidId = papszTokens[7];

    if (nType == NAVAID_NDB)
    {
        const char* pszSubType = "";
        CPLString osNavaidName;
        if (EQUAL(papszTokens[nTokens-1], "NDB") ||
            EQUAL(papszTokens[nTokens-1], "LOM") ||
            EQUAL(papszTokens[nTokens-1], "NDB-DME"))
        {
            pszSubType = papszTokens[nTokens-1];
            nTokens--;
        }
        else
        {
            CPLDebug("XPlane", "Unexpected NDB subtype : %s", papszTokens[nTokens-1]);
        }

        osNavaidName = readStringUntilEnd(8);

        if (poNDBLayer)
            poNDBLayer->AddFeature(pszNavaidId, osNavaidName, pszSubType,
                                    dfLat, dfLon,
                                    dfElevation, dfFrequency, dfRange);
    }
    else if (nType == NAVAID_VOR)
    {
        const char* pszSubType = "";
        CPLString osNavaidName;

        double dfSlavedVariation = 0.0;
        RET_IF_FAIL(readDoubleWithBounds(&dfSlavedVariation, 6,
                                         "slaved variation", -180., 180.));

        if (EQUAL(papszTokens[nTokens-1], "VOR") ||
            EQUAL(papszTokens[nTokens-1], "VORTAC") ||
            EQUAL(papszTokens[nTokens-1], "VOR-DME"))
        {
            pszSubType = papszTokens[nTokens-1];
            nTokens--;
        }
        else
        {
            CPLDebug("XPlane", "Unexpected VOR subtype : %s",
                     papszTokens[nTokens-1]);
        }

        osNavaidName = readStringUntilEnd(8);

        if (poVORLayer)
            poVORLayer->AddFeature(pszNavaidId, osNavaidName, pszSubType,
                                   dfLat, dfLon,
                                   dfElevation, dfFrequency,
                                   dfRange, dfSlavedVariation);
    }
    else if (nType == NAVAID_LOC_ILS || nType == NAVAID_LOC_STANDALONE)
    {
        RET_IF_FAIL(readDoubleWithBounds(&dfTrueHeading, 6, "true heading",
                                         0.0, 360.));

        RET_IF_FAIL(assertMinCol(11));

        const char *pszAptICAO = papszTokens[8];
        const char *pszRwyNum = papszTokens[9];
        const char *pszSubType = papszTokens[10];

        if (EQUAL(pszSubType, "ILS-cat-I") ||
            EQUAL(pszSubType, "ILS-cat-II") ||
            EQUAL(pszSubType, "ILS-cat-III") ||
            EQUAL(pszSubType, "LOC") ||
            EQUAL(pszSubType, "LDA") ||
            EQUAL(pszSubType, "SDF") ||
            EQUAL(pszSubType, "IGS") ||
            EQUAL(pszSubType, "LDA-GS"))
        {
            if (poILSLayer)
                poILSLayer->AddFeature(pszNavaidId, pszAptICAO,
                                       pszRwyNum, pszSubType,
                                       dfLat, dfLon,
                                       dfElevation, dfFrequency,
                                       dfRange, dfTrueHeading);
        }
        else
        {
            CPLDebug("XPlane", "Line %d : invalid localizer subtype: '%s'",
                    nLineNumber, pszSubType);
            return;
        }
    }
    else if (nType == NAVAID_GS)
    {
        RET_IF_FAIL(readDouble(&dfVal, 6, "slope & heading"));
        const double dfSlope = (int)(dfVal / 1000) / 100.;
        dfTrueHeading = dfVal - dfSlope * 100000;
        if (dfTrueHeading < 0 || dfTrueHeading > 360)
        {
            CPLDebug("XPlane", "Line %d : invalid true heading '%f'",
                    nLineNumber, dfTrueHeading);
            return;
        }

        RET_IF_FAIL(assertMinCol(11));

        const char *pszAptICAO = papszTokens[8];
        const char *pszRwyNum = papszTokens[9];
        const char *pszSubType = papszTokens[10];

        if (EQUAL(pszSubType, "GS") )
        {
            if (poGSLayer)
                poGSLayer->AddFeature(pszNavaidId, pszAptICAO, pszRwyNum,
                                      dfLat, dfLon,
                                      dfElevation, dfFrequency, dfRange,
                                      dfTrueHeading, dfSlope);
        }
        else
        {
            CPLDebug("XPlane", "Line %d : invalid glideslope subtype: '%s'",
                    nLineNumber, pszSubType);
            return;
        }
    }
    else if (nType == NAVAID_OM || nType == NAVAID_MM || nType == NAVAID_IM)
    {
        const char* pszAptICAO, * pszRwyNum, * pszSubType;

        RET_IF_FAIL(readDoubleWithBounds(&dfTrueHeading, 6, "true heading",
                                         0.0, 360.0));

        RET_IF_FAIL(assertMinCol(11));

        pszAptICAO = papszTokens[8];
        pszRwyNum = papszTokens[9];
        pszSubType = papszTokens[10];

        if (EQUAL(pszSubType, "OM") ||
            EQUAL(pszSubType, "MM") ||
            EQUAL(pszSubType, "IM") )
        {
            if (poMarkerLayer)
                poMarkerLayer->AddFeature(pszAptICAO, pszRwyNum, pszSubType,
                                            dfLat, dfLon,
                                            dfElevation, dfTrueHeading);
        }
        else
        {
            CPLDebug("XPlane",
                     "Line %d : invalid localizer marker subtype: '%s'",
                     nLineNumber, pszSubType);
            return;
        }
    }
    else if (nType == NAVAID_DME_COLOC || nType == NAVAID_DME_STANDALONE)
    {
        const char* pszSubType = "";
        CPLString osNavaidName;

        double dfDMEBias = 0.0;
        RET_IF_FAIL(readDouble(&dfDMEBias, 6, "DME bias"));
        dfDMEBias *= NM_TO_KM;

        if (EQUAL(papszTokens[nTokens-1], "DME-ILS"))
        {
            char* pszAptICAO, * pszRwyNum /* , * pszSubType */;
            if (nTokens != 11)
            {
                CPLDebug("XPlane", "Line %d : not enough columns : %d",
                        nLineNumber, nTokens);
                return;
            }

            pszAptICAO = papszTokens[8];
            pszRwyNum = papszTokens[9];
            /* pszSubType = papszTokens[10]; */

            if (poDMEILSLayer)
                poDMEILSLayer->AddFeature(pszNavaidId, pszAptICAO, pszRwyNum,
                                            dfLat, dfLon,
                                            dfElevation, dfFrequency, dfRange, dfDMEBias);
        }
        else
        {
            if (EQUAL(papszTokens[nTokens-1], "DME"))
            {
                nTokens--;
                if (EQUAL(papszTokens[nTokens-1], "VORTAC") ||
                    EQUAL(papszTokens[nTokens-1], "VOR-DME") ||
                    EQUAL(papszTokens[nTokens-1], "TACAN") ||
                    EQUAL(papszTokens[nTokens-1], "NDB-DME"))
                {
                    /* pszSubType = papszTokens[nTokens-1]; */
                    nTokens--;
                }
            }
            else
            {
                CPLDebug("XPlane", "Line %d : Unexpected DME subtype : %s",
                            nLineNumber, papszTokens[nTokens-1]);
            }

            osNavaidName = readStringUntilEnd(8);

            if (poDMELayer)
                poDMELayer->AddFeature(pszNavaidId, osNavaidName, pszSubType,
                                        dfLat, dfLon,
                                        dfElevation, dfFrequency, dfRange, dfDMEBias);
        }
    }
    else
    {
        CPLAssert(0);
    }

}
// Returns a new reference.
static PyObject*
decode_val(DecodeBuffer* input, TType type, PyObject* typeargs) {
  switch (type) {

  case T_BOOL: {
    int8_t v = readByte(input);
    if (INT_CONV_ERROR_OCCURRED(v)) {
      return NULL;
    }

    switch (v) {
    case 0: Py_RETURN_FALSE;
    case 1: Py_RETURN_TRUE;
    // Don't laugh.  This is a potentially serious issue.
    default: PyErr_SetString(PyExc_TypeError, "boolean out of range"); return NULL;
    }
    break;
  }
  case T_I08: {
    int8_t v = readByte(input);
    if (INT_CONV_ERROR_OCCURRED(v)) {
      return NULL;
    }

    return PyInt_FromLong(v);
  }
  case T_I16: {
    int16_t v = readI16(input);
    if (INT_CONV_ERROR_OCCURRED(v)) {
      return NULL;
    }
    return PyInt_FromLong(v);
  }
  case T_I32: {
    int32_t v = readI32(input);
    if (INT_CONV_ERROR_OCCURRED(v)) {
      return NULL;
    }
    return PyInt_FromLong(v);
  }

  case T_I64: {
    int64_t v = readI64(input);
    if (INT_CONV_ERROR_OCCURRED(v)) {
      return NULL;
    }
    // TODO(dreiss): Find out if we can take this fastpath always when
    //               sizeof(long) == sizeof(long long).
    if (CHECK_RANGE(v, LONG_MIN, LONG_MAX)) {
      return PyInt_FromLong((long) v);
    }

    return PyLong_FromLongLong(v);
  }

  case T_DOUBLE: {
    double v = readDouble(input);
    if (v == -1.0 && PyErr_Occurred()) {
      return false;
    }
    return PyFloat_FromDouble(v);
  }

  case T_STRING: {
    Py_ssize_t len = readI32(input);
    char* buf;
    if (!readBytes(input, &buf, len)) {
      return NULL;
    }

    return PyString_FromStringAndSize(buf, len);
  }

  case T_LIST:
  case T_SET: {
    SetListTypeArgs parsedargs;
    int32_t len;
    PyObject* ret = NULL;
    int i;

    if (!parse_set_list_args(&parsedargs, typeargs)) {
      return NULL;
    }

    if (!checkTypeByte(input, parsedargs.element_type)) {
      return NULL;
    }

    len = readI32(input);
    if (!check_ssize_t_32(len)) {
      return NULL;
    }

    ret = PyList_New(len);
    if (!ret) {
      return NULL;
    }

    for (i = 0; i < len; i++) {
      PyObject* item = decode_val(input, parsedargs.element_type, parsedargs.typeargs);
      if (!item) {
        Py_DECREF(ret);
        return NULL;
      }
      PyList_SET_ITEM(ret, i, item);
    }

    // TODO(dreiss): Consider biting the bullet and making two separate cases
    //               for list and set, avoiding this post facto conversion.
    if (type == T_SET) {
      PyObject* setret;
#if (PY_VERSION_HEX < 0x02050000)
      // hack needed for older versions
      setret = PyObject_CallFunctionObjArgs((PyObject*)&PySet_Type, ret, NULL);
#else
      // official version
      setret = PySet_New(ret);
#endif
      Py_DECREF(ret);
      return setret;
    }
    return ret;
  }

  case T_MAP: {
    int32_t len;
    int i;
    MapTypeArgs parsedargs;
    PyObject* ret = NULL;

    if (!parse_map_args(&parsedargs, typeargs)) {
      return NULL;
    }

    if (!checkTypeByte(input, parsedargs.ktag)) {
      return NULL;
    }
    if (!checkTypeByte(input, parsedargs.vtag)) {
      return NULL;
    }

    len = readI32(input);
    if (!check_ssize_t_32(len)) {
      return false;
    }

    ret = PyDict_New();
    if (!ret) {
      goto error;
    }

    for (i = 0; i < len; i++) {
      PyObject* k = NULL;
      PyObject* v = NULL;
      k = decode_val(input, parsedargs.ktag, parsedargs.ktypeargs);
      if (k == NULL) {
        goto loop_error;
      }
      v = decode_val(input, parsedargs.vtag, parsedargs.vtypeargs);
      if (v == NULL) {
        goto loop_error;
      }
      if (PyDict_SetItem(ret, k, v) == -1) {
        goto loop_error;
      }

      Py_DECREF(k);
      Py_DECREF(v);
      continue;

      // Yuck!  Destructors, anyone?
      loop_error:
      Py_XDECREF(k);
      Py_XDECREF(v);
      goto error;
    }

    return ret;

    error:
    Py_XDECREF(ret);
    return NULL;
  }

  case T_STRUCT: {
    StructTypeArgs parsedargs;
    if (!parse_struct_args(&parsedargs, typeargs)) {
      return NULL;
    }

    PyObject* ret = PyObject_CallObject(parsedargs.klass, NULL);
    if (!ret) {
      return NULL;
    }

    if (!decode_struct(input, ret, parsedargs.spec)) {
      Py_DECREF(ret);
      return NULL;
    }

    return ret;
  }

  case T_STOP:
  case T_VOID:
  case T_UTF16:
  case T_UTF8:
  case T_U64:
  default:
    PyErr_SetString(PyExc_TypeError, "Unexpected TType");
    return NULL;
  }
}