text:
/**
 * @file
 *   This file includes definitions for the message buffer pool and message buffers.
 */

#ifndef MESSAGE_HPP_
#define MESSAGE_HPP_

#include "openthread-core-config.h"

#include <stdint.h>

#include <openthread/message.h>
#include <openthread/platform/messagepool.h>

#include "common/code_utils.hpp"
#include "common/encoding.hpp"
#include "common/linked_list.hpp"
#include "common/locator.hpp"
#include "common/non_copyable.hpp"
#include "mac/mac_types.hpp"
#include "thread/link_quality.hpp"

namespace ot {

/**
 * @addtogroup core-message
 *
 * @brief
 *   This module includes definitions for the message buffer pool and message buffers.
 *
 * @{
 *
 */

enum
{
    kNumBuffers     = OPENTHREAD_CONFIG_NUM_MESSAGE_BUFFERS,
    kBufferSize     = OPENTHREAD_CONFIG_MESSAGE_BUFFER_SIZE,
    kChildMaskBytes = BitVectorBytes(OPENTHREAD_CONFIG_MLE_MAX_CHILDREN),
};

class Message;
class MessagePool;
class MessageQueue;
class PriorityQueue;

/**
 * This structure contains metadata about a Message.
 *
 */
struct MessageMetadata
{
    Message *    mNext;        ///< A pointer to the next Message in a doubly linked list.
    Message *    mPrev;        ///< A pointer to the previous Message in a doubly linked list.
    MessagePool *mMessagePool; ///< Identifies the message pool for this message.
    union
    {
        MessageQueue * mMessage;  ///< Identifies the message queue (if any) where this message is queued.
        PriorityQueue *mPriority; ///< Identifies the priority queue (if any) where this message is queued.
    } mQueue;                     ///< Identifies the queue (if any) where this message is queued.

    uint32_t mDatagramTag;    ///< The datagram tag used for 6LoWPAN fragmentation or identification used for IPv6
                              ///< fragmentation.
    uint16_t    mReserved;    ///< Number of header bytes reserved for the message.
    uint16_t    mLength;      ///< Number of bytes within the message.
    uint16_t    mOffset;      ///< A byte offset within the message.
    RssAverager mRssAverager; ///< The averager maintaining the received signal strength (RSS) average.

    uint8_t  mChildMask[kChildMaskBytes]; ///< A bit-vector to indicate which sleepy children need to receive this.
    uint16_t mMeshDest;                   ///< Used for unicast non-link-local messages.
    uint8_t  mTimeout;                    ///< Seconds remaining before dropping the message.
    union
    {
        uint16_t mPanId;   ///< Used for MLE Discover Request and Response messages.
        uint8_t  mChannel; ///< Used for MLE Announce.
    } mPanIdChannel;       ///< Used for MLE Discover Request, Response, and Announce messages.

    uint8_t mType : 2;         ///< Identifies the type of message.
    uint8_t mSubType : 4;      ///< Identifies the message sub type.
    bool    mDirectTx : 1;     ///< Used to indicate whether a direct transmission is required.
    bool    mLinkSecurity : 1; ///< Indicates whether or not link security is enabled.
    uint8_t mPriority : 2;     ///< Identifies the message priority level (higher value is higher priority).
    bool    mInPriorityQ : 1;  ///< Indicates whether the message is queued in normal or priority queue.
    bool    mTxSuccess : 1;    ///< Indicates whether the direct tx of the message was successful.
    bool    mDoNotEvict : 1;   ///< Indicates whether or not this message may be evicted.
#if OPENTHREAD_CONFIG_TIME_SYNC_ENABLE
    bool    mTimeSync : 1;      ///< Indicates whether the message is also used for time sync purpose.
    uint8_t mTimeSyncSeq;       ///< The time sync sequence.
    int64_t mNetworkTimeOffset; ///< The time offset to the Thread network time, in microseconds.
#endif
};

/**
 * This class represents a Message buffer.
 *
 */
class Buffer : public otMessage, public LinkedListEntry<Buffer>
{
    friend class Message;

public:
    /**
     * This method returns a pointer to the next message buffer.
     *
     * @returns A pointer to the next message buffer.
     *
     */
    Buffer *GetNextBuffer(void) { return GetNext(); }

    /**
     * This method returns a pointer to the next message buffer.
     *
     * @returns A pointer to the next message buffer.
     *
     */
    const Buffer *GetNextBuffer(void) const { return GetNext(); }

    /**
     * This method sets the pointer to the next message buffer.
     *
     * @param[in] aNext  A pointer to the next buffer.
     *
     */
    void SetNextBuffer(Buffer *aNext) { SetNext(aNext); }

private:
    /**
     * This method returns the message metadata in the first message buffer.
     *
     * @returns The message metadata structure.
     *
     */
    MessageMetadata &GetMetadata(void) { return mBuffer.mHead.mMetadata; }

    /**
     * This method returns the message metadata in the first message buffer.
     *
     * @returns The message metadata structure.
     *
     */
    const MessageMetadata &GetMetadata(void) const { return mBuffer.mHead.mMetadata; }

    /**
     * This method returns a pointer to the first byte of data in the first message buffer.
     *
     * @returns A pointer to the first data byte.
     *
     */
    uint8_t *GetFirstData(void) { return mBuffer.mHead.mData; }

    /**
     * This method returns a pointer to the first byte of data in the first message buffer.
     *
     * @returns A pointer to the first data byte.
     *
     */
    const uint8_t *GetFirstData(void) const { return mBuffer.mHead.mData; }

    /**
     * This method returns a pointer to the first data byte of a subsequent message buffer.
     *
     * @returns A pointer to the first data byte.
     *
     */
    uint8_t *GetData(void) { return mBuffer.mData; }

    /**
     * This method returns a pointer to the first data byte of a subsequent message buffer.
     *
     * @returns A pointer to the first data byte.
     *
     */
    const uint8_t *GetData(void) const { return mBuffer.mData; }

    enum
    {
        kBufferDataSize     = kBufferSize - sizeof(otMessage),
        kHeadBufferDataSize = kBufferDataSize - sizeof(MessageMetadata),
    };

protected:
    union
    {
        struct
        {
            MessageMetadata mMetadata;
            uint8_t         mData[kHeadBufferDataSize];
        } mHead;
        uint8_t mData[kBufferDataSize];
    } mBuffer;
};

/**
 * This class represents a message.
 *
 */
class Message : public Buffer
{
    friend class MessagePool;
    friend class MessageQueue;
    friend class PriorityQueue;

public:
    /**
     * This enumeration represents the message type.
     *
     */
    enum Type
    {
        kTypeIp6         = 0, ///< A full uncompressed IPv6 packet
        kType6lowpan     = 1, ///< A 6lowpan frame
        kTypeSupervision = 2, ///< A child supervision frame.
        kTypeOther       = 3, ///< Other (data) message.
    };

    /**
     * This enumeration represents the message sub-type.
     *
     */
    enum SubType
    {
        kSubTypeNone                   = 0,  ///< None
        kSubTypeMleAnnounce            = 1,  ///< MLE Announce
        kSubTypeMleDiscoverRequest     = 2,  ///< MLE Discover Request
        kSubTypeMleDiscoverResponse    = 3,  ///< MLE Discover Response
        kSubTypeJoinerEntrust          = 4,  ///< Joiner Entrust
        kSubTypeMplRetransmission      = 5,  ///< MPL next retransmission message
        kSubTypeMleGeneral             = 6,  ///< General MLE
        kSubTypeJoinerFinalizeResponse = 7,  ///< Joiner Finalize Response
        kSubTypeMleChildUpdateRequest  = 8,  ///< MLE Child Update Request
        kSubTypeMleDataResponse        = 9,  ///< MLE Data Response
        kSubTypeMleChildIdRequest      = 10, ///< MLE Child ID Request
    };

    enum Priority
    {
        kPriorityLow    = OT_MESSAGE_PRIORITY_LOW,      ///< Low priority level.
        kPriorityNormal = OT_MESSAGE_PRIORITY_NORMAL,   ///< Normal priority level.
        kPriorityHigh   = OT_MESSAGE_PRIORITY_HIGH,     ///< High priority level.
        kPriorityNet    = OT_MESSAGE_PRIORITY_HIGH + 1, ///< Network Control priority level.
    };

    enum
    {
        kNumPriorities = 4, ///< Number of priority levels.
    };

    /**
     * This enumeration represents the link security mode (used by `Settings` constructor).
     *
     */
    enum LinkSecurityMode
    {
        kNoLinkSecurity,   ///< Link security disabled (no link security).
        kWithLinkSecurity, ///< Link security enabled.
    };

    /**
     * This class represents settings used for creating a new message.
     *
     */
    class Settings
    {
    public:
        /**
         * This constructor initializes the Settings object.
         *
         * @param[in]  aSecurityMode  A link security mode.
         * @param[in]  aPriority      A message priority.
         *
         */
        Settings(LinkSecurityMode aSecurityMode, Priority aPriority);

        /**
         * This constructor initializes the `Settings` object from a given `otMessageSettings`.
         *
         * @param[in] aSettings  A pointer to `otMessageSettings` to covert from. If nullptr default settings (link
         *                       security enabled with `kPriorityNormal` priority) would be used.
         *
         */
        Settings(const otMessageSettings *aSettings);

        /**
         * This method gets the message priority.
         *
         * @returns The message priority.
         *
         */
        Priority GetPriority(void) const { return mPriority; }

        /**
         * This method indicates whether the link security should be enabled.
         *
         * @returns TRUE if link security should be enabled, FALSE otherwise.
         *
         */
        bool IsLinkSecurityEnabled(void) const { return mLinkSecurityEnabled; }

        /**
         * This static method returns the default settings with link security enabled and `kPriorityNormal` priority.
         *
         * @returns A reference to the default settings (link security enable and `kPriorityNormal` priority).
         *
         */
        static const Settings &GetDefault(void) { return kDefault; }

    private:
        static const Settings kDefault;

        bool     mLinkSecurityEnabled;
        Priority mPriority;
    };

    /**
     * This method frees this message buffer.
     *
     */
    void Free(void);

    /**
     * This method returns a pointer to the next message.
     *
     * @returns A pointer to the next message in the list or nullptr if at the end of the list.
     *
     */
    Message *GetNext(void) const;

    /**
     * This method returns the number of bytes in the message.
     *
     * @returns The number of bytes in the message.
     */
    uint16_t GetLength(void) const { return GetMetadata().mLength; }

    /**
     * This method sets the number of bytes in the message.
     *
     * @param[in]  aLength  Requested number of bytes in the message.
     *
     * @retval OT_ERROR_NONE     Successfully set the length of the message.
     * @retval OT_ERROR_NO_BUFS  Failed to grow the size of the message because insufficient buffers were available.
     *
     */
    otError SetLength(uint16_t aLength);

    /**
     * This method returns the number of buffers in the message.
     *
     */
    uint8_t GetBufferCount(void) const;

    /**
     * This method returns the byte offset within the message.
     *
     * @returns A byte offset within the message.
     *
     */
    uint16_t GetOffset(void) const { return GetMetadata().mOffset; }

    /**
     * This method moves the byte offset within the message.
     *
     * @param[in]  aDelta  The number of bytes to move the current offset, which may be positive or negative.
     *
     */
    void MoveOffset(int aDelta);

    /**
     * This method sets the byte offset within the message.
     *
     * @param[in]  aOffset  The byte offset within the message.
     *
     */
    void SetOffset(uint16_t aOffset);

    /**
     * This method returns the type of the message.
     *
     * @returns The type of the message.
     *
     */
    Type GetType(void) const { return static_cast<Type>(GetMetadata().mType); }

