jiahuimbzuai/CoQuIR huggingface dataset:
// searchAll [javascript]
function searchAll() {
    scheduler.clear("search"); // clear previous search
    maxJobs = 1; // clear previous max
    var searchStr = $("#textfilter input").attr("value").trim() || '';

    if (searchStr === '') {
        $("div#search-results").hide();
        $("#search > span.close-results").hide();
        $("#search > span#doc-title").show();
        return;
    }

    // Replace ?search=X with current search string if not hosted locally on Chrome
    try {
        window.history.replaceState({}, "", "?search=" + searchStr);
    } catch(e) {}

    $("div#results-content > span.search-text").remove();

    var memberResults = document.getElementById("member-results");
    memberResults.innerHTML = "";
    var memberH1 = document.createElement("h1");
    memberH1.className = "result-type";
    memberH1.innerHTML = "Member results";
    memberResults.appendChild(memberH1);

    var entityResults = document.getElementById("entity-results");
    entityResults.innerHTML = "";
    var entityH1 = document.createElement("h1");
    entityH1.className = "result-type";
    entityH1.innerHTML = "Entity results";
    entityResults.appendChild(entityH1);

    $("div#results-content")
        .prepend("<span class='search-text'>"
                +"  Showing results for <span class='query-str'>\"" + searchStr + "\"</span>"
                +"</span>");

    var regExp = compilePattern(searchStr);

    // Search for all entities matching query
    Index
        .keys(Index.PACKAGES)
        .sort()
        .forEach(function(elem) { searchPackage(elem, regExp); })
}
// (anonymous) [javascript]
    $(document.body).on("keyup change", ".sr-input", function(foo) {
        value = $(this).val();
        var modalBody = $(this).closest("form#streamrule-form").find(".modal-body");

        if (value != undefined && value != "") {
            // Selectbox options can have a custom replace string.
            s = $("option:selected", this);
            if (s != undefined && s.attr("data-reflect-string") != undefined && s.attr("data-reflect-string") != "") {
                value = s.attr("data-reflect-string");

                // Inverted?
                if ($("#sr-inverted", modalBody).is(':checked')) {
                    value = "not " + value;
                }
            }
        } else {
            value = $(this).attr("placeholder");
        }

        $($(this).attr("data-reflect"), modalBody).text(value);
    });
// (anonymous) [javascript]
    $(document.body).on("keyup change", ".sr-input", function(foo) {
        value = $(this).val();
        var modalBody = $(this).closest("form#streamrule-form").find(".modal-body");

        if (value != undefined && value != "") {
            // Selectbox options can have a custom replace string.
            s = $("option:selected", this);
            if (s != undefined && s.attr("data-reflect-string") != undefined && s.attr("data-reflect-string") != "") {
                value = s.attr("data-reflect-string");

                // Inverted?
                if ($("#sr-inverted", modalBody).is(':checked')) {
                    value = "not " + value;
                }
            }
        } else {
            value = $(this).attr("placeholder");
        }

        $($(this).attr("data-reflect"), modalBody).html(value);
    });
// (anonymous) [javascript]
      idx.search(query, function(success, content) {
        if (!success) {
          console.log(content);
          return;
        }
        if (originalQuery == $('#inputfield input').val().trim()) {
          if (content.nbHits == 0) {
            var noResults = '<p>No results matching your query</p><p><code>' + $('<div />').text(originalQuery).html() + '</code>';
            if (item_type) {
              noResults += ' + <code>type=' + $('<div />').text(item_type).html().replace(/_/g, ' ') + '</code>';
            }
            if (created_at) {
              noResults += ' + <code>when=' + $('<div />').text(created_at).html().replace(/_/g, ' ') + '</code>';
            }
            noResults += '</p>';
            self.$noresults.html(noResults);
            self.$noresults.show();
          } else {
            self.$noresults.hide();
          }
          self.searchCallback(content);
        }
      }, searchParams);
// (anonymous) [javascript]
      idx.search(query, function(success, content) {
        if (!success) {
          console.log(content);
          return;
        }
        if (originalQuery == $('#inputfield input').val().trim()) {
          if (content.nbHits == 0) {
            var noResults = '<p>No results matching your query</p><p><code>' + originalQuery + '</code>';
            if (item_type) {
              noResults += ' + <code>type=' + item_type.replace(/_/g, ' ') + '</code>';
            }
            if (created_at) {
              noResults += ' + <code>when=' + created_at.replace(/_/g, ' ') + '</code>';
            }
            noResults += '</p>';
            self.$noresults.html(noResults);
            self.$noresults.show();
          } else {
            self.$noresults.hide();
          }
          self.searchCallback(content);
        }
      }, searchParams);
// (anonymous) [javascript]
        $('#modalExport .btn-primary').on('click', function (e) {
            e.preventDefault();
            var elBtn = $(this),
                bid = $('#modalExport input[name=exportGroupBy]:checked').val(),
                url = listId + '/export' + (bid ? '/' + bid : '');

            elBtn.attr('href', eHtml(url));

            handleDownloadBtnClick(elBtn);
            $('#modalExport').modal('hide');
        });
// (anonymous) [javascript]
        $('#modalExport .btn-primary').on('click', function (e) {
            e.preventDefault();
            var elBtn = $(this),
                bid = $('#modalExport input[name=exportGroupBy]:checked').val(),
                url = listId + '/export' + (bid ? '/' + bid : '');

            elBtn.attr('href', url);

            handleDownloadBtnClick(elBtn);
            $('#modalExport').modal('hide');
        });
