void StringList::AppendList(StringList strings) { size_t len = strings.GetSize(); for (size_t i = 0; i < len; ++i) m_strings.push_back(strings.GetStringAtIndex(i)); }
void CodeBlocksProvider::writeDefines(const StringList &defines, std::ofstream &output) const { for (StringList::const_iterator i = defines.begin(); i != defines.end(); ++i) output << "\t\t\t\t\t<Add option=\"-D" << *i << "\" />\n"; }
int main(){ LDAPConstraints* cons=new LDAPConstraints; LDAPControlSet* ctrls=new LDAPControlSet; ctrls->add(LDAPCtrl(LDAP_CONTROL_MANAGEDSAIT)); cons->setServerControls(ctrls); LDAPConnection *lc=new LDAPConnection("localhost",9009); lc->setConstraints(cons); std::cout << "----------------------doing bind...." << std::endl; try{ lc->bind("cn=Manager,o=Organisation,c=DE" , "secret",cons); std::cout << lc->getHost() << std::endl; bool result = lc->compare("cn=Manager,o=Organisation,c=DE", LDAPAttribute("cn","Manaer")); std::cout << "Compare: " << result << std::endl; LDAPAttributeList* attrs=new LDAPAttributeList(); StringList values; StringList s2; values.add("top"); values.add("Person"); attrs->addAttribute(LDAPAttribute("objectClass",values)); attrs->addAttribute(LDAPAttribute("cn","Peter")); attrs->addAttribute(LDAPAttribute("sn","Peter,hallo")); LDAPEntry* entry=new LDAPEntry( "cn=Peter , o=Organisation, c=DE", attrs); // lc->add(entry); // lc->del("ou=Groups,o=Organisation,c=DE"); LDAPSearchResults* entries = lc->search("o=Organisation,c=DE", LDAPConnection::SEARCH_ONE); if (entries != 0){ LDAPEntry* entry = entries->getNext(); if(entry != 0){ std::cout << *(entry) << std::endl; } while(entry){ try{ entry = entries->getNext(); if(entry != 0){ std::cout << *(entry) << std::endl; } delete entry; }catch(LDAPReferralException e){ std::cout << "Caught Referral" << std::endl; } } } lc->unbind(); delete lc; }catch (LDAPException &e){ std::cout << "-------------- caught Exception ---------"<< std::endl; std::cout << e << std::endl; } /* std::cout << "--------------------starting search" << std::endl; LDAPAttributeList* attrs=new LDAPAttributeList(); StringList values; values.add("top"); values.add("organizationalUnit"); attrs->addAttribute(LDAPAttribute("objectClass",values)); attrs->addAttribute(LDAPAttribute("ou","Groups")); LDAPEntry* entry=new LDAPEntry( "ou=Groups, o=Organisation, c=DE", attrs); LDAPAttribute newattr("description"); LDAPModification::mod_op op = LDAPModification::OP_DELETE; LDAPModList *mod=new LDAPModList(); mod->addModification(LDAPModification(newattr,op)); LDAPMessageQueue* q=0; try{ q=lc->search("o=Organisation,c=de",LDAPAsynConnection::SEARCH_SUB, "objectClass=*",StringList()); // q=lc->add(entry); // q=lc->modify("cn=Manager,o=Organisation,c=DE", // mod); LDAPMsg *res=q->getNext(); bool cont=true; while( cont ) { switch(res->getMessageType()){ LDAPSearchResult *res2; const LDAPEntry *entry; case LDAP_RES_SEARCH_ENTRY : res2= (LDAPSearchResult*)res; entry= res2->getEntry(); std::cout << "Entry: " << *entry << std::endl; delete res; res=q->getNext(); break; case LDAP_RES_SEARCH_REFERENCE : std::cout << "Reference: " << std::endl; delete res; res=q->getNext(); break; default : std::cout << ( *(LDAPResult*) res) << std::endl; delete res; std::cout << "-----------------search done" << std::endl; cont=false; break; } } delete q; }catch (LDAPException e){ std::cout << "----------------error during search" << std::endl; delete q; std::cout << e << std::endl; } lc->unbind(); */ }
StringList::StringList( const StringList & rhs ) { for( const_iterator iter = rhs.begin(); iter != rhs.end(); ++iter ) add( (*iter)->c_str(), (*iter)->len() ); }
bool CTagLoaderTagLib::ParseID3v2Tag(ID3v2::Tag *id3v2, EmbeddedArt *art, CMusicInfoTag& tag) { // tag.SetURL(strFile); if (!id3v2) return false; ID3v2::AttachedPictureFrame *pictures[3] = {}; const ID3v2::FrameListMap& frameListMap = id3v2->frameListMap(); for (ID3v2::FrameListMap::ConstIterator it = frameListMap.begin(); it != frameListMap.end(); ++it) { if (it->first == "TPE1") SetArtist(tag, GetID3v2StringList(it->second)); else if (it->first == "TALB") tag.SetAlbum(it->second.front()->toString().to8Bit(true)); else if (it->first == "TPE2") SetAlbumArtist(tag, GetID3v2StringList(it->second)); else if (it->first == "TIT2") tag.SetTitle(it->second.front()->toString().to8Bit(true)); else if (it->first == "TCON") SetGenre(tag, GetID3v2StringList(it->second)); else if (it->first == "TRCK") tag.SetTrackNumber(strtol(it->second.front()->toString().toCString(true), NULL, 10)); else if (it->first == "TPOS") tag.SetPartOfSet(strtol(it->second.front()->toString().toCString(true), NULL, 10)); else if (it->first == "TYER") tag.SetYear(strtol(it->second.front()->toString().toCString(true), NULL, 10)); else if (it->first == "TCMP") tag.SetCompilation((strtol(it->second.front()->toString().toCString(true), NULL, 10) == 0) ? false : true); else if (it->first == "TENC") {} // EncodedBy else if (it->first == "TCOP") {} // Copyright message else if (it->first == "TDRC") tag.SetYear(strtol(it->second.front()->toString().toCString(true), NULL, 10)); else if (it->first == "TDRL") tag.SetYear(strtol(it->second.front()->toString().toCString(true), NULL, 10)); else if (it->first == "TDTG") {} // Tagging time else if (it->first == "TLAN") {} // Languages else if (it->first == "USLT") // Loop through any lyrics frames. Could there be multiple frames, how to choose? for (ID3v2::FrameList::ConstIterator lt = it->second.begin(); lt != it->second.end(); ++lt) { ID3v2::UnsynchronizedLyricsFrame *lyricsFrame = dynamic_cast<ID3v2::UnsynchronizedLyricsFrame *> (*lt); if (lyricsFrame) tag.SetLyrics(lyricsFrame->text().to8Bit(true)); } else if (it->first == "COMM") // Loop through and look for the main (no description) comment for (ID3v2::FrameList::ConstIterator ct = it->second.begin(); ct != it->second.end(); ++ct) { ID3v2::CommentsFrame *commentsFrame = dynamic_cast<ID3v2::CommentsFrame *> (*ct); if (commentsFrame && commentsFrame->description().isEmpty()) tag.SetComment(commentsFrame->text().to8Bit(true)); } else if (it->first == "TXXX") // Loop through and process the UserTextIdentificationFrames for (ID3v2::FrameList::ConstIterator ut = it->second.begin(); ut != it->second.end(); ++ut) { ID3v2::UserTextIdentificationFrame *frame = dynamic_cast<ID3v2::UserTextIdentificationFrame *> (*ut); if (!frame) continue; // First field is the same as the description StringList stringList = frame->fieldList(); stringList.erase(stringList.begin()); if (frame->description() == "MusicBrainz Artist Id") tag.SetMusicBrainzArtistID(StringListToVectorString(stringList)); else if (frame->description() == "MusicBrainz Album Id") tag.SetMusicBrainzAlbumID(stringList.front().to8Bit(true)); else if (frame->description() == "MusicBrainz Album Artist Id") tag.SetMusicBrainzAlbumArtistID(StringListToVectorString(stringList)); else if (frame->description() == "replaygain_track_gain") tag.SetReplayGainTrackGain((int)(atof(stringList.front().toCString(true)) * 100 + 0.5)); else if (frame->description() == "replaygain_album_gain") tag.SetReplayGainAlbumGain((int)(atof(stringList.front().toCString(true)) * 100 + 0.5)); else if (frame->description() == "replaygain_track_peak") tag.SetReplayGainTrackPeak((float)atof(stringList.front().toCString(true))); else if (frame->description() == "replaygain_album_peak") tag.SetReplayGainAlbumPeak((float)atof(stringList.front().toCString(true))); else if (frame->description() == "ALBUMARTIST") SetAlbumArtist(tag, StringListToVectorString(stringList)); else if (frame->description() == "ALBUM ARTIST") SetAlbumArtist(tag, StringListToVectorString(stringList)); else if (g_advancedSettings.m_logLevel == LOG_LEVEL_MAX) CLog::Log(LOGDEBUG, "unrecognized user text tag detected: TXXX:%s", frame->description().toCString(true)); } else if (it->first == "UFID") // Loop through any UFID frames and set them for (ID3v2::FrameList::ConstIterator ut = it->second.begin(); ut != it->second.end(); ++ut) { ID3v2::UniqueFileIdentifierFrame *ufid = reinterpret_cast<ID3v2::UniqueFileIdentifierFrame*> (*ut); if (ufid->owner() == "http://musicbrainz.org") { // MusicBrainz pads with a \0, but the spec requires binary, be cautious char cUfid[64]; int max_size = std::min((int)ufid->identifier().size(), 63); strncpy(cUfid, ufid->identifier().data(), max_size); cUfid[max_size] = '\0'; tag.SetMusicBrainzTrackID(cUfid); } } else if (it->first == "APIC") // Loop through all pictures and store the frame pointers for the picture types we want for (ID3v2::FrameList::ConstIterator pi = it->second.begin(); pi != it->second.end(); ++pi) { ID3v2::AttachedPictureFrame *pictureFrame = dynamic_cast<ID3v2::AttachedPictureFrame *> (*pi); if (!pictureFrame) continue; if (pictureFrame->type() == ID3v2::AttachedPictureFrame::FrontCover) pictures[0] = pictureFrame; else if (pictureFrame->type() == ID3v2::AttachedPictureFrame::Other) pictures[1] = pictureFrame; else if (pi == it->second.begin()) pictures[2] = pictureFrame; } else if (it->first == "POPM") // Loop through and process ratings for (ID3v2::FrameList::ConstIterator ct = it->second.begin(); ct != it->second.end(); ++ct) { ID3v2::PopularimeterFrame *popFrame = dynamic_cast<ID3v2::PopularimeterFrame *> (*ct); if (!popFrame) continue; // @xbmc.org ratings trump others (of course) if (popFrame->email() == "*****@*****.**") tag.SetRating(popFrame->rating() / 51 + '0'); else if (tag.GetRating() == '0') { if (popFrame->email() != "Windows Media Player 9 Series" && popFrame->email() != "no@email" && popFrame->email() != "*****@*****.**" && popFrame->email() != "*****@*****.**") CLog::Log(LOGDEBUG, "unrecognized ratings schema detected: %s", popFrame->email().toCString(true)); tag.SetRating(POPMtoXBMC(popFrame->rating())); } } else if (g_advancedSettings.m_logLevel == LOG_LEVEL_MAX) CLog::Log(LOGDEBUG, "unrecognized ID3 frame detected: %c%c%c%c", it->first[0], it->first[1], it->first[2], it->first[3]); } // for // Process the extracted picture frames; 0 = CoverArt, 1 = Other, 2 = First Found picture for (int i = 0; i < 3; ++i) if (pictures[i]) { string mime = pictures[i]->mimeType().to8Bit(true); TagLib::uint size = pictures[i]->picture().size(); tag.SetCoverArtInfo(size, mime); if (art) art->set((const uint8_t*)pictures[i]->picture().data(), size, mime); // Stop after we find the first picture for now. break; } return true; }
p.setValue("item3", 7.6); p.setValue("doublelist", ListUtils::create<double>("1.22,2.33,4.55")); p.setValue("doublelist2", ListUtils::create<double>("")); p.setValue("doublelist3", ListUtils::create<double>("1.4")); //store String filename; NEW_TMP_FILE(filename); paramFile.store(filename,p); //load Param p2; paramFile.load(filename,p2); TEST_EQUAL(p2.size(),12); TEST_EQUAL(p2.getValue("stringlist").valueType(), DataValue::STRING_LIST) StringList list = p2.getValue("stringlist"); TEST_EQUAL(list.size(),3) TEST_EQUAL(list[0],"a") TEST_EQUAL(list[1],"bb") TEST_EQUAL(list[2],"ccc") TEST_EQUAL(p2.getValue("stringlist2").valueType(), DataValue::STRING_LIST) list = p2.getValue("stringlist2"); TEST_EQUAL(list.size(),0) TEST_EQUAL(p2.getValue("stringlist").valueType(), DataValue::STRING_LIST) list = p2.getValue("stringlist3"); TEST_EQUAL(list.size(),1) TEST_EQUAL(list[0],"1") TEST_EQUAL(p2.getValue("intlist").valueType(), DataValue::INT_LIST)
bool PropertySpecification::ParsePropertyValues(StringList& values_list, const String& values, bool split_values) const { String value; enum ParseState { VALUE, VALUE_PARENTHESIS, VALUE_QUOTE }; ParseState state = VALUE; int open_parentheses = 0; size_t character_index = 0; char previous_character = 0; while (character_index < values.Length()) { char character = values[character_index]; character_index++; switch (state) { case VALUE: { if (character == ';') { value = StringUtilities::StripWhitespace(value); if (value.Length() > 0) { values_list.push_back(value); value.Clear(); } } else if (StringUtilities::IsWhitespace(character)) { if (split_values) { value = StringUtilities::StripWhitespace(value); if (value.Length() > 0) { values_list.push_back(value); value.Clear(); } } else value.Append(character); } else if (character == '"') { if (split_values) { value = StringUtilities::StripWhitespace(value); if (value.Length() > 0) { values_list.push_back(value); value.Clear(); } state = VALUE_QUOTE; } else { value.Append(' '); state = VALUE_QUOTE; } } else if (character == '(') { open_parentheses = 1; value.Append(character); state = VALUE_PARENTHESIS; } else { value.Append(character); } } break; case VALUE_PARENTHESIS: { if (previous_character == '/') { if (character == ')' || character == '(') value.Append(character); else { value.Append('/'); value.Append(character); } } else { if (character == '(') { open_parentheses++; value.Append(character); } else if (character == ')') { open_parentheses--; value.Append(character); if (open_parentheses == 0) state = VALUE; } else if (character != '/') { value.Append(character); } } } break; case VALUE_QUOTE: { if (previous_character == '/') { if (character == '"') value.Append(character); else { value.Append('/'); value.Append(character); } } else { if (character == '"') { if (split_values) { value = StringUtilities::StripWhitespace(value); if (value.Length() > 0) { values_list.push_back(value); value.Clear(); } } else value.Append(' '); state = VALUE; } else if (character != '/') { value.Append(character); } } } } previous_character = character; } if (state == VALUE) { value = StringUtilities::StripWhitespace(value); if (value.Length() > 0) values_list.push_back(value); } return true; }
EC2Resource::BatchStatusResult EC2Resource::StartBatchStatus() { ASSERT( status_gahp ); // m_checkSpotNext starts out false if( ! m_checkSpotNext ) { StringList returnStatus; std::string errorCode; int rc = status_gahp->ec2_vm_status_all( resourceName, m_public_key_file, m_private_key_file, returnStatus, errorCode ); if( rc == GAHPCLIENT_COMMAND_PENDING ) { return BSR_PENDING; } if( rc != 0 ) { std::string errorString = status_gahp->getErrorString(); dprintf( D_ALWAYS, "Error doing batched EC2 status query: %s: %s.\n", errorCode.c_str(), errorString.c_str() ); return BSR_ERROR; } // // We have to let a job know if we can't find a status report for it. // List<EC2Job> myJobs; EC2Job * nextJob = NULL; BaseJob *nextBaseJob = NULL; registeredJobs.Rewind(); while ( (nextBaseJob = registeredJobs.Next()) ) { nextJob = dynamic_cast< EC2Job * >( nextBaseJob ); ASSERT( nextJob ); if ( !nextJob->m_client_token.empty() ) { myJobs.Append( nextJob ); } } returnStatus.rewind(); ASSERT( returnStatus.number() % 6 == 0 ); for( int i = 0; i < returnStatus.number(); i += 6 ) { std::string instanceID = returnStatus.next(); std::string status = returnStatus.next(); std::string clientToken = returnStatus.next(); std::string keyName = returnStatus.next(); std::string stateReasonCode = returnStatus.next(); std::string publicDNSName = returnStatus.next(); // Efficiency suggests we look via the instance ID first, // and then try to look things up via the client token // (or, for GT #3682, via the keypair ID). // We can't use BaseJob::JobsByRemoteId because OpenStack doesn't // include the client token in its status responses, and therefore // we can't always fully reconstruct the remoteJobID used as the key. EC2Job * job = NULL; rc = jobsByInstanceID.lookup( HashKey( instanceID.c_str() ), job ); if( rc == 0 ) { ASSERT( job ); dprintf( D_FULLDEBUG, "Found job object for '%s', updating status ('%s').\n", instanceID.c_str(), status.c_str() ); job->StatusUpdate( instanceID.c_str(), status.c_str(), stateReasonCode.c_str(), publicDNSName.c_str() ); myJobs.Delete( job ); continue; } // If we got a client token, use that to look up the job. We // don't use the instance ID because we may discover it in // this function. Since we need instance ID -based dispatch // code for OpenStack anyway, we'll just use it, rather than // trying the remoteJobID with the instance ID if we don't // find it using only the client token. if( ! clientToken.empty() && clientToken != "NULL" ) { std::string remoteJobID; formatstr( remoteJobID, "ec2 %s %s", resourceName, clientToken.c_str() ); BaseJob * tmp = NULL; rc = BaseJob::JobsByRemoteId.lookup( HashKey( remoteJobID.c_str() ), tmp ); if( rc == 0 ) { ASSERT( tmp ); EC2Job * job = dynamic_cast< EC2Job * >( tmp ); if( job == NULL ) { EXCEPT( "Found non-EC2Job identified by '%s'.", remoteJobID.c_str() ); } dprintf( D_FULLDEBUG, "Found job object via client token for '%s', updating status ('%s').\n", instanceID.c_str(), status.c_str() ); job->StatusUpdate( instanceID.c_str(), status.c_str(), stateReasonCode.c_str(), publicDNSName.c_str() ); myJobs.Delete( job ); continue; } } // Some servers (OpenStack, Eucalyptus) silently ignore client // tokens. So we need to use the ssh keypair to find jobs that // were submitted but which we don't have an instance ID for. // // TODO This code should be made more efficient. We can // do something better than a linear scan through all // jobs for each status result. Ideally, we'd parse the // ssh keypair name and if it looks like one we generated, // pluck out the job id. if ( !ClientTokenWorks() && !keyName.empty() && keyName != "NULL" ) { myJobs.Rewind(); while ( ( job = myJobs.Next() ) ) { if ( job->m_key_pair == keyName ) { dprintf( D_FULLDEBUG, "Found job object via ssh keypair for '%s', updating status ('%s').\n", instanceID.c_str(), status.c_str() ); job->StatusUpdate( instanceID.c_str(), status.c_str(), stateReasonCode.c_str(), publicDNSName.c_str() ); myJobs.Delete( job ); continue; } } } dprintf( D_FULLDEBUG, "Found unknown instance '%s'; skipping.\n", instanceID.c_str() ); continue; } myJobs.Rewind(); while( ( nextJob = myJobs.Next() ) ) { dprintf( D_FULLDEBUG, "Informing job %p it got no status.\n", nextJob ); nextJob->StatusUpdate( NULL, NULL, NULL, NULL ); } // Don't ask for spot results unless we know about a spot job. This // should prevent us from breaking OpenStack. if( spotJobsByRequestID.getNumElements() == 0 ) { m_checkSpotNext = false; return BSR_DONE; } else { m_checkSpotNext = true; } } if( m_checkSpotNext ) { StringList spotReturnStatus; std::string spotErrorCode; int spotRC = status_gahp->ec2_spot_status_all( resourceName, m_public_key_file, m_private_key_file, spotReturnStatus, spotErrorCode ); if( spotRC == GAHPCLIENT_COMMAND_PENDING ) { return BSR_PENDING; } if( spotRC != 0 ) { std::string errorString = status_gahp->getErrorString(); dprintf( D_ALWAYS, "Error doing batched EC2 spot status query: %s: %s.\n", spotErrorCode.c_str(), errorString.c_str() ); return BSR_ERROR; } List<EC2Job> mySpotJobs; EC2Job * nextSpotJob = NULL; spotJobsByRequestID.startIterations(); while( spotJobsByRequestID.iterate( nextSpotJob ) ) { mySpotJobs.Append( nextSpotJob ); } spotReturnStatus.rewind(); ASSERT( spotReturnStatus.number() % 5 == 0 ); for( int i = 0; i < spotReturnStatus.number(); i += 5 ) { std::string requestID = spotReturnStatus.next(); std::string state = spotReturnStatus.next(); /* std::string launchGroup = */ spotReturnStatus.next(); /* std::string instanceID = */ spotReturnStatus.next(); std::string statusCode = spotReturnStatus.next(); EC2Job * spotJob = NULL; spotRC = spotJobsByRequestID.lookup( HashKey( requestID.c_str() ), spotJob ); if( spotRC != 0 ) { dprintf( D_FULLDEBUG, "Found unknown spot request '%s'; skipping.\n", requestID.c_str() ); continue; } ASSERT( spotJob ); if( ! statusCode.empty() ) { state = statusCode; } dprintf( D_FULLDEBUG, "Found spot job object for '%s', updating status ('%s').\n", requestID.c_str(), state.c_str() ); spotJob->StatusUpdate( NULL, state.c_str(), NULL, NULL ); mySpotJobs.Delete( spotJob ); } mySpotJobs.Rewind(); while( ( nextSpotJob = mySpotJobs.Next() ) ) { dprintf( D_FULLDEBUG, "Informing spot job %p it got no status.\n", nextSpotJob ); nextSpotJob->StatusUpdate( NULL, NULL, NULL, NULL ); } m_checkSpotNext = false; return BSR_DONE; } // This should never happen (but the compiler hates you). return BSR_ERROR; }
void StringListUtils::toLower(StringList & sl) { std::for_each(sl.begin(), sl.end(), boost::mem_fn(&String::toLower)); }
using namespace OpenMS; using namespace std; /////////////////////////// START_TEST(StringList, "$Id$") ///////////////////////////////////////////////////////////// START_SECTION((static StringList fromQStringList(const QStringList &rhs))) { QStringList q_str_list; q_str_list << "First Element" << "Second Element" << "Third Element"; StringList str_list = StringListUtils::fromQStringList(q_str_list); TEST_EQUAL((int)str_list.size(), q_str_list.size()) ABORT_IF((int)str_list.size() != q_str_list.size()) for(Size i = 0 ; i < str_list.size() ; ++i) { TEST_EQUAL(str_list[i], String(q_str_list[(int)i])) } } END_SECTION START_SECTION((static void toUpper(StringList &sl))) { StringList list = ListUtils::create<String>("yes,no"); StringListUtils::toUpper(list); TEST_EQUAL(list[0],"YES")
virtual void SetSourceOrder(StringList &sourceNames) { StringList* order = new StringList(); order->CopyList(sourceNames); PostMessage(hwndMain, OBS_SETSOURCEORDER, 0, (LPARAM) order); }
void PepNovoOutfile::load( const std::string & result_filename, vector<PeptideIdentification> & peptide_identifications, ProteinIdentification & protein_identification, const double & score_threshold, const IndexPosMappingType & index_to_precursor, const map<String, String> & pnovo_modkey_to_mod_id ) { // generally used variables StringList substrings; map<String, Int> columns; PeptideHit peptide_hit; String line, score_type = "PepNovo", version = "unknown", identifier, filename, sequence, sequence_with_mods; DateTime datetime = DateTime::now(); // there's no date given from PepNovo protein_identification.setDateTime(datetime); peptide_identifications.clear(); PeptideIdentification peptide_identification; protein_identification = ProteinIdentification(); // open the result ifstream result_file(result_filename.c_str()); if (!result_file) { throw Exception::FileNotFound(__FILE__, __LINE__, OPENMS_PRETTY_FUNCTION, result_filename); } Size line_number(0); // used to report in which line an error occurred Size id_count(0); // number of IDs seen (not necessarily the ones finally returned) getSearchEngineAndVersion(result_filename, protein_identification); //if information could not be retrieved from the outfile use defaults if (protein_identification.getSearchEngineVersion().empty()) { protein_identification.setSearchEngine("PepNovo"); protein_identification.setSearchEngineVersion(version); } identifier = protein_identification.getSearchEngine() + "_" + datetime.getDate(); protein_identification.setIdentifier(identifier); map<String, String> mod_mask_map; const vector<String> & mods = protein_identification.getSearchParameters().variable_modifications; for (vector<String>::const_iterator mod_it = mods.begin(); mod_it != mods.end(); ++mod_it) { if (mod_it->empty()) continue; //cout<<*mod_it<<endl; if (pnovo_modkey_to_mod_id.find(*mod_it) != pnovo_modkey_to_mod_id.end()) { //cout<<keys_to_id.find(*mod_it)->second<<endl; ResidueModification tmp_mod = ModificationsDB::getInstance()->getModification(pnovo_modkey_to_mod_id.find(*mod_it)->second); if (mod_it->prefix(1) == "^" || mod_it->prefix(1) == "$") { mod_mask_map[*mod_it] = "(" + tmp_mod.getId() + ")"; } else { mod_mask_map[*mod_it] = String(tmp_mod.getOrigin()) + "(" + tmp_mod.getId() + ")"; } } else { if (mod_it->prefix(1) != "^" && mod_it->prefix(1) != "$") { mod_mask_map[*mod_it] = mod_it->prefix(1) + "[" + mod_it->substr(1) + "]"; //cout<<mod_mask_map[*mod_it]<<endl; } else { mod_mask_map[*mod_it] = "[" + *mod_it + "]"; //cout<<mod_mask_map[*mod_it]<<endl; } } } Size index; while (getline(result_file, line)) { if (!line.empty() && (line[line.length() - 1] < 33)) line.resize(line.length() - 1); // remove weird EOL character line.trim(); ++line_number; if (line.hasPrefix(">> ")) // >> 1 /home/shared/pepnovo/4611_raw_ms2_picked.mzXML.1001.2.dta { ++id_count; if (!peptide_identification.empty() && !peptide_identification.getHits().empty()) { peptide_identifications.push_back(peptide_identification); } line.split(' ', substrings); //String index = File::basename(line.substr(line.find(' ', strlen(">> ")) + 1)); if (substrings.size() < 3) { throw Exception::ParseError(__FILE__, __LINE__, OPENMS_PRETTY_FUNCTION, "Not enough columns (spectrum Id) in file in line " + String(line_number) + String(" (should be 2 or more)!"), result_filename); } try { index = substrings[2].trim().toInt(); } catch (...) { throw Exception::ParseError(__FILE__, __LINE__, OPENMS_PRETTY_FUNCTION, "Expected an index number in line " + String(line_number) + String(" at position 2 (line was: '" + line + "')!"), result_filename); } //cout<<"INDEX: "<<index<<endl; peptide_identification = PeptideIdentification(); bool success = false; if (index_to_precursor.size()>0) { if (index_to_precursor.find(index) != index_to_precursor.end()) { peptide_identification.setRT(index_to_precursor.find(index)->second.first); peptide_identification.setMZ(index_to_precursor.find(index)->second.second); success = true; } else throw Exception::ParseError(__FILE__, __LINE__, OPENMS_PRETTY_FUNCTION, "Index '" + String(index) + String("' in line '" + line + "' not found in index table (line was: '" + line + "')!"), result_filename); } if (!success) { // try to reconstruct from title entry (usually sensible when MGF is supplied to PepNovo) try { if (substrings.size() >= 4) { StringList parts = ListUtils::create<String>(substrings[3], '_'); if (parts.size() >= 2) { peptide_identification.setRT(parts[1].toDouble()); peptide_identification.setMZ(parts[0].toDouble()); success = true; } } } catch (...) { } if (!success) throw Exception::ParseError(__FILE__, __LINE__, OPENMS_PRETTY_FUNCTION, "Precursor could not be reconstructed from title '" + substrings[3] + String("' in line '" + line + "' (line was: '" + line + "')!"), result_filename); } peptide_identification.setSignificanceThreshold(score_threshold); peptide_identification.setScoreType(score_type); peptide_identification.setIdentifier(identifier); } else if (line.hasPrefix("#Index")) // #Index Prob Score N-mass C-Mass [M+H] Charge Sequence { if (columns.empty()) // map the column names to their column number { line.split('\t', substrings); for (vector<String>::const_iterator s_i = substrings.begin(); s_i != substrings.end(); ++s_i) { if ((*s_i) == "#Index") columns["Index"] = s_i - substrings.begin(); else if ((*s_i) == "RnkScr") columns["RnkScr"] = s_i - substrings.begin(); else if ((*s_i) == "PnvScr") columns["PnvScr"] = s_i - substrings.begin(); else if ((*s_i) == "N-Gap") columns["N-Gap"] = s_i - substrings.begin(); else if ((*s_i) == "C-Gap") columns["C-Gap"] = s_i - substrings.begin(); else if ((*s_i) == "[M+H]") columns["[M+H]"] = s_i - substrings.begin(); else if ((*s_i) == "Charge") columns["Charge"] = s_i - substrings.begin(); else if ((*s_i) == "Sequence") columns["Sequence"] = s_i - substrings.begin(); } if (columns.size() != 8) { result_file.close(); result_file.clear(); throw Exception::ParseError(__FILE__, __LINE__, OPENMS_PRETTY_FUNCTION, "Not enough columns in file in line " + String(line_number) + String(" (should be 8)!"), result_filename); } } while (getline(result_file, line)) { ++line_number; if (!line.empty() && (line[line.length() - 1] < 33)) line.resize(line.length() - 1); line.trim(); if (line.empty()) break; line.split('\t', substrings); if (!substrings.empty()) { if (substrings.size() != 8) { result_file.close(); result_file.clear(); throw Exception::ParseError(__FILE__, __LINE__, OPENMS_PRETTY_FUNCTION, "Not enough columns in file in line " + String(line_number) + String(" (should be 8)!"), result_filename); } if (substrings[columns["RnkScr"]].toFloat() >= score_threshold) { peptide_hit = PeptideHit(); peptide_hit.setCharge(substrings[columns["Charge"]].toInt()); peptide_hit.setRank(substrings[columns["Index"]].toInt() + 1); peptide_hit.setScore(substrings[columns["RnkScr"]].toFloat()); peptide_hit.setMetaValue("PnvScr", substrings[columns["PnvScr"]].toFloat()); peptide_hit.setMetaValue("N-Gap", substrings[columns["N-Gap"]].toFloat()); peptide_hit.setMetaValue("C-Gap", substrings[columns["C-Gap"]].toFloat()); peptide_hit.setMetaValue("MZ", substrings[columns["[M+H]"]].toFloat()); sequence = substrings[columns["Sequence"]]; for (map<String, String>::iterator mask_it = mod_mask_map.begin(); mask_it != mod_mask_map.end(); ++mask_it) { if (mask_it->first.hasPrefix("^") && sequence.hasSubstring(mask_it->first)) { sequence.substitute(mask_it->first, ""); sequence = mask_it->second + sequence; } //cout<<mask_it->first<<" "<<mask_it->second<<endl; sequence.substitute(mask_it->first, mask_it->second); } peptide_hit.setSequence(AASequence::fromString(sequence)); peptide_identification.insertHit(peptide_hit); } } } } } if (!peptide_identifications.empty() || !peptide_identification.getHits().empty()) { peptide_identifications.push_back(peptide_identification); } result_file.close(); result_file.clear(); LOG_INFO << "Parsed " << id_count << " ids, retained " << peptide_identifications.size() << "." << std::endl; }
// creates a page based on user input -- either displays data from // form or presents a form for users to submit data. ResponseCode FormTester::HandleRequest ( HttpRequest * ipoHttpRequest, HttpResponse * ipoHttpResponse ) { char psHtml[ 5000 ]; // if we got data from the user, show it if ( ipoHttpRequest->oFormValueMap [ "user" ].sBody.length ( ) || ipoHttpRequest->oFormValueMap [ "existinguser" ].sBody.length ( ) ) { std::string sName; sName = ipoHttpRequest->oFormValueMap [ "existinguser" ].sBody; if ( ipoHttpRequest->oFormValueMap [ "user" ].sBody.length() ) { sName = ipoHttpRequest->oFormValueMap [ "user" ].sBody; } fprintf ( stderr, "Got name of %s\n", sName.c_str ( ) ); char * psHtml = new char [ 5000 ]; sprintf ( psHtml, "<html><head><title>StringList</title></head>\n<body>Hi %s</body></html>", sName.c_str ( ) ); oNameList.push_back ( sName ); ipoHttpResponse->SetBody( psHtml, strlen( psHtml ) ); return HTTPRESPONSECODE_200_OK; } else { // otherwise, present the form to the user to fill in fprintf ( stderr, "Got no form data\n" ); // create the options for the dropdown box char * psOptions; if ( oNameList.size ( ) > 0 ) psOptions = new char [ oNameList.size ( ) * 200 ]; else psOptions = new char [1]; psOptions [ 0 ] = '\0'; for ( StringList::iterator oCurrentName = oNameList.begin(); oCurrentName != oNameList.end ( ); oCurrentName++ ) { char psOption [ 200 ]; sprintf ( psOption, "<option>%s\n", oCurrentName->substr ( 0, 150 ).c_str ( ) ); strcat ( psOptions, psOption ); } sprintf ( psHtml, "<html><head><title>StringList</title></head> <body>Please log in<P> <form action = \"/\" method=GET> User name: <input type = text name = user><BR> <select name = existinguser width = 20> %s </select> <input type = submit> </form>\n", psOptions ); delete[] psOptions; ipoHttpResponse->SetBody( psHtml, strlen( psHtml ) ); return HTTPRESPONSECODE_200_OK; } }
int CondorQ::fetchQueueFromHostAndProcessV2(const char *host, const char *constraint, StringList &attrs, condor_q_process_func process_func, void * process_func_data, int connect_timeout, CondorError *errstack) { classad::ClassAdParser parser; classad::ExprTree *expr = NULL; parser.ParseExpression(constraint, expr); if (!expr) return Q_INVALID_REQUIREMENTS; classad::ExprList *projList = new classad::ExprList(); if (!projList) return Q_INTERNAL_ERROR; attrs.rewind(); const char *attr; while ((attr = attrs.next())) { classad::Value value; value.SetStringValue(attr); classad::ExprTree *entry = classad::Literal::MakeLiteral(value); if (!entry) return Q_INTERNAL_ERROR; projList->push_back(entry); } classad::ClassAd ad; ad.Insert(ATTR_REQUIREMENTS, expr); classad::ExprTree *projTree = static_cast<classad::ExprTree*>(projList); ad.Insert(ATTR_PROJECTION, projTree); DCSchedd schedd(host); Sock* sock; if (!(sock = schedd.startCommand(QUERY_JOB_ADS, Stream::reli_sock, connect_timeout, errstack))) return Q_SCHEDD_COMMUNICATION_ERROR; classad_shared_ptr<Sock> sock_sentry(sock); if (!putClassAd(sock, ad) || !sock->end_of_message()) return Q_SCHEDD_COMMUNICATION_ERROR; dprintf(D_FULLDEBUG, "Sent classad to schedd\n"); do { classad_shared_ptr<compat_classad::ClassAd> ad(new ClassAd()); if (!getClassAd(sock, *ad.get())) return Q_SCHEDD_COMMUNICATION_ERROR; if (!sock->end_of_message()) return Q_SCHEDD_COMMUNICATION_ERROR; dprintf(D_FULLDEBUG, "Got classad from schedd.\n"); long long intVal; if (ad->EvaluateAttrInt(ATTR_OWNER, intVal) && (intVal == 0)) { // Last ad. sock->close(); dprintf(D_FULLDEBUG, "Ad was last one from schedd.\n"); std::string errorMsg; if (ad->EvaluateAttrInt(ATTR_ERROR_CODE, intVal) && intVal && ad->EvaluateAttrString(ATTR_ERROR_STRING, errorMsg)) { if (errstack) errstack->push("TOOL", intVal, errorMsg.c_str()); return Q_REMOTE_ERROR; } break; } (*process_func) (process_func_data, ad); } while (true); return 0; }
ExitCodes main_(int, const char**) { ExitCodes ret = checkParameters_(); if (ret != EXECUTION_OK) return ret; MapAlignmentAlgorithmSpectrumAlignment algorithm; Param algo_params = getParam_().copy("algorithm:", true); algorithm.setParameters(algo_params); algorithm.setLogType(log_type_); StringList ins = getStringList_("in"); StringList outs = getStringList_("out"); StringList trafos = getStringList_("trafo_out"); Param model_params = getParam_().copy("model:", true); String model_type = model_params.getValue("type"); model_params = model_params.copy(model_type + ":", true); std::vector<TransformationDescription> transformations; //------------------------------------------------------------- // perform peak alignment //------------------------------------------------------------- ProgressLogger progresslogger; progresslogger.setLogType(log_type_); // load input std::vector<MSExperiment<> > peak_maps(ins.size()); MzMLFile f; f.setLogType(log_type_); progresslogger.startProgress(0, ins.size(), "loading input files"); for (Size i = 0; i < ins.size(); ++i) { progresslogger.setProgress(i); f.load(ins[i], peak_maps[i]); } progresslogger.endProgress(); // try to align algorithm.align(peak_maps, transformations); if (model_type != "none") { for (vector<TransformationDescription>::iterator it = transformations.begin(); it != transformations.end(); ++it) { it->fitModel(model_type, model_params); } } // write output progresslogger.startProgress(0, outs.size(), "applying RT transformations and writing output files"); for (Size i = 0; i < outs.size(); ++i) { progresslogger.setProgress(i); MapAlignmentTransformer::transformRetentionTimes(peak_maps[i], transformations[i]); // annotate output with data processing info addDataProcessing_(peak_maps[i], getProcessingInfo_(DataProcessing::ALIGNMENT)); f.store(outs[i], peak_maps[i]); } progresslogger.endProgress(); if (!trafos.empty()) { TransformationXMLFile trafo_file; for (Size i = 0; i < transformations.size(); ++i) { trafo_file.store(trafos[i], transformations[i]); } } return EXECUTION_OK; }
StringListUtils::ConstIterator StringListUtils::searchSuffix(const StringList & container, const String & text, bool trim) { return searchSuffix(container.begin(), container.end(), text, trim); }
void CryptoManager::loadCertificates() throw() { if(!BOOLSETTING(USE_TLS)) return; SSL_CTX_set_verify(serverContext, SSL_VERIFY_NONE, 0); SSL_CTX_set_verify(clientContext, SSL_VERIFY_NONE, 0); SSL_CTX_set_verify(clientVerContext, SSL_VERIFY_PEER | SSL_VERIFY_FAIL_IF_NO_PEER_CERT, 0); SSL_CTX_set_verify(serverVerContext, SSL_VERIFY_PEER | SSL_VERIFY_FAIL_IF_NO_PEER_CERT, 0); const string& cert = SETTING(TLS_CERTIFICATE_FILE); const string& key = SETTING(TLS_PRIVATE_KEY_FILE); if(cert.empty() || key.empty()) { LogManager::getInstance()->message(STRING(NO_CERTIFICATE_FILE_SET)); return; } if(File::getSize(cert) == -1 || File::getSize(key) == -1) { // Try to generate them... try { generateCertificate(); } catch(const CryptoException& e) { LogManager::getInstance()->message(STRING(CERTIFICATE_GENERATION_FAILED) + e.getError()); } } if(SSL_CTX_use_certificate_file(serverContext, SETTING(TLS_CERTIFICATE_FILE).c_str(), SSL_FILETYPE_PEM) != SSL_SUCCESS) { LogManager::getInstance()->message(STRING(FAILED_TO_LOAD_CERTIFICATE)); return; } if(SSL_CTX_use_certificate_file(clientContext, SETTING(TLS_CERTIFICATE_FILE).c_str(), SSL_FILETYPE_PEM) != SSL_SUCCESS) { LogManager::getInstance()->message(STRING(FAILED_TO_LOAD_CERTIFICATE)); return; } if(SSL_CTX_use_certificate_file(serverVerContext, SETTING(TLS_CERTIFICATE_FILE).c_str(), SSL_FILETYPE_PEM) != SSL_SUCCESS) { LogManager::getInstance()->message(STRING(FAILED_TO_LOAD_CERTIFICATE)); return; } if(SSL_CTX_use_certificate_file(clientVerContext, SETTING(TLS_CERTIFICATE_FILE).c_str(), SSL_FILETYPE_PEM) != SSL_SUCCESS) { LogManager::getInstance()->message(STRING(FAILED_TO_LOAD_CERTIFICATE)); return; } if(SSL_CTX_use_PrivateKey_file(serverContext, SETTING(TLS_PRIVATE_KEY_FILE).c_str(), SSL_FILETYPE_PEM) != SSL_SUCCESS) { LogManager::getInstance()->message(STRING(FAILED_TO_LOAD_PRIVATE_KEY)); return; } if(SSL_CTX_use_PrivateKey_file(clientContext, SETTING(TLS_PRIVATE_KEY_FILE).c_str(), SSL_FILETYPE_PEM) != SSL_SUCCESS) { LogManager::getInstance()->message(STRING(FAILED_TO_LOAD_PRIVATE_KEY)); return; } if(SSL_CTX_use_PrivateKey_file(serverVerContext, SETTING(TLS_PRIVATE_KEY_FILE).c_str(), SSL_FILETYPE_PEM) != SSL_SUCCESS) { LogManager::getInstance()->message(STRING(FAILED_TO_LOAD_PRIVATE_KEY)); return; } if(SSL_CTX_use_PrivateKey_file(clientVerContext, SETTING(TLS_PRIVATE_KEY_FILE).c_str(), SSL_FILETYPE_PEM) != SSL_SUCCESS) { LogManager::getInstance()->message(STRING(FAILED_TO_LOAD_PRIVATE_KEY)); return; } StringList certs = File::findFiles(SETTING(TLS_TRUSTED_CERTIFICATES_PATH), "*.pem"); StringList certs2 = File::findFiles(SETTING(TLS_TRUSTED_CERTIFICATES_PATH), "*.crt"); certs.insert(certs.end(), certs2.begin(), certs2.end()); for(StringIter i = certs.begin(); i != certs.end(); ++i) { if( SSL_CTX_load_verify_locations(clientContext, i->c_str(), NULL) != SSL_SUCCESS || SSL_CTX_load_verify_locations(clientVerContext, i->c_str(), NULL) != SSL_SUCCESS || SSL_CTX_load_verify_locations(serverContext, i->c_str(), NULL) != SSL_SUCCESS || SSL_CTX_load_verify_locations(serverVerContext, i->c_str(), NULL) != SSL_SUCCESS ) { LogManager::getInstance()->message("Failed to load trusted certificate from " + *i); } } certsLoaded = true; }
bool DictClient::parse(gchar *line, int status_code) { g_debug("get %s\n", line); if (!cmd_.get()) { if (status_code == STATUS_CONNECT) is_connected_ = true; else if (status_code == STATUS_SERVER_DOWN || status_code == STATUS_SHUTDOWN) { gchar *mes = g_strdup_printf("Unable to connect to the " "dictionary server at '%s:%d'. " "The server replied with code" " %d (server down)", host_.c_str(), port_, status_code); on_error_.emit(mes); g_free(mes); return true; } else { gchar *mes = g_strdup_printf("Unable to parse the dictionary" " server reply: '%s'", line); on_error_.emit(mes); g_free(mes); return false; } } bool success = false; switch (status_code) { case STATUS_BAD_PARAMETERS: { gchar *mes = g_strdup_printf("Bad parameters for command '%s'", cmd_->query().c_str()); on_error_.emit(mes); g_free(mes); cmd_->state_ = DICT::Cmd::FINISH; break; } case STATUS_BAD_COMMAND: { gchar *mes = g_strdup_printf("Bad command '%s'", cmd_->query().c_str()); on_error_.emit(mes); g_free(mes); cmd_->state_ = DICT::Cmd::FINISH; break; } default: success = true; break; } if (cmd_->state_ == DICT::Cmd::START) { GError *err = NULL; cmd_->send(channel_, err); if (err) { on_error_.emit(err->message); g_error_free(err); return false; } return true; } if (status_code == STATUS_OK || cmd_->state_ == DICT::Cmd::FINISH || status_code == STATUS_NO_MATCH || status_code == STATUS_BAD_DATABASE || status_code == STATUS_BAD_STRATEGY || status_code == STATUS_NO_DATABASES_PRESENT || status_code == STATUS_NO_STRATEGIES_PRESENT) { defmap_.clear(); const DICT::DefList& res = cmd_->result(); if (simple_lookup_) { IndexList ilist(res.size()); for (size_t i = 0; i < res.size(); ++i) { ilist[i] = last_index_; defmap_.insert(std::make_pair(last_index_++, res[i])); } last_index_ = 0; cmd_.reset(0); disconnect(); on_simple_lookup_end_.emit(ilist); } else { StringList slist; for (size_t i = 0; i < res.size(); ++i) slist.push_back(res[i].word_); last_index_ = 0; cmd_.reset(0); disconnect(); on_complex_lookup_end_.emit(slist); } return success; } if (!cmd_->parse(line, status_code)) return false; return true; }
void SettingsPublish::SetWarningInfo() { int serviceID = (int)SendMessage(GetDlgItem(hwnd, IDC_SERVICE), CB_GETITEMDATA, SendMessage(GetDlgItem(hwnd, IDC_SERVICE), CB_GETCURSEL, 0, 0), 0); bool bUseCBR = AppConfig->GetInt(TEXT("Video Encoding"), TEXT("UseCBR"), 1) != 0; int maxBitRate = AppConfig->GetInt(TEXT("Video Encoding"), TEXT("MaxBitrate"), 1000); int keyframeInt = AppConfig->GetInt(TEXT("Video Encoding"), TEXT("KeyframeInterval"), 0); int audioBitRate = AppConfig->GetInt(TEXT("Audio Encoding"), TEXT("Bitrate"), 96); String currentx264Profile = AppConfig->GetString(TEXT("Video Encoding"), TEXT("X264Profile"), L"high"); String currentAudioCodec = AppConfig->GetString(TEXT("Audio Encoding"), TEXT("Codec"), TEXT("AAC")); //ignore for non-livestreams if (data->mode != 0) { SetDlgItemText(hwnd, IDC_WARNINGS, TEXT("")); return; } int errors = 0; String strWarnings; XConfig serverData; if(serverData.Open(TEXT("services.xconfig"))) { XElement *services = serverData.GetElement(TEXT("services")); if(services) { UINT numServices = services->NumElements(); for(UINT i=0; i<numServices; i++) { XElement *service = services->GetElementByID(i); if (service->GetInt(TEXT("id")) == serviceID) { strWarnings = FormattedString(Str("Settings.Publish.Warning.BadSettings"), service->GetName()); //check to see if the service we're using has recommendations if (!service->HasItem(TEXT("recommended"))) { SetDlgItemText(hwnd, IDC_WARNINGS, TEXT("")); return; } XElement *r = service->GetElement(TEXT("recommended")); if (r->HasItem(TEXT("ratecontrol"))) { CTSTR rc = r->GetString(TEXT("ratecontrol")); if (!scmp (rc, TEXT("cbr")) && !bUseCBR) { errors++; strWarnings << Str("Settings.Publish.Warning.UseCBR"); } } if (r->HasItem(TEXT("max bitrate"))) { int max_bitrate = r->GetInt(TEXT("max bitrate")); if (maxBitRate > max_bitrate) { errors++; strWarnings << FormattedString(Str("Settings.Publish.Warning.Maxbitrate"), max_bitrate); } } if (r->HasItem(TEXT("profile"))) { String expectedProfile = r->GetString(TEXT("profile")); if (!expectedProfile.CompareI(currentx264Profile)) { errors++; strWarnings << Str("Settings.Publish.Warning.RecommendMainProfile"); } } if (r->HasItem(TEXT("max audio bitrate aac")) && (!scmp(currentAudioCodec, TEXT("AAC")))) { int maxaudioaac = r->GetInt(TEXT("max audio bitrate aac")); if (audioBitRate > maxaudioaac) { errors++; strWarnings << FormattedString(Str("Settings.Publish.Warning.MaxAudiobitrate"), maxaudioaac); } } if (r->HasItem(TEXT("max audio bitrate mp3")) && (!scmp(currentAudioCodec, TEXT("MP3")))) { int maxaudiomp3 = r->GetInt(TEXT("max audio bitrate mp3")); if (audioBitRate > maxaudiomp3) { errors++; strWarnings << FormattedString(Str("Settings.Publish.Warning.MaxAudiobitrate"), maxaudiomp3); } } if (r->HasItem(TEXT("keyint"))) { int keyint = r->GetInt(TEXT("keyint")); if (!keyframeInt || keyframeInt * 1000 > keyint) { errors++; strWarnings << FormattedString(Str("Settings.Publish.Warning.Keyint"), keyint / 1000); } } if (r->HasItem(L"supported audio codec")) { StringList codecs; r->GetStringList(L"supported audio codec", codecs); if (codecs.FindValueIndex(currentAudioCodec) == INVALID) { String msg = Str("Settings.Publish.Warning.UnsupportedAudioCodec"); //good thing OBS only supports MP3 (and AAC), otherwise I'd have to come up with a better translation solution msg.FindReplace(L"$1", codecs[0].Array()); msg.FindReplace(L"$2", currentAudioCodec.Array()); errors += 1; strWarnings << msg; } } break; } } } } if (errors) SetDlgItemText(hwnd, IDC_WARNINGS, strWarnings.Array()); else SetDlgItemText(hwnd, IDC_WARNINGS, TEXT("")); }
ExitCodes main_(int, const char**) { //------------------------------------------------------------- // parsing parameters //------------------------------------------------------------- String in = getStringOption_("in"); String out = getStringOption_("out"); String target_qp = getStringOption_("qp_att_acc"); String target_acc = getStringOption_("cv_acc"); String target_run = getStringOption_("name"); String target_file = getStringOption_("run"); String plot_file = getStringOption_("plot"); String tab = getStringOption_("table"); //------------------------------------------------------------- // fetch vocabularies //------------------------------------------------------------ ControlledVocabulary cv; cv.loadFromOBO("PSI-MS", File::find("/CV/psi-ms.obo")); cv.loadFromOBO("QC", File::find("/CV/qc-cv.obo")); //------------------------------------------------------------- // reading input //------------------------------------------------------------ if (target_file != "") { target_run = QFileInfo(QString::fromStdString(target_file)).baseName(); } QcMLFile qcmlfile; if (in != "") { qcmlfile.load(in); } if (target_run == "") { //~ check if only one run in file std::vector<String> nas; qcmlfile.getRunNames(nas); if (nas.size() == 1) { target_run = nas.front(); } else { cerr << "Error: You have to give at least one of the following parameter (in ascending precedence): name, run. Aborting!" << endl; return ILLEGAL_PARAMETERS; } } QFile f(plot_file.c_str()); String plot_b64; if (f.open(QIODevice::ReadOnly)) { QByteArray ba = f.readAll(); f.close(); plot_b64 = String(QString(ba.toBase64())); } QcMLFile::Attachment at; at.cvAcc = target_acc; at.id = String(UniqueIdGenerator::getUniqueId()); at.cvRef = "QC"; //TODO assign right cv reference if (plot_b64 != "" || tab != "") { if (plot_b64 != "") { try { const ControlledVocabulary::CVTerm& term = cv.getTerm(target_acc); at.name = term.name; ///< Name //~ at.unitRef; //TODO MIME type //~ at.unitAcc; } catch (...) { cerr << "Error: You have to give the accession of a existing cv term. Aborting!" << endl; return ILLEGAL_PARAMETERS; } at.binary = plot_b64; } else if (tab != "") { try { const ControlledVocabulary::CVTerm& term = cv.getTerm(target_acc); at.name = term.name; ///< Name //~ at.unitRef; //TODO MIME type //~ at.unitAcc; } catch (...) { cerr << "Error: You have to give the accession of a existing cv term. Aborting!" << endl; return ILLEGAL_PARAMETERS; } CsvFile csv_file(tab); if (csv_file.rowCount() > 1) { StringList li; csv_file.getRow(0, li); for (Size i = 0; i < li.size(); ++i) { at.colTypes.push_back(li[i]); } for (UInt i = 1; i < csv_file.rowCount(); ++i) { StringList li; std::vector<String> v; csv_file.getRow(i, li); //TODO throw error if li.size() != at.colTypes.size() for (Size i = 0; i < li.size(); ++i) { v.push_back(li[i]); } at.tableRows.push_back(v); } } } else { cerr << "Error: Nothing valid to attach. Aborting!" << endl; return ILLEGAL_PARAMETERS; } std::vector<String> ids; qcmlfile.existsRunQualityParameter(target_run, target_qp, ids); if (!ids.empty()) { at.qualityRef = ids.front(); qcmlfile.addRunAttachment(target_run, at); } else { qcmlfile.existsSetQualityParameter(target_run, target_qp, ids); if (!ids.empty()) { at.qualityRef = ids.front(); qcmlfile.addSetAttachment(target_run, at); } else { cerr << "Error: You have to give the accession of a existing cv term to attacht to. Aborting!" << endl; return ILLEGAL_PARAMETERS; } } } qcmlfile.store(out); return EXECUTION_OK; }
void ASF::Tag::removeUnsupportedProperties(const StringList &props) { StringList::ConstIterator it = props.begin(); for(; it != props.end(); ++it) d->attributeListMap.erase(*it); }
bool XM::File::save() { if(readOnly()) { debug("XM::File::save() - Cannot save to a read only file."); return false; } seek(17); writeString(d->tag.title(), 20); seek(38); writeString(d->tag.trackerName(), 20); seek(60); unsigned long headerSize = 0; if(!readU32L(headerSize)) return false; seek(70); unsigned short patternCount = 0; unsigned short instrumentCount = 0; if(!readU16L(patternCount) || !readU16L(instrumentCount)) return false; long pos = 60 + headerSize; // should be long long in taglib2. // need to read patterns again in order to seek to the instruments: for(unsigned short i = 0; i < patternCount; ++ i) { seek(pos); unsigned long patternHeaderLength = 0; if(!readU32L(patternHeaderLength) || patternHeaderLength < 4) return false; seek(pos + 7); unsigned short dataSize = 0; if (!readU16L(dataSize)) return false; pos += patternHeaderLength + dataSize; } const StringList lines = d->tag.comment().split("\n"); unsigned int sampleNameIndex = instrumentCount; for(unsigned short i = 0; i < instrumentCount; ++ i) { seek(pos); unsigned long instrumentHeaderSize = 0; if(!readU32L(instrumentHeaderSize) || instrumentHeaderSize < 4) return false; seek(pos + 4); const unsigned int len = std::min(22UL, instrumentHeaderSize - 4U); if(i >= lines.size()) writeString(String(), len); else writeString(lines[i], len); unsigned short sampleCount = 0; if(instrumentHeaderSize >= 29U) { seek(pos + 27); if(!readU16L(sampleCount)) return false; } unsigned long sampleHeaderSize = 0; if(sampleCount > 0) { seek(pos + 29); if(instrumentHeaderSize < 33U || !readU32L(sampleHeaderSize)) return false; } pos += instrumentHeaderSize; for(unsigned short j = 0; j < sampleCount; ++ j) { if(sampleHeaderSize > 4U) { seek(pos); unsigned long sampleLength = 0; if(!readU32L(sampleLength)) return false; if(sampleHeaderSize > 18U) { seek(pos + 18); const unsigned int len = std::min(sampleHeaderSize - 18U, 22UL); if(sampleNameIndex >= lines.size()) writeString(String(), len); else writeString(lines[sampleNameIndex ++], len); } } pos += sampleHeaderSize; } } return true; }
/** \internal Does all the actual globbing. \author Matthias Wandel ([email protected]) http://http://www.sentex.net/~mwandel/ \author Joshua Jensen ([email protected]) Matthias Wandel wrote the original C algorithm, which is contained in his Exif Jpeg header parser at http://www.sentex.net/~mwandel/jhead/ under the filename MyGlob.c. It should be noted that the MAJORITY of this function is his, albeit rebranded style-wise. I have made the following extensions: - Support for ignoring directories. - Perforce-style (and DJGPP-style) ... for recursion, instead of **. - Automatic conversion from ...Stuff to .../*Stuff. Allows lookup of files by extension, too: '....h' translates to '.../*.h'. - Ability to handle forward slashes and backslashes. - A minimal C++ class design. - Wildcard matching not based on FindFirstFile(). Should allow greater control in the future and patching in of the POSIX fnmatch() function on systems that support it. **/ void FileGlobBase::GlobHelper( const char* inPattern ) { char patternBuf[ _MAX_PATH * 2 ]; strcpy( patternBuf, inPattern ); DoRecursion: char basePath[ _MAX_PATH ]; char* basePathEndPtr = basePath; char* recurseAtPtr = NULL; // Split the path into base path and pattern to match against. bool hasWildcard = false; char* pattern; for ( pattern = patternBuf; *pattern != '\0'; ++pattern ) { char ch = *pattern; // Is it a '?' ? if ( ch == '?' ) hasWildcard = true; // Is it a '*' ? else if ( ch == '*' ) { hasWildcard = true; // Is there a '**'? if ( pattern[ 1 ] == '*' ) { // If we're just starting the pattern or the characters immediately // preceding the pattern are a drive letter ':' or a directory path // '/', then set up the internals for later recursion. if ( pattern == patternBuf || pattern[ -1 ] == '/' || pattern[ -1 ] == ':') { char ch2 = pattern[ 2 ]; if ( ch2 == '/' ) { recurseAtPtr = pattern; memcpy(pattern, pattern + 3, strlen( pattern ) - 2 ); } else if ( ch2 == '\0' ) { recurseAtPtr = pattern; *pattern = '\0'; } } } } // Is there a '/' or ':' in the pattern at this location? if ( ch == '/' || ch == ':' ) { if ( hasWildcard ) break; basePathEndPtr = &basePath[ pattern - patternBuf + 1 ]; } } // If there is no wildcard this time, then just add the current file and // get out of here. if ( !hasWildcard ) { // This should refer to a file. FoundMatch( patternBuf ); return; } // Did we make it to the end of the pattern? If so, we should match files, // since there were no slashes encountered. bool matchFiles = *pattern == '\0'; // Copy the directory down. size_t basePathLen = basePathEndPtr - basePath; strncpy( basePath, patternBuf, basePathLen ); // Copy the wildcard matching string. char matchPattern[ _MAX_PATH ]; size_t matchLen = ( pattern - patternBuf ) - basePathLen; strncpy( matchPattern, patternBuf + basePathLen, matchLen + 1 ); if ( matchPattern[ matchLen ] == '/' ) matchPattern[ matchLen ] = 0; StringList fileList; // Do the file search with *.* in the directory specified in basePattern. strcpy( basePathEndPtr, "*.*" ); // Start the find. WIN32_FIND_DATA fd; HANDLE handle = FindFirstFile( basePath, &fd ); // Clear out the *.* so we can use the original basePattern string. *basePathEndPtr = 0; // Any files found? if ( handle != INVALID_HANDLE_VALUE ) { for ( ;; ) { // Is the file a directory? if ( ( fd.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY ) && !matchFiles ) { // Do a wildcard match. if ( WildMatch( matchPattern, fd.cFileName, false ) ) { // It matched. Let's see if the file should be ignored. bool ignore = false; // Knock out "." or ".." if they haven't already been. size_t len = strlen( fd.cFileName ); fd.cFileName[ len ] = '/'; fd.cFileName[ len + 1 ] = '\0'; // See if this is a directory to ignore. ignore = MatchIgnorePattern( fd.cFileName ); fd.cFileName[ len ] = 0; // Should this file be ignored? if ( !ignore ) { // Nope. Add it to the linked list. fileList.push_back( fd.cFileName ); } } } else if ( !( fd.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY ) && matchFiles ) { // Do a wildcard match. if ( WildMatch( matchPattern, fd.cFileName, false ) ) { // It matched. Let's see if the file should be ignored. bool ignore = MatchIgnorePattern( fd.cFileName ); // Is this pattern exclusive? if ( !ignore && m_exclusiveFilePatterns.begin() != m_exclusiveFilePatterns.end() ) { ignore = !MatchExclusivePattern( fd.cFileName ); } // Should this file be ignored? if ( !ignore ) { // Nope. Add it to the linked list. fileList.push_back( fd.cFileName ); } } } // Look up the next file. if ( !FindNextFile( handle, &fd ) ) break; } // Close down the file find handle. FindClose( handle ); } // Sort the list. fileList.sort(); // Iterate the file list and either recurse or add the file as a found // file. if ( !matchFiles ) { for ( StringList::iterator it = fileList.begin(); it != fileList.end(); ++it ) { char combinedName[ _MAX_PATH * 2 ]; // Need more directories. CatPath( combinedName, basePath, (*it).c_str() ); strcat( combinedName, pattern ); GlobHelper( combinedName ); } } else // if ( !matchFiles ) { for ( StringList::iterator it = fileList.begin(); it != fileList.end(); ++it ) { char combinedName[ _MAX_PATH * 2 ]; CatPath( combinedName, basePath, (*it).c_str()); FoundMatch( combinedName ); } } // Clear out the file list, so the goto statement below can recurse // internally. fileList.clear(); // Do we need to recurse? if ( !recurseAtPtr ) return; // Copy in the new recursive pattern to match. strcpy( matchPattern, recurseAtPtr ); strcpy( recurseAtPtr, "*/**/" ); strcat( patternBuf, matchPattern ); // As this function context is no longer needed, we can just go back // to the top of it to avoid adding another context on the stack. goto DoRecursion; }
void XM::File::read(bool) { if(!isOpen()) return; seek(0); ByteVector magic = readBlock(17); // it's all 0x00 for stripped XM files: READ_ASSERT(magic == "Extended Module: " || magic == ByteVector(17, 0)); READ_STRING(d->tag.setTitle, 20); READ_BYTE_AS(escape); // in stripped XM files this is 0x00: READ_ASSERT(escape == 0x1A || escape == 0x00); READ_STRING(d->tag.setTrackerName, 20); READ_U16L(d->properties.setVersion); READ_U32L_AS(headerSize); READ_ASSERT(headerSize >= 4); unsigned short length = 0; unsigned short restartPosition = 0; unsigned short channels = 0; unsigned short patternCount = 0; unsigned short instrumentCount = 0; unsigned short flags = 0; unsigned short tempo = 0; unsigned short bpmSpeed = 0; StructReader header; header.u16L(length) .u16L(restartPosition) .u16L(channels) .u16L(patternCount) .u16L(instrumentCount) .u16L(flags) .u16L(tempo) .u16L(bpmSpeed); unsigned int count = header.read(*this, headerSize - 4U); unsigned int size = std::min(headerSize - 4U, (unsigned long)header.size()); READ_ASSERT(count == size); d->properties.setLengthInPatterns(length); d->properties.setRestartPosition(restartPosition); d->properties.setChannels(channels); d->properties.setPatternCount(patternCount); d->properties.setInstrumentCount(instrumentCount); d->properties.setFlags(flags); d->properties.setTempo(tempo); d->properties.setBpmSpeed(bpmSpeed); seek(60 + headerSize); // read patterns: for(unsigned short i = 0; i < patternCount; ++ i) { READ_U32L_AS(patternHeaderLength); READ_ASSERT(patternHeaderLength >= 4); unsigned char packingType = 0; unsigned short rowCount = 0; unsigned short dataSize = 0; StructReader pattern; pattern.byte(packingType).u16L(rowCount).u16L(dataSize); unsigned int count = pattern.read(*this, patternHeaderLength - 4U); READ_ASSERT(count == std::min(patternHeaderLength - 4U, (unsigned long)pattern.size())); seek(patternHeaderLength - (4 + count) + dataSize, Current); } StringList intrumentNames; StringList sampleNames; unsigned int sumSampleCount = 0; // read instruments: for(unsigned short i = 0; i < instrumentCount; ++ i) { READ_U32L_AS(instrumentHeaderSize); READ_ASSERT(instrumentHeaderSize >= 4); String instrumentName; unsigned char instrumentType = 0; unsigned short sampleCount = 0; StructReader instrument; instrument.string(instrumentName, 22).byte(instrumentType).u16L(sampleCount); // 4 for instrumentHeaderSize unsigned int count = 4 + instrument.read(*this, instrumentHeaderSize - 4U); READ_ASSERT(count == std::min(instrumentHeaderSize, (unsigned long)instrument.size() + 4)); unsigned long sampleHeaderSize = 0; long offset = 0; if(sampleCount > 0) { sumSampleCount += sampleCount; // wouldn't know which header size to assume otherwise: READ_ASSERT(instrumentHeaderSize >= count + 4 && readU32L(sampleHeaderSize)); // skip unhandeled header proportion: seek(instrumentHeaderSize - count - 4, Current); for(unsigned short j = 0; j < sampleCount; ++ j) { unsigned long sampleLength = 0; unsigned long loopStart = 0; unsigned long loopLength = 0; unsigned char volume = 0; unsigned char finetune = 0; unsigned char sampleType = 0; unsigned char panning = 0; unsigned char noteNumber = 0; unsigned char compression = 0; String sampleName; StructReader sample; sample.u32L(sampleLength) .u32L(loopStart) .u32L(loopLength) .byte(volume) .byte(finetune) .byte(sampleType) .byte(panning) .byte(noteNumber) .byte(compression) .string(sampleName, 22); unsigned int count = sample.read(*this, sampleHeaderSize); READ_ASSERT(count == std::min(sampleHeaderSize, (unsigned long)sample.size())); // skip unhandeled header proportion: seek(sampleHeaderSize - count, Current); offset += sampleLength; sampleNames.append(sampleName); } } else { offset = instrumentHeaderSize - count; } intrumentNames.append(instrumentName); seek(offset, Current); } d->properties.setSampleCount(sumSampleCount); String comment(intrumentNames.toString("\n")); if(!sampleNames.isEmpty()) { comment += "\n"; comment += sampleNames.toString("\n"); } d->tag.setComment(comment); }
std::string ret = "Opaque list: ["; bool first = true; for (auto entry : l) { if (!first) ret += ", "; ret += entry; first = false; } return ret + "]"; }); m.def("return_void_ptr", []() { return (void *) 0x1234; }); m.def("get_void_ptr_value", [](void *ptr) { return reinterpret_cast<std::intptr_t>(ptr); }); m.def("return_null_str", []() { return (char *) nullptr; }); m.def("get_null_str_value", [](char *ptr) { return reinterpret_cast<std::intptr_t>(ptr); }); m.def("return_unique_ptr", []() -> std::unique_ptr<StringList> { StringList *result = new StringList(); result->push_back("some value"); return std::unique_ptr<StringList>(result); }); });
void Logger::printStackInternal( rfc_threadstack *stack , int skipTop , bool printInplace ) { int startItem = rfc_thr_stackfulldepth( stack ) - 1; StringList lines; lines.add( String( "CALL STACK:" ) ); if( skipTop == 0 ) skipTop = stack -> extraLevels; if( skipTop > 0 ) { lines.add( String( "\t...skipped..." ) ); startItem -= skipTop; } bool skipLast = false; for( int k = startItem; k >= 0; k-- ) { rfc_threadstacklevel *sl = rfc_thr_stacklevel( stack , k ); // extract short name String moduleName = sl -> moduleName; int from = moduleName.findLastAny( "/\\" ); int to = moduleName.findLast( '.' ); String moduleNameShort = moduleName; if( from >= 0 && to >= 0 ) moduleNameShort = moduleNameShort.getMid( from + 1 , to - from - 1 ); if( !strcmp( moduleNameShort , "unknown" ) ) continue; lines.add( String( "\t" ) + sl -> className + "::" + sl -> functionName + " (" + moduleNameShort + ", " + sl -> message + ")" ); // stop after main function String functionName = sl -> functionName; if( strcmp( functionName , "_main" ) == 0 || strcmp( functionName , "threadMainFunction" ) == 0 || strcmp( functionName , "runThread" ) == 0 ) { if( k > 0 ) skipLast = true; break; } } if( skipLast ) lines.add( "\t...skipped..." ); for( int k = 0; k < lines.count(); k++ ) { LogOutputMode mode = Logger::LogLine; if( !printInplace ) if( k == 0 ) mode = Logger::LogStart; else if( k == lines.count() - 1 ) mode = Logger::LogStop; log( lines.get( k ) , mode , Logger::LogLevelInfo ); } }
void S3M::File::read(bool) { if(!isOpen()) return; READ_STRING(d->tag.setTitle, 28); READ_BYTE_AS(mark); READ_BYTE_AS(type); READ_ASSERT(mark == 0x1A && type == 0x10); seek(32); READ_U16L_AS(length); READ_U16L_AS(sampleCount); d->properties.setSampleCount(sampleCount); READ_U16L(d->properties.setPatternCount); READ_U16L(d->properties.setFlags); READ_U16L(d->properties.setTrackerVersion); READ_U16L(d->properties.setFileFormatVersion); READ_ASSERT(readBlock(4) == "SCRM"); READ_BYTE(d->properties.setGlobalVolume); READ_BYTE(d->properties.setBpmSpeed); READ_BYTE(d->properties.setTempo); READ_BYTE_AS(masterVolume); d->properties.setMasterVolume(masterVolume & 0x7f); d->properties.setStereo((masterVolume & 0x80) != 0); // I've seen players who call the next two bytes // "ultra click" and "use panning values" (if == 0xFC). // I don't see them in any spec, though. // Hm, but there is "UltraClick-removal" and some other // variables in ScreamTracker IIIs GUI. seek(12, Current); int channels = 0; for(int i = 0; i < 32; ++ i) { READ_BYTE_AS(setting); // or if(setting >= 128)? // or channels = i + 1;? // need a better spec! if(setting != 0xff) ++ channels; } d->properties.setChannels(channels); seek(96); ushort realLength = 0; for(ushort i = 0; i < length; ++ i) { READ_BYTE_AS(order); if(order == 255) break; if(order != 254) ++ realLength; } d->properties.setLengthInPatterns(realLength); seek(channels, Current); // Note: The S3M spec mentions samples and instruments, but in // the header there are only pointers to instruments. // However, there I never found instruments (SCRI) but // instead samples (SCRS). StringList comment; for(ushort i = 0; i < sampleCount; ++ i) { seek(96L + length + ((long)i << 1)); READ_U16L_AS(sampleHeaderOffset); seek((long)sampleHeaderOffset << 4); READ_BYTE_AS(sampleType); READ_STRING_AS(dosFileName, 13); READ_U16L_AS(sampleDataOffset); READ_U32L_AS(sampleLength); READ_U32L_AS(repeatStart); READ_U32L_AS(repeatStop); READ_BYTE_AS(sampleVolume); seek(1, Current); READ_BYTE_AS(packing); READ_BYTE_AS(sampleFlags); READ_U32L_AS(baseFrequency); seek(12, Current); READ_STRING_AS(sampleName, 28); // The next 4 bytes should be "SCRS", but I've found // files that are otherwise ok with 4 nils instead. // READ_ASSERT(readBlock(4) == "SCRS"); comment.append(sampleName); } d->tag.setComment(comment.toString("\n")); d->tag.setTrackerName("ScreamTracker III"); }
// clears all the inner structures and loads the configuration parameters' // values again void ReplicatorStateMachine::reinitialize() { // delete all configurations and start everything over from the scratch finalize( ); AbstractReplicatorStateMachine::reinitialize( ); m_myVersion.initialize( m_stateFilePath, m_versionFilePath ); m_replicationInterval = param_integer("REPLICATION_INTERVAL", 5 * MINUTE, 0); // min value, must be positive // deduce HAD alive tolerance int hadConnectionTimeout = param_integer("HAD_CONNECTION_TIMEOUT", DEFAULT_SEND_COMMAND_TIMEOUT, 0); // min value, must be positive m_maxTransfererLifeTime = param_integer("MAX_TRANSFER_LIFETIME", 5 * MINUTE, 0); // min value, must be positive m_newlyJoinedWaitingVersionInterval = param_integer("NEWLY_JOINED_WAITING_VERSION_INTERVAL", NEWLY_JOINED_TOLERANCE_FACTOR * (hadConnectionTimeout + 1), 0); // min value, must be positive char* buffer = param( "HAD_LIST" ); if ( buffer ) { StringList hadList; hadList.initializeFromString( buffer ); free( buffer ); m_hadAliveTolerance = HAD_ALIVE_TOLERANCE_FACTOR * ( 2 * hadConnectionTimeout * hadList.number() + 1 ); dprintf( D_FULLDEBUG, "ReplicatorStateMachine::reinitialize %s=%d\n", "HAD_LIST", m_hadAliveTolerance ); } else { utilCrucialError( utilNoParameterError( "HAD_LIST", "HAD" ).Value( )); } initializeClassAd(); int updateInterval = param_integer ( "REPLICATION_UPDATE_INTERVAL", 300 ); if ( m_updateInterval != updateInterval ) { m_updateInterval = updateInterval; utilCancelTimer(m_updateCollectorTimerId); m_updateCollectorTimerId = daemonCore->Register_Timer ( 0, m_updateInterval, (TimerHandlercpp) &ReplicatorStateMachine::updateCollectors, "ReplicatorStateMachine::updateCollectors", this ); } // set a timer to replication routine dprintf( D_ALWAYS, "ReplicatorStateMachine::reinitialize setting " "replication timer\n" ); m_replicationTimerId = daemonCore->Register_Timer( m_replicationInterval, (TimerHandlercpp) &ReplicatorStateMachine::replicationTimer, "Time to replicate file", this ); // register the download/upload reaper for the transferer process if( m_downloadReaperId == -1 ) { m_downloadReaperId = daemonCore->Register_Reaper( "downloadReplicaTransfererReaper", (ReaperHandler)&ReplicatorStateMachine::downloadReplicaTransfererReaper, "downloadReplicaTransfererReaper", this ); } if( m_uploadReaperId == -1 ) { m_uploadReaperId = daemonCore->Register_Reaper( "uploadReplicaTransfererReaper", (ReaperHandler) &ReplicatorStateMachine::uploadReplicaTransfererReaper, "uploadReplicaTransfererReaper", this ); } // for debugging purposes only printDataMembers( ); beforePassiveStateHandler( ); }
void MSVCProvider::addResourceFiles(const BuildSetup &setup, StringList &includeList, StringList &excludeList) { includeList.push_back(setup.srcDir + "/icons/" + setup.projectName + ".ico"); includeList.push_back(setup.srcDir + "/dists/" + setup.projectName + ".rc"); }
void SearchResultsDatabase::executeQuery(shared_ptr<IPortalDatabase> database, shared_ptr<Portal> portal, shared_ptr<SearchQuery> query, const StringMap& objectsMap) { clear(); shared_ptr<DbSqlSelect> select(new DbSqlSelect(DBTABLES::SNAPSHOT_OBJECTS_TABLE)); select->fields.add(DbSqlField(DBTABLES::SNAPSHOT_OBJECTS::ENTITY, DBTABLES::SNAPSHOT_OBJECTS_TABLE)); // Se il primo step di un groupMode, ho bisogno di estrarre anche il padre. if(query->getGroupMode() && (objectsMap.empty())) select->fields.add(DbSqlField(DBTABLES::SNAPSHOT_OBJECTS::PARENT, DBTABLES::SNAPSHOT_OBJECTS_TABLE)); // Solo se non specificata gi una lista di oggetti. // Le where si riferiscono agli oggetti singoli (ex. post), non al loro oggetto da visualizzare. // Quindi non necessario specificarle nel secondo giro. if(objectsMap.empty()) { // current != "" select->where.add(DbSqlField(DBTABLES::SNAPSHOT_OBJECTS::CURRENT, DBTABLES::SNAPSHOT_OBJECTS_TABLE), Convert::toSQL(String::EMPTY), DbSqlCondition::cfDifferent | DbSqlCondition::cfAnd); // Controlla se stata specificata una data di creazione minima const DateTime &fromSubmitDate = query->convertSearchDateTime(query->getFromSubmitDateType(),query->getFromSubmitDateSpecific()); if(fromSubmitDate.isValid()) { // submit_date >= fromSubmitDate select->where.add(DbSqlField(DBTABLES::SNAPSHOT_OBJECTS::SUBMIT_DATE, DBTABLES::SNAPSHOT_OBJECTS_TABLE), Convert::toSQL(fromSubmitDate), DbSqlCondition::cfMajor | DbSqlCondition::cfEqual | DbSqlCondition::cfAnd); } // Controlla se stata specificata una data di creazione massima const DateTime &toSubmitDate = query->convertSearchDateTime(query->getToSubmitDateType(),query->getToSubmitDateSpecific()); if(toSubmitDate.isValid()) { // submit_date <= toSubmitDate select->where.add(DbSqlField(DBTABLES::SNAPSHOT_OBJECTS::SUBMIT_DATE, DBTABLES::SNAPSHOT_OBJECTS_TABLE), Convert::toSQL(toSubmitDate), DbSqlCondition::cfMinor | DbSqlCondition::cfEqual | DbSqlCondition::cfAnd); } // Controlla se stata specificata una data di inserimento minima const DateTime &fromInsertDate = query->convertSearchDateTime(query->getFromInsertDateType(),query->getFromInsertDateSpecific()); if(fromInsertDate.isValid()) { // insert_date >= fromInsertDate select->where.add(DbSqlField(DBTABLES::SNAPSHOT_OBJECTS::INSERT_DATE, DBTABLES::SNAPSHOT_OBJECTS_TABLE), Convert::toSQL(fromInsertDate), DbSqlCondition::cfMajor | DbSqlCondition::cfEqual | DbSqlCondition::cfAnd); } // Controlla se stata specificata una data di creazione massima const DateTime &toInsertDate = query->convertSearchDateTime(query->getToInsertDateType(),query->getToInsertDateSpecific()); if(toInsertDate.isValid()) { // insert_date <= toInsertDate select->where.add(DbSqlField(DBTABLES::SNAPSHOT_OBJECTS::INSERT_DATE, DBTABLES::SNAPSHOT_OBJECTS_TABLE), Convert::toSQL(toInsertDate), DbSqlCondition::cfMinor | DbSqlCondition::cfEqual | DbSqlCondition::cfAnd); } // Non mostrare le entit virtuali. Dato che le entit virtuali hanno insertDate==null, select->where.add(DbSqlField(DBTABLES::SNAPSHOT_OBJECTS::INSERT_DATE, DBTABLES::SNAPSHOT_OBJECTS_TABLE), Convert::toSQL(DateTime::EMPTY), DbSqlCondition::cfDifferent | DbSqlCondition::cfAnd); // Se non deve mostrare gli oggetti cancellati forza la visibilit ad 1 if(query->getShowDeleted() == false) // visible == 1 select->where.add(DbSqlField(DBTABLES::SNAPSHOT_OBJECTS::VISIBLE, DBTABLES::SNAPSHOT_OBJECTS_TABLE), Convert::toSQL(true)); StringList types; for(SearchQuery::Options::const_iterator i = query->getOptions().begin(); i != query->getOptions().end(); ++i) { shared_ptr<ISearchOptions> options = i->second; if(options->getActive()) { types.push_back(Convert::toString(options->getType())); } } if(types.empty() == false) // type in (...) select->where.add(DbSqlField(DBTABLES::SNAPSHOT_OBJECTS::TYPE, DBTABLES::SNAPSHOT_OBJECTS_TABLE), types); // Ricerca in determinati padri StringList parentsList; query->computeParentsList(database, portal, parentsList); // Ci metto gli apici... for(StringList::iterator i = parentsList.begin(); i != parentsList.end(); ++i) { *i = _S("'") + String(*i) + _S("'"); } if(!parentsList.empty()) { select->where.add(DbSqlField(DBTABLES::SNAPSHOT_OBJECTS::PARENT, DBTABLES::SNAPSHOT_OBJECTS_TABLE), parentsList); } // 0.14 RC3 if(query->getText().substr(0,17) == _S("title-start-with:")) { select->where.add(DbSqlField(DBTABLES::SNAPSHOT_OBJECTS::TITLE), Convert::toSQL(query->getText().substr(17) + _S("%")), DbSqlCondition::cfLike | DbSqlCondition::cfAnd); } // 0.14 RC3 if(query->getText().substr(0,17) == _S("title-start-with:")) { select->where.add(DbSqlField(DBTABLES::SNAPSHOT_OBJECTS::TITLE), query->getText().substr(17) + _S("%"), DbSqlCondition::cfLike | DbSqlCondition::cfAnd); } // 0.12 if( (query->getByUser().empty() == false) && (query->getByUser() != _S("*")) ) { String user = query->getByUser(); // MySelf test if(user == _S("myself")) { // VERYURGENTRAZOR: Commentata perchè ho piallato il loggedUser come parametro... rivalutare la cosa /* if( (loggedUser != nullptr) && loggedUser->isLogged() && (loggedUser->getGuestMode() == false)) { user = loggedUser->getUser()->id->toUTF16(); } else { user == String::EMPTY; } */ user == String::EMPTY; } else { // VERYURGENT, un test migliore per verificare se è un ID? // VERYURGENT, l'sql potrebbe essere Sqlite-specifica. // Fatto meglio, dovrei avere un'altro combo "localizza per" "nick/id" // Inoltre qui ci sarebbe da supportare una ricerca "non exact-match" per farlo stile Invision. if(user.length() != 48) { algorithms::to_upper(user); String sql = String::format(_S("select rs.id from os_snapshot_users ts, os_users tu where ts.id=tu.id and upper(tu.name) = %S").c_str(), Convert::toSQL(user).c_str()); DataTable result; if(database->execute(sql, result)) { if(result.rows() > 0 && result.columns() > 0) user = static_cast<String>(*result[0][0]); } } } // Come autore della primaria select->tables.add(DbSqlTable(DBTABLES::ENTRIES_TABLE)); // Crea la join select->where.add(DbSqlField(DBTABLES::SNAPSHOT_OBJECTS::ENTITY, DBTABLES::SNAPSHOT_OBJECTS_TABLE), DbSqlField(DBTABLES::ENTRIES::ID, DBTABLES::ENTRIES_TABLE)); select->where.add(DbSqlField(DBTABLES::ENTRIES::AUTHOR, DBTABLES::ENTRIES_TABLE), Convert::toSQL(user)); // Come editore dell'oggetto // where DBTABLES::SNAPSHOT_OBJECTS::REFERENCE in (select id from os_entries where revision= getByUser(); } } else { // Se objectsList valorizzata, allora il secondo passo di una ricerca in groupMode, gli passo l'elenco oggetti. StringList objectsList; for(StringMap::const_iterator i = objectsMap.begin(); i != objectsMap.end(); ++i) { objectsList.push_back(_S("'") + i->first + _S("'")); } //select->where.add(String(DBTABLES::SNAPSHOT_OBJECTS_TABLE) + _S(".") + DBTABLES::SNAPSHOT_OBJECTS::REFERENCE, objectsList); select->where.add(DbSqlField(DBTABLES::SNAPSHOT_OBJECTS::ENTITY, DBTABLES::SNAPSHOT_OBJECTS_TABLE), objectsList); } // Se il primo passaggio di una groupMode, l'ordinamento inutile. // 0.12 RC5, tolto, con un limite nel primo giro di group-mode, devono essere ordinati. //if( (!query->getGroupMode()) || (!objectsMap.empty()) ) { DbSqlField::Order order = DbSqlField::foNone; switch(query->getOrderDirection()) { case searchOrderDirectionDescendent: order = DbSqlField::foDesc; break; case searchOrderDirectionAscendent: order = DbSqlField::foAsc; break; default: OS_ASSERTFALSE(); break; } SearchOrderMode orderMode = query->getOrderMode(); // 0.12 RC5, da testare // Se è il primo passaggio di una group-mode, l'ordinamento "omLastObject" deve essere un "omSubmitDate". if( (query->getGroupMode()) && (objectsMap.empty()) ) { if(orderMode == searchOrderModeLastObject) orderMode = searchOrderModeSubmitDate; else if(orderMode == searchOrderModeVotesTotal) orderMode = searchOrderModeSubmitDate; else if(orderMode == searchOrderModeVotesAverage) orderMode = searchOrderModeSubmitDate; } switch(orderMode) { case searchOrderModeRelevance: // Non c' la rilevanza nelle search non basate sul Lucene. break; // TOCLEAN_SNAPSHOT_SCORE /* Per riprestinarlo, devo fare una join con la snapshot::users. case searchOrderModeReputation: select->orderBy.add(DbSqlField(DBTABLES::SNAPSHOT_OBJECTS::SCORE, DBTABLES::SNAPSHOT_OBJECTS_TABLE)); select->orderBy.add(DbSqlField(DBTABLES::SNAPSHOT_OBJECTS::POSITION, DBTABLES::SNAPSHOT_OBJECTS_TABLE), order); break; */ case searchOrderModeSubmitDate: select->orderBy.add(DbSqlField(DBTABLES::SNAPSHOT_OBJECTS::SUBMIT_DATE, DBTABLES::SNAPSHOT_OBJECTS_TABLE), order); break; case searchOrderModeInsertDate: select->orderBy.add(DbSqlField(DBTABLES::SNAPSHOT_OBJECTS::INSERT_DATE, DBTABLES::SNAPSHOT_OBJECTS_TABLE), order); break; case searchOrderModePosition: select->orderBy.add(DbSqlField(DBTABLES::SNAPSHOT_OBJECTS::POSITION, DBTABLES::SNAPSHOT_OBJECTS_TABLE), order); break; case searchOrderModeTitle: select->orderBy.add(DbSqlField(DBTABLES::SNAPSHOT_OBJECTS::TITLE, DBTABLES::SNAPSHOT_OBJECTS_TABLE), order); break; case searchOrderModeLastObject: { select->tables.add(DbSqlTable(DBTABLES::DISCUSSIONS_STATS_TABLE)); // Crea la join select->where.add(DbSqlField(DBTABLES::SNAPSHOT_OBJECTS::ENTITY, DBTABLES::SNAPSHOT_OBJECTS_TABLE), DbSqlField(DBTABLES::DISCUSSIONS_STATS::REFERENCE, DBTABLES::DISCUSSIONS_STATS_TABLE)); DbSqlField last_entry_date(DBTABLES::DISCUSSIONS_STATS::LAST_ENTRY_DATE, DBTABLES::DISCUSSIONS_STATS_TABLE); last_entry_date.setOrder(order); select->orderBy.fields.add(last_entry_date); } break; case searchOrderModeVotesTotal: { select->tables.add(DbSqlTable(DBTABLES::DISCUSSIONS_STATS_TABLE)); // Crea la join select->where.add(DbSqlField(DBTABLES::SNAPSHOT_OBJECTS::ENTITY, DBTABLES::SNAPSHOT_OBJECTS_TABLE), DbSqlField(DBTABLES::DISCUSSIONS_STATS::REFERENCE, DBTABLES::DISCUSSIONS_STATS_TABLE)); DbSqlField last_entry_date(DBTABLES::DISCUSSIONS_STATS::VOTES, DBTABLES::DISCUSSIONS_STATS_TABLE); last_entry_date.setOrder(order); select->orderBy.fields.add(last_entry_date); } break; case searchOrderModeVotesAverage: { select->tables.add(DbSqlTable(DBTABLES::DISCUSSIONS_STATS_TABLE)); // Crea la join select->where.add(DbSqlField(DBTABLES::SNAPSHOT_OBJECTS::ENTITY, DBTABLES::SNAPSHOT_OBJECTS_TABLE), DbSqlField(DBTABLES::DISCUSSIONS_STATS::REFERENCE, DBTABLES::DISCUSSIONS_STATS_TABLE)); DbSqlField last_entry_date(DBTABLES::DISCUSSIONS_STATS::VOTES_AVERAGE, DBTABLES::DISCUSSIONS_STATS_TABLE); last_entry_date.setOrder(order); select->orderBy.fields.add(last_entry_date); } break; default: OS_EXCEPTION("Unknown query order mode"); break; } } uint32 searchLimit = Options::instance()->getOption<uint32>(Options::portals_options::search_limit); if(searchLimit != 0) { // 0.12 RC5 - Altrimenti, setto cmq un massimo di risultati, come limite massimo ragionevole. select->limit.setCount(searchLimit); } if(query->hasMaxResults()) { // 0.13 RC2 select->limit.setCount(query->getMaxResults()); } // Fa prima una "count" per sapere quanti risultati totali, ad esempio per calcolare le pagine del pager. // Poi, vengono estratti solo i record che servono alla pagina attuale (se non è il primo giro di un group-mode). select->count = true; DataTable result; if(database->execute(select, result)) { OS_ASSERT(result.hasRow(0)); m_totalResults = result.get(0, 0); if(m_totalResults > 0) // In teoria non serve rieseguire la query se non ci sono risultati... { // Se è in groupMode, ed è il primo passaggio, controllo se è parziale. if( (query->getGroupMode()) && (objectsMap.empty()) ) if( (searchLimit != 0) && (m_totalResults >= searchLimit) ) m_partial = true; // Se non è in groupMode, o è il secondo passaggio, allora filtro per il pager. if( (!query->getGroupMode()) || (!objectsMap.empty()) ) { uint32 limit=0; if( (query->hasLimit()) && (query->hasMaxResults()) ) limit = std::min<uint32>(query->getLimit(), query->getMaxResults()); else if(query->hasLimit()) limit = query->getLimit(); else if(query->hasMaxResults()) limit = query->getMaxResults(); if(limit != 0) { select->limit.setCount(limit); select->limit.setOffset(query->getOffset()); } } else { if(searchLimit != 0) { // 0.12 RC5 - Altrimenti, setto cmq un massimo di risultati, come limite massimo ragionevole. select->limit.setCount(searchLimit); } } select->count = false; result.clear(); if(database->execute(select, result)) { for(uint32 r = 0; r < result.rows(); r++) { EntityID reference = static_cast<String>(result.get(r, DBTABLES::SNAPSHOT_OBJECTS::ENTITY)).to_ascii(); if(query->getGroupMode()) { shared_ptr<EntitiesEntity> entity = database->getPortal()->getEntity(database, reference); if( (entity != NULL) && (entity->getCurrent() != NULL) ) { if(ObjectsSystem::instance()->getDescriptor(entity->getObjectType())->isGroupable()) reference = static_cast<String>(result.get(r, DBTABLES::SNAPSHOT_OBJECTS::PARENT)).to_ascii(); } } add(reference); } } } } }