问:
Parse into a complex struct with boost::spirit
I have an input encoded with ABNF grammar rules (it is MEGACO protocol):

```<code>!/3 [15.232.33.21]:2134
T=173619123
{
    C=230234621
    {
        PR=9,
        MF=ip/187/6/23045241
        {
           ...
        },
        MF=ip/187/6/23045242
        {
</code>```

I want to parse it into a complex struct with boost::spirit, pseudo-code:

```<code>megaco
{
    param1
    param2
    {
        param1
        param2
        list of param3
            param3-1
            {
                param4
                ...
            }
            param3-2
            {
                ...
            }
    }
}
</code>```

It should be noted that the grammar is complex and contains a lot of alternatives, levels and sequences. I am not sure how to create a boost::spirit parser to decode such a message level by level saving necessary values in the process.

Also I am not sure that boost::spirit is the right tool for it.

So how should I do it?

UPDATE: I want to thanks sehe for the great example, still the main task is to populate some structure with the values from the message. The only possible way I see now is to use BOOST_FUSION_ADAPT_STRUCT with a lot of structs using boost::variant for alternative and std::vector for lists of items. Am I right?

答:
Ironically, heading over to Appendix B.2 of RFC 3525, and implementing the bulk of it superficially¹ it turns out your sample snippet is invalid.

It was missing ammParameter, that's not optional as soon as you have the opening {:

So, fixing the snippet, here's something to get you started. It's only 850 lines of code because the spec is lengthy:

Live On Coliru

```//#define BOOST_SPIRIT_DEBUG
#include <boost/spirit/include/qi.hpp>
namespace qi = boost::spirit::qi;

template <typename It> struct Megaco {

struct Tokens {
    Tokens() {
        using namespace qi;
        auto SafeChar = copy(alnum | char_("-+&!_/'?@^`~*$\\()%|."));
        auto RestChar = copy(char_(";[]{}:,#<>="));
        auto WSP         = copy(char_(" \t"));
        COMMENT      = ';' >> *(SafeChar | RestChar | WSP | '"') >> (eol|eoi);

        SEP = +(WSP | COMMENT | eol);
        LWSP = *(WSP | COMMENT | eol);
        NAME = raw [ alpha >> repeat(0,63) [alnum|'_'] ];

        // Note - The double-quote character is not allowed in quotedString.
        quotedString = '"' >> *(SafeChar | RestChar | WSP) >> '"';
        VALUE       = quotedString | lexeme[+SafeChar];
        octetString = *("\\}" | char_("\x01-\x7C\x7E-\xFF"));

        MTPToken=no_case["MTP"];
        H221Token=no_case["H221"];
        H223Token=no_case["H223"];
        H226Token=no_case["H226"];
        V18Token=no_case["V18"];
        V22Token=no_case["V22"];
        V22bisToken=no_case["V22b"];
        V32Token=no_case["V32"];
        V32bisToken=no_case["V32b"];
        V34Token=no_case["V34"];
        V76Token=no_case["V76"];
        V90Token=no_case["V90"];
        V91Token=no_case["V91"];

        BOOST_SPIRIT_DEBUG_NODES(
                // snipped for Stack Overflow, see Coliru
           )
    }
  protected:
    using Token = qi::rule<It>;
    Token COMMENT, SEP, LWSP;
    qi::rule<It, std::string()> NAME, quotedString, VALUE, octetString;
    #define TOK(name,long,short) name##Token{qi::no_case[qi::lit(#long)|#short]},
    Token
        TOK(Add,Add,A) TOK(Audit,Audit,AT) TOK(AuditCap,AuditCapability,AC) TOK(AuditValue,AuditValue,AV) TOK(Auth,Authentication,AU)
        TOK(Bothway,Bothway,BW) TOK(Brief,Brief,BR) TOK(Buffer,Buffer,BF) TOK(Ctx,Context,C) TOK(ContextAudit,ContextAudit,CA)
        TOK(DigitMap,DigitMap,DM) TOK(Disconnected,Disconnected,DC) TOK(Delay,Delay,DL) TOK(Duration,Duration,DR) TOK(Embed,Embed,EM)
        TOK(Emergency,Emergency,EG) TOK(Error,Error,ER) TOK(EventBuffer,EventBuffer,EB) TOK(Events,Events,E) TOK(Failover,Failover,FL)
        TOK(Forced,Forced,FO) TOK(Graceful,Graceful,GR) TOK(HandOff,HandOff,HO) TOK(ImmAckRequired,ImmAckRequired,IA)
        TOK(Inactive,Inactive,IN) TOK(Isolate,Isolate,IS) TOK(InSvc,InService,IV) TOK(InterruptByEvent,IntByEvent,IBE)
        TOK(InterruptByNewSignalsDescr,IntBySigDescr,IBS) TOK(KeepActive,KeepActive,KA) TOK(Local,Local,L) TOK(LocalControl,LocalControl,O)
        TOK(LockStep,LockStep,SP) TOK(Loopback,Loopback,LB) TOK(Media,Media,M) TOK(Megacop,MEGACO,!) TOK(Method,Method,MT)
        TOK(MgcId,MgcIdToTry,MG) TOK(Mode,Mode,MO) TOK(Modify,Modify,MF) TOK(Modem,Modem,MD) TOK(Move,Move,MV)
        TOK(Mux,Mux,MX) TOK(Notify,Notify,N) TOK(NotifyCompletion,NotifyCompletion,NC) TOK(ObservedEvents,ObservedEvents,OE) TOK(Oneway,Oneway,OW)
        TOK(OnOff,OnOff,OO) TOK(OtherReason,OtherReason,OR) TOK(OutOfSvc,OutOfService,OS) TOK(Packages,Packages,PG) TOK(Pending,Pending,PN)
        TOK(Priority,Priority,PR) TOK(Profile,Profile,PF) TOK(Reason,Reason,RE) TOK(Recvonly,ReceiveOnly,RC) TOK(Reply,Reply,P)
        TOK(Restart,Restart,RS) TOK(Remote,Remote,R) TOK(ReservedGroup,ReservedGroup,RG) TOK(ReservedValue,ReservedValue,RV) TOK(Sendonly,SendOnly,SO)
        TOK(Sendrecv,SendReceive,SR) TOK(Services,Services,SV) TOK(ServiceStates,ServiceStates,SI) TOK(ServiceChange,ServiceChange,SC)
        TOK(ServiceChangeAddress,ServiceChangeAddress,AD) TOK(SignalList,SignalList,SL) TOK(Signals,Signals,SG) TOK(SignalType,SignalType,SY)
        TOK(Stats,Statistics,SA) TOK(Stream,Stream,ST) TOK(Subtract,Subtract,S) TOK(SynchISDN,SynchISDN,SN) TOK(TerminationState,TerminationState,TS)
        TOK(Test,Test,TE) TOK(TimeOut,TimeOut,TO) TOK(Topology,Topology,TP) TOK(Trans,Transaction,T) TOK(ResponseAck,TransactionResponseAck,K)
        TOK(Version,Version,V) MTPToken, H221Token, H223Token, H226Token, V18Token, V22Token, V22bisToken,
        V32Token, V32bisToken, V34Token, V76Token, V90Token, V91Token;

    // The values 0x0, 0xFFFFFFFE and 0xFFFFFFFF are reserved.
    struct SpecialContexts : qi::symbols<char, uint32_t> {
        enum { NULL_, CHOOSE = 0xFFFFFFFEl, ALL = 0xFFFFFFFFl };
        SpecialContexts() { this->add
            ("$", CHOOSE)
            ("*", ALL)
            ("-", NULL_);
        }
    } SpecialContext;
};

struct Parser : Tokens, qi::grammar<It> {
    using Tokens::LWSP;
    using Tokens::SEP;
    using Tokens::SpecialContext;
    using Tokens::NAME;
    using Tokens::VALUE;
    using Tokens::quotedString;
    using Tokens::octetString;