    /**
     * This method sets the message type.
     *
     * @param[in]  aType  The message type.
     *
     */
    void SetType(Type aType) { GetMetadata().mType = aType; }

    /**
     * This method returns the sub type of the message.
     *
     * @returns The sub type of the message.
     *
     */
    SubType GetSubType(void) const { return static_cast<SubType>(GetMetadata().mSubType); }

    /**
     * This method sets the message sub type.
     *
     * @param[in]  aSubType  The message sub type.
     *
     */
    void SetSubType(SubType aSubType) { GetMetadata().mSubType = aSubType; }

    /**
     * This method returns whether or not the message is of MLE subtype.
     *
     * @retval TRUE   If message is of MLE subtype.
     * @retval FALSE  If message is not of MLE subtype.
     *
     */
    bool IsSubTypeMle(void) const;

    /**
     * This method returns the message priority level.
     *
     * @returns The priority level associated with this message.
     *
     */
    Priority GetPriority(void) const { return static_cast<Priority>(GetMetadata().mPriority); }

    /**
     * This method sets the messages priority.
     * If the message is already queued in a priority queue, changing the priority ensures to
     * update the message in the associated queue.
     *
     * @param[in]  aPriority  The message priority level.
     *
     * @retval OT_ERROR_NONE           Successfully set the priority for the message.
     * @retval OT_ERROR_INVALID_ARGS   Priority level is not invalid.
     *
     */
    otError SetPriority(Priority aPriority);

    /**
     * This method prepends bytes to the front of the message.
     *
     * On success, this method grows the message by @p aLength bytes.
     *
     * @param[in]  aBuf     A pointer to a data buffer.
     * @param[in]  aLength  The number of bytes to prepend.
     *
     * @retval OT_ERROR_NONE     Successfully prepended the bytes.
     * @retval OT_ERROR_NO_BUFS  Not enough reserved bytes in the message.
     *
     */
    otError Prepend(const void *aBuf, uint16_t aLength);

    /**
     * This method removes header bytes from the message.
     *
     * @param[in]  aLength  Number of header bytes to remove.
     *
     */
    void RemoveHeader(uint16_t aLength);

    /**
     * This method appends bytes to the end of the message.
     *
     * On success, this method grows the message by @p aLength bytes.
     *
     * @param[in]  aBuf     A pointer to a data buffer.
     * @param[in]  aLength  The number of bytes to append.
     *
     * @retval OT_ERROR_NONE     Successfully appended the bytes.
     * @retval OT_ERROR_NO_BUFS  Insufficient available buffers to grow the message.
     *
     */
    otError Append(const void *aBuf, uint16_t aLength);

    /**
     * This method reads bytes from the message.
     *
     * @param[in]  aOffset  Byte offset within the message to begin reading.
     * @param[in]  aLength  Number of bytes to read.
     * @param[in]  aBuf     A pointer to a data buffer.
     *
     * @returns The number of bytes read.
     *
     */
    uint16_t Read(uint16_t aOffset, uint16_t aLength, void *aBuf) const;

    /**
     * This method writes bytes to the message.
     *
     * @param[in]  aOffset  Byte offset within the message to begin writing.
     * @param[in]  aLength  Number of bytes to write.
     * @param[in]  aBuf     A pointer to a data buffer.
     *
     * @returns The number of bytes written.
     *
     */
    int Write(uint16_t aOffset, uint16_t aLength, const void *aBuf);

    /**
     * This method copies bytes from one message to another.
     *
     * @param[in] aSourceOffset       Byte offset within the source message to begin reading.
     * @param[in] aDestinationOffset  Byte offset within the destination message to begin writing.
     * @param[in] aLength             Number of bytes to copy.
     * @param[in] aMessage            Message to copy to.
     *
     * @returns The number of bytes copied.
     *
     */
    int CopyTo(uint16_t aSourceOffset, uint16_t aDestinationOffset, uint16_t aLength, Message &aMessage) const;

    /**
     * This method creates a copy of the message.
     *
     * It allocates the new message from the same message pool as the original one and copies @p aLength octets
     * of the payload. The `Type`, `SubType`, `LinkSecurity`, `Offset`, `InterfaceId`, and `Priority` fields on the
     * cloned message are also copied from the original one.
     *
     * @param[in] aLength  Number of payload bytes to copy.
     *
     * @returns A pointer to the message or nullptr if insufficient message buffers are available.
     *
     */
    Message *Clone(uint16_t aLength) const;

    /**
     * This method creates a copy of the message.
     *
     * It allocates the new message from the same message pool as the original one and copies the entire payload. The
     * `Type`, `SubType`, `LinkSecurity`, `Offset`, `InterfaceId`, and `Priority` fields on the cloned message are also
     * copied from the original one.
     *
     * @returns A pointer to the message or nullptr if insufficient message buffers are available.
     *
     */
    Message *Clone(void) const { return Clone(GetLength()); }

    /**
     * This method returns the datagram tag used for 6LoWPAN fragmentation or the identification used for IPv6
     * fragmentation.
     *
     * @returns The 6LoWPAN datagram tag or the IPv6 fragment identification.
     *
     */
    uint32_t GetDatagramTag(void) const { return GetMetadata().mDatagramTag; }

    /**
     * This method sets the datagram tag used for 6LoWPAN fragmentation.
     *
     * @param[in]  aTag  The 6LoWPAN datagram tag.
     *
     */
    void SetDatagramTag(uint32_t aTag) { GetMetadata().mDatagramTag = aTag; }

    /**
     * This method returns whether or not the message forwarding is scheduled for the child.
     *
     * @param[in]  aChildIndex  The index into the child table.
     *
     * @retval TRUE   If the message is scheduled to be forwarded to the child.
     * @retval FALSE  If the message is not scheduled to be forwarded to the child.
     *
     */
    bool GetChildMask(uint16_t aChildIndex) const;

    /**
     * This method unschedules forwarding of the message to the child.
     *
     * @param[in]  aChildIndex  The index into the child table.
     *
     */
    void ClearChildMask(uint16_t aChildIndex);

    /**
     * This method schedules forwarding of the message to the child.
     *
     * @param[in]  aChildIndex  The index into the child table.
     *
     */
    void SetChildMask(uint16_t aChildIndex);

    /**
     * This method returns whether or not the message forwarding is scheduled for at least one child.
     *
     * @retval TRUE   If message forwarding is scheduled for at least one child.
     * @retval FALSE  If message forwarding is not scheduled for any child.
     *
     */
    bool IsChildPending(void) const;

    /**
     * This method returns the RLOC16 of the mesh destination.
     *
     * @note Only use this for non-link-local unicast messages.
     *
     * @returns The IEEE 802.15.4 Destination PAN ID.
     *
     */
    uint16_t GetMeshDest(void) const { return GetMetadata().mMeshDest; }

    /**
     * This method sets the RLOC16 of the mesh destination.
     *
     * @note Only use this when sending non-link-local unicast messages.
     *
     * @param[in]  aMeshDest  The IEEE 802.15.4 Destination PAN ID.
     *
     */
    void SetMeshDest(uint16_t aMeshDest) { GetMetadata().mMeshDest = aMeshDest; }

    /**
     * This method returns the IEEE 802.15.4 Destination PAN ID.
     *
     * @note Only use this when sending MLE Discover Request or Response messages.
     *
     * @returns The IEEE 802.15.4 Destination PAN ID.
     *
     */
    uint16_t GetPanId(void) const { return GetMetadata().mPanIdChannel.mPanId; }

    /**
     * This method sets the IEEE 802.15.4 Destination PAN ID.
     *
     * @note Only use this when sending MLE Discover Request or Response messages.
     *
     * @param[in]  aPanId  The IEEE 802.15.4 Destination PAN ID.
     *
     */
    void SetPanId(uint16_t aPanId) { GetMetadata().mPanIdChannel.mPanId = aPanId; }

    /**
     * This method returns the IEEE 802.15.4 Channel to use for transmission.
     *
     * @note Only use this when sending MLE Announce messages.
     *
     * @returns The IEEE 802.15.4 Channel to use for transmission.
     *
     */
    uint8_t GetChannel(void) const { return GetMetadata().mPanIdChannel.mChannel; }

    /**
     * This method sets the IEEE 802.15.4 Channel to use for transmission.
     *
     * @note Only use this when sending MLE Announce messages.
     *
     * @param[in]  aChannel  The IEEE 802.15.4 Channel to use for transmission.
     *
     */
    void SetChannel(uint8_t aChannel) { GetMetadata().mPanIdChannel.mChannel = aChannel; }

    /**
     * This method returns the timeout used for 6LoWPAN reassembly.
     *
     * @returns The time remaining in seconds.
     *
     */
    uint8_t GetTimeout(void) const { return GetMetadata().mTimeout; }

    /**
     * This method sets the timeout used for 6LoWPAN reassembly.
     *
     * @param[in]  aTimeout  The timeout value.
     *
     */
    void SetTimeout(uint8_t aTimeout) { GetMetadata().mTimeout = aTimeout; }

    /**
     * This method decrements the timeout.
     *
     */
    void DecrementTimeout(void) { GetMetadata().mTimeout--; }

    /**
     * This method returns whether or not message forwarding is scheduled for direct transmission.
     *
     * @retval TRUE   If message forwarding is scheduled for direct transmission.
     * @retval FALSE  If message forwarding is not scheduled for direct transmission.
     *
     */
    bool GetDirectTransmission(void) const { return GetMetadata().mDirectTx; }

    /**
     * This method unschedules forwarding using direct transmission.
     *
     */
    void ClearDirectTransmission(void) { GetMetadata().mDirectTx = false; }

    /**
     * This method schedules forwarding using direct transmission.
     *
     */
    void SetDirectTransmission(void) { GetMetadata().mDirectTx = true; }

    /**
     * This method indicates whether the direct transmission of message was successful.
     *
     * @retval TRUE   If direct transmission of message was successful (all fragments were delivered and acked).
     * @retval FALSE  If direct transmission of message failed (at least one fragment failed).
     *
     */
    bool GetTxSuccess(void) const { return GetMetadata().mTxSuccess; }

    /**
     * This method sets whether the direct transmission of message was successful.
     *
     * @param[in] aTxSuccess   TRUE if the direct transmission is successful, FALSE otherwise (i.e., at least one
     *                         fragment transmission failed).
     *
     */
    void SetTxSuccess(bool aTxSuccess) { GetMetadata().mTxSuccess = aTxSuccess; }

    /**
     * This method indicates whether the message may be evicted.
     *
     * @retval TRUE   If the message must not be evicted.
     * @retval FALSE  If the message may be evicted.
     *
     */
    bool GetDoNotEvict(void) const { return GetMetadata().mDoNotEvict; }

    /**
     * This method sets whether the message may be evicted.
     *
     * @param[in]  aDoNotEvict  TRUE if the message may not be evicted, FALSE otherwise.
     *
     */
    void SetDoNotEvict(bool aDoNotEvict) { GetMetadata().mDoNotEvict = aDoNotEvict; }

    /**
     * This method indicates whether or not link security is enabled for the message.
     *
     * @retval TRUE   If link security is enabled.
     * @retval FALSE  If link security is not enabled.
     *
     */
    bool IsLinkSecurityEnabled(void) const { return GetMetadata().mLinkSecurity; }

    /**
     * This method sets whether or not link security is enabled for the message.
     *
     * @param[in]  aEnabled  TRUE if link security is enabled, FALSE otherwise.
     *
     */
    void SetLinkSecurityEnabled(bool aEnabled) { GetMetadata().mLinkSecurity = aEnabled; }

