text:
var requires = [
    "root/externallib/text!root/plugins/messages/messages.html",
    "root/externallib/text!root/plugins/messages/recent.html",
    "root/externallib/text!root/plugins/messages/conversation.html",
    "root/externallib/text!root/plugins/messages/contact.html",
    "root/externallib/text!root/plugins/messages/contacts.html",
    "root/externallib/text!root/plugins/messages/search.html",
    "root/externallib/text!root/plugins/messages/bubbles.html"
];

define(requires, function (messagesTpl, recentTpl, conversationTpl, contactTpl, contactsTpl, searchTpl, bubblesTpl) {

    var plugin = {
        settings: {
            name: "messages",
            type: "general",
            icon: "plugins/messages/icon.png",
            menuURL: "#messages",
            lang: {
                component: "core"
            }
        },

        routes: [
            ["messages", "messages", "showMessages"],
            ["messages/conversation/:userId", "messages_conversation", "showConversation"],
            ["messages/contacts", "messages_contacts", "showContacts"],
            ["messages/contact/:userId", "messages_contact", "showContact"]
        ],

        templates: {
            "messages": {
                html: messagesTpl
            },
            "recent": {
                html: recentTpl
            },
            "conversation": {
                html: conversationTpl
            },
            "contact": {
                html: contactTpl
            },
            "contacts": {
                html: contactsTpl
            },
            "search": {
                html: searchTpl
            },
            "bubbles": {
                html: bubblesTpl
            }
        },

        wsPrefix: "",

        recentContactMessages: [],

        recentContactsIds: {},

        blockedUsersIds: {},

        pollingInterval: 5000,

        /**
         * Determines is the plugin is visible.
         * It may check Moodle remote site version, device OS, device type, etc...
         * This function is called when a alink to a plugin functinality is going to be rendered.
         *
         * @return {bool} True if the plugin is visible for the site and device
         */
        isPluginVisible: function() {
            // The plugin is visible either if is available the remote service for pulling messages or
            // the platform support Push messages.

            var visible = false;

            if (MM.util.wsAvailable('local_mobile_core_message_get_messages')) {
                MM.plugins.messages.wsPrefix = "local_mobile_";
                visible = true;
            } else if (MM.util.wsAvailable('core_message_get_messages')) {
                visible = true;
            }

            return visible;
        },

        /**
         * Messages plugin main entry point for the user
         * It may display the button for enable messages or the list of messages received
         *
         */
        showMessages: function() {
            var html, tpl;

            $('a[href="#messages"]').addClass('loading-row');

            // Checks if all the messaging WS are available.
            if (MM.util.wsAvailable('core_message_get_contacts') ||
                    MM.util.wsAvailable(MM.plugins.messages.wsPrefix + 'core_message_get_contacts')) {
                MM.panels.showLoading('center');
                MM.panels.showLoading('right');
                MM.plugins.messages._renderRecentMessages();
            } else {
                MM.panels.showLoading('center');
                MM.panels.hide("right", "");
                MM.Router.navigate('');
                MM.plugins.messages._renderMessageList();
            }
        },

        showConversation: function(userId) {

            var userName = "";
            var userPicture = "img/userimage.png";
            var user = MM.db.get('users', MM.config.current_site.id + "-" + userId);
            if (user) {
                userName = user.get("fullname");
                if (user.get("profileimageurl")) {
                    userPicture = user.get("profileimageurl");
                }
            }

            var data = {
                userName: userName
            };

            MM.panels.show('right', "", {title: userName});
            MM.panels.showLoading('right');

            var params = {
                useridto: MM.config.current_site.userid,
                useridfrom: userId,
                type: 'conversations',
                read: 0,
                newestfirst: 1,
                limitfrom: 0,
                limitnum: 50
            };

            // First, messages received.
            MM.plugins.messages._getRecentMessages(
                params,
                function(messagesReceived) {
                    // Now, messages sent.
                    params.useridto = userId;
                    params.useridfrom = MM.config.current_site.userid;

                    MM.plugins.messages._getRecentMessages(
                        params,
                        function(messagesSent) {
                            MM.plugins.messages._renderConversation(userId, userName, userPicture, messagesReceived, messagesSent);
                        },
                        function(e) {
                            MM.popErrorMessage(e);
                        }
                    );
                },
                function(e) {
                    MM.popErrorMessage(e);
                }
            );
        },

        _renderConversation: function(userId, userName, userPicture, messagesReceived, messagesSent) {

            // Join the arrays and sort.
            var messages = messagesReceived.concat(messagesSent);
            // Sort by timecreated.
            messages = messages.sort(function (a, b) {
                a = parseInt(a.timecreated, 10);
                b = parseInt(b.timecreated, 10);

                return a - b;
            });

            var data = {
                messages: messages,
                otherUser: userId,
                userName: userName,
                userPicture: userPicture
            };

            html = MM.tpl.render(MM.plugins.messages.templates.conversation.html, data);
            MM.panels.show('right', html, {title: userName});

            $('#message-send-form').on('submit', function(e) {
                e.preventDefault();
                var originalMessage = $(this).find("#message-text").val();

                $("#message-text").val("");
                conversationArea = $(".conversation-area");
                messageId = hex_md5(message + MM.util.timestamp());

                var message = '
' + MM.util.formatText(originalMessage, true);
                message += '
';
                conversationArea.append(message);
                // Scroll bottom.
                conversationArea.scrollTop(conversationArea.prop("scrollHeight"));

                MM.plugins.messages._sendMessage(userId, originalMessage,
                    function(m) {
                        $("#" + messageId).addClass("removeMessage");
                        $("#message-text").val("");
                    },
                    function(e) {
                        $("#" + messageId).find("img").attr("src", "img/error.png");
                    }
                );
            });

            setTimeout(function() {
                MM.plugins.messages._pollingMessages(userId);
            }, MM.plugins.messages.pollingInterval);

            // Conversation area height.
            var headerHeight = $('.header-wrapper').height();
            var inputArea = $(".path-messages .conversation .input-area");
            var inputHeight  = inputArea.height();
            var conversationArea = $('.path-messages .conversation .conversation-area');

            // Uggly hack.
            var fixFactor = 115;
            if (MM.deviceType == "tablet") {
                fixFactor = 60;
            } else if (MM.deviceOS == "ios") {
                fixFactor = 60;
            }

            // Height of the conversation area.
            conversationArea.css('height', $(document).innerHeight() - headerHeight - inputHeight - fixFactor);
            conversationArea.css('width', $("#panel-right").width());
            // Scroll bottom.
            conversationArea.scrollTop(conversationArea.prop("scrollHeight"));
        },

        _renderMessages: function(messages) {
            tpl = {messages: messages};
            html = MM.tpl.render(MM.plugins.messages.templates.messages.html, tpl);
            MM.panels.show('center', html, {hideRight: true, title: MM.lang.s("messages")});
            $(".reply-button").on(MM.clickType, function(e) {
                e.preventDefault();
                var userId = $(this).data("useridfrom");
                if (MM.plugins.sendmessage) {
                    MM.plugins.sendmessage._displayMessageForm(userId);
                } else {
                    var url = MM.config.current_site.siteurl + "/message/index.php?user=" + MM.config.current_site.userid + "&id=" + userId;
                    window.open(url, "_system");
                }
            });
        },

         _format: function(text) {
            text = text.replace(/-{4,}/ig, '');
            text = MM.util.formatText(text, true);
            text = MM.util.createLinks(text).replace(/

/ig, "
");
            return text;
        },

        /**
         * Render the recent messages page.
         * Displays a list of contacts with last message (whatsapp/telegram style).
         */
        _renderRecentMessages: function() {

            MM.plugins.messages.recentContactMessages = [];
            MM.plugins.messages.recentContactsIds = {};

            var params = {
                useridto: MM.config.current_site.userid,
                useridfrom: 0,
                type: 'conversations',
                read: 0,
                newestfirst: 1,
                limitfrom: 0,
                limitnum: 50
            };

            // Get recent messages received (and sender).
            MM.plugins.messages._getRecentMessages(
                params,
                function(messages) {
                    // Find different senders in the messages list, in the latest 50 messages.
                    if (messages.length > 0) {
                        messages.forEach(function(m) {
                            if (!(m.useridfrom in MM.plugins.messages.recentContactsIds)) {
                                MM.plugins.messages.recentContactsIds[m.useridfrom] = {
                                    fullname: m.userfromfullname,
                                    profileimageurl: ""
                                };
                                if (!m.timeread) {
                                    MM.plugins.messages.recentContactsIds[m.useridfrom]["unread"] = 1;
                                }
                                MM.plugins.messages.recentContactMessages.push({
                                    user: m.useridfrom,
                                    message: m.smallmessage,
                                    timecreated: m.timecreated,
                                });
                            }
                        });
                    }

                    // Now get my latest messages send. Maybe I didn't receive a response.
                    params.useridfrom = MM.config.current_site.userid;
                    params.useridto = 0;

                    MM.plugins.messages._getRecentMessages(
                        params,
                        function(messagesSent) {

                            if (messagesSent.length > 0) {
                                messagesSent.forEach(function(m) {
                                    if (!(m.useridto in MM.plugins.messages.recentContactsIds)) {
                                        MM.plugins.messages.recentContactsIds[m.useridto] = {
                                            fullname: m.usertofullname,
                                            profileimageurl: ""
                                        };
                                        MM.plugins.messages.recentContactMessages.push({
                                            user: m.useridto,
                                            message: m.smallmessage,
                                            timecreated: m.timecreated,
                                        });
                                    }
                                });
                            }

                            // Now, get my contacts (the function returns unread messages count for contacts,
                            // maybe some are not included in the latest 50).
                            MM.plugins.messages._getContacts(
                                function(contacts) {
                                    var types = ["online", "offline", "strangers"];
                                    types.forEach(function(type) {
                                        if (contacts[type] && contacts[type].length > 0) {
                                            contacts[type].forEach(function(contact) {
                                                if (!(contact.id in MM.plugins.messages.recentContactsIds)) {
                                                    // Is a contact with unread messages, add it to the recent contact messages.
                                                    MM.plugins.messages.recentContactsIds[contact.id] = {
                                                        fullname: contact.fullname,
                                                        profileimageurl: ""
                                                    };

                                                    if (contact.unread) {
                                                        MM.plugins.messages.recentContactMessages.push({
                                                            user: contact.id,
                                                            message: "...",
                                                            timecreated: 0,
                                                        });
                                                    }
                                                }

                                                if (contact.profileimageurl) {
                                                    MM.plugins.messages.recentContactsIds[contact.id]["profileimageurl"] = contact.profileimageurl;
                                                }
                                                if (typeof contact.unread != "undefined") {
                                                    MM.plugins.messages.recentContactsIds[contact.id]["unread"] = contact.unread;
                                                }
                                            });
                                        }
                                    });
                                    // Save the users. Using a cache.
                                    var usersStored = [];
                                    MM.db.each("users", function(el){
                                        if(el.get("site") == MM.config.current_site.id) {
                                            usersStored.push(el.get("id"));
                                        }
                                    });

                                    var newUser;
                                    for (var userId in MM.plugins.messages.recentContactsIds) {
                                        if(MM.plugins.messages.recentContactsIds.hasOwnProperty(userId)){
                                            if (usersStored.indexOf(MM.config.current_site.id + "-" + userId) < 0) {
                                                newUser = {
                                                    'id': MM.config.current_site.id + '-' + userId,
                                                    'userid': userId,
                                                    'fullname': MM.plugins.messages.recentContactsIds[userId].fullname,
                                                    'profileimageurl': MM.plugins.messages.recentContactsIds[userId].profileimageurl
                                                };
                                                MM.db.insert('users', newUser);
                                            }
                                        }
                                    }

                                    $('a[href="#messages"]').removeClass('loading-row');
                                    var data = {
                                        messages: MM.plugins.messages.recentContactMessages,
                                        contacts: MM.plugins.messages.recentContactsIds
                                    };
                                    html = MM.tpl.render(MM.plugins.messages.templates.recent.html, data);
                                    MM.panels.show('center', html, {title: MM.lang.s("messages")});

                                    // Load the first event.
                                    if (MM.deviceType == "tablet" && messages.length > 0) {
                                        $("#panel-center li:eq(0)").addClass("selected-row");
                                        MM.plugins.messages.showConversation(data.messages[0]["user"]);
                                        $("#panel-center li:eq(0)").addClass("selected-row");
                                    }

                                },
                                function(e) {
                                    MM.log("Error retrieving contacts", "Messages");
                                }
                            );
                        },
                        function(e) {
                            MM.log("Error retrieving contacts", "Messages");
                        }
                    );
                },
                function(e) {
                    $('a[href="#messages"]').removeClass('loading-row');
                    MM.popErrorMessage(e);
                }
            );

            //$('a[href="#messages"]').removeClass('loading-row');
        },

        /**
         * Render a list of messages.
         * This function is used when the Moodle site doesn't have all the messaging functions available.
         */
        _renderMessageList: function() {

            var params = {
                useridto: MM.config.current_site.userid,
                useridfrom: 0,
                type: 'conversations',
                read: 0,
                newestfirst: 1,
                limitfrom: 0,
                limitnum: 50
            };

            MM.plugins.messages._getRecentMessages(
                params,
                function(messages) {
                    $('a[href="#messages"]').removeClass('loading-row');
                    MM.plugins.messages._renderMessages(messages);
                },
                function(e) {
                    $('a[href="#messages"]').removeClass('loading-row');
                    MM.popErrorMessage(e);
                }
            );
        },

        _getMessages: function(params, successCallback, errorCallback) {
            MM.moodleWSCall(
                MM.plugins.messages.wsPrefix + 'core_message_get_messages',
                params,
                function(messages) {
                    if (typeof successCallback == "function") {
                        successCallback(messages);
                    }
                },
                {
                    getFromCache: false,
                    saveToCache: true
                },
                function(e) {
                    if (typeof errorCallback == "function") {
                        errorCallback(e);
                    }
                }
            );
        },

        _getRecentMessages: function(params, successCallback, errorCallback) {

            params.read = 0;
            MM.plugins.messages._getMessages(
                params,
                function(messages) {
                    if (messages.messages) {
                        if (messages.messages.length >= params.limitnum) {
                            successCallback(messages.messages);
                        } else {
                            params.limitnum = params.limitnum - messages.messages.length;
                            params.read = 1;
                            // Load more messages but now read messages.
                            MM.plugins.messages._getMessages(
                                params,
                                function(moremessages) {
                                    if (moremessages.messages) {
                                        successCallback(messages.messages.concat(moremessages.messages));
                                    } else {
                                        successCallback(messages.messages);
                                    }
                                },
                                function() {
                                    successCallback(messages.messages);
                                }
                            );
                        }
                    } else {
                        if (messages.exception && messages.errorcode == "disabled") {
                            errorCallback(messages.message);
                        } else {
                            successCallback([]);
                        }
                    }
                },
                function(e) {
                    errorCallback(e);
                }
            );
        },

        /**
         * Get contacts
         * @param  {object} successCallback Success callback function
         * @param  {object} errorCallback   Error callback function
         */
        _getContacts: function(successCallback, errorCallback, settings) {
            settings = settings || {};

            var wsFn = 'core_message_get_contacts';
            if (MM.util.wsAvailable('local_mobile_core_message_get_contacts')) {
                wsFn = 'local_mobile_core_message_get_contacts';
            }

            MM.moodleWSCall(
                wsFn,
                {},
                function(contacts) {
                    if (typeof successCallback == "function") {
                        successCallback(contacts);
                    }
                },
                settings,
                function(e) {
                    if (typeof errorCallback == "function") {
                        errorCallback(e);
                    }
                }
            );
        },

        /**
         * Retrieve a list of blocked users
         * @param  {number} userId who is blocking the users
         * @param  {object} successCallback Success callback function
         * @param  {object} errorCallback   Error callback function
         */
        _getBlockedUsers: function(userId, successCallback, errorCallback) {
            var data = {
                "userid" : userId
            };

            var wsFn = 'core_message_get_blocked_users';
            if (MM.util.wsAvailable('local_mobile_core_message_get_blocked_users')) {
                wsFn = 'local_mobile_core_message_get_blocked_users';
            }

            MM.moodleWSCall(
                wsFn,
                data,
                function(result) {
                    if (result.warnings && result.warnings.length) {
                        if (typeof errorCallback == "function") {
                            errorCallback(result.warnings[0]['message']);
                        }
                        return;
                    }
                    result.users.forEach(function(user) {
                        MM.plugins.messages.blockedUsersIds[user.id] = user.id;
                        newUser = {
                            'id': MM.config.current_site.id + '-' + user.id,
                            'userid': user.id,
                            'fullname': user.fullname,
                            'profileimageurl': user.profileimageurl
                        };
                        MM.db.insert('users', newUser);
                    });
                    if (typeof successCallback == "function") {
                        successCallback(result.users);
                    }
                },
                {
                    getFromCache: false,
                    saveToCache: true
                },
                function(e) {
                    if (typeof errorCallback == "function") {
                        errorCallback(e);
                    }
                }
            );
        },

        /**
         * Create a contact
         * @param  {number} userId userId to be added as contact
         * @param  {object} successCallback Success callback function
         * @param  {object} errorCallback   Error callback function
         */
        _createContact: function(userId, successCallback, errorCallback) {
            var data = {
                "userids[0]" : userId
            };

            var wsFn = 'core_message_create_contacts';
            if (MM.util.wsAvailable('local_mobile_core_message_create_contacts')) {
                wsFn = 'local_mobile_core_message_create_contacts';
            }

            MM.moodleWSCall(
                wsFn,
                data,
                function(warnings) {
                    if (warnings && warnings.length) {
                        if (typeof errorCallback == "function") {
                            errorCallback(warnings[0]['message']);
                        }
                        return;
                    }
                    if (typeof successCallback == "function") {
                        successCallback();
                    }
                },
                {
                    getFromCache: false,
                    saveToCache: false
                },
                function(e) {
                    if (typeof errorCallback == "function") {
                        errorCallback(e);
                    }
                }
            );
        },

        /**
         * Delete a contact
         * @param  {number} userId userId to be deleted as contact
         * @param  {object} successCallback Success callback function
         * @param  {object} errorCallback   Error callback function
         */
        _deleteContact: function(userId, successCallback, errorCallback) {
            var data = {
                "userids[0]": userId
            };

            var wsFn = 'core_message_delete_contacts';
            if (MM.util.wsAvailable('local_mobile_core_message_delete_contacts')) {
                wsFn = 'local_mobile_core_message_delete_contacts';
            }

            MM.moodleWSCall(
                wsFn,
                data,
                function(result) {
                    if (typeof successCallback == "function") {
                        successCallback();
                    }
                },
                {
                    getFromCache: false,
                    saveToCache: false
                },
                function(e) {
                    if (typeof errorCallback == "function") {
                        errorCallback(e);
                    }
                }
            );
        },

        /**
         * Block a contact
         * @param  {number} userId userId to be blocked
         * @param  {object} successCallback Success callback function
         * @param  {object} errorCallback   Error callback function
         */
        _blockContact: function(userId, successCallback, errorCallback) {
            var data = {
                "userids[0]" : userId
            };

            var wsFn = 'core_message_block_contacts';
            if (MM.util.wsAvailable('local_mobile_core_message_block_contacts')) {
                wsFn = 'local_mobile_core_message_block_contacts';
            }

            MM.moodleWSCall(
                wsFn,
                data,
                function(warnings) {
                    if (warnings && warnings.length) {
                        if (typeof errorCallback == "function") {
                            errorCallback(warnings[0]['message']);
                        }
                        return;
                    }
                    if (typeof successCallback == "function") {
                        successCallback();
                    }
                },
                {
                    getFromCache: false,
                    saveToCache: false
                },
                function(e) {
                    if (typeof errorCallback == "function") {
                        errorCallback(e);
                    }
                }
            );
        },

        /**
         * Unblock a contact
         * @param  {number} userId userId to be unblocked
         * @param  {object} successCallback Success callback function
         * @param  {object} errorCallback   Error callback function
         */
        _unblockContact: function(userId, successCallback, errorCallback) {
            var data = {
                "userids[0]" : userId
            };

            var wsFn = 'core_message_unblock_contacts';
            if (MM.util.wsAvailable('local_mobile_core_message_unblock_contacts')) {
                wsFn = 'local_mobile_core_message_unblock_contacts';
            }

            MM.moodleWSCall(
                wsFn,
                data,
                function(result) {
                    if (typeof successCallback == "function") {
                        successCallback();
                    }
                },
                {
                    getFromCache: false,
                    saveToCache: false
                },
                function(e) {
                    if (typeof errorCallback == "function") {
                        errorCallback(e);
                    }
                }
            );
        },

        /**
         * Search contacts
         * @param  {string} text search text
         * @param  {string} onlyMyCourses search only in my courses
         * @param  {object} successCallback Success callback function
         * @param  {object} errorCallback   Error callback function
         */
        _searchContacts: function(text, onlyMyCourses, successCallback, errorCallback) {
            var data = {
                "searchtext" : text,
                "onlymycourses": onlyMyCourses
            };

            var wsFn = 'core_message_search_contacts';
            if (MM.util.wsAvailable('local_mobile_core_message_search_contacts')) {
                wsFn = 'local_mobile_core_message_search_contacts';
            }

            MM.moodleWSCall(
                wsFn,
                data,
                function(contacts) {
                    if (typeof successCallback == "function") {
                        // Save the users in the cache/db.
                        var usersStored = [];
                        MM.db.each("users", function(el){
                            if(el.get("site") == MM.config.current_site.id) {
                                usersStored.push(el.get("id"));
                            }
                        });

                        var newUser;
                        _.each(contacts, function(contact) {
                            if (usersStored.indexOf(MM.config.current_site.id + "-" + contact.id) < 0) {
                                newUser = {
                                    'id': MM.config.current_site.id + '-' + contact.id,
                                    'userid': contact.id,
                                    'fullname': contact.fullname,
                                    'profileimageurl': (contact.profileimageurl)? contact.profileimageurl : ''
                                };
                                MM.db.insert('users', newUser);
                            }
                        });
                        successCallback(contacts);
                    }
                },
                null,
                function(e) {
                    if (typeof errorCallback == "function") {
                        errorCallback(e);
                    }
                }
            );
        },

        _sendMessage: function(userTo, message, successCallback, errorCallback) {
            message = message.replace(/(?:\r\n|\r|\n)/g, '
');

            if (!message.trim()) {
                return;
            }

            var data = {
                "messages[0][touserid]" : userTo,
                "messages[0][text]" : message,
                "messages[0][textformat]" : 1
            };

            MM.moodleWSCall('moodle_message_send_instantmessages', data,
                function(r){
                    if (typeof successCallback == "function") {
                        successCallback(r);
                    }
                },
                {
                    getFromCache: false,
                    saveToCache: false
                },
                function(e) {
                    if (typeof errorCallback == "function") {
                        errorCallback(e);
                    }
                }
            );
        },

        showContacts: function() {

            MM.panels.showLoading('center');

            var fillContacts = function(blockedUsers) {
                MM.plugins.messages._getContacts(
                    function(contacts) {

                        contacts["blocked"] = blockedUsers;

                        MM.db.each("users", function(user) {
                            user = user.toJSON();
                            if(user.site == MM.config.current_site.id) {
                                user.id = user.userid;
                                contacts["strangers"].push(user);
                            }
                        });

                        html = MM.tpl.render(MM.plugins.messages.templates.contacts.html, {contacts: contacts});

                        MM.panels.show('center', html, {title: MM.lang.s("contacts")});

                        $('#search-contacts').on('submit', function(e) {
                            e.preventDefault();
                            var text = $('#search-text').val();

                            if (!text.trim()) {
                                return;
                            }
                            MM.plugins.messages._searchContacts(text, 0,
                                function(contacts) {
                                    var data = {
                                        users: contacts
                                    };
                                    var result = MM.lang.s('nousersfound');

                                    if (contacts.length) {
                                        result = MM.tpl.render(MM.plugins.messages.templates.search.html, data);
                                    }

                                    $("#contacts-list").css("display", "none");
                                    $("#search-result").css("display", "block");
                                    $("#search-result").html(result);
                                },
                                function(e) {
                                    MM.popErrorMessage(e);
                                }
                            );
                        });

                        $("#search-text").keyup(function(e) {
                            if ($(this).val() == "") {
                                $("#contacts-list").css("display", "block");
                                $("#search-result").css("display", "none");
                            }
                        });

                    },
                    function(e) {
                        MM.log("Error retrieving contacts", "Messages");
                    }
                );
            };

            MM.plugins.messages._getBlockedUsers(
                MM.config.current_site.userid,
                fillContacts,
                function(e) {
                    fillContacts([]);
                }
            );

        },

        showContact: function(userId) {
            var user = MM.db.get('users', MM.config.current_site.id + "-" + userId);
            if (!user) {
                MM.popErrorMessage("Invalid user");
                return;
            }
            user = user.toJSON();

            MM.plugins.messages._getContacts(
                function(contacts) {
                    var isContact = false;
                    var types = ["online", "offline"];
                    types.forEach(function(type) {
                        if (contacts[type] && contacts[type].length > 0) {
                            contacts[type].forEach(function(contact) {
                                if (contact.id == user.userid) {
                                    isContact = true;
                                    return;
                                }
                            });
                        }
                    });

                    var isBlocked = false;
                    if (typeof MM.plugins.messages.blockedUsersIds[userId] != "undefined") {
                        isBlocked = true;
                    }

                    var data = {
                        user: user,
                        isContact: isContact,
                        isBlocked: isBlocked
                    };

                    var html = MM.tpl.render(MM.plugins.messages.templates.contact.html, data);
                    MM.panels.show('right', html, {title: MM.lang.s("info")});

                    $(".add-remove-contact").on(MM.clickType, function(e) {
                        var userId = $(this).data("userid");
                        var add = $(this).data("add");
                        $(this).addClass("loading-row-black");

                        var fn = "_createContact";
                        if (parseInt(add, 10) === 0) {
                            fn = "_deleteContact";
                        }
                        MM.plugins.messages[fn](
                            userId,
                            function() {
                                MM.plugins.messages.showContact(userId);
                            },
                            function(e) {
                                $(this).removeClass("loading-row-black");
                                MM.popErrorMessage(e);
                            }
                        );
                    });

                    $(".block-unblock-contact").on(MM.clickType, function(e) {
                        var userId = $(this).data("userid");
                        var block = parseInt($(this).data("block"), 10);
                        $(this).addClass("loading-row-black");

                        var fn = "_blockContact";
                        if (block === 0) {
                            fn = "_unblockContact";
                        }
                        MM.plugins.messages[fn](
                            userId,
                            function() {
                                // Refresh cache of blocked users.
                                if (block === 0) {
                                    delete MM.plugins.messages.blockedUsersIds[userId];
                                } else {
                                    MM.plugins.messages.blockedUsersIds[userId] = userId;
                                }
                                MM.plugins.messages.showContact(userId);
                            },
                            function(e) {
                                $(this).removeClass("loading-row-black");
                                MM.popErrorMessage(e);
                            }
                        );
                    });

                },
                function(e) {
                    MM.log("Error retrieving contacts", "Messages");
                },
                {
                    getFromCache: false,
                    saveToCache: true
                }
            );
        },

        _pollingMessages: function(userId) {
            if (location.href.indexOf("#messages/conversation/" + userId) > -1) {
                var params = {
                    useridto: MM.config.current_site.userid,
                    useridfrom: userId,
                    type: 'conversations',
                    read: 0,
                    newestfirst: 1,
                    limitfrom: 0,
                    limitnum: 5
                };

                // First, messages received.
                MM.plugins.messages._getRecentMessages(
                    params,
                    function(messagesReceived) {
                        // Now, messages sent.
                        params.useridto = userId;
                        params.useridfrom = MM.config.current_site.userid;

                        MM.plugins.messages._getRecentMessages(
                            params,
                            function(messagesSent) {
                                // Remove rendered messages.
                                var rendered = [];

                                $(".bubble").each(function() {
                                    rendered.push($(this).data("messageid"));
                                });

                                var messages = messagesReceived.concat(messagesSent);
                                // Sort by timecreated.
                                messages = messages.sort(function (a, b) {
                                    a = parseInt(a.timecreated, 10);
                                    b = parseInt(b.timecreated, 10);

                                    return a - b;
                                });

                                for(var i = messages.length -1; i >= 0 ; i--){
                                    var m = messages[i];
                                    var id = m.useridfrom + "-" + m.id + "-" + m.timecreated;
                                    if(rendered.indexOf(id) > -1){
                                        messages.splice(i, 1);
                                    }
                                }

                                if (messages.length > 0) {
                                    var d = new Date(messages[0].timecreated * 1000);
                                    var previousDate = MM.util.toLocaleDateString(d, MM.lang.current, {year: 'numeric', month:'long', day: '2-digit'});

                                    var html = MM.plugins.messages._renderConversationArea(messages, userId, previousDate);
                                    // Double check we are in the correct conversation window.
                                    if (location.href.indexOf("#messages/conversation/" + userId) > -1) {
                                        conversationArea = $(".conversation-area");
                                        conversationArea.find(".removeMessage").remove();
                                        conversationArea.append(html);
                                        conversationArea.scrollTop(conversationArea.prop("scrollHeight"));
                                    }
                                }

                                setTimeout(function() {
                                    MM.plugins.messages._pollingMessages(userId);
                                }, MM.plugins.messages.pollingInterval);
                            },
                            function(e) {
                                setTimeout(function() {
                                    MM.plugins.messages._pollingMessages(userId);
                                }, MM.plugins.messages.pollingInterval);
                            }
                        );
                    },
                    function(e) {
                        setTimeout(function() {
                            MM.plugins.messages._pollingMessages(userId);
                        }, MM.plugins.messages.pollingInterval);
                    }
                );
            }
        },

        _renderConversationArea: function(messages, userId, previousDate) {
            var data = {
                messages: messages,
                otherUser: userId,
                previousDate: previousDate
            };

            return MM.tpl.render(MM.plugins.messages.templates.bubbles.html, data);
        }
    };

    MM.registerPlugin(plugin);

    // After register the plugin, bind events.
    $(document).bind('resume', MM.plugins.messages.check);
});


text:
package org.wso2.carbon.appmgt.impl.token;

import org.wso2.carbon.appmgt.api.AppManagementException;

import java.util.SortedMap;

/**
 * This interface encapsulates a user claims retriever.
 * The retrieved claims are encoded to the JWT during subscriber validation
 * in the order defined by the SortedMap.
 * Anyone trying to add custom user properties to the JWT should implement this interface
 * and mention the fully qualified class name in app-manager.xml ->
 * AppConsumerAuthConfiguration -> ClaimsRetrieverImplClass
 */
public interface ClaimsRetriever {

    String CLAIMS_RETRIEVER_IMPL_CLASS = "AppConsumerAuthConfiguration.ClaimsRetrieverImplClass";

    String CONSUMER_DIALECT_URI = "AppConsumerAuthConfiguration.ConsumerDialectURI";

    String DEFAULT_DIALECT_URI = "http://wso2.org/claims";

  /**
     * Initialization method that runs only once.
     *
     * @throws org.wso2.carbon.appmgt.api.AppManagementException
     */
    void init() throws AppManagementException;

  /**
     * Method that retrieves user claims
     *
     * @return a sorted map
     *                  keys - claimURIs
     *                  values - claim values.
     * @throws org.wso2.carbon.appmgt.api.AppManagementException
     */
    SortedMap<String,String> getClaims(String endUserName) throws AppManagementException;

  /**
     * Must return the dialect URI of the user ClaimURIs.
     *
     * @throws org.wso2.carbon.appmgt.api.AppManagementException
     */
    String getDialectURI(String endUserName);

}

redpajama_set_name: RedPajamaGithub


text:
/* util
 */

function clone (obj) {
  return JSON.parse(JSON.stringify(obj))
}

function extendLevel (obj, defaults = {}) {
  // copy default keys where undefined
  Object.keys(defaults).forEach(function (key) {
    if (typeof obj[key] === 'undefined') {
      // default
      obj[key] = clone(defaults[key])
    } else if (typeof obj[key] === 'object') {
      extendLevel(obj[key], defaults[key])
    }
  })

  return obj
}

// multi-level object merge
function extend (obj, defaults) {
  if (obj === null) {
    obj = {}
  }

  return extendLevel(clone(obj), defaults)
}

function guid () {
  return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) {
    var r = Math.random() * 16 | 0
    var v = c === 'x' ? r : (r & 0x3 | 0x8)
    return v.toString(16)
  })
}

