Exemplo n.º 1
0
uninstallDialog::uninstallDialog(const QString &port, const QString &daddr,QWidget *parent) :
   QDialog(parent),m_port(port),m_daddr(daddr),
    ui(new Ui::uninstallDialog)




{



    if (ost == 1)
       {
        tmpdir = "./";
         adb2 = tmpdir+"adb.exe";
       }


     if (ost == 2)
       {
         tmpdir = QCoreApplication::applicationDirPath();
         tmpdir = tmpdir+"/adbfiles/";
        adb2 = tmpdir+"adb.osx";
       }

     if (ost == 0)
       {
         tmpdir = QCoreApplication::applicationDirPath();
         tmpdir = tmpdir+"/adbfiles/";
         adb2 = tmpdir+"adb.linux";
       }


    ui->setupUi(this);

tmpstr = tmpdir+"tempfl";
QString c1;
   QProcess packages;
   packages.setProcessChannelMode(QProcess::MergedChannels);

   if (m_port.isEmpty())
   argument = " -s "+m_daddr+ " shell pm list packages";
   else
   argument = " -s "+m_daddr+":"+m_port+" shell pm list packages";

    cstr = adb2 + argument;


   // QMessageBox::critical(0, "",cstr,QMessageBox::Cancel);

   packages.start(cstr);
   packages.waitForFinished(-1);
   commstr=packages.readAll();



                QFile file2(tmpstr);

                  if(!file2.open(QFile::WriteOnly |
                                QFile::Text))
                  {
                      QMessageBox::critical(this,"","Error creating file!");
                      return;
                  }


                  QTextStream out(&file2);
                  out  << commstr << endl;

                  file2.flush();
                  file2.close();



     QFile file3(tmpstr);
       if (!file3.open(QIODevice::ReadOnly | QIODevice::Text))
         {QMessageBox::critical(this,"","Error reading file!");
            return; }

       QTextStream in(&file3);
        while (!in.atEnd())
         {


          fline = in.readLine();

            if (!fline.isEmpty())
             {

            fline.remove(0,8);


                     ui->unlistWidget->addItem(fline);

           }

        }

          file3.close();

       QFile::remove(tmpstr);
}
Exemplo n.º 2
0
//=============================================================================
//------------------------------ProjNode---------------------------------------
uint ProjNode::hash() const {
  // only one input
  return (uintptr_t)in(TypeFunc::Control) + (_con << 1) + (_is_io_use ? 1 : 0);
}
Exemplo n.º 3
0
const Type *ProjNode::bottom_type() const {
  if (in(0) == NULL) return Type::TOP;
  return proj_type(in(0)->bottom_type());
}
Exemplo n.º 4
0
int bcp_implementation::run()
{
   //
   // check output path is OK:
   //
   if(!m_list_mode && !m_license_mode && !fs::exists(m_dest_path))
   {
      std::string msg("Destination path does not exist: ");
      msg.append(m_dest_path.string());
      std::runtime_error e(msg);
      boost::throw_exception(e);
   }
   //
   // Check Boost path is OK if it hasn't been checked already:
   //
   if(m_boost_path == "")
   {
      set_boost_path("");
   }
   // start by building a list of permitted files
   // if m_cvs_mode is true:
   if(m_cvs_mode)
   {
      std::cerr << "CAUTION: Boost is no longer in CVS, cvs mode may not work anymore!!!" << std::endl;
      scan_cvs_path(fs::path());
   }
   if(m_svn_mode)
   {
      scan_svn_path(fs::path());
   }
   //
   // if in license mode, try to load more/blanket_permission.txt
   //
   fs::path blanket_permission(m_boost_path / "more" / "blanket-permission.txt");
   if (fs::exists(blanket_permission)) {
     fs::ifstream in(blanket_permission);
     std::string line;
     while (std::getline(in, line)) {
       static const boost::regex e("([^(]+)\\(");
       boost::smatch result;
       if (boost::regex_search(line, result, e))
         m_bsl_authors.insert(format_authors_name(result[1]));
     }
   }

   //
   // scan through modules looking for the equivalent
   // file to add to our list:
   //
   std::list<std::string>::const_iterator i = m_module_list.begin();
   std::list<std::string>::const_iterator j = m_module_list.end();
   while(i != j)
   {
      //
      // convert *i to a path - could be native or portable:
      //
      fs::path module;
      fs::path exmodule;
      module = fs::path(*i);
      exmodule = fs::path(*i + ".hpp");
      
      if(m_scan_mode)
      {
         // in scan mode each module must be a real file:
         add_file_dependencies(module, true);
      }
      else
      {
         int count = 0;
         if(fs::exists(m_boost_path / "tools" / module))
         {
            add_path(fs::path("tools") / module);
            ++count;
         }
         if(fs::exists(m_boost_path / "libs" / module))
         {
            add_path(fs::path("libs") / module);
            ++count;
         }
         if(fs::exists(m_boost_path / "boost" / module))
         {
            add_path(fs::path("boost") / module);
            ++count;
         }
         if(fs::exists(m_boost_path / "boost" / exmodule))
         {
            add_path(fs::path("boost") / exmodule);
            ++count;
         }
         if(fs::exists(m_boost_path / module))
         {
            add_path(module);
            ++count;
         }
      }
      ++i;
   }
   //
   // now perform output:
   //
   if(m_list_namespaces)
   {
      // List the namespaces, in two lists, headers and source files
      // first, then everything else afterwards:
      //
      boost::regex important_file("boost/.*|libs/[^/]*/(?:[^/]*/)?/src/.*");
      std::map<std::string, fs::path>::const_iterator i, j;
      i = m_top_namespaces.begin();
      j = m_top_namespaces.end();
      std::cout << "\n\nThe top level namespaces found for header and source files were:\n";
      while(i != j)
      {
         if(regex_match(i->second.generic_string(), important_file))
            std::cout << i->first << " (from " << i->second << ")" << std::endl;
         ++i;
      }

      i = m_top_namespaces.begin();
      std::cout << "\n\nThe top level namespaces found for all other source files were:\n";
      while(i != j)
      {
         if(!regex_match(i->second.generic_string(), important_file))
            std::cout << i->first << " (from " << i->second << ")" << std::endl;
         ++i;
      }
      return 0;
   }
   std::set<fs::path, path_less>::iterator m, n;
   std::set<fs::path, path_less> short_paths;
   m = m_copy_paths.begin();
   n = m_copy_paths.end();
   if(!m_license_mode)
   {
      while(m != n)
      {
         if(m_list_summary_mode)
         {
            fs::path p = get_short_path(*m);
            if(short_paths.find(p) == short_paths.end())
            {
               short_paths.insert(p);
               std::cout << p.string() << "\n";
            }
         }
         else if(m_list_mode)
            std::cout << m->string() << "\n";
         else
            copy_path(*m);
         ++m;
      }
   }
   else
      output_license_info();
   return 0;
}
Exemplo n.º 5
0
bool ProjNode::pinned() const { return in(0)->pinned(); }
Exemplo n.º 6
0
void QCOMM::readtcppendingdatagrams()
{
    QDataStream in(tcpsocket);
    in.setByteOrder(QDataStream::LittleEndian);
    in.setVersion(QDataStream::Qt_4_7);
    unsigned short funcode;
    while(1){
        if(nexttcpblocksize==0){
            if(tcpsocket->bytesAvailable()<2)
                break;
            in>>nexttcpblocksize;
        }
        if(tcpsocket->bytesAvailable()<(nexttcpblocksize-2))
            break;
        int tcpblocksize = nexttcpblocksize;
        nexttcpblocksize = 0;

        in>>funcode;
        Q_ASSERT(sizeof(TCPHEARDER)==4);
        unsigned short  datasize= tcpblocksize-sizeof(TCPHEARDER);
        switch(funcode){
        case TCP_DOWNLOADFILE:{
            unsigned int filelen;
            in>>filelen;
            QByteArray filenameRaw =  tcpsocket->read(datasize-4);
            QString filename(filenameRaw);
            qDebug()<<"be required to receive file \""<<filename<<"\";"<<"filelen:"<<filelen;
            filetrans = QPointer<FileTrans>(new FileTrans(tcpsocket,filename,filelen));
            break;
        }

        case TCP_FILETRANSFER:{
            if(!filetrans.isNull())
                filetrans->receivData(datasize);
            else{
                in.skipRawData(datasize);
                qDebug("windowmanager:invalid file transmition task");
            }
            break;
        }
        case TCP_MACHINEINFO:

            break;
        case TCP_FILELIST:{
            QDir dir("./media");
            QStringList list = dir.entryList(QDir::NoDotAndDotDot|QDir::Files );
            QByteArray filenames = list.join(":").toUtf8();
            unsigned short lenofack = sizeof(TCPHEARDER)+filenames.size();
            FILELISTACK *ack = (FILELISTACK*)malloc(lenofack);
            ack->header.sizeofpack = sizeof(TCPHEARDER)+filenames.size();
            ack->header.funcode = TCP_FILELIST;
            qMemCopy(ack->filenamelist,filenames.data(),filenames.size());
            tcpsocket->write((char*)ack,lenofack);
            free(ack);
            break;
        }
        case TCP_STARTPLAY:{
            QByteArray rawfilename  = tcpsocket->read(datasize);
            QString filename(rawfilename);
            PLAYACK ack;
            ack.header.funcode = TCP_STARTPLAY;
            ack.header.sizeofpack = sizeof(ack);
            screensaver->setPlayFileName(filename);
            if(QWSServer::screenSaverActive())
                QWSServer::screenSaverActivate(FALSE);
            QWSServer::screenSaverActivate(TRUE);
            if(QWSServer::screenSaverActive())
                ack.ack = 0;
            else
                ack.ack = -EFILENOTEXIST
            tcpsocket->write((char*)&ack,sizeof(ack));
        }
        case TCP_STOPPLAY:{
            STOPPLAYACK ack;
            ack.header.funcode = TCP_STOPPLAY;
            ack.header.sizeofpack = sizeof(ack);
            ack.ack = 0;
            tcpsocket->write((char*)&ack,sizeof(ack));
            break;
        }
        default:
            break;
        }
    }
}
Exemplo n.º 7
0
bool DeckList::loadFromFile_Plain(QIODevice *device)
{
	QTextStream in(device);
	return loadFromStream_Plain(in);
}
Exemplo n.º 8
0
Common::String EoBCoreEngine::readOriginalSaveFile(Common::String &file) {
	Common::String desc;

	Common::SeekableReadStream *fs = _res->createReadStream(file);
	if (!fs)
		return desc;

	Common::SeekableSubReadStreamEndian in(fs, 0, fs->size(), _flags.platform == Common::kPlatformAmiga, DisposeAfterUse::YES);

	if (_flags.gameID == GI_EOB1) {
		// Nothing to read here for EOB 1. Original EOB 1 has
		// only one save slot without save file description.
		desc = "<IMPORTED GAME>";
	} else {
		char tempStr[20];
		in.read(tempStr, 20);
		desc = tempStr;
	}

	for (int i = 0; i < 6; i++) {
		EoBCharacter *c = &_characters[i];
		c->id = in.readByte();
		c->flags = in.readByte();
		in.read(c->name, 11);
		c->strengthCur = in.readSByte();
		c->strengthMax = in.readSByte();
		c->strengthExtCur = in.readSByte();
		c->strengthExtMax = in.readSByte();
		c->intelligenceCur = in.readSByte();
		c->intelligenceMax = in.readSByte();
		c->wisdomCur = in.readSByte();
		c->wisdomMax = in.readSByte();
		c->dexterityCur = in.readSByte();
		c->dexterityMax = in.readSByte();
		c->constitutionCur = in.readSByte();
		c->constitutionMax = in.readSByte();
		c->charismaCur = in.readSByte();
		c->charismaMax = in.readSByte();
		c->hitPointsCur = (_flags.gameID == GI_EOB1) ? in.readSByte() : in.readSint16();
		c->hitPointsMax = (_flags.gameID == GI_EOB1) ? in.readSByte() : in.readSint16();
		c->armorClass = in.readSByte();
		c->disabledSlots = in.readByte();
		c->raceSex = in.readByte();
		c->cClass = in.readByte();
		c->alignment = in.readByte();
		c->portrait = in.readSByte();
		c->food = in.readByte();
		in.read(c->level, 3);
		for (int ii = 0; ii < 3; ii++)
			c->experience[ii] = in.readUint32();
		in.skip(4);
		delete[] c->faceShape;
		c->faceShape = 0;
		in.read(c->mageSpells, (_flags.gameID == GI_EOB1) ? 30 : 80);
		in.read(c->clericSpells, (_flags.gameID == GI_EOB1) ? 30 : 80);
		c->mageSpellsAvailableFlags = in.readUint32();
		for (int ii = 0; ii < 27; ii++)
			c->inventory[ii] = in.readSint16();
		uint32 ct = _system->getMillis();
		for (int ii = 0; ii < 10; ii++) {
			c->timers[ii] = in.readUint32() * _tickLength;
			if (c->timers[ii])
				c->timers[ii] += ct;
		}
		in.read(c->events, 10);
		in.read(c->effectsRemainder, 4);
		c->effectFlags = in.readUint32();
		if (c->effectFlags && _flags.gameID == GI_EOB1) {
			warning("EoBCoreEngine::readOriginalSaveFile(): Unhandled character effect flags encountered in original EOB1 save file '%s' ('%s')", file.c_str(), desc.c_str());
			c->effectFlags = 0;
		}
		c->damageTaken = in.readByte();
		in.read(c->slotStatus, 5);
		in.skip(6);
	}

	setupCharacterTimers();

	_currentLevel = in.readUint16();
	_currentSub = (_flags.gameID == GI_EOB1) ? 0 : in.readSint16();
	_currentBlock = in.readUint16();
	_currentDirection = in.readUint16();
	_itemInHand = in.readSint16();
	_hasTempDataFlags = (_flags.gameID == GI_EOB1) ? in.readUint16() : in.readUint32();
	_partyEffectFlags = (_flags.gameID == GI_EOB1) ? in.readUint16() : in.readUint32();
	if (_partyEffectFlags && _flags.gameID == GI_EOB1) {
		warning("EoBCoreEngine::readOriginalSaveFile(): Unhandled party effect flags encountered in original EOB1 save file '%s' ('%s')", file.c_str(), desc.c_str());
		_partyEffectFlags = 0;
	}
	if (_flags.gameID == GI_EOB2)
		in.skip(1);

	_inf->loadState(in, true);

	int numItems = (_flags.gameID == GI_EOB1) ? 500 : 600;
	for (int i = 0; i < numItems; i++) {
		EoBItem *t = &_items[i];
		t->nameUnid = in.readByte();
		t->nameId = in.readByte();
		t->flags = in.readByte();
		t->icon = in.readSByte();
		t->type = in.readSByte();
		t->pos = in.readSByte();
		t->block = in.readSint16();
		t->next = in.readSint16();
		t->prev = in.readSint16();
		t->level = in.readByte();
		t->value = in.readSByte();
	}

	int numParts = (_flags.gameID == GI_EOB1) ? 13 : 18;
	int partSize = (_flags.gameID == GI_EOB1) ? 2040 : 2130;
	uint32 nextPart = in.pos();
	uint8 *cmpData = new uint8[1200];

	for (int i = 0; i < numParts; i++) {
		in.seek(nextPart);
		nextPart += partSize;

		if (!(_hasTempDataFlags & (1 << i)))
			continue;

		if (_lvlTempData[i]) {
			delete[] _lvlTempData[i]->wallsXorData;
			delete[] _lvlTempData[i]->flags;
			releaseMonsterTempData(_lvlTempData[i]);
			releaseFlyingObjectTempData(_lvlTempData[i]);
			releaseWallOfForceTempData(_lvlTempData[i]);
			delete _lvlTempData[i];
		}

		_lvlTempData[i] = new LevelTempData;
		LevelTempData *l = _lvlTempData[i];
		l->wallsXorData = new uint8[4096];
		l->flags = new uint16[1024];
		memset(l->flags, 0, 1024 * sizeof(uint16));
		EoBMonsterInPlay *lm = new EoBMonsterInPlay[30];
		l->monsters = lm;
		EoBFlyingObject *lf = new EoBFlyingObject[_numFlyingObjects];
		memset(lf, 0, _numFlyingObjects * sizeof(EoBFlyingObject));
		l->flyingObjects = lf;
		WallOfForce *lw = new WallOfForce[5];
		memset(lw, 0, 5 * sizeof(WallOfForce));
		l->wallsOfForce = lw;

		in.read(cmpData, 1200);
		_screen->decodeFrame4(cmpData, l->wallsXorData, 4096);
		_curBlockFile = getBlockFileName(i + 1, 0);
		const uint8 *p = getBlockFileData();
		uint16 len = READ_LE_UINT16(p + 4);
		p += 6;

		uint8 *d = l->wallsXorData;
		for (int ii = 0; ii < 1024; ii++) {
			for (int iii = 0; iii < 4; iii++)
				*d++ ^= p[ii * len + iii];
		}

		for (int ii = 0; ii < 30; ii++) {
			EoBMonsterInPlay *m = &lm[ii];
			m->type = in.readByte();
			m->unit = in.readByte();
			m->block = in.readUint16();
			m->pos = in.readByte();
			m->dir = in.readSByte();
			m->animStep = in.readByte();
			m->shpIndex = in.readByte();
			m->mode = in.readSByte();
			m->f_9 = in.readSByte();
			m->curAttackFrame = in.readSByte();
			m->spellStatusLeft = in.readSByte();
			m->hitPointsMax = in.readSint16();
			m->hitPointsCur = in.readSint16();
			m->dest = in.readUint16();
			m->randItem = in.readUint16();
			m->fixedItem = in.readUint16();
			m->flags = in.readByte();
			m->idleAnimState = in.readByte();

			if (_flags.gameID == GI_EOB1)
				m->stepsTillRemoteAttack = in.readByte();
			else
				m->curRemoteWeapon = in.readByte();

			m->numRemoteAttacks = in.readByte();
			m->palette = in.readSByte();

			if (_flags.gameID == GI_EOB1) {
				in.skip(1);
			} else {
				m->directionChanged = in.readByte();
				m->stepsTillRemoteAttack = in.readByte();
				m->sub = in.readByte();
			}

			_levelBlockProperties[m->block].flags++;
		}

		if (_flags.gameID == GI_EOB1)
			continue;

		for (int ii = 0; ii < 5; ii++) {
			WallOfForce *w = &lw[ii];
			w->block = in.readUint16();
			w->duration = in.readUint32();
		}
	}

	delete[] cmpData;

	restoreBlockTempData(_currentLevel);

	in.skip(3);

	delete[] _itemTypes;
	_itemTypes = new EoBItemType[65];
	memset(_itemTypes, 0, sizeof(EoBItemType) * 65);

	if (_flags.gameID == GI_EOB1)
		return desc;

	for (int i = 51; i < 65; i++) {
		EoBItemType *t = &_itemTypes[i];
		t->invFlags = in.readUint16();
		t->handFlags = in.readUint16();
		t->armorClass = in.readSByte();
		t->allowedClasses = in.readSByte();
		t->requiredHands = in.readSByte();
		t->dmgNumDiceS = in.readSByte();
		t->dmgNumPipsS = in.readSByte();
		t->dmgIncS = in.readSByte();
		t->dmgNumDiceL = in.readSByte();
		t->dmgNumPipsL = in.readSByte();
		t->dmgIncL = in.readSByte();
		t->unk1 = in.readByte();
		t->extraProperties = in.readUint16();
	}

	return in.err() ? Common::String() : desc;
}
Exemplo n.º 9
0
  Interpreter::CompilationResult
  MetaProcessor::readInputFromFile(llvm::StringRef filename,
                                   Value* result,
                                   size_t posOpenCurly,
                                   bool lineByLine) {

    // FIXME: This will fail for Unicode BOMs (and seems really weird)
    {
      // check that it's not binary:
      std::ifstream in(filename.str().c_str(), std::ios::in | std::ios::binary);
      if (in.fail())
        return reportIOErr(filename, "open");

      char magic[1024] = {0};
      in.read(magic, sizeof(magic));
      size_t readMagic = in.gcount();
      // Binary files < 300 bytes are rare, and below newlines etc make the
      // heuristic unreliable.
      if (!in.fail() && readMagic >= 300) {
        llvm::StringRef magicStr(magic,in.gcount());
        llvm::file_magic fileType
          = llvm::identify_magic(magicStr);
        if (fileType != llvm::file_magic::unknown)
          return reportIOErr(filename, "read from binary");

        unsigned printable = 0;
        for (size_t i = 0; i < readMagic; ++i)
          if (isprint(magic[i]))
            ++printable;
        if (10 * printable <  5 * readMagic) {
          // 50% printable for ASCII files should be a safe guess.
          return reportIOErr(filename, "won't read from likely binary");
        }
      }
    }

    std::ifstream in(filename.str().c_str());
    if (in.fail())
      return reportIOErr(filename, "open");

    in.seekg(0, std::ios::end);
    if (in.fail())
      return reportIOErr(filename, "seek");

    size_t size = in.tellg();
    if (in.fail())
      return reportIOErr(filename, "tell");

    in.seekg(0);
    if (in.fail())
      return reportIOErr(filename, "rewind");

    std::string content(size, ' ');
    in.read(&content[0], size);
    if (in.fail())
      return reportIOErr(filename, "read");

    static const char whitespace[] = " \t\r\n";
    if (content.length() > 2 && content[0] == '#' && content[1] == '!') {
      // Convert shebang line to comment. That's nice because it doesn't
      // change the content size, leaving posOpenCurly untouched.
      content[0] = '/';
      content[1] = '/';
    }

    if (posOpenCurly != (size_t)-1 && !content.empty()) {
      assert(content[posOpenCurly] == '{'
             && "No curly at claimed position of opening curly!");
      // hide the curly brace:
      content[posOpenCurly] = ' ';
      // and the matching closing '}'
      size_t posCloseCurly = content.find_last_not_of(whitespace);
      if (posCloseCurly != std::string::npos) {
        if (content[posCloseCurly] == ';' && content[posCloseCurly-1] == '}') {
          content[posCloseCurly--] = ' '; // replace ';' and enter next if
        }
        if (content[posCloseCurly] == '}') {
          content[posCloseCurly] = ' '; // replace '}'
        } else {
          std::string::size_type posBlockClose = content.find_last_of('}');
          if (posBlockClose != std::string::npos) {
            content[posBlockClose] = ' '; // replace '}'
          }
          std::string::size_type posComment
            = content.find_first_not_of(whitespace, posBlockClose);
          if (posComment != std::string::npos
              && content[posComment] == '/' && content[posComment+1] == '/') {
            // More text (comments) are okay after the last '}', but
            // we can not easily find it to remove it (so we need to upgrade
            // this code to better handle the case with comments or
            // preprocessor code before and after the leading { and
            // trailing })
            while (posComment <= posCloseCurly) {
              content[posComment++] = ' '; // replace '}' and comment
            }
          } else {
            content[posCloseCurly] = '{';
            // By putting the '{' back, we keep the code as consistent as
            // the user wrote it ... but we should still warn that we not
            // goint to treat this file an unamed macro.
            cling::errs()
              << "Warning in cling::MetaProcessor: can not find the closing '}', "
              << llvm::sys::path::filename(filename)
              << " is not handled as an unamed script!\n";
          } // did not find "//"
        } // remove comments after the trailing '}'
      } // find '}'
    } // ignore outermost block

    m_CurrentlyExecutingFile = filename;
    bool topmost = !m_TopExecutingFile.data();
    if (topmost)
      m_TopExecutingFile = m_CurrentlyExecutingFile;

    content.insert(0, "#line 2 \"" + filename.str() + "\" \n");
    // We don't want to value print the results of a unnamed macro.
    if (content.back() != ';')
      content.append(";");

    Interpreter::CompilationResult ret = Interpreter::kSuccess;
    if (lineByLine) {
      int rslt = 0;
      std::string line;
      std::stringstream ss(content);
      while (std::getline(ss, line, '\n')) {
        rslt = process(line, ret, result);
        if (ret == Interpreter::kFailure)
          break;
      }
      if (rslt) {
        cling::errs() << "Error in cling::MetaProcessor: file "
                     << llvm::sys::path::filename(filename)
                     << " is incomplete (missing parenthesis or similar)!\n";
      }
    } else
      ret = m_Interp.process(content, result);

    m_CurrentlyExecutingFile = llvm::StringRef();
    if (topmost)
      m_TopExecutingFile = llvm::StringRef();
    return ret;
  }