    Parser() : Parser::base_type(megacoMessage) {
        using namespace qi;

        auto LBRKT   = copy(LWSP >> '{' >> LWSP);
        auto RBRKT   = copy(LWSP >> '}' >> LWSP);
        auto EQUAL   = copy(LWSP >> '=' >> LWSP);
        auto COMMA   = copy(LWSP >> ',' >> LWSP);
        auto INEQUAL = copy(LWSP >> char_("><#") >> LWSP);
        auto LSBRKT  = copy(LWSP >> '[' >> LWSP);
        auto RSBRKT  = copy(LWSP >> ']' >> LWSP);
        auto LPAREN  = copy(LWSP >> '(' >> LWSP);
        auto RPAREN  = copy(LWSP >> ')' >> LWSP);
        auto PIPE    = copy(LWSP >> '|' >> LWSP);

        megacoMessage = LWSP >> -(authenticationHeader >> SEP) >> message;

        authenticationHeader
            = Tokens::AuthToken
            >> EQUAL
            >> ("0x" >> repeat(8)[xdigit])
            >> ':'
            >> ("0x" >> repeat(8)[xdigit])
            >> ':'
            >> repeat(24,64)[xdigit]
            ;

        message
            = Tokens::MegacopToken >> '/' >> Version >> SEP >> mId >> SEP
            >> messageBody;

        mId
            = ((domainAddress | domainName) >> -(':' >> portNumber))
            | mtpAddress
            | deviceName
            ;

        domainName
            = '<' >> alnum >> repeat(0,63)[char_("a-zA-Z0-9.-")] >> '>';
        deviceName
            = pathNAME.alias();
        pathNAME // TODO total lenght limit according to RFC comment
            = -lit('*') >> NAME >> *char_("/*a-zA-Z0-9_$") >> -('@' >> pathDomainName);

        pathDomainName = raw [(alnum|'*') >> repeat(0,63)[alnum|'-'|'*'|'.'] ];

        ContextID = SpecialContext | UINT32;

        domainAddress = '[' >> (IPv4address | IPv6address) >> ']';

        // RFC2373 contains the definition of IP6Addresses.
        IPv6address   = hexpart >> - (':' >> IPv4address);
        IPv4address   = V4hex >> '.' >> V4hex >> '.' >> V4hex >> '.' >> V4hex;
        V4hex         = qi::uint_parser<uint8_t, 10, 1, 3>{}; // "0".."255"

        hexpart = raw [
                  "::" >> -hexseq
                | hexseq >> "::" >> -hexseq
                | hexseq
            ];

        hexseq = raw[ uint_parser<uint16_t, 16, 1, 4>{} % ':' ];

        portNumber = UINT16;

        // TODO constraint checking?
        // To octet align the mtpAddress the MSBs shall be encoded as 0s.
        // An octet shall be represented by 2 hex digits.
        mtpAddress
            = Tokens::MTPToken
            >> LBRKT
            >> uint_parser<uint32_t, 16, 4, 8>{}
            >> RBRKT
            ;

        messageBody = errorDescriptor | transactionList;

        transactionList      = +( transactionRequest | transactionReply |
                               transactionPending | transactionResponseAck );
        //Use of response acks is dependent on underlying transport

        transactionPending   = Tokens::PendingToken >> EQUAL >> transactionID >> LBRKT >> RBRKT;

        transactionResponseAck = Tokens::ResponseAckToken
            >> LBRKT >> (transactionAck % COMMA) >> RBRKT;
        transactionAck = transactionID | (transactionID >> "-" >> transactionID);

        transactionRequest   = Tokens::TransToken >> EQUAL >> transactionID >> LBRKT
                               >> (actionRequest % COMMA) >> RBRKT;

        actionRequest        = Tokens::CtxToken >> EQUAL >> ContextID >> LBRKT >> ((
                               contextRequest >> -(COMMA  >> commandRequestList))
                               | commandRequestList) >> RBRKT;

        contextRequest    = ((contextProperties >> -(COMMA >> contextAudit))
                    | contextAudit);

        contextProperties    = contextProperty % COMMA;

        // at-most-once
        contextProperty    = (topologyDescriptor | priority | Tokens::EmergencyToken);

        contextAudit   = Tokens::ContextAuditToken
            >> LBRKT >> (contextAuditProperties % COMMA) >> RBRKT;

        // at-most-once
        contextAuditProperties = ( Tokens::TopologyToken | Tokens::EmergencyToken | Tokens::PriorityToken );

        // "O-" indicates an optional command
        // "W-" indicates a wildcarded response to a command
        commandRequestList = -lit("O-") >> -lit("W-") >> commandRequest
                             >> *(COMMA >> -lit("O-") >> -lit("W-") >> commandRequest);

        commandRequest      = ( ammRequest | subtractRequest | auditRequest |
                                notifyRequest | serviceChangeRequest);

        transactionReply     = Tokens::ReplyToken >> EQUAL >> transactionID >> LBRKT
                          >> -( Tokens::ImmAckRequiredToken >> COMMA)
                        >> ( errorDescriptor | actionReplyList ) >> RBRKT;

        actionReplyList      = actionReply % COMMA ;

        actionReply          = Tokens::CtxToken >> EQUAL >> ContextID >> LBRKT
                          >> ( ( errorDescriptor | commandReply ) |
                 (commandReply >> COMMA >> errorDescriptor) ) >> RBRKT;

        commandReply      = (( contextProperties >> -(COMMA >> commandReplyList) ) |
                                commandReplyList );

        commandReplyList     = commandReplys % COMMA ;

        commandReplys        = (serviceChangeReply | auditReply | ammsReply |
                                notifyReply );

        //Add Move and Modify have the same request parameters
        ammRequest           = (Tokens::AddToken | Tokens::MoveToken | Tokens::ModifyToken ) >> EQUAL
                                >> TerminationID >>
                                -(LBRKT >> (ammParameter % COMMA) >> RBRKT);

        //at-most-once
        ammParameter         = (mediaDescriptor | modemDescriptor |
                                muxDescriptor | eventsDescriptor |
                                signalsDescriptor | digitMapDescriptor |
                                eventBufferDescriptor | auditDescriptor);

        ammsReply            = (Tokens::AddToken | Tokens::MoveToken | Tokens::ModifyToken |
                                Tokens::SubtractToken ) >> EQUAL >> TerminationID >> -( LBRKT
                                >> terminationAudit >> RBRKT );

        subtractRequest      =  Tokens::SubtractToken >> EQUAL >> TerminationID
                                >> -( LBRKT >> auditDescriptor >> RBRKT);

        auditRequest         =  (Tokens::AuditValueToken | Tokens::AuditCapToken ) >> EQUAL
                                >> TerminationID >> LBRKT >> auditDescriptor >> RBRKT;

        auditReply           = (Tokens::AuditValueToken | Tokens::AuditCapToken )
                               >> ( contextTerminationAudit  | auditOther);

        auditOther           = EQUAL >> TerminationID >> -(LBRKT >> terminationAudit >> RBRKT);

        terminationAudit = auditReturnParameter % COMMA;

        contextTerminationAudit = EQUAL >> Tokens::CtxToken >> ( terminationIDList |
                               LBRKT >> errorDescriptor >> RBRKT );

        auditReturnParameter = (mediaDescriptor | modemDescriptor |
                                muxDescriptor | eventsDescriptor |
                                signalsDescriptor | digitMapDescriptor |

                           observedEventsDescriptor | eventBufferDescriptor |
                                statisticsDescriptor | packagesDescriptor |
                                 errorDescriptor | auditItem);

        auditDescriptor      = Tokens::AuditToken >> LBRKT >> -( auditItem % COMMA ) >> RBRKT;

        notifyRequest        = Tokens::NotifyToken >> EQUAL >> TerminationID
                               >> LBRKT >> ( observedEventsDescriptor
                                     >> -( COMMA >> errorDescriptor ) ) >> RBRKT;

        notifyReply          = Tokens::NotifyToken >> EQUAL >> TerminationID
                               >> -( LBRKT >> errorDescriptor >> RBRKT );

        serviceChangeRequest = Tokens::ServiceChangeToken >> EQUAL >> TerminationID
                               >> LBRKT >> serviceChangeDescriptor >> RBRKT;

        serviceChangeReply   = Tokens::ServiceChangeToken >> EQUAL >> TerminationID
                               >> -(LBRKT >> (errorDescriptor | serviceChangeReplyDescriptor) >> RBRKT);

        errorDescriptor   = Tokens::ErrorToken >> EQUAL >> ErrorCode
                            >> LBRKT >> -quotedString >> RBRKT;

        ErrorCode            = repeat(1,4)[digit]; // could be extended

        transactionID        = UINT32;

        // OTHER STUFF, DESCRIPTORS
        terminationIDList  = LBRKT >> (TerminationID % COMMA) >> RBRKT;

        TerminationID        = "ROOT" | pathNAME | "$" | "*";

        mediaDescriptor = Tokens::MediaToken >> LBRKT >> (mediaParm % COMMA) >> RBRKT;

        // at-most one terminationStateDescriptor
        // and either streamParm(s) or streamDescriptor(s) but not both
        mediaParm            = (streamParm | streamDescriptor | terminationStateDescriptor);

        // at-most-once per item
        streamParm           = (localDescriptor | remoteDescriptor | localControlDescriptor);

        streamDescriptor     = Tokens::StreamToken >> EQUAL >> StreamID
            >> LBRKT >> streamParm >> *(COMMA >> streamParm) >> RBRKT;

        localControlDescriptor = Tokens::LocalControlToken
            >> LBRKT >> localParm >> *(COMMA >> localParm) >> RBRKT;

        // at-most-once per item except for propertyParm
        localParm = (streamMode | propertyParm | reservedValueMode | reservedGroupMode);

        reservedValueMode    = Tokens::ReservedValueToken >> EQUAL >> ( lit("ON") | "OFF" );
        reservedGroupMode    = Tokens::ReservedGroupToken >> EQUAL >> ( lit("ON") | "OFF" );

        streamMode           = Tokens::ModeToken >> EQUAL >> streamModes;

        streamModes     = (Tokens::SendonlyToken | Tokens::RecvonlyToken | Tokens::SendrecvToken |
                               Tokens::InactiveToken | Tokens::LoopbackToken );

        propertyParm         = pkgdName >> parmValue;
        parmValue            = (EQUAL >> alternativeValue | INEQUAL >> VALUE);
        alternativeValue     = ( VALUE
                       | LSBRKT >> (VALUE % COMMA) >> RSBRKT // sublist (i.e., A AND B AND ...)
                       | LBRKT >> (VALUE % COMMA) >> RBRKT // alternatives (i.e., A OR B OR ...)
                       | LSBRKT >> VALUE >> ':' >> VALUE >> RSBRKT ) // range
                       ;
        // Note - The octet zero is not among the permitted characters in
        // octet string.  As the current definition is limited to SDP, and a
        // zero octet would not be a legal character in SDP, this is not a
        // concern.

        localDescriptor      = Tokens::LocalToken >> LBRKT >> octetString >> RBRKT;

        remoteDescriptor     = Tokens::RemoteToken >> LBRKT >> octetString >> RBRKT;

        eventBufferDescriptor= Tokens::EventBufferToken >> -( LBRKT >> eventSpec >> *( COMMA >> eventSpec) >> RBRKT );

        eventSpec      = pkgdName >> -( LBRKT >> (eventSpecParameter % COMMA) >> RBRKT );
        eventSpecParameter   = (eventStream | eventOther);

        eventBufferControl     = Tokens::BufferToken >> EQUAL >> ( "OFF" | Tokens::LockStepToken );

        terminationStateDescriptor = Tokens::TerminationStateToken >> LBRKT
                   >> terminationStateParm >> *( COMMA >> terminationStateParm ) >> RBRKT;

        // at-most-once per item except for propertyParm
        terminationStateParm = (propertyParm | serviceStates | eventBufferControl);

        serviceStates        = Tokens::ServiceStatesToken >> EQUAL >> ( Tokens::TestToken | Tokens::OutOfSvcToken | Tokens::InSvcToken );

        muxDescriptor        = Tokens::MuxToken >> EQUAL >> MuxType  >> terminationIDList;

        MuxType              = ( Tokens::H221Token | Tokens::H223Token | Tokens::H226Token | Tokens::V76Token
                                | extensionParameter );

        StreamID             = UINT16;
        pkgdName     = (PackageName >> '/' >> ItemID) //specific item
                     | (PackageName >> "/*") //all items in package
                     | "*/*" // all items supported by the MG
                     ;
        PackageName          = NAME.alias();
        ItemID               = NAME.alias();

        eventsDescriptor     = Tokens::EventsToken >> -( EQUAL >> RequestID >> LBRKT >> requestedEvent >> *( COMMA >> requestedEvent ) >> RBRKT );

        requestedEvent       = pkgdName >> -( LBRKT >> eventParameter >> *( COMMA >> eventParameter ) >> RBRKT );

        // at-most-once each of KeepActiveToken , eventDM and eventStream
        //at most one of either embedWithSig or embedNoSig but not both
        //KeepActiveToken and embedWithSig must not both be present
        eventParameter       = ( embedWithSig | embedNoSig | Tokens::KeepActiveToken | eventDM | eventStream | eventOther );

        embedWithSig         = Tokens::EmbedToken >> LBRKT >> signalsDescriptor
                                 >> -(COMMA >> embedFirst ) >> RBRKT;
        embedNoSig        = Tokens::EmbedToken >> LBRKT >> embedFirst >> RBRKT;

        // at-most-once of each
        embedFirst      = Tokens::EventsToken >> -( EQUAL >> RequestID >> LBRKT >> (secondRequestedEvent % COMMA) >> RBRKT );

        secondRequestedEvent = pkgdName >> -( LBRKT >> secondEventParameter >> *( COMMA >> secondEventParameter ) >> RBRKT );

        // at-most-once each of embedSig , KeepActiveToken, eventDM or
        // eventStream
        // KeepActiveToken and embedSig must not both be present
        secondEventParameter = ( embedSig | Tokens::KeepActiveToken | eventDM |
                                 eventStream | eventOther );

        embedSig  = Tokens::EmbedToken >> LBRKT >> signalsDescriptor >> RBRKT;

        eventStream          = Tokens::StreamToken >> EQUAL >> StreamID;

        eventOther           = eventParameterName >> parmValue;

        eventParameterName   = NAME.alias();

        eventDM              = Tokens::DigitMapToken >> EQUAL >> ( digitMapName  |
                               (LBRKT >> digitMapValue >> RBRKT ));

        signalsDescriptor    = Tokens::SignalsToken >> LBRKT >> -( signalParm % COMMA) >> RBRKT;

        signalParm           = signalList | signalRequest;

        signalRequest        = signalName >> -( LBRKT >> (sigParameter % COMMA) >> RBRKT );

        signalList           = Tokens::SignalListToken >> EQUAL >> signalListId >> LBRKT
                               >> (signalListParm % COMMA) >> RBRKT;

        signalListId         = UINT16;

        //exactly once signalType, at most once duration and every signal
        //parameter
        signalListParm       = signalRequest.alias();

        signalName           = pkgdName.alias();
        //at-most-once sigStream, at-most-once sigSignalType,
        //at-most-once sigDuration, every signalParameterName at most once
        sigParameter = sigStream | sigSignalType | sigDuration | sigOther
                    | notifyCompletion | Tokens::KeepActiveToken;
        sigStream            = Tokens::StreamToken >> EQUAL >> StreamID;
        sigOther             = sigParameterName >> parmValue;
        sigParameterName     = NAME.alias();
        sigSignalType        = Tokens::SignalTypeToken >> EQUAL >> signalType;
        signalType           = (Tokens::OnOffToken | Tokens::TimeOutToken | Tokens::BriefToken);
        sigDuration          = Tokens::DurationToken >> EQUAL >> UINT16;
        notifyCompletion     = Tokens::NotifyCompletionToken >> EQUAL >> (LBRKT
                 >> (notificationReason % COMMA) >> RBRKT);

        notificationReason   = ( Tokens::TimeOutToken | Tokens::InterruptByEventToken
                             | Tokens::InterruptByNewSignalsDescrToken
                             | Tokens::OtherReasonToken );
        observedEventsDescriptor = Tokens::ObservedEventsToken >> EQUAL >> RequestID
                           >> LBRKT >> (observedEvent % COMMA) >> RBRKT;

        //time per event, because it might be buffered
        observedEvent        = -( TimeStamp >> LWSP >> ':') >> LWSP
                               >> pkgdName >> -( LBRKT >> (observedEventParameter % COMMA) >> RBRKT );

        //at-most-once eventStream, every eventParameterName at most once
        observedEventParameter = eventStream | eventOther;

        // For an AuditCapReply with all events, the RequestID should be ALL.
        RequestID            = ( UINT32 | "*" );

        modemDescriptor      = Tokens::ModemToken >> (( EQUAL >> modemType) |
                           (LSBRKT >> (modemType % COMMA) >> RSBRKT))
                          >> -( LBRKT >> (propertyParm % COMMA) >> RBRKT );

        // at-most-once except for extensionParameter
        modemType            = (Tokens::V32bisToken | Tokens::V22bisToken | Tokens::V18Token |
                                Tokens::V22Token | Tokens::V32Token | Tokens::V34Token | Tokens::V90Token |
                              Tokens::V91Token | Tokens::SynchISDNToken | extensionParameter);

        digitMapDescriptor  = Tokens::DigitMapToken >> EQUAL
                             >> ( ( LBRKT >> digitMapValue >> RBRKT ) |
                             (digitMapName >> -( LBRKT >> digitMapValue >> RBRKT )) );
        digitMapName        = NAME.alias();
        digitMapValue       = -("T:" >> Timer >> COMMA) >> -("S:" >> Timer >> COMMA)
                           >> -("L:" >> Timer >> COMMA) >> digitMap;
        Timer               = repeat(1,2)[digit];
        // Units are seconds for T, S, and L timers, and hundreds of
        // milliseconds for Z timer.  Thus T, S, and L range from 1 to 99
        // seconds and Z from 100 ms to 9.9 s
        digitMap = (digitString |
                    LPAREN >> digitStringList >> RPAREN);
        digitStringList   = digitString >> *( PIPE >> digitString );
        digitString       = +digitStringElement;
        digitStringElement = digitPosition >> -lit('.');
        digitPosition     = digitMapLetter | digitMapRange;
        digitMapRange     = ("x" | (LSBRKT >> digitLetter >> RSBRKT));
        digitLetter       = *((digit >> "-" >> digit ) | digitMapLetter);
        digitMapLetter    = char_("0-9" //Basic event symbols
                                  "a-kA-K"
                                  "LS" // Inter-event timers (long, short)
                                  "Z" //Long duration modifier
                                  );

        //at-most-once, and DigitMapToken and PackagesToken are not allowed
        //in AuditCapabilities command
        auditItem            = ( Tokens::MuxToken | Tokens::ModemToken | Tokens::MediaToken |
                                Tokens::SignalsToken | Tokens::EventBufferToken |
                                Tokens::DigitMapToken | Tokens::StatsToken | Tokens::EventsToken |
                                Tokens::ObservedEventsToken | Tokens::PackagesToken );

        serviceChangeDescriptor = Tokens::ServicesToken
            >> LBRKT >> serviceChangeParm >> *(COMMA >> serviceChangeParm) >> RBRKT;

        // each parameter at-most-once
        // at most one of either serviceChangeAddress or serviceChangeMgcId
        // but not both
        // serviceChangeMethod and serviceChangeReason are REQUIRED
        serviceChangeParm    = (serviceChangeMethod | serviceChangeReason |
                               serviceChangeDelay | serviceChangeAddress |
                               serviceChangeProfile | extension | TimeStamp |
                               serviceChangeMgcId | serviceChangeVersion );

        serviceChangeReplyDescriptor = Tokens::ServicesToken >> LBRKT
                             >> (servChgReplyParm % COMMA) >> RBRKT;

        // at-most-once.  Version is REQUIRED on first ServiceChange response
        // at most one of either serviceChangeAddress or serviceChangeMgcId
        // but not both
        servChgReplyParm     = (serviceChangeAddress | serviceChangeMgcId |
                               serviceChangeProfile | serviceChangeVersion |
                               TimeStamp);
        serviceChangeMethod  = Tokens::MethodToken >> EQUAL >> (Tokens::FailoverToken |
                               Tokens::ForcedToken | Tokens::GracefulToken | Tokens::RestartToken |
                               Tokens::DisconnectedToken | Tokens::HandOffToken |
                               extensionParameter);
        // A serviceChangeReason consists of a numeric reason code
        // and an optional text description.
        // A serviceChangeReason MUST be encoded using the quotedString
        // form of VALUE.
        // The quotedString SHALL contain a decimal reason code,
        // optionally followed by a single space character and a
        // textual description string.

        serviceChangeReason  = Tokens::ReasonToken  >> EQUAL >> VALUE;
        serviceChangeDelay   = Tokens::DelayToken   >> EQUAL >> UINT32;
        serviceChangeAddress = Tokens::ServiceChangeAddressToken >> EQUAL >> ( mId |
                               portNumber );
        serviceChangeMgcId   = Tokens::MgcIdToken   >> EQUAL >> mId;
        serviceChangeProfile = Tokens::ProfileToken >> EQUAL >> NAME >> '/' >> Version;
        serviceChangeVersion = Tokens::VersionToken >> EQUAL >> Version;
        extension            = extensionParameter >> parmValue;

        packagesDescriptor   = Tokens::PackagesToken
            >> LBRKT >> packagesItem >> *(COMMA >> packagesItem) >> RBRKT;

        packagesItem         = NAME >> "-" >> UINT16;

        TimeStamp            = Date >> "T" >> Time; // per ISO 8601:1988
        // Date = yyyymmdd
        Date                 = repeat(8)[digit];
        // Time = hhmmssss
        Time                 = repeat(8)[digit];
        statisticsDescriptor = Tokens::StatsToken
            >> LBRKT >> statisticsParameter >> *(COMMA >> statisticsParameter ) >> RBRKT;

        //at-most-once per item
        statisticsParameter  = pkgdName >> -(EQUAL >> VALUE);

        topologyDescriptor   = Tokens::TopologyToken
            >> LBRKT >> topologyTriple >> *(COMMA >> topologyTriple) >> RBRKT;
        topologyTriple       = terminationA >> COMMA >>
                               terminationB >> COMMA >> topologyDirection;
        terminationA         = TerminationID.alias();
        terminationB         = TerminationID.alias();
        topologyDirection    = Tokens::BothwayToken | Tokens::IsolateToken | Tokens::OnewayToken;

        priority             = Tokens::PriorityToken >> EQUAL >> UINT16;

        extensionParameter   = "X" >> char_("-+") >> repeat(1,6)[alnum];

        BOOST_SPIRIT_DEBUG_NODES(
            // snipped for Stack Overflow, see Coliru
        )

    }
  private:
    qi::rule<It> megacoMessage, message;
    qi::rule<It, uint32_t()> mtpAddress, ContextID;

