text:
/* jshint undef: true, unused: true, browser: true, strict: true */
/* global jQuery, Clipboard,  videojs */
(function($){
	"use strict";

	// Module name: Header Fixed
	// Dependencies: no dependencies
	var HeaderFixed = (function(){
		var header = $('.js-header-fixed');
		var headerWrapper = $('
');
		var pub = {};

		// Public functions
		pub.isPresent 	= function () { return header.length; };
		pub.isOver 		= function () { return header.hasClass('header-over'); };
		pub.getHeight 	= function () { return header.outerHeight(); };
		pub.getOffset 	= function () { return pub.isPresent() ? pub.getHeight() : 0; };

		// Private functions
		var updateHeader = function (helper) {
			if($(window).scrollTop() === 0){
	            header.removeClass('header-fixed').addClass(helper);
	        }else{
	            header.addClass('header-fixed').removeClass(helper);
	        }
		};

		var init = function () {
			if (!pub.isOver()){
				header.wrap(headerWrapper.height(header.outerHeight()));
				header.addClass('header-fixed');
			} else {
				var helper = '';

				if (header.hasClass('large')){ helper = 'large'; }
				else if (header.hasClass('small')){ helper = 'small'; }

				updateHeader(helper);

				$(window).scroll(function () {
					updateHeader(helper);
				});
			}

		};

		if(pub.isPresent()){
			init();
		}

		return pub;

	})();

	// Get the correct copy message depending on client's OS.
	var getCopyMessage = function (action) {
		var actionMsg = '';
		var actionKey = (action === 'cut' ? 'X' : 'C');

		if(/iPhone|iPad/i.test(navigator.userAgent)) {
			actionMsg = 'no support :(';
	    } else if (/Mac/i.test(navigator.userAgent)) {
	        actionMsg = 'press ⌘-' + actionKey + ' to ' + action;
	    } else {
	        actionMsg = 'press Ctrl-' + actionKey + ' to ' + action;
	    }

	    return actionMsg;
	};

	// Module name: Copy to clipboard
	// Dependencies: clipboard.js.min.js
	// Docs: https://github.com/zenorocha/clipboard.js/
	(function(){

		var clipboard = new Clipboard('.js-copy-to-clipboard', {
			target: function (trigger) {
				return $(trigger).parent().find('.js-code')[0];
			}
		});

		clipboard.on('success', function (e) {
			e.clearSelection();

			$(e.trigger).text('copied');
			setTimeout(function () {
				$(e.trigger).text('copy');
			}, 700);

		});

		clipboard.on('error', function (e) {
			$(e.trigger).text(getCopyMessage(e.action)).addClass('copy-code-error');
			setTimeout(function () {
				$(e.trigger).text('copy').removeClass('copy-code-error');
			}, 1400);
		});

	})();

	// Module name: Filetree
	// Dependencies: jquery.treeView.js
	// Docs: https://github.com/samarjeet27/TreeViewJS
	(function(){
		$('.js-file-tree').each(function () {
			var fileTree = $(this);
			var expanded = fileTree.data('expanded');
			fileTree.treeView();

			if(expanded === true){
				fileTree.treeView('expandAll');
			}

			$('.js-expand', fileTree.parent()).click(function () {
				fileTree.treeView('expandAll');
			});

			$('.js-collapse', fileTree.parent()).click(function () {
				fileTree.treeView('collapseAll');
			});
		});
	})();

	// Module name: Filetree Text
	// Dependencies: no dependencies
	(function(){
		// Select all file trees on the page
		$('.js-file-tree-text').each(function () {
			var folderClass = '.file-tree-text-folder'; // Folder class, used to count the number of parents
			var nameClass = '.file-tree-text-name'; // Folder/File name class, used to prepend the tree prefix
			var fileTreeText = $(this);
			var space = '\u2502   ';
			var folder = '\u251C\u2500\u2500 ';

			var getPrefix = function (level) {
				var prefix = '';

 				for (var i = 0; i < level; i++) {
 					prefix += (i === level-1) ? folder : space;
 				}

 				return prefix;
			};

			fileTreeText.find('li').each(function () {
				var level = $(this).parents(folderClass).length;

				$(this).children(nameClass).first().prepend(getPrefix(level));
			});
		});
	})();

	// Module name: Modal
	// Dependencies: jquery.bPopup.js
	// Docs: https://github.com/dinbror/bpopup
	(function(){
		$('.js-open-modal').click(function(event) {
			event.preventDefault();

			var button   = $(this),
				target   = $(button.data('target')),
				options  = button.data('config'),
				defaults = {
					closeClass: 'js-close-modal-button'
				};

			$.extend(defaults, options);

			target.bPopup(defaults);
		});
	})();

	// Module name: Before and After
	// Dependencies: jquery.twentytwenty.js
	// Docs: https://github.com/zurb/twentytwenty
	(function(){
		$(window).load(function () {
			$('.js-ba').twentytwenty();
		});
	})();

	// Module name: Accordion
	// Dependencies: no dependencies
	(function(){
		var accordions = $('.js-accordion');

		accordions.each(function () {
			var accordion = $(this);
			var title = accordion.find('.accordion-title');

			title.click(function (event) {
				event.preventDefault();

				var title = $(this);
				var scope = title.closest('.accordion-item');
				var description = $('.accordion-description', scope);

				if(description.hasClass('active')){
					scope.removeClass('active');
					description.stop().slideUp().removeClass('active');
				}else{
					scope.addClass('active');
					description.stop().slideDown().addClass('active');
				}
			});
		});
	})();

	// Module name: FAQ
	// Dependencies: jquery.fastLiveFilter.js
	// Docs: https://github.com/awbush/jquery-fastLiveFilter
	(function(){
		var faqFilters = $('.js-faq-filter');
		var faqs = $('.js-faq');

		faqFilters.each(function() {
			var faqFilter = $(this);
			var faqFilterInput = faqFilter.find('input');
			var target = faqFilter.data('target');

			if(typeof target !== 'undefined'){
				faqFilterInput.fastLiveFilter(target, {
					selector: $(target).find('.faq-question')
				});
			}

		});

		faqs.each(function() {
			var faq = $(this);
			var questions = faq.find('.faq-question');

			questions.click(function (event) {
				event.preventDefault();

				var question = $(this);
				var scope = question.closest('.faq-item');
				var answer = $('.faq-answer', scope);

				if(answer.hasClass('active')){
					question.removeClass('active');
					answer.stop().slideUp().removeClass('active');
				}else{
					question.addClass('active');
					answer.stop().slideDown().addClass('active');
				}
			});
		});
	})();

	// Module name: Interactive steps
	// Dependencies: jquery.steps.js
	// Docs: https://github.com/rstaib/jquery-steps
	(function(){
		var steps = $('.js-steps-interactive');

		steps.each(function() {
			var step = $(this);
			var config = {
				headerTag: "h4",
			    transitionEffect: "fade",
			    enableAllSteps: true,
			    labels: {
			    	current: ''
			    }
			};
			var userConfig = step.data('config');

			$.extend(true, config, userConfig);
			steps.steps(config);
		});
	})();

	// Module name: Tabs
	// Dependencies: jquery.steps.js
	// Docs: https://github.com/rstaib/jquery-steps
	(function(){
		var tabsList = $('.js-tabs');

		tabsList.each(function() {
			var tab = $(this);
			var config = {
				headerTag: "h4",
			    bodyTag: "div",
			    titleTemplate: '#title#',
			    transitionEffect: "fade",
			    enableFinishButton: false,
		        enablePagination: false,
		        enableAllSteps: true,
		        labels: {
			    	current: ''
			    }
			};
			var userConfig = tab.data('config');

			$.extend(true, config, userConfig);
			tab.steps(config);
		});
	})();

	// Module name: Video
	// Dependencies: jquery.fitvids.js
	// Docs: https://github.com/davatron5000/FitVids.js
	(function(){
		$('body').fitVids();
	})();

	// Module name: Video Advanced
	// Dependencies: jquery.ytv.js
	// Docs: https://github.com/Giorgio003/Youtube-TV
	(function(){
		var vids = $('.js-video-advanced');

		vids.each(function() {
			var vid = $(this);
			var config = {
				apiKey: vid.data('api')
			};
			var userConfig = vid.data('config');
			$.extend(true, config, userConfig);

			vid.ytv(config);

			vid.removeAttr('data-api');
		});

	})();

	// Module name: Menu Mobile
	// Dependencies: jquery.slicknav.js
	// Docs: https://github.com/ComputerWolf/SlickNav
	(function(){
		var menus = $('.js-menu');

		menus.each(function() {
			var menu = $(this);
			var config = {
				label: '',
				prependTo: menu.parent(),
				closedSymbol: '&#xf054',
				openedSymbol: '&#xf078',
				allowParentLinks: true
			};

			var userConfig = menu.data('config');

			// Merge default and user's configurations
			$.extend(true, config, userConfig);

			// Initialize SlickNav
			menu.slicknav(config);

			// Initialize SuperFish
			menu.superfish({
				delay: 300,
			    autoArrows: false,
			    speed: 'fast',
			    disableHI: true
			});

			// Switch to light menu on mobiles if necessary
			if(menu.hasClass('menu-light')){
				$('.slicknav_menu').addClass('menu-light');
			}

			// Close menu on offclick
			$('body').click(function() {
				if($('.slicknav_btn').hasClass('slicknav_open')){
					menu.slicknav('close');
				}
			});

			$('.slicknav_btn, .slicknav_nav').on('click', function(event) {
				event.stopPropagation();
			});

		});
	})();

	// Module name: Menu Side
	// Dependencies: jquery.sidr.js
	// Docs: https://github.com/artberri/sidr
	(function(){
		var position = 'left';
		var button = $('.js-menu-side');

		if(button.length){
			if(button.data('position') === 'right'){
				position = 'right';
			}

			button.sidr({
				source: '.js-menu-side-content',
				side: position
			});

			$('.page').click(function() {
				if($('#sidr').is(':visible')){
					$.sidr('close');
				}
			});

			button.click(function(event) {
				event.stopPropagation();
			});
		}

	})();

	// Module menu: Fixed sidebar
	// Dependencies: no dependencies
	var FixedSidebar = (function(){
		if (!HeaderFixed.isPresent()) {
			var sidebars = $('.js-sidebar-fixed');
			var additionalOffset = 30;
			var pub = {};

			pub.updateSidebarWidth = function (sidebar) {
				if(sidebar){
					sidebar.outerWidth(sidebar.parent().outerWidth());
				}
			};
			pub.updateFixedSidebar = function (sidebar) {
				var topDistance = $(window).scrollTop();
				var layout = sidebar.closest('.js-layout');
				var layoutHeight = layout.outerHeight();
				var layoutOffset = layout.offset().top - additionalOffset;
				var sidebarHeight = sidebar.outerHeight();
				var heightLeft = topDistance + sidebarHeight - layoutHeight - layoutOffset;

				// Update wrapper height - act as a placeholder
				sidebar.closest('.js-sidebar-wrapper').height(sidebar.outerHeight());

				// If sidebar should be fixed
				if(topDistance > layoutOffset && heightLeft <= 0){
					sidebar.addClass('sidebar-is-fixed').removeClass('sidebar-is-bottom');
					pub.updateSidebarWidth(sidebar);

				// If sidebar should be sticked to the bottom
				}else if(topDistance > layoutOffset && heightLeft > 0){
					sidebar.removeClass('sidebar-is-fixed').addClass('sidebar-is-bottom');
					pub.updateSidebarWidth(sidebar);

				// If sidebar should be static
				}else{
					sidebar.removeClass('sidebar-is-fixed sidebar-is-bottom');
				}
			};

			sidebars.each(function() {
				var sidebar = $(this);
				var resizeTimer;

				// Wrap all the sidebars
				sidebar.wrap('
');

				pub.updateFixedSidebar(sidebar);
				pub.updateSidebarWidth(sidebar);

				$(window).on('resize', function() {
					clearTimeout(resizeTimer);
					resizeTimer = setTimeout(function() {
						if (sidebar.is(':visible')) {
							pub.updateSidebarWidth(sidebar);
							pub.updateFixedSidebar(sidebar);
						}
					}, 250);
				});

				$(window).scroll(function () {
					if (sidebar.is(':visible')) {
						pub.updateFixedSidebar(sidebar);
					}
				});
			});

			return pub;
		}

	})();

	// Module name: Menu Vertical
	// Dependencies: tendina.min.js, jquery.resmenu.js
	// Docs:
	// https://github.com/iprignano/tendina
	// https://github.com/micc83/ReSmenu
	(function(){
		var menus = $('.js-menu-vertical');

		menus.each(function() {
			var menu = $(this);
			var prependTo = menu.data('prepend-to');
			var select = menu.data('select');

			menu.find('li').each(function() {
				if ($(this).has('ul').length) {
					$(this).addClass('has-children');
				}
			});

			menu.tendina({
				animate: false,
				activeMenu: '.selected',
				openCallback: function() {
					if(FixedSidebar){
						FixedSidebar.updateFixedSidebar(menu.closest('.js-sidebar-fixed'));
					}

				}
			});

			menu.ReSmenu({
				maxWidth: 974,
				prependTo: prependTo,
				menuClass: "vertical-menu-select",
				selectId: "vertical-menu-dropdown",
				activeClass: "selected",
				selectOption: select
			});
		});
	})();

	// Module name: Search Minimal
	// Dependencies: no dependencies
	(function(){
		var searchIcons = $('.js-search-minimal-icon');

		searchIcons.each(function () {
			var btn = $(this);
			var scope = btn.closest('.js-search-minimal');
			var input = scope.find('.js-search-minimal-input');

			btn.click(function () {
				if(!input.is(':visible')){
					input.fadeIn('fast');
					$('input', input).focus();
				}else{
					input.fadeOut('fast');
				}
			});
		});
	})();

	// Module name: Scroll Top
	// Dependencies: no dependencies
	(function(){
		var scrollButton = $('.js-scroll-top');

		scrollButton.click(function(e) {
			e.preventDefault();
			$("html, body").animate({ scrollTop: "0px" });
		});
	})();

	// Module name: Full Page Section
	// Dependencies: no dependencies
	(function(){
		var elems = $('.js-full-page');
		var height = $(window).height();
		var doit;

		elems.outerHeight(height);

		function resizedw(){
			height = $(window).height();
		    elems.outerHeight(height);
		}

		window.onresize = function(){
			clearTimeout(doit);
			doit = setTimeout(resizedw, 100);
		};
	})();

	// Module name: Scroll To
	// Dependencies: no dependencies
	(function(){
		var buttons = $('.js-scroll-to');

		buttons.each(function () {
			var button = $(this);
			var target = button.data('target');
			var speed = button.data('speed') ? button.data('speed') : 1000;

			if(typeof target !== 'undefined' && $(target).length){
				button.click(function(event) {
					event.preventDefault();

					$('html, body').animate({
				        scrollTop: $(target).first().offset().top - HeaderFixed.getOffset()
				    }, speed);
				});
			}
		});
	})();

	// Module name: Documentation version
	// Dependencies: no dependencies
	(function(){
		var scope = $('.js-docs-version');
		var currentBtn = scope.find('.js-docs-current-version');
		var versionList = scope.find('.js-docs-version-list');

		if(scope.length){
			currentBtn.click(function (e) {
				e.preventDefault();
				e.stopPropagation();

				if(versionList.is(':visible')){
					versionList.fadeOut('fast');
				}else{
					versionList.fadeIn('fast');
				}
			});

			$('body').click(function() {
				if(versionList.is(':visible')){
					versionList.fadeOut('fast');
				}
			});
		}
	})();

	// Module name: Notes
	// Dependencies: no dependencies
	(function(){
		var elems = $('.js-note');

		elems.each(function () {
			var note = $(this);
			var close = note.find('.js-close');
			close.click(function(e) {
				e.preventDefault();
				note.fadeOut();
			});
		});
	})();

	// Module name: Grid View
	// Dependencies: jquery.equalHeight.js
	// Docs: https://github.com/Sam152/Javascript-Equal-Height-Responsive-Rows
	(function(){
		var grid = $('.js-grid-view');
		var elems = grid.find('.js-grid-view-elem');

		elems.responsiveEqualHeightGrid();
	})();

	// Module name: Steps Slider
	// Dependencies: owl.carousel.min.js
	// Docs: https://github.com/smashingboxes/OwlCarousel2
	(function(){
		var slider = $('.js-steps-slider');

		slider.owlCarousel({
			items: 1,
			margin: 5,
			nav: true,
			navText: ['',''],
			navSpeed: 600,
			dragEndSpeed: 600
		});
	})();

	// Module name: Gif Player
	// Dependencies: jquery.gifplayer.js
	// Docs: https://github.com/rubentd/gifplayer
	(function(){
		var gifs = $('.js-gif-player');

		gifs.gifplayer({
			label: ''
		});
	})();

	// Module name: Rotator
	// Dependencies: morphext.js
	// Docs: https://github.com/MrSaints/Morphext
	(function(){
		var rotators = $('.js-rotator');

		rotators.Morphext({
			animation: "bounceIn",
			separator: ",",
			speed: 2000
		});
	})();

	// Module name: Notification
	// Dependencies: no dependencies
	(function(){
		var notifications = $('.js-notification');

		notifications.each(function () {
			var elem = $(this);
			var close = elem.find('.js-close');

			close.click(function (e) {
				e.preventDefault();
				elem.slideUp(500);
			});
		});
	})();

	// Module name: Languages
	// Dependencies: no dependencies
	(function(){
		var languages = $('.js-languages');

		languages.each(function() {
			var language = $(this);
			var list = language.find('.js-languages-list');

			language.mouseenter(function() {
				list.stop().fadeIn();
			}).mouseleave(function () {
				list.stop().fadeOut();
			});
		});
	})();

	// Module name: Parallax
	// Dependencies: no dependencies
	(function(){
		var elems = $('.js-parallax');

		elems.each(function () {
			var elem = $(this);
			var height = elem.outerHeight();
			var percent = height * 0.4;

			elem.css('background-size', '120%');

			$(window).scroll(function () {
				var top = $(window).scrollTop();
				var offsetBottom = elem.offset().top + height;
				var scrolledPercents = (top * 100) / height;
				var move = -(percent * scrolledPercents) / 100;

				if (top < offsetBottom){
					elem.css('background-position', 'center '+ move + "px");
				}

			});
		});
	})();

	// Module name: Animate numbers
	// Dependencies: jquery.animateNumbers.js
	// Docs: https://github.com/talmand/jquery-animate-numbers
	(function(){
		var elems = $('.js-animate-number');
		var animateNumbers = function (elem) {
			if(elem.data('animated') !== true){
				var scrollTop = $(window).scrollTop() + $(window).outerHeight();
				var elemOffset = elem.offset().top + elem.outerHeight();

				if(scrollTop > elemOffset){
					elem.data('animated', true);
					elem.animateNumbers(elem.data('number'), false, 2000, "swing");
				}
			}
		};

		elems.each(function() {
			var elem = $(this);
			animateNumbers(elem);

			$(window).scroll(function () {
				animateNumbers(elem);
			});
		});

	})();

	// Module name: Placeholder fix for old browsers
	// Dependencies: jquery.placeholder.js
	// Docs: https://github.com/mathiasbynens/jquery-placeholder
	(function(){
		$('input, textarea').placeholder();
	})();

	// Module name: Info
	// Dependencies: no dependencies
	(function(){
		var infos = $('.js-info');

		infos.each(function () {
			var info = $(this);
			var closeBtn = info.find('.js-info-close');
			closeBtn.click(function (e) {
				e.preventDefault();
				info.slideUp();
			});
		});
	})();

	// Module name: Changelog
	// Dependencies: jquery.instafilta.js
	// Docs: https://github.com/chromawoods/instaFilta/
	(function(){
		var changelogs = $('.js-changelog');

		changelogs.each(function() {
			var changelog = $(this);
			var changelogItems = changelog.find('.js-changelog-item');

			var changelogFilter = changelog.find('.js-changelog-input').instaFilta({
				scope: '.js-changelog',
				targets: '.js-changelog-update-description'
			});

			var changelogCheckBox = changelog.find('.js-changelog-checkbox');

			changelogItems.each(function() {
				var changelogItem = $(this);
				var switchBtn = changelogItem.find('.js-changelog-switch');
				var fileFilters = changelogItem.find('.js-changelog-file-filter');
				var filesScope = changelogItem.find('.js-changelog-files-scope').instaFilta({
					targets: '.js-changelog-file',
					scope: '.js-changelog-files-scope'
				});

				fileFilters.click(function () {
					var filters = [];
					$(this).toggleClass('inactive');

					fileFilters.each(function () {
						if(!$(this).hasClass('inactive')){
							filters.push($(this).data('type'));
						}
					});

					filesScope.filterCategory(filters);
				});

				switchBtn.click(function(e) {
					e.preventDefault();
					changelogItem.toggleClass('changelog-view-files');
				});
			});

			changelogCheckBox.on('change', function () {
				var checkedCategories = [];

			    changelogCheckBox.each(function() {
			        if ($(this).prop('checked')) {
			            checkedCategories.push($(this).val());
			        }
			    });

			    changelogFilter.filterCategory(checkedCategories);
			});

		});
	})();

	// Module name: Video Playlist Custom
	// Dependencies: video.js, videojs-playlist.js
	// Docs: https://github.com/videojs/video.js
	// https://github.com/tim-peterson/videojs-playlist
	(function(){
		var videoPlaylists = $('.js-video-playlist');

		videoPlaylists.each(function() {
			var video = $(this);
			var videoId = video.attr('id');
			var config = video.data('config');

			videojs(videoId, {
				controlBar: {
				    // Remove the full screen toggle button from the panel
					// It's a workaround, since there's no way to add custom buttons at specific index
					fullscreenToggle: false
				}
			}).ready(function(){
			    var myPlayer = this;
			    var myPlaylist = null;

			    if (config) {
				    myPlaylist = myPlayer.playlist(config);
			    }else{
				    myPlaylist = myPlayer.playlist();
			    }

			    // Create and add the previous button to the panel
			    myPlayer.controlBar.addChild('button').addClass('vjs-prev-button').on('click', function () {
			    	myPlaylist.prev();
			    });

			    // Create and add the next button to the panel
			    myPlayer.controlBar.addChild('button').addClass('vjs-next-button').on('click', function () {
			    	myPlaylist.next();
			    });

			    // Add the full screen toggle button to the panel
				// It's a workaround, since there's no way to add custom buttons at specific index
			    myPlayer.controlBar.addChild('fullscreenToggle');

			});

		});

		$('.js-video-playlist-item-download').click(function(event) {
			event.stopPropagation();
		});

	})();

	// Module name: Video Trigger
	// Dependencies: jquery.bpopup.js
	// Docs: https://github.com/dinbror/bpopup/
	(function() {
		$('.js-video-trigger').click(function (e) {
			e.preventDefault();
			var trigger = $(this);
			var url = trigger.data('video');
			var content = $('.js-video-trigger-modal-content');

			$('.js-video-trigger-modal').bPopup({
	            onOpen: function() {
                    content.html(url || '');
                },
                onClose: function() {
                    content.empty();
                }
	        });

		});

		var self = $(this); //button
        var content = $('.content');

        $('element_to_pop_up').bPopup({
            onOpen: function() {
                content.html(self.data('bpopup') || '');
            },
            onClose: function() {
                content.empty();
            }
        });

	})();

	// Module name: Fragment Identifier
	// Dependencies: clipboard.js.min.js
	// Docs: https://github.com/zenorocha/clipboard.js/
	(function(){

		var clipboard = new Clipboard('.js-fragment-identifier', {
			text: function (trigger) {
				return window.location.host + window.location.pathname + $(trigger).attr('href');
			}
		});

		clipboard.on('success', function (e) {
			e.clearSelection();

			$(e.trigger).addClass('fragment-identifier-copied');
			setTimeout(function () {
				$(e.trigger).removeClass('fragment-identifier-copied');
			}, 1000);

		});

		clipboard.on('error', function (e) {
			$(e.trigger).addClass('fragment-identifier-error');
			setTimeout(function () {
				$(e.trigger).removeClass('fragment-identifier-error');
			}, 1400);
		});

		$('.js-fragment-identifier').click(function(event) {
			event.preventDefault();

			var btn = $(this);
			var href = btn.attr('href');

			if (btn.hasClass('fragment-identifier-scroll')) {
			    $('html, body').animate({
			        scrollTop: $(href).offset().top - HeaderFixed.getOffset()
			    }, 500);
			}

		});
	})();

	// Module name: Contact Form
	// Dependencies: jquery.form-validator.min.js
	// Docs: https://github.com/victorjonsson/jQuery-Form-Validator
	(function(){
		var form = $('#js-contact-form');

		if(form.length){
			var submitForm = function ($form) {
				var formURL = $form.attr("action"); // Get the form's action
				var postData = $form.serialize(); // Serialize the form's data
				var successMessage = $('.js-contacts-success'); // Select the success modal

				// Submit an AJAX request
				$.ajax({
				    url : formURL,
				    type: "POST",
				    data : postData,
				    success:function() {
				    	// On success clear the data from the inputs
				    	$form.find('input:text, textarea').val('');
				    	// Show the success modal for 2 seconds
				    	successMessage.fadeIn().delay(2000).fadeOut();
				    }
				});

				// Prevent form default behavior
				return false;
			};

			// Validate the contact form, if succeeded, call the submitForm function
			$.validate({
		  		form : form,
		  		onSuccess: submitForm
			});
		}
	})();

	// Module name: Footer Fixed
	// Dependencies: no dependencies
	(function(){
		var footerFixed = $('.js-footer-is-fixed'); // Select the fixed footer
		var page = $('.js-page'); // Select the page
		var resizeTimer; // Define the timer

		// Calculate the footer height and set it as a padding-bottom to the page
		var updateHeight = function () {
			var footerHeight = footerFixed.outerHeight();
			page.css('padding-bottom', footerHeight + 'px');
		};

		// Check if fixed footer is enabled of disabled
		if (footerFixed.length) {
			footerFixed.addClass('footer-is-fixed');
			updateHeight();

			// Update the height on window resize
			$(window).on('resize', function() {
				clearTimeout(resizeTimer);
				resizeTimer = setTimeout(function() {
					updateHeight();
				}, 250);
			});
		}
	})();

	// Module name: Video Background
	// Dependencies: jquery.vide.min.js
	// Docs: https://github.com/VodkaBears/Vide
	(function(){
		if ($('.js-video-background').length) {
			var video = $('.js-video-background');
			var videoSrc = video.data('video');

			video.vide(videoSrc, {
				posterType: 'jpg',
				bgColor: '#000'
			});
		}
	})();

	// Module name: Custom Scrollbar
	// Dependencies: jquery.jscrollpane.js, jquery.mousewheel-3.0.6.js
	// Docs: https://github.com/vitch/jScrollPane
	// Settings: http://jscrollpane.kelvinluck.com/settings.html
	(function(){
		// Select the custom scrollable areas
		var customScrollbars = $('.js-custom-scrollbar');

		customScrollbars.each(function() {
			var customScrollbar = $(this);
			var resizeTimer;
			var api;

			// Initialize the plugin
			customScrollbar.jScrollPane({
				mouseWheelSpeed: 40
			});

			// Accessing the plugin's API
			api = customScrollbar.data('jsp');

			$(window).on('resize', function() {
				clearTimeout(resizeTimer);
				resizeTimer = setTimeout(function() {
					// On Window resize done, update the plugin
					api.reinitialise();
				}, 250);
			});

		});

	})();

	// Module name: One Page Navigation
	// Dependencies: jquery.nav.js
	// Docs: https://github.com/davist11/jQuery-One-Page-Nav
	(function(){
		// Select one page navigation elements
		var navs = $('.js-one-page-nav');

		navs.each(function() {
			var nav = $(this);

			// Initialize the plugin
			nav.onePageNav({
				currentClass: "is-active",
				filter: ':not(.is-external)',
				scrollOffset: HeaderFixed.getOffset()
			});
		});
	})();

	// Module name: Rating
	// Dependencies: jquery.rating.js
	// Docs: https://github.com/dreyescat/bootstrap-rating
	(function(){
		var rateWrappers = $('.js-rate-wrapper');

		rateWrappers.each(function() {
			var rateWrapper = $(this);
			var rate = rateWrapper.find('.js-rate');
			var rateCurrent = rateWrapper.find('.js-rate-current');

			rate.rating({
				extendSymbol: function () {
					// On hovering a rating, update the current number.
					$(this).on('rating.rateenter', function (e, rateNumber) {
						rateCurrent.text(rateNumber);

					// On mouse leave, set the current number to the selected one.
				    }).on('rating.rateleave', function () {
				    	if (rate.val()) {
							rateCurrent.text(rate.val());
				    	}else{
							rateCurrent.text('-');
				    	}
				    });
				}
			});
		});

	})();

	// Module name: Preloader
	// Dependencies: no dependencies
	(function(){
		var preloader = $('.js-preloader');
		var preload = $('.js-preload-me').length;

		// Check if the preloader is active
		if(preload){
			$(window).load(function () {
				preloader.fadeOut('slow',function () {
					$(this).remove();
				});
			});
		}
	})();

})(jQuery);


text: Operational transformation

redpajama_set_name: RedPajamaGithub


text:
import serversToApiObjects from "../../../../source/iml/server/servers-to-api-objects.js";

describe("servers to api objects", function() {
  let ADD_SERVER_AUTH_CHOICES, servers;

  beforeEach(function() {
    ADD_SERVER_AUTH_CHOICES = {
      EXISTING_KEYS: "existing_keys_choice",
      ROOT_PASSWORD: "id_password_root",
      ANOTHER_KEY: "private_key_choice"
    };

    servers = {
      addresses: ["lotus-34vm5.iml.intel.com", "lotus-34vm6.iml.intel.com"]
    };
  });

  it("should munge servers added with an existing key", function() {
    servers.auth_type = ADD_SERVER_AUTH_CHOICES.EXISTING_KEYS;

    const result = serversToApiObjects(servers);

    expect(result).toEqual([
      {
        address: "lotus-34vm5.iml.intel.com",
        auth_type: "existing_keys_choice"
      },
      {
        address: "lotus-34vm6.iml.intel.com",
        auth_type: "existing_keys_choice"
      }
    ]);
  });

  it("should munge servers added with a root password", function() {
    servers.auth_type = ADD_SERVER_AUTH_CHOICES.ROOT_PASSWORD;
    servers.root_password = "foo";

    const result = serversToApiObjects(servers);

    expect(result).toEqual([
      {
        address: "lotus-34vm5.iml.intel.com",
        auth_type: ADD_SERVER_AUTH_CHOICES.ROOT_PASSWORD,
        root_password: "foo"
      },
      {
        address: "lotus-34vm6.iml.intel.com",
        auth_type: ADD_SERVER_AUTH_CHOICES.ROOT_PASSWORD,
        root_password: "foo"
      }
    ]);
  });

  it("should munge servers added with a private key", function() {
    servers.auth_type = ADD_SERVER_AUTH_CHOICES.ANOTHER_KEY;
    servers.private_key = "bar";
    servers.private_key_passphrase = "baz";

    const result = serversToApiObjects(servers);

    expect(result).toEqual([
      {
        address: "lotus-34vm5.iml.intel.com",
        auth_type: ADD_SERVER_AUTH_CHOICES.ANOTHER_KEY,
        private_key: "bar",
        private_key_passphrase: "baz"
      },
      {
        address: "lotus-34vm6.iml.intel.com",
        auth_type: ADD_SERVER_AUTH_CHOICES.ANOTHER_KEY,
        private_key: "bar",
        private_key_passphrase: "baz"
      }
    ]);
  });
});


text:
/**
 **  namespace.h: l symbol bindings
 **
 **/
#if !defined(LIBLMACHINE_ENVIRONMENT_NAMESPACE_H_)
#define LIBLMACHINE_ENVIRONMENT_NAMESPACE_H_

#include <algorithm>
#include <iostream>
#include <unordered_map>
#include <utility>

#include "kernel/Pointer.h"

#include "system-class/Char.h"
#include "system-class/Symbol.h"
#include "vector/String.h"

namespace liblmachine {

class Env;

class Namespace : public Pointer {

  private:

    Env* env_;

    typedef std::unordered_map<uint64_t, ptr_t>::const_iterator map_type;
    typedef map_type*                                               map_type_ptr;

    std::unordered_map<uint64_t, ptr_t> hash_;

    static const size_t FNV_prime = 16777619;
    static const uint64_t OFFSET_BASIS = 2166136261UL;

    auto find(ptr_t key) -> map_type {

        return hash_.find(key);
    }

    bool isFound(map_type el) {

        return el != hash_.end();
    }

    ptr_t insert(size_t key, ptr_t symbol) {

        hash_[key] = symbol;
        return symbol;
    }

    uint64_t hash_id(ptr_t str) {

        uint64_t    hash = OFFSET_BASIS;

        String::string_iter<int> iter(str);

        for (auto it = iter.begin(); it != iter.end(); it = ++iter) {
            hash ^= *it;
            hash *= FNV_prime;
        }

        return hash;
    }

  public:
    ptr_t intern(ptr_t str) {

        uint64_t key = hash_id(str);
        auto entry = find(key);

        return isFound(entry) ? entry->second : insert(key, Symbol::make(env_, str));
    }

    ptr_t intern(std::string str) {

        uint64_t key = hash_id(String(str).pointerOf());
        auto entry = find(key);

        return isFound(entry) ?
            entry->second : insert(key, Symbol::make(env_, String::make(env_, str)));
    }

    Namespace(Env* env) : env_(env) { }

    ~Namespace() {
        hash_.clear();
    }
};

}   // namespace liblmachine

#endif // LIBLMACHINE_ENVIRONMENT_NAMESPACE_H_


text:
- Support for redirect rules
- Support for custom URL routes
- Support for bindParam functionality in the database module
- Added unit tests for the engine and db module

### Refactor
- Improved the db module to return more information
- Refactored dbHandler module so it can interact with the refactored db module
- Moved the engine/class.config.php file to sites/class.config.php so each site directory contains it's own configuration
- Refactored engine/class.router.php to seperate functionality to different methods
- Refactored the upload module to make a more clean implementation
- replace the normal array syntax with the short array syntax available from PHP 5.4
- Added header information in engine/class.router.php
- Optimized engine/modules/class.view.php code

### Bug fixes
- Fixed the devtools link in engine/class.routes.php

## V-1.1.1

### Features
- A databaseHandler with predefined methods for models to interact with the database.

### Refactor
- Renamed 'class.sql.php' to 'class.db.php'

### Bug fixes
- Fixed support for show query's

## V-1.1.0

### Features
- Load models in the controller with the model module
- Smart autoloader for modules and models
- Support for session variables in the templates and snippets
- Support for if statements in the templates and snippets

### Refactor
- Optimized how to use the modules
- Changed namespace 'model' to 'models'
- Changed class 'index' to 'router'

### Bug fixes
- Made a little adjustment to the sql module to support lastInsertId with insert query's
- Fixed wrong code replacement with if statements in the template engine
- Fixed a bug when you use cssExceptions or jsExceptions to exclude the all files. The tags where still visible

## V-1.0.0

### Features
- Support for controllers
- Autoloading CSS and JS Files
- Exclude CSS and JS files from autoloading
- Manual load CSS and JS files
- Support for modules
- Override V-Engine modules with custom made modules
- Support for uploading files
- Support for databases and sql query's
- Support for connecting controllers to template files
- Parse variables from the controller to the template file
- Parse datasets from the controller to the template file
- Support for template snippet objects
- Parse variables from the controller to a snippet object
- Parse datasets from the controller to a snippet object
- Support for a custom 404 error webpage

### Refactor
- Changed the namespace 'engine' to 'v'
- Changed the structure from the view module
- Moved modules directory from site/modules to engine/modules
- Removed unnecessary code from the sql module

### Bug fixes
- Fixed a bug in file upload path


text:
gspush: pushing data to google spreadsheet command line interface

## Installation

Add this line to your application's Gemfile:

    gem 'gspush'

And then execute:

    $ bundle

Or install it yourself as:

    $ gem install gspush

## Usage

typical usage to batch process

```sh
url=(YOUR SPREADSHEET URL)
user=(YOUR SPREADSHEET EMAIL ADDRESS)
pass=(YOUR PASSWORD) # FIXME
datetime=`date +%Y%m%d %H:00:00`
num1=123
num2=456
num3=789

echo $datetime $num1 $num2 $num3 | gspush $url -u $user -p $pass
```

then append your numbers to the spreadsheet

## Contributing

1. Fork it
2. Create your feature branch (`git checkout -b my-new-feature`)
3. Commit your changes (`git commit -am 'Added some feature'`)
4. Push to the branch (`git push origin my-new-feature`)
5. Create new Pull Request


text:
- to contribute to this project you need to be a paying member of fitadk.
- You will hand over all ownership of what you contribute to the fitadk organisation.


text:
package org.springframework.richclient.dialog.control;

import javax.swing.DefaultSingleSelectionModel;

/**
 * Custom SingleSelectionModel implementation that allows for
 * vetoing the selection of tabs.
 *

 * The {@link #selectionAllowed(int)} method must return true if
 * the tab at the index can be selected, or false if not.
 *
 * @author Peter De Bruycker
 */
public abstract class VetoableSingleSelectionModel extends DefaultSingleSelectionModel {

	public final void setSelectedIndex(int index) {
		if (selectionAllowed(index)) {
			super.setSelectedIndex(index);
		}
	}

	protected abstract boolean selectionAllowed(int index);
}


text:
(function () {
  'use strict';

  angular
    .module('deities')
    .config(routeConfig);

  routeConfig.$inject = ['$stateProvider'];

  function routeConfig($stateProvider) {
    $stateProvider
      .state('deities', {
        abstract: true,
        url: '/deities',
        template: '<ui-view/>'
      })
      .state('deities.list', {
        url: '',
        templateUrl: 'modules/deities/client/views/list-deities.client.view.html',
        controller: 'DeitiesListController',
        controllerAs: 'vm',
        data: {
          pageTitle: 'Deities List'
        }
      })
      .state('deities.create', {
        url: '/create',
        templateUrl: 'modules/deities/client/views/form-deity.client.view.html',
        controller: 'DeitiesController',
        controllerAs: 'vm',
        resolve: {
          deityResolve: newDeity
        },
        data: {
          roles: ['admin'],
          pageTitle: 'Deities Create'
        }
      })
      .state('deities.edit', {
        url: '/:deityId/edit',
        templateUrl: 'modules/deities/client/views/form-deity.client.view.html',
        controller: 'DeitiesController',
        controllerAs: 'vm',
        resolve: {
          deityResolve: getDeity
        },
        data: {
          roles: ['admin'],
          pageTitle: 'Edit Deity {{ deityResolve.name }}'
        }
      })
      .state('deities.view', {
        url: '/:deityId',
        templateUrl: 'modules/deities/client/views/view-deity.client.view.html',
        controller: 'DeitiesController',
        controllerAs: 'vm',
        resolve: {
          deityResolve: getDeity
        },
        data: {
          pageTitle: 'Deity {{ deityResolve.name }}'
        }
      });
  }

  getDeity.$inject = ['$stateParams', 'DeitiesService'];

  function getDeity($stateParams, DeitiesService) {
    return DeitiesService.get({
      deityId: $stateParams.deityId
    }).$promise;
  }

  newDeity.$inject = ['DeitiesService'];

  function newDeity(DeitiesService) {
    return new DeitiesService();
  }
}());


text:
package org.springframework.security;

import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;

import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.security.config.BeanIds;
import org.springframework.security.ldap.server.UnboundIdContainer;

import static org.assertj.core.api.Assertions.assertThat;

/**
 * @author Eddú Meléndez
 */
public class LdapServerBeanDefinitionParserTests {

	private ClassPathXmlApplicationContext context;

	@BeforeEach
	public void setup() {
		this.context = new ClassPathXmlApplicationContext("applicationContext-security.xml");
	}

	@AfterEach
	public void closeAppContext() {
		if (this.context != null) {
			this.context.close();
			this.context = null;
		}
	}

	@Test
	public void apacheDirectoryServerIsStartedByDefault() {
		String[] beanNames = this.context.getBeanNamesForType(UnboundIdContainer.class);
		assertThat(beanNames).hasSize(1);
		assertThat(beanNames[0]).isEqualTo(BeanIds.EMBEDDED_UNBOUNDID);
	}

}


text:
/*
 * @test
 * @bug 4222827 4506596
 * @summary Tests PropertyEditor for value of type long
 * @author Sergey Malenkov
 */

public class TestLongTypeValue {
    public static void main(String[] args) {
        TestEditor test = new TestEditor(Long.TYPE);
        test.testValue(0l, "0");
        test.testValue(null, null);
        test.testText("1", 1l);
        test.testText(null, null);
    }
}


text:
<?php
// This is a SPIP language file  --  Ceci est un fichier langue de SPIP
// extrait automatiquement de http://www.spip.net/trad-lang/
// ** ne pas modifier le fichier **

if (!defined("_ECRIRE_INC_VERSION")) return;

$GLOBALS[$GLOBALS['idx_lang']] = array(

	// C
	'choix_explication' => '
Cette configuration vous permet d'améliorer la compatibilité du site public avec le navigateur Internet Explorer.

iFixPng (par défaut) rétablit la semi-transparence les images au format PNG sous MSIE 5 et 6.

IE7.js corrige les images PNG et ajoute des sélecteurs CSS2 pour MSIE 5 et 6 (vous pouvez consulter la liste des sélecteurs compatibles introduits par IE7.js et IE8.js).

IE8.js complète IE7.js en enrichissant les comportements des CSS de MSIE 5 à 7.

IE7-squish corrige trois bugs de MSIE 6 (notamment la double marge des éléments flottants), mais des effets indésirables peuvent apparaître (le webmestre doit vérifier la compatibilité).

',
	'choix_non' => 'Ne pas activer : ne rien ajouter à mes squelettes',
	'choix_titre' => 'Compatibilité Microsoft Internet Explorer'
);

?>


text:
package com.squareup.okhttp.internal.http;

import com.squareup.okhttp.Address;
import com.squareup.okhttp.Authenticator;
import com.squareup.okhttp.Connection;
import com.squareup.okhttp.ConnectionPool;
import com.squareup.okhttp.internal.Network;
import com.squareup.okhttp.OkHttpClient;
import com.squareup.okhttp.Protocol;
import com.squareup.okhttp.Request;
import com.squareup.okhttp.internal.Internal;
import com.squareup.okhttp.internal.RouteDatabase;
import com.squareup.okhttp.internal.SslContextBuilder;
import java.io.IOException;
import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.net.Proxy;
import java.net.UnknownHostException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.NoSuchElementException;
import javax.net.SocketFactory;
import javax.net.ssl.HostnameVerifier;
import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLHandshakeException;
import javax.net.ssl.SSLSocketFactory;
import org.junit.Before;
import org.junit.Test;

import static com.squareup.okhttp.internal.http.RouteSelector.SSL_V3;
import static com.squareup.okhttp.internal.http.RouteSelector.TLS_V1;
import static java.net.Proxy.NO_PROXY;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;

public final class RouteSelectorTest {
  private static final int proxyAPort = 1001;
  private static final String proxyAHost = "proxyA";
  private static final Proxy proxyA =
      new Proxy(Proxy.Type.HTTP, new InetSocketAddress(proxyAHost, proxyAPort));
  private static final int proxyBPort = 1002;
  private static final String proxyBHost = "proxyB";
  private static final Proxy proxyB =
      new Proxy(Proxy.Type.HTTP, new InetSocketAddress(proxyBHost, proxyBPort));
  private String uriHost = "hostA";
  private int uriPort = 1003;

  private SocketFactory socketFactory;
  private final SSLContext sslContext = SslContextBuilder.localhost();
  private final SSLSocketFactory sslSocketFactory = sslContext.getSocketFactory();
  private HostnameVerifier hostnameVerifier;

  private final Authenticator authenticator = AuthenticatorAdapter.INSTANCE;
  private final List<Protocol> protocols = Arrays.asList(Protocol.HTTP_1_1);
  private final FakeDns dns = new FakeDns();
  private final RecordingProxySelector proxySelector = new RecordingProxySelector();
  private OkHttpClient client;
  private RouteDatabase routeDatabase;
  private Request httpRequest;
  private Request httpsRequest;

  @Before public void setUp() throws Exception {
    socketFactory = SocketFactory.getDefault();
    hostnameVerifier = HttpsURLConnection.getDefaultHostnameVerifier();

    client = new OkHttpClient()
        .setAuthenticator(authenticator)
        .setProxySelector(proxySelector)
        .setSocketFactory(socketFactory)
        .setSslSocketFactory(sslSocketFactory)
        .setHostnameVerifier(hostnameVerifier)
        .setProtocols(protocols)
        .setConnectionPool(ConnectionPool.getDefault());
    Internal.instance.setNetwork(client, dns);

    routeDatabase = Internal.instance.routeDatabase(client);

    httpRequest = new Request.Builder()
        .url("http://" + uriHost + ":" + uriPort + "/path")
        .build();
    httpsRequest = new Request.Builder()
        .url("https://" + uriHost + ":" + uriPort + "/path")
        .build();
  }

  @Test public void singleRoute() throws Exception {
    Address address = httpAddress();
    RouteSelector routeSelector = RouteSelector.get(httpRequest, client);

    assertTrue(routeSelector.hasNext());
    dns.inetAddresses = makeFakeAddresses(255, 1);
    assertConnection(routeSelector.nextUnconnected(), address, NO_PROXY, dns.inetAddresses[0],
        uriPort, SSL_V3);
    dns.assertRequests(uriHost);

    assertFalse(routeSelector.hasNext());
    try {
      routeSelector.nextUnconnected();
      fail();
    } catch (NoSuchElementException expected) {
    }
  }

  @Test public void singleRouteReturnsFailedRoute() throws Exception {
    Address address = httpAddress();
    RouteSelector routeSelector = RouteSelector.get(httpRequest, client);

    assertTrue(routeSelector.hasNext());
    dns.inetAddresses = makeFakeAddresses(255, 1);
    Connection connection = routeSelector.nextUnconnected();
    routeDatabase.failed(connection.getRoute());
    routeSelector = RouteSelector.get(httpRequest, client);
    assertConnection(routeSelector.nextUnconnected(), address, NO_PROXY, dns.inetAddresses[0],
        uriPort, SSL_V3);
    assertFalse(routeSelector.hasNext());
    try {
      routeSelector.nextUnconnected();
      fail();
    } catch (NoSuchElementException expected) {
    }
  }

  @Test public void explicitProxyTriesThatProxysAddressesOnly() throws Exception {
    Address address = new Address(uriHost, uriPort, socketFactory, null, null, authenticator,
        proxyA, protocols);
    client.setProxy(proxyA);
    RouteSelector routeSelector = RouteSelector.get(httpRequest, client);

    assertTrue(routeSelector.hasNext());
    dns.inetAddresses = makeFakeAddresses(255, 2);
    assertConnection(routeSelector.nextUnconnected(), address, proxyA, dns.inetAddresses[0],
        proxyAPort, SSL_V3);
    assertConnection(routeSelector.nextUnconnected(), address, proxyA, dns.inetAddresses[1],
        proxyAPort, SSL_V3);

    assertFalse(routeSelector.hasNext());
    dns.assertRequests(proxyAHost);
    proxySelector.assertRequests(); // No proxy selector requests!
  }

  @Test public void explicitDirectProxy() throws Exception {
    Address address = new Address(uriHost, uriPort, socketFactory, null, null, authenticator,
        NO_PROXY, protocols);
    client.setProxy(NO_PROXY);
    RouteSelector routeSelector = RouteSelector.get(httpRequest, client);

    assertTrue(routeSelector.hasNext());
    dns.inetAddresses = makeFakeAddresses(255, 2);
    assertConnection(routeSelector.nextUnconnected(), address, NO_PROXY, dns.inetAddresses[0],
        uriPort, SSL_V3);
    assertConnection(routeSelector.nextUnconnected(), address, NO_PROXY, dns.inetAddresses[1],
        uriPort, SSL_V3);

    assertFalse(routeSelector.hasNext());
    dns.assertRequests(uriHost);
    proxySelector.assertRequests(); // No proxy selector requests!
  }

  @Test public void proxySelectorReturnsNull() throws Exception {
    Address address = httpAddress();

    proxySelector.proxies = null;
    RouteSelector routeSelector = RouteSelector.get(httpRequest, client);
    proxySelector.assertRequests(httpRequest.uri());

    assertTrue(routeSelector.hasNext());
    dns.inetAddresses = makeFakeAddresses(255, 1);
    assertConnection(routeSelector.nextUnconnected(), address, NO_PROXY, dns.inetAddresses[0],
        uriPort, SSL_V3);
    dns.assertRequests(uriHost);

    assertFalse(routeSelector.hasNext());
  }

  @Test public void proxySelectorReturnsNoProxies() throws Exception {
    Address address = httpAddress();
    RouteSelector routeSelector = RouteSelector.get(httpRequest, client);

    assertTrue(routeSelector.hasNext());
    dns.inetAddresses = makeFakeAddresses(255, 2);
    assertConnection(routeSelector.nextUnconnected(), address, NO_PROXY, dns.inetAddresses[0],
        uriPort, SSL_V3);
    assertConnection(routeSelector.nextUnconnected(), address, NO_PROXY, dns.inetAddresses[1],
        uriPort, SSL_V3);

    assertFalse(routeSelector.hasNext());
    dns.assertRequests(uriHost);
    proxySelector.assertRequests(httpRequest.uri());
  }

  @Test public void proxySelectorReturnsMultipleProxies() throws Exception {
    Address address = httpAddress();

    proxySelector.proxies.add(proxyA);
    proxySelector.proxies.add(proxyB);
    RouteSelector routeSelector = RouteSelector.get(httpRequest, client);
    proxySelector.assertRequests(httpRequest.uri());

    // First try the IP addresses of the first proxy, in sequence.
    assertTrue(routeSelector.hasNext());
    dns.inetAddresses = makeFakeAddresses(255, 2);
    assertConnection(routeSelector.nextUnconnected(), address, proxyA, dns.inetAddresses[0], proxyAPort,
        SSL_V3);
    assertConnection(routeSelector.nextUnconnected(), address, proxyA, dns.inetAddresses[1], proxyAPort,
        SSL_V3);
    dns.assertRequests(proxyAHost);

    // Next try the IP address of the second proxy.
    assertTrue(routeSelector.hasNext());
    dns.inetAddresses = makeFakeAddresses(254, 1);
    assertConnection(routeSelector.nextUnconnected(), address, proxyB, dns.inetAddresses[0], proxyBPort,
        SSL_V3);
    dns.assertRequests(proxyBHost);

    // Finally try the only IP address of the origin server.
    assertTrue(routeSelector.hasNext());
    dns.inetAddresses = makeFakeAddresses(253, 1);
    assertConnection(routeSelector.nextUnconnected(), address, NO_PROXY, dns.inetAddresses[0], uriPort,
        SSL_V3);
    dns.assertRequests(uriHost);

    assertFalse(routeSelector.hasNext());
  }

  @Test public void proxySelectorDirectConnectionsAreSkipped() throws Exception {
    Address address = httpAddress();

    proxySelector.proxies.add(NO_PROXY);
    RouteSelector routeSelector = RouteSelector.get(httpRequest, client);
    proxySelector.assertRequests(httpRequest.uri());

    // Only the origin server will be attempted.
    assertTrue(routeSelector.hasNext());
    dns.inetAddresses = makeFakeAddresses(255, 1);
    assertConnection(routeSelector.nextUnconnected(), address, NO_PROXY, dns.inetAddresses[0], uriPort,
        SSL_V3);
    dns.assertRequests(uriHost);

    assertFalse(routeSelector.hasNext());
  }

  @Test public void proxyDnsFailureContinuesToNextProxy() throws Exception {
    Address address = httpAddress();

    proxySelector.proxies.add(proxyA);
    proxySelector.proxies.add(proxyB);
    proxySelector.proxies.add(proxyA);
    RouteSelector routeSelector = RouteSelector.get(httpRequest, client);
    proxySelector.assertRequests(httpRequest.uri());

    assertTrue(routeSelector.hasNext());
    dns.inetAddresses = makeFakeAddresses(255, 1);
    assertConnection(routeSelector.nextUnconnected(), address, proxyA, dns.inetAddresses[0], proxyAPort,
        SSL_V3);
    dns.assertRequests(proxyAHost);

    assertTrue(routeSelector.hasNext());
    dns.inetAddresses = null;
    try {
      routeSelector.nextUnconnected();
      fail();
    } catch (UnknownHostException expected) {
    }
    dns.assertRequests(proxyBHost);

    assertTrue(routeSelector.hasNext());
    dns.inetAddresses = makeFakeAddresses(255, 1);
    assertConnection(routeSelector.nextUnconnected(), address, proxyA, dns.inetAddresses[0], proxyAPort,
        SSL_V3);
    dns.assertRequests(proxyAHost);

    assertTrue(routeSelector.hasNext());
    dns.inetAddresses = makeFakeAddresses(254, 1);
    assertConnection(routeSelector.nextUnconnected(), address, NO_PROXY, dns.inetAddresses[0], uriPort,
        SSL_V3);
    dns.assertRequests(uriHost);

    assertFalse(routeSelector.hasNext());
  }

  // https://github.com/square/okhttp/issues/442
  @Test public void nonSslErrorAddsAllTlsModesToFailedRoute() throws Exception {
    client.setProxy(Proxy.NO_PROXY);
    RouteSelector routeSelector = RouteSelector.get(httpsRequest, client);

    dns.inetAddresses = makeFakeAddresses(255, 1);
    Connection connection = routeSelector.nextUnconnected();
    routeSelector.connectFailed(connection, new IOException("Non SSL exception"));
    assertTrue(routeDatabase.failedRoutesCount() == 2);
    assertFalse(routeSelector.hasNext());
  }

  @Test public void sslErrorAddsOnlyFailedTlsModeToFailedRoute() throws Exception {
    client.setProxy(Proxy.NO_PROXY);
    RouteSelector routeSelector = RouteSelector.get(httpsRequest, client);

    dns.inetAddresses = makeFakeAddresses(255, 1);
    Connection connection = routeSelector.nextUnconnected();
    routeSelector.connectFailed(connection, new SSLHandshakeException("SSL exception"));
    assertTrue(routeDatabase.failedRoutesCount() == 1);
    assertTrue(routeSelector.hasNext());
  }

  @Test public void multipleProxiesMultipleInetAddressesMultipleTlsModes() throws Exception {
    Address address = new Address(uriHost, uriPort, socketFactory, sslSocketFactory,
        hostnameVerifier, authenticator, null, protocols);
    proxySelector.proxies.add(proxyA);
    proxySelector.proxies.add(proxyB);
    RouteSelector routeSelector = RouteSelector.get(httpsRequest, client);

    // Proxy A
    dns.inetAddresses = makeFakeAddresses(255, 2);
    assertConnection(routeSelector.nextUnconnected(), address, proxyA, dns.inetAddresses[0],
        proxyAPort, TLS_V1);
    dns.assertRequests(proxyAHost);
    assertConnection(routeSelector.nextUnconnected(), address, proxyA, dns.inetAddresses[0],
        proxyAPort, SSL_V3);
    assertConnection(routeSelector.nextUnconnected(), address, proxyA, dns.inetAddresses[1],
        proxyAPort, TLS_V1);
    assertConnection(routeSelector.nextUnconnected(), address, proxyA, dns.inetAddresses[1],
        proxyAPort, SSL_V3);

    // Proxy B
    dns.inetAddresses = makeFakeAddresses(254, 2);
    assertConnection(routeSelector.nextUnconnected(), address, proxyB, dns.inetAddresses[0],
        proxyBPort, TLS_V1);
    dns.assertRequests(proxyBHost);
    assertConnection(routeSelector.nextUnconnected(), address, proxyB, dns.inetAddresses[0],
        proxyBPort, SSL_V3);
    assertConnection(routeSelector.nextUnconnected(), address, proxyB, dns.inetAddresses[1],
        proxyBPort, TLS_V1);
    assertConnection(routeSelector.nextUnconnected(), address, proxyB, dns.inetAddresses[1],
        proxyBPort, SSL_V3);

    // Origin
    dns.inetAddresses = makeFakeAddresses(253, 2);
    assertConnection(routeSelector.nextUnconnected(), address, NO_PROXY, dns.inetAddresses[0],
        uriPort, TLS_V1);
    dns.assertRequests(uriHost);
    assertConnection(routeSelector.nextUnconnected(), address, NO_PROXY, dns.inetAddresses[0],
        uriPort, SSL_V3);
    assertConnection(routeSelector.nextUnconnected(), address, NO_PROXY, dns.inetAddresses[1],
        uriPort, TLS_V1);
    assertConnection(routeSelector.nextUnconnected(), address, NO_PROXY, dns.inetAddresses[1],
        uriPort, SSL_V3);

    assertFalse(routeSelector.hasNext());
  }

  @Test public void failedRoutesAreLast() throws Exception {
    client.setProxy(Proxy.NO_PROXY);
    RouteSelector routeSelector = RouteSelector.get(httpsRequest, client);

    dns.inetAddresses = makeFakeAddresses(255, 1);

    // Extract the regular sequence of routes from selector.
    List<Connection> regularRoutes = new ArrayList<>();
    while (routeSelector.hasNext()) {
      regularRoutes.add(routeSelector.nextUnconnected());
    }

    // Check that we do indeed have more than one route.
    assertTrue(regularRoutes.size() > 1);
    // Add first regular route as failed.
    routeDatabase.failed(regularRoutes.get(0).getRoute());
    // Reset selector
    routeSelector = RouteSelector.get(httpsRequest, client);

    List<Connection> routesWithFailedRoute = new ArrayList<>();
    while (routeSelector.hasNext()) {
      routesWithFailedRoute.add(routeSelector.nextUnconnected());
    }

    assertEquals(regularRoutes.get(0).getRoute(),
        routesWithFailedRoute.get(routesWithFailedRoute.size() - 1).getRoute());
    assertEquals(regularRoutes.size(), routesWithFailedRoute.size());
  }

  private void assertConnection(Connection connection, Address address, Proxy proxy,
      InetAddress socketAddress, int socketPort, String tlsVersion) {
    assertEquals(address, connection.getRoute().getAddress());
    assertEquals(proxy, connection.getRoute().getProxy());
    assertEquals(socketAddress, connection.getRoute().getSocketAddress().getAddress());
    assertEquals(socketPort, connection.getRoute().getSocketAddress().getPort());
    assertEquals(tlsVersion, connection.getRoute().getTlsVersion());
  }

  /** Returns an address that's without an SSL socket factory or hostname verifier. */
  private Address httpAddress() {
    return new Address(uriHost, uriPort, socketFactory, null, null, authenticator, null, protocols);
  }

  private static InetAddress[] makeFakeAddresses(int prefix, int count) {
    try {
      InetAddress[] result = new InetAddress[count];
      for (int i = 0; i < count; i++) {
        result[i] =
            InetAddress.getByAddress(new byte[] { (byte) prefix, (byte) 0, (byte) 0, (byte) i });
      }
      return result;
    } catch (UnknownHostException e) {
      throw new AssertionError();
    }
  }

  private static class FakeDns implements Network {
    List<String> requestedHosts = new ArrayList<>();
    InetAddress[] inetAddresses;

    @Override public InetAddress[] resolveInetAddresses(String host) throws UnknownHostException {
      requestedHosts.add(host);
      if (inetAddresses == null) throw new UnknownHostException();
      return inetAddresses;
    }

    public void assertRequests(String... expectedHosts) {
      assertEquals(Arrays.asList(expectedHosts), requestedHosts);
      requestedHosts.clear();
    }
  }
}


text:
/**
 * @module parjs
 */
/** */

import {NumericHelpers} from "./numeric-helpers";
import {ParsingState} from "../state";
import {ResultKind} from "../result";
import {ParserDefinitionError} from "../../errors";
import {ParjserBase} from "../parser";
import {Parjser} from "../parjser";
import defaults from "lodash/defaults";

/**
 * A set of options for parsing integers.
 */
export interface IntOptions {
    allowSign: boolean;
    base: number;
}

const defaultOptions: IntOptions = {
    allowSign: true,
    base: 10
};

/**
 * Returns a parser that will parse a single integer, with the options
 * given by `options`.
 * @param pOptions A set of options for parsing integers.
 */
export function int(pOptions ?: Partial<IntOptions>): Parjser<number> {
    let options = defaults(pOptions, defaultOptions);
    if (options.base > 36) {
        throw new ParserDefinitionError("int", "invalid base");
    }
    let expecting = `expecting a ${options.allowSign ? "signed" : "unsigned"} integer in base ${options.base}`;
    return new class Int extends ParjserBase {
        type = "int";
        displayName = "int";
        expecting = expecting;

        _apply(ps: ParsingState): void {
            let {allowSign, base} = options;
            let {position, input} = ps;
            let initPos = ps.position;
            let sign = allowSign ? NumericHelpers.parseSign(ps) : 0;
            let parsedSign = false;
            if (sign !== 0) {
                parsedSign = true;
            } else {
                sign = 1;
            }
            position = ps.position;
            NumericHelpers.parseDigitsInBase(ps, base);
            let value = parseInt(input.substring(initPos, ps.position), base);

            if (ps.position === position) {
                ps.kind = parsedSign ? ResultKind.HardFail : ResultKind.SoftFail;
            } else {
                ps.value = value;
                ps.kind = ResultKind.Ok;
            }
        }

    }();
}


text:
import random

from client import Client
from scenario_five import scenario_five
from scheduler import scheduler
from server_job import ServerJob
from simulation import run_scenario
from utils import logger
from varz import Counter

def spike_client():
  client = Client.get_random_client()
  n = client.get_wants('resource0') + 100
  logger.info(
      'Random mishap: Setting %s wants to %d' %
      (client.get_client_id(), n))
  client.set_wants('resource0', n)

def trigger_master_election():
  job = ServerJob.get_random_server_job()
  logger.info(
      'Random mishap: Triggering master election in job %s' %
      job.get_job_name())
  job.trigger_master_election()

def lose_master():
  job = ServerJob.get_random_server_job()
  t = random.randint(0, 60)
  logger.info(
      'Random mishap: Losing master job %s for %d seconds' %
      (job.get_job_name(), t))
  job.lose_master()
  scheduler.add_relative(t, lambda: job.trigger_master_election())

_mishap_map = dict([
    (5, lambda: spike_client()),
    (10, lambda: trigger_master_election()),
    (15, lambda: lose_master()),
])

# Invoke some random mishap.

def random_mishap():
  scheduler.add_relative(60, lambda: random_mishap())

  total = max(_mishap_map.keys())
  m = random.randint(0, total - 1)
  n = 0

  for (key, value) in _mishap_map.iteritems():
    if n >= m:
      Counter.get('mishap.%d' % key).inc()
      value()
      return

    n += key

  assert False

# Uses the setup of scenario five, but runs for a (simulated) hour
# and invokes random mishap every 60 seconds.

def scenario_seven(reporter):
  scenario_five(reporter)
  reporter.set_filename('scenario_seven')
  scheduler.add_absolute(60, lambda: random_mishap())

if __name__ == '__main__':
  run_scenario(lambda reporter: scenario_seven(reporter), run_for=3600)


text:
using RazorViewsForMarketers.Models.Fields;
using Sitecore.Data.Fields;
using Sitecore.Data.Items;

namespace RazorViewsForMarketers.Core.FieldRenderers
{
    public class CaptchaInitializer : FieldInitializerBase<CaptchaField>
    {
        public CaptchaInitializer(Item fieldItem) : base(fieldItem) { }

        public override void PopulateParameters(Field field, CaptchaField model)
        {

        }

        public override void PopulateLocalizedParameters(Field field, CaptchaField model)
        {

        }
    }
}


text:
// This fuzzer explores the behavior of HCM with replay of trace actions that describe the behavior
// of a mocked codec and decoder/encoder filters. It is only partially complete (~60% test coverage
// with supplied corpus), since HCM has a lot of behavior to model, requiring investment in building
// out modeling actions and a corpus, which is time consuming and may not have significant security
// of functional correctness payoff beyond existing tests. Places where we could increase fuzz
// coverage include:
// * Watermarks
// * WebSocket upgrades
// * Tracing and stats.
// * Encode filter actions (e.g. modeling stop/continue, only done for decoder today).
// * SSL
// * Idle/drain timeouts.
// * HTTP 1.0 special cases
// * Fuzz config settings
#include "envoy/extensions/filters/network/http_connection_manager/v3/http_connection_manager.pb.h"

#include "source/common/common/empty_string.h"
#include "source/common/http/conn_manager_impl.h"
#include "source/common/http/context_impl.h"
#include "source/common/http/date_provider_impl.h"
#include "source/common/http/exception.h"
#include "source/common/http/header_utility.h"
#include "source/common/network/address_impl.h"
#include "source/common/network/utility.h"

#include "test/common/http/conn_manager_impl_fuzz.pb.validate.h"
#include "test/fuzz/fuzz_runner.h"
#include "test/fuzz/utility.h"
#include "test/mocks/access_log/mocks.h"
#include "test/mocks/common.h"
#include "test/mocks/http/mocks.h"
#include "test/mocks/local_info/mocks.h"
#include "test/mocks/network/mocks.h"
#include "test/mocks/router/mocks.h"
#include "test/mocks/runtime/mocks.h"
#include "test/mocks/server/mocks.h"
#include "test/mocks/ssl/mocks.h"
#include "test/mocks/tracing/mocks.h"
#include "test/mocks/upstream/cluster_manager.h"
#include "test/test_common/simulated_time_system.h"

#include "gmock/gmock.h"

using testing::InvokeWithoutArgs;
using testing::Return;

namespace Envoy {
namespace Http {

class FuzzConfig : public ConnectionManagerConfig {
public:
  FuzzConfig(envoy::extensions::filters::network::http_connection_manager::v3::
                 HttpConnectionManager::ForwardClientCertDetails forward_client_cert)
      : stats_({ALL_HTTP_CONN_MAN_STATS(POOL_COUNTER(fake_stats_), POOL_GAUGE(fake_stats_),
                                        POOL_HISTOGRAM(fake_stats_))},
               "", fake_stats_),
        tracing_stats_{CONN_MAN_TRACING_STATS(POOL_COUNTER(fake_stats_))},
        listener_stats_{CONN_MAN_LISTENER_STATS(POOL_COUNTER(fake_stats_))},
        local_reply_(LocalReply::Factory::createDefault()) {
    ON_CALL(route_config_provider_, lastUpdated()).WillByDefault(Return(time_system_.systemTime()));
    ON_CALL(scoped_route_config_provider_, lastUpdated())
        .WillByDefault(Return(time_system_.systemTime()));
    access_logs_.emplace_back(std::make_shared<NiceMock<AccessLog::MockInstance>>());
    request_id_extension_ = Extensions::RequestId::UUIDRequestIDExtension::defaultInstance(random_);
    forward_client_cert_ = fromClientCert(forward_client_cert);
  }

  void newStream() {
    if (!codec_) {
      codec_ = new NiceMock<MockServerConnection>();
    }
    decoder_filter_ = new NiceMock<MockStreamDecoderFilter>();
    encoder_filter_ = new NiceMock<MockStreamEncoderFilter>();

    EXPECT_CALL(filter_factory_, createFilterChain(_))
        .WillOnce(Invoke([this](FilterChainManager& manager) -> bool {
          FilterFactoryCb decoder_filter_factory = [this](FilterChainFactoryCallbacks& callbacks) {
            callbacks.addStreamDecoderFilter(StreamDecoderFilterSharedPtr{decoder_filter_});
          };
          FilterFactoryCb encoder_filter_factory = [this](FilterChainFactoryCallbacks& callbacks) {
            callbacks.addStreamEncoderFilter(StreamEncoderFilterSharedPtr{encoder_filter_});
          };

          manager.applyFilterFactoryCb({}, decoder_filter_factory);
          manager.applyFilterFactoryCb({}, encoder_filter_factory);
          return true;
        }));
    EXPECT_CALL(*decoder_filter_, setDecoderFilterCallbacks(_))
        .WillOnce(Invoke([this](StreamDecoderFilterCallbacks& callbacks) -> void {
          decoder_filter_->callbacks_ = &callbacks;
          callbacks.streamInfo().setResponseCodeDetails("");
        }));
    EXPECT_CALL(*encoder_filter_, setEncoderFilterCallbacks(_));
    EXPECT_CALL(filter_factory_, createUpgradeFilterChain("WebSocket", _, _))
        .WillRepeatedly(Invoke([&](absl::string_view, const Http::FilterChainFactory::UpgradeMap*,
                                   FilterChainManager& manager) -> bool {
          return filter_factory_.createFilterChain(manager);
        }));
  }

  Http::ForwardClientCertType
  fromClientCert(envoy::extensions::filters::network::http_connection_manager::v3::
                     HttpConnectionManager::ForwardClientCertDetails forward_client_cert) {
    switch (forward_client_cert) {
    case envoy::extensions::filters::network::http_connection_manager::v3::HttpConnectionManager::
        SANITIZE:
      return Http::ForwardClientCertType::Sanitize;
    case envoy::extensions::filters::network::http_connection_manager::v3::HttpConnectionManager::
        FORWARD_ONLY:
      return Http::ForwardClientCertType::ForwardOnly;
    case envoy::extensions::filters::network::http_connection_manager::v3::HttpConnectionManager::
        APPEND_FORWARD:
      return Http::ForwardClientCertType::AppendForward;
    case envoy::extensions::filters::network::http_connection_manager::v3::HttpConnectionManager::
        SANITIZE_SET:
      return Http::ForwardClientCertType::SanitizeSet;
    case envoy::extensions::filters::network::http_connection_manager::v3::HttpConnectionManager::
        ALWAYS_FORWARD_ONLY:
      return Http::ForwardClientCertType::AlwaysForwardOnly;
    default:
      return Http::ForwardClientCertType::Sanitize;
    }
  }

  // Http::ConnectionManagerConfig
  const RequestIDExtensionSharedPtr& requestIDExtension() override { return request_id_extension_; }
  const std::list<AccessLog::InstanceSharedPtr>& accessLogs() override { return access_logs_; }
  ServerConnectionPtr createCodec(Network::Connection&, const Buffer::Instance&,
                                  ServerConnectionCallbacks&) override {
    return ServerConnectionPtr{codec_};
  }
  DateProvider& dateProvider() override { return date_provider_; }
  std::chrono::milliseconds drainTimeout() const override { return std::chrono::milliseconds(100); }
  FilterChainFactory& filterFactory() override { return filter_factory_; }
  bool generateRequestId() const override { return true; }
  bool preserveExternalRequestId() const override { return false; }
  bool alwaysSetRequestIdInResponse() const override { return false; }
  uint32_t maxRequestHeadersKb() const override { return max_request_headers_kb_; }
  uint32_t maxRequestHeadersCount() const override { return max_request_headers_count_; }
  absl::optional<std::chrono::milliseconds> idleTimeout() const override { return idle_timeout_; }
  bool isRoutable() const override { return true; }
  absl::optional<std::chrono::milliseconds> maxConnectionDuration() const override {
    return max_connection_duration_;
  }
  absl::optional<std::chrono::milliseconds> maxStreamDuration() const override {
    return max_stream_duration_;
  }
  std::chrono::milliseconds streamIdleTimeout() const override { return stream_idle_timeout_; }
  std::chrono::milliseconds requestTimeout() const override { return request_timeout_; }
  std::chrono::milliseconds requestHeadersTimeout() const override {
    return request_headers_timeout_;
  }
  std::chrono::milliseconds delayedCloseTimeout() const override { return delayed_close_timeout_; }
  Router::RouteConfigProvider* routeConfigProvider() override {
    if (use_srds_) {
      return nullptr;
    }
    return &route_config_provider_;
  }
  Config::ConfigProvider* scopedRouteConfigProvider() override {
    if (use_srds_) {
      return &scoped_route_config_provider_;
    }
    return nullptr;
  }
  const std::string& serverName() const override { return server_name_; }
  HttpConnectionManagerProto::ServerHeaderTransformation
  serverHeaderTransformation() const override {
    return server_transformation_;
  }
  const absl::optional<std::string>& schemeToSet() const override { return scheme_; }
  ConnectionManagerStats& stats() override { return stats_; }
  ConnectionManagerTracingStats& tracingStats() override { return tracing_stats_; }
  bool useRemoteAddress() const override { return use_remote_address_; }
  const Http::InternalAddressConfig& internalAddressConfig() const override {
    return internal_address_config_;
  }
  uint32_t xffNumTrustedHops() const override { return 0; }
  bool skipXffAppend() const override { return false; }
  const std::string& via() const override { return EMPTY_STRING; }
  Http::ForwardClientCertType forwardClientCert() const override { return forward_client_cert_; }
  const std::vector<Http::ClientCertDetailsType>& setCurrentClientCertDetails() const override {
    return set_current_client_cert_details_;
  }
  const Network::Address::Instance& localAddress() override { return local_address_; }
  const absl::optional<std::string>& userAgent() override { return user_agent_; }
  Tracing::HttpTracerSharedPtr tracer() override { return http_tracer_; }
  const TracingConnectionManagerConfig* tracingConfig() override { return tracing_config_.get(); }
  ConnectionManagerListenerStats& listenerStats() override { return listener_stats_; }
  bool proxy100Continue() const override { return proxy_100_continue_; }
  bool streamErrorOnInvalidHttpMessaging() const override {
    return stream_error_on_invalid_http_messaging_;
  }
  const Http::Http1Settings& http1Settings() const override { return http1_settings_; }
  bool shouldNormalizePath() const override { return false; }
  bool shouldMergeSlashes() const override { return false; }
  bool shouldStripTrailingHostDot() const override { return false; }
  Http::StripPortType stripPortType() const override { return Http::StripPortType::None; }
  envoy::config::core::v3::HttpProtocolOptions::HeadersWithUnderscoresAction
  headersWithUnderscoresAction() const override {
    return envoy::config::core::v3::HttpProtocolOptions::ALLOW;
  }
  const LocalReply::LocalReply& localReply() const override { return *local_reply_; }
  envoy::extensions::filters::network::http_connection_manager::v3::HttpConnectionManager::
      PathWithEscapedSlashesAction
      pathWithEscapedSlashesAction() const override {
    return envoy::extensions::filters::network::http_connection_manager::v3::HttpConnectionManager::
        KEEP_UNCHANGED;
  }
  const std::vector<Http::OriginalIPDetectionSharedPtr>&
  originalIpDetectionExtensions() const override {
    return ip_detection_extensions_;
  }
  uint64_t maxRequestsPerConnection() const override { return 0; }
  const HttpConnectionManagerProto::ProxyStatusConfig* proxyStatusConfig() const override {
    return proxy_status_config_.get();
  }
  Http::HeaderValidatorPtr makeHeaderValidator(Protocol, StreamInfo::StreamInfo&) override {
    // TODO(yanavlasov): fuzz test interface should use the default validator, although this could
    // be changed too
    return nullptr;
  }

  const envoy::extensions::filters::network::http_connection_manager::v3::HttpConnectionManager
      config_;
  NiceMock<Random::MockRandomGenerator> random_;
  RequestIDExtensionSharedPtr request_id_extension_;
  std::list<AccessLog::InstanceSharedPtr> access_logs_;
  MockServerConnection* codec_{};
  MockStreamDecoderFilter* decoder_filter_{};
  MockStreamEncoderFilter* encoder_filter_{};
  NiceMock<MockFilterChainFactory> filter_factory_;
  Event::SimulatedTimeSystem time_system_;
  SlowDateProviderImpl date_provider_{time_system_};
  bool use_srds_{};
  Router::MockRouteConfigProvider route_config_provider_;
  Router::MockScopedRouteConfigProvider scoped_route_config_provider_;
  std::string server_name_;
  HttpConnectionManagerProto::ServerHeaderTransformation server_transformation_{
      HttpConnectionManagerProto::OVERWRITE};
  absl::optional<std::string> scheme_;
  Stats::IsolatedStoreImpl fake_stats_;
  ConnectionManagerStats stats_;
  ConnectionManagerTracingStats tracing_stats_;
  ConnectionManagerListenerStats listener_stats_;
  uint32_t max_request_headers_kb_{Http::DEFAULT_MAX_REQUEST_HEADERS_KB};
  uint32_t max_request_headers_count_{Http::DEFAULT_MAX_HEADERS_COUNT};
  absl::optional<std::chrono::milliseconds> idle_timeout_;
  absl::optional<std::chrono::milliseconds> max_connection_duration_;
  absl::optional<std::chrono::milliseconds> max_stream_duration_;
  std::chrono::milliseconds stream_idle_timeout_{};
  std::chrono::milliseconds request_timeout_{};
  std::chrono::milliseconds request_headers_timeout_{};
  std::chrono::milliseconds delayed_close_timeout_{};
  bool use_remote_address_{true};
  Http::ForwardClientCertType forward_client_cert_;
  std::vector<Http::ClientCertDetailsType> set_current_client_cert_details_;
  Network::Address::Ipv4Instance local_address_{"127.0.0.1"};
  absl::optional<std::string> user_agent_;
  Tracing::HttpTracerSharedPtr http_tracer_{std::make_shared<NiceMock<Tracing::MockHttpTracer>>()};
  TracingConnectionManagerConfigPtr tracing_config_;
  bool proxy_100_continue_{true};
  bool stream_error_on_invalid_http_messaging_ = false;
  bool preserve_external_request_id_{false};
  Http::Http1Settings http1_settings_;
  Http::DefaultInternalAddressConfig internal_address_config_;
  bool normalize_path_{true};
  LocalReply::LocalReplyPtr local_reply_;
  std::vector<Http::OriginalIPDetectionSharedPtr> ip_detection_extensions_{};
  std::unique_ptr<HttpConnectionManagerProto::ProxyStatusConfig> proxy_status_config_;
};

// Internal representation of stream state. Encapsulates the stream state, mocks
// and encoders for both the request/response.
class FuzzStream {
public:
  // We track stream state here to prevent illegal operations, e.g. applying an
  // encodeData() to the codec after encodeTrailers(). This is necessary to
  // maintain the preconditions for operations on the codec at the API level. Of
  // course, it's the codecs must be robust to wire-level violations. We
  // explore these violations via MutateAction and SwapAction at the connection
  // buffer level.
  enum class StreamState {
    PendingHeaders,
    PendingNonInformationalHeaders,
    PendingDataOrTrailers,
    Closed
  };

  FuzzStream(ConnectionManagerImpl& conn_manager, FuzzConfig& config,
             const HeaderMap& request_headers,
             test::common::http::HeaderStatus decode_header_status, bool end_stream)
      : conn_manager_(conn_manager), config_(config) {
    config_.newStream();
    request_state_ = end_stream ? StreamState::Closed : StreamState::PendingDataOrTrailers;
    response_state_ = StreamState::PendingHeaders;
    decoder_filter_ = config.decoder_filter_;
    encoder_filter_ = config.encoder_filter_;
    EXPECT_CALL(*config_.codec_, dispatch(_))
        .WillOnce(InvokeWithoutArgs([this, &request_headers, end_stream] {
          decoder_ = &conn_manager_.newStream(encoder_);
          auto headers = std::make_unique<TestRequestHeaderMapImpl>(request_headers);
          if (headers->Method() == nullptr) {
            headers->setReferenceKey(Headers::get().Method, "GET");
          }
          if (headers->Host() != nullptr &&
              !HeaderUtility::authorityIsValid(headers->getHostValue())) {
            // Sanitize host header so we don't fail at ASSERTs that verify header sanity checks
            // which should have been performed by the codec.
            headers->setHost(Fuzz::replaceInvalidHostCharacters(headers->getHostValue()));
          }
          // If sendLocalReply is called:
          ON_CALL(encoder_, encodeHeaders(_, true))
              .WillByDefault(Invoke([this](const ResponseHeaderMap&, bool end_stream) -> void {
                response_state_ =
                    end_stream ? StreamState::Closed : StreamState::PendingDataOrTrailers;
              }));
          decoder_->decodeHeaders(std::move(headers), end_stream);
          return Http::okStatus();
        }));
    ON_CALL(*decoder_filter_, decodeHeaders(_, _))
        .WillByDefault(
            InvokeWithoutArgs([this, decode_header_status]() -> Http::FilterHeadersStatus {
              header_status_ = fromHeaderStatus(decode_header_status);
              return *header_status_;
            }));
    fakeOnData();
    FUZZ_ASSERT(testing::Mock::VerifyAndClearExpectations(config_.codec_));
  }

  void fakeOnData() {
    Buffer::OwnedImpl fake_input;
    conn_manager_.onData(fake_input, false);
  }

  Http::FilterHeadersStatus fromHeaderStatus(test::common::http::HeaderStatus status) {
    switch (status) {
    case test::common::http::HeaderStatus::HEADER_CONTINUE:
      return Http::FilterHeadersStatus::Continue;
    case test::common::http::HeaderStatus::HEADER_STOP_ITERATION:
      return Http::FilterHeadersStatus::StopIteration;
    case test::common::http::HeaderStatus::HEADER_STOP_ALL_ITERATION_AND_BUFFER:
      return Http::FilterHeadersStatus::StopAllIterationAndBuffer;
    case test::common::http::HeaderStatus::HEADER_STOP_ALL_ITERATION_AND_WATERMARK:
      return Http::FilterHeadersStatus::StopAllIterationAndWatermark;
    default:
      return Http::FilterHeadersStatus::Continue;
    }
  }

  Http::FilterDataStatus fromDataStatus(test::common::http::DataStatus status) {
    switch (status) {
    case test::common::http::DataStatus::DATA_CONTINUE:
      return Http::FilterDataStatus::Continue;
    case test::common::http::DataStatus::DATA_STOP_ITERATION_AND_BUFFER:
      return Http::FilterDataStatus::StopIterationAndBuffer;
    case test::common::http::DataStatus::DATA_STOP_ITERATION_AND_WATERMARK:
      return Http::FilterDataStatus::StopIterationAndWatermark;
    case test::common::http::DataStatus::DATA_STOP_ITERATION_NO_BUFFER:
      return Http::FilterDataStatus::StopIterationNoBuffer;
    default:
      return Http::FilterDataStatus::Continue;
    }
  }

  Http::FilterTrailersStatus fromTrailerStatus(test::common::http::TrailerStatus status) {
    switch (status) {
    case test::common::http::TrailerStatus::TRAILER_CONTINUE:
      return Http::FilterTrailersStatus::Continue;
    case test::common::http::TrailerStatus::TRAILER_STOP_ITERATION:
      return Http::FilterTrailersStatus::StopIteration;
    default:
      return Http::FilterTrailersStatus::Continue;
    }
  }

  void decoderFilterCallbackAction(
      const test::common::http::DecoderFilterCallbackAction& decoder_filter_callback_action) {
    switch (decoder_filter_callback_action.decoder_filter_callback_action_selector_case()) {
    case test::common::http::DecoderFilterCallbackAction::kAddDecodedData: {
      if (request_state_ == StreamState::PendingDataOrTrailers) {
        Buffer::OwnedImpl buf(std::string(
            decoder_filter_callback_action.add_decoded_data().size() % (1024 * 1024), 'a'));
        decoder_filter_->callbacks_->addDecodedData(
            buf, decoder_filter_callback_action.add_decoded_data().streaming());
      }
      break;
    }
    default:
      // Maybe nothing is set?
      break;
    }
  }

  void requestAction(StreamState& state, const test::common::http::RequestAction& request_action) {
    switch (request_action.request_action_selector_case()) {
    case test::common::http::RequestAction::kData: {
      if (state == StreamState::PendingDataOrTrailers) {
        const auto& data_action = request_action.data();
        ON_CALL(*decoder_filter_, decodeData(_, _))
            .WillByDefault(InvokeWithoutArgs([this, &data_action]() -> Http::FilterDataStatus {
              if (data_action.has_decoder_filter_callback_action()) {
                decoderFilterCallbackAction(data_action.decoder_filter_callback_action());
              }
              data_status_ = fromDataStatus(data_action.status());
              return *data_status_;
            }));
        EXPECT_CALL(*config_.codec_, dispatch(_)).WillOnce(InvokeWithoutArgs([this, &data_action] {
          Buffer::OwnedImpl buf(std::string(data_action.size() % (1024 * 1024), 'a'));
          decoder_->decodeData(buf, data_action.end_stream());
          return Http::okStatus();
        }));
        fakeOnData();
        FUZZ_ASSERT(testing::Mock::VerifyAndClearExpectations(config_.codec_));
        state = data_action.end_stream() ? StreamState::Closed : StreamState::PendingDataOrTrailers;
        decoding_done_ = false;
      }
      break;
    }
    case test::common::http::RequestAction::kTrailers: {
      if (state == StreamState::PendingDataOrTrailers) {
        const auto& trailers_action = request_action.trailers();
        ON_CALL(*decoder_filter_, decodeTrailers(_))
            .WillByDefault(
                InvokeWithoutArgs([this, &trailers_action]() -> Http::FilterTrailersStatus {
                  if (trailers_action.has_decoder_filter_callback_action()) {
                    decoderFilterCallbackAction(trailers_action.decoder_filter_callback_action());
                  }
                  trailers_status_ = fromTrailerStatus(trailers_action.status());
                  return *trailers_status_;
                }));
        EXPECT_CALL(*config_.codec_, dispatch(_))
            .WillOnce(InvokeWithoutArgs([this, &trailers_action] {
              decoder_->decodeTrailers(std::make_unique<TestRequestTrailerMapImpl>(
                  Fuzz::fromHeaders<TestRequestTrailerMapImpl>(trailers_action.headers())));
              return Http::okStatus();
            }));
        fakeOnData();
        FUZZ_ASSERT(testing::Mock::VerifyAndClearExpectations(config_.codec_));
        state = StreamState::Closed;
        decoding_done_ = false;
      }
      break;
    }
    case test::common::http::RequestAction::kContinueDecoding: {
      if (!decoding_done_ &&
          (header_status_ == FilterHeadersStatus::StopAllIterationAndBuffer ||
           header_status_ == FilterHeadersStatus::StopAllIterationAndWatermark ||
           header_status_ == FilterHeadersStatus::StopIteration) &&
          (!data_status_.has_value() || data_status_ == FilterDataStatus::StopIterationAndBuffer ||
           data_status_ == FilterDataStatus::StopIterationAndWatermark ||
           data_status_ == FilterDataStatus::StopIterationNoBuffer) &&
          (!trailers_status_.has_value() ||
           trailers_status_ == FilterTrailersStatus::StopIteration)) {
        decoder_filter_->callbacks_->continueDecoding();
        decoding_done_ = true;
      }
      break;
    }
    case test::common::http::RequestAction::kThrowDecoderException:
    // Dispatch no longer throws, execute subsequent kReturnDecoderError case.
    case test::common::http::RequestAction::kReturnDecoderError: {
      if (state == StreamState::PendingDataOrTrailers) {
        EXPECT_CALL(*config_.codec_, dispatch(_))
            .WillOnce(testing::Return(codecProtocolError("blah")));
        fakeOnData();
        FUZZ_ASSERT(testing::Mock::VerifyAndClearExpectations(config_.codec_));
        state = StreamState::Closed;
        decoding_done_ = true;
      }
      break;
    }
    default:
      // Maybe nothing is set or not a request action?
      break;
    }
  }

  void responseAction(StreamState& state,
                      const test::common::http::ResponseAction& response_action) {
    const bool end_stream = response_action.end_stream();
    switch (response_action.response_action_selector_case()) {
    case test::common::http::ResponseAction::kContinueHeaders: {
      if (state == StreamState::PendingHeaders) {
        auto headers = std::make_unique<TestResponseHeaderMapImpl>(
            Fuzz::fromHeaders<TestResponseHeaderMapImpl>(response_action.continue_headers()));
        headers->setReferenceKey(Headers::get().Status, "100");
        decoder_filter_->callbacks_->encode1xxHeaders(std::move(headers));
        // We don't allow multiple 100-continue headers in HCM, UpstreamRequest is responsible
        // for coalescing.
        state = StreamState::PendingNonInformationalHeaders;
      }
      break;
    }
    case test::common::http::ResponseAction::kHeaders: {
      if (state == StreamState::PendingHeaders ||
          state == StreamState::PendingNonInformationalHeaders) {
        auto headers = std::make_unique<TestResponseHeaderMapImpl>(
            Fuzz::fromHeaders<TestResponseHeaderMapImpl>(response_action.headers()));
        // The client codec will ensure we always have a valid :status.
        // Similarly, local replies should always contain this.
        const auto status = Utility::getResponseStatusOrNullopt(*headers);
        // The only 1xx header that may be provided to encodeHeaders() is a 101 upgrade,
        // guaranteed by the codec parsers. See include/envoy/http/filter.h.
        if (!status.has_value() || (CodeUtility::is1xx(status.value()) &&
                                    status.value() != enumToInt(Http::Code::SwitchingProtocols))) {
          headers->setReferenceKey(Headers::get().Status, "200");
        }
        decoder_filter_->callbacks_->encodeHeaders(std::move(headers), end_stream, "details");
        state = end_stream ? StreamState::Closed : StreamState::PendingDataOrTrailers;
      }
      break;
    }
    case test::common::http::ResponseAction::kData: {
      if (state == StreamState::PendingDataOrTrailers) {
        Buffer::OwnedImpl buf(std::string(response_action.data() % (1024 * 1024), 'a'));
        decoder_filter_->callbacks_->encodeData(buf, end_stream);
        state = end_stream ? StreamState::Closed : StreamState::PendingDataOrTrailers;
      }
      break;
    }
    case test::common::http::ResponseAction::kTrailers: {
      if (state == StreamState::PendingDataOrTrailers) {
        decoder_filter_->callbacks_->encodeTrailers(std::make_unique<TestResponseTrailerMapImpl>(
            Fuzz::fromHeaders<TestResponseTrailerMapImpl>(response_action.trailers())));
        state = StreamState::Closed;
      }
      break;
    }
    default:
      // Maybe nothing is set?
      break;
    }
  }

  void streamAction(const test::common::http::StreamAction& stream_action) {
    switch (stream_action.stream_action_selector_case()) {
    case test::common::http::StreamAction::kRequest: {
      requestAction(request_state_, stream_action.request());
      break;
    }
    case test::common::http::StreamAction::kResponse: {
      responseAction(response_state_, stream_action.response());
      break;
    }
    default:
      // Maybe nothing is set?
      break;
    }
  }

  ConnectionManagerImpl& conn_manager_;
  FuzzConfig& config_;
  RequestDecoder* decoder_{};
  NiceMock<MockResponseEncoder> encoder_;
  MockStreamDecoderFilter* decoder_filter_{};
  MockStreamEncoderFilter* encoder_filter_{};
  StreamState request_state_;
  StreamState response_state_;
  absl::optional<Http::FilterHeadersStatus> header_status_;
  absl::optional<Http::FilterDataStatus> data_status_;
  absl::optional<Http::FilterTrailersStatus> trailers_status_;
  bool decoding_done_{};
};

using FuzzStreamPtr = std::unique_ptr<FuzzStream>;

DEFINE_PROTO_FUZZER(const test::common::http::ConnManagerImplTestCase& input) {
  try {
    TestUtility::validate(input);
  } catch (const ProtoValidationException& e) {
    ENVOY_LOG_MISC(debug, "ProtoValidationException: {}", e.what());
    return;
  } catch (const Envoy::ProtobufMessage::DeprecatedProtoFieldException& e) {
    ENVOY_LOG_MISC(debug, "DeprecatedProtoFieldException: {}", e.what());
    return;
  }

  FuzzConfig config(input.forward_client_cert());
  NiceMock<Network::MockDrainDecision> drain_close;
  NiceMock<Random::MockRandomGenerator> random;
  Stats::SymbolTableImpl symbol_table;
  Http::ContextImpl http_context(symbol_table);
  NiceMock<Runtime::MockLoader> runtime;
  NiceMock<LocalInfo::MockLocalInfo> local_info;
  NiceMock<Upstream::MockClusterManager> cluster_manager;
  NiceMock<Network::MockReadFilterCallbacks> filter_callbacks;
  NiceMock<Server::MockOverloadManager> overload_manager;
  auto ssl_connection = std::make_shared<Ssl::MockConnectionInfo>();
  bool connection_alive = true;

  ON_CALL(filter_callbacks.connection_, ssl()).WillByDefault(Return(ssl_connection));
  ON_CALL(Const(filter_callbacks.connection_), ssl()).WillByDefault(Return(ssl_connection));
  ON_CALL(filter_callbacks.connection_, close(_))
      .WillByDefault(InvokeWithoutArgs([&connection_alive] { connection_alive = false; }));
  filter_callbacks.connection_.stream_info_.downstream_connection_info_provider_->setLocalAddress(
      std::make_shared<Network::Address::Ipv4Instance>("127.0.0.1"));
  filter_callbacks.connection_.stream_info_.downstream_connection_info_provider_->setRemoteAddress(
      std::make_shared<Network::Address::Ipv4Instance>("0.0.0.0"));

  ConnectionManagerImpl conn_manager(config, drain_close, random, http_context, runtime, local_info,
                                     cluster_manager, overload_manager, config.time_system_);
  conn_manager.initializeReadFilterCallbacks(filter_callbacks);

  std::vector<FuzzStreamPtr> streams;

  for (const auto& action : input.actions()) {
    ENVOY_LOG_MISC(trace, "action {} with {} streams", action.DebugString(), streams.size());
    if (!connection_alive) {
      ENVOY_LOG_MISC(trace, "skipping due to dead connection");
      break;
    }

    switch (action.action_selector_case()) {
    case test::common::http::Action::kNewStream: {
      streams.emplace_back(new FuzzStream(
          conn_manager, config,
          Fuzz::fromHeaders<TestRequestHeaderMapImpl>(action.new_stream().request_headers(),
                                                      /* ignore_headers =*/{}, {":authority"}),
          action.new_stream().status(), action.new_stream().end_stream()));
      break;
    }
    case test::common::http::Action::kStreamAction: {
      const auto& stream_action = action.stream_action();
      if (streams.empty()) {
        break;
      }
      (*std::next(streams.begin(), stream_action.stream_id() % streams.size()))
          ->streamAction(stream_action);
      break;
    }
    default:
      // Maybe nothing is set?
      break;
    }
  }

  filter_callbacks.connection_.raiseEvent(Network::ConnectionEvent::LocalClose);
  filter_callbacks.connection_.dispatcher_.clearDeferredDeleteList();
}

} // namespace Http
} // namespace Envoy


text:
require 'spec_helper'

describe Groups::AvatarsController do
  let(:user)  { create(:user) }
  let(:group) { create(:group, avatar: fixture_file_upload("spec/fixtures/dk.png", "image/png")) }

  before do
    group.add_owner(user)
    sign_in(user)
  end

  it 'removes avatar from DB calling destroy' do
    delete :destroy, group_id: group.path
    @group = assigns(:group)
    expect(@group.avatar.present?).to be_falsey
    expect(@group).to be_valid
  end
end