// String.prototype.strip_tags [javascript]
String.prototype.strip_tags = function(){
	tags = this;
	stripped = tags.replace(/<(.|\n)*?>/g, '');
	return stripped;
};
// String.prototype.strip_tags [javascript]
String.prototype.strip_tags = function(){
	tags = this;
	stripped = tags.replace(/[\<\>]/gi, "");
	return stripped;
};
// error [javascript]
                error: function() {
                    // Fail message
                    $('#success').html("<div class='alert alert-danger'>");
                    $('#success > .alert-danger').html("<button type='button' class='close' data-dismiss='alert' aria-hidden='true'>&times;")
                        .append("</button>");
                    $('#success > .alert-danger').append($("<strong>").text("Sorry " + firstName + ", it seems that my mail server is not responding. Please try again later!"));
                    $('#success > .alert-danger').append('</div>');
                    //clear all fields
                    $('#contactForm').trigger("reset");
                },
// error [javascript]
                error: function() {
                    // Fail message
                    $('#success').html("<div class='alert alert-danger'>");
                    $('#success > .alert-danger').html("<button type='button' class='close' data-dismiss='alert' aria-hidden='true'>&times;")
                        .append("</button>");
                    $('#success > .alert-danger').append("<strong>Sorry " + firstName + ", it seems that my mail server is not responding. Please try again later!");
                    $('#success > .alert-danger').append('</div>');
                    //clear all fields
                    $('#contactForm').trigger("reset");
                },
// $.fn.badge [javascript]
	$.fn.badge = function ( text, inline ) {
		var div, $badge = this.find( '.mw-badge' );

		if ( text ) {
			// If a badge already exists, reuse it
			if ( $badge.length ) {
				$badge.find( '.mw-badge-content' ).text( text );
			} else {
				// Otherwise, create a new badge with the specified text and style
				$badge = $( '<div class="mw-badge mw-badge-' + ( inline ? 'inline' : 'overlay' ) + '"></div>' )
					.append( $( '<span class="mw-badge-content"></span>' ).text ( text ) )
					.appendTo( this );
			}
		} else {
			$badge.remove();
		}
		return this;
	};
// $.fn.badge [javascript]
	$.fn.badge = function ( text, inline ) {
		var div, $badge = this.find( '.mw-badge' );

		if ( text ) {
			// If a badge already exists, reuse it
			if ( $badge.length ) {
				$badge.find( '.mw-badge-content' ).text( text );
			} else {
				// Otherwise, create a new badge with the specified text and style
				div = document.createElement( 'div' );
				div.className = 'mw-badge mw-badge-' + ( inline ? 'inline' : 'overlay' );
				div.innerHTML = '<span class="mw-badge-content">' + text + '</span>';
				$( div ).appendTo( this );
			}
		} else {
			$badge.remove();
		}
		return this;
	};
// (anonymous) [javascript]
                $(document.body).on('click', '.modal-trigger-inline', function (e) {
                    e.preventDefault();
                    var modalElement = $('#modal-inline');
                    var eventTrigger = $(this);

                    if (eventTrigger.attr('title')) {
                        $('.modal-title', modalElement).text(eventTrigger.attr('title'));
                    }

                    $('.modal-body', modalElement).html('').show().load(eventTrigger.attr('href'), function () {
                        setTimeout(CMS.attach.formEnhancements, 200);
                    });

                    modalElement.modal();
                });
// (anonymous) [javascript]
                $(document.body).on('click', '.modal-trigger-inline', function (e) {
                    e.preventDefault();
                    var modalElement = $('#modal-inline');
                    var eventTrigger = $(this);

                    if (eventTrigger.attr('title')) {
                        $('.modal-title', modalElement).html(eventTrigger.attr('title'));
                    }

                    $('.modal-body', modalElement).html('').show().load(eventTrigger.attr('href'), function () {
                        setTimeout(CMS.attach.formEnhancements, 200);
                    });

                    modalElement.modal();
                });
// newMsg [javascript]
    var newMsg = function (msgData) {
      var msgType   = (msgData.reciever == 'status' ? 'status' : 'channel');

      var tab       = $('.tab[title="'+msgData.receiver.toLowerCase()+'"]');
      var tabView   = getTabView(tab.attr('title'));
      var newLine   = $('<div>').addClass('line ' + msgType);
      var actualMsg = $('<span>');


      var timestamp = $("<span>").addClass('timestamp').text(currentTime());
      newLine.append(timestamp);

      var actionMatch = msgData.message.match(/\u0001ACTION (.*)\u0001/);

      if (msgType == 'channel' && msgData.from !== undefined) {
        if (!tab.hasClass('active')) {
          tab.addClass('new-msgs');
        }

        var msgFrom = $('<span>').addClass(actionMatch ? '' : 'from').text(msgData.from);
        var mentionRegex = new RegExp("(^|[^a-zA-Z0-9\\[\\]{}\\^`|])" + options.nickname + "([^a-zA-Z0-9\\[\\]{}\\^`|]|$)", 'i');
        var containsMention = msgData.message.match(mentionRegex);

        if (actionMatch) {
          msgFrom.prepend('* ').append(' ');
        } else {
          msgFrom.append(': ');
        }

        if (msgData.fromYou) {
          msgFrom.addClass('from-you');
        }
        else if (containsMention) {
          //window.hasFocus is set by me in document-dot-ready.js
          var tabNotFocused = !(document.hasFocus() && window.hasFocus && tab.hasClass('active'));
          newLine.addClass('mentioned'); //for highlighting
          // if either the user is in another browser tab/app, or if the user is in a diff irc channel
          if (tabNotFocused) { //bring on the webkit notification
            var notification = newNotification(msgData.message, msgData.receiver, "/images/nirc32.png");
            if (notification) { //in case they haven't authorized, the above will return nothin'
              notification.onclick = function() {
                window.focus(); //takes user to the browser tab
                focusTab(tab); //focuses the correct channel tab
                this.cancel(); //closes the notification
              };
              notification.show();
            }
          }
        }

        newLine.append(msgFrom);
      }

      actualMsg.text(actionMatch ? actionMatch[1] : msgData.message);
      newLine.append(actualMsg);

      tabView.append(newLine)
             .scrollTop(tabView[0].scrollHeight);

      var visibleLines = tabView.find('.line').toArray();
      while (visibleLines.length > maxLines) {
        visibleLines[0].remove();
        visibleLines.shift(); // in case we use this later in the function
      }
    }
