int main(int argc, const char** argv)
{
   try{
   e1.assign(expression_text);
   e2.assign(pre_expression);
   for(int i = 1; i < argc; ++i)
   {
      std::cout << "Processing file " << argv[i] << std::endl;
      std::ifstream fs(argv[i]);
      std::string in;
      load_file(in, fs);
      fs.close();
      std::string out_name = std::string(argv[i]) + std::string(".htm");
      std::ofstream os(out_name.c_str());
      os << header_text;
      // strip '<' and '>' first by outputting to a
      // temporary string stream
      std::ostringstream t(std::ios::out | std::ios::binary);
      std::ostream_iterator<char> oi(t);
      boost::regex_replace(oi, in.begin(), in.end(), e2, pre_format, boost::match_default | boost::format_all);
      // then output to final output stream
      // adding syntax highlighting:
      std::string s(t.str());
      std::ostream_iterator<char> out(os);
      boost::regex_replace(out, s.begin(), s.end(), e1, format_string, boost::match_default | boost::format_all);
      os << footer_text;
      os.close();
   }
   }
   catch(...)
   { return -1; }
   return 0;
}
//Extracts opcodes out of the client
QStringList OpcodeFinder::ExtractOpcodes(QString path)
{
	QStringList opcodes;
	QFile file(path);

	//Open the file
	if(file.open(QIODevice::ReadOnly))
	{
		//Read the file data and convert it to hex
		std::string data = QString(file.readAll().toHex()).toUpper().toAscii().data();
		file.close();

		if(data.empty())
		{
			//No data read
			QMessageBox::critical(this, "Error", "No data was read from the client.");
		}
		else
		{
			//Regex string for locating opcodes
			const static boost::regex e("C744240C(?<opcode>....)0000C7442410........E8........8D|8D..24108D..2418....8BCEC7442418(?<opcode>....)0000C744241C........E8|8B4E10C7442410(?<opcode>....)000041C74424..........518BCEE8");

			boost::match_results<std::string::const_iterator> what;
			boost::match_flag_type flags = boost::match_default;

			std::string::const_iterator start = data.begin();
			std::string::const_iterator end = data.end();

			try
			{
				//Search
				while(boost::regex_search(start, end, what, e, flags))
				{
					//Get the opcode
					std::string temp = what["opcode"];

					//Add it to the list
					opcodes.append((temp.substr(2, 2) + temp.substr(0, 2)).c_str());

					//Next
					start = what[0].second;
					flags |= boost::match_prev_avail;
					flags |= boost::match_not_bob;
				}
			}
			catch(std::exception & e)
			{
				//Display error message (regular expression is probably outdated for this client)
				QMessageBox::critical(this, "Error", e.what());
			}
		}
	}
	else
	{
		//File open error
		QMessageBox::critical(this, "Error", QString("Unable to open %0 for reading. Could not extract opcodes.").arg(path));
	}

	return opcodes;
}
Exemple #3
0
/**
 * Generic tokenizer.
 * Splits source into tokens and tries to lexically cast them to TARGET.
 * If that fails, boost::bad_lexical_cast is thrown.
 * \param source the source string to be split up
 * \param separator regular expression to delimit the tokens (defaults to \\s+)
 * \param prefix regular expression for text to be removed from the string before it is split up
 * ("^" if not given, will be added at the beginning)
 * \param postfix regular expression for text to be removed from the string before it is split up
 * ("$" if not given, will be added at the end)
 * \returns a list of the casted tokens
 */
