コード例 #1
0
QVariantList FileService::loadPlayListService(QString playlistdir , QString theplaylist )  {

    FileService::localAudiodir=playlistdir + "/" + audiodir ;
    FileService::localLyricsdir=playlistdir + "/" + lyricsdir ;
    FileService::localChordsdir=playlistdir + "/" + chordsdir;

    QList<QJsonObject> dictTunes;
    QVariantList tuneDescList;

    int i;
    QString line;
    QStringList csvDecode;
    QJsonObject tuneDesc ;

    QFile file(playlistdir + "/" + theplaylist);
    if (!file.open(QIODevice::ReadOnly | QIODevice::Text))
        return QVariantList() << "Error Open File " << playlistdir << "/" << theplaylist ;

    QTextStream in(&file);
    i=0;

    while (!in.atEnd()) {
        line = in.readLine();
        csvDecode=csv(line,i);
        if(csvDecode.count() > 1) {
            tuneDesc = getTuneDesc(csvDecode) ;
            tuneDescList << tuneDesc;
        }
        i+=1;
    }
    return tuneDescList;
}
コード例 #2
0
int main( int ac, char** av )
{
    try
    {
        comma::command_line_options options( ac, av );
        if( options.exists( "--help" ) || options.exists( "-h" ) || ac == 1 ) { usage(); }        
        double d = boost::lexical_cast< double >( options.unnamed( "", "--binary,-b,--delimiter,-d,--fields,-f" )[0] );
        int sign = d < 0 ? -1 : 1;
        int minutes = int( std::floor( std::abs( d )/60 ) );
        int seconds = int( std::floor( std::abs( d ) - double(minutes) * 60 ) );
        int microseconds = int( ( std::abs( d ) - ( double(minutes) * 60 + seconds ) ) * 1000000 );
        minutes *= sign;
        seconds *= sign;
        microseconds *= sign;
        boost::posix_time::time_duration delay = boost::posix_time::minutes( minutes ) + boost::posix_time::seconds( seconds ) + boost::posix_time::microseconds( microseconds );
        comma::csv::options csv( options );
        comma::csv::input_stream< Point > istream( std::cin, csv );
        comma::csv::output_stream< Point > ostream( std::cout, csv );
        comma::signal_flag is_shutdown;
        while( !is_shutdown && std::cin.good() && !std::cin.eof() )
        {
            const Point* p = istream.read();
            if( !p ) { break; }
            Point q = *p;
            q.timestamp = p->timestamp + delay;
            if( csv.binary() ) { ostream.write( q, istream.binary().last() ); }
            else { ostream.write( q, istream.ascii().last() ); }
        }
        if( is_shutdown ) { std::cerr << "csv-time-delay: interrupted by signal" << std::endl; }
        return 0;     
    }
    catch( std::exception& ex ) { std::cerr << "csv-time-delay: " << ex.what() << std::endl; }
    catch( ... ) { std::cerr << "csv-time-delay: unknown exception" << std::endl; }
    usage();
}
コード例 #3
0
ファイル: lines_nearest.cpp プロジェクト: acfr/snark
int traits::run( const comma::command_line_options& options )
{
    comma::csv::options csv( options );
    csv.full_xpath = true;
    bool discard_collinear = options.exists( "--discard-collinear" );
    line_t first_default = comma::csv::ascii< line_t >().get( options.value< std::string >( "--first", "0,0,0,0,0,0" ) );
    line_t second_default = comma::csv::ascii< line_t >().get( options.value< std::string >( "--second", "0,0,0,0,0,0" ) );
    comma::csv::input_stream< lines_t > istream( std::cin, csv, std::make_pair( first_default, second_default ) );
    comma::csv::output_stream < output_t > ostream( std::cout, csv.binary(), false, csv.flush );
    comma::csv::tied< lines_t, output_t > tied( istream, ostream );
    while( istream.ready() || ( std::cin.good() && !std::cin.eof() ) )
    {
        const lines_t* r = istream.read();
        if( !r ) { break; }
        const Eigen::Vector3d& f = ( r->first.second - r->first.first ).normalized();
        const Eigen::Vector3d& s = ( r->second.second - r->second.first ).normalized();
        if( comma::math::equal( f.dot( s ), f.norm() * s.norm() ) )
        {
            if( discard_collinear ) { continue; }
            std::cerr << "points-calc: lines-nearest: got collinear lines (" << r->first.first.transpose() << " , " << r->first.second.transpose() << ") and (" << r->second.first.transpose() << " , " << r->second.second.transpose() << "), please use --discard collinear to discard" << std::endl;
            return 1;
        }
        const Eigen::Vector3d& m = s.cross( f ).normalized();
        const Eigen::Vector3d& n = s.cross( m ).normalized();
        const Eigen::Vector3d& d = r->second.first - r->first.first;
        const Eigen::Vector3d& a = r->first.first + f * n.dot( d ) / n.dot( f );
        const Eigen::Vector3d& b = a + m * m.dot( d );
        tied.append( output_t( a, b ) );
    }
    return 0;
}
コード例 #4
0
// Read in a csv file containing transactions in the following format:
// location,item_sku,sales_amount currency_code
// Total all sales for a given item_sku in the requested currency
double totalTransactions(QString filename, QString item, QString currency) {
    // for each line, split, if matches item, get currency, convert, add to total
    double sum = 0.0;
    QFile csv(filename);
    csv.open(QIODevice::ReadOnly);
    while (true) {
        QString line = csv.readLine();
        if (line.isEmpty())
            break;
        QStringList split = line.split(QRegExp("[, \n]"));
        if (split.size() < 4 || split[1] != item)
            continue;
        bool ok = false;
        double amount = split[2].toDouble(&ok);
        Currency *c = Currency::get(split[3]);
        if (!ok) {
            qDebug() << "Failed to parse amount:" << split[2];
            continue;
        }
        if (!c)
            continue;
        sum += roundToEven(amount * c->to(currency) * 100.0) / 100.0;
    }
    return sum;
}
コード例 #5
0
void SqlTableModel::ouvrirCSV(QString commande)
{
    QTemporaryFile* temporaryFile = new QTemporaryFile(parent());
    if (temporaryFile->open()) {
        QxtCsvModel csv(this);
        csv.insertColumns(0, columnCount());
        csv.insertRows(0, rowCount());
        for (int column = 0; column < csv.columnCount(); column ++) {
            csv.setHeaderText(column, headerData(column, Qt::Horizontal).toString());
        }
        for (int row = 0; row < csv.rowCount(); row ++) {
            for (int column = 0; column < csv.columnCount(); column ++) {
                csv.setText(row, column, QSqlTableModel::data(index(row, column)).toString());
            }
        }
        csv.toCSV(temporaryFile->fileName(), true);
        temporaryFile->close();
        QProcess* process = new QProcess();
        process->start(commande, QStringList { temporaryFile->fileName() });
        connect(process, SIGNAL(finished(int)), temporaryFile, SLOT(deleteLater()));
    } else {
        qCritical() << temporaryFile->errorString();
    }

}
コード例 #6
0
ファイル: asd-to-csv.cpp プロジェクト: WangFei-DUT/snark
 static void run(const comma::command_line_options& options)
 {
     comma::csv::options csv(options);
     if(options.exists("--output-fields")) { std::cout<<comma::join(comma::csv::names<T>(), ',')<<std::endl; return;}
     if(options.exists("--output-format")) { std::cout<< comma::csv::format::value<T>(csv.fields,true)<<std::endl; return;}
     process(csv);
 }
