コード例 #1
0
ファイル: Scparag3.cpp プロジェクト: jimmccurdy/ArchiveGit
eRefEvent scContUnit::Reformat2( scCOLRefData&	cData,
								 PrevParaData&	prevParaData,
								 int			keepWNextControl,
								 int&			breakControl			
#if SCDEBUG > 1
								, int&			reformatEvent 
#endif
								)
{

	DCState	dcState;
	Bool	tryAgain;
	Bool	leadRetry		= false;	// a retry based upon a leading increase on the line
	Bool	overFlow		= false;
	Bool	testGetStrip	= true;


	SCDebugTrace( 1, scString( "scContUnit::Reformat IN 0x%08x %d\n" ), this, GetCount() );

	cData.PARAInit( this, breakControl, keepWNextControl, prevParaData );
 
	dcState.SetColumn( cData.GetActive()  );
	scFlowDir fd( cData.fCol->GetFlowdir() );
	
	if ( cData.fPData.fPrevline ) {
		if ( fd.IsHorizontal() )
			cData.fSavedPrevEnd.x = LONG_MAX;
		else {
			cData.fSavedPrevEnd.y = LONG_MAX;
		}
	}

	for ( tryAgain = true; tryAgain; ) {
		for ( overFlow = false; cData.fPData.fBreakType != eEndStreamBreak || overFlow; ) {
			
			if ( !overFlow )
				cData.fPData.SetLineData( leadRetry );		// set up initial line conditions
			
			if ( !overFlow && cData.AllocGeometry() ) {	  	// allocatate the geometry from
															// the parent column, if we overflow
															// the column, we go to the next column

				try {
					cData.AllocLine( leadRetry );	 		// allocate the memory, reuse scheme is used
				} 
				catch( ... ) {
					cData.fPData.PARAFini( );
					throw;
				} 

				cData.fPData.SetColumn( cData.fCol );
				leadRetry = cData.fPData.ComposeLine( dcState );  // compose the line
				
				if ( !leadRetry ) {
					// we are accepting the line as is 
					MicroPoint x, y;
					if ( fd.IsHorizontal() ) {
						x = cData.fPData.fComposedLine.fOrg.x + cData.fPData.fComposedLine.fMeasure;
						y = cData.fPData.fComposedLine.fOrg.y;
					}
					else {
						x = cData.fPData.fComposedLine.fOrg.x;
						y = cData.fPData.fComposedLine.fOrg.y + cData.fPData.fComposedLine.fMeasure;
					}
					cData.fSavedPrevEnd.Set( x, y );
				}
				else
					; // we are going to reposition the line and rebreak it
			}
			else {
					// No more room in column, let's try the next column
				overFlow	= false;

					// if we try and relead at the bottom of a container and we 
					// overflow we need to set "leadRetry" to false since at this
					// point it is not a retry any more but a whole new container
				leadRetry 	= false;

				if ( !cData.fPData.fPrevline )
					testGetStrip = false;

				if ( !breakControl && cData.ResetOrphan( testGetStrip ) ) {
					breakControl++;
					return eRebreak;
				}
				
				cData.fCol->DeleteExcessLines( this, cData.fPData.fPrevline, testGetStrip, cData );
				testGetStrip = true;

					// find the next column 
				if ( cData.FindNextCol( dcState ) )	{
						// the finding of the next column may reset the para spec
					scCachedStyle::SetParaStyle( this, defspec_ ); 
					continue;
				}
				else {
					overFlow = true;
					break;
				}
			}


		}

		tryAgain = ResetWidow( cData, testGetStrip );

	}

	if ( GetFirstline() )
		cData.PARADeleteExcessLines( );

#if SCDEBUG > 1
	SetReformatEvent( reformatEvent++ );
#endif

	Unmark( scREBREAK );

	if ( !overFlow )
		scAssert( GetLastline() != 0 );

	cData.fPData.PARAFini( );

	prevParaData.lastLineH	= cData.fPData.fTextline;
	prevParaData.lastSpec	= cData.fPData.fCurSpecRec->spec();

	SCDebugTrace( 1, scString( "scContUnit::Reformat OUT 0x%08x %d\n" ), this, GetCount() );

	return !overFlow ? eNormalReformat : eOverflowGeometry;
}
コード例 #2
0
ファイル: ip++.cpp プロジェクト: Proteas/codesign
void Socket::listen(int backlog)
{
    checkError(::listen(fd(), backlog));
}
コード例 #3
0
ファイル: ip++.cpp プロジェクト: Proteas/codesign
void Socket::shutdown(int how)
{
    assert(how >= 0 && how <= 2);
    checkError(::shutdown(fd(), how));
}
コード例 #4
0
void RTFDocVisitor::visit(DocInclude *inc)
{
  if (m_hide) return;
  SrcLangExt langExt = getLanguageFromFileName(inc->extension());
  DBG_RTF("{\\comment RTFDocVisitor::visit(DocInclude)}\n");
  switch(inc->type())
  {
     case DocInclude::IncWithLines:
      { 
         m_t << "{" << endl;
         m_t << "\\par" << endl;
         m_t << rtf_Style_Reset << getStyle("CodeExample");
         QFileInfo cfi( inc->file() );
         FileDef fd( cfi.dirPath().utf8(), cfi.fileName().utf8() );
         Doxygen::parserManager->getParser(inc->extension())
                               ->parseCode(m_ci,inc->context(),
                                           inc->text(),
                                           langExt,
                                           inc->isExample(),
                                           inc->exampleFile(), &fd);
         m_t << "\\par";
         m_t << "}" << endl;
      }
      break;
    case DocInclude::Include: 
      m_t << "{" << endl;
      m_t << "\\par" << endl;
      m_t << rtf_Style_Reset << getStyle("CodeExample");
      Doxygen::parserManager->getParser(inc->extension())
                            ->parseCode(m_ci,inc->context(),
                                        inc->text(),langExt,inc->isExample(),
                                        inc->exampleFile());
      m_t << "\\par";
      m_t << "}" << endl;
      break;
    case DocInclude::DontInclude: 
      break;
    case DocInclude::HtmlInclude: 
      break;
    case DocInclude::LatexInclude:
      break;
    case DocInclude::VerbInclude: 
      m_t << "{" << endl;
      m_t << "\\par" << endl;
      m_t << rtf_Style_Reset << getStyle("CodeExample");
      filter(inc->text());
      m_t << "\\par";
      m_t << "}" << endl;
      break;
    case DocInclude::Snippet:
      m_t << "{" << endl;
      if (!m_lastIsPara) m_t << "\\par" << endl;
      m_t << rtf_Style_Reset << getStyle("CodeExample");
      Doxygen::parserManager->getParser(inc->extension())
                            ->parseCode(m_ci,
                                        inc->context(),
                                        extractBlock(inc->text(),inc->blockId()),
                                        langExt,
                                        inc->isExample(),
                                        inc->exampleFile()
                                       );
      m_t << "}";
      break;
  }
  m_lastIsPara=TRUE;
}
コード例 #5
0
ファイル: ip++.cpp プロジェクト: Proteas/codesign
void Socket::open(int domain, int type, int protocol)
{
    checkSetFd(::socket(domain, type, protocol));
    mAtEnd = false;
    secdebug("sockio", "socket(%d,%d) -> %d", type, protocol, fd());
}
コード例 #6
0
ファイル: DisAsmFrame.cpp プロジェクト: 0179cool/rpcs3
void DisAsmFrame::Dump(wxCommandEvent& WXUNUSED(event)) 
{
	wxFileDialog ctrl( this, L"Select output file...",
		wxEmptyString, "DisAsm.txt", "*.txt", wxFD_SAVE);

	if(ctrl.ShowModal() == wxID_CANCEL) return;

	vfsLocalFile& f_elf = *new vfsLocalFile(nullptr);
	f_elf.Open(Emu.m_path);

	ConLog.Write("path: %s", Emu.m_path.c_str());
	Elf_Ehdr ehdr;
	ehdr.Load(f_elf);

	if(!ehdr.CheckMagic())
	{
		ConLog.Error("Corrupted ELF!");
		return;
	}
	std::vector<std::string> name_arr;

	switch(ehdr.GetClass())
	{
	case CLASS_ELF64:
		ElfType64 = true;
		l_elf64 = new ELF64Loader(f_elf);
		if(!l_elf64->LoadInfo())
		{
			delete l_elf64;
			return;
		}
		name_arr = l_elf64->shdr_name_arr;
		shdr_arr_64 = &l_elf64->shdr_arr;
		if(l_elf64->shdr_arr.size() <= 0) return;
	break;

	case CLASS_ELF32:
		ElfType64 = false;
		l_elf32 = new ELF32Loader(f_elf);
		if(!l_elf32->LoadInfo())
		{
			delete l_elf32;
			return;
		}

		name_arr = l_elf32->shdr_name_arr;
		shdr_arr_32 = &l_elf32->shdr_arr;
		if(l_elf32->shdr_arr.size() <= 0) return;
	break;

	default: ConLog.Error("Corrupted ELF!"); return;
	}

	PPCDisAsm* disasm;
	PPCDecoder* decoder;

	switch(Emu.GetCPU().GetThreads()[0]->GetType())
	{
	case CPU_THREAD_PPU:
	{
		PPUDisAsm* dis_asm = new PPUDisAsm(CPUDisAsm_DumpMode);
		decoder = new PPUDecoder(dis_asm);
		disasm = dis_asm;
	}
	break;

	case CPU_THREAD_SPU:
	case CPU_THREAD_RAW_SPU:
	{
		SPUDisAsm& dis_asm = *new SPUDisAsm(CPUDisAsm_DumpMode);
		decoder = new SPUDecoder(dis_asm);
		disasm = &dis_asm;
	}
	break;
	}

	const u32 shdr_count = ElfType64 ? shdr_arr_64->size() : shdr_arr_32->size();

	u64 max_count = 0;
	for(u32 sh=0; sh<shdr_count; ++sh)
	{
		const u64 sh_size = (ElfType64 ? (*shdr_arr_64)[sh].sh_size : (*shdr_arr_32)[sh].sh_size) / 4;
		max_count += sh_size;
	}

	wxArrayLong max;
	max.Add(max_count);
	MTProgressDialog& prog_dial = *new MTProgressDialog(NULL, wxDefaultSize, "Saving", "Loading...", max, 1);
	max.Clear();

	wxFile fd(ctrl.GetPath(), wxFile::write);

	for(u32 sh=0, vsize=0; sh<shdr_count; ++sh)
	{
		const u64 sh_size = (ElfType64 ? (*shdr_arr_64)[sh].sh_size : (*shdr_arr_32)[sh].sh_size) / 4;
		const u64 sh_addr = (ElfType64 ? (*shdr_arr_64)[sh].sh_addr : (*shdr_arr_32)[sh].sh_addr);

		const std::string name = sh < name_arr.size() ? name_arr[sh] : "Unknown";

		fd.Write(wxString::Format("Start of section header %s[%d] (instructions count: %d)\n", name.c_str(), sh, sh_size));
		prog_dial.Update(0, vsize, wxString::Format("Disasm %s section", name.c_str()));

		if(Memory.IsGoodAddr(sh_addr))
		{
			for(u64 addr=sh_addr; addr<sh_addr+sh_size; addr++, vsize++)
			{
				disasm->dump_pc = addr;
				decoder->Decode(Memory.Read32(disasm->dump_pc));
				fd.Write("\t");
				fd.Write(fmt::FromUTF8(disasm->last_opcode));
			}
		}
		fd.Write(wxString::Format("End of section header %s[%d]\n\n", name.c_str(), sh));
	}

	prog_dial.Close();
	Emu.Stop();
	/*
	SYSTEM_INFO si;
	GetSystemInfo(&si);
	const uint cores_count =
		(si.dwNumberOfProcessors < 1 || si.dwNumberOfProcessors > 8 ? 2 : si.dwNumberOfProcessors); 

	wxArrayLong max;
	max.Clear();

	u64 max_count = 0;

	if(ElfType64)
	{
		for(uint sh=0; sh<l_elf64->shdr_arr.GetCount(); ++sh)
		{
			max_count += l_elf64->shdr_arr[sh].sh_size / 4;
		}
	}
	else
	{
		for(uint sh=0; sh<l_elf32->shdr_arr.GetCount(); ++sh)
		{
			max_count += l_elf32->shdr_arr[sh].sh_size / 4;
		}
	}

	for(uint c=0; c<cores_count; ++c) max.Add(max_count / cores_count);
	for(uint c=0; c<max_count % cores_count; ++c) max[c]++;

	MTProgressDialog& prog_dial = *new MTProgressDialog(this, wxDefaultSize, "Dumping...", "Loading", max, cores_count);

	DumperThread* dump = new DumperThread[cores_count];
	wxArrayString** arr = new wxArrayString*[cores_count];

	bool* threads_done = new bool[cores_count];

	for(uint i=0; i<cores_count; ++i)
	{
		arr[i] = new wxArrayString[ElfType64 ? l_elf64->shdr_arr.GetCount() : l_elf32->shdr_arr.GetCount()];
		dump[i].Set(i, cores_count, &threads_done[i], prog_dial, arr);
		dump[i].Start();
	}

	WaitDumperThread& wait_dump = 
		*new WaitDumperThread(threads_done, cores_count, ctrl.GetPath(), prog_dial, arr);
	wait_dump.Start();
	*/
}
コード例 #7
0
ファイル: data_file.hpp プロジェクト: MapQuest/osm2pgsql
 /**
  * Grow file to given size.
  *
  * If the file is large enough already, nothing is done.
  * The file is never shrunk.
  *
  * @throws std::system_error if ftruncate(2) call failed
  */
 void grow(size_t new_size) const {
     if (size() < new_size) {
         osmium::util::resize_file(fd(), new_size);
     }
 }
