text:
#ifndef hpp_CompressStream_hpp
#define hpp_CompressStream_hpp

// We need stream declarations
#include "Streams.hpp"

#if (WantCompression == 1)

// We need base compressor declaration too
#include "../Compress/BaseCompress.hpp"
// We need ZLib implementation too for default usage
#include "../Compress/ZLib.hpp"

namespace Stream
{
    /** An input stream that's decompressing on-the-fly while being read.
        This is a pseudo stream, in the sense that a real stream is used
        underneath to refill the compressed buffer when necessary.
        It's not possible to seek this stream. */
    class DecompressInputStream : public LineSplitStream<Strings::FastString>
    {
        // Members
    private:
        /** The input stream to read from */
        Utils::OwnPtr<const InputStream> stream;
        /** The compressor to use */
        Utils::ScopePtr<Compression::BaseCompressor> compressor;
        /** The current accumulator of output bytes */
        mutable uint64 position;
        /** The decompressed size (if known at construction time) */
        const uint64 decompressedSize;

        // Interface
    public:
        /** Get the compressor used */
        inline const Compression::BaseCompressor * getCompressor() const { return compressor; }
        /** Try to read the given amount of data to the specified buffer
            @return the number of byte truly read (this method doesn't throw) */
        inline uint64 read(void * const outBuffer, const uint64 _size) const throw()
        {
            uint32 size = (uint32)min((uint64)0xFFFFFFFE, _size);
            MemoryBlockOutStream outStr((uint8*)outBuffer, size);
            if (compressor->decompressStream(outStr, *stream, size))
            {
                position += (uint64)outStr.currentPosition();
                return (uint64)outStr.currentPosition();
            }
            return (uint64)-1;
        }
        /** Move the stream position forward of the given amount
            This should give the same results as setPosition(currentPosition() + value),
            but implementation can be faster for non-seek-able stream. */
        inline bool goForward(const uint64 size) { return read(0, size) == size; }
        /** This method returns the stream length in byte, if known
            For stream where the length is not known, this method will return (uint64)-1.
            Returning -1 is safer than returning the compressed stream size */
        inline uint64 fullSize() const { return decompressedSize; }
        /** This method returns true if the end of stream is reached */
        inline bool endReached() const { return stream->currentPosition() == stream->fullSize() && !compressor->hasDataToFlush(); }
        /** This method returns the position of the next byte that could be read from this stream
            @warning This is false (as it returns the position in the compressed stream), but can nonetheless
                     can be used to estimate the current amount of data processed */
        inline uint64 currentPosition() const { return position; }
        /** Try to seek to the given absolute position (return false if not supported) */
        inline bool setPosition(const uint64) { return false; }

        // Construction and destruction
    public:
        /** Construct a DecompressInputStream object from the given stream with the given compressor (it's owned).
            @param stream       The actual stream to read compressed data from
            @param compressor   A pointer on a new allocated compressor that's own by this stream. If 0, a GZip is built and used. */
        DecompressInputStream(const InputStream & stream, Compression::BaseCompressor * compressor = 0, const uint64 decompressedSize = -1)
            : stream(stream), compressor(compressor), position(0), decompressedSize(decompressedSize)
        {
            if (!compressor)
                this->compressor = new Compression::GZip;
        }
        /** Construct a DecompressInputStream object from the given stream with the given compressor (it's owned).
            @param stream       The actual stream to read compressed data from (it's owned)
            @param compressor   A pointer on a new allocated compressor that's own by this stream. If 0, a GZip is built and used. */
        DecompressInputStream(const InputStream * stream, Compression::BaseCompressor * compressor = 0, const uint64 decompressedSize = -1)
            : stream(stream), compressor(compressor), position(0), decompressedSize(decompressedSize)
        {
            if (!compressor)
                this->compressor = new Compression::GZip;
        }

        ~DecompressInputStream()
        {
            // Before actually destructing the compressor, we have to read nothing out of the decompressor.
            // Some compression engine might require doing cleanup stuff and this is the signal for it.
            Strings::FastString outString;
            OutputStringStream outStream(outString);
            Strings::FastString inString;
            InputStringStream inStream(inString); // Empty input stream to empty any pending buffer of the compressor
            compressor->decompressStream(outStream, inStream); // We don't care about the result.
        }
    };

    /** An output stream that's compressing on-the-fly while being written into.
        This is a pseudo stream, in the sense that a real stream is used
        underneath to fill a compressed buffer and flush to the output stream when necessary.
        It's not possible to seek this stream.
        Beware that the output will only be correct with the object is deleted
        (some compressor require writing footer informations to the stream)  */
    class CompressOutputStream : public OutputStream
    {
        // Members
    private:
        /** The stream to write to */
        Utils::OwnPtr<OutputStream> stream;
        /** The amount written */
        uint64  amount;
        /** The compressor to use */
        Utils::ScopePtr<Compression::BaseCompressor> compressor;

        // Interface
    public:
        /** Get the compressor used */
        inline const Compression::BaseCompressor * getCompressor() const { return compressor; }
        /** This method returns the stream length in byte, if known
            If the length is equal or higher than 2^32 - 1, the returned value is 0xfffffffe */
        virtual uint64 fullSize() const  { return amount; }
        /** This method returns true if the end of stream is reached */
        virtual bool endReached() const  { return true; }
        /** This method returns the position of the next byte that could be read from this stream */
        virtual uint64 currentPosition() const { return fullSize(); }
        /** Try to seek to the given absolute position (return false if not supported) */
        virtual bool setPosition(const uint64) { return false; }
        /** Move the stream position forward of the given amount
            This should give the same results as setPosition(currentPosition() + value),
            but implementation can be faster for non-seek-able stream. */
        virtual bool goForward(const uint64) { return false; }
        /** Try to write the given amount of data to the specified buffer
            @return the number of byte truly written (this method doesn't throw) */
        virtual uint64 write(const void * const buffer, const uint64 size) throw()
        {   // Don't flush the stream
            if (compressor->compressStream(*stream, MemoryBlockStream((const uint8*)buffer, size), 0, false))
            {
                amount += size;
                return size;
            }
            return (uint64)-1;
        }
        /** Try to write the given amount of data to the specified buffer.
            Unlike the former version, this version also tells if the stream needs to be flushed */
        virtual uint64 write(const void * const buffer, const uint64 size, const bool flush) throw()
        {
            if (compressor->compressStream(*stream, MemoryBlockStream((const uint8*)buffer, size), 0, flush))
            {
                amount += size;
                return size;
            }
            return (uint64)-1;
        }

        // Construction and destruction
    public:
        /** Construct a DecompressInputStream object from the given stream with the given compressor (it's owned).
            @param stream       The actual stream to read compressed data to (must exist after this object is deleted)
            @param comp        A pointer on a new allocated compressor that's own by this stream. If 0, a GZip is built and used. */
        CompressOutputStream(OutputStream & stream, Compression::BaseCompressor * comp = 0)
            : stream(stream), compressor(comp)
        {
            if (!compressor)
                compressor = new Compression::GZip;
        }
        /** Construct a DecompressInputStream object from the given stream with the given compressor (it's owned).
            @param stream       A pointer on an output stream that's owned by this object
            @param comp        A pointer on a new allocated compressor that's own by this stream. If 0, a GZip is built and used. */
        CompressOutputStream(OutputStream * stream, Compression::BaseCompressor * comp = 0)
            : stream(stream), compressor(comp)
        {
            if (!compressor)
                compressor = new Compression::GZip;
        }

        ~CompressOutputStream()
        {
            // Before actually destructing the compressor, we have to write nothing out of the compressor.
            // Some compression engine might require doing cleanup stuff and this is the signal for it.
            compressor->compressStream(*stream, MemoryBlockStream(0, 0), 0, true); // We don't care about the result, we force flushing
        }
    };

    /** An output stream based on a memory buffer for the first one,
        and a general purpose stream for the second one.
        In general, it's used when you need to write a header and then the data,
        and have to go back to the header to rewrite part of it.
        In order to do so, this stream check the functionalities of the given output streams,
        and if the output stream doesn't support seeking, it has to buffer the whole output to memory in order to work.
        In that case, the destructor will copy the output stream (so it must still exists by that time).
        You might be interested in absolutePosition() method. */
    class HeaderBodyStream : public OutputStream
    {
        // Members
    private:
        /** The header stream (its size must be known at construction) */
        MemoryBlockOutStream header;
        /** The data stream to write too */
        OutputStream & dataStream;
        /** The initial output stream position */
        uint64 initialOutPosition;
        /** The memory data stream if the former is not seekable */
        Utils::ScopePtr<OutputMemStream> bufferStream;
        /** The current global position */
        uint64 position;

        // Interface
    public:
        /** This method returns the stream length in byte, if known
            If the length is equal or higher than 2^32 - 1, the returned value is 0xfffffffe
            For stream where the length is not known, this method will return 0xffffffff. */
        virtual uint64 fullSize() const { return (bufferStream ? header.fullSize() + bufferStream->fullSize() : dataStream.fullSize() - initialOutPosition); }
        /** This method returns true if the end of stream is reached */
        virtual bool endReached() const { return position == fullSize(); }
        /** This method returns the position of the next byte that could be read from this stream */
        virtual uint64 currentPosition() const { return position; }
        /** Returns the absolute position.
            Since there are multiple streams, with possibly buffered output, the currentPosition() above
            will return the position for the current stream.
            On the other side, this method will return the (theoretical) position of the final output stream
            (so it includes any offset in the output stream and un-buffering computation) */
        inline uint64 absolutePosition() const { return bufferStream ? (header.fullSize() + dataStream.currentPosition() + bufferStream->fullSize()) : header.fullSize() + dataStream.currentPosition(); }
        /** Try to seek to the given absolute position (return false if not supported) */
        virtual bool setPosition(const uint64 newPos)
        {
            position = newPos;
            if (bufferStream)
            {
                if (newPos > header.fullSize())
                    return bufferStream->setPosition(newPos - header.fullSize());
            }
            else return dataStream.setPosition(initialOutPosition + newPos);
            return true;
        }
        /** Try to write the given amount of data to the specified buffer
            @return the number of byte truly written (this method doesn't throw) */
        virtual uint64 write(const void * const buffer, const uint64 size) throw()
        {
            uint64 done = 0;
            if (position < header.fullSize())
            {
                uint64 amount = min(header.fullSize() - position, size);
                if (buffer) memcpy(header.getBuffer() + position, buffer, (size_t)amount);
                position += amount;
                done += amount;
            }
            // Need to write to the second stream ?
            if (done < size)
            {
                OutputStream * out = bufferStream ? bufferStream : &dataStream;
                uint64 res = out->write((uint8*)buffer + done, size - done);
                if (res == (uint64)-1) return res;
                done += res;
                position += res;
            }
            return done;
        }

        /** Build an header body stream.
            @param outStream    The output stream to write too
            @param headerSize   The header size */
        HeaderBodyStream(OutputStream & outStream, const uint32 headerSize)
            : header(new uint8[headerSize], headerSize), dataStream(outStream), initialOutPosition(dataStream.currentPosition()),
              bufferStream(dataStream.setPosition(dataStream.currentPosition()) ? 0 : new OutputMemStream()), position(0)
        {
            if (!bufferStream) dataStream.setPosition(headerSize + initialOutPosition); // Since we don't always start from 0
        }

        ~HeaderBodyStream()
        {
            if (!bufferStream)
                dataStream.setPosition(initialOutPosition);
            // Need to copy the final operation to the output stream
            dataStream.write(header.getBuffer(), header.fullSize());
            if (bufferStream)
                dataStream.write(bufferStream->getBuffer(), bufferStream->fullSize()); // Not checking the result
            // Seek back to the end of stream (might fail, but we don't care)
            dataStream.setPosition(dataStream.fullSize());
            // Now wipe the header
            delete[] header.getBuffer();
        }
    };

}
#endif