コード例 #7
0
// Test heating HLT based on mash out temperature (non-cascaded control)
BOOST_FIXTURE_TEST_CASE(Simulate_HLT_Heater_Acts_On_MashTemp, SimMashDirect)
{
    ofstream csv("./test_results/" + boost_test_name() + ".csv");
    csv << "1# mash setPoint, 2#error, 1#mash out sensor, 1#hlt sensor, 1#mash in temp, 3#heater pwm, 3# header realized pwm, 4#p, 4#i, 4#d" << endl;
    double SetPointDouble = 68;
    for(int t = 0; t < 7200; t++){
        /*if(t==600){
            SetPointDouble = 68;
        }*/
        mashSet->write(SetPointDouble);
        update();

        csv     << mashSet->read() << "," // setpoint
                << hltHeaterPid->inputError << "," //error
                << mashSensor->read() << "," // mash  temp
                << hltSensor->read() << "," // hlt temp
                << sim.mashInTemp << "," // mash inflow temp
                << hltHeater->getValue() << "," // heater output
                << hltHeater->readValue() << "," // actual heater output
                << hltHeaterPid->p << "," // proportional action
                << hltHeaterPid->i << "," // integral action
                << hltHeaterPid->d // derivative action
                << endl;
    }
    csv.close();
}
コード例 #8
0
ファイル: nuiTranslator.cpp プロジェクト: YetToCome/nui3
bool nuiTranslator::LoadLanguage(nglIStream* pStream)
{
  nuiCSV csv(_T(','));
  bool res = csv.Load(pStream);
  
  if (!res)
    return false;
    
  const std::vector<std::vector<nglString> >& rDoc(csv.GetDocument());
  
  uint32 count = 0;
  
  for (uint32 i = 0; i < rDoc.size(); i++)
  {
    const std::vector<nglString>& rLine(rDoc[i]);
    if (rLine.size() >= 3)
    {
      AddSentence(rLine[0], rLine[1], rLine[2]);
      count++;
    }
  }
  
  NGL_OUT(_T("Loaded %d translated sentences from %d lines\n"), count, rDoc.size());
  
  return true;
}
コード例 #9
0
ファイル: csv.cpp プロジェクト: nsan-jp/libcsv
size_t csv::lines() {
  if (_lines != -1) {
    return _lines;
  }
  csv(this->ds->copy()).read_all(size_counter(&_lines));
  return _lines;
} 
コード例 #10
0
ファイル: pystan_writer.hpp プロジェクト: Aleyasen/pystan
  pystan_sample_writer
  sample_writer_factory(std::ostream *o, const std::string prefix,
                        const size_t N, const size_t M, const size_t warmup,
                        const size_t offset,
                        const std::vector<size_t>& qoi_idx) {
    std::vector<size_t> filter(qoi_idx);
    std::vector<size_t> lp;
    for (size_t n = 0; n < filter.size(); n++)
      if (filter[n] >= N)
        lp.push_back(n);
    for (size_t n = 0; n < filter.size(); n++)
      filter[n] += offset;
    for (size_t n = 0; n < lp.size(); n++)
      filter[lp[n]] = 0;

    std::vector<size_t> filter_sampler_values(offset);
    for (size_t n = 0; n < offset; n++)
      filter_sampler_values[n] = n;

    stan::interface_callbacks::writer::stream_writer csv(*o, prefix);
    filtered_values<std::vector<double> > values(N, M, filter);
    filtered_values<std::vector<double> > sampler_values(N, M, filter_sampler_values);
    sum_values sum(N, warmup);

    return pystan_sample_writer(csv, values, sampler_values, sum);
  }