Exemplo n.º 10
0
///////////////////////////////////////////////////////////////////////////////
//  Main program
///////////////////////////////////////////////////////////////////////////////
int main(int argc, char **argv)
{
    char const* filename;
    if (argc > 1)
    {
        filename = argv[1];
    }
    else
    {
        std::cerr << "Error: No input file provided." << std::endl;
        return 1;
    }

    std::ifstream in(filename, std::ios_base::in);

    if (!in)
    {
        std::cerr << "Error: Could not open input file: "
            << filename << std::endl;
        return 1;
    }

    std::string source_code; // We will read the contents here.
    in.unsetf(std::ios::skipws); // No white space skipping!
    std::copy(
        std::istream_iterator<char>(in),
        std::istream_iterator<char>(),
        std::back_inserter(source_code));

    typedef std::string::const_iterator base_iterator_type;
    typedef client::lexer::conjure_tokens<base_iterator_type> lexer_type;
    typedef lexer_type::iterator_type iterator_type;

    lexer_type lexer;                           // Our lexer

    base_iterator_type first = source_code.begin();
    base_iterator_type last = source_code.end();

    iterator_type iter = lexer.begin(first, last);
    iterator_type end = lexer.end();

    client::vmachine vm;                        // Our virtual machine
    client::ast::function_list ast;             // Our AST

    client::error_handler<base_iterator_type, iterator_type>
        error_handler(first, last);             // Our error handler
    client::parser::function<iterator_type, lexer_type>
        function(error_handler, lexer);         // Our parser
    client::code_gen::compiler
        compiler(error_handler);                // Our compiler

    // note: we don't need a skipper
    bool success = parse(iter, end, +function, ast);

    std::cout << "-------------------------\n";

    if (success && iter == end)
    {
        if (compiler(ast))
        {
            boost::shared_ptr<client::code_gen::function>
                p  = compiler.find_function("main");
            if (!p)
                return 1;

            int nargs = argc-2;
            if (p->nargs() != nargs)
            {
                std::cerr << "Error: main function requires " << p->nargs() << " arguments." << std::endl;
                std::cerr << nargs << " supplied." << std::endl;
                return 1;
            }

            std::cout << "Success\n";
            std::cout << "-------------------------\n";
            std::cout << "Assembler----------------\n\n";
            compiler.print_assembler();

            // Push the arguments into our stack
            for (int i = 0; i < nargs; ++i)
                vm.get_stack()[i] = boost::lexical_cast<int>(argv[i+2]);

            // Call the interpreter
            int r = vm.execute(compiler.get_code());

            std::cout << "-------------------------\n";
            std::cout << "Result: " << r << std::endl;
            std::cout << "-------------------------\n\n";
        }
        else
        {
            std::cout << "Compile failure\n";
        }
    }
    else
    {
        std::cout << "Parse failure\n";
    }
    return 0;
}
Exemplo n.º 11
0
Common::Error EoBCoreEngine::loadGameState(int slot) {
	// Special slot id -1 for EOB1 party transfer
	const char *fileName = (slot == -1) ? _savegameFilename.c_str() : getSavegameFilename(slot);

	SaveHeader header;
	Common::InSaveFile *saveFile = openSaveForReading(fileName, header, (slot != -1));
	if (!saveFile)
		return Common::Error(Common::kReadingFailed);

	Common::SeekableSubReadStreamEndian in(saveFile, saveFile->pos(), saveFile->size(), !header.originalSave, DisposeAfterUse::YES);
	_loading = true;

	if (slot != -1)
		_screen->fadeToBlack(10);

	for (int i = 0; i < 6; i++) {
		EoBCharacter *c = &_characters[i];
		c->id = in.readByte();
		c->flags = in.readByte();
		in.read(c->name, 11);
		c->strengthCur = in.readSByte();
		c->strengthMax = in.readSByte();
		c->strengthExtCur = in.readSByte();
		c->strengthExtMax = in.readSByte();
		c->intelligenceCur = in.readSByte();
		c->intelligenceMax = in.readSByte();
		c->wisdomCur = in.readSByte();
		c->wisdomMax = in.readSByte();
		c->dexterityCur = in.readSByte();
		c->dexterityMax = in.readSByte();
		c->constitutionCur = in.readSByte();
		c->constitutionMax = in.readSByte();
		c->charismaCur = in.readSByte();
		c->charismaMax = in.readSByte();
		c->hitPointsCur = in.readSint16BE();
		c->hitPointsMax = in.readSint16BE();
		c->armorClass = in.readSByte();
		c->disabledSlots = in.readByte();
		c->raceSex = in.readByte();
		c->cClass = in.readByte();
		c->alignment = in.readByte();
		c->portrait = in.readSByte();
		if (slot == -1 && c->portrait < 0)
			c->portrait = -c->portrait + 43;
		c->food = in.readByte();
		in.read(c->level, 3);
		for (int ii = 0; ii < 3; ii++)
			c->experience[ii] = in.readUint32BE();
		delete[] c->faceShape;
		c->faceShape = 0;
		in.read(c->mageSpells, 80);
		in.read(c->clericSpells, 80);
		c->mageSpellsAvailableFlags = in.readUint32BE();
		for (int ii = 0; ii < 27; ii++)
			c->inventory[ii] = in.readSint16BE();
		uint32 ct = _system->getMillis();
		for (int ii = 0; ii < 10; ii++) {
			c->timers[ii] = in.readUint32BE();
			if (c->timers[ii])
				c->timers[ii] += ct;
		}
		in.read(c->events, 10);
		in.read(c->effectsRemainder, 4);
		c->effectFlags = in.readUint32BE();
		c->damageTaken = in.readByte();
		in.read(c->slotStatus, 5);
	}

	setupCharacterTimers();

	_screen->loadShapeSetBitmap("CHARGENA", 3, 3);
	for (int i = 0; i < 6; i++) {
		EoBCharacter *c = &_characters[i];
		if (!c->flags || c->portrait < 0)
			continue;
		c->faceShape = _screen->encodeShape((c->portrait % 10) << 2, (c->portrait / 10) << 5, 4, 32, true, _cgaMappingDefault);
	}

	_screen->loadShapeSetBitmap(_flags.gameID == GI_EOB2 ? "OUTPORTS" : "OUTTAKE", 3, 3);
	for (int i = 0; i < 6; i++) {
		EoBCharacter *c = &_characters[i];
		if (!c->flags || c->portrait >= 0)
			continue;
		c->faceShape = _screen->encodeShape((-(c->portrait + 1)) << 2, _flags.gameID == GI_EOB2 ? 0 : 160, 4, 32, true, _cgaMappingDefault);
	}
	_screen->_curPage = 0;

	if (slot == -1) {
		// Skip all settings which aren't necessary for party transfer.
		// Jump directly to the items list.
		in.skip(108);
	} else {
		_currentLevel = in.readByte();
		_currentSub = in.readSByte();
		_currentBlock = in.readUint16BE();
		_currentDirection = in.readUint16BE();
		_itemInHand = in.readSint16BE();
		_hasTempDataFlags = in.readUint32BE();
		_partyEffectFlags = in.readUint32BE();

		_updateFlags = in.readUint16BE();
		_compassDirection = in.readUint16BE();
		_currentControlMode = in.readUint16BE();
		_updateCharNum = in.readSint16BE();
		_openBookSpellLevel = in.readSByte();
		_openBookSpellSelectedItem  = in.readSByte();
		_openBookSpellListOffset = in.readSByte();
		_openBookChar = in.readByte();
		_openBookType = in.readByte();
		_openBookCharBackup = in.readByte();
		_openBookTypeBackup = in.readByte();
		_activeSpellCharId = in.readByte();
		_activeSpellCharacterPos = in.readByte();
		_activeSpell = in.readByte();
		_returnAfterSpellCallback = in.readByte() ? true : false;

		_inf->loadState(in);
	}

	for (int i = 0; i < 600; i++) {
		EoBItem *t = &_items[i];
		t->nameUnid = in.readByte();
		t->nameId = in.readByte();
		t->flags = in.readByte();
		t->icon = in.readSByte();
		t->type = in.readSByte();
		t->pos = in.readSByte();
		t->block = in.readSint16BE();
		t->next = in.readSint16BE();
		t->prev = in.readSint16BE();
		t->level = in.readByte();
		t->value = in.readSByte();
	}

	// No more data needed for party transfer
	if (slot == -1) {
		_loading = false;
		return Common::kNoError;
	}

	for (int i = 51; i < 65; i++) {
		EoBItemType *t = &_itemTypes[i];
		t->invFlags = in.readUint16BE();
		t->handFlags = in.readUint16BE();
		t->armorClass = in.readSByte();
		t->allowedClasses = in.readSByte();
		t->requiredHands = in.readSByte();
		t->dmgNumDiceS = in.readSByte();
		t->dmgNumPipsS = in.readSByte();
		t->dmgIncS = in.readSByte();
		t->dmgNumDiceL = in.readSByte();
		t->dmgNumPipsL = in.readSByte();
		t->dmgIncL = in.readSByte();
		t->unk1 = in.readByte();
		t->extraProperties = in.readUint16BE();
	}

	for (int i = 0; i < 18; i++) {
		if (!(_hasTempDataFlags & (1 << i)))
			continue;

		if (_lvlTempData[i]) {
			delete[] _lvlTempData[i]->wallsXorData;
			delete[] _lvlTempData[i]->flags;
			releaseMonsterTempData(_lvlTempData[i]);
			releaseFlyingObjectTempData(_lvlTempData[i]);
			releaseWallOfForceTempData(_lvlTempData[i]);
			delete _lvlTempData[i];
		}

		_lvlTempData[i] = new LevelTempData;
		LevelTempData *l = _lvlTempData[i];
		l->wallsXorData = new uint8[4096];
		l->flags = new uint16[1024];
		EoBMonsterInPlay *lm = new EoBMonsterInPlay[30];
		l->monsters = lm;
		EoBFlyingObject *lf = new EoBFlyingObject[_numFlyingObjects];
		l->flyingObjects = lf;
		WallOfForce *lw = new WallOfForce[5];
		l->wallsOfForce = lw;

		in.read(l->wallsXorData, 4096);
		for (int ii = 0; ii < 1024; ii++)
			l->flags[ii] = in.readByte();

		for (int ii = 0; ii < 30; ii++) {
			EoBMonsterInPlay *m = &lm[ii];
			m->type = in.readByte();
			m->unit = in.readByte();
			m->block = in.readUint16BE();
			m->pos = in.readByte();
			m->dir = in.readSByte();
			m->animStep = in.readByte();
			m->shpIndex = in.readByte();
			m->mode = in.readSByte();
			m->f_9 = in.readSByte();
			m->curAttackFrame = in.readSByte();
			m->spellStatusLeft = in.readSByte();
			m->hitPointsMax = in.readSint16BE();
			m->hitPointsCur = in.readSint16BE();
			m->dest = in.readUint16BE();
			m->randItem = in.readUint16BE();
			m->fixedItem = in.readUint16BE();
			m->flags = in.readByte();
			m->idleAnimState = in.readByte();
			m->curRemoteWeapon = in.readByte();
			m->numRemoteAttacks = in.readByte();
			m->palette = in.readSByte();
			m->directionChanged = in.readByte();
			m->stepsTillRemoteAttack = in.readByte();
			m->sub = in.readByte();
		}

		for (int ii = 0; ii < _numFlyingObjects; ii++) {
			EoBFlyingObject *m = &lf[ii];
			m->enable = in.readByte();
			m->objectType = in.readByte();
			m->attackerId = in.readSint16BE();
			m->item = in.readSint16BE();
			m->curBlock = in.readUint16BE();
			m->starting = in.readUint16BE();
			m->u1 = in.readByte();
			m->direction = in.readByte();
			m->distance = in.readByte();
			m->callBackIndex = in.readSByte();
			m->curPos = in.readByte();
			m->flags = in.readByte();
			m->unused = in.readByte();
		}

		for (int ii = 0; ii < 5; ii++) {
			WallOfForce *w = &lw[ii];
			w->block = in.readUint16BE();
			w->duration = in.readUint32BE();
		}
	}

	loadLevel(_currentLevel, _currentSub);
	_sceneUpdateRequired = true;
	_screen->setFont(Screen::FID_6_FNT);

	for (int i = 0; i < 6; i++) {
		for (int ii = 0; ii < 10; ii++) {
			if (_characters[i].events[ii] == -57)
				spellCallback_start_trueSeeing();
		}
	}

	_screen->setCurPage(0);
	gui_drawPlayField(false);

	if (_currentControlMode)
		_screen->copyRegion(176, 0, 0, 0, 144, 168, 0, 5, Screen::CR_NO_P_CHECK);

	_screen->setCurPage(0);
	gui_drawAllCharPortraitsWithStats();
	drawScene(1);

	if (_updateFlags) {
		_updateFlags = 0;
		useMagicBookOrSymbol(_openBookChar, _openBookType);
	}

	_screen->copyRegion(0, 120, 0, 0, 176, 24, 0, 12, Screen::CR_NO_P_CHECK);

	gui_toggleButtons();
	setHandItem(_itemInHand);

	while (!_screen->isMouseVisible())
		_screen->showMouse();

	_loading = false;
	_screen->fadeFromBlack(20);
	removeInputTop();

	return Common::kNoError;
}
Exemplo n.º 12
0
//-------------------------------------------------------------------------------
// @ Player::ReadData()
//-------------------------------------------------------------------------------
// Read in geometry data
//-------------------------------------------------------------------------------
bool
Player::ReadData()
{
    // read in geometric data
    IvFileReader in("Tank.txt");
    if (!in)
        return false;

    unsigned int numVerts;
    
    // get number of vertices
    in >> numVerts;
    if ( !in.good() )
        return false;

    mVertices = IvRenderer::mRenderer->GetResourceManager()->CreateVertexBuffer(kCNPFormat, numVerts,
                                                                                nullptr, kDefaultUsage);
    IvCNPVertex* dataPtr = (IvCNPVertex*) mVertices->BeginLoadData();

    // read positions
    for ( UInt32 i = 0; i < numVerts; ++i )
    {
        float x, y, z;
        in >> x >> y >> z;
        dataPtr[i].position.Set(x,y,z);
        if (!in.good() )
        {
            CleanData();
            return false;
        }
    }

    // read normals
    for ( UInt32 i = 0; i < numVerts; ++i )
    {
        float x, y, z;
        in >> x >> y >> z;
        dataPtr[i].normal.Set(x,y,z);
        if (!in.good() )
        {
            CleanData();
            return false;
        }
    }

    // read colors
    for ( UInt32 i = 0; i < numVerts; ++i )
    {
        float r, g, b;
        in >> r >> g >> b;
        dataPtr[i].color.mRed = UChar8(r*255);
        dataPtr[i].color.mGreen = UChar8(g*255);
        dataPtr[i].color.mBlue = UChar8(b*255);
        dataPtr[i].color.mAlpha = 255;

        if (!in.good() )
        {
            CleanData();
            return false;
        }
    }

    if (!mVertices->EndLoadData())
    {
        CleanData();
        return false;
    }

    // get number of indices
    UInt32 numTankBodyIndices;
    in >> numTankBodyIndices;
    if ( !in.good() )
        return false;

    // read indices
    mIndices = IvRenderer::mRenderer->GetResourceManager()->CreateIndexBuffer(numTankBodyIndices,
                                                                              nullptr, kDefaultUsage);
    UInt32* indexPtr = static_cast<UInt32*>(mIndices->BeginLoadData());
    for ( UInt32 i = 0; i < numTankBodyIndices; ++i )
    {
        in >> indexPtr[i];
        if (!in.good() )
        {
            CleanData();
            return false;
        }
    }
    if (!mIndices->EndLoadData())
    {
        CleanData();
        return false;
    }

    // read in turret
    if ( !mTurret || !mTurret->ReadData() )
    {
        CleanData();
        return false;
    }

    return true;

}   // End of Player::ReadData()
Exemplo n.º 13
0
int main(int arg, char* args[])
{
	int filterWidth = 10;
	int filterHeight = 10;
	int platformId = 0;
	if (arg > 1)
	{
		platformId = atoi(args[1]);
	}
	if (arg > 3)
	{
		filterWidth = std::atoi(args[2]);
		filterHeight = std::atoi(args[3]);
	}

	std::vector<cl::Platform> platforms;
	cl::Platform::get(&platforms);
	if (platforms.size() == 0)
	{
		std::cout << "No OpenCL platforms found" << std::endl;//This means you do not have an OpenCL compatible platform on your system.
		exit(1);
	}
	std::vector<cl::Device> devices;
	platforms[platformId].getDevices(CL_DEVICE_TYPE_ALL, &devices);
	cl::Device device = devices[0];
	std::cout << "Using device: " << device.getInfo<CL_DEVICE_NAME>() << std::endl;
	std::cout << "Using platform: " << platforms[platformId].getInfo<CL_PLATFORM_NAME>() << std::endl;
	cl::Context context(device);

	//load our image
	PNG inPng("Lenna.png");

	//store width and height so we can use them for our output image later
	const unsigned int w = inPng.w;
	const unsigned int h = inPng.h;

	//input image
	const cl::ImageFormat format(CL_RGBA, CL_UNSIGNED_INT8);
	cl::Image2D in(context, CL_MEM_READ_ONLY | CL_MEM_COPY_HOST_PTR, format, w, h, 0, &inPng.data[0]);

	//we are done with the image so free up its memory
	inPng.Free();

	//output image
	cl::Image2D out(context, CL_MEM_WRITE_ONLY, format, w, h, 0, NULL);

	cl::Program::Sources sources;
	std::string kernel_code = readFile("cl_tutorial_3_boxFilter.cl");
	//Add your program source
	sources.push_back({ kernel_code.c_str(),kernel_code.length() });

	//Create your OpenCL program and build it.
	cl::Program program(context, sources);
	if (program.build({ device }) != CL_SUCCESS)
	{
		std::cout << " Error building: " << program.getBuildInfo<CL_PROGRAM_BUILD_LOG>(device) << std::endl;//print the build log to find any issues with your source
		exit(1);//Quit if your program doesn't compile
	}

	//create command queue
	cl::CommandQueue queue(context, device, CL_QUEUE_PROFILING_ENABLE, NULL);

	//set the kernel arguments
	cl::Kernel kernelboxFilter(program, "boxFilter");
	kernelboxFilter.setArg(0, in);
	kernelboxFilter.setArg(1, out);
	kernelboxFilter.setArg(2, w);
	kernelboxFilter.setArg(3, h);
	kernelboxFilter.setArg(4, filterWidth);
	kernelboxFilter.setArg(5, filterHeight);

	cl::Event timer;

	//execute kernel
	queue.enqueueNDRangeKernel(kernelboxFilter, cl::NullRange, cl::NDRange(w, h), cl::NullRange, NULL, &timer);

	//wait for kernel to finish
	timer.wait();

	cl_ulong time_start, time_end;
	double total_time;

	time_start = timer.getProfilingInfo<CL_PROFILING_COMMAND_START>();
	time_end = timer.getProfilingInfo<CL_PROFILING_COMMAND_END>();
	total_time = time_end - time_start;

	printf("\nExecution time in milliseconds = %0.3f ms\n", (total_time / 1000000.0));

	//start and end coordinates for reading our image (I really do not like how the c++ wrapper does this)
	cl::size_t<3> origin;
	cl::size_t<3> size;
	origin[0] = 0;
	origin[1] = 0;
	origin[2] = 0;
	size[0] = w;
	size[1] = h;
	size[2] = 1;

	//output png
	PNG outPng;
	//create the image with the same width and height as original
	outPng.Create(w, h);

	//temporary array to store the result from opencl
	auto tmp = new unsigned char[w * h * 4];
	//CL_TRUE means that it waits for the entire image to be copied before continuing
	queue.enqueueReadImage(out, CL_TRUE, origin, size, 0, 0, tmp);

	//copy the data from the temp array to the png
	std::copy(&tmp[0], &tmp[w * h * 4], std::back_inserter(outPng.data));

	//write the image to file
	outPng.Save("cl_tutorial_3.png");
	//free the iamge's resources since we are done with it
	outPng.Free();

	//free the temp array
	delete[] tmp;

	return 0;
}
Exemplo n.º 14
0
MainWindow::MainWindow(QWidget *parent) :
  QMainWindow(parent)
{
  setupUi(this);

  modelClient = 0;
  modelVisit = 0;
  modelDoctor = 0;
  modelReason = 0;
  modelBrend = 0;
  modelCare_agent = 0;

  QString pathToDB = "";
  QFile file("./params.conf");
  if(!file.open(QIODevice::ReadOnly | QIODevice::Text)){
	this->close();
	pathToDB = setParamsFirstTime();
  }
  else{
	QTextStream in(&file);
	if(!in.atEnd()){
	  pathToDB = in.readLine();
	}
	file.close();
  }
  if(pathToDB.isEmpty()){
	qDebug() << "Error open file";
	exit(-1);
  }
  db = QSqlDatabase::addDatabase("QSQLITE");
  db.setDatabaseName(pathToDB);
  if(!db.open()){
	qDebug() << "Error open db";
	exit(-1);
  }
  //странная проверка на открытие базы
  //т.к. открывается любой файл - пытаемся выполнить запрос
  QSqlQuery query;
  query.exec("select * from client limit 1");
  if(query.lastError().type() == 2){
	qDebug() << "Error open db";
	exit(-1);
  }

  modelClient = new QSqlTableModel(0, db);
  modelClient->setTable("client");
  modelClient->setHeaderData(0, Qt::Horizontal, tr("id"));
  modelClient->setHeaderData(1, Qt::Horizontal, tr("ФИО"));
  modelClient->setHeaderData(2, Qt::Horizontal, tr("Дата рождения"));
  modelClient->setHeaderData(3, Qt::Horizontal, tr("Телефон"));
  modelClient->select();

  this->client_tableView->setModel(modelClient);
  this->client_tableView->setColumnHidden(0, true);
  this->client_tableView->setColumnHidden(2, true);
  this->client_tableView->setColumnHidden(3, true);
  this->client_tableView->show();

//  modelDoctor = new QSqlTableModel(0, db);
//  modelDoctor->setTable("doctor");
//  modelDoctor->setHeaderData(0, Qt::Horizontal, tr("id"));
//  modelDoctor->setHeaderData(1, Qt::Horizontal, tr("Врач"));
//  modelDoctor->select();

//  this->doctor_tableView->setModel(modelDoctor);
//  this->doctor_tableView->setColumnHidden(0, true);
//  this->doctor_tableView->show();

//  modelReason = new QSqlTableModel(0, db);
//  modelReason->setTable("reason");
//  modelReason->setHeaderData(0, Qt::Horizontal, tr("id"));
//  modelReason->setHeaderData(1, Qt::Horizontal, tr("Причина"));
//  modelReason->select();

//  this->reason_tableView->setModel(modelClient);
//  this->reason_tableView->setColumnHidden(0, true);
//  this->reason_tableView->show();

}
Exemplo n.º 15
0
void request(char method[], char path[], char file_name[], char Buffer2[])
{
	char path1[PATH_MAX];
	char path2[PATH_MAX];
	char buf2[32];
	strcpy(path1, path);
	unsigned char buf[BUFSIZE];
	static char Buffer3[BUFSIZE3];
	int count;

	//Check path
	strcpy(path2, file_name);
	char *p = strrchr(path2, '/');
	if (p) {
		if (path2[0] == '/') {
			file_name += 1;
		}
		*p = '\0';

		if (path1[strlen(path) - 1] == '/')
			strcat(path1, path2);
		else {
			strcat(path1, "/");
			strcat(path1, path2);
		}

		chdir(path1);
		getcwd(path2, PATH_MAX);
		chdir(path);
		getcwd(path1, PATH_MAX);

		if (!strstr(path2, path1)) {
			strcpy(Buffer2, "HTTP/1.0 404 Not Found\n\n");
			return;
		}
	} else {
		chdir(path);
	}

	//Open file
	std::ifstream in(file_name, std::ios::in | std::ios::binary);

	if (!in) {
		strcpy(Buffer2, "HTTP/1.0 404 Not Found\n\n");
		return;
	}

	//Work http request
	if (!strcmp(method, "HEAD"))
		strcpy(Buffer2, "HTTP/1.0 200 OK\n\n");
	else if (!strcmp(method, "GET") || !strcmp(method, "POST")) {
		strcpy(Buffer2, "HTTP/1.0 200 OK\n");
		strcpy(Buffer3, "");
		count = 0;
		while (!in.eof()) {
			in.read((char *) buf, sizeof buf);
			if (in.gcount()) {
				strncat(Buffer3, (char *) buf, in.gcount());
				count += in.gcount();
			}
		}
		strcat(Buffer2, "Content-Length: ");
		sprintf(buf2, "%d", count);
		strcat(Buffer2, buf2);
		strcat(Buffer2, "\n");

		strcpy(path2, file_name);
		char *q = strrchr(path2, '.');
		if (!strcmp(q, ".html") || !strcmp(q, ".htm"))
			strcat(Buffer2, "Content-Type: text/html\n\n");
		if (!strcmp(q, ".txt"))
			strcat(Buffer2, "Content-Type: text/plain\n\n");
		if (!strcmp(q, ".jpeg") || !strcmp(q, ".jpg"))
			strcat(Buffer2, "Content-Type: image/jpeg\n\n");

		strncat(Buffer2, Buffer3, count);
		in.close();
	}
}
Exemplo n.º 16
0
  bool call(const char* cmd, const Properties& args,
            const char* cmd_reply, Properties& reply,
            const char* bulk = NULL,
            bool name_value_pairs = true){

    if (!is_connected()){
      error("call: not connected");
      return false;
    }

    SocketOutputStream out(socket());

    if (out.println("%s", cmd)){
      error("call: println failed at line %d", __LINE__);
      return false;
    }

    Properties::Iterator iter(&args);
    const char *name;
    while((name = iter.next()) != NULL) {
      PropertiesType t;
      Uint32 val_i;
      Uint64 val_64;
      BaseString val_s;

      args.getTypeOf(name, &t);
      switch(t) {
      case PropertiesType_Uint32:
	args.get(name, &val_i);
	if (out.println("%s: %d", name, val_i)){
          error("call: println failed at line %d", __LINE__);
          return false;
        }
	break;
      case PropertiesType_Uint64:
	args.get(name, &val_64);
	if (out.println("%s: %Ld", name, val_64)){
          error("call: println failed at line %d", __LINE__);
          return false;
        }
	break;
      case PropertiesType_char:
	args.get(name, val_s);
	if (out.println("%s: %s", name, val_s.c_str())){
          error("call: println failed at line %d", __LINE__);
          return false;
        }
	break;
      default:
      case PropertiesType_Properties:
	/* Illegal */
        abort();
	break;
      }
    }

    // Emtpy line terminates argument list
    if (out.print("\n")){
      error("call: print('\n') failed at line %d", __LINE__);
      return false;
    }

    // Send any bulk data
    if (bulk)
    {
      if (out.write(bulk, strlen(bulk)) >= 0)
      {
        if (out.write("\n", 1) < 0)
        {
          error("call: print('<bulk>') failed at line %d", __LINE__);
          return false;
        }
      }
    }

    BaseString buf;
    SocketInputStream2 in(socket());
    if (cmd_reply)
    {
      // Read the reply header and compare against "cmd_reply"
      if (!in.gets(buf)){
        error("call: could not read reply command");
        return false;
      }

      // 1. Check correct reply header
      if (buf != cmd_reply){
        error("call: unexpected reply command, expected: '%s', got '%s'",
              cmd_reply, buf.c_str());
        return false;
      }
    }

    // 2. Read lines until empty line
    int line = 1;
    while(in.gets(buf)){

      // empty line -> end of reply
      if (buf == "")
        return true;

      if (name_value_pairs)
      {
        // 3a. Read colon separated name value pair, split
        // the name value pair on first ':'
        Vector<BaseString> name_value_pair;
        if (buf.split(name_value_pair, ":", 2) != 2){
          error("call: illegal name value pair '%s' received", buf.c_str());
          return false;
        }

        reply.put(name_value_pair[0].trim(" ").c_str(),
                  name_value_pair[1].trim(" ").c_str());
      }
      else
      {
        // 3b. Not name value pair, save the line into "reply"
        // using unique key
        reply.put("line", line++, buf.c_str());
      }
    }

    error("call: should never come here");
    reply.print();
    abort();
    return false;
  }