#endif


text:
Compiled example
----------------
![Example](Analysis_Wichtige_Formeln.png)

redpajama_set_name: RedPajamaGithub


text:
dhis2.util.namespace( 'dhis2.commons' );

dhis2.commons.getCurrentPage = function() {
	return $.cookie( "currentPage" );
}

dhis2.commons.getCurrentKey = function() {
	return $.cookie( "currentKey" );
}

dhis2.commons.redirectCurrentPage = function( url ) {
	var currentPage = dhis2.commons.getCurrentPage();
	var currentKey = dhis2.commons.getCurrentKey();
	var separator = url && url.indexOf( "?" ) == -1 ? "?" : "&";

    var redirect = url;

    if ( currentPage && currentKey ) {
        redirect = currentPage ? ( url + separator + "currentPage=" + currentPage + "&key=" + currentKey ) : url;
    }
    else if ( currentPage ) {
        redirect = currentPage ? ( url + separator + "currentPage=" + currentPage ) : url;
    }

    window.location.href = redirect;
};

// -----------------------------------------------------------------------------
// Global variables
// -----------------------------------------------------------------------------

var headerMessageTimeout = -1;
var _loading_bar_html = "";
var _loading_circle_html = "";

/**
 * Go back using the document.referrer.
 *
 * @param defaultUrl if there is not document.referrer, use this url
 */
function referrerBack( defaultUrl )
{
	if ( document.referrer !== undefined && document.referrer != "" )
	{
		if ( document.referrer.indexOf( "login.action" ) == -1 )
		{
			location.href = document.referrer;
			return;
		}
	}

	location.href = defaultUrl;
}

/**
 * Redirects to the translate GUI.
 *
 * @param context Context vars from context menu
 */
function translateWithContext( context )
{
  translate( context.type, context.uid );
}

/**
 * Redirects to the translate GUI.
 *
 * @param className the name of the object class.
 * @param objectId the identifier of the object.
 */
function translate( className, uid )
{
    var url = "../dhis-web-commons/i18n.action?className=" + className + "&uid=" + uid + "&returnUrl=" + htmlEncode( window.location.href );

    window.location.href = url;
}

/**
 * Scrolls the view port to the bottom of the document.
 */
function scrollToBottom()
{
	var scrollTop = parseInt( $( document ).height() - $( window ).height() );

	if ( scrollIsRelevant() )
	{
		$( document ).scrollTop( scrollTop );
	}
}

/**
 * Scrolls the view port to the top of the document.
 */
function scrollToTop()
{
	$( document ).scrollTop( 0 );
}

/**
 * Indicates whether there is a need for scrolling.
 */
function scrollIsRelevant()
{
	var scrollTop = parseInt( $( document ).height() - $( window ).height() );
	var relevant = ( scrollTop > 0 );
	return relevant;
}

/**
 * Joins the names of the given array of objects and returns it as a single string.
 */
function joinNameableObjects( objects )
{
	var string = "";
	var size = objects.length;

	for ( var i in objects )
	{
		string += objects[i].name;

		if ( i < ( size - 1 ) )
		{
			string += ", ";
		}
	}

	return string;
}

/**
 * Gets help content for the given id. Opens the right bar and puts the content
 * inside. Reads data from an underlying docbook file.
 *
 * @param id the content id, refers to the section id in the docbook file.
 */
function getHelpContent( id )
{
    $.get(
       '../dhis-web-commons-about/getHelpContent.action',
       { "id": id },
       function( data )
       {
           $( "div#rightBar" ).fadeIn();
           $( "div#rightBarContents" ).html( data );
       } );
}

/**
 * Hides the help content.
 */
function hideHelpContent()
{
	$( "div#rightBar" ).fadeOut();
}

/**
 * Filters values in a html table with tbody id "list".
 *
 * @param filter the filter.
 */
function filterValues( filter, columnIndex )
{
	if( columnIndex==undefined ) columnIndex = 1;

    var list = document.getElementById( 'list' );

    var rows = list.getElementsByTagName( 'tr' );

    for ( var i = 0; i < rows.length; ++i )
    {
        var cell = rows[i].getElementsByTagName( 'td' )[columnIndex - 1];

        var value = cell.firstChild.nodeValue;

        if ( value.toLowerCase().indexOf( filter.toLowerCase() ) != -1 )
        {
            rows[i].style.display = 'table-row';
        }
        else
        {
            rows[i].style.display = 'none';
        }
    }
}

/**
 * Returns the value of the selected option in the list with the given
 * identifier.
 *
 * @param listId the list identifier.
 */
function getListValue( listId )
{
    var list = document.getElementById( listId );
    var value = list.options[ list.selectedIndex ].value;

    return value;
}

/**
 * Hides the document element with the given identifier.
 *
 * @param id the element identifier.
 */
function hideById( id )
{
    jQuery("#" + id).hide();
}

/**
 * Shows the document element with the given identifier.
 *
 * @param id the element identifier.
 */
function showById( id )
{
    jQuery("#" + id).show();
}

/**
 * Returns true if the element with the given identifier has text, false if not.
 *
 * @param inputId the identifier of the input element.
 */
function hasText( inputId )
{
    return trim( getFieldValue( inputId ) ) != "";
}

function trim( string )
{
	return jQuery.trim( string );
}

/**
 * Returns true if the element with the given identifier is checked, false if
 * not or if it does not exist.
 *
 * @param checkboxId the identifier of the checkbox element.
 */
function isChecked( checkboxId )
{
	return jQuery( "#" + checkboxId ).length && jQuery( "#" + checkboxId ).is( ":checked" );
}

/**
 * Toggles the checked property of checkbox elements.
 */
function toggleChecked( checkBoxId )
{
	var box = jQuery( "#" + checkBoxId );

	if ( box.length )
	{
		box.prop( "checked", !box.is( ":checked" ) );
	}
}

/**
 * Checks the checkbox with the given identifier if the checkbox exists.
 */
function check( checkBoxId )
{
    jQuery( "#" + checkBoxId ).prop( "checked", true );
}

/**
 * Unchecks the checkbox with the given identifier if the checkbox exists.
 */
function uncheck( checkBoxId )
{
    jQuery( "#" + checkBoxId ).prop( "checked", false );
}

/**
 * Enables the element with the given identifier if the element exists.
 */
function enable( elementId )
{
	var hasDatePicker = jQuery("#" + elementId ).data("datepicker");
	if( hasDatePicker == undefined)
	{
		jQuery( "#" + elementId ).removeAttr( "disabled" );
	}
	else
	{
		jQuery('#' + elementId ).datepicker( "enable" );
	}
}

function enableGroup( selectorJQueryString )
{
	jQuery.each( jQuery( selectorJQueryString ), function( i, item ){
		item.disabled = false;
	});
}

/**
 * Disables the element with the given identifier if the element exists.
 */
function disable( elementId )
{
	var hasDatePicker = jQuery("#" + elementId ).data("datepicker");
	if( hasDatePicker == undefined)
	{
		jQuery( "#" + elementId ).prop("disabled", true );
	}
	else
	{
		jQuery('#' + elementId ).datepicker( "disable" );
	}
}

function disableGroup( selectorJQueryString )
{
	jQuery.each( jQuery( selectorJQueryString ), function( i, item ){
		item.disabled = true;
	});
}

/**
 * Enables the element with the given identifier if the element exists in parent
 * window of frame.
 */
function enableParent( elementId )
{
    var element = parent.document.getElementById( elementId );

    if ( element )
    {
        element.disabled = false;
    }
}

/**
 * Disables the element with the given identifier if the element exists in
 * parent window of frame.
 */
function disableParent( elementId )
{
    var element = parent.document.getElementById( elementId );

    if ( element )
    {
        element.disabled = true;
    }
}

/**
 * Returns true if the element with the given identifier has selected elements
 * associated with it, false if not.
 *
 * @param listId the identifier of the list element.
 */
function hasElements( listId )
{
    return jQuery( "#" + listId ).children().length > 0;
}

/**
 * Returns true if the given value not equals null or "null" string, false if not.
 *
 * @param value the given value.
 */
function isNotNull( value )
{
    return ( value != null && trim(value) != "null" );
}

/**
 * Returns true if the element with the given identifier exists, false if not.
 *
 * @param elementId the identifier of the element.
 */
function isNotEmpty( elementId )
{
    return jQuery("#" + elementId).length == 1;
}

/**
 * HTML encodes the given string.
 *
 * @param str the input string.
 * @return the HTML encoded string.
 */