template<typename TARGET> std::list<TARGET> stringToList(
	std::string source, const boost::regex &separator,
	boost::regex prefix, boost::regex postfix )
{
	std::list<TARGET> ret;
	assert( ! separator.empty() );

	if ( ! prefix.empty() ) {
		if ( prefix.str()[0] != '^' )
			prefix = boost::regex( std::string( "^" ) + prefix.str(), prefix.flags() );

		source = boost::regex_replace( source, prefix, "", boost::format_first_only | boost::match_default );
	}

	if ( ! postfix.empty() ) {
		if ( postfix.str()[postfix.size() - 1] != '$' )
			postfix = boost::regex( postfix.str() + "$", postfix.flags() );

		source = boost::regex_replace( source, postfix, "", boost::format_first_only | boost::match_default );
	}

	boost::sregex_token_iterator i = boost::make_regex_token_iterator( source, separator, -1 );
	const boost::sregex_token_iterator token_end;

	while ( i != token_end ) {
		ret.push_back( boost::lexical_cast<TARGET>( ( i++ )->str() ) );
	}

	return ret;
}
Exemple #4
0
	bool operator()(boost::regex& r) const {
		try {
			if (wildCard) {
				r.assign(AirUtil::regexEscape(pattern, true), boost::regex::icase);
			} else {
				r.assign(pattern);
			}
			return true;
		} catch(const std::runtime_error&) {
			LogManager::getInstance()->message(STRING_F(INVALID_PATTERN, pattern), LogManager::LOG_ERROR);
			return false;
		}
	}
Exemple #5
0
bool EnumService::parse_regex_replace(const std::string& regex_replace, boost::regex& regex, std::string& replace)
{
  bool success = false;

  // Split the regular expression into the match and replace sections.  RFC3402
  // says any character other than 1-9 or i can be the delimiter, but
  // recommends / or !.  We just use the first character and reject if it
  // doesn't neatly split the regex into two.
  std::vector<std::string> match_replace;
  Utils::split_string(regex_replace, regex_replace[0], match_replace);

  if (match_replace.size() == 2)
  {
    TRC_DEBUG("Split regex into match=%s, replace=%s", match_replace[0].c_str(), match_replace[1].c_str());
    try
    {
      regex.assign(match_replace[0], boost::regex::extended);
      replace = match_replace[1];
      success = true;
    }
    catch (...)
    {
      success = false;
    }
  }
  else
  {
    success = false;
  }

  return success;
}
void Location::parseGprmc(string gprmc)
{
	DebugOut(7)<<"parsing gprmc message"<<endl;

	regularExpression.assign(gprmcRegEx);

	boost::smatch tokens;

	if (boost::regex_match (gprmc, tokens, regularExpression) )
	{


		if(tokens[4] == "A")
		{
			isActive = true;
		}

		int i=0;
		for(auto tok : tokens)
		{
			DebugOut(0)<<i++<<":"<<tok<<endl;

		}

		parseTime(tokens[1],tokens[2],tokens[3],tokens[13],tokens[14],tokens[15]);

		parseLatitude(tokens[5], tokens[6], tokens[7]);
		parseLongitude(tokens[8], tokens[9], tokens[10]);
		parseSpeed(tokens[11]);
		parseDirection(tokens[12]);
	}
}
Exemple #7
0
	bool operator()(const boost::regex& r) const {
		try {
			return !r.empty() && boost::regex_search(str, r);
		} catch(const std::runtime_error&) {
			// most likely a stack overflow, ignore...
			return false;
		}
	}
