text:
define(['./request'], function(Request) {

    'use strict';

    var apiBaseUrl = 'https://api.mendeley.com';
    var authFlow = false;

    /**
     * API
     *
     * @namespace
     * @name api
     */
    return {
        setAuthFlow: setAuthFlow,
        setApiBaseUrl: setApiBaseUrl,
        documents: documents(),
        folders: folders(),
        files: files(),
        catalog: catalog(),
        trash: trash()
    };

    function setAuthFlow(auth) {
        authFlow = auth;
    }

    function setApiBaseUrl(url) {
        apiBaseUrl = url;
    }

    /**
     * Documents API
     *
     * @namespace
     * @name api.documents
     */
    function documents() {
        var dataHeaders = {
            'Content-Type': 'application/vnd.mendeley-document.1+json'
        };

        var listDocuments = requestFun('GET', '/documents/');
        var listFolder = requestFun('GET', '/folders/{id}/documents', ['id']);
        return {

            /**
             * Create a new document
             *
             * @method
             * @memberof api.documents
             * @param {object} data - The document data
             * @returns {promise}
             */
            create: requestWithDataFun('POST', '/documents', false, dataHeaders, true),

            /**
             * Create a new document from a file
             *
             * @method
             * @memberof api.documents
             * @param {object} file - A file object
             * @returns {promise}
             */
            createFromFile: requestWithFileFun('POST', '/documents'),

            /**
             * Retrieve a document
             *
             * @method
             * @memberof api.documents
             * @param {string} id - A document UUID
             * @returns {promise}
             */
            retrieve: requestFun('GET', '/documents/{id}', ['id']),

            /**
             * Update document
             *
             * @method
             * @memberof api.documents
             * @param {object} data - The new document data
             * @returns {promise}
             */
            update: requestWithDataFun('PATCH', '/documents/{id}', ['id'], dataHeaders, true),

            /**
             * List documents
             *
             * @method
             * @memberof api.documents
             * @param {object} params - Query paramaters
             * @returns {promise}
             */
            list: function(params) {
                if(!params || typeof params.folderId === 'undefined') {
                    return listDocuments.call(this, params);
                } else {
                    var folderId = params.folderId,
                        callParams = {
                            limit: params.limit
                        };
                    delete params.folderId;
                    return listFolder.call(this, folderId, callParams);
                }
            },

            /**
             * Move a document to the trash
             *
             * @method
             * @memberof api.documents
             * @param {object} id - A document UUID
             * @returns {promise}
             */
            trash: requestFun('POST', '/documents/{id}/trash', ['id'], dataHeaders),

            /**
             * The total number of documents - set after the first call to documents.list()
             *
             * @var
             * @memberof api.documents
             * @type {integer}
             */
            count: 0,

            /**
             * Get the next page of documents
             *
             * @method
             * @memberof api.documents
             * @returns {promise}
             */
            nextPage: requestPageFun('next'),

            /**
             * Get the previous page of documents
             *
             * @method
             * @memberof api.documents
             * @returns {promise}
             */
            previousPage: requestPageFun('previous'),

            /**
             * Get the last page of documents
             *
             * @method
             * @memberof api.documents
             * @returns {promise}
             */
            lastPage: requestPageFun('last'),

            /**
             * Get pagination links
             *
             * @method
             * @memberof api.documents
             * @returns {object}
             */
            paginationLinks: {
                last: false,
                next: false,
                previous: false
            },

            /**
             * Reset all pagination
             *
             * @method
             * @memberof api.documents
             */
            resetPagination: resetPaginationLinks
        };
    }

    /**
     * Folders API
     *
     * @namespace
     * @name api.folders
     */
    function folders() {
        var dataHeaders = {
            folder: { 'Content-Type': 'application/vnd.mendeley-folder.1+json' },
            'document': { 'Content-Type': 'application/vnd.mendeley-document.1+json' }
        };

        return {
            /**
             * Create a new folder
             *
             * @method
             * @memberof api.folders
             * @param {object} data - The folder data
             * @returns {promise}
             */
            create: requestWithDataFun('POST', '/folders', [], dataHeaders.folder, true),

            /**
             * Retrieve a folder
             *
             * @method
             * @memberof api.folders
             * @param {string} id - A folder UUID
             * @returns {promise}
             */
            retrieve: requestFun('GET', '/folders/{id}', ['id']),

            /**
             * Update a folder
             *
             * @method
             * @memberof api.folders
             * @param {object} data - The folder data
             * @returns {promise}
             */
            update: requestWithDataFun('PATCH', '/folders/{id}', ['id'], dataHeaders.folder, true),

            /**
             * Delete a folder
             *
             * @method
             * @memberof api.folders
             * @param {string} id - A folder UUID
             * @returns {promise}
             */
            delete: requestFun('DELETE', '/folders/{id}', ['id']),

            /**
             * Remove a document from a folder
             *
             * @method
             * @memberof api.folders
             * @param {string} id - A folder UUID
             * @param {string} documentId - A document UUID
             * @returns {promise}
             */
            removeDocument: requestFun('DELETE', '/folders/{id}/documents/{docId}', ['id', 'docId'], dataHeaders.folder),

            /**
             * Add a document to a folder
             *
             * @method
             * @memberof api.folders
             * @param {string} id - A folder UUID
             * @param {string} documentId - A document UUID
             * @returns {promise}
             */
            addDocument: requestWithDataFun('POST', '/folders/{id}/documents', ['id'], dataHeaders.document, false),

            /**
             * Get a list of folders
             *
             * @method
             * @memberof api.folders
             * @returns {promise}
             */
            list: requestFun('GET', '/folders/'),

            /**
             * The total number of folders - set after the first call to folders.list()
             *
             * @var
             * @memberof api.folders
             * @type {integer}
             */
            count: 0,

            /**
             * Get the next page of folders
             *
             * @method
             * @memberof api.folders
             * @returns {promise}
             */
            nextPage: requestPageFun('next'),

            /**
             * Get the previous page of folders
             *
             * @method
             * @memberof api.folders
             * @returns {promise}
             */
            previousPage: requestPageFun('previous'),

            /**
             * Get the last page of folders
             *
             * @method
             * @memberof api.folders
             * @returns {promise}
             */
            lastPage: requestPageFun('last'),

            /**
             * Get pagination links
             *
             * @method
             * @memberof api.folders
             * @returns {object}
             */
            paginationLinks: {
                last: false,
                next: false,
                previous: false
            },

            /**
             * Reset all pagination links
             *
             * @method
             * @memberof api.folders
             */
            resetPagination: resetPaginationLinks
        };
    }

    /**
     * Files API
     *
     * @namespace
     * @name api.files
     */
    function files() {

        return {
            /**
             * Create a new file
             *
             * @method
             * @memberof api.files
             * @param {object} file - A file object
             * @param {string} documentId - A document UUID
             * @returns {promise}
             */
            create: requestWithFileFun('POST', '/files'),

            /**
             * Get a list of files for a document
             *
             * @method
             * @memberof api.files
             * @param {string} id - A document UUID
             * @returns {promise}
             */
            list: requestFun('GET', '/files?document_id={id}', ['id']),

            /**
             * Delete a file
             *
             * @method
             * @memberof api.files
             * @param {string} id - A file UUID
             * @returns {promise}
             */
            remove: requestFun('DELETE', '/files/{id}', ['id'])
        };
    }

    /**
     * Catalog API
     *
     * @namespace
     * @name api.catalog
     */
    function catalog() {
        return {
            /**
             * Search the catalog
             *
             * @method
             * @memberof api.catalog
             * @param {object} params - A catalogue search filter
             * @returns {promise}
             */
            search: requestFun('GET', '/catalog')
        };
    }

    /**
     * Trash API
     *
     * @namespace
     * @name api.trash
     */
    function trash() {
        return {
            /**
             * Retrieve a document from the trash
             *
             * @method
             * @memberof api.trash
             * @param {string} id - A document UUID
             * @returns {promise}
             */
            retrieve: requestFun('GET', '/trash/{id}', ['id']),

            /**
             * List all documents in the trash
             *
             * @method
             * @memberof api.trash
             * @returns {promise}
             */
            list: requestFun('GET', '/trash/'),

            /**
             * Restore a trashed document
             *
             * @method
             * @memberof api.trash
             * @param {string} id - A document UUID
             * @returns {promise}
             */
            restore: requestFun('POST', '/trash/{id}/restore', ['id']),

            /**
             * Permanently delete a trashed document
             *
             * @method
             * @memberof api.trash
             * @param {string} id - A document UUID
             * @returns {promise}
             */
            destroy: requestFun('DELETE', '/trash/{id}', ['id']),

            /**
             * The total number of trashed documents - set after the first call to trash.list()
             *
             * @var
             * @memberof api.trash
             * @type {integer}
             */
            count: 0,

            /**
             * Get the next page of trash
             *
             * @method
             * @memberof api.trash
             * @returns {promise}
             */
            nextPage: requestPageFun('next'),

            /**
             * Get the previous page of trash
             *
             * @method
             * @memberof api.trash
             * @returns {promise}
             */
            previousPage: requestPageFun('previous'),

            /**
             * Get the last page of trash
             *
             * @method
             * @memberof api.trash
             * @returns {promise}
             */
            lastPage: requestPageFun('last'),

            /**
             * Get pagination links
             *
             * @method
             * @memberof api.trash
             * @returns {object}
             */
            paginationLinks: {
                last: false,
                next: false,
                previous: false
            },

            /**
             * Reset all pagination links
             *
             * @method
             * @memberof api.trash
             */
            resetPagination: resetPaginationLinks
        };
    }

    /**
     * Set the current pagination links for a given API by extracting
     * looking at the headers retruend with the response.
     *
     * @private
     * @param {object} headers
     */
    function setPaginationLinks(headers) {
        if (headers.hasOwnProperty('Mendeley-Count')) {
            this.count = parseInt(headers['Mendeley-Count'], 10);
        }

        if (!headers.hasOwnProperty('Link') || typeof headers.Link !== 'object') {
            return ;
        }

        for (var p in this.paginationLinks) {
            this.paginationLinks[p] = headers.Link.hasOwnProperty(p) ? headers.Link[p] : false;
        }
    }

    /**
     * Reset the pagination links
     *
     * @private
     */
    function resetPaginationLinks() {
        this.paginationLinks = {
            last: false,
            next: false,
            previous: false
        };
        this.count = 0;
    }

    /**
     * A general purpose request functions
     *
     * @private
     * @param {string} method
     * @param {string} uriTemplate
     * @param {array} uriVars
     * @param {array} headers
     * @returns {function}
     */
    function requestFun(method, uriTemplate, uriVars, headers) {

        uriVars = uriVars || [];

        return function() {
            var args = Array.prototype.slice.call(arguments, 0);
            var url = getUrl(uriTemplate, uriVars, args);
            var data = args[uriVars.length];
            var request = {
                type: method,
                dataType: 'json',
                url: url,
                headers: getRequestHeaders(headers),
                data: data
            };
            var settings = {
                authFlow: authFlow
            };

            if (method === 'GET') {
                settings.maxRetries = 1;
            }

            var promise = Request.create(request, settings).send();
            promise.done(function(response, headers) {
                setPaginationLinks.call(this, headers);
            }.bind(this));

            return promise;
        };
    }

    /**
     * Get a function for getting a pagination rel
     *
     * @private
     * @param {string} rel - One of "next", "prev" or "last"
     * @returns {function}
     */
    function requestPageFun(rel) {

        return function() {
            if (!this.paginationLinks[rel]) {
                return new $.Deferred().reject();
            }

            var request = {
                type: 'GET',
                dataType: 'json',
                url: this.paginationLinks[rel],
                headers: getRequestHeaders({})
            };

            var settings = {
                authFlow: authFlow,
                maxRetries: 1
            };

            var promise = Request.create(request, settings).send();
            promise.done(function(response, headers) {
                setPaginationLinks.call(this, headers);
            }.bind(this));

            return promise;
        };
    }

    /**
     * Get a request function that sends data i.e. for POST, PUT, PATCH
     *
     * @private
     * @param {string} method
     * @param {string} uriTemplate
     * @param {array} uriVars
     * @param {array} headers
     * @param {function} dataFun - Function for preparing data
     * @returns {function}
     */
    function requestWithDataFun(method, uriTemplate, uriVars, headers, followLocation) {
        uriVars = uriVars || [];

        return function() {
            var args = Array.prototype.slice.call(arguments, 0);
            var url = getUrl(uriTemplate, uriVars, args);
            var data = args[uriVars.length];
            var request = {
                type: method,
                url: url,
                headers: getRequestHeaders(headers, data),
                data: JSON.stringify(data),
                processData: false
            };

            var settings = {
                authFlow: authFlow,
                followLocation: followLocation
            };

            return Request.create(request, settings).send();
        };
    }

    /**
     * Get a request function that sends a file
     *
     * @private
     * @param {string} method
     * @param {string} uriTemplate
     * @returns {function}
     */
    function requestWithFileFun(method, uriTemplate) {

        return function() {

            var args = Array.prototype.slice.call(arguments, 0);
            var url = getUrl(uriTemplate, [], args);
            var file = args[0];
            var documentId = args[1];
            var request = {
                type: method,
                url: url,
                headers: getRequestHeaders(uploadHeaders(file, documentId), method),
                data: file,
                processData: false
            };

            var settings = {
                authFlow: authFlow,
                fileUpload: true
            };

            return Request.create(request, settings).send();
        };
    }

    /**
     * Provide the correct encoding for UTF-8 Content-Disposition header value.
     * See https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/encodeURIComponent
     *
     * @private
     * @param {string} str
     * @returns {string}
     */
    function encodeRFC5987ValueChars(str) {
        return encodeURIComponent(str).
            replace(/'/g, '%27').
            replace(/\(/g, '%28').
            replace(/\)/g, '%29').
            replace(/\*/g, '%2A');
    }

    /**
     * Get headers for an upload
     *
     * @private
     * @param {object} file
     * @param {string} documentId
     * @returns {string}
     */
    function uploadHeaders(file, documentId) {
        var headers = {
            'Content-Type': !!file.type ? file.type : 'application/octet-stream',
            'Content-Disposition': 'attachment; filename*=UTF-8\'\'' + encodeRFC5987ValueChars(file.name)
        };
        if(documentId) {
            headers.Link = '<' + apiBaseUrl + '/documents/' + documentId +'>; rel="document"';
        }

        return headers;
    }

    /**
     * Generate a URL from a template with properties and values
     *
     * @private
     * @param {string} uriTemplate
     * @param {array} uriProps
     * @param {array} uriValues
     * @returns {string}
     */
    function getUrl(uriTemplate, uriProps, uriValues) {
        if (!uriProps.length) {
            return apiBaseUrl + uriTemplate;
        }
        var uriParams = {};
        uriProps.forEach(function(prop, i) {
            uriParams[prop] = uriValues[i];
        });

        return apiBaseUrl + expandUriTemplate(uriTemplate, uriParams);
    }

    /**
     * Get the headers for a request
     *
     * @private
     * @param {array} headers
     * @param {array} data
     * @returns {array}
     */
    function getRequestHeaders(headers, data) {
        for (var headerName in headers) {
            var val = headers[headerName];
            if (typeof val === 'function') {
                headers[headerName] = val(data);
            }
        }

        return headers;
    }

    /**
     * Populate a URI template with data
     *
     * @private
     * @param {string} template
     * @param {object} data
     * @returns {string}
     */
    function expandUriTemplate(template, data) {
        var matches = template.match(/\{[a-z]+\}/gi);
        matches.forEach(function(match) {
            var prop = match.replace(/[\{\}]/g, '');
            if (!data.hasOwnProperty(prop)) {
                throw new Error('Endpoint requires ' + prop);
            }
            template = template.replace(match, data[prop]);
        });

        return template;
    }
});


text:
require "rss-testcase"

require "rss/maker"

module RSS
  class TestSetupMaker10 < TestCase

    def setup
      t = Time.iso8601("2000-01-01T12:00:05+00:00")
      class << t
        alias_method(:to_s, :iso8601)
      end

      @dc_elems = {
        :title => "hoge",
        :description =>
          " XML is placing increasingly heavy loads on
          the existing technical infrastructure of the Internet.",
        :creator => "Rael Dornfest (mailto:rael@oreilly.com)",
        :subject => "XML",
        :publisher => "The O'Reilly Network",
        :contributor => "hogehoge",
        :type => "fugafuga",
        :format => "hohoho",
        :identifier => "fufufu",
        :source => "barbar",
        :language => "ja",
        :relation => "cococo",
        :rights => "Copyright (c) 2000 O'Reilly & Associates, Inc.",
        :date => t,
      }

      @sy_elems = {
        :updatePeriod => "hourly",
        :updateFrequency => "2",
        :updateBase => t,
      }

      @content_elems = {
        :encoded => "ATTENTION",
      }

      @trackback_elems = {
        :ping => "http://bar.com/tb.cgi?tb_id=rssplustrackback",
        :about => [
          "http://foo.com/trackback/tb.cgi?tb_id=20020923",
          "http://foo.com/trackback/tb.cgi?tb_id=20021010",
        ],
      }

      @taxo_topic_elems = [
        {
          :link => "http://meerkat.oreillynet.com/?c=cat23",
          :title => "Data: XML",
          :description => "A Meerkat channel",
        },
        {
          :link => "http://dmoz.org/Computers/Data_Formats/Markup_Languages/XML/",
          :title => "XML",
          :subject => "XML",
          :description => "DMOZ category",
          :topics => [
            "http://meerkat.oreillynet.com/?c=cat23",
            "http://dmoz.org/Computers/Data_Formats/Markup_Languages/SGML/",
            "http://dmoz.org/Computers/Programming/Internet/",
          ]
        },
      ]
    end

    def test_setup_maker_channel
      about = "http://hoge.com"
      title = "fugafuga"
      link = "http://hoge.com"
      description = "fugafugafugafuga"

      rss = RSS::Maker.make("1.0") do |maker|
        maker.channel.about = about
        maker.channel.title = title
        maker.channel.link = link
        maker.channel.description = description

        @dc_elems.each do |var, value|
          maker.channel.__send__("dc_#{var}=", value)
        end

        @sy_elems.each do |var, value|
          maker.channel.__send__("sy_#{var}=", value)
        end

        setup_dummy_item(maker)
      end

      new_rss = RSS::Maker.make("1.0") do |maker|
        rss.channel.setup_maker(maker)
        rss.items.each do |item|
          item.setup_maker(maker)
        end
      end
      channel = new_rss.channel

      assert_equal(about, channel.about)
      assert_equal(title, channel.title)
      assert_equal(link, channel.link)
      assert_equal(description, channel.description)
      assert_equal(1, channel.items.Seq.lis.size)
      assert_nil(channel.image)
      assert_nil(channel.textinput)

      @dc_elems.each do |var, value|
        assert_equal(value, channel.__send__("dc_#{var}"))
      end

      @sy_elems.each do |var, value|
        value = value.to_i if var == :updateFrequency
        assert_equal(value, channel.__send__("sy_#{var}"))
      end

    end

    def test_setup_maker_image
      title = "fugafuga"
      link = "http://hoge.com"
      url = "http://hoge.com/hoge.png"

      rss = RSS::Maker.make("1.0") do |maker|
        setup_dummy_channel(maker)
        maker.channel.link = link

        maker.image.title = title
        maker.image.url = url

        @dc_elems.each do |var, value|
          maker.image.__send__("dc_#{var}=", value)
        end

        setup_dummy_item(maker)
      end

      new_rss = RSS::Maker.make("1.0") do |maker|
        rss.channel.setup_maker(maker)
        rss.image.setup_maker(maker)
        rss.items.each do |item|
          item.setup_maker(maker)
        end
      end

      image = new_rss.image
      assert_equal(url, image.about)
      assert_equal(url, new_rss.channel.image.resource)
      assert_equal(title, image.title)
      assert_equal(link, image.link)
      assert_equal(url, image.url)

      @dc_elems.each do |var, value|
        assert_equal(image.__send__("dc_#{var}"), value)
      end
    end

    def test_setup_maker_textinput
      title = "fugafuga"
      description = "text hoge fuga"
      name = "hoge"
      link = "http://hoge.com"

      rss = RSS::Maker.make("1.0") do |maker|
        setup_dummy_channel(maker)

        maker.textinput.link = link
        maker.textinput.title = title
        maker.textinput.description = description
        maker.textinput.name = name

        @dc_elems.each do |var, value|
          maker.textinput.__send__("dc_#{var}=", value)
        end

        setup_dummy_item(maker)
      end

      new_rss = RSS::Maker.make("1.0") do |maker|
        rss.channel.setup_maker(maker)
        rss.textinput.setup_maker(maker)
        rss.items.each do |item|
          item.setup_maker(maker)
        end
      end

      textinput = new_rss.textinput
      assert_equal(link, textinput.about)
      assert_equal(link, new_rss.channel.textinput.resource)
      assert_equal(title, textinput.title)
      assert_equal(name, textinput.name)
      assert_equal(description, textinput.description)
      assert_equal(link, textinput.link)

      @dc_elems.each do |var, value|
        assert_equal(textinput.__send__("dc_#{var}"), value)
      end
    end

    def test_setup_maker_items(for_backward_compatibility=false)
      title = "TITLE"
      link = "http://hoge.com/"
      description = "text hoge fuga"

      item_size = 5

      rss = RSS::Maker.make("1.0") do |maker|
        setup_dummy_channel(maker)

        item_size.times do |i|
          maker.items.new_item do |item|
            item.title = "#{title}#{i}"
            item.link = "#{link}#{i}"
            item.description = "#{description}#{i}"

            @dc_elems.each do |var, value|
              item.__send__("dc_#{var}=", value)
            end

            @content_elems.each do |var, value|
              item.__send__("content_#{var}=", value)
            end

            item.trackback_ping = @trackback_elems[:ping]
            @trackback_elems[:about].each do |value|
              item.trackback_abouts.new_about do |new_about|
                new_about.value = value
              end
            end
          end
        end
      end

      new_rss = RSS::Maker.make("1.0") do |maker|
        rss.channel.setup_maker(maker)

        rss.items.each do |item|
          if for_backward_compatibility
            item.setup_maker(maker)
          else
            item.setup_maker(maker.items)
          end
        end
      end

      assert_equal(item_size, new_rss.items.size)
      new_rss.items.each_with_index do |item, i|
        assert_equal("#{link}#{i}", item.about)
        assert_equal("#{title}#{i}", item.title)
        assert_equal("#{link}#{i}", item.link)
        assert_equal("#{description}#{i}", item.description)

        @dc_elems.each do |var, value|
          assert_equal(item.__send__("dc_#{var}"), value)
        end

        @content_elems.each do |var, value|
          assert_equal(item.__send__("content_#{var}"), value)
        end

        assert_equal(@trackback_elems[:ping], item.trackback_ping)
        assert_equal(@trackback_elems[:about].size, item.trackback_abouts.size)
        item.trackback_abouts.each_with_index do |about, j|
          assert_equal(@trackback_elems[:about][j], about.value)
        end
      end
    end

    def test_setup_maker_items_sort
      title = "TITLE"
      link = "http://hoge.com/"
      description = "text hoge fuga"

      item_size = 5

      rss = RSS::Maker.make("1.0") do |maker|
        setup_dummy_channel(maker)

        item_size.times do |i|
          item = RSS::RDF::Item.new("#{link}#{i}")
          item.title = "#{title}#{i}"
          item.link = "#{link}#{i}"
          item.description = "#{description}#{i}"
          item.dc_date = Time.now + i * 60
          item.setup_maker(maker.items)
        end
        maker.items.do_sort = false
      end
      assert_equal(item_size, rss.items.size)
      rss.items.each_with_index do |item, i|
        assert_equal("#{link}#{i}", item.about)
        assert_equal("#{title}#{i}", item.title)
        assert_equal("#{link}#{i}", item.link)
        assert_equal("#{description}#{i}", item.description)
      end

      rss = RSS::Maker.make("1.0") do |maker|
        setup_dummy_channel(maker)

        item_size.times do |i|
          item = RSS::RDF::Item.new("#{link}#{i}")
          item.title = "#{title}#{i}"
          item.link = "#{link}#{i}"
          item.description = "#{description}#{i}"
          item.dc_date = Time.now + i * 60
          item.setup_maker(maker.items)
        end
        maker.items.do_sort = true
      end
      assert_equal(item_size, rss.items.size)
      rss.items.reverse.each_with_index do |item, i|
        assert_equal("#{link}#{i}", item.about)
        assert_equal("#{title}#{i}", item.title)
        assert_equal("#{link}#{i}", item.link)
        assert_equal("#{description}#{i}", item.description)
      end
    end

    def test_setup_maker_items_backward_compatibility
      test_setup_maker_items(true)
    end

    def test_setup_maker
      encoding = "EUC-JP"
      standalone = true

      href = 'a.xsl'
      type = 'text/xsl'
      title = 'sample'
      media = 'printer'
      charset = 'UTF-8'
      alternate = 'yes'

      rss = RSS::Maker.make("1.0") do |maker|
        maker.encoding = encoding
        maker.standalone = standalone

        maker.xml_stylesheets.new_xml_stylesheet do |xss|
          xss.href = href
          xss.type = type
          xss.title = title
          xss.media = media
          xss.charset = charset
          xss.alternate = alternate
        end

        setup_dummy_channel(maker)
        setup_dummy_item(maker)
      end

      new_rss = RSS::Maker.make("1.0") do |maker|
        rss.setup_maker(maker)
      end

      assert_equal("1.0", new_rss.rss_version)
      assert_equal(encoding, new_rss.encoding)
      assert_equal(standalone, new_rss.standalone)

      xss = new_rss.xml_stylesheets.first
      assert_equal(1, new_rss.xml_stylesheets.size)
      assert_equal(href, xss.href)
      assert_equal(type, xss.type)
      assert_equal(title, xss.title)
      assert_equal(media, xss.media)
      assert_equal(charset, xss.charset)
      assert_equal(alternate, xss.alternate)
    end

    def test_setup_maker_full
      encoding = "EUC-JP"
      standalone = true

      href = 'a.xsl'
      type = 'text/xsl'
      title = 'sample'
      media = 'printer'
      charset = 'UTF-8'
      alternate = 'yes'

      channel_about = "http://hoge.com"
      channel_title = "fugafuga"
      channel_link = "http://hoge.com"
      channel_description = "fugafugafugafuga"

      image_title = "fugafuga"
      image_url = "http://hoge.com/hoge.png"

      textinput_title = "fugafuga"
      textinput_description = "text hoge fuga"
      textinput_name = "hoge"
      textinput_link = "http://hoge.com"

      item_title = "TITLE"
      item_link = "http://hoge.com/"
      item_description = "text hoge fuga"

      item_size = 5

      rss = RSS::Maker.make("1.0") do |maker|
        maker.encoding = encoding
        maker.standalone = standalone

        maker.xml_stylesheets.new_xml_stylesheet do |xss|
          xss.href = href
          xss.type = type
          xss.title = title
          xss.media = media
          xss.charset = charset
          xss.alternate = alternate
        end

        maker.channel.about = channel_about
        maker.channel.title = channel_title
        maker.channel.link = channel_link
        maker.channel.description = channel_description
        @dc_elems.each do |var, value|
          maker.channel.__send__("dc_#{var}=", value)
        end
        @sy_elems.each do |var, value|
          maker.channel.__send__("sy_#{var}=", value)
        end

        maker.image.title = image_title
        maker.image.url = image_url
        @dc_elems.each do |var, value|
          maker.image.__send__("dc_#{var}=", value)
        end

        maker.textinput.link = textinput_link
        maker.textinput.title = textinput_title
        maker.textinput.description = textinput_description
        maker.textinput.name = textinput_name
        @dc_elems.each do |var, value|
          maker.textinput.__send__("dc_#{var}=", value)
        end

        item_size.times do |i|
          maker.items.new_item do |item|
            item.title = "#{item_title}#{i}"
            item.link = "#{item_link}#{i}"
            item.description = "#{item_description}#{i}"

            @dc_elems.each do |var, value|
              item.__send__("dc_#{var}=", value)
            end

            @content_elems.each do |var, value|
              item.__send__("content_#{var}=", value)
            end

            item.trackback_ping = @trackback_elems[:ping]
            @trackback_elems[:about].each do |value|
              item.trackback_abouts.new_about do |new_about|
                new_about.value = value
              end
            end
          end
        end

        setup_taxo_topic(maker, @taxo_topic_elems)
      end

      new_rss = RSS::Maker.make("1.0") do |maker|
        rss.setup_maker(maker)
      end

      assert_equal("1.0", new_rss.rss_version)
      assert_equal(encoding, new_rss.encoding)
      assert_equal(standalone, new_rss.standalone)

      xss = new_rss.xml_stylesheets.first
      assert_equal(1, new_rss.xml_stylesheets.size)
      assert_equal(href, xss.href)
      assert_equal(type, xss.type)
      assert_equal(title, xss.title)
      assert_equal(media, xss.media)
      assert_equal(charset, xss.charset)
      assert_equal(alternate, xss.alternate)

      channel = new_rss.channel
      assert_equal(channel_about, channel.about)
      assert_equal(channel_title, channel.title)
      assert_equal(channel_link, channel.link)
      assert_equal(channel_description, channel.description)
      item_resources = []
      item_size.times do |i|
        item_resources << "#{item_link}#{i}"
      end
      assert_equal(item_resources, channel.items.resources)
      assert_equal(image_url, channel.image.resource)
      assert_equal(textinput_link, channel.textinput.resource)
      @dc_elems.each do |var, value|
        assert_equal(value, channel.__send__("dc_#{var}"))
      end
      @sy_elems.each do |var, value|
        value = value.to_i if var == :updateFrequency
        assert_equal(value, channel.__send__("sy_#{var}"))
      end

      image = new_rss.image
      assert_equal(image_url, image.about)
      assert_equal(image_url, new_rss.channel.image.resource)
      assert_equal(image_title, image.title)
      assert_equal(channel_link, image.link)
      assert_equal(image_url, image.url)
      @dc_elems.each do |var, value|
        assert_equal(image.__send__("dc_#{var}"), value)
      end

      textinput = new_rss.textinput
      assert_equal(textinput_link, textinput.about)
      assert_equal(textinput_link, new_rss.channel.textinput.resource)
      assert_equal(textinput_title, textinput.title)
      assert_equal(textinput_name, textinput.name)
      assert_equal(textinput_description, textinput.description)
      assert_equal(textinput_link, textinput.link)
      @dc_elems.each do |var, value|
        assert_equal(textinput.__send__("dc_#{var}"), value)
      end

      assert_equal(item_size, new_rss.items.size)
      new_rss.items.each_with_index do |item, i|
        assert_equal("#{item_link}#{i}", item.about)
        assert_equal("#{item_title}#{i}", item.title)
        assert_equal("#{item_link}#{i}", item.link)
        assert_equal("#{item_description}#{i}", item.description)

        @dc_elems.each do |var, value|
          assert_equal(item.__send__("dc_#{var}"), value)
        end

        @content_elems.each do |var, value|
          assert_equal(item.__send__("content_#{var}"), value)
        end

        assert_equal(@trackback_elems[:ping], item.trackback_ping)
        assert_equal(@trackback_elems[:about].size, item.trackback_abouts.size)
        item.trackback_abouts.each_with_index do |about, j|
          assert_equal(@trackback_elems[:about][j], about.value)
        end
      end

      assert_taxo_topic(@taxo_topic_elems, new_rss)
    end

  end
end

redpajama_set_name: RedPajamaGithub


text:
package com.netbrasoft.gnuob.application.category;

import static de.agilecoders.wicket.jquery.JQuery.$;

import java.util.List;

import org.apache.wicket.AttributeModifier;
import org.apache.wicket.Component;
import org.apache.wicket.ajax.AjaxEventBehavior;
import org.apache.wicket.ajax.AjaxRequestTarget;
import org.apache.wicket.authorization.Action;
import org.apache.wicket.authroles.authorization.strategies.role.annotations.AuthorizeAction;
import org.apache.wicket.markup.head.IHeaderResponse;
import org.apache.wicket.markup.html.WebMarkupContainer;
import org.apache.wicket.markup.html.basic.Label;
import org.apache.wicket.markup.html.panel.Fragment;
import org.apache.wicket.markup.html.panel.Panel;
import org.apache.wicket.markup.repeater.Item;
import org.apache.wicket.markup.repeater.data.DataView;
import org.apache.wicket.markup.repeater.data.IDataProvider;
import org.apache.wicket.markup.repeater.data.ListDataProvider;
import org.apache.wicket.model.CompoundPropertyModel;
import org.apache.wicket.model.IModel;
import org.apache.wicket.model.Model;

import com.netbrasoft.gnuob.api.Category;
import com.netbrasoft.gnuob.api.Content;
import com.netbrasoft.gnuob.application.NetbrasoftApplicationConstants;
import com.netbrasoft.gnuob.application.security.AppRoles;

import de.agilecoders.wicket.core.markup.html.bootstrap.button.BootstrapAjaxLink;
import de.agilecoders.wicket.core.markup.html.bootstrap.button.Buttons;
import de.agilecoders.wicket.core.markup.html.bootstrap.image.GlyphIconType;
import de.agilecoders.wicket.core.markup.html.bootstrap.navigation.BootstrapPagingNavigator;
import de.agilecoders.wicket.core.markup.html.bootstrap.table.TableBehavior;
import de.agilecoders.wicket.extensions.markup.html.bootstrap.confirmation.ConfirmationBehavior;
import de.agilecoders.wicket.extensions.markup.html.bootstrap.confirmation.ConfirmationConfig;

@SuppressWarnings("unchecked")
@AuthorizeAction(action = Action.RENDER, roles = {AppRoles.MANAGER, AppRoles.EMPLOYEE})
public class CategoryContentPanel extends Panel {

  @AuthorizeAction(action = Action.RENDER, roles = {AppRoles.MANAGER})
  class CategoryContentEditFragment extends Fragment {

    @AuthorizeAction(action = Action.RENDER, roles = {AppRoles.MANAGER})
    class ContentEditTable extends WebMarkupContainer {

      @AuthorizeAction(action = Action.RENDER, roles = {AppRoles.MANAGER})
      class AddAjaxLink extends BootstrapAjaxLink<Category> {

        private static final long serialVersionUID = 9191172039973638020L;

        public AddAjaxLink(final String id, final IModel<Category> model, final Buttons.Type type, final IModel<String> labelModel) {
          super(id, model, type, labelModel);
          setIconType(GlyphIconType.plus);
          setSize(Buttons.Size.Small);
        }

        @Override
        public void onClick(final AjaxRequestTarget target) {
          final Content content = new Content();
          content.setActive(true);
          ((Category) AddAjaxLink.this.getDefaultModelObject()).getContents().add(content);
          contentDataviewContainer.contentDataview.index = ((Category) AddAjaxLink.this.getDefaultModelObject()).getContents().size() - 1;
          categoryContentViewOrEditPanel.removeAll();
          target.add(contentDataviewContainer.setOutputMarkupId(true));
          target.add(categoryContentViewOrEditPanel.add(categoryContentViewOrEditPanel.new CategoryContentEditFragment()).setOutputMarkupId(true));
        }
      }

      @AuthorizeAction(action = Action.RENDER, roles = {AppRoles.MANAGER})
      class ContentDataviewContainer extends WebMarkupContainer {

        @AuthorizeAction(action = Action.RENDER, roles = {AppRoles.MANAGER})
        class ContentDataview extends DataView<Content> {

          @AuthorizeAction(action = Action.RENDER, roles = {AppRoles.MANAGER})
          class RemoveAjaxLink extends BootstrapAjaxLink<Content> {

            private static final long serialVersionUID = -6950515027229520882L;

            public RemoveAjaxLink(final String id, final IModel<Content> model, final Buttons.Type type, final IModel<String> labelModel) {
              super(id, model, type, labelModel);
              setIconType(GlyphIconType.remove);
              setSize(Buttons.Size.Mini);
            }

            @Override
            public void onClick(final AjaxRequestTarget target) {
              ((Category) ContentDataviewContainer.this.getDefaultModelObject()).getContents().remove(RemoveAjaxLink.this.getDefaultModelObject());
              contentDataview.index = ((Category) ContentDataviewContainer.this.getDefaultModelObject()).getContents().size() - 1;
              categoryContentViewOrEditPanel.removeAll();
              target.add(contentDataviewContainer.setOutputMarkupId(true));
              target.add(categoryContentViewOrEditPanel.add(categoryContentViewOrEditPanel.new CategoryContentEditFragment()).setOutputMarkupId(true));
            }
          }

          private static final String NAME_ID = "name";

          private static final long serialVersionUID = 2246346365193989354L;

          private static final String CONFIRMATION_FUNCTION_NAME = "confirmation";

          private static final String REMOVE_ID = "remove";

          private static final String CLICK_EVENT = "click";

          private static final String INFO_VALUE = "info";

          private static final String CLASS_ATTRIBUTE = "class";

          private int index = 0;

          protected ContentDataview(final String id, final IDataProvider<Content> dataProvider, final long itemsPerPage) {
            super(id, dataProvider, itemsPerPage);
          }

          @Override
          protected Item<Content> newItem(final String id, final int index, final IModel<Content> model) {
            final Item<Content> item = super.newItem(id, index, model);
            if (this.index == index) {
              item.add(new AttributeModifier(CLASS_ATTRIBUTE, INFO_VALUE));
            }
            return item;
          }

          @Override
          protected void onConfigure() {
            final IModel<Category> model = (IModel<Category>) ContentDataviewContainer.this.getDefaultModel();
            if (!model.getObject().getContents().isEmpty()) {
              categoryContentViewOrEditPanel.setEnabled(true);
              categoryContentViewOrEditPanel.removeAll();
              categoryContentViewOrEditPanel.setSelectedModel(Model.of(model.getObject().getContents().get(index)));
              categoryContentViewOrEditPanel.add(categoryContentViewOrEditPanel.new CategoryContentEditFragment()).setOutputMarkupId(true);
            } else {
              categoryContentViewOrEditPanel.setEnabled(false);
              categoryContentViewOrEditPanel.removeAll();
              categoryContentViewOrEditPanel.setSelectedModel(Model.of(new Content()));
              categoryContentViewOrEditPanel.add(categoryContentViewOrEditPanel.new CategoryContentEditFragment()).setOutputMarkupId(true);
            }
            super.onConfigure();
          }

          @Override
          protected void populateItem(final Item<Content> item) {
            final IModel<Content> compound = new CompoundPropertyModel<Content>(item.getModelObject());
            item.setModel(compound);
            item.add(new Label(NAME_ID));
            item.add(new AjaxEventBehavior(CLICK_EVENT) {

              private static final long serialVersionUID = 1L;

              @Override
              public void onEvent(final AjaxRequestTarget target) {
                index = item.getIndex();
                categoryContentViewOrEditPanel.setSelectedModel(item.getModel());
                categoryContentViewOrEditPanel.removeAll();
                target.add(contentDataviewContainer.setOutputMarkupId(true));
                target.add(categoryContentViewOrEditPanel.add(categoryContentViewOrEditPanel.new CategoryContentEditFragment()).setOutputMarkupId(true));
              }
            });
            item.add(new RemoveAjaxLink(REMOVE_ID, item.getModel(), Buttons.Type.Default,
                Model.of(CategoryContentPanel.this.getString(NetbrasoftApplicationConstants.REMOVE_MESSAGE_KEY))).add(new ConfirmationBehavior() {

                  private static final long serialVersionUID = 7744720444161839031L;

                  @Override
                  public void renderHead(final Component component, final IHeaderResponse response) {
                    response.render($(component).chain(CONFIRMATION_FUNCTION_NAME,
                        new ConfirmationConfig().withTitle(getString(NetbrasoftApplicationConstants.CONFIRMATION_MESSAGE_KEY)).withSingleton(true).withPopout(true)
                            .withBtnOkLabel(getString(NetbrasoftApplicationConstants.CONFIRM_MESSAGE_KEY))
                            .withBtnCancelLabel(getString(NetbrasoftApplicationConstants.CANCEL_MESSAGE_KEY)))
                        .asDomReadyScript());
                  }
                }));
          }
        }

        private static final String CONTENT_DATAVIEW_ID = "contentDataview";

        private static final long serialVersionUID = 9165996901588092749L;

        private final ContentDataview contentDataview;

        private final ListDataProvider<Content> contentListDataProvider;

        public ContentDataviewContainer(final String id, final IModel<Category> model) {
          super(id, model);
          contentListDataProvider = new ListDataProvider<Content>() {

            private static final long serialVersionUID = -3261859241046697057L;

            @Override
            protected List<Content> getData() {
              return ((Category) ContentDataviewContainer.this.getDefaultModelObject()).getContents();
            }
          };
          contentDataview = new ContentDataview(CONTENT_DATAVIEW_ID, contentListDataProvider, ITEMS_PER_PAGE);
        }

        @Override
        protected void onInitialize() {
          add(contentDataview.setOutputMarkupId(true));
          super.onInitialize();
        }
      }

      private static final String CATEGORY_CONTENT_VIEW_OR_EDIT_PANEL_ID = "categoryContentViewOrEditPanel";

      private static final String CONTENT_PAGING_NAVIGATOR_MARKUP_ID = "contentPagingNavigator";

      private static final String CONTENT_DATAVIEW_CONTAINER_ID = "contentDataviewContainer";

      private static final long serialVersionUID = -615589482625248433L;

      private static final String ADD_ID = "add";

      private final AddAjaxLink addAjaxLink;

      private final ContentDataviewContainer contentDataviewContainer;

      private final BootstrapPagingNavigator contentPagingNavigator;

      private final CategoryContentViewOrEditPanel categoryContentViewOrEditPanel;

      public ContentEditTable(final String id, final IModel<Category> model) {
        super(id, model);
        addAjaxLink = new AddAjaxLink(ADD_ID, (IModel<Category>) ContentEditTable.this.getDefaultModel(), Buttons.Type.Primary,
            Model.of(CategoryContentPanel.this.getString(NetbrasoftApplicationConstants.ADD_MESSAGE_KEY)));
        contentDataviewContainer = new ContentDataviewContainer(CONTENT_DATAVIEW_CONTAINER_ID, (IModel<Category>) ContentEditTable.this.getDefaultModel());
        contentPagingNavigator = new BootstrapPagingNavigator(CONTENT_PAGING_NAVIGATOR_MARKUP_ID, contentDataviewContainer.contentDataview);
        categoryContentViewOrEditPanel = new CategoryContentViewOrEditPanel(CATEGORY_CONTENT_VIEW_OR_EDIT_PANEL_ID, (IModel<Category>) ContentEditTable.this.getDefaultModel());
      }

      @Override
      protected void onInitialize() {
        add(addAjaxLink.setOutputMarkupId(true));
        add(contentDataviewContainer.setOutputMarkupId(true));
        add(contentPagingNavigator.setOutputMarkupId(true));
        add(categoryContentViewOrEditPanel.add(categoryContentViewOrEditPanel.new CategoryContentEditFragment()).setOutputMarkupId(true));
        super.onInitialize();
      }
    }

    private static final String CONTENT_EDIT_TABLE_ID = "contentEditTable";

    private static final String CATEGORY_CONTENT_EDIT_FRAGMENT_MARKUP_ID = "categoryContentEditFragment";

    private static final String CATEGORY_CONTENT_VIEW_OR_EDIT_FRAGMENT_ID = "categoryContentViewOrEditFragment";

    private static final long serialVersionUID = 8640403483040526601L;

    private final ContentEditTable contentEditTable;

    public CategoryContentEditFragment() {
      super(CATEGORY_CONTENT_VIEW_OR_EDIT_FRAGMENT_ID, CATEGORY_CONTENT_EDIT_FRAGMENT_MARKUP_ID, CategoryContentPanel.this, CategoryContentPanel.this.getDefaultModel());
      contentEditTable = new ContentEditTable(CONTENT_EDIT_TABLE_ID, (IModel<Category>) CategoryContentEditFragment.this.getDefaultModel());
    }

    @Override
    protected void onInitialize() {
      add(contentEditTable.add(new TableBehavior().hover()).setOutputMarkupId(true));
      super.onInitialize();
    }
  }

  @AuthorizeAction(action = Action.RENDER, roles = {AppRoles.MANAGER, AppRoles.EMPLOYEE})
  class CategoryContentViewFragment extends Fragment {

    @AuthorizeAction(action = Action.RENDER, roles = {AppRoles.MANAGER, AppRoles.EMPLOYEE})
    class ContentViewTable extends WebMarkupContainer {

      @AuthorizeAction(action = Action.RENDER, roles = {AppRoles.MANAGER, AppRoles.EMPLOYEE})
      class ContentDataviewContainer extends WebMarkupContainer {

        @AuthorizeAction(action = Action.RENDER, roles = {AppRoles.MANAGER, AppRoles.EMPLOYEE})
        class ContentDataview extends DataView<Content> {

          private static final String NAME_ID = "name";

          private static final long serialVersionUID = 2246346365193989354L;

          private static final String CLICK_EVENT = "click";

          private static final String INFO_VALUE = "info";

          private static final String CLASS_ATTRIBUTE = "class";

          private int index = 0;

          protected ContentDataview(final String id, final IDataProvider<Content> dataProvider, final long itemsPerPage) {
            super(id, dataProvider, itemsPerPage);
          }

          @Override
          protected Item<Content> newItem(final String id, final int index, final IModel<Content> model) {
            final Item<Content> item = super.newItem(id, index, model);
            if (this.index == index) {
              item.add(new AttributeModifier(CLASS_ATTRIBUTE, INFO_VALUE));
            }
            return item;
          }

          @Override
          protected void onConfigure() {
            final IModel<Category> model = (IModel<Category>) ContentDataviewContainer.this.getDefaultModel();
            if (!model.getObject().getContents().isEmpty()) {
              categoryContentViewOrEditPanel.removeAll();
              categoryContentViewOrEditPanel.setSelectedModel(Model.of(model.getObject().getContents().get(index)));
              categoryContentViewOrEditPanel.add(categoryContentViewOrEditPanel.new CategoryContentViewFragment()).setOutputMarkupId(true);
            } else {
              categoryContentViewOrEditPanel.removeAll();
              categoryContentViewOrEditPanel.setSelectedModel(Model.of(new Content()));
              categoryContentViewOrEditPanel.add(categoryContentViewOrEditPanel.new CategoryContentViewFragment()).setOutputMarkupId(true);
            }
            super.onConfigure();
          }

          @Override
          protected void populateItem(final Item<Content> item) {
            final IModel<Content> compound = new CompoundPropertyModel<Content>(item.getModelObject());
            item.setModel(compound);
            item.add(new Label(NAME_ID));
            item.add(new AjaxEventBehavior(CLICK_EVENT) {

              private static final long serialVersionUID = 1L;

              @Override
              public void onEvent(final AjaxRequestTarget target) {
                index = item.getIndex();
                categoryContentViewOrEditPanel.setSelectedModel(item.getModel());
                categoryContentViewOrEditPanel.removeAll();
                target.add(contentDataviewContainer.setOutputMarkupId(true));
                target.add(categoryContentViewOrEditPanel.add(categoryContentViewOrEditPanel.new CategoryContentViewFragment()).setOutputMarkupId(true));
              }
            });
          }
        }

        private static final String CONTENT_DATAVIEW_ID = "contentDataview";

        private static final long serialVersionUID = 9165996901588092749L;

        private final ContentDataview contentDataview;

        private final ListDataProvider<Content> contentListDataProvider;

        public ContentDataviewContainer(final String id, final IModel<Category> model) {
          super(id, model);
          contentListDataProvider = new ListDataProvider<Content>() {

            private static final long serialVersionUID = -3261859241046697057L;

            @Override
            protected List<Content> getData() {
              return ((Category) ContentDataviewContainer.this.getDefaultModelObject()).getContents();
            }
          };
          contentDataview = new ContentDataview(CONTENT_DATAVIEW_ID, contentListDataProvider, ITEMS_PER_PAGE);
        }

        @Override
        protected void onInitialize() {
          add(contentDataview.setOutputMarkupId(true));
          super.onInitialize();
        }
      }

      private static final String CATEGORY_CONTENT_VIEW_OR_EDIT_PANEL_ID = "categoryContentViewOrEditPanel";

      private static final String CONTENT_PAGING_NAVIGATOR_MARKUP_ID = "contentPagingNavigator";

      private static final String CONTENT_DATAVIEW_CONTAINER_ID = "contentDataviewContainer";

      private static final long serialVersionUID = -615589482625248433L;

      private final ContentDataviewContainer contentDataviewContainer;

      private final BootstrapPagingNavigator contentPagingNavigator;

      private final CategoryContentViewOrEditPanel categoryContentViewOrEditPanel;

      public ContentViewTable(final String id, final IModel<Category> model) {
        super(id, model);
        contentDataviewContainer = new ContentDataviewContainer(CONTENT_DATAVIEW_CONTAINER_ID, (IModel<Category>) ContentViewTable.this.getDefaultModel());
        contentPagingNavigator = new BootstrapPagingNavigator(CONTENT_PAGING_NAVIGATOR_MARKUP_ID, contentDataviewContainer.contentDataview);
        categoryContentViewOrEditPanel = new CategoryContentViewOrEditPanel(CATEGORY_CONTENT_VIEW_OR_EDIT_PANEL_ID, (IModel<Category>) ContentViewTable.this.getDefaultModel());
      }

      @Override
      protected void onInitialize() {
        add(contentDataviewContainer.setOutputMarkupId(true));
        add(contentPagingNavigator.setOutputMarkupId(true));
        add(categoryContentViewOrEditPanel.add(categoryContentViewOrEditPanel.new CategoryContentViewFragment()).setOutputMarkupId(true));
        super.onInitialize();
      }
    }

    private static final String CONTENT_VIEW_TABLE_ID = "contentViewTable";

    private static final String CATEGORY_CONTENT_VIEW_FRAGMENT_MARKUP_ID = "categoryContentViewFragment";

    private static final String CATEGORY_CONTENT_VIEW_OR_EDIT_FRAGMENT_ID = "categoryContentViewOrEditFragment";

    private static final long serialVersionUID = 8640403483040526601L;

    private final ContentViewTable contentEditTable;

    public CategoryContentViewFragment() {
      super(CATEGORY_CONTENT_VIEW_OR_EDIT_FRAGMENT_ID, CATEGORY_CONTENT_VIEW_FRAGMENT_MARKUP_ID, CategoryContentPanel.this, CategoryContentPanel.this.getDefaultModel());
      contentEditTable = new ContentViewTable(CONTENT_VIEW_TABLE_ID, (IModel<Category>) CategoryContentViewFragment.this.getDefaultModel());
    }

    @Override
    protected void onInitialize() {
      add(contentEditTable.add(new TableBehavior().hover()).setOutputMarkupId(true));
      super.onInitialize();
    }
  }

  private static final long serialVersionUID = 180343040391839545L;

  private static final int ITEMS_PER_PAGE = 10;

  public CategoryContentPanel(final String id, final IModel<Category> model) {
    super(id, model);
  }
}


text:
/* eslint-env jest */
const { mockClient, fetchMock } = require('../mocks/client.mock')
const Module = require('../../src/endpoints/nodes')

describe('endpoints > nodes', () => {
  let endpoint
  beforeEach(() => {
    endpoint = new Module(mockClient)
    fetchMock.reset()
  })

  it('test /v2/nodes', async () => {
    expect(endpoint.isPaginated).toEqual(true)
    expect(endpoint.isBulk).toEqual(true)
    expect(endpoint.supportsBulkAll).toEqual(true)
    expect(endpoint.isLocalized).toEqual(false)
    expect(endpoint.isAuthenticated).toEqual(false)
    expect(endpoint.cacheTime).not.toEqual(undefined)
    expect(endpoint.url).toEqual('/v2/nodes')

    fetchMock.addResponse({ id: 'basic_ore_nodes' })
    let content = await endpoint.get('basic_ore_nodes')
    expect(content.id).toEqual('basic_ore_nodes')
  })
})


text:
"""Model from `Big Transfer (BiT): General Visual Representation Learning`.

The model is pre-trained on ImageNet21k and fine-tuned to ImageNet
(https://arxiv.org/abs/1912.11370). The `logits` key in `representation`
signature contains the ImageNet logits.
"""
from robustness_metrics.common import pipeline_builder
import tensorflow as tf
import tensorflow_hub as hub

def create(dataset, network, size, resolution=None):
  """Returns the BiT pre-trained models with the linear classifier layer."""
  # Mapping the dataset names to the BiT qualifiers.
  supported_datasets = {
      "Imagenet1k": "s",
      "Imagenet21k": "m",
  }
  supported_networks = ["R50", "R101", "R152"]
  supported_sizes = ["x1", "x3", "x4"]

  if size not in supported_sizes:
    raise ValueError(f"Size {size} is not in {supported_sizes!r}.")
  if dataset not in supported_datasets:
    raise ValueError(f"Dataset {dataset} is not in {supported_datasets!r}.")
  if network not in supported_networks:
    raise ValueError(f"Network {network} is not in {supported_networks!r}.")

  root = ("https://tfhub.dev/google/bit/{qualifier}-{network_name}{size}/"
          "ilsvrc2012_classification/1")
  path = root.format(
      qualifier=supported_datasets[dataset],
      network_name=network.lower(),
      size=size)
  module = hub.load(path)

  @tf.function
  def model(features):
    return tf.nn.softmax(module(features["image"]), axis=-1)

  if resolution is not None:
    preprocess_config_fmt = "resize_small({})|central_crop({})|value_range(0,1)"
    preprocess_config = preprocess_config_fmt.format(
        int(1.15 * resolution), resolution)
  elif size == "x4":
    preprocess_config = "resize_small(512)|central_crop(480)|value_range(0,1)"
  else:
    preprocess_config = "resize(384)|value_range(0,1)"
  preprocess_fn = pipeline_builder.get_preprocess_fn(
      preprocess_config, remove_tpu_dtypes=False)

  return model, preprocess_fn


text:
<form action='#' data-app-submit="admin_reports|ebayReportViewSubmit">

<fieldset class='labelsAsBreaks floatLeft ui-widget ui-widget-content ui-corner-all marginRight oneThird borderNone'>
	<legend>eBay Listings CSV Export</legend>
	<input name='query' value="listing-active" type="radio" /> Active Listings
	<input name='query' value="listing-active-fixed" type="radio" /> Active Listings (Fixed Price)
	<input name='query' value="listing-active-store" type="radio" /> Active Listings (Store)
	<input name='query' value="listing-active-auction" type="radio" /> Active Listings (Auction)
	<input name='query' value="listing-all" type="radio" /> All Listings (including ended)
	<input name='query' value="listing-allattempts" type="radio" /> All Listings and Attempts
</fieldset>

<fieldset class='labelsAsBreaks floatLeft ui-widget ui-widget-content ui-corner-all oneThird borderNone'>
	<legend>Event CSV Export</legend>
	<input name='query' value="event-all" type="radio" /> All Events
	<input name='query' value="event-pending" type="radio" /> - Pending/Running
	<input name='query' value="event-error" type="radio" /> - Result: ERROR
	<input name='query' value="event-warning" type="radio" /> - Result: SUCCESS w/WARNING
	<input name='query' value="event-success" type="radio" /> - Result: SUCCESS
	<input name='query' value="event-target-powr.auction" type="radio" /> eBay Powerlister
	<input name='query' value="event-target-ebay.fixed" type="radio" /> eBay Fixed Price
	<input name='query' value="event-target-ebay.auction" type="radio" /> eBay Auctions
	BatchID/Job#: <input name="batchid" size="10" value="" type='number' class='smallInput' />optional
</fieldset>

<fieldset class='marginTop ui-widget ui-widget-content ui-corner-all smallPadding'>

<button  class='applyButton'>View</button>

	Time period/since: <input type='number' class='datepicker' name='since_gmt' />
</fieldset>
</form>

				<button data-app-event="admin_reports|showAdminKPIDBCollectionCreate">Add New Collection</button>
				<button data-app-event="admin_reports|showChartAdd">Explore Data</button>

KPI

	<button data-app-event="admin_reports|handleCollectionMenu"></button>

<select>

	<option id='KPICollectionOptionTemplate' data-bind="useParentData:true; format:collectionAsOptions; extension:admin_reports;"></option>

</select>

	<form onsubmit="return false;" class='labelsAsBreaks'>
	<input type='hidden' name='function' value='sum' />

Graph Type Preview:

			<select name='graph' data-app-event="admin_reports|addTriggerKPIGraphTypeChange" required='required' data-bind="var: chart(graph); format:popVal;">
				<option value='' selected='selected' disabled='disabled'>Choose visualization...</option>
				<option data-image="extensions/admin/images/sample-chart-dashboard.jpg" value='text'>KPI Dashboard (text - no graph)</option>
				<option data-image="extensions/admin/images/sample-chart-area.jpg" value='area'>Area</option>
				<option data-image="extensions/admin/images/sample-chart-areastacked.jpg" value='area.stacked'>Area - Stacked</option>
				<option data-image="extensions/admin/images/sample-chart-areapercent.jpg" value='area.percent'>Area - Stacked Percentage</option>
				<option data-image="extensions/admin/images/sample-chart-horizontalbar.jpg" value='bar'>Horizontal Bar Graph</option>
				<option data-image="extensions/admin/images/sample-chart-horizontalbarstacked.jpg" value='bar.stacked'>Horizontal Bar Graph - Stacked</option>
				<option data-image="extensions/admin/images/sample-chart-horizontalbarpercent.jpg" value='bar.percent'>Horizontal Bar Graph - Stacked Percentage</option>
				<option data-image="extensions/admin/images/sample-chart-verticalcolumn.jpg" value='column'>Vertical Column Graph</option>
				<option data-image="extensions/admin/images/sample-chart-verticalcolumnstacked.jpg" value='column.stacked'>Vertical Column Graph - Stacked</option>
				<option data-image="extensions/admin/images/sample-chart-verticalcolumnpercent.jpg" value='column.percent'>Vertical Column Graph - Stacked Percentage</option>
				<option data-image="extensions/admin/images/sample-chart-areaspline.jpg" value='areaspline'>Area Spline</option>
				<option data-image="extensions/admin/images/sample-chart-line.jpg" value='line'>Line Graph</option>
				<option data-image="extensions/admin/images/sample-chart-pie.jpg" value='pie'>Pie Chart</option>
			</select>
			?

				<select name='period' data-app-event="admin_reports|addTriggerKPIPeriodChange" required='required' data-bind="var: chart(period); format: popVal;">
						<option selected='selected' disabled='disabled'>Timeframe (period)</option>
						<optgroup label='daily' >
							<option value='day.today'>Today</option>
							<option value='day.yesterday'>Yesterday</option>
							<option value='days.7'>Last 7 Days</option>
							<option value='days.10'>Last 10 Days</option>
							<option value='days.14'>Last 14 Days</option>
							<option value='days.21'>Last 21 Days</option>
							<option value='days.28'>Last 28 Days</option>
							<option value='days.90'>Last 90 Days</option>
						</optgroup>

						<optgroup label='weekly' >
							<option value='week.this'>This Week</option>
							<option value='week.tly'>This Week Last Year</option>
							<option value='week.last'>Last Week</option>
							<option value='weeks.1'>This Week + 1 Prior</option>
							<option value='weeks.2'>This Week + 2 Prior</option>
							<option value='weeks.3'>This Week + 3 Prior</option>
							<option value='weeks.4'>This Week + 4 Prior</option>
							<option value='weeks.5'>This Week + 5 Prior</option>
							<option value='weeks.6'>This Week + 6 Prior</option>
							<option value='weeks.7'>This Week + 7 Prior</option>
							<option value='weeks.8'>This Week + 8 Prior</option>

						</optgroup>

						<optgroup label='monthly' >
							<option value='month.this'>This Month</option>
							<option value='month.tly'>This Month Last Year</option>
							<option value='month.last'>Last Month</option>
							<option value='months.1'>This Month + 1 Prior</option>
							<option value='months.2'>This Month + 2 Prior</option>
							<option value='months.3'>This Month + 3 Prior</option>
						</optgroup>

						<optgroup label='quarterly' >
							<option value='quarter.this'>This Quarter</option>
							<option value='quarter.tly'>This Quarter Last Year</option>
							<option value='quarter.last'>Last Quarter</option>
						</optgroup>

						<optgroup label='Annual'>
							<option value='ytd.this'>Year-To-Date</option>
							<option value='ytd.last'>Last Year</option>
						</optgroup>
					</select>
				?

				<select name='grpby' disabled='disabled' required='required' data-bind="var: chart(grpby); format:popVal;">
					<option selected='selected' disabled='disabled' value=''>units of time</option>
					<option value='none'>None (Merge Datasets into a single value)</option>
					<option value='day'>Date: Day (maximum detail level)</option>
					<option value='week'>Date: Week (1-52 values per year)</option>
					<option value='month'>Date: Month (1-12 values per year)</option>
					<option value='quarter'>Date: Quarter (1-4 values per year)</option>
					<option value='dow'>Day of Week (Mon - Sun possible values)</option>
				</select>
				?

Columns:

					<input type='radio' name='dataColumns' value='fixed' data-app-event="admin_reports|addTriggerKPIDataColumnsChange" data-bind="var:chart(dataColumns); format:popVal;" />
					User Specified : choose one or more columns individually.
					?

					<input type='radio' name='dataColumns' value='dynamic' data-app-event="admin_reports|addTriggerKPIDataColumnsChange" data-bind="var:chart(dataColumns); format:popVal;" />
					Dynamic List : automatically use all possible columns from preset lists.
					?

					Data Point:
					?

				<input type='radio' name='column' value='gms' data-bind="var:chart(column); format:popVal;" /> Gross Sales
				<input type='radio' name='column' value='distinct' data-bind="var:chart(column); format:popVal;" /> # Orders
				<input type='radio' name='column' value='total' data-bind="var:chart(column); format:popVal;" /> # Units Sold

			Dynamic Lists
			<select name='ddataset' data-bind="var:chart(ddataset); format:popVal;">
				<option selected='selected' disabled="disabled" value=''>Dynamic List</option>
				<option value='PRTS'>Sales By Partition</option>
				<option value='SCHEDULES'>Sales By Pricing Schedules</option>
				<option value='OGMS' >Overall Gross Merchandise Sales</option>
				<option value='DOMAINS' >By Domains</option>
				<option value='TAGS'>By Tags</option>
				<option value='MARKETS'>By Marketplace/Integrations</option>
			</select>

			User Specified Columns
			<select name='datasetGrp' data-app-event="admin_reports|addTriggerKPIDatasetChange"  data-bind="var:chart(datasetGrp); format:popVal;">
				<option value='' disabled='disabled' selected='selected'>choose data column</option>
				<option value='OVERALL'>All Domains/Partitions</option>
				<option value='COUPON'>Coupon</option>
				<option value='DOMAIN'>Domain</option>
				<option value='MANUFACTURER'>Manufacturer</option>
				<option value='MARKETPLACE'>Marketplace / Syndication</option>
				<option value='PARTITION'>Partition</option>
				<option value='PRODUCT_TAG'>Product Tag</option>
				<option value='SUPPLIER'>Supplier</option>
				<option value='OTHER'>Other (affiliate, crm, etc)</option>
			</select>
			?

Available Axis Points:

Selected Axis Points/Order:

			<fieldset class='displayNone marginTop' data-app-role='saveInputsFieldset'>
				<legend>Graph Name & Location</legend>

<input type='text' size='40' placeholder='graph title' required='required' name='title' data-bind="var: chart(title); format:popVal;" /> ?

<select name='collection' required='required' >
					<option selected='selected' disabled='disabled'>collection/graph location</option>

					<optgroup label="KPI" data-bind="var: users(@COLLECTIONS); format:processList; loadsTemplate:KPICollectionOptionTemplate;">
					</optgroup>

				</select>
				?

			</fieldset>

		<button class='floatRight' data-app-event="admin_reports|execAdminKPIDBCollectionUpdate">Save Graph to Collection</button>
		<button class='floatRight' data-app-event="admin_reports|showKPIGraphPreview">Show Graph</button>

</form>

	Title
	Graph Type
	Period/Timeframe

			<button data-app-event="admin_reports|showChartRemove">delete</button>
			<button data-app-event="admin_reports|showChartUpdate">edit</button>

Reports

Sales Reports

Inventory Reports

eBay and Listings Report

Recently Run Reports

	Job ID
	Job Name

Sales/Order Reporting

Find out what products are selling and what's not.

Order Detail:

	Today |
	Yesterday |
	This Month

Order Summary:
	Today |
	This Month

Sales SKU Ranking:
	Today |
	This Month

More Options

Listing Reports

Take a look at how many marketplaces each of your products is currently in.

eBay Active Listing w/Detail

Marketplace Disposition Report

More Options

			<form onsubmit="return false">

				<fieldset class='twoColumn labelsAsBreaks noPadOrMargin'>
					<legend>Report Type</legend>

					<input type="radio" value="SALES" name="REPORT" checked="checked" /> Order Details ?

					<input type="radio" value="SALE_SUMMARY" name="REPORT" /> Order Summary ?

					<input type="radio" value="SALES_SKU_RANK" name="REPORT" /> Sales by SKU Ranking ?

					<input type="radio" value="SALES_PRODUCT_RANK" name="REPORT" /> Sales by Product Ranking ?

					<input type="radio" value="SALES_SOG_RANK" name="REPORT" /> Sales by Store Option Group Ranking ?

					<input type="radio" value="SALES_BY_SCHEDULE" name="REPORT" /> Sales by Pricing Schedule ?

				</fieldset>

				<fieldset class='twoColumn column2 labelsAsBreaks noPadOrMargin'>
					<legend>Report Options</legend>

						Report by:
						<select name="key" required='required'>
							<option value="CREATED">Created Date</option>
							<option value="PAID">Paid Date</option>
							<option value="SHIP">Shipped Date</option>
						</select>

					<input type="checkbox" name="include_deleted" /> Gross Sales: Include Cancelled Orders

						Dates
						<select name='PERIOD' data-panel-selector=".formPeriodRange" data-input-change='show-panel' required='required'>
							<option value=''>please choose</option>
							<option value="today">Today Only</option>
							<option value="thismonth">Month to Date</option>
							<option value="4week">Last 4 Weeks</option>
							<option value="all">All Orders</option>
							<option value='BYMONTH' data-show-panel='formPeriodRange-BYMONTH'>by month</option>
							<option value='BYINVOICE' data-show-panel='formPeriodRange-BYINVOICE'>invoice range</option>
							<option value='BYTIMESTAMP' data-show-panel='formPeriodRange-BYTIMESTAMP'>Date range</option>
						</select>

		<select name="month">
			<option value="1">January</option>
			<option value="2">February</option>
			<option value="3">March</option>
			<option value="4">April</option>
			<option value="5">May</option>
			<option value="6">June</option>
			<option value="7">July</option>
			<option value="8">August</option>
			<option value="9">September</option>
			<option value="10">October</option>
			<option value="11">November</option>
			<option value="12">December</option>
		</select>
		<select name="year">
			<option value="2007">2007</option>
			<option value="2008">2008</option>
			<option value="2009">2009</option>
			<option value="2010">2010</option>
			<option value="2011">2011</option>
			<option value="2012">2012</option>
			<option value="2013">2013</option>
			<option value="2014">2014</option>
			<option selected="selected" value="2015">2015</option>
			<option value="2014">2016</option>
			<option value="2014">2017</option>
		</select>

			Begins <input type="text" name="begints" size="20" class='datepicker' >
			Ends <input type="text" name="endts" size="20" class='datepicker' >

			First Invoice: <input type="text" name="startinv" maxlength="15" size="15"> ####-##-####
			Last Invoice: <input type="text" name="endinv" maxlength="15" size="15"> ####-##-####

				</fieldset>

<button data-app-click="admin_reports|execAdminReportCreate" class='applyButton'>Build Report</button>

			</form>

		SKU Summary Reporting
		?

Quick Reports

			Recent changes

			All skus (brief)

			Zero available qty

			All skus (detailed)

Custom Reports

			Add custom report

		Inventory Detail Records
		<span class='toolTip' title="The purpose of an Inventory detail is to
		track each unique instance of SKU, quantity.
		For example if a store had a warehouse with the same SKU (Stock
		Keeping Unit) at two locations in a warehouse each would have their
		own Inventory Detail.

		Every inventory detail record has a BASETYPE field which indicates the type of inventory detail it
		contains common BASETYPEs are SIMPLE, SUPPLIER, WMS, PICK, DONE.
		Each order that is placed creates a PICK reservation, which is
		ultimately convert into a DONE record when the physical inventory is
		pulled from the shelf.  (This makes keeping accurate on-shelf
		quantites possible).  In the case of SIMPLE inventory records which
		are just +/- counters the quantities are automatically decremented
		from SIMPLE inventory the moment the order is placed (so no advanced
		item routing is necessary/possible -- hence the name 'SIMPLE').
		Inventory detail records are automatically summed to create a SKU summary
		that is used for decision logic in syndication, and shopping cart checkouts.
		">?

Quick Reports

			Recent changes

			All skus (brief)

			Simple Inventory

			WMS Inventory

			Supplier Inventory

			Pick Inventory

Custom Reports

			Add custom report

		<button data-app-click="admin_batchjob|showReport" class='displayNone applyButton' data-text='false' data-icon-primary='ui-icon-image'>View Report</button>
		<button data-app-click="admin_batchjob|showBatchDetail" class='applyButton' data-text='false' data-icon-primary='ui-icon-info'>Batch Details</button>

<form onsubmit='return false'>

Step 1: Select Product

			<fieldset data-app-role='pickerContainer'></fieldset>

Step 2: Specify Filters and Formats

			<fieldset class='labelsAsBreaks marginBottom'>
				<legend>Report</legend>
				<input type='hidden' name='BATCH_EXEC' value='' data-bind="var: report(BATCH_EXEC); format:popVal;" />

					Title
					<input type='text' name='TITLE' value='' size='40' maxlength="80" />

					<input type='checkbox' name='PRIVATE' class='applyAnycb' checked='checked' />
					Private
					?

					Attributes
					<select name='headers'>
						<option value='ALL'>All</option>
						<option value='ORDER'>Order</option>
						<option value='ROUTE'>Route</option>
						<option value='SUPPLIER'>Supplier</option>
						<option value='WMS'>WMS</option>
					</select>

			</fieldset>

			<fieldset class='marginBottom'>
				<legend>Filter</legend>

					By
				<select name='summary' data-input-change="panel-selector" data-panel-selector=".reportsInventorySummaryPanel">
					<option value=''>All</option>
					<option value='AVAILABLE' data-show-panel='reportsInventorySummaryINVStatus'>Available</option>
					<option value='ONSHELF' data-show-panel='reportsInventorySummaryINVStatus'>On shelf</option>
					<option value='SUPPLIER' data-show-panel='reportsInventorySummarySupplier'>Supplier</option>
					<option value='TS' data-show-panel='reportsInventorySummaryTS'>Timestamp</option>
					<option value='MODIFIED_TS' data-show-panel='reportsInventorySummaryTS'>Modified timestamp</option>
					<option value='PID' data-show-panel='reportsInventorySummaryPID'>PID</option>
					<option value='ORDERID' data-show-panel='reportsInventorySummaryOrderID'>Our orderid</option>
					<option value='PICK_ROUTE' data-show-panel='reportsInventorySummaryPickRoute'>Pick route</option>
				</select>

					where quantity is
					<select name='operand'>
						<option value='LT'>Less than</option>
						<option value='EQ'>Equal to</option>
						<option value='GT'>Greater than</option>
					</select>

						#
						<input type='number' name='operand_match' step='1' min='0' size='5' class='smallInput' />

						Vendor
						<input type='text' name='SUPPLIER' size='6' class='smallInput' />

				Time period/since: <input type='number' class='datepicker' name='TS' />

				PID: <input type='text' name='PID' size='20' />

				Order ID: <input type='text' name='ORDERID' size='20' />

				Route: <input type='text' name='PICK_ROUTE' size='20' />

			</fieldset>

Step 3: Make It So

		<button data-app-event="admin_reports|adminInventoryReportSaveExec">Save as Report</button>

</form>


text:
<!doctype html>

<meta charset="utf-8">
<title>Untitled Document</title>

Login and Register


text:
#ifndef TINY_HPP
#define TINY_HPP
#include "common-header.hpp"

struct none {};

struct tiny_tag {};

template <class T0 = none,
          class T1 = none,
          class T2 = none
          >
struct tiny {
    typedef tiny type;
    typedef tiny_tag tag;
    typedef T0 t0;
    typedef T1 t1;
    typedef T2 t2;
};

template <class Tiny, class Pos>
struct tiny_iterator {
    typedef mpl::random_access_iterator_tag category;
    typedef tiny_iterator<Tiny, Pos> type;
};

namespace boost { namespace mpl {

template <class Tiny, class Pos>
struct next<tiny_iterator<Tiny, Pos> > {
    typedef tiny_iterator<Tiny, typename mpl::next<Pos>::type> type;
};

template <class Tiny, class Pos>
struct prior<tiny_iterator<Tiny, Pos> > {
    typedef tiny_iterator<Tiny, typename mpl::prior<Pos>::type> type;
};

}}/* end of namespace boost::mpl */

template <class Tiny, long N>
struct tiny_at;

template <class Tiny>
struct tiny_at<Tiny, 0> {
    typedef typename Tiny::t0 type;
};

template <class Tiny>
struct tiny_at<Tiny, 1> {
    typedef typename Tiny::t1 type;
};

template <class Tiny>
struct tiny_at<Tiny, 2> {
    typedef typename Tiny::t2 type;
};

namespace boost { namespace mpl {

//template <class T0, class T1, class T2, class Pos>
//struct at<tiny<T0, T1, T2>, Pos>
//    : tiny_at<tiny<T0, T1, T2>, Pos::value> {
//};

template <>
struct at_impl<tiny_tag> {
    template <class Tiny, class N>
    struct apply: tiny_at<Tiny, N::value> {};
};

template <class Tiny, class Pos>
struct deref<tiny_iterator<Tiny, Pos> >
    : mpl::at<Tiny, Pos> {
};

template <class Tiny, class Pos, class N>
struct advance<tiny_iterator<Tiny, Pos>, N> {
    typedef
    typename tiny_iterator<
                Tiny,
                typename mpl::plus<Pos, N>::type
             >::type type;
};

template <class Tiny, class Pos1, class Pos2>
struct distance<
    tiny_iterator<Tiny, Pos1>,
    tiny_iterator<Tiny, Pos2>
    >
    : mpl::minus<Pos2, Pos1>{
};

template <>
struct begin_impl<tiny_tag> {
    template <class Tiny>
    struct apply {
        typedef tiny_iterator<Tiny, mpl::int_<0> > type;
    };
};

}}/* end of namespace boost::mpl */

template <class T0, class T1, class T2>
struct tiny_size
    : mpl::int_<3> {
};

template <class T0, class T1>
struct tiny_size<T0, T1, none>
    : mpl::int_<2> {
};

template <class T0>
struct tiny_size<T0, none, none>
    : mpl::int_<1> {
};

template <>
struct tiny_size<none, none, none>
    : mpl::int_<0> {
};

namespace boost { namespace mpl {

template <>
struct size_impl<tiny_tag> {
    template <class Tiny>
    struct apply
        :tiny_size<
            typename Tiny::t0,
            typename Tiny::t1,
            typename Tiny::t2
        > {
    };
};
template <>
struct end_impl<tiny_tag> {
    template <class Tiny>
    struct apply {
        typedef typename tiny_iterator<
                Tiny,
                typename tiny_size<
                        typename Tiny::t0,
                        typename Tiny::t1,
                        typename Tiny::t2
                        >::type
                >::type  type;
    };
};

template <>
struct clear_impl<tiny_tag> {
    template <class Tiny>
    struct apply
        : tiny<> {
    };
};

template <>
struct push_front_impl<tiny_tag> {
    template <class Tiny, class T>
    struct apply
        : tiny<T, typename Tiny::t0, typename Tiny::t1> {
    };
};

}} /* end of namespace boost::mpl */

template <class Tiny, class T, int Size>
struct tiny_push_back;

template <class Tiny, class T>
struct tiny_push_back<Tiny, T, 0>
    : tiny<T>{
};

template <class Tiny, class T>
struct tiny_push_back<Tiny, T, 1>
    : tiny<typename Tiny::t0, T> {
};

template <class Tiny, class T>
struct tiny_push_back<Tiny, T, 2>
    : tiny<typename Tiny::t0, typename Tiny::t1, T> {
};

namespace boost { namespace mpl {
template <>
struct push_back_impl<tiny_tag> {
    template <class Tiny, class T>
    struct apply
        : tiny_push_back<
            Tiny,
            T,
            mpl::size<Tiny>::value
        >{
    };
};
}}/* end of namespace boost::mpl */

namespace test_tiny {

typedef tiny<short, unsigned, int> t1;
typedef mpl::deref<mpl::begin<t1>::type>::type head;
static_assert(
        std::is_same<
            head,
            short
        >::value,
        "begin");

typedef mpl::next<mpl::begin<t1>::type>::type body;
static_assert(
        std::is_same<
            mpl::deref<body>::type,
            unsigned
        >::value,
        "next");

/* test for fold */

typedef tiny<mpl::int_<1>, mpl::int_<2>, mpl::int_<3> > t2;
typedef mpl::fold<t2, mpl::int_<0>, mpl::plus<_, _> >::type t3;
static_assert(
        mpl::equal_to<
            t3,
            mpl::int_<6>
        >::value,
        "fold");

/* test for equal */
static_assert(
        mpl::equal<
            t1,
            tiny<short, unsigned, int>
        >::value,
        "equal");

/* test for at */
static_assert(
        std::is_same<
            mpl::at_c<t1, 1>::type,
            unsigned
        >::value,
        "at");
} /* end of namespace test_tiny */
#endif


text:
import { StyleSheet } from 'react-native';

/**
 * LightSettingsForm styles
 */
const palette = {
  background: '#FFF',
  settings: '#8E8E93',
  lines: '#CECED2',
};

const sizes = {
  primaryFontSize: 17,
  headingFontSize: 13,
  fieldHeight: 44,
};

const styles = StyleSheet.create({
  blockHeading: {
    top: 20,
    paddingHorizontal: 20,
    height: sizes.fieldHeight,
  },
  textHeading: {
    color: palette.settings,
    fontSize: sizes.headingFontSize,
  },
  blockFields: {
    backgroundColor: palette.background,
    borderBottomWidth: 0.5,
    borderColor: palette.lines,
    borderTopWidth: 0.5,
  },
  textInput: {
    height: sizes.fieldHeight,
    paddingHorizontal: 20,
  },
  picker: {
    height: sizes.fieldHeight,
  },
  fieldDivider: {
    backgroundColor: palette.lines,
    height: 0.5,
    marginLeft: 20,
  },
  blockSelect: {
    alignItems: 'center',
    backgroundColor: palette.background,
    borderBottomWidth: 0.5,
    borderColor: palette.lines,
    borderTopWidth: 0.5,
    flexDirection: 'row',
    height: sizes.fieldHeight,
    justifyContent: 'space-between',
    paddingHorizontal: 20,
  },
  textSelect: {
    fontSize: sizes.primaryFontSize,
  },
  buttonSelectItem: {
    alignItems: 'center',
    flexDirection: 'row',
  },
  iconSelectItem: {
    marginLeft: 8,
    top: 2,
  },
  textItemSelected: {
    color: palette.settings,
    fontSize: sizes.primaryFontSize,
  },
});

export default styles;


text:
//******************************************************************************************************
//  HistoriansUserControl.cs - Gbtc
//
//  Copyright © 2010, Grid Protection Alliance.  All Rights Reserved.
//
//  Licensed to the Grid Protection Alliance (GPA) under one or more contributor license agreements. See
//  the NOTICE file distributed with this work for additional information regarding copyright ownership.
//  The GPA licenses this file to you under the Eclipse Public License -v 1.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.opensource.org/licenses/eclipse-1.0.php
//
//  Unless agreed to in writing, the subject software distributed under the License is distributed on an
//  "AS-IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. Refer to the
//  License for the specific language governing permissions and limitations.
//
//  Code Modification History:
//  ----------------------------------------------------------------------------------------------------
//  07/09/2010 - Mehulbhai P Thakkar
//       Generated original version of source code.
//
//******************************************************************************************************

using System;
using System.Collections.Generic;
using System.Windows;
using openPDCManager.Data;
using openPDCManager.Data.Entities;
using openPDCManager.Data.ServiceCommunication;
using openPDCManager.ModalDialogs;
using openPDCManager.Utilities;

namespace openPDCManager.UserControls.CommonControls
{
    public partial class HistoriansUserControl
    {
        #region [ Members ]

        WindowsServiceClient serviceClient;

        #endregion

        #region [ Methods ]

        void Initialize()
        {
            serviceClient = ((App)Application.Current).ServiceClient;
            if (((App)Application.Current).Principal.IsInRole("Administrator, Editor"))
            {
                ButtonSave.IsEnabled = true;
                ButtonInitialize.IsEnabled = true;
            }
            else
            {
                ButtonSave.IsEnabled = false;
                ButtonInitialize.IsEnabled = false;
            }
        }

        void SendInitialize()
        {
            SystemMessages sm;
            try
            {
                if (serviceClient != null && serviceClient.Helper.RemotingClient.CurrentState == TVA.Communication.ClientState.Connected)
                {
                    string result = CommonFunctions.SendCommandToWindowsService(serviceClient, "Initialize " + TextBlockRuntimeID.Text);
                    sm = new SystemMessages(new Message() { UserMessage = result, SystemMessage = "", UserMessageType = MessageType.Success }, ButtonType.OkOnly);
                }
                else
                    sm = new SystemMessages(new Message() { UserMessage = "Application is disconnected", SystemMessage = "Connection String: " + ((App)Application.Current).RemoteStatusServiceUrl, UserMessageType = MessageType.Error }, ButtonType.OkOnly);

            }
            catch (Exception ex)
            {
                CommonFunctions.LogException(null, "WPF.SendInitialize", ex);
                sm = new SystemMessages(new Message() { UserMessage = "Failed to Send Initialize Command", SystemMessage = ex.Message, UserMessageType = MessageType.Error },
                        ButtonType.OkOnly);
            }
            sm.Owner = Window.GetWindow(this);
            sm.WindowStartupLocation = WindowStartupLocation.CenterOwner;
            sm.ShowPopup();
        }

        void GetHistorians()
        {
            try
            {
                ListBoxHistorianList.ItemsSource = CommonFunctions.GetHistorianList(null, m_nodeID);
                if (ListBoxHistorianList.Items.Count > 0 && ListBoxHistorianList.SelectedIndex < 0)
                    ListBoxHistorianList.SelectedIndex = 0;
            }
            catch (Exception ex)
            {
                CommonFunctions.LogException(null, "WPF.GetHistorianList", ex);
                SystemMessages sm = new SystemMessages(new Message() { UserMessage = "Failed to Save Historian Information", SystemMessage = ex.Message, UserMessageType = MessageType.Error },
                        ButtonType.OkOnly);
                sm.Owner = Window.GetWindow(this);
                sm.ShowPopup();
            }
        }

        void GetNodes()
        {
            try
            {
                ComboBoxNode.ItemsSource = CommonFunctions.GetNodes(null, true, false);
                if (ComboBoxNode.Items.Count > 0)
                    ComboBoxNode.SelectedIndex = 0;
            }
            catch (Exception ex)
            {
                CommonFunctions.LogException(null, "WPF.GetNodes", ex);
                SystemMessages sm = new SystemMessages(new Message() { UserMessage = "Failed to Retrieve Nodes", SystemMessage = ex.Message, UserMessageType = MessageType.Error },
                        ButtonType.OkOnly);
                sm.Owner = Window.GetWindow(this);
                sm.ShowPopup();
            }
        }

        void SaveHistorian(Historian historian, bool isNew)
        {
            try
            {
                bool continueSave = true;

                if (!isNew)
                {
                    if ((m_typeName == "HistorianAdapters.LocalOutputAdapter" && historian.TypeName != m_typeName) ||
                        (m_isLocal && !historian.IsLocal))
                    {
                        SystemMessages sm = new SystemMessages(new Message() { UserMessage = "You are changing your historian type.", SystemMessage = "You are changing your historian type from an in-process local historian to another historian provider. Please note that once the changes are applied, any customizations you may have made to the in-process local historian in the openPDC configuration file will be lost." + Environment.NewLine + "Do you want to continue?", UserMessageType = MessageType.Confirmation }, ButtonType.YesNo);
                        sm.Closed += new EventHandler(delegate(object popupWindow, EventArgs eargs)
                        {
                            if ((bool)sm.DialogResult)
                                continueSave = true;
                            else
                                continueSave = false;
                        });
                        sm.Owner = Window.GetWindow(this);
                        sm.ShowPopup();
                    }
                }

                if (continueSave)
                {
                    string result = CommonFunctions.SaveHistorian(null, historian, isNew);
                    SystemMessages sm = new SystemMessages(new Message() { UserMessage = result, SystemMessage = string.Empty, UserMessageType = MessageType.Success },
                            ButtonType.OkOnly);
                    sm.Owner = Window.GetWindow(this);
                    sm.ShowPopup();
                    GetHistorians();
                    //make this newly added or updated item as default selected. So user can click initialize right away.
                    ListBoxHistorianList.SelectedItem = ((List<Historian>)ListBoxHistorianList.ItemsSource).Find(c => c.Acronym == historian.Acronym);
                }
            }
            catch (Exception ex)
            {
                CommonFunctions.LogException(null, "WPF.SaveHistorian", ex);
                SystemMessages sm = new SystemMessages(new Message() { UserMessage = "Failed to Save Historian Information", SystemMessage = ex.Message, UserMessageType = MessageType.Error },
                        ButtonType.OkOnly);
                sm.Owner = Window.GetWindow(this);
                sm.ShowPopup();
            }
        }

        void DisplayRuntimeID()
        {
            TextBlockRuntimeID.Text = CommonFunctions.GetRuntimeID(null, "Historian", m_historianID);
        }

        #endregion
    }
}


text:
#include <windows.h>
#include <wincon.h>
#include "Backdrop.h"
#include "Utils.h"

HINSTANCE ghInstance;

COLORREF GetColorFromDialog(void);

/** Application entry point */
int WINAPI WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR lpszCmdLine, int nCmdShow){
	HWND       backdropWindow;
	MSG        msg;
	LPTSTR     cmdLine;
	COLORREF   backgroundColor;

	ghInstance = hInstance;

	/* Check if we can attach to the console; if we can't we're running in the GUI and show the
	** colour picker; see http://stackoverflow.com/questions/510805
	** Note: AttachConsole only appears in Win32 v5.1 (XP) or higher
	*/
	if (AttachConsole((DWORD)-1) == 0)
	{
		backgroundColor = GetColorFromDialog();
	}
	else
	{
		/* Parse command line */
		cmdLine = GetCommandLine();
		backgroundColor = RgbTripleToColorref(cmdLine);
	}

	backdropWindow = CreateBackdropWindow(backgroundColor);
	ShowWindow(backdropWindow, nCmdShow);
	UpdateWindow(backdropWindow);

	/* Message loop */
	while (GetMessage(&msg, (HWND)NULL, 0, 0))
	{
		TranslateMessage(&msg);
		DispatchMessage(&msg);
	}
	DestroyBackdropWindow();
	ExitProcess(msg.wParam);
}

