std::string parseKeyValue(std::stringstream& stream, std::unique_ptr<DataIO::Node>& node, const std::string& key) { // Read the assignment symbol from the stream and remove the whitespace behind it char chr; stream.read(&chr, 1); REMOVE_WHITESPACE_AND_COMMENTS(true) // Check for subsection as value if (stream.peek() == '{') return parseSection(stream, node, key); // Read the value std::string line = trim(readLine(stream)); if (!line.empty()) { // Remove the ';' if it is there if (stream.peek() == ';') stream.read(&chr, 1); // Create a value node to store the value auto valueNode = std::make_unique<DataIO::ValueNode>(); valueNode->value = line; // It might be a list node if ((line.size() >= 2) && (line[0] == '[') && (line.back() == ']')) { valueNode->listNode = true; if (line.size() >= 3) { valueNode->valueList.push_back(""); std::size_t i = 1; while (i < line.size()-1) { if (line[i] == ',') { i++; valueNode->valueList.back() = trim(valueNode->valueList.back()); valueNode->valueList.push_back(""); } else if (line[i] == '"') { valueNode->valueList.back().insert(valueNode->valueList.back().getSize(), line[i]); i++; bool backslash = false; while (i < line.size()-1) { valueNode->valueList.back().insert(valueNode->valueList.back().getSize(), line[i]); if (line[i] == '"' && !backslash) { i++; break; } if (line[i] == '\\' && !backslash) backslash = true; else backslash = false; i++; } } else { valueNode->valueList.back().insert(valueNode->valueList.back().getSize(), line[i]); i++; } } valueNode->valueList.back() = trim(valueNode->valueList.back()); } } node->propertyValuePairs[toLower(key)] = std::move(valueNode); return ""; } else { if (stream.peek() == EOF) return "Found EOF while trying to read a value."; else { chr = stream.peek(); if (chr == '=') return "Found '=' while trying to read a value."; else if (chr == '{') return "Found '{' while trying to read a value."; else return "Found empty value."; } } }
void App::setViewer(const std::string& newFilename) { logPrintf("App::setViewer(\"%s\")\n", filename.c_str()); drawMessage("Loading " + newFilename); filename = newFilename; CFrame cframe(Vector3(0,8,15)); cframe.lookAt(Point3::zero()); m_debugCamera->setFrame(cframe); m_debugController->setFrame(m_debugCamera->frame()); //modelController->setFrame(CoordinateFrame(Matrix3::fromAxisAngle(Vector3(0,1,0), toRadians(180)))); delete viewer; viewer = NULL; if (filename == "<events>") { viewer = new EventViewer(); } else { std::string ext = toLower(filenameExt(filename)); std::string base = toLower(filenameBase(filename)); if ((ext == "3ds") || (ext == "ifs") || (ext == "obj") || (ext == "ply2") || (ext == "off") || (ext == "ply") || (ext == "bsp") || (ext == "stl") || (ext == "stla") || (ext == "dae") || (ext == "fbx") || ((ext == "any" && endsWith(base, ".am")) || (ext == "any" && endsWith(base, ".articulatedmodel")))) { showDebugText = false; viewer = new ArticulatedViewer(); } else if (Texture::isSupportedImage(filename)) { // Images can be either a Texture or a Sky, TextureViewer will figure it out viewer = new TextureViewer(); // Angle the camera slightly so a sky/cube map doesn't see only 1 face m_debugController->setFrame(Matrix3::fromAxisAngle(Vector3::unitY(), (float)halfPi() / 2.0f) * Matrix3::fromAxisAngle(Vector3::unitX(), (float)halfPi() / 2.0f)); } else if (ext == "fnt") { viewer = new FontViewer(debugFont); /* } else if (ext == "bsp") { viewer = new BSPViewer(); */ } else if (ext == "md2") { viewer = new MD2Viewer(); } else if (ext == "md3") { viewer = new MD3Viewer(); } else if (ext == "gtm") { viewer = new GUIViewer(this); } else if (ext == "icn") { viewer = new IconSetViewer(debugFont); } else if (ext == "pk3") { // Something in Quake format - figure out what we should load Array <std::string> files; bool set = false; // First, try for a .bsp map std::string search = filename + "/maps/*"; FileSystem::getFiles(search, files, true); for (int t = 0; t < files.length(); ++t) { if (filenameExt(files[t]) == "bsp") { filename = files[t]; viewer = new ArticulatedViewer(); // viewer = new BSPViewer(); set = true; } } if (! set) { viewer = new EmptyViewer(); } } else if (ext == "avi" || ext == "wmv" || ext == "mp4" || ext == "asf" || (ext == "mov") || (ext == "dv") || (ext == "qt") || (ext == "asf") || (ext == "mpg")) { viewer = new VideoViewer(); } else { viewer = new EmptyViewer(); } } if (viewer != NULL) { viewer->onInit(filename); } if (filename != "") { if (filename == "<events>") { window()->setCaption("Events - G3D Viewer"); } else { window()->setCaption(filenameBaseExt(filename) + " - G3D Viewer"); } } logPrintf("Done App::setViewer(...)\n"); }
void String8::toLower() { toLower(0, size()); }
str FITSattach(Client cntxt, MalBlkPtr mb, MalStkPtr stk, InstrPtr pci) { mvc *m = NULL; sql_trans *tr; sql_schema *sch; sql_table *fits_tp, *fits_fl, *fits_tbl, *fits_col, *tbl = NULL; sql_column *col; str msg = MAL_SUCCEED; str fname = *getArgReference_str(stk, pci, 1); fitsfile *fptr; /* pointer to the FITS file */ int status = 0, i, j, hdutype, hdunum = 1, cnum = 0, bitpixnumber = 0; oid fid, tid, cid, rid = oid_nil; char tname[BUFSIZ], *tname_low = NULL, *s, bname[BUFSIZ], stmt[BUFSIZ]; long tbcol; /* type long used by fits library */ char cname[BUFSIZ], tform[BUFSIZ], tunit[BUFSIZ], tnull[BUFSIZ], tdisp[BUFSIZ]; double tscal, tzero; char xtensionname[BUFSIZ] = "", stilversion[BUFSIZ] = ""; char stilclass[BUFSIZ] = "", tdate[BUFSIZ] = "", orig[BUFSIZ] = "", comm[BUFSIZ] = ""; if ((msg = getSQLContext(cntxt, mb, &m, NULL)) != MAL_SUCCEED) return msg; if ((msg = checkSQLContext(cntxt)) != MAL_SUCCEED) return msg; if (fits_open_file(&fptr, fname, READONLY, &status)) { msg = createException(MAL, "fits.attach", "Missing FITS file %s.\n", fname); return msg; } tr = m->session->tr; sch = mvc_bind_schema(m, "sys"); fits_fl = mvc_bind_table(m, sch, "fits_files"); if (fits_fl == NULL) FITSinitCatalog(m); fits_fl = mvc_bind_table(m, sch, "fits_files"); fits_tbl = mvc_bind_table(m, sch, "fits_tables"); fits_col = mvc_bind_table(m, sch, "fits_columns"); fits_tp = mvc_bind_table(m, sch, "fits_table_properties"); /* check if the file is already attached */ col = mvc_bind_column(m, fits_fl, "name"); rid = table_funcs.column_find_row(m->session->tr, col, fname, NULL); if (rid != oid_nil) { fits_close_file(fptr, &status); msg = createException(SQL, "fits.attach", "File %s already attached\n", fname); return msg; } /* add row in the fits_files catalog table */ col = mvc_bind_column(m, fits_fl, "id"); fid = store_funcs.count_col(tr, col, 1) + 1; store_funcs.append_col(m->session->tr, mvc_bind_column(m, fits_fl, "id"), &fid, TYPE_int); store_funcs.append_col(m->session->tr, mvc_bind_column(m, fits_fl, "name"), fname, TYPE_str); col = mvc_bind_column(m, fits_tbl, "id"); tid = store_funcs.count_col(tr, col, 1) + 1; if ((s = strrchr(fname, DIR_SEP)) == NULL) s = fname; else s++; strcpy(bname, s); s = strrchr(bname, '.'); if (s) *s = 0; fits_get_num_hdus(fptr, &hdunum, &status); for (i = 1; i <= hdunum; i++) { fits_movabs_hdu(fptr, i, &hdutype, &status); if (hdutype != ASCII_TBL && hdutype != BINARY_TBL) continue; /* SQL table name - the name of FITS extention */ fits_read_key(fptr, TSTRING, "EXTNAME", tname, NULL, &status); if (status) { snprintf(tname, BUFSIZ, "%s_%d", bname, i); tname_low = toLower(tname); status = 0; }else { /* check table name for existence in the fits catalog */ tname_low = toLower(tname); col = mvc_bind_column(m, fits_tbl, "name"); rid = table_funcs.column_find_row(m->session->tr, col, tname_low, NULL); /* or as regular SQL table */ tbl = mvc_bind_table(m, sch, tname_low); if (rid != oid_nil || tbl) { snprintf(tname, BUFSIZ, "%s_%d", bname, i); tname_low = toLower(tname); } } fits_read_key(fptr, TSTRING, "BITPIX", &bitpixnumber, NULL, &status); if (status) { status = 0; } fits_read_key(fptr, TSTRING, "DATE-HDU", tdate, NULL, &status); if (status) { status = 0; } fits_read_key(fptr, TSTRING, "XTENSION", xtensionname, NULL, &status); if (status) { status = 0; } fits_read_key(fptr, TSTRING, "STILVERS", stilversion, NULL, &status); if (status) { status = 0; } fits_read_key(fptr, TSTRING, "STILCLAS", stilclass, NULL, &status); if (status) { status = 0; } fits_read_key(fptr, TSTRING, "ORIGIN", orig, NULL, &status); if (status) { status = 0; } fits_read_key(fptr, TSTRING, "COMMENT", comm, NULL, &status); if (status) { status = 0; } fits_get_num_cols(fptr, &cnum, &status); store_funcs.append_col(m->session->tr, mvc_bind_column(m, fits_tbl, "id"), &tid, TYPE_int); store_funcs.append_col(m->session->tr, mvc_bind_column(m, fits_tbl, "name"), tname_low, TYPE_str); store_funcs.append_col(m->session->tr, mvc_bind_column(m, fits_tbl, "columns"), &cnum, TYPE_int); store_funcs.append_col(m->session->tr, mvc_bind_column(m, fits_tbl, "file_id"), &fid, TYPE_int); store_funcs.append_col(m->session->tr, mvc_bind_column(m, fits_tbl, "hdu"), &i, TYPE_int); store_funcs.append_col(m->session->tr, mvc_bind_column(m, fits_tbl, "date"), tdate, TYPE_str); store_funcs.append_col(m->session->tr, mvc_bind_column(m, fits_tbl, "origin"), orig, TYPE_str); store_funcs.append_col(m->session->tr, mvc_bind_column(m, fits_tbl, "comment"), comm, TYPE_str); store_funcs.append_col(m->session->tr, mvc_bind_column(m, fits_tp, "table_id"), &tid, TYPE_int); store_funcs.append_col(m->session->tr, mvc_bind_column(m, fits_tp, "xtension"), xtensionname, TYPE_str); store_funcs.append_col(m->session->tr, mvc_bind_column(m, fits_tp, "bitpix"), &bitpixnumber, TYPE_int); store_funcs.append_col(m->session->tr, mvc_bind_column(m, fits_tp, "stilvers"), stilversion, TYPE_str); store_funcs.append_col(m->session->tr, mvc_bind_column(m, fits_tp, "stilclas"), stilclass, TYPE_str); /* read columns description */ s = stmt; col = mvc_bind_column(m, fits_col, "id"); cid = store_funcs.count_col(tr, col, 1) + 1; for (j = 1; j <= cnum; j++, cid++) { fits_get_acolparms(fptr, j, cname, &tbcol, tunit, tform, &tscal, &tzero, tnull, tdisp, &status); snprintf(stmt, BUFSIZ, FITS_INS_COL, (int)cid, cname, tform, tunit, j, (int)tid); msg = SQLstatementIntern(cntxt, &s, "fits.attach", TRUE, FALSE, NULL); if (msg != MAL_SUCCEED) { fits_close_file(fptr, &status); return msg; } } tid++; } fits_close_file(fptr, &status); return MAL_SUCCEED; }
bool filter_lib::load_filters(string fitsfile,int logflag){ std::unique_ptr<CCfits::FITS> pInfile; try{ pInfile.reset(new CCfits::FITS(fitsfile,CCfits::Read,true)); } catch(...){ printf("Error reading FITS file %s\n",fitsfile.c_str()); exit(1); } CCfits::HDU& head = pInfile->pHDU(); CCfits::ExtHDU& filters = pInfile->extension(1); int ntcols = filters.numCols(); if(ntcols != 6){ printf("Wrong number of filters included (need 3):"); exit(1); } vector<double> band; vector<double> transmission; double units[] = {1.0,1.0,1.0}; long tablelength = filters.rows(); string bands[] = {"BAND_1","BAND_2","BAND_3"}; string unitKeys[] = {"UNITS1","UNITS2","UNITS3"}; string limitKeys[] = {"LIMIT1","LIMIT2","LIMIT3"}; string errorKeys[] = {"ERROR1","ERROR2","ERROR3"}; string serrorKeys[] = {"SERROR1","SERROR2","SERROR3"}; for(int i=0;i<3;i++){ //reading units, defaults to units in mJy try{ string stemp; head.readKey(unitKeys[i],stemp); if(toLower(stemp) == "jy"){ units[i]=1e3; } else if(toLower(stemp) == "mjy"){ units[i]=1.0; } else if(toLower(stemp) == "ujy"){ units[i]=1e-3; } else{ LOG_CRITICAL(printf("Keyword \"%s\" contains unknown unit, defaulting to standard units mJy\n",unitKeys[i].c_str())); } } catch(...){ LOG_CRITICAL(printf("Error reading keyword \"%s\", defaulting to standard units mJy\n",unitKeys[i].c_str())); } //reading flux limits, converting units try{ head.readKey(limitKeys[i],limits[i]); if(limits[i]<0){ LOG_CRITICAL(printf("Warning: keyword \"%s\" contains negative value, defaulting to standard value 0\n",limitKeys[i].c_str())); limits[i]=0.0; } else limits[i]*=units[i]; } catch(...){ printf("Error reading keyword \"%s\"\n",limitKeys[i].c_str()); exit(10); } //reading errors, converting units try{ head.readKey(errorKeys[i],errors[i]); //if(errors[i]<0){ // LOG_CRITICAL(printf("Warning: keyword \"%s\" contains negative value, defaulting to standard value 0\n",errorKeys[i].c_str())); // errors[i]=0.0; //} //else errors[i]*=units[i]; } catch(...){ printf("Error reading keyword \"%s\"\n",errorKeys[i].c_str()); exit(10); } //reading skew errors, converting units try{ head.readKey(serrorKeys[i],skew_errors[i]); if(skew_errors[i]<0){ LOG_CRITICAL(printf("Warning: keyword \"%s\" contains negative value, defaulting to standard value 0\n",serrorKeys[i].c_str())); skew_errors[i]=0.0; } else skew_errors[i]*=units[i]; } catch(...){ printf("Error reading keyword \"%s\"\n",serrorKeys[i].c_str()); exit(10); } } double scale = -10; try{ double dtemp; filters.readKey("LSCALE", dtemp); scale = dtemp; } catch(...){ LOG_CRITICAL(printf("Error reading keyword \"LSCALE\", defaulting to Angstroms\n")); } double exp_scale = pow(10,scale); double nullvalue=-1; for(int i=1;i<7;i+=2){ filters.column(i).read(band,1,tablelength,&nullvalue); filters.column(i+1).read(transmission,1,tablelength); int num = floor(i/2); if(band.back() <= 0.0){ while(band.back() <= 0.0){ band.pop_back(); transmission.pop_back(); } } for(unsigned int j=0;j<band.size();j++){ band[j]*=exp_scale; } LOG_INFO(printf("Loaded Filter %i (Lambda: %8.2e m -> %8.2e m, limit: %5.2e, error: %5.2e, skew error: %5.2e)\n",num+1,band.front(),band.back(),limits[num],errors[num],skew_errors[num])); if(not this->filters[num].load(bands[num],band,transmission,logflag) ){ printf("Error loading filter %i from %s, exiting\n",i,fitsfile.c_str()); exit(1); } } initialized = true; return true; }
bool Burmese::processPhoneticInput() { wchar_t burglishData[BGLEN]={0}; int idx=0;bool isPatsint=false; bool bufferFull=false; this->clearPhoneticMenuData(); //clear all wcscpy(burglishData,charBuff); if (len(burglishData)<1) return false; for(int i=0; i<BCLEN;i++){ //loop for consonent if(bufferFull) break; if(burglishData[0]>65 && burglishData[0]<65+26){ isPatsint = true; burglishData[0]=burglishData[0]+32; } if(wcsstr(burglishData, _bc[i].key)==burglishData){ //find "m" in "man", ==burglishData means find at firstpos :P for(int i1=0; i1<4;i1++){ //loop for sub items if(bufferFull) break; if(_bc[i].val[i1]==0) break; // if no more sub items break it wchar_t burmeseData[BMLEN]={0}; if(cmp(L"a",burglishData)!=0) //only done when it is start with "a" sub(burmeseData,burglishData,_bc[i].key, L""); //copy non-consonent part in displayData else wcscpy(burmeseData,burglishData); if(len(burmeseData)==0) wcscpy(burmeseData,L"a");//if only type consonent, append "a" for(int j=0; j<BVLEN;j++){ //loop for vowel if(bufferFull) break; if(wcscmp(burmeseData, _bv[j].key)==0){ // match "an" for(int j1=0; j1<10;j1++){ //loop for sub items if(_bv[j].val[j1]==0) break; // if no more sub items break it wchar_t displayData[BMLEN]={0}; if(isPatsint){ wcscpy(burglishData,_bc[i].val[i1]); burglishData[0]=toLower(burglishData[0]); sub(burmeseData,_bv[j].val[j1],L"$1", burglishData); wcscpy(displayData,L"---"); }else{ sub(burmeseData,_bv[j].val[j1],L"$1", _bc[i].val[i1]); //replace "in" with burmese "a sat", displayData is reused } wcscat(displayData,burmeseData); //copying data into menu array wcscpy(menuItem[idx/MROW][idx%MROW].burglish,burglishData); wcscpy(menuItem[idx/MROW][idx%MROW].burmese,burmeseData); if((idx++)>=MLEN) { bufferFull=true; break; } } } } } } } menuLength=idx; this->processCustomDictionary(); this->processPhoneticMenuAutoCorrect(); #ifndef _TEST LPVOID lpOut; lpOut = VirtualAlloc(NULL, 20, MEM_COMMIT, PAGE_READWRITE); for(int Row = 0; Row < MROW; Row++) { for(int Col = 0; Col < MCOL; Col++) { if( wcslen(menuItem[Col][Row].burmese) <= 0) break; wcscpy((wchar_t*)lpOut,menuItem[Col][Row].burmese); lpOut = DoSourceReplace(lpOut,20,Zawgyi_One,curFontIndex); LiveConvert(Zawgyi_One,curFontIndex,(wchar_t*)lpOut); lpOut = replace(L"\u103B\u102B",L"\u102B\u103A",(wchar_t*)lpOut,10, curFontIndex); wcscpy(menuItem[Col][Row].burmese,(wchar_t*)lpOut); } } #endif return menuLength>0; };
bool AutoResponse::processMsg(std::string msg, uint16_t whatModule, std::string nick, std::string ownNick, std::vector<std::string>& out) { bool ok = false; toLower(msg); std::vector<ConfigHandler::AutoResponseRule>::iterator it; ConfigHandler::AutoResponseRule r; for(it = _rules->begin(); it != _rules->end(); it++) { r = *it; //std::cout << "AutoResponse::processMsgRetroShare() rule " << r.name << std::endl; // check if rule applies to retroshare //std::cout << "AutoResponse::processMsgRetroShare() usedBy=" << r.usedBy << " mod=" << whatModule << std::endl; if(!Utils::isModuleAll(r.usedBy) && !(r.usedBy & whatModule)) continue; //std::cout << "AutoResponse::processMsgRetroShare() rule " << r.name << " applies" << std::endl; { std::string tmpNick = ownNick; toLower(tmpNick); ApplyReplacements(r.searchFor, nick, tmpNick); } std::size_t pos = msg.find(r.searchFor); //std::cout << "AutoResponse::processMsgRetroShare() find()=" << pos << " found" << std::endl; //std::cout << "AutoResponse::processMsgRetroShare() msg=" << msg << " searchFor=" << r.searchFor << std::endl; // check if keyword is in the message at all if(pos == std::string::npos) continue; //std::cout << "AutoResponse::processMsgRetroShare() key word " << r.searchFor << " found" << std::endl; // check for leading character if(r.hasLeadingChar && (pos == 0 || msg[pos-1] != r.leadingChar)) continue; //std::cout << "AutoResponse::processMsgRetroShare() leading char check passed" << std::endl; // FYI: at this point we know that the key word is in the message at position pos // and that the leading character - if required - is ok // check for context if(!r.allowContext && ( // no context is allowed (msg.size() > r.searchFor.size() && !r.hasLeadingChar) || // msg == key word (msg.size() > r.searchFor.size() + 1 && r.hasLeadingChar) // msg == key word + 1 char )) continue; // "/me bla" is ok - "/mebla" not -> check if there is space around the key word(s) if(r.isSeparated && ( (msg.size() > pos + r.searchFor.size() && msg[pos + r.searchFor.size()] != ' ') || // after the key word(s) (r.hasLeadingChar && pos > 1 && msg[pos - 2] != ' ') || // before with leading chat (!r.hasLeadingChar && pos > 0 && msg[pos - 1] != ' '))) // before withou leading char continue; //std::cout << "AutoResponse::processMsgRetroShare() context check passed" << std::endl; // all seems good std::string ans = r.answer; ApplyReplacements(ans, nick, ownNick); if(whatModule == Utils::MODULE_IRC) fixNewLineForIrc(ans); out.push_back(ans); ok = true; } return ok; }
ObjModel::ObjModel(std::string fileName, Singleton* s): s(s) { xpos = ypos = zpos = xrot = yrot = zrot = 0; this->obj = this; if(fileName == ""){ return; } std::string dirName = fileName; if (dirName.rfind("/") != std::string::npos) dirName = dirName.substr(0, dirName.rfind("/")); if (dirName.rfind("\\") != std::string::npos) dirName = dirName.substr(0, dirName.rfind("\\")); if (fileName == dirName) dirName = ""; std::ifstream pFile(fileName.c_str()); if (!pFile.is_open()) { //std::cout << "Could not open file " << fileName << std::endl; return; } ObjGroup *currentGroup = new ObjGroup(); currentGroup->materialIndex = -1; while (!pFile.eof()) { std::string line; std::getline(pFile, line); line = replace(line, "\t", " "); while (line.find(" ") != std::string::npos) line = replace(line, " ", " "); if (line == "") continue; if (line[0] == ' ') line = line.substr(1); if (line == "") continue; if (line[line.length() - 1] == ' ') line = line.substr(0, line.length() - 1); if (line == "") continue; if (line[0] == '#') continue; std::vector<std::string> params = split(line, " "); params[0] = toLower(params[0]); if (params[0] == "v") vertices.push_back(new Vec3f((float) atof(params[1].c_str()), (float) atof(params[2].c_str()), (float) atof(params[3].c_str()))); else if (params[0] == "vn") normals.push_back(new Vec3f((float) atof(params[1].c_str()), (float) atof(params[2].c_str()), (float) atof(params[3].c_str()))); else if (params[0] == "vt") texcoords.push_back(new Vec2f((float) atof(params[1].c_str()), (float) atof(params[2].c_str()))); else if (params[0] == "f") { for (size_t ii = 4; ii <= params.size(); ii++) { Face face; for (size_t i = ii - 3; i < ii; i++) //magische forlus om van quads triangles te maken ;) { Vertex vertex; std::vector<std::string> indices = split(params[i == (ii - 3) ? 1 : i], "/"); if (indices.size() >= 1) //er is een positie vertex.position = atoi(indices[0].c_str()) - 1; if (indices.size() == 2) //alleen texture vertex.texcoord = atoi(indices[1].c_str()) - 1; if (indices.size() == 3) //v/t/n of v//n { if (indices[1] != "") vertex.texcoord = atoi(indices[1].c_str()) - 1; vertex.normal = atoi(indices[2].c_str()) - 1; } face.vertices.push_back(vertex); } currentGroup->faces.push_back(face); } } else if (params[0] == "s") {//smoothing } else if (params[0] == "mtllib") { loadMaterialFile(dirName + "/" + params[1], dirName); } else if (params[0] == "usemtl") { if (currentGroup->faces.size() != 0) groups.push_back(currentGroup); currentGroup = new ObjGroup(); currentGroup->materialIndex = -1; for (size_t i = 0; i < materials.size(); i++) { MaterialInfo *info = materials[i]; if (info->name == params[1]) { currentGroup->materialIndex = i; break; } } if (currentGroup->materialIndex == -1) { //std::cout << "Could not find material name " << params[1] << std::endl; } } } groups.push_back(currentGroup); CalcMinVertex(); CalcMaxVertex(); InitBoundingSpheres(); CalcBoundingSpheres(); }
static void cAnimGender(int argc, char **argv) { // 'F','f' -> female, 'N','n' -> neutral, other - male if (argc < 2) return; gci->modelGender = toLower(argv[1][0]); }
static int run(int argc, char **argv) { static const MeCab::Option long_options[] = { { "dicdir", 'd', ".", "DIR", "set DIR as dicdir(default \".\" )" }, { "outdir", 'o', ".", "DIR", "set DIR as output dir" }, { "model", 'm', 0, "FILE", "use FILE as model file" }, { "version", 'v', 0, 0, "show the version and exit" }, { "training-algorithm", 'a', "crf", "(crf|hmm)", "set training algorithm" }, { "default-emission-cost", 'E', "4000", "INT", "set default emission cost for HMM" }, { "default-transition-cost", 'T', "4000", "INT", "set default transition cost for HMM" }, { "help", 'h', 0, 0, "show this help and exit." }, { 0, 0, 0, 0 } }; Param param; if (!param.open(argc, argv, long_options)) { std::cout << param.what() << "\n\n" << COPYRIGHT << "\ntry '--help' for more information." << std::endl; return -1; } if (!param.help_version()) return 0; ContextID cid; DecoderFeatureIndex fi; DictionaryRewriter rewrite; const std::string dicdir = param.get<std::string>("dicdir"); const std::string outdir = param.get<std::string>("outdir"); const std::string model = param.get<std::string>("model"); #define DCONF(file) create_filename(dicdir, std::string(file)).c_str() #define OCONF(file) create_filename(outdir, std::string(file)).c_str() CHECK_DIE(param.load(DCONF(DICRC))) << "no such file or directory: " << DCONF(DICRC); std::string charset; { Dictionary dic; CHECK_DIE(dic.open(DCONF(SYS_DIC_FILE), "r")); charset = dic.charset(); CHECK_DIE(!charset.empty()); } int default_emission_cost = 0; int default_transition_cost = 0; std::string type = param.get<std::string>("training-algorithm"); toLower(&type); if (type == "hmm") { default_emission_cost = param.get<int>("default-emission-cost"); default_transition_cost = param.get<int>("default-transition-cost"); CHECK_DIE(default_transition_cost > 0) << "default transition cost must be > 0"; CHECK_DIE(default_emission_cost > 0) << "default transition cost must be > 0"; param.set("identity-template", 1); } CharProperty property; CHECK_DIE(property.open(param)); property.set_charset(charset.c_str()); const std::string bos = param.get<std::string>("bos-feature"); const int factor = param.get<int>("cost-factor"); std::vector<std::string> dic; enum_csv_dictionaries(dicdir.c_str(), &dic); { CHECK_DIE(dicdir != outdir) << "output directory = dictionary directory! " "Please specify different directory."; CHECK_DIE(!outdir.empty()) << "output directory is empty"; CHECK_DIE(!model.empty()) << "model file is empty"; CHECK_DIE(fi.open(param)) << fi.what(); CHECK_DIE(factor > 0) << "cost factor needs to be positive value"; CHECK_DIE(!bos.empty()) << "bos-feature is empty"; CHECK_DIE(dic.size()) << "no dictionary is found in " << dicdir; CHECK_DIE(rewrite.open(DCONF(REWRITE_FILE))); } gencid_bos(bos, &rewrite, &cid); gencid(DCONF(UNK_DEF_FILE), &rewrite, &cid); for (std::vector<std::string>::const_iterator it = dic.begin(); it != dic.end(); ++it) { gencid(it->c_str(), &rewrite, &cid); } std::cout << "emitting " << OCONF(LEFT_ID_FILE) << "/ " << OCONF(RIGHT_ID_FILE) << std::endl; cid.build(); cid.save(OCONF(LEFT_ID_FILE), OCONF(RIGHT_ID_FILE)); gendic(DCONF(UNK_DEF_FILE), OCONF(UNK_DEF_FILE), property, &rewrite, cid, &fi, true, factor, default_emission_cost); for (std::vector<std::string>::const_iterator it = dic.begin(); it != dic.end(); ++it) { std::string file = *it; remove_pathname(&file); gendic(it->c_str(), OCONF(file.c_str()), property, &rewrite, cid, &fi, false, factor, default_emission_cost); } genmatrix(OCONF(MATRIX_DEF_FILE), cid, &fi, factor, default_transition_cost); copy(DCONF(CHAR_PROPERTY_DEF_FILE), OCONF(CHAR_PROPERTY_DEF_FILE)); copy(DCONF(REWRITE_FILE), OCONF(REWRITE_FILE)); copy(DCONF(DICRC), OCONF(DICRC)); if (type == "crf") copy(DCONF(FEATURE_FILE), OCONF(FEATURE_FILE)); #undef OCONF #undef DCONF std::cout << "\ndone!\n"; return 0; }
bool TestCase::hasTag( std::string const& tag ) const { return tags.find( toLower( tag ) ) != tags.end(); }
void CSheetId::loadSheetId () { H_AUTO(CSheetIdInit); //nldebug("Loading sheet_id.bin"); // Open the sheet id to sheet file name association CIFile file; std::string path = CPath::lookup("sheet_id.bin", false, false); if(!path.empty() && file.open(path)) { // clear entries _FileExtensions.clear (); _SheetIdToName.clear (); _SheetNameToId.clear (); // reserve space for the vector of file extensions _FileExtensions.resize(1 << (NL_SHEET_ID_TYPE_BITS)); // Get the map from the file map<uint32,string> tempMap; contReset(tempMap); file.serialCont(tempMap); file.close(); if (_RemoveUnknownSheet) { uint32 removednbfiles = 0; uint32 nbfiles = (uint32)tempMap.size(); // now we remove all files that not available map<uint32,string>::iterator itStr2; for( itStr2 = tempMap.begin(); itStr2 != tempMap.end(); ) { if (CPath::exists ((*itStr2).second)) { ++itStr2; } else { map<uint32,string>::iterator olditStr = itStr2; //nldebug ("Removing file '%s' from CSheetId because the file not exists", (*olditStr).second.c_str ()); itStr2++; tempMap.erase (olditStr); removednbfiles++; } } nlinfo ("SHEETID: Removed %d files on %d from CSheetId because these files doesn't exists", removednbfiles, nbfiles); } // Convert the map to one big string and 1 static map (id to name) { // Get the number and size of all strings vector<CChar> tempVec; // Used to initialise the first map uint32 nNb = 0; uint32 nSize = 0; map<uint32,string>::const_iterator it = tempMap.begin(); while (it != tempMap.end()) { nSize += (uint32)it->second.size()+1; nNb++; it++; } // Make the big string (composed of all strings) and a vector referencing each string tempVec.resize(nNb); _AllStrings.Ptr = new char[nSize]; it = tempMap.begin(); nSize = 0; nNb = 0; while (it != tempMap.end()) { tempVec[nNb].Ptr = _AllStrings.Ptr+nSize; strcpy(_AllStrings.Ptr+nSize, it->second.c_str()); toLower(_AllStrings.Ptr+nSize); nSize += (uint32)it->second.size()+1; nNb++; it++; } // Finally build the static map (id to name) _SheetIdToName.reserve(tempVec.size()); it = tempMap.begin(); nNb = 0; while (it != tempMap.end()) { _SheetIdToName.add(pair<uint32, CChar>(it->first, CChar(tempVec[nNb]))); nNb++; it++; } // The vector of all small string is not needed anymore we have all the info in // the static map and with the pointer AllStrings referencing the beginning. } // Build the invert map (Name to Id) & file extension vector { uint32 nSize = (uint32)_SheetIdToName.size(); _SheetNameToId.reserve(nSize); CStaticMap<uint32,CChar>::iterator itStr; for( itStr = _SheetIdToName.begin(); itStr != _SheetIdToName.end(); ++itStr ) { // add entry to the inverse map _SheetNameToId.add( make_pair((*itStr).second, (*itStr).first) ); // work out the type value for this entry in the map TSheetId sheetId; sheetId.Id=(*itStr).first; uint32 type = sheetId.IdInfos.Type; // check whether we need to add an entry to the file extensions vector if (_FileExtensions[type].empty()) { // find the file extension part of the given file name _FileExtensions[type] = toLower(CFile::getExtension((*itStr).second.Ptr)); } nSize--; } _SheetNameToId.endAdd(); } } else { nlerror("<CSheetId::init> Can't open the file sheet_id.bin"); } nldebug("Finished loading sheet_id.bin: %u entries read",_SheetIdToName.size()); }
//----------------------------------------------- // Build // //----------------------------------------------- bool CSheetId::buildSheetId(const std::string& sheetName) { nlassert(_Initialised); // When no sheet_id.bin is loaded, use dynamically assigned IDs. if (_DontHaveSheetKnowledge) { std::string sheetNameLc = toLower(sheetName); std::map<std::string, uint32>::iterator it = _DevSheetNameToId.find(sheetNameLc); if (it == _DevSheetNameToId.end()) { // Create a new dynamic sheet ID. // nldebug("SHEETID: Creating a dynamic sheet id for '%s'", sheetName.c_str()); std::string sheetType = CFile::getExtension(sheetNameLc); std::string sheetName = CFile::getFilenameWithoutExtension(sheetNameLc); std::map<std::string, uint32>::iterator tit = _DevTypeNameToId.find(sheetType); uint32 typeId; if (tit == _DevTypeNameToId.end()) { _FileExtensions.push_back(sheetType); _DevSheetIdToName.push_back(std::vector<std::string>()); typeId = (uint32)_FileExtensions.size() - 1; _DevTypeNameToId[sheetType] = typeId; std::string unknownNewType = std::string("unknown." + sheetType); _DevSheetIdToName[typeId].push_back(unknownNewType); _Id.IdInfos.Type = typeId; _Id.IdInfos.Id = _DevSheetIdToName[typeId].size() - 1; _DevSheetNameToId[unknownNewType] = _Id.Id; if (sheetName == "unknown") return true; // Return with the unknown sheet id of this type } else { typeId = tit->second; _Id.IdInfos.Type = typeId; } // Add a new sheet name to the type _DevSheetIdToName[typeId].push_back(sheetNameLc); _Id.IdInfos.Id = _DevSheetIdToName[typeId].size() - 1; // nldebug("SHEETID: Type %i, id %i, sheetid %i", _Id.IdInfos.Type, _Id.IdInfos.Id, _Id.Id); _DevSheetNameToId[sheetNameLc] = _Id.Id; return true; } _Id.Id = it->second; return true; } // try looking up the sheet name in _SheetNameToId CStaticMap<CChar,uint32,CCharComp>::const_iterator itId; CChar c; c.Ptr = new char [sheetName.size()+1]; strcpy(c.Ptr, sheetName.c_str()); toLower(c.Ptr); itId = _SheetNameToId.find (c); delete [] c.Ptr; if( itId != _SheetNameToId.end() ) { _Id.Id = itId->second; #ifdef NL_DEBUG_SHEET_ID // store debug info _DebugSheetName = itId->first.Ptr; #endif return true; } // we failed to find the sheet name in the sheetname map so see if the string is numeric if (sheetName.size()>1 && sheetName[0]=='#') { uint32 numericId; NLMISC::fromString((const char*)(sheetName.c_str()+1), numericId); if (NLMISC::toString("#%u",numericId)==sheetName) { _Id.Id= numericId; return true; } } #ifdef NL_TEMP_YUBO_NO_SOUND_SHEET_ID if (a_NoSoundSheetId && sheetName.find(".sound") != std::string::npos) { std::string sheetNameLc = toLower(sheetName); std::map<std::string, uint32>::iterator it = _DevSheetNameToId.find(sheetNameLc); if (it == _DevSheetNameToId.end()) { // nldebug("SHEETID: Creating a temporary sheet id for '%s'", sheetName.c_str()); _DevSheetIdToName[0].push_back(sheetName); _Id.IdInfos.Type = a_NoSoundSheetType; _Id.IdInfos.Id = _DevSheetIdToName[0].size() - 1; _DevSheetNameToId[sheetNameLc] = _Id.Id; return true; } _Id.Id = it->second; return true; } #endif return false; }
vector<string> OptionsParser::parse(int argc, const char * const * argv) { vector<string> unprocessedArgs; size_t out_arg_i = 0; for (int arg_i = 1; arg_i < argc; arg_i++) { string originalCaseArg = argv[arg_i]; string currarg = toLower(originalCaseArg); if (currarg.compare(0, 2, "--") == 0) //long option { bool invert = (currarg.compare(2, 2, "no") == 0); size_t name_i = (invert ? 4 : 2); size_t equalspos = currarg.find_first_of("=-", name_i); string name = currarg.substr(name_i, equalspos - name_i); string value = (equalspos >= currarg.length()) ? "" : currarg.substr(equalspos); optsMap_t::iterator option = optsMap.find(name); if (option == optsMap.end()) { cerr << "Unknown option: " << currarg << endl; exit(-1); } valueMap_t::iterator valueIt = valueMap.find(value); if (valueIt == valueMap.end()) { cerr << "Unknown value: " << currarg << endl; exit(-1); } *option->second = valueIt->second ^ invert; } // "--" else if (currarg[0] == '-') //string of single char options { for (size_t c = 1; currarg[c] != '\0'; c++) { optsMap_t::iterator option = optsMap.find(string(1,currarg[c])); if (option == optsMap.end()) { cerr << "Unknown option: -" << currarg[c] << endl; exit(-1); } *option->second = true; } } else //positional argument { if (out_arg_i < args.size()) *args[out_arg_i] = originalCaseArg; else unprocessedArgs.push_back(originalCaseArg); out_arg_i++; } } return unprocessedArgs; }
bool DialogueManager::isMatching (const MWWorld::Ptr& actor, const ESM::DialInfo& info) const { // actor id if (!info.actor.empty()) if (toLower (info.actor)!=MWWorld::Class::get (actor).getId (actor)) return false; if (!info.race.empty()) { ESMS::LiveCellRef<ESM::NPC, MWWorld::RefData> *cellRef = actor.get<ESM::NPC>(); if (!cellRef) return false; if (toLower (info.race)!=toLower (cellRef->base->race)) return false; } if (!info.clas.empty()) { ESMS::LiveCellRef<ESM::NPC, MWWorld::RefData> *cellRef = actor.get<ESM::NPC>(); if (!cellRef) return false; if (toLower (info.clas)!=toLower (cellRef->base->cls)) return false; } if (!info.npcFaction.empty()) { ESMS::LiveCellRef<ESM::NPC, MWWorld::RefData> *cellRef = actor.get<ESM::NPC>(); if (!cellRef) return false; if (toLower (info.npcFaction)!=toLower (cellRef->base->faction)) return false; } // TODO check player faction // check cell if (!info.cell.empty()) if (mEnvironment.mWorld->getPlayerPos().getPlayer().getCell()->cell->name != info.cell) return false; // TODO check DATAstruct for (std::vector<ESM::DialInfo::SelectStruct>::const_iterator iter (info.selects.begin()); iter != info.selects.end(); ++iter) if (!isMatching (actor, *iter)) return false; std::cout << "unchecked entries:" << std::endl << " player faction: " << info.pcFaction << std::endl << " disposition: " << info.data.disposition << std::endl << " NPC rank: " << static_cast<int> (info.data.rank) << std::endl << " gender: " << static_cast<int> (info.data.gender) << std::endl << " PC rank: " << static_cast<int> (info.data.PCrank) << std::endl; return true; }
std::string Utils::toLowerCopy(const std::string& str) { std::string retStr(str); toLower(retStr); return retStr; }
/// Returns lower case copy of input string static std::string lowerCase(const std::string &in) { std::string out = in; return toLower(out); }
bool CHttpParser::setData(const char *pszData, const int iDataLen) { bool bOk = true; m_sHttpContent.assign(pszData, iDataLen); this->reset(); string sValue; string sName; string::size_type pos1 = 0; string::size_type pos2 = 0; string::size_type headEndPos = m_sHttpContent.find("\r\n\r\n"); //http command pos2 = m_sHttpContent.find(' ', pos1); if (pos2 != string::npos) { sValue = m_sHttpContent.substr(0,pos2); if (sValue == "GET") { m_nCommand = GET; } else if (sValue == "POST") { m_nCommand = POST; } else if (sValue == "HEAD") { m_nCommand = HEAD; } else { snprintf(m_szErrMsg, sizeof(m_szErrMsg), "http command error: %s.", sValue.c_str()); return false; } } else { snprintf(m_szErrMsg, sizeof(m_szErrMsg), "parse http command error: can't find space."); return false; } //uri pos1 = pos2 + 1; pos2 = m_sHttpContent.find(' ', pos1); if (string::npos != pos2) { m_sURI = m_sHttpContent.substr(pos1, pos2-pos1); if ( m_sURI.empty() ) { snprintf(m_szErrMsg, sizeof(m_szErrMsg), "URI error: uri is empty."); return false; } if (m_nCommand == GET) { string::size_type tmpPos = m_sURI.find('?'); if (tmpPos != string::npos) { m_sValues = m_sURI.substr(tmpPos+1); m_sURI.erase(tmpPos); } } else if ( m_nCommand == POST ) { m_sValues = m_sHttpContent.substr(headEndPos+4); } } else { snprintf(m_szErrMsg, sizeof(m_szErrMsg), "parse http URI error: can't find space."); return false; } //version pos1 = pos2 + 1; pos2 = m_sHttpContent.find("\r\n", pos1); if (pos2 != string::npos) { m_sVersion = m_sHttpContent.substr( pos1, pos2 - pos1 ); if ( m_sVersion.empty() ) { snprintf(m_szErrMsg, sizeof(m_szErrMsg), "version error: version is empty."); return false; } } else { snprintf(m_szErrMsg, sizeof(m_szErrMsg), "parse http version error: can't find <\\r\\n>."); return false; } pos1 = pos2 + 2; string sLine; string::size_type colonPos = 0; string sBoundary;//2010-02-26 解析post 的formdata等 while ( string::npos != pos1 && pos1 < headEndPos ) { pos2 = m_sHttpContent.find("\r\n", pos1); if ( pos2 == string::npos || headEndPos < pos2 ) break; sLine = m_sHttpContent.substr(pos1, pos2-pos1); pos1 = pos2 + 2; colonPos = sLine.find(": "); sName = sLine.substr( 0, colonPos ); if (sName.empty()) { snprintf(m_szErrMsg, sizeof(m_szErrMsg), "name error: name is empty<pos1=%d, pos2=%d>.", (uint32_t)pos1, (uint32_t)pos2); return false; } sValue = sLine.substr( colonPos+2 ); static const string BOUNDARY_STR("multipart/form-data; boundary="); if(sBoundary.empty() && sName == "Content-Type" && sValue.substr(0, BOUNDARY_STR.length()) == BOUNDARY_STR) { sBoundary = sValue.substr(BOUNDARY_STR.length()); } else { m_mapHeadInfo[toLower(sName.c_str())] = sValue; } } this->parseCookies(); this->parseValues(); //2010-02-26 解析post 的formdata等 if(m_nCommand == POST && !sBoundary.empty()) { sBoundary.insert(0, "--"); this->parsePostFormData(sBoundary, headEndPos); } return bOk; }
int32_t write(WriterI* _writer, const char* _format, va_list _argList, Error* _err) { MemoryReader reader(_format, strnlen(_format) ); int32_t size = 0; while (_err->isOk() ) { char ch = '\0'; read(&reader, ch, _err); if (!_err->isOk() ) { break; } else if ('%' == ch) { // %[ -0][<width>][.<precision>] read(&reader, ch); Param param; param.base = 10; param.prec = 6; param.left = false; param.fill = ' '; param.width = 0; while (' ' == ch || '-' == ch || '0' == ch) { switch (ch) { case '-': param.left = true; break; case ' ': param.fill = ' '; break; case '0': param.fill = '0'; break; } if (param.left) { param.fill = ' '; } read(&reader, ch); } if ('*' == ch) { read(&reader, ch); param.width = va_arg(_argList, int32_t); if (0 > param.width) { param.left = true; param.width = -param.width; } } else { while (isNumeric(ch) ) { param.width = param.width * 10 + ch - '0'; read(&reader, ch); } } if ('.' == ch) { read(&reader, ch); if ('*' == ch) { read(&reader, ch); param.prec = va_arg(_argList, int32_t); } else { param.prec = 0; while (isNumeric(ch) ) { param.prec = param.prec * 10 + ch - '0'; read(&reader, ch); } } } switch (toLower(ch) ) { case 'c': size += write(_writer, char(va_arg(_argList, int32_t) ), _err); break; case 's': size += write(_writer, va_arg(_argList, const char*), param, _err); break; case 'd': param.base = 10; size += write(_writer, va_arg(_argList, int32_t), param, _err); break; case 'f': size += write(_writer, va_arg(_argList, double), param, _err); break; case 'p': size += write(_writer, va_arg(_argList, void*), param, _err); break; case 'x': param.base = 16; size += write(_writer, va_arg(_argList, uint32_t), param, _err); break; case 'u': param.base = 10; size += write(_writer, va_arg(_argList, uint32_t), param, _err); break; default: size += write(_writer, ch, _err); break; } } else {
void listFiles(const std::string & dir, const bool recurse, std::vector<std::string> & files, bool & abort) { std::vector<std::string> childDirs; std::string child_name; #ifdef WINDOWS WIN32_FIND_DATA fileData; std::string child_search = (dir + PATH_SEP) + "*"; HANDLE fileHandle = FindFirstFile(child_search.c_str(), &fileData); // empty directory if (fileHandle == INVALID_HANDLE_VALUE) { return; } // process the next child in the driectory while (FindNextFile(fileHandle, &fileData) != 0) { child_name = fileData.cFileName; #else DIR * directory = opendir(dir.c_str()); struct dirent entry; struct dirent * next_entry; if (NULL == directory) { return; } while (0 == readdir_r(directory, &entry, &next_entry) && next_entry != NULL) { child_name = entry.d_name; #endif abort = (abort_monitor == child_name); // if the child represents the directory itself, or its parent, skip if (child_name == "." || child_name == "..") continue; // build the full path std::string child = dir + PATH_SEP + child_name; // deal appropriately with the file depending on whether it is a directory or file /*#ifdef WINDOWS if ((fileData.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) != 0) #else #error Not implemented #endif */ if (dirExists(child)) { // if not doing a recursive search, no point in even adding to the list if (recurse) continue; childDirs.push_back(child); } else { files.push_back(child); } } #ifdef WINDOWS FindClose(fileHandle); #else closedir(directory); #endif if (recurse) { for(std::vector<std::string>::const_iterator cDir = childDirs.begin(); cDir != childDirs.end(); ++cDir) listFiles(*cDir, recurse, files, abort); } } // not passed-by-ref on purpose - need a copy here bool hasRarSuffix(std::string s) { // file must be at least a.rar long if (s.length() < 5) return false; toLower(s); // index s.length() - 1 points to r // index s.length() - 4 points to . return (s.substr(s.length() - 4) == ".rar"); } bool isDigit(char c) { return c >= '0' && c <= '9'; } bool hasR01Suffix(std::string s) { // .rXX s = s.substr(s.length() - 4); return s == ".r01"; }
str FITSexportTable(Client cntxt, MalBlkPtr mb, MalStkPtr stk, InstrPtr pci) { str msg = MAL_SUCCEED; str tname = *getArgReference_str(stk, pci, 1); mvc *m = NULL; sql_trans *tr; sql_schema *sch; sql_table *tbl, *column, *tables = NULL; sql_column *col; oid rid = oid_nil; str type, name, *colname, *tform; fitsfile *fptr; char filename[BUFSIZ]; size_t nrows = 0; long optimal; /* type long used by fits library */ rids * rs; int tm0, texportboolean=0, texportchar=0, texportstring=0, texportshort=0, texportint=0, texportlng=0, texportfloat=0, texportdouble=0; size_t numberrow = 0, dimension = 0; int cc = 0, status = 0, j = 0, columns, *fid, block = 0; int boolcols = 0, charcols = 0, strcols = 0, shortcols = 0, intcols = 0, lngcols = 0, floatcols = 0, doublecols = 0; int hdutype; char *charvalue, *readcharrows; str strvalue; char **readstrrows; short *shortvalue, *readshortrows; int *intvalue, *readintrows; lng *lngvalue, *readlngrows; float *realvalue, *readfloatrows; double *doublevalue, *readdoublerows; _Bool *boolvalue, *readboolrows; struct list * set; if ((msg = getSQLContext(cntxt, mb, &m, NULL)) != MAL_SUCCEED) return msg; if ((msg = checkSQLContext(cntxt)) != MAL_SUCCEED) return msg; tr = m->session->tr; sch = mvc_bind_schema(m, "sys"); /* First step: look if the table exists in the database. If the table is not in the database, the export function cannot continue */ tbl = mvc_bind_table(m, sch, tname); if (tbl == NULL) { msg = createException (MAL, "fits.exporttable", "Table %s is missing.\n", tname); return msg; } set = (*tbl).columns.set; columns = list_length(set); colname = (str *) GDKmalloc(columns * sizeof(str)); tform = (str *) GDKmalloc(columns * sizeof(str)); /* fprintf(stderr,"Number of columns: %d\n", columns);*/ tables = mvc_bind_table(m, sch, "_tables"); col = mvc_bind_column(m, tables, "name"); rid = table_funcs.column_find_row(m->session->tr, col, tname, NULL); col = mvc_bind_column(m, tables, "id"); fid = (int*) table_funcs.column_find_value(m->session->tr, col, rid); column = mvc_bind_table(m, sch, "_columns"); col = mvc_bind_column(m, column, "table_id"); rs = table_funcs.rids_select(m->session->tr, col, (void *) fid, (void *) fid, NULL); GDKfree(fid); while ((rid = table_funcs.rids_next(rs)) != oid_nil) { col = mvc_bind_column(m, column, "name"); name = (char *) table_funcs.column_find_value(m->session->tr, col, rid); colname[j] = toLower(name); GDKfree(name); col = mvc_bind_column(m, column, "type"); type = (char *) table_funcs.column_find_value(m->session->tr, col, rid); if (strcmp(type,"boolean")==0) tform[j] = "1L"; if (strcmp(type,"char")==0) tform[j] = "1S"; if (strcmp(type,"varchar")==0) tform[j] = "8A"; if (strcmp(type,"smallint")==0) tform[j] = "1I"; if (strcmp(type,"int")==0) tform[j] = "1J"; if (strcmp(type,"bigint")==0) tform[j] = "1K"; if (strcmp(type,"real")==0) tform[j] = "1E"; if (strcmp(type,"double")==0) tform[j] = "1D"; GDKfree(type); j++; } col = mvc_bind_column(m, tbl, colname[0]); nrows = store_funcs.count_col(tr, col, 1); assert(nrows <= (size_t) GDK_oid_max); snprintf(filename,BUFSIZ,"\n%s.fit",tname); fprintf(stderr, "Filename: %s\n", filename); remove(filename); status=0; fits_create_file(&fptr, filename, &status); fits_create_img(fptr, USHORT_IMG, 0, NULL, &status); fits_close_file(fptr, &status); fits_open_file(&fptr, filename, READWRITE, &status); fits_movabs_hdu(fptr, 1, &hdutype, &status); fits_create_tbl( fptr, BINARY_TBL, 0, columns, colname, tform, NULL, tname, &status); for (cc = 0; cc < columns; cc++) { char * columntype; col = mvc_bind_column(m, tbl, colname[cc]); columntype = col -> type.type->sqlname; if (strcmp(columntype,"boolean")==0) { boolcols++; dimension = 0; block = 0; fits_get_rowsize(fptr,&optimal,&status); readboolrows = (_Bool *) GDKmalloc (sizeof(_Bool) * optimal); for (numberrow = 0; numberrow < nrows ; numberrow++) { boolvalue = (_Bool*) table_funcs.column_find_value(m->session->tr, col, (oid) numberrow); readboolrows[dimension] = *boolvalue; GDKfree(boolvalue); dimension++; if (dimension == (size_t) optimal) { dimension = 0; tm0 = GDKms(); fits_write_col(fptr, TLOGICAL, cc+1, (optimal*block)+1, 1, optimal, readboolrows, &status); texportboolean += GDKms() - tm0; GDKfree(readboolrows); readboolrows = (_Bool *) GDKmalloc (sizeof(_Bool) * optimal); block++; } } tm0 = GDKms(); fits_write_col(fptr, TLOGICAL, cc+1, (optimal*block)+1, 1, dimension, readboolrows, &status); texportboolean += GDKms() - tm0; GDKfree(readboolrows); } if (strcmp(columntype,"char")==0) { charcols++; dimension = 0; block = 0; fits_get_rowsize(fptr,&optimal,&status); readcharrows = (char *) GDKmalloc (sizeof(char) * optimal); for (numberrow = 0; numberrow < nrows ; numberrow++) { charvalue = (char*) table_funcs.column_find_value(m->session->tr, col, (oid) numberrow); readcharrows[dimension] = *charvalue; GDKfree(charvalue); dimension++; if (dimension == (size_t) optimal) { dimension = 0; tm0 = GDKms(); fits_write_col(fptr, TBYTE, cc+1, (optimal*block)+1, 1, optimal, readcharrows, &status); texportchar += GDKms() - tm0; GDKfree(readcharrows); readcharrows = (char *) GDKmalloc (sizeof(char) * optimal); block++; } } tm0 = GDKms(); fits_write_col(fptr, TBYTE, cc+1, (optimal*block)+1, 1, dimension, readcharrows, &status); texportchar += GDKms() - tm0; GDKfree(readcharrows); } if (strcmp(columntype,"varchar")==0) { strcols++; dimension=0; block=0; fits_get_rowsize(fptr,&optimal,&status); readstrrows = (char **) GDKmalloc (sizeof(char *) * optimal); for (numberrow = 0; numberrow < nrows ; numberrow++) { strvalue = (char *) table_funcs.column_find_value(m->session->tr, col, (oid) numberrow); readstrrows[dimension] = strvalue; dimension++; if (dimension == (size_t) optimal) { dimension = 0; tm0 = GDKms(); fits_write_col_str(fptr, cc+1, (optimal*block)+1, 1, optimal, readstrrows, &status); texportstring += GDKms() - tm0; for (dimension = 0; dimension < (size_t) optimal; dimension++) GDKfree(readstrrows[dimension]); dimension = 0; GDKfree(readstrrows); readstrrows = (char **) GDKmalloc(sizeof(char *) * optimal); block++; } } tm0 = GDKms(); fits_write_col_str(fptr, cc+1, (optimal*block)+1, 1, dimension, readstrrows, &status); texportstring += GDKms() - tm0; for (numberrow = 0; numberrow < dimension; numberrow++) GDKfree(readstrrows[numberrow]); GDKfree(readstrrows); } if (strcmp(columntype,"smallint")==0) { shortcols++; dimension = 0; block = 0; fits_get_rowsize(fptr,&optimal,&status); readshortrows = (short *) GDKmalloc (sizeof(short) * optimal); for (numberrow = 0; numberrow < nrows ; numberrow++) { shortvalue = (short*) table_funcs.column_find_value(m->session->tr, col, (oid) numberrow); readshortrows[dimension] = *shortvalue; GDKfree(shortvalue); dimension++; if (dimension == (size_t) optimal) { dimension = 0; tm0 = GDKms(); fits_write_col(fptr, TSHORT, cc+1, (optimal*block)+1, 1, optimal, readshortrows, &status); texportshort += GDKms() - tm0; GDKfree(readshortrows); readshortrows = (short *) GDKmalloc (sizeof(short) * optimal); block++; } } tm0 = GDKms(); fits_write_col(fptr, TSHORT, cc+1, (optimal*block)+1, 1, dimension, readshortrows, &status); texportshort += GDKms() - tm0; GDKfree(readshortrows); } if (strcmp(columntype,"int")==0) { intcols++; dimension = 0; block = 0; fits_get_rowsize(fptr,&optimal,&status); readintrows = (int *) GDKmalloc (sizeof(int) * optimal); for (numberrow = 0; numberrow < nrows ; numberrow++) { intvalue = (int*) table_funcs.column_find_value(m->session->tr, col, (oid) numberrow); readintrows[dimension] = *intvalue; GDKfree(intvalue); dimension++; if (dimension == (size_t) optimal) { dimension = 0; tm0 = GDKms(); fits_write_col(fptr, TINT, cc+1, (optimal*block)+1, 1, optimal, readintrows, &status); texportint += GDKms() - tm0; GDKfree(readintrows); readintrows = (int *) GDKmalloc (sizeof(int) * optimal); block++; } } tm0 = GDKms(); fits_write_col(fptr, TINT, cc+1, (optimal*block)+1, 1, dimension, readintrows, &status); texportint += GDKms() - tm0; GDKfree(readintrows); } if (strcmp(columntype,"bigint")==0) { lngcols++; dimension = 0; block = 0; fits_get_rowsize(fptr,&optimal,&status); readlngrows = (lng *) GDKmalloc (sizeof(lng) * optimal); for (numberrow = 0; numberrow < nrows ; numberrow++) { lngvalue = (lng*) table_funcs.column_find_value(m->session->tr, col, (oid) numberrow); readlngrows[dimension] = *lngvalue; GDKfree(lngvalue); dimension++; if (dimension == (size_t) optimal) { dimension = 0; tm0 = GDKms(); fits_write_col(fptr, TLONG, cc+1, (optimal*block)+1, 1, optimal, readlngrows, &status); texportlng += GDKms() - tm0; GDKfree(readlngrows); readlngrows = (lng *) GDKmalloc (sizeof(lng) * optimal); block++; } } tm0 = GDKms(); fits_write_col(fptr, TLONG, cc+1, (optimal*block)+1, 1, dimension, readlngrows, &status); texportlng += GDKms() - tm0; GDKfree(readlngrows); } if (strcmp(columntype,"real")==0) { floatcols++; dimension = 0; block = 0; fits_get_rowsize(fptr,&optimal,&status); readfloatrows = (float *) GDKmalloc (sizeof(float) * optimal); for (numberrow = 0; numberrow < nrows ; numberrow++) { realvalue = (float*) table_funcs.column_find_value(m->session->tr, col, (oid) numberrow); readfloatrows[dimension] = *realvalue; GDKfree(realvalue); dimension++; if (dimension == (size_t) optimal) { dimension = 0; tm0 = GDKms(); fits_write_col(fptr, TFLOAT, cc+1, (optimal*block)+1, 1, optimal, readfloatrows, &status); texportfloat += GDKms() - tm0; GDKfree(readfloatrows); readfloatrows = (float *) GDKmalloc (sizeof(float) * optimal); block++; } } tm0 = GDKms(); fits_write_col(fptr, TFLOAT, cc+1, (optimal*block)+1, 1, dimension, readfloatrows, &status); texportfloat += GDKms() - tm0; GDKfree(readfloatrows); } if (strcmp(columntype,"double")==0) { doublecols++; dimension = 0; block = 0; fits_get_rowsize(fptr,&optimal,&status); readdoublerows = (double *) GDKmalloc (sizeof(double) * optimal); for (numberrow = 0; numberrow < nrows ; numberrow++) { doublevalue = (double*) table_funcs.column_find_value(m->session->tr, col, (oid) numberrow); readdoublerows[dimension] = *doublevalue; GDKfree(doublevalue); dimension++; if (dimension == (size_t) optimal) { dimension = 0; tm0 = GDKms(); fits_write_col(fptr, TDOUBLE, cc+1, (optimal*block)+1, 1, optimal, readdoublerows, &status); texportdouble += GDKms() - tm0; GDKfree(readdoublerows); readdoublerows = (double *) GDKmalloc (sizeof(double) * optimal); block++; } } tm0 = GDKms(); fits_write_col(fptr, TDOUBLE, cc+1, (optimal*block)+1, 1, optimal, readdoublerows, &status); texportdouble += GDKms() - tm0; GDKfree(readdoublerows); } } /* print all the times that were needed to export each one of the columns fprintf(stderr, "\n\n"); if (texportboolean > 0) fprintf(stderr, "%d Boolean\tcolumn(s) exported in %d ms\n", boolcols, texportboolean); if (texportchar > 0) fprintf(stderr, "%d Char\t\tcolumn(s) exported in %d ms\n", charcols, texportchar); if (texportstring > 0) fprintf(stderr, "%d String\tcolumn(s) exported in %d ms\n", strcols, texportstring); if (texportshort > 0) fprintf(stderr, "%d Short\t\tcolumn(s) exported in %d ms\n", shortcols, texportshort); if (texportint > 0) fprintf(stderr, "%d Integer\tcolumn(s) exported in %d ms\n", intcols, texportint); if (texportlng > 0) fprintf(stderr, "%d Long\t\tcolumn(s) exported in %d ms\n", lngcols, texportlng); if (texportfloat > 0) fprintf(stderr, "%d Float\t\tcolumn(s) exported in %d ms\n", floatcols, texportfloat); if (texportdouble > 0) fprintf(stderr, "%d Double\tcolumn(s) exported in %d ms\n", doublecols, texportdouble); */ fits_close_file(fptr, &status); return msg; }
string ProfileData::getName() { return toLower(name); }
str FITSloadTable(Client cntxt, MalBlkPtr mb, MalStkPtr stk, InstrPtr pci) { mvc *m = NULL; sql_schema *sch; sql_table *fits_fl, *fits_tbl, *tbl = NULL; sql_column *col; sql_subtype tpe; fitsfile *fptr; str tname = *getArgReference_str(stk, pci, 1); str fname; str msg = MAL_SUCCEED; oid rid = oid_nil, frid = oid_nil; int status = 0, cnum = 0, *fid, *hdu, hdutype, j, anynull = 0, mtype; int *tpcode = NULL; long *rep = NULL, *wid = NULL, rows; /* type long used by fits library */ char keywrd[80], **cname, nm[FLEN_VALUE]; ptr nilptr; if ((msg = getSQLContext(cntxt, mb, &m, NULL)) != MAL_SUCCEED) return msg; if ((msg = checkSQLContext(cntxt)) != MAL_SUCCEED) return msg; sch = mvc_bind_schema(m, "sys"); fits_tbl = mvc_bind_table(m, sch, "fits_tables"); if (fits_tbl == NULL) { msg = createException(MAL, "fits.loadtable", "FITS catalog is missing.\n"); return msg; } tbl = mvc_bind_table(m, sch, tname); if (tbl) { msg = createException(MAL, "fits.loadtable", "Table %s is already created.\n", tname); return msg; } col = mvc_bind_column(m, fits_tbl, "name"); rid = table_funcs.column_find_row(m->session->tr, col, tname, NULL); if (rid == oid_nil) { msg = createException(MAL, "fits.loadtable", "Table %s is unknown in FITS catalog. Attach first the containing file\n", tname); return msg; } /* Open FITS file and move to the table HDU */ col = mvc_bind_column(m, fits_tbl, "file_id"); fid = (int*)table_funcs.column_find_value(m->session->tr, col, rid); fits_fl = mvc_bind_table(m, sch, "fits_files"); col = mvc_bind_column(m, fits_fl, "id"); frid = table_funcs.column_find_row(m->session->tr, col, (void *)fid, NULL); GDKfree(fid); col = mvc_bind_column(m, fits_fl, "name"); fname = (char *)table_funcs.column_find_value(m->session->tr, col, frid); if (fits_open_file(&fptr, fname, READONLY, &status)) { msg = createException(MAL, "fits.loadtable", "Missing FITS file %s.\n", fname); GDKfree(fname); return msg; } GDKfree(fname); col = mvc_bind_column(m, fits_tbl, "hdu"); hdu = (int*)table_funcs.column_find_value(m->session->tr, col, rid); fits_movabs_hdu(fptr, *hdu, &hdutype, &status); if (hdutype != ASCII_TBL && hdutype != BINARY_TBL) { msg = createException(MAL, "fits.loadtable", "HDU %d is not a table.\n", *hdu); GDKfree(hdu); fits_close_file(fptr, &status); return msg; } GDKfree(hdu); /* create a SQL table to hold the FITS table */ /* col = mvc_bind_column(m, fits_tbl, "columns"); cnum = *(int*) table_funcs.column_find_value(m->session->tr, col, rid); */ fits_get_num_cols(fptr, &cnum, &status); tbl = mvc_create_table(m, sch, tname, tt_table, 0, SQL_PERSIST, 0, cnum); tpcode = (int *)GDKzalloc(sizeof(int) * cnum); rep = (long *)GDKzalloc(sizeof(long) * cnum); wid = (long *)GDKzalloc(sizeof(long) * cnum); cname = (char **)GDKzalloc(sizeof(char *) * cnum); for (j = 1; j <= cnum; j++) { /* fits_get_acolparms(fptr, j, cname, &tbcol, tunit, tform, &tscal, &tzero, tnull, tdisp, &status); */ snprintf(keywrd, 80, "TTYPE%d", j); fits_read_key(fptr, TSTRING, keywrd, nm, NULL, &status); if (status) { snprintf(nm, FLEN_VALUE, "column_%d", j); status = 0; } cname[j - 1] = toLower(nm); fits_get_coltype(fptr, j, &tpcode[j - 1], &rep[j - 1], &wid[j - 1], &status); fits2subtype(&tpe, tpcode[j - 1], rep[j - 1], wid[j - 1]); /* fprintf(stderr,"#%d %ld %ld - M: %s\n", tpcode[j-1], rep[j-1], wid[j-1], tpe.type->sqlname); */ mvc_create_column(m, tbl, cname[j - 1], &tpe); } /* data load */ fits_get_num_rows(fptr, &rows, &status); fprintf(stderr,"#Loading %ld rows in table %s\n", rows, tname); for (j = 1; j <= cnum; j++) { BAT *tmp = NULL; int time0 = GDKms(); mtype = fits2mtype(tpcode[j - 1]); nilptr = ATOMnilptr(mtype); col = mvc_bind_column(m, tbl, cname[j - 1]); tmp = BATnew(TYPE_void, mtype, rows, TRANSIENT); if ( tmp == NULL){ GDKfree(tpcode); GDKfree(rep); GDKfree(wid); GDKfree(cname); throw(MAL,"fits.load", MAL_MALLOC_FAIL); } BATseqbase(tmp, 0); if (mtype != TYPE_str) { fits_read_col(fptr, tpcode[j - 1], j, 1, 1, rows, nilptr, (void *)BUNtloc(bat_iterator(tmp), BUNfirst(tmp)), &anynull, &status); BATsetcount(tmp, rows); tmp->tsorted = 0; tmp->trevsorted = 0; } else { /* char *v = GDKzalloc(wid[j-1]);*/ /* type long demanded by "rows", i.e., by fits library */ long bsize = 50, batch = bsize, k, i; int tm0, tloadtm = 0, tattachtm = 0; char **v = (char **) GDKzalloc(sizeof(char *) * bsize); for(i = 0; i < bsize; i++) v[i] = GDKzalloc(wid[j-1]); for(i = 0; i < rows; i += batch) { batch = rows - i < bsize ? rows - i: bsize; tm0 = GDKms(); fits_read_col(fptr, tpcode[j - 1], j, 1 + i, 1, batch, nilptr, (void *)v, &anynull, &status); tloadtm += GDKms() - tm0; tm0 = GDKms(); for(k = 0; k < batch ; k++) BUNappend(tmp, v[k], TRUE); tattachtm += GDKms() - tm0; } for(i = 0; i < bsize ; i++) GDKfree(v[i]); GDKfree(v); fprintf(stderr,"#String column load %d ms, BUNappend %d ms\n", tloadtm, tattachtm); } if (status) { char buf[FLEN_ERRMSG + 1]; fits_read_errmsg(buf); msg = createException(MAL, "fits.loadtable", "Cannot load column %s of %s table: %s.\n", cname[j - 1], tname, buf); break; } fprintf(stderr,"#Column %s loaded for %d ms\t", cname[j-1], GDKms() - time0); store_funcs.append_col(m->session->tr, col, tmp, TYPE_bat); fprintf(stderr,"#Total %d ms\n", GDKms() - time0); BBPunfix(tmp->batCacheid); } GDKfree(tpcode); GDKfree(rep); GDKfree(wid); GDKfree(cname); fits_close_file(fptr, &status); return msg; }
void ProfileData::addTrackedName(const string& mTrackedName) { trackedNames.push_back(toLower(mTrackedName)); }
/* attach a single shp file given its name, fill in shp catalog tables */ str SHPattach(Client cntxt, MalBlkPtr mb, MalStkPtr stk, InstrPtr pci) { mvc *m = NULL; sql_schema *sch = NULL; sql_table *fls = NULL, *shps = NULL, *shps_dbf = NULL; sql_column *col; str msg = MAL_SUCCEED; str fname = *(str*)getArgReference(stk, pci, 1); /* SHP-level descriptor */ char buf[BUFSIZ], temp_buf[BUFSIZ], *s=buf; int i=0, shpid = 0; oid fid, rid = oid_nil; GDALWConnection shp_conn; GDALWConnection * shp_conn_ptr = NULL; GDALWSimpleFieldDef * field_definitions; GDALWSpatialInfo spatial_info; char *nameToLowerCase = NULL; if((msg = getSQLContext(cntxt, mb, &m, NULL)) != MAL_SUCCEED) return msg; if((msg = checkSQLContext(cntxt)) != MAL_SUCCEED) return msg; if(!(sch = mvc_bind_schema(m, "sys"))) return createException(MAL, "shp.attach", SQLSTATE(38000) "Schema sys missing\n"); fls = mvc_bind_table(m, sch, "files"); shps = mvc_bind_table(m, sch, "shapefiles"); shps_dbf = mvc_bind_table(m, sch, "shapefiles_dbf"); if (fls == NULL || shps == NULL || shps_dbf == NULL ) return createException(MAL, "shp.attach", SQLSTATE(38000) "Catalog table missing\n"); if ((shp_conn_ptr = GDALWConnect((char *) fname)) == NULL) { return createException(MAL, "shp.attach", SQLSTATE(38000) "Missing shape file %s\n", fname); } shp_conn = *shp_conn_ptr; /* check if the file is already attached */ col = mvc_bind_column(m, fls, "path"); rid = table_funcs.column_find_row(m->session->tr, col, fname, NULL); if (!is_oid_nil(rid)) { GDALWClose(shp_conn_ptr); return createException(MAL, "shp.attach", SQLSTATE(38000) "File %s already attached\n", fname); } /* add row in the files(id, path) catalog table */ col = mvc_bind_column(m, fls, "id"); fid = store_funcs.count_col(m->session->tr, col, 1) + 1; snprintf(buf, BUFSIZ, INSFILE, (int)fid, fname); if ( ( msg = SQLstatementIntern(cntxt, &s,"shp.attach",TRUE,FALSE,NULL)) != MAL_SUCCEED) goto finish; /*if (shp_conn.layer == NULL || shp_conn.source == NULL || shp_conn.handler == NULL || shp_conn.driver == NULL) { msg = createException(MAL, "shp.attach", SQLSTATE(38000) "lol-1\n"); return msg; }*/ /* add row in the shapefiles catalog table (e.g. the name of the table that will store tha data of the shapefile) */ spatial_info = GDALWGetSpatialInfo(shp_conn); col = mvc_bind_column(m, shps, "shapefileid"); shpid = store_funcs.count_col(m->session->tr, col, 1) + 1; nameToLowerCase = toLower(shp_conn.layername); snprintf(buf, BUFSIZ, INSSHP, shpid, (int)fid, spatial_info.epsg, nameToLowerCase); GDKfree(nameToLowerCase); if ( ( msg = SQLstatementIntern(cntxt, &s,"shp.attach",TRUE,FALSE,NULL)) != MAL_SUCCEED) goto finish; /* add information about the fields of the shape file * one row for each field with info (shapefile_id, field_name, field_type) */ field_definitions = GDALWGetSimpleFieldDefinitions(shp_conn); if (field_definitions == NULL) { GDALWClose(&shp_conn); return createException(MAL, "shp.attach", SQLSTATE(HY001) MAL_MALLOC_FAIL); } for (i=0 ; i<shp_conn.numFieldDefinitions ; i++) { snprintf(buf, BUFSIZ, INSSHPDBF, shpid, field_definitions[i].fieldName, field_definitions[i].fieldType); if ( ( msg = SQLstatementIntern(cntxt, &s,"shp.attach",TRUE,FALSE,NULL)) != MAL_SUCCEED) goto fin; } /* create the table that will store the data of the shape file */ temp_buf[0]='\0'; for (i=0 ; i<shp_conn.numFieldDefinitions ; i++) { nameToLowerCase = toLower(field_definitions[i].fieldName); if (strcmp(field_definitions[i].fieldType, "Integer") == 0) { sprintf(temp_buf + strlen(temp_buf), "\"%s\" INT, ", nameToLowerCase); } else if (strcmp(field_definitions[i].fieldType, "Real") == 0) { sprintf(temp_buf + strlen(temp_buf), "\"%s\" FLOAT, ", nameToLowerCase); #if 0 } else if (strcmp(field_definitions[i].fieldType, "Date") == 0) { sprintf(temp_buf + strlen(temp_buf), "\"%s\" STRING, ", nameToLowerCase); #endif } else sprintf(temp_buf + strlen(temp_buf), "\"%s\" STRING, ", nameToLowerCase); GDKfree(nameToLowerCase); } sprintf(temp_buf + strlen(temp_buf), "geom GEOMETRY "); snprintf(buf, BUFSIZ, CRTTBL, shp_conn.layername, temp_buf); if ( ( msg = SQLstatementIntern(cntxt, &s,"shp.import",TRUE,FALSE,NULL)) != MAL_SUCCEED) goto fin; fin: free(field_definitions); finish: /* if (msg != MAL_SUCCEED){ snprintf(buf, BUFSIZ,"ROLLBACK;"); SQLstatementIntern(cntxt,&s,"geotiff.attach",TRUE,FALSE)); }*/ GDALWClose(&shp_conn); return msg; }
bool Checkbox::setProperty(std::string property, const std::string& value) { property = toLower(property); if (property == "configfile") { load(value); } else if (property == "checked") { if ((value == "true") || (value == "True")) check(); else if ((value == "false") || (value == "False")) uncheck(); else TGUI_OUTPUT("TGUI error: Failed to parse 'Checked' property."); } else if (property == "text") { setText(value); } else if (property == "textcolor") { setTextColor(extractColor(value)); } else if (property == "textsize") { setTextSize(atoi(value.c_str())); } else if (property == "allowtextclick") { if ((value == "true") || (value == "True")) allowTextClick(true); else if ((value == "false") || (value == "False")) allowTextClick(false); else TGUI_OUTPUT("TGUI error: Failed to parse 'AllowTextClick' property."); } else if (property == "callback") { ClickableWidget::setProperty(property, value); std::vector<sf::String> callbacks; decodeList(value, callbacks); for (auto it = callbacks.begin(); it != callbacks.end(); ++it) { if ((*it == "Checked") || (*it == "checked")) bindCallback(Checked); else if ((*it == "Unchecked") || (*it == "unchecked")) bindCallback(Unchecked); else if ((*it == "SpaceKeyPressed") || (*it == "spacekeypressed")) bindCallback(SpaceKeyPressed); else if ((*it == "ReturnKeyPressed") || (*it == "returnkeypressed")) bindCallback(ReturnKeyPressed); } } else // The property didn't match return ClickableWidget::setProperty(property, value); // You pass here when one of the properties matched return true; }
//*************************************************** int Logic::AddIncludes() { TStringList IncludeStrings,IncludeLines; int CurInputLine,CurIncludeLine; string filename; int err=0; string::size_type pos1,pos2; int CurLine; char *ptr; IncludeFilenames = TStringList(); IncludeStrings = TStringList(); EditLines = TStringList(); IncludeLines = TStringList(); CurLine = 0; for(CurInputLine = 0;CurInputLine<InputLines.num;CurInputLine++){ EditLines.add(InputLines.at(CurInputLine)); CurLine = EditLines.num -1; RealLineNum[CurLine] = CurInputLine; LineFile[CurLine] = 0; #ifdef _WIN32 if(_strnicmp(InputLines.at(CurInputLine).c_str(),"#include",8)) { #else if(strncasecmp(InputLines.at(CurInputLine).c_str(),"#include",8)){ #endif continue; } string str = InputLines.at(CurInputLine).substr(8); if(str.length()<4){ ShowError(CurLine,"Missing include filename !"); err=1; continue; } if(str[0] != ' '){ ShowError(CurLine,"' ' expected after #include."); err=1; continue; } pos1 = str.find_first_of("\"",1); pos2 = str.find_first_of("\"",pos1+1); if(pos1 == string::npos || pos2 == string::npos){ ShowError(CurLine,"Include filenames need quote marks around them."); err=1; continue; } filename = str.substr(pos1+1,pos2-pos1-1); if(filename.find_first_of("/")!=string::npos){ ShowError(CurLine,"Only files in the src directory can be included."); err=1; continue; } sprintf(tmp,"%s/src/%s",game->dir.c_str(),filename.c_str()); FILE *fptr = fopen(tmp,"rb"); if(fptr==NULL){ sprintf(tmp,"Can't open include file: %s/src/%s",game->dir.c_str(),filename.c_str()); ShowError(CurLine,tmp); err=1; continue; } IncludeLines.lfree(); while(fgets(tmp,MAX_TMP,fptr)!=NULL){ if((ptr=strchr(tmp,0x0a)))*ptr=0; if((ptr=strchr(tmp,0x0d)))*ptr=0; IncludeLines.add(tmp); } fclose(fptr); if(IncludeLines.num==0)continue; IncludeFilenames.add(filename); RemoveComments(IncludeLines); EditLines.replace(CurLine,empty_tmp); for(CurIncludeLine=0;CurIncludeLine<IncludeLines.num;CurIncludeLine++){ EditLines.add(IncludeLines.at(CurIncludeLine)); CurLine=EditLines.num-1; RealLineNum[CurLine] = CurIncludeLine; LineFile[CurLine] = IncludeFilenames.num; } } IncludeLines.lfree(); InputLines.lfree(); return err; } //*************************************************** int Logic::ReadDefines() { int err=0,i; string::size_type pos1,pos2; string ThisDefineName,ThisDefineValue; int CurLine; NumDefines = 0; for(CurLine = 0;CurLine<EditLines.num;CurLine++){ #ifdef _WIN32 if(_strnicmp(EditLines.at(CurLine).c_str(),"#define",7)){ #else if(strncasecmp(EditLines.at(CurLine).c_str(),"#define",7)){ #endif continue; } string str = EditLines.at(CurLine).substr(7); toLower(&str); if(str.length()<4){ ShowError(CurLine,"Missing define name !"); err=1; continue; } if(str[0] != ' '){ ShowError(CurLine,"' ' expected after #define."); err=1; continue; } if(NumDefines >= MaxDefines){ ShowError(CurLine,"Too many defines (max " + IntToStr(MaxDefines) + ")"); err=1; continue; } pos1 = str.find_first_not_of(" ",1); pos2 = str.find_first_of(" ",pos1); if(pos1 == string::npos||pos2 == string::npos){ ShowError(CurLine,"Missing define name !"); err=1; continue; } ThisDefineName = str.substr(pos1,pos2-1); if(ThisDefineName.find_first_not_of("qwertyuiopasdfghjklzxcvbnm1234567890._") != string::npos){ ShowError(CurLine,"Define name can contain only characters from [a-z],'.' and '_'."); err=1; continue; } for(i=0;i<NumDefines;i++){ if(ThisDefineName == DefineNames[i]){ ShowError(CurLine,ThisDefineName + " already defined !"); err=1; break; } } if(err)continue; for(i=0;i<=NumAGICommands;i++){ if(ThisDefineName == AGICommand[i].Name){ ShowError(CurLine,"Define name can not be a command name."); err=1; break; } } if(err)continue; for(i=1;i<=NumTestCommands;i++){ if(ThisDefineName == TestCommand[i].Name){ ShowError(CurLine,"Define name can not be a command name."); err=1; break; } } if(err)continue; if(ThisDefineName == "if" || ThisDefineName == "else" || ThisDefineName == "goto"){ ShowError(CurLine,"Invalid define name (" + ThisDefineName + ")"); err=1; continue; } pos1 = str.find_first_not_of(" ",pos2+1); if(pos1 == string::npos){ ShowError(CurLine,"Missing define value !"); err=1; continue; } if(str[pos1] == '"'){ ThisDefineValue = "\"" + ReadString(&pos1,str) + "\""; if(ErrorOccured)continue; if(str.find_first_not_of(" ",pos1) != string::npos){ ShowError(CurLine,"Nothing allowed on line after define value."); err=1; continue; } } else{ pos2 = str.find_first_of(" ",pos1+1); if(pos2 == string::npos){ ThisDefineValue = str.substr(pos1); } else{ ThisDefineValue = str.substr(pos1,pos2-pos1); if(str.find_first_not_of(" ",pos2) != string::npos){ ShowError(CurLine,"Nothing allowed on line after define value."); err=1; continue; } } if(ThisDefineValue.find_first_not_of("qwertyuiopasdfghjklzxcvbnm1234567890._") != string::npos){ ShowError(CurLine,"Non-string define value can contain only characters from [a-z],'.' and '_'."); err=1; continue; } } DefineNames[NumDefines]=ThisDefineName; DefineValues[NumDefines]=ThisDefineValue; DefineNameLength[NumDefines] = ThisDefineName.length(); NumDefines++; EditLines.replace(CurLine,empty_tmp); } return err; } //*************************************************** int Logic::ReadPredefinedMessages() { int err=0,i; string::size_type pos1; int MessageNum; for(i=0;i<MaxMessages;i++){ Messages[i]=""; MessageExists[i]=false; } for(CurLine = 0;CurLine<EditLines.num;CurLine++){ #ifdef _WIN32 if(_strnicmp(EditLines.at(CurLine).c_str(),"#message",8)){ #else if(strncasecmp(EditLines.at(CurLine).c_str(),"#message",8)){ #endif continue; } string str = EditLines.at(CurLine).substr(8); if(str[0] != ' '){ ShowError(CurLine,"' ' expected after #message."); err=1; continue; } MessageNum = atoi(str.c_str()); if(MessageNum==0){ ShowError(CurLine,"Invalid message number (must be 1-255)."); err=1; continue; } pos1 = str.find_first_of("\""); if(pos1 == string::npos){ ShowError(CurLine,"\" required at start of string."); err=1; continue; } Messages[MessageNum]=ReadString(&pos1,str); if(ErrorOccured)continue; if(Messages[MessageNum].find_first_not_of(" ",pos1) != string::npos){ sprintf(tmp,"Nothing allowed on line after message. "); ShowError(CurLine,tmp); err=1; continue; } MessageExists[MessageNum] =true; EditLines.replace(CurLine,empty_tmp); } return err; } //*************************************************** int Logic::ReadLabels() { int err=0,i; string::size_type pos1,pos2; string LabelName; int CurLine; NumLabels = 0; for(CurLine = 0;CurLine<EditLines.num;CurLine++){ string str = EditLines.at(CurLine); toLower(&str); pos1 = str.find_first_not_of(" "); if(pos1 == string::npos)continue; pos2 = str.find_first_not_of("qwertyuiopasdfghjklzxcvbnm1234567890._",pos1); if(pos2 == string::npos)continue; if((pos1 == pos2) || (str[pos2]!=':'))continue; LabelName = str.substr(pos1,pos2-pos1); for(i=1;i<=NumLabels;i++){ if(LabelName == Labels[i].Name){ ShowError(CurLine,"Label "+LabelName+" already defined."); err=1;break; } } if(err)continue; if(NumLabels > MaxLabels){ ShowError(CurLine,"Too many labels (max "+IntToStr(MaxLabels)+")"); err=1;continue; } if(LabelName == "if" || LabelName == "else" || LabelName == "goto"){ ShowError(CurLine,"Invalid label name ("+LabelName+")"); err=1;continue; } for(i=0;i<NumDefines;i++){ if((LabelName == DefineNames[i]) || (LabelName+":" == DefineNames[i])){ ShowError(CurLine,"Can't have a label with the same name a a define."); err=1;break; } } if(err)continue; NumLabels++; Labels[NumLabels].Name = LabelName; Labels[NumLabels].Loc = 0; } return err; }
bool DialogueManager::isMatching (const MWWorld::Ptr& actor, const ESM::DialInfo::SelectStruct& select) const { char type = select.selectRule[1]; if (type!='0') { char comp = select.selectRule[4]; std::string name = select.selectRule.substr (5); // TODO types 4, 5, 6, 7, 8, 9, A, B, C switch (type) { case '1': // function return false; // TODO implement functions case '2': // global if (select.type==ESM::VT_Short || select.type==ESM::VT_Int || select.type==ESM::VT_Long) { if (!checkGlobal (comp, toLower (name), select.i, *mEnvironment.mWorld)) return false; } else if (select.type==ESM::VT_Float) { if (!checkGlobal (comp, toLower (name), select.f, *mEnvironment.mWorld)) return false; } else throw std::runtime_error ( "unsupported variable type in dialogue info select"); return true; case '3': // local if (select.type==ESM::VT_Short || select.type==ESM::VT_Int || select.type==ESM::VT_Long) { if (!checkLocal (comp, toLower (name), select.i, actor, mEnvironment.mWorld->getStore())) return false; } else if (select.type==ESM::VT_Float) { if (!checkLocal (comp, toLower (name), select.f, actor, mEnvironment.mWorld->getStore())) return false; } else throw std::runtime_error ( "unsupported variable type in dialogue info select"); return true; default: std::cout << "unchecked select: " << type << " " << comp << " " << name << std::endl; } } return true; }
std::string Utils::tolower(const std::string &s) { std::string buffer = s; toLower(buffer); return buffer; }
CTransformShape *CScene::createInstance(const string &shapeName) { // We must attach a bank to the scene (a ShapeBank handle the shape caches and // the creation/deletion of the instances) nlassert( _ShapeBank != NULL ); // If the shape is not present in the bank if (_ShapeBank->getPresentState( shapeName ) != CShapeBank::Present) { // Load it from file _ShapeBank->load( shapeName ); if (_ShapeBank->getPresentState( shapeName ) != CShapeBank::Present) { return NULL; } } // Then create a reference to the shape CTransformShape *pTShp = _ShapeBank->addRef( shapeName )->createInstance(*this); if (pTShp) pTShp->setDistMax(pTShp->Shape->getDistMax()); // Look if this instance get lightmap information #if defined(__GNUC__) && __GNUC__ < 3 CMeshBase *pMB = (CMeshBase*)((IShape*)(pTShp->Shape)); #else // not GNUC CMeshBase *pMB = dynamic_cast<CMeshBase*>((IShape*)(pTShp->Shape)); #endif // not GNUC CMeshBaseInstance *pMBI = dynamic_cast<CMeshBaseInstance*>( pTShp ); if( ( pMB != NULL ) && ( pMBI != NULL ) ) { // Init lightmap information pMBI->initAnimatedLightIndex (*this); // Auto animations //========================== if (_AutomaticAnimationSet) { if (pMB->getAutoAnim()) { std::string animName = toLower(CFile::getFilenameWithoutExtension(shapeName)); uint animID = _AutomaticAnimationSet->getAnimationIdByName(animName); if (animID != CAnimationSet::NotFound) { CChannelMixer *chanMix = new CChannelMixer; chanMix->setAnimationSet((CAnimationSet *) _AutomaticAnimationSet); chanMix->setSlotAnimation(0, animID); pMBI->registerToChannelMixer(chanMix, ""); // Gives this object ownership of the channel mixer so we don't need to keep track of it pMBI->setChannelMixerOwnerShip(true); } } } } CLandscapeModel *pLM = dynamic_cast<CLandscapeModel*>( pTShp ); if( pLM != NULL ) { // Init lightmap information pLM->Landscape.initAnimatedLightIndex (*this); } return pTShp; }