    /**
     * This method updates the average RSS (Received Signal Strength) associated with the message by adding the given
     * RSS value to the average. Note that a message can be composed of multiple 802.15.4 data frame fragments each
     * received with a different signal strength.
     *
     * @param[in] aRss A new RSS value (in dBm) to be added to average.
     *
     */
    void AddRss(int8_t aRss) { IgnoreError(GetMetadata().mRssAverager.Add(aRss)); }

    /**
     * This method returns the average RSS (Received Signal Strength) associated with the message.
     *
     * @returns The current average RSS value (in dBm) or OT_RADIO_RSSI_INVALID if no average is available.
     *
     */
    int8_t GetAverageRss(void) const { return GetMetadata().mRssAverager.GetAverage(); }

    /**
     * This method returns a const reference to RssAverager of the message.
     *
     * @returns A const reference to the RssAverager of the message.
     *
     */
    const RssAverager &GetRssAverager(void) const { return GetMetadata().mRssAverager; }

    /**
     * This static method updates a checksum.
     *
     * @param[in]  aChecksum  The checksum value to update.
     * @param[in]  aValue     The 16-bit value to update @p aChecksum with.
     *
     * @returns The updated checksum.
     *
     */
    static uint16_t UpdateChecksum(uint16_t aChecksum, uint16_t aValue);

    /**
     * This static method updates a checksum.
     *
     * @param[in]  aChecksum  The checksum value to update.
     * @param[in]  aBuf       A pointer to a buffer.
     * @param[in]  aLength    The number of bytes in @p aBuf.
     *
     * @returns The updated checksum.
     *
     */
    static uint16_t UpdateChecksum(uint16_t aChecksum, const void *aBuf, uint16_t aLength);

    /**
     * This method is used to update a checksum value.
     *
     * @param[in]  aChecksum  Initial checksum value.
     * @param[in]  aOffset    Byte offset within the message to begin checksum computation.
     * @param[in]  aLength    Number of bytes to compute the checksum over.
     *
     * @retval The updated checksum value.
     *
     */
    uint16_t UpdateChecksum(uint16_t aChecksum, uint16_t aOffset, uint16_t aLength) const;

    /**
     * This method returns a pointer to the message queue (if any) where this message is queued.
     *
     * @returns A pointer to the message queue or nullptr if not in any message queue.
     *
     */
    MessageQueue *GetMessageQueue(void) const
    {
        return (!GetMetadata().mInPriorityQ) ? GetMetadata().mQueue.mMessage : nullptr;
    }

    /**
     * This method returns a pointer to the priority message queue (if any) where this message is queued.
     *
     * @returns A pointer to the priority queue or nullptr if not in any priority queue.
     *
     */
    PriorityQueue *GetPriorityQueue(void) const
    {
        return (GetMetadata().mInPriorityQ) ? GetMetadata().mQueue.mPriority : nullptr;
    }

    /**
     * This method indicates whether or not the message is also used for time sync purpose.
     *
     * When OPENTHREAD_CONFIG_TIME_SYNC_ENABLE is 0, this method always return false.
     *
     * @retval TRUE   If the message is also used for time sync purpose.
     * @retval FALSE  If the message is not used for time sync purpose.
     *
     */
    bool IsTimeSync(void) const;

#if OPENTHREAD_CONFIG_TIME_SYNC_ENABLE
    /**
     * This method sets whether or not the message is also used for time sync purpose.
     *
     * @param[in]  aEnabled  TRUE if the message is also used for time sync purpose, FALSE otherwise.
     *
     */
    void SetTimeSync(bool aEnabled) { GetMetadata().mTimeSync = aEnabled; }

    /**
     * This method sets the offset to network time.
     *
     * @param[in]  aNetworkTimeOffset  The offset to network time.
     *
     */
    void SetNetworkTimeOffset(int64_t aNetworkTimeOffset) { GetMetadata().mNetworkTimeOffset = aNetworkTimeOffset; }

    /**
     * This method gets the offset to network time.
     *
     * @returns  The offset to network time.
     *
     */
    int64_t GetNetworkTimeOffset(void) const { return GetMetadata().mNetworkTimeOffset; }

    /**
     * This method sets the time sync sequence.
     *
     * @param[in]  aTimeSyncSeq  The time sync sequence.
     *
     */
    void SetTimeSyncSeq(uint8_t aTimeSyncSeq) { GetMetadata().mTimeSyncSeq = aTimeSyncSeq; }

    /**
     * This method gets the time sync sequence.
     *
     * @returns  The time sync sequence.
     *
     */
    uint8_t GetTimeSyncSeq(void) const { return GetMetadata().mTimeSyncSeq; }
#endif // OPENTHREAD_CONFIG_TIME_SYNC_ENABLE

private:
    /**
     * This method returns a pointer to the message pool to which this message belongs
     *
     * @returns A pointer to the message pool.
     *
     */
    MessagePool *GetMessagePool(void) const { return GetMetadata().mMessagePool; }

    /**
     * This method sets the message pool this message to which this message belongs.
     *
     * @param[in] aMessagePool  A pointer to the message pool
     *
     */
    void SetMessagePool(MessagePool *aMessagePool) { GetMetadata().mMessagePool = aMessagePool; }

    /**
     * This method returns `true` if the message is enqueued in any queue (`MessageQueue` or `PriorityQueue`).
     *
     * @returns `true` if the message is in any queue, `false` otherwise.
     *
     */
    bool IsInAQueue(void) const { return (GetMetadata().mQueue.mMessage != nullptr); }

    /**
     * This method sets the message queue information for the message.
     *
     * @param[in]  aMessageQueue  A pointer to the message queue where this message is queued.
     *
     */
    void SetMessageQueue(MessageQueue *aMessageQueue);

    /**
     * This method sets the message queue information for the message.
     *
     * @param[in]  aPriorityQueue  A pointer to the priority queue where this message is queued.
     *
     */
    void SetPriorityQueue(PriorityQueue *aPriorityQueue);

    /**
     * This method returns a reference to the `mNext` pointer.
     *
     * @returns A reference to the mNext pointer.
     *
     */
    Message *&Next(void) { return GetMetadata().mNext; }

    /**
     * This method returns a reference to the `mNext` pointer (const pointer).
     *
     *
     * @returns A reference to the mNext pointer.
     *
     */
    Message *const &Next(void) const { return GetMetadata().mNext; }

    /**
     * This method returns a reference to the `mPrev` pointer.
     *
     * @returns A reference to the mPrev pointer.
     *
     */
    Message *&Prev(void) { return GetMetadata().mPrev; }

    /**
     * This method returns the number of reserved header bytes.
     *
     * @returns The number of reserved header bytes.
     *
     */
    uint16_t GetReserved(void) const { return GetMetadata().mReserved; }

    /**
     * This method sets the number of reserved header bytes.
     *
     * @param[in] aReservedHeader  The number of header bytes to reserve.
     *
     */
    void SetReserved(uint16_t aReservedHeader) { GetMetadata().mReserved = aReservedHeader; }

    /**
     * This method adds or frees message buffers to meet the requested length.
     *
     * @param[in]  aLength  The number of bytes that the message buffer needs to handle.
     *
     * @retval OT_ERROR_NONE     Successfully resized the message.
     * @retval OT_ERROR_NO_BUFS  Could not grow the message due to insufficient available message buffers.
     *
     */
    otError ResizeMessage(uint16_t aLength);
};

/**
 * This class implements a message queue.
 *
 */
class MessageQueue : public otMessageQueue
{
    friend class Message;
    friend class PriorityQueue;

public:
    /**
     * This enumeration represents a position (head or tail) in the queue. This is used to specify where a new message
     * should be added in the queue.
     *
     */
    enum QueuePosition
    {
        kQueuePositionHead, ///< Indicates the head (front) of the list.
        kQueuePositionTail, ///< Indicates the tail (end) of the list.
    };

    /**
     * This constructor initializes the message queue.
     *
     */
    MessageQueue(void);

    /**
     * This method returns a pointer to the first message.
     *
     * @returns A pointer to the first message.
     *
     */
    Message *GetHead(void) const;

    /**
     * This method adds a message to the end of the list.
     *
     * @param[in]  aMessage  The message to add.
     *
     */
    void Enqueue(Message &aMessage) { Enqueue(aMessage, kQueuePositionTail); }

    /**
     * This method adds a message at a given position (head/tail) of the list.
     *
     * @param[in]  aMessage  The message to add.
     * @param[in]  aPosition The position (head or tail) where to add the message.
     *
     */
    void Enqueue(Message &aMessage, QueuePosition aPosition);

    /**
     * This method removes a message from the list.
     *
     * @param[in]  aMessage  The message to remove.
     *
     */
    void Dequeue(Message &aMessage);

    /**
     * This method returns the number of messages and buffers enqueued.
     *
     * @param[out]  aMessageCount  Returns the number of messages enqueued.
     * @param[out]  aBufferCount   Returns the number of buffers enqueued.
     *
     */
    void GetInfo(uint16_t &aMessageCount, uint16_t &aBufferCount) const;

private:
    /**
     * This method returns the tail of the list (last message in the list)
     *
     * @returns A pointer to the tail of the list.
     *
     */
    Message *GetTail(void) const { return static_cast<Message *>(mData); }

    /**
     * This method set the tail of the list.
     *
     * @param[in]  aMessage  A pointer to the message to set as new tail.
     *
     */
    void SetTail(Message *aMessage) { mData = aMessage; }
};

/**
 * This class implements a priority queue.
 *
 */
class PriorityQueue
{
    friend class Message;
    friend class MessageQueue;
    friend class MessagePool;

public:
    /**
     * This constructor initializes the priority queue.
     *
     */
    PriorityQueue(void);

    /**
     * This method returns a pointer to the first message.
     *
     * @returns A pointer to the first message.
     *
     */
    Message *GetHead(void) const;

    /**
     * This method returns a pointer to the first message for a given priority level.
     *
     * @param[in] aPriority   Priority level.
     *
     * @returns A pointer to the first message with given priority level or nullptr if there is no messages with
     *          this priority level.
     *
     */
    Message *GetHeadForPriority(Message::Priority aPriority) const;

    /**
     * This method adds a message to the queue.
     *
     * @param[in]  aMessage  The message to add.
     *
     */
    void Enqueue(Message &aMessage);

    /**
     * This method removes a message from the list.
     *
     * @param[in]  aMessage  The message to remove.
     *
     */
    void Dequeue(Message &aMessage);

    /**
     * This method returns the number of messages and buffers enqueued.
     *
     * @param[out]  aMessageCount  Returns the number of messages enqueued.
     * @param[out]  aBufferCount   Returns the number of buffers enqueued.
     *
     */
    void GetInfo(uint16_t &aMessageCount, uint16_t &aBufferCount) const;

    /**
     * This method returns the tail of the list (last message in the list)
     *
     * @returns A pointer to the tail of the list.
     *
     */
    Message *GetTail(void) const;

private:
    /**
     * This method increases (moves forward) the given priority while ensuring to wrap from
     * priority value `kNumPriorities` -1 back to 0.
     *
     * @param[in] aPriority  A given priority level
     *
     * @returns Increased/Moved forward priority level
     */
    uint8_t PrevPriority(uint8_t aPriority) const
    {
        return (aPriority == Message::kNumPriorities - 1) ? 0 : (aPriority + 1);
    }