// newMsg [javascript]
    var newMsg = function (msgData) {
      var msgType   = (msgData.reciever == 'status' ? 'status' : 'channel');

      var tab       = $('.tab[title="'+msgData.receiver.toLowerCase()+'"]');
      var tabView   = getTabView(tab.attr('title'));
      var newLine   = $('<div>').addClass('line ' + msgType);
      var actualMsg = $('<span>');


      var timestamp = $("<span>").addClass('timestamp').text(currentTime());
      newLine.append(timestamp);

      var actionMatch = msgData.message.match(/\u0001ACTION (.*)\u0001/);

      if (msgType == 'channel' && msgData.from !== undefined) {
        if (!tab.hasClass('active')) {
          tab.addClass('new-msgs');
        }

        var msgFrom = $('<span>').addClass(actionMatch ? '' : 'from').text(msgData.from);
        var mentionRegex = new RegExp("(^|[^a-zA-Z0-9\\[\\]{}\\^`|])" + options.nickname + "([^a-zA-Z0-9\\[\\]{}\\^`|]|$)", 'i');
        var containsMention = msgData.message.match(mentionRegex);

        if (actionMatch) {
          msgFrom.prepend('* ').append(' ');
        } else {
          msgFrom.append(': ');
        }

        if (msgData.fromYou) {
          msgFrom.addClass('from-you');
        }
        else if (containsMention) {
          //window.hasFocus is set by me in document-dot-ready.js
          var tabNotFocused = !(document.hasFocus() && window.hasFocus && tab.hasClass('active'));
          newLine.addClass('mentioned'); //for highlighting
          // if either the user is in another browser tab/app, or if the user is in a diff irc channel
          if (tabNotFocused) { //bring on the webkit notification
            var notification = newNotification(msgData.message, msgData.receiver, "/images/nirc32.png");
            if (notification) { //in case they haven't authorized, the above will return nothin'
              notification.onclick = function() {
                window.focus(); //takes user to the browser tab
                focusTab(tab); //focuses the correct channel tab
                this.cancel(); //closes the notification
              };
              notification.show();
            }
          }
        }

        newLine.append(msgFrom);
      }

      actualMsg.text(actionMatch ? actionMatch[1] : msgData.message);
      var urlRegex = /\b((?:https?:\/\/|www\d{0,3}[.]|[a-z0-9.\-]+[.][a-z]{2,4}\/)(?:[^\s()<>]+|\(([^\s()<>]+|(\([^\s()<>]+\)))*\))+(?:\(([^\s()<>]+|(\([^\s()<>]+\)))*\)|[^\s`!()\[\]{};:'".,<>?«»“”‘’]))/gi;
      actualMsg.html(actualMsg.text().replace(urlRegex, "<a target='_blank' href='$1'>$1</a>"));
      newLine.append(actualMsg);

      tabView.append(newLine)
             .scrollTop(tabView[0].scrollHeight);

      var visibleLines = tabView.find('.line').toArray();
      while (visibleLines.length > maxLines) {
        visibleLines[0].remove();
        visibleLines.shift(); // in case we use this later in the function
      }
    }
// (anonymous) [javascript]
			$('#fn').change(function(){
				var name = $('#fn').val().strip_tags();
				var item = $('#contacts [data-id="'+Contacts.UI.Card.id+'"]');
				$(item).find('a').html(name);
				var added = false;
				$('#contacts li').each(function(){
					if ($(this).text().toLowerCase() > name.toLowerCase()) {
						$(this).before(item).fadeIn('fast');
						added = true;
						return false;
					}
				});
				if(!added) {
					$('#leftcontent ul').append(item);
				}
				Contacts.UI.Contacts.scrollTo(Contacts.UI.Card.id);
			});
// (anonymous) [javascript]
			$('#fn').change(function(){
				var name = $('#fn').val();
				var item = $('#contacts [data-id="'+Contacts.UI.Card.id+'"]');
				$(item).find('a').html(name);
				var added = false;
				$('#contacts li').each(function(){
					if ($(this).text().toLowerCase() > name.toLowerCase()) {
						$(this).before(item).fadeIn('fast');
						added = true;
						return false;
					}
				});
				if(!added) {
					$('#leftcontent ul').append(item);
				}
				Contacts.UI.Contacts.scrollTo(Contacts.UI.Card.id);
			});
// update [javascript]
function update() {
	for (const line of regexField.value.split('\n')) {
		// Don't allow delimiters in RegExp string
		if (delimiters.test(line)) {
			return setValidity(escapeTag`Use <code>${line.replace(/^\/|\/$/g, '')}</code> instead of <code>${line}</code>. Slashes are not required.`);
		}

		// Fully test each RegExp
		try {
			// eslint-disable-next-line no-new
			new RegExp(line);
		} catch (error) {
			return setValidity(error.message);
		}
	}

	setValidity();
	saveOptions();
}
// update [javascript]
function update() {
	for (const line of regexField.value.split('\n')) {
		// Don't allow delimiters in RegExp string
		if (delimiters.test(line)) {
			return setValidity(`Use <code>${line.replace(/^\/|\/$/g, '')}</code> instead of <code>${line}</code>. Slashes are not required.`);
		}

		// Fully test each RegExp
		try {
			// eslint-disable-next-line no-new
			new RegExp(line);
		} catch (error) {
			return setValidity(error.message);
		}
	}

	setValidity();
	saveOptions();
}
// saveTitle [javascript]
saveTitle: function(cancel) {
	if ($("#conversationTitle").hasClass("editing")) {

		// Return the conversation title input back to normal.
		var title = $("#conversationTitle input").val();
		if (!title || cancel) title = ETConversation.title;
		var sanitized = $('<div/>').text(title).html();
		$("#conversationTitle").html("<a href='#'>"+sanitized+"</a>").removeClass("editing");

		// If we're cancelling, that's all we need to do.
		if (cancel || ETConversation.title == title) return;

		// Otherwise, update the document title with the new title.
		$(document).attr("title", $(document).attr("title").replace(ETConversation.title, title));
		ETConversation.title = title;

		// And save it.
		$.ETAjax({
			url: "conversation/save.json/" + ETConversation.id,
			type: "post",
			data: {title: title},
			global: true
		});
	}
},
// saveTitle [javascript]
saveTitle: function(cancel) {
	if ($("#conversationTitle").hasClass("editing")) {

		// Return the conversation title input back to normal.
		var title = $("#conversationTitle input").val();
		if (!title || cancel) title = ETConversation.title;
		$("#conversationTitle").html("<a href='#'>"+title+"</a>").removeClass("editing");

		// If we're cancelling, that's all we need to do.
		if (cancel || ETConversation.title == title) return;

		// Otherwise, update the document title with the new title.
		$(document).attr("title", $(document).attr("title").replace(ETConversation.title, title));
		ETConversation.title = title;

		// And save it.
		$.ETAjax({
			url: "conversation/save.json/" + ETConversation.id,
			type: "post",
			data: {title: title},
			global: true
		});
	}
},
// changeValue [javascript]
	changeValue:function(val){ 
		var txtValue = $('<div/>').text($('#akSelectValueField_'+val).val()).html();		
		$('#akSelectValueStatic_'+val).html( txtValue );
		this.editValue(val)
	},
// changeValue [javascript]
	changeValue:function(val){ 
		$('#akSelectValueStatic_'+val).html( $('#akSelectValueField_'+val).val() );
		this.editValue(val)
	},
// (anonymous) [javascript]
.factory('Alert', ['$rootScope', '$filter', function ($rootScope, $filter) {
    return function (hdr, msg, cls, action, secondAlert, disableButtons, backdrop) {
        var scope = $rootScope.$new(), alertClass, local_backdrop;
        msg = $filter('sanitize')(msg);
        if (secondAlert) {

            $('#alertHeader2').html(hdr);
            $('#alert2-modal-msg').html(msg);

            alertClass = (cls) ? cls : 'alert-danger'; //default alert class is alert-danger
            local_backdrop = (backdrop === undefined) ? "static" : backdrop;

            $('#alert2-modal-msg').attr({ "class": "alert " + alertClass });
            $('#alert-modal2').modal({
                show: true,
                keyboard: true,
                backdrop: local_backdrop
            });
            scope.disableButtons2 = (disableButtons) ? true : false;

            $('#alert-modal2').on('hidden.bs.modal', function () {
                if (action) {
                    action();
                }
            });
            $('#alert-modal2').on('shown.bs.modal', function () {
                $('#alert2_ok_btn').focus();
            });
            $(document).bind('keydown', function (e) {
                if (e.keyCode === 27 || e.keyCode === 13) {
                    $('#alert-modal2').modal('hide');
                }
            });
        } else {

            $('#alertHeader').html(hdr);
            $('#alert-modal-msg').html(msg);
            alertClass = (cls) ? cls : 'alert-danger'; //default alert class is alert-danger
            local_backdrop = (backdrop === undefined) ? "static" : backdrop;

            $('#alert-modal-msg').attr({ "class": "alert " + alertClass });
            $('#alert-modal').modal({
                show: true,
                keyboard: true,
                backdrop: local_backdrop
            });

            $('#alert-modal').on('hidden.bs.modal', function () {
                if (action) {
                    action();
                }
            });
            $('#alert-modal').on('shown.bs.modal', function () {
                $('#alert_ok_btn').focus();
            });
            $(document).bind('keydown', function (e) {
                if (e.keyCode === 27 || e.keyCode === 13) {
                    $('#alert-modal').modal('hide');
                }
            });

            scope.disableButtons = (disableButtons) ? true : false;
        }
    };
}])
// (anonymous) [javascript]
.factory('Alert', ['$rootScope', function ($rootScope) {
    return function (hdr, msg, cls, action, secondAlert, disableButtons, backdrop) {
        var scope = $rootScope.$new(), alertClass, local_backdrop;
        if (secondAlert) {

            $('#alertHeader2').html(hdr);
            $('#alert2-modal-msg').html(msg);

            alertClass = (cls) ? cls : 'alert-danger'; //default alert class is alert-danger
            local_backdrop = (backdrop === undefined) ? "static" : backdrop;

            $('#alert2-modal-msg').attr({ "class": "alert " + alertClass });
            $('#alert-modal2').modal({
                show: true,
                keyboard: true,
                backdrop: local_backdrop
            });
            scope.disableButtons2 = (disableButtons) ? true : false;

            $('#alert-modal2').on('hidden.bs.modal', function () {
                if (action) {
                    action();
                }
            });
            $('#alert-modal2').on('shown.bs.modal', function () {
                $('#alert2_ok_btn').focus();
            });
            $(document).bind('keydown', function (e) {
                if (e.keyCode === 27 || e.keyCode === 13) {
                    $('#alert-modal2').modal('hide');
                }
            });
        } else {

            $('#alertHeader').html(hdr);
            $('#alert-modal-msg').html(msg);
            alertClass = (cls) ? cls : 'alert-danger'; //default alert class is alert-danger
            local_backdrop = (backdrop === undefined) ? "static" : backdrop;

            $('#alert-modal-msg').attr({ "class": "alert " + alertClass });
            $('#alert-modal').modal({
                show: true,
                keyboard: true,
                backdrop: local_backdrop
            });

            $('#alert-modal').on('hidden.bs.modal', function () {
                if (action) {
                    action();
                }
            });
            $('#alert-modal').on('shown.bs.modal', function () {
                $('#alert_ok_btn').focus();
            });
            $(document).bind('keydown', function (e) {
                if (e.keyCode === 27 || e.keyCode === 13) {
                    $('#alert-modal').modal('hide');
                }
            });

            scope.disableButtons = (disableButtons) ? true : false;
        }
    };
}])
// (anonymous) [javascript]
      this.element.find('table tbody').find('tr').each(function(index, tr) {
        // add custom td handlers
        var $currentRow = $(tr);
        var $expand = null;
        if(thisObj.options.expand_callback && thisObj.table){
          var allTds = thisObj.table.fnGetTds($currentRow[0]);      
          var row = [];
          var i =0; 
          $(allTds).each(function(){ 
            row[i++] = $(this).html();
          }); 
          $expand = thisObj.options.expand_callback(row);
          if($expand === null){
            var text = $currentRow.find('a.twist').text(); 
            $currentRow.find('a.twist').parent().text(text);
            $currentRow.find('a.twist').remove();
          }
        }
        
        if(!$currentRow.data('events') || !('click' in $currentRow.data('events'))){
          $currentRow.unbind('click').bind('click', function (e) {
            if($(e.target).is('a') && $(e.target).hasClass('twist') && thisObj.options.expand_callback){
              if(!$currentRow.next().hasClass('expanded')){
                thisObj.element.find('table tbody').find('tr.expanded').remove(); // remove all expanded
                thisObj.element.find('table tbody').find('a.expanded').removeClass('expanded');
                if(!$expand.hasClass('expanded-row-inner-wrapper'))
                  $expand.addClass('expanded-row-inner-wrapper');
                if($expand && $expand.length > 0){
                  $currentRow.after($('<tr>').addClass('expanded').append(
                                  $('<td>').attr('colspan', $currentRow.find('td').length).append(
                                    $expand)));
                  $currentRow.find('a.twist').addClass('expanded');
                }
              }else{
                thisObj.element.find('table tbody').find('tr.expanded').remove(); // remove all expanded 
                thisObj.element.find('table tbody').find('a.expanded').removeClass('expanded');
              }
            }else{
              var $selectedRow = $currentRow; 
              var $rowCheckbox = $selectedRow.find('input[type="checkbox"]');
              if($rowCheckbox && $rowCheckbox.length > 0){
                $selectedRow.toggleClass('selected-row');
                if($selectedRow.hasClass('selected-row'))
                  $rowCheckbox.attr('checked', true);
                else
                  $rowCheckbox.attr('checked', false);
              }
            }  
          // checked/uncheck on checkbox
            thisObj._onRowClick();
            thisObj._trigger('row_click', e);
          });
        }

        if (DEPRECATE && thisObj.options.context_menu_actions) {
          rID = 'ri-'+S4()+S4();
          $currentRow.attr('id', rID);
          $.contextMenu({
            selector: '#'+rID,
            build: function(trigger, e) {
              if(thisObj._countSelectedRows() <= 0)
                return null;
              return { items: thisObj.options.context_menu_actions()};
            }
          });
        }
      });
      this.element.qtip();
    },
// (anonymous) [javascript]
      this.element.find('table tbody').find('tr').each(function(index, tr) {
        // add custom td handlers
        var $currentRow = $(tr);
        var $expand = null;
        if(thisObj.options.expand_callback && thisObj.table){
          var allTds = thisObj.table.fnGetTds($currentRow[0]);      
          var row = [];
          var i =0; 
          $(allTds).each(function(){ 
            row[i++] = $(this).html();
          }); 
          $expand = thisObj.options.expand_callback(row);
          if($expand === null){
            var text = $currentRow.find('a.twist').text(); 
            $currentRow.find('a.twist').parent().append(text);
            $currentRow.find('a.twist').remove();
          }
        }
        
        if(!$currentRow.data('events') || !('click' in $currentRow.data('events'))){
          $currentRow.unbind('click').bind('click', function (e) {
            if($(e.target).is('a') && $(e.target).hasClass('twist') && thisObj.options.expand_callback){
              if(!$currentRow.next().hasClass('expanded')){
                thisObj.element.find('table tbody').find('tr.expanded').remove(); // remove all expanded
                thisObj.element.find('table tbody').find('a.expanded').removeClass('expanded');
                if(!$expand.hasClass('expanded-row-inner-wrapper'))
                  $expand.addClass('expanded-row-inner-wrapper');
                if($expand && $expand.length > 0){
                  $currentRow.after($('<tr>').addClass('expanded').append(
                                  $('<td>').attr('colspan', $currentRow.find('td').length).append(
                                    $expand)));
                  $currentRow.find('a.twist').addClass('expanded');
                }
              }else{
                thisObj.element.find('table tbody').find('tr.expanded').remove(); // remove all expanded 
                thisObj.element.find('table tbody').find('a.expanded').removeClass('expanded');
              }
            }else{
              var $selectedRow = $currentRow; 
              var $rowCheckbox = $selectedRow.find('input[type="checkbox"]');
              if($rowCheckbox && $rowCheckbox.length > 0){
                $selectedRow.toggleClass('selected-row');
                if($selectedRow.hasClass('selected-row'))
                  $rowCheckbox.attr('checked', true);
                else
                  $rowCheckbox.attr('checked', false);
              }
            }  
          // checked/uncheck on checkbox
            thisObj._onRowClick();
            thisObj._trigger('row_click', e);
          });
        }

        if (DEPRECATE && thisObj.options.context_menu_actions) {
          rID = 'ri-'+S4()+S4();
          $currentRow.attr('id', rID);
          $.contextMenu({
            selector: '#'+rID,
            build: function(trigger, e) {
              if(thisObj._countSelectedRows() <= 0)
                return null;
              return { items: thisObj.options.context_menu_actions()};
            }
          });
        }
      });
      this.element.qtip();
    },
// buildHTML [javascript]
  function buildHTML(results) {
    var html = [];
    for (var i=0; i<results.length; i++) {
      html.push([
        '<li class="module-item">',
          '<p class="module-item-title">',
              'File: <a href="', results[i].absolute_url, 
                    '?highlight=', encodeURIComponent($("#id_site_search_2").val()), '">', 
                    _(results[i].project.name),
                    " - ", _(results[i].name), "</a>",
          "</p>",
          "<p>", _(results[i].text), "</p>",
        "</li>"].join('')
      );
    }   
    return html.join('');
  }
// buildHTML [javascript]
  function buildHTML(results) {
    var html = [];
    for (var i=0; i<results.length; i++) {
      html.push([
        '<li class="module-item">',
          '<p class="module-item-title">',
              'File: <a href="', results[i].absolute_url, 
                    '?highlight=', $("#id_site_search_2").val(), '">', 
                    results[i].project.name,
                    " - ", results[i].name, "</a>",
          "</p>",
          "<p>", results[i].text, "</p>",
        "</li>"].join('')
      );
    }   
    return html.join('');
  }
// (anonymous) [javascript]
					input.keypress(function(event) {
						if(event.keyCode == 13) {
							event.preventDefault();
							event.stopPropagation();
							var li=$(this).parent();
							$(this).remove();
							li.text('+ '+settings.createText);
							li.before(createItem(this));
							var select=button.parent().next();
							var option=$('<option selected="selected"/>');
							option.attr('value',$(this).val());
							option.text($(this).val());
							select.append(optione);
							li.prev().children('input').trigger('click');
							button.parent().data('preventHide',false);
							if(settings.createCallback){
								settings.createCallback();
							}
						}
					});
// (anonymous) [javascript]
					input.keypress(function(event) {
						if(event.keyCode == 13) {
							event.preventDefault();
							event.stopPropagation();
							var li=$(this).parent();
							$(this).remove();
							li.text('+ '+settings.createText);
							li.before(createItem(this));
							var select=button.parent().next();
							select.append($('<option selected="selected" value="'+$(this).val()+'">'+$(this).val()+'</option>'));
							li.prev().children('input').trigger('click');
							button.parent().data('preventHide',false);
							if(settings.createCallback){
								settings.createCallback();
							}
						}
					});
// (anonymous) [javascript]
setTimeout(function() {
  if ( $( '.plexBack a').length < 1 ) {
    $( '.plexBack' ).append('<a href="' + encodeURI(document.referrer) + '"></a>');
  }
},10);
// (anonymous) [javascript]
setTimeout(function() {
  if ( $( '.plexBack a').length < 1 ) {
    $( '.plexBack' ).append('<a href="' + document.referrer + '"></a>');
  }
},10);
// updateOption [javascript]
	function updateOption (that) {
		try {
			var thisId = jQuery('#fb-field-id').val();
			var thisOptionid = that.attr('optionid');
			var thisOptionValue = that.val();
			var thisType = jQuery('#fb-new-type').val();
			// Update preview
			if (thisType === "radio") {
				jQuery('#fb-radio-' + thisId + '-' + thisOptionid + ' span').text(thisOptionValue);
			} else {
				jQuery('#fb-' + thisId + '-' + thisOptionid).text(thisOptionValue);
			}
			// Update fbForm object
			fbForm.fields[thisId].options[thisOptionid] = thisOptionValue;
		} catch(e) {
			if (debug) {
				console.log("updateOption(): " + e);
			}
		}
	}
// updateOption [javascript]
	function updateOption (that) {
		try {
			var thisId = jQuery('#fb-field-id').val();
			var thisOptionid = that.attr('optionid');
			var thisOptionValue = that.val();
			var thisType = jQuery('#fb-new-type').val();
			// Update preview
			if (thisType === "radio") {
				jQuery('#fb-radio-' + thisId + '-' + thisOptionid + ' span').html(thisOptionValue);
			} else {
				jQuery('#fb-' + thisId + '-' + thisOptionid).text(thisOptionValue);
			}
			// Update fbForm object
			fbForm.fields[thisId].options[thisOptionid] = thisOptionValue;
		} catch(e) {
			if (debug) {
				console.log("updateOption(): " + e);
			}
		}
	}
// createItem [javascript]
			function createItem(element,checked){
				element=$(element);
				var item=element.val();
				var id='ms'+multiSelectId+'-option-'+item;
				var input=$('<input type="checkbox"/>');
				input.attr('id',id);
				var label=$('<label/>');
				label.attr('for',id);
				label.text(item);
				if(settings.checked.indexOf(item)!=-1 || checked){
					input.attr('checked',true);
				}
				if(checked){
					settings.checked.push(item);
				}
				input.change(function(){
					var groupname=$(this).next().text();
					if($(this).is(':checked')){
						element.attr('selected','selected');
						if(settings.oncheck){
							if(settings.oncheck(groupname)===false){
								$(this).attr('checked', false);
								return;
							}
						}
						settings.checked.push(groupname);
					}else{
						var index=settings.checked.indexOf(groupname);
						element.attr('selected',null);
						if(settings.onuncheck){
							if(settings.onuncheck(groupname)===false){
								$(this).attr('checked',true);
								return;
							}
						}
						settings.checked.splice(index,1);
					}
					var oldWidth=button.width();
					if(settings.checked.length>0){
						button.children('span').first().text(settings.checked.join(', '));
					}else{
						button.children('span').first().text(settings.title);
					}
					var newOuterWidth=Math.max((button.outerWidth()-2),settings.minOuterWidth)+'px';
					var newWidth=Math.max(button.width(),settings.minWidth);
					var pos=button.position();
					button.css('height',button.height());
					button.css('white-space','nowrap');
					button.css('width',oldWidth);
					button.animate({'width':newWidth},undefined,undefined,function(){
						button.css('width','');
					});
					list.animate({'width':newOuterWidth,'left':pos.left+3});
				});
				var li=$('<li></li>');
				li.append(input).append(label);
				return li;
			}
// createItem [javascript]
			function createItem(element,checked){
				element=$(element);
				var item=element.val();
				var id='ms'+multiSelectId+'-option-'+item;
				var input=$('<input id="'+id+'" type="checkbox"/>');
				var label=$('<label for="'+id+'">'+item+'</label>');
				if(settings.checked.indexOf(item)!=-1 || checked){
					input.attr('checked',true);
				}
				if(checked){
					settings.checked.push(item);
				}
				input.change(function(){
					var groupname=$(this).next().text();
					if($(this).is(':checked')){
						element.attr('selected','selected');
						if(settings.oncheck){
							if(settings.oncheck(groupname)===false){
								$(this).attr('checked', false);
								return;
							}
						}
						settings.checked.push(groupname);
					}else{
						var index=settings.checked.indexOf(groupname);
						element.attr('selected',null);
						if(settings.onuncheck){
							if(settings.onuncheck(groupname)===false){
								$(this).attr('checked',true);
								return;
							}
						}
						settings.checked.splice(index,1);
					}
					var oldWidth=button.width();
					if(settings.checked.length>0){
						button.children('span').first().text(settings.checked.join(', '));
					}else{
						button.children('span').first().text(settings.title);
					}
					var newOuterWidth=Math.max((button.outerWidth()-2),settings.minOuterWidth)+'px';
					var newWidth=Math.max(button.width(),settings.minWidth);
					var pos=button.position();
					button.css('height',button.height());
					button.css('white-space','nowrap');
					button.css('width',oldWidth);
					button.animate({'width':newWidth},undefined,undefined,function(){
						button.css('width','');
					});
					list.animate({'width':newOuterWidth,'left':pos.left+3});
				});
				var li=$('<li></li>');
				li.append(input).append(label);
				return li;
			}
// variables [python]
    @expose('/variables/<form>', methods=["GET", "POST"])
    @login_required
    @wwwutils.action_logging
    def variables(self, form):
        try:
            if request.method == 'POST':
                data = request.json
                if data:
                    session = settings.Session()
                    var = models.Variable(key=form, val=json.dumps(data))
                    session.add(var)
                    session.commit()
                return ""
            else:
                return self.render(
                    'airflow/variables/{}.html'.format(form)
                )
        except:
            # prevent XSS
            form = escape(form)
            return ("Error: form airflow/variables/{}.html "
                    "not found.").format(form), 404
// variables [python]
    @expose('/variables/<form>', methods=["GET", "POST"])
    @login_required
    @wwwutils.action_logging
    def variables(self, form):
        try:
            if request.method == 'POST':
                data = request.json
                if data:
                    session = settings.Session()
                    var = models.Variable(key=form, val=json.dumps(data))
                    session.add(var)
                    session.commit()
                return ""
            else:
                return self.render(
                    'airflow/variables/{}.html'.format(form)
                )
        except:
            return ("Error: form airflow/variables/{}.html "
                    "not found.").format(form), 404
// get [python]
    @web.authenticated
    def get(self, value):
        user_id = self.current_user_id()

        try:
            subm_id = int(value)
        except:
            raise web.HTTPError(400)

        error_log = contest.get_error_log(user_id, subm_id, is_admin=self.is_admin())
        if not error_log:
            raise web.HTTPError(404)
        self.set_header('Content-Type', 'text/html')
        self.write('<pre>')
        self.write(escape.xhtml_escape(str(error_log)))
        self.write('</pre>')
// get [python]
    @web.authenticated
    def get(self, value):
        user_id = self.current_user_id()

        try:
            subm_id = int(value)
        except:
            raise web.HTTPError(400)

        error_log = contest.get_error_log(user_id, subm_id, is_admin=self.is_admin())
        if not error_log:
            raise web.HTTPError(404)
        self.set_header('Content-Type', 'text/html')
        self.write('<pre>')
        self.write(str(error_log))
        self.write('</pre>')
// handle_json [python]
@socketio.on('sendmsg', namespace='/pychattr')
def handle_json(json):
	json = jsondecode.loads(json)
	channel = json['room']
	text = json['text']
	text = text.translate(None, '}{<>') #antiXSS
	text = text.replace("'", "\'")
	text = text.replace('"', '\"')
	user = session["username"]
	tjson = '{"room": "'+channel+'", "text": "'+text+'", "from": "'+user+'"}'
	send(tjson, room=channel) # send it :)
// handle_json [python]
@socketio.on('sendmsg', namespace='/pychattr')
def handle_json(json):
	print "got msg"
	json = jsondecode.loads(json)
	channel = json['room']
	text = json['text']
	user = session["username"]
	tjson = '{"room": "'+channel+'", "text": "'+text+'", "from": "'+user+'"}'
	send(tjson, room=channel) # send it :)
	print str(tjson)
// get [python]
    @web.authenticated
    def get(self, value):
        if not self.is_admin():
            raise web.HTTPError(404)
        self.set_header('Content-Type', 'text/html')
        self.write("<pre>")
        try:
            server_log_path = os.path.join(options.contest_dir, "server_log.txt")
            with open(server_log_path, 'r') as in_file:
                lines = [line.decode('utf-8') for line in in_file.readlines()]
                lines = [line for line in lines if all([v in line for v in value.split('/')])]
                self.write(escape.xhtml_escape(''.join(lines)))
        except:
            logger.error("unable to read log: %s" % (traceback.format_exception(*sys.exc_info()),))
            self.write("unable to read log")
        self.write("</pre>")
// get [python]
    @web.authenticated
    def get(self, value):
        if not self.is_admin():
            raise web.HTTPError(404)
        self.set_header('Content-Type', 'text/html')
        self.write("<pre>")
        try:
            server_log_path = os.path.join(options.contest_dir, "server_log.txt")
            with open(server_log_path, 'r') as in_file:
                lines = [line.decode('utf-8') for line in in_file.readlines()]
                lines = [line for line in lines if all([v in line for v in value.split('/')])]
                self.write(''.join(lines))
        except:
            logger.error("unable to read log: %s" % (traceback.format_exception(*sys.exc_info()),))
            self.write("unable to read log")
        self.write("</pre>")
// pref_get [python]
@app.route("/api/preferences/get/<key>")
def pref_get(key):
    if get_user() is None:
        return "Authentication required", 401

    if key in get_preferences():
        return Response(
            json.dumps({'key': key, 'value': get_preferences()[key]}),
            mimetype='application/json'
        )
    else:
        return Response(
            json.dumps({'key': key, 'error': 'novalue'}),
            mimetype='application/json'
        )
// pref_get [python]
@app.route("/api/preferences/get/<key>")
def pref_get(key):
    if get_user() is None:
        return "Authentication required", 401

    if key in get_preferences():
        return Response(json.dumps({'key': key, 'value': get_preferences()[key]}))
    else:
        return Response(json.dumps({'key': key, 'error': 'novalue'}))
// stats_for_realm [python]
@require_server_admin
@has_request_variables
def stats_for_realm(request: HttpRequest, realm_str: str) -> HttpResponse:
    try:
        realm = get_realm(realm_str)
    except Realm.DoesNotExist:
        return HttpResponseNotFound()

    return render_stats(
        request,
        f"/realm/{realm_str}",
        realm.name or realm.string_id,
        analytics_ready=is_analytics_ready(realm),
    )
// stats_for_realm [python]
@require_server_admin
@has_request_variables
def stats_for_realm(request: HttpRequest, realm_str: str) -> HttpResponse:
    try:
        realm = get_realm(realm_str)
    except Realm.DoesNotExist:
        return HttpResponseNotFound(f"Realm {realm_str} does not exist")

    return render_stats(
        request,
        f"/realm/{realm_str}",
        realm.name or realm.string_id,
        analytics_ready=is_analytics_ready(realm),
    )
// get_realm_activity [python]
@require_server_admin
def get_realm_activity(request: HttpRequest, realm_str: str) -> HttpResponse:
    data: List[Tuple[str, str]] = []
    all_user_records: Dict[str, Any] = {}

    try:
        admins = Realm.objects.get(string_id=realm_str).get_human_admin_users()
    except Realm.DoesNotExist:
        return HttpResponseNotFound()

    admin_emails = {admin.delivery_email for admin in admins}

    for is_bot, page_title in [(False, "Humans"), (True, "Bots")]:
        all_records = list(get_user_activity_records_for_realm(realm_str, is_bot))

        user_records, content = realm_user_summary_table(all_records, admin_emails)
        all_user_records.update(user_records)

        data += [(page_title, content)]

    page_title = "Clients"
    content = realm_client_table(all_user_records)
    data += [(page_title, content)]

    page_title = "History"
    content = sent_messages_report(realm_str)
    data += [(page_title, content)]

    title = realm_str
    return render(
        request,
        "analytics/activity.html",
        context=dict(data=data, realm_link=None, title=title),
    )
// get_realm_activity [python]
@require_server_admin
def get_realm_activity(request: HttpRequest, realm_str: str) -> HttpResponse:
    data: List[Tuple[str, str]] = []
    all_user_records: Dict[str, Any] = {}

    try:
        admins = Realm.objects.get(string_id=realm_str).get_human_admin_users()
    except Realm.DoesNotExist:
        return HttpResponseNotFound(f"Realm {realm_str} does not exist")

    admin_emails = {admin.delivery_email for admin in admins}

    for is_bot, page_title in [(False, "Humans"), (True, "Bots")]:
        all_records = list(get_user_activity_records_for_realm(realm_str, is_bot))

        user_records, content = realm_user_summary_table(all_records, admin_emails)
        all_user_records.update(user_records)

        data += [(page_title, content)]

    page_title = "Clients"
    content = realm_client_table(all_user_records)
    data += [(page_title, content)]

    page_title = "History"
    content = sent_messages_report(realm_str)
    data += [(page_title, content)]

    title = realm_str
    return render(
        request,
        "analytics/activity.html",
        context=dict(data=data, realm_link=None, title=title),
    )
// pref_set [python]
@app.route("/api/preferences/set/<key>/<value>")
def pref_set(key, value):
    if get_user() is None:
        return "Authentication required", 401

    get_preferences()[key] = (None if value == 'null' else value)
    return Response(
        json.dumps({'key': key, 'success': ''}),
        mimetype='application/json'
    ), 201
// pref_set [python]
@app.route("/api/preferences/set/<key>/<value>")
def pref_set(key, value):
    if get_user() is None:
        return "Authentication required", 401

    get_preferences()[key] = (None if value == 'null' else value)
    return Response(json.dumps({'key': key, 'success': ''})), 201