/** Displays the common colour chooser dialog and returns the selected value */
COLORREF GetColorFromDialog(void)
{
	COLORREF acrCustClr[16] = {
		RGB(0xFF, 0xFF, 0xFF), RGB(0xEF, 0xEF, 0xEF),
		RGB(0xDF, 0xDF, 0xDF), RGB(0xCF, 0xCF, 0xCF),
		RGB(0xBF, 0xBF, 0xBF), RGB(0xAF, 0xAF, 0xAF),
		RGB(0x9F, 0x9F, 0x9F), RGB(0x8F, 0x8F, 0x8F),
		RGB(0x7F, 0x7F, 0x7F), RGB(0x6F, 0x6F, 0x6F),
		RGB(0x5F, 0x5F, 0x5F), RGB(0x4F, 0x4F, 0x4F),
		RGB(0x3F, 0x3F, 0x3F), RGB(0x2F, 0x2F, 0x2F),
		RGB(0x1F, 0x1F, 0x1F), RGB(0x0F, 0x0F, 0x0F)
	};
	CHOOSECOLOR colorChooser;

	colorChooser.lStructSize = sizeof(colorChooser);
	colorChooser.hwndOwner = NULL;
	colorChooser.hInstance = NULL;
	colorChooser.rgbResult = RGB(0xFF, 0xFF, 0xFF);
	colorChooser.lpCustColors = acrCustClr;
	colorChooser.Flags = CC_RGBINIT;
	colorChooser.lCustData = 0L;
	colorChooser.lpfnHook = NULL;
	colorChooser.lpTemplateName = NULL;

	if (ChooseColor(&colorChooser))
	{
		return colorChooser.rgbResult;
	}
	else
	{
		ExitProcess(0);
	}
}