module.exports = {
  clone: clone,
  extend: extend,
  guid: guid
}


text:
import * as assert from "assert";
import * as css from "css";
import {astDiff} from "./ast_diff";

describe("astDiff", () => {
  it("should return result that represents 'no changed' when there are no changed between 2 StyleSheets", () => {
    const styleSheetA = css.parse("a { display: none; }");
    const styleSheetB = css.parse("a { display: none; }");

    const result = astDiff(styleSheetA, styleSheetB);
    assert(!result.changed);
  });

  it("should return extra nodes when the last StyleSheet has an extra node", () => {
    const styleSheetA = css.parse("");
    const styleSheetB = css.parse(".extra { display: none; }");

    const result = astDiff(styleSheetA, styleSheetB);
    assert(result.changed);

    assert.strictEqual(result.extra.length, 1);
    assertRuleNodeEqual(result.extra[0], [".extra"]);

    assert.deepEqual(result.missing, []);
  });

  it("should return missing nodes when the first StyleSheet has an extra node", () => {
    const styleSheetA = css.parse(".missing { display: none; }");
    const styleSheetB = css.parse("");

    const result = astDiff(styleSheetA, styleSheetB);
    assert(result.changed);

    assert.deepEqual(result.extra, []);

    assert.strictEqual(result.missing.length, 1);
    assertRuleNodeEqual(result.missing[0], [".missing"]);
  });

  it("should return extra and missing nodes when the both 2 StyleSheet have an extra node", () => {
    const styleSheetA = css.parse(".missing { display: none; }");
    const styleSheetB = css.parse(".extra { display: none; }");

    const result = astDiff(styleSheetA, styleSheetB);
    assert(result.changed);

    assert.strictEqual(result.extra.length, 1);
    assertRuleNodeEqual(result.extra[0], [".extra"]);

    assert.strictEqual(result.missing.length, 1);
    assertRuleNodeEqual(result.missing[0], [".missing"]);
  });

  it("should return extra and missing nodes when the both 2 StyleSheet have an extra node and several common nodes", () => {
    const styleSheetA = css.parse(".missing { display: none; } .common { display: none; }");
    const styleSheetB = css.parse(".extra { display: none; } .common { display: none; }");

    const result = astDiff(styleSheetA, styleSheetB);
    assert(result.changed);

    assert.strictEqual(result.extra.length, 1);
    assertRuleNodeEqual(result.extra[0], [".extra"]);

    assert.strictEqual(result.missing.length, 1);
    assertRuleNodeEqual(result.missing[0], [".missing"]);
  });
});

