text:
XmlElement::XmlAttributeNode::XmlAttributeNode (const XmlAttributeNode& other) noexcept
    : name (other.name),
      value (other.value)
{
}

XmlElement::XmlAttributeNode::XmlAttributeNode (const Identifier& n, const String& v) noexcept
    : name (n), value (v)
{
   #if JUCE_DEBUG
    // this checks whether the attribute name string contains any illegal characters..
    for (String::CharPointerType t (name.getCharPointer()); ! t.isEmpty(); ++t)
        jassert (t.isLetterOrDigit() || *t == '_' || *t == '-' || *t == ':');
   #endif
}

XmlElement::XmlAttributeNode::XmlAttributeNode (String::CharPointerType nameStart, String::CharPointerType nameEnd)
    : name (nameStart, nameEnd)
{
}

//==============================================================================
static void sanityCheckTagName (const String& tag)
{
    (void) tag;

    // the tag name mustn't be empty, or it'll look like a text element!
    jassert (tag.containsNonWhitespaceChars());

    // The tag can't contain spaces or other characters that would create invalid XML!
    jassert (! tag.containsAnyOf (" <>/&(){}"));
}

XmlElement::XmlElement (const String& tag)
    : tagName (StringPool::getGlobalPool().getPooledString (tag))
{
    sanityCheckTagName (tagName);
}

XmlElement::XmlElement (const char* tag)
    : tagName (StringPool::getGlobalPool().getPooledString (tag))
{
    sanityCheckTagName (tagName);
}

XmlElement::XmlElement (StringRef tag)
    : tagName (StringPool::getGlobalPool().getPooledString (tag))
{
    sanityCheckTagName (tagName);
}

XmlElement::XmlElement (const Identifier& tag)
    : tagName (tag.toString())
{
    sanityCheckTagName (tagName);
}

XmlElement::XmlElement (String::CharPointerType tagNameStart, String::CharPointerType tagNameEnd)
    : tagName (StringPool::getGlobalPool().getPooledString (tagNameStart, tagNameEnd))
{
    sanityCheckTagName (tagName);
}

XmlElement::XmlElement (int /*dummy*/) noexcept
{
}

XmlElement::XmlElement (const XmlElement& other)
    : tagName (other.tagName)
{
    copyChildrenAndAttributesFrom (other);
}

XmlElement& XmlElement::operator= (const XmlElement& other)
{
    if (this != &other)
    {
        removeAllAttributes();
        deleteAllChildElements();
        tagName = other.tagName;
        copyChildrenAndAttributesFrom (other);
    }

    return *this;
}

#if JUCE_COMPILER_SUPPORTS_MOVE_SEMANTICS
XmlElement::XmlElement (XmlElement&& other) noexcept
    : nextListItem      (static_cast<LinkedListPointer<XmlElement>&&> (other.nextListItem)),
      firstChildElement (static_cast<LinkedListPointer<XmlElement>&&> (other.firstChildElement)),
      attributes        (static_cast<LinkedListPointer<XmlAttributeNode>&&> (other.attributes)),
      tagName           (static_cast<String&&> (other.tagName))
{
}

XmlElement& XmlElement::operator= (XmlElement&& other) noexcept
{
    jassert (this != &other); // hopefully the compiler should make this situation impossible!

    removeAllAttributes();
    deleteAllChildElements();

    nextListItem      = static_cast<LinkedListPointer<XmlElement>&&> (other.nextListItem);
    firstChildElement = static_cast<LinkedListPointer<XmlElement>&&> (other.firstChildElement);
    attributes        = static_cast<LinkedListPointer<XmlAttributeNode>&&> (other.attributes);
    tagName           = static_cast<String&&> (other.tagName);

    return *this;
}
#endif

void XmlElement::copyChildrenAndAttributesFrom (const XmlElement& other)
{
    jassert (firstChildElement.get() == nullptr);
    firstChildElement.addCopyOfList (other.firstChildElement);

    jassert (attributes.get() == nullptr);
    attributes.addCopyOfList (other.attributes);
}

XmlElement::~XmlElement() noexcept
{
    firstChildElement.deleteAll();
    attributes.deleteAll();
}

//==============================================================================
namespace XmlOutputFunctions
{
   #if 0 // (These functions are just used to generate the lookup table used below)
    bool isLegalXmlCharSlow (const juce_wchar character) noexcept
    {
        if ((character >= 'a' && character <= 'z')
             || (character >= 'A' && character <= 'Z')
                || (character >= '0' && character <= '9'))
            return true;

        const char* t = " .,;:-()_+=?!'#@[]/\\*%~{}$|";

        do
        {
            if (((juce_wchar) (uint8) *t) == character)
                return true;
        }
        while (*++t != 0);

        return false;
    }

    void generateLegalCharLookupTable()
    {
        uint8 n[32] = { 0 };
        for (int i = 0; i < 256; ++i)
            if (isLegalXmlCharSlow (i))
                n[i >> 3] |= (1 << (i & 7));

        String s;
        for (int i = 0; i < 32; ++i)
            s << (int) n[i] << ", ";

        DBG (s);
    }
   #endif

    static bool isLegalXmlChar (const uint32 c) noexcept
    {
        static const unsigned char legalChars[] = { 0, 0, 0, 0, 187, 255, 255, 175, 255,
                                                    255, 255, 191, 254, 255, 255, 127 };
        return c < sizeof (legalChars) * 8
                 && (legalChars [c >> 3] & (1 << (c & 7))) != 0;
    }