text:
require "bundler/setup"
require "indexter"
require "active_record"

ActiveRecord::Base.establish_connection adapter: "sqlite3", database: ":memory:"

require "support/schema"

RSpec.configure do |config|
  # Enable flags like --only-failures and --next-failure
  config.example_status_persistence_file_path = ".rspec_status"

  config.expect_with :rspec do |c|
    c.syntax = :expect
  end

end


text:
package stonehorse.candy;

import org.junit.Test;

import java.util.function.BiFunction;
import java.util.function.Function;
import java.util.function.Predicate;

import static junit.framework.TestCase.assertEquals;
import static junit.framework.TestCase.assertFalse;
import static junit.framework.TestCase.fail;
import static org.junit.Assert.assertSame;
import static org.junit.Assert.assertTrue;

public class FunctionsTest {
    @Test
    public void testPartial() {
        assertEquals("lue", Functions.function((BiFunction<String, Integer, String>) String::substring, "Value").apply(2));

        try {
            BiFunction<String, String, String> nil = null;
            Functions.function(nil, "Value");
            fail();
        } catch (NullPointerException e) {
        }

        assertEquals("VALUE", Functions.supplier((Function<String, String>) String::toUpperCase, "value").get());
        try {
            Function<String, String> nil = null;
            Functions.supplier(nil, "Value");
            fail();
        } catch (NullPointerException e) {
        }

    }