コード例 #8
0
bool Maps::FileInfo::ReadMP2(const std::string & filename)
{
    if(filename.empty()) return false;

    Reset();

    std::ifstream fd(filename.c_str(), std::ios::binary);

    if(!fd.is_open())
    {
	DEBUG(DBG_GAME, DBG_WARN, "file not found " << filename);
	return false;
    }

    file = filename;
    kingdom_colors = 0;
    allow_human_colors = 0;
    allow_comp_colors = 0;
    rnd_races = 0;
    localtime = 0;

    u8  byte8;
    u16 byte16;
    u32 byte32;

    // magic byte
    fd.read(reinterpret_cast<char *>(&byte32), sizeof(byte32));
    SwapLE32(byte32);

    if(byte32 != 0x0000005C)
    {
	DEBUG(DBG_GAME, DBG_WARN, "incorrect maps file " << filename);
	fd.close();
	return false;
    }

    // level
    fd.read(reinterpret_cast<char *>(&byte16), sizeof(byte16));
    SwapLE16(byte16);

    switch(byte16)
    {
	case 0x00:
	    difficulty = Difficulty::EASY;
	    break;

	case 0x01:
	    difficulty = Difficulty::NORMAL;
	    break;

	case 0x02:
	    difficulty = Difficulty::HARD;
	    break;

	case 0x03:
	    difficulty = Difficulty::EXPERT;
	    break;

	default:
	    DEBUG(DBG_GAME, DBG_WARN, "incorrect difficulty" << ", maps: " << filename << ", load easy default");
	    break;
    }

    // width
    fd.read(reinterpret_cast<char *>(&byte8), 1);
    size_w = byte8;

    // height
    fd.read(reinterpret_cast<char *>(&byte8), 1);
    size_h = byte8;

    // kingdom color blue
    fd.read(reinterpret_cast<char *>(&byte8), 1);
    if(byte8) kingdom_colors |= Color::BLUE;

    // kingdom color green
    fd.read(reinterpret_cast<char *>(&byte8), 1);
    if(byte8) kingdom_colors |= Color::GREEN;

    // kingdom color red
    fd.read(reinterpret_cast<char *>(&byte8), 1);
    if(byte8) kingdom_colors |= Color::RED;

    // kingdom color yellow
    fd.read(reinterpret_cast<char *>(&byte8), 1);
    if(byte8) kingdom_colors |= Color::YELLOW;

    // kingdom color orange
    fd.read(reinterpret_cast<char *>(&byte8), 1);
    if(byte8) kingdom_colors |= Color::ORANGE;

    // kingdom color purple
    fd.read(reinterpret_cast<char *>(&byte8), 1);
    if(byte8) kingdom_colors |= Color::PURPLE;

    // allow human blue
    fd.read(reinterpret_cast<char *>(&byte8), 1);
    if(byte8) allow_human_colors |= Color::BLUE;

    // allow human green
    fd.read(reinterpret_cast<char *>(&byte8), 1);
    if(byte8) allow_human_colors |= Color::GREEN;

    // allow human red
    fd.read(reinterpret_cast<char *>(&byte8), 1);
    if(byte8) allow_human_colors |= Color::RED;

    // allow human yellow
    fd.read(reinterpret_cast<char *>(&byte8), 1);
    if(byte8) allow_human_colors |= Color::YELLOW;

    // allow human orange
    fd.read(reinterpret_cast<char *>(&byte8), 1);
    if(byte8) allow_human_colors |= Color::ORANGE;

    // allow human purple
    fd.read(reinterpret_cast<char *>(&byte8), 1);
    if(byte8) allow_human_colors |= Color::PURPLE;

    // allow comp blue
    fd.read(reinterpret_cast<char *>(&byte8), 1);
    if(byte8) allow_comp_colors |= Color::BLUE;

    // allow comp green
    fd.read(reinterpret_cast<char *>(&byte8), 1);
    if(byte8) allow_comp_colors |= Color::GREEN;

    // allow comp red
    fd.read(reinterpret_cast<char *>(&byte8), 1);
    if(byte8) allow_comp_colors |= Color::RED;

    // allow comp yellow
    fd.read(reinterpret_cast<char *>(&byte8), 1);
    if(byte8) allow_comp_colors |= Color::YELLOW;

    // allow comp orange
    fd.read(reinterpret_cast<char *>(&byte8), 1);
    if(byte8) allow_comp_colors |= Color::ORANGE;

    // allow comp purple
    fd.read(reinterpret_cast<char *>(&byte8), 1);
    if(byte8) allow_comp_colors |= Color::PURPLE;

    // kingdom count
    // fd.seekg(0x1A, std::ios_base::beg);
    // fd.read(&byte8, 1);

    // wins
    fd.seekg(0x1D, std::ios_base::beg);
    fd.read(reinterpret_cast<char *>(&byte8), 1);
    conditions_wins = byte8;

    // data wins
    fd.read(reinterpret_cast<char *>(&byte8), 1);
    wins1 = byte8;
    // data wins
    fd.read(reinterpret_cast<char *>(&byte8), 1);
    wins2 = byte8;
    // data wins
    fd.read(reinterpret_cast<char *>(&byte16), 2);
    SwapLE16(byte16);
    wins3 = byte16;
    // data wins
    fd.seekg(0x2c, std::ios_base::beg);
    fd.read(reinterpret_cast<char *>(&byte16), 2);
    SwapLE16(byte16);
    wins4 = byte16;

    // loss
    fd.seekg(0x22, std::ios_base::beg);
    fd.read(reinterpret_cast<char *>(&byte8), 1);
    conditions_loss = byte8;
    // data loss
    fd.read(reinterpret_cast<char *>(&byte16), 2);
    SwapLE16(byte16);
    loss1 = byte16;
    // data loss
    fd.seekg(0x2e, std::ios_base::beg);
    fd.read(reinterpret_cast<char *>(&byte16), 2);
    SwapLE16(byte16);
    loss2 = byte16;

    // start with hero
    fd.seekg(0x25, std::ios_base::beg);
    fd.read(reinterpret_cast<char *>(&byte8), 1);
    with_heroes = 0 == byte8;

    // race color
    fd.read(reinterpret_cast<char *>(&byte8), 1);
    races[0] = ByteToRace(byte8);
    if(Race::RAND == races[0]) rnd_races |= Color::BLUE;
    fd.read(reinterpret_cast<char *>(&byte8), 1);
    races[1] = ByteToRace(byte8);
    if(Race::RAND == races[1]) rnd_races |= Color::GREEN;
    fd.read(reinterpret_cast<char *>(&byte8), 1);
    races[2] = ByteToRace(byte8);
    if(Race::RAND == races[2]) rnd_races |= Color::RED;
    fd.read(reinterpret_cast<char *>(&byte8), 1);
    races[3] = ByteToRace(byte8);
    if(Race::RAND == races[3]) rnd_races |= Color::YELLOW;
    fd.read(reinterpret_cast<char *>(&byte8), 1);
    races[4] = ByteToRace(byte8);
    if(Race::RAND == races[4]) rnd_races |= Color::ORANGE;
    fd.read(reinterpret_cast<char *>(&byte8), 1);
    races[5] = ByteToRace(byte8);
    if(Race::RAND == races[5]) rnd_races |= Color::PURPLE;

    // name
    char bufname[LENGTHNAME];
    fd.seekg(0x3A, std::ios_base::beg);
    fd.read(bufname, LENGTHNAME);
    bufname[LENGTHNAME - 1] = 0;
    name = Game::GetEncodeString(bufname);

    // description
    char bufdescription[LENGTHDESCRIPTION];
    fd.seekg(0x76, std::ios_base::beg);
    fd.read(bufdescription, LENGTHDESCRIPTION);
    bufdescription[LENGTHDESCRIPTION - 1] = 0;
    description = Game::GetEncodeString(bufdescription);

    fd.close();
    
    //fill unions
    if(4 == conditions_wins)
    {
	u8 side1 = 0;
	u8 side2 = 0;

	const Colors colors(kingdom_colors);

	for(Colors::const_iterator
	    it = colors.begin(); it != colors.end(); ++it)
	{
	    if(Color::GetIndex(*it) < wins3)
		side1 |= *it;
	    else
		side2 |= *it;
	}

	for(u8 ii = 0; ii < KINGDOMMAX; ++ii)
	{
	    u8 cl = ByteToColor(ii);
	
	    if(side1 & cl)
		unions[ii] = side1;
	    else
	    if(side2 & cl)
		unions[ii] = side2;
	    else
		unions[ii] = cl;
	}
    }

    return true;
}
コード例 #9
0
bool
RemapRawSlabs::setFile(QList<QString> fl)
{
  m_fileName = fl;

  {
    m_slices.clear();

    QFileInfo fi(fl[0]);

    QString hdrflnm;
    hdrflnm = QFileDialog::getOpenFileName(0,
					"Load text header file",
					fi.absolutePath(),
					"Files (*.*)");

    int nfX0, nfY0, nfZ0;
    
    if (hdrflnm.isEmpty())
      {
	uchar nvt0;
	QFile fd(m_fileName[0]);
	fd.open(QFile::ReadOnly);
	fd.read((char*)&nvt0, sizeof(unsigned char));
	fd.read((char*)&nfX0, sizeof(int));
	fd.read((char*)&nfY0, sizeof(int));
	fd.read((char*)&nfZ0, sizeof(int));
	fd.close();
    
	m_voxelType = _UChar;
	if (nvt0 == 0) m_voxelType = _UChar;
	if (nvt0 == 1) m_voxelType = _Char;
	if (nvt0 == 2) m_voxelType = _UShort;
	if (nvt0 == 3) m_voxelType = _Short;
	if (nvt0 == 4) m_voxelType = _Int;
	if (nvt0 == 8) m_voxelType = _Float;

	m_headerBytes = m_skipBytes = 13;
	int nslices = nfX0;
	m_slices.append(nslices);
	
	for (int nf=1; nf<m_fileName.count(); nf++)
	  {
	    uchar nvt;
	    int nfX, nfY, nfZ;
	    QFile fd(m_fileName[nf]);
	    fd.open(QFile::ReadOnly);
	    fd.read((char*)&nvt, sizeof(unsigned char));
	    fd.read((char*)&nfX, sizeof(int));
	    fd.read((char*)&nfY, sizeof(int));
	    fd.read((char*)&nfZ, sizeof(int));
	    fd.close();
	    if (nvt != nvt0 || nfY != nfY0 || nfZ != nfZ0)
	      {
		QMessageBox::information(0, "", "Raw File format does not match");
		return false;
	      }
	    
	    nslices += nfX;
	    m_slices.append(nslices);
	  }
      }
    else
      {
	// load header information from a text file
	
	int nvt0, nvt;
	int nfX, nfY, nfZ;
	
	QFile fd(hdrflnm);
	fd.open(QFile::ReadOnly | QFile::Text);
	QTextStream in(&fd);

	QString line = (in.readLine()).simplified();
	QStringList words = line.split(" ", QString::SkipEmptyParts);
	if (words.count() >= 2)
	  {
	    int nvt0 = words[0].toInt();
	    m_voxelType = _UChar;
	    if (nvt0 == 0) m_voxelType = _UChar;
	    if (nvt0 == 1) m_voxelType = _Char;
	    if (nvt0 == 2) m_voxelType = _UShort;
	    if (nvt0 == 3) m_voxelType = _Short;
	    if (nvt0 == 4) m_voxelType = _Int;
	    if (nvt0 == 8) m_voxelType = _Float;
	    m_headerBytes = m_skipBytes = words[1].toInt();
	  }
	else
	  {
	    QMessageBox::information(0, "",
	     QString("Expecting voxeltype and headerbytes\nGot this %1").arg(line));
	    return false;
	  }

	int nslices = 0;
	while (!in.atEnd())
	  {
	    line = (in.readLine()).simplified();
	    words = line.split(" ", QString::SkipEmptyParts);
	    if (words.count() >= 3)
	      {
		nfX = words[0].toInt();
		nfY = words[1].toInt();
		nfZ = words[2].toInt();
		
		if (nslices == 0)
		  {
		    nfY0 = nfY;
		    nfZ0 = nfZ;
		  }
		else
		  {
		    if (nfY0 != nfY || nfZ0 != nfZ)
		      {
			QMessageBox::information(0, "",
			   QString("Slice size not same :: %1 %2 : %3 %4").\
			     arg(nfY0).arg(nfZ0).arg(nfY).arg(nfZ));
			return false;
		      }
		  }

		nslices += nfX;
		m_slices.append(nslices);
	      }
	    else
	      {
		QMessageBox::information(0, "",
	          QString("Expecting dimensions\nGot this %1").arg(line));
		return false;
	      }
	  }	
      }
    setGridSize(m_slices[m_slices.count()-1], nfY0, nfZ0);
  }
  //------------------------------
  m_bytesPerVoxel = 1;
  if (m_voxelType == _UChar) m_bytesPerVoxel = 1;
  else if (m_voxelType == _Char) m_bytesPerVoxel = 1;
  else if (m_voxelType == _UShort) m_bytesPerVoxel = 2;
  else if (m_voxelType == _Short) m_bytesPerVoxel = 2;
  else if (m_voxelType == _Int) m_bytesPerVoxel = 4;
  else if (m_voxelType == _Float) m_bytesPerVoxel = 4;

  if (m_voxelType == _UChar ||
      m_voxelType == _Char ||
      m_voxelType == _UShort ||
      m_voxelType == _Short)
    {
      findMinMaxandGenerateHistogram();
    }
  else
    {
      findMinMax();
      generateHistogram();
    }

  m_rawMap.append(m_rawMin);
  m_rawMap.append(m_rawMax);
  m_pvlMap.append(0);
  m_pvlMap.append(255);

  return true;
}
コード例 #10
0
ファイル: main.cpp プロジェクト: KDE/khangman
int main(int argc, char **argv)
{
    QApplication app(argc, argv);

    QStringList configFiles;
    configFiles << QStringLiteral("khangmanrc");
    Kdelibs4ConfigMigrator migrator(QStringLiteral("khangman"));
    migrator.setConfigFiles(configFiles);
    migrator.migrate();

    KLocalizedString::setApplicationDomain("khangman");
    QApplication::setApplicationName(QStringLiteral("khangman"));
    QApplication::setApplicationVersion(KHM_VERSION);
    QApplication::setOrganizationDomain(QStringLiteral("kde.org"));
    QApplication::setApplicationDisplayName(i18n("KHangMan"));
    QApplication::setWindowIcon(QIcon::fromTheme(QStringLiteral("khangman")));

    app.connect(&app, &QGuiApplication::lastWindowClosed, &app, &QCoreApplication::quit);

    KAboutData aboutData(I18N_NOOP("khangman"),
                         i18n("KHangMan"),
                         I18N_NOOP(KHM_VERSION),
                         i18n(description),
                         KAboutLicense::GPL,
                         i18n("(c) 2001-2011, Anne-Marie Mahfouf"));
    aboutData.addAuthor(i18n("Primoz Anzur"), i18n("Previous maintainer"),
            QStringLiteral("[email protected]"));

    // Write the names with accents and all and this file save with
    // utf8 encoding.
    aboutData.addAuthor(i18n("Anne-Marie Mahfouf"), i18n("Original Author"),
                        QStringLiteral("[email protected]"), QStringLiteral("http://annma.blogspot.com"), QStringLiteral("annma"));
    aboutData.addAuthor(i18n("Rahul Chowdhury"), i18n("Developer"),
                        QStringLiteral("[email protected]"), QStringLiteral("http://rahulc93.wordpress.com/"), QStringLiteral("rahulch"));
    aboutData.addCredit(i18n("Stefan Böhmann"),
                        i18n("Coding help"), QStringLiteral("[email protected]"), QStringLiteral("http://www.hilefoks.org"), QStringLiteral("hilefoks"));
    aboutData.addCredit(i18n("Stefan Asserhäll"),
                        i18n("Swedish data files, coding help, transparent pictures and i18n fixes"),
                                QStringLiteral("[email protected]"));
    aboutData.addCredit(i18n("eXParTaKus"),
                        i18n("Spanish data files"), QStringLiteral("[email protected]"));
    aboutData.addCredit(i18n("Erik Kjær Pedersenn"),
                        i18n("Danish data files"), QStringLiteral("[email protected]") );
    aboutData.addCredit(i18n("Niko Lewman"),
                        i18n("Finnish data files"), QStringLiteral("[email protected]") );
    aboutData.addCredit(i18n("João Sebastião de Oliveira Bueno"),
                        i18n("Brazilian Portuguese data files"), QStringLiteral("[email protected]") );
    aboutData.addCredit(i18n("Antoni Bella"),
                        i18n("Catalan data files"), QStringLiteral("[email protected]"));
    aboutData.addCredit(i18n("Giovanni Venturi"),
                        i18n("Italian data files"), QStringLiteral("[email protected]"));
    aboutData.addCredit(i18n("Rinse"),
                        i18n("Dutch data files"), QStringLiteral("[email protected]"));
    aboutData.addCredit(i18n("Lukáš Tinkl"),
                        i18n("Czech data files"), QStringLiteral("[email protected]"));
    aboutData.addCredit(i18n("Kristóf Kiszel"),
                        i18n("Hungarian data files"), QStringLiteral("[email protected]"));
    aboutData.addCredit(i18n("Torger Åge Sinnes"),
                        i18n("Norwegian (Bokmål) data files"), QStringLiteral("[email protected]"));
    aboutData.addCredit(i18n("Roger Kovacs"),
                        i18n("Tajik data files"), QStringLiteral("[email protected]"));
    aboutData.addCredit(i18n("Chusslove Illich"),
                        i18n("Serbian (Cyrillic and Latin) data files"), QStringLiteral("[email protected]"));
    aboutData.addCredit(i18n("Jure Repinc"),
                        i18n("Slovenian data files"), QStringLiteral("[email protected]"));
    aboutData.addCredit(i18n("Pedro Morais"),
                        i18n("Portuguese data files"), QStringLiteral("[email protected]"));
    aboutData.addCredit(i18n("Gaute Hvoslef Kvalnes"),
                        i18n("Norwegian (Nynorsk) data files"), QStringLiteral("[email protected]"));
    aboutData.addCredit(i18n("Mehmet Özel"),
                        i18n("Turkish data files"), QStringLiteral("[email protected]"));
    aboutData.addCredit(i18n("Черепанов Андрей"),
                        i18n("Russian data files"), QStringLiteral("[email protected]"));
    aboutData.addCredit(i18n("Radostin Radnev"),
                        i18n("Bulgarian data files"), QStringLiteral("[email protected]"));
    aboutData.addCredit(i18n("Kevin Patrick Scannell"),
                        i18n("Irish (Gaelic) data files"), QStringLiteral("[email protected]"));
    aboutData.addCredit(i18n("Matt Howe"),
                        i18n("Softer Hangman Pictures"), QStringLiteral("[email protected]"));
    aboutData.addCredit(i18n("Benjamin Meyer"),
                        i18n("Coding help"), QStringLiteral("[email protected]"));
    aboutData.addCredit(i18n("Robert Gogolok"),
                        i18n("Coding help"), QStringLiteral("[email protected]"));
    aboutData.addCredit(i18n("Lubos Lunàk"),
                        i18n("Coding help"), QStringLiteral("[email protected]"));
    aboutData.addCredit(i18n("Albert Astals Cid"),
                        i18n("Coding help, fixed a lot of things"), QStringLiteral("[email protected]"));
    aboutData.addCredit(i18n("Peter Hedlund"),
                        i18n("Code for generating icons for the characters toolbar"), QStringLiteral("[email protected]"));
    aboutData.addCredit(i18n("Inge Wallin"),
                        i18n("Code cleaning"), QStringLiteral("[email protected]"));
    aboutData.setTranslator(i18nc("NAME OF TRANSLATORS", "Your names"), i18nc("EMAIL OF TRANSLATORS", "Your emails"));

    KAboutData::setApplicationData(aboutData);

    KCrash::initialize();

    QFont f(QStringLiteral("Domestic Manners"), 12, QFont::Normal, true);
    if (!QFontInfo(f).exactMatch())
    {
        QFontDatabase::addApplicationFont(QStandardPaths::locate(QStandardPaths::DataLocation, QStringLiteral("fonts/Domestic_Manners.ttf")));
    }

    QFont fd(QStringLiteral("Dustismo Roman"), 12, QFont::Normal, true);
    if (!QFontInfo(fd).exactMatch())
    {
        QFontDatabase::addApplicationFont(QStandardPaths::locate(QStandardPaths::DataLocation, QStringLiteral("fonts/Dustismo_Roman.ttf")));
    }

    KHangMan hangman;
    QObject::connect(hangman.getEngine(), &QQmlEngine::quit, &app, &QCoreApplication::quit);
    hangman.show();
    return app.exec();
}
コード例 #11
0
// Save file, return ok (false if save canceled)
void CentralWorkSaver::SaveFile( bool prompt, FILE_MODE fm, bool save_as )
{
    bool ok=true;
    if( prompt )
    {
        wxString msg = "Save changes to ";
        msg += gc->pgn_filename;
        msg += " ?";
        int answer = wxMessageBox( msg, "Confirm",  wxYES_NO|wxCANCEL, objs.frame );
        if( answer == wxCANCEL )
            any_cancel = true;
        if( answer != wxYES )
            ok = false;
    }
    if( ok )
    {
        switch( fm )
        {
            case FILE_EXISTS_GAME_UNCHANGED:
            case FILE_EXISTS_GAME_MODIFIED:
            case FILE_EXISTS_GAME_NEW:
            {
                if( !save_as )
                {
                    if( fm == FILE_EXISTS_GAME_NEW )
                        AddGameToFile();
                    else if( fm == FILE_EXISTS_GAME_MODIFIED )
                        PutBackDocument();
                    gc->FileSave( gc_clipboard );
                    gd->modified = false;
                    gd->game_details_edited = false;
                    undo->Clear(*gd);
                }
                else
                {
                    ok = false;
                    wxFileDialog fd( objs.frame, "Create new .pgn file, or append games to existing .pgn file", "", "", "*.pgn", wxFD_SAVE ); //|wxFD_CHANGE_DIR );
                    wxString dir = objs.repository->nv.m_doc_dir;
                    fd.SetDirectory(dir);
                    int answer = fd.ShowModal();
                    if( answer == wxID_CANCEL )
                        any_cancel = true;
                    if( answer == wxID_OK)
                    {
                        wxString dir;
                        wxFileName::SplitPath( fd.GetPath(), &dir, NULL, NULL );
                        objs.repository->nv.m_doc_dir = dir;
                        wxString wx_filename = fd.GetPath();
                        std::string filename = wx_filename.c_str();
                        if( !::wxFileExists(wx_filename ) )
                        {
                            if( fm == FILE_EXISTS_GAME_NEW )
                                AddGameToFile();
                            else if( fm == FILE_EXISTS_GAME_MODIFIED )
                                PutBackDocument();
                            gc->FileSaveAs( filename, gc_clipboard );
                            gd->modified = false;
                            gd->game_details_edited = false;
                            undo->Clear(*gd);
                            ok = true;
                        }

                        // Else if it's an existing file, load it and add file, then this game to
                        //  end of a new file game list
                        else
                        {
                            if( fm == FILE_EXISTS_GAME_NEW )
                                AddGameToFile();
                            else if( fm == FILE_EXISTS_GAME_MODIFIED )
                                PutBackDocument();
                            gc->Debug( "Games that are about to be added to an existing file" );
                            std::vector<GameDocument> gds = gc->gds;
                            if( !gc->Load(filename) )
                            {
                                wxString msg="Cannot append to existing file ";
                                msg += wx_filename;
                                wxMessageBox( msg, "Error reading file", wxOK|wxICON_ERROR );
                                gc->gds = gds;
                            }
                            else
                            {
                                gc->Debug( "The existing file" );
                                int existing_nbr = gc->gds.size();
                                for( int i=0; i<gds.size(); i++ )
                                {
                                    GameDocument doc = gds[i];
                                    doc.game_nbr = existing_nbr + i;
                                    if( doc.current_game )
                                    {
                                        gd->game_nbr = doc.game_nbr+1;  // todo: why +1 ?
                                        objs.gl->file_game_idx = doc.game_nbr;
                                    }
                                    gc->gds.push_back( doc );
                                }
                                gc->FileSave( gc_clipboard );
                                gc->KillResumePreviousWindow();
                                gd->modified = false;
                                gd->game_details_edited = false;
                                undo->Clear(*gd);
                                ok = true;
                            }
                            gc->Debug( "After adding games to an existing file" );
                        }
                    }
                }
                break;
            }

            case FILE_NEW_GAME_NEW:
            {
                ok = false;
                wxFileDialog fd( objs.frame, "Save either to a new or existing .pgn file", "", "", "*.pgn", wxFD_SAVE ); //|wxFD_CHANGE_DIR );
                wxString dir = objs.repository->nv.m_doc_dir;
                fd.SetDirectory(dir);
                int answer = fd.ShowModal();
                if( answer == wxID_CANCEL )
                    any_cancel = true;
                if( answer == wxID_OK)
                {
                    wxString dir;
                    wxFileName::SplitPath( fd.GetPath(), &dir, NULL, NULL );
                    objs.repository->nv.m_doc_dir = dir;
                    gd->game_nbr = 0;
                    wxString wx_filename = fd.GetPath();
                    std::string filename = wx_filename.c_str();

                    // If it's a new file, create with single game
                    if( !::wxFileExists( wx_filename ) )
                    {
                        AddGameToFile();
                        gc->FileCreate( filename, *gd );
                        gd->modified = false;
                        gd->game_details_edited = false;
                        undo->Clear(*gd);
                        ok = true;
                    }

                    // Else if it's an existing file, load it and add this game to
                    //  end of a new file game list
                    else
                    {
                        if( !gc->Load(filename) )
                        {
                            wxString msg="Cannot append to existing file ";
                            msg += wx_filename;
                            wxMessageBox( msg, "Error reading file", wxOK|wxICON_ERROR );
                        }
                        else
                        {
                            AddGameToFile();
                            gc->FileSave( gc_clipboard );
                            gd->modified = false;
                            gd->game_details_edited = false;
                            undo->Clear(*gd);
                            ok = true;
                        }
                    }
                }
                break;
            }
        }
    }
}
コード例 #12
0
ファイル: diff_restore.cpp プロジェクト: AMDmi3/osm2go
int main(int argc, char **argv)
{
  int result = 0;

  if(argc != 4)
    return EINVAL;

  xmlInitParser();

  const std::string osm_path = argv[1];
  assert_cmpnum(osm_path[osm_path.size() - 1], '/');

  map_state_t dummystate;
  project_t project(dummystate, argv[2], osm_path);
  project.osmFile = argv[2] + std::string(".osm");

  bool b = project.parse_osm();
  if(!b) {
    std::cerr << "cannot open " << argv[1] << argv[2] << ": " << strerror(errno) << std::endl;
    return 1;
  }
  osm_t::ref osm = project.osm;
  assert(osm);

  assert_cmpnum(osm->uploadPolicy, osm_t::Upload_Blocked);
  assert(osm->sanity_check().isEmpty());

  const relation_t * const r255 = osm->relation_by_id(296255);
  assert(r255 != nullptr);
  assert_cmpnum(r255->flags, 0);
  assert_cmpnum(r255->members.size(), 165);
  assert_cmpnum(r255->tags.asMap().size(), 8);
  const node_t * const n72 = osm->node_by_id(638499572);
  assert_cmpnum(n72->tags.asMap().size(), 4);
  const object_t r255m572(const_cast<node_t *>(n72));
  std::vector<member_t>::const_iterator r255it = r255->find_member_object(r255m572);
  assert(r255it != r255->members.end());
  assert(r255it->role != nullptr);
  assert_cmpstr(r255it->role, "stop");
  const relation_t * const r66316 = osm->relation_by_id(66316);
  assert(r66316 != nullptr);
  object_t rmember(object_t::RELATION_ID, 296255);
  assert(!rmember.is_real());
  const std::vector<member_t>::const_iterator r66316it = r66316->find_member_object(rmember);
  assert(r66316it != r66316->members.end());
  // the child relation exists, so it should be stored as real ref
  assert(r66316it->object.is_real());

  assert_cmpnum(10, osm->nodes.size());
  assert_cmpnum(3, osm->ways.size());
  assert_cmpnum(4, osm->relations.size());

  assert(osm->is_clean(true));

  assert(project.diff_file_present());
  unsigned int flags = project.diff_restore();
  assert_cmpnum(flags, DIFF_RESTORED | DIFF_HAS_HIDDEN);

  verify_diff(osm);

  xmlString rel_str(r255->generate_xml("42"));
  printf("%s\n", rel_str.get());

  rel_str.reset(n72->generate_xml("42"));
  printf("%s\n", rel_str.get());

  char tmpdir[] = "/tmp/osm2go-diff_restore-XXXXXX";

  if(mkdtemp(tmpdir) == nullptr) {
    std::cerr << "cannot create temporary directory" << std::endl;
    result = 1;
  } else {
    // create an empty directoy
    std::string bpath = tmpdir + std::string("/") + argv[2];
    const std::string osmpath = bpath + '/' + argv[2] + ".osm";
    mkdir(bpath.c_str(), 0755);
    bpath.erase(bpath.rfind('/') + 1);
    // and create a new project from that
    std::unique_ptr<project_t> sproject(new project_t(dummystate, argv[2], bpath));
    // CAUTION: osm is shared between the projects now
    sproject->osm.reset(osm.get());

    // the directory is empty, there can't be any diff
    flags = sproject->diff_restore();
    assert_cmpnum(flags, DIFF_NONE_PRESENT);
    // should not do anything bad
    diff_restore(sproject, nullptr);

    sproject->diff_save();
    bpath += argv[2];
    std::string bdiff = bpath;
    std::string no_diff = bpath;
    bpath += '/';
    bpath += argv[2];
    bpath += '.';
    bpath += "diff";

    bdiff += "/backup.diff";
    assert(sproject->diff_file_present());
    assert_cmpnum(rename(bpath.c_str(), bdiff.c_str()), 0);
    // having backup.diff should still count as being present
    assert(sproject->diff_file_present());
    no_diff += "/no.diff";
    assert_cmpnum(rename(bdiff.c_str(), no_diff.c_str()), 0);
    assert(!sproject->diff_file_present());

    // saving without OSM data should just do nothing
    sproject->osm.release();
    // CAUTION: end of sharing
    sproject->diff_save();
    assert(!sproject->diff_file_present());

    // put the OSM data into this directory
    const std::string origosmpath = project.path + project.osmFile;
    symlink(origosmpath.c_str(), osmpath.c_str());
    sproject->osmFile = project.osmFile;
    bool pvalid = sproject->parse_osm();
    assert(pvalid);
    assert(sproject->osm);

    // now create a diff file dummy
    fdguard fd(open(bpath.c_str(), O_CREAT | O_WRONLY, 0600));
    assert(fd.valid());
    {
      fdguard none(-1);
      none.swap(fd);
    }
    assert(sproject->diff_file_present());
    sproject->diff_save();
    assert(!sproject->diff_file_present());

    assert_cmpnum(rename(no_diff.c_str(), bdiff.c_str()), 0);
    flags = sproject->diff_restore();
    assert_cmpnum(flags, DIFF_RESTORED | DIFF_HAS_HIDDEN);

    verify_diff(osm);

    unlink(osmpath.c_str());
    unlink(bdiff.c_str());
    bpath.erase(bpath.rfind('/'));
    rmdir(bpath.c_str());
    bpath.erase(bpath.rfind('/'));
    rmdir(bpath.c_str());
  }

  test_osmChange(osm, argv[3]);

  xmlCleanupParser();

  return result;
}
コード例 #13
0
//
// Executable code.
// Read from disk, evaluate properly, cache as indicated. The whole thing, so far.
//
void PolicyEngine::evaluateCode(CFURLRef path, AuthorityType type, SecAssessmentFlags flags, CFDictionaryRef context, CFMutableDictionaryRef result,
	bool handleUnsignedCode /* = true */)
{
	FileQuarantine qtn(cfString(path).c_str());
	if (qtn.flag(QTN_FLAG_HARD))
		MacOSError::throwMe(errSecCSFileHardQuarantined);
	
	CFRef<SecStaticCodeRef> code;
	MacOSError::check(SecStaticCodeCreateWithPath(path, kSecCSDefaultFlags, &code.aref()));
	OSStatus rc = noErr;	// last validation error
	
	const SecCSFlags validationFlags = kSecCSEnforceRevocationChecks;
	
	WhitelistPrescreen whitelistScreen(code); // pre-screening filter for whitelist pre-screening (only)

	SQLite::Statement query(*this,
		"SELECT allow, requirement, id, label, expires, flags, disabled, filter_unsigned, remarks FROM scan_authority"
		" WHERE type = :type"
		" ORDER BY priority DESC;");
	query.bind(":type").integer(type);
	SQLite3::int64 latentID = 0;		// first (highest priority) disabled matching ID
	std::string latentLabel;			// ... and associated label, if any
	while (query.nextRow()) {
		bool allow = int(query[0]);
		const char *reqString = query[1];
		SQLite3::int64 id = query[2];
		const char *label = query[3];
		double expires = query[4];
		sqlite3_int64 ruleFlags = query[5];
		SQLite3::int64 disabled = query[6];
		const char *filter = query[7];
		const char *remarks = query[8];
		
		CFRef<SecRequirementRef> requirement;
		MacOSError::check(SecRequirementCreateWithString(CFTempString(reqString), kSecCSDefaultFlags, &requirement.aref()));
		rc = SecStaticCodeCheckValidity(code, validationFlags, requirement);
		
		// ad-hoc sign unsigned code, skip of Gatekeeper is off or the rule is disabled; but always do it for whitelist recording
		if (rc == errSecCSUnsigned && handleUnsignedCode && (!(disabled || overrideAssessment()) || SYSPOLICY_RECORDER_MODE_ENABLED())) {
			if (!SYSPOLICY_RECORDER_MODE_ENABLED()) {
				// apply whitelist pre-screening to speed things up for non-matches
				if (ruleFlags & kAuthorityFlagDefault)	// can't ever match standard rules with unsigned code
					continue;
				if (whitelistScreen.reject(filter, remarks))	// apply whitelist pre-filter
					continue;
			}
			try {
				// ad-hoc sign the code and attach the signature
				CFRef<CFDataRef> signature = CFDataCreateMutable(NULL, 0);
				CFTemp<CFDictionaryRef> arguments("{%O=%O, %O=#N}", kSecCodeSignerDetached, signature.get(), kSecCodeSignerIdentity);
				CFRef<SecCodeSignerRef> signer;
				MacOSError::check(SecCodeSignerCreate(arguments, kSecCSDefaultFlags, &signer.aref()));
				MacOSError::check(SecCodeSignerAddSignature(signer, code, kSecCSDefaultFlags));
				MacOSError::check(SecCodeSetDetachedSignature(code, signature, kSecCSDefaultFlags));
								
				// if we're in GKE recording mode, save that signature and report its location
				if (SYSPOLICY_RECORDER_MODE_ENABLED()) {
					int status = recorder_code_unable;	// ephemeral signature (not recorded)
					if (geteuid() == 0) {
						CFRef<CFUUIDRef> uuid = CFUUIDCreate(NULL);
						std::string sigfile = RECORDER_DIR + cfStringRelease(CFUUIDCreateString(NULL, uuid)) + ".tsig";
						try {
							UnixPlusPlus::AutoFileDesc fd(sigfile, O_WRONLY | O_CREAT);
							fd.write(CFDataGetBytePtr(signature), CFDataGetLength(signature));
							status = recorder_code_adhoc;	// recorded signature
							SYSPOLICY_RECORDER_MODE_ADHOC_PATH(cfString(path).c_str(), type, sigfile.c_str());
						} catch (...) { }
					}

					// now report the D probe itself
					CFRef<CFDictionaryRef> info;
					MacOSError::check(SecCodeCopySigningInformation(code, kSecCSDefaultFlags, &info.aref()));
					CFDataRef cdhash = CFDataRef(CFDictionaryGetValue(info, kSecCodeInfoUnique));
					SYSPOLICY_RECORDER_MODE(cfString(path).c_str(), type, "",
						cdhash ? CFDataGetBytePtr(cdhash) : NULL, status);
				}
				
				// rerun the validation to update state
				rc = SecStaticCodeCheckValidity(code, validationFlags | kSecCSBasicValidateOnly, requirement);
			} catch (...) { }
		}

		switch (rc) {
		case noErr: // well signed and satisfies requirement...
			break;	// ... continue below
		case errSecCSSignatureFailed:
			if (!codeInvalidityExceptions(code, result)) {
				if (SYSPOLICY_ASSESS_OUTCOME_BROKEN_ENABLED())
					SYSPOLICY_ASSESS_OUTCOME_BROKEN(cfString(path).c_str(), type, false);
				MacOSError::throwMe(rc);
			}
			if (SYSPOLICY_ASSESS_OUTCOME_BROKEN_ENABLED())
				SYSPOLICY_ASSESS_OUTCOME_BROKEN(cfString(path).c_str(), type, true);
			// treat as unsigned to fix problems in the field
		case errSecCSUnsigned:
			if (handleUnsignedCode) {
				cfadd(result, "{%O=#F}", kSecAssessmentAssessmentVerdict);
				addAuthority(result, "no usable signature");
			}
			return;
		case errSecCSReqFailed: // requirement missed, but otherwise okay
			continue;
		default: // broken in some way; all tests will fail like this so bail out
			MacOSError::throwMe(rc);
		}
		if (disabled) {
			if (latentID == 0) {
				latentID = id;
				if (label)
					latentLabel = label;
			}
			continue;	// the loop
		}
	
		CFRef<CFDictionaryRef> info;	// as needed
		if (flags & kSecAssessmentFlagRequestOrigin) {
			if (!info)
				MacOSError::check(SecCodeCopySigningInformation(code, kSecCSSigningInformation, &info.aref()));
			if (CFArrayRef chain = CFArrayRef(CFDictionaryGetValue(info, kSecCodeInfoCertificates)))
				setOrigin(chain, result);
		}
		if (!(ruleFlags & kAuthorityFlagInhibitCache) && !(flags & kSecAssessmentFlagNoCache)) {	// cache inhibit
			if (!info)
				MacOSError::check(SecCodeCopySigningInformation(code, kSecCSSigningInformation, &info.aref()));
			if (SecTrustRef trust = SecTrustRef(CFDictionaryGetValue(info, kSecCodeInfoTrust))) {
				CFRef<CFDictionaryRef> xinfo;
				MacOSError::check(SecTrustCopyExtendedResult(trust, &xinfo.aref()));
				if (CFDateRef limit = CFDateRef(CFDictionaryGetValue(xinfo, kSecTrustExpirationDate))) {
					this->recordOutcome(code, allow, type, min(expires, dateToJulian(limit)), id);
				}
			}
		}
		if (allow) {
			if (SYSPOLICY_ASSESS_OUTCOME_ACCEPT_ENABLED()) {
				if (!info)
					MacOSError::check(SecCodeCopySigningInformation(code, kSecCSSigningInformation, &info.aref()));
				CFDataRef cdhash = CFDataRef(CFDictionaryGetValue(info, kSecCodeInfoUnique));
				SYSPOLICY_ASSESS_OUTCOME_ACCEPT(cfString(path).c_str(), type, label, cdhash ? CFDataGetBytePtr(cdhash) : NULL);
			}
		} else {
			if (SYSPOLICY_ASSESS_OUTCOME_DENY_ENABLED() || SYSPOLICY_RECORDER_MODE_ENABLED()) {
				if (!info)
					MacOSError::check(SecCodeCopySigningInformation(code, kSecCSSigningInformation, &info.aref()));
				CFDataRef cdhash = CFDataRef(CFDictionaryGetValue(info, kSecCodeInfoUnique));
				std::string cpath = cfString(path);
				const void *hashp = cdhash ? CFDataGetBytePtr(cdhash) : NULL;
				SYSPOLICY_ASSESS_OUTCOME_DENY(cpath.c_str(), type, label, hashp);
				SYSPOLICY_RECORDER_MODE(cpath.c_str(), type, label, hashp, recorder_code_untrusted);
			}
		}
		cfadd(result, "{%O=%B}", kSecAssessmentAssessmentVerdict, allow);
		addAuthority(result, label, id);
		return;
	}

	if (rc == errSecCSUnsigned) {	// skipped all applicable rules due to pre-screening
		cfadd(result, "{%O=#F}", kSecAssessmentAssessmentVerdict);
		addAuthority(result, "no usable signature");
		return;
	}
	
	// no applicable authority (but signed, perhaps temporarily). Deny by default
	CFRef<CFDictionaryRef> info;
	MacOSError::check(SecCodeCopySigningInformation(code, kSecCSSigningInformation, &info.aref()));
	if (flags & kSecAssessmentFlagRequestOrigin) {
		if (CFArrayRef chain = CFArrayRef(CFDictionaryGetValue(info, kSecCodeInfoCertificates)))
			setOrigin(chain, result);
	}
	if (SYSPOLICY_ASSESS_OUTCOME_DEFAULT_ENABLED() || SYSPOLICY_RECORDER_MODE_ENABLED()) {
		CFDataRef cdhash = CFDataRef(CFDictionaryGetValue(info, kSecCodeInfoUnique));
		const void *hashp = cdhash ? CFDataGetBytePtr(cdhash) : NULL;
		std::string cpath = cfString(path);
		SYSPOLICY_ASSESS_OUTCOME_DEFAULT(cpath.c_str(), type, latentLabel.c_str(), hashp);
		SYSPOLICY_RECORDER_MODE(cpath.c_str(), type, latentLabel.c_str(), hashp, 0);
	}
	if (!(flags & kSecAssessmentFlagNoCache))
		this->recordOutcome(code, false, type, this->julianNow() + NEGATIVE_HOLD, latentID);
	cfadd(result, "{%O=%B}", kSecAssessmentAssessmentVerdict, false);
	addAuthority(result, latentLabel.c_str(), latentID);
}
コード例 #14
0
ファイル: RunDlg.cpp プロジェクト: Oldes/npp-community
BOOL CALLBACK RunDlg::run_dlgProc(UINT message, WPARAM wParam, LPARAM /*lParam*/)
{
	switch (message)
	{
		case WM_COMMAND :
		{
			switch (wParam)
			{
				case IDCANCEL :
					display(false);
					return TRUE;

				case IDOK :
				{
					TCHAR cmd[MAX_PATH];
					::GetDlgItemText(_hSelf, IDC_COMBO_RUN_PATH, cmd, MAX_PATH);
					_cmdLine = cmd;

					HINSTANCE hInst = run(_hParent);
					if (int(hInst) > 32)
					{
						addTextToCombo(_cmdLine.c_str());
						display(false);
					}
					else
					{
						removeTextFromCombo(_cmdLine.c_str());
					}
					return TRUE;
				}

				case IDC_BUTTON_SAVE :
				{
					std::vector<UserCommand> & theUserCmds = (NppParameters::getInstance())->getUserCommandList();

					int nbCmd = theUserCmds.size();

					int cmdID = ID_USER_CMD + nbCmd;
					TCHAR cmd[MAX_PATH];
					::GetDlgItemText(_hSelf, IDC_COMBO_RUN_PATH, cmd, MAX_PATH);
					UserCommand uc(Shortcut(), cmd, cmdID);
					uc.init(_hInst, _hSelf);

					if (uc.doDialog() != -1)
					{
						HMENU hRunMenu = ::GetSubMenu((HMENU)::SendMessage(_hParent, NPPM_INTERNAL_GETMENU, 0, 0), MENUINDEX_RUN);
						int const posBase = 2;

						if (nbCmd == 0)
							::InsertMenu(hRunMenu, posBase - 1, MF_BYPOSITION, (unsigned int)-1, 0);

						theUserCmds.push_back(uc);
						::InsertMenu(hRunMenu, posBase + nbCmd, MF_BYPOSITION, cmdID, uc.toMenuItemString().c_str());

                        if (nbCmd == 0)
                        {
                            // Insert the separator and modify/delete command
			                ::InsertMenu(hRunMenu, posBase + nbCmd + 1, MF_BYPOSITION, (unsigned int)-1, 0);
                            const char * nativeLangShortcutMapperRun = (NppParameters::getInstance())->getNativeLangMenuStringA(IDM_SETTING_SHORTCUT_MAPPER_RUN);
                            const char * shortcutMapperRunStr = nativeLangShortcutMapperRun?nativeLangShortcutMapperRun:"Modify Shortcut/Delete Command...";
#ifdef UNICODE
		                    WcharMbcsConvertor *wmc = WcharMbcsConvertor::getInstance();
                            const wchar_t * shortcutMapperRunStrW = wmc->char2wchar(shortcutMapperRunStr, ::SendMessage(_hParent, NPPM_GETCURRENTNATIVELANGENCODING, 0, 0));
		                    ::InsertMenu(hRunMenu, posBase + nbCmd + 2, MF_BYCOMMAND, IDM_SETTING_SHORTCUT_MAPPER_RUN, shortcutMapperRunStrW);
#else
		                    ::InsertMenu(hRunMenu, posBase + nbCmd + 2, MF_BYCOMMAND, IDM_SETTING_SHORTCUT_MAPPER_RUN, shortcutMapperRunStr);
#endif
                        }
						(NppParameters::getInstance())->getAccelerator()->updateShortcuts();
					}
					return TRUE;
				}

				case IDC_BUTTON_FILE_BROWSER :
				{
					FileDialog fd(_hSelf, _hInst);
					fd.setExtFilter(TEXT("Executable file : "), TEXT(".exe"), TEXT(".com"), TEXT(".cmd"), TEXT(".bat"), NULL);
					fd.setExtFilter(TEXT("All files : "), TEXT(".*"), NULL);

					if (const TCHAR *fn = fd.doOpenSingleFileDlg())
						addTextToCombo(fn);
					return TRUE;
				}

				default :
					break;
			}
		}
		break;

		default:
		break;
	}
	return FALSE;
}
コード例 #15
0
ファイル: base_allocator.cpp プロジェクト: Avitella/geo-base
void base_allocator_t::deallocate(void *ptr, size_t count)
{
    block_allocator_t::deallocate(ptr, count);
    if (ftruncate(fd(), total_allocated_size()) < 0)
        throw exception_t("Unable ftrancate: %s", strerror(errno));
}
コード例 #16
0
ファイル: SolidTools.cpp プロジェクト: play113/swer
void SaveSolids::Run(){
	std::list<HeeksObj*> objects;

	for(std::list<HeeksObj*>::const_iterator It = wxGetApp().m_marked_list->list().begin(); It != wxGetApp().m_marked_list->list().end(); It++){
		HeeksObj* object = *It;
		switch(object->GetType())
		{
		case SolidType:
		case StlSolidType:
		case FaceType:
		{
				objects.push_back(object);
			}
			break;
		}
	}

	if(objects.size() > 0)
	{
		wxString filepath(_T(""));
		{
			// get last used filepath
			HeeksConfig config;
			config.Read(_T("SolidExportFilepath"), &filepath, _T(""));
		}

		wxFileDialog fd(wxGetApp().m_frame, _("Save solid file"), wxEmptyString, filepath, wxString(_("Solid Files")) + _T(" |*.igs;*.iges;*.stp;*.step;*.stl;*.cpp;*.py;*.obj|") + _("IGES files") + _T(" (*.igs *.iges)|*.igs;*.iges|") + _("STEP files") + _T(" (*.stp *.step)|*.stp;*.step|") + _("STL files") + _T(" (*.stl)|*.stl|") + _("CPP files") + _T(" (*.cpp)|*.cpp|") + _("OpenCAMLib python files") + _T(" (*.py)|*.py|") + _("Wavefront .obj files") + _T(" (*.obj)|*.obj"), wxFD_SAVE | wxFD_OVERWRITE_PROMPT);
		fd.SetFilterIndex(0);

		if (fd.ShowModal() == wxID_CANCEL)return;
		filepath = fd.GetPath();

		wxString wf(filepath);
		wf.LowerCase();

		if(wf.EndsWith(_T(".stl")))
		{
			wxGetApp().SaveSTLFile(objects, filepath, -1.0, NULL, wxGetApp().m_stl_save_as_binary);
		}
		else if(wf.EndsWith(_T(".cpp")))
		{
			wxGetApp().SaveCPPFile(objects, filepath);
		}
		else if (wf.EndsWith(_T(".py")))
		{
			wxGetApp().SavePyFile(objects, filepath);
		}
		else if (wf.EndsWith(_T(".obj")))
		{
			wxGetApp().SaveOBJFileAscii(objects, filepath);
		}
		else if (CShape::ExportSolidsFile(objects, filepath))
		{
		}
		else
		{
			wxMessageBox(_("Invalid solid file type chosen"));
			return;
		}

		{
			// save last used filepath
			HeeksConfig config;
			config.Write(_T("SolidExportFilepath"), filepath);
		}
	}
}
コード例 #17
0
ファイル: flfoverf.cpp プロジェクト: ABratovic/open-watcom-v2
  int filebuf::overflow( int c ) {

    unsigned int    waiting;
    int             written;
    streamoff       offset;

    __lock_it( __b_lock );

    // Flush any input waiting in the buffer:
    if( in_avail() > 0 ) {
        // note that sync() will discard get area
        if( sync() == EOF ) {
            return( EOF );
        }
    } else {
        // discard get area
        setg( NULL, NULL, NULL );
    }

    // Try to allocate a buffer:
    if( base() == NULL ) {
        if( allocate() == EOF ) {
            return( EOF );
        }
        if( base() == NULL ) {
            if( c != EOF ) {
                char charbuf = (char)c;
                written = ::write( fd(), &charbuf, sizeof( charbuf ) );
                return( written == sizeof( charbuf ) ? __NOT_EOF : EOF );
            }
            return( __NOT_EOF );
        } else {
            setp( base(), ebuf() );
        }
    } else if( pptr() <= pbase() ) {
        setp( base(), ebuf() );
    }

    // if appending, remember current offset and seek to end
    if( __file_mode & ios::app ) {
        offset = tell( fd() );
        if( offset < 0 ) {
            return( EOF );
        }
        if( lseek( fd(), 0, ios::end ) < 0 ) {
            return( EOF );
        }
    }

    // Now write the output:
    if( (c != EOF) && (pptr() < epptr()) ) {
        *(pptr()) = (char)c;
        pbump( 1 );
        c = EOF;
    }
    waiting = (__huge_ptr_int)(pptr() - pbase());
    while( waiting > 0 ) {
        written = ::write( fd(), pbase(), (waiting>INT_MAX?INT_MAX:waiting) );
        if( written == -1 ) {
            return( EOF );
        } else if( written == 0 ) {
            break;
        }
        waiting -= written;
        if( waiting > 0 ) {
            ::memmove( pbase(), pbase() + written, waiting );
            setp( pbase(), epptr() );
            pbump( waiting );
        } else {
            setp( pbase(), epptr() );
        }
    }
    if( c != EOF ) {
        if( pptr() < epptr() ) {
            *(pptr()) = (char)c;
            pbump( 1 );
        } else {
            return( EOF );
        }
    }

    // if appending, restore current offset
    if( __file_mode & ios::app ) {
        if( lseek( fd(), offset, ios::beg ) < 0 ) {
            return( EOF );
        }
    }

    if( waiting ) {
        return( EOF );
    }
    return( __NOT_EOF );
  }