function assertNodeTypeEqual(node: css.Node, nodeType: string): void {
  assert.strictEqual(node.type, nodeType);
}

function assertRuleNodeEqual(node: css.Node, selectors: string[]): void {
  assertNodeTypeEqual(node, "rule");
  const ruleNode = <css.Rule>node;
  assert.deepEqual(ruleNode.selectors, selectors);
}


text:
<?php

return [
    'login' => 'Sign in',
    'email' => 'Email',
    'remember me' => 'Remember me',
    'forgot password' => 'I forgot my password',
    'register' => 'Register a new membership',
    'password' => 'Password',
    'password confirmation' => 'Password confirmation',
    'register me' => 'Register',
    'I already have a membership' => 'I already have a membership',
    'reset password' => 'Reset password',
    'I remembered my password' => 'I remembered my password',
    'to reset password complete this form' => 'To reset your password, complete this form: ',
    'welcome title' => 'Welcome',
    'please confirm email' => 'Please confirm your email address by clicking the link below.',
    'additional confirm email message' => 'We may need to send you critical information about our service and it is important that we have an accurate email address.',
    'confirm email button' => 'Confirm email address',
    'end greeting' => 'The team',
    'sign in welcome message' => 'Sign in to start your session',
    'reset password email was sent' => 'Reset password email was sent',
];


