BarChart4::BarChart4(MyPlotwindow *m_plot, wxString filename, PlotParam b4style) { pls = m_plot->GetStream(); double x[10]; double xa[10],xb[10],za[10],zb[10]; wxFileInputStream fin( filename ); wxTextInputStream text( fin ); for(int i=0;i<10;i++) { x[i]=i+1.0; text>>xb[i] >>zb[i] >>xa[i] >>za[i]; } //pls->env( 0, 11, 0, 0.012, 0, 0 ); pls->adv( 0 ); pls->vsta(); pls->wind( 0, 11, 0, b4style.ymax*0.015 ); plcol0( 15 ); pls->box( "bcnt", 1.0, 0, "bcntv", 0, 4 ); pls->lab( "harmonic number", "", "Stopband harmonics components" ); plcol0( 0 ); plcol1( 1 ); pls->psty( 0 ); for (int i = 0; i < 10; i++ ) { plfbox_solid( x[i]-0.4, xb[i], 0.2); } plcol1( 1 ); pls->psty( 3 ); for (int i = 0; i < 10; i++ ) { plfbox_solid( x[i]-0.2, xa[i] , 0.2); plfbox_hollow( x[i]-0.2, xa[i] , 0.2); } plcol1( 0 ); pls->psty( 0 ); for (int i = 0; i < 10; i++ ) { plfbox_solid( x[i]+0.0, zb[i], 0.2); } plcol1( 0 ); pls->psty( 3 ); //pls->lsty( 1 ); for (int i = 0; i < 10; i++ ) { plfbox_solid( x[i]+0.2, za[i] , 0.2); plfbox_hollow( x[i]+0.2, za[i] , 0.2); } //legend pls->vpor(0.15, 0.90, 0.75, 0.85); pls->wind( 0, 1, 0, 1 ); plcol0( 5 ); pls->lsty( 1 ); pls->box( "bc", 0, 0, "bc", 0, 0 ); pls->ptex( 0.1, 0.70, 0.0, 0.0, 0, "red: horizontal" ); pls->ptex( 0.1, 0.20, 0.0, 0.0, 0, "blue: vertical" ); pls->ptex( 0.6, 0.70, 0.0, 0.0, 0, "solid: before" ); pls->ptex( 0.6, 0.20, 0.0, 0.0, 0, "shadow: after" ); /* pls->vpor(0.15, 0.40, 0.65, 0.85); pls->wind( 0, 1, 0, 1 ); plcol0( 5 ); pls->box( "bc", 0, 0, "bc", 0, 0 ); pls->ptex( 0.4, 0.6, 0.0, 0.0, 0, "legend 1" ); pls->ptex( 0.4, 0.3, 0.0, 0.0, 0, "legend 2" ); pls->vpor(0.6, 0.9, 0.5, 0.85); pls->wind( 0, 1, -0.003, 0.003 ); plcol0( 6 ); //pls->box( "bc", 0, 0, "bc", 0, 0 ); pls->box( "abcnt", 0, 0, "bcntv", 0, 0 ); pls->ptex( 0.5, 0.5, 0.0, 0.0, 0, "inset" ); */ m_plot->RenewPlot(); }
void GrdPlugin::findMinMax() { QProgressDialog progress("Finding Min and Max", "Cancel", 0, 100, 0); progress.setMinimumDuration(0); int nbytes = m_width*m_height*m_bytesPerVoxel; uchar *tmp = new uchar[nbytes]; QFile fin(m_fileName[0]); fin.open(QFile::ReadOnly); fin.seek(m_headerBytes); m_rawMin = 10000000; m_rawMax = -10000000; for(uint i=0; i<m_depth; i++) { progress.setValue((int)(100.0*(float)i/(float)m_depth)); qApp->processEvents(); //---------------------------- QFile fin(m_imageList[i]); fin.open(QFile::ReadOnly); fin.seek(m_headerBytes); fin.read((char*)tmp, nbytes); fin.close(); //---------------------------- if (m_voxelType == _UChar) { uchar *ptr = tmp; FINDMINMAX(); } else if (m_voxelType == _Char) { char *ptr = (char*) tmp; FINDMINMAX(); } if (m_voxelType == _UShort) { ushort *ptr = (ushort*) tmp; FINDMINMAX(); } else if (m_voxelType == _Short) { short *ptr = (short*) tmp; FINDMINMAX(); } else if (m_voxelType == _Int) { int *ptr = (int*) tmp; FINDMINMAX(); } else if (m_voxelType == _Float) { float *ptr = (float*) tmp; FINDMINMAX(); } } fin.close(); delete [] tmp; progress.setValue(100); qApp->processEvents(); }
void GrdPlugin::saveTrimmed(QString trimFile, int dmin, int dmax, int wmin, int wmax, int hmin, int hmax) { QProgressDialog progress("Saving trimmed volume", 0, 0, 100, 0); progress.setMinimumDuration(0); int nX, nY, nZ; nX = m_depth; nY = m_width; nZ = m_height; int mX, mY, mZ; mX = dmax-dmin+1; mY = wmax-wmin+1; mZ = hmax-hmin+1; int nbytes = nY*nZ*m_bytesPerVoxel; uchar *tmp = new uchar[nbytes]; uchar vt; if (m_voxelType == _UChar) vt = 0; // unsigned byte if (m_voxelType == _Char) vt = 1; // signed byte if (m_voxelType == _UShort) vt = 2; // unsigned short if (m_voxelType == _Short) vt = 3; // signed short if (m_voxelType == _Int) vt = 4; // int if (m_voxelType == _Float) vt = 8; // float QFile fout(trimFile); fout.open(QFile::WriteOnly); fout.write((char*)&vt, 1); fout.write((char*)&mX, 4); fout.write((char*)&mY, 4); fout.write((char*)&mZ, 4); for(uint i=dmin; i<=dmax; i++) { //---------------------------- QFile fin(m_imageList[i]); fin.open(QFile::ReadOnly); fin.seek(m_headerBytes); fin.read((char*)tmp, nbytes); fin.close(); //---------------------------- for(uint j=wmin; j<=wmax; j++) { memcpy(tmp+(j-wmin)*mZ*m_bytesPerVoxel, tmp+(j*nZ + hmin)*m_bytesPerVoxel, mZ*m_bytesPerVoxel); } fout.write((char*)tmp, mY*mZ*m_bytesPerVoxel); progress.setValue((int)(100*(float)(i-dmin)/(float)mX)); qApp->processEvents(); } fout.close(); delete [] tmp; m_headerBytes = 13; // to be used for applyMapping function }
int main(/*int argc, char *argv[]*/) { typedef patl::trie_set<std::string> StringSet; StringSet test1, test2; //&test2 = test1; // test1.insert("balka"); test1.insert("balet"); test1.insert("bulat"); test1.insert("bulka"); test1.insert("bal"); // test2.insert("balet"); test2.insert("balon"); test2.insert("bal"); test2.insert("baton"); // test1.merge(test2.begin(), test2.end()); test1.change_root(test1.find("balon")); // { typedef StringSet::const_iterator const_iterator; typedef std::pair<const_iterator, const_iterator> pair_cit_cit; pair_cit_cit pcc = test1.equal_range("balda"); const_iterator low_cit = test1.lower_bound("balda"), upp_cit = test1.upper_bound("balda"); printf("equal == <lower, upper>: %s\n", pcc == std::make_pair(low_cit, upp_cit) ? "true" : "false"); printf("range of 'balda' (first: %s, limit: %s):\n", pcc.first != test1.end() ? pcc.first->c_str() : "end", pcc.second != test1.end() ? pcc.second->c_str() : "end"); for (const_iterator cit = pcc.first; cit != pcc.second; ++cit) printf("\t%s\n", cit->c_str()); // printf("\n---\n\n"); // pcc = test1.equal_range("balda", 3 * 8); low_cit = test1.lower_bound("balda", 3 * 8); upp_cit = test1.upper_bound("balda", 3 * 8); printf("equal == <lower, upper>: %s\n", pcc == std::make_pair(low_cit, upp_cit) ? "true" : "false"); printf("range of 'balda' [3] (first: %s, limit: %s):\n", pcc.first != test1.end() ? pcc.first->c_str() : "end", pcc.second != test1.end() ? pcc.second->c_str() : "end"); for (const_iterator cit = pcc.first; cit != pcc.second; ++cit) printf("\t%s\n", cit->c_str()); } // printf("\n--- iterator\n\n"); // { typedef StringSet::const_iterator const_iter; const_iter itBeg = test1.begin(), itEnd = test1.end(), it = itBeg; for (; it != itEnd; ++it) printf("%s\n", it->c_str()); printf("---\n"); while (it != itBeg) { --it; printf("%s\n", it->c_str()); } } // printf("\n--- partial_match\n\n"); // { typedef patl::partial_match<StringSet, false> part_match; part_match pm(test1, "b?l?t"); StringSet::const_partimator<part_match> it = test1.begin(pm), itEnd = test1.end(pm); printf("*** 'b?l?t':\n"); for (; it != itEnd; ++it) printf("%s\n", it->c_str()); printf("---\n"); pm = part_match(test1, "b?l??"); it = test1.begin(pm); itEnd = test1.end(pm); printf("*** 'b?l??\':\n"); for (; it != itEnd; ++it) printf("%s\n", it->c_str()); } // printf("\n--- hamming_distance\n\n"); // { typedef patl::hamming_distance<StringSet, false> hamm_dist; hamm_dist hd(test1, 1, "bulk"); StringSet::const_partimator<hamm_dist> it = test1.begin(hd), itEnd = test1.end(hd); printf("*** 'bulk', dist == 1:\n"); for (; it != itEnd; ++it) printf("%s, dist: %u\n", it->c_str(), it.decis().distance()); } // printf("\n--- levenshtein_distance\n\n"); // { typedef patl::levenshtein_distance<StringSet, false> leven_dist; leven_dist ld(test1, 1, "balt"); StringSet::const_partimator<leven_dist> it = test1.begin(ld), itEnd = test1.end(ld); printf("*** 'balt', dist == 1:\n"); for (; it != itEnd; ++it) printf("%s, dist: %u\n", it->c_str(), it.decis().distance()); } // printf("\n--- postorder_iterator\n\n"); // typedef StringSet::const_vertex const_vertex; const const_vertex vtx_root = test1.root(); { typedef StringSet::const_postorder_iterator const_postorder_iterator; const_postorder_iterator itBeg = vtx_root.postorder_begin(), itEnd = vtx_root.postorder_end(), it = itBeg; for (; it != itEnd; ++it) printf("%d\t%s\n", it->skip(), it->key().c_str()); printf("---\n"); while (it != itBeg) { --it; printf("%d\t%s\n", it->skip(), it->key().c_str()); } } // printf("\n--- preorder_iterator\n\n"); // { typedef StringSet::const_preorder_iterator const_preorder_iterator; const_preorder_iterator itBeg = vtx_root.preorder_begin(), itEnd = vtx_root.preorder_end(), it = itBeg; preorder_iterator_callback<typename StringSet::const_vertex> icb; for (; it != itEnd; /*++it*/it.increment(icb)) printf("%d\t%s\n", it->skip(), it->key().c_str()); printf("---\n"); while (it != itBeg) { //--it; it.decrement(icb); printf("%d\t%s\n", it->skip(), it->key().c_str()); } } // printf("\n--- preorder_iterator with levelorder behavior\n\n"); // { const char *const X[] = { "asm", "auto", "bool", "break", "case", "catch", "char", "class", "const", "const_cast", "continue", "default", "delete", "do", "double", "dynamic_cast", "else", "enum", "explicit", "export", "extern", "false", "float", "for", "friend", "goto", "if", "inline", "int", "long", "mutable", "namespace", "new", "operator", "private", "protected", "public", "register", "reinterpret_cast", "return", "short", "signed", "sizeof", "static", "static_cast", "struct", "switch", "template", "this", "throw", "true", "try", "typedef", "typeid", "typename", "union", "unsigned", "using", "virtual", "void", "volatile", "wchar_t", "while"}; // typedef patl::trie_set<std::string> ReservSet; typedef ReservSet::const_vertex const_vertex; const ReservSet rvset(X, X + sizeof(X) / sizeof(X[0])); // printf("*** Regexp:\n"); const_vertex vtx = rvset.root(); print_regexp(0, vtx.preorder_begin(8), vtx.preorder_end()); printf("\n"); } // printf("\n--- [super_]maxrep_iterator\n\n"); // { typedef patl::suffix_set<char*> SuffixSet; char str[] = //"abrakadabraa"; "xabcyiiizabcqabcyr"; //"cxxaxxaxxb"; //"How many wood would a woodchuck chuck."; //"xgtcacaytgtgacz"; printf("*** string: '%s':\n", str); SuffixSet suffix(str); for (word_t i = 0; i != sizeof(str) - 1; ++i) suffix.push_back(); for (uxn::patl::maxrep_iterator<SuffixSet> mrit(&suffix) ; !mrit->is_root() ; ++mrit) { printf("'%s' x %d:", std::string(mrit->key(), mrit->length()).c_str(), mrit.freq()); const SuffixSet::const_vertex vtx = mrit->get_vertex(); for (SuffixSet::const_iterator it = vtx.begin() ; it != vtx.end() ; ++it) printf(" at %u", suffix.index_of( static_cast<const SuffixSet::const_vertex&>(it))); printf("\n"); } printf("---\n"); for (uxn::patl::super_maxrep_iterator<SuffixSet> mrit(&suffix) ; !mrit->is_root() ; ++mrit) { printf("'%s' x %d:", std::string(mrit->key(), mrit->length()).c_str(), mrit.freq()); const SuffixSet::const_vertex vtx = mrit->get_vertex(); for (SuffixSet::const_iterator it = vtx.begin() ; it != vtx.end() ; ++it) printf(" at %u", suffix.index_of( static_cast<const SuffixSet::const_vertex&>(it))); printf("\n"); } } // printf("\n--- search tandem repeats in O(n)\n\n"); // { //typedef int typ; typedef char typ; typedef patl::suffix_set<const typ*> suffix_t; //typ arr[] = {10, 5, 6, 7, 5, 6, 7, 89, 64}; typ arr[] = "qabrabrabrweabrabraaaad"; //typ arr[] = "qweabrabrrrrd"; printf("*** string: '%s':\n", arr); suffix_t suf(arr, 16 /* maximal length of tandem repeat + 1 */); do { const suffix_t::const_vertex vtx = suf.push_back(), sibl = vtx.sibling(); if (suf.size() > 1) { const int skip = vtx.skip() / 8 / sizeof(typ); const word_t delta = vtx.key() - sibl.key(), count = skip / delta + 1; if (count > 1) { printf("begin: %u, length: %u, count: %u\n", sibl.key() - arr, delta, count); suf.rebind(sibl.key() + delta * count); suf.clear(); } if (!suf.empty() && suf.endpoint()) suf.pop_front(); } } while (suf.keys() + suf.size() != arr + sizeof(arr) / sizeof(arr[0])); } // printf("\n--- generate graphviz dot\n\n"); // patl::patricia_dot_creator<StringSet>().create(vtx_root); #if 0 // pat_.dot & pat_.clust.dot creation { std::ifstream fin(argc > 1 ? argv[1] : "WORD.LST"); if (fin.is_open()) { StringSet dict; std::string str; while (fin >> str) dict.insert(str); const_vertex vtx(dict.root()); // #if 0 vtx.mismatch("patch", 5 * 8); typedef StringSet::const_preorder_iterator const_preorder_iterator; const_preorder_iterator itBeg = vtx.preorder_begin(), itEnd = vtx.preorder_end(), it = itBeg; for (; it != itEnd; it.increment(6 * 8)) { if (it->limited(6 * 8)) printf("* "); printf("%d\t%s\n", it->skip(), it->key().c_str()); } printf("---\n"); while (it != itBeg) { it.decrement(6 * 8); if (it->limited(6 * 8)) printf("* "); printf("%d\t%s\n", it->skip(), it->key().c_str()); } #else vtx.mismatch("patr", 4 * 8); { std::ofstream fout("patr_.dot"); patl::patricia_dot_creator<StringSet, std::ofstream>(fout).create(vtx); } printf("\npatr_.dot created!\n"); { std::ofstream fout("patr_.clust.dot"); patl::patricia_dot_creator<StringSet, std::ofstream>(fout).create(vtx, true); } printf("\npatr_.clust.dot created!\n"); #endif } else
void GenNoCompressCfg::Trigger(const std::string& src_dir, const std::string& src_cfg, const std::string& dst_dir) { wxArrayString files; ee::FileHelper::FetchAllFiles(src_dir, files); std::set<std::string> paths; // read from old cfg Json::Value src_value; Json::Reader reader; std::locale::global(std::locale("")); std::ifstream fin(src_cfg.c_str()); std::locale::global(std::locale("C")); reader.parse(fin, src_value); fin.close(); if (src_value.isMember("no_compress")) { for (int i = 0, n = src_value["no_compress"].size(); i < n; ++i) { std::string path = src_value["no_compress"][i].asString(); auto full_path = gum::FilepathHelper::Absolute(src_dir.c_str(), path.c_str()); paths.insert(gum::FilepathHelper::Format(full_path.c_str()).c_str()); } } // add scale9 for (int i = 0, n = files.size(); i < n; ++i) { wxFileName filename(files[i]); filename.Normalize(); std::string filepath = filename.GetFullPath(); int type = ee::SymbolFile::Instance()->Type(filepath); if (type != s2::SYM_SCALE9) { continue; } Json::Value value; Json::Reader reader; std::locale::global(std::locale("")); std::ifstream fin(filepath.c_str()); std::locale::global(std::locale("C")); reader.parse(fin, value); fin.close(); int zero = 0; std::string dir = ee::FileHelper::GetFileDir(filepath); int s9_type = value["type"].asInt(); switch (s9_type) { case s2::S9_NULL: break; case s2::S9_9GRID: AddPath(paths, dst_dir, value["sprite"][1], dir); AddPath(paths, dst_dir, value["sprite"][3], dir); AddPath(paths, dst_dir, value["sprite"][4], dir); AddPath(paths, dst_dir, value["sprite"][5], dir); AddPath(paths, dst_dir, value["sprite"][7], dir); break; case s2::S9_3GRID_HORI: AddPath(paths, dst_dir, value["sprite"][1], dir); break; case s2::S9_3GRID_VERT: AddPath(paths, dst_dir, value["sprite"][1], dir); break; case s2::S9_6GRID_UPPER: AddPath(paths, dst_dir, value["sprite"][zero], dir); AddPath(paths, dst_dir, value["sprite"][1], dir); AddPath(paths, dst_dir, value["sprite"][2], dir); AddPath(paths, dst_dir, value["sprite"][4], dir); break; case s2::S9_9GRID_HOLLOW: AddPath(paths, dst_dir, value["sprite"][1], dir); AddPath(paths, dst_dir, value["sprite"][3], dir); AddPath(paths, dst_dir, value["sprite"][4], dir); AddPath(paths, dst_dir, value["sprite"][6], dir); break; } Json::StyledStreamWriter writer; std::locale::global(std::locale("")); std::ofstream fout(filepath.c_str()); std::locale::global(std::locale("C")); writer.write(fout, value); fout.close(); } // output std::ofstream f_compress((dst_dir + "\\compress.tmp").c_str()); std::ofstream f_no_compress((dst_dir + "\\no_compress.tmp").c_str()); for (int i = 0, n = files.size(); i < n; ++i) { wxFileName filename(files[i]); filename.Normalize(); std::string filepath = filename.GetFullPath(); int type = ee::SymbolFile::Instance()->Type(filepath); if (type != s2::SYM_IMAGE) { continue; } filepath = gum::FilepathHelper::Format(filepath.c_str()).c_str(); if (paths.find(filepath) != paths.end()) { f_no_compress << filepath << "\n"; } else { f_compress << filepath << "\n"; } } f_compress.close(); f_no_compress.close(); }
static bool exists(const std::string& path) { std::ifstream fin(path.c_str()); bool rst = fin.good(); fin.close(); return rst; }
bool GlobalTrafficTable::load(const char *fname) { // Open file ifstream fin(fname, ios::in); if (!fin) return false; // Initialize variables traffic_table.clear(); // Cycle reading file while (!fin.eof()) { char line[512]; fin.getline(line, sizeof(line) - 1); if (line[0] != '\0') { if (line[0] != '%') { int src, dst; // Mandatory double pir, por; int t_on, t_off, t_period; int params = sscanf(line, "%d %d %lf %lf %d %d %d", &src, &dst, &pir, &por, &t_on, &t_off, &t_period); if (params >= 2) { // Create a communication from the parameters read on the line Communication communication; // Mandatory fields communication.src = src; communication.dst = dst; // Custom PIR if (params >= 3 && pir >= 0 && pir <= 1) communication.pir = pir; else communication.pir = GlobalParams::packet_injection_rate; // Custom POR if (params >= 4 && por >= 0 && por <= 1) communication.por = por; else communication.por = communication.pir; // GlobalParams::probability_of_retransmission; // Custom Ton if (params >= 5 && t_on >= 0) communication.t_on = t_on; else communication.t_on = 0; // Custom Toff if (params >= 6 && t_off >= 0) { assert(t_off > t_on); communication.t_off = t_off; } else communication.t_off = GlobalParams::reset_time + GlobalParams::simulation_time; // Custom Tperiod if (params >= 7 && t_period > 0) { assert(t_period > t_off); communication.t_period = t_period; } else communication.t_period = GlobalParams::reset_time + GlobalParams::simulation_time; // Add this communication to the vector of communications traffic_table.push_back(communication); } } } } return true; }
void ExportBodymovin::Trigger(const std::string& src_file, const std::string& dst_dir) { Json::Value val; Json::Reader reader; std::locale::global(std::locale("")); std::ifstream fin(src_file.c_str()); std::locale::global(std::locale("C")); reader.parse(fin, val); fin.close(); auto dir = gum::FilepathHelper::Dir(src_file.c_str()); s2loader::BodymovinParser parser; parser.Parse(val, dir); auto sym_loader = std::make_shared<ee::SymbolLoader>(); auto spr_loader = std::make_shared<ee::SpriteLoader>(); CU_MAP<CU_STR, s2::SprPtr> map_assets; auto& assets = parser.GetAssets(); std::vector<bool> flags(assets.size(), false); while (true) { bool fail = false; for (int i = 0, n = assets.size(); i < n; ++i) { if (flags[i]) { continue; } const s2loader::BodymovinParser::Asset& a = assets[i]; if (a.layers.empty()) { auto filepath = gum::FilepathHelper::Absolute(".", a.filepath); auto spr = spr_loader->Create(filepath); map_assets.insert(std::make_pair(a.id, spr)); flags[i] = true; } else { bool skip = false; for (int j = 0, m = a.layers.size(); j < m; ++j) { const s2loader::BodymovinParser::Layer& layer = a.layers[j]; if (layer.layer_type == s2loader::BodymovinParser::LAYER_SOLID || layer.layer_type == s2loader::BodymovinParser::LAYER_NULL) { continue; } auto& id = a.layers[j].ref_id; auto itr = map_assets.find(id); if (itr == map_assets.end()) { skip = true; break; } } flags[i] = !skip; if (skip) { fail = true; continue; } auto sym = std::make_shared<libanim::Symbol>(); s2loader::BodymovinAnimLoader loader(*std::dynamic_pointer_cast<s2::AnimSymbol>(sym), sym_loader, spr_loader); loader.LoadLayers(map_assets, a.layers, parser.GetFrameRate(), parser.GetWidth(), parser.GetHeight(), parser.GetStartFrame(), parser.GetEndFrame()); std::string filepath = dst_dir + "\\" + std::string(a.id.c_str()) + "_" + ee::SymbolFile::Instance()->Tag(s2::SYM_ANIMATION) + ".json"; libanim::FileSaver::Store(filepath, *sym); sym->SetFilepath(filepath); libanim::Sprite* spr = new libanim::Sprite(sym); spr->UpdateBounding(); map_assets.insert(std::make_pair(a.id, spr)); } } if (!fail) { break; } } auto sym = std::make_shared<libanim::Symbol>(); s2loader::BodymovinAnimLoader loader(*sym, sym_loader, spr_loader); loader.LoadLayers(map_assets, parser.GetLayers(), parser.GetFrameRate(), parser.GetWidth(), parser.GetHeight(), parser.GetStartFrame(), parser.GetEndFrame()); std::string filepath = dst_dir + "\\data_" + ee::SymbolFile::Instance()->Tag(s2::SYM_ANIMATION) + ".json"; libanim::FileSaver::Store(filepath, *sym); FixFontLayers(dst_dir); }
bool CModelMD3::LoadAnimations(LPSTR strConfigFile) { tAnimationInfo animations[MAX_ANIMATIONS] = {0}; ifstream fin(strConfigFile); if( fin.fail() ) { return false; } string strWord = ""; string strLine = ""; int currentAnim = 0; int torsoOffset = 0; while( fin >> strWord) { if(!isdigit( strWord[0] )) { getline(fin, strLine); continue; } int startFrame = atoi(strWord.c_str()); int numOfFrames = 0, loopingFrames = 0, framesPerSecond = 0; fin >> numOfFrames >> loopingFrames >> framesPerSecond; animations[currentAnim].startFrame = startFrame; animations[currentAnim].endFrame = startFrame + numOfFrames; animations[currentAnim].loopingFrames = loopingFrames; animations[currentAnim].framesPerSecond = framesPerSecond; fin >> strLine >> strLine; strcpy(animations[currentAnim].strName, strLine.c_str()); if(IsInString(strLine, "BOTH")) { m_Upper.pAnimations.push_back(animations[currentAnim]); m_Lower.pAnimations.push_back(animations[currentAnim]); } else if(IsInString(strLine, "TORSO")) { m_Upper.pAnimations.push_back(animations[currentAnim]); } else if(IsInString(strLine, "LEGS")) { if(!torsoOffset) torsoOffset = animations[LEGS_WALKCR].startFrame - animations[TORSO_GESTURE].startFrame; animations[currentAnim].startFrame -= torsoOffset; animations[currentAnim].endFrame -= torsoOffset; m_Lower.pAnimations.push_back(animations[currentAnim]); } currentAnim++; } m_Lower.numOfAnimations = m_Lower.pAnimations.size(); m_Upper.numOfAnimations = m_Upper.pAnimations.size(); m_Head.numOfAnimations = m_Head.pAnimations.size(); m_Weapon.numOfAnimations = m_Head.pAnimations.size(); return true; }
bool CConfig::Load() { const char* pFileName; pFileName = SERVER_CONFIG_FILE; if (NULL == pFileName) { return false; } ifstream fin(pFileName); if (!fin.is_open()) { return false; } string strLine; string strSection; string strName; string strValue; string::size_type begin = 0; string::size_type end = 0; while (!fin.eof()) { strLine.clear(); begin = end = 0; getline(fin, strLine, '\n'); if (strLine.empty() || strLine[0] == '\r' || strLine[0] == '\n' || strLine[0] == '#') { continue; } if (strLine[0] == '[') { end = strLine.find_first_of("]", begin); if (string::npos != end) { strSection = strLine.substr(begin+1, end-1); } continue; } if (!Parse(strLine, strName, strValue)) { continue; } if ("COMMON" == strSection) { if ("email_address" == strName) { m_strEmailAddress = strValue; m_strEmailAddress = replace_all_distinct(m_strEmailAddress, "/", " "); // printf("m_strEmailAddress:%s\r\n", m_strEmailAddress.c_str()); } else if("log_level" == strName){ m_wLogLevel = atoi(strValue.c_str()); } } else if ("WEB_SERVER_INFO" == strSection) { if ("svr_port" == strName) { m_wWebSvrPort = atoi(strValue.c_str()); } else if("web_ip" == strName) { m_dwWebIp = ntohl(inet_addr(strValue.c_str())); } else if ("web_port" == strName) { m_wWebPort = atoi(strValue.c_str()); } else if ("http_api_head" == strName) { m_strHttpApiHead = strValue; } else if ("http_api_url" == strName) { m_strHttpApiUrl = strValue; // printf("m_strHttpApiUrl:%s\r\n", strValue.c_str()); } } } fin.close(); return true; }
void ExportBodymovin::FixFontLayer(const std::string& filepath, const std::string& dir) { Json::Value val; Json::Reader reader; std::locale::global(std::locale("")); std::ifstream fin(filepath.c_str()); std::locale::global(std::locale("C")); reader.parse(fin, val); fin.close(); Json::Value dst_val; dst_val["fps"] = val["fps"]; dst_val["name"] = val["name"]; int IDX0 = 0; auto layer_name = gum::FilepathHelper::Filename(filepath.c_str()); layer_name = layer_name.substr(0, layer_name.size() - 10); bool dirty = false; for (int i = 0, n = val["layer"].size(); i < n; ++i) { const Json::Value& layer_val = val["layer"][i]; assert(layer_val.size() > 0 && layer_val["frame"].size() > 0); const Json::Value& frame_val = layer_val["frame"][IDX0]; assert(frame_val.size() > 0 && frame_val["actor"].size() > 0); const Json::Value& actor_val = frame_val["actor"][IDX0]; std::string filename = actor_val["filepath"].asString(); filename = gum::FilepathHelper::Filename(filename.c_str()).c_str(); int sz = dst_val["layer"].size(); dst_val["layer"][sz] = val["layer"][i]; if (filename.size() != 6 || filename[0] != '0' || filename.substr(2) != ".png") { continue; } auto t_sym = ee::SymbolFactory::Create(s2::SYM_TEXTBOX); s2::Textbox tb; tb.width = 200; tb.height = 200; tb.font_type = 0; tb.font_size = 40; tb.font_color = pt2::Color(0, 0, 0); tb.has_edge = false; tb.align_hori = s2::Textbox::HA_LEFT; tb.align_vert = s2::Textbox::VA_CENTER; std::dynamic_pointer_cast<etext::Symbol>(t_sym)->SetTextbox(tb); auto t_spr = ee::SpriteFactory::Instance()->Create(t_sym); t_spr->UpdateBounding(); auto text_spr = std::dynamic_pointer_cast<etext::Sprite>(t_spr); text_spr->SetExport(true); auto c_sym = ee::SymbolFactory::Create(s2::SYM_COMPLEX); std::dynamic_pointer_cast<ecomplex::Symbol>(c_sym)->Add(t_spr); CU_STR text_path = layer_name + "_" + gum::StringHelper::ToString(i) + "_text_complex.json"; c_sym->SetFilepath(dir + "\\" + std::string(text_path.c_str())); auto c_spr = ee::SpriteFactory::Instance()->Create(c_sym); c_spr->UpdateBounding(); ecomplex::FileStorer::Store(c_sym->GetFilepath(), *std::dynamic_pointer_cast<ecomplex::Symbol>(c_sym), dir, false); Json::Value new_layer = layer_val; for (int j = 0, m = new_layer["frame"].size(); j < m; ++j) { Json::Value& frame_val = new_layer["frame"][j]; assert(frame_val["actor"].size() == 1); const Json::Value& src_val = frame_val["actor"][IDX0]; ee::SpriteIO spr_io; spr_io.Load(src_val, dir.c_str()); sm::vec2 anchor = spr_io.m_position + spr_io.m_offset; spr_io.m_position = spr_io.m_position + sm::rotate_vector(-spr_io.m_offset, spr_io.m_angle) + spr_io.m_offset; spr_io.m_angle = 0; float scale = std::min(fabs(spr_io.m_scale.x), fabs(spr_io.m_scale.y)); spr_io.m_scale.x = scale; spr_io.m_scale.y = scale; spr_io.m_offset = anchor - spr_io.m_position; Json::Value dst_val; dst_val["filepath"] = text_path.c_str(); spr_io.Store(dst_val, dir.c_str()); frame_val["actor"][IDX0] = dst_val; } dst_val["layer"][sz + 1] = new_layer; dirty = true; } if (dirty) { Json::StyledStreamWriter writer; std::locale::global(std::locale("")); std::ofstream fout(filepath.c_str()); std::locale::global(std::locale("C")); writer.write(fout, dst_val); fout.close(); } }
int main(int argc, char *argv[]) { //QMultiHash<QString, StringPair> hashTable; QHash<QString, QSet<QString> > predictTable; QHash<StringPair, ulong> countTable; QVector<QString> tagsV; QHash<ulong, QVector<StringPair> > hashTb; tagsV.clear(); QFile fin(argv[1]); QTextStream out(stdout); QTextStream err(stderr); if (argc != 3) { out << "Usage: genhashtable dictfile.txt hashtablefile.txt" << endl; return 0; } if (!fin.open(QIODevice::ReadOnly | QIODevice::Text)) { err << "ERROR: input file not found" << endl; return 1; } QTextStream sfin(&fin); sfin.setCodec("UTF-8"); out.setCodec("UTF-8"); QString line = sfin.readLine(); QStringList lineParts; bool isfirst = false; QString form, normalForm, tags; while (!line.isNull()) { lineParts = line.split(QRegExp("[\t ]"), QString::SkipEmptyParts); if (isfirst) { if (!(lineParts.size() < 2 || lineParts[1].startsWith("VERB,") || lineParts[1].startsWith("PRTF,") || lineParts[1].startsWith("PRTS,") || lineParts[1].startsWith("GRND,"))) { normalForm = lineParts[0]; } isfirst = false; } if (lineParts.size() > 2 && lineParts[1].startsWith("INFN,")) { normalForm = lineParts[0]; } if (lineParts.size() < 1) { line = sfin.readLine(); continue; } if (lineParts.size() == 1) { isfirst = true; line = sfin.readLine(); continue; } form = lineParts[0]; QChar yo = QString::fromUtf8("Ё")[0]; QChar ye = QString::fromUtf8("Е")[0]; form.replace(yo, ye, Qt::CaseInsensitive); tags = lineParts[1]; if (lineParts.size() == 3) { tags += ("," + lineParts[2]); } if (tagsV.indexOf(tags) == -1) { tagsV.append(tags); } hashTb[tagsV.indexOf(tags)].append(StringPair(normalForm, form)); //hashTable.insert(form, StringPair(normalForm, tags)); predictTable[form.right(3)].insert(tags); ++countTable[StringPair(form.right(3), tags)]; line = sfin.readLine(); } fin.close(); //out << "Table size: " << hashTable.size() << endl; QString result(""); for (int i = 0; i < tagsV.size(); ++i) { result += ("& " + tagsV[i] + " "); for (int j = 0; j < hashTb[i].size(); ++j) { result += (hashTb[i][j].first + " " + hashTb[i][j].second + " "); } } result += "\n----------"; for (QHash<QString, QSet<QString> >::const_iterator itr = predictTable.begin(); itr != predictTable.end(); ++itr) { for (QSet<QString>::const_iterator jtr = itr.value().begin(); jtr != itr.value().end(); ++jtr) { result += (" " + itr.key() + " " + *jtr); } } result += "\n----------"; for (QHash<StringPair, ulong>::const_iterator itr = countTable.begin(); itr != countTable.end(); ++itr) { result += (" " + itr.key().first + " " + itr.key().second + " " + QString::number(itr.value())); } result += "\n----------"; QFile hashFile(argv[2]); hashFile.open(QIODevice::WriteOnly); QTextCodec *cp1251 = QTextCodec::codecForName("CP1251"); hashFile.write(qCompress(cp1251->fromUnicode(result))); hashFile.flush(); hashFile.close(); return 0; }
int main(int argc, char **argv) { if (argc != 6) { // 1 2 3 4 5 6 cout<<"Usage: "<<argv[0]<<" <win_size> <input normal.db (Use N/A to start without file)> <output normal.db> <trace> <schema_file>"<<endl; //if ( (argc == 2) && (string(argv[1]) == "-h") ) documentation(); exit(1); } int win_size = atoi(argv[1]); string in_db_file = argv[2]; string out_db_file = argv[3]; string trace = argv[4]; string schema_file = argv[5]; vector<int> sliding_win; // this is the regular sliding win that we use in pH vector<int> sliding_win2; // this is the resulting pattern vector<int> schema; // read in the schema file ifstream fin2(schema_file.c_str()); assert(fin2); char ch2; string line = ""; int numr; int max_schema_loc = 0; while (fin2.get(ch2)) { if( ch2 !='\n') line+= ch2; else // process the line { int idx1 = -1; int idx2 = line.find(","); while (idx2 != string::npos) { string str = line.substr(idx1 + 1, idx2 - idx1 - 1); numr = atoi(str.c_str()); if (numr > max_schema_loc) max_schema_loc = numr; schema.push_back(numr); idx1 = idx2; idx2 = line.find(",", idx1 + 1); } string str = line.substr(idx1 + 1); numr = atoi(str.c_str()); if (numr > max_schema_loc) max_schema_loc = numr; schema.push_back(numr); break; // once the first line is finished } } fin2.close(); //for (int i=0;i<schema.size();++i) //{ // cout<<schema.at(i)<<endl; //} if(max_schema_loc >= win_size) { cout<<"Error: Maximum schema location ("<<max_schema_loc<<") can't be larger than the window size ("<<win_size<<"). exitting..."<<endl; exit(1); } // we don't know how many system calls the application makes so start from a large number (like 400) //int normalDB[SYSCALL_COUNT][SYSCALL_COUNT][win_size]; //for (int i=0;i<SYSCALL_COUNT; ++i) // for (int j=0;j<SYSCALL_COUNT; ++j) // for (int k=0;k<win_size; ++k) // normalDB[i][j][k] = 0; // read in the existing normal db (if provided) int ***normalDB; normalDB = new int **[SYSCALL_COUNT]; for (int i=0;i<SYSCALL_COUNT; ++i) { normalDB[i] = new int *[SYSCALL_COUNT]; for (int j=0;j<SYSCALL_COUNT; ++j) { normalDB[i][j] = new int[win_size]; // no need to init over winsize (now we have schema len) but leave it like this for now } } if (in_db_file.find("N/A") == string::npos) { vector<int> col1; vector<int> col2; vector<int> col3; // read the normal db into a 2d array observing the max of last column (i.e. window_size) ifstream fin(in_db_file.c_str()); assert(fin); char ch; line = ""; string anomaly; while (fin.get(ch)) { if( ch !='\n') line+= ch; else // process the line { int idx1 = line.find(","); int idx2 = line.find(",", idx1 + 1); string part1 = line.substr(0, idx1); string part2 = line.substr(idx1 + 1, idx2-idx1-1); string part3 = line.substr(idx2 + 1); int p1 = atoi(part1.c_str()); int p2 = atoi(part2.c_str()); int p3 = atoi(part3.c_str()); col1.push_back(p1); col2.push_back(p2); col3.push_back(p3); //cout<<p1<<"---"<<p2<<"---"<<p3<<endl; line = ""; } } fin.close(); if( (col1.size() != col2.size()) || (col1.size() != col3.size()) ) { cout<<"Col vectors are not properly initialized..."<<endl; exit(1); } else { for (int i=0; i<col1.size();++i) { int x = col1.at(i); int y = col2.at(i); int z = col3.at(i); normalDB[x][y][z] = 1; } } } // Start working on the trace ifstream fin(trace.c_str()); assert(fin); char ch; line = ""; string anomaly; while (fin.get(ch)) { if( ch !='\n') line+= ch; else // process the line { int idx = line.find(" "); string part1 = line.substr(0, idx); string part2 = line.substr(idx + 1); int process_no = atoi(part1.c_str()); int syscall = atoi(part2.c_str()); //cout<<process_no<<"---"<<syscall<<endl; sliding_win.push_back(syscall); // now we have win_size syscalls in sliding window where the vector end is the most recent if (sliding_win.size() == win_size) { // create the sliding window2 sliding_win2.clear(); for (int i=0; i<schema.size(); ++i) { sliding_win2.push_back(sliding_win.at(schema.at(i))); } /* for (int i=0; i<sliding_win.size(); ++i) { cout<<sliding_win.at(i)<<" "; } cout<<endl; for (int i=0; i<sliding_win2.size(); ++i) { cout<<sliding_win2.at(i)<<" "; } cout<<endl; */ for (int i=0; i<sliding_win2.size() -1; ++i) { int x = sliding_win2.at(sliding_win2.size() - 1); int y = sliding_win2.at(i); int z = sliding_win2.size() - i - 1; normalDB[x][y][z] = 1; } } if (sliding_win.size() == win_size) sliding_win.erase(sliding_win.begin()); //cout<<sliding_win.size()<<endl; line = ""; } } fin.close(); // we have the normal db, write it to a file ofstream fout(out_db_file.c_str()); for (int i=0;i<SYSCALL_COUNT; ++i) for (int j=0;j<SYSCALL_COUNT; ++j) for (int k=0;k<win_size; ++k) if (normalDB[i][j][k] != 0) { fout<<i<<","<<j<<","<<k<<endl; } fout.close(); //deallocate array for (int i=0;i<SYSCALL_COUNT; ++i) { for (int j=0;j<SYSCALL_COUNT; ++j) { delete[] normalDB[i][j]; } delete[] normalDB[i]; } delete[] normalDB; }
void plotpidket(){ gStyle->SetOptTitle(0); gStyle->SetOptStat(0); gStyle->SetStripDecimals(0); float mpion = 0.13957; float mkaon = 0.49368; float mproton = 0.93827; float pt[13], ept[12], v2[13], ev2[13], sv2[13]; ifstream fin("run12dAu_fvtx0s_hadron_v2_0_5.txt"); for(int i=0; i<13; i++){ ept[i]=0; fin>>pt[i]>>v2[i]>>ev2[i]; } fin.close(); TGraphErrors *grhadron = new TGraphErrors(13, pt, v2, ept, ev2); ifstream fin("run12dAu_fvtx0s_pion_v2_0_5.txt"); for(int i=0; i<13; i++){ ept[i]=0; fin>>pt[i]>>v2[i]>>ev2[i]; pt[i]= sqrt(pt[i]**2+mpion**2)-mpion; pt[i] = pt[i]/2.0; v2[i] = v2[i]/2.0; ev2[i] = ev2[i]/2.0; } fin.close(); TGraphErrors *grpion = new TGraphErrors(13, pt, v2, ept, ev2); ifstream fin("run12dAu_fvtx0s_kaon_v2_0_5.txt"); for(int i=0; i<13; i++){ ept[i]=0; fin>>pt[i]>>v2[i]>>ev2[i]; pt[i]= sqrt(pt[i]**2+mkaon**2)-mkaon; pt[i] = pt[i]/2.0; v2[i] = v2[i]/2.0; ev2[i] = ev2[i]/2.0; } fin.close(); TGraphErrors *grkaon = new TGraphErrors(13, pt, v2, ept, ev2); ifstream fin2("run12dAu_fvtx0s_proton_v2_0_5.txt"); for(int i=0; i<13; i++){ pt[i]=0; fin2>>pt[i]>>v2[i]>>ev2[i]; pt[i]= sqrt(pt[i]**2+mproton**2)-mproton; pt[i] = pt[i]/3.0; v2[i] = v2[i]/3.0; ev2[i] = ev2[i]/3.0; cout<<pt[i]<<endl; } fin2.close(); TGraphErrors *grproton = new TGraphErrors(13, pt, v2, ept, ev2); c1=new TCanvas("c1","c1"); c1->SetFillColor(10); c1->cd(); TH1F *h = new TH1F("h","h",21, 0, 2.1); h->SetMinimum(-0.02); h->SetMaximum(0.18); h->SetMarkerStyle(20); h->SetMarkerSize(1.2); h->Draw(); h->GetYaxis()->SetTitleOffset(0.9); h->GetYaxis()->SetTitleSize(0.05); h->GetYaxis()->SetTitle("v_{2}/n_{q}"); h->GetXaxis()->SetTitle("KE_{T}/n_{q} (GeV)"); h->GetXaxis()->SetTitleSize(0.04); h->GetYaxis()->CenterTitle(kTRUE); h->GetXaxis()->CenterTitle(kTRUE); grkaon->SetMarkerStyle(21); grkaon->SetMarkerSize(1.2); grkaon->SetMarkerColor(6); grkaon->Draw("P"); grpion->SetMarkerStyle(20); grpion->SetMarkerSize(1.2); grpion->SetMarkerColor(2); grpion->Draw("P"); grproton->SetMarkerStyle(24); grproton->SetMarkerSize(1.2); grproton->SetMarkerColor(4); grproton->Draw("P"); TLegend *leg1 = new TLegend(0.60,0.58,0.90,0.88); leg1->SetFillColor(10); leg1->SetLineStyle(4000); leg1->SetLineColor(10); leg1->SetLineWidth(0.); leg1->SetTextSize(0.05); leg1->SetBorderSize(0); leg1->AddEntry(grpion,"0~5%",""); leg1->AddEntry(grpion,"pion","P"); leg1->AddEntry(grkaon,"kaon","P"); leg1->AddEntry(grproton,"proton","P"); leg1->Draw(); }
int genblast::blastn_results_parser(const char* filename) { char buffer[256], a_buffer[256], b_buffer[256], c_buffer[256]; char* token; int hit_count = 0; char query[64]; long query_length = 0; char subject[64]; ifstream fin(filename); while(fin.getline(buffer, 255)) { if(!strncmp(buffer, "Query=", 6)) { token = buffer + 7; strcpy(query, token); fin.getline(buffer, 255); if(!strncmp(buffer, "Length", 6)) { token = buffer + 7; query_length = atol(token); } else { fin.getline(buffer, 255); if(!strncmp(buffer, "Length", 6)) { token = buffer + 7; query_length = atol(token); } else cout << "Error - Query length missed\n"; } while(fin.getline(buffer, 255)) { if(!strncmp(buffer, "Subject", 7)) { token = strtok(buffer, " =(),\n\t\r"); // "Subject" token = strtok(NULL, " =(),\n\t\r"); strcpy(subject, token); fin.getline(buffer, 255); if(!strncmp(buffer, "Length", 6)) { token = buffer + 7; tmp.subject_length = atol(token); } else { fin.getline(buffer, 255); if(!strncmp(buffer, "Length", 6)) { token = buffer + 7; tmp.subject_length = atol(token); } } break; } } // Now get hits //hit_count = 0; while(fin.getline(buffer, 255)) { if(!strncmp(buffer, "*****", 5)) { // No hits //cout << "No hits\n"; } if(!strncmp(buffer, " Score", 6)) { fin.getline(buffer, 255); token = strtok(buffer, " =(),/\n\t\r"); // "Identities" token = strtok(NULL, " =(),/\n\t\r"); // identity tmp.identity = atoi(token); token = strtok(NULL, " =(),/\n\t\r"); // match length tmp.match_length = atoi(token); token = strtok(NULL, " =(),/%\n\t\r"); // score value tmp.percent_identity = atof(token); // Next line example:- Strand=Plus/Plus, Strand=Plus/Minus fin.getline(buffer, 255); // Blank line fin.getline(buffer, 255); // Next line - Eg: Query 43 GGCCCCTCGAGGCGGTTCGACGA 65 fin.getline(buffer, 255); strcpy(a_buffer, buffer); token = strtok(buffer, " =(),/\n\t\r"); // "Query" token = strtok(NULL, " =(),/\n\t\r"); // start location tmp.query_start_location = atoi(token); token = strtok(NULL, " =(),/\n\t\r"); // query_hit_sequence strcpy(tmp.query_hit_sequence, token); token = strtok(NULL, " =(),/%\n\t\r"); // end location tmp.query_end_location = atoi(token); // Eg: ||||| |||||| |||||||||| fin.getline(buffer, 255); strcpy(b_buffer, buffer); token = strtok(buffer, " =(),/\n\t\r"); strcpy(tmp.identity_sequence, token); // Eg: Sbjct 20307025 GGCCCGTCGAGGTGGTTCGACGA 20307003 fin.getline(buffer, 255); strcpy(c_buffer, buffer); token = strtok(buffer, " =(),/\n\t\r"); // "Sbjct" token = strtok(NULL, " =(),/\n\t\r"); // start location tmp.subject_start_location = atoi(token); token = strtok(NULL, " =(),/\n\t\r"); // query_hit_sequence strcpy(tmp.subject_hit_sequence, token); token = strtok(NULL, " =(),/%\n\t\r"); // end location tmp.subject_end_location = atoi(token); if(tmp.match_length > min_match_length && tmp.percent_identity > identity && tmp.query_end_location >= query_length - tail_loc) { hit_count++; if(report) { cout << a_buffer << endl; cout << b_buffer << endl; cout << c_buffer << endl << endl; } } if(tmp.match_length == min_match_length && tmp.percent_identity == 100 && tmp.query_end_location >= query_length - tail_loc) { hit_count++; if(report) { cout << a_buffer << endl; cout << b_buffer << endl; cout << c_buffer << endl << endl; } } /*if(tmp.identity > 8 && tmp.query_end_location >= query_length - 1) { hit_count++; if(report) { cout << a_buffer << endl; cout << b_buffer << endl; cout << c_buffer << endl << endl; } } */ } if(!strncmp(buffer, "Lambda", 6)) // End of record for sequence/chromosome { fin.getline(buffer, 255); // tokenise(" \t") buffer to get Lambda, K and H values break; } } //cout << "We have " << hit_count << " for " << subject << endl; hits_total = hit_count; } } return(1); }
void CodeConvert::load_from_file(){ ifstream fin("morse.txt"); if (!fin)//if fin didn't open { cout << "'morse.txt' file not found." << endl; return; } cout << "File successfully opened." << endl; /****************************************************************************************/ // NOTE: All the cout calls below are just for me, to make sure everything is storing correctly // We do not have to include them in the final version of the program /***********************************************************************************/ char key; string value; int item_count = 0; while (fin){ fin >> key; fin >> value; cout << key << "==>" << value << endl; Map[key] = value; //cout << Map[key] << endl; //fin.close(); //return; item_count++; } cout << "Stored '" << item_count << "' items succesfully"; cout << endl << endl; cout << "Showing map" << endl; cout << Map['a'] << endl << Map['b'] << endl << Map['c'] << endl << Map['d'] << endl << Map['e'] << endl << Map['f'] << endl << Map['g'] << endl << Map['h'] << endl << Map['i'] << endl << Map['j'] << endl << Map['k'] << endl << Map['l'] << endl << Map['m'] << endl << Map['n'] << endl << Map['o'] << endl << Map['p'] << endl << Map['q'] << endl << Map['r'] << endl << Map['s'] << endl << Map['t'] << endl << Map['u'] << endl << Map['v'] << endl << Map['w'] << endl << Map['x'] << endl << Map['y'] << endl << Map['z'] << endl; fin.close(); }
SymbolTable::SymbolTable(string file_name) { file = file_name; ifstream fin(file.c_str()); ofstream fout("data/symbol_table.txt"); Symbol symbol = Symbol(file); Table table[ symbol.GetCount() ]; string line; int count = 0; int level_max = 0; /*------temp save for table------*/ int level = 0; string symbol_name = ""; string type_name = ""; bool array_bool = false; bool function_bool = false; Origin(); while(getline(fin, line)) { istringstream fin_word(line); string word = ""; string remain = ""; int pos = 0; while(fin_word >> word) { while(word != "") { if((pos = Check(word)) != -1) { if(pos != 0) { remain = word.substr(pos); word = word.substr(0, pos); } else { remain = word.substr(pos + length(word)); word = word.substr(0, length(word)); } } /*-----save in table------*/ if( FindKeyWord(word) ) { type_name = word; } else { if(type_name != "") { if(word == ";" || word == "," || word == ")" || word == "=" || word == "(" || word == "[") { if(word == ";" || word == "," || word == ")" || word == "=") { array_bool = false; function_bool = false; } else if(word == "(") { level = 0; array_bool = false; function_bool = true; } else if(word == "[") { array_bool = true; function_bool = false; } table[count].Set(level, symbol_name, type_name, array_bool, function_bool); count = count + 1; type_name = ""; } else { symbol_name = word; } } } if(word == "{" || word == "(") { level = level + 1; } else if(word == ")") { level = level - 1; } if(level > level_max) { level_max = level; } /*------------------------*/ pos = 0; word = remain; remain = ""; } } } int level_temp = 0; while(level_temp <= level_max) { for(int i = 0; i < (sizeof(table)/sizeof(*table)); i++) { if(table[i].GetLevel() == level_temp) { if(table[i].GetLevel() == table[i - 1].GetLevel() + 1) { scope = scope + 1; } table[i].SetScope(scope); } } level_temp = level_temp + 1; } //sort table for(int i = 0; i < (sizeof(table)/sizeof(*table)); i++) { for(int j = i + 1; j < (sizeof(table)/sizeof(*table)); j++) { if(table[j].GetScope() < table[i].GetScope()) { Table temp = Table(); temp.Set(table[j].GetLevel(), table[j].GetSymbol(), table[j].GetType(), table[j].GetArray(), table[j].GetFunction()); temp.SetScope(table[j].GetScope()); for(int k = j; k >= i + 1; k--) { table[k].Set(table[k - 1].GetLevel(), table[k - 1].GetSymbol(), table[k - 1].GetType(), table[k - 1].GetArray(), table[k - 1].GetFunction()); table[k].SetScope(table[k - 1].GetScope()); } table[i].Set(temp.GetLevel(), temp.GetSymbol(), temp.GetType(), temp.GetArray(), temp.GetFunction()); table[i].SetScope(temp.GetScope()); } } } int temp = 0; for(int i = 0; i < (sizeof(table)/sizeof(*table)); i++) { if(temp != table[i].GetScope()) { temp = table[i].GetScope(); fout << endl; } fout << table[i].GetScope() << " "; fout << table[i].GetSymbol() << " "; fout << table[i].GetType() << " "; fout << (table[i].GetArray() ? "true" : "false") << " "; fout << (table[i].GetFunction() ? "true" : "false") << " "; fout << endl; } fin.close(); fout.close(); }
void ImageMesh::GetPixelInfo(std::string filename, int & xpixels, int & ypixels) { // For reporting possible error messages std::string error_message = ""; // A template for creating a temporary file. char temp_file[] = "file_command_output.XXXXXX"; // Use a do-loop so we can break out under various error conditions // while still cleaning up temporary files. Basically use goto // statements without actually using them. do { // mkstemp is not in namespace std for whatever reason... int fd = mkstemp(temp_file); // If mkstemp fails, we failed. if (fd == -1) { error_message = "Error creating temporary file in ImageMesh::buildMesh()"; break; } // Construct the command string std::ostringstream command; command << "file " << filename << " 2>/dev/null 1>" << temp_file; // Make the system call, catch the return code int exit_status = std::system(command.str().c_str()); // If the system command returned a non-zero status, we failed. if (exit_status != 0) { error_message = "Error calling 'file' command in ImageMesh::buildMesh()"; break; } // Open the file which contains the result of the system command std::ifstream fin(temp_file); // Read the contents of the output file into a string std::string command_result; std::getline(fin, command_result); // A regular expression which matches "NNN x NNN" , i.e. any number // of digits, a space, an 'x', a space, and any number of digits. // The parentheses define capture groups which are stored into the // xsize and ysize integers. // Here's an example string: // sixteenth_image001_cropped3_closing_298.png: PNG image data, 115 x 99, 16-bit/color RGB, non-interlaced xpixels = 0, ypixels = 0; pcrecpp::RE re("(\\d+) x (\\d+)"); re.PartialMatch(command_result, &xpixels, &ypixels); // Detect failure of the regex if ((xpixels==0) || (ypixels==0)) { error_message = "Regex failed to find a match in " + command_result; break; } } while (false); // Remove the temporary file. This will still work even if the file was never created... std::remove(temp_file); // Report and exit if there was an error if (error_message != "") mooseError(error_message); }
void Mesh_Obj::RawAttach() { if (this->is_Attached) return; else this->is_Attached = true; fstream fin(this->Dir, ios::in); if (!fin.is_open()) { fin.close(); cout << this->Dir << " :Obj Not Found!" << endl; exit(1); } else { cout << this->Dir << " :Obj Loading Now!" << endl; } fin.seekg(0, ios::end); size_t fileSize = fin.tellg(); fin.seekg(0); string source; source.assign(std::istreambuf_iterator<char>(fin), std::istreambuf_iterator<char>()); fin.close(); vector<vec3> VertexAttribTemp[texCoord + 1]; vector<GLuint> ElementArrayTemp; set<Vertex> VertexBuffer; set<Edge> EdgeTemp; glGenVertexArrays(1, VAO); glGenBuffers(4, VBO); glBindVertexArray(VAO[0]); stringstream objStream(source); while (!objStream.eof()) { string line; getline(objStream, line); stringstream lineStream(line); char numb; if (line.empty()) continue; switch (line.at(0)) { case 'v': switch (line.at(1)) { case ' ': float CoordData[3]; lineStream >> numb >> CoordData[0] >> CoordData[1] >> CoordData[2]; VertexAttribTemp[Coord].push_back(vec3(CoordData[0], CoordData[1], CoordData[2])); break; case 'n': float normalData[3]; lineStream >> numb >> numb >> normalData[0] >> normalData[1] >> normalData[2]; VertexAttribTemp[normalDir].push_back(vec3(normalData[0], normalData[1], normalData[2])); break; case 't': float texCoordData[3]; char numb; lineStream >> numb >> numb >> texCoordData[0] >> texCoordData[1] >> texCoordData[2]; VertexAttribTemp[texCoord].push_back(vec3(texCoordData[0], texCoordData[1], texCoordData[2])); break; default: break; } break; case 'f': lineStream >> numb; if (line.find("//") != line.npos) { for (int i = 0; i != 3; ++i) { unsigned PosTexNor[3]; lineStream >> PosTexNor[Coord] >> numb >> numb >> PosTexNor[normalDir]; for (int i = 0; i != 3; ++i) { PosTexNor[i]--; } ElementArrayTemp.push_back(PosTexNor[0]); VertexBuffer.insert(Vertex(VertexAttribTemp[Coord].at(PosTexNor[Coord]), VertexAttribTemp[normalDir].at(PosTexNor[normalDir]), vec3(0, 0, 0), PosTexNor[0])); } } else { for (int i = 0; i != 3; ++i) { unsigned PosTexNor[3]; lineStream >> PosTexNor[Coord] >> numb >> PosTexNor[texCoord] >> numb >> PosTexNor[normalDir]; for (int i = 0; i != 3; ++i) { PosTexNor[i]--; } ElementArrayTemp.push_back(PosTexNor[0]); VertexBuffer.insert(Vertex(VertexAttribTemp[Coord].at(PosTexNor[Coord]), VertexAttribTemp[normalDir].at(PosTexNor[normalDir]), VertexAttribTemp[texCoord].at(PosTexNor[texCoord]), PosTexNor[0])); } } break; default: break; } }
int main() { std::ifstream fin("input.txt"); std::stringstream buffer; buffer << fin.rdbuf(); std::string input = buffer.str(); fin.close(); std::string::const_iterator f,l; f=input.begin(); l=input.end(); std::string strip; bool ok; ok = qi::phrase_parse(f ,l , +qi::char_ ,"--" >> *(qi::char_ - qi::eol) >> qi::eol ,strip ); typedef std::string::const_iterator It; qi::rule<It> skip_ws_and_comments = qi::space | "--" >> *(qi::char_-qi::eol) >> qi::eol ; while(f!=l) { //parser<std::string::const_iterator, qi::rule<std::string::const_iterator> > p; parser<It, qi::rule<It> > p; try { expr result; ok = qi::phrase_parse(f ,l ,p >> ';' ,qi::space ,result); if (!ok) { std::cerr << "invalid input\n"; break; } else { std::cout << result << "\n\n\n"; } } catch (const qi::expectation_failure<std::string::const_iterator>& e) { std::cerr << "expectation_failure at '" << std::string(e.first, e.last) << "'" << std::endl; break; } } return 0; }
int main( int argc, char *argv[] ) { std::stringstream in; std::stringstream out; std::string filename; std::string header; char *gateway_var = getenv( "GATEWAY_INTERFACE" ); if( gateway_var == nullptr ) { // Expect a single filename for now. if( argc == 2 ) { filename = argv[1]; } else if( argc != 1 ) { std::cout << "Supply a filename to style or no arguments." << std::endl; exit( EXIT_FAILURE ); } if( filename.empty() ) { in << std::cin.rdbuf(); } else { std::ifstream fin( filename, std::ios::binary ); if( !fin.good() ) { std::cout << "Failed to open " << filename << std::endl; exit( EXIT_FAILURE ); } in << fin.rdbuf(); fin.close(); } } else { std::map<std::string, std::string> params; initializePost( params ); std::string data = params[ "data" ]; if( data.empty() ) { exit( -255 ); } in.str( data ); header = "Content-type: application/json\n\n"; } if( in.str().size() == 0 ) { std::cout << "Error, input empty." << std::endl; exit( EXIT_FAILURE ); } JsonOut jsout( out, true ); JsonIn jsin( in ); format( jsin, jsout ); out << std::endl; if( filename.empty() ) { std::cout << header; std::cout << out.str(); } else { std::string in_str = in.str(); #ifdef MSYS2 erase_char( in_str, '\r' ); #endif if( in_str == out.str() ) { std::cout << "Unformatted " << filename << std::endl; exit( EXIT_SUCCESS ); } else { std::ofstream fout( filename, std::ios::binary | std::ios::trunc ); fout << out.str(); fout.close(); std::cout << "Formatted " << filename << std::endl; exit( EXIT_FAILURE ); } } }
/*! Load, parse, and process a qdoc configuration file. This function is only called by the other load() function, but this one is recursive, i.e., it calls itself when it sees an \c{include} statement in the qdoc configuration file. */ void Config::load(Location location, const QString& fileName) { pushWorkingDir(QFileInfo(fileName).path()); QDir::setCurrent(QFileInfo(fileName).path()); QRegExp keySyntax(QLatin1String("\\w+(?:\\.\\w+)*")); #define SKIP_CHAR() \ do { \ location.advance(c); \ ++i; \ c = text.at(i); \ cc = c.unicode(); \ } while (0) #define SKIP_SPACES() \ while (c.isSpace() && cc != '\n') \ SKIP_CHAR() #define PUT_CHAR() \ word += c; \ SKIP_CHAR(); if (location.depth() > 16) location.fatal(tr("Too many nested includes")); QFile fin(fileName); if (!fin.open(QFile::ReadOnly | QFile::Text)) { if (!Config::installDir.isEmpty()) { int prefix = location.filePath().length() - location.fileName().length(); fin.setFileName(Config::installDir + "/" + fileName.right(fileName.length() - prefix)); } if (!fin.open(QFile::ReadOnly | QFile::Text)) location.fatal(tr("Cannot open file '%1': %2").arg(fileName).arg(fin.errorString())); } QTextStream stream(&fin); #ifndef QT_NO_TEXTCODEC stream.setCodec("UTF-8"); #endif QString text = stream.readAll(); text += QLatin1String("\n\n"); text += QLatin1Char('\0'); fin.close(); location.push(fileName); location.start(); int i = 0; QChar c = text.at(0); uint cc = c.unicode(); while (i < (int) text.length()) { if (cc == 0) { ++i; } else if (c.isSpace()) { SKIP_CHAR(); } else if (cc == '#') { do { SKIP_CHAR(); } while (cc != '\n'); } else if (isMetaKeyChar(c)) { Location keyLoc = location; bool plus = false; QString stringValue; QStringList rhsValues; QString word; bool inQuote = false; bool prevWordQuoted = true; bool metWord = false; MetaStack stack; do { stack.process(c, location); SKIP_CHAR(); } while (isMetaKeyChar(c)); QStringList keys = stack.getExpanded(location); SKIP_SPACES(); if (keys.count() == 1 && keys.first() == QLatin1String("include")) { QString includeFile; if (cc != '(') location.fatal(tr("Bad include syntax")); SKIP_CHAR(); SKIP_SPACES(); while (!c.isSpace() && cc != '#' && cc != ')') { if (cc == '$') { QString var; SKIP_CHAR(); while (c.isLetterOrNumber() || cc == '_') { var += c; SKIP_CHAR(); } if (!var.isEmpty()) { char *val = getenv(var.toLatin1().data()); if (val == 0) { location.fatal(tr("Environment variable '%1' undefined").arg(var)); } else { includeFile += QString::fromLatin1(val); } } } else { includeFile += c; SKIP_CHAR(); } } SKIP_SPACES(); if (cc != ')') location.fatal(tr("Bad include syntax")); SKIP_CHAR(); SKIP_SPACES(); if (cc != '#' && cc != '\n') location.fatal(tr("Trailing garbage")); /* Here is the recursive call. */ load(location, QFileInfo(QFileInfo(fileName).dir(), includeFile).filePath()); } else { /* It wasn't an include statement, so it's something else. We must see either '=' or '+=' next. If not, fatal error. */ if (cc == '+') { plus = true; SKIP_CHAR(); } if (cc != '=') location.fatal(tr("Expected '=' or '+=' after key")); SKIP_CHAR(); SKIP_SPACES(); for (;;) { if (cc == '\\') { int metaCharPos; SKIP_CHAR(); if (cc == '\n') { SKIP_CHAR(); } else if (cc > '0' && cc < '8') { word += QChar(c.digitValue()); SKIP_CHAR(); } else if ((metaCharPos = QString::fromLatin1("abfnrtv").indexOf(c)) != -1) { word += QLatin1Char("\a\b\f\n\r\t\v"[metaCharPos]); SKIP_CHAR(); } else { PUT_CHAR(); } } else if (c.isSpace() || cc == '#') { if (inQuote) { if (cc == '\n') location.fatal(tr("Unterminated string")); PUT_CHAR(); } else { if (!word.isEmpty()) { if (metWord) stringValue += QLatin1Char(' '); stringValue += word; #if 0 if (metWord) rhsValues << QString(" " + word); else #endif rhsValues << word; metWord = true; word.clear(); prevWordQuoted = false; } if (cc == '\n' || cc == '#') break; SKIP_SPACES(); } } else if (cc == '"') { if (inQuote) { if (!prevWordQuoted) stringValue += QLatin1Char(' '); stringValue += word; if (!word.isEmpty()) rhsValues << word; metWord = true; word.clear(); prevWordQuoted = true; } inQuote = !inQuote; SKIP_CHAR(); } else if (cc == '$') { QString var; SKIP_CHAR(); while (c.isLetterOrNumber() || cc == '_') { var += c; SKIP_CHAR(); } if (!var.isEmpty()) { char *val = getenv(var.toLatin1().data()); if (val == 0) { location.fatal(tr("Environment variable '%1' undefined").arg(var)); } else { word += QString::fromLatin1(val); } } } else { if (!inQuote && cc == '=') location.fatal(tr("Unexpected '='")); PUT_CHAR(); } } QStringList::ConstIterator key = keys.constBegin(); while (key != keys.constEnd()) { if (!keySyntax.exactMatch(*key)) keyLoc.fatal(tr("Invalid key '%1'").arg(*key)); ConfigVarMultimap::Iterator i; i = configVars_.insert(*key, ConfigVar(*key, rhsValues, QDir::currentPath(), keyLoc)); i.value().plus_ = plus; ++key; } } } else { location.fatal(tr("Unexpected character '%1' at beginning of line").arg(c)); } } popWorkingDir(); if (!workingDirs_.isEmpty()) QDir::setCurrent(workingDirs_.top()); }
/** Find out operating system name and version This method caches system information in m_osName, m_osVersion and m_osAlias. It requires m_unameInfo to be set prior to call. */ void SCXOSTypeInfo::Init() // private { m_osVersion = L""; m_osName = L"Unknown"; assert(m_unameIsValid); #if defined(hpux) || defined(sun) if (m_unameIsValid) { m_osName = StrFromUTF8(m_unameInfo.sysname); m_osVersion = StrFromUTF8(m_unameInfo.release); } #if defined(hpux) m_osAlias = L"HPUX"; m_osManufacturer = L"Hewlett-Packard Company"; #elif defined(sun) m_osAlias = L"Solaris"; m_osManufacturer = L"Oracle Corporation"; #endif #elif defined(aix) if (m_unameIsValid) { m_osName = StrFromUTF8(m_unameInfo.sysname); // To get "5.3" we must read "5" and "3" from different fields. string ver(m_unameInfo.version); ver.append("."); ver.append(m_unameInfo.release); m_osVersion = StrFromUTF8(ver); } m_osAlias = L"AIX"; m_osManufacturer = L"International Business Machines Corporation"; #elif defined(linux) vector<wstring> lines; SCXStream::NLFs nlfs; #if defined(PF_DISTRO_SUSE) static const string relFileName = "/etc/SuSE-release"; wifstream relfile(relFileName.c_str()); wstring version(L""); wstring patchlevel(L""); SCXStream::ReadAllLines(relfile, lines, nlfs); if (!lines.empty()) { m_osName = ExtractOSName(lines[0]); } // Set the Linux Caption (get first line of the /etc/SuSE-release file) m_linuxDistroCaption = lines[0]; if (0 == m_linuxDistroCaption.length()) { // Fallback - should not normally happen m_linuxDistroCaption = L"SuSE"; } // File contains one or more lines looking like this: // SUSE Linux Enterprise Server 10 (i586) // VERSION = 10 // PATCHLEVEL = 1 for (size_t i = 0; i<lines.size(); i++) { if (StrIsPrefix(StrTrim(lines[i]), L"VERSION", true)) { wstring::size_type n = lines[i].find_first_of(L"="); if (n != wstring::npos) { version = StrTrim(lines[i].substr(n+1)); } } else if (StrIsPrefix(StrTrim(lines[i]), L"PATCHLEVEL", true)) { wstring::size_type n = lines[i].find_first_of(L"="); if (n != wstring::npos) { patchlevel = StrTrim(lines[i].substr(n+1)); } } } if (version.length() > 0) { m_osVersion = version; if (patchlevel.length() > 0) { m_osVersion = version.append(L".").append(patchlevel); } } if (std::wstring::npos != m_osName.find(L"Desktop")) { m_osAlias = L"SLED"; } else { // Assume server. m_osAlias = L"SLES"; } m_osManufacturer = L"SUSE GmbH"; #elif defined(PF_DISTRO_REDHAT) static const string relFileName = "/etc/redhat-release"; wifstream relfile(relFileName.c_str()); SCXStream::ReadAllLines(relfile, lines, nlfs); if (!lines.empty()) { m_osName = ExtractOSName(lines[0]); } // Set the Linux Caption (get first line of the /etc/redhat-release file) m_linuxDistroCaption = lines[0]; if (0 == m_linuxDistroCaption.length()) { // Fallback - should not normally happen m_linuxDistroCaption = L"Red Hat"; } // File should contain one line that looks like this: // Red Hat Enterprise Linux Server release 5.1 (Tikanga) if (lines.size() > 0) { wstring::size_type n = lines[0].find_first_of(L"0123456789"); if (n != wstring::npos) { wstring::size_type n2 = lines[0].substr(n).find_first_of(L" \t\n\t"); m_osVersion = StrTrim(lines[0].substr(n,n2)); } } if ((std::wstring::npos != m_osName.find(L"Client")) // RHED5 || (std::wstring::npos != m_osName.find(L"Desktop"))) // RHED4 { m_osAlias = L"RHED"; } else { // Assume server. m_osAlias = L"RHEL"; } m_osManufacturer = L"Red Hat, Inc."; #elif defined(PF_DISTRO_ULINUX) // The release file is created at agent start time by init.d startup script // This is done to insure that we can write to the appropriate directory at // the time (since, at agent run-time, we may not have root privileges). // // If we CAN create the file here (if we're running as root), then we'll // do so here. But in the normal case, this shouldn't be necessary. Only // in "weird" cases (i.e. starting omiserver by hand, for example). // Create the release file by running GetLinuxOS.sh script // (if we have root privileges) try { if ( !SCXFile::Exists(m_deps->getReleasePath()) && SCXFile::Exists(m_deps->getScriptPath()) && m_deps->isReleasePathWritable() ) { std::istringstream in; std::ostringstream out; std::ostringstream err; int ret = SCXCoreLib::SCXProcess::Run(m_deps->getScriptPath().c_str(), in, out, err, 10000); if ( ret || out.str().length() || err.str().length() ) { wostringstream sout; sout << L"Unexpected errors running script: " << m_deps->getScriptPath().c_str() << L", return code: " << ret << L", stdout: " << StrFromUTF8(out.str()) << L", stderr: " << StrFromUTF8(err.str()); SCX_LOGERROR(m_log, sout.str() ); } } } catch(SCXCoreLib::SCXInterruptedProcessException &e) { wstring msg; msg = L"Timeout running script \"" + m_deps->getScriptPath() + L"\", " + e.Where() + L'.'; SCX_LOGERROR(m_log, msg ); }; // Look in release file for O/S information string sFile = StrToUTF8(m_deps->getReleasePath()); wifstream fin(sFile.c_str()); SCXStream::ReadAllLines(fin, lines, nlfs); if (!lines.empty()) { ExtractToken(L"OSName", lines, m_osName); ExtractToken(L"OSVersion", lines, m_osVersion); ExtractToken(L"OSFullName", lines, m_linuxDistroCaption); ExtractToken(L"OSAlias", lines, m_osAlias); ExtractToken(L"OSManufacturer", lines, m_osManufacturer); } else { m_osAlias = L"Universal"; } // Behavior for m_osCompatName (method GetOSName) should be as follows: // PostInstall scripts will first look for SCX-RELEASE file (only on universal kits) // If found, add "ORIGINAL_KIT_TYPE=Universal" to scxconfig.conf file, // else add "ORIGINAL_KIT_TYPE=!Universal" to scxconfig.conf file. // After that is set up, the SCX-RELEASE file is created. // // A RHEL system should of OSAlias of "RHEL, SLES system should have "SuSE" (in scx-release) // // We need to mimic return values for RHEL and SLES on universal kits that did not // have a universal kit installed previously, but only for RHEL and SLES kits. In // all other cases, continue to return "Linux Distribution". wstring configFilename(m_deps->getConfigPath()); SCXConfigFile configFile(configFilename); try { configFile.LoadConfig(); } catch(SCXFilePathNotFoundException &e) { // Something's whacky with postinstall, so we can't follow algorithm static SCXCoreLib::LogSuppressor suppressor(SCXCoreLib::eError, SCXCoreLib::eTrace); wstring logMessage(L"Unable to load configuration file " + configFilename); SCX_LOG(m_log, suppressor.GetSeverity(logMessage), logMessage); m_osCompatName = L"Unknown Linux Distribution"; } if ( m_osCompatName.empty() ) { wstring kitType; if ( configFile.GetValue(L"ORIGINAL_KIT_TYPE", kitType) ) { if ( L"!Universal" == kitType ) { if ( L"RHEL" == m_osAlias ) { m_osCompatName = L"Red Hat Distribution"; } else if ( L"SLES" == m_osAlias ) { m_osCompatName = L"SuSE Distribution"; } } } if ( m_osCompatName.empty() ) { m_osCompatName = L"Linux Distribution"; } } #else #error "Linux Platform not supported"; #endif #elif defined(macos) m_osAlias = L"MacOS"; m_osManufacturer = L"Apple Inc."; if (m_unameIsValid) { // MacOS is called "Darwin" in uname info, so we hard-code here m_osName = L"Mac OS"; // This value we could read dynamically from the xml file // /System/Library/CoreServices/SystemVersion.plist, but that // file may be named differently based on client/server, and // reading the plist file would require framework stuff. // // Rather than using the plist, we'll use Gestalt, which is an // API designed to figure out versions of anything and everything. // Note that use of Gestalt requires the use of framework stuff // as well, so the Makefiles for MacOS are modified for that. SInt32 major, minor, bugfix; if (0 != Gestalt(gestaltSystemVersionMajor, &major) || 0 != Gestalt(gestaltSystemVersionMinor, &minor) || 0 != Gestalt(gestaltSystemVersionBugFix, &bugfix)) { throw SCXCoreLib::SCXErrnoException(L"Gestalt", errno, SCXSRCLOCATION); } wostringstream sout; sout << major << L"." << minor << L"." << bugfix; m_osVersion = sout.str(); } #else #error "Platform not supported" #endif }
int main(int argc, const char* argv[]) { if (argc < 1) { showUseage(); return 0; } const char* pszInputFileName = NULL; const char* pszOutputFileName = NULL; for (int i=1; i<argc; i++) { if (_stricmp(argv[i], "-i")==0 && i+1<argc) { pszInputFileName = argv[i+1]; i++; } else if (_stricmp(argv[i], "-o")==0 && i+1<argc) { pszOutputFileName = argv[i+1]; i++; } } if (pszInputFileName==NULL || pszOutputFileName==NULL) { showUseage(); return 0; } std::ifstream fin(pszInputFileName); std::ofstream fout(pszOutputFileName); if (!fin.is_open()) { std::cout << "Error(" << errno << ") can't open " << pszInputFileName << std::endl; return -1; } if (!fout.is_open()) { std::cout << "Error(" << errno << ") can't open " << pszOutputFileName << std::endl; return -2; } time_t tBegin = time(NULL); std::string line; unsigned long long idx = 0; while ( getline( fin, line)) { MD5_CTX ctx = {0}; MD5_Init(&ctx); MD5_Update(&ctx, line.c_str(), line.size()); unsigned char digest[16] = {0}; MD5_Final(digest, &ctx); char szMd5[32] = {0}; digest2String(digest, szMd5); #if 0 std::cout << "[" << idx << "]"; std::cout << " MD5("; std::cout << line.c_str(); std::cout << ")= " << szMd5 << std::endl; #endif fout << line << "\t\t" << szMd5 << std::endl; idx++; } fin.close(); fout.close(); time_t tEnd = time(NULL); unsigned int tCost = tEnd - tBegin; std::cout << "cal " << idx << "md5s cost" << tCost << " seconds" << std::endl; return 0; }
void GrdPlugin::findMinMaxandGenerateHistogram() { float rSize; float rMin; m_histogram.clear(); if (m_voxelType == _UChar || m_voxelType == _Char) { if (m_voxelType == _UChar) rMin = 0; if (m_voxelType == _Char) rMin = -127; rSize = 255; for(uint i=0; i<256; i++) m_histogram.append(0); } else if (m_voxelType == _UShort || m_voxelType == _Short) { if (m_voxelType == _UShort) rMin = 0; if (m_voxelType == _Short) rMin = -32767; rSize = 65535; for(uint i=0; i<65536; i++) m_histogram.append(0); } else { QMessageBox::information(0, "Error", "Why am i here ???"); return; } // //================== // // do not calculate histogram // if (m_voxelType == _UChar) // { // m_rawMin = 0; // m_rawMax = 255; // return; // } // //================== int nbytes = m_width*m_height*m_bytesPerVoxel; uchar *tmp = new uchar[nbytes]; m_rawMin = 10000000; m_rawMax = -10000000; QProgressDialog progress("Generating Histogram", 0, 0, 100, 0); progress.setMinimumDuration(0); for(uint i=0; i<m_depth; i++) { progress.setValue((int)(100.0*(float)i/(float)m_depth)); qApp->processEvents(); //---------------------------- QFile fin(m_imageList[i]); fin.open(QFile::ReadOnly); fin.seek(m_headerBytes); fin.read((char*)tmp, nbytes); fin.close(); //---------------------------- if (m_voxelType == _UChar) { uchar *ptr = tmp; MINMAXANDHISTOGRAM(); } else if (m_voxelType == _Char) { char *ptr = (char*) tmp; MINMAXANDHISTOGRAM(); } if (m_voxelType == _UShort) { ushort *ptr = (ushort*) tmp; MINMAXANDHISTOGRAM(); } else if (m_voxelType == _Short) { short *ptr = (short*) tmp; MINMAXANDHISTOGRAM(); } else if (m_voxelType == _Int) { int *ptr = (int*) tmp; MINMAXANDHISTOGRAM(); } else if (m_voxelType == _Float) { float *ptr = (float*) tmp; MINMAXANDHISTOGRAM(); } } delete [] tmp; // while(m_histogram.last() == 0) // m_histogram.removeLast(); // while(m_histogram.first() == 0) // m_histogram.removeFirst(); progress.setValue(100); qApp->processEvents(); }
void SummaryJudge(string infile,string infile2) //语法分析(总) { string filename=infile; sets* x=CreateSets(filename); charset* NotEnd=new charset; //终结符&非终结符 NotEnd->c='$'; NotEnd->next=NULL; charset* End=new charset; End->c='$'; End->next=NULL; CreateCharset(NotEnd,End,x); //终结符&非终结符初始化 firstnode* FirstSet=new firstnode; //First集定义 FirstSet->cur='@'; FirstSet->cs=NULL; FirstSet->next=NULL; firstnode* FollowSet=new firstnode; //Follow集定义 FollowSet->cur='@'; FollowSet->cs=NULL; FollowSet->next=NULL; InitFiFo(FirstSet,FollowSet,filename,x,NotEnd); //First集、Follow集初始化 charset* se=NotEnd->next; //输出First、Follow集 printf("\n First集 : \n"); //输出状态至控制台,可注释 firstnode* fff=FirstSet->next; while(fff) { se=fff->cs->next; printf("\nCurrnet First Start:%c\n",fff->cur); while(se) { printf("%c,",se->c); se=se->next; } printf("\n"); fff=fff->next; } printf("\n Follow集 : \n"); //输出状态至控制台,可注释 fff=FollowSet->next; while(fff) { se=fff->cs->next; printf("\nCurrent Follow Start:%c\n",fff->cur); while(se) { printf("%c,",se->c); se=se->next; } printf("\n"); fff=fff->next; } firstnode* SelectSet=new firstnode; //Select集定义 SelectSet->cur='@'; SelectSet->cs=NULL; SelectSet->next=NULL; InitSelect(SelectSet,x,FirstSet,FollowSet,NotEnd); //建立Select集 tablenode* Table=new tablenode; //定义预测分析表表头 Table->ne='@'; Table->by='@'; Table->to=NULL; Table->next=NULL; CreateTable(Table,SelectSet,x); //建立预测分析表 ifstream fin(infile2,std::ios::in); string s1=" "; while(getline(fin,s1)) { printf("\n待识别串: %s\n",s1.c_str()); //输出状态至控制台,可注释 if(AnalysisString(s1,Table,NotEnd)) //分析字串 printf("\n--Yes!!!--\n"); else printf("\n--No!!!--\n"); } fin.clear(); fin.close(); }
void GrdPlugin::generateHistogram() { QProgressDialog progress("Generating Histogram", "Cancel", 0, 100, 0); progress.setMinimumDuration(0); float rSize = m_rawMax-m_rawMin; int nbytes = m_width*m_height*m_bytesPerVoxel; uchar *tmp = new uchar[nbytes]; QFile fin(m_fileName[0]); fin.open(QFile::ReadOnly); fin.seek(m_headerBytes); m_histogram.clear(); if (m_voxelType == _UChar || m_voxelType == _Char || m_voxelType == _UShort || m_voxelType == _Short) { for(uint i=0; i<rSize+1; i++) m_histogram.append(0); } else { for(uint i=0; i<65536; i++) m_histogram.append(0); } int histogramSize = m_histogram.size()-1; for(uint i=0; i<m_depth; i++) { progress.setValue((int)(100.0*(float)i/(float)m_depth)); qApp->processEvents(); //---------------------------- QFile fin(m_imageList[i]); fin.open(QFile::ReadOnly); fin.seek(m_headerBytes); fin.read((char*)tmp, nbytes); fin.close(); //---------------------------- if (m_voxelType == _UChar) { uchar *ptr = tmp; GENHISTOGRAM(); } else if (m_voxelType == _Char) { char *ptr = (char*) tmp; GENHISTOGRAM(); } if (m_voxelType == _UShort) { ushort *ptr = (ushort*) tmp; GENHISTOGRAM(); } else if (m_voxelType == _Short) { short *ptr = (short*) tmp; GENHISTOGRAM(); } else if (m_voxelType == _Int) { int *ptr = (int*) tmp; GENHISTOGRAM(); } else if (m_voxelType == _Float) { float *ptr = (float*) tmp; GENHISTOGRAM(); } } fin.close(); delete [] tmp; // while(m_histogram.last() == 0) // m_histogram.removeLast(); // while(m_histogram.first() == 0) // m_histogram.removeFirst(); // QMessageBox::information(0, "", QString("%1 %2 : %3").\ // arg(m_rawMin).arg(m_rawMax).arg(rSize)); progress.setValue(100); qApp->processEvents(); }
int MainWindow::RadiosondeEquipmentConverter( const QString &s_FilenameIn, QStringList &sl_FilenameOut, structMethod *Method_ptr, structStation *Station_ptr, const int i_NumOfFiles ) { int i_Year = 2000; int i_Month = 1; int i_Day = 1; int i_StationNumber = 0; int i_MethodID = 0; QString InputStr = ""; QString s_RadiosondeIdentification = ""; QString SearchString1 = "*C0005"; QString SearchString2 = "*U0005"; QString s_StationName = ""; QString s_EventLabel = ""; unsigned int ui_length = 1; unsigned int ui_filesize = 1; bool b_Stop = false; // *********************************************************************************************************************** QFileInfo fi( s_FilenameIn ); if ( ( fi.exists() == false ) || ( fi.suffix().toLower() == "zip" ) || ( fi.suffix().toLower() == "gz" ) ) return( _FILENOEXISTS_ ); // *********************************************************************************************************************** QFile fin( s_FilenameIn ); if ( fin.open( QIODevice::ReadOnly | QIODevice::Text ) == false ) return( -10 ); ui_filesize = fin.size(); // *********************************************************************************************************************** QTextStream tin( &fin ); // *********************************************************************************************************************** initProgress( i_NumOfFiles, s_FilenameIn, tr( "Radiosonde equipment converter working ..." ), 100 ); // *********************************************************************************************************************** InputStr = tin.readLine(); ui_length = incProgress( i_NumOfFiles, ui_filesize, ui_length, InputStr ); if ( ( InputStr.startsWith( "*C0001" ) == false ) && ( InputStr.startsWith( "*U0001" ) == false ) ) { resetProgress( i_NumOfFiles ); fin.close(); return( -40 ); } // *********************************************************************************************************************** InputStr = tin.readLine(); ui_length = incProgress( i_NumOfFiles, ui_filesize, ui_length, InputStr ); i_StationNumber = InputStr.left( 3 ).toInt(); s_StationName = findStationName( i_StationNumber, Station_ptr ); s_EventLabel = findEventLabel( i_StationNumber, Station_ptr ); // *********************************************************************************************************************** i_Day = 1; i_Month = InputStr.mid( 4, 2 ).toInt(); i_Year = InputStr.mid( 7, 4 ).toInt(); QDateTime dt = QDateTime().toUTC(); dt.setDate( QDate( i_Year, i_Month, i_Day ) ); dt.setTime( QTime( 0, 0, 0 ) ); // *********************************************************************************************************************** if ( checkFilename( fi.fileName(), s_EventLabel, InputStr.mid( 4, 2 ), InputStr.mid( 9, 2 ) ) == false ) { resetProgress( i_NumOfFiles ); fin.close(); return( -41 ); } // *********************************************************************************************************************** QFile fout( fi.absolutePath() + "/" + s_EventLabel + "_" + dt.toString( "yyyy-MM" ) + "_0005.txt" ); if ( fout.open( QIODevice::WriteOnly | QIODevice::Text ) == false ) { resetProgress( i_NumOfFiles ); fin.close(); return( -20 ); } QTextStream tout( &fout ); appendItem( sl_FilenameOut, fout.fileName() ); // *********************************************************************************************************************** // LR0005 tout << "File name\tStation ID\tEvent label\tStation\tYYYY-MM\t"; tout << "Manufacturer\tLocation\tDistance from radiation site [km]\t"; tout << "Time of 1st launch [hh]\tTime of 2nd launch [hh]\tTime of 3rd launch [hh]\t"; tout << "Time of 4th launch [hh]\tIdentification of radiosonde\tRemarks\t"; tout << "PANGAEA method\tPANGAEA method ID" << endl; while ( ( tin.atEnd() == false ) && ( ui_length != (unsigned int) _APPBREAK_ ) && ( b_Stop == false ) ) { InputStr = tin.readLine(); ui_length = incProgress( i_NumOfFiles, ui_filesize, ui_length, InputStr ); if ( ( InputStr.startsWith( SearchString1 ) == true ) || ( InputStr.startsWith( SearchString2 ) == true ) ) { tout << s_EventLabel.toLower() << dt.toString( "MMyy" ) << ".dat" << "\t"; tout << i_StationNumber << "\t" << s_EventLabel << "\t" << s_StationName << "\t" << dt.toString( "yyyy-MM" ) << "\t"; InputStr = tin.readLine(); ui_length = incProgress( i_NumOfFiles, ui_filesize, ui_length, InputStr ); if ( InputStr.simplified().right( 1 ) == "Y" ) { InputStr = tin.readLine(); ui_length = incProgress( i_NumOfFiles, ui_filesize, ui_length, InputStr ); tout << InputStr.left( 30 ).simplified() << "\t"; tout << InputStr.mid( 30, 25 ).simplified() << "\t"; tout << InputStr.mid( 57, 3 ) << "\t"; tout << InputStr.mid( 61, 2 ) << "\t"; tout << InputStr.mid( 64, 2 ) << "\t"; tout << InputStr.mid( 67, 2 ) << "\t"; tout << InputStr.mid( 70, 2 ) << "\t"; tout << InputStr.mid( 73, 5 ).simplified() << "\t"; s_RadiosondeIdentification = InputStr.left( 30 ).simplified(); if ( InputStr.mid( 73, 5 ).simplified().isEmpty() == false ) s_RadiosondeIdentification += ", " + InputStr.mid( 73, 5 ).simplified(); i_MethodID = findMethodID( s_RadiosondeIdentification, Method_ptr ); InputStr = tin.readLine(); ui_length = incProgress( i_NumOfFiles, ui_filesize, ui_length, InputStr ); tout << InputStr.simplified() << "\t" << "Radiosonde, " << s_RadiosondeIdentification << "\t"; tout << i_MethodID << endl; } b_Stop = true; } // Abort if first data record reached if ( ( InputStr.startsWith( "*C0100" ) == true ) || ( InputStr.startsWith( "*U0100" ) == true ) ) b_Stop = true; } //--------------------------------------------------------------------------------------------------- resetProgress( i_NumOfFiles ); fin.close(); fout.close(); if ( ui_length == (unsigned int) _APPBREAK_ ) return( _APPBREAK_ ); return( _NOERROR_ ); }
void TrainingDataRenderer::loadTrainingData(const std::string& filename, bool labels) { std::string delimiter = "\t"; std::ifstream fin(filename.c_str()); std::string line; // std::cout << " good()=" << fin.good(); // std::cout << " eof()=" << fin.eof(); // std::cout << " fail()=" << fin.fail(); // std::cout << " bad()=" << fin.bad() << std::endl; if(fin.fail()) { std::cout << "Failed to open " << filename << std::endl; } std::vector< std::vector<float> > data; while(std::getline(fin, line)) { line = rtrim(line); std::vector<std::string> elems; SplitString(line, delimiter.c_str()[0], elems); std::vector<float> positions_row; for(std::string s : elems) { float f = std::stof(s); positions_row.push_back(f); } data.push_back(positions_row); } if(labels == false) { _positions.clear(); for(std::vector<float>& row : data) { if(row.size() % 3 == 0) { std::vector<vec3> p_row; for(unsigned int i = 0; i < row.size(); i+=3) { vec3 p(row[i], row[i+1], row[i+2]); p_row.push_back(p); } _positions.push_back(p_row); } } } else { _labels.clear(); for(std::vector<float>& row : data) { if(row.size() % 3 == 0) { for(unsigned int i = 0; i < row.size(); i+=3) { vec3 p(row[i], row[i+1], row[i+2]); _labels.push_back(p); } } } } }
void solver(const string samp_file, const double theta, const int num_iter, const int probes) { int number_of_nodes, len_samp; ifstream fin(samp_file + ".stat"); fin >> number_of_nodes >> len_samp; fin.close(); vector<double> p(number_of_nodes, 1.0/number_of_nodes); //uniform schedule vector<double> cost(num_iter, 0); vector<clock_t> iteration_time(num_iter); int k, u; double pS, tmp; ofstream fout_p(samp_file+ "_probes-" + to_string(probes) + ".p"); for (int r=0; r < num_iter; ++r) { // saving the schedule: for (double d : p) { fout_p << d << "\t"; } fout_p << endl; clock_t round_time = clock(); fin.open(samp_file); vector<double> W(number_of_nodes, 0); while (fin >> k) { pS = 0; deque<int> S; // TODO: check if it gets new everytime for (int i=0; i<k; ++i) { fin >> u; pS += p[u]; S.push_back(u); } tmp = 1.0/(1 - theta*pow(1-pS,probes)); cost[r] += tmp; // update W: tmp = pow(tmp,2)*pow(1-pS,probes-1); for (int v : S) { W[v] += tmp; } } fin.close(); cost[r] /= len_samp; update(p, W); iteration_time[r] = clock()-round_time; } fout_p.close(); ofstream fout_conv(samp_file + "_probes-" + to_string(probes) + ".conv"); for (double c : cost) fout_conv << c << "\t"; fout_conv << endl; for (clock_t t : iteration_time) fout_conv << t << "\t"; fout_conv << endl; fout_conv.close(); }