Esempio n. 1
0
bool QgsGPXProvider::deleteFeatures( const QgsFeatureIds & id )
{
  if ( mFeatureType == WaypointType )
    data->removeWaypoints( id );
  else if ( mFeatureType == RouteType )
    data->removeRoutes( id );
  else if ( mFeatureType == TrackType )
    data->removeTracks( id );

  // write back to file
  QFile file( mFileName );
  if ( !file.open( QIODevice::WriteOnly ) )
    return false;
  QTextStream ostr( &file );
  data->writeXML( ostr );
  return true;
}
Esempio n. 2
0
int Plugin::replaceWithLink(std::string filepath)
{
    std::cout << "Replacing with link " << filepath.c_str() << std::endl;

    std::ifstream fstr(filepath.c_str());
    MD5Engine md5;
    DigestOutputStream ostr(md5);
    Poco::StreamCopier::copyStream(fstr, ostr);
    ostr.flush();
    const DigestEngine::Digest& digest = md5.digest();
    std::string sourceMd5 = DigestEngine::digestToHex(digest);
    std::cout << "File contents MD5 sum: " << sourceMd5.c_str() << std::endl;

    // Generate new file name
    UUIDGenerator gen;
    UUID tmpUuid = gen.createRandom();
    std::string uuid = tmpUuid.toString(); 
    std::string newFile(Plugin::GIT_CACHE_DIR);
    newFile.append("/");
    newFile.append(uuid);

    Process::Args args;
    args.push_back(filepath);
    args.push_back(newFile);
    Poco::ProcessHandle ph = Process::launch("mv", args, 0, 0, 0);

    // Failback with sudo
    if (ph.wait() != 0)
    {
        args.clear();
        args.push_back("mv");
        args.push_back(filepath);
        args.push_back(newFile);
        ph = Process::launch("sudo", args, 0, 0, 0);
    }

    // Check if file was moved
    File originalFile(filepath);
    if (originalFile.exists())
    {
        std::cout << "Failed to move original file" << std::endl;
        return -1;
    }

    return 1;
}
Esempio n. 3
0
// static
void LLSDRPCServer::buildResponse(
	const LLChannelDescriptors& channels,
	LLBufferArray* data,
	const LLSD& response)
{
	LLMemType m1(LLMemType::MTYPE_IO_SD_SERVER);
	LLBufferStream ostr(channels, data);
	ostr << RESPONSE_PART_1;
	LLSDSerialize::toNotation(response, ostr);
	ostr << RESPONSE_PART_2;
#if LL_DEBUG
	std::ostringstream debug_ostr;
	debug_ostr << "LLSDRPCServer::buildResponse: ";
	LLSDSerialize::toNotation(response, debug_ostr);
	llinfos << debug_ostr.str() << llendl;
#endif
}
Esempio n. 4
0
bool wxRegKey::Export(const wxString& filename) const
{
#if wxUSE_FFILE && wxUSE_STREAMS
    if ( wxFile::Exists(filename) )
    {
        wxLogError(_("Exporting registry key: file \"%s\" already exists and won't be overwritten."),
                   filename.c_str());
        return false;
    }

    wxFFileOutputStream ostr(filename, wxT("w"));

    return ostr.IsOk() && Export(ostr);
#else
    wxUnusedVar(filename);
    return false;
#endif
}
Esempio n. 5
0
void write_ini(const std::string& filename,const ini_t& ini)
{
	std::ofstream ostr(filename.c_str());

	if(!ostr)
		throw std::runtime_error("Could not open \""+filename+"\" for writing.");

	std::vector<std::string> lines;

	for(ini_t::const_iterator iter=ini.begin();iter!=ini.end();++iter)
		lines.push_back(strip_whitespace(iter->first)+"="+strip_whitespace(iter->second));

	for(size_t ii=0;ii<lines.size();++ii)
		if(!(ostr<<lines[ii]<<std::endl))
			throw std::runtime_error("Error while writing \""+filename+"\".");

	ostr.close();
}
Esempio n. 6
0
File: elf.c Progetto: rui314/8cc-old
static void write_one_symbol(Symbol *sym, int *index, String *symtab, String *strtab) {
    if (sym->name) {
        o4(symtab, STRING_LEN(strtab)); // st_name
        ostr(strtab, STRING_BODY(sym->name));
    } else {
        o4(symtab, 0); // st_name
    }
    o1(symtab, ELF64_ST_INFO(sym->bind, sym->type)); // st_info;
    o1(symtab, 0); // st_other;
    if (sym->defined) {
        o2(symtab, sym->section->shndx); // st_shndx
    } else {
        o2(symtab, 0); // st_shndx
    }
    o8(symtab, sym->value); // st_value
    o8(symtab, 0); // st_size
    sym->index = (*index)++;
}
Esempio n. 7
0
std::vector<std::string>
Base::getVarname( std::string &s, std::vector<std::string> &alias)
{
  // There might be a varname specification or not.
  // no varname found: return true
  // The reference 'alias' is special for operations,
  // e.g. v=x=var1,y=var2,... . If given, then var1 is the
  // variable returned via the vector and x,y,... are members
  // stored in alias.

  std::vector<std::string> list;
  std::vector<std::string> names;

  list = getVarname( s ) ;

  // expand the list
  for( size_t i=0 ; i < list.size() ; ++i)
  {
    Split spl(list[i], "=");

    if( spl.size() == 2 )
    {
      alias.push_back( spl[0] ) ;
      names.push_back( spl[1] ) ;
    }
    else if( spl.size() == 1 )
    {
      alias.push_back( "" ) ;
      names.push_back( spl[0] ) ;
    }
    else
    {
      std::ostringstream ostr(std::ios::app);
      ostr << "Base::getVarname(): invalid assignment\n";
      ostr << " of variable names." ;

      exceptionError( ostr.str() );
      std::string note("E9: invalid assignment of variable names.");
      finally(9, note);
    }
  }

  return names;
}
Esempio n. 8
0
bool QgsGPXProvider::addFeatures( QgsFeatureList & flist )
{

  // add all the features
  for ( QgsFeatureList::iterator iter = flist.begin();
        iter != flist.end(); ++iter )
  {
    if ( !addFeature( *iter ) )
      return false;
  }

  // write back to file
  QFile file( mFileName );
  if ( !file.open( QIODevice::WriteOnly ) )
    return false;
  QTextStream ostr( &file );
  data->writeXML( ostr );
  return true;
}
Esempio n. 9
0
void RealSettings::save(boost::shared_ptr<ISettings> const &me)
{
    (debugSettings ? LogNotice : LogDebug) << "RealSettings::save(" << name_ << ")";
    grab aholdof(lock_);
    if (dirty_) {
        //  Only re-write if dirty. This allows a settings file to be edited on disk and re-loaded
        //  with a flush on the admin interface.
        std::string tmpName;
        std::string fileName;
        fileName = fac_->path_ + "/" + name_ + ".set";
        tmpName = fileName + ".tmp";
        {
            std::ofstream ostr(tmpName.c_str(), std::ios::binary | std::ios::out | std::ios::trunc);
            ostr << "# istatd settings 1" << std::endl;
            for (std::map<std::string, std::string>::iterator ptr(settings_.begin()), end(settings_.end());
                ptr != end; ++ptr)
            {
                if ((*ptr).second.size())
                {
                    //  empty string values are not saved -- same as "delete"
                    ostr << (*ptr).first << "=" << istat::sql_quote((*ptr).second) << std::endl;
                }
            }
        }
        //  Now, move the new file in place of the old.
        //  First, remove the old file, to generate an error if we don't have permission.
        if (boost::filesystem::exists(fileName))
        {
            boost::filesystem::remove(fileName);
        }
        boost::filesystem::rename(tmpName, fileName);
    }
    else
    {
        if (debugSettings.enabled())
        {
            LogNotice << "settings not dirty";
        }
    }
    saveQueued_ = false;
    dirty_ = false;
    ++countSaves;
}
Esempio n. 10
0
void
TestLocalXform::testIO()
{
    USING_NK_NS
    USING_NKHIVE_NS

    LocalXform xform(vec3d(0.1f, 0.2f, 0.5f));

    LocalXform xform2;

    CPPUNIT_ASSERT(xform != xform2);

    std::ostringstream ostr(std::ios_base::binary);
    xform.write(ostr);
    std::istringstream istr(ostr.str(), std::ios_base::binary);
    xform2.read(istr);

    CPPUNIT_ASSERT(xform == xform2);
}
Esempio n. 11
0
int main(int argc, char **argv)
{
   int input, output;
   if (argc < 2) {
      std::cerr << "Usage: hddmcp <inputfile1.hddm> ... <outputfile.hddm>"
                << std::endl;
      exit(1);
   }
   else {
      output = argc-1;
   }

   std::ofstream ofs(argv[output]);
   if (!ofs.is_open()) {
      std::cerr << "Usage: hddmcp <inputfile1.hddm> ... <outputfile.hddm>"
                << std::endl;
      exit(1);
   }
   hddm_s::ostream ostr(ofs);
   ostr.setCompression(hddm_s::k_bz2_compression);

   std::ifstream ifs;
   hddm_s::HDDM record;
   for (input=1; input<output; input++) {
      ifs.open(argv[input]);
      if (!ifs.is_open()) {
         std::cerr << "Error - could not open input file " << argv[input]
                   << std::endl;
         exit(1);
      }
      else {
         hddm_s::istream istr(ifs);
         //istr.skip(9999);
         int count=0;
         while (ifs.good()) {
            istr >> record;
            ostr << record;
            record.clear();
            ++count;
         }
      }
   }
}
Esempio n. 12
0
// virtual
LLIOPipe::EStatus LLIOSleeper::process_impl(
	const LLChannelDescriptors& channels,
	buffer_ptr_t& buffer,
	bool& eos,
	LLSD& context,
	LLPumpIO* pump)
{
	if(!mRespond)
	{
		LL_DEBUGS() << "LLIOSleeper::process_impl() sleeping." << LL_ENDL;
		mRespond = true;
		static const F64 SLEEP_TIME = 2.0;
		pump->sleepChain(SLEEP_TIME);
		return STATUS_BREAK;
	}
	LL_DEBUGS() << "LLIOSleeper::process_impl() responding." << LL_ENDL;
	LLBufferStream ostr(channels, buffer.get());
	ostr << "huh? sorry, I was sleeping." << std::endl;
	return STATUS_DONE;
}
Esempio n. 13
0
                        void writeBuffer()
                        {
				std::ofstream ostr(filename.c_str(), std::ios::binary | std::ios::app);
                                ostr.write ( 
                                        reinterpret_cast<char const *>(pa),
                                        reinterpret_cast<char const *>(pc)-reinterpret_cast<char const *>(pa)
				);
				ostr.flush();
				
				if ( ! ostr )
				{
				        ::libmaus::exception::LibMausException se;
				        se.getStream() << "Failed to flush buffer in SynchronousOutputBuffer8::writeBuffer()";
				        se.finish();
				        throw se;
				}

				ostr.close();
                                pc = pa;
                        }
