text:
/**
 * @file
 * @brief
 *  This file defines the OpenThread Thread API (for both FTD and MTD).
 */

#ifndef OPENTHREAD_THREAD_H_
#define OPENTHREAD_THREAD_H_

#include <openthread/dataset.h>
#include <openthread/link.h>
#include <openthread/message.h>

#ifdef __cplusplus
extern "C" {
#endif

/**
 * @addtogroup api-thread-general
 *
 * @{
 *
 */

/**
 * Maximum Number of Network Diagnostic TLV Types to Request or Reset.
 */
#define OT_NETWORK_DIAGNOSTIC_TYPELIST_MAX_ENTRIES 19

/**
 * Represents a Thread device role.
 *
 */
typedef enum {
    OT_DEVICE_ROLE_DISABLED = 0, ///< The Thread stack is disabled.
    OT_DEVICE_ROLE_DETACHED = 1, ///< Not currently participating in a Thread network/partition.
    OT_DEVICE_ROLE_CHILD    = 2, ///< The Thread Child role.
    OT_DEVICE_ROLE_ROUTER   = 3, ///< The Thread Router role.
    OT_DEVICE_ROLE_LEADER   = 4, ///< The Thread Leader role.
} otDeviceRole;

/**
 * This structure represents an MLE Link Mode configuration.
 */
OT_TOOL_ALIGN(4)
typedef struct otLinkModeConfig
{
    bool mRxOnWhenIdle : 1;       ///< 1, if the sender has its receiver on when not transmitting. 0, otherwise.
    bool mSecureDataRequests : 1; ///< 1, if the sender uses IEEE 802.15.4 to secure all data requests. 0, otherwise.
    bool mDeviceType : 1;         ///< 1, if the sender is an FTD. 0, otherwise.
    bool mNetworkData : 1;        ///< 1, if the sender requires the full Network Data. 0, otherwise.
} otLinkModeConfig;

/**
 * This structure holds diagnostic information for a neighboring Thread node
 *
 * `mFrameErrorRate` and `mMessageErrorRate` require `OPENTHREAD_CONFIG_ENABLE_TX_ERROR_RATE_TRACKING` feature to be
 * enabled.
 *
 */
typedef struct
{
    otExtAddress mExtAddress;            ///< IEEE 802.15.4 Extended Address
    uint32_t     mAge;                   ///< Time last heard
    uint16_t     mRloc16;                ///< RLOC16
    uint32_t     mLinkFrameCounter;      ///< Link Frame Counter
    uint32_t     mMleFrameCounter;       ///< MLE Frame Counter
    uint8_t      mLinkQualityIn;         ///< Link Quality In
    int8_t       mAverageRssi;           ///< Average RSSI
    int8_t       mLastRssi;              ///< Last observed RSSI
    uint16_t     mFrameErrorRate;        ///< Frame error rate (0xffff->100%). Requires error tracking feature.
    uint16_t     mMessageErrorRate;      ///< (IPv6) msg error rate (0xffff->100%). Requires error tracking feature.
    bool         mRxOnWhenIdle : 1;      ///< rx-on-when-idle
    bool         mSecureDataRequest : 1; ///< Secure Data Requests
    bool         mFullThreadDevice : 1;  ///< Full Thread Device
    bool         mFullNetworkData : 1;   ///< Full Network Data
    bool         mIsChild : 1;           ///< Is the neighbor a child
} otNeighborInfo;

#define OT_NEIGHBOR_INFO_ITERATOR_INIT 0 ///< Initializer for otNeighborInfoIterator.

typedef int16_t otNeighborInfoIterator; ///< Used to iterate through neighbor table.

/**
 * This structure represents the Thread Leader Data.
 *
 */
typedef struct otLeaderData
{
    uint32_t mPartitionId;       ///< Partition ID
    uint8_t  mWeighting;         ///< Leader Weight
    uint8_t  mDataVersion;       ///< Full Network Data Version
    uint8_t  mStableDataVersion; ///< Stable Network Data Version
    uint8_t  mLeaderRouterId;    ///< Leader Router ID
} otLeaderData;

/**
 * This structure holds diagnostic information for a Thread Router
 *
 */
OT_TOOL_ALIGN(4)
typedef struct
{
    otExtAddress mExtAddress;          ///< IEEE 802.15.4 Extended Address
    uint16_t     mRloc16;              ///< RLOC16
    uint8_t      mRouterId;            ///< Router ID
    uint8_t      mNextHop;             ///< Next hop to router
    uint8_t      mPathCost;            ///< Path cost to router
    uint8_t      mLinkQualityIn;       ///< Link Quality In
    uint8_t      mLinkQualityOut;      ///< Link Quality Out
    uint8_t      mAge;                 ///< Time last heard
    bool         mAllocated : 1;       ///< Router ID allocated or not
    bool         mLinkEstablished : 1; ///< Link established with Router ID or not
} otRouterInfo;

/**
 * This structure represents the IP level counters.
 *
 */
typedef struct otIpCounters
{
    uint32_t mTxSuccess; ///< The number of IPv6 packets successfully transmitted.
    uint32_t mRxSuccess; ///< The number of IPv6 packets successfully received.
    uint32_t mTxFailure; ///< The number of IPv6 packets failed to transmit.
    uint32_t mRxFailure; ///< The number of IPv6 packets failed to receive.
} otIpCounters;

/**
 * This structure represents the Thread MLE counters.
 *
 */
typedef struct otMleCounters
{
    uint16_t mDisabledRole;                  ///< Number of times device entered OT_DEVICE_ROLE_DISABLED role.
    uint16_t mDetachedRole;                  ///< Number of times device entered OT_DEVICE_ROLE_DETACHED role.
    uint16_t mChildRole;                     ///< Number of times device entered OT_DEVICE_ROLE_CHILD role.
    uint16_t mRouterRole;                    ///< Number of times device entered OT_DEVICE_ROLE_ROUTER role.
    uint16_t mLeaderRole;                    ///< Number of times device entered OT_DEVICE_ROLE_LEADER role.
    uint16_t mAttachAttempts;                ///< Number of attach attempts while device was detached.
    uint16_t mParitionIdChanges;             ///< Number of changes to partition ID.
    uint16_t mBetterPartitionAttachAttempts; ///< Number of attempts to attach to a better partition.

    /**
     * Number of times device changed its parents.
     *
     * Support for this counter requires the feature option OPENTHREAD_CONFIG_INFORM_PREVIOUS_PARENT_ON_REATTACH to be
     * enabled.
     *
     * A parent change can happen if device detaches from its current parent and attaches to a different one, or even
     * while device is attached when the periodic parent search feature is enabled  (please see option
     * OPENTHREAD_CONFIG_ENABLE_PERIODIC_PARENT_SEARCH).
     *
     */
    uint16_t mParentChanges;
} otMleCounters;

/**
 * This structure represents the MLE Parent Response data.
 *
 */
typedef struct otThreadParentResponseInfo
{
    otExtAddress mExtAddr;      ///< IEEE 802.15.4 Extended Address of the Parent
    uint16_t     mRloc16;       ///< Short address of the Parent
    int8_t       mRssi;         ///< Rssi of the Parent
    int8_t       mPriority;     ///< Parent priority
    uint8_t      mLinkQuality3; ///< Parent Link Quality 3
    uint8_t      mLinkQuality2; ///< Parent Link Quality 2
    uint8_t      mLinkQuality1; ///< Parent Link Quality 1
    bool         mIsAttached;   ///< Is the node receiving parent response attached
} otThreadParentResponseInfo;

/**
 * This function starts Thread protocol operation.
 *
 * The interface must be up when calling this function.
 *
 * @param[in] aInstance A pointer to an OpenThread instance.
 * @param[in] aEnabled  TRUE if Thread is enabled, FALSE otherwise.
 *
 * @retval OT_ERROR_NONE           Successfully started Thread protocol operation.
 * @retval OT_ERROR_INVALID_STATE  The network interface was not not up.
 *
 */
OTAPI otError OTCALL otThreadSetEnabled(otInstance *aInstance, bool aEnabled);

/**
 * This function queries if the Thread stack is configured to automatically start on reinitialization.
 *
 * @param[in] aInstance A pointer to an OpenThread instance.
 *
 * @retval TRUE   It is configured to automatically start.
 * @retval FALSE  It is not configured to automatically start.
 *
 */
OTAPI bool OTCALL otThreadGetAutoStart(otInstance *aInstance);

/**
 * This function configures the Thread stack to automatically start on reinitialization.
 * It has no effect on the current Thread state.
 *
 * @param[in] aInstance             A pointer to an OpenThread instance.
 * @param[in] aStartAutomatically   TRUE to automatically start; FALSE to not automatically start.
 *
 */
OTAPI otError OTCALL otThreadSetAutoStart(otInstance *aInstance, bool aStartAutomatically);

/**
 * This function indicates whether a node is the only router on the network.
 *
 * @param[in] aInstance A pointer to an OpenThread instance.
 *
 * @retval TRUE   It is the only router in the network.
 * @retval FALSE  It is a child or is not a single router in the network.
 *
 */
OTAPI bool OTCALL otThreadIsSingleton(otInstance *aInstance);

/**
 * This function starts a Thread Discovery scan.
 *
 * @param[in]  aInstance              A pointer to an OpenThread instance.
 * @param[in]  aScanChannels          A bit vector indicating which channels to scan (e.g. OT_CHANNEL_11_MASK).
 * @param[in]  aPanId                 The PAN ID filter (set to Broadcast PAN to disable filter).
 * @param[in]  aJoiner                Value of the Joiner Flag in the Discovery Request TLV.
 * @param[in]  aEnableEui64Filtering  TRUE to filter responses on EUI-64, FALSE otherwise.
 * @param[in]  aCallback              A pointer to a function called on receiving an MLE Discovery Response or
 *                                    scan completes.
 * @param[in]  aCallbackContext       A pointer to application-specific context.
 *
 * @retval OT_ERROR_NONE  Accepted the Thread Discovery request.
 * @retval OT_ERROR_BUSY  Already performing an Thread Discovery.
 *
 */
OTAPI otError OTCALL otThreadDiscover(otInstance *             aInstance,
                                      uint32_t                 aScanChannels,
                                      uint16_t                 aPanId,
                                      bool                     aJoiner,
                                      bool                     aEnableEui64Filtering,
                                      otHandleActiveScanResult aCallback,
                                      void *                   aCallbackContext);

/**
 * This function determines if an MLE Thread Discovery is currently in progress.
 *
 * @param[in] aInstance A pointer to an OpenThread instance.
 *
 */
OTAPI bool OTCALL otThreadIsDiscoverInProgress(otInstance *aInstance);

/**
 * Get the Thread Child Timeout used when operating in the Child role.
 *
 * @param[in]  aInstance A pointer to an OpenThread instance.
 *
 * @returns The Thread Child Timeout value in seconds.
 *
 * @sa otThreadSetChildTimeout
 */
OTAPI uint32_t OTCALL otThreadGetChildTimeout(otInstance *aInstance);

/**
 * Set the Thread Child Timeout used when operating in the Child role.
 *
 * @param[in]  aInstance A pointer to an OpenThread instance.
 * @param[in]  aTimeout  The timeout value in seconds.
 *
 * @sa otThreadSetChildTimeout
 *
 */
OTAPI void OTCALL otThreadSetChildTimeout(otInstance *aInstance, uint32_t aTimeout);

/**
 * Get the IEEE 802.15.4 Extended PAN ID.
 *
 * @param[in]  aInstance A pointer to an OpenThread instance.
 *
 * @returns A pointer to the IEEE 802.15.4 Extended PAN ID.
 *
 * @sa otThreadSetExtendedPanId
 */
OTAPI const otExtendedPanId *OTCALL otThreadGetExtendedPanId(otInstance *aInstance);

/**
 * Set the IEEE 802.15.4 Extended PAN ID.
 *
 * This function can only be called while Thread protocols are disabled.  A successful
 * call to this function invalidates the Active and Pending Operational Datasets in
 * non-volatile memory.
 *
 * @param[in]  aInstance       A pointer to an OpenThread instance.
 * @param[in]  aExtendedPanId  A pointer to the IEEE 802.15.4 Extended PAN ID.
 *
 * @retval OT_ERROR_NONE           Successfully set the Extended PAN ID.
 * @retval OT_ERROR_INVALID_STATE  Thread protocols are enabled.
 *
 * @sa otThreadGetExtendedPanId
 */
OTAPI otError OTCALL otThreadSetExtendedPanId(otInstance *aInstance, const otExtendedPanId *aExtendedPanId);

/**
 * This function returns a pointer to the Leader's RLOC.
 *
 * @param[in]   aInstance    A pointer to an OpenThread instance.
 * @param[out]  aLeaderRloc  A pointer to the Leader's RLOC.
 *
 * @retval OT_ERROR_NONE          The Leader's RLOC was successfully written to @p aLeaderRloc.
 * @retval OT_ERROR_INVALID_ARGS  @p aLeaderRloc was NULL.
 * @retval OT_ERROR_DETACHED      Not currently attached to a Thread Partition.
 *
 */
OTAPI otError OTCALL otThreadGetLeaderRloc(otInstance *aInstance, otIp6Address *aLeaderRloc);

/**
 * Get the MLE Link Mode configuration.
 *
 * @param[in]  aInstance A pointer to an OpenThread instance.
 *
 * @returns The MLE Link Mode configuration.
 *
 * @sa otThreadSetLinkMode
 */
OTAPI otLinkModeConfig OTCALL otThreadGetLinkMode(otInstance *aInstance);

/**
 * Set the MLE Link Mode configuration.
 *
 * @param[in]  aInstance A pointer to an OpenThread instance.
 * @param[in]  aConfig   A pointer to the Link Mode configuration.
 *
 * @retval OT_ERROR_NONE  Successfully set the MLE Link Mode configuration.
 *
 * @sa otThreadGetLinkMode
 */
OTAPI otError OTCALL otThreadSetLinkMode(otInstance *aInstance, otLinkModeConfig aConfig);

/**
 * Get the thrMasterKey.
 *
 * @param[in]   aInstance   A pointer to an OpenThread instance.
 *
 * @returns A pointer to a buffer containing the thrMasterKey.
 *
 * @sa otThreadSetMasterKey
 */
OTAPI const otMasterKey *OTCALL otThreadGetMasterKey(otInstance *aInstance);

/**
 * Set the thrMasterKey.
 *
 * This function succeeds only when Thread protocols are disabled.  A successful
 * call to this function invalidates the Active and Pending Operational Datasets in
 * non-volatile memory.
 *
 * @param[in]  aInstance   A pointer to an OpenThread instance.
 * @param[in]  aKey        A pointer to a buffer containing the thrMasterKey.
 *
 * @retval OT_ERROR_NONE            Successfully set the thrMasterKey.
 * @retval OT_ERROR_INVALID_ARGS    If aKeyLength is larger than 16.
 * @retval OT_ERROR_INVALID_STATE   Thread protocols are enabled.
 *
 * @sa otThreadGetMasterKey
 */
OTAPI otError OTCALL otThreadSetMasterKey(otInstance *aInstance, const otMasterKey *aKey);

/**
 * This function returns a pointer to the Mesh Local EID.
 *
 * @param[in]  aInstance A pointer to an OpenThread instance.
 *
 * @returns A pointer to the Mesh Local EID.
 *
 */
OTAPI const otIp6Address *OTCALL otThreadGetMeshLocalEid(otInstance *aInstance);

/**
 * This function returns a pointer to the Mesh Local Prefix.
 *
 * @param[in]  aInstance A pointer to an OpenThread instance.
 *
 * @returns A pointer to the Mesh Local Prefix.
 *
 */
OTAPI const otMeshLocalPrefix *OTCALL otThreadGetMeshLocalPrefix(otInstance *aInstance);

/**
 * This function sets the Mesh Local Prefix.
 *
 * This function succeeds only when Thread protocols are disabled.  A successful
 * call to this function invalidates the Active and Pending Operational Datasets in
 * non-volatile memory.
 *
 * @param[in]  aInstance         A pointer to an OpenThread instance.
 * @param[in]  aMeshLocalPrefix  A pointer to the Mesh Local Prefix.
 *
 * @retval OT_ERROR_NONE           Successfully set the Mesh Local Prefix.
 * @retval OT_ERROR_INVALID_STATE  Thread protocols are enabled.
 *
 */
OTAPI otError OTCALL otThreadSetMeshLocalPrefix(otInstance *aInstance, const otMeshLocalPrefix *aMeshLocalPrefix);

/**
 * This function returns the Thread link-local IPv6 address.
 *
 * The Thread link local address is derived using IEEE802.15.4 Extended Address as Interface Identifier.
 *
 * @param[in]  aInstance A pointer to an OpenThread instance.
 *
 * @returns A pointer to Thread link-local IPv6 address.
 *
 */
const otIp6Address *otThreadGetLinkLocalIp6Address(otInstance *aInstance);

/**
 * Get the Thread Network Name.
 *
 * @param[in]  aInstance A pointer to an OpenThread instance.
 *
 * @returns A pointer to the Thread Network Name.
 *
 * @sa otThreadSetNetworkName
 *
 */
OTAPI const char *OTCALL otThreadGetNetworkName(otInstance *aInstance);

/**
 * Set the Thread Network Name.
 *
 * This function succeeds only when Thread protocols are disabled.  A successful
 * call to this function invalidates the Active and Pending Operational Datasets in
 * non-volatile memory.
 *
 * @param[in]  aInstance     A pointer to an OpenThread instance.
 * @param[in]  aNetworkName  A pointer to the Thread Network Name.
 *
 * @retval OT_ERROR_NONE           Successfully set the Thread Network Name.
 * @retval OT_ERROR_INVALID_STATE  Thread protocols are enabled.
 *
 * @sa otThreadGetNetworkName
 *
 */
OTAPI otError OTCALL otThreadSetNetworkName(otInstance *aInstance, const char *aNetworkName);

/**
 * Get the thrKeySequenceCounter.
 *
 * @param[in]  aInstance A pointer to an OpenThread instance.
 *
 * @returns The thrKeySequenceCounter value.
 *
 * @sa otThreadSetKeySequenceCounter
 *
 */
OTAPI uint32_t OTCALL otThreadGetKeySequenceCounter(otInstance *aInstance);

/**
 * Set the thrKeySequenceCounter.
 *
 * @param[in]  aInstance            A pointer to an OpenThread instance.
 * @param[in]  aKeySequenceCounter  The thrKeySequenceCounter value.
 *
 * @sa otThreadGetKeySequenceCounter
 *
 */
OTAPI void OTCALL otThreadSetKeySequenceCounter(otInstance *aInstance, uint32_t aKeySequenceCounter);

/**
 * Get the thrKeySwitchGuardTime
 *
 * @param[in]  aInstance A pointer to an OpenThread instance.
 *
 * @returns The thrKeySwitchGuardTime value (in hours).
 *
 * @sa otThreadSetKeySwitchGuardTime
 *
 */
OTAPI uint32_t OTCALL otThreadGetKeySwitchGuardTime(otInstance *aInstance);

/**
 * Set the thrKeySwitchGuardTime
 *
 * @param[in]  aInstance            A pointer to an OpenThread instance.
 * @param[in]  aKeySwitchGuardTime  The thrKeySwitchGuardTime value (in hours).
 *
 * @sa otThreadGetKeySwitchGuardTime
 *
 */
OTAPI void OTCALL otThreadSetKeySwitchGuardTime(otInstance *aInstance, uint32_t aKeySwitchGuardTime);

/**
 * Detach from the Thread network.
 *
 * @param[in]  aInstance A pointer to an OpenThread instance.
 *
 * @retval OT_ERROR_NONE           Successfully detached from the Thread network.
 * @retval OT_ERROR_INVALID_STATE  Thread is disabled.
 *
 */
OTAPI otError OTCALL otThreadBecomeDetached(otInstance *aInstance);

/**
 * Attempt to reattach as a child.
 *
 * @param[in]  aInstance A pointer to an OpenThread instance.
 *
 * @retval OT_ERROR_NONE           Successfully begin attempt to become a child.
 * @retval OT_ERROR_INVALID_STATE  Thread is disabled.
 *
 */
OTAPI otError OTCALL otThreadBecomeChild(otInstance *aInstance);

/**
 * This function gets the next neighbor information. It is used to go through the entries of
 * the neighbor table.
 *
 * @param[in]     aInstance  A pointer to an OpenThread instance.
 * @param[inout]  aIterator  A pointer to the iterator context. To get the first neighbor entry
                             it should be set to OT_NEIGHBOR_INFO_ITERATOR_INIT.
 * @param[out]    aInfo      A pointer to the neighbor information.
 *
 * @retval OT_ERROR_NONE         Successfully found the next neighbor entry in table.
 * @retval OT_ERROR_NOT_FOUND     No subsequent neighbor entry exists in the table.
 * @retval OT_ERROR_INVALID_ARGS  @p aIterator or @p aInfo was NULL.
 *
 */
OTAPI otError OTCALL otThreadGetNextNeighborInfo(otInstance *            aInstance,
                                                 otNeighborInfoIterator *aIterator,
                                                 otNeighborInfo *        aInfo);

/**
 * Get the device role.
 *
 * @param[in]  aInstance A pointer to an OpenThread instance.
 *
 * @retval OT_DEVICE_ROLE_DISABLED  The Thread stack is disabled.
 * @retval OT_DEVICE_ROLE_DETACHED  The device is not currently participating in a Thread network/partition.
 * @retval OT_DEVICE_ROLE_CHILD     The device is currently operating as a Thread Child.
 * @retval OT_DEVICE_ROLE_ROUTER    The device is currently operating as a Thread Router.
 * @retval OT_DEVICE_ROLE_LEADER    The device is currently operating as a Thread Leader.
 *
 */
OTAPI otDeviceRole OTCALL otThreadGetDeviceRole(otInstance *aInstance);

/**
 * This function get the Thread Leader Data.
 *
 * @param[in]   aInstance    A pointer to an OpenThread instance.
 * @param[out]  aLeaderData  A pointer to where the leader data is placed.
 *
 * @retval OT_ERROR_NONE          Successfully retrieved the leader data.
 * @retval OT_ERROR_DETACHED      Not currently attached.
 * @retval OT_ERROR_INVALID_ARGS  @p aLeaderData is NULL.
 *
 */
OTAPI otError OTCALL otThreadGetLeaderData(otInstance *aInstance, otLeaderData *aLeaderData);

/**
 * Get the Leader's Router ID.
 *
 * @param[in]  aInstance A pointer to an OpenThread instance.
 *
 * @returns The Leader's Router ID.
 *
 */
OTAPI uint8_t OTCALL otThreadGetLeaderRouterId(otInstance *aInstance);

/**
 * Get the Leader's Weight.
 *
 * @param[in]  aInstance A pointer to an OpenThread instance.
 *
 * @returns The Leader's Weight.
 *
 */
OTAPI uint8_t OTCALL otThreadGetLeaderWeight(otInstance *aInstance);

/**
 * Get the Partition ID.
 *
 * @param[in]  aInstance A pointer to an OpenThread instance.
 *
 * @returns The Partition ID.
 *
 */
OTAPI uint32_t OTCALL otThreadGetPartitionId(otInstance *aInstance);

/**
 * Get the RLOC16.
 *
 * @param[in]  aInstance A pointer to an OpenThread instance.
 *
 * @returns The RLOC16.
 *
 */
OTAPI uint16_t OTCALL otThreadGetRloc16(otInstance *aInstance);

/**
 * The function retrieves diagnostic information for a Thread Router as parent.
 *
 * @param[in]   aInstance    A pointer to an OpenThread instance.
 * @param[out]  aParentInfo  A pointer to where the parent router information is placed.
 *
 */
OTAPI otError OTCALL otThreadGetParentInfo(otInstance *aInstance, otRouterInfo *aParentInfo);

/**
 * The function retrieves the average RSSI for the Thread Parent.
 *
 * @param[in]   aInstance    A pointer to an OpenThread instance.
 * @param[out]  aParentRssi  A pointer to where the parent RSSI should be placed.
 *
 */
OTAPI otError OTCALL otThreadGetParentAverageRssi(otInstance *aInstance, int8_t *aParentRssi);

/**
 * The function retrieves the RSSI of the last packet from the Thread Parent.
 *
 * @param[in]   aInstance    A pointer to an OpenThread instance.
 * @param[out]  aLastRssi    A pointer to where the last RSSI should be placed.
 *
 * @retval OT_ERROR_NONE          Successfully retrieved the RSSI data.
 * @retval OT_ERROR_FAILED        Unable to get RSSI data.
 * @retval OT_ERROR_INVALID_ARGS  @p aLastRssi is NULL.
 *
 */
OTAPI otError OTCALL otThreadGetParentLastRssi(otInstance *aInstance, int8_t *aLastRssi);

/**
 * This function pointer is called when Network Diagnostic Get response is received.
 *
 * @param[in]  aMessage      A pointer to the message buffer containing the received Network Diagnostic
 *                           Get response payload.
 * @param[in]  aMessageInfo  A pointer to the message info for @p aMessage.
 * @param[in]  aContext      A pointer to application-specific context.
 *
 */
typedef void (*otReceiveDiagnosticGetCallback)(otMessage *aMessage, const otMessageInfo *aMessageInfo, void *aContext);

/**
 * This function registers a callback to provide received raw Network Diagnostic Get response payload.
 *
 * @param[in]  aInstance         A pointer to an OpenThread instance.
 * @param[in]  aCallback         A pointer to a function that is called when Network Diagnostic Get response
 *                               is received or NULL to disable the callback.
 * @param[in]  aCallbackContext  A pointer to application-specific context.
 *
 */
void otThreadSetReceiveDiagnosticGetCallback(otInstance *                   aInstance,
                                             otReceiveDiagnosticGetCallback aCallback,
                                             void *                         aCallbackContext);

/**
 * Send a Network Diagnostic Get request.
 *
 * @param[in]  aInstance      A pointer to an OpenThread instance.
 * @param[in]  aDestination   A pointer to destination address.
 * @param[in]  aTlvTypes      An array of Network Diagnostic TLV types.
 * @param[in]  aCount         Number of types in aTlvTypes
 *
 */
OTAPI otError OTCALL otThreadSendDiagnosticGet(otInstance *        aInstance,
                                               const otIp6Address *aDestination,
                                               const uint8_t       aTlvTypes[],
                                               uint8_t             aCount);

/**
 * Send a Network Diagnostic Reset request.
 *
 * @param[in]  aInstance      A pointer to an OpenThread instance.
 * @param[in]  aDestination   A pointer to destination address.
 * @param[in]  aTlvTypes      An array of Network Diagnostic TLV types. Currently only Type 9 is allowed.
 * @param[in]  aCount         Number of types in aTlvTypes
 *
 */
OTAPI otError OTCALL otThreadSendDiagnosticReset(otInstance *        aInstance,
                                                 const otIp6Address *aDestination,
                                                 const uint8_t       aTlvTypes[],
                                                 uint8_t             aCount);

/**
 * Get the IPv6 counters.
 *
 * @param[in]  aInstance  A pointer to an OpenThread instance.
 *
 * @returns A pointer to the IPv6 counters.
 *
 */
OTAPI const otIpCounters *OTCALL otThreadGetIp6Counters(otInstance *aInstance);

/**
 * Get the Thread MLE counters.
 *
 * @param[in]  aInstance  A pointer to an OpenThread instance.
 *
 * @returns A pointer to the Thread MLE counters.
 *
 */
const otMleCounters *otThreadGetMleCounters(otInstance *aInstance);

/**
 * Reset the Thread MLE counters.
 *
 * @param[in]  aInstance  A pointer to an OpenThread instance.
 *
 */
void otThreadResetMleCounters(otInstance *aInstance);

/**
 * This function pointer is called every time an MLE Parent Response message is received.
 *
 * @param[in]  aStats    pointer to a location on stack holding the stats data.
 * @param[in]  aContext  A pointer to callback client-specific context.
 *
 */
typedef void(OTCALL *otThreadParentResponseCallback)(otThreadParentResponseInfo *aInfo, void *aContext);

/**
 * This function registers a callback to receive MLE Parent Response data.
 *
 * @param[in]  aInstance  A pointer to an OpenThread instance.
 * @param[in]  aCallback  A pointer to a function that is called upon receiving an MLE Parent Response message.
 * @param[in]  aContext   A pointer to callback client-specific context.
 *
 * @retval OT_ERROR_NONE              On successful registration
 * @retval OT_ERROR_DISABLED_FEATURE  If the feature is not supported
 *
 */
OTAPI otError OTCALL otThreadRegisterParentResponseCallback(otInstance *                   aInstance,
                                                            otThreadParentResponseCallback aCallback,
                                                            void *                         aContext);

/**
 * @}
 *
 */

#ifdef __cplusplus
} // extern "C"
#endif