    @Test
    public void testComplement() {

        assertFalse(Functions.complement(v -> true).apply("Value"));
        assertTrue(Functions.complement(v -> false).apply("Value"));
        try {
            Predicate<String> nil = null;
            Functions.complement(nil).apply("Value");
            fail();
        } catch (NullPointerException e) {
        }

    }

    @Test
    public void testCompose() {
        Function<String,String> trim=String::trim;
        Function<String,Integer> len=String::length;
        Function<String, String> nil = null;
assertEquals(Integer.valueOf(13), Functions.compose( trim, len).apply(" heading Space"));
        try{
            Functions.compose(nil, trim);
            fail();
        }catch(NullPointerException e){}
        try{
            Functions.compose( trim, nil);
            fail();
        }catch(NullPointerException e){}
    }

    @Test
    public void testIdentity() {
        Object o =new Object();
        assertSame(o, Functions.identity().apply(o));

    }
}


text:
<?php

/* SUHGestionBundle:AffichageEtudiants:test.html.twig */
class __TwigTemplate_e08f43b5f2634a46d14d0448e99e6e4bd7b761b17e50b5a947b5d6b79ae3be24 extends Twig_Template
{
    public function __construct(Twig_Environment $env)
    {
        parent::__construct($env);

        $this->parent = false;

        $this->blocks = array(
        );
    }

    protected function doDisplay(array $context, array $blocks = array())
    {
        // line 1
        if (array_key_exists("tt", $context)) {
            // line 2
            echo "    ";
            echo $this->env->getExtension('dump')->dump($this->env, $context, (isset($context["tt"]) ? $context["tt"] : $this->getContext($context, "tt")));
            echo "
";
        }
        // line 4
        echo "ok";
    }

    public function getTemplateName()
    {
        return "SUHGestionBundle:AffichageEtudiants:test.html.twig";
    }

    public function isTraitable()
    {
        return false;
    }

    public function getDebugInfo()
    {
        return array (  27 => 4,  21 => 2,  19 => 1,);
    }
}