osgDB::ReaderWriter::WriteResult
ReaderWriterOSGObjects::writeObject( const osg::Object& obj, const std::string& fileName, const Options* options ) const
{
    OSG_INFO << "ReaderWriterOSGObjects: writeObject " << fileName << std::endl;

    const std::string ext = osgDB::getFileExtension( fileName );
    if( !acceptsExtension( ext ) )
        return( WriteResult::FILE_NOT_HANDLED );

    bool result( false );
    osg::Object* nonConstObj( const_cast< osg::Object* >( &obj ) );
    osg::Array* array( dynamic_cast< osg::Array* >( nonConstObj ) );
    if( array != NULL )
    {
        osgDB::Output ostr( fileName.c_str() );
        result = Array_writeLocalData( *array, ostr );
    }

    return( result ? WriteResult::FILE_SAVED : WriteResult::ERROR_IN_WRITING_FILE );
}
Esempio n. 15
0
	Void compressImpl(const std::string& path)
	{
		std::string gzPath(path);
		gzPath.append(".gz");
		FileInputStream istr(path, std::ios::binary | std::ios::in);
		if (!istr.good()) throw OpenFileException(path);
		FileOutputStream ostr(gzPath, std::ios::binary | std::ios::out);
		if (ostr.good())
		{
			DeflatingOutputStream deflater(ostr, DeflatingStreamBuf::STREAM_GZIP);
			StreamCopier::copyStream(istr, deflater);
			deflater.close();
			ostr.close();
			istr.close();
			File f(path);
			f.remove();
		}
		else throw CreateFileException(gzPath);
		return Void();
	}
