Example #1
0
void RemoteClient::readHeader()
{
	QDataStream ds(&m_buffer, QIODevice::ReadOnly);
	qint32 type;

	ds >> type;
	ds >> m_msgSize;

	switch (type)
	{
	case RemoteControl::Sync:
		cmd = new RemoteControls::Sync(this);
		break;

	default:
		m_sock->close();
		return;
	}

	cmd->setManager(m_manager);

	m_header = true;
}
Example #2
0
void Server::handleData(QTcpSocket* socket, QByteArray data) {
  QDataStream ds(&data, QIODevice::ReadWrite);

  WhiteNetwork::Message type;
  ds >> type;

  if(type == WhiteNetwork::Message::RegisterClient) {
    client_socket = socket;
    qDebug() << "Client";
    start_time = std::chrono::system_clock::now();
    sendJobs();
  }
  else if(type == WhiteNetwork::Message::RegisterWorker) {
    workers_sockets.push_back(socket);
    qDebug() << "Worker";
  }
  else if(type == WhiteNetwork::Message::PixelsData) {
    collectResult(ds);
  }
  else if(type == WhiteNetwork::Message::JobDone) {
    sendJob(socket);
  }
}
Example #3
0
bool ON_SpaceMorph::Ev1Der(
          ON_3dPoint rst,
          ON_3dPoint& xyz,
          ON_3dVector& Dr,
          ON_3dVector& Ds,
          ON_3dVector& Dt
          ) const
{
  // This is a quick estimate of the derivative.
  // Space morphs that are used to deform smooth breps
  // should override this function.
  double d = 1.0e-6;
  double e = 1.0/d;
  ON_3dPoint P;
  ON_3dPoint dr(rst.x+d,rst.y,rst.z);
  ON_3dPoint ds(rst.x,rst.y+d,rst.z);
  ON_3dPoint dt(rst.x,rst.y,rst.z+d);
  P = MorphPoint(rst);
  Dr = e*(MorphPoint(dr) - P);
  Ds = e*(MorphPoint(ds) - P);
  Dt = e*(MorphPoint(dt) - P);
  return true;
}
Example #4
0
void FQTermHttp::httpRead(qint64 done, qint64 total) {
  QByteArray ba = netreply_->readAll();
  QFile file(cacheFileName_);
  if (file.open(QIODevice::ReadWrite | QIODevice::Append)) {
    QDataStream ds(&file);
    ds.writeRawData(ba, ba.size());
    file.close();
  }
  if (total != 0) {
	//m_pDialog->setProgress(done,total);
    int p = done *100 / total;
    if (p - lastPercent_ >= 10 && isPreview_ && QFileInfo(cacheFileName_).suffix().toLower() == "jpg") {
      if (!previewEmitted) {
        emit previewImage(cacheFileName_,true, false);
        previewEmitted = true;
      } else {
        emit previewImage(cacheFileName_,false, false);
      }
      lastPercent_ = p;
    }
    emit percent(p);
  }
}
Example #5
0
inline typename boost::enable_if<boost::mpl::and_<is_array<T>, boost::is_fundamental<typename T::value_type> >, void>::type
write_attribute(H5::H5Object const& object, std::string const& name, T const& value)
{
    typedef typename T::value_type value_type;
    enum { size = T::static_size };

    H5::Attribute attr;
    try {
        H5XX_NO_AUTO_PRINT(H5::AttributeIException);
        attr = object.openAttribute(name);
        if (!has_type<T>(attr) || !has_extent<T>(attr)) {
            // recreate attribute with proper type and size
            object.removeAttr(name);
            throw H5::AttributeIException();
        }
    }
    catch (H5::AttributeIException const&) {
        hsize_t dim[1] = { size };
        H5::DataSpace ds(1, dim);
        attr = object.createAttribute(name, ctype<value_type>::hid(), ds);
    }
    attr.write(ctype<value_type>::hid(), &*value.begin());
}
Example #6
0
int main(int argv, char** args) {
  QApplication app(argv, args);

  QLocalSocket sock;
  QObject::connect(&sock, &QLocalSocket::readyRead, [&sock]() {
    qint64 bytesAvailable = sock.bytesAvailable();
    QByteArray buffer = sock.readAll();
    QDataStream ds(buffer);
    while (bytesAvailable > 0) {
      int num;
      ds >> num;

      qDebug("received %d", num);
      bytesAvailable -= 4;

      if (num == 1) {
        sendData(sock, 2);
        sendData(sock, -1);
      } else if (num == 3) {
        sendData(sock, -3);
      }
    }
  });
Foam::scalar Foam::equationReader::getScalarSrcDictSourceDScalar
(
    const equationReader * eqnReader,
    const label equationIndex,
    const label equationOperationIndex,
    const label maxStoreIndex,
    const label storageOffset
) const
{
    dimensionedScalar ds("noSource", dimless, 0.0);
    const equation& eqn(operator[](equationIndex));
    const equationOperation& eqOp(eqn[equationOperationIndex]);
    label zeroSourceIndex = mag(eqOp.sourceIndex()) - 1;

    word varName(dictLookups_[eqOp.dictLookupIndex()]);
    
    ITstream srcStrm
    (
        dictSources_[zeroSourceIndex].lookup(varName)
    );
    srcStrm >> ds;
    return ds.value() * sign(eqOp.sourceIndex());
}
Example #8
0
bool QDSDataStore::add( const QUniqueId& id )
{
    // Update info file (in an atomic fashion)
    QDSLockedFile infoFile( infoFileName( id ) );
    if ( !infoFile.exists() ) {
        qLog(DataSharing) << "QDSDataStore::add - info file doesn't exist";
        return false;
    }

    int refCount = 0;
    int transCount = 0;
    QString type;
    if ( infoFile.openLocked( QIODevice::ReadWrite ) ) {
        QDataStream ds(&infoFile);
        ds >> refCount;
        ds >> transCount;
        ds >> type;
        infoFile.seek( 0 );
        ds << refCount + 1;
        ds << transCount;
        ds << type;
        infoFile.close();
    } else {
/* decoded base64 stream to put on mysql row , file or network streams */
QList<SPics> OpenImageGroup( const QString datastream_base64   )
{
  
  
  QList<SPics> li;
	QByteArray xcode("");
	xcode.append(datastream_base64);
	quint32 magic, version;
	QByteArray bytes(QByteArray::fromBase64(xcode));   /* decoded base64 string to QByteArray */
	QBuffer buffer(&bytes);
	if (!buffer.open(QIODevice::ReadOnly)) {
		return li;
	}
	QDataStream ds(&buffer);
	/* place header */
	ds.setVersion(QDataStream::Qt_4_2);
	ds >> magic;
	if ( (quint32)SPics::MAGICNUMBER != magic ) {
    qDebug() << "######## SPics::MAGICNUMBER not ok  ";
		buffer.close();
		return li;
	}
	ds >> version;
	if ( (quint32)SPics::VERSION != version ) {
		qDebug() << "######## SPics::VERSION not ok  ";
		buffer.close();
		return li;
	}
  SPics appoint;
	/* place header */
    while (!ds.atEnd()) {
         ds >> appoint;
         li.append(appoint);
    }
	buffer.close();
	return li;
}
Example #10
0
/** 
 * Display the dynamic symbol table 
 */
int		cmd_dynsym()
{
  elfshsect_t	*sct;
  elfsh_Sym	*dynsym;
  regex_t	*tmp;
  int		num;
  char		logbuf[BUFSIZ];

  PROFILER_IN(__FILE__, __FUNCTION__, __LINE__);

  dynsym = elfsh_get_dynsymtab(world.curjob->curfile, &num);
  if (dynsym == NULL)
    RET(-1);
  else
    {      
      sct = elfsh_get_section_by_name(world.curjob->curfile, 
				      ELFSH_SECTION_NAME_ALTDYNSYM, 
				      NULL, NULL, &num);
      if (!sct)
	sct = elfsh_get_section_by_type(world.curjob->curfile, SHT_DYNSYM, 0, 
					NULL, NULL, &num);
      
      if (!sct)
	RET(-1);
      num = num / sizeof(elfsh_Sym);
    }

  snprintf(logbuf, BUFSIZ - 1,
	   " [DYNAMIC SYMBOL TABLE]\n [Object %s]\n [Section %s]\n", 
	   world.curjob->curfile->name, sct->name);
  
  revm_output(logbuf);
  FIRSTREGX(tmp);
  PROFILER_ROUT(__FILE__, __FUNCTION__, __LINE__, 
		ds(world.curjob->curfile, sct,
		   num, tmp, elfsh_get_dynsymbol_name));
}
Example #11
0
int main(int argc, char **argv)
{
  if (!parse_arg(argc, argv)) {
    print_help(argc, argv);
    return EXIT_FAILURE;
  }

  // libMesh::LibMeshInit init(argc, argv);
  libMesh::LibMeshInit init(1, argv); // set argc to 1 to supress PETSc warnings. 
 
  Condor2Dataset ds(init.comm()); 
  ds.PrintInfo();
  
  ds.OpenDataFile(filename_in);
  if (!ds.Valid()) {
    fprintf(stderr, "Invalid input data.\n");
    return EXIT_FAILURE;
  }
  
  VortexExtractor extractor;
  extractor.SetDataset(&ds);
  extractor.SetGaugeTransformation(!nogauge);

  ds.LoadTimeStep(T0, 0);
  extractor.ExtractFaces(0);
  for (int t=T0+span; t<T0+T; t+=span) {
    ds.LoadTimeStep(t, 1);
    extractor.ExtractEdges();
    extractor.ExtractFaces(1);
    extractor.RotateTimeSteps();
    // extractor.TraceOverTime(); 
    // extractor.TraceVirtualCells(); 
    // extractor.SaveVortexLines(filename_out); 
  }

  return EXIT_SUCCESS; 
}
Example #12
0
void kio_digikamdates::special(const QByteArray& data)
{
    bool        folders = (metaData("folders") == "true");
    KUrl        kurl;
    QString     filter;
    QDataStream ds(data);
    ds >> kurl;

    kDebug() << "Entered kio_digikamdates::special";

    Digikam::DatabaseParameters dbParameters(kurl);
    QDBusConnection::sessionBus().registerService(QString("org.kde.digikam.KIO-digikamtags-%1")
            .arg(QString::number(QCoreApplication::instance()->applicationPid())));
    Digikam::DatabaseAccess::setParameters(dbParameters);

    if (folders)
    {

        QMap<QDateTime, int> dateNumberMap = Digikam::DatabaseAccess().db()->getAllCreationDatesAndNumberOfImages();
        QByteArray           ba;
        QDataStream          os(&ba, QIODevice::WriteOnly);
        os << dateNumberMap;
        SlaveBase::data(ba);
    }
    else
    {
        Digikam::ImageLister lister;
        lister.setListOnlyAvailable(metaData("listOnlyAvailableImages") == "true");
        // send data every 200 images to be more responsive
        Digikam::ImageListerSlaveBasePartsSendingReceiver receiver(this, 200);
        lister.list(&receiver, kurl);
        // send rest
        receiver.sendData();
    }

    finished();
}
Example #13
0
QString QcepDatasetModel::indexDescription(const QModelIndex &index) const
{
  if (index.isValid()) {
    QcepDataObject* obj = static_cast<QcepDataObject*>(index.internalPointer());

    if (obj) {
      return tr("(%1,%2,\"%3\")")
          .arg(index.row()).arg(index.column())
          .arg(obj->get_Name());
    } else {
      QcepDatasetPtr ds(m_Dataset);

      if (ds) {
        return tr("(%1,%2,\"%3\")")
            .arg(index.row()).arg(index.column())
            .arg(ds->get_Name());
      } else {
        return "";
      }
    }
  }

  return tr("(%1,%2,null)").arg(index.row()).arg(index.column());
}
Example #14
0
inline typename boost::enable_if<is_multi_array<T>, void>::type
write_attribute(H5::H5Object const& object, std::string const& name, T const& value)
{
    typedef typename T::element value_type;
    enum { rank = T::dimensionality };

    H5::Attribute attr;
    try {
        H5XX_NO_AUTO_PRINT(H5::AttributeIException);
        attr = object.openAttribute(name);
        if (!has_type<T>(attr) || !has_extent<T>(attr, value.shape())) {
            // recreate attribute with proper type and size
            object.removeAttr(name);
            throw H5::AttributeIException();
        }
    }
    catch (H5::AttributeIException const&) {
        hsize_t dim[rank];
        std::copy(value.shape(), value.shape() + rank, dim);
        H5::DataSpace ds(rank, dim);
        attr = object.createAttribute(name, ctype<value_type>::hid(), ds);
    }
    attr.write(ctype<value_type>::hid(), value.origin());
}
Example #15
0
int main()
{
  mem_fun_name::value.reserve(100);
  mem_fun_email::value.reserve(100);
  benchmark::Person t;
  t.set_id(100);
  t.set_name("Name");
  t.set_email("*****@*****.**");

  aj::deserializer<> ds;
  fas::nanospan start = fas::process_nanotime();
  for (size_t i = 0; i < TOTAL_OP; ++i)
  {
    *( ds( fasproto_json(), t, fas::range(buffer) ) )='\0';
  }
  fas::nanospan finish = fas::process_nanotime();
  std::cout << finish - start;
  std::clog << std::endl
            << t.id() << std::endl
            << t.name() << std::endl
            << t.email() << std::endl;

  return 0;
}
Example #16
0
// constructor from data
void LagrangianDSTest::testBuildLagrangianDS5()
{
  std::cout << "--> Test: constructor 5." <<std::endl;
  std::string plugin = "TestPlugin:computeMass";
  SP::DynamicalSystem ds(new LagrangianDS(13, *q0, *velocity0, plugin));
  double time = 1.5;
  ds->initialize("TimeStepping", time);
  CPPUNIT_ASSERT_EQUAL_MESSAGE("testBuildLagrangianDS5A : ", Type::value(*ds) == Type::LagrangianDS, true);
  CPPUNIT_ASSERT_EQUAL_MESSAGE("testBuildLagrangianDS5B : ", ds->number() == 13, true);
  CPPUNIT_ASSERT_EQUAL_MESSAGE("testBuildLagrangianDS5D : ", std11::static_pointer_cast<LagrangianDS>(ds)->getNdof() == 3, true);
  CPPUNIT_ASSERT_EQUAL_MESSAGE("testBuildLagrangianDS5L : ", std11::static_pointer_cast<LagrangianDS>(ds)->getMass() == (*mass), true);

  map<string, bool> isPl = ds->getIsPlugin();

  CPPUNIT_ASSERT_EQUAL_MESSAGE("testBuildLagrangianDS5M : ", isPl["mass"], true);
  CPPUNIT_ASSERT_EQUAL_MESSAGE("testBuildLagrangianDS5Q : ", isPl["fExt"], false);
  CPPUNIT_ASSERT_EQUAL_MESSAGE("testBuildLagrangianDS5R : ", isPl["fInt"], false);
  CPPUNIT_ASSERT_EQUAL_MESSAGE("testBuildLagrangianDS5S : ", isPl["fGyr"], false);
  CPPUNIT_ASSERT_EQUAL_MESSAGE("testBuildLagrangianDS5T : ", isPl["jacobianFIntq"], false);
  CPPUNIT_ASSERT_EQUAL_MESSAGE("testBuildLagrangianDS5T : ", isPl["jacobianFIntVelocity"], false);
  CPPUNIT_ASSERT_EQUAL_MESSAGE("testBuildLagrangianDS5T : ", isPl["jacobianFGyrq"], false);
  CPPUNIT_ASSERT_EQUAL_MESSAGE("testBuildLagrangianDS5T : ", isPl["jacobianFGyrVelocity"], false);
  std::cout << "--> Constructor 5 test ended with success." <<std::endl;
}
QString SaveRichDoc( RichDoc e )
{
	QByteArray bytes;
	QBuffer buffer(&bytes);
	if (!buffer.open(QIODevice::WriteOnly)) {
		return QString();
	}
	QDataStream ds(&buffer);
	/* place header */
	ds.setVersion(QDataStream::Qt_4_2);
	ds << (quint32)RichDoc::MAGICNUMBER;
	ds << (quint32)RichDoc::VERSION;
	/* place header */
  ds << e.html;
  ds << e.style;
             QMapIterator<QString,SPics> i(e.resource);
             while (i.hasNext()) {
                 i.next();
				         SPics record = i.value();
                 ds << record;
             } 
	buffer.close();
	return bytes.toBase64();
}
Example #18
0
void TestQgsField::dataStream()
{
  QgsField original;
  original.setName( QStringLiteral( "name" ) );
  original.setType( QVariant::Int );
  original.setLength( 5 );
  original.setPrecision( 2 );
  original.setTypeName( QStringLiteral( "typename1" ) );
  original.setComment( QStringLiteral( "comment1" ) );
  original.setAlias( QStringLiteral( "alias" ) );
  original.setDefaultValueExpression( QStringLiteral( "default" ) );

  QByteArray ba;
  QDataStream ds( &ba, QIODevice::ReadWrite );
  ds << original;

  QgsField result;
  ds.device()->seek( 0 );
  ds >> result;

  QCOMPARE( result, original );
  QCOMPARE( result.typeName(), original.typeName() ); //typename is NOT required for equality
  QCOMPARE( result.comment(), original.comment() ); //comment is NOT required for equality
}
Example #19
0
QDomElement KWMailMergeDataBase::save(QDomDocument &doc) const
{
    kdDebug()<<"KWMailMergeDataBase::save()"<<endl;
    QDomElement parentElem=doc.createElement("MAILMERGE");
    if (plugin)
    {
        kdDebug()<<"KWMailMergeDataBase::save() There is really something to save"<<endl;
        QDomElement el=doc.createElement(QString::fromLatin1("PLUGIN"));

        QDataStream ds(plugin->info,IO_ReadOnly);
        QString libname;
        ds>>libname;
        el.setAttribute("library",libname);
        parentElem.appendChild(el);
        kdDebug()<<"KWMailMergeDataBase::save() Calling datasource save()"<<endl;
        QDomElement el2=doc.createElement(QString::fromLatin1("DATASOURCE"));
        plugin->save(doc,el2);
        parentElem.appendChild(el2);

    }
    kdDebug()<<"KWMailMergeDataBase::save() leaving now"<<endl;
    return parentElem;
    // if (plugin) plugin->save(parentElem); // Not completely sure, perhaps the database itself has to save something too (JoWenn)
}
Example #20
0
void
KUniqueApplication::processDelayed()
{
  if (dcopClient()->isSuspended())
  {
    // Try again later.
    TQTimer::singleShot( 200, this, TQT_SLOT(processDelayed()));
    return;
  }
  d->processingRequest = true;
  while( !d->requestList.isEmpty() )
  {
     DCOPRequest *request = d->requestList.take(0);
     TQByteArray replyData;
     TQCString replyType;
     if (request->fun == "newInstance()") {
       dcopClient()->setPriorityCall(false);
       TQDataStream ds(request->data, IO_ReadOnly);
       TDECmdLineArgs::loadAppArgs(ds);
       if( !ds.atEnd()) // backwards compatibility
       {
           TQCString asn_id;
           ds >> asn_id;
           setStartupId( asn_id );
       }
       s_handleAutoStarted = false;
       int exitCode = newInstance();
       d->firstInstance = false;
#if defined Q_WS_X11
       if( s_handleAutoStarted )
           TDEStartupInfo::handleAutoAppStartedSending(); // KDE4 remove?
#endif
       TQDataStream rs(replyData, IO_WriteOnly);
       rs << exitCode;
       replyType = "int";
     }
  R operator()(T& t, R r )
  {
    typedef typename T::aspect::template advice_cast<_deserializer_>::type deserializer;
    deserializer ds;

//#warning: TODO: выбор объекта по типу range
    raw_object obj;
    r = ds(raw_object_json(), obj, r);

    if ( ds && obj.is_valid() )
    {
      t.get_aspect().template get<_process_object_>()(t, obj);
    }
    else if ( obj.has_id() )
    {
      t.get_aspect().template get<_invalid_request_>()(t, obj.id );
    }
    else
    {
      t.get_aspect().template get<_invalid_request_>()(t);
    }
    
    return r;
  }
Example #22
0
/*
** Parse command line and setup argc and argv.
** Must be executed with es == psp
*/
_parse() {
  char *ptr;
#asm
  mov     cl,es:[80h]  ; get parameter string length
  mov     ch,0       
  push    cx           ; save it
  inc     cx
  push    cx           ; 1st __alloc() arg
  mov     ax,1
  push    ax           ; 2nd __alloc() arg
  call    __alloc      ; allocate zeroed memory for args
  add     sp,4
  mov     [bp-2],ax    ; ptr = addr of allocated memory
  pop     cx
  push    es           ; exchange
  push    ds           ; es         (source)
  pop     es           ;    and
  pop     ds           ;        ds  (destination)
  mov     si,81h       ; source offset
  mov     di,[bp-2]    ; destination offset
  rep     movsb        ; move string
  mov     al,0
  stosb                ; terminate with null byte
  push    es
  pop     ds           ; restore ds
#endasm
  _vec[0]=_arg1;       /* first arg = "*" */
  while (*ptr) {
    if(isspace(*ptr)) {++ptr; continue;}
    if(_cnt < 20) _vec[_cnt++] = ptr;
    while(*ptr) {
      if(isspace(*ptr)) {*ptr = NULL; ++ptr; break;}
      ++ptr;
      }
    }
  }
Example #23
0
QByteArray CustomBindingParser::compile(const QList<QQmlCustomParserProperty> &properties)
{
    QByteArray result;
    QDataStream ds(&result, QIODevice::WriteOnly);

    ds << properties.count();
    for (int i = 0; i < properties.count(); ++i) {
        const QQmlCustomParserProperty &prop = properties.at(i);
        ds << prop.name();

        Q_ASSERT(prop.assignedValues().count() == 1);
        QVariant value = prop.assignedValues().first();

        Q_ASSERT(value.userType() == qMetaTypeId<QQmlScript::Variant>());
        QQmlScript::Variant v = qvariant_cast<QQmlScript::Variant>(value);
        Q_ASSERT(v.type() == QQmlScript::Variant::Script);
        int bindingId = bindingIdentifier(v, prop.name());
        ds << bindingId;

        ds << prop.location().line;
    }

    return result;
}
Example #24
0
void CustomBinding::componentComplete()
{
    Q_ASSERT(m_target);

    QDataStream ds(m_bindingData);
    int count;
    ds >> count;
    for (int i = 0; i < count; ++i) {
        QString name;
        ds >> name;

        int bindingId;
        ds >> bindingId;

        int line;
        ds >> line;

        QQmlBinding *binding = QQmlBinding::createBinding(QQmlBinding::Identifier(bindingId), m_target, qmlContext(this), QString(), line);

        QQmlProperty property(m_target, name, qmlContext(this));
        binding->setTarget(property);
        QQmlPropertyPrivate::setBinding(property, binding);
    }
}
Example #25
0
void TestQgsFields::dataStream()
{
    QgsField original1;
    original1.setName( "name" );
    original1.setType( QVariant::Int );
    original1.setLength( 5 );
    original1.setPrecision( 2 );
    original1.setTypeName( "typename1" );
    original1.setComment( "comment1" );

    QgsField original2;
    original2.setName( "next name" );
    original2.setType( QVariant::Double );
    original2.setLength( 15 );
    original2.setPrecision( 3 );
    original2.setTypeName( "double" );
    original2.setComment( "comment for field 2" );

    QgsFields originalFields;
    originalFields.append( original1 );
    originalFields.append( original2 );

    QByteArray ba;
    QDataStream ds( &ba, QIODevice::ReadWrite );
    ds << originalFields;

    QgsFields resultFields;
    ds.device()->seek( 0 );
    ds >> resultFields;

    QCOMPARE( resultFields, originalFields );
    QCOMPARE( resultFields.field( 0 ).typeName(), originalFields.field( 0 ).typeName() ); //typename is NOT required for equality
    QCOMPARE( resultFields.field( 0 ).comment(), originalFields.field( 0 ).comment() ); //comment is NOT required for equality
    QCOMPARE( resultFields.field( 1 ).typeName(), originalFields.field( 1 ).typeName() );
    QCOMPARE( resultFields.field( 1 ).comment(), originalFields.field( 1 ).comment() );
}
Example #26
0
bool QtLocalPeer::sendMessage(const QString &message, int timeout)
{
	if (!isClient())
		return false;

	QLocalSocket socket;
	bool connOk = false;
	for(int i = 0; i < 2; i++) {
		// Try twice, in case the other instance is just starting up
		socket.connectToServer(socketName);
		connOk = socket.waitForConnected(timeout/2);
		if (connOk || i)
			break;
		int ms = 250;
#if defined(Q_OS_WIN)
		Sleep(DWORD(ms));
#else
		struct timespec ts = { ms / 1000, (ms % 1000) * 1000 * 1000 };
		nanosleep(&ts, NULL);
#endif
	}
	if (!connOk)
		return false;

#if defined(Q_OS_WIN)
	AllowSetForegroundWindow(ASFW_ANY);
#endif

	QByteArray uMsg(message.toUtf8());
	QDataStream ds(&socket);
	ds.writeBytes(uMsg.constData(), uMsg.size());
	bool res = socket.waitForBytesWritten(timeout);
	res &= socket.waitForReadyRead(timeout);   // wait for ack
	res &= (socket.read(qstrlen(ack)) == ack);
	return res;
}
Example #27
0
void BDT_cuts_norm(){
    
    
    gROOT->ProcessLine(".L ~/cern/project/lhcbStyle.C");
    lhcbStyle();
    
    const std::string filename("/afs/cern.ch/work/a/apmorris/private/cern/ntuples/new_tuples/normalisation_samples/Lb2JpsipK_2011_2012_signal_withbdt.root");
    const std::string treename = "withbdt";
    
    const std::string filenameMC("/afs/cern.ch/work/a/apmorris/private/cern/ntuples/new_tuples/normalisation_samples/Lb2JpsipK_MC_2011_2012_norm_withbdt.root");
    
    TFile* file = TFile::Open( filename.c_str() );
    if( !file ) std::cout << "file " << filename << " does not exist" << std::endl;
    TTree* tree = (TTree*)file->Get( treename.c_str() );
    if( !tree ) std::cout << "tree " << treename << " does not exist" << std::endl;
    
    TFile* fileMC = TFile::Open( filenameMC.c_str() );
    if( !fileMC ) std::cout << "file " << filenameMC << " does not exist" << std::endl;
    TTree* treeMC = (TTree*)fileMC->Get( treename.c_str() );
    if( !treeMC ) std::cout << "tree " << treename << " does not exist" << std::endl;
    
    
    // -- signal, mass shape
    RooRealVar Lambda_b0_DTF_MASS_constr1("Lambda_b0_DTF_MASS_constr1","m(J/#psi pK^{-})", 5550., 5700., "MeV/c^{2}"); 
    RooRealVar Jpsi_M("Jpsi_M","m(#mu#mu)", 3000., 3200., "MeV/c^{2}"); 
    RooRealVar chi_c_M("chi_c_M","m(J/#psi#gamma)", 3400., 3700., "MeV/c^{2}"); 
    RooRealVar mean("mean","mean", 5630., 5610., 5650.);
    RooRealVar sigma1("sigma1","sigma1", 10., 1., 100.);
    RooRealVar sigma2("sigma2","sigma2", 30.0, 5.0, 300.0);
    RooRealVar alpha1("alpha1","alpha1", 1.0, 0.5, 5.0);
    RooRealVar n1("n1","n1", 1.8, 0.2, 15.0);
    RooRealVar alpha2("alpha2","alpha2", -0.5, -5.5, 0.0);
    RooRealVar n2("n2","n2", 0.7, 0.2, 10.0);
    //RooRealVar bkgcat_chic("bkgcat_chic","bkgcat_chic", 0, 100);
    RooRealVar bdtg3("bdtg3", "bdtg3", -1.0, 1.0);
    RooRealVar frac2("frac2","frac2", 0.3, 0., 1.);
    
    RooGaussian gauss1("gauss1","gauss1", Lambda_b0_DTF_MASS_constr1, mean, sigma1);
    RooGaussian gauss2("gauss2","gauss2", Lambda_b0_DTF_MASS_constr1, mean, sigma2);
    RooCBShape cb1("cb1","cb1", Lambda_b0_DTF_MASS_constr1, mean, sigma1, alpha1, n1); 
    RooCBShape cb2("cb2","cb2", Lambda_b0_DTF_MASS_constr1, mean, sigma2, alpha2, n2); 
    RooAddPdf sig("sig", "sig", RooArgList(cb1, cb2), RooArgList( frac2 ));
    RooRealVar cbRatio("cbRatio","cb Ratio", 0.8, 0.1, 1.0);
    RooRealVar sigYield("sigYield","sig Yield", 4e2, 1e0, 1e6);
    RooRealVar bgYield("bgYield","bg Yield", 1e4, 1e0, 1e6);
    
    
    
    //put in values from fit_MC here <<--- DON'T FORGET TO CHANGE THESE IF THE FIT CHANGES!!!
    /*
    EXT PARAMETER                                INTERNAL      INTERNAL
  NO.   NAME      VALUE            ERROR       STEP SIZE       VALUE
   1  alpha1       2.18020e+00   2.85078e-02   1.38432e-04  -2.56034e-01
   2  alpha2      -2.79102e+00   6.74385e-02   1.51818e-04  -1.49177e-02
   3  cbRatio      3.07172e-01   1.49204e-02   1.72642e-04  -5.69984e-01
   4  mean         5.61985e+03   9.58397e-03   5.56682e-05  -9.66293e-02
   5  n1           1.49358e+00   8.14447e-02   2.09300e-04  -9.70542e-01
   6  n2           1.45276e+00   1.09864e-01   2.59028e-04  -8.39538e-01
   7  sigma1       8.46303e+00   1.32851e-01   2.86985e-05  -1.01453e+00
   8  sigma2       4.93976e+00   3.42842e-02   5.03572e-06  -1.44512e+00
    */
    alpha1.setVal( 2.18020e+00 );
    alpha2.setVal( -2.79102e+00 );
    n1.setVal( 1.49358e+00 );
    n2.setVal( 1.45276e+00 );
    frac2.setVal( 3.07172e-01 );
    sigma1.setVal( 8.46303e+00 );
    sigma2.setVal( 4.93976e+00 );
    
    alpha1.setConstant( true );
    alpha2.setConstant( true );
    frac2.setConstant( true );
    n1.setConstant( true );
    n2.setConstant( true );
    sigma1.setConstant( true );
    sigma2.setConstant( true );
    
    // -- bg, mass shape
    RooRealVar a1("a1","a1", -0.1, -0.5, 0.5);
    RooChebychev comb("comb","comb", Lambda_b0_DTF_MASS_constr1, a1);
    RooRealVar mean3("mean3","mean3", 5560., 5500., 5600.);
    RooRealVar sigma3("sigma3","sigma3", 5., 1., 10.);
    RooRealVar frac3("frac3","frac", 0.2, 0.0, 0.3);
    RooGaussian gauss3("gauss3","gauss3", Lambda_b0_DTF_MASS_constr1, mean3, sigma3);
    //RooAddPdf bg("bg","bg", RooArgList(comb), RooArgList(frac3));
    
    // -- add signal & bg
    RooAddPdf pdf("pdf", "pdf", RooArgList(sig, comb), RooArgList( sigYield, bgYield));  
    
    
    double efficiencies1[40];
    double efficiencies1_error[40];
    double bdt_cuts[40];
    double efficiencies2[40];
    double efficiencies2_error[40];
    double sideband_bg_val[40];
    
    double MC_pre = treeMC->GetEntries();
    
    double effvals[40];
    
    
    //loop starting here
    for(int i=0; i < 40; i=i+1) {
        double cut_val = -1.0 + i*0.05;
        //double cut_val = -1.0; // testing
        bdt_cuts[i] = cut_val;
        
        std::stringstream c;
        c << "bdtg3" << " >= " << cut_val;
        const std::string cut = c.str();
        
        //std::cout << cut;
    
        RooArgSet obs;
        obs.add(Lambda_b0_DTF_MASS_constr1);
        //obs.add(chi_c_Mp);
        //obs.add(mass_pK);
        obs.add(Jpsi_M);
        obs.add(chi_c_M);
        obs.add(bdtg3); 
    
        RooDataSet ds("ds","ds", obs, RooFit::Import(*tree), RooFit::Cut(cut.c_str())); 
    
        RooPlot* plot = Lambda_b0_DTF_MASS_constr1.frame();
    
        RooFitResult * result = pdf.fitTo( ds, RooFit::Extended() );
        
        double sig_val = sigYield.getVal();
        double bg_val = bgYield.getVal();
        double sig_error = sigYield.getError();
        double bg_error = bgYield.getError();
        
        double efficiency1 = (sig_val)/(sqrt(sig_val + bg_val));
        efficiencies1[i] = efficiency1;
        
        double efficiency1_error_sq = (pow(sig_error,2)/(sig_val+bg_val) + (pow(sig_val,2)*(pow(sig_error,2)+pow(bg_error,2))/(4*pow((sig_val+bg_val),3))));
        
        double efficiency1_error = sqrt(efficiency1_error_sq);
        efficiencies1_error[i] = efficiency1_error;
        
        /*
        double MC_post = treeMC->GetEntries(cut.c_str());
        
        double eff_val = MC_post/MC_pre; 
        
        //something here to get the sideband background count
        
        
        Lambda_b0_DTF_MASS_constr1.setRange("R", 5650., 5700.);
        RooFitResult * sideband = bg.fitTo( ds, RooFit::Range("R") );
        sideband->Print();
        
        Lambda_b0_DTF_MASS_constr1.setRange("R", 5650., 5700.);
        RooAbsReal* integral = pdf.createIntegral(Lambda_b0_DTF_MASS_constr1, RooFit::Range("R"));
        //std::cout << integral->getVal() << std::endl;
        //std::cout << integral->getError() << std::endl;
        //Double_t sideband_bg_val = integral->getVal();
        //double sideband_bg_error = integral->getError();
        
        std::stringstream r;
        r << "bdtg3" << " >= " << cut_val << " && Lambda_b0_DTF_MASS_constr1 >= 5650 && Lambda_b0_DTF_MASS_constr1 <= 5700";
        const std::string cut2 = r.str();
        
        double integ = tree->GetEntries(cut2.c_str());
        //double integ = integral->getVal();
        
        double efficiency2 = eff_val/(5./2. + sqrt(integ));
        efficiencies2[i] = efficiency2;
        
        effvals[i]=eff_val;
        
        
        std::cout << "\n" << integ << std::endl;
        std::cout << "\n" << eff_val << std::endl;
        std::cout << "\n" << efficiency2 << std::endl;
        */
        
        //double efficiency2_error = efficiency2*sqrt(pow(eff_error/eff_val,2)+(1/(4*sideband_bg_val))*pow(sideband_bg_error/(5/2+sideband_bg_val),2));
        
        //std::cout << "\n\n" << "BDT cut value = " << cut_val << "\n" ;
        //std::cout << "S = " << sig_val << " +/- " << sig_error << "\n" ;
        //std::cout << "B = " << bg_val << " +/- " << bg_error << "\n" ;
        //std::cout << "S/sqrt(S+B) = " << efficiency << " +/- " << efficiency_error << "\n\n" ;
        
        //ds.plotOn( plot );
        //pdf.plotOn( plot );
        
        //RooPlot* plotPullMass = mass.frame();
        
        //plotPullMass->addPlotable( plot->pullHist() );
        //plotPullMass->SetMinimum();
        //plotPullMass->SetMaximum();
        
        //std::cout << cut_val;
    }
    
    
    TCanvas *c1 = new TCanvas(); 
    
    //double zeros[20];
    //for (i=0, i<20, i++) zeros[i]=0.0;
    
    TGraphErrors* graph = new TGraphErrors(40, bdt_cuts, efficiencies1, 0, efficiencies1_error);
    
    graph->SetTitle("S/sqrt(S+B) vs BDTG3 cut");
    //graph->SetMarkerColor(4);
    //graph->SetMarkerStyle(20);
    //graph->SetMarkerSize(1.0);
    graph->GetXaxis()->SetTitle("BDTG3 cut (>)");
    graph->GetXaxis()->SetRangeUser(-1.0,1.0);
    graph->GetYaxis()->SetTitle("S/sqrt(S+B)");
    //graph->Fit("pol5"); 
    graph->Draw("AP");
    c1->SaveAs("~/cern/plots/bdt_cuts_norm/Lb2JpsipK_2011_2012_BDTG3_cuts_S_sqrtS+B.pdf");
    //return c1;
    
    //std::cout << efficiencies1_error[5] << std::endl;
    
    //gStyle->SetOptFit(1011);
    /*TCanvas *c2 = new TCanvas();
    
    TGraph* graph2 = new TGraph(40, bdt_cuts, efficiencies2);
    
    graph2->SetTitle("eff/[5/2+sqrt(B)] vs BDTG3 cut");
    graph2->SetMarkerColor(4);
    graph2->SetMarkerStyle(20);
    graph2->SetMarkerSize(1.0);
    graph2->GetXaxis()->SetTitle("BDTG3 cut (>)");
    graph2->GetXaxis()->SetRangeUser(-1.0,1.0);
    graph2->GetYaxis()->SetTitle("eff/[5/2+sqrt(B)]");
    //graph2->Fit("pol7"); 
    graph2->Draw("AP");
    c2->SaveAs("~/cern/plots/bdt_cuts_norm/Lb2JpsipK_2011_2012_BDTG3_cuts_Punzi.png");
    //return c2;
    */
    
    
    
    /*
    TCanvas* c = new TCanvas();
    
    TPad* pad1 = new TPad("pad1","pad1", 0, 0.3, 1, 1.0);
    pad1->SetBottomMargin(0.1);
    pad1->SetTopMargin(0.1);
    pad1->Draw();
    c->cd();
    TPad* pad2 = new TPad("pad2","pad2", 0, 0, 1, 0.3);
    pad2->SetBottomMargin(0.1);
    pad2->SetTopMargin(0.0);
    pad2->Draw();
    
    
    //pdf.plotOn( plot, RooFit::Components( DfbPdf ), RooFit::LineColor( kRed ), RooFit::LineStyle(kDashed) );
    //pdf.plotOn( plot, RooFit::Components( promptPdf ), RooFit::LineColor( kBlue ), RooFit::LineStyle(kDotted) );
    //pdf.plotOn( plot, RooFit::Components( bgPdf ), RooFit::LineColor( kOrange ), RooFit::LineStyle(kDashDotted) );
    
    pad1->cd();
    plot->Draw();
    
    pad2->cd();
    plotPullMass->Draw("AP");
    
    c->SaveAs(out_file_mass);
    
    RooStats::SPlot* sData = new RooStats::SPlot("sData","An SPlot",
            ds, &pdf, RooArgList(sigYield, bgYield) );
    
    
    RooDataSet * dataw_z = new RooDataSet(ds.GetName(),ds.GetTitle(),&ds,*(ds.get()),0,"sigYield_sw") ;
    */
    /*   
    TCanvas* d = new TCanvas();
    RooPlot* w_mass_chicp = mass_chicp.frame();
    dataw_z->plotOn(w_mass_chicp, RooFit::DataError(RooAbsData::SumW2), RooFit::Binning(20)) ;
    w_mass_chicp->Draw();
    d->SaveAs("m_chicp_sweighted.png");
    
    TCanvas* e = new TCanvas();
    RooPlot* w_mass_pK = mass_pK.frame();
    dataw_z->plotOn(w_mass_pK, RooFit::DataError(RooAbsData::SumW2), RooFit::Binning(20)) ;
    w_mass_pK->Draw();
    e->SaveAs("m_pK_sweighted.png");
    */
    /*
    TCanvas* f = new TCanvas();
    RooPlot* w_mass_Jpsi = mass_Jpsi.frame();
    dataw_z->plotOn(w_mass_Jpsi, RooFit::DataError(RooAbsData::SumW2), RooFit::Binning(20)) ;
    w_mass_Jpsi->Draw();
    f->SaveAs("m_Jpsi_sweighted.png");
    
    TCanvas* g = new TCanvas();
    RooPlot* w_mass_Chic = mass_Chic.frame();
    dataw_z->plotOn(w_mass_Chic, RooFit::DataError(RooAbsData::SumW2), RooFit::Binning(20)) ;
    w_mass_Chic->Draw();
    g->SaveAs("m_Chic_sweighted.png");
    */
    
    
}
Example #28
0
NS_IMETHODIMP
nsTypeAheadFind::Find(const nsAString& aSearchString, bool aLinksOnly,
                      uint16_t* aResult)
{
  *aResult = FIND_NOTFOUND;

  nsCOMPtr<nsIPresShell> presShell (GetPresShell());
  if (!presShell) {
    nsCOMPtr<nsIDocShell> ds (do_QueryReferent(mDocShell));
    NS_ENSURE_TRUE(ds, NS_ERROR_FAILURE);

    presShell = ds->GetPresShell();
    NS_ENSURE_TRUE(presShell, NS_ERROR_FAILURE);
    mPresShell = do_GetWeakReference(presShell);
  }

  nsCOMPtr<nsISelection> selection;
  nsCOMPtr<nsISelectionController> selectionController =
    do_QueryReferent(mSelectionController);
  if (!selectionController) {
    GetSelection(presShell, getter_AddRefs(selectionController),
                 getter_AddRefs(selection)); // cache for reuse
    mSelectionController = do_GetWeakReference(selectionController);
  } else {
    selectionController->GetSelection(
      nsISelectionController::SELECTION_NORMAL, getter_AddRefs(selection));
  }

  if (selection)
    selection->CollapseToStart();

  if (aSearchString.IsEmpty()) {
    mTypeAheadBuffer.Truncate();

    // These will be initialized to their true values after the first character
    // is typed
    mStartFindRange = nullptr;
    mSelectionController = nullptr;

    *aResult = FIND_FOUND;
    return NS_OK;
  }

  bool atEnd = false;    
  if (mTypeAheadBuffer.Length()) {
    const nsAString& oldStr = Substring(mTypeAheadBuffer, 0, mTypeAheadBuffer.Length());
    const nsAString& newStr = Substring(aSearchString, 0, mTypeAheadBuffer.Length());
    if (oldStr.Equals(newStr))
      atEnd = true;
  
    const nsAString& newStr2 = Substring(aSearchString, 0, aSearchString.Length());
    const nsAString& oldStr2 = Substring(mTypeAheadBuffer, 0, aSearchString.Length());
    if (oldStr2.Equals(newStr2))
      atEnd = true;
    
    if (!atEnd)
      mStartFindRange = nullptr;
  }

  if (!mIsSoundInitialized && !mNotFoundSoundURL.IsEmpty()) {
    // This makes sure system sound library is loaded so that
    // there's no lag before the first sound is played
    // by waiting for the first keystroke, we still get the startup time benefits.
    mIsSoundInitialized = true;
    mSoundInterface = do_CreateInstance("@mozilla.org/sound;1");
    if (mSoundInterface && !mNotFoundSoundURL.EqualsLiteral("beep")) {
      mSoundInterface->Init();
    }
  }

#ifdef XP_WIN
  // After each keystroke, ensure sound object is destroyed, to free up memory 
  // allocated for error sound, otherwise Windows' nsISound impl 
  // holds onto the last played sound, using up memory.
  mSoundInterface = nullptr;
#endif

  int32_t bufferLength = mTypeAheadBuffer.Length();

  mTypeAheadBuffer = aSearchString;

  bool isFirstVisiblePreferred = false;

  // --------- Initialize find if 1st char ----------
  if (bufferLength == 0) {
    // If you can see the selection (not collapsed or thru caret browsing),
    // or if already focused on a page element, start there.
    // Otherwise we're going to start at the first visible element
    bool isSelectionCollapsed = true;
    if (selection)
      selection->GetIsCollapsed(&isSelectionCollapsed);

    // If true, we will scan from top left of visible area
    // If false, we will scan from start of selection
    isFirstVisiblePreferred = !atEnd && !mCaretBrowsingOn && isSelectionCollapsed;
    if (isFirstVisiblePreferred) {
      // Get the focused content. If there is a focused node, ensure the
      // selection is at that point. Otherwise, we will just want to start
      // from the caret position or the beginning of the document.
      nsPresContext* presContext = presShell->GetPresContext();
      NS_ENSURE_TRUE(presContext, NS_OK);

      nsCOMPtr<nsIDocument> document =
        do_QueryInterface(presShell->GetDocument());
      if (!document)
        return NS_ERROR_UNEXPECTED;

      nsCOMPtr<nsIDOMWindow> window = do_QueryInterface(document->GetWindow());

      nsCOMPtr<nsIFocusManager> fm = do_GetService(FOCUSMANAGER_CONTRACTID);
      if (fm) {
        nsCOMPtr<nsIDOMElement> focusedElement;
        nsCOMPtr<nsIDOMWindow> focusedWindow;
        fm->GetFocusedElementForWindow(window, false, getter_AddRefs(focusedWindow),
                                       getter_AddRefs(focusedElement));
        // If the root element is focused, then it's actually the document
        // that has the focus, so ignore this.
        if (focusedElement &&
            !SameCOMIdentity(focusedElement, document->GetRootElement())) {
          fm->MoveCaretToFocus(window);
          isFirstVisiblePreferred = false;
        }
      }
    }
  }

  // ----------- Find the text! ---------------------
  // Beware! This may flush notifications via synchronous
  // ScrollSelectionIntoView.
  nsresult rv = FindItNow(nullptr, aLinksOnly, isFirstVisiblePreferred,
                          false, aResult);

  // ---------Handle success or failure ---------------
  if (NS_SUCCEEDED(rv)) {
    if (mTypeAheadBuffer.Length() == 1) {
      // If first letter, store where the first find succeeded
      // (mStartFindRange)

      mStartFindRange = nullptr;
      if (selection) {
        nsCOMPtr<nsIDOMRange> startFindRange;
        selection->GetRangeAt(0, getter_AddRefs(startFindRange));
        if (startFindRange)
          startFindRange->CloneRange(getter_AddRefs(mStartFindRange));
      }
    }
  }
  else {
    // Error sound
    if (mTypeAheadBuffer.Length() > mLastFindLength)
      PlayNotFoundSound();
  }

  SaveFind();
  return NS_OK;
}
Example #29
0
//**********************************************************************
BOOL CBCGPToolTipCtrl::OnDrawIcon (CDC* pDC, CRect rectImage)
{
	ASSERT_VALID (pDC);

#ifndef BCGP_EXCLUDE_RIBBON
	if (m_pRibbonButton != NULL)
	{
		ASSERT_VALID (m_pRibbonButton);
		m_pRibbonButton->OnDrawTooltipImage(pDC, (CBCGPBaseRibbonElement::RibbonImageType) m_nRibbonImageType, rectImage);

		return TRUE;
	}
#endif

	if (m_pHotButton == NULL)
	{
		return FALSE;
	}

	ASSERT_VALID (m_pHotButton);

	CBCGPToolBarImages* pImages = m_pToolBarImages;
	
	CBCGPToolBar* pToolBar = DYNAMIC_DOWNCAST(CBCGPToolBar, m_pHotButton->GetParentWnd());
	if (pToolBar != NULL)
	{
		ASSERT_VALID(pToolBar);
		pToolBar->CheckForButtonImages(m_pHotButton, &pImages);
	}

	if (pImages == NULL)
	{
		return FALSE;
	}

	ASSERT_VALID(pImages);

	CBCGPDrawState ds(CBCGPVisualManager::GetInstance()->IsAutoGrayscaleImages());
	pImages->PrepareDrawImage (ds);

	UINT nSaveStyle = m_pHotButton->m_nStyle;
	BOOL bSaveText = m_pHotButton->m_bText;
	BOOL bSaveImage = m_pHotButton->m_bImage;

	BOOL bSaveLargeIcons = CBCGPToolBar::m_bLargeIcons;
	CBCGPToolBar::m_bLargeIcons = FALSE;

	m_pHotButton->m_bText = FALSE;
	m_pHotButton->m_bImage = TRUE;

	m_pHotButton->m_nStyle = 0;

	m_pHotButton->CBCGPToolbarButton::OnDraw (pDC, rectImage, pImages);

	m_pHotButton->m_nStyle = nSaveStyle;
	m_pHotButton->m_bText = bSaveText;
	m_pHotButton->m_bImage = bSaveImage;

	CBCGPToolBar::m_bLargeIcons = bSaveLargeIcons;

	pImages->EndDrawImage (ds);
	return TRUE;
}
Example #30
0
/** No descriptions */
bool MoTranslator::loadMoFile(QString filename,const char* context)
{
  int max_len = 0;
  int word_size;
  bool big_endian;
  char* orig_string = 0;
  char* trans_string;
  Q_UINT32 magic_number;
  qint32 file_revision;
  qint32 string_number;
  qint32 original_offset;
  qint32 translation_offset;
  QFile mofile(filename);

  if(!qSysInfo(&word_size,&big_endian))
    return false;
  if(mofile.open(IO_ReadOnly) == false)
    return false;
  QDataStream ds(&mofile);
  //read magic number
  ds >> magic_number;
  if(magic_number == 0xde120495)
  {
    //The file has been saved in reversed byte order in comparison
    //to this machine.
    //If this machines byte order is big endian, than the files
    //byte order is little endian and vice versa.
    qDebug("Reverse mo file byte order.");
    if(big_endian == true)
    {
      ds.setByteOrder(QDataStream::BigEndian);
    }
    else
    {
      ds.setByteOrder(QDataStream::LittleEndian);
    }
  }
  else if(magic_number != 0x950412de)
  {
    //wrong file format
    mofile.close();
    qDebug("mo file has wrong magic number.");
    return false;
  }
  //read file revision
  ds >> file_revision;
  if(file_revision != 0)
  {
    //wrong file format
    mofile.close();
    qDebug("Wrong mo file revision.");
    return false;
  }
  //read number of strings
  ds >> string_number;
  //read offset to original strings
  ds >> original_offset;
  //read offset to translation strings
  ds >> translation_offset;
  //We do not use the hash table; in fact, a mo file isn't required to contain a hash
  //table at all.
  qDebug("string number: %u",string_number);
  qDebug("orig offset: %u",original_offset);
  qDebug("trans offset: %u",translation_offset);
  QVector<qint32> orig_table(string_number*2);
  QVector<qint32> trans_table(string_number*2);
  //read original table
  if(ds.device()->at(original_offset))
  {
    for(qint32 i=0;i<string_number;i++)
    {
      ds >> orig_table[i*2];
      ds >> orig_table[i*2+1];
      if(orig_table[i*2] > max_len)
        max_len = orig_table[i*2];
    }
  }
  //read translation table
  if(ds.device()->at(translation_offset))
  {
    for(qint32 i=0;i<string_number;i++)
    {
      ds >> trans_table[i*2];
      ds >> trans_table[i*2+1];
      if(trans_table[i*2] > max_len)
        max_len = trans_table[i*2];
    }
  }

  QString trans;
  orig_string = new char [max_len+10];
  trans_string = new char [max_len+10];
  for(int i=0;i<string_number;i++)
  {
    if(ds.device()->at(orig_table[i*2+1]))
    {
      ds.readRawBytes(orig_string,orig_table[i*2]+1);
      qDebug("orig: %s",orig_string);
    }
    if(ds.device()->at(trans_table[i*2+1]))
    {
      ds.readRawBytes(trans_string,trans_table[i*2]+1);
      trans = QString::fromUtf8(trans_string);
      qDebug("trans: %s",trans.latin1());
     }
     QTranslatorMessage tm(context,orig_string,0,trans);
     insert(tm);
  }
  delete [] orig_string;
  delete [] trans_string;
  mofile.close();
  squeeze(Stripped);
  return true;
}