    /**
     * This private method finds the first non-nullptr tail starting from the given priority level and moving forward.
     * It wraps from priority value `kNumPriorities` -1 back to 0.
     *
     * aStartPriorityLevel  Starting priority level.
     *
     * @returns The first non-nullptr tail pointer, or nullptr if all the
     *
     */
    Message *FindFirstNonNullTail(Message::Priority aStartPriorityLevel) const;

private:
    Message *mTails[Message::kNumPriorities]; ///< Tail pointers associated with different priority levels.
};

/**
 * This class represents a message pool
 *
 */
class MessagePool : public InstanceLocator, private NonCopyable
{
    friend class Message;
    friend class MessageQueue;
    friend class PriorityQueue;

public:
    /**
     * This constructor initializes the object.
     *
     */
    explicit MessagePool(Instance &aInstance);

    /**
     * This method is used to obtain a new message.
     *
     * The link security is enabled by default on the newly obtained message.
     *
     * @param[in]  aType           The message type.
     * @param[in]  aReserveHeader  The number of header bytes to reserve.
     * @param[in]  aPriority       The priority level of the message.
     *
     * @returns A pointer to the message or nullptr if no message buffers are available.
     *
     */
    Message *New(Message::Type aType, uint16_t aReserveHeader, Message::Priority aPriority);

public:
    /**
     * This method is used to obtain a new message with specified settings.
     *
     * @param[in]  aType           The message type.
     * @param[in]  aReserveHeader  The number of header bytes to reserve.
     * @param[in]  aSettings       The message settings.
     *
     * @returns A pointer to the message or nullptr if no message buffers are available.
     *
     */
    Message *New(Message::Type            aType,
                 uint16_t                 aReserveHeader,
                 const Message::Settings &aSettings = Message::Settings::GetDefault());

    /**
     * This method is used to free a message and return all message buffers to the buffer pool.
     *
     * @param[in]  aMessage  The message to free.
     *
     */
    void Free(Message *aMessage);

    /**
     * This method returns the number of free buffers.
     *
     * @returns The number of free buffers.
     *
     */
    uint16_t GetFreeBufferCount(void) const;

private:
    Buffer *NewBuffer(Message::Priority aPriority);
    void    FreeBuffers(Buffer *aBuffer);
    otError ReclaimBuffers(int aNumBuffers, Message::Priority aPriority);

#if OPENTHREAD_CONFIG_PLATFORM_MESSAGE_MANAGEMENT == 0
    uint16_t           mNumFreeBuffers;
    Buffer             mBuffers[kNumBuffers];
    LinkedList<Buffer> mFreeBuffers;
#endif
};

/**
 * @}
 *
 */

} // namespace ot

#endif // MESSAGE_HPP_


text:
KryPy is a Python (versions 2 and 3) module for Krylov subspace methods for the solution of linear algebraic systems. This includes enhanced versions of CG, MINRES and GMRES as well as methods for the efficient solution of sequences of linear systems.

# Features