Esempio n. 16
0
void Parse(const std::string& rcFile, const std::string& out)
{
    std::ifstream fstr(rcFile);
    std::ofstream ostr(out);
    std::regex rexBuildNum("\\s*#define\\s*BUILD_NUM\\s*(\\d+)");
    for (std::string line; std::getline(fstr, line);)
    {
        std::smatch res;
        if (std::regex_match(line, res, rexBuildNum))
        {
            std::string incremented("#define BUILD_NUM ");
            incremented.append(std::to_string(std::stoi(res[1]) + 1));
            ostr << incremented << '\n';
        }
        else
        {
            ostr << line << '\n';
        }
    }
}
Esempio n. 17
0
        static bool generate(OutputIterator& sink, Context& context
          , Delimiter const& d, Attribute const& attr)
        {
            typedef karma::detail::iterator_sink<
                OutputIterator, Char, CharEncoding, Tag
            > sink_device;

            if (!traits::has_optional_value(attr))
                return false;

            // use existing operator<<()
            typedef typename attribute<Context>::type attribute_type;

            boost::iostreams::stream<sink_device> ostr(sink);
            ostr << traits::extract_from<attribute_type>(attr, context) << std::flush;

            if (ostr.good()) 
                return karma::delimit_out(sink, d);   // always do post-delimiting
            return false;
        }
Esempio n. 18
0
			static void sortFile(std::string const & filename)
			{
				uint64_t const len = ::libmaus2::util::GetFileSize::getFileSize(filename);
				assert ( len % sizeof(::libmaus2::graph::TripleEdge) == 0 );
				uint64_t const numtriples = len / sizeof(::libmaus2::graph::TripleEdge);
				std::ifstream istr(filename.c_str(), std::ios::binary);
				::libmaus2::autoarray::AutoArray< ::libmaus2::graph::TripleEdge> T(numtriples);
				istr.read ( reinterpret_cast<char *>(T.get()), len);
				assert ( istr );
				assert ( istr.gcount() == static_cast<int64_t>(len) );
				istr.close(); 
				
				std::sort ( T.get(), T.get() + numtriples );

				std::ofstream ostr(filename.c_str(), std::ios::binary);
				ostr.write( reinterpret_cast<char const *>(T.get()), len );
				assert ( ostr );
				ostr.flush();
				assert ( ostr );
				ostr.close();
			}