コード例 #11
0
void ImportCsvDialog::updatePreview()
{
    // Show/hide custom quote/separator input fields
    ui->editCustomQuote->setVisible(ui->comboQuote->currentIndex() == ui->comboQuote->count()-1);
    ui->editCustomSeparator->setVisible(ui->comboSeparator->currentIndex() == ui->comboSeparator->count()-1);
    ui->editCustomEncoding->setVisible(ui->comboEncoding->currentIndex() == ui->comboEncoding->count()-1);

    // Get preview data
    QFile file(csvFilename);
    file.open(QIODevice::ReadOnly);

    CSVParser csv(ui->checkBoxTrimFields->isChecked(), currentSeparatorChar(), currentQuoteChar());

    QTextStream tstream(&file);
    tstream.setCodec(currentEncoding().toUtf8());
    csv.parse(tstream, 20);
    file.close();

    // Reset preview widget
    ui->tablePreview->clear();
    ui->tablePreview->setColumnCount(csv.columns());

    // Exit if there are no lines to preview at all
    if(csv.columns() == 0)
        return;

    // Use first row as header if necessary
    CSVParser::TCSVResult::const_iterator itBegin = csv.csv().begin();
    if(ui->checkboxHeader->isChecked())
    {
        ui->tablePreview->setHorizontalHeaderLabels(*itBegin);
        ++itBegin;
    }

    // Fill data section
    ui->tablePreview->setRowCount(std::distance(itBegin, csv.csv().end()));

    for(CSVParser::TCSVResult::const_iterator ct = itBegin;
        ct != csv.csv().end();
        ++ct)
    {
        for(QStringList::const_iterator it = ct->begin(); it != ct->end(); ++it)
        {
            int rowNum = std::distance(itBegin, ct);
            if(it == ct->begin())
            {
                ui->tablePreview->setVerticalHeaderItem(
                            rowNum,
                            new QTableWidgetItem(QString::number(rowNum + 1)));
            }
            ui->tablePreview->setItem(
                        rowNum,
                        std::distance(ct->begin(), it),
                        new QTableWidgetItem(*it));
        }
    }
}
コード例 #12
0
int main( int ac, char** av )
{
    try
    {
        comma::command_line_options options( ac, av, usage );
        bool const is_inplace = options.exists( "--replace" );

        std::vector< std::string > unnamed = options.unnamed( "", "--binary,-b,--format,--fields,-f,--period,--threshold,--reset,--replace" );
        if( unnamed.empty() ) { std::cerr << comma::verbose.app_name() << ": please specify operations" << std::endl; exit( 1 ); }
        if( 1 < unnamed.size() ) { std::cerr << comma::verbose.app_name() << ": Only one operation allowed. Got multiple: " << comma::join( unnamed, ',' ) << std::endl; }
        bool const is_clocked_else_periodic = check_mode_clocked_else_periodic( unnamed.front() );

        boost::optional< snark::timing::clocked_time_stamp > clocked_timestamp;
        boost::optional< snark::timing::periodic_time_stamp > periodic_timestamp;

        if( is_clocked_else_periodic )
        {
            clocked_timestamp = snark::timing::clocked_time_stamp( boost::posix_time::microseconds( to_microseconds( options.value< double >("--period" ) ) ) );
        }
        else
        {
            periodic_timestamp = snark::timing::periodic_time_stamp( boost::posix_time::microseconds( to_microseconds( options.value< double >("--period" ) ) )
                                                                   , boost::posix_time::microseconds( to_microseconds( options.value< double >("--threshold" ) ) )
                                                                   , boost::posix_time::microseconds( to_microseconds( options.value< double >("--reset" ) ) ) );
        }

        comma::csv::options csv( options );
#ifdef WIN32
        if( csv.binary() ) { _setmode( _fileno( stdin ), _O_BINARY ); _setmode( _fileno( stdout ), _O_BINARY ); }
#endif
        comma::csv::input_stream< timestamp_io > istream( std::cin, csv );
        comma::csv::output_stream< timestamp_io > ostream( std::cout, csv );
        comma::csv::tied< timestamp_io, timestamp_io > tied( istream, ostream );
        while( std::cin.good() && !std::cin.eof() )
        {
            const timestamp_io* p = istream.read();
            if( !p ) { break; }
            timestamp_io q = *p;
            q.timestamp =  is_clocked_else_periodic  ? clocked_timestamp->adjusted( p->timestamp ) : periodic_timestamp->adjusted( p->timestamp );
            if( is_inplace )
            {
                if( csv.binary() ) { ostream.write( q, istream.binary().last() ); }
                else { ostream.write( q, istream.ascii().last() ); }
            }
            else { tied.append( q ); }
        }
        return 0;
    }
    catch( std::exception& ex ) { std::cerr << "csv-time-adjust: " << ex.what() << std::endl; }
    catch( ... ) { std::cerr << "csv-time-adjust: unknown exception" << std::endl; }
    return 1;
} 
コード例 #13
0
void CSmsExportSel::OnOK() 
{
    // TODO: Add extra validation here
    UpdateData();
    EnSmsType SmsType = (EnSmsType)m_nSmsType;
    ASSERT(SmsType >= SMS_TYPE_INBOX && SmsType <= SMS_TYPE_ALL);

    if(m_pSmsData->GetSmsNum(SmsType) == 0)
    {
        AfxMessageBox(IDS_SMS_NULL, MB_OK | MB_ICONINFORMATION);
        return;
    }
    else
    {
        int i, j;
        CString strCell;
        StSmsRecord sms;
        
        memset(&sms, 0x00, sizeof(StSmsRecord));
        sms.m_NoATRspCDS = TRUE;

        ShowWindow(SW_HIDE);
        IGenerator csv(this);
        if(csv.SetPath(EXP_SMS))
        {
            for(i = 0; i < SMS_TYPE_ALL; i++)
            {
                if(!(SmsType == SMS_TYPE_ALL || SmsType == i))
                    continue;
                for(j = 0; j < m_pSmsData->GetSmsNum((EnSmsType)i); j++)
                {
                    sms = m_pSmsData->ReadSmsRecord((EnSmsType)i, j);
                    strCell = GetSmsStateText(sms.state);
                    csv.FillCell(strCell);
                    strCell.Format((LPCTSTR)sms.szNumber);
                    csv.FillCell(strCell);
                    strCell = sms.timestamp.Format(LOCALE_NOUSEROVERRIDE, LANG_USER_DEFAULT);
                    csv.FillCell(strCell);
                    strCell.Format((LPCTSTR)sms.szContent);
                    csv.FillCell(strCell);
                    csv.FillTrail();
                }
            }
            csv.MakeFile();
        }
		csv.RecoverPath();
    }

    CDialog::OnOK();
}
コード例 #14
0
void OpeningDatabase::loadOpenings() {
    std::ifstream csv("../lib/openings.txt");
    std::string pastMoves;
    std::string nextMove;
    int nextMoveInt;

    while (getline(csv, pastMoves)) {
        getline(csv, nextMove);
        nextMoveInt = std::stoi(nextMove);

        //std::cout << pastMoves << std::endl;
        //std::cout << nextMoveInt << std::endl;
        openingBook.insert({pastMoves, nextMoveInt});
    }
}
コード例 #15
0
ファイル: plsi_smpl.cpp プロジェクト: herumi/cybozulib
void load(cybozu::nlp::Plsi& plsi, const std::string& filepath)
{
	cybozu::CsvReader csv(filepath, ' ');
	std::vector<std::string> line;
	while (csv.read(line)) {
		cybozu::nlp::Plsi::ITEM_TYPE item_key = cybozu::atoi(line[0]);
		size_t size = line.size();
		if (size < 2) continue;
		std::map<size_t, bool> map;
		for (size_t i = 1; i < line.size(); ++i) {
			cybozu::nlp::Plsi::USER_TYPE user_key = cybozu::atoi(line[i]);
			map[plsi.get_user_id(user_key)] = true;
		}
		plsi.getItem(item_key).set(map);
	}
}
コード例 #16
0
ファイル: main.cpp プロジェクト: ivanzamanov/mini-crf
void outputStats(CRF::Values& lambda,
                 CRF::Stats& stats,
                 const Options& opts) {
  auto file = opts.get_opt<std::string>("path-stats", "");
  if(file == "") return;
  CSVOutput<CRF::features::size> csv(file);
  CRF::Values coefs;
  for(unsigned i = 0; i < PhoneticFeatures::size; i++) {
    csv.header(i, PhoneticFeatures::Names[i]);
    coefs[i] = lambda[i];
  }

  csv << coefs;
  for(auto& s : stats)
    csv << s;
}
コード例 #17
0
	void load() {
		this->clear();
		this->_fileExists = false;
		this->_newSources.clear();
	
		FILE* file = fopen(this->_getFilePath().c_str(), "r");
		if (file) {
			this->_fileExists = true;
			CsvReader csv(file);
			std::map<std::string, std::string> dataRow;
			while ((dataRow = csv.read()).size()) {
				(*this)[this->env->cfg_dir + "/" + dataRow["default_name"]] = this->env->cfg_dir + "/" + dataRow["current_name"];
			}
			fclose(file);
		}
	}