text:
package jiacrontabd

import (
	"bytes"
	"context"
	"jiacrontab/pkg/proto"
	"time"

	"github.com/iwannay/log"
)

type depEntry struct {
	jobID       uint   // 定时任务id
	jobUniqueID string // job的唯一标志
	processID   int    // 当前依赖的父级任务(可能存在多个并发的task)
	id          string // depID uuid
	once        bool
	workDir     string
	user        string
	env         []string
	from        string
	commands    []string
	dest        string
	done        bool
	timeout     int64
	err         error
	ctx         context.Context
	name        string
	logPath     string
	logContent  []byte
}

func newDependencies(jd *Jiacrontabd) *dependencies {
	return &dependencies{
		jd:  jd,
		dep: make(chan *depEntry, 100),
	}
}

type dependencies struct {
	jd  *Jiacrontabd
	dep chan *depEntry
}

func (d *dependencies) add(t *depEntry) {
	select {
	case d.dep <- t:
	default:
		log.Warnf("discard %v", t)
	}

}

func (d *dependencies) run() {
	go func() {
		for {
			select {
			case t := <-d.dep:
				go d.exec(t)
			}
		}
	}()
}

// TODO: 主任务退出杀死依赖
func (d *dependencies) exec(task *depEntry) {

	var (
		reply bool
		err   error
	)

	if task.timeout == 0 {
		// 默认超时10分钟
		task.timeout = 600
	}

	ctx, cancel := context.WithTimeout(context.Background(), time.Duration(task.timeout)*time.Second)
	defer cancel()
	myCmdUnit := cmdUint{
		args:          [][]string{task.commands},
		ctx:           ctx,
		dir:           task.workDir,
		user:          task.user,
		logPath:       task.logPath,
		ignoreFileLog: true,
		jd:            d.jd,
		exportLog:     true,
	}

	log.Infof("dep start exec %s->%v", task.name, task.commands)
	task.err = myCmdUnit.launch()
	task.logContent = bytes.TrimRight(myCmdUnit.content, "\x00")
	task.done = true
	log.Infof("exec %s %s cost %.4fs %v", task.name, task.commands, float64(myCmdUnit.costTime)/1000000000, err)

	task.dest, task.from = task.from, task.dest

	if !d.jd.SetDependDone(task) {
		err = d.jd.rpcCallCtx(ctx, "Srv.SetDependDone", proto.DepJob{
			Name:        task.name,
			Dest:        task.dest,
			From:        task.from,
			ID:          task.id,
			JobUniqueID: task.jobUniqueID,
			ProcessID:   task.processID,
			JobID:       task.jobID,
			Commands:    task.commands,
			LogContent:  task.logContent,
			Err:         err,
			Timeout:     task.timeout,
		}, &reply)

		if err != nil {
			log.Error("Srv.SetDependDone error:", err, "server addr:", d.jd.getOpts().AdminAddr)
		}

		if !reply {
			log.Errorf("task %s %v call Srv.SetDependDone failed! err:%v", task.name, task.commands, err)
		}
	}
}


text:
export function startServer(_: any): any {
	throw new Error('Not implemented');
}

export function createServer(_: any): any {
	throw new Error('Not implemented');
}


text:
package net.boatcake.allthetrees;

import net.boatcake.allthetrees.plugins.IPlugin;
import net.boatcake.allthetrees.plugins.PluginBOP;
import cpw.mods.fml.common.Loader;
import cpw.mods.fml.common.Mod;
import cpw.mods.fml.common.Mod.EventHandler;
import cpw.mods.fml.common.event.FMLInitializationEvent;
import cpw.mods.fml.common.event.FMLPostInitializationEvent;

@Mod(modid = "AllTheTrees", name = "All the Trees!", version = "1.0", dependencies = "after:BiomesOPlenty; required-after:Forestry; required-after:Forge")
public class AllTheTrees {
	@EventHandler
	public void postInit(FMLPostInitializationEvent e) {
		registerPlugins();
	}
	private void registerPlugins() {
		if (Loader.isModLoaded(PluginBOP.MODID)) {
			new PluginBOP().register();
		}
	}
}


text:
package Utils;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.PrintWriter;
import java.net.Socket;
import android.util.Log;
import android.widget.TextView;

public class ClientThread extends Thread {