    qi::rule<It, std::string()> mId, domainName, deviceName, pathNAME, domainAddress, pathDomainName,
        IPv4address, IPv6address, hexpart, hexseq;
    qi::rule<It, uint16_t()> portNumber;
    qi::rule<It, uint8_t()> V4hex;

    // implicit lexemes (no implicit whitespace allowed):
    qi::rule<It> authenticationHeader;
    qi::uint_parser<int, 10, 1, 2> Version;
    qi::uint_parser<uint32_t, 10, 1, 10> UINT32;
    qi::uint_parser<uint16_t, 10, 1, 5>  UINT16;

    // message payload
    qi::rule<It> messageBody,
        transactionList, transactionPending, transactionResponseAck, transactionAck, transactionRequest,
        actionRequest,
        contextRequest, contextProperties, contextProperty, contextAudit, contextAuditProperties,
        commandRequestList, commandRequest,
        transactionReply,
        actionReplyList, actionReply, commandReply,
        commandReplyList, commandReplys,
        ammRequest, ammParameter, ammsReply,
        subtractRequest,
        auditRequest, auditReply, auditOther,
        terminationAudit,
        contextTerminationAudit,
        auditReturnParameter, auditDescriptor, notifyRequest,
        notifyReply,
        serviceChangeRequest, serviceChangeReply,
        errorDescriptor, ErrorCode, transactionID;