int ChessEngineGnu::match(const string   &str,
                          boost::regex   &re,
                          vector<string> &matches)
{
  boost::cmatch what;

  matches.clear();

  GC_TRACE("match(): %s\n", re.str().c_str());

  if( boost::regex_match(str.c_str(), what, re) )
  {
    // what[0] is the whole string
    for(size_t i=1; i<what.size(); ++i)
    {
      GC_TRACE("  \"%s\"\n", what[i].str().c_str());
      matches.push_back(what[i].str());
    }
  }

  GC_TRACE("  %zu matches\n", matches.size());

  return (int)matches.size();
}
TestCaseReader::TestCaseReader(const boost::filesystem::path & testCaseDir)
{
    const boost::regex expr("(\\d{3,4})-(.*)\\.xml");
    for (boost::filesystem::directory_iterator it = boost::filesystem::directory_iterator(testCaseDir);
         it != boost::filesystem::directory_iterator(); ++it)
    {
        const boost::filesystem::path path = it->path();
        //ignore files that don't end in ".xml"
        if (path.extension() != ".xml")
        {
            continue;
        }

#if defined (BOOST_FILESYSTEM_VERSION) && BOOST_FILESYSTEM_VERSION == 3
        const std::string filename = path.filename().string();
#else
        const std::string filename = path.filename();
#endif

        boost::smatch matchResults;

        if (boost::regex_match(filename,matchResults,expr))
        {
            //std::wcout << "Found testcase " << matchResults[1].str().c_str() << " brief description '" << matchResults[2].str().c_str()<< "'" << std::endl;
            const size_t tc = boost::lexical_cast<size_t>(matchResults[1]);

            if (m_testCases.size() < (tc + 1))
            {
                m_testCases.resize(tc + 1);
            }

            if (m_testCases[tc] != NULL)
            {
                std::wcerr << "There appears to be two test cases with number " << tc << std::endl;
                exit(1);
            }

            std::ostringstream xml;
            xml << boost::filesystem::ifstream(path).rdbuf();
            //std::wcout << "Read xml (" << xml.str().size() << " bytes) '" << xml.str().c_str() << "'" << std::endl;
            try
            {
                m_testCases[tc] = boost::dynamic_pointer_cast<DoseTest::Items::TestCase>
                    (Safir::Dob::Typesystem::Serialization::ToObject(Safir::Dob::Typesystem::Utilities::ToWstring(xml.str())));
            }
            catch (const std::exception & exc)
            {
                std::wcerr << "Failed to read file '" << path.string().c_str() << "' due to exception with message" << std::endl
                           <<exc.what() << std::endl;
                exit(2);
            }
        }
        else
        {
            std::wcerr << "File '"
                       << path.filename().c_str()
                       << "' did not match the pattern for test case files: '"
                       << expr.str().c_str()
                       << "'"  << std::endl;
        }
    }
}
void write( const string& sourceFilepath,
            pwiz::identdata::IdentDataFile::Format outputFormat,
            const string& filenameSuffix,
            const string& searchEngineName,
            const string& searchEngineVersion,
            const string& searchEngineURI,
            const string& searchDatabase,
            boost::regex cleavageAgentRegex,
            const string& decoyPrefix,
            const RunTimeVariableMap& vars ) const
{
    using namespace pwiz::identdata;
    namespace msdata = pwiz::msdata;
    namespace proteome = pwiz::proteome;

    IdentData mzid;

    mzid.id = sourceFilepath + " " + searchDatabase + " " + searchEngineName + " " + searchEngineVersion;
    mzid.creationDate = GetDateTime();

    // add default CVs
    mzid.cvs = defaultCVList();

    // add the SpectrumIdentificationProtocol
    SpectrumIdentificationProtocolPtr sipPtr(new SpectrumIdentificationProtocol("SIP"));
    mzid.analysisProtocolCollection.spectrumIdentificationProtocol.push_back(sipPtr);

    CVTranslator cvTranslator;
    CVID searchEngineCVID = cvTranslator.translate(searchEngineName);

    // add analysis software
    sipPtr->analysisSoftwarePtr.reset(new AnalysisSoftware("AS"));
    mzid.analysisSoftwareList.push_back(sipPtr->analysisSoftwarePtr);

    // set software name
    if (searchEngineCVID != CVID_Unknown)
        sipPtr->analysisSoftwarePtr->softwareName.set(searchEngineCVID);
    else
        sipPtr->analysisSoftwarePtr->softwareName.set(MS_custom_unreleased_software_tool, searchEngineName);

    // set version and URI
    sipPtr->analysisSoftwarePtr->version = searchEngineVersion;
    sipPtr->analysisSoftwarePtr->URI = searchEngineURI;

    // set search type
    sipPtr->searchType.cvid = MS_ms_ms_search;

    // add a mass table for all MS levels
    MassTablePtr massTable(new MassTable("MT"));
    massTable->msLevel.push_back(1);
    massTable->msLevel.push_back(2);
    massTable->msLevel.push_back(3);
    sipPtr->massTable.push_back(massTable);

    // specify amino acid masses used
    const char* residueSymbols = "ACDEFGHIKLMNPQRSTUVWY";
    for (int i=0; i < 21; ++i)
    {
        const AminoAcid::Info::Record& record = AminoAcid::Info::record(residueSymbols[i]);       
        ResiduePtr rp(new Residue);
        rp->code = record.symbol;
        rp->mass = record.residueFormula.monoisotopicMass();
        massTable->residues.push_back(rp);
    }

    // add the SpectrumIdentificationList
    SpectrumIdentificationListPtr silPtr(new SpectrumIdentificationList("SIL"));
    mzid.dataCollection.analysisData.spectrumIdentificationList.push_back(silPtr);

    if (vars.count("SearchStats: Overall"))
    {
        string searchStats = vars.find("SearchStats: Overall")->second;
        silPtr->numSequencesSearched = lexical_cast<int>(searchStats.substr(0, searchStats.find_first_of(' ')));
    }

    // add the SpectrumIdentification
    SpectrumIdentificationPtr siPtr(new SpectrumIdentification("SI"));
    siPtr->spectrumIdentificationListPtr = silPtr;
    siPtr->spectrumIdentificationProtocolPtr = sipPtr;
    siPtr->activityDate = mzid.creationDate;
    mzid.analysisCollection.spectrumIdentification.push_back(siPtr);

    // add search database
    SearchDatabasePtr sdb(new SearchDatabase("SDB"));
    sdb->fileFormat.cvid = MS_FASTA_format;
    sdb->location = searchDatabase;
    sdb->name = bfs::path(searchDatabase).filename();
    sdb->set(MS_database_type_amino_acid);
    sdb->databaseName.userParams.push_back(UserParam("database name", sdb->name, "xsd:string"));
    mzid.dataCollection.inputs.searchDatabase.push_back(sdb);
    mzid.analysisCollection.spectrumIdentification[0]->searchDatabase.push_back(sdb);

    // add source file
    SpectraDataPtr spectraData(new SpectraData("SD"));
    spectraData->location = sourceFilepath;
    spectraData->name = bfs::path(spectraData->location).filename();
    mzid.dataCollection.inputs.spectraData.push_back(spectraData);
    mzid.analysisCollection.spectrumIdentification[0]->inputSpectra.push_back(spectraData);

    // set source file format (required for a semantically valid mzIdentML file)
    msdata::ReaderPtr readers(new msdata::FullReaderList);
    CVID sourceFileFormat = msdata::identifyFileFormat(readers, sourceFilepath);
    if (sourceFileFormat != CVID_Unknown)
        spectraData->fileFormat.cvid = sourceFileFormat;
    else if (outputFormat == IdentDataFile::Format_MzIdentML)
        throw runtime_error("[SearchSpectraList::write] unable to determine source file format of \"" + sourceFilepath + "\"");

    {
        msdata::MSDataFile msd(sourceFilepath, readers.get());
        spectraData->spectrumIDFormat.cvid = msdata::id::getDefaultNativeIDFormat(msd);
    }

    // add the cleavage rules
    EnzymePtr enzyme(new Enzyme);
    enzyme->id = "ENZ_" + lexical_cast<string>(sipPtr->enzymes.enzymes.size()+1);
    enzyme->terminalSpecificity = (proteome::Digestion::Specificity) lexical_cast<int>(vars.find("Config: MinTerminiCleavages")->second);
    enzyme->nTermGain = "H";
    enzyme->cTermGain = "OH";
    enzyme->missedCleavages = lexical_cast<int>(vars.find("Config: MaxMissedCleavages")->second);
    enzyme->minDistance = 1;
    enzyme->siteRegexp = cleavageAgentRegex.str();

    CVID cleavageAgent = proteome::Digestion::getCleavageAgentByRegex(enzyme->siteRegexp);
    if (cleavageAgent != CVID_Unknown)
        enzyme->enzymeName.set(cleavageAgent);

    sipPtr->enzymes.enzymes.push_back(enzyme);


    // use monoisotopic mass unless PrecursorMzToleranceRule forces average
    bool forceAverageMass = vars.find("Config: PrecursorMzToleranceRule")->second == "avg";

    if (forceAverageMass)
        sipPtr->additionalSearchParams.set(MS_parent_mass_type_average);
    else
        sipPtr->additionalSearchParams.set(MS_parent_mass_type_mono);

    sipPtr->additionalSearchParams.set(MS_fragment_mass_type_mono);

    MZTolerance precursorMzTolerance;
    string precursorMassType = forceAverageMass ? "Avg" : "Mono";
    parse(precursorMzTolerance, vars.find("Config: " + precursorMassType + "PrecursorMzTolerance")->second);
    sipPtr->parentTolerance.set(MS_search_tolerance_minus_value, precursorMzTolerance.value);
    sipPtr->parentTolerance.set(MS_search_tolerance_plus_value, precursorMzTolerance.value);
    sipPtr->parentTolerance.cvParams[0].units = sipPtr->parentTolerance.cvParams[1].units =
        precursorMzTolerance.units == MZTolerance::PPM ? UO_parts_per_million : UO_dalton;

    MZTolerance fragmentMzTolerance;
    parse(fragmentMzTolerance, vars.find("Config: FragmentMzTolerance")->second);
    sipPtr->fragmentTolerance.set(MS_search_tolerance_minus_value, fragmentMzTolerance.value);
    sipPtr->fragmentTolerance.set(MS_search_tolerance_plus_value, fragmentMzTolerance.value);
    sipPtr->fragmentTolerance.cvParams[0].units = sipPtr->fragmentTolerance.cvParams[1].units =
        fragmentMzTolerance.units == MZTolerance::PPM ? UO_parts_per_million : UO_dalton;

    sipPtr->threshold.set(MS_no_threshold);

    string fragmentationRule = vars.find("Config: FragmentationRule")->second;
    if (bal::icontains(fragmentationRule, "cid"))     translateIonSeriesConsidered(*sipPtr, "b,y");
    if (bal::icontains(fragmentationRule, "etd"))     translateIonSeriesConsidered(*sipPtr, "c,z+1");
    if (bal::icontains(fragmentationRule, "manual"))  translateIonSeriesConsidered(*sipPtr, fragmentationRule.substr(7)); // skip "manual:"


    DynamicModSet dynamicMods( vars.find("Config: DynamicMods")->second );
    BOOST_FOREACH(const DynamicMod& mod, dynamicMods)
    {
        SearchModificationPtr searchModification(new SearchModification);

        switch( mod.unmodChar )
        {
            case PEPTIDE_N_TERMINUS_SYMBOL:
                searchModification->massDelta = mod.modMass;
                searchModification->fixedMod = false;
                searchModification->specificityRules.cvid = MS_modification_specificity_N_term;
                break;

            case PEPTIDE_C_TERMINUS_SYMBOL:
                searchModification->massDelta = mod.modMass;
                searchModification->fixedMod = false;
                searchModification->specificityRules.cvid = MS_modification_specificity_C_term;
                break;

            default:
            {
                string specificity; // either empty, n, or c, but not both

                if (mod.NTerminalFilters.size() == 1 &&
                    mod.NTerminalFilters[0].m_filter[PEPTIDE_N_TERMINUS_SYMBOL])
                    specificity += 'n';
                else if (mod.CTerminalFilters.size() == 1 &&
                         mod.CTerminalFilters[0].m_filter[PEPTIDE_C_TERMINUS_SYMBOL])
                specificity += 'c';

                searchModification->massDelta = mod.modMass;
                searchModification->residues.push_back(mod.unmodChar);
                searchModification->fixedMod = false;

                if (specificity == "n")
                    searchModification->specificityRules.cvid = MS_modification_specificity_N_term;
                else if (specificity == "c")
                    searchModification->specificityRules.cvid = MS_modification_specificity_C_term;
                break;
            }
        }
        sipPtr->modificationParams.push_back(searchModification);
    }
void bcp_implementation::copy_path(const fs::path& p)
{
   assert(!fs::is_directory(m_boost_path / p));
   if(fs::exists(m_dest_path / p))
   {
      std::cout << "Copying (and overwriting) file: " << p.string() << "\n";
     fs::remove(m_dest_path / p);
   }
   else
      std::cout << "Copying file: " << p.string() << "\n";
   //
   // create the path to the new file if it doesn't already exist:
   //
   create_path(p.branch_path());
   //
   // do text based copy if requested:
   //
   if(p.leaf() == "Jamroot")
   {
      static std::vector<char> v1, v2;
      v1.clear();
      v2.clear();
      std::ifstream is((m_boost_path / p).c_str());
      std::copy(std::istreambuf_iterator<char>(is), std::istreambuf_iterator<char>(), std::back_inserter(v1));

      static boost::regex libname_matcher;
      if(libname_matcher.empty())
      {
         libname_matcher.assign("boost_");
      }

      regex_replace(std::back_inserter(v2), v1.begin(), v1.end(), libname_matcher, m_namespace_name + "_");
      std::swap(v1, v2);
      v2.clear();

      std::ofstream os;
      if(m_unix_lines)
         os.open((m_dest_path / p).c_str(), std::ios_base::binary | std::ios_base::out);
      else
         os.open((m_dest_path / p).c_str(), std::ios_base::out);
      os.write(&*v1.begin(), v1.size());
      os.close();
   }
   else if(m_namespace_name.size() && m_lib_names.size() && is_jam_file(p))
   {
      static std::vector<char> v1, v2;
      v1.clear();
      v2.clear();
      std::ifstream is((m_boost_path / p).c_str());
      std::copy(std::istreambuf_iterator<char>(is), std::istreambuf_iterator<char>(), std::back_inserter(v1));

      static boost::regex libname_matcher;
      if(libname_matcher.empty())
      {
         std::string re = "\\<";
         re += *m_lib_names.begin();
         for(std::set<std::string>::const_iterator i = ++m_lib_names.begin(); i != m_lib_names.end(); ++i)
         {
            re += "|" + *i;
         }
         re += "\\>";
         libname_matcher.assign(re);
      }

      regex_replace(std::back_inserter(v2), v1.begin(), v1.end(), libname_matcher, get_new_library_name(m_namespace_name));
      std::swap(v1, v2);
      v2.clear();

      std::ofstream os;
      if(m_unix_lines)
         os.open((m_dest_path / p).c_str(), std::ios_base::binary | std::ios_base::out);
      else
         os.open((m_dest_path / p).c_str(), std::ios_base::out);
      os.write(&*v1.begin(), v1.size());
      os.close();
   }
   else if(m_namespace_name.size() && is_source_file(p))
   {
      //
      // v1 hold the current content, v2 is temp buffer.
      // Each time we do a search and replace the new content 
      // ends up in v2: we then swap v1 and v2, and clear v2.
      //
      static std::vector<char> v1, v2;
      v1.clear();
      v2.clear();
      std::ifstream is((m_boost_path / p).c_str());
      std::copy(std::istreambuf_iterator<char>(is), std::istreambuf_iterator<char>(), std::back_inserter(v1));

      static const boost::regex namespace_matcher(
         "(?|"
            "(namespace\\s+)boost(_\\w+)?(?:(\\s*::\\s*)phoenix)?"
         "|"
            "(namespace\\s+)(adstl|phoenix|rapidxml)\\>"
         "|"
            "()\\<boost((?:_(?!intrusive_tags)\\w+)?\\s*(?:::))(?:(\\s*)phoenix)?"
         "|"
            "()\\<((?:adstl|phoenix|rapidxml)\\s*(?:::))"
         "|"
         "(namespace\\s+\\w+\\s*=\\s*(?:::\\s*)?)boost(_\\w+)?(?:(\\s*::\\s*)phoenix)?"
         "|"
            "(namespace\\s+\\w+\\s*=\\s*(?:::\\s*)?(?:\\w+\\s*::\\s*)?)(adstl|phoenix|rapidxml)\\>"
         "|"
            "(^\\s*#\\s*define\\s+\\w+\\s+)boost((?:_\\w+)?\\s*)$"
         "|"
            "(^\\s*#\\s*define[^\\n]+)((?:adstl|phoenix|rapidxml)\\s*)$"
         "|"
            "()boost(_asio_detail_posix_thread_function|_regex_free_static_mutex)"
         "|"
            "()(lw_thread_routine|at_thread_exit|on_process_enter|on_process_exit|on_thread_enter|on_thread_exit|tss_cleanup_implemented)"
         "|"
            "(BOOST_CLASS_REQUIRE4?[^;]*)boost((?:_\\w+)?\\s*,)"
         "|"
            "(\\(\\s*)boost(\\s*\\))"
         ")"
      );

      regex_replace(std::back_inserter(v2), v1.begin(), v1.end(), namespace_matcher, "$1" + m_namespace_name + "$2(?3$3" + m_namespace_name + "phoenix)", boost::regex_constants::format_all);
      std::swap(v1, v2);
      v2.clear();

      if(m_namespace_alias)
      {
         static const boost::regex namespace_alias(
            /*
            "namespace\\s+" + m_namespace_name + 
            "\\s*"
            "("
               "\\{"
               "(?:"
                  "(?>[^\\{\\}/]+)"
                  "(?>"
                     "(?:"
                        "(?1)"
                        "|//[^\\n]+$"
                        "|/[^/]"
                        "|(?:^\\s*#[^\\n]*"
                           "(?:(?<=\\\\)\\n[^\\n]*)*)"
                     ")"
                     "[^\\{\\}]+"
                  ")*"
               ")*"
               "\\}"
            ")"
            */
            /*
            "(namespace\\s+" + m_namespace_name + 
            "\\s*\\{.*"
            "\\})([^\\{\\};]*)\\z"
            */
            "namespace\\s+" + m_namespace_name + 
            "\\s*\\{"
            );
         regex_replace(std::back_inserter(v2), v1.begin(), v1.end(), namespace_alias, 
            "namespace " + m_namespace_name + "{} namespace boost = " + m_namespace_name + "; namespace " + m_namespace_name + "{");
         std::swap(v1, v2);
         v2.clear();
      }

      std::ofstream os;
      if(m_unix_lines)
         os.open((m_dest_path / p).c_str(), std::ios_base::binary | std::ios_base::out);
      else
         os.open((m_dest_path / p).c_str(), std::ios_base::out);
      if(v1.size())
         os.write(&*v1.begin(), v1.size());
      os.close();
   }
   else if(m_unix_lines && !is_binary_file(p))
   {
      std::ifstream is((m_boost_path / p).c_str());
      std::istreambuf_iterator<char> isi(is);
      std::istreambuf_iterator<char> end;

      std::ofstream os((m_dest_path / p).c_str(), std::ios_base::binary | std::ios_base::out);
      std::ostreambuf_iterator<char> osi(os);

      std::copy(isi, end, osi);
   }
   else
   {
      // binary copy:
      fs::copy_file(m_boost_path / p, m_dest_path / p);
   }
}
Exemple #12
0
	MarkExtracter(std::ostream& inOutStream, const DesignSharedPtr& inDesign, 
		string inPattern) : mStream(inOutStream), mDesign(inDesign), mPattern(inPattern) {
		mStream << "Searching for '" << mPattern << "'" << std::endl;
		mStream << "NEAT" << std::endl;
		mRegex.assign(mPattern);
	}
Exemple #13
0
int main(int argc, char * argv[])
{
   try{
      po::options_description opts("Options");
      opts.add_options()
         ("help,h", "produce help message") 
         //("after-context,A", po::value<int>(&after_context)->default_value(0), "Print arg  lines  of  trailing  context  after  matching  lines. Places  a  line  containing  --  between  contiguous  groups  of matches.")
         //("before-context,B", po::value<int>(&before_context)->default_value(0), "Print  arg  lines  of  leading  context  before  matching lines. Places  a  line  containing  --  between  contiguous  groups  of matches.")
         //("context,C", po::value<int>(), "Print  arg lines of output context.  Places a line containing -- between contiguous groups of matches.")
         ("byte-offset,b", "Print the byte offset within the input file before each line  of output.")
         ("count,c", "Suppress normal output; instead print a count of matching  lines for  each  input  file.  With the -v, --invert-match option (see below), count non-matching lines.")
         ("extended-regexp,E", "Interpret PATTERN as an POSIX-extended regular expression.")
         ("perl-regexp,P", "Interpret PATTERN as a Perl regular expression.")
         //("regexp,e", po::value<std::string>(&pattern), "Use PATTERN as the pattern; useful to protect patterns beginning with -.")
         ("basic-regexp,G", "Interpret arg as a POSIX-basic regular expression (see below).  This is the default.")
         ("ignore-case,i", "Ignore case distinctions in  both  the  PATTERN  and  the  input files.")
         ("files-without-match,L", "Suppress  normal  output;  instead  print the name of each input file from which no output would normally have been printed.  The scanning will stop on the first match.")
         ("files-with-matches,l", "Suppress  normal  output;  instead  print the name of each input file from which output would normally have  been  printed.   The scanning will stop on the first match.")
         ("line-number,n", "Prefix each line of output with the line number within its input file.")
         ;
      // Hidden options, will be allowed both on command line and
      // in config file, but will not be shown to the user.
      po::options_description hidden("Hidden options");
      hidden.add_options()
         ("input-file", po::value< std::vector<std::string> >(), "input file")
         ("input-pattern", po::value< std::string >(), "input file")
         ;

      po::options_description cmdline_options;
      cmdline_options.add(opts).add(hidden);

      po::positional_options_description p;
      p.add("input-pattern", 1);
      p.add("input-file", -1);

      po::variables_map vm;
      po::store(po::command_line_parser(argc, argv).options(cmdline_options)/*.options(hidden)*/.positional(p).run(), vm);
      po::notify(vm);

      if (vm.count("help")) 
      {
         std::cout << opts << "\n";
         return 0;
      }
      if (vm.count("context")) 
      {
         after_context = vm["context"].as< int >();
         before_context = after_context;
      }
      if(vm.count("extended-regexp"))
      {
         flags = boost::regex_constants::extended;
      }
      if(vm.count("basic-regexp"))
      {
         flags = boost::regex_constants::basic;
      }
      if(vm.count("perl-regexp"))
      {
         flags = boost::regex_constants::perl;
      }
      if(vm.count("ignore-case"))
      {
         flags |= boost::regex_constants::icase;
      }
      if(vm.count("byte-offset"))
      {
         print_byte_offset = true;
      }
      if(vm.count("count"))
      {
         count_only = true;
      }
      if(vm.count("files-without-match"))
      {
         print_non_matching_files = true;
      }
      if(vm.count("files-with-matches"))
      {
         files_only = true;
      }
      if(vm.count("line-number"))
      {
         print_line_numbers = true;
      }
      if(vm.count("input-pattern"))
      {
         pattern = vm["input-pattern"].as< std::string >();
         re.assign(pattern, flags);
      }
      else
      {
         std::cerr << "No pattern specified" << std::endl;
         return 1;
      }
      if (vm.count("input-file"))
      {
         const std::vector<std::string>& files = vm["input-file"].as< std::vector<std::string> >();
         file_count = files.size();
         for(std::vector<std::string>::const_iterator i = files.begin(); i != files.end(); ++i)
         {
            process_file(*i);
         }
      }
      else
      {
         // no input files, scan stdin instead:
         process_stream(std::cin);
      }

   }
   catch(const std::exception& e)
   {
      std::cerr << e.what() << std::endl;
   }

   return 0;
}
Exemple #14
-1
int
main (int argc, const char *argv[])
{
    Filesystem::convert_native_arguments (argc, (const char **)argv);
    ArgParse ap;
    ap.options ("iinfo -- print information about images\n"
                OIIO_INTRO_STRING "\n"
                "Usage:  iinfo [options] filename...",
                "%*", parse_files, "",
                "--help", &help, "Print help message",
                "-v", &verbose, "Verbose output",
                "-m %s", &metamatch, "Metadata names to print (default: all)",
                "-f", &filenameprefix, "Prefix each line with the filename",
                "-s", &sum, "Sum the image sizes",
                "-a", &subimages, "Print info about all subimages",
                "--hash", &compute_sha1, "Print SHA-1 hash of pixel values",
                "--stats", &compute_stats, "Print image pixel statistics (data window)",
                NULL);
    if (ap.parse(argc, argv) < 0 || filenames.empty()) {
        std::cerr << ap.geterror() << std::endl;
        ap.usage ();
        return EXIT_FAILURE;
    }
    if (help) {
        ap.usage ();
        exit (EXIT_FAILURE);
    }

    if (! metamatch.empty())
        field_re.assign (metamatch,
                         boost::regex::extended | boost::regex_constants::icase);

    // Find the longest filename
    size_t longestname = 0;
    BOOST_FOREACH (const std::string &s, filenames)
        longestname = std::max (longestname, s.length());
    longestname = std::min (longestname, (size_t)40);

    long long totalsize = 0;
    BOOST_FOREACH (const std::string &s, filenames) {
        ImageInput *in = ImageInput::open (s.c_str());
        if (! in) {
            std::string err = geterror();
            if (err.empty())
                err = Strutil::format ("Could not open \"%s\"", s.c_str());
            std::cerr << "iinfo: " << err << "\n";
            continue;
        }
        ImageSpec spec = in->spec();
        print_info (s, longestname, in, spec, verbose, sum, totalsize);
        in->close ();
        delete in;
    }