Esempio n. 19
0
void MainWindow::on_action_save_as_triggered() {
    QString default_path;
    {
        const auto &desktop_abs = QStandardPaths::standardLocations(
                    QStandardPaths::DesktopLocation);

        if (desktop_abs.count() == 0) {
            default_path = QDir().absolutePath();
        }
        else {
            default_path = desktop_abs.first();
        }
    }

    QString target_path = m_image_path;
    QString ext = m_image_path.split(".").last().toLower();

    if (QImageReader::supportedImageFormats().contains(ext.toUtf8())) {
        target_path = target_path.mid(0, target_path.length() - ext.length() - 1); // -1 is for "."
    }
    target_path = QStringLiteral("%1.webp").arg(target_path);

    QString image_path = QFileDialog::getSaveFileName(
            this, tr("Save File"),
            QDir(default_path).absoluteFilePath(target_path),
            tr("WEBP (*.webp)"));

    if (image_path.isEmpty()) {
        return;
    }

    QFile ostr(image_path);
    if (ostr.open(QIODevice::WriteOnly | QIODevice::Truncate)) {
        ostr.write(m_out_data);
    }
    else {
        QMessageBox::critical(this, tr("File could not be saved"),
                              tr("%1 could not be opened for writing").arg(image_path));
    }
}
Esempio n. 20
0
void Foam::writeFaceSet
(
    const bool binary,
    const vtkMesh& vMesh,
    const faceSet& set,
    const fileName& fileName
)
{
    const faceList& faces = vMesh.mesh().faces();

    std::ofstream ostr(fileName.c_str());

    writeFuns::writeHeader
    (
        ostr,
        binary,
        set.name()
    );

    ostr<< "DATASET POLYDATA" << std::endl;

    //------------------------------------------------------------------
    //
    // Write topology
    //
    //------------------------------------------------------------------


    // Construct primitivePatch of faces in faceSet.

    faceList setFaces(set.size());
    labelList setFaceLabels(set.size());
    label setFacei = 0;

    forAllConstIter(faceSet, set, iter)
    {
        setFaceLabels[setFacei] = iter.key();
        setFaces[setFacei] = faces[iter.key()];
        setFacei++;
    }
Esempio n. 21
0
                        static std::vector<FastInterval> buildIndex(std::string const & filename, uint64_t const steps = 1)
                        {
				std::string const indexfilename = getIndexFileName(filename,steps);

				if ( ::libmaus2::util::GetFileSize::fileExists ( indexfilename ) )
				{
				        libmaus2::aio::InputStreamInstance istr(indexfilename);
				        std::vector < FastInterval > intervals = ::libmaus2::fastx::FastInterval::deserialiseVector(istr);
				        return intervals;
				}
				else
				{
                                        reader_type reader(filename);
	        			std::vector<FastInterval> intervals = reader.enumerateOffsets(steps);

        				libmaus2::aio::OutputStreamInstance ostr(indexfilename);
	        			FastInterval::serialiseVector(ostr,intervals);
		        		ostr.flush();

			        	return intervals;
                                }
                        }
Esempio n. 22
0
static int
deffuncs(struct lk_ctx *ctx, int fd)
{
	unsigned int i;
	int ct = 0;
	char *ptr, *s;
	struct kbsentry kbs;

	for (i = 0; i < MAX_NR_FUNC; i++) {
		kbs.kb_func = (unsigned char) i;

		ptr = lk_array_get_ptr(ctx->func_table, i);

		if (ptr) {
			strcpy((char *)kbs.kb_string, ptr);
			if (ioctl(fd, KDSKBSENT, (unsigned long)&kbs)) {
				s = ostr(ctx, (char *)kbs.kb_string);
				if (s == NULL)
					return -1;
				ERR(ctx, _("failed to bind string '%s' to function %s"),
				    s, get_sym(ctx, KT_FN, kbs.kb_func));
				free(s);
			} else {
				ct++;
			}
		} else if (ctx->flags & LK_FLAG_CLEAR_STRINGS) {
			kbs.kb_string[0] = 0;

			if (ioctl(fd, KDSKBSENT, (unsigned long)&kbs)) {
				ERR(ctx, _("failed to clear string %s"),
				    get_sym(ctx, KT_FN, kbs.kb_func));
			} else {
				ct++;
			}
		}
	}
	return ct;
}
Esempio n. 23
0
void ServiceDaemon::daemonize()
{
  pid_t pid;
  if ((pid = fork()) < 0)
  {
    std::cerr << "Unable to fork daemon!"  << std::endl;
    std::cerr.flush();
    _exit(0);
  }
  else if (pid != 0)
  {
    _exit(0);
  }
  setpgrp();
  ::close(STDIN_FILENO);

  if (!_pidFile.empty())
  {
    std::ofstream ostr(_pidFile.c_str());
    if (ostr.good())
      ostr << getpid() << std::endl;
  }
}
Esempio n. 24
0
void WinTestRunner::run()
{
	// Note: The following code is some evil hack to
	// add batch capability to the MFC based WinTestRunner.
	
	std::string cmdLine(AfxGetApp()->m_lpCmdLine);
	if (cmdLine.size() >= 2 && cmdLine[0] == '/' && (cmdLine[1] == 'b' || cmdLine[1] == 'B'))
	{
		// We're running in batch mode.
		std::string outPath;
		if (cmdLine.size() > 4 && cmdLine[2] == ':')
			outPath = cmdLine.substr(3);
		else
			outPath = "CON";
		std::ofstream ostr(outPath.c_str());
		if (ostr.good())
		{
			TestRunner runner(ostr);
			for (std::vector<Test*>::iterator it = _tests.begin(); it != _tests.end(); ++it)
				runner.addTest((*it)->toString(), *it);
			_tests.clear();
			std::vector<std::string> args;
			args.push_back("WinTestRunner");
			args.push_back("-all");
			bool success = runner.run(args);
			ExitProcess(success ? 0 : 1);
		}
		else ExitProcess(2);
	}
	else
	{
		// We're running in interactive mode.
		TestRunnerDlg dlg;
		dlg.setTests(_tests);
		dlg.DoModal();
	}
}
Esempio n. 25
0
void Susi::Syscall::Worker::run() {
	Poco::Pipe outPipe;
	Poco::Pipe errPipe;

	Poco::ProcessHandle ph = Poco::Process::launch(_cmd, _args, 0, &outPipe, &errPipe);

	Poco::PipeInputStream ostr(outPipe);
	Poco::PipeInputStream estr(errPipe);


	if(_bg == true) {
		auto start_payload = Susi::Util::Any::Object{
			{"process_type" , _process_type },
			{"started", true}			
		};
		auto started_event = Susi::Events::createEvent("syscall::startedProcess");
		started_event->payload["result"] = start_payload;

		Susi::Events::publish(std::move(started_event));
	}

	int rc = ph.wait();

	Susi::Util::Any end_payload = Susi::Util::Any::Object{
		{"process_type" , _process_type },
		{"stdout", this->getPipeContent(ostr)},
		{"stderr", this->getPipeContent(estr)},
		{"return", rc}
	};

	//std::cout<<"Payload:"<<end_payload.toString()<<std::endl;

	auto end_event = Susi::Events::createEvent("syscall::endProcess");
	end_event->payload["result"] = end_payload;

	Susi::Events::publish(std::move(end_event));	
}
TskModule::Status TskExecutableModule::execute(TskFile * fileToAnalyze){
    try
    {
        // Perform macro expansion on command line args.
        std::string arguments = expandArgumentMacros(m_arguments, fileToAnalyze);

        // Split the arguments into a vector of strings.
        Poco::StringTokenizer tokenizer(arguments, " ");

        std::vector<std::string> vectorArgs(tokenizer.begin(), tokenizer.end());

        // Perform macro expansion on our output location
        std::string outFilePath = expandArgumentMacros(m_output, fileToAnalyze);

        // If an output file has been specified we need to ensure that anything
        // written to stdout gets put in the file. This is accomplished by passing
        // a pipe to Poco::Process::launch and reading its contents once the process
        // has terminated.
        if (!outFilePath.empty())
        {
            // Create directories that may be missing along the path.
            std::string outFilePathNoQuote(TskUtilities::stripQuotes(outFilePath));
            Poco::Path outPath(outFilePathNoQuote);
            Poco::File outDir(outPath.parent());
            outDir.createDirectories();

            // Create the output file if it does not exist.
            Poco::File outFile(outFilePathNoQuote);

            if (!outFile.exists())
            {
                outFile.createFile();
            }

            // Create process redirecting its output to a Pipe.
            Poco::Pipe outPipe;

            Poco::ProcessHandle handle = Poco::Process::launch(m_modulePath, vectorArgs, NULL, &outPipe, NULL);
            
            // Copy output from Pipe to the output file.
            Poco::PipeInputStream istr(outPipe);
            Poco::FileOutputStream ostr(outFile.path(), std::ios::out|std::ios::app);

            while (istr)
            {
                Poco::StreamCopier::copyStream(istr, ostr);
            }

            // The process should be finished. Check its exit code.
            int exitCode = Poco::Process::wait(handle);

            if (exitCode != 0)
            {
                // If a module fails we log a warning message and continue.
                std::wstringstream msg;
                msg << L"TskExecutableModule::execute - Module (" << m_modulePath.c_str()
                    << L") failed with exit code: " << exitCode << std::endl;
                LOGWARN(msg.str());
            }
        }
        else
        {
            // No output file was specified.
            Poco::ProcessHandle handle = Poco::Process::launch(m_modulePath, vectorArgs);

            // Wait for the process to complete
            int exitCode = Poco::Process::wait(handle);

            if (exitCode != 0)
            {
                // If a module fails we log a warning message and continue.
                std::wstringstream msg;
                msg << L"TskExecutableModule::execute - Module (" << m_modulePath.c_str()
                    << L") failed with exit code: " << exitCode << std::endl;
                LOGWARN(msg.str());
            }
        }
    }
    catch (Poco::Exception& ex)
    {
        std::wstringstream errorMsg;
        errorMsg << L"TskExecutableModule::execute - Error: " << ex.displayText().c_str() << std::endl;
        LOGERROR(errorMsg.str());
        throw TskException("Module execution failed.");
    }

    return TskModule::OK;
}
Esempio n. 27
0
int main(int argc, char *argv[])
{
  Test::Output *pout;
  TestType tt(testTypeCompiler);
  int rtn(EXIT_SUCCESS);

  // if user passed command line argument then parse it
  if (argc==1)
  {
    tt=testTypeCompiler;
  }
  else if (argc==2)
  {
    size_t lenargv(strlen(argv[1]));

    // using short codes
    if (lenargv==2)
    {
      if (argv[1][0]=='-')
      {
        switch(argv[1][1])
        {
          case('t'):
            tt=testTypeText;
            break;
          case('c'):
            tt=testTypeCompiler;
            break;
          case('h'):
            tt=testTypeHTML;
            break;
          default:
            std::cerr << "Unrecognized parameter: " << argv[1] << std::endl;
            rtn=EXIT_FAILURE;
            break;
        }
      }
      else
      {
        std::cerr << "Unrecognized parameter: " << argv[1] << std::endl;
        rtn=EXIT_FAILURE;
      }
    }
    else
    {
      if (lenargv==6)
      {
        if (std::strncmp(argv[1], "--text", lenargv)==0)
          tt=testTypeText;
        else if (std::strncmp(argv[1], "--html", lenargv)==0)
          tt=testTypeHTML;
        else if (std::strncmp(argv[1], "--help", lenargv)==0)
          rtn=EXIT_FAILURE;
        else
        {
          std::cerr << "Unrecognized parameter: " << argv[1] << std::endl;
          rtn=EXIT_FAILURE;
        }
      }
      else if (lenargv==10)
      {
        if (std::strncmp(argv[1], "--compiler", lenargv)==0)
          tt=testTypeCompiler;
        else
        {
          std::cerr << "Unrecognized parameter: " << argv[1] << std::endl;
          rtn=EXIT_FAILURE;
        }
      }
    }
  }
  else
  {
    std::cerr << "Can only pass one argument." << std::endl;
    rtn=EXIT_FAILURE;
  }
  if (rtn==EXIT_FAILURE)
  {
    std::cerr << "  Usage: " << argv[0] << " [--text|-t|--compiler|-c|--html|-h]" << std::endl;
    return rtn;
  }

  // allocate the correct output type
  switch (tt)
  {
    case(testTypeText):
    {
      Test::TextOutput *po = new Test::TextOutput(Test::TextOutput::Verbose);
      pout = static_cast<Test::Output *>(po);
      break;
    }
    case(testTypeCompiler):
    {
      Test::CompilerOutput *po = new Test::CompilerOutput(Test::CompilerOutput::GCC);
      pout = static_cast<Test::Output *>(po);
      break;
    }
    case(testTypeHTML):
    {
      Test::HtmlOutput *po = new Test::HtmlOutput;
      pout = static_cast<Test::Output *>(po);
      break;
    }
    default:
    {
      rtn=EXIT_FAILURE;
      break;
    }
  }

  if (rtn == EXIT_SUCCESS)
  {
    // get the current time information
    time_t rawtime;
    struct tm * timeinfo;
    std::string datetime;
    time (&rawtime);
    timeinfo = localtime(&rawtime);
    datetime = asctime(timeinfo);

    // add the test suites to the test runner
    // NOTE: This is where changes should be needed
    //
    Test::Suite ts;
    std::string ostr_filename("airfoil_test_results.html");

    // add the cppack test suites
    ts.add(std::auto_ptr<Test::Suite>(new four_digit_test_suite<float>()));
    ts.add(std::auto_ptr<Test::Suite>(new four_digit_test_suite<double>()));
    ts.add(std::auto_ptr<Test::Suite>(new four_digit_test_suite<long double>()));

    //
    // NOTE: End of section that should be changed

    // run the test
    rtn = (ts.run(*pout)) ? EXIT_SUCCESS : EXIT_FAILURE;

    // generate the html data if requested
    if (tt==testTypeHTML)
    {
      std::ofstream ostr(ostr_filename.c_str());
      Test::HtmlOutput *phtmlout=dynamic_cast<Test::HtmlOutput *>(pout);

      phtmlout->generate(ostr, true, datetime);

      ostr.close();
    }

    delete pout;
  }

  return rtn;
}
Esempio n. 28
0
int main (int argc, char **argv)
{
	if (argc < 7)
	{
		std::cerr << "Usage: " << argv [0] << " a b from to num_samples variance" << std::endl;
		return 0;
	}

	const double a = boost::lexical_cast<double> (argv [1]);
	const double b = boost::lexical_cast<double> (argv [2]);
	const double from = boost::lexical_cast<double> (argv [3]);
	const double to = boost::lexical_cast<double> (argv [4]);
	const size_t samples = boost::lexical_cast<size_t> (argv [5]);
	const double variance = boost::lexical_cast<double> (argv [6]);

	std::cout << "computing " << a << " + " << b << "x" << " on [" << from << ":" << to << "] with " << samples << " samples and " << variance << " variance" << std::endl;

	const auto& srcXs = generateXs (from, to, samples);
	auto xs = srcXs;
	const auto xAvg = std::accumulate (xs.begin (), xs.end (), 0.0) / samples;
	for (auto& x : xs)
		x -= xAvg;

	const auto& ys = generateYs (xs, a, b, variance);

	const auto diffs = std::accumulate (srcXs.begin (), srcXs.end (), 0.0, [xAvg] (DType_t res, DType_t x) { return res + std::pow (x - xAvg, 2); });

	std::vector<std::pair<SampleType_t<>, DType_t>> pairs;
	for (auto ix = xs.cbegin (), iy = ys.begin (); ix != xs.cend (); ++ix, ++iy)
	{
		SampleType_t<> sample;
		sample (0) = *ix;
		pairs.push_back ({ sample, *iy });
	}

	auto res = [] (const std::pair<SampleType_t<>, DType_t>& data, const Params_t<2>& p)
		{ return p (0) + p (1) * data.first (0) - data.second; };
	auto der = [] (const std::pair<SampleType_t<>, DType_t>& data, const Params_t<2>& p) -> Params_t<2>
	{
		Params_t<2> res;
		res (0) = 1;
		res (1) = data.first (0);
		return res;
	};

	const auto& p = solve<2> (pairs, res, der, {{ 1, 1 }});
	std::cout << "inferred params: " << dlib::trans (p) << std::endl;

	const auto& pca = solve<2> (pairs, res, der,
			[] (auto, const Params_t<2>& p) { return p (1); },
			[] (auto) { return 0.01; },
			[] (auto) { return 0.01; },
			{{ 1, 1 }},
			1);
	std::cout << "inferred 'fixed' L-M params: " << dlib::trans (pca) << std::endl;

	const auto da0 = variance * variance / samples;
	const auto da1 = variance * variance / diffs;
	std::cout << "book stuff: " << da0 << "; " << da1 << std::endl;

	std::cout << "real stuff diff: " << std::endl;
	auto solver = [res, der] (const TrainingSet_t<>& set) { return solve<2> (set, res, der, {{ 1, 1 }}); };
	StatsKeeper<decltype (solver)> keeper (solver, 0, variance, pairs, false);

	std::ofstream ostr (std::string ("linear_log_") + argv [1] + "x_" + argv [2] + "_samples_" + argv [5] + "_variance_" + argv [6] + ".log");
	std::ofstream ostrN (std::string ("linear_log_") + argv [1] + "x_" + argv [2] + "_samples_" + argv [5] + "_variance_" + argv [6] + "_norm.log");

	for (size_t i = 0; i < 100000; ++i)
	{
		keeper.TryMore (1000);
		const auto& stats = keeper.GetRunning ();

		const auto diff0 = std::abs (std::pow (stats [0].stddev (), 2) - da0);
		const auto diff1 = std::abs (std::pow (stats [1].stddev (), 2) - da1);

		if (!(i % 10))
		{
			std::cout << "\t" << i << "\t" << diff0 << ";\t\t";
			std::cout << diff1 << std::endl;
		}

		ostr << i << " " << diff0 << " " << diff1 << std::endl;
		ostrN << i << " " << diff0 / da0 << " " << diff1 / da1 << std::endl;
	}

	return 0;
}
Esempio n. 29
0
int main(int argc, char* argv[]) {

  // timing mechanism
  clock_t start, before_operation, after_operation, end;
  start = clock();

  // parse the command line arguments
  if (argc != 5 && argc != 7) {
    std::cerr << "Error: wrong number of arguments." << std::endl;
    usage();
  }
  std::string data_structure = argv[1];
  std::string operation = argv[2];
  std::string input = argv[3];
  int input_count = -1;
  int string_length = -1;
  std::string output_file;
  if (input == "random") {
    assert (argc == 7);
    input_count = atoi(argv[4]);
    string_length = atoi(argv[5]);
    output_file = argv[6];
  } else {
    assert (argc == 5);
    output_file = argv[4];
  } 

  // load the data into a heap-allocated, C-style array
  std::string *input_data;
  load_data(input,input_data,input_count,string_length);

  // prepare space for the answer (at most the same size as the input!)
  std::string *output_data = new std::string[input_count];
  int output_count;

  // mark the time before we start
  before_operation = clock();

  // perform the operation
  if (data_structure == "vector") 
    vector_test(input_data,input_count,operation,output_data,output_count);
  else if (data_structure == "list")
    list_test(input_data,input_count,operation,output_data,output_count);
  else if (data_structure == "bst")  // STL set or map
    bst_test(input_data,input_count,operation,output_data,output_count);
  else if (data_structure == "priority_queue")
    priority_queue_test(input_data,input_count,operation,output_data,output_count);
  else if (data_structure == "hash_table")  // STL unordered_set or unordered_map
    hash_table_test(input_data,input_count,operation,output_data,output_count);
  else {
    std::cerr << "Error: unknown data structure: " << data_structure << std::endl;
    usage();
    exit(0);
  }

  // mark the time once we are done
  after_operation = clock();

  // output the data
  std::ofstream ostr(output_file.c_str());
  for (int i = 0; i < output_count; i++) {
    ostr << output_data[i] << std::endl;
  }
  // cleanup
  delete [] input_data;
  delete [] output_data;

  // print statistics
  end = clock();
  double load_time = double(before_operation-start)/CLOCKS_PER_SEC;
  double operation_time = double(after_operation-before_operation)/CLOCKS_PER_SEC;
  double output_time = double(end-after_operation)/CLOCKS_PER_SEC;
  std::cout << "load time:          " << load_time << std::endl;
  std::cout << "operation time:     " << operation_time << std::endl;
  std::cout << "output time:        " << output_time << std::endl;
  std::cout << "input/output ratio: " << input_count << ":" << output_count << std::endl;
  return 0;
}
Esempio n. 30
0
void Mesh::CreateSVG(const std::string& filename) const {
  std::ofstream ostr(filename.c_str());
  ostr << "<body bgcolor=dddddd  onLoad=\"render()\" >\n";

  // a few checkboxes at the top of the page to control the visualization
  ostr << "<form name=\"orderForm\">\n";
  ostr << "   <input type=\"checkbox\" name=\"illegal\"   checked  "
       << " onClick=\"render()\">draw illegal (red) & next legal collapse (blue) edges<br>\n";
  ostr << "   <input type=\"checkbox\" name=\"wireframe\"          "
       << " onClick=\"render()\">draw all edges<br>\n";
  ostr << "   <input type=\"checkbox\" name=\"black\"              "
       << " onClick=\"render()\">toggle white vs. black<br>\n";
  ostr << "</form>\n";

  // javascript to actually change the visualization based on the checkboxes
  ostr << "<script language=\"JavaScript\">\n";
  ostr << "  function render() {\n";
  ostr << "    var mysvg = document.getElementById(\"mesh\");\n";
  ostr << "    if (document.orderForm.wireframe.checked == false) {\n";
  ostr << "      var polys = mysvg.children;\n";
  ostr << "      for (var i = 0; i < polys.length; i++) {\n";
  ostr << "        if (polys[i].tagName.toUpperCase() == \"POLYGON\") {\n";
  ostr << "          polys[i].style[\"strokeWidth\"] = \"0\"\n";
  ostr << "        }\n";
  ostr << "      }\n";
  ostr << "    } else if (document.orderForm.black.checked == false) {\n";
  ostr << "      var polys = mysvg.children;\n";
  ostr << "      for (var i = 0; i < polys.length; i++) {\n";
  ostr << "        if (polys[i].tagName.toUpperCase() == \"POLYGON\") {\n";
  ostr << "          polys[i].style.stroke = \"#FFFFFF\"\n";
  ostr << "          polys[i].style[\"strokeWidth\"] = \"1\"\n";
  ostr << "        }\n";
  ostr << "      }\n";
  ostr << "      mysvg.style.background = \"white\"\n";
  ostr << "    } else  {\n";
  ostr << "      var polys = mysvg.children;\n";
  ostr << "      for (var i = 0; i < polys.length; i++) {\n";
  ostr << "        if (polys[i].tagName.toUpperCase() == \"POLYGON\") {\n";
  ostr << "          polys[i].style.stroke = \"#000000\"\n";
  ostr << "          polys[i].style[\"strokeWidth\"] = \"2\"\n";
  ostr << "        }\n";
  ostr << "      }\n";
  ostr << "      mysvg.style.background = \"white\"\n";
  ostr << "    }\n";
  ostr << "    if (document.orderForm.illegal.checked == false) {\n";
  ostr << "      var polys = mysvg.children;\n";
  ostr << "      for (var i = 0; i < polys.length; i++) {\n";
  ostr << "        if (polys[i].tagName.toUpperCase() == \"LINE\") {\n";
  ostr << "          polys[i].style[\"strokeWidth\"] = \"0\"\n";
  ostr << "        }\n";
  ostr << "      }\n";
  ostr << "    } else  {\n";
  ostr << "      var polys = mysvg.children;\n";
  ostr << "      for (var i = 0; i < polys.length; i++) {\n";
  ostr << "        if (polys[i].tagName.toUpperCase() == \"LINE\") {\n";
  ostr << "          polys[i].style[\"strokeWidth\"] = \"5\"\n";
  ostr << "        }\n";
  ostr << "      }\n";
  ostr << "      mysvg.style.background = \"white\"\n";
  ostr << "    }\n";
  ostr << "  }\n";
  ostr << "</script>\n";

  ostr << "<svg  id=\"mesh\" height=\"" << height + 2*BORDER
       << "\" width=\""    << width + 2*BORDER
       << "\" style=\"background:white\" shape-rendering=\"crispEdges\">\n";

  // draw the triangles with the average color of the vertices
  for (triangles_set::const_iterator itr = triangles.begin(); itr != triangles.end(); itr++) {
    Triangle *t = *itr;
    float r = (t->getVertex(0)->r() +t->getVertex(1)->r() +t->getVertex(2)->r()) / 3.0;
    float g = (t->getVertex(0)->g() +t->getVertex(1)->g() +t->getVertex(2)->g()) / 3.0;
    float b = (t->getVertex(0)->b() +t->getVertex(1)->b() +t->getVertex(2)->b()) / 3.0;
    ostr << "<polygon points=\""
         << std::setw(8) << t->getVertex(0)->x() << "," << std::setw(8) << t->getVertex(0)->y() << "  "
         << std::setw(8) << t->getVertex(1)->x() << "," << std::setw(8) << t->getVertex(1)->y() << "  "
         << std::setw(8) << t->getVertex(2)->x() << "," << std::setw(8) << t->getVertex(2)->y()
         << "\" style=\"fill:#" << OutputColor(Vertex(0,0,r,g,b)) 
         << ";stroke:#" << OutputColor(Vertex(0,0,r,g,b)) 
         << ";stroke-width:1"
         << ";stroke-linecap:round\" "
         << ";stroke-linejoin:round\" "
         << "/>" << std::endl;
  }

  // draw the illegal edges in red
  for (edges_map::const_iterator itr = edges.begin(); itr != edges.end(); itr++) {
    const Edge *e = itr->second;
    assert (itr->first.first->getID() < itr->first.second->getID());
    if (!e->isLegal()) {
      ostr << "<line "
           << "x1=\"" << std::setw(8) << e->getV1()->x() << "\" "
           << "y1=\"" << std::setw(8) << e->getV1()->y() << "\" "
           << "x2=\"" << std::setw(8) << e->getV2()->x() << "\" " 
           << "y2=\"" << std::setw(8) << e->getV2()->y() << "\" "
           << " stroke=\"red\" "
           << " stroke-width=\"0\" "
           << " stroke-linecap=\"round\" "
           << "/>" << std::endl;
    }
  }

  // draw the next (legal) edge to collapse in blue
  Edge *e = FindEdge();
  if (e != NULL) {
    ostr << "<line "
         << "x1=\"" << std::setw(8) << e->getV1()->x() << "\" " 
         << "y1=\"" << std::setw(8) << e->getV1()->y() << "\" "
         << "x2=\"" << std::setw(8) << e->getV2()->x() << "\" " 
         << "y2=\"" << std::setw(8) << e->getV2()->y() << "\" "
         << " stroke=\"blue\" "
         << " stroke-width=\"0\" "
         << " stroke-linecap=\"round\" "
         << "/>" << std::endl;
  }
  
  ostr << "</svg>\n";

  // print some simple stats at the bottom of the page
  ostr << "<p>" << *this << "</p>" << std::endl;
  ostr << "</body>\n";
}