std::string Maker::GetFileTime(const std::string &goal, const std::string &preferredPath, Time &timeval) { std::string rv; if (goal.find_first_of(CmdFiles::DIR_SEP) != std::string::npos) { std::fstream fil(goal.c_str(), std::ios::in); if (fil != NULL) { fil.close(); timeval = OS::GetFileTime(goal); } } else { std::string vpath = preferredPath + std::string(" .\\ ") + Eval::GetVPATH(goal); std::string sep = std::string(" ") + CmdFiles::PATH_SEP; while (vpath.size()) { std::string cur = Eval::ExtractFirst(vpath, sep); if (cur[cur.size() -1] != CmdFiles::DIR_SEP[0]) cur += CmdFiles::DIR_SEP; std::string name ; if (goal[0] != CmdFiles::DIR_SEP[0] && goal[1] != ':') name = cur + goal; else name = goal; if (cur != ".\\") filePaths[goal] = cur; // tentatively enter this as the goal path // this will collide if there are multiple paths and no file exists // and choose the last one std::fstream fil(name.c_str(), std::ios::in); if (fil != NULL) { fil.close(); rv = cur; // return value is the path, with a slash on the end timeval = OS::GetFileTime(name); filePaths[goal] = cur; break; } } } if (ScanList(newFiles, goal) || ScanList(newFiles, rv + goal)) { timeval = OS::GetCurrentTime(); } else if (ScanList(oldFiles, goal) || ScanList(oldFiles, rv + goal)) { timeval.Clear(); } return rv; }
/**************************************** function: writeToFile of WritingJSON Inputs: N/A Outputs: N/A Description: read result vector and convert them into JSON and write them into txt file. ****************************************/ void WritingJSON::writeToFile(void){ vector<result*>::iterator it; //iterator of vector of pointers of result vector<listing*>::iterator il; //iterator for listing vector in each result object vector<listing*> list; //temp var to store listing of current result object in the loop string title; string manufacturer; string currency; string price; Json::FastWriter fast_writer; //FastWriter function of json //cout<<"result set size is "<<res.size()<<endl; std::ofstream fil("result.txt", std::ios::out); //generate result.txt file //iterate the whole vector of pointers of result for(it = res.begin(); it != res.end(); it++){ Json::Value value; //for each record of result, generate a new json data and according to the result object Json::Value arrayobj; value["product_name"] = (*it)->getPDname(); list = (*it)->getList(); //cout<<(*it)->getPDname()<<endl; for(il = list.begin(); il !=list.end(); il++){ //this loop is used to read the related listing of each result object and put them in array of json. Json::Value item; item["title"] = (*il)->getTit(); item["manufacturer"] = (*il)->getManuf(); item["currency"] = (*il)->getCur(); item["price"] = (*il)->getPrice(); arrayobj.append(item); } value["listing"] = arrayobj; fil<<reOrder(fast_writer.write(value))<<endl; //convert json data to string and write into result.text } fil.close(); }
/**************************************** function: ProductDecode of ReadingJSON Inputs: N/A Outputs: a vector which stores all addresses of product objects. Description: open product file according to the product file path, and read each line of JSON to convert it into a product object. After this function, all product data is stored in vector and easy to headle with. ****************************************/ vector<product*> ReadingJSON::ProductDecode(void){ //cout<<"123"<<endl; Json::Reader reader; std::vector<product*> opt; std::ifstream fil(product_path, std::ios::in); char line[10240]={0}; std::string x = ""; while(fil.getline(line, sizeof(line))){ std::stringstream st; st<<line; x = st.str(); Json::Value value; if (reader.parse(x, value)){ product *p = new product(); (*p).setPDname(value["product_name"].asString()); (*p).setManuf(value["manufacturer"].asString()); (*p).setFamily(value["family"].asString()); (*p).setModel(value["model"].asString()); (*p).setAnn(value["announced-date"].asString()); opt.push_back(p); } } fil.close(); return opt; }
/**************************************** function: ListingDecode of ReadingJSON Inputs: N/A Outputs: a vector which stores all addresses of listing objects. Description: open listing file according to the listing file path, and read each line of JSON to convert it into a listing object. After this function, all listing data is stored in vector and easy to headle with. ****************************************/ vector<listing*> ReadingJSON::ListingDecode(void){ Json::Reader reader; Json::Value value; vector<listing*> opt; std::ifstream fil(list_path, std::ios::in); char line[10240]={0}; std::string x = ""; while(fil.getline(line, sizeof(line))){ std::stringstream st; st<<line; x = st.str(); //cout<<x<<endl; if (reader.parse(x, value)){ listing *l = new listing(); (*l).setTit(value["title"].asString()); (*l).setManuf(value["manufacturer"].asString()); (*l).setCur(value["currency"].asString()); (*l).setPrice(value["price"].asString()); opt.push_back(l); } } fil.close(); return opt; }
int main(int argc, char** argv) { // lowpass response // cf = sr/10 // trans bw = sr/10 float max = 1.f; float min = 0.f; float cf = 0.1f; float tbw = 0.1f; // magnitude response curve float points[3]= {max,min,min}; float lens[3]= {cf,tbw,1-(cf+tbw)}; // using Hamming window // filter order = 3.33*sr/tbw int order = 333; HammingTable window(order, 0.54f); ImpulseTable imp(order,3, 1.f, points, lens, 0.f,&window); // test signal wavetable HarmTable t1(1024, 50, SAW); SndWave output("test.wav", OVERWRITE); /* output */ Oscili oscil(&t1, 100.f, 32767.f); /* test signal */ Convol fil(&imp, &oscil, 16.f); /* filter */ int dur = 5; for(int i=0; i<dur*(DEF_SR/DEF_VECSIZE); i++) { oscil.DoProcess(); fil.DoProcess(); fil >> output; } return 0; }
int File_inport::inport(Glib::ustring file) { //convert adress to file name int poz = file.rfind("/"); Glib::ustring subor = Glib::ustring(file.c_str()+poz); File_load fil(file); if(fil.getType().compare(CUSTOMVIDEO)==0){ return 1; } std::fstream vys; vys.open((confDir+subor).c_str(), std::fstream::in); if(vys.good()){ // std::cout<<"exist"<<std::endl; return -1; } Glib::ustring command = "cp -n \"" + file + "\" " + confDir; if(system(command.c_str())!=0){ return -2; } vys.close(); vys.open(confFile.c_str(), std::fstream::out | std::fstream::app); vys<<confDir+subor<<std::endl; vys.close(); return 0; }
GdbServer::GdbServer(QObject *parent, QStLink * st, bool notverify, int portnumber, QByteArray & file) : QObject(parent), stlink(st), server(new QTcpServer(this)), port(portnumber), NotVerify(notverify), VeriFile(file) { Q_ASSERT(stlink); //VeriFile = "/home/kubanec/workspace/ARMCM4-STM32F407-DISCOVERY/build/test.bin"; new Kelnet(*stlink,parent); connect(server,SIGNAL(newConnection()),this,SLOT(newConnection())); connect(stlink,SIGNAL(CoreHalted(quint32)),this,SLOT(CoreHalted(quint32))); bool ok = server->listen(QHostAddress::Any,port); printMCUInfo(); QFile fil(VeriFile); if (fil.exists()) { qDebug() << QString("Binary file: " + fil.fileName()); //VeriFile.append(fil.absolutePath()); } if (ok) { INFO(QString("Listening on port %1").arg(port)); qDebug() << QString("Listening on port %1").arg(port); } else { ERR("Cannot open listening port"); } connect(stlink,SIGNAL(Erasing(int)),this,SLOT(Erasing(int))); connect(stlink,SIGNAL(Flashing(int)),this,SLOT(Flashing(int))); connect(stlink,SIGNAL(Verifing(int)),this,SLOT(Verify(int))); threaed.insert(THD_MAIN,QStLink::Thread); threaed.insert(THD_HAN,QStLink::Handler); threaed.insert(0,QStLink::Unknown); QTimer * timer = new QTimer; timer->start(1000); connect(timer,SIGNAL(timeout()),this,SLOT(timeout())); soc = NULL; qsThreadInfo = 0; switched = false; std::cout << std::endl << std::flush; }
QString readTemplate(const QString& template_file_name){ // ://templates/numero.js QFile fil(template_file_name); if (!fil.open(QIODevice::ReadOnly | QIODevice::Text)) return ""; QTextStream file_utf8(&fil); return file_utf8.readAll(); }
wxTreeItemId DirectoryTree::AddChild(const wxTreeItemId& tidParent, const wxString& sPath) { DirectoryTreeItem * dti = new DirectoryTreeItem(sPath); wxTreeItemId tid; if(sPath == FILE_SYSTEM_ROOT) { // TBI: ASSERT tree is empty tid = AddRoot(FILE_SYSTEM_ROOT, 0, 1, dti); } else { if(!tidParent.IsOk()) { wxLogDebug(wxT("DirectoryTree::AddChild(): invalid parent wxTreeItemId %u"), (int) tidParent); return wxTreeItemId(); } #ifdef __WXMSW__ // Treat drives differently wxString sDirectory; if(sPath.Length() == 3) sDirectory = sPath; else { wxFileName fil(sPath); sDirectory = fil.GetFullName(); } #else wxFileName fil(sPath); wxString sDirectory = fil.GetFullName(); #endif // def __WXMSW__ tid = AppendItem(tidParent, sDirectory, 0, 1, dti); } // Show the '+' button SetItemHasChildren(tid, true); return tid; }
int main(int, char *argv[]) { unsigned char *tab=new unsigned char[24]; for(int i=0; i<3*8; i+=3) { tab[i]=tab[i+1]=tab[i+2]=((char)~0)<<(i/3); } int w=3, h=8; fil(tab, w, h, 3); /** *in gdb ./main: (gdb) disass main shows that arguments in 64-bit goes to registers 0x0000000000400934 <+93>: mov -0x38(%rbp),%edx 0x0000000000400937 <+96>: mov -0x34(%rbp),%ebx 0x000000000040093a <+99>: lea -0x30(%rbp),%rax 0x000000000040093e <+103>: mov $0x3,%ecx 0x0000000000400943 <+108>: mov %ebx,%esi 0x0000000000400945 <+110>: mov %rax,%rdi 0x0000000000400948 <+113>: callq 0x4008c4 <_Z3filPhiii> (gdb) disass fil shows that even simple function stores those arguments just after being called on stack Dump of assembler code for function _Z3filPhiii: 0x00000000004008c4 <+0>: push %rbp 0x00000000004008c5 <+1>: mov %rsp,%rbp 0x00000000004008c8 <+4>: mov %rdi,-0x8(%rbp) 0x00000000004008cc <+8>: mov %esi,-0xc(%rbp) 0x00000000004008cf <+11>: mov %edx,-0x10(%rbp) 0x00000000004008d2 <+14>: mov %ecx,-0x14(%rbp) 0x00000000004008d5 <+17>: leaveq 0x00000000004008d6 <+18>: retq :next steps examine stack: (gdb) x/w $rbp-0x8 0x7fffffffea08: 4294961728 (gdb) x/w $rbp-0xc 0x7fffffffea04: 3 (gdb) x/w $rbp-0x10 0x7fffffffea00: 4 (gdb) x/w $rbp-0x14 0x7fffffffe9fc: 3 function arguments are on stack and in registers %rdi(buf), %esi(w), %edx(h), %ecx(bpp) it is useful for writing asm 64-bit insertions to 64-bit c++ **/ print(tab, w*h); filter(tab, w, h, 3); print(tab, w*h); return 0; }
void WidgetToolBar::SaveDataToFile() { QString cesta = QFileInfo( QCoreApplication::applicationFilePath() ).absolutePath(); cesta += "/jmeno.txt"; QFile fil(cesta); if (!fil.open(QFile::WriteOnly)) return; fil.write(ui->editName->text().toUtf8() + '\n'); fil.write(ui->spinCislo->text().toUtf8()+ '\n'); fil.write(ui->spinDovolena->text().toUtf8()+ '\n'); fil.close(); }
/** * Open image file and parse it by MD */ void MainWindow::on_pbOpenImageFile_clicked() { quint8 data; int currPosX, currPosY; doperations.init(); QString tmp = QDir::currentPath(); QFile fil("imgpath.txt"); if( fil.open( QIODevice::ReadOnly ) ) { QDataStream stream(&fil); stream.setVersion (QDataStream::Qt_4_2) ; stream >> tmp; fil.close(); }
Kart::Kart( QString url ) { kou = 0; QFile fil( url ); if ( fil.open( QIODevice::ReadOnly | QIODevice::Text ) ) { QTextStream in( &fil ); // Putter pekere til klosser inn i en 2D QList, som forestiller et 2D kart. for ( int i = 0; !in.atEnd(); i++ ) { QString line = fil.readLine(); // # er kommentarfelt, og $ er ekstrainformasjon om kartet. De hopper vi over nå. if ( line.at( 0 ) != '#' && line.at( 0 ) != '$' ) { QList<QPixmap*> tmpliste; for ( int j = 0; j < line.size(); j++ ) { tmpliste.append( finnUrl( line.at( j ).toAscii(), j, bildekart.size() ) ); } bildekart.append( tmpliste ); } else if ( line.at( 0 ) == '$' ) { if ( line.startsWith( "$bakgrunn" ) ) { QString bg = line.remove( "$bakgrunn=" ); bg = bg.remove( "\n" ); bakgrunn.load( bg ); } else if ( line.startsWith( "$tid" ) ) { QString bg = line.remove( "$tid=" ); bg = bg.remove( "\n" ); tid = bg.toInt(); } } } } fil.close(); }
bool Entity::executeComment(){ QFile fil(fileInfo.absoluteFilePath()); if (!fil.open(QIODevice::ReadOnly | QIODevice::Text)) return -1; QTextStream file_utf8(&fil); file_utf8.setAutoDetectUnicode(true); Comment dummyStartTag(DUMMY,-1,-1); Comment dummyEndTag(DUMMY,fil.size(),fil.size()); qDebug() << fil.size(); QBuffer mem; mem.open(QBuffer::WriteOnly|QBuffer::Text); handleTag(&dummyStartTag, &dummyEndTag, file_utf8,mem ); mem.close(); check(); QFileInfo outputfileInfo(outputSite,fileInfo.baseName()+".html"); QFile output(outputfileInfo.absoluteFilePath()); if (!output.open(QIODevice::WriteOnly | QIODevice::Text | QIODevice::Truncate)) return -1; outputStringList(output,static_header_1); if (!embedded_styles.isEmpty()){ output.write(QString("<style>").toUtf8()); outputStringList(output,embedded_styles); output.write(QString("</style>").toUtf8()); } outputStringList(output,static_header_2); output.write(mem.buffer()); generatePageFooter(output); output.close(); }
ExperimentModel::ExperimentModel(QDir dir,QObject *parent) : QAbstractListModel(parent), dir(dir) { qDebug() << dir; QFileInfoList folders = dir.entryInfoList(QDir::Dirs | QDir::NoDotAndDotDot); for (int i = 0; i < folders.size(); ++i) { qDebug() << folders[i].absoluteFilePath(); QFileInfoList fil(QDir(folders[i].absoluteFilePath()).entryInfoList( QStringList("*.ebs2"))); if (fil.size() > 0) { qDebug() << fil[0].absoluteFilePath(); this->insertRow(this->rowCount(), *new Experiment(QFileInfo(fil[0].absoluteFilePath()), this)); } } qDebug() << "ExperimentModel construction"; }
void DocumentsDir::generateTemplateDir() { QFileInfoList fil( QDir(":/templates/").entryInfoList() ); QDir templatesDir( getTemplatesDirName() ); if( !templatesDir.mkpath( "." ) ) { return; } foreach( const QFileInfo &fi, fil ) { QString srcFile( fi.absoluteFilePath() ); QString destFile( templatesDir.absoluteFilePath( fi.fileName() ) ); if( QFile::copy( srcFile, destFile ) ) { QFile::setPermissions( destFile, QFile::permissions( destFile ) | QFile::WriteUser ); } }
int main(int argc, char *argv[]) { if (argc < 2) return -1; try { File fil("httpget.out", "w"); StdoutLog log; SocketHandler h(&log); HttpGetSocket sock(h, argv[1], "empty.html"); sock.SetTrafficMonitor(&fil); h.Add(&sock); while (h.GetCount()) h.Select(); } catch (const Exception& e) { std::cerr << e.ToString() << std::endl; } }
void Entity::extractCommentPosition(){ QFile fil(fileInfo.absoluteFilePath()); if (!fil.open(QIODevice::ReadOnly | QIODevice::Text)) return ; QTextStream file_utf8(&fil); file_utf8.setAutoDetectUnicode(true); QChar c1='\0',c2='\0',c3='\0',c4='\0'; bool inComment=false; QByteArray qb; qint64 commentStart; qint64 commentEnd; while (!file_utf8.atEnd()) { c4=c3; c3=c2; c2=c1; file_utf8 >> c1; if (!inComment && (c4=='<')&& (c3=='!')&&(c2=='-')&&(c1=='-')){ inComment=true; qb.clear(); qb.append("<!--"); commentStart=file_utf8.pos()-4; } else if (inComment && (c3=='-')&& (c2=='-')&&(c1=='>')){ inComment=false; commentEnd=file_utf8.pos()-1; qb.append(">"); createComment(qb,commentStart,commentEnd); } else { if (inComment){ qb.append(c1); } } } qDebug() << file_utf8.pos(); }
void WidgetToolBar::LoadDataFromFile() { QString cesta = QFileInfo( QCoreApplication::applicationFilePath() ).absolutePath(); cesta += "/jmeno.txt"; QFile fil(cesta); if (!fil.open(QFile::ReadOnly)) return; QByteArray buffer; buffer = fil.readLine().trimmed(); ui->editName->setText(QString::fromUtf8(buffer)); buffer = fil.readLine().trimmed(); bool ok; ui->spinCislo->setValue(buffer.toInt(&ok)); Q_ASSERT(ok); buffer = fil.readLine().trimmed(); ui->spinDovolena->setValue(buffer.toInt(&ok)); Q_ASSERT(ok); fil.close(); }
void Window::readWriteScore() { QFile fil("score.dat"); fil.open(QIODevice::ReadOnly); QDataStream in(&fil); str; in >> str; QFile files("score.dat"); files.open(QIODevice::WriteOnly); QDataStream out(&files); nome = edit->text(); scoreTxt = QString::number(scr); txtSave = str + "\n" + nome + " - " + scoreTxt; out << QString(txtSave); qDebug() << "Score"; qDebug() << txtSave; newWindow->close(); chamaOpenScore(); }
void SaveISISNexus::selog() { // find log files with names <RawFilenameWithoutExt>_LogName.txt and save them // in potentialLogFiles std::vector<std::string> potentialLogFiles; Poco::File l_path(inputFilename); std::string l_filenamePart = Poco::Path(l_path.path()).getFileName(); std::string::size_type i = l_filenamePart.find_last_of('.'); if (i != std::string::npos) // remove the file extension { l_filenamePart.erase(i); } std::string base_name = l_filenamePart; boost::regex regex(l_filenamePart + "_.*\\.txt", boost::regex_constants::icase); Poco::DirectoryIterator end_iter; for (Poco::DirectoryIterator dir_itr(Poco::Path(inputFilename).parent()); dir_itr != end_iter; ++dir_itr) { if (!Poco::File(dir_itr->path()).isFile()) continue; l_filenamePart = Poco::Path(dir_itr->path()).getFileName(); if (boost::regex_match(l_filenamePart, regex)) { potentialLogFiles.push_back(dir_itr->path()); } } Progress prog(this, 0.5, 1, potentialLogFiles.size()); NXmakegroup(handle, "selog", "IXselog"); NXopengroup(handle, "selog", "IXselog"); // create a log for each of the found log files std::size_t nBase = base_name.size() + 1; for (auto &potentialLogFile : potentialLogFiles) { std::string logName = Poco::Path(potentialLogFile).getFileName(); logName.erase(0, nBase); logName.erase(logName.size() - 4); if (logName.size() > 3) { std::string icp = logName.substr(0, 3); std::transform(icp.begin(), icp.end(), icp.begin(), toupper); if (icp == "ICP") continue; } std::ifstream fil(potentialLogFile.c_str()); if (!fil) { g_log.warning("Cannot open log file " + potentialLogFile); continue; } start_time_str[10] = ' '; // make it compatible with boost::posix_time::ptime boost::posix_time::ptime start_time( boost::posix_time::time_from_string(start_time_str)); start_time_str[10] = 'T'; // revert std::vector<float> time_vec; std::vector<std::string> str_vec; std::vector<float> flt_vec; std::string line; bool isNotNumeric = false; while (std::getline(fil, line)) { if (line.empty()) continue; std::string date_time_str = line.substr(0, 19); date_time_str[10] = ' '; boost::posix_time::ptime time( boost::posix_time::time_from_string(date_time_str)); boost::posix_time::time_duration dt = time - start_time; time_vec.push_back(float(dt.total_seconds())); std::istringstream istr(line.substr(20)); // check if the data are numeric then save them in flt_vec if (!isNotNumeric) { float flt; istr >> flt; if (istr.bad() || istr.fail()) { isNotNumeric = true; } else { flt_vec.push_back(flt); } } str_vec.push_back(istr.str()); } fil.close(); NXmakegroup(handle, &logName[0], "IXseblock"); NXopengroup(handle, &logName[0], "IXseblock"); { saveString("vi_name", " "); saveString("set_control", " "); saveString("read_control", " "); float tmp = 0.0; saveFloatOpen("setpoint", &tmp, 1); putAttr("units", "mV"); close(); } NXmakegroup(handle, "value_log", "NXlog"); NXopengroup(handle, "value_log", "NXlog"); saveFloatOpen("time", &time_vec[0], static_cast<int>(time_vec.size())); putAttr("start", start_time_str); putAttr("units", "seconds"); close(); if (flt_vec.size() == str_vec.size()) { saveFloatOpen("value", &flt_vec[0], static_cast<int>(flt_vec.size())); } else { saveStringVectorOpen("value", str_vec); } putAttr("units", " "); close(); saveString("name", " "); NXclosegroup(handle); // value_log NXclosegroup(handle); // logName prog.report(); }
/** * Create and write run logs form \<RawFilename\>_ICPstatus.txt log file */ void SaveISISNexus::runlog() { progress(0); std::string ICPstatus_filename = inputFilename; std::string ICPevent_filename; std::string::size_type i = ICPstatus_filename.find_last_of('.'); if (i != std::string::npos) // remove the file extension { ICPstatus_filename.erase(i); } ICPevent_filename = ICPstatus_filename + "_ICPevent.txt"; ICPstatus_filename += "_ICPstatus.txt"; std::ifstream fil(ICPstatus_filename.c_str()); if (!fil) { g_log.warning("Cannot find the ICPstatus file. Skipping runlog"); progress(0.5); return; } std::vector<float> time_vec; std::vector<int> period_vec; std::vector<int> is_running_vec; std::vector<int> is_waiting_vec; std::vector<int> good_frames_vec; std::vector<int> raw_frames_vec; std::vector<int> monitor_sum_1_vec; std::vector<int> total_counts_vec; std::vector<int> run_status_vec; std::vector<float> proton_charge_vec; std::vector<float> proton_charge_raw_vec; std::vector<float> dae_beam_current_vec; std::vector<float> count_rate_vec; std::vector<float> np_ratio_vec; start_time_str[10] = ' '; // make it compatible with boost::posix_time::ptime boost::posix_time::ptime start_time( boost::posix_time::time_from_string(start_time_str)); start_time_str[10] = 'T'; // revert std::string line; std::getline(fil, line); // skip the first line while (std::getline(fil, line)) { std::string date_time_str; int period; int is_running; int is_waiting; int good_frames; int raw_frames; int monitor_sum_1; int total_counts; float proton_charge; float proton_charge_raw; float dae_beam_current; float count_rate; float np_ratio; std::istringstream istr(line); istr >> date_time_str >> period >> is_running >> is_waiting >> good_frames >> raw_frames >> proton_charge >> proton_charge_raw >> monitor_sum_1 >> dae_beam_current >> total_counts >> count_rate >> np_ratio; date_time_str[10] = ' '; boost::posix_time::ptime time( boost::posix_time::time_from_string(date_time_str)); boost::posix_time::time_duration dt = time - start_time; time_vec.push_back(float(dt.total_seconds())); period_vec.push_back(period); is_running_vec.push_back(is_running); is_waiting_vec.push_back(is_waiting); good_frames_vec.push_back(good_frames); raw_frames_vec.push_back(raw_frames); monitor_sum_1_vec.push_back(monitor_sum_1); total_counts_vec.push_back(total_counts); proton_charge_vec.push_back(proton_charge); proton_charge_raw_vec.push_back(proton_charge_raw); dae_beam_current_vec.push_back(dae_beam_current); count_rate_vec.push_back(count_rate); np_ratio_vec.push_back(np_ratio); } fil.close(); run_status_vec.resize(time_vec.size()); std::transform(is_running_vec.begin(), is_running_vec.end(), run_status_vec.begin(), std::bind2nd(std::plus<int>(), 1)); NXmakegroup(handle, "runlog", "IXrunlog"); NXopengroup(handle, "runlog", "IXrunlog"); int time_vec_size = static_cast<int>(time_vec.size()); write_runlog("period", &time_vec[0], &period_vec[0], NX_INT32, time_vec_size, "none"); write_runlog("is_running", &time_vec[0], &is_running_vec[0], NX_INT32, time_vec_size, "none"); write_runlog("is_waiting", &time_vec[0], &is_waiting_vec[0], NX_INT32, time_vec_size, "none"); write_runlog("good_frames", &time_vec[0], &good_frames_vec[0], NX_INT32, time_vec_size, "frames"); write_runlog("raw_frames", &time_vec[0], &raw_frames_vec[0], NX_INT32, time_vec_size, "frames"); write_runlog("monitor_sum_1", &time_vec[0], &monitor_sum_1_vec[0], NX_INT32, time_vec_size, "counts"); write_runlog("total_counts", &time_vec[0], &total_counts_vec[0], NX_INT32, time_vec_size, "counts"); write_runlog("proton_charge", &time_vec[0], &proton_charge_vec[0], NX_FLOAT32, time_vec_size, "uAh"); write_runlog("proton_charge_raw", &time_vec[0], &proton_charge_raw_vec[0], NX_FLOAT32, time_vec_size, "uAh"); write_runlog("dae_beam_current", &time_vec[0], &dae_beam_current_vec[0], NX_FLOAT32, time_vec_size, "uAh"); write_runlog("count_rate", &time_vec[0], &count_rate_vec[0], NX_FLOAT32, time_vec_size, "counts"); write_runlog("np_ratio", &time_vec[0], &np_ratio_vec[0], NX_FLOAT32, time_vec_size, "nones"); write_runlog("run_status", &time_vec[0], &run_status_vec[0], NX_INT32, time_vec_size, "none"); // read in ICPevent file and create icp_event log std::ifstream icpevent_fil(ICPevent_filename.c_str()); if (!icpevent_fil) { g_log.warning("Cannot find the ICPevent file"); progress(0.5); return; } time_vec.clear(); std::vector<std::string> event_vec; while (std::getline(icpevent_fil, line)) { if (line.empty()) continue; std::string date_time_str = line.substr(0, 19); date_time_str[10] = ' '; boost::posix_time::ptime time( boost::posix_time::time_from_string(date_time_str)); boost::posix_time::time_duration dt = time - start_time; time_vec.push_back(float(dt.total_seconds())); event_vec.push_back(line.substr(20)); } icpevent_fil.close(); NXmakegroup(handle, "icp_event", "NXlog"); NXopengroup(handle, "icp_event", "NXlog"); saveFloatOpen("time", &time_vec[0], static_cast<int>(time_vec.size())); putAttr("start", start_time_str); putAttr("units", "seconds"); close(); saveStringVectorOpen("value", event_vec, 72); putAttr("units", " "); close(); NXclosegroup(handle); // icp_event NXclosegroup(handle); // runlog progress(0.5); }
void TorrentDownloader::WriteTorrent(void){ // Do some sanity checks // TODO: evaluate if this is the right thing to do if(!this->status==FAILED){ syslog(LOG_NOTICE,"Torrent had failures, not writing torrent data"); return; } // Find directory to write to string wp="/home/"+User::UIDToUser(this->user); string suf="/torrents/"; try{ FtdConfig& cfg=FtdConfig::Instance(); suf="/"+cfg.GetString("torrent","torrentdir")+"/"; }catch(std::runtime_error& err){ syslog(LOG_ERR,"Unable to read torrent dir"); } if(!Stat::DirExists(wp+suf)){ FileUtils::MkPath(wp+suf); FileUtils::Chown(wp+suf,this->user,"users"); DirWatcher::Instance().AddWatch(wp+suf); } string fn=wp+suf+".ftdtrXXXXXX"; int fd; char *pt=(char*)malloc(fn.length()+1); if(!pt){ syslog(LOG_CRIT,"Failed to allocate memory for path %s because %m" ,wp.c_str()); return; } sprintf(pt,"%s",fn.c_str()); if((fd=mkstemp(pt))<0){ syslog(LOG_ERR,"Failed to create torrent file in %s because %m",fn.c_str()); return; } this->torrentfilename=pt; FILE* file=fdopen(fd,"w"); // This is definetly not portable.... __gnu_cxx::stdio_filebuf<char> fb(file,std::ios_base::out); iostream fil(&fb); fil<< m_dlstream.str(); fil.flush(); fb.close(); // Rewind stream for output later use m_dlstream.seekg (0, ios::beg); uid_t user=this->user==0xffff?0:this->user; gid_t group=this->group==0xffff?0:this->group; if(chown(pt,user,group)){ syslog(LOG_NOTICE,"Failed to chown file %s because %m",wp.c_str()); } free(pt); close(fd); }
float operator()(float in){ return delay( fil( delay() + in ) ); }
void calcu(int x,int y) {if(r==15) {sa[0]=x-r;sa[1]=y;sa[2]=x+r;sa[3]=y;} if(r==30) {sa[0]=x-r/2;sa[1]=y;sa[2]=x+r+r/2;sa[3]=y; if(x>300) {sa[0]=x-r-r/2;sa[2]=x+r/2;}} if(r==60) {sa[0]=x-15;sa[1]=y;sa[2]=x+105;sa[3]=y; if(x>100) {sa[0]=x-40;sa[2]=x+80; } if(x>200) {sa[0]=x-60;sa[2]=x+60;} if(x>300) {sa[0]=x-80;sa[2]=x+40; } if(x>=450) {sa[0]=x-105;sa[2]=x+15;}} if(p==0) {sa1[0]=(sa[0]+sa[2])/2;sa1[1]=y-5;} if(p==1) {if(sa1[0]>=sa[0]&&sa1[0]<=sa[2]) if(sa1[1]+r1>=sa[1]) {a=sa[0]+r; sa1[2]=(sa1[0]-a)/4; sa1[3]=-sa1[3];} } if(p==1) {if(sa1[0]-r1<=40) sa1[2]=-sa1[2]; if(sa1[1]-r1<=40) { sa1[3]=-sa1[3]; } if(sa1[0]+r1>=600) sa1[2]=-sa1[2]; } if(p==1) {for(i=0;i<30;i++) { if(bool3[i]==1) { a=bool1[i]-sa1[0]; if(a<0) a=-a; a=a*a; b=bool2[i]-sa1[1]; if(b<0) b=-b; b=b*b; c=a+b; c=sqrt(c); a=(r1+28); if(c<=a) {bool3[i]=0;d=d-5;score=score+50; if(bool4[i]!=0) {sin1[kk]=bool1[i];sin2[kk]=bool2[i];sin3[kk]=bool4[i]; kk++; } } } } if(d<5) {d=powe;sa1[3]=-sa1[3];} } if(p==1) {a=0; for(i=0;i<30;i++) if(bool3[i]==0) a=a+1; if(a>10) {powe=10;oo=10;} if(a>20) {powe=15;oo=15;} if(a>25) {powe=20;oo=20;} if(a==30) { lave=lave+1; switch(lave) {case 1:bo2();break; case 2:bo3();break; case 3:bo4();break; case 4:bo5();break; case 5:outtextxy(40,40,"YOU WON THE GAME AND YOUR SCORE:"); printf("\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n %ld",score); delay(5000); getch(); fil(); li=0; break; } get();} } if(p==1) {if(sa1[1]>=460) { outtextxy(150,350,"LIFE LOSE"); li=li-1; delay(5000); if(li==0) {outtextxy(370,150,"GAME OVER"); outtextxy(380,250,"YOUR SCORE"); printf("\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n %ld",score); delay(4000); fil(); } if(li!=0) {get(); } } } if(p==1) {sa1[0]=sa1[0]+sa1[2]; sa1[1]=sa1[1]+sa1[3]; } }
void ConfigManager::Read() { wxTextFile fil(filename); if (!fil.Exists()) return; fil.Open(); wxString key, value; long l; for ( wxString str = fil.GetFirstLine(); !fil.Eof(); str = fil.GetNextLine() ) { if (str[0]=='#') { continue; } else { key=str.BeforeFirst('='); value=str.AfterFirst('='); if (key=="version") { value.ToLong(&l); version=l; lang.Reset(version); } else if (key=="font_size") { value.ToLong(&l); font_size=l; } else if (key=="tabWidth") { value.ToLong(&l); tabw=l; } else if (key=="size_x") { value.ToLong(&l); size_x=l; } else if (key=="size_y") { value.ToLong(&l); size_y=l; } else if (key=="pos_x") { value.ToLong(&l); pos_x=l; } else if (key=="pos_y") { value.ToLong(&l); pos_y=l; } else if (key=="debug_port") { value.ToLong(&l); debug_port=l; } else if (key=="comm_port") { value.ToLong(&l); comm_port=l; } else if (key=="use_psterm") use_psterm=utils->IsTrue(value); else if (key=="use_dark_psterm") use_dark_psterm=utils->IsTrue(value); else if (key=="check_for_updates") check_for_updates=utils->IsTrue(value); else if (key=="fixed_port") fixed_port=utils->IsTrue(value); else if (key=="stepstep_tspeed") { value.ToLong(&l); stepstep_tspeed=l; } else if (key=="rt_syntax") rt_syntax=utils->IsTrue(value); else if (key=="smart_indent") smart_indent=utils->IsTrue(value); else if (key=="show_commands") show_commands=utils->IsTrue(value); else if (key=="show_vars") show_vars=utils->IsTrue(value); else if (key=="show_opers") show_opers=utils->IsTrue(value); else if (key=="show_debug_panel") show_debug_panel=utils->IsTrue(value); else if (key=="show_toolbar") show_toolbar=utils->IsTrue(value); else if (key=="auto_quickhelp") auto_quickhelp=utils->IsTrue(value); else if (key=="calltip_helps") calltip_helps=utils->IsTrue(value); else if (key=="autocomp") autocomp=utils->IsTrue(value); else if (key=="highlight_blocks") highlight_blocks=utils->IsTrue(value); else if (key=="autoclose") autoclose=utils->IsTrue(value); else if (key=="shape_colors") shape_colors=utils->IsTrue(value); else if (key=="colour_sintax") colour_sintax=utils->IsTrue(value); else if (key=="use_colors") use_colors=utils->IsTrue(value); else if (key=="animate_gui") animate_gui=utils->IsTrue(value); else if (key=="reorganize_for_debug") reorganize_for_debug=utils->IsTrue(value); else if (key=="images_path") images_path=value; else if (key=="help_dir") help_dir=value; else if (key=="proxy") proxy=value; else if (key=="profiles_dir") profiles_dir=value; else if (key=="profile") profile=value; else if (key=="examples_dir") examples_dir=value; else if (key=="last_dir") last_dir=value; else if (key=="temp_dir") temp_dir=value; // else if (key=="pseint_command") pseint_command=value; // else if (key=="psterm_command") psterm_command=value; // else if (key=="psexport_command") psexport_command=value; // else if (key=="psdrawe_command") psdrawe_command=value; // else if (key=="psdraw3_command") psdraw3_command=value; else if (key=="terminal") { tty_command=value; } else if (key=="history") last_files.Add(value); else lang.ProcessConfigLine(key.c_str(),value.c_str()); } } fil.Close(); LoadProfile(profile); lang.Fix(); if (version<20130805) use_psterm=true; }
int main(int argc, char**argv) { try { if (argc!=2) { std::cerr << "Usage: " << argv[0] << " <DATASET.rawlog>\n"; return 1; } std::cout << "Opening: " << argv[1] << std::endl; mrpt::io::CFileGZInputStream fil(argv[1]); bool rawlog_eof = false; pcl::visualization::CloudViewer viewer("Cloud Viewer from MRPT's rawlog"); //This will only get called once viewer.runOnVisualizationThreadOnce (viewerOneOff); //This will get called once per visualization iteration viewer.runOnVisualizationThread (viewerUpdate); while (!viewer.wasStopped ()) { mrpt::obs::CActionCollection::Ptr actions; mrpt::obs::CSensoryFrame::Ptr SF; mrpt::obs::CObservation::Ptr obs; if (!rawlog_eof) { if (!mrpt::obs::CRawlog::getActionObservationPairOrObservation(fil, actions, SF, obs,rawlogEntry)) { rawlog_eof = true; std::cerr << "End of rawlog file!! Close the window to exit\n"; } else { // Can generate a point cloud from this data? // TODO: Process Kinect observations differently to extract RGB data. mrpt::maps::CPointsMap::Ptr new_map; if (SF) { new_map = mrpt::make_aligned_shared<mrpt::maps::CSimplePointsMap>(); // new_map->insertionOptions.minDistBetweenLaserPoints = 0; SF->insertObservationsInto(new_map); } else if (obs) { new_map = mrpt::make_aligned_shared<mrpt::maps::CSimplePointsMap>(); // new_map->insertionOptions.minDistBetweenLaserPoints = 0; new_map->insertObservation(obs.get()); } if (new_map) { pcl::PointCloud<pcl::PointXYZRGB>::Ptr cloud (new pcl::PointCloud<pcl::PointXYZRGB>); // Convert MRPT point maps -> PCL point cloud. new_map->getPCLPointCloud(*cloud); { // Mutex protected std::lock_guard<std::mutex> lock(td_cs); td.new_timestamp = mrpt::system::now(); td.new_cloud = cloud; } std::this_thread::sleep_for(30ms); // Delay to allow the point cloud to show up. } } } std::this_thread::sleep_for(1ms); } return 0; } catch (std::exception &e) { std::cerr << e.what() << std::endl; return 1; } }
/** Get a workspace identified by an InputData structure. * @param data :: InputData with name and either spec or i fields defined. * @return InputData structure with the ws field set if everything was OK. */ PlotPeakByLogValue::InputData PlotPeakByLogValue::getWorkspace(const InputData& data) { InputData out(data); if (API::AnalysisDataService::Instance().doesExist(data.name)) { DataObjects::Workspace2D_sptr ws = boost::dynamic_pointer_cast<DataObjects::Workspace2D>( API::AnalysisDataService::Instance().retrieve(data.name)); if (ws) { out.ws = ws; } else { return data; } } else { std::ifstream fil(data.name.c_str()); if (!fil) { g_log.warning() << "File "<<data.name<<" does not exist\n"; return data; } fil.close(); std::string::size_type i = data.name.find_last_of('.'); if (i == std::string::npos) { g_log.warning() << "Cannot open file "<<data.name<<"\n"; return data; } std::string ext = data.name.substr(i); try { API::IAlgorithm_sptr load = createSubAlgorithm("Load"); load->initialize(); load->setPropertyValue("FileName",data.name); load->execute(); if (load->isExecuted()) { API::Workspace_sptr rws = load->getProperty("OutputWorkspace"); if (rws) { DataObjects::Workspace2D_sptr ws = boost::dynamic_pointer_cast<DataObjects::Workspace2D>(rws); if (ws) { out.ws = ws; } else { API::WorkspaceGroup_sptr gws = boost::dynamic_pointer_cast<API::WorkspaceGroup>(rws); if (gws) { std::vector<std::string> wsNames = gws->getNames(); std::string propName = "OUTPUTWORKSPACE_" + boost::lexical_cast<std::string>(data.period); if (load->existsProperty(propName)) { Workspace_sptr rws1 = load->getProperty(propName); out.ws = boost::dynamic_pointer_cast<DataObjects::Workspace2D>(rws1); } } } } } } catch(std::exception& e) { g_log.error(e.what()); return data; } } if (!out.ws) return data; API::Axis* axis = out.ws->getAxis(1); if (axis->isSpectra()) {// spectra axis if (out.spec < 0) { if (out.i >= 0) { out.spec = axis->spectraNo(out.i); } else {// i < 0 && spec < 0 => use start and end for(size_t i=0;i<axis->length();++i) { double s = double(axis->spectraNo(i)); if (s >= out.start && s <= out.end) { out.indx.push_back(static_cast<int>(i)); } } } } else { for(size_t i=0;i<axis->length();++i) { int j = axis->spectraNo(i); if (j == out.spec) { out.i = static_cast<int>(i); break; } } } if (out.i < 0 && out.indx.empty()) { return data; } } else {// numeric axis out.spec = -1; if (out.i >= 0) { out.indx.clear(); } else { if (out.i < -1) { out.start = (*axis)(0); out.end = (*axis)(axis->length()-1); } for(size_t i=0;i<axis->length();++i) { double s = (*axis)(i); if (s >= out.start && s <= out.end) { out.indx.push_back(static_cast<int>(i)); } } } } return out; }
int Spawner::Run(Command &commands, RuleList *ruleList, Rule *rule) { int rv = 0; for (Command::iterator it = commands.begin(); it != commands.end() && !rv ; ++it) { bool curSilent = silent; bool curIgnore = ignoreErrors; bool curDontRun = dontRun; const std::string &a = (*it); int i; for (i=0; i < a.size(); i++) if (a[i] == '+') curDontRun = false; else if (a[i] == '@') curSilent = true; else if (a[i] == '-') curIgnore = true; else break; if (a.find("$(MAKE)") != std::string::npos || a.find("${MAKE}") != std::string::npos) curDontRun = false; std::string cmd = a.substr(i); Eval c(cmd, false, ruleList, rule); cmd = c.Evaluate(); // deferred evaluation size_t n = cmd.find("&&"); std::string makeName; if (n == cmd.size() - 3) { char match = cmd[n+2]; cmd.erase(n); std::strstream str; str << "maketemp." << std::setw(3) << std::setfill('0') << tempNum++; str >> makeName; std::fstream fil(makeName.c_str(), std::ios::out); bool done = false; std::string tail; do { ++it; std::string current = *it; size_t n = current.find(match); if (n != std::string::npos) { done = true; if (n+1 < current.size()) tail = current.substr(n+1); current.erase(n); } Eval ce(current, false, ruleList, rule); fil << ce.Evaluate() << std::endl; } while (!done); fil.close(); cmd += makeName + tail; } cmd = QualifyFiles(cmd); rv = Run(cmd, curIgnore, curSilent, curDontRun); if (curIgnore) rv = 0; if (makeName.size()) OS::RemoveFile(makeName); }
void ConfigManager::Save() { wxTextFile fil(filename); if (fil.Exists()) fil.Open(); else fil.Create(); fil.Clear(); fil.AddLine(wxString("# generado por PSeInt ")<<VERSION<<"-"ARCHITECTURE); fil.AddLine(wxString("version=")<<VERSION); fil.AddLine(wxString("images_path=")<<images_path); // fil.AddLine(wxString("pseint_command=")<<pseint_command); // fil.AddLine(wxString("psterm_command=")<<psterm_command); // fil.AddLine(wxString("psexport_command=")<<psexport_command); // fil.AddLine(wxString("psdrawe_command=")<<psdrawe_command); // fil.AddLine(wxString("psdraw3_command=")<<psdraw3_command); if (tty_command!=_no_tty) fil.AddLine(wxString("terminal=")<<tty_command); fil.AddLine(wxString("temp_dir=")<<temp_dir); fil.AddLine(wxString("last_dir=")<<last_dir); fil.AddLine(wxString("help_dir=")<<help_dir); fil.AddLine(wxString("proxy=")<<proxy); fil.AddLine(wxString("profiles_dir=")<<profiles_dir); fil.AddLine(wxString("profile=")<<profile); fil.AddLine(wxString("examples_dir=")<<examples_dir); fil.AddLine(wxString("rt_syntax=")<<(rt_syntax?1:0)); fil.AddLine(wxString("smart_indent=")<<(smart_indent?1:0)); fil.AddLine(wxString("shape_colors=")<<(shape_colors?1:0)); fil.AddLine(wxString("colour_sintax=")<<(colour_sintax?1:0)); fil.AddLine(wxString("show_vars=")<<(show_vars?1:0)); fil.AddLine(wxString("show_opers=")<<(show_opers?1:0)); fil.AddLine(wxString("show_commands=")<<(show_commands?1:0)); fil.AddLine(wxString("show_debug_panel=")<<(show_debug_panel?1:0)); fil.AddLine(wxString("show_toolbar=")<<(show_toolbar?1:0)); fil.AddLine(wxString("calltip_helps=")<<(calltip_helps?1:0)); fil.AddLine(wxString("autocomp=")<<(autocomp?1:0)); fil.AddLine(wxString("highlight_blocks=")<<(highlight_blocks?1:0)); fil.AddLine(wxString("autoclose=")<<(autoclose?1:0)); fil.AddLine(wxString("auto_quickhelp=")<<(auto_quickhelp?1:0)); fil.AddLine(wxString("use_colors=")<<(use_colors?1:0)); fil.AddLine(wxString("animate_gui=")<<(animate_gui?1:0)); fil.AddLine(wxString("reorganize_for_debug=")<<(reorganize_for_debug?1:0)); for(int i=0;i<LS_COUNT;i++) fil.AddLine(lang.GetConfigLine(i).c_str()); fil.AddLine(wxString("maximized=")<<(maximized?1:0)); fil.AddLine(wxString("font_size=")<<font_size); fil.AddLine(wxString("tabw=")<<tabw); fil.AddLine(wxString("stepstep_tspeed=")<<stepstep_tspeed); fil.AddLine(wxString("size_x=")<<size_x); fil.AddLine(wxString("size_y=")<<size_y); fil.AddLine(wxString("pos_x=")<<pos_x); fil.AddLine(wxString("pos_y=")<<pos_y); fil.AddLine(wxString("maximized=")<<maximized); if (fixed_port) { fil.AddLine(wxString("debug_port=")<<debug_port); fil.AddLine(wxString("comm_port=")<<comm_port); } fil.AddLine(wxString("use_psterm=")<<(use_psterm?1:0)); fil.AddLine(wxString("use_dark_psterm=")<<(use_dark_psterm?1:0)); fil.AddLine(wxString("check_for_updates=")<<(check_for_updates?1:0)); fil.AddLine(wxString("fixed_port=")<<(fixed_port?1:0)); for (unsigned int i=0;i<last_files.GetCount();i++) fil.AddLine(wxString("history=")<<last_files[i]); fil.AddLine(""); fil.Write(); fil.Close(); }