	private String   address;
	private int      port;
	private String   informationType;
	private TextView weatherForecastTextView;

	private Socket   socket;

	public ClientThread(
			String address,
			int port,
			String informationType,
			TextView weatherForecastTextView) {
		this.address                 = address;
		this.port                    = port;
		this.informationType         = informationType;
		this.weatherForecastTextView = weatherForecastTextView;
	}

	@Override
	public void run() {
		try {
			socket = new Socket(address, port);
			if (socket == null) {
				Log.e("App", "[CLIENT THREAD] Could not create socket!");
			}

			BufferedReader bufferedReader = Utilities.getReader(socket);
			PrintWriter    printWriter    = Utilities.getWriter(socket);
			if (bufferedReader != null && printWriter != null) {
				printWriter.println(informationType);
				printWriter.flush();
				String weatherInformation;
				while ((weatherInformation = bufferedReader.readLine()) != null) {
					final String finalizedWeatherInformation = weatherInformation;
					weatherForecastTextView.post(new Runnable() {
						@Override
						public void run() {
							weatherForecastTextView.append(finalizedWeatherInformation + "\n");
						}
					});
				}
			} else {
				Log.e("app", "[CLIENT THREAD] BufferedReader / PrintWriter are null!");
			}
			socket.close();
		} catch (IOException ioException) {
			Log.e("app", "[CLIENT THREAD] An exception has occurred: " + ioException.getMessage());

				ioException.printStackTrace();

		}
	}

}


text:
<map>
  <entry>
    <string>plugin_status</string>
    <string>ready</string>
  </entry>
  <entry>
    <string>plugin_identifier</string>
    <string>org.lockss.plugin.anu.ClockssAnuPlugin</string>
  </entry>
  <entry>
    <string>plugin_version</string>
    <string>24</string>
  </entry>
  <entry>
    <string>plugin_feature_version_map</string>
    <map>
      <entry>
        <string>Metadata</string>
        <string>5</string>
      </entry>
      <entry>
        <string>Poll</string>
        <string>4</string>
      </entry>
      <entry>
        <string>Substance</string>
        <string>2</string>
      </entry>
    </map>
  </entry>
  <entry>
    <string>plugin_name</string>
    <string>Australian National University Press Journals Plugin (CLOCKSS)</string>
  </entry>
  <entry>
    <string>au_name</string>
    <string>"Australian National University Press Journals Plugin (CLOCKSS), Base URL %s, JID %s, Volume %s", base_url, journal_id, volume_name</string>
  </entry>
  <entry>
    <string>au_start_url</string>
    <!--  6/14/19 - intentional backwards incompatible change -->
    <!-- site changed and redirects + new journal_id did not work; lock down processed content on production and change start_url -->
    <!-- crawl rules still work for legacy content so production content maintenance will be fine -->
    <string>"%spublications/journals/%s", base_url, journal_id</string>
  </entry>
  <entry>
    <string>au_permission_url</string>
    <list>
      <string>"%slockss.txt", base_url</string>
      <string>"https://style.anu.edu.au/lockss.txt"</string>
      <string>"https://press-files.anu.edu.au/lockss.txt"</string>
    </list>
  </entry>
  <entry>
    <!-- the au_permitted_host_pattern must also find match in lockss-daemon config
         org.lockss.crawler.allowedPluginPermittedHosts -->
    <string>au_permitted_host_pattern</string>
    <list>
      <string>(fonts|ajax)\.(googleapis|gstatic)\.com</string>
    </list>
  </entry>
  <entry>
    <string>au_def_new_content_crawl</string>
    <long>1209600000</long>
  </entry>
  <entry>
    <string>au_def_pause_time</string>
    <long>3000</long>
  </entry>
  <entry>
    <!-- start page to landing page, is difficult to determine
        as the first good link may be on the 3rd page of listings,
        however, daemon may recompute depth so only need to add 1 to depth -->
    <string>au_refetch_depth</string>
    <int>3</int>
  </entry>
  <entry>
    <string>au_crawlrules</string>
    <list>
      <string>1,"^https?://((fonts|ajax)\.(googleapis|gstatic)\.com)/.*\.?(bmp|css|eot|gif|ico|jpe?g|js|otf|png|svg|tif?f|ttf|woff.?)(\?.*)?"</string>
      <string>1,"^https?://(press(-files)?|style)\.anu\.edu\.au/.*\.(bmp|css|eot|gif|ico|jpe?g|js|otf|png|svg|tif?f|ttf|woff.?)$"</string>
      <string>1,"^https?://(press(-files)?|style)\.anu\.edu\.au/lockss.txt$"</string>
      <string>4,"^https?://(press(-files)?|style)\.anu\.edu\.au/"</string>
      <!--  start_url now redirects to version without publications and we need to allow this before next rule -->
      <string>1,"^https?://%s/%s(\?page=[0-9]+)?$", url_host(base_url), journal_id</string>
      <!-- in cases where there is a bad link, seems to redirect to search page, don't follow these links -->
      <string>2,"(^https?://%s/([^/?]+)?$|\?search=|/authors-editors/)", url_host(base_url)</string>
      <!-- start url has publications/ but redirects to version without publications/ now allowed above -->
      <string>1,"^https?://%s%spublications/(journals/)?%s(\?page=[0-9]+)?$", url_host(base_url), url_path(base_url), journal_id</string>
      <string>1,"^https?://%s%s[?]p=[0-9]+$", url_host(base_url), url_path(base_url)</string>
      <string>1,"^https?://%s%snode/[0-9]+(/download)?$", url_host(base_url), url_path(base_url)</string>
      <!-- 6/14/19 - some journals use short jid on TOC link; allow any lower-case-char sequence in this position since the full journal id is also there -->
      <!-- e.g. https://press.anu.edu.au/publications/journals/australian-journal-biography-and-history/ajbh-1 -->
      <!-- e.g. https://press.anu.edu.au/publications/journals/international-review-environmental-history/ireh-volume-5-issue-1-2019 -->
      <!--  and agenda uses short and then long /journals/agenda/agenda-journal-policy... -->
      <string>1,"^https?://%s%spublications/(journals/(%s/)?)?(%s|[a-z-]+)(-(ii-number|issue|volume|no-[1-9]|winter))?-%s(-[12ni][^/]*?)?(/download)?$", url_host(base_url), url_path(base_url), journal_id, journal_id, volume_name</string>
      <string>1,"^https?://press-files\.anu\.edu\.au/downloads/press/[^/]+/(html|media|pdf|epub|mobi)/", base_url</string>
    </list>
  </entry>
  <entry>
    <string>au_substance_url_pattern</string>
    <list>
<!--       <string>"^https?://press-files.anu.edu.au/downloads/press/[^/]+/pdf/book\.pdf"</string> -->
      <string>"^https?://press-files.anu.edu.au/downloads/press/[^/]+/pdf/.+\.pdf"</string>
    </list>
  </entry>
  <entry>
    <string>plugin_config_props</string>
    <list>
      <org.lockss.daemon.ConfigParamDescr>
        <key>base_url</key>
        <displayName>Base URL</displayName>
        <description>Usually of the form http://<journal-name>.com/</description>
        <type>3</type>
        <size>40</size>
        <definitional>true</definitional>
        <defaultOnly>false</defaultOnly>
      </org.lockss.daemon.ConfigParamDescr>
      <org.lockss.daemon.ConfigParamDescr>
        <key>journal_id</key>
        <displayName>Journal Id</displayName>
        <description>Identifier for journal (often used as part of file names)</description>
        <type>1</type>
        <size>100</size>
        <definitional>true</definitional>
        <defaultOnly>false</defaultOnly>
      </org.lockss.daemon.ConfigParamDescr>
      <org.lockss.daemon.ConfigParamDescr>
        <key>volume_name</key>
        <displayName>Volume</displayName>
        <type>1</type>
        <size>40</size>
        <definitional>true</definitional>
        <defaultOnly>false</defaultOnly>
      </org.lockss.daemon.ConfigParamDescr>
    </list>
  </entry>
  <entry>
    <string>au_url_normalizer</string>
    <string>org.lockss.plugin.anu.AnuUrlNormalizer</string>
  </entry>
  <entry>
    <string>text/html_link_extractor_factory</string>
    <string>org.lockss.plugin.anu.AnuHtmlLinkExtractorFactory</string>
  </entry>
  <entry>
    <string>text/html_crawl_filter_factory</string>
    <string>org.lockss.plugin.anu.AnuHtmlCrawlFilterFactory</string>
  </entry>
  <entry>
    <string>text/html_filter_factory</string>
    <string>org.lockss.plugin.anu.AnuHtmlHashFilterFactory</string>
  </entry>
  <entry>
    <string>plugin_article_iterator_factory</string>
    <string>org.lockss.plugin.anu.AnuArticleIteratorFactory</string>
  </entry>
  <entry>
    <string>plugin_article_metadata_extractor_factory</string>
    <string>org.lockss.plugin.anu.AnuArticleIteratorFactory</string>
  </entry>
  <entry>
    <string>text/html_metadata_extractor_factory_map</string>
    <map>
      <entry>
        <string>*;DublinCore</string>
        <string>org.lockss.plugin.anu.AnuHtmlMetadataExtractorFactory</string>
      </entry>
    </map>
  </entry>
  <entry>
    <string>plugin_cache_result_list</string>
    <list>
      <string>403=org.lockss.plugin.anu.AnuHttpResponseHandler</string>
      <string>500=org.lockss.plugin.anu.AnuHttpResponseHandler</string>
    </list>
  </entry>
  <entry>
    <string>au_repair_from_peer_if_missing_url_pattern</string>
    <list>
      <string>.+[.](bmp|css|dfont|eot|gif|ico|jpe?g|js|otf|png|svg|tif?f|ttc|ttf|woff.?)(\?.*)?$"</string>
      <string>https://fonts\.googleapis\.com/css\?</string>
      <string>/html/(banner|frames)\.php</string>
    </list>
  </entry>
  <entry>
    <!-- these will not count towards poll results but will replicate from peer if above -->
    <string>au_url_poll_result_weight</string>
    <list>
      <string>".+[.](bmp|css|dfont|eot|gif|ico|jpe?g|js|otf|png|svg|tif?f|ttc|ttf|woff.?)(\?.*)?$", 0</string>
      <string>"https://fonts\.googleapis\.com/css\?", 0</string>
      <string>"/html/(banner|frames)\.php", 0</string>
    </list>
  </entry>
  <!--  tell the default base.MimeTypeContentValidator what url patterns to validate by mime type -->
  <entry>
    <string>au_url_mime_validation_map</string>
    <list>
      <string>\.pdf$, application/pdf</string>
      <string>node/[0-9]+$, text/html</string>
      <string>downloads/press/[^/]+/html/.+\.x?html, text/html</string>
      <!--  terminating download doesn't appear to exist any more but no harm to leave it in -->
      <string>/download$, text/html</string>
    </list>
  </entry>