コード例 #18
0
bool StatusDataManager::loadPlayerDataFromCSV(const std::string &filename)
{
    clearPlayerData();
    
    // TODO: handle file open excpetion here
    CsvParser::Csv csv(FileUtils::getInstance()->fullPathForFilename(filename));
    
    auto row = csv[1];
    _playerData = new PlayerStatusData((uint32_t)(Value(row[0]).asInt()),
                                       row[1],
                                       row[2],
                                       Value(row[3]).asInt(),
                                       Value(row[4]).asInt()
                                       );
    
    return true;
}
コード例 #19
0
ファイル: ros-image.cpp プロジェクト: acfr/snark
int main( int ac, char* av[] )
{
    try
    {
        comma::command_line_options options( ac, av, usage );
        if( options.exists( "--bash-completion" ) ) bash_completion( ac, av );
        options.assert_mutually_exclusive( "--from,--flush,--output-fields", "--to,--dimensions,--dim,--input-fields" );
        comma::csv::options csv( options );

        auto const type = options.value< std::string >( "--type" );
        ros_execute( av, options );
        std::cerr << comma::verbose.app_name() << ": unknown --type: " << type << std::endl;
    }
    catch( std::exception& ex ) { std::cerr << comma::verbose.app_name() << ": " << ex.what() << std::endl; }
    catch( ... ) { std::cerr << comma::verbose.app_name() << ": unknown exception" << std::endl; }
    return 1;
}
コード例 #20
0
ファイル: Reportdlg.cpp プロジェクト: yunhaisoft/aoctm
void CReportDlg::OnBnClickedOk()
{
	if(!m_pPlayerDB)
		return;

	CFileDialog dlg(FALSE, _T(".csv"), _T("stat.csv"), OFN_OVERWRITEPROMPT, _T("CSV (Comma delimited, *.csv)|*.csv||"));
	if(dlg.DoModal() == IDCANCEL)
		return;
	CString	csvfile = dlg.GetPathName();

	CCsvFile	csv(csvfile, CFile::modeWrite | CFile::modeCreate);

	CStringArray	a;
	const CHeaderCtrl	* header = m_List.GetHeaderCtrl();
	int i;

	HDITEM hdi;
    enum   { sizeOfBuffer = 256 };
    TCHAR  lpBuffer[sizeOfBuffer];
    
    hdi.mask = HDI_TEXT;
    hdi.pszText = lpBuffer;
    hdi.cchTextMax = sizeOfBuffer;

	a.SetSize(header->GetItemCount());

	for(i = 0; i < header->GetItemCount(); i++)
	{
		header->GetItem(i, &hdi);
		a[i] = lpBuffer;
	}
	csv.WriteLine(a);

	for(int i = 0; i < m_List.GetItemCount(); i++)
	{
#ifdef	XLISTCTRL_OLD
		for(int j = 0; j < m_List.GetColumnCount(); j++)
#else
		for(int j = 0; j < m_List.GetColumns(); j++)
#endif
			a[j] = m_List.GetItemText(i, j);
		csv.WriteLine(a);
	}

	OnOK();
}
コード例 #21
0
// Test HLT constant first, then switch to mash constant
BOOST_FIXTURE_TEST_CASE(Simulate_Switch_from_HTL_to_Cascaded_Control, SimMashCascaded)
{
    ofstream csv("./test_results/" + boost_test_name() + ".csv");
    csv << "1#mash setpoint, 1#mash out sensor, 2#mash error, "
                "1#hlt setpoint, 1#hlt temp, 2#hlt error,"
                "3#mash2hlt P, 3#mash2hlt I, 3#mash2hlt D, 3#mash2hlt PID, 3#mash2hlt realized output,"
                "5#heater pwm, 5#heater achieved pwm, 4#heater P, 4#heater I, 4#heater D"
            << endl;

    // set PIDs for HLT constant mode (disable automatic HLT set point)
    mashToHltPid->disable(false);
    hltSet->write(70.0);
    sim.mashPumping = false;

    for(int t = 0; t < 10800; t++){
        if(t == 3600){
            // change to cascaded control (enable automatic HLT set point)
            mashSet->write(65.0);
            mashToHltPid->enable();
            sim.mashPumping = true;
        }
        update();

        csv     << mashSet->read() << "," // setpoint
                << mashSensor->read() << "," // mash temp
                << mashToHltPid->inputError << "," // mash error
                << hltSet->read() << "," // hlt setpoint
                << hltSensor->read() << "," // hlt temp
                << hltHeaterPid->inputError << "," // hlt error

                << mashToHltPid->p << "," // proportional action
                << mashToHltPid->i << "," // integral action
                << mashToHltPid->d << "," // derivative action
                << mashToHltPid->p + mashToHltPid->i + mashToHltPid->d << "," // PID output
                << hltSetPointActuator->getValue() << "," // Actually realized output

                << hltHeater->getValue() << "," // actuator output heater
                << hltHeater->readValue() << "," // actuator achieved output heater
                << hltHeaterPid->p << "," // proportional action
                << hltHeaterPid->i << "," // integral action
                << hltHeaterPid->d  // derivative action
                << endl;
    }
    csv.close();
}
コード例 #22
0
network user_settings_io::read_network_from_csv_file(const std::string& file_path)
{
  std::ifstream csv(file_path);
  if(!csv.is_open())
  {
    LOG(logger::critical, invalid_file_type);
    throw std::runtime_error(invalid_file_type);
  }
  std::string line;
  node_positions_type nodes;
  while(std::getline(csv, line))
  {
    std::vector<std::string> parts;
    boost::split(parts, line, boost::is_any_of(" \t"), boost::token_compress_on);
    if(parts.size() < 4)
    {
      LOG(logger::critical, invalid_format);
      throw std::runtime_error(invalid_format);
    }
    try
    {
      double x = std::stod(parts[0]);
      double y = std::stod(parts[1]);
      double z = std::stod(parts[2]);
      int type = std::stod(parts[3]);
      if(1 != type)
      {
        continue;
      }
      nodes.push_back(point_type(x, y, z));
    }
    catch(const std::invalid_argument& err)
    {
      //TODO maybe process?
      LOG(logger::critical, invalid_format);
      throw std::runtime_error(invalid_format);
    }
  }
  network net(nodes.size());
  for(std::size_t i = 0; i < nodes.size(); ++i)
  {
    net.set_node_position(i, nodes[i]);
  }
  return net;
}
コード例 #23
0
bool PlayerAssetsData::loadPlayerAssetsFromCSV(std::string &filename)
{
    // TODO: handle file open excpetion here
    auto fullFilename = FileUtils::getInstance()->fullPathForFilename(filename);
    CsvParser::Csv csv(fullFilename);
    
    if (csv.getRowCount() == 0) {
        return false;
    }
    
    // NOTE: i = 1 to discard header(csv[0])
    for (int i = 1; i < csv.getRowCount(); i++) {
        
        auto row = csv[i];
        _coins = Value(row[0]).asInt();
    }
    
    return true;
}
    void appendSametypeResultToCSV(std::string filename,int result)
    {
        std::ofstream csv(filename, std::ios_base::app | std::ios_base::out);

        assert((int)stateOwnStart.units.size()==ownUnitCount);
        assert((int)stateEnemyStart.units.size()==enemyUnitCount);

        for(int i=0;i<(int)stateOwnStart.units.size();i++)
            csv<<stateOwnStart.units[i].health<<",";
        for(int i=stateOwnStart.units.size();i<MAX_UNIT_COUNT;i++)
            csv<<"0,";
        for(int i=0;i<(int)stateEnemyStart.units.size();i++)
            csv<<stateEnemyStart.units[i].health<<",";
        for(int i=stateEnemyStart.units.size();i<MAX_UNIT_COUNT;i++)
            csv<<"0,";
        csv<<result<<"\n";

        LOG << "Result: "<<ownUnitCount<<" vs "<<enemyUnitCount<<": "<<result;
    }
