<commit_before>/*
 * Licensed to the Sakai Foundation (SF) under one
 * or more contributor license agreements. See the NOTICE file
 * distributed with this work for additional information
 * regarding copyright ownership. The SF licenses this file
 * to you under the Apache License, Version 2.0 (the
 * "License"); you may not use this file except in compliance
 * with the License. You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing,
 * software distributed under the License is distributed on an
 * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
 * KIND, either express or implied. See the License for the
 * specific language governing permissions and limitations under the License.
 */

/*global $, Config, History, Widgets */

var sakai = sakai || {};
sakai.search = function() {

    //////////////////////////
    //    Config variables    //
    //////////////////////////

    var resultsToDisplay = 12;
    var searchterm = "";
    var currentpage = 0;
    var foundPeople = [];
    var contactclicked = false;
    var mainSearch = false;
    var max_items = 2000;

    // Search URL mapping
    var searchURLmap = {
        allusers : sakai.config.URL.SEARCH_USERS,
        mycontacts : sakai.config.URL.SEARCH_USERS_ACCEPTED,
        invitedcontacts : sakai.config.URL.CONTACTS_INVITED,
        pendingcontacts : sakai.config.URL.CONTACTS_PENDING,
        onlinecontacts : sakai.config.URL.PRESENCE_CONTACTS_SERVICE
    };

    //    CSS IDs

    var search = "#search";

    var searchConfig = {
        search : "#search",
        global : {
            resultTemp : search + "_result_temp",
            button : search + "_button",
            text  :search + '_text',
            numberFound : search + '_numberFound',
            searchTerm : search + "_mysearchterm",
            searchBarSelectedClass : "search_bar_selected",
            pagerClass : ".jq_pager",
            messageClass : ".search_result_person_link_message",
            messageID : "search_result_person_link_message_",
            addToContactsLink : ".link_add_to_contacts",
            addToContactsDialog : '#add_to_contacts_dialog',
            sendmessageContainer : "#sendmessagecontainer"
        },
        addFriend : {
            types : '#add_friend_types',
            typesList : 'add_friends_list_type',
            typesTemplate : "add_friend_types_template",
            displayNameClass : ".add_friend_displayname",
            profilePicture : "#add_friend_profilepicture",
            personalNote : "#add_friend_personal_note",
            personalNoteTemplate : "add_friend_personal_note_template",
            doInvite : "#add_friends_do_invite",
            form : "#add_friends_form",
            response: "#add_to_contacts_response",
            addToContacts : "#link_add_to_contacts_{USERID}",
            addToContactsDivider : "#link_add_to_contacts_{USERID}_divider",
            errors : {
                request : "#add_to_contacts_error_request",
                message : "#add_to_contacts_error_message",
                noTypeSelected : "#add_to_contacts_error_noTypeSelected"
            }

        },
        filters : {
            filter : search + "_filter",
            sites : {
                filterSites : search + "_filter_my_sites",
                filterSitesTemplate : "search_filter_my_sites_template",
                ids : {
                    entireCommunity : '#search_filter_community',
                    allMySites : '#search_filter_all_my_sites',
                    specificSite : '#search_filter_my_sites_'
                },
                values : {
                    entireCommunity :'entire_community',
                    allMySites : "all_my_sites"
                }
            }
        },
        tabs : {
            all : "#tab_search_all",
            content : "#tab_search_content",
            people : "#tab_search_people",
            sites : "#tab_search_sites"
        },
        results : {
            container : search + '_results_container',
            header : search + '_results_header',
            template : 'search_results_template'
        },
        facetedConfig : {
            title : "Refine your search",
            value : "People",
            categories : ["All Users", "My Contacts", "Online Now", "Invited", "Requested", "Not known"],
            searchurls : [searchURLmap.allusers, searchURLmap.mycontacts, searchURLmap.onlinecontacts, searchURLmap.invitedcontacts, searchURLmap.pendingcontacts, '']
        }
    };

    //////////////////
    //    functions    //
    //////////////////

    /**
     * This method will show all the appropriate elements for when a search is executed.
     */
    var showSearchContent = function() {
        $(searchConfig.global.searchTerm).text(sakai.api.Security.saneHTML(searchterm));
        $(searchConfig.global.numberFound).text("0");
        $(searchConfig.results.header).show();
        $(searchConfig.results.container).html($(searchConfig.global.resultTemp).html());
    };

    /**
     * This method will cretae a flat space separeted
     * string from a numbered object. For example: obj = {0:"Foo",1:"Bar"} will return "Foo Bar"
     * @param {Object} input_object
     * @return {String} The concatenated String
     */
    var concatObjectValues = function(input_object) {

        var return_string = "";

        // Error handling
        if ((input_object.length === 0) || (!input_object)) {
            return return_string;
        }

        // Concatenate
        for (var i = 0, j = input_object.length; i<j; i++) {
            return_string += input_object[i]+" ";
        }

        // Remove extra space at the end
        return_string = return_string.substring(0,return_string.length-1);

        return return_string;
    };

    /**
     * Will search for a user in the list of results we got from the server.
     * @param {String} userid
     * @return Will return the user object if something is found, false if nothing is found.
     */
    var searchPerson = function(userid) {
        var person = false;
        for (var i = 0, j = foundPeople.length; i<j; i++) {
            if (foundPeople[i].userid === userid) {
                person = foundPeople[i];
                break;
            }
        }
        return person;
    };

    //////////////////////////////
    //    Search functionality    //
    //////////////////////////////

    /**
     * Used to do a search. This will add the page and the searchterm to the url and add
     * it too the history without reloading the page. This way the user can navigate
     * using the back and forward button.
     * @param {Integer} page The page you are on (optional / default = 1.)
     * @param {String} searchquery The searchterm you want to look for (optional / default = input box value.)
     */
    var doHSearch = function(page, searchquery, searchwhere) {
        if (!page) {
            page = 1;
        }
        if (!searchquery) {
            searchquery = $(searchConfig.global.text).val().toLowerCase();
        }
        if (!searchwhere) {
            searchwhere = mainSearch.getSearchWhereSites();
        }
        currentpage = page;
        //    This will invoke the sakai._search.doSearch function and change the url.
        History.addBEvent(page, encodeURIComponent(searchquery), searchwhere);
    };

    /**
     * When the pager gets clicked.
     * @param {integer} pageclickednumber The page you want to go to.
     */
    var pager_click_handler = function(pageclickednumber) {
        currentpage = pageclickednumber;
        //    Redo the search
        doHSearch(currentpage, searchterm);
    };

    /**
     * This will render all the results we have found.
     * @param {Object} results The json object containing all the result info.
     * @param {Boolean} success If the request was succesfull or not
     */
    var renderResults = function(results, success) {
        var finaljson = {};
        finaljson.items = [];
        if (success) {

            // Adjust display global total
            // If number is higher than a configurable threshold show a word instead conveying ther uncountable volume -- TO DO: i18n this
            if ((results.total <= sakai.config.Search.MAX_CORRECT_SEARCH_RESULT_COUNT) && (results.total >= 0)) {
                $(searchConfig.global.numberFound).text(""+results.total);
            } else if (results.results.length <= 0) {
                $(searchConfig.global.numberFound).text(0);
            } else {
                $(searchConfig.global.numberFound).text("thousands");
            }

            // Reset the pager.
            $(searchConfig.global.pagerClass).pager({
                pagenumber: currentpage,
                pagecount: Math.ceil(results.total / resultsToDisplay),
                buttonClickCallback: pager_click_handler
            });

            if (results.results) {
                finaljson = mainSearch.preparePeopleForRender(results.results, finaljson);
            }

            // If we don't have any results or they are less then the number we should display
            // we hide the pager
            if ((results.total < resultsToDisplay) || (results.results.length <= 0)) {
                $(searchConfig.global.pagerClass).hide();
            }
            else {
                $(searchConfig.global.pagerClass).show();
            }

        }
        else {
            $(searchConfig.global.pagerClass).hide();
        }
        foundPeople = finaljson.items;
        //    Render the results.
        $(searchConfig.results.container).html($.TemplateRenderer(searchConfig.results.template, finaljson));
        $("#search_results_page1").show();
    };

    //////////////////////////
    //    _search functions    //
    //////////////////////////

    /*
     * These are functions that are defined in search_history.js .
     * We override these with our owm implementation.
     */

    /**
     * This function gets called everytime the page loads and a new searchterm is entered.
     * It gets called by search_history.js
     * @param {Integer} page The page you are on.
     * @param {String} searchquery The searchterm you want to search trough.
     * @param {string} searchwhere The subset of contact you want to search in.
     *  * = entire community
     *  my contacts = the site the user is registered on
     */
    sakai._search.doSearch = function(page, searchquery, searchwhere) {

        facetedurl = mainSearch.getFacetedUrl();

        if (isNaN(page)){
            page = 1;
        }

        currentpage = parseInt(page,  10);

        //    Set all the input fields and paging correct.
        mainSearch.fillInElements(page, searchquery, searchwhere);

        //    Get the search term out of the input box.
        //    If we were redirected to this page it will be added previously already.
        searchterm = $(searchConfig.global.text).val().toLowerCase();

        //    Rebind everything
        mainSearch.addEventListeners(searchterm, searchwhere);

        if (searchterm) {
            // Show and hide the correct elements.
            showSearchContent();

            // Set off the AJAX request

            // Look to in which place we are searching (is it all the contacts or only my contacts)
            var searchWhere = mainSearch.getSearchWhereUsers();

            // What are we looking for?
            var urlsearchterm = mainSearch.prepSearchTermForURL(searchterm);

            // The search URL depends on the searchWhere variable
            var searchURL;

            if(searchWhere === "mycontacts") {
                searchURL = sakai.config.URL.SEARCH_USERS_ACCEPTED + "&q=" + urlsearchterm;
            }  else {
                searchURL = sakai.config.URL.SEARCH_USERS + "?page=" + (currentpage - 1) + "&items=" + resultsToDisplay + "&q=" + urlsearchterm + "&sortOn=sakai:firstName&sortOrder=ascending";
            }

            // Check if we want to search using a faceted link
            if (facetedurl)
                searchURL = facetedurl + "?page=" + (currentpage - 1) + "&items=" + resultsToDisplay + "&q=" + urlsearchterm + "&sortOn=sakai:firstName&sortOrder=ascending";

            $.ajax({
                cache: false,
                url: searchURL,
                success: function(data) {

                    // Store found people in data cache
                    sakai.data.search.results_people = {};

                    // if results are returned in a different format
                    if (!data.results && data.contacts && facetedurl === sakai.config.URL.PRESENCE_CONTACTS_SERVICE) {
                        var resultsTemp = { results : [] };
                        var j = 0;
                        $.each(data.contacts, function(i, val) {
                            if (val.profile && val["sakai:status"] === "online") {
                                resultsTemp.results[j] = val.profile;
                                j++;
                            }
                        });
                        data = resultsTemp;
                    } else if (data.results) {
                        var resultsTemp = { results : [] };
                        var updateData = false;
                        $.each(data.results, function(i, val) {
                            if (val.profile) {
                                resultsTemp.results[i] = val.profile;
                                updateData = true;
                            }
                        });
                        if (updateData)
                            data = resultsTemp;
                    }

                    for (var i = 0, j = data.results.length; i < j; i++) {
                        sakai.data.search.results_people[data.results[i]["rep:userId"]] = data.results[i];
                    }

                    renderResults(data, true);
                },
                error: function(xhr, textStatus, thrownError) {
                    sakai.data.search.results_people = {};
                    renderResults(sakai.data.search.results_people, false);
                }
            });

        }
        else {
            sakai._search.reset();
        }
    };

    /**
     * Will reset the view to standard.
     */
    sakai._search.reset = function() {
        $(searchConfig.results.header).hide();
    };

    ///////////////////////////////////
    // Create site with found people //
    ///////////////////////////////////

    $("#create_site_these_people_link").bind("click", function(ev){
        var searchterm = $(searchConfig.global.text).val().toLowerCase();
        var urlsearchterm = mainSearch.prepSearchTermForURL(searchterm);
        var url = sakai.config.URL.SEARCH_USERS + "?page=" + 0 + "&items=" + results.total + "&q=" + urlsearchterm;
        $.ajax({
            cache: false,
            url: url,
            success: function(data) {
                var finaljson = {};
                finaljson.items = [];
                finaljson = mainSearch.preparePeopleForRender(data.results, finaljson);
                sakai.createsite.initialise(finaljson);
            },
            error: function(xhr, textStatus, thrownError) {
                alert(sakai.api.i18n.Widgets.getValueForKey("__MSG__AN_ERROR_HAS_OCCURED__"));
            }
        });
    });

    //////////////////////
    //    Event binding    //
    //////////////////////

    /** When a user wants to message another  user */
    $(searchConfig.global.messageClass).live("click", function() {
        var reg = new RegExp(searchConfig.global.messageID, "gi");
        var contactclicked = $(this).attr("id").replace(reg,"");
        var person = searchPerson(contactclicked);
        if (contactclicked) {
            $(searchConfig.global.sendmessageContainer).show();
            if (!person.uuid) {
                person.uuid = person.userid;
            }
            if (!person.hasOwnProperty("firstName") && !person.hasOwnProperty("lastName")) {
                person.firstName = person.uuid;
                person.lastName = "";
            }
            sakai.sendmessage.initialise(person, true);
        }
    });

    /** A user want to make a new friend. */
    $(searchConfig.global.addToContactsLink).live("click", function(ev) {
        contactclicked = this.id.split("_")[4];
        sakai.addtocontacts.initialise(contactclicked, mainSearch.removeAddContactLinks);
    });

    //////////////////////
    //    init function    //
    //////////////////////

    var thisFunctionality = {
        "doHSearch" : doHSearch
    };

    /**
     * Will fetch the sites and add a new item to the history list.
     */
    var doInit = function() {
        mainSearch = sakai._search(searchConfig, thisFunctionality);
        //    Make sure that we are still logged in.
        if (mainSearch.isLoggedIn()) {
            //    Get my friends
            mainSearch.fetchMyFriends();
            //    add the bindings
            mainSearch.addEventListeners();

            // display faceted panel
            mainSearch.addFacetedPanel();
        }
    };
    doInit();
};