</map>


text:
'use strict';

var is = require('bpmn-js/lib/util/ModelUtil').is;

var elementHelper = require('../../../../helper/ElementHelper'),
    inputOutputHelper = require('../../../../helper/InputOutputHelper'),
    cmdHelper = require('../../../../helper/CmdHelper'),
    utils = require('../../../../Utils');

var entryFactory = require('../../../../factory/EntryFactory'),
    script = require('./Script')('scriptFormat', 'value', true);

function createElement(type, parent, factory, properties) {
  return elementHelper.createElement(type, properties, parent, factory);
}

function isScript(elem) {
  return is(elem, 'camunda:Script');
}

function isList(elem) {
  return is(elem, 'camunda:List');
}

function isMap(elem) {
  return is(elem, 'camunda:Map');
}

function ensureInputOutputSupported(element, insideConnector) {
  return inputOutputHelper.isInputOutputSupported(element, insideConnector);
}

module.exports = function(element, bpmnFactory, options, translate) {

  var typeInfo = {
    'camunda:Map': {
      value: 'map',
      label: translate('Map')
    },
    'camunda:List': {
      value: 'list',
      label: translate('List')
    },
    'camunda:Script': {
      value: 'script',
      label: translate('Script')
    }
  };

  options = options || {};

  var insideConnector = !!options.insideConnector,
      idPrefix        = options.idPrefix || '';

  var getSelected = options.getSelectedParameter;

  if (!ensureInputOutputSupported(element, insideConnector)) {
    return [];
  }

  var entries = [];

  var isSelected = function(element, node) {
    return getSelected(element, node);
  };

  // parameter name ////////////////////////////////////////////////////////

  entries.push(entryFactory.validationAwareTextField({
    id: idPrefix + 'parameterName',
    label: 'Name',
    modelProperty: 'name',

    getProperty: function(element, node) {
      return (getSelected(element, node) || {}).name;
    },

    setProperty: function(element, values, node) {
      var param = getSelected(element, node);
      return cmdHelper.updateBusinessObject(element, param, values);
    },

    validate: function(element, values, node) {
      var bo = getSelected(element, node);

      var validation = {};
      if (bo) {
        var nameValue = values.name;

        if (nameValue) {
          if (utils.containsSpace(nameValue)) {
            validation.name = 'Name must not contain spaces';
          }
        }
        else {
          validation.name = 'Parameter must have a name';
        }
      }

      return validation;
    },

    hidden: function(element, node) {
      return !isSelected(element, node);
    }
  }));

  // parameter type //////////////////////////////////////////////////////

  var selectOptions = [
    { value: 'text', name: 'Text' },
    { value: 'script', name: 'Script' },
    { value: 'list', name: 'List' },
    { value: 'map', name: 'Map' }
  ];

  entries.push(entryFactory.selectBox({
    id : idPrefix + 'parameterType',
    label: 'Type',
    selectOptions: selectOptions,
    modelProperty: 'parameterType',

    get: function(element, node) {
      var bo = getSelected(element, node);

      var parameterType = 'text';

      if (typeof bo !== 'undefined') {
        var definition = bo.get('definition');
        if (typeof definition !== 'undefined') {
          var type = definition.$type;
          parameterType = typeInfo[type].value;
        }
      }

      return {
        parameterType: parameterType
      };
    },

    set: function(element, values, node) {
      var bo = getSelected(element, node);

      var properties = {
        value: undefined,
        definition: undefined
      };

      var createParameterTypeElem = function(type) {
        return createElement(type, bo, bpmnFactory);
      };

      var parameterType = values.parameterType;

      if (parameterType === 'script') {
        properties.definition = createParameterTypeElem('camunda:Script');
      }
      else if (parameterType === 'list') {
        properties.definition = createParameterTypeElem('camunda:List');
      }
      else if (parameterType === 'map') {
        properties.definition = createParameterTypeElem('camunda:Map');
      }

      return cmdHelper.updateBusinessObject(element, bo, properties);
    },

    show: function(element, node) {
      return isSelected(element, node);
    }

  }));

  // parameter value (type = text) ///////////////////////////////////////////////////////

  entries.push(entryFactory.textBox({
    id : idPrefix + 'parameterType-text',
    label : 'Value',
    modelProperty: 'value',
    get: function(element, node) {
      return {
        value: (getSelected(element, node) || {}).value
      };
    },

    set: function(element, values, node) {
      var param = getSelected(element, node);
      values.value = values.value || undefined;
      return cmdHelper.updateBusinessObject(element, param, values);
    },

    show: function(element, node) {
      var bo = getSelected(element, node);
      return bo && !bo.definition;
    }

  }));

  // parameter value (type = script) ///////////////////////////////////////////////////////

  entries.push({
    id: idPrefix + 'parameterType-script',
    html: '
' +
            script.template +
          '
',
    get: function(element, node) {
      var bo = getSelected(element, node);
      return bo && isScript(bo.definition) ? script.get(element, bo.definition) : {};
    },

    set: function(element, values, node) {
      var bo = getSelected(element, node);
      var update = script.set(element, values);
      return cmdHelper.updateBusinessObject(element, bo.definition, update);
    },

    validate: function(element, values, node) {
      var bo = getSelected(element, node);
      return bo && isScript(bo.definition) ? script.validate(element, bo.definition) : {};
    },

    isScript: function(element, node) {
      var bo = getSelected(element, node);
      return bo && isScript(bo.definition);
    },

    script: script

  });

  // parameter value (type = list) ///////////////////////////////////////////////////////

  entries.push(entryFactory.table({
    id: idPrefix + 'parameterType-list',
    modelProperties: [ 'value' ],
    labels: [ 'Value' ],

    getElements: function(element, node) {
      var bo = getSelected(element, node);

      if (bo && isList(bo.definition)) {
        return bo.definition.items;
      }

      return [];
    },

    updateElement: function(element, values, node, idx) {
      var bo = getSelected(element, node);
      var item = bo.definition.items[idx];
      return cmdHelper.updateBusinessObject(element, item, values);
    },

    addElement: function(element, node) {
      var bo = getSelected(element, node);
      var newValue = createElement('camunda:Value', bo.definition, bpmnFactory, { value: undefined });
      return cmdHelper.addElementsTolist(element, bo.definition, 'items', [ newValue ]);
    },

    removeElement: function(element, node, idx) {
      var bo = getSelected(element, node);
      return cmdHelper.removeElementsFromList(element, bo.definition, 'items', null, [ bo.definition.items[idx] ]);
    },

    editable: function(element, node, prop, idx) {
      var bo = getSelected(element, node);
      var item = bo.definition.items[idx];
      return !isMap(item) && !isList(item) && !isScript(item);
    },

    setControlValue: function(element, node, input, prop, value, idx) {
      var bo = getSelected(element, node);
      var item = bo.definition.items[idx];

      if (!isMap(item) && !isList(item) && !isScript(item)) {
        input.value = value;
      }
      else {
        input.value = typeInfo[item.$type].label;
      }
    },

    show: function(element, node) {
      var bo = getSelected(element, node);
      return bo && bo.definition && isList(bo.definition);
    }

  }));

  // parameter value (type = map) ///////////////////////////////////////////////////////

  entries.push(entryFactory.table({
    id: idPrefix + 'parameterType-map',
    modelProperties: [ 'key', 'value' ],
    labels: [ 'Key', 'Value' ],
    addLabel: 'Add Entry',

    getElements: function(element, node) {
      var bo = getSelected(element, node);

      if (bo && isMap(bo.definition)) {
        return bo.definition.entries;
      }

      return [];
    },

    updateElement: function(element, values, node, idx) {
      var bo = getSelected(element, node);
      var entry = bo.definition.entries[idx];

      if (isMap(entry.definition) || isList(entry.definition) || isScript(entry.definition)) {
        values = {
          key: values.key
        };
      }

      return cmdHelper.updateBusinessObject(element, entry, values);
    },

    addElement: function(element, node) {
      var bo = getSelected(element, node);
      var newEntry = createElement('camunda:Entry', bo.definition, bpmnFactory, { key: undefined, value: undefined });
      return cmdHelper.addElementsTolist(element, bo.definition, 'entries', [ newEntry ]);
    },

    removeElement: function(element, node, idx) {
      var bo = getSelected(element, node);
      return cmdHelper.removeElementsFromList(element, bo.definition, 'entries', null, [ bo.definition.entries[idx] ]);
    },

    editable: function(element, node, prop, idx) {
      var bo = getSelected(element, node);
      var entry = bo.definition.entries[idx];
      return prop === 'key' || (!isMap(entry.definition) && !isList(entry.definition) && !isScript(entry.definition));
    },

    setControlValue: function(element, node, input, prop, value, idx) {
      var bo = getSelected(element, node);
      var entry = bo.definition.entries[idx];

      if (prop === 'key' || (!isMap(entry.definition) && !isList(entry.definition) && !isScript(entry.definition))) {
        input.value = value;
      }
      else {
        input.value = typeInfo[entry.definition.$type].label;
      }
    },

    show: function(element, node) {
      var bo = getSelected(element, node);
      return bo && bo.definition && isMap(bo.definition);
    }

  }));

  return entries;

};


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

<META http-equiv="Content-Type" content="text/html; charset=UTF-8">
<TITLE>
javax.mail.search (JavaMail API documentation)
</TITLE>

<META NAME="date" CONTENT="2011-01-14">

<LINK REL ="stylesheet" TYPE="text/css" HREF="../../../stylesheet.css" TITLE="Style">

javax.mail.search

Classes

AddressStringTerm

AddressTerm

AndTerm

BodyTerm

ComparisonTerm

DateTerm