Exemplo n.º 17
0
void
TeXmacs_main (int argc, char** argv) {
  int i;
  bool flag= true;
  string the_default_font;
  for (i=1; i<argc; i++)
    if (argv[i][0] == '\0') argc= i;
    else if (((argv[i][0] == '-') ||
	      (argv[i][0] == '+')) && (argv[i][1] != '\0'))
    {
      string s= argv[i];
      if ((N(s)>=2) && (s(0,2)=="--")) s= s (1, N(s));
      if ((s == "-s") || (s == "-silent")) flag= false;
      else if ((s == "-V") || (s == "-verbose"))
        debug (DEBUG_FLAG_VERBOSE, true);
      else if ((s == "-d") || (s == "-debug")) debug (DEBUG_FLAG_STD, true);
      else if (s == "-debug-events") debug (DEBUG_FLAG_EVENTS, true);
      else if (s == "-debug-io") debug (DEBUG_FLAG_IO, true);
      else if (s == "-debug-bench") debug (DEBUG_FLAG_BENCH, true);
      else if (s == "-debug-history") debug (DEBUG_FLAG_HISTORY, true);
      else if (s == "-debug-qt") debug (DEBUG_FLAG_QT, true);
      else if (s == "-debug-qt-widgets") debug (DEBUG_FLAG_QT_WIDGETS, true);
      else if (s == "-debug-keyboard") debug (DEBUG_FLAG_KEYBOARD, true);
      else if (s == "-debug-packrat") debug (DEBUG_FLAG_PACKRAT, true);
      else if (s == "-debug-flatten") debug (DEBUG_FLAG_FLATTEN, true);
      else if (s == "-debug-correct") debug (DEBUG_FLAG_CORRECT, true);
      else if (s == "-debug-convert") debug (DEBUG_FLAG_CONVERT, true);
      else if (s == "-debug-all") {
        debug (DEBUG_FLAG_EVENTS, true);
        debug (DEBUG_FLAG_STD, true);
        debug (DEBUG_FLAG_IO, true);
        debug (DEBUG_FLAG_HISTORY, true);
        debug (DEBUG_FLAG_BENCH, true);
        debug (DEBUG_FLAG_QT, true);
        debug (DEBUG_FLAG_QT_WIDGETS, true);
      }
      else if (s == "-disable-error-recovery") disable_error_recovery= true;
      else if ((s == "-fn") || (s == "-font")) {
	i++;
	if (i<argc) the_default_font= argv[i];
      }
      else if ((s == "-g") || (s == "-geometry")) {
	i++;
	if (i<argc) {
	  string g= argv[i];
	  int j=0, j1, j2, j3;
	  for (j=0; j<N(g); j++)
	    if (g[j] == 'x') break;
	  j1=j; if (j<N(g)) j++;
	  for (; j<N(g); j++)
	    if ((g[j] == '+') || (g[j] == '-')) break;
	  j2=j; if (j<N(g)) j++;
	  for (; j<N(g); j++)
	    if ((g[j] == '+') || (g[j] == '-')) break;
	  j3=j;
	  if (j1<N(g)) {
	    geometry_w= max (as_int (g (0, j1)), 320);
	    geometry_h= max (as_int (g (j1+1, j2)), 200);
	  }
	  if (j3<N(g)) {
	    if (g[j2] == '-') geometry_x= as_int (g (j2, j3)) - 1;
	    else geometry_x= as_int (g (j2+1, j3));
	    if (g[j3] == '-') geometry_y= as_int (g (j3, N(g))) - 1;
	    else geometry_y= as_int (g (j3+1, N(g)));
	  }
	}
      }
      else if ((s == "-b") || (s == "-initialize-buffer")) {
	i++;
	if (i<argc) tm_init_buffer_file= url_system (argv[i]);
      }
      else if ((s == "-i") || (s == "-initialize")) {
	i++;
	if (i<argc) tm_init_file= url_system (argv[i]);
      }
      else if ((s == "-v") || (s == "-version")) {
	cout << "\n";
	cout << "TeXmacs version " << TEXMACS_VERSION << "\n";
	cout << TEXMACS_COPYRIGHT << "\n";
	cout << "\n";
	exit (0);
      }
      else if ((s == "-p") || (s == "-path")) {
	cout << get_env ("TEXMACS_PATH") << "\n";
	exit (0);
      }
      else if ((s == "-bp") || (s == "-binpath")) {
	cout << get_env ("TEXMACS_BIN_PATH") << "\n";
	exit (0);
      }
      else if ((s == "-q") || (s == "-quit"))
	my_init_cmds= my_init_cmds * " (quit-TeXmacs)";
      else if ((s == "-r") || (s == "-reverse"))
	set_reverse_colors (true);
      else if (s == "-no-retina") {
        retina_manual= true;
        retina_factor= 1;
        retina_icons = 1;
	retina_scale = 1.0;
      }
      else if ((s == "-R") || (s == "-retina")) {
        retina_manual= true;
        retina_factor= 2;
        retina_icons = 2;
	retina_scale = 1.4;
      }
      else if (s == "-no-retina-icons") {
        retina_iman  = true;
        retina_icons = 1;
      }
      else if (s == "-retina-icons") {
        retina_iman  = true;
        retina_icons = 2;
      }
      else if ((s == "-c") || (s == "-convert")) {
	i+=2;
	if (i<argc) {
	  url in  ("$PWD", argv[i-1]);
	  url out ("$PWD", argv[ i ]);
	  my_init_cmds= my_init_cmds * " " *
	    "(load-buffer " * scm_quote (as_string (in)) * " :strict) " *
	    "(export-buffer " * scm_quote (as_string (out)) * ")";
	}
      }
      else if ((s == "-x") || (s == "-execute")) {
	i++;
	if (i<argc) my_init_cmds= (my_init_cmds * " ") * argv[i];
      }
      else if (s == "-server") start_server_flag= true;
      else if (s == "-log-file") i++;
      else if ((s == "-Oc") || (s == "-no-char-clipping")) char_clip= false;
      else if ((s == "+Oc") || (s == "-char-clipping")) char_clip= true;
      else if ((s == "-S") || (s == "-setup") ||
	       (s == "-delete-cache") || (s == "-delete-font-cache") ||
	       (s == "-delete-style-cache") || (s == "-delete-file-cache") ||
	       (s == "-delete-doc-cache") || (s == "-delete-plugin-cache") ||
	       (s == "-delete-server-data") || (s == "-delete-databases"));
      else if (starts (s, "-psn"));
      else {
	cout << "\n";
	cout << "Options for TeXmacs:\n\n";
	cout << "  -b [file]  Specify scheme buffers initialization file\n";
	cout << "  -c [i] [o] Convert file 'i' into file 'o'\n";
	cout << "  -d         For debugging purposes\n";
	cout << "  -fn [font] Set the default TeX font\n";
	cout << "  -g [geom]  Set geometry of window in pixels\n";
	cout << "  -h         Display this help message\n";
	cout << "  -i [file]  Specify scheme initialization file\n";
	cout << "  -p         Get the TeXmacs path\n";
	cout << "  -q         Shortcut for -x \"(quit-TeXmacs)\"\n";
	cout << "  -r         Reverse video mode\n";
	cout << "  -s         Suppress information messages\n";
	cout << "  -S         Rerun TeXmacs setup program before starting\n";
	cout << "  -v         Display current TeXmacs version\n";
	cout << "  -V         Show some informative messages\n";
	cout << "  -x [cmd]   Execute scheme command\n";
	cout << "  -Oc        TeX characters bitmap clipping off\n";
	cout << "  +Oc        TeX characters bitmap clipping on (default)\n";
	cout << "\nPlease report bugs to <bugs@texmacs.org>\n";
	cout << "\n";
	exit (0);
      }
    }
  if (flag) debug (DEBUG_FLAG_AUTO, true);

  // Further options via environment variables
  if (get_env ("TEXMACS_RETINA") == "off") {
    retina_manual= true;
    retina_factor= 1;
    retina_icons = 1;
    retina_scale = 1.0;
  }
  if (get_env ("TEXMACS_RETINA") == "on") {
    retina_manual= true;
    retina_factor= 2;
    retina_icons = 2;
    retina_scale = 1.4;
  }
  if (get_env ("TEXMACS_RETINA_ICONS") == "off") {
    retina_iman  = true;
    retina_icons = 1;
  }
  if (get_env ("TEXMACS_RETINA_ICONS") == "on") {
    retina_iman  = true;
    retina_icons = 2;
  }
  // End options via environment variables
  
  if (DEBUG_STD) debug_boot << "Installing internal plug-ins...\n";
  bench_start ("initialize plugins");
  init_plugins ();
  bench_cumul ("initialize plugins");
  if (DEBUG_STD) debug_boot << "Opening display...\n";
  
#if defined(X11TEXMACS) && defined(MACOSX_EXTENSIONS)
  init_mac_application ();
#endif
    
  gui_open (argc, argv);
  set_default_font (the_default_font);
  if (DEBUG_STD) debug_boot << "Starting server...\n";
  { // opening scope for server sv
  server sv;

  // HACK:
  // Qt and Guile want to change the locale. 
  // We need to force it to C to parse correctly the configuration files
  // (see as_double() in string.cpp)
  setlocale(LC_NUMERIC, "C");    
    
  string where= "";
  for (i=1; i<argc; i++) {
    if (argv[i] == NULL) break;
    string s= argv[i];
    if ((N(s)>=2) && (s(0,2)=="--")) s= s (1, N(s));
    if ((s[0] != '-') && (s[0] != '+')) {
      if (DEBUG_STD) debug_boot << "Loading " << s << "...\n";
      url u= url_system (s);
      if (!is_rooted (u)) u= resolve (url_pwd (), "") * u;
      string b= scm_quote (as_string (u));
      string cmd= "(load-buffer " * b * " " * where * ")";
      where= " :new-window";
      exec_delayed (scheme_cmd (cmd));
    }
    if      ((s == "-c") || (s == "-convert")) i+=2;
    else if ((s == "-b") || (s == "-initialize-buffer") ||
             (s == "-fn") || (s == "-font") ||
             (s == "-i") || (s == "-initialize") ||
             (s == "-g") || (s == "-geometry") ||
             (s == "-x") || (s == "-execute") ||
             (s == "-log-file")) i++;
  }
  if (install_status == 1) {
    if (DEBUG_STD) debug_boot << "Loading welcome message...\n";
    url u= "tmfs://help/plain/tm/doc/about/welcome/first.en.tm";
    string b= scm_quote (as_string (u));
    string cmd= "(load-buffer " * b * " " * where * ")";
    where= " :new-window";
    exec_delayed (scheme_cmd (cmd));
  }
  else if (install_status == 2) {
    if (DEBUG_STD) debug_boot << "Loading upgrade message...\n";
    url u= "tmfs://help/plain/tm/doc/about/changes/changes-recent.en.tm";
    string b= scm_quote (as_string (u));
    string cmd= "(load-buffer " * b * " " * where * ")";
    where= " :new-window";
    exec_delayed (scheme_cmd (cmd));
  }
  if (number_buffers () == 0) {
    if (DEBUG_STD) debug_boot << "Creating 'no name' buffer...\n";
    open_window ();
  }

  bench_print ();
  bench_reset ("initialize texmacs");
  bench_reset ("initialize plugins");
  bench_reset ("initialize scheme");

  if (DEBUG_STD) debug_boot << "Starting event loop...\n";
  texmacs_started= true;
  if (!disable_error_recovery) signal (SIGSEGV, clean_exit_on_segfault);
  if (start_server_flag) server_start ();
  gui_start_loop ();

  if (DEBUG_STD) debug_boot << "Stopping server...\n";
  } // ending scope for server sv

  if (DEBUG_STD) debug_boot << "Closing display...\n";
  gui_close ();
  
#if defined(X11TEXMACS) && defined(MACOSX_EXTENSIONS)
  finalize_mac_application ();
#endif
  
  if (DEBUG_STD) debug_boot << "Good bye...\n";
}
Exemplo n.º 18
0
void beamtest::readbinarywithcolor()
	{


QTime time;
time.start();
Handle_AIS_InteractiveContext ic = ui::getInstance()->getWindowContext();

QString filename = QFileDialog::getOpenFileName ( this,
												 tr("Import File"),"");

QFile file(filename);
 file.open(QIODevice::ReadOnly);
 QDataStream in(&file);    // read the data serialized from the file

 //double pcount;
 //in >> pcount ;         // extract "the answer is" and 42


//QProgressDialog progress("loading cloudpoint", "Abort Copy", 1,100);

//QList<Graphic3d_Vertex> vertlist;
QList<gp_Pnt> vertlist;




//for (int i=0;i < pcount;i++)
//{
	       
	double x ;
	double y ;
	double z ;
	double intensity;
	int i=0;
	do {
		
	i++;
	in >> x >> y >> z >> intensity;

	if (i % 100000 == 0) qDebug() << i;
	

			//Graphic3d_Vertex thevert(x,y,z);
			gp_Pnt thevert(x,y,z);
			vertlist.append(thevert);

//			Quantity_Color rgbval(intensity,0,0,Quantity_TOC_RGB);
//			colorlist.append(rgbval);


	//if (i > 30000000) break;
			
		} while ( in.status() ==QDataStream::Ok );

file.close();

Handle(AIS_PointCloud) mypc1 = new AIS_PointCloud(vertlist);
ic->Display(mypc1);

double milliseconds = time.elapsed();
double seconds = (milliseconds/1000);
double minutes = seconds/60;
double hours = minutes/60;

QString timetxt;
QTextStream linestream(&timetxt);
linestream << "h" << hours << ":m " << minutes << ":s " << seconds << ".ms" << milliseconds; 

ui::getInstance()->Statusbar(timetxt);
qDebug() <<  "time ellapsed:" << timetxt;

}
Exemplo n.º 19
0
std::ostream& ossimJp2Info::print(std::ostream& out) const
{
    if ( m_file.size() )
    {
        // Open the file.
        std::ifstream str( m_file.c_str(), std::ios_base::in | std::ios_base::binary );
        if (str.good())
        {
            //---
            // ISO/IEC 15444-1:2004 (E)
            // LBox, Box Length. This field specifies the length of the box, stored
            // as a 4-byte big endian unsigned integer. This value includes all of
            // the fields of the box, including the length and type. If the value
            // of this field is 1, then the XLBox field shall exist and the value
            // of that field shall be the actual length of the box. If the value
            // of this field is 0, then the length of the box was not known when
            // the LBox field was written. In this case, this box contains all
            // bytes up to the end of the file. If a box of length 0 is contained
            // within another box (its superbox), then the length of that superbox
            // shall also be 0.  This means that this box is the last box in the
            // file. The values 2-7 are reserved for ISO use.
            //---
            ossim_uint32 lbox  = 0;
            ossim_uint32 tbox  = 0;
            ossim_uint64 xlbox = 0;

            const ossim_uint32 UUID_TYPE = 0x75756964;
            const ossim_uint8 GEOTIFF_UUID[GEOTIFF_UUID_SIZE] =
            {
                0xb1, 0x4b, 0xf8, 0xbd,
                0x08, 0x3d, 0x4b, 0x43,
                0xa5, 0xae, 0x8c, 0xd7,
                0xd5, 0xa6, 0xce, 0x03
            };

            while ( str.good() )
            {
                std::streamoff boxPos = str.tellg();

                readUInt32( lbox, str );
                readUInt32( tbox, str );

                if ( 1 == lbox )
                {
                    readUInt64( xlbox, str );
                }

                if ( traceDebug() )
                {
                    ossimNotify(ossimNotifyLevel_DEBUG)
                            << "jp2.lbox: " << std::dec << lbox << "\n"
                            << "jp2.tbox: " << std::hex << tbox << std::dec << "\n";
                    printTboxType( tbox, ossimNotify(ossimNotifyLevel_DEBUG)  );

                    if ( 1 == lbox )
                    {
                        ossimNotify(ossimNotifyLevel_DEBUG) << "jp2.xlbox: " << xlbox << std::endl;
                    }
                }

                if (tbox == UUID_TYPE)
                {
                    // Check for GeoTIFF box.

                    ossim_uint8 geotiffUuid[GEOTIFF_UUID_SIZE];

                    // Read in the id.
                    str.read((char*)geotiffUuid, GEOTIFF_UUID_SIZE);

#if 0
                    bool foundIt = true;
                    for (ossim_uint32 i = 0; i < GEOTIFF_UUID_SIZE; ++i)
                    {
                        if (geotiffUuid[i] != GEOTIFF_UUID[i])
                        {
                            foundIt = false;
                            break;
                        }
                    }
#endif

                    if( memcmp( (char*)geotiffUuid, GEOTIFF_UUID, GEOTIFF_UUID_SIZE) == 0)
                    {
                        //---
                        // Feed the stream to the tiff info object to get a keyword
                        // list with geometry/projection info.
                        //---
                        ossimTiffInfo info;

                        //---
                        // Have geotiff boxes with badly terminated geotiffs. So to keep
                        // the tag parser from walking past the first image file directory
                        // (IFD) into garbage we will set the process overview flag to false.
                        //
                        // Note if we ever get multiple entries we will need to take this out.
                        //---
                        info.setProcessOverviewFlag(false);

                        // Do a print to a memory stream.
                        std::ostringstream os;
                        info.print(str, os);

                        // Open an input stream to pass to the keyword list.
                        std::istringstream in( os.str() );

                        ossimKeywordlist kwl;
                        if ( kwl.parseStream(in) )
                        {
                            kwl.addPrefixToAll( ossimString("jp2.") );

                            // Print it:
                            out << kwl << std::endl;
                        }

                        // Get out of while loop.
                        // break;
                    }
                }

                if (lbox == 0) // last box?
                {
                    break;
                }

                // Seek to the next box.  If xlbox is 1
                if (lbox == 1)
                {
                    boxPos += (std::streamoff)xlbox;
                }
                else
                {
                    boxPos += (std::streamoff)lbox;
                }

                // Go to next box:
                str.seekg(boxPos, std::ios_base::beg);

            } // matches: while ( str.good() )

            // Close the stream.
            str.close();

        } // matches: if ( str.is_open() )

    } // matches: if ( m_file.size() )

    return out;
}
Exemplo n.º 20
0
void MainWindow::checkForPasswordFile()
{
    QString fileInput = "password.txt";
    QString hidden = ".password.txt";

    QList<QString> asList;

    QFile file(fileInput);

    if (!file.exists() && !QFile(hidden).exists())
    {
        UserWindow * newUser = new UserWindow(0, false);
        connect(newUser, SIGNAL(createAccount(QString,QString)), this, SLOT(makeAccount(QString,QString)));
        newUser->show();
    }//first run, or file cannot be found.

    else if (!file.exists() && QFile(hidden).exists())
    {
        QFile file2(hidden);
        file2.copy(fileInput);
        /**
          Load the password into memory.

          **/

        if (!file2.open(QIODevice::ReadOnly))
        {
            QMessageBox::critical(this, tr("Error"), tr("Could not open file"));
            return;
        }//end if
        QTextStream in(&file2);


        while (!in.atEnd())
        {
            asList.push_back(in.readLine());
        }//iterate through the file. All of it. Store.

    if (asList.size() > 0)
    {
        QString current = asList.at(0);
        int index1 = current.indexOf("User:");
        current.remove(0, 6);
        m_username = current;
        current = asList.at(1);
        //"password: "
        current.remove(0, 10);
        m_password = current;
    }//end if

    countCash();
    displayInfo();
    }//someone poisoned the water hole! 

    else if (fileInput != "")
    {
        /**
          Load the password into memory.

          **/

        if (!file.open(QIODevice::ReadOnly))
        {
            QMessageBox::critical(this, tr("Error"), tr("Could not open file"));
            return;
        }//end if
        QTextStream in(&file);


        while (!in.atEnd())
        {
            asList.push_back(in.readLine());
        }//iterate through the file. All of it. Store.

    if (asList.size() > 0)
    {
        QString current = asList.at(0);
        int index1 = current.indexOf("User:");
        current.remove(0, 6);
        m_username = current;
        current = asList.at(1);
        //"password: "
        current.remove(0, 10);
        m_password = current;
    }//end if

    countCash();
    displayInfo();
    }//open last save.
}
Exemplo n.º 21
0
int main(int argc, char *argv[])
{
    if (argc != 3) {
        std::cout << "Usage: " << argv[0] << " matrix rhs" << std::endl;
        return -1;
    }

    // *** reading matrix in crs format from file
    std::string fname(argv[1]);
    MathLib::CRSMatrixDiagPrecond *mat(new MathLib::CRSMatrixDiagPrecond(fname));

    unsigned n(mat->getNRows());
    bool verbose(true);
    if (verbose) std::cout << "Parameters read: n=" << n << std::endl;

    double *x(new double[n]);
    double *b(new double[n]);

    // *** init start vector x
    for (std::size_t k(0); k < n; k++) {
        x[k] = 1.0;
    }
    // *** read rhs
    fname = argv[2];
    std::ifstream in(fname.c_str());
    if (in) {
        read(in, n, b);
        in.close();
    } else {
        std::cout << "problem reading rhs - initializing b with 1.0"
                  << std::endl;
        for (std::size_t k(0); k < n; k++) {
            b[k] = 1.0;
        }
    }

    if (verbose)
        std::cout << "solving system with GMRes method (diagonal preconditioner) ... "
                  << std::flush;

    double eps(1.0e-6);
    unsigned steps(4000);
    BaseLib::RunTime run_timer;
    BaseLib::CPUTime cpu_timer;
    run_timer.start();
    cpu_timer.start();

    MathLib::GMRes((*mat), b, x, eps, 30, steps);

    if (verbose) {
        std::cout << " in " << steps << " iterations" << std::endl;
        std::cout << "\t(residuum is " << eps << ") took "
                  << cpu_timer.elapsed() << " sec time and "
                  << run_timer.elapsed() << " sec" << std::endl;
    } else {
        std::cout << cpu_timer.elapsed() << std::endl;
    }

    delete mat;
    delete[] x;
    delete[] b;

    return 0;
}
Exemplo n.º 22
0
void MainWindow::parseFile(QString fileInput)
{
    if (fileInput != "")
    {
        QFile file(fileInput);
        if (!file.open(QIODevice::ReadOnly))
        {
            QMessageBox::critical(this, tr("Error"), tr("Could not open file"));
            return;
        }//end if
        QTextStream in(&file);
        QList<QString> asList;
        QList<QString> dataList;
        QString email, date;

        while (!in.atEnd())
        {
            asList.push_back(in.readLine());
        }//iterate through the file. All of it. Store.

        ui->fileDisplay->clear();

        for (int x = 0; x < asList.size(); x++)
        {
            if (asList.at(x) == "" && x > 0)
            { asList.removeAt(x); x--; }
            //remove the blank lines
        }//end for x

        for (int z = 0; z < asList.size(); z++)
        {
            /** Order of the file here,
              lastname:
              period:
              version:
              denomination:
              serial:
              Submit: Submit
              HTTP_USER_AGENT:
              WOW64;
              REMOTE_ADDR:
              From: lastname [email]
              Sent: date **/



            if (asList.at(z).contains("From"))
            {
                int index1, index2;
                QString current;
                current = asList.at(z);
                if (current.contains("["))
                {
                    index1 = current.indexOf("[");
                    current.remove(0, index1 + 1);
                    index2 = current.indexOf("]");
                    current.remove(index2, current.size() - 1);
                }//end if

                else
                {
                    index1 = current.indexOf("<");
                    current.remove(0, index1 + 1);
                    index2 = current.indexOf(">");
                    current.remove(index2, current.size() - 1);
                }

                email = current;
                z++;

                current = asList.at(z);

                index1 = current.indexOf(",");
                current.remove(0, index1 + 1);
                index2 = current.indexOf(":");
                current.remove(index2 - 2, current.size() - 1);
                date = current;
                z++;
            }

            else if (asList.at(z).contains("lastname: "))
            {
                QString lastname, period, version, denom,
                        serial, remote;
                //we have a section to extract from.
                QString toSize;
                QString current;
                current = asList.at(z);
                int theSize = 0;
                toSize = "lastname: ";
                theSize = toSize.size();
                current.remove(0, theSize);
                lastname = current;
                z++; //we can go to the next line now

                if (asList.at(z).contains("period: "))
                {
                    toSize = "period: ";
                    current = asList.at(z);
                    current.remove(0, toSize.size() - 1);
                    period = current;
                    z++;
                }//make sure it exists!
                else
                    period = "invalid";

                if (asList.at(z).contains("version"))
                {
                    current = asList.at(z);
                    toSize = "version: ";
                    current.remove(0, toSize.size() - 1);
                    version = current;
                    z++;
                }

                if (asList.at(z).contains("denomination"))
                {
                    toSize = "denomination: ";
                    current = asList.at(z);
                    current.remove(0, toSize.size() - 1);
                    denom = current;
                    z++;
                }

                if (asList.at(z).contains("serial"))
                {
                    toSize = "serial: ";
                    current = asList.at(z);
                    current.remove(0, toSize.size() - 1);
                    serial = current;
                    z += 3; //go to remote line
                }

                if (asList.at(z).contains("REMOTE_ADDR"))
                {
                    toSize = "REMOTE_ADDR: ";
                    current = asList.at(z);
                    current.remove(0, toSize.size() - 1);
                    remote = current;
                }

                //get email

                bool exists = false;
                int index = -1;

                for (int k = 0; k < kids.size(); k++)
                {
                    if (QString::compare(kids.at(k).name, lastname, Qt::CaseInsensitive) == 0)
                    { exists = true; index = k; break; }
                }

                KedighKid toPush(lastname, period, email);

                if (!exists)
                {
                    kids.push_back(toPush);

                    KedighCash dolla(serial, date, lastname, remote, toInt(denom));
                    kids.last().addMoney(dolla);
                }//end if.

                else
                {
                    KedighCash dolla(serial, date, lastname, remote, toInt(denom));
                    kids.last().addMoney(dolla);
                }//end else
            }

            else if (asList.at(z).contains("denomination"))
            {
                QString lastname, period, version, denom,
                        serial, remote;
                //we have a section to extract from.
                QString toSize; 
                QString current;
                current = asList.at(z);
                int theSize = 0;
                toSize = "denomination: ";
                current = asList.at(z); 
                current.remove(0, toSize.size() - 1);
                denom = current;
                z++; 


                if (asList.at(z).contains("serial"))
                {
                    toSize = "serial: ";
                    current = asList.at(z);
                    current.remove(0, toSize.size() - 1);
                    serial = current;
                    z ++; //go to remote line
                }

                if (asList.at(z).contains("period"))
                {
                    toSize = "period: ";
                    current = asList.at(z);
                    current.remove(0, toSize.size() - 1);
                    period = current;
                    z++;
                }//make sure it exists!
                else
                    period = "invalid";


                if (asList.at(z).contains("lastname"))
                {
                    current = asList.at(z);
                    toSize = "lastname: ";
                    theSize = toSize.size();
                    current.remove(0, theSize);
                    lastname = current;
                    z += 3; //we can go to the next line now
                }

                if (asList.at(z).contains("REMOTE_ADDR"))
                {
                    toSize = "REMOTE_ADDR: ";
                    current = asList.at(z);
                    current.remove(0, toSize.size() - 1);
                    remote = current;
                }

                //get email

                bool exists = false;
                int index = -1;

                for (int k = 0; k < kids.size(); k++)
                {
                    if (QString::compare(kids.at(k).name, lastname, Qt::CaseInsensitive) == 0)
                    { exists = true; index = k; break; }
                }

                KedighKid toPush(lastname, period, email);

                if (!exists)
                {
                    kids.push_back(toPush);

                    KedighCash dolla(serial, date, lastname, remote, toInt(denom));
                    kids.last().addMoney(dolla);
                }//end if.

                else
                {
                    KedighCash dolla(serial, date, lastname, remote, toInt(denom));
                    kids.last().addMoney(dolla);
                }//end else
            }//end else if.
        }

        qSort(kids.begin(), kids.end());
        for (int i = 0; i < kids.size(); i++)
        {
            ui->studentSelect->addItem(kids.at(i).name);
        }

        for (int y = 0; y < kids.size(); y++)
        {
            ui->fileDisplay->addItem(kids.at(y).name);
        }

        file.close();
    }//end if

    countCash();
}
Exemplo n.º 23
0
bool RemotePlugin::init( const QString &pluginExecutable,
							bool waitForInitDoneMsg )
{
	lock();
	if( m_failed )
	{
#ifdef SYNC_WITH_SHM_FIFO
		reset( new shmFifo(), new shmFifo() );
#endif
		m_failed = false;
	}
	QString exec = QFileInfo(QDir("plugins:"), pluginExecutable).absoluteFilePath();
#ifdef LMMS_BUILD_APPLE
	// search current directory first
	QString curDir = QCoreApplication::applicationDirPath() + "/" + pluginExecutable;
	if( QFile( curDir ).exists() )
	{
		exec = curDir;
	}
#endif
#ifdef LMMS_BUILD_WIN32
	if( ! exec.endsWith( ".exe", Qt::CaseInsensitive ) )
	{
		exec += ".exe";
	}
#endif

	if( ! QFile( exec ).exists() )
	{
		qWarning( "Remote plugin '%s' not found.",
						exec.toUtf8().constData() );
		m_failed = true;
		invalidate();
		unlock();
		return failed();
	}

	QStringList args;
#ifdef SYNC_WITH_SHM_FIFO
	// swap in and out for bidirectional communication
	args << QString::number( out()->shmKey() );
	args << QString::number( in()->shmKey() );
#else
	args << m_socketFile;
#endif
#ifndef DEBUG_REMOTE_PLUGIN
	m_process.setProcessChannelMode( QProcess::ForwardedChannels );
	m_process.setWorkingDirectory( QCoreApplication::applicationDirPath() );
	m_process.start( exec, args );
	m_watcher.start( QThread::LowestPriority );
#else
	qDebug() << exec << args;
#endif

	connect( &m_process, SIGNAL( finished( int, QProcess::ExitStatus ) ),
		this, SLOT( processFinished( int, QProcess::ExitStatus ) ) );

#ifndef SYNC_WITH_SHM_FIFO
	struct pollfd pollin;
	pollin.fd = m_server;
	pollin.events = POLLIN;

	switch ( poll( &pollin, 1, 30000 ) )
	{
		case -1:
			qWarning( "Unexpected poll error." );
			break;

		case 0:
			qWarning( "Remote plugin did not connect." );
			break;

		default:
			m_socket = accept( m_server, NULL, NULL );
			if ( m_socket == -1 )
			{
				qWarning( "Unexpected socket error." );
			}
	}
#endif

	resizeSharedProcessingMemory();

	if( waitForInitDoneMsg )
	{
		waitForInitDone();
	}
	unlock();

	return failed();
}
Exemplo n.º 24
0
void MainWindow::checkForSaveFile()
{
    QFile file2("autosave.dat");
    QString fileInput = "autosave.dat";

    if (!file2.exists() && !QFile(QString(".autosave.dat")).exists())
        QString fileInput = QFileDialog::getSaveFileName(this, tr("Autosave File"), "", tr("Data File (*.dat)"));

    else if (!file2.exists() && QFile(QString(".autosave.dat")).exists())
        QFile(QString(".autosave.dat")).copy(fileInput);

    QList<QString> asList;

    if (fileInput != "")
    {
        /**
          Load the last save into memory.

          Allows us to extract the serials/class members.
          **/

        QFile file(fileInput);
        if (!file.open(QIODevice::ReadOnly))
        {
            QMessageBox::critical(this, tr("Error"), tr("Could not open file"));
            return;
        }//end if
        QTextStream in(&file);


        while (!in.atEnd())
        {
            asList.push_back(in.readLine());
        }//iterate through the file. All of it. Store.
    }//end if.

    for (int x = 0; x < asList.size(); x++)
    {
        /**
          Now, we segment the file.
          **/
        QString current = asList.at(x);
        QString flipped = reverse(current);
        QList<QString> currentKid;

        int y = x;

        while (asList.at(y) != flipped)
        {
            y++;
        }

        for (int z = x; z < y; z++)
        {
            currentKid.push_back(asList.at(z));
            x++;
        }//end for z.

        if (true)
        {
            QString last = currentKid.at(0);
            QString email = currentKid.at(1);
            int index = email.indexOf(":") + 1;
            email.remove(0, index);
            QString period = currentKid.at(2);
            index = period.indexOf(":") + 1;
            period.remove(0, index);
            QString balance = currentKid.at(3);

            KedighKid toPush(last, period, email);


            for (int i = 4; i < currentKid.size(); i++)
            {
                QString line = currentKid.at(i);
                QString tabLength = "\t\t";
                line.remove(0, tabLength.length());
                int index = line.indexOf(":");
                QString serial = line;
                serial.remove(index, line.size());
                QString denom = line;
                denom.remove(0, serial.size());
                QString toSize = " $";
                denom.remove(0, 3);
                int _denomination = denom.toInt();

                KedighCash money(serial, "Today", _denomination);
                toPush.addMoney(money);
            }
            kids.push_back(toPush);
            x++;
        }
    }

    qSort(kids.begin(), kids.end());
    for (int i = 0; i < kids.size(); i++)
    {
        ui->studentSelect->addItem(kids.at(i).name);
    }

    for (int y = 0; y < kids.size(); y++)
    {
        ui->fileDisplay->addItem(kids.at(y).name);
    }

    countCash();
    displayInfo();
}//open last save.
Exemplo n.º 25
0
//------------------------------Value------------------------------------------
const Type *ProjNode::Value( PhaseTransform *phase ) const {
  if (in(0) == NULL) return Type::TOP;
  return proj_type(phase->type(in(0)));
}
Exemplo n.º 26
0
int main (int argc, char* argv[]) {
    set<string> words;
    vector<int> locations;
    BaseBogglePlayer * p = new BogglePlayer();
    set<string> lex;
    std::ifstream in("/Users/m2/Desktop/pa4/pa4/brd.txt");
    string n, m;
    getline(in, n);
    getline(in, m);
    int r = std::atoi(n.c_str());
    int c = std::atoi(m.c_str());
    string **board = new string*[c];
    for (int i = 0; i < r; i++)
        board[i] = new string[c];
    for (int i = 0; i < r; i++) {
        for (int j = 0; j < c; j++) {
            getline(in, board[i][j]);
            //cout << board[i][j] << " ";
        }
        //cout << "\n";
    }
    in.close();
    in.open("/Users/m2/Desktop/pa4/pa4/lex.txt");
    string line;
    while (in.good()) {
        getline(in, line);
        if (in.good()) lex.insert(line);
    }
  /*string wordA("nod");
  string wordB("where");
  string wordC("do");
  string wordD("we");
  string wordE("go");
  string wordX("fvrst");
  lex.insert(wordA);
  lex.insert(wordC);
  lex.insert(wordD);
  lex.insert(wordE);
  lex.insert(wordB);
  string row0[] = {"a","a","a","fv","a","a","a","a"};
  string row1[] = {"e","f","g","h","rst","a","i","v"};
  string row2[] = {"i","j","k", "l","r","a","i","v"};
  string row3[] = {"r","a","i","v","a","c","d","f"};
  string* board[] = {row0,row1,row2,row3};*/


  p->buildLexicon(lex);

  p->setBoard(r,c,board);

  /*if(p->isInLexicon(wordX)) {
    std::cerr << "Apparent problem with isInLexicon #1." << std::endl;
    return -1;
  }
  if(!p->isInLexicon(wordA) || !p->isInLexicon(wordB)) {
    std::cerr << "Apparent problem with isInLexicon #2." << std::endl;
    return -1;
  }
    locations = p->isOnBoard(wordX);
  if(p->isOnBoard(wordX).size() > 0) {
      for (int i = 0; i < locations.size(); i++) std::cout << locations[i] << " " << board[(locations[i]-locations[i]%8)/8][locations[i]%8] << "\n";
    std::cerr << "Apparent problem with isOnBoard #1." << std::endl;
    return -1;
  }
  locations.clear();
  locations = p->isOnBoard(wordA);
  if(locations.size() != 3 || locations[0] != 3) {
    std::cerr << "Apparent problem with isOnBoard #2." << std::endl;
    return -1;
  }*/
  if(!p->getAllValidWords(2,&words)) {
    std::cerr << "Apparent problem with getAllValidWords #1." << std::endl;
    return -1;
  };
 /*if(words.size() != 2 || words.count(wordA) != 1) {
      std::set<string>::iterator it;
      for (it = words.begin(); it != words.end(); ++it)
          std::cout << *it << "\n";
    std::cerr << "Apparent problem with getAllValidWords #2." << std::endl;
    return -1;
  }*/
  delete p;
  return 0;

}
Exemplo n.º 27
0
// Test if we propagate interesting control along this projection
bool ProjNode::is_CFG() const {
  Node *def = in(0);
  return (_con == TypeFunc::Control && def->is_CFG());
}
Exemplo n.º 28
0
bool QtCurveHandler::readConfig(bool compositingToggled)
{
    QtCurveConfig      oldConfig=m_config;
    KConfig            configFile("kwinqtcurverc");
    const KConfigGroup config(&configFile, "General");
    QFontMetrics       fm(m_titleFont);  // active font = inactive font
    int                oldSize=m_titleHeight,
                       oldToolSize=m_titleHeightTool;
    bool               changedBorder=false;

    // The title should stretch with bigger font sizes!
    m_titleHeight = qMax(16, fm.height() + 4); // 4 px for the shadow etc.
    // have an even title/button size so the button icons are fully centered...
    if (m_titleHeight%2 == 0)
        m_titleHeight++;

    fm = QFontMetrics(m_titleFontTool);  // active font = inactive font
    // The title should stretch with bigger font sizes!
    m_titleHeightTool = qMax(13, fm.height()); // don't care about the shadow etc.
    // have an even title/button size so the button icons are fully centered...
    if (m_titleHeightTool%2 == 0)
        m_titleHeightTool++;

    m_config.load(&configFile);

#if KDE_IS_VERSION(4, 3, 85)
    static bool borderHack=false;
    if(borderHack)
    {
    m_config.setOuterBorder(KWindowSystem::compositingActive() ? QtCurveConfig::SHADE_NONE :
                             (m_config.customShadows() ? QtCurveConfig::SHADE_SHADOW : QtCurveConfig::SHADE_DARK));
        changedBorder=true;
        borderHack=false;
    }
    else if(compositingToggled && !m_config.outerBorder() &&
           (m_config.borderSize()<QtCurveConfig::BORDER_TINY ||
            (wStyle()->pixelMetric((QStyle::PixelMetric)QtC_WindowBorder, 0L, 0L)&WINDOW_BORDER_COLOR_TITLEBAR_ONLY)))
    {
        QDBusConnection::sessionBus().send(QDBusMessage::createSignal("/KWin", "org.kde.KWin", "reloadConfig"));
        borderHack=true;
    }
#endif

    m_titleHeight+=2*titleBarPad();

    QFile in(xdgConfigFolder() + "/qtcurve/" BORDER_SIZE_FILE);
    int   prevSize(-1), prevToolSize(-1), prevSide(-1), prevBot(-1);

    if(in.open(QIODevice::ReadOnly))
    {
        QTextStream stream(&in);
        prevSize=in.readLine().toInt();
        prevToolSize=in.readLine().toInt();
        prevBot=in.readLine().toInt();
        prevSide=in.readLine().toInt();
        in.close();
    }

    setBorderSize();

    int borderEdge=borderEdgeSize()*2;
    bool borderSizesChanged=prevSize!=(m_titleHeight+borderEdge) || prevToolSize!=(m_titleHeightTool+borderEdge) ||
                            prevBot!=borderSize(true) || prevSide!=borderSize(false);
    if(borderSizesChanged)
    {
        KSaveFile sizeFile(xdgConfigFolder() + "/qtcurve/" BORDER_SIZE_FILE);

        if (sizeFile.open())
        {
            QTextStream stream(&sizeFile);
            stream << m_titleHeight+borderEdge << endl
                   << m_titleHeightTool+borderEdge << endl
                   << borderSize(true) << endl
                   << borderSize(false) << endl;
            stream.flush();
            sizeFile.finalize();
            sizeFile.close();
        }
    }
#if KDE_IS_VERSION(4, 3, 0)
    bool shadowChanged(false);

    if(customShadows())
    {
        QtCurveShadowConfiguration actShadow(QPalette::Active),
                                   inactShadow(QPalette::Inactive);

        actShadow.load(&configFile);
        inactShadow.load(&configFile);

        shadowChanged=m_shadowCache.shadowConfigurationChanged(actShadow) ||
                      m_shadowCache.shadowConfigurationChanged(inactShadow);

        m_shadowCache.setShadowConfiguration(actShadow);
        m_shadowCache.setShadowConfiguration(inactShadow);

        if(shadowChanged || oldConfig.roundBottom()!=roundBottom())
            m_shadowCache.reset();
    }
#endif

    if(m_dBus && (borderSizesChanged || changedBorder))
    {
        m_dBus->emitBorderSizes(); // KDE4 apps...
        borderSizeChanged(); // Gtk2 apps...
    }

    return changedBorder ||
           oldSize!=m_titleHeight ||
           oldToolSize!=m_titleHeightTool ||
#if KDE_IS_VERSION(4, 3, 0)
           shadowChanged ||
#endif
           m_config!=oldConfig;
}
Exemplo n.º 29
0
void Loader::load()
{
    QFile in(QLatin1String("tree.xml"));

    /* LoadingModel::m_result will be null, signalling failure. */
    if(!in.open(QIODevice::ReadOnly))
        return;

    QXmlStreamReader reader(&in);
    while(!reader.atEnd())
    {
        reader.readNext();

        switch(reader.tokenType())
        {
            case QXmlStreamReader::StartDocument:
            /* Fallthrough. */
            case QXmlStreamReader::StartElement:
            {
                QXmlName name;
                if(reader.tokenType() == QXmlStreamReader::StartElement)
                {
                    name = QXmlName(m_namePool,
                                    reader.name().toString(),
                                    reader.namespaceUri().toString(),
                                    reader.prefix().toString());
                }
                /* Else, the name is null. */

                LoadingModel::Node *const tmp = new LoadingModel::Node(reader.tokenType() == QXmlStreamReader::StartElement
                                                                       ? QXmlNodeModelIndex::Element
                                                                       : QXmlNodeModelIndex::Document,
                                                                       m_parentStack.top(),
                                                                       QString(),
                                                                       name);
                m_result.append(tmp);

                if(m_currentNode)
                {
                    if(m_currentNode->parent == m_parentStack.top())
                        m_currentNode->followingSibling = tmp;
                }

                const QXmlStreamAttributes attributes(reader.attributes());
                const int len = attributes.count();

                for(int i = 0; i < len; ++i)
                {
                    const QXmlStreamAttribute &attr = attributes.at(i);
                    const LoadingModel::Node *const a = new LoadingModel::Node(QXmlNodeModelIndex::Attribute,
                                                                               m_parentStack.top(),
                                                                               attr.value().toString(),
                                                                               QXmlName(m_namePool,
                                                                                       attr.name().toString(),
                                                                                       attr.namespaceUri().toString(),
                                                                                       attr.prefix().toString()));
                    /* We add it also to m_result such that compareOrder() is correct
                     * for attributes. m_result owns a. */
                    tmp->attributes.append(a);
                    m_result.append(a);
                }

                adjustSiblings(tmp);
                m_parentStack.push(m_currentNode);
                break;
            }
            case QXmlStreamReader::EndDocument:
            /* Fallthrough. */
            case QXmlStreamReader::EndElement:
            {
                m_currentNode->followingSibling = 0;
                m_currentNode = m_parentStack.pop();

                if(reader.tokenType() == QXmlStreamReader::EndDocument)
                    const_cast<LoadingModel::Node *>(m_result.first())->followingSibling = 0;

                break;
            }
            case QXmlStreamReader::Characters:
            {
                LoadingModel::Node *const tmp = new LoadingModel::Node(QXmlNodeModelIndex::Text, m_parentStack.top(), reader.text().toString());
                m_result.append(tmp);
                adjustSiblings(tmp);
                break;
            }
            case QXmlStreamReader::ProcessingInstruction:
            {
                LoadingModel::Node *const tmp = new LoadingModel::Node(QXmlNodeModelIndex::ProcessingInstruction,
                                                                       m_parentStack.top(),
                                                                       reader.processingInstructionData().toString(),
                                                                       QXmlName(m_namePool, reader.processingInstructionTarget().toString()));
                m_result.append(tmp);
                adjustSiblings(tmp);
                break;
            }
            case QXmlStreamReader::Comment:
            {
                LoadingModel::Node *const tmp = new LoadingModel::Node(QXmlNodeModelIndex::Comment, m_parentStack.top(), reader.text().toString());
                m_result.append(tmp);
                adjustSiblings(tmp);
                break;
            }
            case QXmlStreamReader::DTD:
                qFatal("%s: QXmlStreamReader::DTD token is not supported", Q_FUNC_INFO);
                break;
            case QXmlStreamReader::EntityReference:
                qFatal("%s: QXmlStreamReader::EntityReference token is not supported", Q_FUNC_INFO);
                break;
            case QXmlStreamReader::NoToken:
            /* Fallthrough. */
            case QXmlStreamReader::Invalid:
            {
                qWarning("%s", qPrintable(reader.errorString()));
                m_result.clear();
                return;
            }
        }
    }

    if(reader.hasError())
    {
        qWarning("%s", qPrintable(reader.errorString()));
        m_result.clear();
    }
}
Exemplo n.º 30
0
  void Path::copy(const std::string & source, const std::string & destination)
  {
    NTA_CHECK(!source.empty()) 
      << "Can't copy from an empty source";

    NTA_CHECK(!destination.empty()) 
      << "Can't copy to an empty destination";

    NTA_CHECK(source != destination)
      << "Source and destination must be different";
      
    if (isDirectory(source))
    {
      Directory::copyTree(source, destination);
      return;
    } 

    // The target is always a filename. The input destination
    // Can be either a directory or a filename. If the destination
    // doesn't exist it is treated as a filename.
    std::string target(destination);
    if (Path::exists(destination) && isDirectory(destination))
      target = Path::normalize(Path::join(destination, Path::getBasename(source)));
    
    bool success = true;
  #ifdef WIN32

    // Must remove read-only or hidden files before copy 
    // because they cannot be overwritten. For simplicity
    // I just always remove if it exists.
    if (Path::exists(target))
      Path::remove(target);

    // This will quietly overwrite the destination file if it exists
    std::wstring wsource(utf8ToUnicode(source));
    std::wstring wtarget(utf8ToUnicode(target));
    BOOL res = ::CopyFileW(wsource.c_str(), 
                          wtarget.c_str(), 
                           FALSE);

    success = res != FALSE;
  #else

    try
    {
      OFStream  out(target.c_str()); 
      out.exceptions(std::ofstream::failbit | std::ofstream::badbit);
      UInt64 size = Path::getFileSize(source);
      if(size) {
        IFStream  in(source.c_str());
        if(out.fail()) {
          std::cout << OS::getErrorMessage() << std::endl;
        }
        in.exceptions(std::ifstream::failbit | std::ifstream::badbit);
        out << in.rdbuf();
      }
    }
    catch(std::exception &e) {
      std::cerr << "Path::copy('" << source << "', '" << target << "'): "
           << e.what() << std::endl;
    }
    catch (...)
    {
      success = false;
    }
  #endif
    if (!success)
      NTA_THROW << "Path::copy() - failed copying file " 
                << source << " to " << destination << " os error: "
                << OS::getErrorMessage();
  }