sakai.api.Widgets.Container.registerForLoad("sakai.search");
<commit_msg>SAKIII-733 changes to people search facet name from currently online to contact currently online<commit_after>/*
 * Licensed to the Sakai Foundation (SF) under one
 * or more contributor license agreements. See the NOTICE file
 * distributed with this work for additional information
 * regarding copyright ownership. The SF licenses this file
 * to you under the Apache License, Version 2.0 (the
 * "License"); you may not use this file except in compliance
 * with the License. You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing,
 * software distributed under the License is distributed on an
 * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
 * KIND, either express or implied. See the License for the
 * specific language governing permissions and limitations under the License.
 */

/*global $, Config, History, Widgets */

var sakai = sakai || {};
sakai.search = function() {

    //////////////////////////
    //    Config variables    //
    //////////////////////////

    var resultsToDisplay = 12;
    var searchterm = "";
    var currentpage = 0;
    var foundPeople = [];
    var contactclicked = false;
    var mainSearch = false;
    var max_items = 2000;

    // Search URL mapping
    var searchURLmap = {
        allusers : sakai.config.URL.SEARCH_USERS,
        mycontacts : sakai.config.URL.SEARCH_USERS_ACCEPTED,
        invitedcontacts : sakai.config.URL.CONTACTS_INVITED,
        pendingcontacts : sakai.config.URL.CONTACTS_PENDING,
        onlinecontacts : sakai.config.URL.PRESENCE_CONTACTS_SERVICE
    };

    //    CSS IDs

    var search = "#search";

    var searchConfig = {
        search : "#search",
        global : {
            resultTemp : search + "_result_temp",
            button : search + "_button",
            text  :search + '_text',
            numberFound : search + '_numberFound',
            searchTerm : search + "_mysearchterm",
            searchBarSelectedClass : "search_bar_selected",
            pagerClass : ".jq_pager",
            messageClass : ".search_result_person_link_message",
            messageID : "search_result_person_link_message_",
            addToContactsLink : ".link_add_to_contacts",
            addToContactsDialog : '#add_to_contacts_dialog',
            sendmessageContainer : "#sendmessagecontainer"
        },
        addFriend : {
            types : '#add_friend_types',
            typesList : 'add_friends_list_type',
            typesTemplate : "add_friend_types_template",
            displayNameClass : ".add_friend_displayname",
            profilePicture : "#add_friend_profilepicture",
            personalNote : "#add_friend_personal_note",
            personalNoteTemplate : "add_friend_personal_note_template",
            doInvite : "#add_friends_do_invite",
            form : "#add_friends_form",
            response: "#add_to_contacts_response",
            addToContacts : "#link_add_to_contacts_{USERID}",
            addToContactsDivider : "#link_add_to_contacts_{USERID}_divider",
            errors : {
                request : "#add_to_contacts_error_request",
                message : "#add_to_contacts_error_message",
                noTypeSelected : "#add_to_contacts_error_noTypeSelected"
            }

        },
        filters : {
            filter : search + "_filter",
            sites : {
                filterSites : search + "_filter_my_sites",
                filterSitesTemplate : "search_filter_my_sites_template",
                ids : {
                    entireCommunity : '#search_filter_community',
                    allMySites : '#search_filter_all_my_sites',
                    specificSite : '#search_filter_my_sites_'
                },
                values : {
                    entireCommunity :'entire_community',
                    allMySites : "all_my_sites"
                }
            }
        },
        tabs : {
            all : "#tab_search_all",
            content : "#tab_search_content",
            people : "#tab_search_people",
            sites : "#tab_search_sites"
        },
        results : {
            container : search + '_results_container',
            header : search + '_results_header',
            template : 'search_results_template'
        },
        facetedConfig : {
            title : "Refine your search",
            value : "People",
            categories : ["All Users", "My Contacts", "Contact Currently Online", "Invited", "Requested", "Not known"],
            searchurls : [searchURLmap.allusers, searchURLmap.mycontacts, searchURLmap.onlinecontacts, searchURLmap.invitedcontacts, searchURLmap.pendingcontacts, '']
        }
    };

    //////////////////
    //    functions    //
    //////////////////

    /**
     * This method will show all the appropriate elements for when a search is executed.
     */
    var showSearchContent = function() {
        $(searchConfig.global.searchTerm).text(sakai.api.Security.saneHTML(searchterm));
        $(searchConfig.global.numberFound).text("0");
        $(searchConfig.results.header).show();
        $(searchConfig.results.container).html($(searchConfig.global.resultTemp).html());
    };

    /**
     * This method will cretae a flat space separeted
     * string from a numbered object. For example: obj = {0:"Foo",1:"Bar"} will return "Foo Bar"
     * @param {Object} input_object
     * @return {String} The concatenated String
     */
    var concatObjectValues = function(input_object) {

        var return_string = "";

        // Error handling
        if ((input_object.length === 0) || (!input_object)) {
            return return_string;
        }

        // Concatenate
        for (var i = 0, j = input_object.length; i<j; i++) {
            return_string += input_object[i]+" ";
        }

        // Remove extra space at the end
        return_string = return_string.substring(0,return_string.length-1);

        return return_string;
    };

    /**
     * Will search for a user in the list of results we got from the server.
     * @param {String} userid
     * @return Will return the user object if something is found, false if nothing is found.
     */
    var searchPerson = function(userid) {
        var person = false;
        for (var i = 0, j = foundPeople.length; i<j; i++) {
            if (foundPeople[i].userid === userid) {
                person = foundPeople[i];
                break;
            }
        }
        return person;
    };

    //////////////////////////////
    //    Search functionality    //
    //////////////////////////////

    /**
     * Used to do a search. This will add the page and the searchterm to the url and add
     * it too the history without reloading the page. This way the user can navigate
     * using the back and forward button.
     * @param {Integer} page The page you are on (optional / default = 1.)
     * @param {String} searchquery The searchterm you want to look for (optional / default = input box value.)
     */
    var doHSearch = function(page, searchquery, searchwhere) {
        if (!page) {
            page = 1;
        }
        if (!searchquery) {
            searchquery = $(searchConfig.global.text).val().toLowerCase();
        }
        if (!searchwhere) {
            searchwhere = mainSearch.getSearchWhereSites();
        }
        currentpage = page;
        //    This will invoke the sakai._search.doSearch function and change the url.
        History.addBEvent(page, encodeURIComponent(searchquery), searchwhere);
    };

    /**
     * When the pager gets clicked.
     * @param {integer} pageclickednumber The page you want to go to.
     */
    var pager_click_handler = function(pageclickednumber) {
        currentpage = pageclickednumber;
        //    Redo the search
        doHSearch(currentpage, searchterm);
    };

    /**
     * This will render all the results we have found.
     * @param {Object} results The json object containing all the result info.
     * @param {Boolean} success If the request was succesfull or not
     */
    var renderResults = function(results, success) {
        var finaljson = {};
        finaljson.items = [];
        if (success) {

            // Adjust display global total
            // If number is higher than a configurable threshold show a word instead conveying ther uncountable volume -- TO DO: i18n this
            if ((results.total <= sakai.config.Search.MAX_CORRECT_SEARCH_RESULT_COUNT) && (results.total >= 0)) {
                $(searchConfig.global.numberFound).text(""+results.total);
            } else if (results.results.length <= 0) {
                $(searchConfig.global.numberFound).text(0);
            } else {
                $(searchConfig.global.numberFound).text("thousands");
            }

            // Reset the pager.
            $(searchConfig.global.pagerClass).pager({
                pagenumber: currentpage,
                pagecount: Math.ceil(results.total / resultsToDisplay),
                buttonClickCallback: pager_click_handler
            });

            if (results.results) {
                finaljson = mainSearch.preparePeopleForRender(results.results, finaljson);
            }

            // If we don't have any results or they are less then the number we should display
            // we hide the pager
            if ((results.total < resultsToDisplay) || (results.results.length <= 0)) {
                $(searchConfig.global.pagerClass).hide();
            }
            else {
                $(searchConfig.global.pagerClass).show();
            }

        }
        else {
            $(searchConfig.global.pagerClass).hide();
        }
        foundPeople = finaljson.items;
        //    Render the results.
        $(searchConfig.results.container).html($.TemplateRenderer(searchConfig.results.template, finaljson));
        $("#search_results_page1").show();
    };

    //////////////////////////
    //    _search functions    //
    //////////////////////////

    /*
     * These are functions that are defined in search_history.js .
     * We override these with our owm implementation.
     */

    /**
     * This function gets called everytime the page loads and a new searchterm is entered.
     * It gets called by search_history.js
     * @param {Integer} page The page you are on.
     * @param {String} searchquery The searchterm you want to search trough.
     * @param {string} searchwhere The subset of contact you want to search in.
     *  * = entire community
     *  my contacts = the site the user is registered on
     */
    sakai._search.doSearch = function(page, searchquery, searchwhere) {

        facetedurl = mainSearch.getFacetedUrl();

        if (isNaN(page)){
            page = 1;
        }

        currentpage = parseInt(page,  10);

        //    Set all the input fields and paging correct.
        mainSearch.fillInElements(page, searchquery, searchwhere);

        //    Get the search term out of the input box.
        //    If we were redirected to this page it will be added previously already.
        searchterm = $(searchConfig.global.text).val().toLowerCase();

        //    Rebind everything
        mainSearch.addEventListeners(searchterm, searchwhere);

        if (searchterm) {
            // Show and hide the correct elements.
            showSearchContent();

            // Set off the AJAX request

            // Look to in which place we are searching (is it all the contacts or only my contacts)
            var searchWhere = mainSearch.getSearchWhereUsers();

            // What are we looking for?
            var urlsearchterm = mainSearch.prepSearchTermForURL(searchterm);

            // The search URL depends on the searchWhere variable
            var searchURL;

            if(searchWhere === "mycontacts") {
                searchURL = sakai.config.URL.SEARCH_USERS_ACCEPTED + "&q=" + urlsearchterm;
            }  else {
                searchURL = sakai.config.URL.SEARCH_USERS + "?page=" + (currentpage - 1) + "&items=" + resultsToDisplay + "&q=" + urlsearchterm + "&sortOn=sakai:firstName&sortOrder=ascending";
            }

            // Check if we want to search using a faceted link
            if (facetedurl)
                searchURL = facetedurl + "?page=" + (currentpage - 1) + "&items=" + resultsToDisplay + "&q=" + urlsearchterm + "&sortOn=sakai:firstName&sortOrder=ascending";

            $.ajax({
                cache: false,
                url: searchURL,
                success: function(data) {

                    // Store found people in data cache
                    sakai.data.search.results_people = {};

                    // if results are returned in a different format
                    if (!data.results && data.contacts && facetedurl === sakai.config.URL.PRESENCE_CONTACTS_SERVICE) {
                        var resultsTemp = { results : [] };
                        var j = 0;
                        $.each(data.contacts, function(i, val) {
                            if (val.profile && val["sakai:status"] === "online") {
                                resultsTemp.results[j] = val.profile;
                                j++;
                            }
                        });
                        data = resultsTemp;
                    } else if (data.results) {
                        var resultsTemp = { results : [] };
                        var updateData = false;
                        $.each(data.results, function(i, val) {
                            if (val.profile) {
                                resultsTemp.results[i] = val.profile;
                                updateData = true;
                            }
                        });
                        if (updateData)
                            data = resultsTemp;
                    }

                    for (var i = 0, j = data.results.length; i < j; i++) {
                        sakai.data.search.results_people[data.results[i]["rep:userId"]] = data.results[i];
                    }

                    renderResults(data, true);
                },
                error: function(xhr, textStatus, thrownError) {
                    sakai.data.search.results_people = {};
                    renderResults(sakai.data.search.results_people, false);
                }
            });

        }
        else {
            sakai._search.reset();
        }
    };

    /**
     * Will reset the view to standard.
     */
    sakai._search.reset = function() {
        $(searchConfig.results.header).hide();
    };

    ///////////////////////////////////
    // Create site with found people //
    ///////////////////////////////////

    $("#create_site_these_people_link").bind("click", function(ev){
        var searchterm = $(searchConfig.global.text).val().toLowerCase();
        var urlsearchterm = mainSearch.prepSearchTermForURL(searchterm);
        var url = sakai.config.URL.SEARCH_USERS + "?page=" + 0 + "&items=" + results.total + "&q=" + urlsearchterm;
        $.ajax({
            cache: false,
            url: url,
            success: function(data) {
                var finaljson = {};
                finaljson.items = [];
                finaljson = mainSearch.preparePeopleForRender(data.results, finaljson);
                sakai.createsite.initialise(finaljson);
            },
            error: function(xhr, textStatus, thrownError) {
                alert(sakai.api.i18n.Widgets.getValueForKey("__MSG__AN_ERROR_HAS_OCCURED__"));
            }
        });
    });

    //////////////////////
    //    Event binding    //
    //////////////////////

    /** When a user wants to message another  user */
    $(searchConfig.global.messageClass).live("click", function() {
        var reg = new RegExp(searchConfig.global.messageID, "gi");
        var contactclicked = $(this).attr("id").replace(reg,"");
        var person = searchPerson(contactclicked);
        if (contactclicked) {
            $(searchConfig.global.sendmessageContainer).show();
            if (!person.uuid) {
                person.uuid = person.userid;
            }
            if (!person.hasOwnProperty("firstName") && !person.hasOwnProperty("lastName")) {
                person.firstName = person.uuid;
                person.lastName = "";
            }
            sakai.sendmessage.initialise(person, true);
        }
    });

    /** A user want to make a new friend. */
    $(searchConfig.global.addToContactsLink).live("click", function(ev) {
        contactclicked = this.id.split("_")[4];
        sakai.addtocontacts.initialise(contactclicked, mainSearch.removeAddContactLinks);
    });

    //////////////////////
    //    init function    //
    //////////////////////

    var thisFunctionality = {
        "doHSearch" : doHSearch
    };

    /**
     * Will fetch the sites and add a new item to the history list.
     */
    var doInit = function() {
        mainSearch = sakai._search(searchConfig, thisFunctionality);
        //    Make sure that we are still logged in.
        if (mainSearch.isLoggedIn()) {
            //    Get my friends
            mainSearch.fetchMyFriends();
            //    add the bindings
            mainSearch.addEventListeners();

            // display faceted panel
            mainSearch.addFacetedPanel();
        }
    };
    doInit();
};