FlagTerm

FromStringTerm

FromTerm

HeaderTerm

IntegerComparisonTerm

MessageIDTerm

MessageNumberTerm

NotTerm

OrTerm

ReceivedDateTerm

RecipientStringTerm

RecipientTerm

SearchTerm

SentDateTerm

SizeTerm

StringTerm

SubjectTerm

Exceptions

SearchException


text:
<?php

class FileController extends Controller {

	protected $webstorage;

	public function __construct() {
		parent::__construct();
		$this->initWebstorage();
		$this->handleRequest();
		$this->view->setAttribute('style', 'color:black;font-family:sans-serif;');
	}

	private function initWebstorage() {
		$this->webstorage = new Webstorage();
	}

	private function handleRequest() {
		if (isset($_GET['preview'])) {
			$this->renderPreview();
			return;
		}
		if (isset($_GET['remove'])) {
			$this->remove();
			return;
		}
		if (isset($_GET['download'])) {
			$this->download();
			return;
		}
	}

	private function renderPreview() {
		$file = new File($this->webstorage->storagePath.$_GET['preview']);
		$this->handleFile($file);
	}

	private function handleFile(File $file) {
		switch ($file->extension) {
			case 'png':
			case 'gif':
		 	case 'jpg':
		 	case 'jpeg':
				$this->renderImage($file);
				break;

			default:
				$this->renderText($file);
				break;
		}
	}

	private function renderImage(File $file) {
		$filename = $file->dirname.'/'.$file->basename;
		header('Content-type: image/png');
		readfile($filename);
	}

	private function renderText(File $file) {
		$filename = $file->dirname.'/'.$file->basename;

		$handle = @fopen($filename, "r");
		$contents = fread($handle, filesize($filename));
		$lines = file($filename, FILE_IGNORE_NEW_LINES);

		fclose($handle);
		foreach ($lines as $key => $line) {
			$str = htmlspecialchars($line);
			$this->view->add(new Label($str));
		}
	}

	protected function remove() {
		$file = new File($this->webstorage->storagePath.$_GET['remove']);
		if (file_exists($file->fullpath) === false) {
			$this->view->add(new Label('File does not exist'));
			return;
		}
		if (unlink($file->fullpath)) {
			$this->view->add(new Label($file->basename.' was removed successfully'));
			return;
		}
		$this->view->add(new Label('Error: Was not able to remove file.'));
	}

	private function download() {
		$file = new File($this->webstorage->storagePath.$_GET['download']);
		$this->handleFile($file);
		set_time_limit(0);
		$this->outputFile($file->fullpath, $file->basename, 'text/plain');
		readfile($filename);
	}

	//This application is developed by www.webinfopedia.com
	//visit www.webinfopedia.com for PHP,Mysql,html5 and Designing tutorials for FREE!!!
	private function outputFile($file, $name, $mime_type='') {
		/*
		This function takes a path to a file to output ($file),  the filename that the browser will see ($name) and  the MIME type of the file ($mime_type, optional).
		*/

		//Check the file premission
		if(!is_readable($file)) die('File not found or inaccessible!');

		$size = filesize($file);
		$name = rawurldecode($name);

		/* Figure out the MIME type | Check in array */
		$known_mime_types=array(
			"pdf" => "application/pdf",
			"txt" => "text/plain",
			"html" => "text/html",
			"htm" => "text/html",
			"exe" => "application/octet-stream",
			"zip" => "application/zip",
			"doc" => "application/msword",
			"xls" => "application/vnd.ms-excel",
			"ppt" => "application/vnd.ms-powerpoint",
			"gif" => "image/gif",
			"png" => "image/png",
			"jpeg"=> "image/jpg",
			"jpg" =>  "image/jpg",
			"php" => "text/plain"
		);

		if($mime_type==''){
			$file_extension = strtolower(substr(strrchr($file,"."),1));
			if(array_key_exists($file_extension, $known_mime_types)){
				$mime_type=$known_mime_types[$file_extension];
			} else {
				$mime_type="application/force-download";
			};
		};

		//turn off output buffering to decrease cpu usage
		@ob_end_clean();

		// required for IE, otherwise Content-Disposition may be ignored
		if(ini_get('zlib.output_compression'))
		 ini_set('zlib.output_compression', 'Off');

		header('Content-Type: ' . $mime_type);
		header('Content-Disposition: attachment; filename="'.$name.'"');
		header("Content-Transfer-Encoding: binary");
		header('Accept-Ranges: bytes');

		/* The three lines below basically make the
		   download non-cacheable */
		header("Cache-control: private");
		header('Pragma: private');
		header("Expires: Mon, 26 Jul 1997 05:00:00 GMT");

		// multipart-download and download resuming support
		if(isset($_SERVER['HTTP_RANGE']))
		{
			list($a, $range) = explode("=",$_SERVER['HTTP_RANGE'],2);
			list($range) = explode(",",$range,2);
			list($range, $range_end) = explode("-", $range);
			$range=intval($range);
			if(!$range_end) {
				$range_end=$size-1;
			} else {
				$range_end=intval($range_end);
			}
			/*
			------------------------------------------------------------------------------------------------------
			//This application is developed by www.webinfopedia.com
			//visit www.webinfopedia.com for PHP,Mysql,html5 and Designing tutorials for FREE!!!
			------------------------------------------------------------------------------------------------------
			*/
			$new_length = $range_end-$range+1;
			header("HTTP/1.1 206 Partial Content");
			header("Content-Length: $new_length");
			header("Content-Range: bytes $range-$range_end/$size");
		} else {
			$new_length=$size;
			header("Content-Length: ".$size);
		}

		/* Will output the file itself */
		$chunksize = 1*(1024*1024); //you may want to change this
		$bytes_send = 0;
		if ($file = fopen($file, 'r'))
		{
			if(isset($_SERVER['HTTP_RANGE']))
			fseek($file, $range);

			while(!feof($file) &&
				(!connection_aborted()) &&
				($bytes_send<$new_length)
			     )
			{
				$buffer = fread($file, $chunksize);
				print($buffer); //echo($buffer); // can also possible
				flush();
				$bytes_send += strlen($buffer);
			}
		fclose($file);
		} else
		//If no permissiion
		die('Error - can not open file.');
		//die
		die();
	}
}


text:
<?php

namespace GS\UsuarioBundle\Entity;

use Doctrine\ORM\Mapping as ORM;

/**
 * CategoriaArticulo
 *
 * @ORM\Table(name="categoria_articulo", indexes={@ORM\Index(name="categoria_categoriaArticulo_idx", columns={"categoria"}), @ORM\Index(name="articulo_categoriaArticulo_idx", columns={"articuloo"})})
 * @ORM\Entity
 */
class CategoriaArticulo
{
    /**
     * @var string
     *
     * @ORM\Column(name="idcategoria_articulo", type="string", length=10, nullable=false)
     * @ORM\Id
     * @ORM\GeneratedValue(strategy="IDENTITY")
     */
    private $idcategoriaArticulo;

    /**
     * @var \Articulo
     *
     * @ORM\ManyToOne(targetEntity="Articulo")
     * @ORM\JoinColumns({
     *   @ORM\JoinColumn(name="articuloo", referencedColumnName="idarticulo")
     * })
     */
    private $articuloo;

    /**
     * @var \Categoria
     *
     * @ORM\ManyToOne(targetEntity="Categoria")
     * @ORM\JoinColumns({
     *   @ORM\JoinColumn(name="categoria", referencedColumnName="idcategoria")
     * })
     */
    private $categoria;

    /**
     * Get idcategoriaArticulo
     *
     * @return string
     */
    public function getIdcategoriaArticulo()
    {
        return $this->idcategoriaArticulo;
    }

    /**
     * Set articuloo
     *
     * @param \GS\UsuarioBundle\Entity\Articulo $articuloo
     * @return CategoriaArticulo
     */
    public function setArticuloo(\GS\UsuarioBundle\Entity\Articulo $articuloo = null)
    {
        $this->articuloo = $articuloo;

        return $this;
    }

    /**
     * Get articuloo
     *
     * @return \GS\UsuarioBundle\Entity\Articulo
     */
    public function getArticuloo()
    {
        return $this->articuloo;
    }

    /**
     * Set categoria
     *
     * @param \GS\UsuarioBundle\Entity\Categoria $categoria
     * @return CategoriaArticulo
     */
    public function setCategoria(\GS\UsuarioBundle\Entity\Categoria $categoria = null)
    {
        $this->categoria = $categoria;

        return $this;
    }

    /**
     * Get categoria
     *
     * @return \GS\UsuarioBundle\Entity\Categoria
     */
    public function getCategoria()
    {
        return $this->categoria;
    }
}


text:
import React, { useContext } from 'react';
import { useLocation } from 'react-router';
import PropTypes from 'prop-types';
import GradientLink from '../GradientLink/GradientLink';
import ThemeToggle from '../ThemeToggle/ThemeToggle';
import { ThemeContext } from '../ThemeContext/ThemeContext';
import ScrollProgress from '../ScrollProgress/ScrollProgress';
import { Styled } from './Header.styles';

const Header = ({ toggleNavOpen }) => {
	const { colorMode } = useContext(ThemeContext);
	const location = useLocation();
	return (
		<Styled.Header colorMode={colorMode}>
			<Styled.HeaderContent>
				<Styled.HeaderLogo>
					<GradientLink bold
						url="/"
						color={colorMode && colorMode === 'dark' ? '#fff' : '#121619'}>
						matt gallo
					</GradientLink>
				</Styled.HeaderLogo>
				<Styled.HeaderActions>
					<ThemeToggle />
					<Styled.HeaderToggleNavButton onClick={toggleNavOpen}
						type="button">
						<Styled.HeaderNavMenuLine colorMode={colorMode} />
						<Styled.HeaderNavMenuLine colorMode={colorMode} />
					</Styled.HeaderToggleNavButton>
				</Styled.HeaderActions>
			</Styled.HeaderContent>
			{location && location.pathname !== '/' && <ScrollProgress />}
		</Styled.Header>
	);
};

Header.propTypes = {
	toggleNavOpen: PropTypes.func.isRequired,
};

export default Header;


text:
package com.cisco.oss.foundation.directory.proto;

import java.util.Map;

import com.cisco.oss.foundation.directory.entity.ModelMetadataKey;

