JSON_STATUS CSystemOperations::GetInfoLabels(const CStdString &method, ITransportLayer *transport, IClient *client, const Value ¶meterObject, Value &result) { if (!parameterObject.isArray()) return InvalidParams; std::vector<CStdString> info; for (unsigned int i = 0; i < parameterObject.size(); i++) { if (!parameterObject[i].isString()) continue; CStdString field = parameterObject[i].asString(); field = field.ToLower(); info.push_back(parameterObject[i].asString()); } if (info.size() > 0) { std::vector<CStdString> infoLabels = g_application.getApplicationMessenger().GetInfoLabels(info); for (unsigned int i = 0; i < info.size(); i++) result[info[i].c_str()] = infoLabels[i]; } return OK; }
void Value::merge(const Value &value) { // Merge lists if (isList() && value.isList()) { appendFrom(value); return; } if (!isDict() || !value.isDict()) TYPE_ERROR("Cannot merge JSON nodes of type " << getType() << " and " << value.getType()); // Merge dicts for (unsigned i = 0; i < value.size(); i++) { const string &key = value.keyAt(i); ValuePtr src = value.get(i); if (has(key)) { ValuePtr dst = get(key); if ((src->isDict() && dst->isDict()) || (src->isList() && dst->isList())) { dst->merge(*src); continue; } } insert(key, src); } }
bool StyledStreamWriter::isMultineArray( const Value &value ) { int size = value.size(); bool isMultiLine = size*3 >= rightMargin_ ; childValues_.clear(); for ( int index =0; index < size && !isMultiLine; ++index ) { const Value &childValue = value[index]; isMultiLine = isMultiLine || ( (childValue.isArray() || childValue.isObject()) && childValue.size() > 0 ); } if ( !isMultiLine ) // check if line length > max line length { childValues_.reserve( size ); addChildValues_ = true; int lineLength = 4 + (size-1)*2; // '[ ' + ', '*n + ' ]' for ( int index =0; index < size && !isMultiLine; ++index ) { writeValue( value[index] ); lineLength += int( childValues_[index].length() ); isMultiLine = isMultiLine && hasCommentForValue( value[index] ); } addChildValues_ = false; isMultiLine = isMultiLine || lineLength >= rightMargin_; } return isMultiLine; }
void CFileItemHandler::FillDetails(ISerializable* info, CFileItemPtr item, const Value& fields, Value &result) { if (info == NULL || fields.size() == 0) return; CVariant data; info->Serialize(data); Value serialization; data.toJsonValue(serialization); for (unsigned int i = 0; i < fields.size(); i++) { CStdString field = fields[i].asString(); if (item) { if (item->IsAlbum() && item->HasProperty(field)) { if (field == "album_rating") result[field] = item->GetPropertyInt(field); else result[field] = item->GetProperty(field); continue; } if (field == "fanart") { CStdString cachedFanArt = item->GetCachedFanart(); if (!cachedFanArt.IsEmpty()) { result["fanart"] = cachedFanArt.c_str(); continue; } } } if (serialization.isMember(field)) { Value value = serialization[field]; if (!value.isString() || (value.isString() && !value.asString().empty())) result[field] = value; } } }
void FastWriter::writeValue( const Value &value ) { switch ( value.type() ) { case nullValue: document_ += "null"; break; case intValue: document_ += valueToString( value.asLargestInt() ); break; case uintValue: document_ += valueToString( value.asLargestUInt() ); break; case realValue: document_ += valueToString( value.asDouble() ); break; case stringValue: document_ += valueToQuotedString( value.asCString() ); break; case booleanValue: document_ += valueToString( value.asBool() ); break; case arrayValue: { document_ += "["; int size = value.size(); for ( int index =0; index < size; ++index ) { if ( index > 0 ) document_ += ","; writeValue( value[index] ); } document_ += "]"; } break; case objectValue: { Value::Members members( value.getMemberNames() ); document_ += "{"; for ( Value::Members::iterator it = members.begin(); it != members.end(); ++it ) { const std::string &name = *it; if ( it != members.begin() ) document_ += ","; document_ += valueToQuotedString( name.c_str() ); document_ += yamlCompatiblityEnabled_ ? ": " : ":"; writeValue( value[name] ); } document_ += "}"; } break; } }
bool parseVector3(const Value &val, btVector3 &retVec) { if (!val.isArray() && val.size() == 3) return false; if (!val[0].isConvertibleTo(ValueType::realValue)) return false; if (!val[1].isConvertibleTo(ValueType::realValue)) return false; if (!val[2].isConvertibleTo(ValueType::realValue)) return false; retVec.setValue(val[0].asDouble(), val[1].asDouble(), val[2].asDouble()); return true; }
void StyledStreamWriter::writeArrayValue ( const Value& value ) { unsigned size = value.size (); if ( size == 0 ) pushValue ( "[]" ); else { bool isArrayMultiLine = isMultineArray ( value ); if ( isArrayMultiLine ) { writeWithIndent ( "[" ); indent (); bool hasChildValue = !childValues_.empty (); unsigned index = 0; while ( true ) { const Value& childValue = value[index]; if ( hasChildValue ) writeWithIndent ( childValues_[index] ); else { writeIndent (); writeValue ( childValue ); } if ( ++index == size ) break; *document_ << ","; } unindent (); writeWithIndent ( "]" ); } else // output on a single line { assert ( childValues_.size () == size ); *document_ << "[ "; for ( unsigned index = 0; index < size; ++index ) { if ( index > 0 ) *document_ << ", "; *document_ << childValues_[index]; } *document_ << " ]"; } } }
bool parseQuaternion(const Value &val, btQuaternion &retQuat) { if (!(val.isArray() && val.size() == 4)) return false; if (!val[0].isConvertibleTo(ValueType::realValue)) return false; if (!val[1].isConvertibleTo(ValueType::realValue)) return false; if (!val[2].isConvertibleTo(ValueType::realValue)) return false; if (!val[3].isConvertibleTo(ValueType::realValue)) return false; retQuat.setValue(val[0].asDouble(), val[1].asDouble(), val[2].asDouble(), val[3].asDouble()); return true; }
void FastWriter::writeValue(const Value& value) { switch (value.type()) { case nullValue: if (!dropNullPlaceholders_) document_ += "null"; break; case intValue: document_ += valueToString(value.asLargestInt()); break; case uintValue: document_ += valueToString(value.asLargestUInt()); break; case realValue: document_ += valueToString(value.asDouble()); break; case stringValue: { // Is NULL possible for value.string_? No. char const* str; char const* end; bool ok = value.getString(&str, &end); if (ok) document_ += valueToQuotedStringN(str, static_cast<unsigned>(end-str)); break; } case booleanValue: document_ += valueToString(value.asBool()); break; case arrayValue: { document_ += '['; ArrayIndex size = value.size(); for (ArrayIndex index = 0; index < size; ++index) { if (index > 0) document_ += ','; writeValue(value[index]); } document_ += ']'; } break; case objectValue: { Value::Members members(value.getMemberNames()); document_ += '{'; for (Value::Members::iterator it = members.begin(); it != members.end(); ++it) { const JSONCPP_STRING& name = *it; if (it != members.begin()) document_ += ','; document_ += valueToQuotedStringN(name.data(), static_cast<unsigned>(name.length())); document_ += yamlCompatiblityEnabled_ ? ": " : ":"; writeValue(value[name]); } document_ += '}'; } break; } }
ApolloStoryProducer :: ApolloStoryProducer (string dir) { ifstream rFile(dir+string("/task_info.json")); if (!rFile) { cout << "task_info.json does not exist." << endl; candidate = false; return; } string line; getline (rFile, line); Reader reader; Value metaData; reader.parse(line, metaData); Value query = metaData["query"]; Value analysisType = query["analysis_types"]; for (unsigned int i=0; i<analysisType.size(); i++) { if (analysisType[i].asString() == string("Diversity")) { candidate = true; break; } } Name nRoot = Name("Apollo"); nRoot.append(Name(query["dataset"].asString())); this->storyName = query["dataset"].asString(); this->producer = new InfoMaxProducer(nRoot); vector<Name> nameList; vector<Data> dataList; string subdir = string(dir+string("/analysis/Diversity")); if (readDirintoNameAndData(subdir, &nameList, &dataList)) { for(unsigned int i=0; i<nameList.size(); i++) { producer->add(nameList[i], dataList[i]); } } if (!candidate) { cout << "This folder doesn't have Diversity folder." << endl; candidate = false; return; } }
void PokemonFactory::addSpecies(Value& value) { // parse all single values from json int id = (int) value.get("id", Value::null).asInt(); string name = value.get("name", Value::null).asString(); int hp = value.get("hp", Value::null).asInt(); int attack = value.get("attack", Value::null).asInt(); int defense = value.get("defense", Value::null).asInt(); int specialAttack = value.get("specialAttack", Value::null).asInt(); int specialDefense = value.get("specialDefense", Value::null).asInt(); int speed = value.get("speed", Value::null).asInt(); float genderDist = (float) value.get("gender", Value::null).asDouble(); // parse types string type1 = value.get("type1", Value::null).asString(); string type2 = Type::NO_TYPE; const Value& type2Value = value.get("type2", Value::null); if(type2Value.isString()) { type2 = type2Value.asString(); } // check that types are valid assert(Type::isType(type1)); assert(Type::isType(type2)); assert(type1 != Type::NO_TYPE); assert(type1 != type2); // initialize container for the pokemon species' moves vector<int> moveIds; // parse move id values into move species Value moveIdsRaw = value.get("moves", Value::null); for(int i = 0; i < moveIdsRaw.size(); i++) { Value moveId = moveIdsRaw[i]; moveIds.push_back((int) moveId.asInt()); } // check that the number of moves is valid assert(moveIds.size() > 0); assert(moveIds.size() <= Environment::MAX_MOVES); // create species with parsed values PokemonSpecies* species = new PokemonSpecies(name, type1, type2, hp, attack, defense, specialAttack, specialDefense, speed, moveIds, genderDist); // add to container println_debug("Registering Pokemon " << id << " \"" << name << "\""); allSpecies.insert(std::pair<int, PokemonSpecies*>(id, species)); }
void StyledWriter::writeArrayValue( const Value &value ) { unsigned size = value.size(); if ( size == 0 ) pushValue( "[]" ); else { bool isArrayMultiLine = isMultineArray( value ); if ( isArrayMultiLine ) { writeWithIndent( "[" ); indent(); bool hasChildValue = !childValues_.empty(); unsigned index =0; for (;;) { const Value &childValue = value[index]; writeCommentBeforeValue( childValue ); if ( hasChildValue ) writeWithIndent( childValues_[index] ); else { writeIndent(); writeValue( childValue ); } if ( ++index == size ) { writeCommentAfterValueOnSameLine( childValue ); break; } document_ += ","; writeCommentAfterValueOnSameLine( childValue ); } unindent(); writeWithIndent( "]" ); } else // output on a single line { assert( childValues_.size() == size ); document_ += "[ "; for ( unsigned index =0; index < size; ++index ) { if ( index > 0 ) document_ += ", "; document_ += childValues_[index]; } document_ += " ]"; } } }
// on "init" you need to initialize your instance bool HelloWorld::init() { ////////////////////////////// // 1. super init first if ( !CCLayer::init() ) { return false; } unsigned long fileSize; unsigned char * fileData = CCFileUtils::sharedFileUtils()->getFileData("data.json", "r", &fileSize); Reader r; Value root; r.parse((const char*)fileData, (const char*)(fileData+fileSize), root,false); Value peopleArr = root["people"]; Value people; for (Value::iterator it = peopleArr.begin(); it!=peopleArr.end(); it++) { people = *it; CCLog("name:%s,age:%d",people["name"].asCString(),people["age"].asInt()); } CCLog("size : %d",peopleArr.size()); for (int i=0; i<peopleArr.size(); i++) { people = peopleArr[i]; CCLog("name:%s,age:%d",people["name"].asCString(),people["age"].asInt()); } return true; }
std::pair<size_t, bool> StreamWriter<StreamType>::append_array(const Value& value) { std::pair<size_t, bool> rtn(2, false); const std::size_t size = value.size(); write(Marker::Array_Start); for(size_t i=0; i < size; i++) update(append_value(value[i]), rtn); write(Marker::Array_End); return rtn; //! \todo TODO... detect homogenepus arrays and treat accordingly //! WORK in progress }
bool Command::handle_reply_message(const Url &url, const Value &val) { if (url.path() == REPLY_PATH) { RootProxy *proxy = find_proxy(url.location()); if (proxy) { if (val.size() < 2 || !val[0].is_string()) { std::cerr << "Bad argument to " << REPLY_PATH << " :" << val << "\n"; return true; } proxy->handle_reply(val[0].str(), val[1]); } else { // std::cerr << "Could not handle reply from '" << url.location() << "' (no proxy for this location).\n"; } return true; } else { return false; } }
void BuiltStyledStreamWriter::writeArrayValue(Value const& value) { unsigned size = value.size(); if (size == 0) pushValue("[]"); else { bool isMultiLine = (cs_ == CommentStyle::All) || isMultineArray(value); if (isMultiLine) { writeWithIndent("["); indent(); bool hasChildValue = !childValues_.empty(); unsigned index = 0; for (;;) { Value const& childValue = value[index]; writeCommentBeforeValue(childValue); if (hasChildValue) writeWithIndent(childValues_[index]); else { if (!indented_) writeIndent(); indented_ = true; writeValue(childValue); indented_ = false; } if (++index == size) { writeCommentAfterValueOnSameLine(childValue); break; } sout_ << ","; writeCommentAfterValueOnSameLine(childValue); } unindent(); writeWithIndent("]"); } else // output on a single line { assert(childValues_.size() == size); sout_ << "["; if (!indentation_.empty()) sout_ << " "; for (unsigned index = 0; index < size; ++index) { if (index > 0) sout_ << ", "; sout_ << childValues_[index]; } if (!indentation_.empty()) sout_ << " "; sout_ << "]"; } } }
std::set<string> WsNodeProperties::getGroups() { std::set<std::string> grp; { boost::mutex::scoped_lock lock(m_mutex); if (!m_parsed) { string p = getPath(); if (parse(p) == ErrorCode::Failure) return grp; } const Value groups = m_root["global"]["groups"]; if (groups != Value::null) { for ( int i = 0; i < groups.size(); ++i) { grp.insert(groups[i].asString()); } } return grp; } }
JSON_STATUS CSystemOperations::GetInfoBooleans(const CStdString &method, ITransportLayer *transport, IClient *client, const Value ¶meterObject, Value &result) { if (!parameterObject.isArray()) return InvalidParams; std::vector<CStdString> info; bool CanControlPower = (client->GetPermissionFlags() & ControlPower) > 0; for (unsigned int i = 0; i < parameterObject.size(); i++) { if (!parameterObject[i].isString()) continue; CStdString field = parameterObject[i].asString(); field = field.ToLower(); // Need to override power management of whats in infomanager since jsonrpc // have a security layer aswell. if (field.Equals("system.canshutdown")) result[parameterObject[i].asString()] = (g_powerManager.CanPowerdown() && CanControlPower); else if (field.Equals("system.canpowerdown")) result[parameterObject[i].asString()] = (g_powerManager.CanPowerdown() && CanControlPower); else if (field.Equals("system.cansuspend")) result[parameterObject[i].asString()] = (g_powerManager.CanSuspend() && CanControlPower); else if (field.Equals("system.canhibernate")) result[parameterObject[i].asString()] = (g_powerManager.CanHibernate() && CanControlPower); else if (field.Equals("system.canreboot")) result[parameterObject[i].asString()] = (g_powerManager.CanReboot() && CanControlPower); else info.push_back(parameterObject[i].asString()); } if (info.size() > 0) { std::vector<bool> infoLabels = g_application.getApplicationMessenger().GetInfoBooleans(info); for (unsigned int i = 0; i < info.size(); i++) result[info[i].c_str()] = Value(infoLabels[i]); } return OK; }
/** * Ham convert mot chuoi string duoc ma hoa bang Json sang Item. ( Khong tra ve itemID cho item). * @param jsonString * @return Item */ Item ItemDB::convertJsonToItem(string jsonString) { Item itemReturn; Value root; Reader reader; bool parsedSuccess = reader.parse(jsonString, root, false); if (not parsedSuccess) { // Report failures and their locations // in the document. cout << "Failed to parse JSON" << endl << reader.getFormatedErrorMessages() << endl; poco_error_f1(*logger, "convertJsonToItem: Failed to parse JSON %s", reader.getFormatedErrorMessages()); return itemReturn; } Value content = root["content"]; Value tagsID = root["tagsID"]; Value viewCounts = root["viewCounts"]; Value likeCounts = root["likeCounts"]; Value dislikeCounts = root["dislikeCounts"]; Value dateAdd = root["dateAdd"]; Value dateUpdate = root["dateUpdate"]; //cout << "Tags:" << tags << endl; //itemReturn.itemID = itemID.asString(); itemReturn.content = content.asString(); int n = tagsID.size(); for (int i = 0; i < n; i++) { string str = tagsID[i].asString(); itemReturn.tagsID.push_back(str); } itemReturn.viewCounts = viewCounts.asInt(); itemReturn.likeCounts = likeCounts.asInt(); itemReturn.dislikeCounts = dislikeCounts.asInt(); itemReturn.dateAdd = dateAdd.asString(); itemReturn.dateUpdate = dateUpdate.asString(); return itemReturn; }
void Freeze::ObjectStoreBase::unmarshal(ObjectRecord& v, const Value& bytes, const CommunicatorPtr& communicator, const EncodingVersion& encoding, bool keepStats) { IceInternal::InstancePtr instance = IceInternal::getInstance(communicator); IceInternal::BasicStream stream(instance.get(), encoding, &bytes[0], &bytes[0] + bytes.size()); stream.sliceObjects(false); stream.startReadEncaps(); if(keepStats) { stream.read(v); } else { stream.read(v.servant); } stream.readPendingObjects(); stream.endReadEncaps(); }
int parsefile(const char *idstr) { char filename[256]; sprintf(filename, "html/%s", idstr); char *buf = readfile(filename); if (!buf) { return 1; } string bstr = string(buf); free(buf); map <string, string> kv; kv["site_id"] = "91kuaiche"; kv["project_name"] = extract(bstr,"class=\"expeheader","<b>","","</b>"); kv["project_id"] = idstr; kv["borrowing_amount"] = num_util(extract(bstr,"募集总额","<strong id=\"weighbold\">","","</strong>")); if(bstr.find("mess12-div") != string::npos) { kv["borrower"] = extract(bstr, "mess12-div", "借款人", "</span>","</li>"); } // kv["release_time"] = longtostring(stringtotime(extract(bstr,"",":","","</li>").c_str(),"%Y.%m.%d")); kv["invested_amount"] = doubletostring(s_atod(kv["borrowing_amount"].c_str()) - s_atod(num_util(extract(bstr, "可投金额", "weighbold\">", "", "</strong>")).c_str())); kv["annulized_rating"] = filternum(extract(bstr, "年化收益", "margin-right:6px","\">", "%")); kv["loan_period"] = loanperiod_util(extract(bstr, "项目期限", "weighbold", "table-td1\">","</td>")); kv["payment_method"] = extract(bstr,"收益方式","<strong>","","</strong>"); { sprintf(filename, "html/%s.brec",idstr); buf = readfile(filename); size_t buflen = strlen(buf); char *p = buf; string retstr; while(p < buf + buflen - 8) { int len; sscanf(p,"%08x",&len); p += 8; string jstr = string(p, len); p += len; Value json = stringtojson(jstr); string ivname; string ivaccount; string ivtime; for(int i = 0;i != json.size(); i++) { if(!get_string_member(json[i],"account",ivname) || !get_string_member(json[i],"tender_money",ivaccount) || !get_string_member(json[i],"create_time",ivtime)) continue; //ivtime = longtostring(stringtotime(ivtime.c_str(),"%Y-%m-%d")); retstr += ivtime + "|" + ivname + "|" + ivaccount + "|"; } } free(buf); kv["investor"] = retstr; } printstringmap(kv); if (kv["project_id"] == "" ) { return 1; } sprintf(filename, "data/%s", idstr); return savestringmap(kv, filename); }
bool Stations::Load() { char appDataPath[MAX_PATH]; SHGetFolderPath(nullptr, CSIDL_COMMON_APPDATA, nullptr, SHGFP_TYPE_CURRENT, appDataPath); string path = string(appDataPath) + "\\InternetRadio\\stations.json"; stringstream ssArchive; try { HTTP::Get( "http://internetradio.clemensboos.net/stations/archive.json", &ssArchive); } catch(...) { } Reader jsonReader; Value archiveRootValue; jsonReader.parse(ssArchive, archiveRootValue); map<int, string> staVersions; for (size_t i = 0; i < (size_t)archiveRootValue.size(); ++i) { string versionStr = archiveRootValue.getMemberNames().at(i); Value versionMinVerVal = archiveRootValue.get(versionStr, Value( nullValue)); if (!versionMinVerVal.isString()) continue; staVersions.insert(pair<int, string>( atoi(versionStr.c_str()), versionMinVerVal.asString())); } uint16_t installedVersion[4]; VersionUtil::GetInstalledVersion(installedVersion); for (map<int, string>::reverse_iterator it = staVersions.rbegin(); it != staVersions.rend(); ++it) { uint16_t staVer[4]; VersionUtil::VersionStrToArr(it->second, staVer); if (VersionUtil::CompareVersions(installedVersion, staVer) != VCR_Older) { stringstream ssVer; ssVer << it->first; stringstream ssNewStaChecksumsF; try { HTTP::Get("http://internetradio.clemensboos.net/stations/" + ssVer.str() + "/checksums", &ssNewStaChecksumsF); } catch(...) { break; } while (ssNewStaChecksumsF.good()) { string filePathAndChecksum; ssNewStaChecksumsF >> filePathAndChecksum; if (filePathAndChecksum == "") continue; vector<string> filePathAndChecksumSplit = StringUtil::Explode(filePathAndChecksum, ":"); if (filePathAndChecksumSplit.size() != 2) continue; string fileName = filePathAndChecksumSplit[0]; string locPath = string(appDataPath) + "\\InternetRadio\\" + fileName; StringUtil::SearchAndReplace(locPath, "/", "\\"); string remoteChecksum = filePathAndChecksumSplit[1]; bool update = false; ifstream fileStream(locPath); if (fileStream.is_open()) { fileStream.close(); string localChecksum = CryptUtil::FileMD5Hash(locPath); if (remoteChecksum != localChecksum) update = true; } else { update = true; } if (!update) continue; string fileRemURL = "http://internetradio.clemensboos.net/stations/" + ssVer.str() + "/" + fileName; StringUtil::SearchAndReplace(fileRemURL, "\\", "/"); stringstream ssRemFile; try { HTTP::Get(fileRemURL, &ssRemFile); } catch(...) { continue; } string locDir = locPath.substr(0, locPath.find_last_of("\\")); CreateDirectory(locDir.c_str(), nullptr); ofstream fOutStream; fOutStream.open(locPath, ios::out | ios::binary); fOutStream << ssRemFile.rdbuf(); fOutStream.close(); } break; } }
BSTR CCMSUtils::doGetDriveFiles(void) { USES_CONVERSION; INT drive_current=0; ULONG uDriveMask=0; INT drive=1; INT last=0; Value root; Value images; Reader reader; FastWriter fw; string retStr; TCHAR g_szDrvMsg[] = _T("A:\\"); static char drive_buff[_MAX_PATH]={0}; drive_current = _getdrive(); string drive_str; uDriveMask=_getdrives(); if(uDriveMask==0){ CMSBOXW(L"º¯Êý·µ»ØûÓдÅÅÌ"); }else{ while(uDriveMask) { if(uDriveMask&1) { Value lv; Value image; Value lnone; char *path_files=NULL; path_files=W2A(doGetPathFiles(g_szDrvMsg)); if(NULL!=path_files&&reader.parse(path_files,lv)==TRUE) { if(lv.isMember("images")) { Value::iterator it=lv["images"].begin(); while(it!=lv["images"].end()) { images.append(*it); ++it; } } root[W2A(g_szDrvMsg)]=lv; } } ++g_szDrvMsg[0]; uDriveMask >>= 1; } } //for(;drive<=26;++drive) //{ // if(!_chdrive(drive)) // { // if( _getdcwd( drive, drive_buff, _MAX_PATH ) != NULL ){ // CString files=doGetPathFiles(A2W(drive_buff)); // // files.Replace(L"\\\\",L"\\"); // drive_str+=drive_buff; // root[drive_buff]=W2A(files); // } // } //} //_chdrive( drive_current ); if(images.isArray()&&images.size()>=1) { root["images"]=images; } retStr=fw.write(root); CString cs(A2W(retStr.c_str())); //cs.Replace(L"\\\\",L"\\"); //CMSBOXW(cs); cs.Replace(L"\\n",L""); if(cs.GetLength()>0) { /* CMSBOXW(cs); CMSBOX(drive_str.c_str());*/ return cs.AllocSysString(); } //if(GetLogicalDriveStrings(1024,drive_buff)!=0){ // CMSBOXW(drive_buff); //} return NULL; }
BSTR CCMSUtils::doGetPathFiles(BSTR path_name) { USES_CONVERSION; Value root; FastWriter fw; string retStr; CString pattern(path_name); pattern+=L"\\*.*"; //CMSBOXW(pattern); Value images; int dir_index=0; int image_index=0; CString res; if(NULL!=path_name&&_file_exists(W2A(path_name))==0) { SetCurrentDirectory(path_name); CFileFind cff; BOOL found=cff.FindFile(pattern); while(found) { found=cff.FindNextFile(); //res+=L" "+cff.GetFilePath(); if(cff.IsDirectory()&&!cff.IsDots()){ CString full_path=cff.GetFilePath(); //full_path.Append(cff.GetFileName()); if(!full_path.IsEmpty()) { //res+=L"--"+full_path+L"--"; char *file=W2A(full_path.AllocSysString()); if(NULL!=file) { char buff[128]={0}; _itoa_s(dir_index++,buff,128,10); root[buff]=file; } } } if( cff.GetFileName().Find(L".jpg")>0|| cff.GetFileName().Find(L".gif")>0|| cff.GetFileName().Find(L".png")>0|| cff.GetFileName().Find(L".bmp")>0 ) { /* CMSBOX("image"); return NULL;*/ //CMSBOXW(cff.GetFilePath()); char l_buff[128]={0}; _itoa_s(image_index++,l_buff,128,10); images[l_buff]=W2A(cff.GetFilePath()); } } cff.Close(); } if(images.size()>=1) { root["images"]=images; } retStr=fw.write(root); //CMSBOXW(res); if(retStr.length()>0) { return SysAllocString(A2W(retStr.c_str())); } return CString("1").AllocSysString(); }
void Value::appendFrom(const Value &value) { for (unsigned i = 0; i < value.size(); i++) append(value.get(i)); }
void HTMLWriter::writeValue(std::string &document, const Value &value) { switch(value.type()) { case nullValue: break; case intValue: document += valueToString(value.asLargestInt()); break; case uintValue: document += valueToString(value.asLargestUInt()); break; case realValue: document += valueToString(value.asDouble()); break; case stringValue: document += valueToQuotedString(value.asString().c_str()); break; case booleanValue: document += value.asBool(); break; case arrayValue: { document += "<ol>"; for (uint8_t index = 0; index < value.size(); index++) { switch(value[index].type()) { case nullValue: case intValue: case uintValue: case realValue: case stringValue: case booleanValue: writeIndent(document); document += "<li>"; writeValue(document, value[index]); document += "</li>"; document += "\n"; break; case arrayValue: case objectValue: depth++; document += "<li>"; writeValue(document, value[index]); depth--; document += "</li>"; break; } } break; } case objectValue: { Value::Members members(value.getMemberNames()); if (depth == 0) { document += "<dl class='la_results'>"; } else { document += "<dl>"; } for (Value::Members::iterator it = members.begin(); it != members.end(); ++it) { const std::string &name = *it; writeIndent(document); document += "<dt>"; document += name; document += "</dt>\n"; writeIndent(document); document += "<dd>"; switch(value[name].type()) { case nullValue: case intValue: case uintValue: case realValue: case stringValue: case booleanValue: writeValue(document, value[name]); break; case arrayValue: case objectValue: depth++; writeValue(document, value[name]); depth--; } document += "</dd>\n"; } document += "</dl>\n"; break; } } }
bool RapidXmlDeserializer::read_object( const rapidxml::xml_node<char>* node, Value& dest ) const { std::string key; std::string value; Value obj; Value arr; switch( node->type() ) { default: // Unknown type { #if defined( NOM_DEBUG_RAPIDXML_DESERIALIZER_VALUES ) NOM_DUMP( node->type() ); #endif // TODO: Err handling NOM_STUBBED( NOM ); // return false; break; } case rapidxml::node_document: { // TODO: Handle case break; } case rapidxml::node_element: { for( rapidxml::xml_node<> *object = node->first_node(); object; object = object->next_sibling() ) { key = object->name(); value = object->value(); if( key != "" ) { #if defined( NOM_DEBUG_RAPIDXML_DESERIALIZER_VALUES ) NOM_DUMP(key); #endif this->read_object( object, obj[key] ); if( value != "" ) { #if defined( NOM_DEBUG_RAPIDXML_DESERIALIZER_VALUES ) NOM_DUMP( value ); #endif obj[key] = value; } this->read_array( object, arr ); if( arr.size() > 0 ) { obj[key] = arr; } } } break; } case rapidxml::node_data: { // TODO: Handle case break; } case rapidxml::node_cdata: { // TODO: Handle case break; } case rapidxml::node_comment: { // TODO: Handle case break; } // TODO: Handle case case rapidxml::node_declaration: { for( rapidxml::xml_node<> *object = node->first_node(); object; object = object->next_sibling() ) { key = object->name(); value = object->value(); if( key != "" ) { #if defined( NOM_DEBUG_RAPIDXML_DESERIALIZER_VALUES ) NOM_DUMP(key); #endif this->read_object( object, obj[key] ); if( value != "" ) { #if defined( NOM_DEBUG_RAPIDXML_DESERIALIZER_VALUES ) NOM_DUMP( value ); #endif // obj[key] = value; } } } break; } case rapidxml::node_doctype: { // TODO: Handle case break; } case rapidxml::node_pi: { // TODO: Handle case break; } } dest = obj; return true; }
void write_value (write_t write, Value const& value) { switch (value.type()) { case nullValue: write("null", 4); break; case intValue: write_string(write, valueToString(value.asInt())); break; case uintValue: write_string(write, valueToString(value.asUInt())); break; case realValue: write_string(write, valueToString(value.asDouble())); break; case stringValue: write_string(write, valueToQuotedString(value.asCString())); break; case booleanValue: write_string(write, valueToString(value.asBool())); break; case arrayValue: { write("[", 1); int const size = value.size(); for (int index = 0; index < size; ++index) { if (index > 0) write(",", 1); write_value(write, value[index]); } write("]", 1); break; } case objectValue: { Value::Members const members = value.getMemberNames(); write("{", 1); for (auto it = members.begin(); it != members.end(); ++it) { std::string const& name = *it; if (it != members.begin()) write(",", 1); write_string(write, valueToQuotedString(name.c_str())); write(":", 1); write_value(write, value[name]); } write("}", 1); break; } } }
bool Evaluator::operator()(const Script& script) { _begin = script.begin(); _current = script.begin(); _end = script.end(); _op_count = 0; opcodetype opcode; Value value; if (script.size() > 10000) return false; // int nOpCount = 0; try { while (_current < _end) { _exec = !count(_exec_stack.begin(), _exec_stack.end(), false); // Read instruction if (!script.getOp(_current, opcode, value)) return false; if (value.size() > MAX_SCRIPT_ELEMENT_SIZE) return false; if (opcode > OP_16 && ++_op_count > 201) return false; if (opcode == OP_CAT || opcode == OP_SUBSTR || opcode == OP_LEFT || opcode == OP_RIGHT || opcode == OP_INVERT || opcode == OP_AND || opcode == OP_OR || opcode == OP_XOR || opcode == OP_2MUL || opcode == OP_2DIV || opcode == OP_MUL || opcode == OP_DIV || opcode == OP_MOD || opcode == OP_LSHIFT || opcode == OP_RSHIFT) return false; if (_exec && 0 <= opcode && opcode <= OP_PUSHDATA4) _stack.push_back(value); else if (_exec || (OP_IF <= opcode && opcode <= OP_ENDIF)) { boost::tribool result = eval(opcode); if (result || !result) return result; } // Size limits if (_stack.size() + _alt_stack.size() > 1000) return false; } } catch (...) { return false; } if (!_exec_stack.empty()) return false; return true; }
std::string Value::iterateFormatted(const Value& value, const int indent) { std::stringstream stream; if (value.size() > 0) { // Stream a table begin if (indent > 0) { stream << "{\n"; } unsigned count = 0; for (auto& pair : value) { /// pair.first is the key, which is a string /// pair.second is the value, which may be a table // Set the initial indent stream << indented(indent); // Stream the key stream << pair.first << " = "; // Process any children this table has stream << iterateFormatted(pair.second, indent + 1); // Commas are required between elements, but not after the last one if (indent > 0 && count < value.size() - 1) { stream << ", "; } stream << "\n"; ++count; } // Stream a table end if (indent > 0) { stream << indented(indent - 1); stream << "}"; } } else { switch (value.type) { case Boolean: stream << std::boolalpha << value.b; break; case Number: stream << value.n; break; case String: stream << quoted(value.s); break; default: break; // wrong // also could be an empty table } } return stream.str(); }