コード例 #18
0
ファイル: filebuf.C プロジェクト: Kiddinglife/4.4BSD-Lite
fpos_t filebuf::sys_seek(fpos_t offset, _seek_dir dir)
{
    return ::lseek(fd(), offset, (int)dir);
}
コード例 #19
0
ファイル: data_file.hpp プロジェクト: MapQuest/osm2pgsql
 /**
  * Ask the operating system for the size of this file.
  *
  * @throws std::system_error if fstat(2) call failed
  */
 size_t size() const {
     return osmium::util::file_size(fd());
 }
コード例 #20
0
ファイル: filebuf.C プロジェクト: Kiddinglife/4.4BSD-Lite
int filebuf::sys_stat(void* st)
{
    return ::_fstat(fd(), (struct stat*)st);
}
コード例 #21
0
ファイル: process.cpp プロジェクト: vasi/kdelibs
int PtyProcess::waitForChild()
{
    fd_set fds;
    FD_ZERO(&fds);
    QByteArray remainder;

    while (1)
    {
        FD_SET(fd(), &fds);

        // specify timeout to make sure select() does not block, even if the
        // process is dead / non-responsive. It does not matter if we abort too
        // early. In that case 0 is returned, and we'll try again in the next
        // iteration. (As long as we don't consitently time out in each iteration)
        timeval timeout;
        timeout.tv_sec = 0;
        timeout.tv_usec = 100000;
        int ret = select(fd()+1, &fds, 0L, 0L, &timeout);
        if (ret == -1)
        {
            if (errno != EINTR)
            {
                kError(kdesuDebugArea()) << k_lineinfo << "select():" << perror;
                return -1;
            }
            ret = 0;
        }

        if (ret)
        {
            forever {
                QByteArray output = readAll(false);
                if (output.isEmpty())
                    break;
                if (m_bTerminal)
                {
                    fwrite(output.constData(), output.size(), 1, stdout);
                    fflush(stdout);
                }
                if (!m_Exit.isEmpty())
                {
                    // match exit string only at line starts
                    remainder += output;
                    while (remainder.length() >= m_Exit.length()) {
                        if (remainder.startsWith(m_Exit)) {
                            kill(m_Pid, SIGTERM);
                            remainder.remove(0, m_Exit.length());
                        }
                        int off = remainder.indexOf('\n');
                        if (off < 0)
                            break;
                        remainder.remove(0, off + 1);
                    }
                }
            }
        }

        ret = checkPidExited(m_Pid);
        if (ret == Error)
        {
            if (errno == ECHILD) return 0;
            else return 1;
        }
        else if (ret == Killed)
        {
            return 0;
        }
        else if (ret == NotExited)
        {
            // keep checking
        }
        else
        {
            return ret;
        }
    }
}
コード例 #22
0
ファイル: filebuf.C プロジェクト: Kiddinglife/4.4BSD-Lite
int filebuf::sys_close()
{
    return ::close(fd());
}
コード例 #23
0
ファイル: CollocationWorker.cpp プロジェクト: m-angelov/ugene
void CollocationWorkerFactory::init() {

    QMap<Descriptor, DataTypePtr> m;
    {
        m[BaseSlots::DNA_SEQUENCE_SLOT()] = BaseTypes::DNA_SEQUENCE_TYPE();
        m[BaseSlots::ANNOTATION_TABLE_SLOT()] = BaseTypes::ANNOTATION_TABLE_LIST_TYPE();
    }
    DataTypePtr inSet(new MapDataType(Descriptor("regioned.sequence"), m));
    DataTypeRegistry* dr = WorkflowEnv::getDataTypeRegistry();
    assert(dr);
    dr->registerEntry(inSet);

    QList<PortDescriptor*> p; QList<Attribute*> a;
    p << new PortDescriptor(Descriptor(BasePorts::IN_SEQ_PORT_ID(), CollocationWorker::tr("Input data"),
        CollocationWorker::tr("An input sequence and a set of annotations to search in.")), inSet, true /*input*/);
    QMap<Descriptor, DataTypePtr> outM;
    outM[BaseSlots::ANNOTATION_TABLE_SLOT()] = BaseTypes::ANNOTATION_TABLE_TYPE();
    p << new PortDescriptor(Descriptor(BasePorts::OUT_ANNOTATIONS_PORT_ID(),
        CollocationWorker::tr("Group annotations"), CollocationWorker::tr("Annotated regions containing found collocations.")),
        DataTypePtr(new MapDataType(Descriptor("collocation.annotations"), outM)), false /*input*/, true/*multi*/);

    static const QString newAnnsStr = CollocationWorker::tr("Create new annotations");
    {
        Descriptor nd(NAME_ATTR, CollocationWorker::tr("Result annotation"),
            CollocationWorker::tr("Name of the result annotations to mark found collocations."));
        Descriptor ad(ANN_ATTR, CollocationWorker::tr("Group of annotations"),
            CollocationWorker::tr("A list of annotation names to search. Found regions will contain all the named annotations."));
        Descriptor ld(LEN_ATTR, CollocationWorker::tr("Region size"),
            CollocationWorker::tr("Effectively this is the maximum allowed distance between the interesting annotations in a group."));
        Descriptor fd(FIT_ATTR, CollocationWorker::tr("Must fit into region"),
            CollocationWorker::tr("Whether the interesting annotations should entirely fit into the specified region to form a group."));
        Descriptor td(TYPE_ATTR, CollocationWorker::tr("Result type"),
            CollocationWorker::tr("Copy original annotations or annotate found regions with new ones."));
        Descriptor id(INC_BOUNDARY_ATTR, CollocationWorker::tr("Include boundaries"),
            CollocationWorker::tr("Include most left and most right boundary annotations regions into result or exclude them."));
        Attribute *nameAttr = new Attribute(nd, BaseTypes::STRING_TYPE(), true, QVariant("misc_feature"));
        Attribute *typeAttr = new Attribute(td, BaseTypes::STRING_TYPE(), false, NEW_TYPE_ATTR);
        Attribute *boundAttr = new Attribute(id, BaseTypes::BOOL_TYPE(), false, true);
        a << typeAttr;
        a << nameAttr;
        a << boundAttr;
        a << new Attribute(ad, BaseTypes::STRING_TYPE(), true);
        a << new Attribute(ld, BaseTypes::NUM_TYPE(), false, QVariant(1000));
        a << new Attribute(fd, BaseTypes::BOOL_TYPE(), false, QVariant(false));

        nameAttr->addRelation(new VisibilityRelation(TYPE_ATTR, NEW_TYPE_ATTR));
        boundAttr->addRelation(new VisibilityRelation(TYPE_ATTR, NEW_TYPE_ATTR));
    }

    Descriptor desc(ACTOR_ID, CollocationWorker::tr("Collocation Search"),
        CollocationWorker::tr("Finds groups of specified annotations in each supplied set of annotations, stores found regions as annotations."));
    ActorPrototype* proto = new IntegralBusActorPrototype(desc, p, a);
    QMap<QString, PropertyDelegate*> delegates;
    {
        QVariantMap lenMap; lenMap["minimum"] = QVariant(0); lenMap["maximum"] = QVariant(INT_MAX);
        delegates[LEN_ATTR] = new SpinBoxDelegate(lenMap);
        delegates[FIT_ATTR] = new ComboBoxWithBoolsDelegate();

        QVariantMap typeMap;
        typeMap[CollocationWorker::tr("Copy original annotations")] = COPY_TYPE_ATTR;
        typeMap[newAnnsStr] = NEW_TYPE_ATTR;
        delegates[TYPE_ATTR] = new ComboBoxDelegate(typeMap);
    }

    proto->setEditor(new DelegateEditor(delegates));
    proto->setValidator(new CollocationValidator());
    proto->setIconPath(":annotator/images/regions.png");
    proto->setPrompter(new CollocationPrompter());
    WorkflowEnv::getProtoRegistry()->registerProto(BaseActorCategories::CATEGORY_BASIC(), proto);

    DomainFactory* localDomain = WorkflowEnv::getDomainRegistry()->getById(LocalDomainFactory::ID);
    localDomain->registerEntry(new CollocationWorkerFactory());
}
コード例 #24
0
ファイル: test-FOE.C プロジェクト: ulyssesrr/carmen_lcad
// ######################################################################
int main(const int argc, const char **argv)
{
  MYLOGVERB = LOG_INFO;  // suppress debug messages

  volatile int signum = 0;
  catchsignals(&signum);

  ModelManager manager("Test Motion Energy");

  nub::ref<InputFrameSeries> ifs(new InputFrameSeries(manager));
  manager.addSubComponent(ifs);

  nub::ref<OutputFrameSeries> ofs(new OutputFrameSeries(manager));
  manager.addSubComponent(ofs);

  nub::ref<FoeDetector> fd(new FoeDetector(manager));
  manager.addSubComponent(fd);

  if (manager.parseCommandLine((const int)argc, (const char**)argv,
                               "<stimuli> <options>", 0, 9) == false)
    return(1);

  fd->reset(NUM_PYR_LEVEL, NUM_DIRS, NUM_SPEEDS);

  std::string stimuli("Image");
  if(manager.numExtraArgs() > 0)
    stimuli = manager.getExtraArgAs<std::string>(0);
  LINFO("Stimuli: %s", stimuli.c_str());

  manager.start();

  Timer timer(1000000);
  timer.reset();  // reset the timer
  int frame = 0;

  PauseWaiter p;

  uint step; step = 0;

  // to get to the good part
  //for(uint i = 0; i < 50; i++) //was 25
  //  ifs->updateNext();

  // get ground truth file 
  std::string gtFilename
    ("/lab/tmpib/u/siagian/neuroscience/Data/FOE/driving_nat_Browning.txt");
  std::vector<Point2D<int> > gt = getGT(gtFilename);
  int ldpos = gtFilename.find_last_of('.');
  std::string prefix = gtFilename.substr(0, ldpos);

  // for finding ground truth
  rutz::shared_ptr<XWinManaged> win;
  
  float totalErr = 0.0;

  std::vector<std::string> args;
  for(uint i = 0; i < manager.numExtraArgs(); i++)
    args.push_back(manager.getExtraArgAs<std::string>(i)); 

  Image<byte> prevLum;
  Image<PixRGB<byte> > prevImage;
  Image<PixRGB<byte> > prevImage2;
  while (1)
    {
      if (signum != 0)
        {
          LINFO("quitting because %s was caught", signame(signum));
          break;
        }

      if (ofs->becameVoid())
        {
          LINFO("quitting because output stream was closed or became void");
          break;
        }

      if (p.checkPause())
        continue;

      const FrameState is = ifs->updateNext();
      if (is == FRAME_COMPLETE) break; // done receiving frames

      Image< PixRGB<byte> > input = ifs->readRGB();
      if(frame == 0) 
        {
          uint width  = input.getWidth();
          uint height = input.getHeight();
          win.reset(new XWinManaged(Dims(width, height), 0, 0, "GT"));
        }

      // empty image signifies end-of-stream
      if (!input.initialized()) break;
      Image<byte> lum = luminance(input);
      Point2D<float> pshift(0.0,0.0); 
      if(step != 0)
        {
          // calculate planar shift using SIFT 
          lum = calculateShift(lum,prevLum, ofs);
        }
      if( manager.numExtraArgs() > 0)
        lum = getImage(stimuli, args, fd, step);

      // for saving videos
      prevImage2 = prevImage;
      prevImage  = input;

      if (!lum.initialized()) break; step++;

      // compute the focus of expansion (FOE)
      Point2D<int> foe = fd->getFoe(lum, FOE_METHOD_TEMPLATE, false);
      //Point2D<int> foe = fd->getFoe(lum, FOE_METHOD_AVERAGE);
      LINFO("[%d]Foe: %d %d", frame, foe.i, foe.j);

      // illustration of the size of the receptive field
      if(!stimuli.compare("ShowRF"))
        {
          uint rfI = 44;
          uint rfJ = 152;
          lum.setVal(rfI, rfJ, 300.0F);      
          drawRect(lum, Rectangle::tlbrI(144,36,159,51), byte(255));
          drawRect(lum, Rectangle::tlbrI(148,40,155,47), byte(255));
          
          drawRect(lum, Rectangle::tlbrI(rfJ-8, rfI-8, rfJ+8, rfI+8), byte(255));
          drawRect(lum, Rectangle::tlbrI(rfJ-16,rfI-16,rfJ+16,rfI+16), byte(255));
        }

      ofs->writeGrayLayout(fd->getMTfeaturesDisplay(lum), "MT Features",
                           FrameInfo("motion energy output images", SRC_POS));

      // write the file
      if(frame >= 4)
        {
          float err = foe.distance(gt[frame-2]); 
          totalErr += err;
          LINFO("Foe: %d %d: GT: %d %d --> %f --> avg: %f", 
                foe.i, foe.j, gt[frame-2].i, gt[frame-2].j, 
                err, totalErr/(frame-3));

          Image<PixRGB<byte> > simg = prevImage2;
          drawCross(simg, foe        , PixRGB<byte>(0,255,0), 10, 2);
          drawCross(simg, gt[frame-2], PixRGB<byte>(255,0,0), 10, 2);
          win->drawImage(simg,0,0);
          //Raster::WriteRGB(simg, sformat("%s_STnPS_%06d.ppm", prefix.c_str(), frame-2));
        }

      //ofs->writeGrayLayout
      //  (lum, "test-FOE Main", FrameInfo("foe output", SRC_POS));
      const FrameState os = ofs->updateNext();
      //LINFO("frame[%d]: %8.3f %8.3f", frame, pshift.i, pshift.j); 
      Raster::waitForKey();

      if (os == FRAME_FINAL)
        break;

      prevLum  = lum;
      frame++;
    }

  LINFO("%d frames in %gs (%.2ffps)\n", 
        frame, timer.getSecs(), frame / timer.getSecs());

  // stop all our ModelComponents
  manager.stop();

  // all done!
  return 0;

}
コード例 #25
0
ファイル: ip++.cpp プロジェクト: Proteas/codesign
void Socket::bind(const UNSockAddress &local)
{
    checkError(::bind(fd(), local, sizeof(local)));
    secdebug("sockio", "%d bind to %s", fd(), string(local).c_str());
}
コード例 #26
0
 void init() {
   old_stderr_ = dup(STDERR_FILENO);
   ASSERT_NE(-1, old_stderr_);
   ASSERT_NE(-1, dup2(fd(), STDERR_FILENO));
 }