    // OTHER STUFF, DESCRIPTORS
    qi::rule<It>
        terminationIDList,
        TerminationID, mediaDescriptor,
        mediaParm, streamParm,
        streamDescriptor, localControlDescriptor, localParm,
        reservedValueMode, reservedGroupMode,
        streamMode, streamModes,
        propertyParm, parmValue, alternativeValue,
        localDescriptor, remoteDescriptor,
        eventBufferDescriptor, eventSpec, eventSpecParameter, eventBufferControl,
        terminationStateDescriptor, terminationStateParm,
        serviceStates,
        muxDescriptor, MuxType,
        StreamID,
        pkgdName, PackageName,
        ItemID,
        eventsDescriptor, requestedEvent, eventParameter,
        embedWithSig, embedNoSig, embedFirst,
        secondRequestedEvent, secondEventParameter,
        embedSig,
        eventStream, eventOther, eventParameterName, eventDM,
        signalsDescriptor, signalParm, signalRequest, signalList, signalListId, signalListParm, signalName,
        sigParameter, sigStream, sigOther, sigParameterName, sigSignalType, signalType, sigDuration,
        notifyCompletion, notificationReason,
        observedEventsDescriptor, observedEvent, observedEventParameter,
        RequestID,
        modemDescriptor, modemType,
        digitMapDescriptor, digitMapName, digitMapValue,
        Timer,
        digitMap, digitStringList, digitString, digitStringElement, digitPosition, digitMapRange, digitLetter, digitMapLetter,
        auditItem,
        serviceChangeDescriptor, serviceChangeParm, serviceChangeReplyDescriptor,
        servChgReplyParm,
        serviceChangeMethod, serviceChangeReason, serviceChangeDelay, serviceChangeAddress, serviceChangeMgcId, serviceChangeProfile, serviceChangeVersion,
        extension,
        packagesDescriptor,
        packagesItem,
        TimeStamp, Date, Time,
        statisticsDescriptor, statisticsParameter,
        topologyDescriptor, topologyTriple,
        terminationA, terminationB,
        topologyDirection,
        priority,
        extensionParameter;
};

};
int main() {
    std::string const  sample = R"(
!/3 [15.232.33.21]:2134
T=173619123
{
    C=230234621
    {
        PR=9,
        MF=ip/187/6/23045241
        {
            MD=V90
        },
        MF=ip/187/6/23045242
        {
            MD=V90
        }
    }
})";

    using It = std::string::const_iterator;
    Megaco<It>::Parser parser;

    It f = sample.begin(), l = sample.end();
    bool ok = qi::parse(f, l, parser);

    if (ok)
        std::cout << "Parse success\n";
    else
        std::cout << "Parse failed\n";

    if (f != l)
        std::cout << "Remaining unparsed input: '" << std::string(f,l) << "'\n";
}
```
<p>Prints</p>
```Parse success
```

¹ i.e. mostly dumb transformation of the productions, specifically barely no attribute handling and very heavy (e.g. no symbols<> for the modemtypes etc.)

Body:
I have an input encoded with ABNF grammar rules (it is MEGACO protocol):

!/3 [15.232.33.21]:2134
T=173619123
{
    C=230234621
    {
        PR=9,
        MF=ip/187/6/23045241
        {
           ...
        },
        MF=ip/187/6/23045242
        {

I want to parse it into a complex struct with boost::spirit, pseudo-code:

megaco
{
    param1
    param2
    {
        param1
        param2
        list of param3
            param3-1
            {
                param4
                ...
            }
            param3-2
            {
                ...
            }
    }
}

It should be noted that the grammar is complex and contains a lot of alternatives, levels and sequences. I am not sure how to create a boost::spirit parser to decode such a message level by level saving necessary values in the process.

Also I am not sure that boost::spirit is the right tool for it.

So how should I do it?

UPDATE: I want to thanks sehe for the great example, still the main task is to populate some structure with the values from the message. The only possible way I see now is to use BOOST_FUSION_ADAPT_STRUCT with a lot of structs using boost::variant for alternative and std::vector for lists of items. Am I right?

Body:
Ironically, heading over to Appendix B.2 of RFC 3525, and implementing the bulk of it superficially¹ it turns out your sample snippet is invalid.

It was missing ammParameter, that's not optional as soon as you have the opening {:

So, fixing the snippet, here's something to get you started. It's only 850 lines of code because the spec is lengthy:

Live On Coliru

//#define BOOST_SPIRIT_DEBUG
#include <boost/spirit/include/qi.hpp>
namespace qi = boost::spirit::qi;

template <typename It> struct Megaco {

struct Tokens {
    Tokens() {
        using namespace qi;
        auto SafeChar = copy(alnum | char_("-+&!_/'?@^`~*$\\()%|."));
        auto RestChar = copy(char_(";[]{}:,#<>="));
        auto WSP         = copy(char_(" \t"));
        COMMENT      = ';' >> *(SafeChar | RestChar | WSP | '"') >> (eol|eoi);

        SEP = +(WSP | COMMENT | eol);
        LWSP = *(WSP | COMMENT | eol);
        NAME = raw [ alpha >> repeat(0,63) [alnum|'_'] ];

        // Note - The double-quote character is not allowed in quotedString.
        quotedString = '"' >> *(SafeChar | RestChar | WSP) >> '"';
        VALUE       = quotedString | lexeme[+SafeChar];
        octetString = *("\\}" | char_("\x01-\x7C\x7E-\xFF"));

        MTPToken=no_case["MTP"];
        H221Token=no_case["H221"];
        H223Token=no_case["H223"];
        H226Token=no_case["H226"];
        V18Token=no_case["V18"];
        V22Token=no_case["V22"];
        V22bisToken=no_case["V22b"];
        V32Token=no_case["V32"];
        V32bisToken=no_case["V32b"];
        V34Token=no_case["V34"];
        V76Token=no_case["V76"];
        V90Token=no_case["V90"];
        V91Token=no_case["V91"];

        BOOST_SPIRIT_DEBUG_NODES(
                // snipped for Stack Overflow, see Coliru
           )
    }
  protected:
    using Token = qi::rule<It>;
    Token COMMENT, SEP, LWSP;
    qi::rule<It, std::string()> NAME, quotedString, VALUE, octetString;
    #define TOK(name,long,short) name##Token{qi::no_case[qi::lit(#long)|#short]},
    Token
        TOK(Add,Add,A) TOK(Audit,Audit,AT) TOK(AuditCap,AuditCapability,AC) TOK(AuditValue,AuditValue,AV) TOK(Auth,Authentication,AU)
        TOK(Bothway,Bothway,BW) TOK(Brief,Brief,BR) TOK(Buffer,Buffer,BF) TOK(Ctx,Context,C) TOK(ContextAudit,ContextAudit,CA)
        TOK(DigitMap,DigitMap,DM) TOK(Disconnected,Disconnected,DC) TOK(Delay,Delay,DL) TOK(Duration,Duration,DR) TOK(Embed,Embed,EM)
        TOK(Emergency,Emergency,EG) TOK(Error,Error,ER) TOK(EventBuffer,EventBuffer,EB) TOK(Events,Events,E) TOK(Failover,Failover,FL)
        TOK(Forced,Forced,FO) TOK(Graceful,Graceful,GR) TOK(HandOff,HandOff,HO) TOK(ImmAckRequired,ImmAckRequired,IA)
        TOK(Inactive,Inactive,IN) TOK(Isolate,Isolate,IS) TOK(InSvc,InService,IV) TOK(InterruptByEvent,IntByEvent,IBE)
        TOK(InterruptByNewSignalsDescr,IntBySigDescr,IBS) TOK(KeepActive,KeepActive,KA) TOK(Local,Local,L) TOK(LocalControl,LocalControl,O)
        TOK(LockStep,LockStep,SP) TOK(Loopback,Loopback,LB) TOK(Media,Media,M) TOK(Megacop,MEGACO,!) TOK(Method,Method,MT)
        TOK(MgcId,MgcIdToTry,MG) TOK(Mode,Mode,MO) TOK(Modify,Modify,MF) TOK(Modem,Modem,MD) TOK(Move,Move,MV)
        TOK(Mux,Mux,MX) TOK(Notify,Notify,N) TOK(NotifyCompletion,NotifyCompletion,NC) TOK(ObservedEvents,ObservedEvents,OE) TOK(Oneway,Oneway,OW)
        TOK(OnOff,OnOff,OO) TOK(OtherReason,OtherReason,OR) TOK(OutOfSvc,OutOfService,OS) TOK(Packages,Packages,PG) TOK(Pending,Pending,PN)
        TOK(Priority,Priority,PR) TOK(Profile,Profile,PF) TOK(Reason,Reason,RE) TOK(Recvonly,ReceiveOnly,RC) TOK(Reply,Reply,P)
        TOK(Restart,Restart,RS) TOK(Remote,Remote,R) TOK(ReservedGroup,ReservedGroup,RG) TOK(ReservedValue,ReservedValue,RV) TOK(Sendonly,SendOnly,SO)
        TOK(Sendrecv,SendReceive,SR) TOK(Services,Services,SV) TOK(ServiceStates,ServiceStates,SI) TOK(ServiceChange,ServiceChange,SC)
        TOK(ServiceChangeAddress,ServiceChangeAddress,AD) TOK(SignalList,SignalList,SL) TOK(Signals,Signals,SG) TOK(SignalType,SignalType,SY)
        TOK(Stats,Statistics,SA) TOK(Stream,Stream,ST) TOK(Subtract,Subtract,S) TOK(SynchISDN,SynchISDN,SN) TOK(TerminationState,TerminationState,TS)
        TOK(Test,Test,TE) TOK(TimeOut,TimeOut,TO) TOK(Topology,Topology,TP) TOK(Trans,Transaction,T) TOK(ResponseAck,TransactionResponseAck,K)
        TOK(Version,Version,V) MTPToken, H221Token, H223Token, H226Token, V18Token, V22Token, V22bisToken,
        V32Token, V32bisToken, V34Token, V76Token, V90Token, V91Token;

    // The values 0x0, 0xFFFFFFFE and 0xFFFFFFFF are reserved.
    struct SpecialContexts : qi::symbols<char, uint32_t> {
        enum { NULL_, CHOOSE = 0xFFFFFFFEl, ALL = 0xFFFFFFFFl };
        SpecialContexts() { this->add
            ("$", CHOOSE)
            ("*", ALL)
            ("-", NULL_);
        }
    } SpecialContext;
};

struct Parser : Tokens, qi::grammar<It> {
    using Tokens::LWSP;
    using Tokens::SEP;
    using Tokens::SpecialContext;
    using Tokens::NAME;
    using Tokens::VALUE;
    using Tokens::quotedString;
    using Tokens::octetString;