#endif // OPENTHREAD_THREAD_H_


text:
You can add an `EventListener` to upload the analysis result to a server of your choosing:

```kotlin
class DebugExampleApplication : ExampleApplication() {

  override fun onCreate() {
    super.onCreate()
    val analysisUploadListener = EventListener { event ->
      if (event is HeapAnalysisSucceeded) {
        val heapAnalysis = event.heapAnalysis
        TODO("Upload heap analysis to server")
      }
    }

    LeakCanary.config = LeakCanary.config.run {
      copy(eventListeners = eventListeners + analysisUploadListener)
    }
  }
}
```

## Uploading to Bugsnag

A leak trace has a lot in common with a stack trace, so if you lack the engineering resources to
build a backend for LeakCanary, you can instead upload leak traces to a crash reporting backend.
The client needs to support grouping via custom client-side hashing as well as custom metadata with
support for newlines.

!!! info
    As of this writing, the only known library suitable for uploading leaks is the Bugsnag client.
    If you managed to make it work with another library, please [file an issue](https://github.com/square/leakcanary/issues/new/choose).

Create a [Bugsnag account](https://app.bugsnag.com/user/new/), create a new project for leak
reporting and grab an **API key**. Make sure the app has the `android.permission.INTERNET`
permission then add the [latest version](https://docs.bugsnag.com/platforms/android/) of the
Bugsnag Android client library to `build.gradle`:

```groovy
dependencies {
  // debugImplementation because LeakCanary should only run in debug builds.
  debugImplementation 'com.squareup.leakcanary:leakcanary-android:{{ leak_canary.release }}'
  debugImplementation "com.bugsnag:bugsnag-android:$bugsnagVersion"
}
```

!!! info
    If you're only using Bugsnag for uploading leaks, then you do not need to set up the Bugsnag
    Gradle plugin or to configure the API key in your app manifest.

Create a new `BugsnagLeakUploader`:

--8<-- "docs/snippets/bugsnag-uploader.md"

Then add an `EventListener` to upload the analysis result to Bugsnag:

```kotlin
class DebugExampleApplication : ExampleApplication() {

  override fun onCreate() {
    super.onCreate()
    LeakCanary.config = LeakCanary.config.copy(
        onHeapAnalyzedListener = BugsnagLeakUploader(applicationContext = this)
    )
  }
}
```

You should start seeing leaks reported into Bugsnag, grouped by their leak signature:

![list](images/bugsnag-list.png)

The `LEAK` tab contains the leak trace:

![leak](images/bugsnag-leak.png)

redpajama_set_name: RedPajamaGithub


text:
using FluentAssertions;
using Moq;
using Nancy.Security;
using NUnit.Framework;
using Owin;
using Owin.StatelessAuth;
using VaraniumSharp.Monolith.Interfaces.Configuration;
using VaraniumSharp.Monolith.Security;
using VaraniumSharp.Monolith.Tests.Helpers;

namespace VaraniumSharp.Monolith.Tests.Security
{
    public class StatelessOAuthValidationTests
    {
        #region Public Methods

        [Test]
        public void DisablingStatelessAuthWorksCorrectly()
        {
            // arrange
            var appBuilderMock = new AppBuilderFixture();
            var configurationMock = new Mock<IOAuthTokenValidatorConfiguration>();
            var validatorMock = new Mock<ITokenValidator>();

            // act
            appBuilderMock.UserStatelessOAuthTokenValidation(validatorMock.Object, configurationMock.Object);

            // assert
            appBuilderMock.MiddleWareRegistrationInvocations.Should().Be(0);
        }

        [Test]
        public void EnablingStatelessAuthWorkCorrectly()
        {
            // arrange
            var appBuilderMock = new AppBuilderFixture();
            var configurationMock = new Mock<IOAuthTokenValidatorConfiguration>();
            var validatorMock = new Mock<ITokenValidator>();

            configurationMock
                .Setup(t => t.Enabled)
                .Returns(true);

            // act
            appBuilderMock.UserStatelessOAuthTokenValidation(validatorMock.Object, configurationMock.Object);

            // assert
            appBuilderMock.MiddleWareRegistrationInvocations.Should().Be(1);
        }

        #endregion
    }
}


text:
describe('Model', function() {

    var UserModel;
    var mgModel;

    beforeEach(function() {
        module('mgmodel');
    });

    beforeEach(inject(function(_mgModel_) {
        mgModel = _mgModel_;
        UserModel = mgModel.extend({
            id: null,
            firstName: null,
            lastName: null,
            constructor: function() {
                this.email = 'test@example.com';
                mgModel.apply(this, arguments);
            },
            getName: function() {
                return this.firstName + ' ' + this.lastName;
            }
        });
    }));

    it('should be created', function() {
        var model = new UserModel();
        expect(model.firstName).toBe(null);
        expect(model.email).toBe('test@example.com');
        expect(model.getId()).toBe(null);
        expect(model.constructor.$collection).toBe(mgModel.$collection);
    });

    it('should store values', function() {
        var model = new UserModel({
            id: 1,
            firstName: 'John',
            lastName: 'Doe',
            email: 'john@example.com'
        });
        expect(model.firstName).toBe('John');
        expect(model.email).toBe('john@example.com');
        expect(model.getId()).toBe(1);
        expect(model.getName()).toBe('John Doe');
    });
});


text:
<?php

namespace Pastum\Component\PAMI\Message\Action;

/**
 * QueuePenalty action message.
 */
class QueuePenaltyAction extends ActionMessage
{
    /**
     * Constructor.
     *
     * @param string $queue Queue name
     * @param string $event Event
     */
    public function __construct($interface, $penalty, $queue = false)
    {
        parent::__construct('QueuePenalty');

        $this->setKey('Interface', $interface);
        $this->setKey('Penalty', $penalty);

        if ($queue !== false) {
            $this->setKey('Queue', $queue);
        }
    }
}


text:
package com.adenki.smpp.message;

import org.testng.annotations.Test;

import com.adenki.smpp.Address;

@Test
public class DataSMTest extends PacketTests<DataSM> {

    protected Class<DataSM> getPacketType() {
        return DataSM.class;
    }

    @Override
    protected DataSM getInitialisedPacket() {
        DataSM packet = new DataSM();
        packet.setDataCoding(4);
        packet.setDestination(new Address(2, 2, "22222222"));
        packet.setEsmClass(32);
        packet.setServiceType("serviceType");
        packet.setSource(new Address(1, 1, "111111111111"));
        packet.setRegistered(0);
        return packet;
    }
}


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
Prodr. fl. neomarch. 335 (1804)

#### Original name
Sphaeria umbratilis Rebent.

### Remarks
null


text:
using System;
using AtomicNet;
using Microsoft.VisualStudio.TestTools.UnitTesting;

namespace AtomicNetTests
{

    [System.Diagnostics.CodeAnalysis.ExcludeFromCodeCoverage]
    public  class   TestAtom : Atom<TestAtom> {}

    [System.Diagnostics.CodeAnalysis.ExcludeFromCodeCoverage]
    public  class   SubTestAtom : TestAtom {}

    [System.Diagnostics.CodeAnalysis.ExcludeFromCodeCoverage]
    [TestClass]
    public  class   AtomTests {}

}


text:
<TITLE>Review for Romeo Must Die (2000)</TITLE>
<LINK REL="STYLESHEET" TYPE="text/css" HREF="/ramr.css">

Romeo Must Die (2000)

reviewed by
Susan Granger

http://www.speakers-podium.com/susangranger.

Susan Granger's review of "ROMEO MUST DIE" (Warner Bros.)

 Despite its thin veneer of Shakespeare's Romeo and Juliet
tragedy, this is a martial-arts adventure featuring Jet Li (Lethal
Weapon 4) and recording star Aaliyah as reluctant members of the
Chinese and African-American mobs who are drawn to one other despite
their crime lord families' disapproval. Aimed specifically at fans of
Hong Kong action pictures, the story introduces 36 year-old Jet Li as
a disgraced ex-Hong Kong cop who escapes from jail to arrive in
Oakland, California, in time for his younger brother's funeral and, of
course, to avenge his murder. The plot that ensues is not logical yet
utterly predictable. But who cares? Audiences flock to see Jackie
Chan, Chow Yun-Fat, and now Asian superstar Jet Li for the fighting
not the fiction. And the intricate fights are impressively staged by
cinematographer-turned-director Andrzej Bartkowiak, who did the
visuals for Lethal Weapon 4.  One cool, computer-enhanced sequence
that impressed me showed precisely what happens inside the human body
when bones crack and break. But the audience seemed to respond best to
a stunt in which Jet Li polishes off five opponents while hanging
upside down, tied to a rope by one foot. Russell Wong, Henry O, Delroy
Lindo, and Isiah Washington co-star and popular R&B singer Aaliyah
makes a creditable feature-film acting debut - plus makin' music with
hip hop star DMX. Credit writers Mitchell Kapner, Eric Bernt, and John
Jarrell for trying to give their stock characters, bound by tradition,
some background and depth. On the Granger Movie Gauge of 1 to 10,
Romeo Must Die is a violent, fast-paced 5 - but recommended for fight
fans only.

The review above was posted to the
rec.arts.movies.reviews newsgroup (de.rec.film.kritiken for German reviews).

The Internet Movie Database accepts no responsibility for the contents of the
review and has no editorial control. Unless stated otherwise, the copyright
belongs to the author.

Please direct comments/criticisms of the review to relevant newsgroups.

Broken URLs inthe reviews are the responsibility of the author.

The formatting of the review is likely to differ from the original due
to ASCII to HTML conversion.

Related links: index of all rec.arts.movies.reviews reviews


text:
@host {
  display: inline-block;
  -webkit-user-select: none;
}

.toggle {
  position: relative;
  height: 27px;
  line-height: 27px;
  width: 94px;
  overflow: hidden;
  border: 1px solid #CCC;
  border-radius: 2px;
  font-size: 13px;
  font-weight: bold;
  color: #666;
  background-image: -webkit-linear-gradient(top, #EEEEEE, #e0e0e0);
  box-shadow: inset 0px 1px 2px 0 rgba(0,0,0,0.1);
}

.toggle span {
  width: 47px;
  float: left;
  text-align: center;
  border-radius: 2px 2px 0 0;
}

.toggle span.on {
  color: #FFF;
  background-image: -webkit-linear-gradient(top, #3b93ff, #3689EE);
  box-shadow: inset 0px 1px 2px 0 rgba(0,0,0,0.1);
  border-radius: 2px 0 0 2px;
}

.toggle .thumb {
  position: absolute;
  display: block;
  top: -1px;
  left: -1px;
  height: 27px;
  width: 47px;
  border: 1px solid #CCC;
  border-radius: 2px;
  box-shadow: 0px 1px 2px 0 rgba(0,0,0,0.1);
  background-image: -webkit-linear-gradient(top, #f8f8f8, #f1f1f1);
  -webkit-transition: all 0.130s ease-out;
}

.thumb.dragging {
  -webkit-transition: all 0;
}

.toggle.on .thumb {
  -webkit-transform: translate3d(47px, 0, 0);
}

.toggle .thumb::after {
  content: "";
  position: absolute;
  display: block;
  top: 9px;
  left: 15px;
  height: 9px;
  width: 17px;
  background-image: -webkit-linear-gradient(left, #ccc 50%, transparent 50%), -webkit-linear-gradient(left, #ccc 50%, transparent 50%), -webkit-linear-gradient(left, #ccc 50%, transparent 50%), -webkit-linear-gradient(left, #ccc 50%, transparent 50%), -webkit-linear-gradient(left, #ccc 50%, transparent 50%);
  background-size: 2px;
  background-position: 0 0, 0 2px, 0 4px, 0 6px, 0 8px;
  background-repeat: repeat-x;
}


text:
export default function getExtraFields(appKey) {
  if (appKey === 'search' || appKey === 'navigator') {
    return [{

    }];
  }
  return [];
}


text:
"""
Takes an AST (abstract syntax tree) and an environment in order to
evaluate the AST under the environment
"""

from . import utils
from abc import ABCMeta, abstractmethod
from .environment import Env
from .exceptions import EvaluationError

class Primitive(object):
    __metaclass__ = ABCMeta

#    def __repr__(self):
#        return str(self.eval(Env()))

    @abstractmethod
    def eval(self, env):
        raise NotImplementedError()

    def apply(self, env, caller):
        raise EvaluationError(self, 'Cannot invoke with: \'{0}\'', self)

    def quoted_form(self, env):
        return self.eval(env)

class InterOp(Primitive):
    """ Helper class for wrapping Python functions """

    def __init__(self, func, *args):
        self.func = func
        self.args = args

    def eval(self, env):
        values = [a.eval(env) for a in self.args]
        try:
            return self.func(*values)
        except TypeError as ex:
            raise EvaluationError(self, str(ex))

class SpecialForm(Primitive):
    """ A proxy for other built-in types """

    def __init__(self, name):
        self.impl = __special_forms__[name]

    def eval(self, env):
        return self

    def apply(self, env, caller):
        """ Don't evaluate params for special forms """
        return self.impl(*caller.params).eval(env)

class Atom(Primitive):
    """ An atom """

    def __init__(self, value):
        self.value = value

    def eval(self, env):
        return self.value

    def __repr__(self):
        return repr(self.value)

class Closure(Primitive):
    """ A closure is not in 'source' programs; it is what functions evaluate to """

    def __init__(self, env, func):
        self.env = env
        self.func = func

    def eval(self, env):
        return self

    @classmethod
    def bind(cls, env_to_extend, formals, params, caller_env):
        """
        Extend the closure's environment by binding the
        params to the functions formals
        """
        for i, bind_variable in enumerate(formals):
            if bind_variable == Lambda.VARIADIC_MARKER:  # variadic arg indicator
                # Use the next formal as the /actual/ bind variable,
                # evaluate the remaining arguments into a list (NOTE offset from i)
                # and dont process any more arguments
                bind_variable = formals[i + 1]
                value = List.make_lazy_list(params[i:]).eval(caller_env)
                env_to_extend = env_to_extend.extend(bind_variable.name, value)
                break
            else:
                value = params[i].eval(caller_env)
                env_to_extend = env_to_extend.extend(bind_variable.name, value)
        return env_to_extend

    def apply(self, env, caller):
        if not self.func.has_sufficient_arity(caller.params):
            raise EvaluationError(self,
                                  'Call to \'{0}\' applied with insufficient arity: {1} args expected, {2} supplied',
                                  # FIXME: probably ought rely on __repr__ of symbol here....
                                  caller.funexp.name,
                                  self.func.arity(),
                                  len(caller.params))

        if not self.func.is_variadic() and len(self.func.formals) != len(caller.params):
            raise EvaluationError(self,
                                  'Call to \'{0}\' applied with excessive arity: {1} args expected, {2} supplied',
                                  # FIXME: probably ought rely on __repr__ of symbol here....
                                  caller.funexp.name,
                                  self.func.arity(),
                                  len(caller.params))

        extended_env = Closure.bind(
            self.env, self.func.formals, caller.params, env)
        extended_env.stack_depth = env.stack_depth + 1
        return self.func.body.eval(extended_env)

class ForwardRef(Primitive):
    """
    A forward reference is a placeholder that can be set at a later point
    when the value is available. Evaluating before the reference is set will
    yield None. Evaluating after the reference is set will yield the
    referenced value.
    """

    def __init__(self):
        self.reference = None

    def eval(self, env):
        return self.reference

    def apply(self, env, caller):
        """ Don't evaluate params for special forms """
        return self.reference.apply(env, caller)

# http://code.activestate.com/recipes/474088/
class List(Primitive):
    """ A list """

    def __init__(self, *args):
        self.args = args
        if args:
            self.funexp = self.args[0]
            self.params = self.args[1:]

    def __repr__(self):
        return str(self.args).replace(',', '')

    def __len__(self):
        return len(self.args)

    def __iter__(self):
        return self.args.__iter__()

    def __getitem__(self, index):
        return self.args.__getitem__(index)

    def index(self, value):
        return self.args.index(value)

    @classmethod
    def make_lazy_list(cls, arr):
        t = Atom(None)
        while arr:
            t = List(Symbol('cons'), arr[-1], Delay(t))
            arr = arr[:-1]
        return t

    def splice_args(self, args, env):
        for arg in args:
            if isinstance(arg, UnquoteSplice):
                for elem in self.splice_args(arg.eval(env), env):
                    yield elem
            else:
                yield arg

    def quoted_form(self, env):
        """ Override default implementation to present as a list """
        quote = SyntaxQuote if SyntaxQuote.ID in env else Quote
        return List.make_lazy_list([quote(a) for a in self.splice_args(self.args, env)]).eval(env)

    def eval(self, env):
        if self.args:
            value = self.funexp.eval(env)
            if env['*debug*']:
                utils.debug('{0}{1} {2}', '  ' * env.stack_depth,
                            self.funexp.name, self.params)
            try:
                return value.apply(env, self)
            except AttributeError:
                raise EvaluationError(
                    self, 'Cannot invoke with: \'{0}\'', value)

class BuiltIn(Primitive):
    pass

class Symbol(BuiltIn):
    """
    A symbolic reference, resolved in the environment firstly against lexical
    closures in local symbol stack, then against a global symbol table.
    """

    def __init__(self, name):
        self.name = name

    def __repr__(self):
        return str(self.name)

    def __hash__(self):
        return hash('symbol') ^ hash(self.name)

    def __eq__(self, other):
        return isinstance(other, Symbol) and self.name == other.name

    def __ne__(self, other):
        return not self == other

    def eval(self, env):
        try:
            return env[self.name]
        except ValueError as ex:
            raise EvaluationError(self, str(ex))

    def quoted_form(self, env):
        if self.name.endswith('#') and SyntaxQuote.ID in env:
            unique_id = env[SyntaxQuote.ID]
            name = "{0}__{1}__auto__".format(self.name[:-1], unique_id)
            return Symbol(name)
        else:
            return self

class Quote(BuiltIn):
    """ Makes no effort to call the supplied expression when evaluated """

    def __init__(self, expr):
        self.expr = expr

    def eval(self, env):
        return self.expr.quoted_form(env)

    def quoted_form(self, env):
        return self.expr

class SyntaxQuote(Quote):

    ID = 'G__syntax_quote_id'

    def eval(self, env):
        if SyntaxQuote.ID not in env:
            env = env.extend(SyntaxQuote.ID, Env.next_id())
        return self.expr.quoted_form(env)

class Unquote(BuiltIn):

    def __init__(self, expr):
        self.expr = expr

    def eval(self, env):
        value = self.expr.eval(env)
        if isinstance(value, List):
            value = value.eval(env)
        return value

class UnquoteSplice(BuiltIn):

    def __init__(self, expr):
        self.expr = expr

    def eval(self, env):
        list_ = self.expr.eval(env)
        return Realize(list_).eval(env)

class Body(BuiltIn):
    """
    Evaluates a sequence of expressions, presumably for side effects, returning
    the result of the last evaluated expression.
    """

    def __init__(self, *body):
        self.body = body

    def eval(self, env):
        result = None
        for expr in self.body:
            result = expr.eval(env)
        return result

class Let(BuiltIn):
    """ A local binding """

    def __init__(self, binding, *body):
        self.binding_form = binding.args[0]
        self.expr = binding.args[1]
        self.body = Body(*body)

    def eval(self, env):
        value = self.expr.eval(env)
        extended_env = env.extend(self.binding_form.name, value)
        extended_env.stack_depth = env.stack_depth + 1
        return self.body.eval(extended_env)

class Let_STAR(BuiltIn):
    """ Multiple local bindings """

    def __init__(self, bindings, *body):
        self.bindings = bindings
        self.body = Body(*body)

    def eval(self, env):
        extended_env = env
        for symbol, expr in self.bindings:
            value = expr.eval(extended_env)
            extended_env = extended_env.extend(symbol.name, value)

        extended_env.stack_depth = env.stack_depth + 1
        return self.body.eval(extended_env)

class LetRec(BuiltIn):
    """ Multiple recursive local bindings, which must not be shadowed """

    def __init__(self, bindings, *body):
        self.bindings = bindings
        self.body = Body(*body)

    def eval(self, env):
        extended_env = env

        # All names are created first and filled with forward
        # references and bound to the environment
        forward_refs = {}
        for symbol, _ in self.bindings:

            if symbol in forward_refs:
                # bindings are NOT shadowed in letrec
                raise EvaluationError(
                    self, "'{0}' is not distinct in letrec", symbol)

            ref = ForwardRef()
            forward_refs[symbol] = ref
            extended_env = extended_env.extend(symbol.name, ref)

        # Then the binding expressions are evaluated and set in the fwd-refs
        for symbol, expr in self.bindings:
            forward_refs[symbol].reference = expr.eval(extended_env)

        extended_env.stack_depth = env.stack_depth + 1
        return self.body.eval(extended_env)

class Lambda(BuiltIn):
    """ A recursive n-argument anonymous function """

    VARIADIC_MARKER = Symbol('.')

    def __init__(self, formals, *body):
        self.formals = formals
        self.body = Body(*body)

    def arity(self):
        if self.is_variadic():
            return self.formals.index(Lambda.VARIADIC_MARKER)
        else:
            return len(self.formals)

    def is_variadic(self):
        return Lambda.VARIADIC_MARKER in self.formals

    def has_sufficient_arity(self, args):
        try:
            # Must be at least n args (where n is the variadic marker position)
            return len(args) >= self.formals.index(Lambda.VARIADIC_MARKER)
        except ValueError:
            # no. args must match exactly
            return len(args) == len(self.formals)

    def eval(self, env):
        if self.is_variadic():
            if sum(1 for f in self.formals if f == Lambda.VARIADIC_MARKER) > 1:
                raise EvaluationError(
                    self, 'Invalid variadic argument spec: {0}', self.formals)

            if self.formals.index(Lambda.VARIADIC_MARKER) != len(self.formals) - 2:
                raise EvaluationError(
                    self, 'Only one variadic argument is allowed: {0}', self.formals)

        if len(self.formals) != len(set(self.formals)):
            raise EvaluationError(
                self, 'Formals are not distinct: {0}', self.formals)

        return Closure(env, self)

class Promise(Closure):

    def __init__(self, closure):
        self.closure = closure
        self.realized = False
        self.result = None

    def eval(self, env):
        return self

    def apply(self, env, caller):
        if not self.realized:
            self.result = self.closure.apply(env, caller)
            self.realized = True

        return self.result

class Delay(BuiltIn):
    """
    Creates a promise that when forced, evaluates the body to produce its
    value. The result is then cached so that further uses of force produces
    the cached value immediately.
    """

    def __init__(self, *body):
        self.body = body

    def eval(self, env):
        return Promise(Lambda(List(), *self.body).eval(env))

class If(BuiltIn):
    """ If """

    def __init__(self, test_expr, then_expr, else_expr=Atom(None)):
        self.test_expr = test_expr
        self.then_expr = then_expr
        self.else_expr = else_expr

    def eval(self, env):
        if self.test_expr.eval(env):
            return self.then_expr.eval(env)
        else:
            return self.else_expr.eval(env)

class Unbound(BuiltIn):
    def eval(self, env):
        return self

    def __eq__(self, other):
        return isinstance(other, Unbound)

    def __ne__(self, other):
        return not self == other

    def __hash__(self):
        return hash('unbound') ^ hash(self.__class__)

class Define(BuiltIn):
    """ Updates entries in the Global Symbol Table """

    def __init__(self, *args):
        if len(args) == 0:
            raise EvaluationError(self, "Too few arguments supplied to define")
        self.args = args

    def name(self):
        first = self.args[0]
        if isinstance(first, List):
            return first.args[0]
        else:
            return first

    def docstring(self):
        return [text for text in self.args[1:] if isinstance(text, str) and text.startswith(';^')]

    def body(self):
        return [expr for expr in self.args[1:] if isinstance(expr, Primitive)]

    def set_docstring_on(self, obj):
        params = ''
        if isinstance(obj, Closure) and obj.func.formals:
            params = ' ' + str(obj.func.formals).replace(',',
                                                         '').replace('\'', '')

        if self.docstring():
            tidied = [repr(self.name()) + params] + \
                     ['  ' + x.replace(';^', '  ').strip()
                      for x in self.docstring()]
            setattr(obj, '__docstring__', '\n'.join(tidied))

    def set_source_on(self, obj):
        if isinstance(obj, Closure):
            for attr in ['__source__', '__location__']:
                setattr(obj, attr, getattr(self.name(), attr, None))

    def eval(self, env):
        symbol = self.name()
        first = self.args[0]
        if isinstance(first, List):
            formals = first.args[1:]
            obj = Lambda(List(*formals), *self.body()).eval(env)
        else:
            body = self.body()
            body_size = len(body)
            if body_size > 1:
                raise EvaluationError(
                    self, "Too many arguments supplied to define")
            elif body_size == 0:
                obj = Unbound()
            else:
                obj = body[0].eval(env)

        self.set_docstring_on(obj)
        self.set_source_on(obj)

        env[symbol.name] = obj
        return symbol

class Set_PLING(BuiltIn):
    """ Updates a local binding """

    def __init__(self, binding_form, expr):
        self.binding_form = binding_form
        self.expr = expr

    def eval(self, env):
        try:
            value = self.expr.eval(env)
            env.set_local(self.binding_form.name, value)
            return None
        except ValueError as ex:
            raise EvaluationError(self, str(ex))

class Realize(Primitive):
    """
    Lazy list unpacker - eagerly takes *ALL* the content from a nested lazy list
    and returns as a nested array of arrays. Should not be used with infinite
    streams.
    """

    def __init__(self, value):
        self.value = value

    def eval(self, env):
        if type(self.value) == tuple:
            arr = []
            current_head = self.value
            while current_head is not None:
                value = List(Symbol('first'), Atom(current_head)).eval(env)
                arr.append(Realize(value).eval(env))
                current_head = List(
                    Symbol('rest'), Atom(current_head)).eval(env)
            return arr
        elif isinstance(self.value, Primitive):
            return self.value.eval(env)
        else:
            return self.value

class Repr(Primitive):
    """
    A string representation of atoms/lists, implemented with iteration so as
    not to blow Python's stack. Note nested lists are (presently) handled
    with recursion - this may change to an explicit stack.

    List traversal will not extend beyond the *print-length* (if not nil).
    """

    def __init__(self, value):
        self.value = value

    def print_length(self, env):
        if '*print-length*' in env:
            return env['*print-length*']

    # TODO: make this and Realize into one implementation
    def eval(self, env):
        if type(self.value) == tuple:
            current_head = self.value
            max_iterations = self.print_length(env)
            ret = '('
            while current_head and (max_iterations is None or max_iterations > 0):
                value = List(Symbol('first'), Atom(current_head)).eval(env)
                ret += Repr(value).eval(env)
                current_head = List(
                    Symbol('rest'), Atom(current_head)).eval(env)
                if max_iterations is not None:
                    max_iterations -= 1
                if current_head is not None:
                    ret += ' '

            if current_head is not None and max_iterations == 0:
                ret += '...'

            ret += ')'
            return ret
        elif isinstance(self.value, Primitive):
            return self.value.eval(env)
        elif isinstance(self.value, str):
            return self.value
        else:
            return repr(self.value)

class Eval(BuiltIn):

    def __init__(self, expr):
        self.expr = expr

    def eval(self, env):
        return self.expr.quoted_form(env).eval(env)

__special_forms__ = {
    'symbol': Symbol,
    'quote': Quote,
    'lambda': Lambda,
    'λ': Lambda,
    'define': Define,
    'begin': Body,
    'if': If,
    'let': Let,
    'let*': Let_STAR,
    'letrec': LetRec,
    'set!': Set_PLING,
    'delay': Delay,
    'eval': Eval
}


text:
test: lint dist/fetch.umd.js

lint: node_modules/
	./node_modules/.bin/eslint --report-unused-disable-directives *.js test/*.js

dist/fetch.umd.js: fetch.js rollup.config.js node_modules/
	./node_modules/.bin/rollup -c

dist/fetch.umd.js.flow: fetch.js.flow
	cp $< $@

node_modules/:
	npm install

clean:
	rm -rf ./bower_components ./node_modules

.PHONY: clean lint test


text:
title:  Od Subote do nedelje
date:   08/05/2018
---

Kao adventistički hrišćani često čujemo hrišćansku braću i sestre iz drugih verskih zajednica da je Zakon ukinut ili da više nismo pod Zakonom već pod blagodaću. Međutim, oni zapravo kažu da je samo četvrta zapovest ukinuta. Iako, neki ne misle tako. Oni smatraju da je sedmi dan, Subota, zamenjen prvim danom, nedeljom, u znak sećanja na Isusovo vaskrsenje.

Oni veruju da to mogu dokazati biblijskim tekstovima.

Slede novozavetni tekstovi koje mnogi hrišćani obično navode u želji da pokažu da je sedmi dan Subota iz Starog zaveta u Novom zavetu zamenjen prvim danom. Dok ih čitamo, zapitajmo se da li oni zaista govore o promeni dana ili samo opisuju tadašnje događaje, ne podižući ih na nivo uspostavljanja promene.

`Pročitajte: Jovan 20,19-23. Kakav je razlog naveden što su se učenici okupili u toj sobi? Da li je u pitanju bilo bogosluženje u čast Isusovog vaskrsenja, kao što neki tvrde?`

`Pročitajte: Dela 20,6.7. Šta u ovim stihovima, ako postoji nešto, ukazuje da je Subota promenjena u nedelju, prvi dan sedmice? Vidi: Dela 2,46.`

`Pročitajte: 1. Korinćanima 16,1-4. Pored činjenice da je trebalo da sakupljaju milostinju kod kuće prvog dana u sedmici, šta ovaj tekst uči o promeni Subote u nedelju?`

Ovi tekstovi predstavljaju srž »dokaza« koji se koriste u širenju učenja da je prvi dan u sedmici zamenio sedmi dan Subotu. Osim što je nekoliko puta opisano da su se vernici okupili iz različitih razloga, nijedan tekst ne ukazuje da su ova okupljanja predstavljala bogosluženja održana prvog dana kao zamena za sedmi dan Subotu. Pojedinci pripisuju ovim stihovima značenje koje nikada nisu imali.


text:
package com.iluwatar.urm.testdomain.person;

public class DoubleReferer {
  private Manager myBoss;
  private Manager myTeamManager;
}


text:
<title>Using fast enumeration - Using the GNU Compiler Collection (GCC)</title>
<meta http-equiv="Content-Type" content="text/html">
<meta name="description" content="Using the GNU Compiler Collection (GCC)">
<meta name="generator" content="makeinfo 4.11">
<link title="Top" rel="start" href="index.html#Top">
<link rel="up" href="Fast-enumeration.html#Fast-enumeration" title="Fast enumeration">
<link rel="next" href="c99_002dlike-fast-enumeration-syntax.html#c99_002dlike-fast-enumeration-syntax" title="c99-like fast enumeration syntax">
<link href="http://www.gnu.org/software/texinfo/" rel="generator-home" title="Texinfo Homepage">

<meta http-equiv="Content-Style-Type" content="text/css">

Next: c99-like fast enumeration syntax,
Up: Fast enumeration

8.9.1 Using fast enumeration

GNU Objective-C provides support for the fast enumeration syntax:

       id array = ...;
       id object;

       for (object in array)
       {
         /* Do something with 'object' */
       }

array needs to be an Objective-C object (usually a collection
object, for example an array, a dictionary or a set) which implements
the “Fast Enumeration Protocol” (see below).  If you are using a
Foundation library such as GNUstep Base or Apple Cocoa Foundation, all
collection objects in the library implement this protocol and can be
used in this way.

The code above would iterate over all objects in array.  For
each of them, it assigns it to object, then executes the
Do something with 'object' statements.

Here is a fully worked-out example using a Foundation library (which
provides the implementation of NSArray, NSString and
NSLog):

       NSArray *array = [NSArray arrayWithObjects: @"1", @"2", @"3", nil];
       NSString *object;

       for (object in array)
         NSLog (@"Iterating over %@", object);


text:
#include <cstdio>
#include <dlfcn.h>
#include <exception>

#include <glog/logging.h>

#include <lua.hpp>

#include "folly/String.h"

namespace facebook { namespace deeplearning { namespace torch {

namespace {

int wrapExceptions(lua_State* L, lua_CFunction f) {
  try {
    return f(L);
  } catch (const std::exception& e) {
    lua_pushstring(L, folly::exceptionStr(e).c_str());
  }
  // Do not catch (...) as that ends up catching Lua errors, which
  // causes problems if wrapExceptions is on the stack multiple times.
  return lua_error(L);  // Rethrow as a Lua error
}

}  // namespace

// There is no way to hook on module unloading, but if the module containing
// wrapExceptions() gets unloaded (and dlclose()d) during Lua shutdown, all
// future calls to C library functions (from other finalizers) will segfault!
//
// This is a bug in LuaJIT 2.0.2.
//
// First, I (tudorb) tried to work around this by creating a global userdata
// object that we use as a sentinel. When that object gets GCed, we turn off
// wrapping. It didn't work; that ensures that future code generated
// by LuaJIT won't call the wrapper, but code that's already compiled
// still does.
//
// This is a horrible hack: we want to prevent unloading the current shared
// library. We'll reopen it to bump the reference count and leak the reference.

void initWrappedExceptions(lua_State* L) {
  Dl_info thisLib;
  int r = dladdr(reinterpret_cast<void*>(&wrapExceptions), &thisLib);
  CHECK(r != 0 && thisLib.dli_fname);

  void* leakedHandle = dlopen(thisLib.dli_fname, RTLD_NODELETE | RTLD_NOW);
  CHECK(leakedHandle);

  lua_pushlightuserdata(L, reinterpret_cast<void*>(&wrapExceptions));
  luaJIT_setmode(L, -1, LUAJIT_MODE_WRAPCFUNC | LUAJIT_MODE_ON);
  lua_pop(L, 1);
}

}}}  // namespaces


text:
<?php
namespace keeko\user\action;

use keeko\user\action\base\UserCreateActionTrait;
use keeko\core\package\AbstractAction;

/**
 * Creates an user
 *
 * @author Tester
 * @author gossi
 */
class UserCreateAction extends AbstractAction {

	use UserCreateActionTrait;
}


text:
package com.github.phsym.violation2gerrit.comments;

import com.google.gerrit.extensions.api.changes.ReviewInput.CommentInput;

public class Comment {
	protected Severity severity;
	protected String file;
	protected int line;
	protected String message;

	public Comment(String file, int line, String message) {
		this(file, line, message, Severity.UNKNOWN);
	}

	public Comment(String file, int line, String message, Severity severity) {
		this.file = file.replaceAll("\\\\", "/");
		this.line = line;
		this.message = message;
		this.severity = severity;
	}

	public Comment(String file, String line, String message) {
		this(file, line, message, Severity.UNKNOWN);
	}

	public Comment(String file, String line, String message, Severity severity) {
		this(file, Integer.parseInt(line), message, severity);
	}

	public Severity getSeverity() {
		return severity;
	}

	public String getFile() {
		return file;
	}

	public int getLine() {
		return line;
	}

	public String getMessage() {
		return message;
	}

	public CommentInput toCommentInput() {
		CommentInput cmt = new CommentInput();
		cmt.line = line;
		cmt.message = message;
		return cmt;
	}

	@Override
	public String toString() {
		return "Comment [severity=" + severity + ", file=" + file + ", line="
				+ line + ", message=" + message + "]";
	}

	public boolean isSimilar(Comment other) {
		if (this == other)
			return true;
		if (other == null)
			return false;
		if (file == null) {
			if (other.file != null)
				return false;
		} else if (!file.equals(other.file))
			return false;
		if (line != other.line)
			return false;
		if (message == null) {
			if (other.message != null)
				return false;
		} else if (!message.equals(other.message))
			return false;
		if (severity != other.severity)
			return false;
		return true;
	}
}


text:
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using CQRSMicroservices.Articles;
using CQRSMicroservices.Customers;
using CQRSMicroservices.Framework;
using Newtonsoft.Json.Linq;

namespace CQRSMicroservices.Application
{
  public class Deserializer : IDeserializer
  {
    /// <summary>
    /// You could implement this with reflection or some other deserialize algorithm.
    /// For this sample, we explicitly implemented this.
    /// </summary>
    /// <param name="commandJson"></param>
    /// <returns></returns>
    public Command CreateCommand(JObject commandJson)
    {
      var commandName = commandJson.Properties().First().Name;
      var commandBody = commandJson.Properties().First().Value.Value<JObject>();

      switch(commandName)
      {
        case "CQRSMicroservices.Articles.CreateArticleCommand":
          return new CreateArticleCommand
          {
            ArticleId = Guid.Parse(commandBody["ArticleId"].Value<string>()),
            Description = commandBody["Description"].Value<string>(),
            Price = decimal.Parse(commandBody["Price"].Value<string>(), System.Globalization.CultureInfo.InvariantCulture)
          };

        case "CQRSMicroservices.Articles.MakeArticleAvailableCommand":

          return new MakeArticleAvailableCommand
          {
            ArticleId = Guid.Parse(commandBody["ArticleId"].Value<string>()),
          };

        case "CQRSMicroservices.Articles.MakeArticleUnavailableCommand":
          return new MakeArticleUnavailableCommand
          {
            ArticleId = Guid.Parse(commandBody["ArticleId"].Value<string>()),
          };

        case "CQRSMicroservices.Articles.SellArticleCommand":
          return new SellArticleCommand
          {
            ArticleId = Guid.Parse(commandBody["ArticleId"].Value<string>()),
            CustomerId = Guid.Parse(commandBody["CustomerId"].Value<string>()),
          };

        case "CQRSMicroservices.Customers.CreateCustomerCommand":
          return new CreateCustomerCommand
          {
            CustomerId = Guid.Parse(commandBody["CustomerId"].Value<string>()),
            Name = commandBody["Name"].Value<string>()
          };

        default:
          throw new CommandNotFoundException(commandName);
      }
    }
    /// <summary>
    /// You could implement this with reflection or some other deserialize algorithm.
    /// For this sample, we explicitly implemented this.
    /// </summary>
    /// <param name="eventJson"></param>
    /// <returns></returns>
    public Event CreateEvent(JObject eventJson)
    {
      var eventName = eventJson.Properties().First().Name;
      var eventBody = eventJson.Properties().First().Value.Value<JObject>();

      switch(eventName)
      {
        case "CQRSMicroservices.Articles.ArticleCreatedEvent":

          return new ArticleCreatedEvent
          {
            ArticleId = Guid.Parse(eventBody["ArticleId"].Value<string>()),
            Description = eventBody["Description"].Value<string>(),
            Price = decimal.Parse(eventBody["Price"].Value<string>(), CultureInfo.InvariantCulture)
          };

        case "CQRSMicroservices.Articles.ArticleAvailableEvent":

          return new ArticleAvailableEvent
          {
            ArticleId = Guid.Parse(eventBody["ArticleId"].Value<string>()),
          };

        case "CQRSMicroservices.Articles.ArticleUnavailableEvent":
          return new ArticleUnavailableEvent
          {
            ArticleId = Guid.Parse(eventBody["ArticleId"].Value<string>()),
          };

        case "CQRSMicroservices.Articles.ArticleSoldEvent":
          return new ArticleSoldEvent
          {
            ArticleId = Guid.Parse(eventBody["ArticleId"].Value<string>()),
            CustomerId = Guid.Parse(eventBody["CustomerId"].Value<string>()),
            Price = decimal.Parse(eventBody["Price"].Value<string>(), CultureInfo.InvariantCulture)
          };

        case "CQRSMicroservices.Customers.CustomerCreatedEvent":
          return new CustomerCreatedEvent
          {
            CustomerId = Guid.Parse(eventBody["CustomerId"].Value<string>()),
            Name = eventBody["Name"].Value<string>()
          };

        default:
          throw new EventNotFoundException(eventName);
      }
    }

    public Query CreateQuery(string name, IEnumerable<KeyValuePair<string, IEnumerable<string>>> query)
    {
      switch(name)
      {
        case "/CQRSMicroservices/Articles/GetArticleQuery.query":
          return new GetArticleQuery
          {
            ArticleId = Guid.Parse(query.First(kv => kv.Key == "ArticleId").Value.First())
          };

        case "/CQRSMicroservices/Customers/GetCustomerQuery.query":
          return new GetCustomerQuery
          {
            CustomerId = Guid.Parse(query.First(kv => kv.Key == "CustomerId").Value.First())
          };

        default:
          throw new QueryNotFoundException(name);
      }
    }
  }
}


text:
#include "fsl_mcan.h"

/*******************************************************************************
 * Definitons
 ******************************************************************************/

#define MCAN_TIME_QUANTA_NUM (16U)

/*! @brief MCAN Internal State. */
enum _mcan_state
{
    kMCAN_StateIdle = 0x0,     /*!< MB/RxFIFO idle.*/
    kMCAN_StateRxData = 0x1,   /*!< MB receiving.*/
    kMCAN_StateRxRemote = 0x2, /*!< MB receiving remote reply.*/
    kMCAN_StateTxData = 0x3,   /*!< MB transmitting.*/
    kMCAN_StateTxRemote = 0x4, /*!< MB transmitting remote request.*/
    kMCAN_StateRxFifo = 0x5,   /*!< RxFIFO receiving.*/
};

/* Typedef for interrupt handler. */
typedef void (*mcan_isr_t)(CAN_Type *base, mcan_handle_t *handle);

/*******************************************************************************
 * Prototypes
 ******************************************************************************/

/*!
 * @brief Get the MCAN instance from peripheral base address.
 *
 * @param base MCAN peripheral base address.
 * @return MCAN instance.
 */
uint32_t MCAN_GetInstance(CAN_Type *base);

/*!
 * @brief Reset the MCAN instance.
 *
 * @param base MCAN peripheral base address.
 */
static void MCAN_Reset(CAN_Type *base);

/*!
 * @brief Set Baud Rate of MCAN.
 *
 * This function set the baud rate of MCAN.
 *
 * @param base MCAN peripheral base address.
 * @param sourceClock_Hz Source Clock in Hz.
 * @param baudRate_Bps Baud Rate in Bps.
 */
static void MCAN_SetBaudRate(CAN_Type *base, uint32_t sourceClock_Hz, uint32_t baudRateA_Bps);

#if (defined(FSL_FEATURE_CAN_SUPPORT_CANFD) && FSL_FEATURE_CAN_SUPPORT_CANFD)
/*!
 * @brief Set Baud Rate of MCAN FD.
 *
 * This function set the baud rate of MCAN FD.
 *
 * @param base MCAN peripheral base address.
 * @param sourceClock_Hz Source Clock in Hz.
 * @param baudRateD_Bps Baud Rate in Bps.
 */
static void MCAN_SetBaudRateFD(CAN_Type *base, uint32_t sourceClock_Hz, uint32_t baudRateD_Bps);
#endif /* FSL_FEATURE_CAN_SUPPORT_CANFD */

/*!
 * @brief Get the element's address when read receive fifo 0.
 *
 * @param base MCAN peripheral base address.
 * @return Address of the element in receive fifo 0.
 */
static uint32_t MCAN_GetRxFifo0ElementAddress(CAN_Type *base);

/*!
 * @brief Get the element's address when read receive fifo 1.
 *
 * @param base MCAN peripheral base address.
 * @return Address of the element in receive fifo 1.
 */
static uint32_t MCAN_GetRxFifo1ElementAddress(CAN_Type *base);

/*!
 * @brief Get the element's address when read receive buffer.
 *
 * @param base MCAN peripheral base address.
 * @param idx Number of the erceive buffer element.
 * @return Address of the element in receive buffer.
 */
static uint32_t MCAN_GetRxBufferElementAddress(CAN_Type *base, uint8_t idx);

/*!
 * @brief Get the element's address when read transmit buffer.
 *
 * @param base MCAN peripheral base address.
 * @param idx Number of the transmit buffer element.
 * @return Address of the element in transmit buffer.
 */
static uint32_t MCAN_GetTxBufferElementAddress(CAN_Type *base, uint8_t idx);

/*******************************************************************************
 * Variables
 ******************************************************************************/
/* Array of MCAN handle. */
static mcan_handle_t *s_mcanHandle[FSL_FEATURE_SOC_LPC_CAN_COUNT];

/* Array of MCAN peripheral base address. */
static CAN_Type *const s_mcanBases[] = CAN_BASE_PTRS;

/* Array of MCAN IRQ number. */
static const IRQn_Type s_mcanIRQ[][2] = CAN_IRQS;

#if !(defined(FSL_SDK_DISABLE_DRIVER_CLOCK_CONTROL) && FSL_SDK_DISABLE_DRIVER_CLOCK_CONTROL)
/* Array of MCAN clock name. */
static const clock_ip_name_t s_mcanClock[] = MCAN_CLOCKS;
#endif /* FSL_SDK_DISABLE_DRIVER_CLOCK_CONTROL */

/* MCAN ISR for transactional APIs. */
static mcan_isr_t s_mcanIsr;

/*******************************************************************************
 * Code
 ******************************************************************************/

uint32_t MCAN_GetInstance(CAN_Type *base)
{
    uint32_t instance;

    /* Find the instance index from base address mappings. */
    for (instance = 0; instance < ARRAY_SIZE(s_mcanBases); instance++)
    {
        if (s_mcanBases[instance] == base)
        {
            break;
        }
    }

    assert(instance < ARRAY_SIZE(s_mcanBases));

    return instance;
}

static void MCAN_Reset(CAN_Type *base)
{
    /* Set INIT bit. */
    base->CCCR |= CAN_CCCR_INIT_MASK;
    /* Confirm the value has been accepted. */
    while (!((base->CCCR & CAN_CCCR_INIT_MASK) >> CAN_CCCR_INIT_SHIFT))
    {
    }

    /* Set CCE bit to have access to the protected configuration registers,
       and clear some status registers. */
    base->CCCR |= CAN_CCCR_CCE_MASK;
}

static void MCAN_SetBaudRate(CAN_Type *base, uint32_t sourceClock_Hz, uint32_t baudRateA_Bps)
{
    mcan_timing_config_t timingConfigA;
    uint32_t preDivA = baudRateA_Bps * MCAN_TIME_QUANTA_NUM;

    if (0 == preDivA)
    {
        preDivA = 1U;
    }

    preDivA = (sourceClock_Hz / preDivA) - 1U;

    /* Desired baud rate is too low. */
    if (preDivA > 0x1FFU)
    {
        preDivA = 0x1FFU;
    }

    /* MCAN timing setting formula:
     * MCAN_TIME_QUANTA_NUM = 1 + (xTSEG1 + 1) + (xTSEG2 + 1));
     */
    timingConfigA.preDivider = preDivA;
    timingConfigA.seg1 = 0xAU;
    timingConfigA.seg2 = 0x3U;
    timingConfigA.rJumpwidth = 0x3U;

    /* Update actual timing characteristic. */
    MCAN_SetArbitrationTimingConfig(base, &timingConfigA);
}

#if (defined(FSL_FEATURE_CAN_SUPPORT_CANFD) && FSL_FEATURE_CAN_SUPPORT_CANFD)
static void MCAN_SetBaudRateFD(CAN_Type *base, uint32_t sourceClock_Hz, uint32_t baudRateD_Bps)
{
    mcan_timing_config_t timingConfigD;
    uint32_t preDivD = baudRateD_Bps * MCAN_TIME_QUANTA_NUM;

    if (0 == preDivD)
    {
        preDivD = 1U;
    }

    preDivD = (sourceClock_Hz / preDivD) - 1U;

    /* Desired baud rate is too low. */
    if (preDivD > 0x1FU)
    {
        preDivD = 0x1FU;
    }

    /* MCAN timing setting formula:
     * MCAN_TIME_QUANTA_NUM = 1 + (xTSEG1 + 1) + (xTSEG2 + 1));
     */
    timingConfigD.preDivider = preDivD;
    timingConfigD.seg1 = 0xAU;
    timingConfigD.seg2 = 0x3U;
    timingConfigD.rJumpwidth = 0x3U;

    /* Update actual timing characteristic. */
    MCAN_SetDataTimingConfig(base, &timingConfigD);
}
#endif

void MCAN_Init(CAN_Type *base, const mcan_config_t *config, uint32_t sourceClock_Hz)
{
#if !(defined(FSL_SDK_DISABLE_DRIVER_CLOCK_CONTROL) && FSL_SDK_DISABLE_DRIVER_CLOCK_CONTROL)
    /* Enable MCAN clock. */
    CLOCK_EnableClock(s_mcanClock[MCAN_GetInstance(base)]);
#endif /* FSL_SDK_DISABLE_DRIVER_CLOCK_CONTROL */

    MCAN_Reset(base);

    if (config->enableLoopBackInt)
    {
        base->CCCR |= CAN_CCCR_TEST_MASK | CAN_CCCR_MON_MASK;
        base->TEST |= CAN_TEST_LBCK_MASK;
    }
    if (config->enableLoopBackExt)
    {
        base->CCCR |= CAN_CCCR_TEST_MASK;
        base->TEST |= CAN_TEST_LBCK_MASK;
    }
    if (config->enableBusMon)
    {
        base->CCCR |= CAN_CCCR_MON_MASK;
    }
#if (defined(FSL_FEATURE_CAN_SUPPORT_CANFD) && FSL_FEATURE_CAN_SUPPORT_CANFD)
    if (config->enableCanfdNormal)
    {
        base->CCCR |= CAN_CCCR_FDOE_MASK;
    }
    if (config->enableCanfdSwitch)
    {
        base->CCCR |= CAN_CCCR_FDOE_MASK | CAN_CCCR_BRSE_MASK;
    }
#endif

    /* Set baud rate of arbitration and data phase. */
    MCAN_SetBaudRate(base, sourceClock_Hz, config->baudRateA);
#if (defined(FSL_FEATURE_CAN_SUPPORT_CANFD) && FSL_FEATURE_CAN_SUPPORT_CANFD)
    MCAN_SetBaudRateFD(base, sourceClock_Hz, config->baudRateD);
#endif
}

void MCAN_Deinit(CAN_Type *base)
{
    /* Reset all Register Contents. */
    MCAN_Reset(base);

#if !(defined(FSL_SDK_DISABLE_DRIVER_CLOCK_CONTROL) && FSL_SDK_DISABLE_DRIVER_CLOCK_CONTROL)
    /* Disable MCAN clock. */
    CLOCK_DisableClock(s_mcanClock[MCAN_GetInstance(base)]);
#endif /* FSL_SDK_DISABLE_DRIVER_CLOCK_CONTROL */
}

void MCAN_EnterNormalMode(CAN_Type *base)
{
    /* Reset INIT bit to enter normal mode. */
    base->CCCR &= ~CAN_CCCR_INIT_MASK;
    while (((base->CCCR & CAN_CCCR_INIT_MASK) >> CAN_CCCR_INIT_SHIFT))
    {
    }
}

void MCAN_GetDefaultConfig(mcan_config_t *config)
{
    /* Assertion. */
    assert(config);

    /* Initialize MCAN Module config struct with default value. */
    config->baudRateA = 500000U;
    config->baudRateD = 500000U;
    config->enableCanfdNormal = false;
    config->enableCanfdSwitch = false;
    config->enableLoopBackInt = false;
    config->enableLoopBackExt = false;
    config->enableBusMon = false;
}

#if (defined(FSL_FEATURE_CAN_SUPPORT_CANFD) && FSL_FEATURE_CAN_SUPPORT_CANFD)
void MCAN_SetDataTimingConfig(CAN_Type *base, const mcan_timing_config_t *config)
{
    /* Assertion. */
    assert(config);

    /* Cleaning previous Timing Setting. */
    base->DBTP &= ~(CAN_DBTP_DSJW_MASK | CAN_DBTP_DTSEG2_MASK | CAN_DBTP_DTSEG1_MASK | CAN_DBTP_DBRP_MASK);

    /* Updating Timing Setting according to configuration structure. */
    base->DBTP |= (CAN_DBTP_DBRP(config->preDivider) | CAN_DBTP_DSJW(config->rJumpwidth) |
                   CAN_DBTP_DTSEG1(config->seg1) | CAN_DBTP_DTSEG2(config->seg2));
}
#endif /* FSL_FEATURE_CAN_SUPPORT_CANFD */

void MCAN_SetArbitrationTimingConfig(CAN_Type *base, const mcan_timing_config_t *config)
{
    /* Assertion. */
    assert(config);

    /* Cleaning previous Timing Setting. */
    base->NBTP &= ~(CAN_NBTP_NSJW_MASK | CAN_NBTP_NTSEG2_MASK | CAN_NBTP_NTSEG1_MASK | CAN_NBTP_NBRP_MASK);

    /* Updating Timing Setting according to configuration structure. */
    base->NBTP |= (CAN_NBTP_NBRP(config->preDivider) | CAN_NBTP_NSJW(config->rJumpwidth) |
                   CAN_NBTP_NTSEG1(config->seg1) | CAN_NBTP_NTSEG2(config->seg2));
}

void MCAN_SetFilterConfig(CAN_Type *base, const mcan_frame_filter_config_t *config)
{
    /* Set global configuration of remote/nonmasking frames, set filter address and list size. */
    if (config->idFormat == kMCAN_FrameIDStandard)
    {
        base->GFC |= CAN_GFC_RRFS(config->remFrame) | CAN_GFC_ANFS(config->nmFrame);
        base->SIDFC |= CAN_SIDFC_FLSSA(config->address >> CAN_SIDFC_FLSSA_SHIFT) | CAN_SIDFC_LSS(config->listSize);
    }
    else
    {
        base->GFC |= CAN_GFC_RRFE(config->remFrame) | CAN_GFC_ANFE(config->nmFrame);
        base->XIDFC |= CAN_XIDFC_FLESA(config->address >> CAN_XIDFC_FLESA_SHIFT) | CAN_XIDFC_LSE(config->listSize);
    }
}

void MCAN_SetRxFifo0Config(CAN_Type *base, const mcan_rx_fifo_config_t *config)
{
    /* Set Rx FIFO 0 start address, element size, watermark, operation mode. */
    base->RXF0C |= CAN_RXF0C_F0SA(config->address >> CAN_RXF0C_F0SA_SHIFT) | CAN_RXF0C_F0S(config->elementSize) |
                   CAN_RXF0C_F0WM(config->watermark) | CAN_RXF0C_F0OM(config->opmode);
    /* Set Rx FIFO 0 data field size */
    base->RXESC |= CAN_RXESC_F0DS(config->datafieldSize);
}

void MCAN_SetRxFifo1Config(CAN_Type *base, const mcan_rx_fifo_config_t *config)
{
    /* Set Rx FIFO 1 start address, element size, watermark, operation mode. */
    base->RXF1C |= CAN_RXF1C_F1SA(config->address >> CAN_RXF1C_F1SA_SHIFT) | CAN_RXF1C_F1S(config->elementSize) |
                   CAN_RXF1C_F1WM(config->watermark) | CAN_RXF1C_F1OM(config->opmode);
    /* Set Rx FIFO 1 data field size */
    base->RXESC |= CAN_RXESC_F1DS(config->datafieldSize);
}

void MCAN_SetRxBufferConfig(CAN_Type *base, const mcan_rx_buffer_config_t *config)
{
    /* Set Rx Buffer start address. */
    base->RXBC |= CAN_RXBC_RBSA(config->address >> CAN_RXBC_RBSA_SHIFT);
    /* Set Rx Buffer data field size */
    base->RXESC |= CAN_RXESC_RBDS(config->datafieldSize);
}

void MCAN_SetTxEventFifoConfig(CAN_Type *base, const mcan_tx_fifo_config_t *config)
{
    /* Set TX Event FIFO start address, element size, watermark. */
    base->TXEFC |= CAN_TXEFC_EFSA(config->address >> CAN_TXEFC_EFSA_SHIFT) | CAN_TXEFC_EFS(config->elementSize) |
                   CAN_TXEFC_EFWM(config->watermark);
}

void MCAN_SetTxBufferConfig(CAN_Type *base, const mcan_tx_buffer_config_t *config)
{
    assert((config->dedicatedSize + config->fqSize) <= 32U);

    /* Set Tx Buffer start address, size, fifo/queue mode. */
    base->TXBC |= CAN_TXBC_TBSA(config->address >> CAN_TXBC_TBSA_SHIFT) | CAN_TXBC_NDTB(config->dedicatedSize) |
                  CAN_TXBC_TFQS(config->fqSize) | CAN_TXBC_TFQM(config->mode);
    /* Set Tx Buffer data field size */
    base->TXESC |= CAN_TXESC_TBDS(config->datafieldSize);
}

void MCAN_SetSTDFilterElement(CAN_Type *base,
                              const mcan_frame_filter_config_t *config,
                              const mcan_std_filter_element_config_t *filter,
                              uint8_t idx)
{
    uint8_t *elementAddress = 0;
    elementAddress = (uint8_t *)(MCAN_GetMsgRAMBase(base) + config->address + idx * 4U);
    memcpy(elementAddress, filter, sizeof(filter));
}

void MCAN_SetEXTFilterElement(CAN_Type *base,
                              const mcan_frame_filter_config_t *config,
                              const mcan_ext_filter_element_config_t *filter,
                              uint8_t idx)
{
    uint8_t *elementAddress = 0;
    elementAddress = (uint8_t *)(MCAN_GetMsgRAMBase(base) + config->address + idx * 8U);
    memcpy(elementAddress, filter, sizeof(filter));
}

static uint32_t MCAN_GetRxFifo0ElementAddress(CAN_Type *base)
{
    uint32_t eSize;
    eSize = (base->RXESC & CAN_RXESC_F0DS_MASK) >> CAN_RXESC_F0DS_SHIFT;
    if (eSize < 5U)
    {
        eSize += 4U;
    }
    else
    {
        eSize = eSize * 4U - 10U;
    }
    return (base->RXF0C & CAN_RXF0C_F0SA_MASK) +
           ((base->RXF0S & CAN_RXF0S_F0GI_MASK) >> CAN_RXF0S_F0GI_SHIFT) * eSize * 4U;
}

static uint32_t MCAN_GetRxFifo1ElementAddress(CAN_Type *base)
{
    uint32_t eSize;
    eSize = (base->RXESC & CAN_RXESC_F1DS_MASK) >> CAN_RXESC_F1DS_SHIFT;
    if (eSize < 5U)
    {
        eSize += 4U;
    }
    else
    {
        eSize = eSize * 4U - 10U;
    }
    return (base->RXF1C & CAN_RXF1C_F1SA_MASK) +
           ((base->RXF1S & CAN_RXF1S_F1GI_MASK) >> CAN_RXF1S_F1GI_SHIFT) * eSize * 4U;
}

static uint32_t MCAN_GetRxBufferElementAddress(CAN_Type *base, uint8_t idx)
{
    assert(idx <= 63U);
    uint32_t eSize;
    eSize = (base->RXESC & CAN_RXESC_RBDS_MASK) >> CAN_RXESC_RBDS_SHIFT;
    if (eSize < 5U)
    {
        eSize += 4U;
    }
    else
    {
        eSize = eSize * 4U - 10U;
    }
    return (base->RXBC & CAN_RXBC_RBSA_MASK) + idx * eSize * 4U;
}

static uint32_t MCAN_GetTxBufferElementAddress(CAN_Type *base, uint8_t idx)
{
    assert(idx <= 31U);
    uint32_t eSize;
    eSize = (base->TXESC & CAN_TXESC_TBDS_MASK) >> CAN_TXESC_TBDS_SHIFT;
    if (eSize < 5U)
    {
        eSize += 4U;
    }
    else
    {
        eSize = eSize * 4U - 10U;
    }
    return (base->TXBC & CAN_TXBC_TBSA_MASK) + idx * eSize * 4U;
}

uint32_t MCAN_IsTransmitRequestPending(CAN_Type *base, uint8_t idx)
{
    return (base->TXBRP & (uint32_t)(1U << idx)) >> (uint32_t)idx;
}

uint32_t MCAN_IsTransmitOccurred(CAN_Type *base, uint8_t idx)
{
    return (base->TXBTO & (uint32_t)(1U << idx)) >> (uint32_t)idx;
}

status_t MCAN_WriteTxBuffer(CAN_Type *base, uint8_t idx, const mcan_tx_buffer_frame_t *txFrame)
{
    if (!MCAN_IsTransmitRequestPending(base, idx))
    {
        uint8_t *elementAddress = 0;
        elementAddress = (uint8_t *)(MCAN_GetMsgRAMBase(base) + MCAN_GetTxBufferElementAddress(base, idx));

        /* Write 2 words configuration field. */
        memcpy(elementAddress, (uint8_t *)txFrame, 8U);
        /* Write data field. */
        memcpy(elementAddress + 8U, txFrame->data, txFrame->size);
        return kStatus_Success;
    }
    else
    {
        return kStatus_Fail;
    }
}

status_t MCAN_ReadRxBuffer(CAN_Type *base, uint8_t idx, mcan_rx_buffer_frame_t *rxFrame)
{
    mcan_rx_buffer_frame_t *elementAddress = 0;
    elementAddress = (mcan_rx_buffer_frame_t *)(MCAN_GetMsgRAMBase(base) + MCAN_GetRxBufferElementAddress(base, idx));
    memcpy(rxFrame, elementAddress, (rxFrame->size + 8U) * 4U);
    return kStatus_Success;
}

status_t MCAN_ReadRxFifo(CAN_Type *base, uint8_t fifoBlock, mcan_rx_buffer_frame_t *rxFrame)
{
    assert((fifoBlock == 0) || (fifoBlock == 1U));
    mcan_rx_buffer_frame_t *elementAddress = 0;
    if (0 == fifoBlock)
    {
        elementAddress = (mcan_rx_buffer_frame_t *)(MCAN_GetMsgRAMBase(base) + MCAN_GetRxFifo0ElementAddress(base));
    }
    else
    {
        elementAddress = (mcan_rx_buffer_frame_t *)(MCAN_GetMsgRAMBase(base) + MCAN_GetRxFifo1ElementAddress(base));
    }
    memcpy(rxFrame, elementAddress, 8U);
    rxFrame->data = (uint8_t *)elementAddress + 8U;
    /* Acknowledge the read. */
    if (0 == fifoBlock)
    {
        base->RXF0A = (base->RXF0S & CAN_RXF0S_F0GI_MASK) >> CAN_RXF0S_F0GI_SHIFT;
    }
    else
    {
        base->RXF1A = (base->RXF1S & CAN_RXF1S_F1GI_MASK) >> CAN_RXF1S_F1GI_SHIFT;
    }
    return kStatus_Success;
}

status_t MCAN_TransferSendBlocking(CAN_Type *base, uint8_t idx, mcan_tx_buffer_frame_t *txFrame)
{
    if (kStatus_Success == MCAN_WriteTxBuffer(base, idx, txFrame))
    {
        MCAN_TransmitAddRequest(base, idx);

        /* Wait until message sent out. */
        while (!MCAN_IsTransmitOccurred(base, idx))
        {
        }
        return kStatus_Success;
    }
    else
    {
        return kStatus_Fail;
    }
}

status_t MCAN_TransferReceiveBlocking(CAN_Type *base, uint8_t bufferIdx, mcan_rx_buffer_frame_t *rxFrame)
{
    assert(bufferIdx <= 63U);

    while (!MCAN_GetRxBufferStatusFlag(base, bufferIdx))
    {
    }
    MCAN_ClearRxBufferStatusFlag(base, bufferIdx);
    return MCAN_ReadRxBuffer(base, bufferIdx, rxFrame);
}

status_t MCAN_TransferReceiveFifoBlocking(CAN_Type *base, uint8_t fifoBlock, mcan_rx_buffer_frame_t *rxFrame)
{
    assert((fifoBlock == 0) || (fifoBlock == 1U));
    if (0 == fifoBlock)
    {
        while (!MCAN_GetStatusFlag(base, CAN_IR_RF0N_MASK))
        {
        }
        MCAN_ClearStatusFlag(base, CAN_IR_RF0N_MASK);
    }
    else
    {
        while (!MCAN_GetStatusFlag(base, CAN_IR_RF1N_MASK))
        {
        }
        MCAN_ClearStatusFlag(base, CAN_IR_RF1N_MASK);
    }
    return MCAN_ReadRxFifo(base, fifoBlock, rxFrame);
}

void MCAN_TransferCreateHandle(CAN_Type *base, mcan_handle_t *handle, mcan_transfer_callback_t callback, void *userData)
{
    assert(handle);

    uint8_t instance;

    /* Clean MCAN transfer handle. */
    memset(handle, 0, sizeof(*handle));

    /* Get instance from peripheral base address. */
    instance = MCAN_GetInstance(base);

    /* Save the context in global variables to support the double weak mechanism. */
    s_mcanHandle[instance] = handle;

    /* Register Callback function. */
    handle->callback = callback;
    handle->userData = userData;

    s_mcanIsr = MCAN_TransferHandleIRQ;

    /* We Enable Error & Status interrupt here, because this interrupt just
     * report current status of MCAN module through Callback function.
     * It is insignificance without a available callback function.
     */
    if (handle->callback != NULL)
    {
        MCAN_EnableInterrupts(base, 0,
                              kMCAN_BusOffInterruptEnable | kMCAN_ErrorInterruptEnable | kMCAN_WarningInterruptEnable);
    }
    else
    {
        MCAN_DisableInterrupts(base,
                               kMCAN_BusOffInterruptEnable | kMCAN_ErrorInterruptEnable | kMCAN_WarningInterruptEnable);
    }

    /* Enable interrupts in NVIC. */
    EnableIRQ((IRQn_Type)(s_mcanIRQ[instance][0]));
    EnableIRQ((IRQn_Type)(s_mcanIRQ[instance][1]));
}

status_t MCAN_TransferSendNonBlocking(CAN_Type *base, mcan_handle_t *handle, mcan_buffer_transfer_t *xfer)
{
    /* Assertion. */
    assert(handle);
    assert(xfer);
    assert(xfer->bufferIdx <= 63U);

    /* Check if Tx Buffer is idle. */
    if (kMCAN_StateIdle == handle->bufferState[xfer->bufferIdx])
    {
        handle->txbufferIdx = xfer->bufferIdx;
        /* Distinguish transmit type. */
        if (kMCAN_FrameTypeRemote == xfer->frame->xtd)
        {
            handle->bufferState[xfer->bufferIdx] = kMCAN_StateTxRemote;

            /* Register user Frame buffer to receive remote Frame. */
            handle->bufferFrameBuf[xfer->bufferIdx] = xfer->frame;
        }
        else
        {
            handle->bufferState[xfer->bufferIdx] = kMCAN_StateTxData;
        }

        if (kStatus_Success == MCAN_WriteTxBuffer(base, xfer->bufferIdx, xfer->frame))
        {
            /* Enable Buffer Interrupt. */
            MCAN_EnableTransmitBufferInterrupts(base, xfer->bufferIdx);
            MCAN_EnableInterrupts(base, 0, CAN_IE_TCE_MASK);

            MCAN_TransmitAddRequest(base, xfer->bufferIdx);

            return kStatus_Success;
        }
        else
        {
            handle->bufferState[xfer->bufferIdx] = kMCAN_StateIdle;
            return kStatus_Fail;
        }
    }
    else
    {
        return kStatus_MCAN_TxBusy;
    }
}

status_t MCAN_TransferReceiveFifoNonBlocking(CAN_Type *base,
                                             uint8_t fifoBlock,
                                             mcan_handle_t *handle,
                                             mcan_fifo_transfer_t *xfer)
{
    /* Assertion. */
    assert((fifoBlock == 0) || (fifoBlock == 1U));
    assert(handle);
    assert(xfer);

    /* Check if Message Buffer is idle. */
    if (kMCAN_StateIdle == handle->rxFifoState)
    {
        handle->rxFifoState = kMCAN_StateRxFifo;

        /* Register Message Buffer. */
        handle->rxFifoFrameBuf = xfer->frame;

        /* Enable FIFO Interrupt. */
        if (fifoBlock)
        {
            MCAN_EnableInterrupts(base, 0, CAN_IE_RF1NE_MASK);
        }
        else
        {
            MCAN_EnableInterrupts(base, 0, CAN_IE_RF0NE_MASK);
        }
        return kStatus_Success;
    }
    else
    {
        return fifoBlock ? kStatus_MCAN_RxFifo1Busy : kStatus_MCAN_RxFifo0Busy;
    }
}

void MCAN_TransferAbortSend(CAN_Type *base, mcan_handle_t *handle, uint8_t bufferIdx)
{
    /* Assertion. */
    assert(handle);
    assert(bufferIdx <= 63U);

    /* Disable Buffer Interrupt. */
    MCAN_DisableTransmitBufferInterrupts(base, bufferIdx);
    MCAN_DisableInterrupts(base, CAN_IE_TCE_MASK);

    /* Cancel send request. */
    MCAN_TransmitCancelRequest(base, bufferIdx);

    /* Un-register handle. */
    handle->bufferFrameBuf[bufferIdx] = 0x0;

    handle->bufferState[bufferIdx] = kMCAN_StateIdle;
}

void MCAN_TransferAbortReceiveFifo(CAN_Type *base, uint8_t fifoBlock, mcan_handle_t *handle)
{
    /* Assertion. */
    assert(handle);
    assert((fifoBlock == 0) || (fifoBlock == 1));

    /* Check if Rx FIFO is enabled. */
    if (fifoBlock)
    {
        /* Disable Rx Message FIFO Interrupts. */
        MCAN_DisableInterrupts(base, CAN_IE_RF1NE_MASK);
    }
    else
    {
        MCAN_DisableInterrupts(base, CAN_IE_RF0NE_MASK);
    }
    /* Un-register handle. */
    handle->rxFifoFrameBuf = 0x0;

    handle->rxFifoState = kMCAN_StateIdle;
}

void MCAN_TransferHandleIRQ(CAN_Type *base, mcan_handle_t *handle)
{
    /* Assertion. */
    assert(handle);

    status_t status = kStatus_MCAN_UnHandled;
    uint32_t result;

    /* Store Current MCAN Module Error and Status. */
    result = base->IR;

    do
    {
        /* Solve Rx FIFO, Tx interrupt. */
        if (result & kMCAN_TxTransmitCompleteFlag)
        {
            status = kStatus_MCAN_TxIdle;
            MCAN_TransferAbortSend(base, handle, handle->txbufferIdx);
        }
        else if (result & kMCAN_RxFifo0NewFlag)
        {
            MCAN_ReadRxFifo(base, 0, handle->rxFifoFrameBuf);
            status = kStatus_MCAN_RxFifo0Idle;
            MCAN_TransferAbortReceiveFifo(base, 0, handle);
        }
        else if (result & kMCAN_RxFifo0LostFlag)
        {
            status = kStatus_MCAN_RxFifo0Lost;
        }
        else if (result & kMCAN_RxFifo1NewFlag)
        {
            MCAN_ReadRxFifo(base, 1, handle->rxFifoFrameBuf);
            status = kStatus_MCAN_RxFifo1Idle;
            MCAN_TransferAbortReceiveFifo(base, 1, handle);
        }
        else if (result & kMCAN_RxFifo1LostFlag)
        {
            status = kStatus_MCAN_RxFifo0Lost;
        }
        else
        {
            ;
        }

        /* Clear resolved Rx FIFO, Tx Buffer IRQ. */
        MCAN_ClearStatusFlag(base, result);

        /* Calling Callback Function if has one. */
        if (handle->callback != NULL)
        {
            handle->callback(base, handle, status, result, handle->userData);
        }

        /* Reset return status */
        status = kStatus_MCAN_UnHandled;

        /* Store Current MCAN Module Error and Status. */
        result = base->IR;
    } while ((0 != MCAN_GetStatusFlag(base, 0xFFFFFFFFU)) ||
             (0 != (result & (kMCAN_ErrorWarningIntFlag | kMCAN_BusOffIntFlag | kMCAN_ErrorPassiveIntFlag))));
}

#if defined(CAN0)
void CAN0_IRQ0_DriverIRQHandler(void)
{
    assert(s_mcanHandle[0]);

    s_mcanIsr(CAN0, s_mcanHandle[0]);
}

void CAN0_IRQ1_DriverIRQHandler(void)
{
    assert(s_mcanHandle[0]);

    s_mcanIsr(CAN0, s_mcanHandle[0]);
}
#endif

#if defined(CAN1)
void CAN1_IRQ0_DriverIRQHandler(void)
{
    assert(s_mcanHandle[1]);

    s_mcanIsr(CAN1, s_mcanHandle[1]);
}

void CAN1_IRQ1_DriverIRQHandler(void)
{
    assert(s_mcanHandle[1]);

    s_mcanIsr(CAN1, s_mcanHandle[1]);
}
#endif


text:
@interface IBDocumentLayoutConstraintAbstraction (IBDocumentLayoutConstraintAbstraction)
+ (id)ibDefaultImageForInstance:(id)arg1;
- (id)ibMemberToHighlightInUI;
- (id)ibDefaultLabel;
@end