    static void escapeIllegalXmlChars (OutputStream& outputStream, const String& text, const bool changeNewLines)
    {
        String::CharPointerType t (text.getCharPointer());

        for (;;)
        {
            const uint32 character = (uint32) t.getAndAdvance();

            if (character == 0)
                break;

            if (isLegalXmlChar (character))
            {
                outputStream << (char) character;
            }
            else
            {
                switch (character)
                {
                case '&':   outputStream << "&"; break;
                case '"':   outputStream << """; break;
                case '>':   outputStream << ">"; break;
                case '<':   outputStream << "<"; break;

                case '\n':
                case '\r':
                    if (! changeNewLines)
                    {
                        outputStream << (char) character;
                        break;
                    }
                    // Note: deliberate fall-through here!
                default:
                    outputStream << "&#" << ((int) character) << ';';
                    break;
                }
            }
        }
    }

    static void writeSpaces (OutputStream& out, const size_t numSpaces)
    {
        out.writeRepeatedByte (' ', numSpaces);
    }
}

void XmlElement::writeElementAsText (OutputStream& outputStream,
                                     const int indentationLevel,
                                     const int lineWrapLength) const
{
    using namespace XmlOutputFunctions;

    if (indentationLevel >= 0)
        writeSpaces (outputStream, (size_t) indentationLevel);

    if (! isTextElement())
    {
        outputStream.writeByte ('<');
        outputStream << tagName;

        {
            const size_t attIndent = (size_t) (indentationLevel + tagName.length() + 1);
            int lineLen = 0;

            for (const XmlAttributeNode* att = attributes; att != nullptr; att = att->nextListItem)
            {
                if (lineLen > lineWrapLength && indentationLevel >= 0)
                {
                    outputStream << newLine;
                    writeSpaces (outputStream, attIndent);
                    lineLen = 0;
                }

                const int64 startPos = outputStream.getPosition();
                outputStream.writeByte (' ');
                outputStream << att->name;
                outputStream.write ("=\"", 2);
                escapeIllegalXmlChars (outputStream, att->value, true);
                outputStream.writeByte ('"');
                lineLen += (int) (outputStream.getPosition() - startPos);
            }
        }

        if (firstChildElement != nullptr)
        {
            outputStream.writeByte ('>');

            bool lastWasTextNode = false;

            for (XmlElement* child = firstChildElement; child != nullptr; child = child->nextListItem)
            {
                if (child->isTextElement())
                {
                    escapeIllegalXmlChars (outputStream, child->getText(), false);
                    lastWasTextNode = true;
                }
                else
                {
                    if (indentationLevel >= 0 && ! lastWasTextNode)
                        outputStream << newLine;

                    child->writeElementAsText (outputStream,
                                               lastWasTextNode ? 0 : (indentationLevel + (indentationLevel >= 0 ? 2 : 0)), lineWrapLength);
                    lastWasTextNode = false;
                }
            }

            if (indentationLevel >= 0 && ! lastWasTextNode)
            {
                outputStream << newLine;
                writeSpaces (outputStream, (size_t) indentationLevel);
            }

            outputStream.write ("</", 2);
            outputStream << tagName;
            outputStream.writeByte ('>');
        }
        else
        {
            outputStream.write ("/>", 2);
        }
    }
    else
    {
        escapeIllegalXmlChars (outputStream, getText(), false);
    }
}

String XmlElement::createDocument (StringRef dtdToUse,
                                   const bool allOnOneLine,
                                   const bool includeXmlHeader,
                                   StringRef encodingType,
                                   const int lineWrapLength) const
{
    MemoryOutputStream mem (2048);
    writeToStream (mem, dtdToUse, allOnOneLine, includeXmlHeader, encodingType, lineWrapLength);

    return mem.toUTF8();
}

void XmlElement::writeToStream (OutputStream& output,
                                StringRef dtdToUse,
                                const bool allOnOneLine,
                                const bool includeXmlHeader,
                                StringRef encodingType,
                                const int lineWrapLength) const
{
    using namespace XmlOutputFunctions;

    if (includeXmlHeader)
    {
        output << "<?xml version=\"1.0\" encoding=\"" << encodingType << "\"?>";

        if (allOnOneLine)
            output.writeByte (' ');
        else
            output << newLine << newLine;
    }

    if (dtdToUse.isNotEmpty())
    {
        output << dtdToUse;

        if (allOnOneLine)
            output.writeByte (' ');
        else
            output << newLine;
    }

    writeElementAsText (output, allOnOneLine ? -1 : 0, lineWrapLength);

    if (! allOnOneLine)
        output << newLine;
}

bool XmlElement::writeToFile (const File& file,
                              StringRef dtdToUse,
                              StringRef encodingType,
                              const int lineWrapLength) const
{
    TemporaryFile tempFile (file);

    {
        FileOutputStream out (tempFile.getFile());

        if (! out.openedOk())
            return false;

        writeToStream (out, dtdToUse, false, true, encodingType, lineWrapLength);
    }

    return tempFile.overwriteTargetFileWithTemporary();
}

//==============================================================================
bool XmlElement::hasTagName (StringRef possibleTagName) const noexcept
{
    const bool matches = tagName.equalsIgnoreCase (possibleTagName);

    // XML tags should be case-sensitive, so although this method allows a
    // case-insensitive match to pass, you should try to avoid this.
    jassert ((! matches) || tagName == possibleTagName);

    return matches;
}

String XmlElement::getNamespace() const
{
    return tagName.upToFirstOccurrenceOf (":", false, false);
}

String XmlElement::getTagNameWithoutNamespace() const
{
    return tagName.fromLastOccurrenceOf (":", false, false);
}

bool XmlElement::hasTagNameIgnoringNamespace (StringRef possibleTagName) const
{
    return hasTagName (possibleTagName) || getTagNameWithoutNamespace() == possibleTagName;
}

XmlElement* XmlElement::getNextElementWithTagName (StringRef requiredTagName) const
{
    XmlElement* e = nextListItem;

    while (e != nullptr && ! e->hasTagName (requiredTagName))
        e = e->nextListItem;

    return e;
}

//==============================================================================
int XmlElement::getNumAttributes() const noexcept
{
    return attributes.size();
}

const String& XmlElement::getAttributeName (const int index) const noexcept
{
    if (const XmlAttributeNode* const att = attributes [index])
        return att->name.toString();

    return String::empty;
}

const String& XmlElement::getAttributeValue (const int index) const noexcept
{
    if (const XmlAttributeNode* const att = attributes [index])
        return att->value;

    return String::empty;
}

XmlElement::XmlAttributeNode* XmlElement::getAttribute (StringRef attributeName) const noexcept
{
    for (XmlAttributeNode* att = attributes; att != nullptr; att = att->nextListItem)
        if (att->name == attributeName)
            return att;

    return nullptr;
}

bool XmlElement::hasAttribute (StringRef attributeName) const noexcept
{
    return getAttribute (attributeName) != nullptr;
}

//==============================================================================
const String& XmlElement::getStringAttribute (StringRef attributeName) const noexcept
{
    if (const XmlAttributeNode* att = getAttribute (attributeName))
        return att->value;

    return String::empty;
}

String XmlElement::getStringAttribute (StringRef attributeName, const String& defaultReturnValue) const
{
    if (const XmlAttributeNode* att = getAttribute (attributeName))
        return att->value;

    return defaultReturnValue;
}

int XmlElement::getIntAttribute (StringRef attributeName, const int defaultReturnValue) const
{
    if (const XmlAttributeNode* att = getAttribute (attributeName))
        return att->value.getIntValue();

    return defaultReturnValue;
}

double XmlElement::getDoubleAttribute (StringRef attributeName, const double defaultReturnValue) const
{
    if (const XmlAttributeNode* att = getAttribute (attributeName))
        return att->value.getDoubleValue();

    return defaultReturnValue;
}

bool XmlElement::getBoolAttribute (StringRef attributeName, const bool defaultReturnValue) const
{
    if (const XmlAttributeNode* att = getAttribute (attributeName))
    {
        const juce_wchar firstChar = *(att->value.getCharPointer().findEndOfWhitespace());

        return firstChar == '1'
            || firstChar == 't'
            || firstChar == 'y'
            || firstChar == 'T'
            || firstChar == 'Y';
    }

    return defaultReturnValue;
}

bool XmlElement::compareAttribute (StringRef attributeName,
                                   StringRef stringToCompareAgainst,
                                   const bool ignoreCase) const noexcept
{
    if (const XmlAttributeNode* att = getAttribute (attributeName))
        return ignoreCase ? att->value.equalsIgnoreCase (stringToCompareAgainst)
                          : att->value == stringToCompareAgainst;

    return false;
}

//==============================================================================
void XmlElement::setAttribute (const Identifier& attributeName, const String& value)
{
    if (attributes == nullptr)
    {
        attributes = new XmlAttributeNode (attributeName, value);
    }
    else
    {
        for (XmlAttributeNode* att = attributes; ; att = att->nextListItem)
        {
            if (att->name == attributeName)
            {
                att->value = value;
                break;
            }

            if (att->nextListItem == nullptr)
            {
                att->nextListItem = new XmlAttributeNode (attributeName, value);
                break;
            }
        }
    }
}

void XmlElement::setAttribute (const Identifier& attributeName, const int number)
{
    setAttribute (attributeName, String (number));
}

void XmlElement::setAttribute (const Identifier& attributeName, const double number)
{
    setAttribute (attributeName, String (number, 20));
}

void XmlElement::removeAttribute (const Identifier& attributeName) noexcept
{
    for (LinkedListPointer<XmlAttributeNode>* att = &attributes;
         att->get() != nullptr;
         att = &(att->get()->nextListItem))
    {
        if (att->get()->name == attributeName)
        {
            delete att->removeNext();
            break;
        }
    }
}

void XmlElement::removeAllAttributes() noexcept
{
    attributes.deleteAll();
}

//==============================================================================
int XmlElement::getNumChildElements() const noexcept
{
    return firstChildElement.size();
}

XmlElement* XmlElement::getChildElement (const int index) const noexcept
{
    return firstChildElement [index].get();
}

XmlElement* XmlElement::getChildByName (StringRef childName) const noexcept
{
    jassert (! childName.isEmpty());

    for (XmlElement* child = firstChildElement; child != nullptr; child = child->nextListItem)
        if (child->hasTagName (childName))
            return child;

    return nullptr;
}

XmlElement* XmlElement::getChildByAttribute (StringRef attributeName, StringRef attributeValue) const noexcept
{
    jassert (! attributeName.isEmpty());

    for (XmlElement* child = firstChildElement; child != nullptr; child = child->nextListItem)
        if (child->compareAttribute (attributeName, attributeValue))
            return child;

    return nullptr;
}

void XmlElement::addChildElement (XmlElement* const newNode) noexcept
{
    if (newNode != nullptr)
    {
        // The element being added must not be a child of another node!
        jassert (newNode->nextListItem == nullptr);

        firstChildElement.append (newNode);
    }
}

void XmlElement::insertChildElement (XmlElement* const newNode, int indexToInsertAt) noexcept
{
    if (newNode != nullptr)
    {
        // The element being added must not be a child of another node!
        jassert (newNode->nextListItem == nullptr);

        firstChildElement.insertAtIndex (indexToInsertAt, newNode);
    }
}

void XmlElement::prependChildElement (XmlElement* newNode) noexcept
{
    if (newNode != nullptr)
    {
        // The element being added must not be a child of another node!
        jassert (newNode->nextListItem == nullptr);

        firstChildElement.insertNext (newNode);
    }
}

XmlElement* XmlElement::createNewChildElement (StringRef childTagName)
{
    XmlElement* const newElement = new XmlElement (childTagName);
    addChildElement (newElement);
    return newElement;
}

bool XmlElement::replaceChildElement (XmlElement* const currentChildElement,
                                      XmlElement* const newNode) noexcept
{
    if (newNode != nullptr)
    {
        if (LinkedListPointer<XmlElement>* const p = firstChildElement.findPointerTo (currentChildElement))
        {
            if (currentChildElement != newNode)
                delete p->replaceNext (newNode);

            return true;
        }
    }

    return false;
}

void XmlElement::removeChildElement (XmlElement* const childToRemove,
                                     const bool shouldDeleteTheChild) noexcept
{
    if (childToRemove != nullptr)
    {
        firstChildElement.remove (childToRemove);

        if (shouldDeleteTheChild)
            delete childToRemove;
    }
}

bool XmlElement::isEquivalentTo (const XmlElement* const other,
                                 const bool ignoreOrderOfAttributes) const noexcept
{
    if (this != other)
    {
        if (other == nullptr || tagName != other->tagName)
            return false;

        if (ignoreOrderOfAttributes)
        {
            int totalAtts = 0;

            for (const XmlAttributeNode* att = attributes; att != nullptr; att = att->nextListItem)
            {
                if (! other->compareAttribute (att->name, att->value))
                    return false;

                ++totalAtts;
            }

            if (totalAtts != other->getNumAttributes())
                return false;
        }
        else
        {
            const XmlAttributeNode* thisAtt = attributes;
            const XmlAttributeNode* otherAtt = other->attributes;

            for (;;)
            {
                if (thisAtt == nullptr || otherAtt == nullptr)
                {
                    if (thisAtt == otherAtt) // both nullptr, so it's a match
                        break;

                    return false;
                }

                if (thisAtt->name != otherAtt->name
                     || thisAtt->value != otherAtt->value)
                {
                    return false;
                }

                thisAtt = thisAtt->nextListItem;
                otherAtt = otherAtt->nextListItem;
            }
        }

        const XmlElement* thisChild = firstChildElement;
        const XmlElement* otherChild = other->firstChildElement;

        for (;;)
        {
            if (thisChild == nullptr || otherChild == nullptr)
            {
                if (thisChild == otherChild) // both 0, so it's a match
                    break;

                return false;
            }

            if (! thisChild->isEquivalentTo (otherChild, ignoreOrderOfAttributes))
                return false;

            thisChild = thisChild->nextListItem;
            otherChild = otherChild->nextListItem;
        }
    }

    return true;
}

void XmlElement::deleteAllChildElements() noexcept
{
    firstChildElement.deleteAll();
}

void XmlElement::deleteAllChildElementsWithTagName (StringRef name) noexcept
{
    for (XmlElement* child = firstChildElement; child != nullptr;)
    {
        XmlElement* const nextChild = child->nextListItem;

        if (child->hasTagName (name))
            removeChildElement (child, true);

        child = nextChild;
    }
}

bool XmlElement::containsChildElement (const XmlElement* const possibleChild) const noexcept
{
    return firstChildElement.contains (possibleChild);
}

XmlElement* XmlElement::findParentElementOf (const XmlElement* const elementToLookFor) noexcept
{
    if (this == elementToLookFor || elementToLookFor == nullptr)
        return nullptr;

    for (XmlElement* child = firstChildElement; child != nullptr; child = child->nextListItem)
    {
        if (elementToLookFor == child)
            return this;

        if (XmlElement* const found = child->findParentElementOf (elementToLookFor))
            return found;
    }

    return nullptr;
}

void XmlElement::getChildElementsAsArray (XmlElement** elems) const noexcept
{
    firstChildElement.copyToArray (elems);
}

void XmlElement::reorderChildElements (XmlElement** const elems, const int num) noexcept
{
    XmlElement* e = firstChildElement = elems[0];

    for (int i = 1; i < num; ++i)
    {
        e->nextListItem = elems[i];
        e = e->nextListItem;
    }

    e->nextListItem = nullptr;
}

//==============================================================================
bool XmlElement::isTextElement() const noexcept
{
    return tagName.isEmpty();
}

static const String juce_xmltextContentAttributeName ("text");

const String& XmlElement::getText() const noexcept
{
    jassert (isTextElement());  // you're trying to get the text from an element that
                                // isn't actually a text element.. If this contains text sub-nodes, you
                                // probably want to use getAllSubText instead.

    return getStringAttribute (juce_xmltextContentAttributeName);
}

void XmlElement::setText (const String& newText)
{
    if (isTextElement())
        setAttribute (juce_xmltextContentAttributeName, newText);
    else
        jassertfalse; // you can only change the text in a text element, not a normal one.
}

String XmlElement::getAllSubText() const
{
    if (isTextElement())
        return getText();

    if (getNumChildElements() == 1)
        return firstChildElement.get()->getAllSubText();

    MemoryOutputStream mem (1024);

    for (const XmlElement* child = firstChildElement; child != nullptr; child = child->nextListItem)
        mem << child->getAllSubText();

    return mem.toUTF8();
}

String XmlElement::getChildElementAllSubText (StringRef childTagName, const String& defaultReturnValue) const
{
    if (const XmlElement* const child = getChildByName (childTagName))
        return child->getAllSubText();

    return defaultReturnValue;
}

XmlElement* XmlElement::createTextElement (const String& text)
{
    XmlElement* const e = new XmlElement ((int) 0);
    e->setAttribute (juce_xmltextContentAttributeName, text);
    return e;
}

void XmlElement::addTextElement (const String& text)
{
    addChildElement (createTextElement (text));
}

void XmlElement::deleteAllTextElements() noexcept
{
    for (XmlElement* child = firstChildElement; child != nullptr;)
    {
        XmlElement* const next = child->nextListItem;

        if (child->isTextElement())
            removeChildElement (child, true);

        child = next;
    }
}


text:
/// @file iotbus_pwm.h
/// @brief Test Case of APIs for PWM

#include <tinyara/config.h>
#include <stdio.h>
#include <errno.h>
#include "itc_internal.h"
#include <iotbus_pwm.h>
#include <iotbus_error.h>

/**
* @testcase         itc_systemio_pwm_open_close_p
* @brief            open and closes the pwm_context
* @scenario         open and closes the pwm_context
* @apicovered       iotbus_pwm_open, iotbus_pwm_close
* @precondition     none
* @postcondition    none
*/
void itc_systemio_pwm_open_close_p(void)
{
	int ret = 0;
	iotbus_pwm_context_h h_pwm = iotbus_pwm_open(CONFIG_SYSIO_ITC_PWM_DEVICE, CONFIG_SYSIO_ITC_PWM_CHANNEL);
	TC_ASSERT_NEQ("iotbus_pwm_open", h_pwm, NULL);

	ret = iotbus_pwm_close(h_pwm);
	TC_ASSERT_EQ("iotbus_pwm_close", ret, OK);

	TC_SUCCESS_RESULT();
}

/**
* @testcase         itc_systemio_pwm_set_get_duty_cycle_p
* @brief            sets and gets the pwm duty cycle
* @scenario         sets and gets the same pwm duty cycle
* @apicovered       iotbus_pwm_set_duty_cycle, iotbus_pwm_get_duty_cycle
* @precondition     opens the pwm_context
* @postcondition    closes the pwm_context
*/
void itc_systemio_pwm_set_get_duty_cycle_p(void)
{
	int cycle = 20;
	int ret = 0;
	iotbus_pwm_context_h h_pwm = iotbus_pwm_open(CONFIG_SYSIO_ITC_PWM_DEVICE, CONFIG_SYSIO_ITC_PWM_CHANNEL);
	TC_ASSERT_NEQ("iotbus_pwm_open", h_pwm, NULL);

	ret = iotbus_pwm_set_duty_cycle(h_pwm, cycle);
	TC_ASSERT_EQ_CLEANUP("iotbus_pwm_set_duty_cycle", ret, OK, iotbus_pwm_close(h_pwm));

	ret = iotbus_pwm_get_duty_cycle(h_pwm);
	TC_ASSERT_EQ_CLEANUP("iotbus_pwm_get_duty_cycle", ret, cycle, iotbus_pwm_close(h_pwm));

	ret = iotbus_pwm_close(h_pwm);
	TC_ASSERT_EQ("iotbus_pwm_close", ret, OK);

	TC_SUCCESS_RESULT();
}

/**
* @testcase         itc_systemio_pwm_set_get_period_p
* @brief            sets and gets the pwm period
* @scenario         sets and gets the same pwm period
* @apicovered       iotbus_pwm_set_period, iotbus_pwm_get_period
* @precondition     opens the pwm_context
* @postcondition    closes the pwm_context
*/
void itc_systemio_pwm_set_get_period_p(void)
{
	int ret = 0;
	iotbus_pwm_context_h h_pwm = iotbus_pwm_open(CONFIG_SYSIO_ITC_PWM_DEVICE, CONFIG_SYSIO_ITC_PWM_CHANNEL);
	TC_ASSERT_NEQ("iotbus_pwm_open", h_pwm, NULL);

	ret = iotbus_pwm_set_period(h_pwm, CONFIG_SYSIO_ITC_PWM_PERIOD);
	TC_ASSERT_EQ_CLEANUP("iotbus_pwm_set_period", ret, OK, iotbus_pwm_close(h_pwm));

	ret = iotbus_pwm_get_period(h_pwm);
	TC_ASSERT_EQ_CLEANUP("iotbus_pwm_get_period", ret, CONFIG_SYSIO_ITC_PWM_PERIOD, iotbus_pwm_close(h_pwm));

	ret = iotbus_pwm_close(h_pwm);
	TC_ASSERT_EQ("iotbus_pwm_close", ret, OK);

	TC_SUCCESS_RESULT();
}

/**
* @testcase         itc_systemio_pwm_set_period_is_enabled_p
* @brief            checks if pwm state is enabled
* @scenario         sets and gets the same pwm period and checks if pwm state is enabled
* @apicovered       iotbus_pwm_is_enabled
* @precondition     opens the pwm_context
* @postcondition    closes the pwm_context
*/
void itc_systemio_pwm_set_period_is_enabled_p(void)
{
	int ret = 0;
	int default_state = 0;
	int get_state = 0;
	iotbus_pwm_context_h h_pwm = iotbus_pwm_open(CONFIG_SYSIO_ITC_PWM_DEVICE, CONFIG_SYSIO_ITC_PWM_CHANNEL);
	TC_ASSERT_NEQ("iotbus_pwm_open", h_pwm, NULL);

	ret = iotbus_pwm_set_period(h_pwm, CONFIG_SYSIO_ITC_PWM_PERIOD);
	TC_ASSERT_EQ_CLEANUP("iotbus_pwm_set_period", ret, OK, iotbus_pwm_close(h_pwm));

	ret = iotbus_pwm_get_period(h_pwm);
	TC_ASSERT_EQ_CLEANUP("iotbus_pwm_get_period", ret, CONFIG_SYSIO_ITC_PWM_PERIOD, iotbus_pwm_close(h_pwm));

	default_state = iotbus_pwm_is_enabled(h_pwm);
	TC_ASSERT_EQ_CLEANUP("iotbus_pwm_is_enabled", default_state < OK, false, iotbus_pwm_close(h_pwm));

	iotbus_pwm_state_e e_state = IOTBUS_PWM_ENABLE;
	if (default_state == IOTBUS_PWM_DISABLE) {
		ret = iotbus_pwm_set_enabled(h_pwm, e_state);
		TC_ASSERT_EQ_CLEANUP("iotbus_pwm_set_enabled", ret, OK, iotbus_pwm_close(h_pwm));

		get_state = iotbus_pwm_is_enabled(h_pwm);
		TC_ASSERT_EQ_CLEANUP("iotbus_pwm_is_enabled", get_state, e_state, iotbus_pwm_close(h_pwm); iotbus_pwm_set_enabled(h_pwm, default_state));

		// Restoring default state
		iotbus_pwm_set_enabled(h_pwm, default_state);
	} else {
		e_state = IOTBUS_PWM_DISABLE;
		ret = iotbus_pwm_set_enabled(h_pwm, e_state);
		TC_ASSERT_EQ_CLEANUP("iotbus_pwm_set_enabled", ret, OK, iotbus_pwm_close(h_pwm));

		get_state = iotbus_pwm_is_enabled(h_pwm);
		TC_ASSERT_EQ_CLEANUP("iotbus_pwm_is_enabled", get_state, e_state, iotbus_pwm_close(h_pwm); iotbus_pwm_set_enabled(h_pwm, default_state));

		// Restoring default state
		iotbus_pwm_set_enabled(h_pwm, default_state);
	}

	ret = iotbus_pwm_close(h_pwm);
	TC_ASSERT_NEQ("iotbus_pwm_close", h_pwm, NULL);

	TC_SUCCESS_RESULT();
}

/**
* @testcase         itc_systemio_pwm_set_get_duty_cycle_p_different_cycle
* @brief            sets and gets the pwm duty cycle
* @scenario         sets and gets the same pwm duty cycle for all cycle values
* @apicovered       iotbus_pwm_set_duty_cycle, iotbus_pwm_get_duty_cycle
* @precondition     opens the pwm_context
* @postcondition    closes the pwm_context
*/
void itc_systemio_pwm_set_get_duty_cycle_p_different_cycle(void)
{
	int cycle;
	int ret = 0;
	bool check = true;
	iotbus_pwm_context_h h_pwm = iotbus_pwm_open(CONFIG_SYSIO_ITC_PWM_DEVICE, CONFIG_SYSIO_ITC_PWM_CHANNEL);
	TC_ASSERT_NEQ("iotbus_pwm_open", h_pwm, NULL);

	for (cycle = 0; cycle <= 100; cycle++) {
		ret = iotbus_pwm_set_duty_cycle(h_pwm, cycle);
		if (ret != OK) {
			check = false;
			SYSIO_ITC_PRINT("\nitc_pwm_set_get_duty_cycle_p: iotbus_pwm_set_duty_cycle FAIL for cycle : %d\n", cycle);
			continue;
		}

		ret = iotbus_pwm_get_duty_cycle(h_pwm);
		if (ret != cycle) {
			check = false;
			SYSIO_ITC_PRINT("\nitc_pwm_set_get_duty_cycle_p: iotbus_pwm_get_duty_cycle FAIL for cycle : %d\n", cycle);
			continue;
		}
	}
	TC_ASSERT_EQ_CLEANUP("itc_systemio_pwm_set_get_duty_cycle_p_different_cycle", check, true, iotbus_pwm_close(h_pwm));
	ret = iotbus_pwm_close(h_pwm);
	TC_ASSERT_EQ("iotbus_pwm_close", ret, OK);

	TC_SUCCESS_RESULT();
}

/**
* @testcase         itc_systemio_pwm_set_get_period_p_different_period
* @brief            sets and gets the pwm period
* @scenario         sets and gets the same pwm period
* @apicovered       iotbus_pwm_set_period, iotbus_pwm_get_period
* @precondition     opens the pwm_context
* @postcondition    closes the pwm_context
*/
void itc_systemio_pwm_set_get_period_p_different_period(void)
{
	int period[] = { 10, 100, 1000, 10000, 100000, 1000000 };
	int count;
	int index;
	int ret = 0;
	bool check = true;
	count = sizeof(period) / sizeof(period[0]);
	iotbus_pwm_context_h h_pwm = iotbus_pwm_open(CONFIG_SYSIO_ITC_PWM_DEVICE, CONFIG_SYSIO_ITC_PWM_CHANNEL);
	TC_ASSERT_NEQ("iotbus_pwm_open", h_pwm, NULL);

	for (index = 0; index < count; index++) {
		ret = iotbus_pwm_set_period(h_pwm, period[index]);
		if (ret != OK) {
			check = false;
			SYSIO_ITC_PRINT("\nitc_pwm_set_get_different_period_p: iotbus_pwm_set_period FAIL for period : %d\n", period[index]);
			continue;
		}
		ret = iotbus_pwm_get_period(h_pwm);
		if (ret != period[index]) {
			check = false;
			SYSIO_ITC_PRINT("\nitc_pwm_set_get_different_period_p: iotbus_pwm_get_period FAIL for period : %d\n", period[index]);
			continue;
		}
	}
	TC_ASSERT_EQ_CLEANUP("itc_systemio_pwm_set_get_period_p_different_period", check, true, iotbus_pwm_close(h_pwm));
	ret = iotbus_pwm_close(h_pwm);
	TC_ASSERT_EQ("iotbus_pwm_close", ret, OK);

	TC_SUCCESS_RESULT();
}

/**
* @testcase         itc_systemio_pwm_open_n
* @brief            open the pwm_context
* @scenario         open the pwm_context with invalid argument
* @apicovered       iotbus_pwm_open
* @precondition     none
* @postcondition    none
*/
void itc_systemio_pwm_open_n(void)
{
	int invalid_device = 1;
	iotbus_pwm_context_h h_pwm = iotbus_pwm_open(invalid_device, CONFIG_SYSIO_ITC_PWM_CHANNEL);
	TC_ASSERT_EQ_CLEANUP("iotbus_pwm_open", h_pwm, NULL, iotbus_pwm_close(h_pwm));

	TC_SUCCESS_RESULT();
}

/**
* @testcase         itc_systemio_pwm_close_n
* @brief            open and closes the pwm_context
* @scenario         open and closes the pwm_context
* @apicovered       iotbus_pwm_open, iotbus_pwm_close
* @precondition     none
* @postcondition    none
*/
void itc_systemio_pwm_close_n(void)
{
	int ret = iotbus_pwm_close(NULL);
	TC_ASSERT_EQ("iotbus_pwm_close", ret, IOTBUS_ERROR_INVALID_PARAMETER);

	TC_SUCCESS_RESULT();
}

/**
* @testcase         itc_systemio_pwm_set_duty_cycle_n
* @brief            sets the pwm duty cycle
* @scenario         sets the same pwm duty cycle with invalid parameter
* @apicovered       iotbus_pwm_set_duty_cycle
* @precondition     opens the pwm_context
* @postcondition    closes the pwm_context
*/
void itc_systemio_pwm_set_duty_cycle_n(void)
{
	int cycle = 100;
	int invalid_cycle = 101;
	int ret = 0;
	iotbus_pwm_context_h h_pwm = iotbus_pwm_open(CONFIG_SYSIO_ITC_PWM_DEVICE, CONFIG_SYSIO_ITC_PWM_CHANNEL);
	TC_ASSERT_NEQ("iotbus_pwm_open", h_pwm, NULL);

	ret = iotbus_pwm_set_duty_cycle(NULL, cycle);
	TC_ASSERT_EQ_CLEANUP("iotbus_pwm_set_duty_cycle", ret, IOTBUS_ERROR_INVALID_PARAMETER, iotbus_pwm_close(h_pwm));

	ret = iotbus_pwm_set_duty_cycle(h_pwm, invalid_cycle);
	TC_ASSERT_EQ_CLEANUP("iotbus_pwm_set_duty_cycle", ret, IOTBUS_ERROR_INVALID_PARAMETER, iotbus_pwm_close(h_pwm));

	ret = iotbus_pwm_close(h_pwm);
	TC_ASSERT_EQ("iotbus_pwm_close", ret, OK);

	TC_SUCCESS_RESULT();
}

/**
* @testcase         itc_systemio_pwm_set_duty_cycle_n_after_close
* @brief            sets the pwm duty cycle
* @scenario         sets the pwm duty cycle after pwm close
* @apicovered       iotbus_pwm_set_duty_cycle
* @precondition     opens the pwm_context
* @postcondition    closes the pwm_context
*/
void itc_systemio_pwm_set_duty_cycle_n_after_close(void)
{
	int cycle = 20;
	int ret = 0;
	iotbus_pwm_context_h h_pwm = iotbus_pwm_open(CONFIG_SYSIO_ITC_PWM_DEVICE, CONFIG_SYSIO_ITC_PWM_CHANNEL);
	TC_ASSERT_NEQ("iotbus_pwm_open", h_pwm, NULL);

	ret = iotbus_pwm_close(h_pwm);
	TC_ASSERT_EQ("iotbus_pwm_close", ret, OK);

	ret = iotbus_pwm_set_duty_cycle(h_pwm, cycle);
	TC_ASSERT_LT("iotbus_pwm_set_duty_cycle", ret, 0);

	TC_SUCCESS_RESULT();
}

/**
* @testcase         itc_systemio_pwm_get_duty_cycle_n
* @brief            gets the pwm duty cycle
* @scenario         gets the same pwm duty cycle with invalid parameter
* @apicovered       iotbus_pwm_get_duty_cycle
* @precondition     NA
* @postcondition    NA
*/
void itc_systemio_pwm_get_duty_cycle_n(void)
{
	int ret = iotbus_pwm_get_duty_cycle(NULL);
	TC_ASSERT_EQ("iotbus_pwm_get_duty_cycle", ret, IOTBUS_ERROR_INVALID_PARAMETER);

	TC_SUCCESS_RESULT();
}

/**
* @testcase         itc_systemio_pwm_get_duty_cycle_n_after_close
* @brief            sets and gets the pwm duty cycle
* @scenario         sets and gets the same pwm duty cycle
* @apicovered       iotbus_pwm_set_duty_cycle, iotbus_pwm_get_duty_cycle
* @precondition     opens the pwm_context
* @postcondition    closes the pwm_context
*/
void itc_systemio_pwm_get_duty_cycle_n_after_close(void)
{
	int cycle = 20;
	int ret = 0;
	iotbus_pwm_context_h h_pwm = iotbus_pwm_open(CONFIG_SYSIO_ITC_PWM_DEVICE, CONFIG_SYSIO_ITC_PWM_CHANNEL);
	TC_ASSERT_NEQ("iotbus_pwm_open", h_pwm, NULL);

	ret = iotbus_pwm_set_duty_cycle(h_pwm, cycle);
	TC_ASSERT_EQ_CLEANUP("iotbus_pwm_set_duty_cycle", ret, OK, iotbus_pwm_close(h_pwm));

	ret = iotbus_pwm_close(h_pwm);
	TC_ASSERT_EQ("iotbus_pwm_close", ret, OK);

	ret = iotbus_pwm_get_duty_cycle(h_pwm);
	TC_ASSERT_LT("iotbus_pwm_get_duty_cycle", ret, 0);

	TC_SUCCESS_RESULT();
}

/**
* @testcase         itc_systemio_pwm_set_period_n
* @brief            sets the pwm period
* @scenario         sets the pwm period with invalid argument
* @apicovered       iotbus_pwm_set_period
* @precondition     opens the pwm_context
* @postcondition    closes the pwm_context
*/
void itc_systemio_pwm_set_period_n(void)
{
	int ret = 0;
	iotbus_pwm_context_h h_pwm = iotbus_pwm_open(CONFIG_SYSIO_ITC_PWM_DEVICE, CONFIG_SYSIO_ITC_PWM_CHANNEL);
	TC_ASSERT_NEQ("iotbus_pwm_open", h_pwm, NULL);

	ret = iotbus_pwm_set_period(NULL, CONFIG_SYSIO_ITC_PWM_PERIOD);
	TC_ASSERT_EQ_CLEANUP("iotbus_pwm_set_period", ret, IOTBUS_ERROR_INVALID_PARAMETER, iotbus_pwm_close(h_pwm));

	ret = iotbus_pwm_close(h_pwm);
	TC_ASSERT_EQ("iotbus_pwm_close", ret, OK);

	TC_SUCCESS_RESULT();
}

/**
* @testcase         itc_systemio_pwm_set_period_n_after_close
* @brief            sets the pwm period
* @scenario         sets the pwm period after close
* @apicovered       iotbus_pwm_set_period
* @precondition     opens the pwm_context
* @postcondition    closes the pwm_context
*/
void itc_systemio_pwm_set_period_n_after_close(void)
{
	int ret = 0;
	iotbus_pwm_context_h h_pwm = iotbus_pwm_open(CONFIG_SYSIO_ITC_PWM_DEVICE, CONFIG_SYSIO_ITC_PWM_CHANNEL);
	TC_ASSERT_NEQ("iotbus_pwm_open", h_pwm, NULL);

	ret = iotbus_pwm_close(h_pwm);
	TC_ASSERT_EQ("iotbus_pwm_close", ret, OK);

	ret = iotbus_pwm_set_period(h_pwm, CONFIG_SYSIO_ITC_PWM_PERIOD);
	TC_ASSERT_LT("iotbus_pwm_set_period", ret, 0);

	TC_SUCCESS_RESULT();
}

/**
* @testcase         itc_systemio_pwm_get_period_n
* @brief            gets the pwm period
* @scenario         gets the pwm period with invalid parameter
* @apicovered       iotbus_pwm_get_period
* @precondition     opens the pwm_context
* @postcondition    closes the pwm_context
*/
void itc_systemio_pwm_get_period_n(void)
{
	int ret = iotbus_pwm_get_period(NULL);
	TC_ASSERT_EQ("iotbus_pwm_get_period", ret, IOTBUS_ERROR_INVALID_PARAMETER);

	TC_SUCCESS_RESULT();
}

/**
* @testcase         itc_systemio_pwm_get_period_n_after_close
* @brief            gets the pwm period
* @scenario         gets the pwm period after pwm close
* @apicovered       iotbus_pwm_get_period
* @precondition     opens the pwm_context
* @postcondition    closes the pwm_context
*/
void itc_systemio_pwm_get_period_n_after_close(void)
{
	int ret = 0;
	iotbus_pwm_context_h h_pwm = iotbus_pwm_open(CONFIG_SYSIO_ITC_PWM_DEVICE, CONFIG_SYSIO_ITC_PWM_CHANNEL);
	TC_ASSERT_NEQ("iotbus_pwm_open", h_pwm, NULL);

	ret = iotbus_pwm_set_period(h_pwm, CONFIG_SYSIO_ITC_PWM_PERIOD);
	TC_ASSERT_EQ_CLEANUP("iotbus_pwm_set_period", ret, OK, iotbus_pwm_close(h_pwm));

	ret = iotbus_pwm_close(h_pwm);
	TC_ASSERT_EQ("iotbus_pwm_close", ret, OK);

	ret = iotbus_pwm_get_period(h_pwm);
	TC_ASSERT_LT("iotbus_pwm_get_period", ret, 0);

	TC_SUCCESS_RESULT();
}

/**
* @testcase         itc_systemio_pwm_is_enabled_n
* @brief            checks if pwm state is enabled
* @scenario         checks if pwm state is enabled with invalid handle
* @apicovered       iotbus_pwm_is_enabled
* @precondition     opens the pwm_context
* @postcondition    closes the pwm_context
*/
void itc_systemio_pwm_is_enabled_n(void)
{
	int ret = iotbus_pwm_is_enabled(NULL);
	TC_ASSERT_EQ("iotbus_pwm_is_enabled", ret, IOTBUS_ERROR_INVALID_PARAMETER);

	TC_SUCCESS_RESULT();
}

int itc_pwm_main(void)
{
	itc_systemio_pwm_open_close_p();
	itc_systemio_pwm_set_get_duty_cycle_p();
	itc_systemio_pwm_set_get_period_p();
	itc_systemio_pwm_set_period_is_enabled_p();
	itc_systemio_pwm_set_get_duty_cycle_p_different_cycle();
	itc_systemio_pwm_set_get_period_p_different_period();
	itc_systemio_pwm_open_n();
	itc_systemio_pwm_close_n();
	itc_systemio_pwm_set_duty_cycle_n();
	itc_systemio_pwm_set_duty_cycle_n_after_close();
	itc_systemio_pwm_get_duty_cycle_n();
	itc_systemio_pwm_get_duty_cycle_n_after_close();
	itc_systemio_pwm_set_period_n();
	itc_systemio_pwm_set_period_n_after_close();
	itc_systemio_pwm_get_period_n();
	itc_systemio_pwm_get_period_n_after_close();
	itc_systemio_pwm_is_enabled_n();

	return 0;
}

redpajama_set_name: RedPajamaGithub


text:
namespace {

// The address of this module in memory. The linker will take care of defining
// this symbol.
extern "C" IMAGE_DOS_HEADER __ImageBase;

// An invalid load address.
const uint64_t kInvalidLoadAddress = 0xDEADBEEF;

}  // namespace

class ModuleEventSinkImplTest : public testing::Test {
 public:
  ModuleEventSinkImplTest(const ModuleEventSinkImplTest&) = delete;
  ModuleEventSinkImplTest& operator=(const ModuleEventSinkImplTest&) = delete;

 protected:
  ModuleEventSinkImplTest() = default;
  ~ModuleEventSinkImplTest() override = default;

  bool CreateModuleSinkImpl() {
    HANDLE process_handle = 0;
    if (!::DuplicateHandle(::GetCurrentProcess(), ::GetCurrentProcess(),
                           ::GetCurrentProcess(), &process_handle, 0, FALSE,
                           DUPLICATE_SAME_ACCESS)) {
      return false;
    }

    module_event_sink_impl_ = std::make_unique<ModuleEventSinkImpl>(
        base::Process(process_handle), content::PROCESS_TYPE_BROWSER,
        base::BindRepeating(&ModuleEventSinkImplTest::OnModuleEvent,
                            base::Unretained(this)));
    return true;
  }

  void OnModuleEvent(content::ProcessType process_type,
                     const base::FilePath& module_path,
                     uint32_t module_size,
                     uint32_t module_time_date_stamp) {
    ++module_event_count_;
  }

  int module_event_count() { return module_event_count_; }

  // Must be first.
  content::BrowserTaskEnvironment task_environment_;

  std::unique_ptr<ModuleEventSinkImpl> module_event_sink_impl_;

  int module_event_count_ = 0;
};

TEST_F(ModuleEventSinkImplTest, CallsForwardedAsExpected) {
  const uintptr_t kValidLoadAddress = reinterpret_cast<uintptr_t>(&__ImageBase);

  EXPECT_EQ(0, module_event_count());

  ASSERT_TRUE(CreateModuleSinkImpl());
  EXPECT_EQ(0, module_event_count());

  // An invalid load event should not cause a module entry.
  module_event_sink_impl_->OnModuleEvents({kInvalidLoadAddress});
  task_environment_.RunUntilIdle();
  EXPECT_EQ(0, module_event_count());

  // A valid load event should cause a module entry.
  module_event_sink_impl_->OnModuleEvents({kValidLoadAddress});
  task_environment_.RunUntilIdle();
  EXPECT_EQ(1, module_event_count());
}

TEST_F(ModuleEventSinkImplTest, MultipleEvents) {
  const uintptr_t kLoadAddress1 = reinterpret_cast<uintptr_t>(&__ImageBase);
  const uintptr_t kLoadAddress2 =
      reinterpret_cast<uintptr_t>(::GetModuleHandle(L"kernel32.dll"));
  ASSERT_TRUE(CreateModuleSinkImpl());

  EXPECT_EQ(0, module_event_count());

  module_event_sink_impl_->OnModuleEvents({kLoadAddress1, kLoadAddress2});
  task_environment_.RunUntilIdle();
  EXPECT_EQ(2, module_event_count());
}


text:
FROM node:8.7-wheezy
# Create app directory
WORKDIR /UI

# Bundle app source
COPY client.html .
COPY config.js .
COPY package.json .
COPY stream.js .

RUN npm install
# If you are building your code for production
# RUN npm install --only=production
WORKDIR /
EXPOSE 8000
CMD [ "npm", "start" ]


text:
package txsub

import (
	"errors"
	"testing"
	"time"

	. "github.com/smartystreets/goconvey/convey"
	"github.com/stellar/go/build"
	"github.com/stellar/go/services/horizon/internal/test"
	"github.com/stellar/go/services/horizon/internal/txsub/sequence"
)

func TestTxsub(t *testing.T) {
	Convey("txsub.System", t, func() {
		ctx := test.Context()
		submitter := &MockSubmitter{}
		results := &MockResultProvider{}
		sequences := &MockSequenceProvider{}

		system := &System{
			Pending:           NewDefaultSubmissionList(),
			Submitter:         submitter,
			Results:           results,
			Sequences:         sequences,
			SubmissionQueue:   sequence.NewManager(),
			NetworkPassphrase: build.TestNetwork.Passphrase,
		}

		noResults := Result{Err: ErrNoResults}
		successTx := Result{
			Hash:           "2374e99349b9ef7dba9a5db3339b78fda8f34777b1af33ba468ad5c0df946d4d",
			LedgerSequence: 2,
			EnvelopeXDR:    "AAAAAGL8HQvQkbK2HA3WVjRrKmjX00fG8sLI7m0ERwJW/AX3AAAAZAAAAAAAAAABAAAAAAAAAAAAAAABAAAAAAAAAAAAAAAArqN6LeOagjxMaUP96Bzfs9e0corNZXzBWJkFoK7kvkwAAAAAO5rKAAAAAAAAAAABVvwF9wAAAECDzqvkQBQoNAJifPRXDoLhvtycT3lFPCQ51gkdsFHaBNWw05S/VhW0Xgkr0CBPE4NaFV2Kmcs3ZwLmib4TRrML",
			ResultXDR:      "I3Tpk0m57326ml2zM5t4/ajzR3exrzO6RorVwN+UbU0AAAAAAAAAZAAAAAAAAAABAAAAAAAAAAAAAAAAAAAAAA==",
		}

		badSeq := SubmissionResult{
			Err: ErrBadSequence,
		}

		sequences.Results = map[string]uint64{
			"GBRPYHIL2CI3FNQ4BXLFMNDLFJUNPU2HY3ZMFSHONUCEOASW7QC7OX2H": 0,
		}

		Convey("Submit", func() {
			Convey("returns the result provided by the ResultProvider", func() {
				results.Results = []Result{successTx}
				r := <-system.Submit(ctx, successTx.EnvelopeXDR)

				So(r.Err, ShouldBeNil)
				So(r.Hash, ShouldEqual, successTx.Hash)
				So(submitter.WasSubmittedTo, ShouldBeFalse)
			})

			Convey("returns the error from submission if no result is found by hash and the submitter returns an error", func() {
				submitter.R.Err = errors.New("busted for some reason")
				r := <-system.Submit(ctx, successTx.EnvelopeXDR)

				So(r.Err, ShouldNotBeNil)
				So(submitter.WasSubmittedTo, ShouldBeTrue)
				So(system.Metrics.SuccessfulSubmissionsMeter.Count(), ShouldEqual, 0)
				So(system.Metrics.FailedSubmissionsMeter.Count(), ShouldEqual, 1)
				So(system.Metrics.SubmissionTimer.Count(), ShouldEqual, 1)
			})

			Convey("if the error is bad_seq and the result at the transaction's sequence number is for the same hash, return result", func() {
				submitter.R = badSeq
				results.Results = []Result{noResults, successTx}

				r := <-system.Submit(ctx, successTx.EnvelopeXDR)

				So(r.Err, ShouldBeNil)
				So(r.Hash, ShouldEqual, successTx.Hash)
				So(submitter.WasSubmittedTo, ShouldBeTrue)
			})

			Convey("if error is bad_seq and no result is found, return error", func() {
				submitter.R = badSeq
				r := <-system.Submit(ctx, successTx.EnvelopeXDR)

				So(r.Err, ShouldNotBeNil)
				So(submitter.WasSubmittedTo, ShouldBeTrue)
			})

			Convey("if no result found and no error submitting, add to open transaction list", func() {
				_ = system.Submit(ctx, successTx.EnvelopeXDR)
				pending := system.Pending.Pending(ctx)
				So(len(pending), ShouldEqual, 1)
				So(pending[0], ShouldEqual, successTx.Hash)
				So(system.Metrics.SuccessfulSubmissionsMeter.Count(), ShouldEqual, 1)
				So(system.Metrics.FailedSubmissionsMeter.Count(), ShouldEqual, 0)
				So(system.Metrics.SubmissionTimer.Count(), ShouldEqual, 1)
			})
		})

		Convey("Tick", func() {

			Convey("no-ops if there are no open submissions", func() {
				system.Tick(ctx)
			})

			Convey("finishes any available transactions", func() {
				l := make(chan Result, 1)
				system.Pending.Add(ctx, successTx.Hash, l)
				system.Tick(ctx)
				So(len(l), ShouldEqual, 0)
				So(len(system.Pending.Pending(ctx)), ShouldEqual, 1)

				results.Results = []Result{successTx}
				system.Tick(ctx)

				So(len(l), ShouldEqual, 1)
				So(len(system.Pending.Pending(ctx)), ShouldEqual, 0)
			})

			Convey("removes old submissions that have timed out", func() {
				l := make(chan Result, 1)
				system.SubmissionTimeout = 100 * time.Millisecond
				system.Pending.Add(ctx, successTx.Hash, l)
				<-time.After(101 * time.Millisecond)
				system.Tick(ctx)

				So(len(system.Pending.Pending(ctx)), ShouldEqual, 0)
				So(len(l), ShouldEqual, 1)
				<-l
				select {
				case _, stillOpen := <-l:
					So(stillOpen, ShouldBeFalse)
				default:
					panic("could not read from listener")
				}

			})
		})

	})
}


text:
import { Favourites } from "../helpers/spPropertyBagfavourites";
import { IProperty } from "../interfaces/spPropertyBagInterfaces";
import ApiBase from "./../../common/apiBase";
import { constants } from "./../constants/constants";

export default class SpPropertyBagApi extends ApiBase {
    public decodeSpCharacters(strToDecode: string): string {
        strToDecode = strToDecode.replace(constants.PROPERTY_REST_PREFIX, constants.EMPTY_STRING);
        const matchesArray = strToDecode.match(constants.PROPERTY_REST_DECODE_REGEX);
        if (!!matchesArray) {
            matchesArray.forEach((str: string) => {
                const decoded = decodeURIComponent(str
                    .replace(constants.PROPERTY_REST_UNDERSCORE_REGEX, constants.EMPTY_STRING)
                    .replace(constants.PROPERTY_REST_UNDERSCORE_PREFIX_REGEX, constants.PERCET_STRING));
                strToDecode = strToDecode.replace(str, decoded);
            });
        }
        return strToDecode;
    }
    public async getProperties(): Promise<IProperty[]> {

        const webUrl: string = await this.getWebUrl();
        const reqUrl = `${webUrl}${constants.PROPERTY_REST_REQUEST_URL}`;
        const response: any = await this.getRequest(reqUrl);
        const props: IProperty[] = [];
        const rawData = response.data;
        for (const prop in rawData) {
            if (rawData.hasOwnProperty(prop)) {
                const propVal = rawData[prop];
                if (typeof (propVal) === constants.STRING_STRING) {
                    // tslint:disable-next-line:max-line-length
                    const value: string = propVal.replace(constants.PROPERTY_REST_DOUBLEQUOTES_REGEX, constants.PROPERTY_REST_DOUBLEQUOTES);
                    const key: string = this.decodeSpCharacters(prop);
                    props.push({
                        isFavourite: Favourites.Favourites.indexOf(key) >= 0,
                        key,
                        value
                    });
                }
            }
        }
        return props;
    }

    public deleteProperty(property: IProperty): Promise<IProperty> {
        return this.setProperty({ ...property, value: null });
    }

    public createProperty(property: IProperty): Promise<IProperty> {
        return this.setProperty(property);
    }

    public updateProperty(property: IProperty): Promise<IProperty> {
        return this.setProperty(property);
    }

    private setProperty(property: IProperty): Promise<IProperty> {
        return new Promise((resolve, reject) => {
            const ctx = SP.ClientContext.get_current();
            const web = ctx.get_web();
            const allProperties = web.get_allProperties();

            allProperties.set_item(property.key, property.value);

            web.update();

            ctx.executeQueryAsync((sender: any, err: any) => {
                resolve(property);
            }, this.getErrorResolver(reject, constants.ERROR_MESSAGE_RESOLVER_SETTING_PROPERTY));
        });
    }
}


text:
require 'spec_helper'

describe 'CF Binary Buildpack' do
  let(:browser) { Machete::Browser.new(app) }

  after do
    Machete::CF::DeleteApp.new.execute(app)
  end

  describe 'deploying a Ruby script' do
    let(:app_name) { 'webrick_app' }

    context 'when specifying a buildpack' do
      let(:app) { Machete.deploy_app(app_name, buildpack: 'binary-test-buildpack') }

      it 'deploys successfully' do
        expect(app).to be_running

        browser.visit_path('/')

        expect(browser.body).to include('Hello, world!')
      end
    end

    context 'without specifying a buildpack' do
      let(:app) { Machete.deploy_app(app_name) }

      it 'fails to stage' do
        expect(app).not_to be_running
        expect(app).to have_logged("An app was not successfully detected by any available buildpack")
      end
    end
  end
end


text:
layout: page
title: Salinas Media Conference
date: 2016-05-24
author: Samantha Cline
tags: weekly links, java
status: published
summary: Fusce ut libero ut leo.
banner: images/banner/wedding.jpg
booking:
  startDate: 12/15/2019
  endDate: 12/18/2019
  ctyhocn: GZTCCHX
  groupCode: SMC
published: true
---
In nec odio at risus elementum semper id sit amet dolor. Sed nec enim rhoncus, suscipit neque ut, congue nunc. Etiam at diam pellentesque, consectetur nunc id, venenatis nunc. Sed leo sapien, commodo sit amet odio sit amet, fringilla posuere quam. Donec egestas mi ac pellentesque feugiat. Morbi ultricies vitae libero in varius. Morbi viverra volutpat est, eget molestie elit vehicula eu. Morbi faucibus in felis vitae imperdiet. Nullam in justo sem. Morbi molestie, mauris id placerat efficitur, risus sem sodales ex, nec accumsan purus augue id mi. Nam risus magna, posuere ut elit a, venenatis congue nunc. Sed ut mi luctus, feugiat velit ac, elementum tellus. In sit amet arcu auctor, feugiat ante at, malesuada augue.

1 Maecenas euismod neque sit amet diam dictum, ut aliquam tellus efficitur
1 Proin a quam rhoncus, tincidunt massa laoreet, facilisis erat
1 Donec cursus lorem non ligula fringilla luctus nec eget tortor.

In lobortis quam sagittis sodales volutpat. Morbi vitae dictum augue, eget fringilla metus. Pellentesque non sagittis felis, eu sagittis elit. Donec lacinia risus ipsum, in gravida eros euismod id. Aenean eget maximus nibh. Aliquam vestibulum diam eget dui sagittis, vel convallis ligula hendrerit. Mauris et dui dictum, facilisis lacus ut, fermentum libero. Maecenas sed ultrices metus.
Maecenas molestie ornare magna, a facilisis ipsum. Sed mattis ornare neque malesuada ullamcorper. Nulla facilisi. Ut ultrices blandit ex non rhoncus. Nulla rhoncus ipsum vel lacus iaculis euismod. Donec faucibus sapien quis nibh tincidunt, nec pellentesque felis interdum. Curabitur sodales mattis bibendum. In hac habitasse platea dictumst. Nullam iaculis ipsum dui. Class aptent taciti sociosqu ad litora torquent per conubia nostra, per inceptos himenaeos.


text:
class CreateReadings < ActiveRecord::Migration
  def change
    create_table :readings do |t|
      t.integer :state
      t.integer :set_temp
      t.decimal :temp_f, precision: 6, scale: 3

      t.timestamps
    end

    add_index :readings, :created_at
  end
end


text:
"use strict";

var game = game || {};

game.EASY = 0;
game.HARD = 1;

game.difficulty = game.EASY;
game.gameOver = false;
game.finalScore = -1;

// Just a little function to help restrict our textfield to 4-digit numbers
game.init = function() {
  $('#scoreRequestTF').keypress(function(e) {
    var a = [];
    var k = e.which;

    for (var i = 48; i < 58; i++)
      a.push(i);

    if (!($.inArray(k, a) >= 0))
      e.preventDefault();

    if ($('#scoreRequestTF').val().length >= 4) {
      e.preventDefault();
    }
  })
};

game.startGame = function(difficultyLevel) {
  game.difficulty = difficultyLevel;
  game.resetGame();
  $('#game').fadeIn();

};

game.showChallenge = function() {
  if (challenge.isActive && challenge.difficulty == game.difficulty) {
    $("#challengeArea").text("Incoming challenge! Beat "
      + challenge.challenger
      + "'s score of " + challenge.scoreToBeat).show();
  } else {
    $("#challengeArea").hide();
  }
};

game.resetGame = function() {
  if (game.difficulty == game.EASY) {
    $('#pageHeader').text('Type-a-Number (Easy)');
  } else {
    $('#pageHeader').text('Type-a-Number (Hard)');
  }

  $('#gameMessageArea').text('What score do you think you deserve?');
  $('#gameBragArea').hide();
  $('#submitScoreButton').val("Request Score");

  game.showChallenge();

  var $scoreRequestTF = $('#scoreRequestTF');
  $scoreRequestTF.attr('disabled', false);
  $scoreRequestTF.val('');

  game.gameOver = false;
};

game.checkChallenge = function() {
  if (challenge.isActive && challenge.difficulty == game.difficulty) {
    if (game.finalScore > challenge.scoreToBeat) {
      $('#challengeArea').text('Challenge beaten! Good work!');
    } else {
      $('#challengeArea').text('Challenge not beaten. Try again!');
    }

    challenge.resetIncomingChallenge();
  }
};

game.requestScore = function() {
  if (game.gameOver) {
    game.resetGame();

  } else {
    var $scoreRequestTF = $('#scoreRequestTF');
    var requestedScore = parseInt($scoreRequestTF.val());

    if (isNaN(requestedScore))
      return;

    requestedScore = Math.min(9999, Math.max(requestedScore, 0));
    achManager.scoreRequested(requestedScore);

    if (game.difficulty == game.EASY) {
      game.finalScore = requestedScore;
      $("#gameMessageArea").text("Well, okay then. Your final score is "
        + game.finalScore);

    } else {
      game.finalScore = Math.ceil(requestedScore / 2.0);
      $("#gameMessageArea").text(
        "What, you thought it would be that easy? Your final score is "
        + game.finalScore);
    }

    game.checkChallenge();

    achManager.scoreReturned(game.finalScore);
    leadManager.gotScore(game.finalScore, game.difficulty, game.scoreCallback);

    $('#submitScoreButton').val("Play Again");
    $scoreRequestTF.attr('disabled', true);

    game.gameOver = true;
  }
};

game.populateBragButton = function() {
  // Let's generate the deep-link ID so we can link on mobile devices
  var challengeObject = challenge.generateChallenge();

  // Let's JSONify it
  var challengeString = JSON.stringify(challengeObject);
  challengeString = btoa(challengeString);
  var linkUrl = constants.LINK_PAGE_BASE + "?gamedata=" + challengeString;

  // If we wanted, we could also have a different link for the calltoaction
  // url along with the contenturl. Right now, for simplicity, I just have both
  // links going to, which supplies the Schema.org content (if you're a robot)
  // or directs back to the game page (if you're not)

  gapi.interactivepost.render('bragButton',
    {'clientid': constants.CLIENT_ID,
      'calltoactionurl': linkUrl,
      'calltoactiondeeplinkid': challengeString,
      'contenturl': linkUrl,
      'contentdeeplinkid': challengeString,
      'calltoactionlabel': 'PLAY',
      'prefilltext': 'Can you beat my score?',
      'cookiepolicy': 'single_host_origin'
    }
  );
};

game.scoreCallback = function(newHighScore) {
  console.log("New high score? " + newHighScore);

  if (newHighScore) {
    game.populateBragButton();
    $('#bragButton').show();
    $('#bragMessage').text("New high score this week! Challenge your friends?");

  } else {
    $('#bragButton').hide();
    $('#bragMessage').text("Not a new weekly high score. Keep trying!");
  }

  $('#gameBragArea').fadeIn();
};

game.showLeaderboard = function() {
  var leaderboardToShow;

  if (game.difficulty == game.EASY) {
    leaderboardToShow = constants.LEADERBOARD_EASY
  } else {
    leaderboardToShow = constants.LEADERBOARD_HARD;
  }

  leaderboardTable.showLeaderboard(leaderboardToShow,
    leaderboardTable.BACK_TO_GAME);
  $('#game').hide();

};

game.back = function() {
  $('#game').hide();
  welcome.loadUp();
};


text:
var http = require('../../');

var opts = { path : '/beep', method : 'GET' };
var req = http.request(opts, function (res) {
    var div = document.getElementById('result');

    for (var key in res.headers) {
        div.innerHTML += key + ': ' + res.getHeader(key) + '
';
    }
    div.innerHTML += '
';

    res.on('data', function (buf) {
        div.innerHTML += buf;
    });
});

req.setHeader('bling', 'blong');
req.end();


text:
package org.orekit.models.earth.displacement;

import java.lang.reflect.Field;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import org.hipparchus.geometry.euclidean.threed.Vector3D;
import org.hipparchus.util.FastMath;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import org.orekit.Utils;
import org.orekit.bodies.OneAxisEllipsoid;
import org.orekit.data.BodiesElements;
import org.orekit.data.FundamentalNutationArguments;
import org.orekit.frames.FramesFactory;
import org.orekit.time.AbsoluteDate;
import org.orekit.time.TimeScale;
import org.orekit.time.TimeScalesFactory;
import org.orekit.utils.Constants;
import org.orekit.utils.IERSConventions;

public class OceanLoadingTest {

    private OneAxisEllipsoid earth;

    @Test
    public void testSemiDiurnal() {
        TimeScale                    ut1      = TimeScalesFactory.getUT1(IERSConventions.IERS_2010, true);
        FundamentalNutationArguments fna      = IERSConventions.IERS_2010.getNutationArguments(ut1);
        BodiesElements               elements = fna.evaluateAll(new AbsoluteDate(2009, 6, 25, 0, 0, 0.0, ut1));
        for (Tide tide : getTides()) {
            if (tide.getDoodsonMultipliers()[0] == 2) {
                double f = tide.getRate(elements) * Constants.JULIAN_DAY/ (2 * FastMath.PI);
                Assert.assertTrue(f >  1.5);
                Assert.assertTrue(f <= 2.5);
            }
        }
    }

    @Test
    public void testDiurnal() {
        TimeScale                    ut1      = TimeScalesFactory.getUT1(IERSConventions.IERS_2010, true);
        FundamentalNutationArguments fna      = IERSConventions.IERS_2010.getNutationArguments(ut1);
        BodiesElements               elements = fna.evaluateAll(new AbsoluteDate(2009, 6, 25, 0, 0, 0.0, ut1));
        for (Tide tide : getTides()) {
            if (tide.getDoodsonMultipliers()[0] == 1) {
                double f = tide.getRate(elements) * Constants.JULIAN_DAY/ (2 * FastMath.PI);
                Assert.assertTrue(f >  0.5);
                Assert.assertTrue(f <= 1.5);
            }
        }
    }

    @Test
    public void testLongPeriod() {
        TimeScale                    ut1      = TimeScalesFactory.getUT1(IERSConventions.IERS_2010, true);
        FundamentalNutationArguments fna      = IERSConventions.IERS_2010.getNutationArguments(ut1);
        BodiesElements               elements = fna.evaluateAll(new AbsoluteDate(2009, 6, 25, 0, 0, 0.0, ut1));
        for (Tide tide : getTides()) {
            if (tide.getDoodsonMultipliers()[0] == 0) {
                double f = tide.getRate(elements) * Constants.JULIAN_DAY/ (2 * FastMath.PI);
                Assert.assertTrue(f >  0.0);
                Assert.assertTrue(f <= 0.5);
            }
        }
    }

    @Test
    public void testNoExtra() {
        for (Tide tide : getTides()) {
            if (tide.getDoodsonMultipliers()[0] > 2) {
                Assert.fail("unexpected tide " + tide.getDoodsonNumber());
            }
        }
    }

    @Test
    public void testStableRates() {
        // this test checks that tides sort order is date-independent for a large time range
        // (almost 180000 years long)
        // tides sort-order is based on rate, but the rates varies slightly with dates
        // (because Delaunay nutation arguments are polynomials)
        // The variations are however small and we want to make sure
        // that if rate(tideA) < rate(tideB) at time t0, this order remains
        // the same for t1 a few millenia around t0
        final TimeScale                    ut1      = TimeScalesFactory.getUT1(IERSConventions.IERS_2010, true);
        final FundamentalNutationArguments fna      = IERSConventions.IERS_2010.getNutationArguments(ut1);

        // initial sort at J2000.0
        final BodiesElements el2000 = fna.evaluateAll(AbsoluteDate.J2000_EPOCH);
        List<Tide> tides = getTides();
        Collections.sort(tides, (t1, t2) -> Double.compare(t1.getRate(el2000), t2.getRate(el2000)));

        for (double dt = -122000; dt < 54000; dt += 100) {
            final AbsoluteDate date = AbsoluteDate.J2000_EPOCH.shiftedBy(dt * Constants.JULIAN_YEAR);
            final BodiesElements el = fna.evaluateAll(date);
            for (int i = 1; i < tides.size(); ++i) {
                final Tide t1 = tides.get(i - 1);
                final Tide t2 = tides.get(i);
                Assert.assertTrue(t1.getRate(el) < t2.getRate(el));
            }
        }
    }

    @Test
    public void testTidesRatesPastInversion() {
        // on -122502-11-09, the rates for semidiurnal tides 245556 and 245635 cross over
        final TimeScale                    ut1      = TimeScalesFactory.getUT1(IERSConventions.IERS_2010, true);
        final FundamentalNutationArguments fna      = IERSConventions.IERS_2010.getNutationArguments(ut1);
        final Tide                         tide1    = new Tide(245556);
        final Tide                         tide2    = new Tide(245635);

        final AbsoluteDate   t0530  = new AbsoluteDate(-122502, 11, 9, 5, 30, 0.0, TimeScalesFactory.getTAI());
        final BodiesElements el0530 = fna.evaluateAll(t0530);
        Assert.assertTrue(tide1.getRate(el0530) < tide2.getRate(el0530));

        final AbsoluteDate   t0430  = t0530.shiftedBy(-3600.0);
        final BodiesElements el0430 = fna.evaluateAll(t0430);
        Assert.assertTrue(tide1.getRate(el0430) > tide2.getRate(el0430));

    }

    @Test
    public void testTidesRatesFutureInversion() {
        // on 56824-11-02, the rates for semidiurnal tides 274554 (R₂) and 274556 cross over
        final TimeScale                    ut1      = TimeScalesFactory.getUT1(IERSConventions.IERS_2010, true);
        final FundamentalNutationArguments fna      = IERSConventions.IERS_2010.getNutationArguments(ut1);
        final Tide                         tide1    = new Tide(274554);
        final Tide                         tide2    = new Tide(274556);

        final AbsoluteDate   t1700  = new AbsoluteDate(56824, 11, 2, 17, 0, 0.0, TimeScalesFactory.getTAI());
        final BodiesElements el1700 = fna.evaluateAll(t1700);
        Assert.assertTrue(tide1.getRate(el1700) < tide2.getRate(el1700));

        final AbsoluteDate   t1800  = t1700.shiftedBy(3600.0);
        final BodiesElements el1800 = fna.evaluateAll(t1800);
        Assert.assertTrue(tide1.getRate(el1800) > tide2.getRate(el1800));

    }

    @Test
    public void testOnsalaOriginalEarthRotation() {
        // this test is the first test case for HARDISP.F program
        doTestOnsala(true, 4.7e-6);
    }

    @Test
    public void testOnsalaIERSEarthRotation() {
        // this test is the first test case for HARDISP.F program
        doTestOnsala(false, 3.4e-6);
    }

    private void doTestOnsala(boolean patchEarthRotation, double tolerance) {
        OceanLoadingCoefficientsBLQFactory factory      = new OceanLoadingCoefficientsBLQFactory("^hardisp\\.blq$");
        OceanLoadingCoefficients           coefficients = factory.getCoefficients("Onsala");
        Vector3D                           refPoint     = earth.transform(coefficients.getSiteLocation());
        OceanLoading                       loading      = new OceanLoading(earth, coefficients);
        TimeScale                          ut1          = TimeScalesFactory.getUT1(IERSConventions.IERS_2010, true);
        FundamentalNutationArguments       fna          = IERSConventions.IERS_2010.getNutationArguments(ut1);
        if (patchEarthRotation) {
            TideTest.patchEarthRotationModel(fna, ut1);
        }
        AbsoluteDate                       t0      = new AbsoluteDate("2009-06-25T01:10:45", ut1 );
        double[][] ref = new double[][] {
            {  0.003094, -0.001538, -0.000895 },
            {  0.001812, -0.000950, -0.000193 },
            {  0.000218, -0.000248,  0.000421 },
            { -0.001104,  0.000404,  0.000741 },
            { -0.001668,  0.000863,  0.000646 },
            { -0.001209,  0.001042,  0.000137 },
            {  0.000235,  0.000926, -0.000667 },
            {  0.002337,  0.000580, -0.001555 },
            {  0.004554,  0.000125, -0.002278 },
            {  0.006271, -0.000291, -0.002615 },
            {  0.006955, -0.000537, -0.002430 },
            {  0.006299, -0.000526, -0.001706 },
            {  0.004305, -0.000244, -0.000559 },
            {  0.001294,  0.000245,  0.000793 },
            { -0.002163,  0.000819,  0.002075 },
            { -0.005375,  0.001326,  0.003024 },
            { -0.007695,  0.001622,  0.003448 },
            { -0.008669,  0.001610,  0.003272 },
            { -0.008143,  0.001262,  0.002557 },
            { -0.006290,  0.000633,  0.001477 },
            { -0.003566, -0.000155,  0.000282 },
            { -0.000593, -0.000941, -0.000766 },
            {  0.001992, -0.001561, -0.001457 },
            {  0.003689, -0.001889, -0.001680 }
        };
        for (int i = 0; i < ref.length; ++i) {
            BodiesElements elements = fna.evaluateAll(t0.shiftedBy(i * 3600.0));
            final Vector3D d = loading.displacement(elements, earth.getBodyFrame(), refPoint);
            Assert.assertEquals(ref[i][0], Vector3D.dotProduct(d, coefficients.getSiteLocation().getZenith()), tolerance);
            Assert.assertEquals(ref[i][1], Vector3D.dotProduct(d, coefficients.getSiteLocation().getSouth()),  tolerance);
            Assert.assertEquals(ref[i][2], Vector3D.dotProduct(d, coefficients.getSiteLocation().getWest()),   tolerance);
        }
    }

    @Test
    public void testReykjavikOriginalEarthRotation() {
        // this test is the second test case for HARDISP.F program
        doTestReykjavik(true, 9.3e-6);
    }

    @Test
    public void testReykjavikIERSEarthRotation() {
        // this test is the second test case for HARDISP.F program
        doTestReykjavik(false, 16.9e-6);
    }

    private void doTestReykjavik(boolean patchEarthRotation, double tolerance) {
        // the coordinates for Reykjavik are *known* to be wrong in this test file
        // these test data have been extracted from the HARDISP.F file in September 2017
        // and it seems longitude and latitude have been exchanged...
        // With the file coordinates, Reykjavik would be somewhere in the Indian Ocean, about 1800km East of Madagascar
        // The error has been reported to IERS conventions center.
        OceanLoadingCoefficientsBLQFactory factory      = new OceanLoadingCoefficientsBLQFactory("^hardisp\\.blq$");
        OceanLoadingCoefficients           coefficients = factory.getCoefficients("Reykjavik");
        Vector3D                           refPoint     = earth.transform(coefficients.getSiteLocation());
        OceanLoading                       loading      = new OceanLoading(earth, coefficients);
        TimeScale                          ut1          = TimeScalesFactory.getUT1(IERSConventions.IERS_2010, true);
        FundamentalNutationArguments       fna          = IERSConventions.IERS_2010.getNutationArguments(ut1);
        if (patchEarthRotation) {
            TideTest.patchEarthRotationModel(fna, ut1);
        }
        AbsoluteDate                       t0      = new AbsoluteDate("2009-06-25T01:10:45", ut1 );
        double[][] ref = new double[][] {
            { -0.005940, -0.001245, -0.000278 },
            {  0.013516, -0.001086,  0.003212 },
            {  0.029599, -0.000353,  0.005483 },
            {  0.038468,  0.000699,  0.005997 },
            {  0.038098,  0.001721,  0.004690 },
            {  0.028780,  0.002363,  0.001974 },
            {  0.013016,  0.002371, -0.001369 },
            { -0.005124,  0.001653, -0.004390 },
            { -0.021047,  0.000310, -0.006225 },
            { -0.030799, -0.001383, -0.006313 },
            { -0.032056, -0.003048, -0.004549 },
            { -0.024698, -0.004288, -0.001314 },
            { -0.010814, -0.004794,  0.002623 },
            {  0.005849, -0.004416,  0.006291 },
            {  0.020857, -0.003208,  0.008766 },
            {  0.030226, -0.001413,  0.009402 },
            {  0.031437,  0.000594,  0.007996 },
            {  0.024079,  0.002389,  0.004844 },
            {  0.009945,  0.003606,  0.000663 },
            { -0.007426,  0.004022, -0.003581 },
            { -0.023652,  0.003601, -0.006911 },
            { -0.034618,  0.002505, -0.008585 },
            { -0.037515,  0.001044, -0.008270 },
            { -0.031544, -0.000402, -0.006125 }
        };
        for (int i = 0; i < ref.length; ++i) {
            BodiesElements elements = fna.evaluateAll(t0.shiftedBy(i * 3600.0));
            final Vector3D d = loading.displacement(elements, earth.getBodyFrame(), refPoint);
            Assert.assertEquals(ref[i][0], Vector3D.dotProduct(d, coefficients.getSiteLocation().getZenith()), tolerance);
            Assert.assertEquals(ref[i][1], Vector3D.dotProduct(d, coefficients.getSiteLocation().getSouth()),  tolerance);
            Assert.assertEquals(ref[i][2], Vector3D.dotProduct(d, coefficients.getSiteLocation().getWest()),   tolerance);
        }
    }

    private List<Tide> getTides() {
        try {
            Field mapField = OceanLoading.class.getDeclaredField("CARTWRIGHT_EDDEN_AMPLITUDE_MAP");
            mapField.setAccessible(true);
            @SuppressWarnings("unchecked")
            Map<Tide, Double> map = (Map<Tide, Double>) mapField.get(null);
            return map.entrySet().stream().map(e -> e.getKey()).collect(Collectors.toList());
        } catch (NoSuchFieldException | IllegalArgumentException | IllegalAccessException e) {
            Assert.fail(e.getLocalizedMessage());
            return null;
        }
    }

    @Before
    public void setUp() throws Exception {
        Utils.setDataRoot("regular-data:oso-blq");
        earth = new OneAxisEllipsoid(Constants.WGS84_EARTH_EQUATORIAL_RADIUS,
                                     Constants.WGS84_EARTH_FLATTENING,
                                     FramesFactory.getITRF(IERSConventions.IERS_2010, false));
    }

}


text:
using namespace std;

//=====================================================================================================
void usage(char * name)
{
	std::cout << "PEACEFAIR reader" << std::endl << std::endl;
	std::cout << "Usage: " << name << " [-v]" << std::endl << std::endl;
	std::cout << "Options: " << std::endl;
	std::cout << "   -t print time" << std::endl;
	std::cout << "   -h print this help and exit" << std::endl;
	std::cout << "   -c <file path> config file" << endl;
	std::cout << "   -v print version" << std::endl;
}

static bool b_time = false;

//=====================================================================================================
bool msgCallback(const char * data)
{
	if( data == NULL ) return false;

	string value;
	char str_val[4];

	for(int pos = 0;pos < ENERGY_SERIAL_MESSAGE_LENGTH; pos++)
	{
		bzero(str_val, 4);
		sprintf(str_val, "x%.2X", data[pos]);
		value += (value.empty() ? "" : " ") + string(str_val);
	}

// Printing data:
	if(b_time) std::cout << sk::getDate() << ":";
	std::cout << "Message: " << value << "; ";

	energyMed medObj;
	json_object * json = medObj.parseMessage(data);
	if(json)
	{
		std::cout << json_object_to_json_string( json );
		json_object_put( json );
	}

	std::cout << endl;

	return true;
}

//=====================================================================================================
int main(int argc, char* argv[])
{
	int option = 0;
	char conf_file[128];
	bzero(conf_file, sizeof(conf_file));

// Parse Program arguments:
	while ((option = getopt(argc, argv, "-vhtc:")) != -1)
	{
		switch(option)
		{
			case 't':
				b_time = true;
				break;
			case 'v':
				printf("Version: %s\n", APPL_VERSION);
				return 0;
			case 'c':
				strncpy(conf_file, optarg, min(strlen(optarg),sizeof(conf_file)));
				break;
			case 'h':
			default:
				usage(argv[0]);
				return 0;
		}
	}

	energySerial serialObj;

// Load custom config:
	if(strlen( conf_file )) serialObj.loadConfig( conf_file );

	serialObj.initInst();
	serialObj.setDataCallback(msgCallback);
	serialObj.runInstLoop();

	return 0 ;
}


text:
#ifndef wasm_emscripten_h
#define wasm_emscripten_h

#include "wasm.h"

namespace wasm {

namespace emscripten {

void generateMemoryGrowthFunction(Module&);

// Create thunks for use with emscripten Runtime.dynCall. Creates one for each
// signature in the indirect function table.
std::vector<Function*> makeDynCallThunks(Module& wasm, std::vector<Name> const& tableSegmentData);

void generateEmscriptenMetadata(std::ostream& o,
                                Module& wasm,
                                std::unordered_map<Address, Address> segmentsByAddress,
                                Address staticBump,
                                std::vector<Name> const& initializerFunctions);

} // namespace emscripten

} // namespace wasm

#endif // wasm_emscripten_h


text:
const alerts = require('../lib/alerts.js');
const config = require('config');
const assert = require('assert');

var quickAssert = function(error, response) {
  assert.equal(error, null);
  if(response.statusCode != 200) {
    console.log('ERROR!!!!!!!!');
    console.log(response.body);
  }
  assert.equal(response.statusCode, 200);
}

// Global variables
var configId = config.get('configArr')[0];

// Global variables
var policyName = '';

describe('New Relic Alerts Test', function() {
  this.timeout(15000);

  it('gets the list of alert events', function(done) {
    alerts.events.list(configId, function(error, response, body) {
      quickAssert(error, response);
      done();
    });
  });

  it('gets the list of alert policies', function(done) {
    alerts.policies.list(null, configId, function(error, response, body) {
      quickAssert(error, response);

      // Get the name first policy
      policyName = body.policies[0].name;

      done();
    })
  })

  it('gets a specific alert policy by name', function(done) {
    alerts.policies.list(policyName, configId, function(error, response, body) {
      quickAssert(error, response);
      assert.notEqual(body.policies.length, 0, 'Should not return 0 policies');
      done();
    });
  });

  it('gets the notification channels', function(done) {
    alerts.channels.list(configId, function(error, response, body) {
      quickAssert(error, response);
      done();
    });
  });

  it('gets the first page of incidents', function(done) {
    alerts.incidents.list(false, 1, configId, function(error, response, body) {
      quickAssert(error, response);
      done();
    });
  });

});


text:
using System;
using Android.Content;
using Android.OS;
using Android.Accounts;
using ModernHttpClient;
using Newtonsoft.Json;
using System.Collections.Generic;
using Sunshine.Data;
using Android.Preferences;
using Android.Support.V4.App;
using Android.Graphics;
using Android.App;
using Android.Support.V4.Content;
using Android.Util;
using Sunshine.Models;
using System.Net.Http;
using System.Web;

namespace Sunshine.Sync
{
    public class SunshineSyncAdapter : AbstractThreadedSyncAdapter
    {

        const string LogTag = "SunshineSyncAdapter";
        const string SourceContext = "MyNamespace.MyClass";

        private const string _tag = "SunshineSyncAdapter";

        // Interval at which to sync with the weather, in seconds.
        // 60 seconds (1 minute) * 180 = 3 hours
        public const int SyncInterval = 60 * 180;

        // public const int SyncInterval = 20;

        public const int SyncFlextime = SyncInterval / 3;
        const int WeatherNotificationId = 3004;

        readonly string[] _notifyWeatherProjection = new []
        {
            WeatherContract.Weather.ColumnWeatherId,
            WeatherContract.Weather.ColumnMaximumTemp,
            WeatherContract.Weather.ColumnMinimumTemp,
            WeatherContract.Weather.ColumnShortDescription
        };

        // these indices must match the projection
        const int IndexWeatherId = 0;
        const int IndexMaximumTemp = 1;
        const int IndexMinimumTemp = 2;
        const int IndexShortDesc = 3;

        public SunshineSyncAdapter(Context context, bool autoInitialize)
            : base(context, autoInitialize)
        {

        }

        void NotifyWeather()
        {
            Context context = Context;
            //checking the last update and notify if it' the first of the day
            var prefs = PreferenceManager.GetDefaultSharedPreferences(context);
            var displayNotificationsKey = context.GetString(Resource.String.pref_enable_notifications_key);
            bool displayNotifications = prefs.GetBoolean(displayNotificationsKey,
                                            bool.Parse(context.GetString(Resource.String.pref_enable_notifications_default)));

            if (displayNotifications)
            {

                var lastNotificationKey = context.GetString(Resource.String.pref_last_notification);
                long lastSync = prefs.GetLong(lastNotificationKey, 0);

                var startDate = DateTime.UtcNow.StartOfDay();
                var saveDate = new DateTime(lastSync).StartOfDay();
                var diffDate = startDate - saveDate;

                if (diffDate.Days >= 1)
                {
                    // Last sync was more than 1 day ago, let's send a notification with the weather.
                    var locationQuery = Utility.GetPreferredLocation(context);

                    var weatherUri = WeatherContract.Weather.BuildWeatherLocationWithDate(locationQuery, DateTime.UtcNow.Ticks);

                    // we'll query our contentProvider, as always
                    var cursor = context.ContentResolver.Query(weatherUri, _notifyWeatherProjection, null, null, null);

                    if (cursor.MoveToFirst())
                    {
                        int weatherId = cursor.GetInt(IndexWeatherId);
                        double high = cursor.GetDouble(IndexMaximumTemp);
                        double low = cursor.GetDouble(IndexMinimumTemp);
                        String desc = cursor.GetString(IndexShortDesc);

                        int iconId = Utility.GetIconResourceForWeatherCondition(weatherId);
                        var resources = context.Resources;
                        var largeIcon = BitmapFactory.DecodeResource(resources,
                                            Utility.GetArtResourceForWeatherCondition(weatherId));

                        var title = context.GetString(Resource.String.app_name);

                        // Define the text of the forecast.
                        var contentText = Java.Lang.String.Format(context.GetString(Resource.String.format_notification),
                                              desc,
                                              Utility.FormatTemperature(context, high),
                                              Utility.FormatTemperature(context, low));

                        // NotificationCompatBuilder is a very convenient way to build backward-compatible
                        // notifications.  Just throw in some data.
                        var builder =
                            new NotificationCompat.Builder(Context)
                                .SetColor(ContextCompat.GetColor(context, Resource.Color.sunshine_light_blue))
                                .SetSmallIcon(iconId)
                                .SetLargeIcon(largeIcon)
                                .SetContentTitle(title)
                                .SetContentText(contentText);

                        // Make something interesting happen when the user clicks on the notification.
                        // In this case, opening the app is sufficient.
                        var resultIntent = new Intent(context, typeof(MainActivity));

                        // The stack builder object will contain an artificial back stack for the
                        // started Activity.
                        // This ensures that navigating backward from the Activity leads out of
                        // your application to the Home screen.
                        var stackBuilder = Android.Support.V4.App.TaskStackBuilder.Create(context);
                        stackBuilder.AddNextIntent(resultIntent);
                        var resultPendingIntent =
                            stackBuilder.GetPendingIntent(
                                0, (int)PendingIntentFlags.UpdateCurrent

                            );
                        builder.SetContentIntent(resultPendingIntent);

                        var mNotificationManager =
                            (NotificationManager)Context.GetSystemService(Context.NotificationService);
                        // WEATHER_NOTIFICATION_ID allows you to update the notification later on.
                        mNotificationManager.Notify(WeatherNotificationId, builder.Build());

                        //refreshing last sync
                        var editor = prefs.Edit();
                        editor.PutLong(lastNotificationKey, DateTime.UtcNow.Ticks);
                        editor.Commit();

                    }
                    cursor.Close();
                }
            }
        }

        /// <summary>
        /// Helper method to schedule the sync adapter periodic execution
        /// </summary>
        public static void ConfigurePeriodicSync(Context context, int syncInterval, int flexTime)
        {
            var account = GetSyncAccount(context);
            var authority = context.GetString(Resource.String.content_authority);
            if (Build.VERSION.SdkInt >= BuildVersionCodes.Kitkat)
            {
                // we can enable inexact timers in our periodic sync
                var request = new SyncRequest.Builder().
                                        SyncPeriodic(syncInterval, flexTime).
                                        SetSyncAdapter(account, authority).
                    SetExtras(new Bundle()).Build();
                ContentResolver.RequestSync(request);
            }
            else
            {
                ContentResolver.AddPeriodicSync(account,
                    authority, new Bundle(), syncInterval);
            }
        }

        static void OnAccountCreated(Account newAccount, Context context)
        {

            // Since we've created an account
            SunshineSyncAdapter.ConfigurePeriodicSync(context, SyncInterval, SyncFlextime);

            // Without calling setSyncAutomatically, our periodic sync will not be enabled.
            ContentResolver.SetSyncAutomatically(newAccount, context.GetString(Resource.String.content_authority), true);

            // Finally, let's do a sync to get things started
            SyncImmediately(context);
        }

        public static void InitializeSyncAdapter(Context context)
        {
            GetSyncAccount(context);
        }

        public async override void OnPerformSync(Android.Accounts.Account account, Android.OS.Bundle extras, string authority, ContentProviderClient provider, SyncResult syncResult)
        {

            Log.WriteLine(LogPriority.Debug, _tag, "Starting sync");

            try
            {

                var locationQuery = Utility.GetPreferredLocation(Context);

                // Constants for URL
                const string Url = "api.openweathermap.org";
                const string Path = "data/2.5/forecast/daily";
                const string Scheme = "http";

                // Constants for parameters
                const string Format = "json";
                const string Units = "metric";
                const int NumDays = 14;
                const string AppId = "582900aa4d4687a5711f7704ae16611a";

                var builder = new UriBuilder();
                var client = new HttpClient(new NativeMessageHandler());

                builder.Host = Url;
                builder.Path = Path;
                builder.Scheme = Scheme;
                var query = HttpUtility.ParseQueryString(builder.Query);
                query["mode"] = Format;
                query["units"] = Units;
                query["cnt"] = NumDays.ToString();
                query["appid"] = AppId;
                query["q"] = locationQuery;
                builder.Query = query.ToString();

                HttpResponseMessage response = await client.GetAsync(builder.Uri);

                var responseJson = await response.Content.ReadAsStringAsync();
                GetWeatherDataFromJson(responseJson, locationQuery);

            }
            catch (Java.Net.UnknownHostException e)
            {
                Log.WriteLine(LogPriority.Debug, _tag, $"Download failed with result {e.Message}");
            }
            catch (JsonSerializationException e)
            {
                Log.WriteLine(LogPriority.Debug, _tag, $"Json parser failed with error {e.Message}");
            }

            return;

        }

        /// <summary>
        /// Take the String representing the complete forecast in JSON Format and
        /// pull out the data we need to construct the Strings needed for the wireframes.
        /// Fortunately parsing is easy:  constructor takes the JSON string and converts it
        /// into an Object hierarchy for us.
        /// </summary>
        void GetWeatherDataFromJson(string forecastJsonStr, string locationSetting)
        {
            try
            {
                var jsonResult = JsonConvert.DeserializeObject<Weather>(forecastJsonStr);
                var city = jsonResult.City;
                var locationId = AddLocation(locationSetting, city.Name, city.Coord.Lat, city.Coord.Lon);

                // Insert the new weather information into the database
                var contentValuesList = new List<ContentValues>(jsonResult.WeatherDaysList.Count);

                var timeNow = DateTime.UtcNow;
                var startDate = timeNow.StartOfDay();

                for (int i = 0; i < jsonResult.WeatherDaysList.Count; i++)
                {

                    // Current time and time in days
                    var dateTime = startDate.AddDays(i).Ticks;

                    int humidity = jsonResult.WeatherDaysList[i].Humidity;
                    double pressure = jsonResult.WeatherDaysList[i].Pressure;
                    double windSpeed = jsonResult.WeatherDaysList[i].Speed;
                    double windDirection = jsonResult.WeatherDaysList[i].Deg;

                    // Description is in a child array called "weather", which is 1 element long.
                    // That element also contains a weather code.
                    var description = jsonResult.WeatherDaysList[i].Weather[0].Main;
                    int weatherId = jsonResult.WeatherDaysList[i].Weather[0].Id;

                    // Temperatures are in a child object called "temp".  Try not to name variables
                    // "temp" when working with temperature.  It confuses everybody.
                    var high = jsonResult.WeatherDaysList[i].Temp.Max;
                    var low = jsonResult.WeatherDaysList[i].Temp.Min;

                    var weatherValues = new ContentValues();

                    weatherValues.Put(WeatherContract.Weather.ColumnLocationKey, locationId);
                    weatherValues.Put(WeatherContract.Weather.ColumnDate, dateTime);
                    weatherValues.Put(WeatherContract.Weather.ColumnHumidity, humidity);
                    weatherValues.Put(WeatherContract.Weather.ColumnPressure, pressure);
                    weatherValues.Put(WeatherContract.Weather.ColumnWindSpeed, windSpeed);
                    weatherValues.Put(WeatherContract.Weather.ColumnDegrees, windDirection);
                    weatherValues.Put(WeatherContract.Weather.ColumnMaximumTemp, high);
                    weatherValues.Put(WeatherContract.Weather.ColumnMinimumTemp, low);
                    weatherValues.Put(WeatherContract.Weather.ColumnShortDescription, description);
                    weatherValues.Put(WeatherContract.Weather.ColumnWeatherId, weatherId);

                    contentValuesList.Add(weatherValues);

                }

                int inserted = 0;

                // add to database
                if (contentValuesList.Count > 0)
                {
                    inserted = Context.ContentResolver.BulkInsert(WeatherContract.Weather.ContentUri, contentValuesList.ToArray());

                    var yesterday = DateTime.UtcNow.StartOfDay().AddDays(-1);
                    Context.ContentResolver.Delete(WeatherContract.Weather.ContentUri,
                        WeatherContract.Weather.ColumnDate + " <= ?",
                        new string[] { yesterday.Ticks.ToString() });

                    NotifyWeather();
                }
                Log.WriteLine(LogPriority.Debug, _tag, $"FetchWeatherTask Complete {inserted} Inserted");

            }
            catch (JsonException e)
            {
                Log.WriteLine(LogPriority.Error, _tag, e.Message);
            }

        }

        /// <summary>
        /// Helper method to handle insertion of a new location in the weather database.
        /// </summary>
        /// <returns>The row ID of the added location</returns>
        /// <param name="locationSetting">The location string used to request updates from the server.</param>
        /// <param name="cityName">Human-readable city name, e.g "Mountain View"</param>
        /// <param name="lat">Latitude of the city</param>
        /// <param name="lon">Longitude of the city</param>
        public long AddLocation(string locationSetting, string cityName, double lat, double lon)
        {
            long locationId;

            var locationCursor = Context.ContentResolver.Query(WeatherContract.Location.ContentUri,
                                     new string[]{ WeatherContract.Location.Id  },
                                     WeatherContract.Location.TableName +
                                     "." + WeatherContract.Location.ColumnLocationSetting + " = ?",
                                     new string[]  { locationSetting },
                                     null);

            if (locationCursor.MoveToFirst())
            {
                int locationIdIndex = locationCursor.GetColumnIndex(WeatherContract.Location.Id);
                locationId = locationCursor.GetLong(locationIdIndex);

            }
            else
            {
                var contentValues = new ContentValues();
                contentValues.Put(WeatherContract.Location.ColumnCityName, cityName);
                contentValues.Put(WeatherContract.Location.ColumnLocationSetting, locationSetting);
                contentValues.Put(WeatherContract.Location.ColumnCoordinationLat, lat);
                contentValues.Put(WeatherContract.Location.ColumnCoordinationLong, lon);
                var insertedUri = Context.ContentResolver.Insert(WeatherContract.Location.ContentUri, contentValues);

                locationId = ContentUris.ParseId(insertedUri);

            }
            locationCursor.Close();
            return locationId;
        }

        /// <summary>
        /// Helper method to have the sync adapter sync immediately
        /// </summary>
        /// <param name="context">The context used to access the account service</param>
        public static void SyncImmediately(Context context)
        {
            var bundle = new Bundle();
            bundle.PutBoolean(ContentResolver.SyncExtrasExpedited, true);
            bundle.PutBoolean(ContentResolver.SyncExtrasManual, true);
            ContentResolver.RequestSync(GetSyncAccount(context),
                context.GetString(Resource.String.content_authority), bundle);
        }

        /// <summary>
        /// Helper method to get the fake account to be used with SyncAdapter, or make a new one
        /// if the fake account doesn't exist yet.  If we make a new account, we call the
        /// onAccountCreated method so we can initialize things.
        /// </summary>
        /// <returns>A fake account.</returns>
        /// <param name="context">The context used to access the account service</param>
        public static Account GetSyncAccount(Context context)
        {
            // Get an instance of the Android account manager
            var accountManager =
                (AccountManager)context.GetSystemService(Context.AccountService);

            // Create the account type and default account
            var newAccount = new Account(
                                 context.GetString(Resource.String.app_name), context.GetString(Resource.String.sync_account_type));

            // If the password doesn't exist, the account doesn't exist
            if (accountManager.GetPassword(newAccount) == null)
            {

                // Add the account and account type, no password or user data
                // If successful, return the Account object, otherwise report an error.
                if (!accountManager.AddAccountExplicitly(newAccount, "", null))
                {
                    return null;
                }

                OnAccountCreated(newAccount, context);

                // If you don't set android:syncable="true" in
                // in your <provider> element in the manifest,
                // then call ContentResolver.setIsSyncable(account, AUTHORITY, 1)
                //here.
            }
            return newAccount;
        }
    }
}


text:
package com.thinkgem.jeesite.modules.paimai.front.web;

import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import com.thinkgem.jeesite.common.bean.AjaxResult;
import com.thinkgem.jeesite.common.mapper.JsonMapper;
import com.thinkgem.jeesite.common.web.BaseController;
import com.thinkgem.jeesite.modules.sys.entity.gbj.GbjBuy;
import com.thinkgem.jeesite.modules.sys.service.gbj.GbjBuyService;

@Controller
//@RequestMapping(value = "${frontPath}")
public class FrontGbjBuyController extends BaseController{

	@Autowired
	private GbjBuyService gbjBuyService;

	//@RequestMapping(value= {"", "index"})
	public String index(Model model) {
		return "modules/paimai/front/index";
	}

	//@RequestMapping(value= {"buy"})
	@ResponseBody
	public AjaxResult buy(Model model, GbjBuy gbjBuy, HttpServletRequest request, RedirectAttributes redirectAttributes) {

		model.addAttribute("domainInfoJson", JsonMapper.toJsonString(gbjBuy));
		try{

			gbjBuyService.save(gbjBuy);

			addMessage(redirectAttributes, "提交查询成功,我们会及时联系您!");

			return AjaxResult.makeSuccess("提交查询成功,我们会及时联系您!");
		} catch (Exception e) {
			logger.error(e.getMessage());
			addMessage(redirectAttributes, "提交查询成功失败【"+e.getMessage()+"】");
			return AjaxResult.makeError("提交查询成功失败【"+e.getMessage()+"】");
		}

	}

}


text:
@title('Delete forum post by '.$post->user->name)
@extends('app')

@section('content')

Delete post by @avatar($post->user inline)

Forums

slug) }}">{{ $forum->name }}

id) }}">{{ $thread->title }}

Delete Post

    @form(post/delete)
        @hidden(id $post)

Are you sure you want to delete this post?

{!! $post->content_html !!}

        @submit = Delete Post
    @endform
@endsection