    Parser() : Parser::base_type(megacoMessage) {
        using namespace qi;

        auto LBRKT   = copy(LWSP >> '{' >> LWSP);
        auto RBRKT   = copy(LWSP >> '}' >> LWSP);
        auto EQUAL   = copy(LWSP >> '=' >> LWSP);
        auto COMMA   = copy(LWSP >> ',' >> LWSP);
        auto INEQUAL = copy(LWSP >> char_("><#") >> LWSP);
        auto LSBRKT  = copy(LWSP >> '[' >> LWSP);
        auto RSBRKT  = copy(LWSP >> ']' >> LWSP);
        auto LPAREN  = copy(LWSP >> '(' >> LWSP);
        auto RPAREN  = copy(LWSP >> ')' >> LWSP);
        auto PIPE    = copy(LWSP >> '|' >> LWSP);

        megacoMessage = LWSP >> -(authenticationHeader >> SEP) >> message;

        authenticationHeader
            = Tokens::AuthToken
            >> EQUAL
            >> ("0x" >> repeat(8)[xdigit])
            >> ':'
            >> ("0x" >> repeat(8)[xdigit])
            >> ':'
            >> repeat(24,64)[xdigit]
            ;

        message
            = Tokens::MegacopToken >> '/' >> Version >> SEP >> mId >> SEP
            >> messageBody;

        mId
            = ((domainAddress | domainName) >> -(':' >> portNumber))
            | mtpAddress
            | deviceName
            ;

        domainName
            = '<' >> alnum >> repeat(0,63)[char_("a-zA-Z0-9.-")] >> '>';
        deviceName
            = pathNAME.alias();
        pathNAME // TODO total lenght limit according to RFC comment
            = -lit('*') >> NAME >> *char_("/*a-zA-Z0-9_$") >> -('@' >> pathDomainName);

        pathDomainName = raw [(alnum|'*') >> repeat(0,63)[alnum|'-'|'*'|'.'] ];

        ContextID = SpecialContext | UINT32;

        domainAddress = '[' >> (IPv4address | IPv6address) >> ']';

        // RFC2373 contains the definition of IP6Addresses.
        IPv6address   = hexpart >> - (':' >> IPv4address);
        IPv4address   = V4hex >> '.' >> V4hex >> '.' >> V4hex >> '.' >> V4hex;
        V4hex         = qi::uint_parser<uint8_t, 10, 1, 3>{}; // "0".."255"

        hexpart = raw [
                  "::" >> -hexseq
                | hexseq >> "::" >> -hexseq
                | hexseq
            ];

        hexseq = raw[ uint_parser<uint16_t, 16, 1, 4>{} % ':' ];

        portNumber = UINT16;

        // TODO constraint checking?
        // To octet align the mtpAddress the MSBs shall be encoded as 0s.
        // An octet shall be represented by 2 hex digits.
        mtpAddress
            = Tokens::MTPToken
            >> LBRKT
            >> uint_parser<uint32_t, 16, 4, 8>{}
            >> RBRKT
            ;

        messageBody = errorDescriptor | transactionList;

        transactionList      = +( transactionRequest | transactionReply |
                               transactionPending | transactionResponseAck );
        //Use of response acks is dependent on underlying transport

        transactionPending   = Tokens::PendingToken >> EQUAL >> transactionID >> LBRKT >> RBRKT;

        transactionResponseAck = Tokens::ResponseAckToken
            >> LBRKT >> (transactionAck % COMMA) >> RBRKT;
        transactionAck = transactionID | (transactionID >> "-" >> transactionID);

        transactionRequest   = Tokens::TransToken >> EQUAL >> transactionID >> LBRKT
                               >> (actionRequest % COMMA) >> RBRKT;

        actionRequest        = Tokens::CtxToken >> EQUAL >> ContextID >> LBRKT >> ((
                               contextRequest >> -(COMMA  >> commandRequestList))
                               | commandRequestList) >> RBRKT;

        contextRequest    = ((contextProperties >> -(COMMA >> contextAudit))
                    | contextAudit);

        contextProperties    = contextProperty % COMMA;

        // at-most-once
        contextProperty    = (topologyDescriptor | priority | Tokens::EmergencyToken);

        contextAudit   = Tokens::ContextAuditToken
            >> LBRKT >> (contextAuditProperties % COMMA) >> RBRKT;

        // at-most-once
        contextAuditProperties = ( Tokens::TopologyToken | Tokens::EmergencyToken | Tokens::PriorityToken );

        // "O-" indicates an optional command
        // "W-" indicates a wildcarded response to a command
        commandRequestList = -lit("O-") >> -lit("W-") >> commandRequest
                             >> *(COMMA >> -lit("O-") >> -lit("W-") >> commandRequest);

        commandRequest      = ( ammRequest | subtractRequest | auditRequest |
                                notifyRequest | serviceChangeRequest);

        transactionReply     = Tokens::ReplyToken >> EQUAL >> transactionID >> LBRKT
                          >> -( Tokens::ImmAckRequiredToken >> COMMA)
                        >> ( errorDescriptor | actionReplyList ) >> RBRKT;

        actionReplyList      = actionReply % COMMA ;

        actionReply          = Tokens::CtxToken >> EQUAL >> ContextID >> LBRKT
                          >> ( ( errorDescriptor | commandReply ) |
                 (commandReply >> COMMA >> errorDescriptor) ) >> RBRKT;

        commandReply      = (( contextProperties >> -(COMMA >> commandReplyList) ) |
                                commandReplyList );

        commandReplyList     = commandReplys % COMMA ;

        commandReplys        = (serviceChangeReply | auditReply | ammsReply |
                                notifyReply );

        //Add Move and Modify have the same request parameters
        ammRequest           = (Tokens::AddToken | Tokens::MoveToken | Tokens::ModifyToken ) >> EQUAL
                                >> TerminationID >>
                                -(LBRKT >> (ammParameter % COMMA) >> RBRKT);

        //at-most-once
        ammParameter         = (mediaDescriptor | modemDescriptor |
                                muxDescriptor | eventsDescriptor |
                                signalsDescriptor | digitMapDescriptor |
                                eventBufferDescriptor | auditDescriptor);

        ammsReply            = (Tokens::AddToken | Tokens::MoveToken | Tokens::ModifyToken |
                                Tokens::SubtractToken ) >> EQUAL >> TerminationID >> -( LBRKT
                                >> terminationAudit >> RBRKT );

        subtractRequest      =  Tokens::SubtractToken >> EQUAL >> TerminationID
                                >> -( LBRKT >> auditDescriptor >> RBRKT);

        auditRequest         =  (Tokens::AuditValueToken | Tokens::AuditCapToken ) >> EQUAL
                                >> TerminationID >> LBRKT >> auditDescriptor >> RBRKT;

        auditReply           = (Tokens::AuditValueToken | Tokens::AuditCapToken )
                               >> ( contextTerminationAudit  | auditOther);

        auditOther           = EQUAL >> TerminationID >> -(LBRKT >> terminationAudit >> RBRKT);

        terminationAudit = auditReturnParameter % COMMA;

        contextTerminationAudit = EQUAL >> Tokens::CtxToken >> ( terminationIDList |
                               LBRKT >> errorDescriptor >> RBRKT );

        auditReturnParameter = (mediaDescriptor | modemDescriptor |
                                muxDescriptor | eventsDescriptor |
                                signalsDescriptor | digitMapDescriptor |

                           observedEventsDescriptor | eventBufferDescriptor |
                                statisticsDescriptor | packagesDescriptor |
                                 errorDescriptor | auditItem);

        auditDescriptor      = Tokens::AuditToken >> LBRKT >> -( auditItem % COMMA ) >> RBRKT;

        notifyRequest        = Tokens::NotifyToken >> EQUAL >> TerminationID
                               >> LBRKT >> ( observedEventsDescriptor
                                     >> -( COMMA >> errorDescriptor ) ) >> RBRKT;

        notifyReply          = Tokens::NotifyToken >> EQUAL >> TerminationID
                               >> -( LBRKT >> errorDescriptor >> RBRKT );

        serviceChangeRequest = Tokens::ServiceChangeToken >> EQUAL >> TerminationID
                               >> LBRKT >> serviceChangeDescriptor >> RBRKT;

        serviceChangeReply   = Tokens::ServiceChangeToken >> EQUAL >> TerminationID
                               >> -(LBRKT >> (errorDescriptor | serviceChangeReplyDescriptor) >> RBRKT);

        errorDescriptor   = Tokens::ErrorToken >> EQUAL >> ErrorCode
                            >> LBRKT >> -quotedString >> RBRKT;

        ErrorCode            = repeat(1,4)[digit]; // could be extended

        transactionID        = UINT32;

        // OTHER STUFF, DESCRIPTORS
        terminationIDList  = LBRKT >> (TerminationID % COMMA) >> RBRKT;

        TerminationID        = "ROOT" | pathNAME | "$" | "*";

        mediaDescriptor = Tokens::MediaToken >> LBRKT >> (mediaParm % COMMA) >> RBRKT;

        // at-most one terminationStateDescriptor
        // and either streamParm(s) or streamDescriptor(s) but not both
        mediaParm            = (streamParm | streamDescriptor | terminationStateDescriptor);

        // at-most-once per item
        streamParm           = (localDescriptor | remoteDescriptor | localControlDescriptor);

        streamDescriptor     = Tokens::StreamToken >> EQUAL >> StreamID
            >> LBRKT >> streamParm >> *(COMMA >> streamParm) >> RBRKT;

        localControlDescriptor = Tokens::LocalControlToken
            >> LBRKT >> localParm >> *(COMMA >> localParm) >> RBRKT;

        // at-most-once per item except for propertyParm
        localParm = (streamMode | propertyParm | reservedValueMode | reservedGroupMode);

        reservedValueMode    = Tokens::ReservedValueToken >> EQUAL >> ( lit("ON") | "OFF" );
        reservedGroupMode    = Tokens::ReservedGroupToken >> EQUAL >> ( lit("ON") | "OFF" );

        streamMode           = Tokens::ModeToken >> EQUAL >> streamModes;

        streamModes     = (Tokens::SendonlyToken | Tokens::RecvonlyToken | Tokens::SendrecvToken |
                               Tokens::InactiveToken | Tokens::LoopbackToken );

        propertyParm         = pkgdName >> parmValue;
        parmValue            = (EQUAL >> alternativeValue | INEQUAL >> VALUE);
        alternativeValue     = ( VALUE
                       | LSBRKT >> (VALUE % COMMA) >> RSBRKT // sublist (i.e., A AND B AND ...)
                       | LBRKT >> (VALUE % COMMA) >> RBRKT // alternatives (i.e., A OR B OR ...)
                       | LSBRKT >> VALUE >> ':' >> VALUE >> RSBRKT ) // range
                       ;
        // Note - The octet zero is not among the permitted characters in
        // octet string.  As the current definition is limited to SDP, and a
        // zero octet would not be a legal character in SDP, this is not a
        // concern.

        localDescriptor      = Tokens::LocalToken >> LBRKT >> octetString >> RBRKT;

        remoteDescriptor     = Tokens::RemoteToken >> LBRKT >> octetString >> RBRKT;

        eventBufferDescriptor= Tokens::EventBufferToken >> -( LBRKT >> eventSpec >> *( COMMA >> eventSpec) >> RBRKT );

        eventSpec      = pkgdName >> -( LBRKT >> (eventSpecParameter % COMMA) >> RBRKT );
        eventSpecParameter   = (eventStream | eventOther);

        eventBufferControl     = Tokens::BufferToken >> EQUAL >> ( "OFF" | Tokens::LockStepToken );

        terminationStateDescriptor = Tokens::TerminationStateToken >> LBRKT
                   >> terminationStateParm >> *( COMMA >> terminationStateParm ) >> RBRKT;

        // at-most-once per item except for propertyParm
        terminationStateParm = (propertyParm | serviceStates | eventBufferControl);

        serviceStates        = Tokens::ServiceStatesToken >> EQUAL >> ( Tokens::TestToken | Tokens::OutOfSvcToken | Tokens::InSvcToken );

        muxDescriptor        = Tokens::MuxToken >> EQUAL >> MuxType  >> terminationIDList;

        MuxType              = ( Tokens::H221Token | Tokens::H223Token | Tokens::H226Token | Tokens::V76Token
                                | extensionParameter );

        StreamID             = UINT16;
        pkgdName     = (PackageName >> '/' >> ItemID) //specific item
                     | (PackageName >> "/*") //all items in package
                     | "*/*" // all items supported by the MG
                     ;
        PackageName          = NAME.alias();
        ItemID               = NAME.alias();

        eventsDescriptor     = Tokens::EventsToken >> -( EQUAL >> RequestID >> LBRKT >> requestedEvent >> *( COMMA >> requestedEvent ) >> RBRKT );

        requestedEvent       = pkgdName >> -( LBRKT >> eventParameter >> *( COMMA >> eventParameter ) >> RBRKT );

        // at-most-once each of KeepActiveToken , eventDM and eventStream
        //at most one of either embedWithSig or embedNoSig but not both
        //KeepActiveToken and embedWithSig must not both be present
        eventParameter       = ( embedWithSig | embedNoSig | Tokens::KeepActiveToken | eventDM | eventStream | eventOther );

        embedWithSig         = Tokens::EmbedToken >> LBRKT >> signalsDescriptor
                                 >> -(COMMA >> embedFirst ) >> RBRKT;
        embedNoSig        = Tokens::EmbedToken >> LBRKT >> embedFirst >> RBRKT;

        // at-most-once of each
        embedFirst      = Tokens::EventsToken >> -( EQUAL >> RequestID >> LBRKT >> (secondRequestedEvent % COMMA) >> RBRKT );

        secondRequestedEvent = pkgdName >> -( LBRKT >> secondEventParameter >> *( COMMA >> secondEventParameter ) >> RBRKT );

        // at-most-once each of embedSig , KeepActiveToken, eventDM or
        // eventStream
        // KeepActiveToken and embedSig must not both be present
        secondEventParameter = ( embedSig | Tokens::KeepActiveToken | eventDM |
                                 eventStream | eventOther );

        embedSig  = Tokens::EmbedToken >> LBRKT >> signalsDescriptor >> RBRKT;

        eventStream          = Tokens::StreamToken >> EQUAL >> StreamID;

        eventOther           = eventParameterName >> parmValue;

        eventParameterName   = NAME.alias();

        eventDM              = Tokens::DigitMapToken >> EQUAL >> ( digitMapName  |
                               (LBRKT >> digitMapValue >> RBRKT ));

        signalsDescriptor    = Tokens::SignalsToken >> LBRKT >> -( signalParm % COMMA) >> RBRKT;

        signalParm           = signalList | signalRequest;

        signalRequest        = signalName >> -( LBRKT >> (sigParameter % COMMA) >> RBRKT );

        signalList           = Tokens::SignalListToken >> EQUAL >> signalListId >> LBRKT
                               >> (signalListParm % COMMA) >> RBRKT;

        signalListId         = UINT16;

        //exactly once signalType, at most once duration and every signal
        //parameter
        signalListParm       = signalRequest.alias();

        signalName           = pkgdName.alias();
        //at-most-once sigStream, at-most-once sigSignalType,
        //at-most-once sigDuration, every signalParameterName at most once
        sigParameter = sigStream | sigSignalType | sigDuration | sigOther
                    | notifyCompletion | Tokens::KeepActiveToken;
        sigStream            = Tokens::StreamToken >> EQUAL >> StreamID;
        sigOther             = sigParameterName >> parmValue;
        sigParameterName     = NAME.alias();
        sigSignalType        = Tokens::SignalTypeToken >> EQUAL >> signalType;
        signalType           = (Tokens::OnOffToken | Tokens::TimeOutToken | Tokens::BriefToken);
        sigDuration          = Tokens::DurationToken >> EQUAL >> UINT16;
        notifyCompletion     = Tokens::NotifyCompletionToken >> EQUAL >> (LBRKT
                 >> (notificationReason % COMMA) >> RBRKT);

        notificationReason   = ( Tokens::TimeOutToken | Tokens::InterruptByEventToken
                             | Tokens::InterruptByNewSignalsDescrToken
                             | Tokens::OtherReasonToken );
        observedEventsDescriptor = Tokens::ObservedEventsToken >> EQUAL >> RequestID
                           >> LBRKT >> (observedEvent % COMMA) >> RBRKT;

        //time per event, because it might be buffered
        observedEvent        = -( TimeStamp >> LWSP >> ':') >> LWSP
                               >> pkgdName >> -( LBRKT >> (observedEventParameter % COMMA) >> RBRKT );

        //at-most-once eventStream, every eventParameterName at most once
        observedEventParameter = eventStream | eventOther;

        // For an AuditCapReply with all events, the RequestID should be ALL.
        RequestID            = ( UINT32 | "*" );

        modemDescriptor      = Tokens::ModemToken >> (( EQUAL >> modemType) |
                           (LSBRKT >> (modemType % COMMA) >> RSBRKT))
                          >> -( LBRKT >> (propertyParm % COMMA) >> RBRKT );

        // at-most-once except for extensionParameter
        modemType            = (Tokens::V32bisToken | Tokens::V22bisToken | Tokens::V18Token |
                                Tokens::V22Token | Tokens::V32Token | Tokens::V34Token | Tokens::V90Token |
                              Tokens::V91Token | Tokens::SynchISDNToken | extensionParameter);

        digitMapDescriptor  = Tokens::DigitMapToken >> EQUAL
                             >> ( ( LBRKT >> digitMapValue >> RBRKT ) |
                             (digitMapName >> -( LBRKT >> digitMapValue >> RBRKT )) );
        digitMapName        = NAME.alias();
        digitMapValue       = -("T:" >> Timer >> COMMA) >> -("S:" >> Timer >> COMMA)
                           >> -("L:" >> Timer >> COMMA) >> digitMap;
        Timer               = repeat(1,2)[digit];
        // Units are seconds for T, S, and L timers, and hundreds of
        // milliseconds for Z timer.  Thus T, S, and L range from 1 to 99
        // seconds and Z from 100 ms to 9.9 s
        digitMap = (digitString |
                    LPAREN >> digitStringList >> RPAREN);
        digitStringList   = digitString >> *( PIPE >> digitString );
        digitString       = +digitStringElement;
        digitStringElement = digitPosition >> -lit('.');
        digitPosition     = digitMapLetter | digitMapRange;
        digitMapRange     = ("x" | (LSBRKT >> digitLetter >> RSBRKT));
        digitLetter       = *((digit >> "-" >> digit ) | digitMapLetter);
        digitMapLetter    = char_("0-9" //Basic event symbols
                                  "a-kA-K"
                                  "LS" // Inter-event timers (long, short)
                                  "Z" //Long duration modifier
                                  );

        //at-most-once, and DigitMapToken and PackagesToken are not allowed
        //in AuditCapabilities command
        auditItem            = ( Tokens::MuxToken | Tokens::ModemToken | Tokens::MediaToken |
                                Tokens::SignalsToken | Tokens::EventBufferToken |
                                Tokens::DigitMapToken | Tokens::StatsToken | Tokens::EventsToken |
                                Tokens::ObservedEventsToken | Tokens::PackagesToken );

        serviceChangeDescriptor = Tokens::ServicesToken
            >> LBRKT >> serviceChangeParm >> *(COMMA >> serviceChangeParm) >> RBRKT;

        // each parameter at-most-once
        // at most one of either serviceChangeAddress or serviceChangeMgcId
        // but not both
        // serviceChangeMethod and serviceChangeReason are REQUIRED
        serviceChangeParm    = (serviceChangeMethod | serviceChangeReason |
                               serviceChangeDelay | serviceChangeAddress |
                               serviceChangeProfile | extension | TimeStamp |
                               serviceChangeMgcId | serviceChangeVersion );

        serviceChangeReplyDescriptor = Tokens::ServicesToken >> LBRKT
                             >> (servChgReplyParm % COMMA) >> RBRKT;

        // at-most-once.  Version is REQUIRED on first ServiceChange response
        // at most one of either serviceChangeAddress or serviceChangeMgcId
        // but not both
        servChgReplyParm     = (serviceChangeAddress | serviceChangeMgcId |
                               serviceChangeProfile | serviceChangeVersion |
                               TimeStamp);
        serviceChangeMethod  = Tokens::MethodToken >> EQUAL >> (Tokens::FailoverToken |
                               Tokens::ForcedToken | Tokens::GracefulToken | Tokens::RestartToken |
                               Tokens::DisconnectedToken | Tokens::HandOffToken |
                               extensionParameter);
        // A serviceChangeReason consists of a numeric reason code
        // and an optional text description.
        // A serviceChangeReason MUST be encoded using the quotedString
        // form of VALUE.
        // The quotedString SHALL contain a decimal reason code,
        // optionally followed by a single space character and a
        // textual description string.

        serviceChangeReason  = Tokens::ReasonToken  >> EQUAL >> VALUE;
        serviceChangeDelay   = Tokens::DelayToken   >> EQUAL >> UINT32;
        serviceChangeAddress = Tokens::ServiceChangeAddressToken >> EQUAL >> ( mId |
                               portNumber );
        serviceChangeMgcId   = Tokens::MgcIdToken   >> EQUAL >> mId;
        serviceChangeProfile = Tokens::ProfileToken >> EQUAL >> NAME >> '/' >> Version;
        serviceChangeVersion = Tokens::VersionToken >> EQUAL >> Version;
        extension            = extensionParameter >> parmValue;

        packagesDescriptor   = Tokens::PackagesToken
            >> LBRKT >> packagesItem >> *(COMMA >> packagesItem) >> RBRKT;

        packagesItem         = NAME >> "-" >> UINT16;

        TimeStamp            = Date >> "T" >> Time; // per ISO 8601:1988
        // Date = yyyymmdd
        Date                 = repeat(8)[digit];
        // Time = hhmmssss
        Time                 = repeat(8)[digit];
        statisticsDescriptor = Tokens::StatsToken
            >> LBRKT >> statisticsParameter >> *(COMMA >> statisticsParameter ) >> RBRKT;

        //at-most-once per item
        statisticsParameter  = pkgdName >> -(EQUAL >> VALUE);

        topologyDescriptor   = Tokens::TopologyToken
            >> LBRKT >> topologyTriple >> *(COMMA >> topologyTriple) >> RBRKT;
        topologyTriple       = terminationA >> COMMA >>
                               terminationB >> COMMA >> topologyDirection;
        terminationA         = TerminationID.alias();
        terminationB         = TerminationID.alias();
        topologyDirection    = Tokens::BothwayToken | Tokens::IsolateToken | Tokens::OnewayToken;

        priority             = Tokens::PriorityToken >> EQUAL >> UINT16;

        extensionParameter   = "X" >> char_("-+") >> repeat(1,6)[alnum];

        BOOST_SPIRIT_DEBUG_NODES(
            // snipped for Stack Overflow, see Coliru
        )

    }
  private:
    qi::rule<It> megacoMessage, message;
    qi::rule<It, uint32_t()> mtpAddress, ContextID;