コード例 #27
0
ファイル: ip++.cpp プロジェクト: Proteas/codesign
void Socket::accept(Socket &s, UNSockAddress &peer)
{
    socklen_t length = sizeof(UNSockAddress);
    s.checkSetFd(::accept(fd(), peer, &length));
    assert(length == sizeof(UNSockAddress));
}
コード例 #28
0
ファイル: base_allocator.cpp プロジェクト: Avitella/geo-base
void *base_allocator_t::allocate(size_t count)
{
    if (ftruncate(fd(), total_allocated_size() + allocate_size(count)) < 0)
        throw exception_t("Unable ftrancate: %s", strerror(errno));
    return block_allocator_t::allocate(count);
}
コード例 #29
0
ファイル: ip++.cpp プロジェクト: Proteas/codesign
void Socket::getOption(void *value, socklen_t &length, int name, int level /*= SOL_SOCKET*/) const
{
    UnixError::check(::getsockopt(fd(), level, name, value, &length));
}
コード例 #30
0
ファイル: preproc-init.c プロジェクト: BertrandAreal/postgres
int main(void)
{
	struct sa x = { 14 },*y = &x;
	/* exec sql begin declare section */
		 
		 
		 
		 
		 
		 
		 

		 
		 
		 
		  /* = 1L */ 
	
#line 60 "init.pgc"
 int a = ( int ) 2 ;
 
#line 61 "init.pgc"
 int b = 2 + 2 ;
 
#line 62 "init.pgc"
 int b2 = ( 14 * 7 ) ;
 
#line 63 "init.pgc"
 int d = x . member ;
 
#line 64 "init.pgc"
 int g = fb ( 2 ) ;
 
#line 65 "init.pgc"
 int i = 3 ^ 1 ;
 
#line 66 "init.pgc"
 int j = 1 ? 1 : 2 ;
 
#line 68 "init.pgc"
 int e = y -> member ;
 
#line 69 "init.pgc"
 int c = 10 >> 2 ;
 
#line 70 "init.pgc"
 bool h = 2 || 1 ;
 
#line 71 "init.pgc"
 long iay ;
/* exec sql end declare section */
#line 72 "init.pgc"


	int f=fa();

#ifdef _cplusplus
	/* exec sql begin declare section */
	  /* compile error */
	
#line 78 "init.pgc"
 int k = N : : i ;
/* exec sql end declare section */
#line 79 "init.pgc"

#endif

	ECPGdebug(1, stderr);

	printf("%d %d %d %d %d %d %d %d %d %d %d\n", a, b, b2, c, d, e, f, g, h, i, j);
	iay = 0;
	printf("%ld\n", iay);
	/* exec sql whenever sqlerror  do fa ( ) ; */
#line 87 "init.pgc"

	{ ECPGdo(__LINE__, 0, 1, NULL, 0, ECPGst_normal, "select now ( )", ECPGt_EOIT, ECPGt_EORT);
#line 88 "init.pgc"

if (sqlca.sqlcode < 0) fa ( );}
#line 88 "init.pgc"

	/* exec sql whenever sqlerror  do fb ( 20 ) ; */
#line 89 "init.pgc"

	{ ECPGdo(__LINE__, 0, 1, NULL, 0, ECPGst_normal, "select now ( )", ECPGt_EOIT, ECPGt_EORT);
#line 90 "init.pgc"

if (sqlca.sqlcode < 0) fb ( 20 );}
#line 90 "init.pgc"

	/* exec sql whenever sqlerror  do fc ( \"50\" ) ; */
#line 91 "init.pgc"

	{ ECPGdo(__LINE__, 0, 1, NULL, 0, ECPGst_normal, "select now ( )", ECPGt_EOIT, ECPGt_EORT);
#line 92 "init.pgc"

if (sqlca.sqlcode < 0) fc ( "50" );}
#line 92 "init.pgc"

	/* exec sql whenever sqlerror  do fd ( \"50\" , 1 ) ; */
#line 93 "init.pgc"

	{ ECPGdo(__LINE__, 0, 1, NULL, 0, ECPGst_normal, "select now ( )", ECPGt_EOIT, ECPGt_EORT);
#line 94 "init.pgc"

if (sqlca.sqlcode < 0) fd ( "50" , 1 );}
#line 94 "init.pgc"

	/* exec sql whenever sqlerror  do fe ( ENUM0 ) ; */
#line 95 "init.pgc"

	{ ECPGdo(__LINE__, 0, 1, NULL, 0, ECPGst_normal, "select now ( )", ECPGt_EOIT, ECPGt_EORT);
#line 96 "init.pgc"

if (sqlca.sqlcode < 0) fe ( ENUM0 );}
#line 96 "init.pgc"

	/* exec sql whenever sqlerror  do sqlnotice ( NULL , 0 ) ; */
#line 97 "init.pgc"

	{ ECPGdo(__LINE__, 0, 1, NULL, 0, ECPGst_normal, "select now ( )", ECPGt_EOIT, ECPGt_EORT);
#line 98 "init.pgc"

if (sqlca.sqlcode < 0) sqlnotice ( NULL , 0 );}
#line 98 "init.pgc"

	return 0;
}