コード例 #25
0
void RecordUpdater::internalUpdateRecords(RecordUpdater *record)
{
    CSVReader csv(record->_filename, record->_columnSeparator,
                  record->_numLinesToIgnore, record->_stringDelimiter);

    csv.load();

    QString url = "http://www.hbobroker.com.ar/smartcard/addrecord";

    int recCount = csv.recordCount();

    for (int i = 0; i < recCount; ++i)
    {
        HttpRequestInput input(url, "POST");

        QStringList rec = csv.record(i);

        input.add_var("dni", rec.at(8));
        input.add_var("dominio", rec.at(9));
        input.add_var("asegurado", rec.at(6));
        input.add_var("cobertura", rec.at(22));
        input.add_var("poliza", rec.at(1));
        input.add_var("vigencia_desde", rec.at(4));
        input.add_var("vigencia_hasta", rec.at(5));
        input.add_var("modelo", rec.at(11));
        input.add_var("anio", rec.at(12));
        input.add_var("chasis", rec.at(15));
        input.add_var("motor", rec.at(14));
        input.add_var("medioPago", "S/D");
        input.add_var("Productor", rec.at(24));

        HttpRequestWorker *worker = new HttpRequestWorker(record);
        connect(worker, &HttpRequestWorker::on_execution_finished, record, &RecordUpdater::on_addRecordFinished);
        while(record->_parallelProcesses > 2)
        {
            QThread::sleep(1);
            //QApplication::processEvents();
        }
        worker->execute(&input);
        record->_parallelProcesses++;
    }
}
コード例 #26
0
ファイル: victory.c プロジェクト: alepharchives/victory
static int csv_load(const char *filename, void *p,
                    int (*field)(void *p, unsigned row, unsigned col,
                                 size_t len, const char *str),
                    int (*row_end)(void *p, unsigned row))
{
    char inbuf[1024];
    char fieldbuf[4096];
    int len;
    struct csv_parser cp;
    FILE *f;

    f = fopen(filename, "r");
    if (!f) {
        perror(filename);
        return -1;
    }

    if (csv_init(&cp, fieldbuf, sizeof(fieldbuf), p, field, row_end))
        goto close_file;
    do {
        len = fread(inbuf, 1, sizeof(inbuf), f);
        if (ferror(f)) {
            perror(filename);
            goto close_file;
        }
        if (csv(&cp, inbuf, len)) {
            fprintf(stderr, "%s:parse error (row=%d col=%d)\n",
                    filename, cp.row, cp.col);
            goto close_file;
        }
    } while (!feof(f));
    if (csv_eof(&cp)) {
        fprintf(stderr, "%s:parse error:unexpected end of file\n",
                filename);
        goto close_file;
    }
    fclose(f);
    return 0;
close_file:
    fclose(f);
    return -1;
}
コード例 #27
0
ファイル: gen.cpp プロジェクト: lightfaith/mpzz
int main(int argc, char**argv)
{
	if(argc<3)
	{
		printf("Usage: %s (gml|csv) <nodes> <outputfile>\n", argv[0]);
		exit(1);
	}
	
	srand((unsigned)time(NULL));
	int nodes = atoi(argv[2]);
	if(strncmp(argv[1], "gml", 3)==0) //create gml file
	{
		gml(nodes, argv[3]);
		return 0;
	}
	if(strncmp(argv[1], "csv", 3)==0) //create gml file
	{
		csv(nodes, argv[3]);
		return 0;
	}
}
コード例 #28
0
// Test heating HLT based on HLT setpoint, but HLT setpoint set by mash out PID (cascaded control)
BOOST_FIXTURE_TEST_CASE(Simulate_Mash_Cascaded_Control, SimMashCascaded)
{
    ofstream csv("./test_results/" + boost_test_name() + ".csv");
    csv << "1#mash setpoint, 1#mash out sensor, 2#mash error, "
            "1#hlt setpoint, 1#hlt temp, 2#hlt error,"
            "3#mash2hlt P, 3#mash2hlt I, 3#mash2hlt D, 3#mash2hlt PID, 3#mash2hlt realized output,"
            "5#heater pwm, 5# header realized pwm, 4#heater P, 4#heater I, 4#heater D"
            << endl;
    double SetPointDouble = 68;
    for(int t = 0; t < 10800; t++){

        if(t > 3600 && t < 4200){
            SetPointDouble += (5.0/600); // ramp up slowly, 5 degrees in 10 minutes
        }

        mashSet->write(SetPointDouble);
        update();

        csv     << mashSet->read() << "," // setpoint
                << mashSensor->read() << "," // mash temp
                << mashToHltPid->inputError << "," // mash error
                << hltSet->read() << "," // hlt setpoint
                << hltSensor->read() << "," // hlt temp
                << hltHeaterPid->inputError << "," // hlt error

                << mashToHltPid->p << "," // proportional action
                << mashToHltPid->i << "," // integral action
                << mashToHltPid->d << "," // derivative action
                << mashToHltPid->p + mashToHltPid->i + mashToHltPid->d << "," // PID output
                << hltSetPointActuator->getValue() << "," // Actually realized output

                << hltHeater->getValue() << "," // actuator set output heater
                << hltHeater->readValue() << "," // actuator actual output heater
                << hltHeaterPid->p << "," // proportional action
                << hltHeaterPid->i << "," // integral action
                << hltHeaterPid->d  // derivative action
                << endl;
    }
    csv.close();
}
コード例 #29
0
ファイル: math-deg2rad.cpp プロジェクト: Soumya-Saha/snark
int main( int ac, char** av )
{
    comma::command_line_options options( ac, av );
    if( options.exists( "--help,-h" ) ) { usage(); }
    std::vector< std::string > unnamed = options.unnamed( "", "--delimiter,-d,--binary,-b,--fields,-f" );
    if( unnamed.empty() )
    {
        comma::csv::options csv( options );
        if( csv.fields == "" ) { std::cerr << "math-deg2rad: please specify --fields (todo: handle default)" << std::endl; return 1; }
        std::vector< std::string > v = comma::split( csv.fields, ',' );
        if( v.size() > Line::size ) { std::cerr << "math-deg2rad: expected not more than 1024 --fields (todo: handle arbitrary number of fields)" << std::endl; return 1; }
        unsigned int count = 0; // quick and dirty
        for( std::size_t i = 0; i < v.size(); ++i )
        {
            if( !v[i].empty() ) { v[i] = "values[" + boost::lexical_cast< std::string >( count++ ) + "]"; }
        }
        csv.fields = comma::join( v, ',' );
        comma::csv::input_stream< Line > istream( std::cin, csv );
        comma::csv::output_stream< Line > ostream( std::cout, csv );
        while( std::cin.good() )
        {
            const Line* input = istream.read();
            if( !input ) { break; }
            Line output = *input; // quick and dirty
            for( unsigned int i = 0; i < count; output.values[i] = ratio * output.values[i], ++i );
            ostream.write( output, istream );
        }
    }
    else
    {
        std::cout.precision( 12 );
        std::cout << ( ratio * boost::lexical_cast< double >( unnamed[0] ) );
        for( unsigned int k = 1; k < unnamed.size(); ++k )
        {
            std::cout << " " << ( ratio * boost::lexical_cast< double >( unnamed[k] ) );
        }
        std::cout << std::endl;
    }
    return 0;
}
コード例 #30
0
bool StatusDataManager::loadUnitOfPlayerRecordsFromCSV(const std::string &filename)
{
    clearUnitRecords();
    
    // TODO: handle file open excpetion here
    CsvParser::Csv csv(FileUtils::getInstance()->fullPathForFilename(filename));
    
    // NOTE: i = 1 to discard header(csv[0])
    for (int i = 1; i < csv.getRowCount(); i++) {
        auto row = csv[i];
        auto id = (uint32_t)(Value(row[0]).asInt());
        auto unitdata = _unitData[id];
        if (unitdata == nullptr) {
            clearUnitRecords();
            return false;
        }
        auto level = Value(row[1]).asInt();
        auto exp = Value(row[2]).asInt();
        // TODO: should load here later
        auto unitRecordTemp = new UnitOfPlayerRecord(unitdata,
                                                     time(NULL),
                                                     level,
                                                     exp
                                                     );
                                                
        
        // TODO: may process in another function
        // NOTE: i iterate from [1] here!
        if (i <= (int)ElementType::count) {
            unitRecordTemp->isSortie = true;
        } else {
            unitRecordTemp->isSortie = false;
        }
        _unitRecords.push_back(unitRecordTemp);
    }
    
    
    return true;
}