function htmlEncode( str )
{
    str = str.replace( /\%/g, "%25" ); // This line must come first so the %
										// doesn't get overwritten later
    str = str.replace( /\ /g, "%20" );
    str = str.replace( /\!/g, "%21" );
    str = str.replace( /\"/g, "%22" );
    str = str.replace( /\#/g, "%23" );
    str = str.replace( /\$/g, "%24" );
    str = str.replace( /\&/g, "%26" );
    str = str.replace( /\'/g, "%27" );
    str = str.replace( /\(/g, "%28" );
    str = str.replace( /\)/g, "%29" );
    str = str.replace( /\*/g, "%2a" );
    str = str.replace( /\+/g, "%2b" );
    str = str.replace( /\,/g, "%2c" );
    str = str.replace( /\-/g, "%2d" );
    str = str.replace( /\./g, "%2e" );
    str = str.replace( /\//g, "%2f" );
    str = str.replace( /\:/g, "%3a" );
    str = str.replace( /\;/g, "%3b" );
    str = str.replace( /\</g, "%3c" );
    str = str.replace( /\=/g, "%3d" );
    str = str.replace( /\>/g, "%3e" );
    str = str.replace( /\?/g, "%3f" );
    str = str.replace( /\@/g, "%40" );

    return str;
}

/**
 * Gets the value for the element with the given name from the DOM object.
 *
 * @param parentElement the DOM object.
 * @param childElementName the name of the element.
 */
function getElementValue( parentElement, childElementName )
{
    var textNode = parentElement.getElementsByTagName( childElementName )[0].firstChild;

    return textNode ? textNode.nodeValue : null;
}

/**
 * Gets the attribute value from the given DOM element.
 *
 * @param parentElement the DOM object.
 * @param attributeName the name of the attribute.
 */
function getElementAttribute( parentElement, childElementName, childAttributeName )
{
	var textNode = parentElement.getElementsByTagName( childElementName )[0];

    return textNode ? textNode.getAttribute( childAttributeName ) : null;
}

/**
 * Gets the value from the given DOM element.
 *
 * @param rootElement the DOM object.
 */
function getRootElementValue( rootElement )
{
    var textNode = rootElement.firstChild;

    return textNode ? textNode.nodeValue : null;
}

/**
 * Gets the value of the attribute with the given name from the given DOM
 * element.
 *
 * @param rootElement the DOM object.
 * @param attributeName the name of the attribute.
 */
function getRootElementAttribute( rootElement, attributeName )
{
   return rootElement.getAttribute( attributeName );
}

/**
 * Sets the text (HTML is not interpreted) on the given element.
 *
 * @param fieldId the identifier of the element.
 * @param txt the text to set.
 */
function setText( fieldId, txt )
{
    jQuery("#" + fieldId).text( txt );
}

/**
 * Sets a value on the given element.
 *
 * @param fieldId the identifier of the element.
 * @param value the value to set.
 */
function setInnerHTML( fieldId, value )
{
    jQuery("#" + fieldId).html( value );
}

/**
 * Gets a value from the given element and HTML encodes it.
 *
 * @param fieldId the identifier of the element.
 * @return the HTML encoded value of the element with the given identifier.
 */
function getInnerHTML( fieldId )
{
    return jQuery("#" + fieldId).html();
}

/**
 * Sets a value on the given element.
 *
 * @param fieldId the identifier of the element.
 * @param value the value to set.
 */
function setFieldValue( fieldId, value )
{
    jQuery("#" + fieldId).val( value );
}

/**
 * Gets a value from the given element and HTML encodes it.
 *
 * @param fieldId the identifier of the element.
 * @return the HTML encoded value of the element with the given identifier.
 */
function getFieldValue( fieldId )
{
	if ( getTypeById( fieldId, 'multiple' ) )
	{
		var selectedItem = jQuery("#" + fieldId).children( "option:selected" )[0];

		return (selectedItem ? selectedItem.value : selectedItem);
	}

	return jQuery("#" + fieldId).val();
}

/**
 * Gets a value from the given element and HTML encodes it.
 *
 * @param fieldId the identifier of the element.
 * @return the type of the element with the given identifier.
 */
function getTypeById( fieldId, attribute )
{
	return jQuery("#" + fieldId).attr( attribute );
}

/**
 * get value of input radio with name
 *
 * @param radioName name of input radio
 */
function getRadioValue( radioName )
{
	result = null;
	jQuery.each( jQuery( "input[type=radio][name=" + radioName + "]") , function( i, item )
	{
		if ( item.checked )
		{
			result = item.value;
		}
	});

	return result;
}

/**
 * set value for input radio with name
 *
 * @param radioName name of input radio
 */
function setRadioValue( radioName, value )
{
	jQuery.each( jQuery( "input[type=radio][name=" + radioName + "]") , function( i, item )
	{
		if ( item.value == value )
		{
			item.checked = true;
		}
	});
}

// -----------------------------------------------------------------------------
// Message, warning, info, headerMessage
// -----------------------------------------------------------------------------

/**
 * Shows the message span and sets the message as text.
 *
 * @param message the message.
 */
function setMessage( message )
{
	if ( message )
	{
		$( '#message' ).html( message ).show();
	}
}

/**
 * Shows the message span and sets the message as text together with a wait
 * animation.
 *
 * @param message the message.
 */
function setWaitMessage( message )
{
	setMessage( message + "   " + _loading_bar_html );
}

/**
 * Makes the "message" span invisible.
 */
function hideMessage()
{
	$( '#message' ).hide();
}

/**
 * Slides down the header message div and sets the message as text.
 *
 * @param message the message.
 */
function setHeaderMessage( message )
{
	window.clearTimeout( headerMessageTimeout );

    $( '#headerMessage' ).html( message );

    if ( isHeaderMessageHidden() )
    {
    	$( '#headerMessage' ).fadeIn( 'fast' );
    }
}

/**
 * Slides down the header message div and sets the message as text together with
 * a wait animation.
 *
 * @param message the message.
 */
function setHeaderWaitMessage( message )
{
	window.clearTimeout( headerMessageTimeout );

	$( 'div#headerMessage' ).html( message + "   " + _loading_bar_html );

	if ( isHeaderMessageHidden() )
	{
    	$( 'div#headerMessage' ).fadeIn( 'fast' );
	}
}

/**
 * Sets the header message and hides it after 3 seconds.
 */
function setHeaderDelayMessage( message )
{
	setHeaderMessage( message );

	window.clearTimeout( headerMessageTimeout );

	headerMessageTimeout = window.setTimeout( "hideHeaderMessage();", 7000 );
}

/**
 * Sets the header wait message and hides it after 3 seconds.
 */
function setHeaderWaitDelayMessage( message )
{
	setHeaderWaitMessage( message );

	window.clearTimeout( headerMessageTimeout );

	headerMessageTimeout = window.setTimeout( "hideHeaderMessage();", 7000 );
}

/**
 * Hides the header message div.
 */
function hideHeaderMessage()
{
    $( '#headerMessage' ).fadeOut( 'fast' );
}

/**
 * Indicates whether the header message is visible.
 */
function isHeaderMessageVisible()
{
    return $( '#headerMessage' ).is( ":visible" );
}

/**
 * Indicates whether the header message is not visible.
 */
function isHeaderMessageHidden()
{
    return !isHeaderMessageVisible();
}

/**
 * Slides down the info message div and sets the message as text.
 *
 * @param message the message.
 */
function setInfo( message )
{
    $( '#info' ).html( message );
    $( '#info' ).fadeIn( 'fast' );
}

/**
 * Hides the info div.
 */
function hideInfo()
{
    $( '#info' ).fadeOut( 'fast' );
}

/**
 * Makes the "detailsArea" span visible.
 */
function showDetails()
{
	$( '#detailsData' ).css( 'width', '270px' );
    $( '#detailsArea' ).show();
}

/**
 * Makes the "detailsArea" span invisible.
 */
function hideDetails()
{
	$( '#detailsData' ).css( 'width', '0' );
    $( '#detailsArea' ).hide();
}

/**
 * Makes the "warningArea" span visible.
 */
function showWarning()
{
    $( '#warningArea' ).show();
}

/**
 * Makes the "warningArea" span invisible.
 */
function hideWarning()
{
    $( '#warningArea' ).hide();
}

/**
 * Convenience method for getting a document element.
 *
 * @param id id of the element to get.
 */
function byId( elementId )
{
    return document.getElementById( elementId );
}

// -----------------------------------------------------------------------------
// Supportive functions
// -----------------------------------------------------------------------------

/**
 * Toggles visibility for an element.
 *
 * @param id the identifier of the element.
 * @param display boolean indicator.
 */
function toggleByIdAndFlag( id, display )
{
    var node = byId( id );

    if ( !node )
    {
        return;
    }

    node.style.display = ( display ? 'block' : 'none' );
}

/**
 * Toggles visibility for an element.
 *
 * @param id the identifier of the element.
 */
function toggleById( id )
{
    var node = byId( id );

    if ( !node )
    {
        return;
    }

    var display = node.style.display;

    node.style.display = ( display == 'none' || display == '' ? 'block' : 'none' );
}

/**
 * Returns a query string with all element values in the select list and the
 * specified param.
 */
function getParamString( elementId, param )
{
    var result = "";
	var list = jQuery( "#" + elementId ).children();

	list.each( function( i, item ){
		result += param + "=" + item.value;
		result += (i < list.length-1) ? "&" : "";
	});

	return result;
}

/**
 * @deprecated Use addOptionById
 */
function addOptionToList( list, optionValue, optionText )
{
    var option = document.createElement( "option" );
    option.value = optionValue;
    option.text = optionText;
    list.add( option, null );
}

/**
 * Returns a query string on the form <paramName>=<listValue> based on the
 * options in the list with the given identifier.
 *
 * @param listId the list identifier.
 * @param paramName the name of the query param.
 * @return a query string.
 */
function getQueryStringFromList( listId, paramName )
{
	var list = document.getElementById( listId );

	var params = "";

	for ( var i = 0; i < list.options.length; i++ )
	{
		list.options[i].selected = "selected";
		params += paramName + "=" + list.options[i].value + "&";
	}

	return params;
}

/**
 * Shows loader div and hides content div.
 */
function showLoader()
{
    $( "div#loaderDiv" ).show();
    $( "div#contentDiv" ).hide();
}

/**
 * Hides loader div and shows content div.
 */
function hideLoader()
{
    $( "div#loaderDiv" ).hide();
    $( "div#contentDiv" ).show();
}

/**
 * Deletes and removes an item from a table. The table row to be removed must
 * have an identifier on the form "tr[itemId]".
 *
 * @param itemId the item identifier.
 * @param itemName the item name.
 * @param message the confirmation message.
 * @param action the server action url for deleting the item.
 */
function removeItem( itemId, itemName, confirmation, action, success )
{
    var result = window.confirm( confirmation + "\n\n" + itemName );

    if ( result )
    {
    	setHeaderWaitMessage( i18n_deleting );

    	$.postJSON(
    	    action,
    	    {
    	        "id": itemId
    	    },
    	    function( json )
    	    {
    	    	if ( json.response == "success" )
    	    	{
					jQuery( "tr#tr" + itemId ).remove();

					jQuery( "table.listTable tbody tr" ).removeClass( "listRow listAlternateRow" );
	                jQuery( "table.listTable tbody tr:odd" ).addClass( "listAlternateRow" );
	                jQuery( "table.listTable tbody tr:even" ).addClass( "listRow" );
					jQuery( "table.listTable tbody" ).trigger("update");

					if ( success && typeof( success) == "function" )
					{
						success.call();
					}

					setHeaderDelayMessage( i18n_delete_success );
    	    	}
    	    	else if ( json.response == "error" )
    	    	{
					setHeaderMessage( json.message );
    	    	}
    	    }
    	).fail( function(response){
          setHeaderMessage( response.responseText );
      });
    }
}

/**
 * Create jQuery datepicker for input text with id * *
 *
 * @param id the id of input field which you want enter date *
 */
function datePicker( id, hideDel )
{
	$("#" + id).datepicker(
	{
		dateFormat: dateFormat,
		changeMonth: true,
		changeYear: true,
		monthNamesShort: monthNames,
		dayNamesMin: dayNamesMin,
		showOn: 'both',
		createButton: false,
		constrainInput: true,
        yearRange: '-100:+100'
	});
	jQuery( "#" + id ).attr("readonly", true );
	jQuery( ".ui-datepicker-trigger").hide();

	addRemoveDateButton( id, hideDel );

	s = jQuery("#" + id );
	if( s.val()=='' ) s.val( getCurrentDate() );
}

function datePicker( id, today, hideDel )
{
	$("#" + id).datepicker(
	{
		dateFormat: dateFormat,
		changeMonth: true,
		changeYear: true,
		monthNamesShort: monthNames,
		dayNamesMin: dayNamesMin,
		createButton: false,
		constrainInput: true,
        yearRange: '-100:+100'
	});
	jQuery( "#" + id ).attr("readonly", true );
	jQuery( ".ui-datepicker-trigger").hide();
	addRemoveDateButton( id, hideDel );

	if( today == undefined ) today = false;

	if( today ){
		s = jQuery("#" + id );
		if( s.val()=='' ) s.val( getCurrentDate() );
	}

	addRemoveDateButton( id, hideDel );
}

function datePickerjQuery( jQueryString, hideDel )
{
	jQuery( jQueryString ).datepicker(
	{
		dateFormat: dateFormat,
		changeMonth: true,
		changeYear: true,
		monthNamesShort: monthNames,
		dayNamesMin: dayNamesMin,
		buttonImageOnly: true,
		constrainInput: true,
        yearRange: '-100:+100'
	});
	jQuery( "#" + id ).attr("readonly", true );
	jQuery( ".ui-datepicker-trigger").hide();
	addRemoveDateButton( id, hideDel );
}

/**
 * Create jQuery datepicker for input text with id * *
 *
 * @param id the id of input field which you want enter date *
 */
function datePickerValid( id, today, hideDel )
{
	jQuery("#" + id).datepicker(
	{
		dateFormat: dateFormat,
		changeMonth: true,
		changeYear: true,
		monthNamesShort: monthNames,
		dayNamesMin: dayNamesMin,
		createButton: false,
		maxDate: '+0d +0w',
		constrainInput: true,
        yearRange: '-100:+100'
	});
	jQuery( "#" + id ).attr("readonly", true );
	jQuery( ".ui-datepicker-trigger").hide();
	addRemoveDateButton( id, hideDel );

	if ( today == undefined )
	{
		today = false;
	}

	if( today )
	{
		s = jQuery("#" + id );
		if( s.val()=='' ) s.val( getCurrentDate() );
	}
}

function datePickerFuture( id, today, hideDel )
{
	jQuery("#" + id).datepicker(
	{
		dateFormat: dateFormat,
		changeMonth: true,
		changeYear: true,
		monthNamesShort: monthNames,
		dayNamesMin: dayNamesMin,
		createButton: false,
		minDate: '+0d +0w',
		constrainInput: true,
        yearRange: '-100:+100'
	});
	jQuery( "#" + id ).attr("readonly", true );
	jQuery( ".ui-datepicker-trigger").hide();
	addRemoveDateButton( id, hideDel );

	if ( today == undefined )
	{
		today = false;
	}

	if( today )
	{
		s = jQuery("#" + id );
		if( s.val()=='' ) s.val( getCurrentDate() );
	}
}

/**
 * Create jQuery datepicker for start date and end date text with id
 *
 * @param startdate the id of input field which you want enter start date *
 * @param enddate the id of input field which you want enter end date *
 */
function datePickerInRange ( startdate, enddate, setCurrentStartDate, setCurrentEndDate, hideDel )
{
	if( setCurrentStartDate == undefined ) setCurrentStartDate = true;
	if( setCurrentEndDate == undefined ) setCurrentEndDate = true;

	s = jQuery("#" + startdate );
	e = jQuery("#" + enddate );
	if( setCurrentStartDate && s.val()=='') s.val( getCurrentDate() );
	if( setCurrentEndDate && e.val()=='' ) e.val( getCurrentDate() );

	var dates = $('#'+startdate+', #' + enddate).datepicker(
	{
		dateFormat: dateFormat,
		defaultDate: "+1w",
		changeMonth: true,
		changeYear: true,
		numberOfMonths: 1,
		monthNamesShort: monthNames,
		dayNamesMin: dayNamesMin,
		showAnim: '',
		createButton: false,
		constrainInput: true,
        yearRange: '-100:+100',
		onSelect: function(selectedDate)
		{
			var option = this.id == startdate ? "minDate" : "maxDate";
			var instance = $(this).data("datepicker");
			var date = $.datepicker.parseDate(instance.settings.dateFormat || $.datepicker._defaults.dateFormat, selectedDate, instance.settings);
			dates.not(this).datepicker("option", option, date);
		}
	});

	jQuery( "#" + startdate ).attr("readonly", true );
	jQuery( "#" + enddate ).attr("readonly", true );
	jQuery( ".ui-datepicker-trigger").hide();
	addRemoveDateButton( startdate, hideDel );
	addRemoveDateButton( enddate, hideDel );

    $("#ui-datepicker-div").hide();
}

function datePickerInRangeValid( startdate, enddate, setCurrentStartDate, setCurrentEndDate, hideDel )
{
	if( setCurrentStartDate == undefined ) setCurrentStartDate = true;
	if( setCurrentEndDate == undefined ) setCurrentEndDate = true;

	s = jQuery("#" + startdate );
	e = jQuery("#" + enddate );
	if( setCurrentStartDate && s.val()=='') s.val( getCurrentDate() );
	if( setCurrentEndDate && e.val()=='' ) e.val( getCurrentDate() );

	var dates = $('#'+startdate+', #' + enddate).datepicker(
	{
		dateFormat: dateFormat,
		defaultDate: "+1w",
		changeMonth: true,
		changeYear: true,
		numberOfMonths: 1,
		maxDate: '+0d +0w',
		monthNamesShort: monthNames,
		dayNamesMin: dayNamesMin,
		showAnim: '',
		createButton: false,
		constrainInput: true,
        yearRange: '-100:+100',
		onSelect: function(selectedDate)
		{
			var option = this.id == startdate ? "minDate" : "maxDate";
			var instance = $(this).data("datepicker");
			var date = $.datepicker.parseDate(instance.settings.dateFormat || $.datepicker._defaults.dateFormat, selectedDate, instance.settings);
			dates.not(this).datepicker("option", option, date);
		}
	});

	jQuery( "#" + startdate ).attr("readonly", true );
	jQuery( "#" + enddate ).attr("readonly", true );
	jQuery( ".ui-datepicker-trigger").hide();
	addRemoveDateButton( startdate, hideDel );
	addRemoveDateButton( enddate, hideDel );
}

function addRemoveDateButton( id, hideDel )
{
	if( hideDel == undefined ) hideDel = true;
	if( !hideDel ){
		var removeId = 'delete_' + id;
		if( jQuery("#" + removeId).length == 0 )
		{
			jQuery("#" + id).after(function() {
			  return '  ';
			});
		}
	}
	jQuery( "#" + id).click(function() {
		$("#ui-datepicker-div").show();
	});
	jQuery( "#" + id).change(function() {
		$("#ui-datepicker-div").hide();
	});
}

function getCurrentDate()
{
	return jQuery.datepicker.formatDate( dateFormat , new Date() ) ;
}

/**
 * Create input table id become sortable table * *
 *
 * @param tableId the id of table you want to sort * *
 */

function tableSorter( tableId, sortList )
{
	if(sortList==undefined) sortList = [[0,0]];

	jQuery("#" + tableId ).tablesorter();

	if($("#" + tableId ).find("tbody").children().size() > 0 )
	{
		jQuery("#" + tableId ).trigger("sorton",[sortList]);
	}
}

function setSelectionRange( input, selectionStart, selectionEnd )
{
	if ( input.setSelectionRange )
	{
		input.focus();
	    input.setSelectionRange( selectionStart, selectionEnd );
	}
	else if ( input.createTextRange )
	{
	    var range = input.createTextRange();
	    range.collapse( true );
	    range.moveEnd( 'character', selectionEnd );
	    range.moveStart( 'character', selectionStart );
	    range.select();
	}
}

function setCaretToPos ( input, pos )
{
	setSelectionRange( input, pos, pos );
}

function insertTextCommon( inputAreaName, inputText )
{
	var inputArea = document.getElementById( inputAreaName );

	// IE support
	if ( document.selection )
	{
		inputArea.focus();
        sel = document.selection.createRange();
        sel.text = inputText;
        inputArea.focus();
	}
	// MOZILLA/NETSCAPE support
	else if ( inputArea.selectionStart || inputArea.selectionStart == '0' )
	{
		var startPos = inputArea.selectionStart;
		var endPos = inputArea.selectionEnd;

		var existingText = inputArea.value;
		var textBefore = existingText.substring( 0, startPos );
		var textAfter = existingText.substring( endPos, existingText.length );

		inputArea.value = textBefore + inputText + textAfter;
	}
	else
	{
		inputArea.value += inputText;
		inputArea.focus();
	}

	setCaretToPos( inputArea, inputArea.value.length );
}

// -----------------------------------------------------------------------------
// Form validation
// -----------------------------------------------------------------------------

/**
 * Create validator for fileds in form
 *
 * This should replace validation() at some point, but theres just to much code
 * depending on the old version for now.
 *
 * See http://bassistance.de/jquery-plugins/jquery-plugin-validation/ for more
 * information about jquery.validate.
 *
 * @param formId form to validate
 * @param submitHandler the submitHandler to use
 * @param kwargs A dictionary of optional arguments, currently supported are:
 *        beforeValidateHandler, rules
 */
function validation2( formId, submitHandler, kwargs )
{
	var beforeValidateHandler = null;

	if ( isDefined( kwargs ) )
	{
		beforeValidateHandler = kwargs["beforeValidateHandler"];
	}

	var rules = kwargs["rules"];
	var validator = jQuery( "#" + formId ).validate( {
		meta: "validate",
        errorElement: "span",
        warningElement: "span",
		beforeValidateHandler: beforeValidateHandler,
		submitHandler: submitHandler,
		rules: rules,
		errorPlacement: function(error, element) {
			element.parent( "td" ).append( "
" ).append( error );
		}
	} );

	$( "#" + formId + " input" ).each( function( n )
	{
		try
		{
			$( this ).attr( "maxlength", rules[this.id].rangelength[1] );
		}
		catch( e )
		{}
	});

	var nameField = jQuery('#' + formId + ' :input')[0];

	if ( nameField )
	{
		nameField.focus();
	}

	return validator;
}

/**
 * @param form Get validation rules for this form
 *
 * @return Validation rules for a given form
 */
function getValidationRules( form )
{
	if ( form !== undefined ) {
		return validationRules[form];
	}

	return validationRules;
}

function validation( formId, submitHandler, beforeValidateHandler )
{
	var nameField = jQuery('#' + formId + ' :input')[0];

	var validator = jQuery("#" + formId ).validate({
		 meta:"validate"
		,errorElement:"span"
		,beforeValidateHandler:beforeValidateHandler
		,submitHandler: submitHandler
	});

	if ( nameField )
	{
		nameField.focus();
	}

	return validator;
}

/**
 * Add validation rule remote for input field
 *
 * @param inputId is id for input field
 * @param url is ajax request url
 * @param params is array of param will send to server by ajax request
 */
function checkValueIsExist( inputId, url, params )
{
	jQuery("#" + inputId).rules("add",{
		remote: {
			url:url,
			type:'post',
			data:params
		}
	});
}

function checkPassword( inputId, password ) {
    var parameter = $("#" + inputId ).val();
    var passWord = $("#" +  password).val();
    if (passWord) {
        if (parameter) {
            if ((passWord.indexOf(parameter) !== -1) ||  (parameter.indexOf(passWord) !== -1)) {
                alert( i18n_username_email_in_password );
                $("#" +  password).val("");
            }
        }
    }

}

function checkValueIsExistWarning( inputId, url, params )
{
	jQuery("#" + inputId).rules("add",{
		remoteWarning: {
			url:url,
			type:'post',
			data:params
		}
	});
}

function remoteValidateById( inputId, url, params )
{
	jQuery("#" + inputId).rules("add",{
		remote: {
			url:url,
			type:'post',
			data:params
		}
	});
}

function remoteValidate( input , url, params )
{
	jQuery( input ).rules("add",{
		remote: {
			url:url,
			type:'post',
			data:params
		}
	});
}

/**
 * Add any validator Rules for input
 *
 * @param inputId is id for input field
 * @param rules is array of rule
 * @note: input field must have name same with id
 */
function addValidatorRulesById( inputId, rules )
{
	addValidatorRules( jQuery("#" + inputId), rules );
}

function addValidatorRules( input, rules )
{
	jQuery(input).rules( "add", rules );
}

/**
 * Remove validator Rules for input
 *
 * @param inputId is id for input field
 * @param rules is array of rule you want to remove
 * @note: input field must have name same with id
 */
function removeValidatorRulesById( inputId, rules )
{
	removeValidatorRules( jQuery("#" + inputId), rules );
}

function removeValidatorRules( input, rules )
{
	jQuery(input).rules( "remove", rules );
}

function listValidator( validatorId, selectedListId )
{
	memberValidator = jQuery( "#" + validatorId );
	memberValidator.attr( 'multiple', 'multiple');
	memberValidator.attr( 'name', validatorId );
	memberValidator.children().remove();

	jQuery.each( jQuery( "#" + selectedListId ).children(), function(i, item){
		item.selected = 'selected';
		memberValidator.append( '<option value="' + item.value + '" selected="selected">' + item.value + '</option>');
	});
}

// -----------------------------------------------------------------------------
// Message
// -----------------------------------------------------------------------------

/**
 * Show message at the top-right of screen, this message will hide automatic
 * after 3 second if you don't set time
 *
 * @param message is message
 * @param time is time the message will hide after showed. Default is 3 second,
 *            set time is 0 if you don't want to hide this message
 */
function showErrorMessage( message, time )
{
	jQuery.growlUI( i18n_error, message, 'error', time );
}

/**
 * Show message at the top-right of screen, this message will hide automatic
 * after 3 second if you don't set time
 *
 * @param message is message
 * @param time is time the message will hide after showed. Default is 3 second,
 *            set time is 0 if you don't want to hide this message
 */
function showSuccessMessage( message, time )
{
	jQuery.growlUI( i18n_success, message, 'success', time );
}

/**
 * Show message at the top-right of screen, this message will hide automatic
 * after 3 second if you don't set time
 *
 * @param message is message
 * @param time is time the message will hide after showed. Default is 3 second,
 *            set time is 0 if you don't want to hide this message
 */
function showWarningMessage( message, time )
{
	jQuery.growlUI( i18n_warning, message, 'warning', time );
}

function markInvalid( elementId, message )
{
	var element = jQuery("#" + elementId );
	html = '' + message + '';
	element.next().remove();
	jQuery( html ).insertAfter( element );
}

function markValid( elementId )
{
	var element = jQuery("#" + elementId );
	html = '';
	element.next().remove();
	jQuery( html ).insertAfter( element );
}

function isValid( elementId )
{
	var next = jQuery("#" + elementId ).next( 'span[class~=valid]' );

	return  next.length > 0 ;
}

// -----------------------------------------------------------------------------
// GUI operations
// -----------------------------------------------------------------------------

/**
 * Clock screen by mask *
 */
function lockScreen()
{
	jQuery.blockUI({ message: i18n_waiting , css: {
		border: 'none',
		padding: '15px',
		backgroundColor: '#000',
		'-webkit-border-radius': '10px',
		'-moz-border-radius': '10px',
		opacity: .5,
		color: '#fff'
	} });
}
/**
 * unClock screen *
 */
function unLockScreen()
{
	jQuery.unblockUI();
}

function showPopupWindow( html, width, height)
{
	var width_ = document.documentElement.clientWidth;
	var height_ = document.documentElement.clientHeight;

	var top = ((height_ / 2) - (height/2)) + 'px';
	var left =  ((width_ / 2) - (width/2)) + 'px';

	jQuery.blockUI({ message:  html, css: {cursor:'default', width: width + 'px', height: height + 'px', top: top , left: left} });
}

function showPopupWindowById( id, width, height )
{
	var width_ = document.documentElement.clientWidth;
	var height_ = document.documentElement.clientHeight;

	var top = ((height_ / 2) - (height/2)) + 'px';
	var left =  ((width_ / 2) - (width/2)) + 'px';

	container = jQuery("#" + id);
	container.css('width', width + 'px');
	container.css('height', height + 'px');
	container.css('top', top );
	container.css('left', left );
	container.css('z-index', 1000000 );
	container.css('position', 'fixed' );
	container.css('background-color', '#FFFFFF' );
	container.css('overflow', 'auto' );
	container.css('border', 'medium solid silver');
	container.show(  jQuery.blockUI({message:null}));

}

function hidePopupWindow( id )
{
	hideById( id );
	unLockScreen();
}

/**
 * Removes the opacity div from the document. function deleteDivEffect()
 */
function deleteDivEffect()
{
	var divEffect = document.getElementById( 'divEffect' );

	if( divEffect!=null )
	{
		document.body.removeChild(divEffect);
	}
}

/**
 * Used to export PDF file by the given type and the filter params in page
 */
function exportPdfByType( type, params )
{
	if ( jQuery( "table.listTable tbody tr" ).length == 0 )
	{
		showWarningMessage( i18n_no_item_to_export );
		return;
	}

	var form = byId( 'filterKeyForm' );
	form.action = 'exportToPdf.action?' + params;
	form.submit();
	form.action = type + '.action';
}

/**
 * Displays the div with the first argument id, and hides the divs with ids in
 * the second array argument, except the id given in the first argument.
 */
function displayDiv( divId, divIds ) {
	$( "#" + divId ).show();
	for ( i in divIds ) {
		if ( divIds[i] != divId ) {
			$( "#" + divIds[i] ).hide();
		}
	}
}

function relativePeriodsChecked()
{
    if ( isChecked( "reportingMonth" ) ||
         isChecked( "reportingBimonth" ) ||
         isChecked( "reportingQuarter" ) ||
         isChecked( "lastMonth" ) ||
         isChecked( "lastBimonth" ) ||
         isChecked( "lastQuarter" ) ||
         isChecked( "lastSixMonth" ) ||
         isChecked( "monthsThisYear" ) ||
         isChecked( "quartersThisYear" ) ||
         isChecked( "thisYear" ) ||
         isChecked( "monthsLastYear" ) ||
         isChecked( "quartersLastYear" ) ||
         isChecked( "lastYear" ) ||
         isChecked( "last5Years" ) ||
         isChecked( "last12Months" ) ||
         isChecked( "last3Months" ) ||
         isChecked( "last6BiMonths" ) ||
         isChecked( "last4Quarters" ) ||
         isChecked( "last2SixMonths" ) ||
         isChecked( "thisFinancialYear" ) ||
         isChecked( "lastFinancialYear" ) ||
         isChecked( "last5FinancialYears" ) ||
         isChecked( "lastWeek" ) ||
         isChecked( "last4Weeks" ) ||
         isChecked( "last12Weeks" ) )
    {
        return true;
    }

    return false;
}

function startsWith( string, substring )
{
	return ( string && string.lastIndexOf( substring, 0 ) === 0 ) ? true : false;
}

function getRandomNumber()
{
	return Math.floor( 100000000 * Math.random() );
}

function getRandomCode()
{
	var chars = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXTZabcdefghiklmnopqrstuvwxyz";
	var len = 11;
	var string = "";

	for ( var i=0; i < len; i++ )
	{
		var rnum = Math.floor( Math.random() * chars.length );
		string += chars.substring( rnum, rnum+1 );
	}

	return string;
}

function getDC()
{
	return "_dc=" + getRandomNumber();
}

/**
 * Rounds the given number to the given number of decimals.
 */
function roundTo( number, decimals )
{
	if ( number == null || isNaN( number ) || decimals == null || isNaN( decimals ) )
	{
		return number;
	}

	var factor = Math.pow( 10, decimals );

	return ( Math.round( number * factor ) / factor );
}

function isDefined( variable )
{
	return ( typeof( variable ) !== "undefined" );
}

// -----------------------------------------------------------------------------
// Paging
// -----------------------------------------------------------------------------

isAjax = false;
var contentDiv = 'contentDiv';
function pagingList( currentPage, pageSize )
{
	var baseLink = jQuery( "#baseLink" ).val();
	var url = baseLink + "currentPage=" + currentPage + "&pageSize=" + pageSize;

	var index = url.indexOf( '?' );
	var link = url.substring( 0, index );
	var data = url.substring( index + 1 );

	if ( !isAjax )
	{
		window.location.href = encodeURI( url );
	}
	else
	{
		jQuery.postUTF8( link, data, function( html ) {
			setInnerHTML( contentDiv, html );
		} );
	}
}

function changePageSize( event )
{
	var key = event.keyCode || event.charCode || event.which;

	if ( key == 13 || key == 1 ) // Enter
	{
		// ---------------------------------------------------
		// Validate parameters
		// ---------------------------------------------------

		var pageSize = jQuery( "#sizeOfPage" ).val();

		if ( pageSize < 1 )
		{
			pageSize = 1;
		}

		var currentPage = jQuery( "#jumpToPage" ).val();
		var numberOfPages = jQuery( "#numberOfPages" ).val();

		if ( currentPage > numberOfPages )
		{
			currentPage = numberOfPages;
		}

		jQuery.cookie( "pageSize", pageSize, {path: "/"} );

		// ---------------------------------------------------
		// Paging
		// ---------------------------------------------------

		pagingList( currentPage, pageSize );
	}
}

// -----------------------------------------------------------------------------
// Notifications
// -----------------------------------------------------------------------------

function pingNotifications( category, tableId, completedCallback )
{
	var lastUid = $( '#' + tableId ).prop( 'lastUid' ); // Store on table property

	var param = ( undefined !== lastUid ) ? '?lastId=' + lastUid : '';

	$.getJSON( '../api/system/tasks/' + category + param, function( notifications )
	{
		var html = '',
		    isComplete = false;

		if ( isDefined( notifications ) && notifications.length ) {
			$.each( notifications, function( i, notification )
			{
				var first = i == 0,
					loaderHtml = '';

                if ( first ) {
					$( '#' + tableId ).prop( 'lastUid', notification.uid );
					loaderHtml = _loading_bar_html;
					$( '#loaderSpan' ).replaceWith ( '' ); // Hide previous loader bar
				}

				var time = '';

				if ( undefined !== notification.time ) {
					time = notification.time.replace( 'T', ' ' ).substring( 0, 19 );
				}

				html += '
' + time + '	' + notification.message + '  ';

				if ( notification.level == "ERROR" ) {
					html += '';
					isComplete = true;
				}
				else if ( notification.completed ) {
					html += '';
					isComplete = true;
				}
				else {
					html += loaderHtml;
				}

				html += '
';
			} );

			$( '#' + tableId ).show().prepend( html );

			if ( isComplete && completedCallback && completedCallback.call ) {
				completedCallback();
			}
		}
	} );
}

//-----------------------------------------------------------------------------
// Symbol
//-----------------------------------------------------------------------------

function openSymbolDialog()
{
	$( "#symbolDiv" ).dialog( {
		height: 294,
		width: 250,
		modal: true,
		resizable: false,
		title: "Select symbol"
	} );
}

function selectSymbol( img )
{
	$( "#symbol" ).val( img );
	$( "#symbolDiv" ).dialog( "close" );
	$( "#symbolImg" ).attr( "src", "../images/orgunitgroup/" + img ).show();
}

var months =
{
  january: {
      index: 1,
      noOfDays: 28
  },
  february: {
      index: 2,
      noOfDays: 28
  },
  march: {
      index: 3,
      noOfDays: 28
  },
  april: {
      index: 4,
      noOfDays: 28
  },
  may: {
      index: 5,
      noOfDays: 28
  },
  june: {
      index: 6,
      noOfDays: 28
  },
  july: {
      index: 7,
      noOfDays: 28
  },
  august: {
      index: 8,
      noOfDays: 28
  },
  september: {
      index: 9,
      noOfDays: 28
  },
  october: {
      index: 10,
      noOfDays: 28
  },
  november: {
      index: 11,
      noOfDays: 28
  },
  december: {
      index: 12,
      noOfDays: 28
  }
};

var generate =
{
    month: function (id, parentClass)
    {
        var options = Object.keys(months).map(function (month)
        {
            return "<option value='" + months[month].index + "'>" + i18n_months[month] + "</option>";
        }).join("");
        $(parentClass+" #" + id).html(options);
    },
    days: function (id, monthIndex, parentClass)
    {
        var month = Object.keys(months)[--monthIndex];
        var noOfDays = months[month].noOfDays;
        var options = "";
        for (var count = 1; count <= noOfDays; count++)
        {
            options += "<option value='" + count + "'>" + count + "</option>"
        }
        $(parentClass+" #" + id).html(options);
    },
    time: function (id, parentClass)
    {
        var hours = 24;
        var times = [];
        for (var hour = 0; hour < hours; hour++)
        {
            times.push(getHour(hour) + ":00");
            times.push(getHour(hour) + ":30");
        }

        var timeOptions = times.map(function (time)
        {
            return "<option value='" + time + "'>" + time + "</option>"
        }).join("");
        $(parentClass+" #" + id).html(timeOptions);
    }
};

var getHour = function (hour)
{
    return hour < 10 ? "0" + hour : hour;
};

var getMinutes = function (minutes)
{
    return minutes == 0 ? "00" : minutes;
};


text:
require 'active_support'

begin
  require 'rails'
rescue LoadError
  # nothing to do! yay!
end

if defined? Rails
  require 'activerecord/postgresql/expression/railtie'
else
  ActiveSupport.on_load :active_record do
    require 'activerecord/postgresql/expression/base'
  end
end


text:
"use strict";

var assert = require('./util').assert;
var Component = require('./Component');
var RegistrationBuilder = require('./RegistrationBuilder');
var ResolutionError = require('./ResolutionError');
var Resolver = require('./Resolver');

var nullContainer = {
  resolve: function(key, options) {
    if (options && options.optional) {
      return Promise.resolve(null);
    }
    throw new ResolutionError("Not found: " + key);
  },
  keys: function() {
    return [];
  }
};

/**
 * Private constructor. Instances are normally created with these methods:
 *

 *
{@link junkie.newContainer}

 *
{@link Container#newChild}

 *

 *
 * @param {Container|undefined} parent  The optional parent container.
 * @param {Array.<Resolver>|undefined} resolvers  The optional list of resolvers.
 *
 * @constructor
 */
function Container(parent, resolvers) {
  this._parent = parent || nullContainer;
  this._registry = {};
  this._containerResolvers = resolvers ? resolvers.slice() : [];
}

/** @lends Container# */
var C = Container.prototype;

/**
 * Obtain the parent container, or null if this container is an orphan.
 * @returns {Container|null} The parent container or null
 */
C.parent = function() {
  return this._parent === nullContainer
    ? null
    : this._parent;
};

/**
 * Create a new child Container.
 *
 * @param {object} options Optional configuration options
 * @param {boolean} [options.inherit=true] When true, the new child container inherits this container's
 *        resolvers.
 */
C.newChild = function(options) {
  this._checkDisposed();

  options = options || {};

  var resolvers = this._containerResolvers;
  if (options.inherit === false) {
    resolvers = null;
  }

  return new Container(this, resolvers);
};

/**
 * Use the given resolver middleware.
 * @param {String|Function} resolver The resolver to use. Supplying a String attempts to locate a standard resolver
 *        by name. Supplying a Function uses the Function itself as the resolver implementation.
 * @returns {Container} this.
 * @see Resolver
 */
C.use = function(resolver) {
  this._checkDisposed();

  resolver = Resolver.normalize(resolver);
  this._containerResolvers.push(resolver);
  return this;
};

/**
 * Dispose of this container, releasing all references to components. Using any modifying method after this
 * call will throw an Error. Resolve requests will be delegated to the parent container, if available.
 */
C.dispose = function() {
  delete this._registry; // Drop references to all components
};

C._checkDisposed = function() {
  if (!this._registry) {
    throw new Error("Container disposed");
  }
};

/**
 * Register the given component with this Container, making it directly resolvable using the
 * {@link Container#resolve} method, as well as making it available for resolution and as a
 * potential dependency of another component.
 *
 * @param {String} key The key associated with the component.
 * @param {*} component The component instance that will be tracked by this container.
 * @returns {RegistrationBuilder} A registration builder to configure the registration.
 *
 * @throws Error if key is not a string
 * @throws Error if component is not defined or null.
 */
C.register = function(key, component) {
  this._checkDisposed();

  assert.type(key, 'string', "key must be a string");
  assert(component !== undefined, "component must be defined");

  var comp = this._createComponent(key, component);
  this._registry[key] = comp;

  return new RegistrationBuilder(comp);
};

C._createComponent = function(key, component) {
  return new Component(key, component, this, this._containerResolvers);
};

C._get = function(key) {
  assert.type(key, 'string', "key must be a string");
  return this._registry
    ? this._registry[key]
    : null; // If the container was disposed, behave like a 'not found' so we continue searching the parent
};

/**
 * Resolve an instance for the given component key. To resolve an instance, every associated resolver is passed
 * control and given the opportunity to create and configure the resulting component instance.
 *

 * When resolving dependencies of the requested component, this same method is invoked internally for each
 * dependency.
 *
 * @param {string} key The component key with which to obtain an instance.
 * @param {Object} [options] Configuration options.
 * @param {boolean} [options.optional=false] When true, in the event that the component cannot be resolved
 *        return null instead of throwing a ResolutionError.
 * @returns {Promise} A promise capturing the result of the resolution. The promise will be rejected with:
 *          - Error if key is not a string.
 *          - ResolutionError if the mandatory key cannot be located.
 *          - ResolutionError if a failure occurs during the resolution process.
 */
C.resolve = function(key, options) {
  try {
    options = options || {};

    // Lookup the component
    var comp = this._get(key);

    // If the component is not found, delegate to the parent container
    if (!comp) {
      return this._parent.resolve(key, options);
    }

    // Resolve the component instance
    return comp.resolve(options);

  } catch (e) {
    return Promise.reject(e);
  }
};

/**
 * Obtain an array of key names known to this container and, optionally, parent containers.
 *
 * @param {boolean} [includeParent=false] Include keys registered with the parent container, if any.
 * @returns {Array} A set of key names.
 */
C.keys = function(includeParent) {
  var keys = {};
  var addKey = function(key) {
    keys[key] = true;
  };
  if (includeParent) {
    this._parent.keys().forEach(addKey);
  }
  Object.keys(this._registry).forEach(addKey);

  return Object.keys(keys);
};

module.exports = Container;


text:
package com.microsoft.bingads.api.test.entities.adgroup.write;

import com.microsoft.bingads.api.test.entities.adgroup.BulkAdGroupTest;
import com.microsoft.bingads.bulk.entities.BulkAdGroup;
import com.microsoft.bingads.campaignmanagement.AdRotation;
import com.microsoft.bingads.campaignmanagement.AdRotationType;
import com.microsoft.bingads.internal.functionalinterfaces.BiConsumer;
import java.util.Arrays;
import java.util.Collection;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.Parameterized;
import org.junit.runners.Parameterized.Parameter;
import org.junit.runners.Parameterized.Parameters;

@RunWith(Parameterized.class)
public class BulkAdGroupWriteToRowValuesAdRotationTests extends BulkAdGroupTest {

    @Parameter(value = 1)
    public AdRotationType propertyValue;

    @Parameters
    public static Collection<Object[]> data() {
        // In this example, the parameter generator returns a List of
        // arrays.  Each array has two elements: { datum, expected }.
        // These data are hard-coded into the class, but they could be
        // generated or loaded in any way you like.
        return Arrays.asList(new Object[][]{
            {"OptimizeForClicks", AdRotationType.OPTIMIZE_FOR_CLICKS},
            {"RotateAdsEvenly", AdRotationType.ROTATE_ADS_EVENLY},
            {null, null}
        });
    }

    @Test
    public void testWrite() {
        AdRotation rotation = new AdRotation();
        rotation.setType(this.propertyValue);
        this.<AdRotation>testWriteProperty("Ad Rotation", this.datum, rotation, new BiConsumer<BulkAdGroup, AdRotation>() {
            @Override
            public void accept(BulkAdGroup c, AdRotation v) {
                c.getAdGroup().setAdRotation(v);
            }
        });
    }
}


text:
/*
To change this license header, choose License Headers in Project Properties.
To change this template file, choose Tools | Templates
and open the template in the editor.
*/
/*  Created on : 2014-04-29, 18:47:14 Author     : boolka
*/


text:
//=====================================================================
//
//File:      $RCSfile: DescriptionEditorInteraction.java,v $
//Version:   $Revision: 1.21 $
//Modified:  $Date: 2013/05/10 06:03:21 $
//
//(c) Copyright 2004-2014 by Mentor Graphics Corp. All rights reserved.
//
//=====================================================================
// Licensed under the Apache License, Version 2.0 (the "License"); you may not
// use this file except in compliance with the License.  You may obtain a copy
// of the License at
//
//       http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
// WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.   See the
// License for the specific language governing permissions and limitations under
// the License.
//=====================================================================

package com.mentor.nucleus.bp.ui.text.test.description;

import java.util.HashMap;
import java.util.Map;

import org.eclipse.core.resources.IFile;
import org.eclipse.core.resources.IMarker;
import org.eclipse.core.resources.IWorkspaceRunnable;
import org.eclipse.core.resources.ResourcesPlugin;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.core.runtime.IProgressMonitor;
import org.eclipse.core.runtime.NullProgressMonitor;
import org.eclipse.jface.action.Action;
import org.eclipse.jface.text.BadLocationException;
import org.eclipse.jface.text.IDocument;
import org.eclipse.jface.text.IRegion;
import org.eclipse.jface.text.ITextOperationTarget;
import org.eclipse.jface.text.source.ISourceViewer;
import org.eclipse.jface.viewers.IStructuredSelection;
import org.eclipse.jface.viewers.StructuredSelection;
import org.eclipse.ui.ide.IGotoMarker;
import org.eclipse.ui.texteditor.MarkerUtilities;

import com.mentor.nucleus.bp.core.CorePlugin;
import com.mentor.nucleus.bp.core.Package_c;
import com.mentor.nucleus.bp.core.Ooaofooa;
import com.mentor.nucleus.bp.core.Package_c;
import com.mentor.nucleus.bp.core.common.ClassQueryInterface_c;
import com.mentor.nucleus.bp.core.common.PersistableModelComponent;
import com.mentor.nucleus.bp.test.TestUtil;
import com.mentor.nucleus.bp.test.common.TestingUtilities;
import com.mentor.nucleus.bp.test.common.TextEditorUtils;
import com.mentor.nucleus.bp.ui.text.EditorHover;
import com.mentor.nucleus.bp.ui.text.description.DescriptionEditor;
import com.mentor.nucleus.bp.ui.text.description.DescriptionEditorInput;
import com.mentor.nucleus.bp.ui.text.description.ShowDescriptionAction;
import com.mentor.nucleus.bp.ui.text.test.TextTestPlugin;
import com.mentor.nucleus.bp.ui.text.test.UITextTest;

public class DescriptionEditorInteraction extends UITextTest {

	private static boolean firstSetup = true;
	private static String testModelName = "testDescrip1";

	public DescriptionEditorInteraction(String projectName, String name) throws CoreException {
		super(null, name);
	}

	public DescriptionEditorInteraction(String name) throws CoreException {
		super(null, name);
	}

	private static String m_oldDescrip;
	private final static String m_updateText = "New Line \n";
	private static long m_markerId[] = new long [4];
	private static int numMarkers = 0;

	protected void setUp() throws Exception {
    	super.setUp();

        if ( firstSetup ) {
        	loadProject(testModelName);

        	// make sure the user isn't prompted to do a parse all
        	CorePlugin.disableParseAllOnResourceChange();

        	firstSetup = false;
        }

    }

	static public void openDescriptionEditor( final Object uut )
	{

		try
		{
		  IWorkspaceRunnable r = new IWorkspaceRunnable()
		  {
			public void run(IProgressMonitor monitor) throws CoreException
			{
				IStructuredSelection ss = new StructuredSelection(uut);
				ShowDescriptionAction sda = new ShowDescriptionAction();
				Action a = new Action(){};
				sda.selectionChanged(a, ss);
				sda.run( a );
			}
		  };
		  TextTestPlugin.getWorkspace().run(r, null);
		}
		catch (CoreException x)
		{
		  fail("open editor problem");
		}

	}

	private DescriptionEditor openPackageDescriptionEditor()
	{
		final Package_c uut = getTopPackage();
		assertNotNull(uut);

		openDescriptionEditor(uut);
		return getPackageDescriptionEditor();
	}

	private DescriptionEditor getPackageDescriptionEditor()
	{
		return TextEditorUtils.getDescriptionEditor("testDescrip1: Package Description");
	}

	private Package_c getTopPackage()
	{
		// In the test model we're using, there is a top level package with the same name
		// as the project itself.
        ClassQueryInterface_c pkgQuery = new ClassQueryInterface_c(){
            public boolean evaluate(Object candidate){
                return (((Package_c)candidate).getName().equals(testModelName));

            }
        };

		Package_c uut = Package_c.PackageInstance(modelRoot, pkgQuery);
		assertNotNull(uut);

		return uut;
	}

	public static void createMarker(final IFile file, int line, String message, String type) {
		IMarker marker = null;
		Map attributes = new HashMap(11);
		MarkerUtilities.setMessage(attributes, message);
		MarkerUtilities.setLineNumber(attributes, line);
		attributes.put(IMarker.TRANSIENT, new Boolean(true));
		final Map attrs = attributes;
		final String markerType = type;
		try {
			file.getWorkspace().run(new IWorkspaceRunnable() {
				public void run(IProgressMonitor monitor) throws CoreException {
					IMarker marker = file.createMarker(markerType);
					marker.setAttributes(attrs);
					DescriptionEditorInteraction.m_markerId[DescriptionEditorInteraction.numMarkers] = marker.getId();
					++ DescriptionEditorInteraction.numMarkers;
				}
			}, null);
		} catch (CoreException x) {
			fail("Core Exception in DescriptionEditorInteraction.createMarker " + x.toString());
		}
	}

	public void testDirtyFlag()
	{
		DescriptionEditor de = openPackageDescriptionEditor();

		// change data in editor
	    IDocument doc = de.getDocumentProvider().getDocument(de.getEditorInput());
	    try {
			doc.replace(0, 0, "test text ");
	    } catch ( BadLocationException e ) { fail("Bad Location Exception"); }

		assertTrue( de.isSaveOnCloseNeeded() );
		assertTrue( de.isDirty() );
	}

	public void testUndo()
	{
		DescriptionEditor de = getPackageDescriptionEditor();

		// undo
		de.getTextViewer().doOperation(ITextOperationTarget.UNDO);

		assertTrue( de.isSaveOnCloseNeeded() );
		assertTrue( de.isDirty() );

		Package_c uut = getTopPackage();
		assertEquals( uut.getDescrip(), de.getDocumentProvider().getDocument(de.getEditorInput()).get());

	}

	public void testRevert()
	{
		DescriptionEditor de = getPackageDescriptionEditor();

		// revert editor
		de.doRevertToSaved();

		assertFalse( de.isSaveOnCloseNeeded() );
		assertFalse( de.isDirty() );
		Package_c uut = getTopPackage();
		assertEquals( uut.getDescrip(), de.getDocumentProvider().getDocument(de.getEditorInput()).get());
	}

	public void testSave()
	{
		DescriptionEditor de = getPackageDescriptionEditor();
		Package_c uut = getTopPackage();
		m_oldDescrip = uut.getDescrip();

		// change data in editor
		IDocument doc = de.getDocumentProvider().getDocument(de.getEditorInput());
		try {
			doc.replace(0, 0, m_updateText);
		} catch ( BadLocationException e ) { fail("Bad Location Exception"); }

	    de.doSave(new NullProgressMonitor());

		assertFalse( de.isSaveOnCloseNeeded() );
		assertFalse( de.isDirty() );
		assertEquals( m_updateText + m_oldDescrip, de.getDocumentProvider().getDocument(de.getEditorInput()).get());
		de.getSite().getPage().closeEditor(de, false);
	}

	public void testOpenChangedDescription()
	{
		DescriptionEditor de = openPackageDescriptionEditor();
		assertFalse( de.isSaveOnCloseNeeded() );
		assertFalse( de.isDirty() );
		assertEquals( m_updateText + m_oldDescrip, de.getDocumentProvider().getDocument(de.getEditorInput()).get());
	}

	private final int marker_line = 3;

	public void testAddBookmark()
	{
		DescriptionEditor de = getPackageDescriptionEditor();
		DescriptionEditorInput editorInput = (DescriptionEditorInput)de.getEditorInput();
		final IFile file = editorInput.getFile();
		createMarker(file, marker_line, "test bookmark", IMarker.BOOKMARK);
		assertFalse( de.isSaveOnCloseNeeded() );
		assertFalse( de.isDirty() );
		assertEquals( m_updateText + m_oldDescrip, de.getDocumentProvider().getDocument(editorInput).get());

		de.getSite().getPage().closeEditor(de, false);

		IMarker m2 = file.getMarker(m_markerId[0]);
		assertTrue(m2.exists());
		try {
			assertEquals(marker_line, ((Integer)m2.getAttribute("lineNumber")).intValue());
			assertEquals( "test bookmark", (String)m2.getAttribute("message"));
			assertEquals(IMarker.BOOKMARK, m2.getType());
		}
		  catch (CoreException e) {	fail("Core Exception in DescriptionEditorInteraction.testAddBookmark " + e.toString()); }
		assertTrue(m2.getResource().isAccessible());
	}

	public void testBookmarkHoverText()
	{
		DescriptionEditor de = openPackageDescriptionEditor();

		DescriptionEditorInput editorInput = (DescriptionEditorInput)de.getEditorInput();
		final IFile file = editorInput.getFile();
		IMarker m2 = file.getMarker(m_markerId[0]);

        ((IGotoMarker)de.getAdapter(IGotoMarker.class)).gotoMarker(m2);
		IRegion expected = null;
		try {
			IDocument doc = de.getDocumentProvider().getDocument(de.getEditorInput());
			expected = doc.getLineInformation(marker_line);
		}
		catch ( BadLocationException e ) {	fail("Bad Location Exception in DescriptionEditorInteraction.testGotoBookmark " + e.toString()); }
		assertNotNull( expected );

		EditorHover eh = new EditorHover();
		eh.setEditor(de);
		String hoverText = eh.getHoverInfo((ISourceViewer)de.getTextViewer(), marker_line-1);
		assertEquals( "test bookmark", hoverText);
	}
	public void testAddTaskMarker()
	{
		DescriptionEditor de = getPackageDescriptionEditor();
		DescriptionEditorInput editorInput = (DescriptionEditorInput)de.getEditorInput();
		final IFile file = editorInput.getFile();
		createMarker(file, marker_line, "test task", IMarker.TASK);
		assertFalse( de.isSaveOnCloseNeeded() );
		assertFalse( de.isDirty() );
		assertEquals( m_updateText + m_oldDescrip, de.getDocumentProvider().getDocument(editorInput).get());

		de.getSite().getPage().closeEditor(de, false);

		IMarker m2 = file.getMarker(m_markerId[1]);
		assertTrue(m2.exists());
		try {
			assertEquals(IMarker.TASK, m2.getType());
			assertEquals(marker_line, ((Integer)m2.getAttribute("lineNumber")).intValue());
			assertEquals( "test task", (String)m2.getAttribute("message"));
		}
	  catch (CoreException e) {	fail("Core Exception in DescriptionEditorInteraction.testAddBookmark " + e.toString()); }
		assertTrue(m2.getResource().isAccessible());
	}
	public void testMultipleMarkerHoverText()
	{
		DescriptionEditor de = openPackageDescriptionEditor();

		EditorHover eh = new EditorHover();
		eh.setEditor(de);
		String hoverText = eh.getHoverInfo((ISourceViewer)de.getTextViewer(), marker_line-1);
        if (hoverText.equals("Multiple markers at this line\n  - test bookmark\n  - test task")){
            return;
        }else if (hoverText.equals("Multiple markers at this line\n  - test task\n  - test bookmark")){
            return;
        }
		assertFalse(true);
	}
	public void testDeleteBookmark()
	{
		DescriptionEditor de = getPackageDescriptionEditor();
		DescriptionEditorInput editorInput = (DescriptionEditorInput)de.getEditorInput();
		final IFile file = editorInput.getFile();
		IMarker m2 = file.getMarker(m_markerId[0]);

		try {
			m2.delete();
		}
		catch (CoreException e) {	fail("Core Exception in DescriptionEditorInteraction.testDeleteBookmark " + e.toString()); }

		m2 = file.getMarker(m_markerId[0]);
		assertFalse(m2.exists());
	}
	public void testTaskHoverText()
	{
		DescriptionEditor de = getPackageDescriptionEditor();

		EditorHover eh = new EditorHover();
		eh.setEditor(de);
		String hoverText = eh.getHoverInfo((ISourceViewer)de.getTextViewer(), marker_line-1);
		assertEquals( "test task", hoverText);
	}
	public void testDeleteTask()
	{
		DescriptionEditor de = getPackageDescriptionEditor();
		DescriptionEditorInput editorInput = (DescriptionEditorInput)de.getEditorInput();
		final IFile file = editorInput.getFile();
		IMarker m2 = file.getMarker(m_markerId[1]);

		try {
			m2.delete();
		}
		catch (CoreException e) {	fail("Core Exception in DescriptionEditorInteraction.testDeleteBookmark " + e.toString()); }

		m2 = file.getMarker(m_markerId[1]);
		assertFalse(m2.exists());
	}

}


text:
package org.wso2.carbon.device.mgt.core.config;

import org.wso2.carbon.device.mgt.core.config.analytics.AnalyticsConfigurations;
import org.wso2.carbon.device.mgt.core.config.datasource.DataSourceConfig;
import org.wso2.carbon.device.mgt.core.config.email.EmailConfigurations;
import org.wso2.carbon.device.mgt.core.config.identity.IdentityConfigurations;
import org.wso2.carbon.device.mgt.core.config.policy.PolicyConfiguration;

import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;

/**
 * Class for holding management repository data.
 */
@XmlRootElement(name = "ManagementRepository")
public class DeviceManagementConfigRepository {

	private DataSourceConfig dataSourceConfig;
	private EmailConfigurations emailConfigurations;
	private IdentityConfigurations identityConfigurations;
	private PolicyConfiguration policyConfiguration;
	private AnalyticsConfigurations analyticsConfigurations;

	@XmlElement(name = "DataSourceConfiguration", required = true)
	public DataSourceConfig getDataSourceConfig() {
		return dataSourceConfig;
	}

	public void setDataSourceConfig(DataSourceConfig dataSourceConfig) {
		this.dataSourceConfig = dataSourceConfig;
	}

	@XmlElement(name = "EmailClientConfiguration", required = true)
	public EmailConfigurations getEmailConfigurations() {
		return emailConfigurations;
	}

	public void setEmailConfigurations(EmailConfigurations emailConfigurations) {
		this.emailConfigurations = emailConfigurations;
	}

	@XmlElement(name = "IdentityConfiguration", required = true)
	public IdentityConfigurations getIdentityConfigurations() {
		return identityConfigurations;
	}

	public void setIdentityConfigurations(IdentityConfigurations identityConfigurations) {
		this.identityConfigurations = identityConfigurations;
	}

	@XmlElement(name = "PolicyConfiguration", required = true)
	public PolicyConfiguration getPolicyConfiguration() {
		return policyConfiguration;
	}

	public void setPolicyConfiguration(PolicyConfiguration policyConfiguration) {
		this.policyConfiguration = policyConfiguration;
	}

	@XmlElement(name = "AnalyticsConfiguration", required = true)
	public AnalyticsConfigurations getAnalyticsConfigurations() {
		return analyticsConfigurations;
	}

	public void setAnalyticsConfigurations(AnalyticsConfigurations analyticsConfigurations) {
		this.analyticsConfigurations = analyticsConfigurations;
	}
}


text:
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
	<modelVersion>4.0.0</modelVersion>

	<groupId>com.example</groupId>
	<artifactId>servlet-context-listener-error-demo</artifactId>
	<version>0.1-SNAPSHOT</version>
	<packaging>war</packaging>

	<properties>
		<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
		<maven.compiler.source>11</maven.compiler.source>
		<maven.compiler.target>11</maven.compiler.target>
	</properties>

	<dependencies>
		<dependency>
			<groupId>jakarta.servlet</groupId>
			<artifactId>jakarta.servlet-api</artifactId>
			<version>4.0.4</version>
			<scope>provided</scope>
		</dependency>
	</dependencies>

	<build>
		<plugins>
			<plugin>
				<groupId>org.codehaus.cargo</groupId>
				<artifactId>cargo-maven3-plugin</artifactId>
				<version>1.9.6</version>
				<configuration>
					<container>
						<containerId>${cargo.maven.containerId}</containerId>
						<zipUrlInstaller>
							<url>${cargo.maven.containerUrl}</url>
						</zipUrlInstaller>
					</container>
					<deployables>
						<deployable>
							<properties>
								<context>/</context>
							</properties>
						</deployable>
					</deployables>
				</configuration>
			</plugin>
		</plugins>
	</build>

	<profiles>
		<profile>
			<id>tomcat</id>
			<activation>
				<activeByDefault>true</activeByDefault>
			</activation>
			<properties>
				<cargo.maven.containerId>tomcat9x</cargo.maven.containerId>
				<cargo.maven.containerUrl>https://repo.maven.apache.org/maven2/org/apache/tomcat/tomcat/9.0.52/tomcat-9.0.52.zip</cargo.maven.containerUrl>
			</properties>
		</profile>
		<profile>
			<id>jetty</id>
			<properties>
				<cargo.maven.containerId>jetty10x</cargo.maven.containerId>
				<cargo.maven.containerUrl>https://repo1.maven.org/maven2/org/eclipse/jetty/jetty-home/10.0.6/jetty-home-10.0.6.zip</cargo.maven.containerUrl>
			</properties>
		</profile>
		<profile>
			<id>wildfly</id>
			<properties>
				<cargo.maven.containerId>wildfly24x</cargo.maven.containerId>
				<cargo.maven.containerUrl>https://download.jboss.org/wildfly/24.0.1.Final/wildfly-24.0.1.Final.zip</cargo.maven.containerUrl>
			</properties>
		</profile>
		<profile>
			<id>payara</id>
			<properties>
				<cargo.maven.containerId>payara</cargo.maven.containerId>
				<cargo.maven.containerUrl>https://repo.maven.apache.org/maven2/fish/payara/distributions/payara/5.2021.5/payara-5.2021.5.zip</cargo.maven.containerUrl>
			</properties>
		</profile>
		<profile>
			<id>tomee</id>
			<properties>
				<cargo.maven.containerId>tomee8x</cargo.maven.containerId>
				<cargo.maven.containerUrl>https://repo.maven.apache.org/maven2/org/apache/tomee/apache-tomee/8.0.7/apache-tomee-8.0.7-plus.zip</cargo.maven.containerUrl>
			</properties>
		</profile>
	</profiles>
</project>


text:
void secondone();
void pair_stuff();
void pair_p_stuff();
void vcl_stuff();
#ifdef CMAKE_PAREN
void testOdd();
#endif
int main()
{
  printf("Hello from subdirectory\n");
  secondone();
#ifdef CMAKE_PAREN
  testOdd();
#endif
  pair_stuff();
  pair_p_stuff();
  vcl_stuff();
  return 0;
}


text:
<?php

class Google_Service_Webmasters_WmxSite extends Google_Model
{
  public $permissionLevel;
  public $siteUrl;

  public function setPermissionLevel($permissionLevel)
  {
    $this->permissionLevel = $permissionLevel;
  }
  public function getPermissionLevel()
  {
    return $this->permissionLevel;
  }
  public function setSiteUrl($siteUrl)
  {
    $this->siteUrl = $siteUrl;
  }
  public function getSiteUrl()
  {
    return $this->siteUrl;
  }
}


text:
<resources>

    <!-- Machine Translation Only. Latest update release notes.-->
    <string-array name="randremind_release_notes">
        <item name="line0">"Dodano mogućnost jasan podsjetnik dnevnik."</item>
        <item name="line1">"kategorije dodao obavijest."</item>
        <item name="line2">"Dodano lista obavještavanja zvuči sposobnosti."</item>
        <item name="line5">"Dodano link da probaju podsjetnika i ikona paketa na sajtu jamesmorrisstudios."</item>
        <item name="line3">"Dodano mogućnost da pokaže podsjetnik sliku u obavijesti."</item>
        <item name="line4">"Dodano Android namjere na osnovu plugin podrška za korištenje s automatizaciju aplikacije."</item>
        <item name="line4">"Dodano podrška feed RSS za poruke."</item>
        <item name="line4">"Fixed bug gdje auto snooze neće raditi sa lokacija izazvao podsjetnik a."</item>
    </string-array>

    <!--DO NOT TRANSLATE Latest update release notes.-->
    <string-array name="matchblock_release_notes">
        <item name="line0">"Prvo izdanje"</item>
    </string-array>

    <!--DO NOT TRANSLATE Latest update release notes.-->
    <string-array name="oneup_release_notes">
        <item name="line0">"Pojednostavljeno dizajn menija kreće sve na navigaciju ladici."</item>
        <item name="line0">"Promijenjen format oglasa na intersticijski oglase i ukloniti banner oglase."</item>
        <item name="line0">"Promijenio je usluga oglas tako oglasi se uglavnom odnose više igranje."</item>
        <item name="line0">"Poboljšana igra nastup."</item>
        <item name="line0">"Dodano prilagođene podrške temu."</item>
    </string-array>

    <!--DO NOT TRANSLATE Latest update release notes.-->
    <string-array name="bandit_release_notes">
        <item name="line0">"ništa"</item>
    </string-array>

</resources>


text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Uses of Class com.vaadin.fluent.ui.FPasswordField (Fluent API for Vaadin 1.3-SNAPSHOT API)</title>
<meta name="date" content="2017-09-08">
<link rel="stylesheet" type="text/css" href="../../../../../stylesheet.css" title="Style">

JavaScript is disabled on your browser.

Skip navigation links

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

Prev

Next

Frames

No Frames

All Classes

Uses of Class
com.vaadin.fluent.ui.FPasswordField

No usage of com.vaadin.fluent.ui.FPasswordField

Skip navigation links

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

Prev

Next

Frames

No Frames

All Classes

Copyright © 2017 Jean-Christophe Fortier. All rights reserved.


text:
""" A library to export some stats that we can use for monitoring.
"""

def export(values):
  o = []
  for k, v in sorted(values.items()):
    o.append('%s %s' % (escape(k), build_value(v)))
  return '\n'.join(o)

class ExportedMap(object):
  def __init__(self, label, value):
    self.label = label
    self.value = value

  def __str__(self):
    o = ['map:%s' % escape(self.label)]
    for k, v in sorted(self.value.items()):
      o.append('%s:%s' % (escape(k), escape(v)))
    return ' '.join(o)

class ExportedList(object):
  def __init__(self, value):
    self.value = value

  def __str__(self):
    return '/'.join([escape(v) for v in self.value])

class ExportedCallable(object):
  def __init__(self, callable):
    self.callable = callable

  def __str__(self):
    return make_value(self.callable())

def build_value(value):
  """ attempt to do some inference of types """
  # a dict, with label
  if type(value) is type(tuple()) and type(value[1]) is type(dict()):
    return ExportedMap(label=value[0], value=value[1])
  elif type(value) is type(tuple()) or type(value) is type(list()):
    return ExportedList(value)
  elif callable(value):
    return ExportedCallable(value)
  else:
    return escape(value)

def escape(value):
  return str(value).replace('\\', '\\\\').replace(':', '\\:').replace(' ', '-')


text:
<!DOCTYPE html>

<title>Welcome to IgnitePD</title>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no">

<link href="layout/styles/bootstrap.min.css" rel="stylesheet">

<link href="layout/styles/font-awesome.min.css" rel="stylesheet">
<link href="layout/styles/owl.carousel.css" rel="stylesheet">
<link href="layout/styles/owl.theme.css" rel="stylesheet">
<link href="layout/styles/jquery.mmenu.all.css" rel="stylesheet">
<link href="layout/styles/animate.css" rel="stylesheet">
<link href="layout/styles/layout.css" rel="stylesheet" type="text/css" media="all">

Course Calender

Short Courses

Customized Courses

Consulting

Community

About us

Contact us

    			Book a course / Newsletter/  Contact Us/ 006000000

Course Calender

Short Courses

Customized Courses

Consulting

Community

About us

Contact us

<select class="lang">
					<option value="en">ENGLISH</option>
					<option value="lang">LANGUAGE</option>
				</select>

						FIND YOUR NEXT COURSE
						<input type="text" name="search" id="search"/>

						<button>GO</button>

Latest courses

Connect confidently and create profitable relationships.

					LEARN MORE ...

Latest courses

We work in partnership with your organisationto design programmes that support your strategic objectives.

					LEARN MORE ...

Latest courses

Have your team enhance their skills and knowledge while building their ability to work cohesively together

					LEARN MORE ...

Short Courses

Careers

Our Team

Consulting

About Us

Customized Programs

Email: info@ignitepd.com

Phone: 006000000

Privacy Policy

Disclamer

Cancellation

© 2016 IGNITE PROFESSIONAL DEVELOPMENT .All Rights Reserved


text:
module HerokuJson
  class Bootstrapper < Struct.new(:api, :app, :json, :create_app_func)
  include HerokuJson::ApiHelper

  def bootstrap
    self.app = create_app_func.call if app.nil?
    add_addons
    add_config_vars
  end

  private

  def add_addons
    installed_addons = app_addons.map {|a| a.split(':').first }
    json['addons'].each do |addon|
      name, size = addon.split(':')
      next if installed_addons.include?(name)
      Heroku::Helpers.action "Installing addon #{addon}" do
        begin
          api.post_addon(app, addon)
        rescue Heroku::API::Errors::RequestFailed => e
          Heroku::Helpers.status("already installed")
        end
      end
    end
  end

  def add_config_vars
    Heroku::Helpers.action "Deploying environment configs" do
      api.put_config_vars(app, json['env'])
    end
  end
end
end


text:
'use strict';

tvguide.controller('TVGuideController', ['$scope', '$http',
    function ($scope, $http) {

        //        $scope.InitializePage = function () {

        var now = new Date().toISOString();

        $.ajax({
            url: 'http://api.rovicorp.com/TVlistings/v9/listings/gridschedule/70886/info?apikey=j3p5tfznqqppd8ucd99mtcf9&sig=sig&locale=en-CA&startdate=' + now + '&duration=60&&format=json&includechannelimages=true',
            dataType: 'JSONP',
            jsonpCallback: 'callback',
            type: 'GET',
            success: function (data) {
                $scope.dataNow = data.GridScheduleResult;
                $scope.$apply(function () {
                    $scope.dataNow = data.GridScheduleResult;
                });

                console.log(data.GridScheduleResult.Name);
                console.log(data.GridScheduleResult.GridChannels[0]);
                console.log(data.GridScheduleResult.GridChannels[0].ChannelImages[0].ImageUrl);
            },
            error: function (data) {
                console.log(data);
            }
        })
    }]);


text:
(function() {
  var request = require('request');
  var prompt = require('prompt');
  var moduleVersion = require("../package.json").version;
  var moduleName = require("../package.json").name;
  var schema = {
    properties: {
      "git username": {required: true},
      "git password": {hidden: true, required: true},
    }
  };
  prompt.start();
  prompt.get(schema, function (err, result) {
    if(err) {
      console.log(err);
      return;
    }
    var gitUsername = result["git username"];
    var gitPassword = result["git password"];
    var requestOptions = {
      url: "https://api.github.com/repos/" + gitUsername + "/" + moduleName + "/releases",
      headers: {"User-Agent": gitUsername},
      auth: {
        user: gitUsername,
        pass: gitPassword
      },
      json: {
        tag_name: moduleVersion,
        target_commitish: "master",
        name: moduleVersion,
        body: "Version " + moduleVersion
      }
    };
    sendTagRequest(requestOptions);
  });

  function sendTagRequest(requestOptions) {
    request.post(requestOptions, function (error, response, body) {
      if (!error && response.statusCode === 201) {
        console.log("Successfully created tag " + body.name + ".");
      } else {
        logError(error, body);
      }
    });
  }

  function logError(error, body) {
    if(error) {
      console.log("Error sending request: " + error);
      return;
    }
    var errorMessage = body && body.message ? body.message : "";
    var errorCode = body && body.errors && body.errors[0] && body.errors[0].code ? body.errors[0].code : "";
    console.log("Could not create a release tag" +
      (errorMessage ? ": " + errorMessage : "") +
      (errorCode ? ". Error code: " + errorCode : "") +
      ".");
  }
})();


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
Jb. nassau. Ver. Naturk. 157 (1890)

#### Original name
Lophiostoma alpigenum var. alpigenum Fuckel

### Remarks
null