    qi::rule<It, std::string()> mId, domainName, deviceName, pathNAME, domainAddress, pathDomainName,
        IPv4address, IPv6address, hexpart, hexseq;
    qi::rule<It, uint16_t()> portNumber;
    qi::rule<It, uint8_t()> V4hex;

    // implicit lexemes (no implicit whitespace allowed):
    qi::rule<It> authenticationHeader;
    qi::uint_parser<int, 10, 1, 2> Version;
    qi::uint_parser<uint32_t, 10, 1, 10> UINT32;
    qi::uint_parser<uint16_t, 10, 1, 5>  UINT16;

    // message payload
    qi::rule<It> messageBody,
        transactionList, transactionPending, transactionResponseAck, transactionAck, transactionRequest,
        actionRequest,
        contextRequest, contextProperties, contextProperty, contextAudit, contextAuditProperties,
        commandRequestList, commandRequest,
        transactionReply,
        actionReplyList, actionReply, commandReply,
        commandReplyList, commandReplys,
        ammRequest, ammParameter, ammsReply,
        subtractRequest,
        auditRequest, auditReply, auditOther,
        terminationAudit,
        contextTerminationAudit,
        auditReturnParameter, auditDescriptor, notifyRequest,
        notifyReply,
        serviceChangeRequest, serviceChangeReply,
        errorDescriptor, ErrorCode, transactionID;

    // OTHER STUFF, DESCRIPTORS
    qi::rule<It>
        terminationIDList,
        TerminationID, mediaDescriptor,
        mediaParm, streamParm,
        streamDescriptor, localControlDescriptor, localParm,
        reservedValueMode, reservedGroupMode,
        streamMode, streamModes,
        propertyParm, parmValue, alternativeValue,
        localDescriptor, remoteDescriptor,
        eventBufferDescriptor, eventSpec, eventSpecParameter, eventBufferControl,
        terminationStateDescriptor, terminationStateParm,
        serviceStates,
        muxDescriptor, MuxType,
        StreamID,
        pkgdName, PackageName,
        ItemID,
        eventsDescriptor, requestedEvent, eventParameter,
        embedWithSig, embedNoSig, embedFirst,
        secondRequestedEvent, secondEventParameter,
        embedSig,
        eventStream, eventOther, eventParameterName, eventDM,
        signalsDescriptor, signalParm, signalRequest, signalList, signalListId, signalListParm, signalName,
        sigParameter, sigStream, sigOther, sigParameterName, sigSignalType, signalType, sigDuration,
        notifyCompletion, notificationReason,
        observedEventsDescriptor, observedEvent, observedEventParameter,
        RequestID,
        modemDescriptor, modemType,
        digitMapDescriptor, digitMapName, digitMapValue,
        Timer,
        digitMap, digitStringList, digitString, digitStringElement, digitPosition, digitMapRange, digitLetter, digitMapLetter,
        auditItem,
        serviceChangeDescriptor, serviceChangeParm, serviceChangeReplyDescriptor,
        servChgReplyParm,
        serviceChangeMethod, serviceChangeReason, serviceChangeDelay, serviceChangeAddress, serviceChangeMgcId, serviceChangeProfile, serviceChangeVersion,
        extension,
        packagesDescriptor,
        packagesItem,
        TimeStamp, Date, Time,
        statisticsDescriptor, statisticsParameter,
        topologyDescriptor, topologyTriple,
        terminationA, terminationB,
        topologyDirection,
        priority,
        extensionParameter;
};

};
int main() {
    std::string const  sample = R"(
!/3 [15.232.33.21]:2134
T=173619123
{
    C=230234621
    {
        PR=9,
        MF=ip/187/6/23045241
        {
            MD=V90
        },
        MF=ip/187/6/23045242
        {
            MD=V90
        }
    }
})";

    using It = std::string::const_iterator;
    Megaco<It>::Parser parser;

    It f = sample.begin(), l = sample.end();
    bool ok = qi::parse(f, l, parser);

    if (ok)
        std::cout << "Parse success\n";
    else
        std::cout << "Parse failed\n";

    if (f != l)
        std::cout << "Remaining unparsed input: '" << std::string(f,l) << "'\n";
}

Prints

Parse success

¹ i.e. mostly dumb transformation of the productions, specifically barely no attribute handling and very heavy (e.g. no symbols<> for the modemtypes etc.)


来源: stackexchange

问:
Populate unbound text filed in MS ACCESS report via tempvars populated from a dlookup function
I'll try my very best to explain what I'm trying to bo. I'm still kinda novice in MS ACCESS and still trying to learn stuff. So what I'm trying to do is to populate the control source of an unbound textbox in Report. If for example I use this code ="
my name is " & [fullname] & ".
", it will work. The [fullname] field will be populated by the value assigned to it. But if I put that same code in a table then use the dlookup function to store the code in tempvars then use the tempvars to populate the unbound textbox, it will not work.

The unbound textbox is set to rich text so it recognizes the  and makes it bold but the value for the [fullname] field is not populated. It will just be returned as: my name is " & [fullname] & ".

Is there a way to do it so ms access will still populate the [fullname] value and not translate it literally?

Thanks,
Darren

答:
I got the answer to this question. It's just easy as targeting the ControlSource. So instead of targeting directly the unbound textbox by Me.Content = ([TempVars]![FirstResponse]). I targeted the ControlSource Me.Content.ControlSource = ([TempVars]![FirstResponse]). This did the work. It acknowledged both the HTML tags and returned the value of the field ex [fullname].

I still thank you ShieldOfSalvation for making me think that there is a way how to do this.

ContentLicense: CC BY-SA 3.0


问:
Add all IPV6 pool /64 addresses to eth0 on Ubuntu
I would like to bind an application to different IPV6 addresses on my network interface. Currently the /64 pool is correctly routed to my server and I can ping all addresses but Applications still can not bind to them even they are added to the config.

For ex I binded the pool using:

```<code>ip route add local 2a01:xx:xx:xx::/64 dev lo
</code>```

But when I run

```<code>ip -6 address list
</code>```

I can not see any of the routed addresses so I add them one by one like

```<code>ip -6 addr add 2a01:xx:xx:xx::1/64 dev eth0
</code>```

I guess that my application can not bind to it. Any clue how can I get around then otherwise will have to create a bash script with a huge loop?

PS. The application is a Golang app I am writing but I also tested with Tinyproxy with BindSame option which still does not work!

答:
The solution is to add the request IP to the current interface within the application logic. Of course this depends on the security measures on the app.

As far as all IPs were correctly routed to the server

```<code>/sbin/ip route add local 2a01:xx:xx:xx::/64 dev lo
</code>```

For ex in my case using Golang

```<code>exec.Command("/sbin/ip", "addr", "add", "2a01:xx:xx:xx::1/64", "dev", "eth0").Output()
</code>```

Body:
I would like to bind an application to different IPV6 addresses on my network interface. Currently the /64 pool is correctly routed to my server and I can ping all addresses but Applications still can not bind to them even they are added to the config.

For ex I binded the pool using:

ip route add local 2a01:xx:xx:xx::/64 dev lo

But when I run

ip -6 address list

I can not see any of the routed addresses so I add them one by one like

ip -6 addr add 2a01:xx:xx:xx::1/64 dev eth0

I guess that my application can not bind to it. Any clue how can I get around then otherwise will have to create a bash script with a huge loop?

PS. The application is a Golang app I am writing but I also tested with Tinyproxy with BindSame option which still does not work!

Body:
The solution is to add the request IP to the current interface within the application logic. Of course this depends on the security measures on the app.

As far as all IPs were correctly routed to the server

/sbin/ip route add local 2a01:xx:xx:xx::/64 dev lo

For ex in my case using Golang