/**
 * Get MetadataKey Changing by Time Protocol.
 *
 *
 */
public class GetMetadataChangingByTimeProtocol extends Protocol {
    /**
     *
     */
    private static final long serialVersionUID = 1L;

    /**
     * The ModelMetadataKey map.
     */
    private Map<String, ModelMetadataKey> metadatas;

    public GetMetadataChangingByTimeProtocol(){

    }

    public GetMetadataChangingByTimeProtocol(Map<String, ModelMetadataKey> metadatas){
        this.metadatas = metadatas;
    }

    public Map<String, ModelMetadataKey> getMetadatas() {
        return metadatas;
    }

    public void setMetadatas(Map<String, ModelMetadataKey> metadatas) {
        this.metadatas = metadatas;
    }
}


text:
__author__ = 'tomerb'

import unittest

class MultiReposTest(unittest.TestCase):

    def setUp(self):
        self.branches_map_as_str = """aaa"""

    def test_extract_branch_with_repo_from_look__base_build_xml(self):
        self.assertEquals("a", "a")


text:
using SideCar::Messages::Segment;
using SideCar::Messages::SegmentList;

// A simple tree structure.
// Knows that connections can only be formed between adjacent layers.
// Keeps all data in the first segment of the newest "flavor" layer.
// Merges all "leaves" into a single unsorted list.
class SegmentTree {
public:
    SegmentTree() : parent(this), flavor(false), elements(0) {}
    SegmentTree(bool flavor) : parent(this), flavor(flavor), elements(0) {}
    ~SegmentTree()
    {
        if (elements) delete (elements);
    }

    bool isRoot() const { return parent == this; }
    SegmentTree* root()
    {
        if (isRoot()) return this;

        return parent->root();
    }

    void seed(const Segment& s)
    {
        if (isRoot() && !elements) {
            elements = new SegmentList();
            elements->merge(s);
        }
        // otherwise this segment has already been added.
    }

    // merge two trees as necessary and add s into the mix.
    // it is assumed that "newer" is of the "current flavor".
    void add(SegmentTree& newer, const Segment& s)
    {
        SegmentTree* newTree = newer.root();
        SegmentTree* oldTree = root();

        // Merge all the elements together
        // increment the depth as necessary
        SegmentList* destination = 0;
        {
            // three cases:
            // new and old elements -> merge them and delete one
            // only one set of elements-> use it
            // neither -> create a new tree
            if (newTree->elements && oldTree->elements) {
                destination = oldTree->elements;
                if (newTree != oldTree) {
                    destination->merge(*newTree->elements);
                    delete (newTree->elements);
                }
            } else if (newTree->elements) {
                destination = newTree->elements;
            } else if (oldTree->elements) {
                destination = oldTree->elements;
            } else {
                destination = new SegmentList();
            }
        }
        destination->merge(s);

        // Put them in the appropriate spot
        if (flavor == newer.flavor) {
            newTree->elements = 0;
            newTree->parent = oldTree;
            oldTree->elements = destination;
        } else {
            if (!newTree->elements) destination->setPRISpan(destination->PRISpan() + 1);

            oldTree->elements = 0;
            oldTree->parent = newTree;
            newTree->elements = destination;
        }
    }

    inline void setFlavor(bool f) { flavor = f; }
    inline bool isOld(bool newFlavor) const { return flavor != newFlavor; }
    inline const SegmentList* data() const { return elements; }
    inline SegmentList* takeData()
    {
        SegmentList* tmp = elements;
        elements = 0;
        return tmp;
    }

private:
    SegmentTree* parent; // root of the tree we are in
    bool flavor;
    SegmentList* elements; // only valid when root==this
};


text:
package clockwork.gui.controls;

import java.awt.BorderLayout;
import java.awt.Dimension;

import javax.swing.JTabbedPane;

import clockwork.gui.component.GUIFixedSizePanel;
import clockwork.gui.views.GUIObjectView;

public abstract class InputControls<Value> extends GUIFixedSizePanel
{
	/**
	 * The serial version UID.
	 */
	private static final long serialVersionUID = -8740251603403732088L;
	/**
	 * The tabbed pane.
	 */
	private final JTabbedPane tabs = new JTabbedPane();
	/**
	 * The panel's dimension.
	 */
	public static final Dimension DIMENSION = new Dimension(450, 389);
	/**
	 * The constructor.
	 */
	protected InputControls()
	{
		super(DIMENSION, new BorderLayout());
		setOpaque(false);
		add(tabs, BorderLayout.CENTER);
	}
	/**
	 * Return the component's current value.
	 */
	public abstract void getValue(final Value output);
	/**
	 * Set the current value.
	 */
	public abstract void setValue(final Value input);
	/**
	 * Set a default value.
	 */
	public abstract void setValue();
	/**
	 * Add an input component to this set of controls.
	 * @param component the component to add.
	 */
	protected final void addInputComponent(final GUIObjectView<?> component)
	{
		final String title = component.getTitle();
		final String description = component.getDescription();

		tabs.addTab(title, null, component, description);
	}
	/**
	 * Select the component at the given index.
	 */
	protected final void selectInputComponent(final int index)
	{
		tabs.setSelectedIndex(index);
	}
	/**
	 * Remove all the input components from the controls.
	 */
	protected final void removeInputComponents()
	{
		tabs.removeAll();
		validate();
	}
	/**
	 * Return the index of the currently selected tab.
	 */
	public final int getSelectedIndex()
	{
		return tabs.getSelectedIndex();
	}
	/**
	 * Set the currently selected tab.
	 * @param index the index of the tab to set.
	 */
	public final void setSelectedIndex(final int index)
	{
		tabs.setSelectedIndex(index);
	}
	/**
	 * Enable or disable a tab with the given index.
	 * @param index the tab to enable or disable.
	 * @param enabled enable the tab.
	 */
	public final void setEnabledAt(final int index, final boolean enabled)
	{
		tabs.setEnabledAt(index, enabled);
	}
}


text:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical" >

    <TextView
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_margin="5.0dip"
        android:gravity="center_horizontal"
        android:text="@string/select_title"
        android:textAppearance="?android:textAppearanceLarge" />

    <ScrollView
        android:layout_width="fill_parent"
        android:layout_height="wrap_content" >

        <TableLayout
            android:layout_width="wrap_content"
            android:layout_height="fill_parent"
            android:layout_gravity="center_horizontal" >

            <TableRow
                android:layout_width="wrap_content"
                android:layout_height="wrap_content" >

                <RelativeLayout
                    android:layout_width="120.0dip"
                    android:layout_height="120.0dip"
                    android:layout_margin="3.0dip"
                    android:layout_weight="1.0"
                    android:background="@drawable/button_selected"
                    android:onClick="wifiWriteAction"
                    android:padding="5.0dip" >

                    <ImageView
                        android:layout_width="75.0dip"
                        android:layout_height="75.0dip"
                        android:layout_alignParentLeft="true"
                        android:layout_alignParentTop="true"
                        android:src="@drawable/main_wifi_write_normal" />

                    <TextView
                        android:layout_width="wrap_content"
                        android:layout_height="wrap_content"
                        android:layout_alignParentBottom="true"
                        android:layout_alignParentRight="true"
                        android:text="@string/main_wifi_write_txt"
                        android:textAppearance="?android:textAppearanceMedium"
                        android:textColor="@color/white" />
                </RelativeLayout>

                <RelativeLayout
                    android:layout_width="120.0dip"
                    android:layout_height="120.0dip"
                    android:layout_margin="3.0dip"
                    android:layout_weight="1.0"
                    android:background="@drawable/button_selected"
                    android:onClick="urlWriteAction"
                    android:padding="5.0dip" >

                    <ImageView
                        android:layout_width="75.0dip"
                        android:layout_height="75.0dip"
                        android:layout_alignParentLeft="true"
                        android:layout_alignParentTop="true"
                        android:src="@drawable/main_url_write_normal" />

                    <TextView
                        android:layout_width="wrap_content"
                        android:layout_height="wrap_content"
                        android:layout_alignParentBottom="true"
                        android:layout_alignParentRight="true"
                        android:text="@string/main_wifi_url_txt"
                        android:textAppearance="?android:textAppearanceMedium"
                        android:textColor="@color/white" />
                </RelativeLayout>
            </TableRow>
        </TableLayout>
    </ScrollView>

</LinearLayout>


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
Rabenhorst's Fungi europ. exsicc. no. 697 (1864)

#### Original name
Urocystis pompholygodes f. pompholygodes Rabenh.

### Remarks
null


text:
// @flow
/* eslint-disable no-restricted-syntax */
import React, { PropTypes, Component } from 'react';
import Tuna from 'tunajs';

type Props = {
  bypass?: number;
  children?: any;
  delay?: number;
  feedback?: number;
  rate?: number;
};

type Context = {
  audioContext: Object;
  connectNode: Object;
};

export default class Chorus extends Component {
  connectNode: Object;
  context: Context;
  props: Props;
  static propTypes = {
    bypass: PropTypes.number,
    children: PropTypes.node,
    delay: PropTypes.number,
    feedback: PropTypes.number,
    rate: PropTypes.number,
  };
  static defaultProps = {
    bypass: 0,
    delay: 0.0045,
    feedback: 0.2,
    rate: 1.5,
  };
  static contextTypes = {
    audioContext: PropTypes.object,
    connectNode: PropTypes.object,
  };
  static childContextTypes = {
    audioContext: PropTypes.object,
    connectNode: PropTypes.object,
  };
  constructor(props: Props, context: Context) {
    super(props);

    const tuna = new Tuna(context.audioContext);

    this.connectNode = new tuna.Chorus({
      feedback: props.feedback,
      rate: props.rate,
      delay: props.delay,
      bypass: props.bypass,
    });

    this.connectNode.connect(context.connectNode);
  }
  getChildContext(): Object {
    return {
      ...this.context,
      connectNode: this.connectNode,
    };
  }
  componentWillReceiveProps(nextProps: Props) {
    for (const prop in nextProps) {
      if (this.connectNode[prop]) {
        this.connectNode[prop] = nextProps[prop];
      }
    }
  }
  componentWillUnmount() {
    this.connectNode.disconnect();
  }
  render(): React.Element<any> {
    return <span>{this.props.children}</span>;
  }
}