KryPy gives you an easy-to-use yet flexible interface to Krylov subspace methods for linear algebraic systems. Compared to the implementations in [SciPy](http://docs.scipy.org/doc/scipy/reference/sparse.linalg.html) (or MATLAB), KryPy allows you to supply additional arguments that may help you to tune the solver for the specific problem you want to solve. The additional arguments may also be of interest if you are doing research on Krylov subspace methods.

Some features of KryPy are:

*  **User-defined inner products** - useful when solving a linear algebraic system whose operator is self-adjoined in a non-Euclidean inner-product. This way, CG or MINRES can be applied to self-adjoined (but non-symmetric/non-Hermitian) operators easily.
*  **Full control of preconditioners** - the order of applying preconditioners matters. This is why you can supply two left preconditioners (one of whom implicitly changes the inner product and thus has to be positive definite) and one right preconditioner. Take a look at the arguments ```M```, ```Ml``` and ```Mr```.
*  **Get the Arnoldi/Lanczos basis and Hessenberg matrix** - you want to extract further information from the generated vectors (e.g. recycling)? Just pass the optional argument ```return_basis=True```.
*  **Explicitly computed residuals on demand** - if you do research on Krylov subspace methods or preconditioners, then you sometimes want to know the explicitly computed residual in each iteration (in contrast to an updated residual which can be obtained implicitly). Then you should pass the optional argument ```explicit_residual=True```.
*  **Compute errors** - if you have (for research purposes) the exact solution at hand and want to monitor the error in each iteration instead of the residual, you can supply the optional argument ```exact_solution=x_exact```.

# Usage

### Documentation
Here is the [documentation](http://andrenarchy.github.io/krypy/).

### Example
```python
from numpy import ones
from scipy.sparse import spdiags
from krypy.linsys import gmres

N = 10
A = spdiags(range(1,N+1), [0], N, N)
b = ones((N,1))

sol = gmres(A, b)
print (sol['relresvec'])
```

Of course, this is just a toy example. KryPy can handle arbitrary large matrices - as long as they fit into your memory. ;)

### Help

Help can be optained via Python's builtin help system. For example, you can use the ```?``` in ```ipython```:
```ipython
from krypy.linsys import gmres
?gmres
```

# Installing
### Ubuntu
There's an [Ubuntu PPA](https://launchpad.net/~andrenarchy/+archive/python) with packages for Python 2 and Python 3.

### Installing from source
KryPy has the following dependencies:
* NumPy
* SciPy

# Development

KryPy is currently maintained by [André Gaul](http://www.math.tu-berlin.de/~gaul/). Feel free to contact André. Please submit feature requests and bugs as github issues.

KryPy is developed with continuous integration. Each commit is tested with ~60000 automated unittests. Current status: [![Build Status](https://travis-ci.org/andrenarchy/krypy.png?branch=master)](https://travis-ci.org/andrenarchy/krypy)

# License

KryPy is free software licensed under the [MIT License](http://opensource.org/licenses/mit-license.php).

# References

KryPy evolved from the [PyNosh](https://bitbucket.org/nschloe/pynosh) package (Python framework for nonlinear Schrödinger equations; joint work with [Nico Schlömer](https://github.com/nschloe)) which was used for experiments in the following publication:
* [Modified Recycling MINRES with application to nonlinear Schrödinger problems, A. Gaul and N. Schlömer, arxiv: 1208.0264, 2012](http://arxiv.org/abs/1208.0264)

redpajama_set_name: RedPajamaGithub


text:
layout: post
status: published
title: ! '2015 resolution: kill maxlength, add validation'
categories:
- UI
tags: []
---
If you're still looking for a New Year's resolution, here's a suggestion:

Go over all your UI code now, and whenever you see something like this...
<!-- more -->
{% highlight html %}
{% raw %}
<input id="credit-card-number" maxlength="16">
{% endraw %}
{% endhighlight %}

... please spend a few minutes to remove **maxlength** and add some real validation code instead.

Why? Because in 2015, I think it's reasonable to expect any UI to be flexible enough to handle user input even with a few extra characters.

Your users should be able to copy&paste their credit card number from a Google Doc to your form, with or without dashes and blanks. Leading/trailing whitespaces should be handled gracefully. Just remove all those extra characters *before* validation - seriously, it's probably one line of code.

Entering a phone number with or without brackets should just work. Including international numbers. A **maxlength="10"** for phone numbers is just ridiculously inconvenient.

Copying an order/tracking/customer number from an email to a support request form should just work and not require the user to manually un-group numbers in a text editor first.

Come on, this is 2015. Just do it.

Happy New Year!

Discuss on [Hacker News](https://news.ycombinator.com/item?id=8807841)


text:
var env;
try {
  env = require("./env.json");
}
catch (e)
{
  console.log(e);
}
env = env || {};
module.exports = function(grunt) {

  // Load all grunt tasks.
  require("load-grunt-tasks")(grunt);

  // Project configuration.
  grunt.initConfig({
    pkg: grunt.file.readJSON("package.json"),
    nodemon: {
      controller: {
        options: {
          file: "control.js",
          args: ["3001"],
          watchedFolders: ["./lib"],
          env: env
        }
      },
      harvester: {
        options: {
          file: "harvester.js",
          watchedFolders: ["./lib"],
          env: env
        }
      },
      handler: {
        options: {
          file: "handler.js",
          args: ["3000"],
          watchedFolders: ["./lib"],
          env: env
        }
      }
    },
    // Need to install bower components.
    bower: {
      install: {
        options: {
          install: true,
          targetDir: "./controller/bower_components",
          cleanBowerDir: true
        }
      }
    },
    // Build css from stylus
    stylus: {
      compile: {
        options: {
          compress: true
        },
        files: { "controller/css/app.css": "controller/css/app.styl"}
      }
    },
    watch: {
      stylus: {
        files: "controller/css/*.styl",
        tasks: ["stylus"]
      }
    }
  });

  grunt.registerTask("default", ["nodemon:control"]);
  grunt.registerTask("build", ["bower, stylus"]);
  grunt.registerTask("controller", ["bower", "nodemon:controller"]);
  grunt.registerTask("harvester", ["nodemon:harvester"]);
  grunt.registerTask("handler", ["nodemon:handler"]);
};


text:
package org.apache.drill.exec.planner.index;

import org.apache.drill.shaded.guava.com.google.common.collect.Maps;
import org.apache.drill.shaded.guava.com.google.common.collect.Sets;
import org.apache.drill.common.expression.CastExpression;
import org.apache.drill.common.expression.LogicalExpression;
import org.apache.drill.common.expression.SchemaPath;

import java.util.Map;
import java.util.Set;

public class MapRDBFunctionalIndexInfo implements FunctionalIndexInfo {

  final private IndexDescriptor indexDesc;

  private boolean hasFunctionalField = false;

  // When we scan schemaPath in groupscan's columns, we check if this column(schemaPath) should be rewritten to '$N',
  // When there are more than two functions on the same column in index, CAST(a.b as INT), CAST(a.b as VARCHAR),
  // then we should map SchemaPath a.b to a set of SchemaPath, e.g. $1, $2
  private Map<SchemaPath, Set<SchemaPath>> columnToConvert;

  // map of functional index expression to destination SchemaPath e.g. $N
  private Map<LogicalExpression, LogicalExpression> exprToConvert;

  // map of SchemaPath involved in a functional field
  private Map<LogicalExpression, Set<SchemaPath>> pathsInExpr;

  private Set<SchemaPath> newPathsForIndexedFunction;

  private Set<SchemaPath> allPathsInFunction;

  public MapRDBFunctionalIndexInfo(IndexDescriptor indexDesc) {
    this.indexDesc = indexDesc;
    columnToConvert = Maps.newHashMap();
    exprToConvert = Maps.newHashMap();
    pathsInExpr = Maps.newHashMap();
    // keep the order of new paths, it may be related to the naming policy
    newPathsForIndexedFunction = Sets.newLinkedHashSet();
    allPathsInFunction = Sets.newHashSet();
    init();
  }

  private void init() {
    int count = 0;
    for (LogicalExpression indexedExpr : indexDesc.getIndexColumns()) {
      if (!(indexedExpr instanceof SchemaPath)) {
        hasFunctionalField = true;
        SchemaPath functionalFieldPath = SchemaPath.getSimplePath("$"+count);
        newPathsForIndexedFunction.add(functionalFieldPath);

        // now we handle only cast expression
        if (indexedExpr instanceof CastExpression) {
          // We handle only CAST directly on SchemaPath for now.
          SchemaPath pathBeingCasted = (SchemaPath)((CastExpression) indexedExpr).getInput();
          addTargetPathForOriginalPath(pathBeingCasted, functionalFieldPath);
          addPathInExpr(indexedExpr, pathBeingCasted);
          exprToConvert.put(indexedExpr, functionalFieldPath);
          allPathsInFunction.add(pathBeingCasted);
        }

        count++;
      }
    }
  }

  private void addPathInExpr(LogicalExpression expr, SchemaPath path) {
    if (!pathsInExpr.containsKey(expr)) {
      Set<SchemaPath> newSet = Sets.newHashSet();
      newSet.add(path);
      pathsInExpr.put(expr, newSet);
    }
    else {
      pathsInExpr.get(expr).add(path);
    }
  }

  private void addTargetPathForOriginalPath(SchemaPath origPath, SchemaPath newPath) {
    if (!columnToConvert.containsKey(origPath)) {
      Set<SchemaPath> newSet = Sets.newHashSet();
      newSet.add(newPath);
      columnToConvert.put(origPath, newSet);
    }
    else {
      columnToConvert.get(origPath).add(newPath);
    }
  }

  public boolean hasFunctional() {
    return hasFunctionalField;
  }

  public IndexDescriptor getIndexDesc() {
    return indexDesc;
  }

  /**
   * getNewPath: for an original path, return new rename '$N' path, notice there could be multiple renamed paths
   * if the there are multiple functional indexes refer original path.
   * @param path
   * @return
   */
  public SchemaPath getNewPath(SchemaPath path) {
    if (columnToConvert.containsKey(path)) {
      return columnToConvert.get(path).iterator().next();
    }
    return null;
  }

  /**
   * return a plain field path if the incoming index expression 'expr' is replaced to be a plain field
   * @param expr suppose to be an indexed expression
   * @return the renamed schemapath in index table for the indexed expression
   */
  public SchemaPath getNewPathFromExpr(LogicalExpression expr) {
    if (exprToConvert.containsKey(expr)) {
      return (SchemaPath)exprToConvert.get(expr);
    }
    return null;
  }

  /**
   * Suppose the index key has functions (rather than plain columns): CAST(a as int), CAST(b as varchar(10)),
   * then we want to maintain a mapping of the logical expression of that function to the schema path of the
   * base column involved in the function. In this example map has 2 entries:
   *   CAST(a as int)  --> 'a'
   *   CAST(b as varchar(10)) --> 'b'
   * @return the map of indexed expression --> the involved schema paths in a indexed expression
   */
  public Map<LogicalExpression, Set<SchemaPath>> getPathsInFunctionExpr() {
    return pathsInExpr;
  }

  public Map<LogicalExpression, LogicalExpression> getExprMap() {
    return exprToConvert;
  }

  public Set<SchemaPath> allNewSchemaPaths() {
    return newPathsForIndexedFunction;
  }

  public Set<SchemaPath> allPathsInFunction() {
    return allPathsInFunction;
  }

  public boolean supportEqualCharConvertToLike() {
    return true;
  }
}


text:
echo "<title>env</title>
"
for OUT in $(env)
do
	echo "
"
	echo $OUT
	echo "
"
done
echo "
"


text:
{-# LANGUAGE DeriveDataTypeable #-}
{-# LANGUAGE UnicodeSyntax #-}

{-| This module contains a type that specializes the 'Sum' 'Monoid' to 'Int'. -}
module LogicGrowsOnTrees.Utils.IntSum where

import Data.List (foldl')
import Data.Monoid (Monoid(..))
import Data.Serialize (Serialize(..))
import Data.Typeable (Typeable)

{-| An unpacked 'Int' whose 'Monoid' instance is addition. -}
data IntSum = IntSum { getIntSum :: {-# UNPACK #-} !Int } deriving (Eq,Show,Typeable)

{-| This instance sums the two contained 'Int's. -}
instance Monoid IntSum where
    mempty = IntSum 0
    IntSum x `mappend` IntSum y = IntSum (x+y)
    mconcat = foldl' mappend mempty

{-| This instance is equivalent to the instance for 'Int'. -}
instance Serialize IntSum where
    put = put . getIntSum
    get = fmap IntSum get


text:
package com.badlogic.gdx.physics.bullet;

import com.badlogic.gdx.utils.SharedLibraryLoader;

public class Bullet {
	/** Loads the native Bullet native library and initializes the gdx-bullet extension. */
	public static void init () {
		new SharedLibraryLoader().load("gdx-bullet");
	}
}


text:
package org.apache.geode.management.internal.cli.commands;

import java.io.File;
import java.util.List;
import java.util.Optional;

import org.springframework.shell.core.annotation.CliCommand;
import org.springframework.shell.core.annotation.CliOption;

import org.apache.geode.cache.CacheClosedException;
import org.apache.geode.cache.execute.FunctionInvocationTargetException;
import org.apache.geode.cache.execute.ResultCollector;
import org.apache.geode.cache.snapshot.RegionSnapshotService;
import org.apache.geode.distributed.DistributedMember;
import org.apache.geode.management.cli.CliMetaData;
import org.apache.geode.management.cli.ConverterHint;
import org.apache.geode.management.cli.GfshCommand;
import org.apache.geode.management.internal.cli.functions.ExportDataFunction;
import org.apache.geode.management.internal.cli.result.model.ResultModel;
import org.apache.geode.management.internal.functions.CliFunctionResult;
import org.apache.geode.management.internal.i18n.CliStrings;
import org.apache.geode.security.ResourcePermission.Operation;
import org.apache.geode.security.ResourcePermission.Resource;

public class ExportDataCommand extends GfshCommand {
  private final ExportDataFunction exportDataFunction = new ExportDataFunction();

  @CliCommand(value = CliStrings.EXPORT_DATA, help = CliStrings.EXPORT_DATA__HELP)
  @CliMetaData(relatedTopic = {CliStrings.TOPIC_GEODE_DATA, CliStrings.TOPIC_GEODE_REGION})
  public ResultModel exportData(
      @CliOption(key = CliStrings.EXPORT_DATA__REGION, mandatory = true,
          optionContext = ConverterHint.REGION_PATH,
          help = CliStrings.EXPORT_DATA__REGION__HELP) String regionName,
      @CliOption(key = CliStrings.EXPORT_DATA__FILE,
          help = CliStrings.EXPORT_DATA__FILE__HELP) String filePath,
      @CliOption(key = CliStrings.EXPORT_DATA__DIR,
          help = CliStrings.EXPORT_DATA__DIR__HELP) String dirPath,
      @CliOption(key = CliStrings.MEMBER, optionContext = ConverterHint.MEMBERIDNAME,
          mandatory = true, help = CliStrings.EXPORT_DATA__MEMBER__HELP) String memberNameOrId,
      @CliOption(key = CliStrings.EXPORT_DATA__PARALLEL, unspecifiedDefaultValue = "false",
          specifiedDefaultValue = "true",
          help = CliStrings.EXPORT_DATA__PARALLEL_HELP) boolean parallel) {

    authorize(Resource.DATA, Operation.READ, regionName);
    final DistributedMember targetMember = getMember(memberNameOrId);

    Optional<ResultModel> validationResult = validatePath(filePath, dirPath, parallel);
    if (validationResult.isPresent()) {
      return validationResult.get();
    }

    ResultModel result;
    try {
      String path = dirPath != null ? defaultFileName(dirPath, regionName) : filePath;
      final String args[] = {regionName, path, Boolean.toString(parallel)};

      ResultCollector<?, ?> rc = executeFunction(exportDataFunction, args, targetMember);
      result = ResultModel.createMemberStatusResult((List<CliFunctionResult>) rc.getResult());
    } catch (CacheClosedException e) {
      result = ResultModel.createError(e.getMessage());
    } catch (FunctionInvocationTargetException e) {
      result = ResultModel.createError(
          CliStrings.format(CliStrings.COMMAND_FAILURE_MESSAGE, CliStrings.IMPORT_DATA));
    }
    return result;
  }

  private String defaultFileName(String dirPath, String regionName) {
    return new File(dirPath, regionName + RegionSnapshotService.SNAPSHOT_FILE_EXTENSION)
        .getAbsolutePath();
  }

  private Optional<ResultModel> validatePath(String filePath, String dirPath, boolean parallel) {
    if (filePath == null && dirPath == null) {
      return Optional
          .of(ResultModel.createError("Must specify a location to save snapshot"));
    } else if (filePath != null && dirPath != null) {
      return Optional.of(ResultModel.createError(
          "Options \"file\" and \"dir\" cannot be specified at the same time"));
    } else if (parallel && dirPath == null) {
      return Optional.of(
          ResultModel.createError("Must specify a directory to save snapshot files"));
    }

    if (dirPath == null && !filePath.endsWith(CliStrings.GEODE_DATA_FILE_EXTENSION)) {
      return Optional.of(ResultModel.createError(CliStrings.format(
          CliStrings.INVALID_FILE_EXTENSION, CliStrings.GEODE_DATA_FILE_EXTENSION)));
    }
    return Optional.empty();
  }
}


text:
/***
 * Horizontal modifier:
 */
/**
 * Justify content flex start:
 * `.jc-flex-start` `.[size]-jc-flex-start` `.max[size]-jc-flex-start`
 *
 *     @example
 *     div.cntr.cntr--fluid
 *          div.row.jc-flex-start.bgc-success-20.p-y-1
 *              div.col-4
 *                  div.bgc-success-40.p-1
 */
/**
 * Justify content center:
 * `.jc-center` `.[size]-jc-center` `.max[size]-jc-center`
 *
 *     @example
 *     div.cntr.cntr--fluid
 *         div.row.jc-center.bgc-success-20.p-y-1
 *             div.col-4
 *                 div.bgc-success-40.p-1
 */
/**
 * Justify content flex end:
 * `.jc-flex-end` `.[size]-jc-flex-end` `.max[size]-jc-flex-end`
 *
 *     @example
 *     div.cntr.cntr--fluid
 *         div.row.jc-flex-end.bgc-success-20.p-y-1
 *             div.col-4
 *                 div.bgc-success-40.p-1
 */
.jc-flex-start {
  justify-content: flex-start !important; }

.jc-center {
  justify-content: center !important; }

.jc-flex-end {
  justify-content: flex-end !important; }

.jc-space-between {
  justify-content: space-between !important; }

.jc-space-around {
  justify-content: space-around !important; }

@media (min-width: 0) {
  .xs-jc-flex-start {
    justify-content: flex-start !important; }
  .xs-jc-center {
    justify-content: center !important; }
  .xs-jc-flex-end {
    justify-content: flex-end !important; }
  .xs-jc-space-between {
    justify-content: space-between !important; }
  .xs-jc-space-around {
    justify-content: space-around !important; } }

@media (max-width: 767px) {
  .maxsm-jc-flex-start {
    justify-content: flex-start !important; }
  .maxsm-jc-center {
    justify-content: center !important; }
  .maxsm-jc-flex-end {
    justify-content: flex-end !important; }
  .maxsm-jc-space-between {
    justify-content: space-between !important; }
  .maxsm-jc-space-around {
    justify-content: space-around !important; } }

@media (min-width: 768px) {
  .sm-jc-flex-start {
    justify-content: flex-start !important; }
  .sm-jc-center {
    justify-content: center !important; }
  .sm-jc-flex-end {
    justify-content: flex-end !important; }
  .sm-jc-space-between {
    justify-content: space-between !important; }
  .sm-jc-space-around {
    justify-content: space-around !important; } }

@media (max-width: 1023px) {
  .maxmd-jc-flex-start {
    justify-content: flex-start !important; }
  .maxmd-jc-center {
    justify-content: center !important; }
  .maxmd-jc-flex-end {
    justify-content: flex-end !important; }
  .maxmd-jc-space-between {
    justify-content: space-between !important; }
  .maxmd-jc-space-around {
    justify-content: space-around !important; } }

@media (min-width: 1024px) {
  .md-jc-flex-start {
    justify-content: flex-start !important; }
  .md-jc-center {
    justify-content: center !important; }
  .md-jc-flex-end {
    justify-content: flex-end !important; }
  .md-jc-space-between {
    justify-content: space-between !important; }
  .md-jc-space-around {
    justify-content: space-around !important; } }

@media (max-width: 1279px) {
  .maxlg-jc-flex-start {
    justify-content: flex-start !important; }
  .maxlg-jc-center {
    justify-content: center !important; }
  .maxlg-jc-flex-end {
    justify-content: flex-end !important; }
  .maxlg-jc-space-between {
    justify-content: space-between !important; }
  .maxlg-jc-space-around {
    justify-content: space-around !important; } }

@media (min-width: 1280px) {
  .lg-jc-flex-start {
    justify-content: flex-start !important; }
  .lg-jc-center {
    justify-content: center !important; }
  .lg-jc-flex-end {
    justify-content: flex-end !important; }
  .lg-jc-space-between {
    justify-content: space-between !important; }
  .lg-jc-space-around {
    justify-content: space-around !important; } }

@media (max-width: 1679px) {
  .maxxl-jc-flex-start {
    justify-content: flex-start !important; }
  .maxxl-jc-center {
    justify-content: center !important; }
  .maxxl-jc-flex-end {
    justify-content: flex-end !important; }
  .maxxl-jc-space-between {
    justify-content: space-between !important; }
  .maxxl-jc-space-around {
    justify-content: space-around !important; } }

@media (min-width: 1680px) {
  .xl-jc-flex-start {
    justify-content: flex-start !important; }
  .xl-jc-center {
    justify-content: center !important; }
  .xl-jc-flex-end {
    justify-content: flex-end !important; }
  .xl-jc-space-between {
    justify-content: space-between !important; }
  .xl-jc-space-around {
    justify-content: space-around !important; } }


text:
<!DOCTYPE html>

        <link rel="stylesheet" type="text/css" href="webstyle.css">
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
        <title>Ella West | Writing Tips</title>

Home

Books

About Me

Writing Tips

FAQS

Contact

Chat with Ella

Writing Tips

First or all, write because you love doing it.  Don't write to become famous or wealthy or to have lots of friends who admire you.  All of that stuff may happen but don't write because of it.  Write because you enjoy telling a story.

I have heard of people writing a 100,000 word book in two weeks which instantly becomes a best seller but I have never met them.  Don't expect this to be you.  Most writers feel pretty good to crack out 2000 words a day and getting a publishing contract can take a year or more and then it can be another year or even longer before it actually gets published and appears on bookshop shelves.  Of course, self-publishing an ebook is a lot quicker but you have to really know what you are doing.  Be careful.

Write what you want to write.  Don't write books for kids say, about World War One because they seem to be popular at the moment, or crime books because everyone else is doing it.  Write what you love and the way to find that out is probably to have a look at what you read.  If you love romance stories and you read a lot of romance then write a romance.  Don't worry about people judging you – they'll do that whatever you write.

Believe in yourself.  If you want to write, if you love writing then just do it.  And if you can't handle people saying you will probably fail then don't tell them what you are doing.  No one knew I was writing Thieves except my husband until I had a publishing contract.  And even then very few of my friends knew.  Most people I deal with every day still have no idea.  And it's okay to keep it that way.  They don't get it and that's just fine.  My mum was the best when Thieves came out:  "Hi Mum, my book is getting published." "That's nice, where will I be able to find it."  "It will be on bookshop shelves, Mum."  "It's a real book?"  "Yes, Mum, but I'll send you a copy, you don't need to buy it."  She's now one of my biggest supporters.  Thanks Mum.

Whatever you do write a great book.  Not just a good book, but a great book, a mind blowing, amazing, incredible book.  You sell more books this way, win awards, get to do stuff.  Don't complain if your book doesn't sell, if it doesn't make it into awards.  Just go write a better book.

Saying that, there is a lot of luck in this business.  Even with winning awards, just because your book is amazing, that doesn't mean it will win.  I once had a white pony which a friend used to enter into competitions.  These competitions were simply about how the pony looked.  She used to either win everything on the day, or nothing.  She said it was because some judges liked white ponies and some didn't.  If the judges didn't like white ponies, then she wouldn't win anything, however much work she had done brushing it and plaiting its tail.  When luck isn't going your way, don't let it get you down.  When it is going your way, when everyone loves white ponies, then enjoy the rollercoaster ride.


text:
/*
HLF Accordion Visual Tests
==========================
[Page](../../../tests/accordion.visual.html) | [Source](../../src/css/accordion.html)
*/

.sections > ul {
  display: block;
}

.list.js-ac-folded li.no-a:first-child {
  border-bottom-left-radius: var(--radius-size);
  border-bottom-right-radius: var(--radius-size);
  border-bottom-width: var(--line-size);
}


text:
package com.cloudaward.lyl;

import android.os.Bundle;
import android.support.v7.app.ActionBarActivity;

@SuppressWarnings("deprecation")
public abstract class AbstractCheckLoginActivity extends ActionBarActivity {

  protected SessionManager mSessionManager;

  @Override
  protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    mSessionManager = new SessionManager(this);
    mSessionManager.checkLogin();
  }

}


text:
package org.apereo.cas.trusted.authentication.storage;

import org.apereo.cas.CipherExecutor;
import org.apereo.cas.audit.spi.config.CasCoreAuditConfiguration;
import org.apereo.cas.category.RestfulApiCategory;
import org.apereo.cas.configuration.CasConfigurationProperties;
import org.apereo.cas.trusted.authentication.api.MultifactorAuthenticationTrustRecord;
import org.apereo.cas.trusted.authentication.api.MultifactorAuthenticationTrustStorage;
import org.apereo.cas.trusted.config.MultifactorAuthnTrustConfiguration;
import org.apereo.cas.trusted.config.MultifactorAuthnTrustedDeviceFingerprintConfiguration;
import org.apereo.cas.trusted.config.RestMultifactorAuthenticationTrustConfiguration;
import org.apereo.cas.util.CollectionUtils;
import org.apereo.cas.util.MockWebServer;

import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializationFeature;
import lombok.val;
import org.junit.BeforeClass;
import org.junit.ClassRule;
import org.junit.Rule;
import org.junit.Test;
import org.junit.experimental.categories.Category;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.cloud.autoconfigure.RefreshAutoConfiguration;
import org.springframework.core.io.ByteArrayResource;
import org.springframework.http.MediaType;
import org.springframework.test.context.TestPropertySource;
import org.springframework.test.context.junit4.rules.SpringClassRule;
import org.springframework.test.context.junit4.rules.SpringMethodRule;
import org.springframework.web.client.RestTemplate;

import java.nio.charset.StandardCharsets;
import java.time.LocalDateTime;

import static org.junit.Assert.*;

/**
 * This is {@link RestMultifactorAuthenticationTrustStorageTests}.
 *
 * @author Misagh Moayyed
 * @since 5.3.0
 */
@Category(RestfulApiCategory.class)
@SpringBootTest(classes = {
    RestMultifactorAuthenticationTrustConfiguration.class,
    MultifactorAuthnTrustedDeviceFingerprintConfiguration.class,
    MultifactorAuthnTrustConfiguration.class,
    CasCoreAuditConfiguration.class,
    RefreshAutoConfiguration.class})
@TestPropertySource(properties = "cas.authn.mfa.trusted.rest.url=http://localhost:9297")
public class RestMultifactorAuthenticationTrustStorageTests {
    @ClassRule
    public static final SpringClassRule SPRING_CLASS_RULE = new SpringClassRule();

    private static final ObjectMapper MAPPER = new ObjectMapper().findAndRegisterModules();

    @Rule
    public final SpringMethodRule springMethodRule = new SpringMethodRule();

    @Autowired
    @Qualifier("mfaTrustEngine")
    private MultifactorAuthenticationTrustStorage mfaTrustEngine;

    @Autowired
    @Qualifier("mfaTrustCipherExecutor")
    private CipherExecutor mfaTrustCipherExecutor;

    @BeforeClass
    public static void setup() {
        MAPPER.configure(DeserializationFeature.ADJUST_DATES_TO_CONTEXT_TIME_ZONE, false);
        MAPPER.configure(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS, false);
    }

    @Test
    public void verifySetAnExpireByKey() throws Exception {
        val r =
            MultifactorAuthenticationTrustRecord.newInstance("casuser", "geography", "fingerprint");
        val data = MAPPER.writeValueAsString(CollectionUtils.wrap(r));
        try (val webServer = new MockWebServer(9297,
            new ByteArrayResource(data.getBytes(StandardCharsets.UTF_8), "REST Output"), MediaType.APPLICATION_JSON_VALUE)) {
            webServer.start();

            mfaTrustEngine.set(r);
            val records = mfaTrustEngine.get("casuser");
            assertNotNull(records);
        } catch (final Exception e) {
            throw new AssertionError(e.getMessage(), e);
        }
    }

    @Test
    public void verifyExpireByDate() throws Exception {
        val r =
            MultifactorAuthenticationTrustRecord.newInstance("castest", "geography", "fingerprint");
        r.setRecordDate(LocalDateTime.now().minusDays(2));

        val data = MAPPER.writeValueAsString(CollectionUtils.wrap(r));
        try (val webServer = new MockWebServer(9311,
            new ByteArrayResource(data.getBytes(StandardCharsets.UTF_8), "REST Output"), MediaType.APPLICATION_JSON_VALUE)) {
            webServer.start();

            val props = new CasConfigurationProperties();
            props.getAuthn().getMfa().getTrusted().getRest().setUrl("http://localhost:9311");
            val mfaEngine = new RestMultifactorAuthenticationTrustStorage(new RestTemplate(), props);
            mfaEngine.setCipherExecutor(mfaTrustCipherExecutor);

            mfaEngine.set(r);
            val records = mfaEngine.get(r.getPrincipal());
            assertNotNull(records);
        } catch (final Exception e) {
            throw new AssertionError(e.getMessage(), e);
        }
    }
}


text:
<?php
// Copyright (c) 2003-2015, CKSource - Frederico Knabben. All rights reserved.
// For licensing, see LICENSE.html or http://ckfinder.com/license

//  Defines the object for the Spanish language.

return array (
    'ErrorUnknown' => 'No ha sido posible completar la solicitud. (Error %1)',
    'Errors' => array (
        10 => 'Comando incorrecto.',
        11 => 'El tipo de recurso no ha sido especificado en la solicitud.',
        12 => 'El tipo de recurso solicitado no es válido.',
        13 => 'El archivo de configuración del conector no es válido.',
        14 => 'Plugin del conector inválido: %1.',
        102 => 'Nombre de fichero o carpeta no válido.',
        103 => 'No se ha podido completar la solicitud debido a las restricciones de autorización.',
        104 => 'No ha sido posible completar la solicitud debido a restricciones en el sistema de ficheros.',
        105 => 'La extensión del archivo no es válida.',
        109 => 'Petición inválida.',
        110 => 'Error desconocido.',
        111 => 'No fué posible completar la petición debido al tamaño del fichero.',
        115 => 'Ya existe un fichero o carpeta con ese nombre.',
        116 => 'No se ha encontrado la carpeta. Por favor, actualice y pruebe de nuevo.',
        117 => 'No se ha encontrado el fichero. Por favor, actualice la lista de ficheros y pruebe de nuevo.',
        118 => 'Las rutas origen y destino son iguales.',
        201 => 'Ya existía un fichero con ese nombre. El fichero subido ha sido renombrado como "%1".',
        202 => 'Fichero inválido.',
        203 => 'Fichero inválido. El tamaño es demasiado grande.',
        204 => 'El fichero subido está corrupto.',
        205 => 'La carpeta temporal no está disponible en el servidor para las subidas.',
        206 => 'La subida se ha cancelado por razones de seguridad. El fichero contenía código HTML.',
        207 => 'El fichero subido ha sido renombrado como "%1".',
        300 => 'Ha fallado el mover el(los) fichero(s).',
        301 => 'Ha fallado el copiar el(los) fichero(s).',
        302 => 'Ha fallado la eliminación de el/los fichero(s).',
        500 => 'El navegador de archivos está deshabilitado por razones de seguridad. Por favor, contacte con el administrador de su sistema y compruebe el fichero de configuración de CKFinder.',
        501 => 'El soporte para iconos está deshabilitado.'
    )
);


text:
package com.travelersun.schedule.admin.service;

import com.travelersun.schedule.admin.core.model.XxlJobInfo;
import com.travelersun.schedule.core.biz.model.ReturnT;

import java.util.Map;

/**
 * core job action for xxl-job
 *
 * @author xuxueli 2016-5-28 15:30:33
 */
public interface IXxlJobService {

	public Map<String, Object> pageList(int start, int length, int jobGroup, String executorHandler, String filterTime);

	public ReturnT<String> add(XxlJobInfo jobInfo);

	public ReturnT<String> reschedule(XxlJobInfo jobInfo);

	public ReturnT<String> remove(int id);

	public ReturnT<String> pause(int id);

	public ReturnT<String> resume(int id);

	public ReturnT<String> triggerJob(int id);

}


text:
<?php
namespace Squirt\Common;

use Psr\Log\LoggerAwareInterface;
use Squirt\Common\SquirtableInterface;

interface SquirtableLoggingInterface extends LoggerAwareInterface,SquirtableInterface
{}


text:
@interface EAGFile : NSObject

@property (nonatomic, readonly) EAGFileInfo *info;

- (NSData*)readData:(NSError**)error;

- (NSString*)readString:(NSError**)error;

- (void)close;

@end


text:
#include "common.h"

#include "map.h"
#include <errno.h>

#ifndef NO_MMAP

static DWORD get_page_size(void)
{
	static DWORD page_size;
	SYSTEM_INFO sys;

	if (!page_size) {
		GetSystemInfo(&sys);
		page_size = sys.dwPageSize;
	}

	return page_size;
}

static DWORD get_allocation_granularity(void)
{
	static DWORD granularity;
	SYSTEM_INFO sys;

	if (!granularity) {
		GetSystemInfo(&sys);
		granularity = sys.dwAllocationGranularity;
	}

	return granularity;
}

int git__page_size(size_t *page_size)
{
	*page_size = get_page_size();
	return 0;
}

int git__mmap_alignment(size_t *page_size)
{
	*page_size = get_allocation_granularity();
	return 0;
}

int p_mmap(git_map *out, size_t len, int prot, int flags, int fd, git_off_t offset)
{
	HANDLE fh = (HANDLE)_get_osfhandle(fd);
	DWORD alignment = get_allocation_granularity();
	DWORD fmap_prot = 0;
	DWORD view_prot = 0;
	DWORD off_low = 0;
	DWORD off_hi = 0;
	git_off_t page_start;
	git_off_t page_offset;

	GIT_MMAP_VALIDATE(out, len, prot, flags);

	out->data = NULL;
	out->len = 0;
	out->fmh = NULL;

	if (fh == INVALID_HANDLE_VALUE) {
		errno = EBADF;
		git_error_set(GIT_ERROR_OS, "failed to mmap. Invalid handle value");
		return -1;
	}

	if (prot & GIT_PROT_WRITE)
		fmap_prot |= PAGE_READWRITE;
	else if (prot & GIT_PROT_READ)
		fmap_prot |= PAGE_READONLY;

	if (prot & GIT_PROT_WRITE)
		view_prot |= FILE_MAP_WRITE;
	if (prot & GIT_PROT_READ)
		view_prot |= FILE_MAP_READ;

	page_start = (offset / alignment) * alignment;
	page_offset = offset - page_start;

	if (page_offset != 0) { /* offset must be multiple of the allocation granularity */
		errno = EINVAL;
		git_error_set(GIT_ERROR_OS, "failed to mmap. Offset must be multiple of allocation granularity");
		return -1;
	}

	out->fmh = CreateFileMapping(fh, NULL, fmap_prot, 0, 0, NULL);
	if (!out->fmh || out->fmh == INVALID_HANDLE_VALUE) {
		git_error_set(GIT_ERROR_OS, "failed to mmap. Invalid handle value");
		out->fmh = NULL;
		return -1;
	}

	assert(sizeof(git_off_t) == 8);

	off_low = (DWORD)(page_start);
	off_hi = (DWORD)(page_start >> 32);
	out->data = MapViewOfFile(out->fmh, view_prot, off_hi, off_low, len);
	if (!out->data) {
		git_error_set(GIT_ERROR_OS, "failed to mmap. No data written");
		CloseHandle(out->fmh);
		out->fmh = NULL;
		return -1;
	}
	out->len = len;

	return 0;
}

int p_munmap(git_map *map)
{
	int error = 0;

	assert(map != NULL);

	if (map->data) {
		if (!UnmapViewOfFile(map->data)) {
			git_error_set(GIT_ERROR_OS, "failed to munmap. Could not unmap view of file");
			error = -1;
		}
		map->data = NULL;
	}

	if (map->fmh) {
		if (!CloseHandle(map->fmh)) {
			git_error_set(GIT_ERROR_OS, "failed to munmap. Could not close handle");
			error = -1;
		}
		map->fmh = NULL;
	}

	return error;
}

#endif


text:
<?php
if (!defined("WIKINI_VERSION"))
{
        die ("accès direct interdit");
}

// si l'action propose d'autres css à ajouter, on les ajoute
$othercss = $this->GetParameter('othercss');
if (!empty($othercss)) {
	echo $this->Format('{{linkstyle othercss="'.$othercss.'"}}');
} else {
	echo $this->Format('{{linkstyle}}');
}

?>


text:
module ActionKitRest
  class Base < Vertebrae::Model
    def list(filters = {})
      client.get_request(normalized_base_path, filters)
    end

    def get(id)
      client.get_request("#{normalized_base_path}#{url_escape(id)}/")
    end

    def create(params)
      resp = client.post_json_request(normalized_base_path, params)
      id = extract_id_from_response(resp)
      get(id)
    end

    def update(id, params)
      client.put_json_request("#{normalized_base_path}#{url_escape(id)}/", params)
      get(id)
    end

    def normalized_base_path
      "#{base_path}/"
    end

    private

    def url_escape(string)
      CGI.escape(string.to_s)
    end

    def extract_id_from_response(resp)
      extract_id_from_location(resp.response.headers['location'])
    end

    def extract_id_from_location(location)
      location.scan(%r{/(\d+)/$}).first.first
    end
  end
end


text:
<?php

/**
 * Class WPML_Elementor_Form
 */
class WPML_Elementor_Form extends WPML_Elementor_Module_With_Items {

	/**
	 * @return string
	 */
	public function get_items_field() {
		return 'form_fields';
	}

	/**
	 * @return array
	 */
	public function get_fields() {
		return array( 'field_label', 'placeholder', 'field_options' );
	}

	/**
	 * @param string $field
	 *
	 * @return string
	 */
	protected function get_title( $field ) {
		switch( $field ) {
			case 'field_label':
				return esc_html__( 'Form: Field label', 'wpml-string-translation' );

			case 'placeholder':
				return esc_html__( 'Form: Field placeholder', 'wpml-string-translation' );

			case 'field_options':
				return esc_html__( 'Form: Field options', 'wpml-string-translation' );

			default:
				return '';
		}
	}

	/**
	 * @param string $field
	 *
	 * @return string
	 */
	protected function get_editor_type( $field ) {
		switch( $field ) {
			case 'field_label':
			case 'placeholder':
				return 'LINE';

			case 'field_options':
				return 'AREA';

			default:
				return '';
		}
	}

}


text:
'''
Atlas
=====

.. versionadded:: 1.1.0

Atlas manages texture atlases: packing multiple textures into
one. With it, you reduce the number of images loaded and speedup the
application loading. This module contains both the Atlas class and command line
processing for creating an atlas from a set of individual PNG files. The
command line section requires the Pillow library, or the defunct Python Imaging
Library (PIL), to be installed.

An Atlas is composed of 2 or more files:
    - a json file (.atlas) that contains the image file names and texture
      locations of the atlas.
    - one or multiple image files containing textures referenced by the .atlas
      file.

Definition of .atlas files
--------------------------

A file with ``<basename>.atlas`` is a json file formatted like this::

    {
        "<basename>-<index>.png": {
            "id1": [ <x>, <y>, <width>, <height> ],
            "id2": [ <x>, <y>, <width>, <height> ],
            # ...
        },
        # ...
    }

Example from the Kivy ``data/images/defaulttheme.atlas``::

    {
        "defaulttheme-0.png": {
            "progressbar_background": [431, 224, 59, 24],
            "image-missing": [253, 344, 48, 48],
            "filechooser_selected": [1, 207, 118, 118],
            "bubble_btn": [83, 174, 32, 32],
            # ... and more ...
        }
    }

In this example, "defaulttheme-0.png" is a large image, with the pixels in the
rectangle from (431, 224) to (431 + 59, 224 + 24) usable as
``atlas://data/images/defaulttheme/progressbar_background`` in
any image parameter.

How to create an Atlas
----------------------

.. warning::

    The atlas creation requires the Pillow library (or the defunct Imaging/PIL
    library). This requirement will be removed in the future when the Kivy core
    Image is able to support loading, blitting, and saving operations.

You can directly use this module to create atlas files with this command::

    $ python -m kivy.atlas <basename> <size> <list of images...>

Let's say you have a list of images that you want to put into an Atlas. The
directory is named ``images`` with lots of 64x64 png files inside::

    $ ls
    images
    $ cd images
    $ ls
    bubble.png bubble-red.png button.png button-down.png

You can combine all the png's into one and generate the atlas file with::

    $ python -m kivy.atlas myatlas 256x256 *.png
    Atlas created at myatlas.atlas
    1 image has been created
    $ ls
    bubble.png bubble-red.png button.png button-down.png myatlas.atlas
    myatlas-0.png

As you can see, we get 2 new files: ``myatlas.atlas`` and ``myatlas-0.png``.
``myatlas-0.png`` is a new 256x256 .png composed of all your images. If the
size you specify is not large enough to fit all of the source images, more
atlas images will be created as required e.g. ``myatlas-1.png``,
``myatlas-2.png`` etc.

.. note::

    When using this script, the ids referenced in the atlas are the base names
    of the images without the extension. So, if you are going to name a file
    ``../images/button.png``, the id for this image will be ``button``.

    If you need path information included, you should include ``use_path`` as
    follows::

        $ python -m kivy.atlas -- --use_path myatlas 256 *.png

    In which case the id for ``../images/button.png`` will be ``images_button``

How to use an Atlas
-------------------

Usually, you would specify the images by supplying the path::

    a = Button(background_normal='images/button.png',
               background_down='images/button_down.png')

In our previous example, we have created the atlas containing both images and
put them in ``images/myatlas.atlas``. You can use url notation to reference
them::

    a = Button(background_normal='atlas://images/myatlas/button',
               background_down='atlas://images/myatlas/button_down')

In other words, the path to the images is replaced by::

    atlas://path/to/myatlas/id
    # will search for the ``path/to/myatlas.atlas`` and get the image ``id``

.. note::

    In the atlas url, there is no need to add the ``.atlas`` extension. It will
    be automatically append to the filename.

Manual usage of the Atlas
-------------------------

::

    >>> from kivy.atlas import Atlas
    >>> atlas = Atlas('path/to/myatlas.atlas')
    >>> print(atlas.textures.keys())
    ['bubble', 'bubble-red', 'button', 'button-down']
    >>> print(atlas['button'])
    <kivy.graphics.texture.TextureRegion object at 0x2404d10>
'''

__all__ = ('Atlas', )

import json
from os.path import basename, dirname, join, splitext
from kivy.event import EventDispatcher
from kivy.logger import Logger
from kivy.properties import AliasProperty, DictProperty, ListProperty
import os

# late import to prevent recursion
CoreImage = None

class Atlas(EventDispatcher):
    '''Manage texture atlas. See module documentation for more information.
    '''

    original_textures = ListProperty([])
    '''List of original atlas textures (which contain the :attr:`textures`).

    :attr:`original_textures` is a :class:`~kivy.properties.ListProperty` and
    defaults to [].

    .. versionadded:: 1.9.1
    '''

    textures = DictProperty({})
    '''List of available textures within the atlas.

    :attr:`textures` is a :class:`~kivy.properties.DictProperty` and defaults
    to {}.
    '''

    def _get_filename(self):
        return self._filename

    filename = AliasProperty(_get_filename, None)
    '''Filename of the current Atlas.

    :attr:`filename` is an :class:`~kivy.properties.AliasProperty` and defaults
    to None.
    '''

    def __init__(self, filename):
        self._filename = filename
        super(Atlas, self).__init__()
        self._load()

    def __getitem__(self, key):
        return self.textures[key]

    def _load(self):
        # late import to prevent recursive import.
        global CoreImage
        if CoreImage is None:
            from kivy.core.image import Image as CoreImage

        # must be a name finished by .atlas ?
        filename = self._filename
        assert(filename.endswith('.atlas'))
        filename = filename.replace('/', os.sep)

        Logger.debug('Atlas: Load <%s>' % filename)
        with open(filename, 'r') as fd:
            meta = json.load(fd)

        Logger.debug('Atlas: Need to load %d images' % len(meta))
        d = dirname(filename)
        textures = {}
        for subfilename, ids in meta.items():
            subfilename = join(d, subfilename)
            Logger.debug('Atlas: Load <%s>' % subfilename)

            # load the image
            ci = CoreImage(subfilename)
            atlas_texture = ci.texture
            self.original_textures.append(atlas_texture)

            # for all the uid, load the image, get the region, and put
            # it in our dict.
            for meta_id, meta_coords in ids.items():
                x, y, w, h = meta_coords
                textures[meta_id] = atlas_texture.get_region(*meta_coords)

        self.textures = textures

    @staticmethod
    def create(outname, filenames, size, padding=2, use_path=False):
        '''This method can be used to create an atlas manually from a set of
        images.

        :Parameters:
            `outname`: str
                Basename to use for ``.atlas`` creation and ``-<idx>.png``
                associated images.
            `filenames`: list
                List of filenames to put in the atlas.
            `size`: int or list (width, height)
                Size of the atlas image. If the size is not large enough to
                fit all of the source images, more atlas images will created
                as required.
            `padding`: int, defaults to 2
                Padding to put around each image.

                Be careful. If you're using a padding < 2, you might have
                issues with the borders of the images. Because of the OpenGL
                linearization, it might use the pixels of the adjacent image.

                If you're using a padding >= 2, we'll automatically generate a
                "border" of 1px around your image. If you look at
                the result, don't be scared if the image inside is not
                exactly the same as yours :).

            `use_path`: bool, defaults to False
                If True, the relative path of the source png
                file names will be included in the atlas ids rather
                that just in the file names. Leading dots and slashes will be
                excluded and all other slashes in the path will be replaced
                with underscores. For example, if `use_path` is False
                (the default) and the file name is
                ``../data/tiles/green_grass.png``, the id will be
                ``green_grass``. If `use_path` is True, it will be
                ``data_tiles_green_grass``.

            .. versionchanged:: 1.8.0
                Parameter use_path added
        '''
        # Thanks to
        # omnisaurusgames.com/2011/06/texture-atlas-generation-using-python/
        # for its initial implementation.
        try:
            from PIL import Image
        except ImportError:
            Logger.critical('Atlas: Imaging/PIL are missing')
            raise

        if isinstance(size, (tuple, list)):
            size_w, size_h = list(map(int, size))
        else:
            size_w = size_h = int(size)

        # open all of the images
        ims = list()
        for f in filenames:
            fp = open(f, 'rb')
            im = Image.open(fp)
            im.load()
            fp.close()
            ims.append((f, im))

        # sort by image area
        ims = sorted(ims, key=lambda im: im[1].size[0] * im[1].size[1],
                     reverse=True)

        # free boxes are empty space in our output image set
        # the freebox tuple format is: outidx, x, y, w, h
        freeboxes = [(0, 0, 0, size_w, size_h)]
        numoutimages = 1

        # full boxes are areas where we have placed images in the atlas
        # the full box tuple format is: image, outidx, x, y, w, h, filename
        fullboxes = []

        # do the actual atlasing by sticking the largest images we can
        # have into the smallest valid free boxes
        for imageinfo in ims:
            im = imageinfo[1]
            imw, imh = im.size
            imw += padding
            imh += padding
            if imw > size_w or imh > size_h:
                Logger.error(
                    'Atlas: image %s (%d by %d) is larger than the atlas size!'
                    % (imageinfo[0], imw, imh))
                return

            inserted = False
            while not inserted:
                for idx, fb in enumerate(freeboxes):
                    # find the smallest free box that will contain this image
                    if fb[3] >= imw and fb[4] >= imh:
                        # we found a valid spot! Remove the current
                        # freebox, and split the leftover space into (up to)
                        # two new freeboxes
                        del freeboxes[idx]
                        if fb[3] > imw:
                            freeboxes.append((
                                fb[0], fb[1] + imw, fb[2],
                                fb[3] - imw, imh))

                        if fb[4] > imh:
                            freeboxes.append((
                                fb[0], fb[1], fb[2] + imh,
                                fb[3], fb[4] - imh))

                        # keep this sorted!
                        freeboxes = sorted(freeboxes,
                                           key=lambda fb: fb[3] * fb[4])
                        fullboxes.append((im,
                                          fb[0], fb[1] + padding,
                                          fb[2] + padding, imw - padding,
                                          imh - padding, imageinfo[0]))
                        inserted = True
                        break

                if not inserted:
                    # oh crap - there isn't room in any of our free
                    # boxes, so we have to add a new output image
                    freeboxes.append((numoutimages, 0, 0, size_w, size_h))
                    numoutimages += 1

        # now that we've figured out where everything goes, make the output
        # images and blit the source images to the appropriate locations
        Logger.info('Atlas: create an {0}x{1} rgba image'.format(size_w,
                                                                 size_h))
        outimages = [Image.new('RGBA', (size_w, size_h))
                     for i in range(0, int(numoutimages))]
        for fb in fullboxes:
            x, y = fb[2], fb[3]
            out = outimages[fb[1]]
            out.paste(fb[0], (fb[2], fb[3]))
            w, h = fb[0].size
            if padding > 1:
                out.paste(fb[0].crop((0, 0, w, 1)), (x, y - 1))
                out.paste(fb[0].crop((0, h - 1, w, h)), (x, y + h))
                out.paste(fb[0].crop((0, 0, 1, h)), (x - 1, y))
                out.paste(fb[0].crop((w - 1, 0, w, h)), (x + w, y))

        # save the output images
        for idx, outimage in enumerate(outimages):
            outimage.save('%s-%d.png' % (outname, idx))

        # write out an json file that says where everything ended up
        meta = {}
        for fb in fullboxes:
            fn = '%s-%d.png' % (basename(outname), fb[1])
            if fn not in meta:
                d = meta[fn] = {}
            else:
                d = meta[fn]

            # fb[6] contain the filename
            if use_path:
                # use the path with separators replaced by _
                # example '../data/tiles/green_grass.png' becomes
                # 'data_tiles_green_grass'
                uid = splitext(fb[6])[0]
                # remove leading dots and slashes
                uid = uid.lstrip('./\\')
                # replace remaining slashes with _
                uid = uid.replace('/', '_').replace('\\', '_')
            else:
                # for example, '../data/tiles/green_grass.png'
                # just get only 'green_grass' as the uniq id.
                uid = splitext(basename(fb[6]))[0]

            x, y, w, h = fb[2:6]
            d[uid] = x, size_h - y - h, w, h

        outfn = '%s.atlas' % outname
        with open(outfn, 'w') as fd:
            json.dump(meta, fd)

        return outfn, meta

if __name__ == '__main__':
    """ Main line program. Process command line arguments
    to make a new atlas. """

    import sys
    from glob import glob
    argv = sys.argv[1:]
    # earlier import of kivy has already called getopt to remove kivy system
    # arguments from this line. That is all arguments up to the first '--'
    if len(argv) < 3:
        print('Usage: python -m kivy.atlas [-- [--use-path] '
              '[--padding=2]] <outname> '
              '<size|512x256> <img1.png> [<img2.png>, ...]')
        sys.exit(1)

    options = {'use_path': False}
    while True:
        option = argv[0]
        if option == '--use-path':
            options['use_path'] = True
        elif option.startswith('--padding='):
            options['padding'] = int(option.split('=', 1)[-1])
        elif option[:2] == '--':
            print('Unknown option {}'.format(option))
            sys.exit(1)
        else:
            break
        argv = argv[1:]

    outname = argv[0]
    try:
        if 'x' in argv[1]:
            size = list(map(int, argv[1].split('x', 1)))
        else:
            size = int(argv[1])
    except ValueError:
        print('Error: size must be an integer or <integer>x<integer>')
        sys.exit(1)

    filenames = [fname for fnames in argv[2:] for fname in glob(fnames)]
    ret = Atlas.create(outname, filenames, size, **options)
    if not ret:
        print('Error while creating atlas!')
        sys.exit(1)

    fn, meta = ret
    print('Atlas created at', fn)
    print('%d image%s been created' % (len(meta),
          's have' if len(meta) > 1 else ' has'))


text:
package org.javers.spring.boot;

import org.javers.core.Javers;
import org.javers.repository.sql.ConnectionProvider;
import org.javers.repository.sql.DialectName;
import org.javers.repository.sql.JaversSqlRepository;
import org.javers.repository.sql.SqlRepositoryBuilder;
import org.javers.spring.auditable.AuthorProvider;
import org.javers.spring.auditable.aspect.JaversAuditableRepositoryAspect;
import org.javers.spring.jpa.JpaHibernateConnectionProvider;
import org.javers.spring.jpa.TransactionalJaversBuilder;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

/**
 * @author bartosz.walacik
 */
@Configuration
public class JaversSpringBootConfig {

    @Bean
    public Javers javers() {
        JaversSqlRepository sqlRepository = SqlRepositoryBuilder
                .sqlRepository()
                .withConnectionProvider(jpaConnectionProvider())
                .withDialect(DialectName.H2)
                .build();

        return TransactionalJaversBuilder
                .javers()
                .registerJaversRepository(sqlRepository)
                .build();
    }

    @Bean
    public JaversAuditableRepositoryAspect javersAuditableRepositoryAspect() {
        return new JaversAuditableRepositoryAspect(javers(), authorProvider());
    }

    @Bean
    public ConnectionProvider jpaConnectionProvider() {
        return new JpaHibernateConnectionProvider();
    }

    @Bean
    public AuthorProvider authorProvider() {
        return new AuthorProvider() {
            public String provide() {
                return "unknown";
            }
        };
    }

}