exec.Command("/sbin/ip", "addr", "add", "2a01:xx:xx:xx::1/64", "dev", "eth0").Output()


问:
yii2:- how can i manage angularjs post request in yii2
I am trying to send post request from angular controller to yii front end controller.

Here is my controller.js

```<code> 'use strict';

define(['angular', 'd3', 'd3Cloud', 'services'], function (angular, d3) {
/* Controllers */
return angular.module('oc.controllers', ['oc.services'])
    .controller('InitCtrl', ['$scope','$http', function ($scope,$http) {

          $scope.loginFun = function() {

            var formData = {username:$scope.txtUserName, pwd:$scope.txtPassword};
            $http.post("http://localhost/yii2-angular-seed-master/frontend/web/site/login",formData).success(function(data){
              alert(data);
            });

          }

      $scope.promos=[];
          var requestPromo = $http.get('http://localhost/yii2-angular-seed-master/frontend/web/category/promos');
          requestPromo.success(function( data ) {
            $scope.promos=data;
          });
    }])

    .config(['$httpProvider', function ($httpProvider) {
         $httpProvider.defaults.headers.post['X-CSRF-Token'] = $('meta[name="csrf-token"]').attr("content");
         $httpProvider.defaults.headers.common['Accept'] = 'application/json, text/javascript';
         $httpProvider.defaults.headers.common['Content-Type'] = 'application/json; charset=UTF-8';
    }])

 });
</code>```

This is my yii2 frontend controller.

```<code> use Yii;

 class SiteController extends Controller
 {
     public function behaviors()
     {
          return [
            'access' => [
            'class' => AccessControl::className(),
            'only' => ['logout', 'signup'],
            'rules' => [
                [
                    'actions' => ['signup'],
                    'allow' => true,
                    'roles' => ['?'],
                ],
                [
                    'actions' => ['logout'],
                    'allow' => true,
                    'roles' => ['@'],
                ],
            ],
        ],
        'verbs' => [
            'class' => VerbFilter::className(),
            'actions' => [
                'logout' => ['post'],
            ],
        ],
    ];
}

/**
 * @inheritdoc
 */
public function actions()
{
    return [
        'error' => [
            'class' => 'yii\web\ErrorAction',
        ],
        'captcha' => [
            'class' => 'yii\captcha\CaptchaAction',
            'fixedVerifyCode' => YII_ENV_TEST ? 'testme' : null,
        ],
    ];
}

public function actionIndex()
{
    return $this->render('index');
}

public function actionLogin()
{
// How to handle post request here?
// which code i have to use here?
// My angular get request is successfully work.
// But Post request not work. How can i manage it?
}

public function actionLogout()
{
    Yii::$app->user->logout();

    return $this->goHome();
}

}
</code>```

I am getting this error in Firebug.

POST http://localhost/yii2-angular-seed-master/frontend/web/site/login
400 Bad Request

"NetworkError: 400 Bad Request - http://localhost/yii2-angular-seed-master/frontend/web/site/login"

Please suggest me a code for:

```<code>public function actionLogin()
{
   // How to handle post request here?
  // which code i have to use here?
  // My angular get request is successfully work.
  // But Post request not work. How can i manage it?
}
</code>```

答:
```<code>var app = angular.module("myApp", [],
function($httpProvider) {
  // Use x-www-form-urlencoded Content-Type
  $httpProvider.defaults.headers.common['X-Requested-With'] = 'XMLHttpRequest';
  $httpProvider.defaults.headers.common['X-CSRF-Token'] = $('meta[name="csrf-token"]').attr('content');
  $httpProvider.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded;charset=utf-8';

  /**
   * The workhorse; converts an object to x-www-form-urlencoded serialization.
   * @param {Object} obj
   * @return {String}
   */
  var param = function(obj) {
    var query = '', name, value, fullSubName, subName, subValue, innerObj, i;

    for(name in obj) {
      value = obj[name];

      if(value instanceof Array) {
        for(i=0; i<value.length; ++i) {
          subValue = value[i];
          fullSubName = name + '[' + i + ']';
          innerObj = {};
          innerObj[fullSubName] = subValue;
          query += param(innerObj) + '&';
        }
      }
      else if(value instanceof Object) {
        for(subName in value) {
          subValue = value[subName];
          fullSubName = name + '[' + subName + ']';
          innerObj = {};
          innerObj[fullSubName] = subValue;
          query += param(innerObj) + '&';
        }
      }
      else if(value !== undefined && value !== null)
        query += encodeURIComponent(name) + '=' + encodeURIComponent(value) + '&';
    }

    return query.length ? query.substr(0, query.length - 1) : query;
  };

  // Override $http service's default transformRequest
  $httpProvider.defaults.transformRequest = [function(data) {
    return angular.isObject(data) && String(data) !== '[object File]' ? param(data) : data;
  }];
});
</code>```

Body:
I am trying to send post request from angular controller to yii front end controller.

Here is my controller.js

 'use strict';

define(['angular', 'd3', 'd3Cloud', 'services'], function (angular, d3) {
/* Controllers */
return angular.module('oc.controllers', ['oc.services'])
    .controller('InitCtrl', ['$scope','$http', function ($scope,$http) {

          $scope.loginFun = function() {

            var formData = {username:$scope.txtUserName, pwd:$scope.txtPassword};
            $http.post("http://localhost/yii2-angular-seed-master/frontend/web/site/login",formData).success(function(data){
              alert(data);
            });

          }

      $scope.promos=[];
          var requestPromo = $http.get('http://localhost/yii2-angular-seed-master/frontend/web/category/promos');
          requestPromo.success(function( data ) {
            $scope.promos=data;
          });
    }])

    .config(['$httpProvider', function ($httpProvider) {
         $httpProvider.defaults.headers.post['X-CSRF-Token'] = $('meta[name="csrf-token"]').attr("content");
         $httpProvider.defaults.headers.common['Accept'] = 'application/json, text/javascript';
         $httpProvider.defaults.headers.common['Content-Type'] = 'application/json; charset=UTF-8';
    }])

 });

This is my yii2 frontend controller.

 use Yii;

 class SiteController extends Controller
 {
     public function behaviors()
     {
          return [
            'access' => [
            'class' => AccessControl::className(),
            'only' => ['logout', 'signup'],
            'rules' => [
                [
                    'actions' => ['signup'],
                    'allow' => true,
                    'roles' => ['?'],
                ],
                [
                    'actions' => ['logout'],
                    'allow' => true,
                    'roles' => ['@'],
                ],
            ],
        ],
        'verbs' => [
            'class' => VerbFilter::className(),
            'actions' => [
                'logout' => ['post'],
            ],
        ],
    ];
}

/**
 * @inheritdoc
 */
public function actions()
{
    return [
        'error' => [
            'class' => 'yii\web\ErrorAction',
        ],
        'captcha' => [
            'class' => 'yii\captcha\CaptchaAction',
            'fixedVerifyCode' => YII_ENV_TEST ? 'testme' : null,
        ],
    ];
}

public function actionIndex()
{
    return $this->render('index');
}

public function actionLogin()
{
// How to handle post request here?
// which code i have to use here?
// My angular get request is successfully work.
// But Post request not work. How can i manage it?
}

public function actionLogout()
{
    Yii::$app->user->logout();

    return $this->goHome();
}

}

I am getting this error in Firebug.

POST http://localhost/yii2-angular-seed-master/frontend/web/site/login
400 Bad Request

"NetworkError: 400 Bad Request - http://localhost/yii2-angular-seed-master/frontend/web/site/login"

Please suggest me a code for:

public function actionLogin()
{
   // How to handle post request here?
  // which code i have to use here?
  // My angular get request is successfully work.
  // But Post request not work. How can i manage it?
}


问:
Regex: Disable Symbols
Is there any way to disable all symbols, punctuations, block elements, geometric shapes and dingbats such like these:

✁ ✂ ✃ ✄ ✆ ✇ ✈ ✉ ✌ ✍ ✎ ✏ ✐ ✑ ✒ ✓ ✔ ✕  ⟻ ⟼ ⟽ ⟾ ⟿  ⟻ ⟼ ⟽ ⟾ ⟿ ▚ ▛ ▜ ▝ ▞ ▟

without writing down all of them in the Regular Expression Pattern, while enable all other normal language characters such like chinese, arabic etc.. such like these:

文化中国 الجزيرة نت

?

I'm building a javascript validation function and my real problem is that I can't use:

```<code>[a-zA-Z0-9]
</code>```

Because this ignores a lots of languages too not just the symbols.

答:
This depends on your regex dialect. Unfortunately, probably most existing JavaScript engines don't support Unicode character classes.

In regex engines such as the one in (recent) Perl or .Net, Unicode character classes can be referenced.

\p{L}: any kind of letter from any language.
\p{N}: any number symbol from any language (including, as I recall, the Indian and Arabic and CJK number glyphs).

Because Unicode supports composed and decomposed glyphs, you may run into certain complexities: namely, if only decomposed forms exist, it's possible that you might accidentally exclude some diacritic marks in your matching pattern, and you may need to explicitly allow glyphs of the type Mark. You can mitigate this somewhat by using, if I recall correctly, a string that has been normalized using kC normalization (only for characters that have a composed form). In environments that support Unicode well, there's usually a function that allows you to normalize Unicode strings fairly easily (true in Java and .Net, at least).

Edited to add: If you've started down this path, or have considered it, in order to regain some sanity, you may want to experiment with the Unicode Plugin for XRegExp (which will require you to take a dependency on XRegExp).

ContentLicense: CC BY-SA 2.5

Title: Regex: Disable Symbols

Body:
Is there any way to disable all symbols, punctuations, block elements, geometric shapes and dingbats such like these:

✁ ✂ ✃ ✄ ✆ ✇ ✈ ✉ ✌ ✍ ✎ ✏ ✐ ✑ ✒ ✓ ✔ ✕  ⟻ ⟼ ⟽ ⟾ ⟿  ⟻ ⟼ ⟽ ⟾ ⟿ ▚ ▛ ▜ ▝ ▞ ▟

without writing down all of them in the Regular Expression Pattern, while enable all other normal language characters such like chinese, arabic etc.. such like these:

文化中国 الجزيرة نت

?

I'm building a javascript validation function and my real problem is that I can't use:

[a-zA-Z0-9]

Because this ignores a lots of languages too not just the symbols.


问:
Multiple invocations of a static method
my question is this:

In 3 different classes I have to execute a method that has the same procedures but different values in the parameters.

Is it okay to use a new class that contains a static function and
change the values as each call requires?

How does JVM proceed by having several instances of a static method,
a "tail" of orders is generated?

The question is more in the theoretical sense of how JVM handles memory, what I'm looking for is not only saving lines but memory. I want to say that if by doing this I generate more consumption or it is worse to generate more code in each class although I would write more lines.

If there is a better way, I would appreciate it if you told me.

From already thank you very much.

答:
Your question is pretty difficult to understand without some illustrative code, but to address the two explicit points:

Is it okay to use a new class that contains a static function and change the values as each call requires?

Sure, why not?

How does JVM proceed by having several instances of a static method, a "tail" of orders is generated?

There is no such thing as 'instances of a static method'. Possibly you mean 'invocations'. If so, and if '"tail" of orders' and 'generates a kind of waiting' are intended to mean some kind of sequentialization, the answer is no: concurrent calls proceed in parallel, unless synchronization or a lock is employed.

Title: Multiple invocations of a static method


问:
Call a function inside promise
I'm trying to find a way to call the method pageLoader.fetch twice in this promise. I already tried to separate it in a new promise but I get undefined when I try to get the variable links[0]. How to do this?</p>

```<code>pageLoader
  .fetch(url)
  .then(function(data) {
    links = html.orderdList(data);
  })
  .then(function() {
    return pageLoader.fetch(links[0]);
    //links[0] is undefined in the next line!?
  })
  .then(
    pageLoader
      .fetch(links[0])
      .then(function(innerLinks) {
        calLinks = html.unorderList(innerLinks);
      })
      .then(function() {
        return pageLoader.fetch("http:///example.com");
      })
      .catch(function(error) {
        console.log(error);
      })
  );
</code>```

答:
You're almost there. You have some redundant, then()s, which I've removed. It's not clear why you are calling pageLoader.fetch(links[0]) twice. Does it return different results?

You also look like you are setting some global variable (links & calLinks for example), but it's not clear how you will access them asynchronously.