sakai.api.Widgets.Container.registerForLoad("sakai.search");
<|endoftext|>


<commit_before>/**
 * Takes photo info and displays it
 *
 * Show photo: $elem.bsurveyphoto('showPhotoInfo', info);
 * Show loading: $elem.bsurveyphoto('showLoading');
 * Show loading: $elem.bsurveyphoto('showNothing');
 */
$.widget('ui.bsurveyphoto', {

	_init: function() {
		var preloaderImg = '/static/i/b-survey-photo__loader.gif';
		var defaultHeight = 400;

		var w = {
				_self: this,
				$element: this.element,
			};
		this.w = w;

		w.lastInfoHeight = defaultHeight;

		w.$info = $('');
		w.$infoPhoto = $('').appendTo(w.$info);
		w.$infoTitle = $('');//.appendTo(w.$info);
		w.$infoTimestampanduser = $('').appendTo(w.$info);
		w.$infoLogo = $('');//.appendTo(w.$info);

		w.$loading = $('
').append($('', {src: preloaderImg}));
		$.preload([preloaderImg]);

		w.$error = $('
').text('Error loading photograph. It seems like it was just deleted or got hidden.');

	},

	showNothing: function() {
		this.w.$element.empty();
	},

	showLoading: function() {
		var w = this.w;

		w.$element.empty();
		w.$element.append(w.$loading);
	},

	showPhotoInfo: function(info) {
		var w = this.w;
		if (info.status === 0) {
			w.$infoPhoto.attr('src', '');
			w.$infoPhoto.attr('src', info.imgSrc);
			w.$infoTitle.text('').text(info.title);
			w.$infoTimestampanduser.text('').text(/*(info.timestamp ? info.timestamp + " " : "") + */"© " + info.user);
			w.$info.attr('href', info.permalink);
			w.$infoLogo.removeClass("flickr panoramio geograph picasa").addClass(info.source);
			w.$element.empty();
			w.$element.append(w.$info);
			w.lastInfoHeight = w.$info.height();
		} else {
			w.$element.empty();
			w.$element.append(w.$error);
			console.log("Faulty photo: ", info);
		};
	},

	isShowingError: function() {
		return this.w.$error.parent().length != 0;
	}
});<commit_msg>Added source to photo author in b-survey-photo<commit_after>/**
 * Takes photo info and displays it
 *
 * Show photo: $elem.bsurveyphoto('showPhotoInfo', info);
 * Show loading: $elem.bsurveyphoto('showLoading');
 * Show loading: $elem.bsurveyphoto('showNothing');
 */
$.widget('ui.bsurveyphoto', {

	_init: function() {
		var preloaderImg = '/static/i/b-survey-photo__loader.gif';
		var defaultHeight = 400;

		var w = {
				_self: this,
				$element: this.element,
			};
		this.w = w;

		w.lastInfoHeight = defaultHeight;

		w.$info = $('');
		w.$infoPhoto = $('').appendTo(w.$info);
		w.$infoTitle = $('');//.appendTo(w.$info);
		w.$infoTimestampanduser = $('').appendTo(w.$info);
		w.$infoLogo = $('');//.appendTo(w.$info);

		w.$loading = $('
').append($('', {src: preloaderImg}));
		$.preload([preloaderImg]);

		w.$error = $('
').text('Error loading photograph. It seems like it was just deleted or got hidden.');

	},

	showNothing: function() {
		this.w.$element.empty();
	},

	showLoading: function() {
		var w = this.w;

		w.$element.empty();
		w.$element.append(w.$loading);
	},

	showPhotoInfo: function(info) {
		var w = this.w;
		if (info.status === 0) {
			w.$infoPhoto.attr('src', '');
			w.$infoPhoto.attr('src', info.imgSrc);
			w.$infoTitle.text('').text(info.title);
			w.$infoTimestampanduser.text('').text(/*(info.timestamp ? info.timestamp + " " : "") + */"© " + info.user + ' (' + _.capitalize(info.source) + ')');
			w.$info.attr('href', info.permalink);
			w.$infoLogo.removeClass("flickr panoramio geograph picasa").addClass(info.source);
			w.$element.empty();
			w.$element.append(w.$info);
			w.lastInfoHeight = w.$info.height();
		} else {
			w.$element.empty();
			w.$element.append(w.$error);
			console.log("Faulty photo: ", info);
		};
	},

	isShowingError: function() {
		return this.w.$error.parent().length != 0;
	}
});<|endoftext|>


<commit_before>'use strict'

// TODO: replace with Array.find once 0.10 support can be dropped
// https://github.com/nodejs/LTS#lts-schedule
var find = function(collection, predicate) {
  var i
  var element

  for (i = 0; i < collection.length; i++) {
    element = collection[i]

    if (predicate(element)) {
      return element
    }
  }
}

var layerTypes = [
  {
    id: 'tcu',
    name: {
      en: 'top copper'
    },
    match: /((F.Cu)|(top\.gbr$))|(\.((cmp$)|(top$)|(gtl$)))|(\.toplayer\.ger$)/i
  },
  {
    id: 'tsm',
    name: {
      en: 'top soldermask'
    },
    match: /((F.Mask)|(topmask))|(\.((stc$)|(tsm$)|(gts$)|(smt$)))|(\.topsoldermask\.ger$)/i
  },
  {
    id: 'tss',
    name: {
      en: 'top silkscreen'
    },
    match: /((F.SilkS)|(topsilk))|(\.((plc$)|(tsk$)|(gto$)|(sst$)))|(\.topsilkscreen\.ger$)/i
  },
  {
    id: 'tsp',
    name: {
      en: 'top solderpaste'
    },
    match: /((F.Paste)|(toppaste))|(\.((crc$)|(tsp$)|(gtp$)|(spt$)))|(\.tcream\.ger$)/i
  },
  {
    id: 'bcu',
    name: {
      en: 'bottom copper'
    },
    match: /(B.Cu|bottom\.gbr$)|(\.((sol$)|(bot$)|(gbl$)))|(\.bottomlayer\.ger$)/i
  },
  {
    id: 'bsm',
    name: {
      en: 'bottom soldermask'
    },
    match: /(B.Mask|bottommask\.)|(\.((sts$)|(bsm$)|(gbs$)|(smb$)))|(\.bottomsoldermask\.ger$)/i
  },
  {
    id: 'bss',
    name: {
      en: 'bottom silkscreen'
    },
    match: /((B.SilkS)|(bottomsilk\.))|(\.((pls$)|(bsk$)|(gbo$)|(ssb$)))|(\.bottomsilkscreen\.ger$)/i
  },
  {
    id: 'bsp',
    name: {
      en: 'bottom solderpaste'
    },
    match: /(B.Paste)|(\.((crs$)|(bsp$)|(gbp$)|(spb$)))|(\.bcream\.ger$)/i
  },
  {
    id: 'icu',
    name: {
      en: 'inner copper'
    },
    match: /(In(ner)?\d+.Cu)|(\.((ly)|(g)|(in))\d+$)|(\.internalplane\d+\.ger$)/i
  },
  {
    id: 'out',
    name: {
      en: 'board outline'
    },
    match: /((Edge.Cuts)|(outline))|(\.((dim$)|(mil$)|(gm[l\d]$)|(gko$)|(fab$)))|(\.boardoutline\.ger$)/i
  },
  {
    id: 'drl',
    name: {
      en: 'drill hits'
    },
    match: /\.((fab\.gbr$)|(cnc$)|(drl$)|(xln$)|(txt$)|(tap$)|(drd$)|(exc$))/i
  },
  {
    id: 'drw',
    name: {
      en: 'gerber drawing'
    },
    match: /.*/
  }
]

module.exports = function whatsThatGerber(filename) {
  return find(layerTypes, function(type) {
    return type.match.test(filename)
  }).id
}

module.exports.getAllTypes = function() {
  return layerTypes.map(function(type) {
    return type.id
  })
}

module.exports.isValidType = function(type) {
  return layerTypes.some(function(layerType) {
    return layerType.id === type
  })
}

module.exports.getFullName = function whatsThatGerberTypeName(typeId, locale) {
  var type = find(layerTypes, function(type) {
    return type.id === typeId
  })

  locale = locale || 'en'

  if (!type || !type.name[locale]) {
    return ''
  }

  return type.name[locale]
}
<commit_msg>Fix issue with using the word "outline" in filename<commit_after>'use strict'

// TODO: replace with Array.find once 0.10 support can be dropped
// https://github.com/nodejs/LTS#lts-schedule
var find = function(collection, predicate) {
  var i
  var element

  for (i = 0; i < collection.length; i++) {
    element = collection[i]

    if (predicate(element)) {
      return element
    }
  }
}

var layerTypes = [
  {
    id: 'tcu',
    name: {
      en: 'top copper'
    },
    match: /((F.Cu)|(top\.gbr$))|(\.((cmp$)|(top$)|(gtl$)))|(\.toplayer\.ger$)/i
  },
  {
    id: 'tsm',
    name: {
      en: 'top soldermask'
    },
    match: /((F.Mask)|(topmask))|(\.((stc$)|(tsm$)|(gts$)|(smt$)))|(\.topsoldermask\.ger$)/i
  },
  {
    id: 'tss',
    name: {
      en: 'top silkscreen'
    },
    match: /((F.SilkS)|(topsilk))|(\.((plc$)|(tsk$)|(gto$)|(sst$)))|(\.topsilkscreen\.ger$)/i
  },
  {
    id: 'tsp',
    name: {
      en: 'top solderpaste'
    },
    match: /((F.Paste)|(toppaste))|(\.((crc$)|(tsp$)|(gtp$)|(spt$)))|(\.tcream\.ger$)/i
  },
  {
    id: 'bcu',
    name: {
      en: 'bottom copper'
    },
    match: /(B.Cu|bottom\.gbr$)|(\.((sol$)|(bot$)|(gbl$)))|(\.bottomlayer\.ger$)/i
  },
  {
    id: 'bsm',
    name: {
      en: 'bottom soldermask'
    },
    match: /(B.Mask|bottommask\.)|(\.((sts$)|(bsm$)|(gbs$)|(smb$)))|(\.bottomsoldermask\.ger$)/i
  },
  {
    id: 'bss',
    name: {
      en: 'bottom silkscreen'
    },
    match: /((B.SilkS)|(bottomsilk\.))|(\.((pls$)|(bsk$)|(gbo$)|(ssb$)))|(\.bottomsilkscreen\.ger$)/i
  },
  {
    id: 'bsp',
    name: {
      en: 'bottom solderpaste'
    },
    match: /(B.Paste)|(\.((crs$)|(bsp$)|(gbp$)|(spb$)))|(\.bcream\.ger$)/i
  },
  {
    id: 'icu',
    name: {
      en: 'inner copper'
    },
    match: /(In(ner)?\d+.Cu)|(\.((ly)|(g)|(in))\d+$)|(\.internalplane\d+\.ger$)/i
  },
  {
    id: 'out',
    name: {
      en: 'board outline'
    },
    match: /(Edge.Cuts)|(\.((dim$)|(mil$)|(gm[l\d]$)|(gko$)|(fab$)))|(\.boardoutline\.ger$)|(\.outline\.gbr$)/i
  },
  {
    id: 'drl',
    name: {
      en: 'drill hits'
    },
    match: /\.((fab\.gbr$)|(cnc$)|(drl$)|(xln$)|(txt$)|(tap$)|(drd$)|(exc$))/i
  },
  {
    id: 'drw',
    name: {
      en: 'gerber drawing'
    },
    match: /.*/
  }
]

module.exports = function whatsThatGerber(filename) {
  return find(layerTypes, function(type) {
    return type.match.test(filename)
  }).id
}

module.exports.getAllTypes = function() {
  return layerTypes.map(function(type) {
    return type.id
  })
}

module.exports.isValidType = function(type) {
  return layerTypes.some(function(layerType) {
    return layerType.id === type
  })
}

module.exports.getFullName = function whatsThatGerberTypeName(typeId, locale) {
  var type = find(layerTypes, function(type) {
    return type.id === typeId
  })

  locale = locale || 'en'

  if (!type || !type.name[locale]) {
    return ''
  }

  return type.name[locale]
}
<|endoftext|>


<commit_before>export default {
  created() {
    const goTop = !this.$store.state.consumerKey || !this.$store.state.consumerSecret || !this.$store.state.type
    if(goTop) this.$router.replace('/')
  }
}
<commit_msg>Fix redirect<commit_after>export default {
  updated() {
    const goTop = !this.$store.state.consumerKey || !this.$store.state.consumerSecret || !this.$store.state.type
    if(goTop) this.$router.replace('/')
  }
}
<|endoftext|>


<commit_before>var words = [];

var exclam = /!/g;
var exclamrepl = [", verily!", ", verily I say!", ", verily I sayeth!", ", I say!", ", I sayeth!", "! Huzzah!", "! Hear Hear!", "! What-ho!", "! Ho!", "! Fie!", ", indeed!"];

var questi = /\?/g;
var questirepl = [", I say?", ", I wonder?", ", wonder I?", ", what say thee?", ", what sayeth thee?", ", what say thou?", ", what sayeth thou?", ", I ponder?", ", I pondereth?", ", pray tell?", ", ho?", ", do tell?"];

var insults = /idiot|fool|bastard/gi;

var insultnoun = ["mongrel", "codpiece", "jackanape", "ape", "coxcomb", "harlot", "hussy", "strumpet", "cur", "clot", "fool", "barnacle", "harpy", "wench", "churl", "pleb", "taffer", "scoundrel", "scalliwag", "mooncalf", "rapscallion", "doxy", "bawd", "tosspot", "cupshot", "recreant", "fustalarion", "scullion", "rampallion", "knave", "barbermonger", "boil", "plague-sore", "carbuncle", "whoreson", "clotpole", "lout", "gudgeon", "puttock", "skainsmate", "varlet", "bladder"];

var insultadj = ["artless", "droning", "fawning", "warped", "paunchy", "puny", "spongy", "ruttish", "vain", "lumpish", "craven", "witless", "pustulent", "infested", "ill-bred", "blind", "scurvy", "puny", "fetid", "vile", "gibbering", "mewling", "rank", "fawning", "moonish", "brutish", "malapert", "curst", "lack-linen", "bottle-ailed", "lyingest", "embossed", "cheating", "crook-pated", "base-court", "hasty-witted", "two-faced", "pox-marked", "toad-brained", "errant", "idle-headed", "quailing", "flap-mouthed", "puking", "fly-bitten", "surly", "tottering", "villainous", "rump-fed", "bootless", "churlish", "tickle-brained", "froward"]

var startmsgs = ["Forsooth,", "I say,", "I sayeth,", "Forsooth, I say,", "Forsooth, say I,", "Forsooth, sayeth I,", "Hark!", "Harketh!", "By <god>,", "By the Will of <god adjective> <god>,", "By the <body part adjective> <body part> of the <god adjective> <god>,", "By <god adjective> <god>'s <body part adjective> <body part>,", "Avast,", "Zounds,", "Perchance,", "Pray tell,", "Prithee,", "What hey,", "What ho,", "Pray,", "Surely", "Pray pardon,", "Alas,", "In short,", "My Lord,", "My Lady,", "By my faith,", "If it pleases you,", "I pray you,", "In truth,", "By my trowth,", "In sooth,", "By my word,", "S'wounds,", "Z'wounds,", "<god>'s wounds,", "<god>'s <body part>,", "Heigh-ho,", "Ah,", "Quoth I,", "Listen,", "Listen thee,", "Hear me,", "Now hear me,", "I warrant", "Come,", "Kind sire,", "Sire,", "There is much in what you say, and yet,"];
var endmsgs = ["Anon!", "Hum.", "Good sir!", "Good sire!", "Milady!", "My Liege!", "Guvnor!"];

var gods = ["Odin", "Bob", "Zeus", "Hera", "Thor", "Crom", "Mad-poet Navarth", "Cugel", "Wotsit", "Baron Boddisey", "Poseidon", "Saint Mary", "Pallus Athena", "Loki", "Erlik", "Shoggoth", "Omm", "Vishnu", "Azazoth", "Father Odin", "Allfather Odin", "Cthulhu", "Buddha", "Aphrodite", "Isis", "Kali", "Dionysus", "Zarathustra", "Croesus", "Hermes", "Venus", "Montezuma", "Popacatapetl", "Hephaestus", "Bubastes", "Bacchus", "Nebuchadnezzar", "Assurbanipal", "Sargon", "Xerxes", "Mulwatallish", "Labarna", "Hammurabi", "Rameses", "Minos", "Tilgath-Pileser", "Vercingetorix", "Mithradites", "Pericles", "Belasarius", "Archaemides", "Heraclius", "Imhotep", "Artemis", "Orthia", "Phoebe", "Hestia", "Eros", "Persephone", "Minerva", "Mercury", "Aesculapius", "Discordia", "Hecate", "Hespera"];

var godadjs = ["Almighty", "Unthinkable", "Unknowable", "All-knowing", "All-seeing", "Lecherous", "Scandalous", "Merciful", "Ravaging", "Thunderous", "Wrathful", "Distant", "Vengeful", "Supreme", "Wise", "Warlike", "Jealous", "Vindictive", "Powerful", "Adulterous", "Licentious", "Crafty", "Benefical", "Virtuous", "Protective", "Prophetic", "Bloodthirsty", "Murderous", "Ruinous", "Militant", "Invisible", "Omnipotent", "Forgotten", "Enlightened", "Tempestuous", "Destructive", "Grim"];

var bodyparts = ["Beard", "Third Leg", "Scalp", "Eye", "Thigh", "Arm", "Sword", "Heel", "Gaze", "Tongue", "Hammer", "Toenail", "Nether Regions", "Liver", "Lights", "Spleen", "Gall", "Liver and Lights"];

var bodypartadjs = ["Unknowable", "Unescapable", "Unfathomable", "Unthinkable", "Righteous", "Hairy", "Hairless", "Wandering", "Blistered", "Awe-inspiring", "Toothy", "Ravaged", "Aged", "Endless", "Wondrous", "Unavoidable", "Pestilent", "Forgotten", "Beautiful", "Fertile", "Prophetic", "Musical", "Helpful", "Virginal", "Curative", "Bleak", "Incessant", "Sagely", "Unfashionable", "Unfaltering", "Unfamiliar", "Abysmal", "Boundless", "Eternal", "Immeasurable", "Infinite", "Unending", "Soundless", "Incomprehensible", "Inexplicable", "Profound", "Unintelligible", "Unbelievable", "Impenetrable", "Indecipherable", "Esoteric", "Enigmatic", "Ancient", "Venerable", "Baneful", "Contagious", "Corrupting", "Deadly", "Deleterious", "Evil", "Noxious", "Diseased", "Pernicious", "Pestiferous", "Pestilential", "Tainted", "Contaminated", "Pulchritudinous", "Odoriferous", "Misbegotten", "Sacriligio"];

function arrRandom(arr) {
    return arr[sys.rand(0, arr.length)];
}

function word(original, replacement) {
    var len, i;

    if (!Array.isArray(original)) {
        original = [original];
    }
    if (!Array.isArray(replacement)) {
        replacement = [replacement];
    }

    for (i = 0, len = original.length; i < len; i += 1) {
        words.push({regex: new RegExp(original[i], "gi"), replacements: replacement});
    }
}

// http://wiki.teamfortress.com/wiki/Medieval_Mode#Chat_parser
function addWords() {
    words = [];

    // 1
    word(["it is", "it's"], "tis");
    word("it was", "'twas");
    word("it would", "'twould");
    word("it will", "'twill");
    word("it were", "'twere");
    word(["shall not", "will not"], "shan't");
    word("over there", "yonder");
    word("in the", "i' the");
    word("thank you", ["many good thanks to you", "thankee", "kindly thanks to you", "grammercy to you"]);
    word(["you", "u"], ["thou", "thee", "ye"]);
    word("are", "art");
    word("lol", ["lolleth", "lollery"]);
    word(["killed", "beaten"], ["slain", "vanquished", "brung low", "conquered", "fleeced", "humbled", "subjugated", "bested", "foiled"]);
    word(["goodbye", "bye", "seeya", "goodnight"], ["farewell", "fare thee well", "good morrow", "by your leave", "godspeed", "begone", "good day", "good day, sirrah", "good day, sire", "good day, master", "adieu", "cheerio", "pleasant journey", "I bid thee good day", "I bid thee farewell"]);
    word("yes", ["aye", "yea", "yea verily"]);
    word("no", ["nay", "nayeth"]);
    word(["hello", "hi"], ["good day", "well met", "well meteth", "tally ho", "ave"]);
    word("does", ["doeseth", "dost", "doth"]);
    word(["kill", "gank"], ["slay", "vanquish", "bring low", "conquer", "fleece", "humble", "subjugate", "best", "foil"]);
    word("your", ["thy", "thine", "thyne"]);
    word("my", "mine");
    word("in", "within");
    word("flag", ["pennant", "banner", "colors", "heraldry"]);

    // 2
    word("walking", "a-walkin'");
    word("bet", "warrant");
    word("the", "ye");
    word("joke", ["jest", "jape"]);
    word(["balls", "groin"], ["leathers", "beans", "poundables", "nethers", "nadchakles", "buis", "fellahs", "coin purse"]);
    word("afk", ["away, fighting kobolds", "away, fruity knights", "aft, frisking knickers", "abaft, flailing knouts"]);
    word("map", "chart");
    word("please", ["I pray you", "prithee", "pray"]);
    word("ok", ["as you will", "agreed", "well said", "just so"]);
    word("is", "be");
    word("never", "ne'er");
    word(["haha", "hehe", "heh", "hah"], ["guffaw!", "cackle!", "oh, 'tis to laugh!", "zounds!", "chuckle!", "snigger!", "snort!", "snicker!", "cachinnate!", "titter!", "and there was much tittering!", "and there was much guffawing!", "and there was much chuckling!", "and there was much snorting!", "and there was much snickering!", "and there was much mirth!"]);
    word("assist", ["aid", "aideth", "saveth", "assistance", "succor"]);
    word("could", "couldst");
    word("would", "wouldst");
    word("sure", "shore");
    word("maybe", ["mayhaps", "perchance"]);
    word(["girl", "woman"], ["madame", "waif", "mistress", "lass", "lady", "goodwife", "maid", "maiden"]);
    word("later", "anon");
    word("often", "oft");
    word("really", ["indeed", "in truth"]);
    word("those", "yon");
    word("here", "hither");
    word("enough", "enow");
    word("child", "poppet");
    word("why", "wherefore");
    word("away", "aroint");
    word("being", "bein'");
    word("of", "o'");
    word("fucker", "swiver");
    word("shit", "nightsoil");
}

function yeolde(message) {
    var startmsg = arrRandom(startmsg),
        word, len, i;

    startmsg = startmsg
        .replace("<god>", arrRandom(gods))
        .replace("<god adjective>", arrRandom(godadjs))
        .replace("<body part>", arrRandom(bodyparts))
        .replace("<body part adjective>", arrRandom(bodypartadjs));

    message = message.replace(exclam, arrRandom(exclamrepl));
    message = message.replace(questi, arrRandom(questirepl));

    message = message.replace(insults, function () {
        var adjs = insultadj.slice(),
            adj1 = arrRandom(adjs),
            noun = arrRandom(insultnoun);

        adjs.splice(adjs.indexOf(adj1), 1);
        return adj1 + ", " + arrRandom(adjs) + ", " + noun;
    });

    for (i = 0, len = words.length; i < len; i += 1) {
        word = words[i];
        message = message.replace(word.regex, arrRandom(word.replacements));
    }

    return startmsg + message + arrRandom(endmsgs);
}

module.exports = {
    yeolde: yeolde
};

module.reload = function () {
    addWords();
    return true;
};
<commit_msg>Undefined variable<commit_after>var words = [];

var exclam = /!/g;
var exclamrepl = [", verily!", ", verily I say!", ", verily I sayeth!", ", I say!", ", I sayeth!", "! Huzzah!", "! Hear Hear!", "! What-ho!", "! Ho!", "! Fie!", ", indeed!"];

var questi = /\?/g;
var questirepl = [", I say?", ", I wonder?", ", wonder I?", ", what say thee?", ", what sayeth thee?", ", what say thou?", ", what sayeth thou?", ", I ponder?", ", I pondereth?", ", pray tell?", ", ho?", ", do tell?"];

var insults = /idiot|fool|bastard/gi;

var insultnoun = ["mongrel", "codpiece", "jackanape", "ape", "coxcomb", "harlot", "hussy", "strumpet", "cur", "clot", "fool", "barnacle", "harpy", "wench", "churl", "pleb", "taffer", "scoundrel", "scalliwag", "mooncalf", "rapscallion", "doxy", "bawd", "tosspot", "cupshot", "recreant", "fustalarion", "scullion", "rampallion", "knave", "barbermonger", "boil", "plague-sore", "carbuncle", "whoreson", "clotpole", "lout", "gudgeon", "puttock", "skainsmate", "varlet", "bladder"];

var insultadj = ["artless", "droning", "fawning", "warped", "paunchy", "puny", "spongy", "ruttish", "vain", "lumpish", "craven", "witless", "pustulent", "infested", "ill-bred", "blind", "scurvy", "puny", "fetid", "vile", "gibbering", "mewling", "rank", "fawning", "moonish", "brutish", "malapert", "curst", "lack-linen", "bottle-ailed", "lyingest", "embossed", "cheating", "crook-pated", "base-court", "hasty-witted", "two-faced", "pox-marked", "toad-brained", "errant", "idle-headed", "quailing", "flap-mouthed", "puking", "fly-bitten", "surly", "tottering", "villainous", "rump-fed", "bootless", "churlish", "tickle-brained", "froward"];

var startmsgs = ["Forsooth,", "I say,", "I sayeth,", "Forsooth, I say,", "Forsooth, say I,", "Forsooth, sayeth I,", "Hark!", "Harketh!", "By <god>,", "By the Will of <god adjective> <god>,", "By the <body part adjective> <body part> of the <god adjective> <god>,", "By <god adjective> <god>'s <body part adjective> <body part>,", "Avast,", "Zounds,", "Perchance,", "Pray tell,", "Prithee,", "What hey,", "What ho,", "Pray,", "Surely", "Pray pardon,", "Alas,", "In short,", "My Lord,", "My Lady,", "By my faith,", "If it pleases you,", "I pray you,", "In truth,", "By my trowth,", "In sooth,", "By my word,", "S'wounds,", "Z'wounds,", "<god>'s wounds,", "<god>'s <body part>,", "Heigh-ho,", "Ah,", "Quoth I,", "Listen,", "Listen thee,", "Hear me,", "Now hear me,", "I warrant", "Come,", "Kind sire,", "Sire,", "There is much in what you say, and yet,"];
var endmsgs = ["Anon!", "Hum.", "Good sir!", "Good sire!", "Milady!", "My Liege!", "Guvnor!"];

var gods = ["Odin", "Bob", "Zeus", "Hera", "Thor", "Crom", "Mad-poet Navarth", "Cugel", "Wotsit", "Baron Boddisey", "Poseidon", "Saint Mary", "Pallus Athena", "Loki", "Erlik", "Shoggoth", "Omm", "Vishnu", "Azazoth", "Father Odin", "Allfather Odin", "Cthulhu", "Buddha", "Aphrodite", "Isis", "Kali", "Dionysus", "Zarathustra", "Croesus", "Hermes", "Venus", "Montezuma", "Popacatapetl", "Hephaestus", "Bubastes", "Bacchus", "Nebuchadnezzar", "Assurbanipal", "Sargon", "Xerxes", "Mulwatallish", "Labarna", "Hammurabi", "Rameses", "Minos", "Tilgath-Pileser", "Vercingetorix", "Mithradites", "Pericles", "Belasarius", "Archaemides", "Heraclius", "Imhotep", "Artemis", "Orthia", "Phoebe", "Hestia", "Eros", "Persephone", "Minerva", "Mercury", "Aesculapius", "Discordia", "Hecate", "Hespera"];

var godadjs = ["Almighty", "Unthinkable", "Unknowable", "All-knowing", "All-seeing", "Lecherous", "Scandalous", "Merciful", "Ravaging", "Thunderous", "Wrathful", "Distant", "Vengeful", "Supreme", "Wise", "Warlike", "Jealous", "Vindictive", "Powerful", "Adulterous", "Licentious", "Crafty", "Benefical", "Virtuous", "Protective", "Prophetic", "Bloodthirsty", "Murderous", "Ruinous", "Militant", "Invisible", "Omnipotent", "Forgotten", "Enlightened", "Tempestuous", "Destructive", "Grim"];

var bodyparts = ["Beard", "Third Leg", "Scalp", "Eye", "Thigh", "Arm", "Sword", "Heel", "Gaze", "Tongue", "Hammer", "Toenail", "Nether Regions", "Liver", "Lights", "Spleen", "Gall", "Liver and Lights"];

var bodypartadjs = ["Unknowable", "Unescapable", "Unfathomable", "Unthinkable", "Righteous", "Hairy", "Hairless", "Wandering", "Blistered", "Awe-inspiring", "Toothy", "Ravaged", "Aged", "Endless", "Wondrous", "Unavoidable", "Pestilent", "Forgotten", "Beautiful", "Fertile", "Prophetic", "Musical", "Helpful", "Virginal", "Curative", "Bleak", "Incessant", "Sagely", "Unfashionable", "Unfaltering", "Unfamiliar", "Abysmal", "Boundless", "Eternal", "Immeasurable", "Infinite", "Unending", "Soundless", "Incomprehensible", "Inexplicable", "Profound", "Unintelligible", "Unbelievable", "Impenetrable", "Indecipherable", "Esoteric", "Enigmatic", "Ancient", "Venerable", "Baneful", "Contagious", "Corrupting", "Deadly", "Deleterious", "Evil", "Noxious", "Diseased", "Pernicious", "Pestiferous", "Pestilential", "Tainted", "Contaminated", "Pulchritudinous", "Odoriferous", "Misbegotten", "Sacriligio"];

function arrRandom(arr) {
    return arr[sys.rand(0, arr.length)];
}

function word(original, replacement) {
    var len, i;

    if (!Array.isArray(original)) {
        original = [original];
    }
    if (!Array.isArray(replacement)) {
        replacement = [replacement];
    }

    for (i = 0, len = original.length; i < len; i += 1) {
        words.push({regex: new RegExp(original[i], "gi"), replacements: replacement});
    }
}

// http://wiki.teamfortress.com/wiki/Medieval_Mode#Chat_parser
function addWords() {
    words = [];

    // 1
    word(["it is", "it's"], "tis");
    word("it was", "'twas");
    word("it would", "'twould");
    word("it will", "'twill");
    word("it were", "'twere");
    word(["shall not", "will not"], "shan't");
    word("over there", "yonder");
    word("in the", "i' the");
    word("thank you", ["many good thanks to you", "thankee", "kindly thanks to you", "grammercy to you"]);
    word(["you", "u"], ["thou", "thee", "ye"]);
    word("are", "art");
    word("lol", ["lolleth", "lollery"]);
    word(["killed", "beaten"], ["slain", "vanquished", "brung low", "conquered", "fleeced", "humbled", "subjugated", "bested", "foiled"]);
    word(["goodbye", "bye", "seeya", "goodnight"], ["farewell", "fare thee well", "good morrow", "by your leave", "godspeed", "begone", "good day", "good day, sirrah", "good day, sire", "good day, master", "adieu", "cheerio", "pleasant journey", "I bid thee good day", "I bid thee farewell"]);
    word("yes", ["aye", "yea", "yea verily"]);
    word("no", ["nay", "nayeth"]);
    word(["hello", "hi"], ["good day", "well met", "well meteth", "tally ho", "ave"]);
    word("does", ["doeseth", "dost", "doth"]);
    word(["kill", "gank"], ["slay", "vanquish", "bring low", "conquer", "fleece", "humble", "subjugate", "best", "foil"]);
    word("your", ["thy", "thine", "thyne"]);
    word("my", "mine");
    word("in", "within");
    word("flag", ["pennant", "banner", "colors", "heraldry"]);

    // 2
    word("walking", "a-walkin'");
    word("bet", "warrant");
    word("the", "ye");
    word("joke", ["jest", "jape"]);
    word(["balls", "groin"], ["leathers", "beans", "poundables", "nethers", "nadchakles", "buis", "fellahs", "coin purse"]);
    word("afk", ["away, fighting kobolds", "away, fruity knights", "aft, frisking knickers", "abaft, flailing knouts"]);
    word("map", "chart");
    word("please", ["I pray you", "prithee", "pray"]);
    word("ok", ["as you will", "agreed", "well said", "just so"]);
    word("is", "be");
    word("never", "ne'er");
    word(["haha", "hehe", "heh", "hah"], ["guffaw!", "cackle!", "oh, 'tis to laugh!", "zounds!", "chuckle!", "snigger!", "snort!", "snicker!", "cachinnate!", "titter!", "and there was much tittering!", "and there was much guffawing!", "and there was much chuckling!", "and there was much snorting!", "and there was much snickering!", "and there was much mirth!"]);
    word("assist", ["aid", "aideth", "saveth", "assistance", "succor"]);
    word("could", "couldst");
    word("would", "wouldst");
    word("sure", "shore");
    word("maybe", ["mayhaps", "perchance"]);
    word(["girl", "woman"], ["madame", "waif", "mistress", "lass", "lady", "goodwife", "maid", "maiden"]);
    word("later", "anon");
    word("often", "oft");
    word("really", ["indeed", "in truth"]);
    word("those", "yon");
    word("here", "hither");
    word("enough", "enow");
    word("child", "poppet");
    word("why", "wherefore");
    word("away", "aroint");
    word("being", "bein'");
    word("of", "o'");
    word("fucker", "swiver");
    word("shit", "nightsoil");
}

function yeolde(message) {
    var startmsg = arrRandom(startmsgs),
        word, len, i;

    startmsg = startmsg
        .replace("<god>", arrRandom(gods))
        .replace("<god adjective>", arrRandom(godadjs))
        .replace("<body part>", arrRandom(bodyparts))
        .replace("<body part adjective>", arrRandom(bodypartadjs));

    message = message.replace(exclam, arrRandom(exclamrepl));
    message = message.replace(questi, arrRandom(questirepl));

    message = message.replace(insults, function () {
        var adjs = insultadj.slice(),
            adj1 = arrRandom(adjs),
            noun = arrRandom(insultnoun);

        adjs.splice(adjs.indexOf(adj1), 1);
        return adj1 + ", " + arrRandom(adjs) + ", " + noun;
    });

    for (i = 0, len = words.length; i < len; i += 1) {
        word = words[i];
        message = message.replace(word.regex, arrRandom(word.replacements));
    }

    return startmsg + message + arrRandom(endmsgs);
}

module.exports = {
    yeolde: yeolde
};

module.reload = function () {
    addWords();
    return true;
};
<|endoftext|>


<commit_before>define([
	"dojo/_base/declare", "dojo/_base/lang", "dojo/_base/Deferred",
	"dojo/on", "dojo/request", "dojo/dom-style", "dojo/query", "dojo/dom-attr", "dojo/aspect", "dojo/topic",
	"dijit/layout/BorderContainer", "dijit/layout/ContentPane",
	"dgrid/selector", "put-selector/put",
	"../store/ArrangeableMemoryStore", "./Grid", "./formatter"
], function(declare, lang, Deferred,
			on, request, domStyle, domQuery, domAttr, aspect, Topic,
			BorderContainer, ContentPane,
			selector, put,
			Store, Grid, formatter){

	var filterSelector = function(value, cell, object){
		var parent = cell.parentNode;

		// must set the class name on the outer cell in IE for keystrokes to be intercepted
		put(parent && parent.contents ? parent : cell, ".dgrid-selector");
		var input = cell.input || (cell.input = put(cell, 'i', {
				tabIndex: -1,
				checked: !!value
			}));
		input.setAttribute("class", value ? "fa icon-check-square-o" : "fa icon-square-o");
		input.setAttribute("aria-checked", !!value);
		return input;
	};

	var filterSelectorChecked = function(value, cell, object){
		return filterSelector(true, cell, object);
	};

	// create empty Memory Store
	var store = new Store({
		idProperty: "genome_id"
	});

	return declare([Grid], {
		region: "center",
		query: (this.query || ""),
		apiToken: window.App.authorizationToken,
		apiServer: window.App.dataServiceURL,
		store: store,
		bufferRows: 500,
		pfState: null,
		dataModel: "genome",
		primaryKey: "genome_id",
		deselectOnRefresh: true,
		columns: {
			present: selector({label: '', field: 'present', selectorType: 'radio'}, filterSelector),
			absent: selector({label: '', field: 'absent', selectorType: 'radio'}, filterSelector),
			mixed: selector({label: '', field: 'mixed', selectorType: 'radio'}, filterSelectorChecked),
			genome_name: {label: 'Genome Name', field: 'genome_name'},
			genome_status: {label: 'Genome Status', field: 'genome_status'},
			isolation_country: {label: 'Isolation Country', field: 'isolation_country'},
			host_name: {label: 'Host', field: 'host_name'},
			disease: {label: 'Disease', field: 'disease'},
			collection_date: {label: 'Collection Date', field: 'collection_date'},
			completion_date: {label: 'Completion Date', field: 'completion_date', formatter: formatter.dateOnly}
		},
		constructor: function(options){
			if(options && options.state){
				this.state = options.state;
			}
			this.topicId = options.topicId;

			Topic.subscribe(this.topicId, lang.hitch(this, function(){
				// console.log("ProteinFamiliesFilterGrid:", arguments);
				var key = arguments[0], value = arguments[1];

				switch(key){
					case "updatePfState":
						this.pfState = value;
						break;
					case "updateFilterGrid":
						this.store.setData(value);
						this.store._loaded = true;
						this.refresh();
						break;
					case "updateFilterGridOrder":
						// this.updateSortArrow([]);
						this.set('sort', []);
						this.store.arrange(value);
						this.refresh();
						break;
					default:
						break;
				}
			}));
		},
		startup: function(){

			var options = ['present', 'absent', 'mixed'];
			var toggleSelection = function(element, value){
				element.checked = value;
				element.setAttribute("class", value ? "fa icon-check-square-o" : "fa icon-square-o");
				element.setAttribute("aria-checked", value);
			};

			this.on(".dgrid-cell:click", lang.hitch(this, function(evt){
				var cell = this.cell(evt);
				var colId = cell.column.id;
				var columnHeaders = cell.column.grid.columns;

				var conditionIds = this.pfState.genomeIds;
				var conditionStatus = this.pfState.genomeFilterStatus;

				if(!cell.element.input) return;

				if(cell.row){
					// data row is clicked
					var rowId = cell.row.id;

					// deselect other radio in the same row
					options.forEach(function(el){
						if(el != colId && this.cell(rowId, el).element.input.checked){
							toggleSelection(this.cell(rowId, el).element.input, false);
						}
						// updated selected box
						if(el === colId){
							toggleSelection(this.cell(rowId, el).element.input, true);
						}
					}, this);

					// check whether entire rows are selected & mark as needed
					options.forEach(function(el){
						var allSelected = true;
						conditionIds.forEach(function(conditionId){
							if(this.cell(conditionId, el).element.input.checked == false){
								allSelected = false;
							}
						}, this);
						toggleSelection(columnHeaders[el].headerNode.firstChild.firstElementChild, allSelected);
					}, this);

				}else{
					// if header is clicked, reset the selections & update
					conditionIds.forEach(function(conditionId){
						options.forEach(function(el){
							if(el === colId){
								toggleSelection(this.cell(conditionId, el).element.input, true);
							}else{
								toggleSelection(this.cell(conditionId, el).element.input, false);
							}
						}, this);
					}, this);

					// deselect other radio in the header
					options.forEach(function(el){
						if(el != colId && columnHeaders[el].headerNode.firstChild.firstElementChild.checked){
							toggleSelection(columnHeaders[el].headerNode.firstChild.firstElementChild, false);
						}
					});
				}

				// update filter
				Object.keys(conditionStatus).forEach(function(conditionId){
					var status = options.findIndex(function(el){
						if(this.cell(conditionId, el).element.input.checked){
							return el;
						}
					}, this);

					conditionStatus[conditionId].setStatus(status);
				}, this);

				this.pfState.genomeFilterStatus = conditionStatus;
				Topic.publish(this.topicId, "applyConditionFilter", this.pfState);
			}));

			aspect.before(this, 'renderArray', lang.hitch(this, function(results){
				Deferred.when(results.total, lang.hitch(this, function(x){
					this.set("totalRows", x);
				}));
			}));

			// this.inherited(arguments);
			this._started = true;

			// increase grid width after rendering content-pane
			domStyle.set(this.id, "width", "650px");
			// set checkbox title after load
			// console.log(domQuery(".field-present .dgrid-resize-header-container i"));
			domAttr.set(domQuery(".field-present .dgrid-resize-header-container i")[0], "title", "Present in all families");
			domAttr.set(domQuery(".field-absent .dgrid-resize-header-container i")[0], "title", "Absent in all families");
			domAttr.set(domQuery(".field-mixed .dgrid-resize-header-container i")[0], "title", "Either/Mixed");
		},
		_setSort: function(sort){
			this.inherited(arguments);
			this.store.sort = sort;

			if(sort.length > 0){
				var newIds = [];
				var idProperty = this.store.idProperty;
				this.store.query({}, {sort: sort}).forEach(function(condition){
					newIds.push(condition[idProperty]);
				});
				this.pfState.clusterRowOrder = newIds;
				// console.log("new order", this.pfState.clusterRowOrder);

				Topic.publish(this.topicId, "updatePfState", this.pfState);
				Topic.publish(this.topicId, "requestHeatmapData", this.pfState);
			}
		},
		state: null,
		postCreate: function(){
			this.inherited(arguments);
		},
		_setApiServer: function(server){
			this.apiServer = server;
		}
	});
});
<commit_msg>fix PFS bug: not updating heatmap on filter grid after anchoring<commit_after>define([
	"dojo/_base/declare", "dojo/_base/lang", "dojo/_base/Deferred",
	"dojo/on", "dojo/request", "dojo/dom-style", "dojo/query", "dojo/dom-attr", "dojo/aspect", "dojo/topic",
	"dijit/layout/BorderContainer", "dijit/layout/ContentPane",
	"dgrid/selector", "put-selector/put",
	"../store/ArrangeableMemoryStore", "./Grid", "./formatter"
], function(declare, lang, Deferred,
			on, request, domStyle, domQuery, domAttr, aspect, Topic,
			BorderContainer, ContentPane,
			selector, put,
			Store, Grid, formatter){

	var filterSelector = function(value, cell, object){
		var parent = cell.parentNode;

		// must set the class name on the outer cell in IE for keystrokes to be intercepted
		put(parent && parent.contents ? parent : cell, ".dgrid-selector");
		var input = cell.input || (cell.input = put(cell, 'i', {
				tabIndex: -1,
				checked: !!value
			}));
		input.setAttribute("class", value ? "fa icon-check-square-o" : "fa icon-square-o");
		input.setAttribute("aria-checked", !!value);
		return input;
	};

	var filterSelectorChecked = function(value, cell, object){
		return filterSelector(true, cell, object);
	};

	// create empty Memory Store
	var store = new Store({
		idProperty: "genome_id"
	});

	return declare([Grid], {
		region: "center",
		query: (this.query || ""),
		apiToken: window.App.authorizationToken,
		apiServer: window.App.dataServiceURL,
		store: store,
		bufferRows: 500,
		pfState: null,
		dataModel: "genome",
		primaryKey: "genome_id",
		deselectOnRefresh: true,
		columns: {
			present: selector({label: '', field: 'present', selectorType: 'radio'}, filterSelector),
			absent: selector({label: '', field: 'absent', selectorType: 'radio'}, filterSelector),
			mixed: selector({label: '', field: 'mixed', selectorType: 'radio'}, filterSelectorChecked),
			genome_name: {label: 'Genome Name', field: 'genome_name'},
			genome_status: {label: 'Genome Status', field: 'genome_status'},
			isolation_country: {label: 'Isolation Country', field: 'isolation_country'},
			host_name: {label: 'Host', field: 'host_name'},
			disease: {label: 'Disease', field: 'disease'},
			collection_date: {label: 'Collection Date', field: 'collection_date'},
			completion_date: {label: 'Completion Date', field: 'completion_date', formatter: formatter.dateOnly}
		},
		constructor: function(options){
			if(options && options.state){
				this.state = options.state;
			}
			this.topicId = options.topicId;

			Topic.subscribe(this.topicId, lang.hitch(this, function(){
				// console.log("ProteinFamiliesFilterGrid:", arguments);
				var key = arguments[0], value = arguments[1];

				switch(key){
					case "updatePfState":
						this.pfState = value;
						break;
					case "updateFilterGrid":
						this.store.setData(value);
						this.store._loaded = true;
						this.refresh();
						break;
					case "updateFilterGridOrder":
						// this.updateSortArrow([]);
						this.set('sort', []);
						this.store.arrange(value);
						this.refresh();
						break;
					default:
						break;
				}
			}));
		},
		startup: function(){

			var options = ['present', 'absent', 'mixed'];
			var toggleSelection = function(element, value){
				element.checked = value;
				element.setAttribute("class", value ? "fa icon-check-square-o" : "fa icon-square-o");
				element.setAttribute("aria-checked", value);
			};

			this.on(".dgrid-cell:click", lang.hitch(this, function(evt){
				var cell = this.cell(evt);
				var colId = cell.column.id;
				var columnHeaders = cell.column.grid.columns;

				var conditionIds = this.pfState.genomeIds;
				var conditionStatus = this.pfState.genomeFilterStatus;

				if(!cell.element.input) return;

				if(cell.row){
					// data row is clicked
					var rowId = cell.row.id;

					// deselect other radio in the same row
					options.forEach(function(el){
						if(el != colId && this.cell(rowId, el).element.input.checked){
							toggleSelection(this.cell(rowId, el).element.input, false);
						}
						// updated selected box
						if(el === colId){
							toggleSelection(this.cell(rowId, el).element.input, true);
						}
					}, this);

					// check whether entire rows are selected & mark as needed
					options.forEach(function(el){
						var allSelected = true;
						conditionIds.forEach(function(conditionId){
							if(this.cell(conditionId, el).element.input.checked == false){
								allSelected = false;
							}
						}, this);
						toggleSelection(columnHeaders[el].headerNode.firstChild.firstElementChild, allSelected);
					}, this);

				}else{
					// if header is clicked, reset the selections & update
					conditionIds.forEach(function(conditionId){
						options.forEach(function(el){
							if(el === colId){
								toggleSelection(this.cell(conditionId, el).element.input, true);
							}else{
								toggleSelection(this.cell(conditionId, el).element.input, false);
							}
						}, this);
					}, this);

					// deselect other radio in the header
					options.forEach(function(el){
						if(el != colId && columnHeaders[el].headerNode.firstChild.firstElementChild.checked){
							toggleSelection(columnHeaders[el].headerNode.firstChild.firstElementChild, false);
						}
					});
				}

				// update filter
				Object.keys(conditionStatus).forEach(function(conditionId){
					var status = options.findIndex(function(el){
						if(this.cell(conditionId, el).element.input.checked){
							return el;
						}
					}, this);

					conditionStatus[conditionId].setStatus(status);
				}, this);

				this.pfState = lang.mixin({}, this.pfState, {
					genomeFilterStatus: conditionStatus,
					clusterColumnOrder: []
				})

				Topic.publish(this.topicId, "applyConditionFilter", this.pfState);
			}));

			aspect.before(this, 'renderArray', lang.hitch(this, function(results){
				Deferred.when(results.total, lang.hitch(this, function(x){
					this.set("totalRows", x);
				}));
			}));

			// this.inherited(arguments);
			this._started = true;

			// increase grid width after rendering content-pane
			domStyle.set(this.id, "width", "650px");
			// set checkbox title after load
			// console.log(domQuery(".field-present .dgrid-resize-header-container i"));
			domAttr.set(domQuery(".field-present .dgrid-resize-header-container i")[0], "title", "Present in all families");
			domAttr.set(domQuery(".field-absent .dgrid-resize-header-container i")[0], "title", "Absent in all families");
			domAttr.set(domQuery(".field-mixed .dgrid-resize-header-container i")[0], "title", "Either/Mixed");
		},
		_setSort: function(sort){
			this.inherited(arguments);
			this.store.sort = sort;

			if(sort.length > 0){
				var newIds = [];
				var idProperty = this.store.idProperty;
				this.store.query({}, {sort: sort}).forEach(function(condition){
					newIds.push(condition[idProperty]);
				});
				this.pfState.clusterRowOrder = newIds;
				// console.log("new order", this.pfState.clusterRowOrder);

				Topic.publish(this.topicId, "updatePfState", this.pfState);
				Topic.publish(this.topicId, "requestHeatmapData", this.pfState);
			}
		},
		state: null,
		postCreate: function(){
			this.inherited(arguments);
		},
		_setApiServer: function(server){
			this.apiServer = server;
		}
	});
});
<|endoftext|>


<commit_before>import StyleSheet from './StyleSheet'
import cssifyCache from './utils/cssifyCache'

export default class Renderer {
  constructor(config) {
    this.stylesheet = new StyleSheet(config)
  }

  /**
   * renders selector or Keyframe variations, FontFaces and static styles
   * to an intern StyleSheet that caches those for future use
   *
   * @param {Function|Keyframe|FontFace|string|Object} element - selector, Keyframe, FontFace or static styles
   * @param {Object?} props - list of props to render
   * @param {Function[]?} plugins - array of plugins to process styles
   * @return {string} className, animation name, font family
   */
  render(element, props, plugins) {
    return this.stylesheet.handleRender(element, props, plugins)
  }

  /**
   * renders all cached selector styles into a single valid CSS string
   * clusters media query styles into groups to reduce output size

   * @return single concatenated CSS string
   */
  renderToString() {
    let css = ''

    this.stylesheet.fontFaces.forEach(markup => css += markup)
    css += cssifyCache(this.stylesheet.cache)
    this.stylesheet.mediaCache.forEach((cache, media) => {
      css += '@media ' + media + '{' + cssifyCache(cache) + '}'
    })
    this.stylesheet.keyframes.forEach(variation => {
      variation.forEach(markup => css += markup)
    })

    return css
  }

  /**
   * clears the stylesheet
   */
  clear() {
    this.stylesheet.clear()
  }
}
<commit_msg>added statics to renderToStrings markup<commit_after>import StyleSheet from './StyleSheet'
import cssifyCache from './utils/cssifyCache'

export default class Renderer {
  constructor(config) {
    this.stylesheet = new StyleSheet(config)
  }

  /**
   * renders selector or Keyframe variations, FontFaces and static styles
   * to an intern StyleSheet that caches those for future use
   *
   * @param {Function|Keyframe|FontFace|string|Object} element - selector, Keyframe, FontFace or static styles
   * @param {Object?} props - list of props to render
   * @param {Function[]?} plugins - array of plugins to process styles
   * @return {string} className, animation name, font family
   */
  render(element, props, plugins) {
    return this.stylesheet.handleRender(element, props, plugins)
  }

  /**
   * renders all cached selector styles into a single valid CSS string
   * clusters media query styles into groups to reduce output size

   * @return single concatenated CSS string
   */
  renderToString() {
    let css = ''

    this.stylesheet.fontFaces.forEach(markup => css += markup)
    this.stylesheet.statics.forEach(markup => css += markup)
    css += cssifyCache(this.stylesheet.cache)
    this.stylesheet.mediaCache.forEach((cache, media) => {
      css += '@media ' + media + '{' + cssifyCache(cache) + '}'
    })
    this.stylesheet.keyframes.forEach(variation => {
      variation.forEach(markup => css += markup)
    })

    return css
  }

  /**
   * clears the stylesheet
   */
  clear() {
    this.stylesheet.clear()
  }
}
<|endoftext|>


<commit_before>/**
 * @license
 * Copyright 2018 Google LLC. All Rights Reserved.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * =============================================================================
 */

import * as tf from '@tensorflow/tfjs';
import * as loader from './loader';
import * as ui from './ui';
import * as util from './util';

const HOSTED_URLS = {
  model:
      'https://storage.googleapis.com/tfjs-models/tfjs/mnist_transfer_cnn_v1/model.json',
  train:
      'https://storage.googleapis.com/tfjs-models/tfjs/mnist_transfer_cnn_v1/gte5.train.json',
  test:
      'https://storage.googleapis.com/tfjs-models/tfjs/mnist_transfer_cnn_v1/gte5.test.json'
};

const LOCAL_URLS = {
  model: 'http://localhost:1235/resources/model.json',
  train: 'http://localhost:1235/resources/gte5.train.json',
  test: 'http://localhost:1235/resources/gte5.test.json'
};

class MnistTransferCNNPredictor {
  /**
   * Initializes the MNIST Transfer CNN demo.
   */
  async init(urls) {
    this.urls = urls;
    this.model = await loader.loadHostedPretrainedModel(urls.model);
    this.imageSize = this.model.layers[0].batchInputShape[1];
    this.numClasses = 5;

    await this.loadRetrainData();
    this.prepTestExamples();
    return this;
  }

  async loadRetrainData() {
    ui.status('Loading data for transfer learning...');
    this.gte5TrainData =
        await loader.loadHostedData(this.urls.train, this.numClasses);
    this.gte5TestData =
        await loader.loadHostedData(this.urls.test, this.numClasses);
    ui.status('Done loading data for transfer learning.');
  }

  prepTestExamples() {
    // Some hard-coded MNIST image examples for interactive testing.
    const testExamples = {};
    const digitCounts = {5: 0, 6: 0, 7: 0, 8: 0, 9: 0};
    const examplesPerDigit = 10;
    // Enter one example of each of 5, 6, 7, 8, 9 in `testExamples`.
    for (let i = this.gte5TestData.data.length - 1; i >= 0; --i) {
      const datum = this.gte5TestData.data[i];
      const digit = datum.y + 5;
      if (digitCounts[digit] >= examplesPerDigit) {
        continue;
      }
      digitCounts[digit]++;
      const key = String(digit) + '_' + String(digitCounts[digit]);
      testExamples[key] = [];
      for (const row of datum.x) {
        testExamples[key] = testExamples[key].concat(row);
      }
      if (Object.keys(testExamples).length >= 5 * examplesPerDigit) {
        break;
      }
    }

    this.testExamples = testExamples;
  }

  // Perform prediction on the input image using the loaded model.
  predict(imageText) {
    tf.tidy(() => {
      try {
        const image = util.textToImageArray(imageText, this.imageSize);
        const predictOut = this.model.predict(image);
        const winner = predictOut.argMax();

        ui.setPredictResults(predictOut.dataSync(), winner.dataSync()[0] + 5);
      } catch (e) {
        ui.setPredictError(e.message);
      }
    });
  }

  // Perform retraining on the loaded model.
  async retrainModel() {
    ui.status(
        'Please wait and do NOT click anything while the model retrains...',
        'blue');
    await tf.nextFrame();

    console.log('Freezing feature layers of the model.');
    for (let i = 0; i < 7; ++i) {
      this.model.layers[i].trainable = false;
    }
    this.model.compile({
      loss: 'categoricalCrossentropy',
      optimizer: 'Adam',
      metrics: ['acc'],
    });

    const batchSize = 128;
    const epochs = ui.getEpochs();

    console.log('Retraining model.');
    const beginMs = performance.now();
    const history =
        await this.model.fit(this.gte5TrainData.x, this.gte5TrainData.y, {
          batchSize: batchSize,
          epochs: epochs,
          // TODO(cais): visualize validation results in frontend during
          //   training. See b/73735367.
          // validationData: [gte5TestXs, gte5TestYs],
          callbacks: ui.getProgressBarCallbackConfig(epochs),
        });
    console.log(history.history);
    console.log(
        'DONE retraining model: elapsed time = ' +
        (performance.now() - beginMs).toFixed(1) + ' ms');
  }
}

/**
 * Loads the pretrained model and metadata, and registers the predict
 * and retrain functions with the UI.
 */
async function setupMnistTransferCNN() {
  if (await loader.urlExists(HOSTED_URLS.model)) {
    ui.status('Model available: ' + HOSTED_URLS.model);
    const button = document.getElementById('load-pretrained-remote');
    button.addEventListener('click', async () => {
      const predictor = await new MnistTransferCNNPredictor().init(HOSTED_URLS);
      ui.prepUI(
          x => predictor.predict(x), x => predictor.retrainModel(),
          predictor.testExamples, predictor.imageSize);
    });
    button.style.display = 'inline-block';
  }

  if (await loader.urlExists(LOCAL_URLS.model)) {
    ui.status('Model available: ' + LOCAL_URLS.model);
    const button = document.getElementById('load-pretrained-local');
    button.addEventListener('click', async () => {
      const predictor = await new MnistTransferCNNPredictor().init(LOCAL_URLS);
      ui.prepUI(
          x => predictor.predict(x), x => predictor.retrainModel(),
          predictor.testExamples, predictor.imageSize);
    });
    button.style.display = 'inline-block';
  }

  ui.status('Standing by.');
}

setupMnistTransferCNN();
<commit_msg>[mnist-transfer-learning] Correct the computation of predicted output (winner) (#154)<commit_after>/**
 * @license
 * Copyright 2018 Google LLC. All Rights Reserved.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * =============================================================================
 */

import * as tf from '@tensorflow/tfjs';
import * as loader from './loader';
import * as ui from './ui';
import * as util from './util';

const HOSTED_URLS = {
  model:
      'https://storage.googleapis.com/tfjs-models/tfjs/mnist_transfer_cnn_v1/model.json',
  train:
      'https://storage.googleapis.com/tfjs-models/tfjs/mnist_transfer_cnn_v1/gte5.train.json',
  test:
      'https://storage.googleapis.com/tfjs-models/tfjs/mnist_transfer_cnn_v1/gte5.test.json'
};

const LOCAL_URLS = {
  model: 'http://localhost:1235/resources/model.json',
  train: 'http://localhost:1235/resources/gte5.train.json',
  test: 'http://localhost:1235/resources/gte5.test.json'
};

class MnistTransferCNNPredictor {
  /**
   * Initializes the MNIST Transfer CNN demo.
   */
  async init(urls) {
    this.urls = urls;
    this.model = await loader.loadHostedPretrainedModel(urls.model);
    this.imageSize = this.model.layers[0].batchInputShape[1];
    this.numClasses = 5;

    await this.loadRetrainData();
    this.prepTestExamples();
    return this;
  }

  async loadRetrainData() {
    ui.status('Loading data for transfer learning...');
    this.gte5TrainData =
        await loader.loadHostedData(this.urls.train, this.numClasses);
    this.gte5TestData =
        await loader.loadHostedData(this.urls.test, this.numClasses);
    ui.status('Done loading data for transfer learning.');
  }

  prepTestExamples() {
    // Some hard-coded MNIST image examples for interactive testing.
    const testExamples = {};
    const digitCounts = {5: 0, 6: 0, 7: 0, 8: 0, 9: 0};
    const examplesPerDigit = 10;
    // Enter one example of each of 5, 6, 7, 8, 9 in `testExamples`.
    for (let i = this.gte5TestData.data.length - 1; i >= 0; --i) {
      const datum = this.gte5TestData.data[i];
      const digit = datum.y + 5;
      if (digitCounts[digit] >= examplesPerDigit) {
        continue;
      }
      digitCounts[digit]++;
      const key = String(digit) + '_' + String(digitCounts[digit]);
      testExamples[key] = [];
      for (const row of datum.x) {
        testExamples[key] = testExamples[key].concat(row);
      }
      if (Object.keys(testExamples).length >= 5 * examplesPerDigit) {
        break;
      }
    }

    this.testExamples = testExamples;
  }

  // Perform prediction on the input image using the loaded model.
  predict(imageText) {
    tf.tidy(() => {
      try {
        const image = util.textToImageArray(imageText, this.imageSize);
        const predictOut = this.model.predict(image);
        const winner = predictOut.argMax(1);

        ui.setPredictResults(predictOut.dataSync(), winner.dataSync()[0] + 5);
      } catch (e) {
        ui.setPredictError(e.message);
      }
    });
  }

  // Perform retraining on the loaded model.
  async retrainModel() {
    ui.status(
        'Please wait and do NOT click anything while the model retrains...',
        'blue');
    await tf.nextFrame();

    console.log('Freezing feature layers of the model.');
    for (let i = 0; i < 7; ++i) {
      this.model.layers[i].trainable = false;
    }
    this.model.compile({
      loss: 'categoricalCrossentropy',
      optimizer: 'Adam',
      metrics: ['acc'],
    });

    const batchSize = 128;
    const epochs = ui.getEpochs();

    console.log('Retraining model.');
    const beginMs = performance.now();
    const history =
        await this.model.fit(this.gte5TrainData.x, this.gte5TrainData.y, {
          batchSize: batchSize,
          epochs: epochs,
          // TODO(cais): visualize validation results in frontend during
          //   training. See b/73735367.
          // validationData: [gte5TestXs, gte5TestYs],
          callbacks: ui.getProgressBarCallbackConfig(epochs),
        });
    console.log(history.history);
    console.log(
        'DONE retraining model: elapsed time = ' +
        (performance.now() - beginMs).toFixed(1) + ' ms');
  }
}

/**
 * Loads the pretrained model and metadata, and registers the predict
 * and retrain functions with the UI.
 */
async function setupMnistTransferCNN() {
  if (await loader.urlExists(HOSTED_URLS.model)) {
    ui.status('Model available: ' + HOSTED_URLS.model);
    const button = document.getElementById('load-pretrained-remote');
    button.addEventListener('click', async () => {
      const predictor = await new MnistTransferCNNPredictor().init(HOSTED_URLS);
      ui.prepUI(
          x => predictor.predict(x), x => predictor.retrainModel(),
          predictor.testExamples, predictor.imageSize);
    });
    button.style.display = 'inline-block';
  }

  if (await loader.urlExists(LOCAL_URLS.model)) {
    ui.status('Model available: ' + LOCAL_URLS.model);
    const button = document.getElementById('load-pretrained-local');
    button.addEventListener('click', async () => {
      const predictor = await new MnistTransferCNNPredictor().init(LOCAL_URLS);
      ui.prepUI(
          x => predictor.predict(x), x => predictor.retrainModel(),
          predictor.testExamples, predictor.imageSize);
    });
    button.style.display = 'inline-block';
  }

  ui.status('Standing by.');
}

setupMnistTransferCNN();
<|endoftext|>