This should work a little better, but given the above, it may still have issues:

```<code>pageLoader.fetch(url)
.then(function(data) {
  links = html.orderdList(data); // <-- are these global or should you have a var?;
  return pageLoader.fetch(links[0]);
})
.then(function(link) { // <-- did you want to do something with the return from above?
  return pageLoader.fetch(links[0])
})
.then(function(innerLinks) {
    calLinks = html.unorderList(innerLinks); // <-- are these global?;
    return pageLoader.fetch("http:///example.com");
})
.catch(function(error) {
    console.log(error);
})
</code>```

Title: Call a function inside promise

Body:
I'm trying to find a way to call the method pageLoader.fetch twice in this promise. I already tried to separate it in a new promise but I get undefined when I try to get the variable links[0]. How to do this?

pageLoader
  .fetch(url)
  .then(function(data) {
    links = html.orderdList(data);
  })
  .then(function() {
    return pageLoader.fetch(links[0]);
    //links[0] is undefined in the next line!?
  })
  .then(
    pageLoader
      .fetch(links[0])
      .then(function(innerLinks) {
        calLinks = html.unorderList(innerLinks);
      })
      .then(function() {
        return pageLoader.fetch("http:///example.com");
      })
      .catch(function(error) {
        console.log(error);
      })
  );

Body:
You're almost there. You have some redundant, then()s, which I've removed. It's not clear why you are calling pageLoader.fetch(links[0]) twice. Does it return different results?

You also look like you are setting some global variable (links & calLinks for example), but it's not clear how you will access them asynchronously.

This should work a little better, but given the above, it may still have issues:

pageLoader.fetch(url)
.then(function(data) {
  links = html.orderdList(data); // <-- are these global or should you have a var?;
  return pageLoader.fetch(links[0]);
})
.then(function(link) { // <-- did you want to do something with the return from above?
  return pageLoader.fetch(links[0])
})
.then(function(innerLinks) {
    calLinks = html.unorderList(innerLinks); // <-- are these global?;
    return pageLoader.fetch("http:///example.com");
})
.catch(function(error) {
    console.log(error);
})


问:
I want to display the mysql table's contents into gridview
what can  I do when my all database table's name into dropdown list & when i select or click the table name from dropdown list display the whole field into the gridview dynamically..please give me best solution in asp.net.</p>

答:
You can dynamically load the table contents into gridview by putting a select query for the table and then bind that dataset to gridview datasource.

Hope this helps you!!


问:
Can I Add Parameter for Template Type of Template Class
Now I have a template class as base class, declaration as below

```<code>template<class TKey, class TValue>
class BaseKeyValueData
{ ... }
</code>```

Also I declara a element class which targets to replace TKey and TValue in above base class

```<code>class BasicElement
{
    BasicElement() = default;
    BasicElement (const std::string& input) { ... }
}
</code>```

Then I want to create a derive class from BaseKeyValueData, and also replace TKey with BasicElement, but still leave TValue as template argument for derive class. The declaration as below

```<code>template <class T>
class DeriveValueClass() : BaseKeyValueData<BasicElement, T>
{
    DeriveValueClass() : BaseKeyValueData<BasicElement, T>() {}
    ...
}
</code>```

Above code I had implemented and it works. But according new requirement, I want to use a string parameter to initial the BasicElement instance. In above DeriveValueClass class, its default constructor uses BasicElement's default constructor (without parameter). So How can I use a parameter to initial BasicElement in DeriveValueClass constructor. The dummy code as below:

```<code>DeriveValueClass() : BaseKeyValueData<BasicElement(<parameterForBasicElement>), T>() {}
</code>```

Above code is illegal in C++. How can I implement this?

Thanks in advance!

答:
For this question, it really confuses the type declaration and instance initialization. For DeriveValueClass declaration, it just declares the type, not related its constructor. So if want to create the type instance, it should explicit call the type's constructor. In my cpp code, I have explicit create type instance, such as:

```<code>boost::make_shared<TKey>()
</code>```

This is the right place  for considering to use different constructor to initial the instance.

Body:
Now I have a template class as base class, declaration as below

template<class TKey, class TValue>
class BaseKeyValueData
{ ... }

Also I declara a element class which targets to replace TKey and TValue in above base class

class BasicElement
{
    BasicElement() = default;
    BasicElement (const std::string& input) { ... }
}

Then I want to create a derive class from BaseKeyValueData, and also replace TKey with BasicElement, but still leave TValue as template argument for derive class. The declaration as below

template <class T>
class DeriveValueClass() : BaseKeyValueData<BasicElement, T>
{
    DeriveValueClass() : BaseKeyValueData<BasicElement, T>() {}
    ...
}

Above code I had implemented and it works. But according new requirement, I want to use a string parameter to initial the BasicElement instance. In above DeriveValueClass class, its default constructor uses BasicElement's default constructor (without parameter). So How can I use a parameter to initial BasicElement in DeriveValueClass constructor. The dummy code as below:

DeriveValueClass() : BaseKeyValueData<BasicElement(<parameterForBasicElement>), T>() {}

Above code is illegal in C++. How can I implement this?

Thanks in advance!

Body:
For this question, it really confuses the type declaration and instance initialization. For DeriveValueClass declaration, it just declares the type, not related its constructor. So if want to create the type instance, it should explicit call the type's constructor. In my cpp code, I have explicit create type instance, such as:

boost::make_shared<TKey>()

This is the right place  for considering to use different constructor to initial the instance.


问:
tensorflow slim multi-GPU can't work
Currently I use tensorflow slim to train the model from scrach. If I just follow the instruction here https://github.com/tensorflow/models/tree/master/slim#training-a-model-from-scratch, everything is OK.

However, I want to use multi GPU, so I set --num_clones=2 or 4, both of them are not working. The result is that both of them get stuck at global_step/sec: 0. They can't continue. You can see the result image here error result

```<code>DATASET_DIR=/tmp/imagenet
TRAIN_DIR=/tmp/train_logs
python train_image_classifier.py \
--num_clones=4 \
--train_dir=${TRAIN_DIR} \
--dataset_name=imagenet \
--dataset_split_name=train \
--dataset_dir=${DATASET_DIR} \
--model_name=inception_v3
</code>```

Hope someone can help me, thanks in advance. By the way, I use tensorflow 1.1 & python 35 on Ubuntu 16.04. If you need more information, please let me know.

答: Your issue resembles an experience I had after switching from a single-GPU to a multi-GPU configuration using tf-slim. I observed that the parameter server job assumed the name 'localhost', which conflicted with the default job name assigned by model_deploy to my CPU device. I suggest you inspect the device names by following the "Logging Device placement" section of this tensorflow.org article. It explains how to print device names to the console on a per-operation basis. You can then pass the actual job name as an argument to DeployConfig()'s ps_job_name parameter and proceed with training.

Title: tensorflow slim multi-GPU can't work

Body:
Currently I use tensorflow slim to train the model from scrach. If I just follow the instruction here https://github.com/tensorflow/models/tree/master/slim#training-a-model-from-scratch, everything is OK.

However, I want to use multi GPU, so I set --num_clones=2 or 4, both of them are not working. The result is that both of them get stuck at global_step/sec: 0. They can't continue. You can see the result image here error result

DATASET_DIR=/tmp/imagenet
TRAIN_DIR=/tmp/train_logs
python train_image_classifier.py \
--num_clones=4 \
--train_dir=${TRAIN_DIR} \
--dataset_name=imagenet \
--dataset_split_name=train \
--dataset_dir=${DATASET_DIR} \
--model_name=inception_v3

Hope someone can help me, thanks in advance. By the way, I use tensorflow 1.1 & python 35 on Ubuntu 16.04. If you need more information, please let me know.


问:
Using Dagger Multibinding across Gradle modules
Fellow Dagger users...am I trying to do something impossible? Below is a degraph generated Gradle module view of my app.

Imagine my app has a navigation drawer. I want the list items in the drawer to be added based on a collection populated via a multibinding. The contributors to this multibinding are across > 1 Gradle module.
For example, a list item called "Account" is added from the user module, a 2nd item called "Terms & Conditions" is added from the legal module and a "Search" navigation entry is added from the search Gradle module. These modules can be thought of as stand-alone apps that when bundled together form the complete app experience. They are runnable on their own.

The Dagger documentation on this looks like a copy-paste of the Guice but with one big complication. It states;

"Dagger allows you to bind several objects into a collection even when
  the objects are bound in different modules using multibindings. "

...but it means Dagger @Modules, right? Is it possible to populate a multibinding across Gradle modules? I've tried something akin to this and it wasn't what I expected (not all contributions were collected);

Parent app

```<code>@Module
abstract class PluginModule {
  @Multibinds @NavigationContribution abstract Set<NavigationEntry> navigables();
}
</code>```

legal Gradle module that contains the Dagger @Module

```<code>@Module
class LegalModule {
  @Provides
  @NavigationContribution
  @IntoSet
  static NavigationEntry provideLegalNavigation() {
    return ...;
  }
}
</code>```

user Gradle module that contains the Dagger @Module

```<code>@Module
class AccountModule {
  @Provides
  @NavigationContribution
  @IntoSet
  static NavigationEntry provideAccountNavigation() {
    return ...;
  }
}
</code>```

Upon running the app only the contributions under the app 'context' are available upon calling;

```<code>@Inject @NavigationContribution Set<NavigationEntry> navigationEntries();
</code>```

The other contributions can be accessed but 'manually' by getting hold of the dagger.Component of the child Gradle module and exposing a method to get the entries back.

This defeats the purpose of the multibinder for my application. Is this possible? If not, why?

Update: triage with Jeff

So, the top-level module annotations look like this;

```<code>@ApplicationLifecycle
@Component(
    modules = {
        OceanLifeModule.class,
        AddSpotActivityModule.class,
        ModelModule.class,
        PluginModule.class
    },
    dependencies = {
        NavigationComponent.class,
        LegalComponent.class,
        PreferenceComponent.class,
        DomainComponent.class
    }
)
</code>```

答: @jeff-bowman - all I was missing here was the includes = {} on the PluginModule. A blog post by Zac Sweers on the same topic here pointed me in the right direction.

Body:
Fellow Dagger users...am I trying to do something impossible? Below is a degraph generated Gradle module view of my app.

Imagine my app has a navigation drawer. I want the list items in the drawer to be added based on a collection populated via a multibinding. The contributors to this multibinding are across > 1 Gradle module.
For example, a list item called "Account" is added from the user module, a 2nd item called "Terms & Conditions" is added from the legal module and a "Search" navigation entry is added from the search Gradle module. These modules can be thought of as stand-alone apps that when bundled together form the complete app experience. They are runnable on their own.

The Dagger documentation on this looks like a copy-paste of the Guice but with one big complication. It states;

"Dagger allows you to bind several objects into a collection even when
  the objects are bound in different modules using multibindings. "

...but it means Dagger @Modules, right? Is it possible to populate a multibinding across Gradle modules? I've tried something akin to this and it wasn't what I expected (not all contributions were collected);

Parent app

@Module
abstract class PluginModule {
  @Multibinds @NavigationContribution abstract Set<NavigationEntry> navigables();
}

legal Gradle module that contains the Dagger @Module

@Module
class LegalModule {
  @Provides
  @NavigationContribution
  @IntoSet
  static NavigationEntry provideLegalNavigation() {
    return ...;
  }
}

user Gradle module that contains the Dagger @Module

@Module
class AccountModule {
  @Provides
  @NavigationContribution
  @IntoSet
  static NavigationEntry provideAccountNavigation() {
    return ...;
  }
}

Upon running the app only the contributions under the app 'context' are available upon calling;

@Inject @NavigationContribution Set<NavigationEntry> navigationEntries();

The other contributions can be accessed but 'manually' by getting hold of the dagger.Component of the child Gradle module and exposing a method to get the entries back.

This defeats the purpose of the multibinder for my application. Is this possible? If not, why?

Update: triage with Jeff

So, the top-level module annotations look like this;

@ApplicationLifecycle
@Component(
    modules = {
        OceanLifeModule.class,
        AddSpotActivityModule.class,
        ModelModule.class,
        PluginModule.class
    },
    dependencies = {
        NavigationComponent.class,
        LegalComponent.class,
        PreferenceComponent.class,
        DomainComponent.class
    }
)

ContentLicense: CC BY-SA 4.0