<commit_before>Editor.Sanitize = function(editable) {
  this.editable = $(editable);
};

Editor.Sanitize.prototype = {
  run: function() {
    this.sanitizeDiv();
    this.sanitizeTag();
    this.sanitizeAttr();
    this.sanitizeBr();
    this.sanitizeBlockElement();
    this.sanitizeCode();
    this.sanitizeList();
  },

  tagWhiteList: ['p', 'br', 'img', 'a', 'b', 'i', 'strike', 'u', 'h1', 'h2', 'h3', 'h4', 'pre', 'code', 'ol', 'ul', 'li', 'blockquote'],

  attrWhiteList: {
    a: ['href', 'title'],
    img: ['src', 'title', 'alt']
  },

  sanitizeDiv: function() {
    // replace div to p
    this.editable.find('div').each(function() {
      $(this).replaceWith($('
').append($(this).contents()));
    });
  },

  sanitizeTag: function() {
    // stript not allow tags
    this.editable.find(':not(' + this.tagWhiteList.join() + ')').each(function() {
      $(this).replaceWith($(this).contents());
    });
  },

  sanitizeAttr: function() {
    var _this = this;
    // remove all attribute not in attrWhiteList
    var tags = $.map(this.attrWhiteList, function(attrs, tag) { return tag; });
    this.editable.find(':not(' + tags.join() + ')').each(function() {
      var $element = $(this);
      var attributes = $.map(this.attributes, function(item) {
        return item.name;
      });
      $.each(attributes, function(i, name) {
        $element.removeAttr(name);
      });
    });

    // remove attributes not in white list for attrWhiteList
    $.each(this.attrWhiteList, function(tag, attrList) {
      _this.editable.find(tag).each(function() {
        var $element = $(this);
        var attributes = $.map(this.attributes, function(item) {
          return item.name;
        });
        $.each(attributes, function(i, name) {
          if ($.inArray(name, attrList) == -1) {
            $element.removeAttr(name);
          }
        });
      });
    });
  },

  sanitizeBr: function() {
    this.editable.find('> br').each(function() {
      $(this).wrap('
');
    });
  },

  sanitizeBlockElement: function () {
    var _this = this;
    // flatten nested block element
    this.editable.find(this.blockElementSelector).each(function() {
      _this.flattenBlock(this);
    });
    // blockquote as a document
    this.editable.find('> blockquote').find(this.blockElementSelector).each(function() {
      _this.flattenBlock(this);
    });
  },

  blockElementSelector: '> p, > h1, > h2, > h3, > h4',

  flattenBlock: function(element) {
    var _this = this;
    var hasTextNode = $(element).contents().filter(function() { return this.nodeType !== 1; }).length;
    var hasInline = $(element).find('> :not(p, h1, h2, h3, h4, ul, ol, li)').length;
    if (hasTextNode || hasInline) {
      // stript block
      this.flattenBlockStript(element);
    } else {
      // split block

      // stript children
      $(element).children().each(function() {
        _this.flattenBlockStript.call(_this, this);
      });

      $(element).replaceWith($(element).contents());
    }
  },

  flattenBlockStript: function(element) {
    if ($(element).is(':not(ul)')) {
      $(element).find(':not(code, a, img, b, strike, i, br)').each(function() {
        $(this).replaceWith($(this).contents());
      });
    }
  },

  sanitizeCode: function() {
    var _this = this;
    this.editable.find('pre').each(function() {
      if ($(this).find('> code').length === 0) {
        $(this).append($('').append($(this).contents()));
      }
    });
    this.editable.find('code').each(function() {
      _this.striptCode(this);
    });
  },

  striptCode: function(code) {
    $(code).find('p, h1, h2, h3, h4, blockquote, pre').each(function() {
      $(this).replaceWith($(this).text() + "\n");
    });
    $(code).children().each(function() {
      $(this).replaceWith($(this).text());
    });
  },

  sanitizeList: function() {
    var _this = this;
    this.editable.find('li').each(function() {
      var $li = $(this);
      // stript p
      $li.find(':not(code, a, img, b, strike, i, br)').each(function() {
        if ($(this).next().length) {
          $(this).append('
');
        }
        $(this).replaceWith($(this).contents());
      });
    });
  }
};
<commit_msg>remove unnedd call<commit_after>Editor.Sanitize = function(editable) {
  this.editable = $(editable);
};

Editor.Sanitize.prototype = {
  run: function() {
    this.sanitizeDiv();
    this.sanitizeTag();
    this.sanitizeAttr();
    this.sanitizeBr();
    this.sanitizeBlockElement();
    this.sanitizeCode();
    this.sanitizeList();
  },

  tagWhiteList: ['p', 'br', 'img', 'a', 'b', 'i', 'strike', 'u', 'h1', 'h2', 'h3', 'h4', 'pre', 'code', 'ol', 'ul', 'li', 'blockquote'],

  attrWhiteList: {
    a: ['href', 'title'],
    img: ['src', 'title', 'alt']
  },

  sanitizeDiv: function() {
    // replace div to p
    this.editable.find('div').each(function() {
      $(this).replaceWith($('
').append($(this).contents()));
    });
  },

  sanitizeTag: function() {
    // stript not allow tags
    this.editable.find(':not(' + this.tagWhiteList.join() + ')').each(function() {
      $(this).replaceWith($(this).contents());
    });
  },

  sanitizeAttr: function() {
    var _this = this;
    // remove all attribute not in attrWhiteList
    var tags = $.map(this.attrWhiteList, function(attrs, tag) { return tag; });
    this.editable.find(':not(' + tags.join() + ')').each(function() {
      var $element = $(this);
      var attributes = $.map(this.attributes, function(item) {
        return item.name;
      });
      $.each(attributes, function(i, name) {
        $element.removeAttr(name);
      });
    });

    // remove attributes not in white list for attrWhiteList
    $.each(this.attrWhiteList, function(tag, attrList) {
      _this.editable.find(tag).each(function() {
        var $element = $(this);
        var attributes = $.map(this.attributes, function(item) {
          return item.name;
        });
        $.each(attributes, function(i, name) {
          if ($.inArray(name, attrList) == -1) {
            $element.removeAttr(name);
          }
        });
      });
    });
  },

  sanitizeBr: function() {
    this.editable.find('> br').each(function() {
      $(this).wrap('
');
    });
  },

  sanitizeBlockElement: function () {
    var _this = this;
    // flatten nested block element
    this.editable.find(this.blockElementSelector).each(function() {
      _this.flattenBlock(this);
    });
    // blockquote as a document
    this.editable.find('> blockquote').find(this.blockElementSelector).each(function() {
      _this.flattenBlock(this);
    });
  },

  blockElementSelector: '> p, > h1, > h2, > h3, > h4',

  flattenBlock: function(element) {
    var _this = this;
    var hasTextNode = $(element).contents().filter(function() { return this.nodeType !== 1; }).length;
    var hasInline = $(element).find('> :not(p, h1, h2, h3, h4, ul, ol, li)').length;
    if (hasTextNode || hasInline) {
      // stript block
      this.flattenBlockStript(element);
    } else {
      // split block

      // stript children
      $(element).children().each(function() {
        _this.flattenBlockStript(this);
      });

      $(element).replaceWith($(element).contents());
    }
  },

  flattenBlockStript: function(element) {
    if ($(element).is(':not(ul)')) {
      $(element).find(':not(code, a, img, b, strike, i, br)').each(function() {
        $(this).replaceWith($(this).contents());
      });
    }
  },

  sanitizeCode: function() {
    var _this = this;
    this.editable.find('pre').each(function() {
      if ($(this).find('> code').length === 0) {
        $(this).append($('').append($(this).contents()));
      }
    });
    this.editable.find('code').each(function() {
      _this.striptCode(this);
    });
  },

  striptCode: function(code) {
    $(code).find('p, h1, h2, h3, h4, blockquote, pre').each(function() {
      $(this).replaceWith($(this).text() + "\n");
    });
    $(code).children().each(function() {
      $(this).replaceWith($(this).text());
    });
  },

  sanitizeList: function() {
    var _this = this;
    this.editable.find('li').each(function() {
      var $li = $(this);
      // stript p
      $li.find(':not(code, a, img, b, strike, i, br)').each(function() {
        if ($(this).next().length) {
          $(this).append('
');
        }
        $(this).replaceWith($(this).contents());
      });
    });
  }
};
<|endoftext|>


<commit_before>/*! Picturefill - Responsive Images that work today.
*  Author: Scott Jehl, Filament Group, 2012 ( new proposal implemented by Shawn Jansepar )
*  License: MIT/GPLv2
*  Spec: http://picture.responsiveimages.org/
*/
(function( w, doc ) {
	// Enable strict mode
	"use strict";

	// If picture is supported, well, that's awesome. Let's get outta here...
	if( w.HTMLPictureElement ){
		return;
	}

	// HTML shim|v it for old IE (IE9 will still need the HTML video tag workaround)
	doc.createElement( "picture" );
	doc.createElement( "source" );

	// local object for method references and testing exposure
	var pf = {};

	// namespace
	pf.ns = "picturefill";

	// just a string trim workaround
	pf.trim = function( str ){
		return str.trim ? str.trim() : str.replace( /^\s+|\s+$/g, "" );
	};

	// just a string endsWith workaround
	pf.endsWith = function( str, suffix ){
		return str.endsWith ? str.endsWith( suffix ) : str.indexOf( suffix, str.length - suffix.length ) !== -1;
	};

	/**
	 * Shortcut method for matchMedia ( for easy overriding in tests )
	 */
	pf.matchesMedia = function( media ) {
		return w.matchMedia && w.matchMedia( media ).matches;
	};

	/**
	 * Shortcut method for `devicePixelRatio` ( for easy overriding in tests )
	 */
	pf.getDpr = function() {
		return ( w.devicePixelRatio || 1 );
	};

	/**
	 * Get width in css pixel value from a "length" value
	 * http://dev.w3.org/csswg/css-values-3/#length-value
	 */
	var lengthEl;

	pf.getCachedLengthEl = function() {
		lengthEl = lengthEl || doc.createElement( "div" );
		if ( !doc.body ) {
			return;
		}
		doc.body.appendChild( lengthEl );
		return lengthEl;
	};

	pf.getWidthFromLength = function( length ) {
		var lengthEl = pf.getCachedLengthEl();
		lengthEl.style.cssText = "width: " + length + ";";
		// Using offsetWidth to get width from CSS
		return lengthEl.offsetWidth;
	};

	// container of supported mime types that one might need to qualify before using
	pf.types =  {};

	// test svg support
	pf.types[ "image/svg+xml" ] = doc.implementation.hasFeature('http://www.w3.org/TR/SVG11/feature#Image', '1.1');

	// test webp support, only when the markup calls for it
	pf.types[ "image/webp" ] = function(){
		// based on Modernizr's img-webp test
		// note: asynchronous
		var img = new w.Image(),
			type = "image/webp";

		img.onerror = function(){
			pf.types[ type ] = false;
			picturefill();
		};
		img.onload = function(){
			pf.types[ type ] = img.width === 1;
			picturefill();
		};
		img.src = 'data:image/webp;base64,UklGRiQAAABXRUJQVlA4IBgAAAAwAQCdASoBAAEAAwA0JaQAA3AA/vuUAAA=';
	};

	/**
	 * Takes a source element and checks if its type attribute is present and if so, supported
	 * Note: for type tests that require a async logic,
	 * you can define them as a function that'll run only if that type needs to be tested. Just make the test function call picturefill again when it is complete.
	 * see the async webp test above for example
	 */
	pf.verifyTypeSupport = function( source ){
		var type = source.getAttribute( "type" );
		// if type attribute exists, return test result, otherwise return true
		if( type === null || type === "" ){
			return true;
		}
		else {
			// if the type test is a function, run it and return "pending" status. The function will rerun picturefill on pending elements once finished.
			if( typeof( pf.types[ type ] ) === "function" ){
				pf.types[ type ]();
				return "pending";
			}
			else {
				return pf.types[ type ];
			}
		}
	};

	/**
	 * Takes a string of sizes and returns the width in pixels as an int
	 */
	pf.findWidthFromSourceSize = function( sourceSizeListStr ) {
		// Split up source size list, ie ( max-width: 30em ) 100%, ( max-width: 50em ) 50%, 33%
		var sourceSizeList = pf.trim( sourceSizeListStr ).split( /\s*,\s*/ );
		var winningLength;
		for ( var i=0, len=sourceSizeList.length; i < len; i++ ) {
			// Match <media-query>? length, ie ( min-width: 50em ) 100%
			var sourceSize = sourceSizeList[ i ];

			// Split "( min-width: 50em ) 100%" into separate strings
			var match = /(\([^)]+\))?\s*([^\s]+)/g.exec( sourceSize );
			if ( !match ) {
					continue;
			}
			var length = match[ 2 ];
			var media;
			if ( !match[ 1 ] ) {
				// if there is no media query, choose this as our winning length
				winningLength = length;
				break;
			} else {
				media = match[ 1 ];
			}

			if ( pf.matchesMedia( media ) ) {
				// if the media query matches, choose this as our winning length
				// and end algorithm
				winningLength = length;
				break;
			}
		}

		// default to 300px if no length was selected
		if ( !winningLength ) {
			return 300;
		}

		// pass the length to a method that can properly determine length
		// in pixels based on these formats: http://dev.w3.org/csswg/css-values-3/#length-value
		var winningLengthInt = pf.getWidthFromLength( winningLength );
		return winningLengthInt;
	};

	/**
	 * Takes a srcset in the form of url/
	 * ex. "images/pic-medium.png 1x, images/pic-medium-2x.png 2x" or
	 *     "images/pic-medium.png 400w, images/pic-medium-2x.png 800w" or
	 *     "images/pic-small.png"
	 * Get an array of image candidates in the form of
	 *      {url: "/foo/bar.png", resolution: 1}
	 * where resolution is http://dev.w3.org/csswg/css-values-3/#resolution-value
	 * If sizes is specified, resolution is calculated
	 */
	pf.getCandidatesFromSourceSet = function( srcset, sizes ) {
		var candidates = pf.trim( srcset ).split( /\s*,\s*/ );
		var formattedCandidates = [];
		var widthInCssPixels;
		if ( sizes ) {
			widthInCssPixels = pf.findWidthFromSourceSize( sizes );
		}
		for ( var i = 0, len = candidates.length; i < len; i++ ) {
			var candidate = candidates[ i ];
			var candidateArr = candidate.split( /\s+/ );
			var sizeDescriptor = candidateArr[ 1 ];
			var resolution;
			if ( sizeDescriptor && ( sizeDescriptor.slice( -1 ) === "w" || sizeDescriptor.slice( -1 ) === "x" ) ) {
				sizeDescriptor = sizeDescriptor.slice( 0, -1 );
			}
			if ( sizes ) {
				// get the dpr by taking the length / width in css pixels
				resolution = parseFloat( ( parseInt( sizeDescriptor, 10 ) / widthInCssPixels ).toFixed( 2 ) );
			} else {
				// get the dpr by grabbing the value of Nx
				resolution = sizeDescriptor ? parseFloat( sizeDescriptor, 10 ) : pf.getDpr();
			}

			var formattedCandidate = {
				url: candidateArr[ 0 ],
				resolution: resolution
			};
			formattedCandidates.push( formattedCandidate );
		}
		return formattedCandidates;
	};

	/*
	 * if it's an img element and it has a srcset property,
	 * we need to remove the attribute so we can minipulate src
	 * (the property's existence infers native srcset support, and a srcset-supporting browser will prioritize srcset's value over our winning picture candidate)
	 * this moves srcset's value to memory for later use and removes the attr
	 */
	pf.dodgeSrcset = function( img ){
		if( img.srcset ){
			img[ pf.ns ].srcset = img.srcset;
			img.removeAttribute( "srcset" );
		}
	};

	/*
	 * Accept a source or img element and process its srcset and sizes attrs
	 */
	pf.processSourceSet = function( el ) {
		var srcset = el.getAttribute( "srcset" ),
			sizes = el.getAttribute( "sizes" ),
			candidates = [];

		// if it's an img element, use the cached srcset property (defined or not)
		if( el.nodeName === "IMG" ){
			srcset = el[ pf.ns ].srcset;
		}

		if( srcset ) {
			candidates = pf.getCandidatesFromSourceSet( srcset, sizes );
		}
		return candidates;
	};

	pf.applyBestCandidate = function( candidates, picImg ) {
		var sortedImgCandidates = candidates.sort( pf.ascendingSort ),
			candidate;

		for ( var l=0; l < sortedImgCandidates.length; l++ ) {
			candidate = sortedImgCandidates[ l ];
			if ( candidate.resolution >= pf.getDpr() ) {
				if ( !pf.endsWith( picImg.src, candidate.url ) ) {
					picImg.src = candidate.url;
					// currentSrc attribute and property to match http://picture.responsiveimages.org/#the-img-element
					picImg.currentSrc = candidate.url;
				}
				break;
			}
		}
	};

	pf.ascendingSort = function( a, b ) {
		return a.resolution > b.resolution;
	};

	/*
	 * In IE9, <source> elements get removed if they aren"t children of
	 * video elements. Thus, we conditionally wrap source elements
	 * using <!--[if IE 9]><video style="display: none;"><![endif]-->
	 * and must account for that here by moving those source elements
	 * back into the picture element.
	 */
	pf.removeVideoShim = function( picture ){
		var videos = picture.getElementsByTagName( "video" );
		if ( videos.length ) {
			var video = videos[ 0 ];
			var vsources = video.getElementsByTagName( "source" );
			while ( vsources.length ) {
				picture.appendChild( vsources[ 0 ] );
			}
			// Remove the video element once we're finished removing its children
			video.parentNode.removeChild( video );
		}
	};

	function picturefill( options ) {
		var pictures, options = options || {};

		pictures = options.elements || doc.getElementsByTagName( "picture" );

		// Loop through all images on the page that are `<picture>`
		for ( var i=0, plen = pictures.length; i < plen; i++ ) {
			var picture = pictures[ i ];

			// if a picture element has already been evaluated, skip it
			// unless `options.force` is set to true ( this, for example,
			// is set to true when running `picturefill` on `resize` ).
			if ( !options.reevaluate && picture.hasAttribute( "data-picture-evaluated" ) ) {
				continue;
			}
			picture.setAttribute( "data-picture-evaluated", true );
			var firstMatch;

			// IE9 video workaround
			pf.removeVideoShim( picture );

			var sources = picture.getElementsByTagName( "source" );
			var sourcesPending = false;

			// Go through each child, and if they have media queries, evaluate them
			// and add them to matches
			for ( var j=0, slen = sources.length; j < slen; j++ ) {
				var source = sources[ j ];
				var media = source.getAttribute( "media" );

				// if source does not have a srcset attribute, skip
				if ( !source.hasAttribute( "srcset" ) ) {
					continue;
				}

				// if there"s no media specified, OR w.matchMedia is supported
				if( ( !media || pf.matchesMedia( media ) ) ){
					var typeSupported = pf.verifyTypeSupport( source );
					if( typeSupported === true ){
						firstMatch = source;
						break;
					}
					else if( typeSupported === "pending" ){
						sourcesPending = true;
					}
				}
			}

			// if any sources are pending in this picture due to async type test(s), remove the evaluated attr and skip for now ( the pending test will rerun picturefill on this element when complete)
			if( sourcesPending ){
				picture.removeAttribute( "data-picture-evaluated" );
				continue;
			}

			// Find any existing img element in the picture element
			var picImg = picture.getElementsByTagName( "img" )[ 0 ],
				candidates;

			if( picImg ) {

				// expando for caching data on the img
				if( !picImg[ pf.ns ] ){
					picImg[ pf.ns ] = {};
					// cache and remove srcset if present
					pf.dodgeSrcset( picImg );
				}

				if ( firstMatch ) {
					candidates = pf.processSourceSet( firstMatch );
					pf.applyBestCandidate( candidates, picImg );
				} else {
					// No sources matched, so we’re down to processing the inner `img` as a source.
					candidates = pf.processSourceSet( picImg );

					if( picImg.srcset === undefined || picImg.hasAttribute( "sizes" ) ) {
						// Either `srcset` is completely unsupported, or we need to polyfill `sizes` functionality.
						pf.applyBestCandidate( candidates, picImg );
					} // Else, resolution-only `srcset` is supported natively.
				}
			}
		}
	}

	/**
	 * Sets up picture polyfill by polling the document and running
	 * the polyfill every 250ms until the document is ready.
	 * Also attaches picturefill on resize
	 */
	function runPicturefill() {
		picturefill();
		var intervalId = setInterval( function(){
			// When the document has finished loading, stop checking for new images
			// https://github.com/ded/domready/blob/master/ready.js#L15
			w.picturefill();
			if ( /^loaded|^i|^c/.test( doc.readyState ) ) {
				clearInterval( intervalId );
				return;
			}
		}, 250 );
		if( w.addEventListener ){
			w.addEventListener( "resize", function() {
				w.picturefill({ reevaluate: true });
			}, false );
		}
	}

	runPicturefill();

	/* expose methods for testing */
	picturefill._ = pf;

	/* expose picturefill */
	w[ pf.ns ] = picturefill;

} )( this, this.document );
<commit_msg>options already defined as formal param<commit_after>/*! Picturefill - Responsive Images that work today.
*  Author: Scott Jehl, Filament Group, 2012 ( new proposal implemented by Shawn Jansepar )
*  License: MIT/GPLv2
*  Spec: http://picture.responsiveimages.org/
*/
(function( w, doc ) {
	// Enable strict mode
	"use strict";

	// If picture is supported, well, that's awesome. Let's get outta here...
	if( w.HTMLPictureElement ){
		return;
	}

	// HTML shim|v it for old IE (IE9 will still need the HTML video tag workaround)
	doc.createElement( "picture" );
	doc.createElement( "source" );

	// local object for method references and testing exposure
	var pf = {};

	// namespace
	pf.ns = "picturefill";

	// just a string trim workaround
	pf.trim = function( str ){
		return str.trim ? str.trim() : str.replace( /^\s+|\s+$/g, "" );
	};

	// just a string endsWith workaround
	pf.endsWith = function( str, suffix ){
		return str.endsWith ? str.endsWith( suffix ) : str.indexOf( suffix, str.length - suffix.length ) !== -1;
	};

	/**
	 * Shortcut method for matchMedia ( for easy overriding in tests )
	 */
	pf.matchesMedia = function( media ) {
		return w.matchMedia && w.matchMedia( media ).matches;
	};

	/**
	 * Shortcut method for `devicePixelRatio` ( for easy overriding in tests )
	 */
	pf.getDpr = function() {
		return ( w.devicePixelRatio || 1 );
	};

	/**
	 * Get width in css pixel value from a "length" value
	 * http://dev.w3.org/csswg/css-values-3/#length-value
	 */
	var lengthEl;

	pf.getCachedLengthEl = function() {
		lengthEl = lengthEl || doc.createElement( "div" );
		if ( !doc.body ) {
			return;
		}
		doc.body.appendChild( lengthEl );
		return lengthEl;
	};

	pf.getWidthFromLength = function( length ) {
		var lengthEl = pf.getCachedLengthEl();
		lengthEl.style.cssText = "width: " + length + ";";
		// Using offsetWidth to get width from CSS
		return lengthEl.offsetWidth;
	};

	// container of supported mime types that one might need to qualify before using
	pf.types =  {};

	// test svg support
	pf.types[ "image/svg+xml" ] = doc.implementation.hasFeature('http://www.w3.org/TR/SVG11/feature#Image', '1.1');

	// test webp support, only when the markup calls for it
	pf.types[ "image/webp" ] = function(){
		// based on Modernizr's img-webp test
		// note: asynchronous
		var img = new w.Image(),
			type = "image/webp";

		img.onerror = function(){
			pf.types[ type ] = false;
			picturefill();
		};
		img.onload = function(){
			pf.types[ type ] = img.width === 1;
			picturefill();
		};
		img.src = 'data:image/webp;base64,UklGRiQAAABXRUJQVlA4IBgAAAAwAQCdASoBAAEAAwA0JaQAA3AA/vuUAAA=';
	};

	/**
	 * Takes a source element and checks if its type attribute is present and if so, supported
	 * Note: for type tests that require a async logic,
	 * you can define them as a function that'll run only if that type needs to be tested. Just make the test function call picturefill again when it is complete.
	 * see the async webp test above for example
	 */
	pf.verifyTypeSupport = function( source ){
		var type = source.getAttribute( "type" );
		// if type attribute exists, return test result, otherwise return true
		if( type === null || type === "" ){
			return true;
		}
		else {
			// if the type test is a function, run it and return "pending" status. The function will rerun picturefill on pending elements once finished.
			if( typeof( pf.types[ type ] ) === "function" ){
				pf.types[ type ]();
				return "pending";
			}
			else {
				return pf.types[ type ];
			}
		}
	};

	/**
	 * Takes a string of sizes and returns the width in pixels as an int
	 */
	pf.findWidthFromSourceSize = function( sourceSizeListStr ) {
		// Split up source size list, ie ( max-width: 30em ) 100%, ( max-width: 50em ) 50%, 33%
		var sourceSizeList = pf.trim( sourceSizeListStr ).split( /\s*,\s*/ );
		var winningLength;
		for ( var i=0, len=sourceSizeList.length; i < len; i++ ) {
			// Match <media-query>? length, ie ( min-width: 50em ) 100%
			var sourceSize = sourceSizeList[ i ];

			// Split "( min-width: 50em ) 100%" into separate strings
			var match = /(\([^)]+\))?\s*([^\s]+)/g.exec( sourceSize );
			if ( !match ) {
					continue;
			}
			var length = match[ 2 ];
			var media;
			if ( !match[ 1 ] ) {
				// if there is no media query, choose this as our winning length
				winningLength = length;
				break;
			} else {
				media = match[ 1 ];
			}

			if ( pf.matchesMedia( media ) ) {
				// if the media query matches, choose this as our winning length
				// and end algorithm
				winningLength = length;
				break;
			}
		}

		// default to 300px if no length was selected
		if ( !winningLength ) {
			return 300;
		}

		// pass the length to a method that can properly determine length
		// in pixels based on these formats: http://dev.w3.org/csswg/css-values-3/#length-value
		var winningLengthInt = pf.getWidthFromLength( winningLength );
		return winningLengthInt;
	};

	/**
	 * Takes a srcset in the form of url/
	 * ex. "images/pic-medium.png 1x, images/pic-medium-2x.png 2x" or
	 *     "images/pic-medium.png 400w, images/pic-medium-2x.png 800w" or
	 *     "images/pic-small.png"
	 * Get an array of image candidates in the form of
	 *      {url: "/foo/bar.png", resolution: 1}
	 * where resolution is http://dev.w3.org/csswg/css-values-3/#resolution-value
	 * If sizes is specified, resolution is calculated
	 */
	pf.getCandidatesFromSourceSet = function( srcset, sizes ) {
		var candidates = pf.trim( srcset ).split( /\s*,\s*/ );
		var formattedCandidates = [];
		var widthInCssPixels;
		if ( sizes ) {
			widthInCssPixels = pf.findWidthFromSourceSize( sizes );
		}
		for ( var i = 0, len = candidates.length; i < len; i++ ) {
			var candidate = candidates[ i ];
			var candidateArr = candidate.split( /\s+/ );
			var sizeDescriptor = candidateArr[ 1 ];
			var resolution;
			if ( sizeDescriptor && ( sizeDescriptor.slice( -1 ) === "w" || sizeDescriptor.slice( -1 ) === "x" ) ) {
				sizeDescriptor = sizeDescriptor.slice( 0, -1 );
			}
			if ( sizes ) {
				// get the dpr by taking the length / width in css pixels
				resolution = parseFloat( ( parseInt( sizeDescriptor, 10 ) / widthInCssPixels ).toFixed( 2 ) );
			} else {
				// get the dpr by grabbing the value of Nx
				resolution = sizeDescriptor ? parseFloat( sizeDescriptor, 10 ) : pf.getDpr();
			}

			var formattedCandidate = {
				url: candidateArr[ 0 ],
				resolution: resolution
			};
			formattedCandidates.push( formattedCandidate );
		}
		return formattedCandidates;
	};

	/*
	 * if it's an img element and it has a srcset property,
	 * we need to remove the attribute so we can minipulate src
	 * (the property's existence infers native srcset support, and a srcset-supporting browser will prioritize srcset's value over our winning picture candidate)
	 * this moves srcset's value to memory for later use and removes the attr
	 */
	pf.dodgeSrcset = function( img ){
		if( img.srcset ){
			img[ pf.ns ].srcset = img.srcset;
			img.removeAttribute( "srcset" );
		}
	};

	/*
	 * Accept a source or img element and process its srcset and sizes attrs
	 */
	pf.processSourceSet = function( el ) {
		var srcset = el.getAttribute( "srcset" ),
			sizes = el.getAttribute( "sizes" ),
			candidates = [];

		// if it's an img element, use the cached srcset property (defined or not)
		if( el.nodeName === "IMG" ){
			srcset = el[ pf.ns ].srcset;
		}

		if( srcset ) {
			candidates = pf.getCandidatesFromSourceSet( srcset, sizes );
		}
		return candidates;
	};

	pf.applyBestCandidate = function( candidates, picImg ) {
		var sortedImgCandidates = candidates.sort( pf.ascendingSort ),
			candidate;

		for ( var l=0; l < sortedImgCandidates.length; l++ ) {
			candidate = sortedImgCandidates[ l ];
			if ( candidate.resolution >= pf.getDpr() ) {
				if ( !pf.endsWith( picImg.src, candidate.url ) ) {
					picImg.src = candidate.url;
					// currentSrc attribute and property to match http://picture.responsiveimages.org/#the-img-element
					picImg.currentSrc = candidate.url;
				}
				break;
			}
		}
	};

	pf.ascendingSort = function( a, b ) {
		return a.resolution > b.resolution;
	};

	/*
	 * In IE9, <source> elements get removed if they aren"t children of
	 * video elements. Thus, we conditionally wrap source elements
	 * using <!--[if IE 9]><video style="display: none;"><![endif]-->
	 * and must account for that here by moving those source elements
	 * back into the picture element.
	 */
	pf.removeVideoShim = function( picture ){
		var videos = picture.getElementsByTagName( "video" );
		if ( videos.length ) {
			var video = videos[ 0 ];
			var vsources = video.getElementsByTagName( "source" );
			while ( vsources.length ) {
				picture.appendChild( vsources[ 0 ] );
			}
			// Remove the video element once we're finished removing its children
			video.parentNode.removeChild( video );
		}
	};

	function picturefill( options ) {
		var pictures;

		options = options || {};
		pictures = options.elements || doc.getElementsByTagName( "picture" );

		// Loop through all images on the page that are `<picture>`
		for ( var i=0, plen = pictures.length; i < plen; i++ ) {
			var picture = pictures[ i ];

			// if a picture element has already been evaluated, skip it
			// unless `options.force` is set to true ( this, for example,
			// is set to true when running `picturefill` on `resize` ).
			if ( !options.reevaluate && picture.hasAttribute( "data-picture-evaluated" ) ) {
				continue;
			}
			picture.setAttribute( "data-picture-evaluated", true );
			var firstMatch;

			// IE9 video workaround
			pf.removeVideoShim( picture );

			var sources = picture.getElementsByTagName( "source" );
			var sourcesPending = false;

			// Go through each child, and if they have media queries, evaluate them
			// and add them to matches
			for ( var j=0, slen = sources.length; j < slen; j++ ) {
				var source = sources[ j ];
				var media = source.getAttribute( "media" );

				// if source does not have a srcset attribute, skip
				if ( !source.hasAttribute( "srcset" ) ) {
					continue;
				}

				// if there"s no media specified, OR w.matchMedia is supported
				if( ( !media || pf.matchesMedia( media ) ) ){
					var typeSupported = pf.verifyTypeSupport( source );
					if( typeSupported === true ){
						firstMatch = source;
						break;
					}
					else if( typeSupported === "pending" ){
						sourcesPending = true;
					}
				}
			}

			// if any sources are pending in this picture due to async type test(s), remove the evaluated attr and skip for now ( the pending test will rerun picturefill on this element when complete)
			if( sourcesPending ){
				picture.removeAttribute( "data-picture-evaluated" );
				continue;
			}

			// Find any existing img element in the picture element
			var picImg = picture.getElementsByTagName( "img" )[ 0 ],
				candidates;

			if( picImg ) {

				// expando for caching data on the img
				if( !picImg[ pf.ns ] ){
					picImg[ pf.ns ] = {};
					// cache and remove srcset if present
					pf.dodgeSrcset( picImg );
				}

				if ( firstMatch ) {
					candidates = pf.processSourceSet( firstMatch );
					pf.applyBestCandidate( candidates, picImg );
				} else {
					// No sources matched, so we’re down to processing the inner `img` as a source.
					candidates = pf.processSourceSet( picImg );

					if( picImg.srcset === undefined || picImg.hasAttribute( "sizes" ) ) {
						// Either `srcset` is completely unsupported, or we need to polyfill `sizes` functionality.
						pf.applyBestCandidate( candidates, picImg );
					} // Else, resolution-only `srcset` is supported natively.
				}
			}
		}
	}

	/**
	 * Sets up picture polyfill by polling the document and running
	 * the polyfill every 250ms until the document is ready.
	 * Also attaches picturefill on resize
	 */
	function runPicturefill() {
		picturefill();
		var intervalId = setInterval( function(){
			// When the document has finished loading, stop checking for new images
			// https://github.com/ded/domready/blob/master/ready.js#L15
			w.picturefill();
			if ( /^loaded|^i|^c/.test( doc.readyState ) ) {
				clearInterval( intervalId );
				return;
			}
		}, 250 );
		if( w.addEventListener ){
			w.addEventListener( "resize", function() {
				w.picturefill({ reevaluate: true });
			}, false );
		}
	}

	runPicturefill();

	/* expose methods for testing */
	picturefill._ = pf;

	/* expose picturefill */
	w[ pf.ns ] = picturefill;

} )( this, this.document );
<|endoftext|>


<commit_before>
// Express - MockRequest - Copyright TJ Holowaychuk <tj@vision-media.ca> (MIT Licensed)

function request(path, options, fn) {

}

/**
 * Return a mock routing function for _method_.
 *
 * @param  {string} method
 * @return {function}
 * @api private
 */

function route(method) {
  return function(path, options, fn){
    if (options instanceof Function)
      fn = options, options = {}
    if (fn instanceof Function)
      Express.routes.push(new Route(method, path, fn, options))
    else
      request(path, options, fn)
  }
}

// --- Mock routing API

get = view = route('get')
post = create = route('post')
del = destroy = route('delete')
put = update = route('put')<commit_msg>More work on mock routing<commit_after>
// Express - MockRequest - Copyright TJ Holowaychuk <tj@vision-media.ca> (MIT Licensed)

function mockRequest(method, path, options) {
  return {
    method: method,
    uri: {
      full: path,
      path: path,
      queryString: '',
      fragment: '',
      params: {},
    },
    httpVersion: '1.1',
    connection: {
      remoteAddress: '127.0.0.1'
    },
    headers: {
      'host': 'localhost:3000',
      'user-agent': 'Mozilla/5.0 (Macintosh; U; Intel Mac OS X 10_5_8; en-us) AppleWebKit/530.19.2 (KHTML, like Gecko) Version/4.0.2 Safari/530.19',
      'accept': 'application/xml,application/xhtml+xml,text/html;q=0.9,text/plain;q=0.8,image/png,*/*;q=0.5',
      'accept-language': 'en-us',
      'connection': 'keep-alive'
    }
  }
}

function request(method, path, options, fn) {
  Express.server.route(mockRequest(method, path, options))
}

/**
 * Return a mock routing function for _method_.
 *
 * @param  {string} method
 * @return {function}
 * @api private
 */

function route(method) {
  return function(path, options, fn){
    if (options instanceof Function)
      fn = options, options = {}
    if (fn instanceof Function)
      Express.routes.push(new Route(method, path, fn, options))
    else
      request(method, path, options, fn)
  }
}

// --- Mock routing API

get = view = route('get')
post = create = route('post')
del = destroy = route('delete')
put = update = route('put')<|endoftext|>


<commit_before>
var timer = 1; //seconds
var data;
function render_rickshaw(index, data) {

	chart = "chart_"+index
	yaxis = "y_axis_"+index

	graph[index]= new Rickshaw.Graph({
                element: document.getElementById(chart),
                width: 700,
                height: 200,
                renderer: 'line',
                series: [{ color: "#cb513a", data: data }]
        });

        new Rickshaw.Graph.Axis.Y( {
                graph: graph[index],
                orientation: 'left',
                tickFormat: Rickshaw.Fixtures.Number.formatKMBT,
                element: document.getElementById(yaxis)

        } );

        new Rickshaw.Graph.Axis.Time({
                graph: graph[index],
                timeFixture: new Rickshaw.Fixtures.Time.Local()
        });

        ///////
        graph[index].render();

        new Rickshaw.Graph.HoverDetail({
                graph: graph[index],
                formatter: function (series, x, y) {
                        return content = ""+d3.time.format("%Y-%m-%d %H:%M:%S")(new Date(x*1000)) +"
"+y
                }
	});

	unrenderWaiting();
	renderSlider();

}

function render_rickshaw(index) {
	graph[index] = new Rickshaw.Graph({
		element: document.getElementById("chart_"+index),
		width: 700,
		height: 200,
		renderer: 'line',
		series: new Rickshaw.Series.FixedDuration([{name: gon.metric[index]}], undefined, {
			timeInterval: timer*1000,
			maxDataPoints: 200,
			timeBase: new Date().getTime() / 1000
		})
	})

        chart = "chart_"+index
        yaxis = "y_axis_"+index

	 new Rickshaw.Graph.Axis.Y( {
                graph: graph[index],
                orientation: 'left',
                tickFormat: Rickshaw.Fixtures.Number.formatKMBT,
                element: document.getElementById(yaxis)

        } );

        new Rickshaw.Graph.Axis.Time({
                graph: graph[index],
                timeFixture: new Rickshaw.Fixtures.Time.Local()
        });

	graph[index].render()

        new Rickshaw.Graph.HoverDetail({
                graph: graph[index],
                formatter: function (series, x, y) {
                        return content = ""+d3.time.format("%Y-%m-%d %H:%M:%S")(new Date(x*1000)) +"
"+y
                }
        });

	update = gon.feed[index]+"?start="+gon.start+"&stop="+gon.stop+"&step="+gon.step

        console.log(update)
	$.getJSON(update, function(d) {
                $.each(d, function(i, point) {
                        x = {data: point.y}
                        graph[index].series.addData(x) //{name: gon.metric[index], data: point.y})
                })
                graph[index].render()
        })

	unrenderWaiting();
	renderSlider();

}
function updateRickshaw(){
	id = setInterval(function() {
		now = parseInt(Date.now()/1000)

		$.each(gon.feed, function(i, feed) {
			update = feed+"?start="+(now-(gon.step * timer))+"&stop="+now+"&step="+gon.step

			$.getJSON(update, function(d){
				new_data = {data: d[d.length-1].y}
				graph[i].series.addData(new_data);
				graph[i].render()
			})
		})
	}
	, timer*1000);
return id
}

<commit_msg>Multiple rickshaw graph javascript edits for live functionality<commit_after>var graph=[]

var data;
function render_rickshaw(index, data) {
	chart = "chart_"+index
	yaxis = "y_axis_"+index

	graph[index]= new Rickshaw.Graph({
                element: document.getElementById(chart),
                width: 700,
                height: 200,
                renderer: 'line',
                series: [{ color: "#cb513a", data: data }]
        });

        new Rickshaw.Graph.Axis.Y( {
                graph: graph[index],
                orientation: 'left',
                tickFormat: Rickshaw.Fixtures.Number.formatKMBT,
                element: document.getElementById(yaxis)

        } );

        new Rickshaw.Graph.Axis.Time({
                graph: graph[index],
                timeFixture: new Rickshaw.Fixtures.Time.Local()
        });

        ///////
        graph[index].render();

        new Rickshaw.Graph.HoverDetail({
                graph: graph[index],
                formatter: function (series, x, y) {
                        return content = ""+d3.time.format("%Y-%m-%d %H:%M:%S")(new Date(x*1000)) +"
"+y
                }
	});

	unrenderWaiting();
	renderSlider();

}

function render_rickshaw(index) {
	graph[index] = new Rickshaw.Graph({
		element: document.getElementById("chart_"+index),
		width: 700,
		height: 200,
		renderer: 'line',
		series: new Rickshaw.Series.FixedDuration([{name: gon.metric[index]}], undefined, {
			timeInterval: gon.step*1000,
			maxDataPoints: 200,
			timeBase: parseInt(new Date().getTime() / 1000)
		})
	})

        chart = "chart_"+index
        yaxis = "y_axis_"+index

	 new Rickshaw.Graph.Axis.Y( {
                graph: graph[index],
                orientation: 'left',
                tickFormat: Rickshaw.Fixtures.Number.formatKMBT,
                element: document.getElementById(yaxis)

        } );

        new Rickshaw.Graph.Axis.Time({
                graph: graph[index],
                timeFixture: new Rickshaw.Fixtures.Time.Local()
        });

	graph[index].render()

        new Rickshaw.Graph.HoverDetail({
                graph: graph[index],
                formatter: function (series, x, y) {
                        return content = ""+d3.time.format("%Y-%m-%d %H:%M:%S")(new Date(x*1000)) +"
"+y
                }
        });

	update = gon.feed[index]+"?start="+gon.start+"&stop="+gon.stop+"&step="+gon.step

        console.log(update)
	$.getJSON(update, function(d) {
                $.each(d, function(i, point) {
                        x = {data: point.y}
                        graph[index].series.addData(x) //{name: gon.metric[index], data: point.y})
                })
                graph[index].render()
		unrenderWaiting();
		renderSlider();
        })

}
function updateRickshaw(){
	id = setInterval(function() {
		now = parseInt(Date.now()/1000)

		$.each(gon.feed, function(i, feed) {
			update = feed+"?start="+(now-gon.step)+"&stop="+now+"&step="+gon.step

			$.getJSON(update, function(d){
				new_data = {data: d[d.length-1].y}
				graph[i].series.addData(new_data);
				graph[i].render()
			})
		})
	}
	, gon.step*1000);
	return id
}

var complete = 0;
function renderSlider() {
        complete++;

        // Render the multiple graph slider only when all the graphing operations have been completed.
        if (complete = gon.metric.length) {
        new Rickshaw.Graph.RangeSlider({
                graph: graph,
                element: $("#multi_slider")
                });
        }
}
<|endoftext|>


<commit_before>import { Feature } from 'toolkit/core/feature';
// import * as toolkitHelper from 'toolkit/helpers/toolkit';
import { getCurrentRouteName } from 'toolkit/helpers/toolkit';
import { controllerLookup } from 'toolkit/helpers/toolkit';

export class ToggleTransactionFilters extends Feature {
  injectCSS() {
    return require('./index.css');
  }

  shouldInvoke() {
    return getCurrentRouteName().indexOf('account') > -1;
  }

  onRouteChanged() {
    if (!this.shouldInvoke()) return;

    this.invoke();
  }

  invoke() {
    // create or update buttons
    this.initToggleButtons();
  }

  observe(changedNodes) {
    if (!this.shouldInvoke()) return;

    // activate button styles if filters potentially change
    // activate if switch to individual account, or all accounts views
    if (
      changedNodes.has('modal-overlay ynab-u modal-generic modal-account-filters active closing') ||
      changedNodes.has('ynab-grid-body')) {
      this.initToggleButtons();
    }
  }

  toggleReconciled() {
    let container = controllerLookup('accounts');
    let settingReconciled = !container.filters.get('reconciled');
    container.filters.get('propertiesToSet').setProperties({ reconciled: settingReconciled });
    container.filters.applyFilters();

    if (settingReconciled) {
      $('#toolkit-toggleReconciled').removeClass('toolkit-button-toggle-hidden').addClass('toolkit-button-toggle-visible');
    } else {
      $('#toolkit-toggleReconciled').addClass('toolkit-button-toggle-hidden').removeClass('toolkit-button-toggle-visible');
    }
  }

  toggleScheduled() {
    let container = controllerLookup('accounts');
    let settingScheduled = !container.filters.get('scheduled');
    container.filters.get('propertiesToSet').setProperties({ scheduled: settingScheduled });
    container.filters.applyFilters();

    if (settingScheduled) {
      $('#toolkit-toggleScheduled').removeClass('toolkit-button-toggle-hidden').addClass('toolkit-button-toggle-visible');
    } else {
      $('#toolkit-toggleScheduled').addClass('toolkit-button-toggle-hidden').removeClass('toolkit-button-toggle-visible');
    }
  }

  updateToggleButtons(settingReconciled, settingScheduled) {
    // set button classes
    if (settingReconciled) {
      $('#toolkit-toggleReconciled').removeClass('toolkit-button-toggle-hidden').addClass('toolkit-button-toggle-visible');
    } else {
      $('#toolkit-toggleReconciled').addClass('toolkit-button-toggle-hidden').removeClass('toolkit-button-toggle-visible');
    }

    if (settingScheduled) {
      $('#toolkit-toggleScheduled').removeClass('toolkit-button-toggle-hidden').addClass('toolkit-button-toggle-visible');
    } else {
      $('#toolkit-toggleScheduled').addClass('toolkit-button-toggle-hidden').removeClass('toolkit-button-toggle-visible');
    }
  }

  initToggleButtons() {
    // get internal filters
    let container = controllerLookup('accounts');
    let settingReconciled = container.filters.get('reconciled');
    let settingScheduled = container.filters.get('scheduled');

    // insert or edit buttons
    if (!$('#toolkit-toggleReconciled').length) {
      // create buttons if they don't already exist
      $('.accounts-toolbar .accounts-toolbar-right')
        .append($('<button>', { id: 'toolkit-toggleReconciled', class: 'button', title: 'Toggle Reconciled Transactions' })
          .append($('<i>', { class: 'flaticon solid lock-1 is-reconciled' })
          // show both text and icons or just the icon
          .append(this.settings.enabled === '2' ? ' Reconciled' : '')
          .click(() => { this.toggleReconciled(); })));
      $('.accounts-toolbar .accounts-toolbar-right')
        .append($('<button>', { id: 'toolkit-toggleScheduled', class: 'button', title: 'Toggle Scheduled Transactions' })
          .append($('<i>', { class: 'flaticon solid clock-1 is-reconciled' })
          // show both text and icons or just the icon
          .append(this.settings.enabled === '2' ? ' Scheduled' : '')
            .click(() => { this.toggleScheduled(); })));

      this.updateToggleButtons(settingReconciled, settingScheduled);
    } else {
      // if buttons exist, double check visibility classes
      this.updateToggleButtons(settingReconciled, settingScheduled);
    }
  }
}
<commit_msg>Response to PR change request. Gettin fancy.<commit_after>import { Feature } from 'toolkit/core/feature';
import { controllerLookup, getCurrentRouteName } from 'toolkit/helpers/toolkit';

export class ToggleTransactionFilters extends Feature {
  injectCSS() {
    return require('./index.css');
  }

  shouldInvoke() {
    return getCurrentRouteName().indexOf('account') > -1;
  }

  onRouteChanged() {
    if (!this.shouldInvoke()) return;

    this.invoke();
  }

  invoke() {
    // create or update buttons
    this.initToggleButtons();
  }

  observe(changedNodes) {
    if (!this.shouldInvoke()) return;

    // activate button styles if filters potentially change
    // activate if switch to individual account, or all accounts views
    if (
      changedNodes.has('modal-overlay ynab-u modal-generic modal-account-filters active closing') ||
      changedNodes.has('ynab-grid-body')) {
      this.initToggleButtons();
    }
  }

  toggleReconciled() {
    let container = controllerLookup('accounts');
    let settingReconciled = !container.filters.get('reconciled');
    container.filters.get('propertiesToSet').setProperties({ reconciled: settingReconciled });
    container.filters.applyFilters();

    if (settingReconciled) {
      $('#toolkit-toggleReconciled').removeClass('toolkit-button-toggle-hidden').addClass('toolkit-button-toggle-visible');
    } else {
      $('#toolkit-toggleReconciled').addClass('toolkit-button-toggle-hidden').removeClass('toolkit-button-toggle-visible');
    }
  }

  toggleScheduled() {
    let container = controllerLookup('accounts');
    let settingScheduled = !container.filters.get('scheduled');
    container.filters.get('propertiesToSet').setProperties({ scheduled: settingScheduled });
    container.filters.applyFilters();

    if (settingScheduled) {
      $('#toolkit-toggleScheduled').removeClass('toolkit-button-toggle-hidden').addClass('toolkit-button-toggle-visible');
    } else {
      $('#toolkit-toggleScheduled').addClass('toolkit-button-toggle-hidden').removeClass('toolkit-button-toggle-visible');
    }
  }

  updateToggleButtons(settingReconciled, settingScheduled) {
    // set button classes
    if (settingReconciled) {
      $('#toolkit-toggleReconciled').removeClass('toolkit-button-toggle-hidden').addClass('toolkit-button-toggle-visible');
    } else {
      $('#toolkit-toggleReconciled').addClass('toolkit-button-toggle-hidden').removeClass('toolkit-button-toggle-visible');
    }

    if (settingScheduled) {
      $('#toolkit-toggleScheduled').removeClass('toolkit-button-toggle-hidden').addClass('toolkit-button-toggle-visible');
    } else {
      $('#toolkit-toggleScheduled').addClass('toolkit-button-toggle-hidden').removeClass('toolkit-button-toggle-visible');
    }
  }

  initToggleButtons() {
    // get internal filters
    let container = controllerLookup('accounts');
    let settingReconciled = container.filters.get('reconciled');
    let settingScheduled = container.filters.get('scheduled');

    // insert or edit buttons
    if (!$('#toolkit-toggleReconciled').length) {
      // create buttons if they don't already exist
      $('.accounts-toolbar .accounts-toolbar-right')
        .append($('<button>', { id: 'toolkit-toggleReconciled', class: 'button', title: 'Toggle Reconciled Transactions' })
          .append($('<i>', { class: 'flaticon solid lock-1 is-reconciled' })
          // show both text and icons or just the icon
          .append(this.settings.enabled === '2' ? ' Reconciled' : '')
          .click(() => { this.toggleReconciled(); })));
      $('.accounts-toolbar .accounts-toolbar-right')
        .append($('<button>', { id: 'toolkit-toggleScheduled', class: 'button', title: 'Toggle Scheduled Transactions' })
          .append($('<i>', { class: 'flaticon solid clock-1 is-reconciled' })
          // show both text and icons or just the icon
          .append(this.settings.enabled === '2' ? ' Scheduled' : '')
            .click(() => { this.toggleScheduled(); })));

      this.updateToggleButtons(settingReconciled, settingScheduled);
    } else {
      // if buttons exist, double check visibility classes
      this.updateToggleButtons(settingReconciled, settingScheduled);
    }
  }
}
<|endoftext|>


<commit_before>I.wait_for_build = (function ($) {
  var TIMER_SELECTOR = "[data-increment-every-second]";
  var RELOAD_TIMEOUT = 4000;
  var RELOAD_URL = null;

  function initBuildChecker(check_build_url, reload_url) {
    RELOAD_URL = reload_url;
    checkBuild(check_build_url);
    enqueueCheckBuild(check_build_url);
  }

  function checkBuild(check_build_url) {
    jQuery.ajax(check_build_url, {dataType: 'json', success: function(build) {
      if( !window.builds ) window.builds = {};
      if( !window.builds[build.id] ) {
        window.builds[build.id] = build;
      } else {
        var before = window.builds[build.id];
        if( before.status != build.status ) reload();
        window.builds[build.id] = build;
      }
      enqueueCheckBuild(check_build_url);
    }});
  }

  function enqueueCheckBuild(check_build_url) {
    setTimeout(function() {
      checkBuild(check_build_url);
    }, RELOAD_TIMEOUT);
  }

  function updateBuildTimers() {
    jQuery(TIMER_SELECTOR).each(function(index, ele) {
      var span = $(ele);
      var seconds = parseInt( span.html() );
      seconds = seconds + 1;
      span.html(seconds);
    });;
  }

  function initReload(reload_url) {
    RELOAD_URL = reload_url;
    resetTimeout();
  }

  function initTimers() {
    if( !window.build_timer_id ) {
      window.build_timer_id = setInterval(updateBuildTimers, 1000);
    }
  }

  function resetTimeout() {
    setTimeout(reload, RELOAD_TIMEOUT);
  }

  function reload() {
    if( RELOAD_URL ) {
      jQuery.ajax(RELOAD_URL);
    } else {
      log("NO RELOAD URL SET!")
    }
  }

  return {
    initBuildChecker: initBuildChecker,
    initReload: initReload,
    initTimers: initTimers,
    resetTimeout: resetTimeout
  };
}(jQuery));

jQuery(function() {
  I.wait_for_build.initTimers();
});
<commit_msg>Fix wait_for_build to stop pinging after complete<commit_after>I.wait_for_build = (function ($) {
  var TIMER_SELECTOR = "[data-increment-every-second]";
  var RELOAD_TIMEOUT = 4000;
  var RELOAD_URL = null;

  function initBuildChecker(check_build_url, reload_url) {
    RELOAD_URL = reload_url;
    checkBuild(check_build_url);
  }

  function checkBuild(check_build_url) {
    jQuery.ajax(check_build_url, {dataType: 'json', success: function(build) {
      if( !window.builds ) window.builds = {};
      if( !window.builds[build.id] ) {
        window.builds[build.id] = build;
        enqueueCheckBuild(check_build_url);
      } else {
        var before = window.builds[build.id];
        if( before.status == build.status ) {
          enqueueCheckBuild(check_build_url);
        } else {
          reload();
        }
        window.builds[build.id] = build;
      }
    }});
  }

  function enqueueCheckBuild(check_build_url) {
    setTimeout(function() {
      checkBuild(check_build_url);
    }, RELOAD_TIMEOUT);
  }

  function updateBuildTimers() {
    jQuery(TIMER_SELECTOR).each(function(index, ele) {
      var span = $(ele);
      var seconds = parseInt( span.html() );
      seconds = seconds + 1;
      span.html(seconds);
    });;
  }

  function initReload(reload_url) {
    RELOAD_URL = reload_url;
    resetTimeout();
  }

  function initTimers() {
    if( !window.build_timer_id ) {
      window.build_timer_id = setInterval(updateBuildTimers, 1000);
    }
  }

  function resetTimeout() {
    setTimeout(reload, RELOAD_TIMEOUT);
  }

  function reload() {
    if( RELOAD_URL ) {
      jQuery.ajax(RELOAD_URL);
    } else {
      log("NO RELOAD URL SET!")
    }
  }

  return {
    initBuildChecker: initBuildChecker,
    initReload: initReload,
    initTimers: initTimers,
    resetTimeout: resetTimeout
  };
}(jQuery));

jQuery(function() {
  I.wait_for_build.initTimers();
});
<|endoftext|>


<commit_before>import {
  props,
  define,
  hasNativeShadowDomSupport,
  containsTagName,
} from '@bolt/core/utils';
import { withLitHtml, html } from '@bolt/core/renderers/renderer-lit-html';
import { ifDefined } from 'lit-html/directives/if-defined';
import path from 'path';

import classNames from 'classnames/bind';

import ratioStyles from '@bolt/components-ratio/src/ratio.scss';
import imageStyles from './image.scss';

import schema from '../image.schema.yml';

import './_image-lazy-sizes';

let cx = classNames.bind(imageStyles);

@define
class BoltImage extends withLitHtml() {
  static is = 'bolt-image';

  static props = {
    src: props.string,
    alt: props.string,
    noLazy: props.boolean,
    srcset: props.string,
    sizes: props.string,
    ratio: props.string,
    width: props.string,
    height: props.string,
    placeholderColor: props.string,
    placeholderImage: props.string,
    zoom: props.boolean,
  };

  // https://github.com/WebReflection/document-register-element#upgrading-the-constructor-context
  constructor(self) {
    self = super(self);
    self.useShadow = hasNativeShadowDomSupport;
    self.schema = this.getModifiedSchema(schema);
    return self;
  }

  getModifiedSchema(schema) {
    var modifiedSchema = schema;

    // Remove "lazyload" and "useAspectRatio" from schema, does not apply to web component.
    for (let property in modifiedSchema.properties) {
      if (property === 'lazyload' || property === 'useAspectRatio') {
        delete modifiedSchema.properties[property];
      }
    }

    return modifiedSchema;
  }

  lazyloadImage(image) {
    // console.log('@lazyloadImage');
    if (!this.isLoaded) {
      // Note: This immediately unveils the image. Add intersection observer?
      lazySizes.loader.unveil(image);
      this.isLoaded = true;
    }
  }

  connecting() {
    super.connecting && super.connecting();
    while (this.firstChild) {
      this.removeChild(this.firstChild);
    }
  }

  rendered() {
    super.rendered() && super.rendered();
    let lazyImage = this.shadowRoot.querySelector('.js-lazyload');
    if (lazyImage) {
      this.lazyloadImage(lazyImage);
    }
  }

  render() {
    // validate the original prop data passed along -- returns back the validated data w/ added default values
    const {
      src,
      alt,
      noLazy,
      srcset,
      sizes,
      ratio,
      width,
      height,
      placeholderColor,
      placeholderImage,
      zoom,
    } = this.validateProps(this.props);

    // negate and rename variables for readability
    const lazyload = !noLazy;

    // use ratio by default, still depends upon width and height being set
    let useRatio = true;
    let ratioW;
    let ratioH;

    if (ratio) {
      switch (ratio) {
        case 'none':
          useRatio = false;
          break;
        case 'auto':
          useRatio = true;
          break;
        default:
          useRatio = true;
          if (ratio.indexOf(':') > -1) {
            const ratioArr = ratio.split(':');
            ratioW = ratioArr[0];
            ratioH = ratioArr[1];
          }
      }
    }

    const canUseRatio = ratioW > 0 && ratioH > 0 && useRatio;

    const imageExt = path.extname(src);

    const classes = cx('c-bolt-image__image', {
      'c-bolt-image__lazyload': lazyload,
      'c-bolt-image__lazyload--fade': lazyload,
      'c-bolt-image__lazyload--blur': lazyload && imageExt === '.jpg',
      'js-lazyload': lazyload,
    });

    const imageElement = () => {
      if (src) {
        return html`
          <img
            class="${classes}"
            src="${lazyload ? placeholderImage : src}"
            alt="${ifDefined(alt ? alt : undefined)}"
            srcset="${ifDefined(
              !lazyload || this.isLoaded ? srcset || src : undefined,
            )}"
            data-srcset="${ifDefined(lazyload ? srcset || src : undefined)}"
            sizes="${ifDefined(!lazyload || this.isLoaded ? sizes : undefined)}"
            data-sizes="${ifDefined(lazyload ? sizes : undefined)}"
            data-zoom="${ifDefined(zoom ? src : undefined)}"
          />
        `;
      }
    };

    const placeholderImageElement = () => {
      if (canUseRatio && imageExt === '.jpg') {
        return html`
          <img
            class="${cx('c-bolt-image__image-placeholder')}"
            src="${placeholderImage}"
            alt="${ifDefined(alt ? alt : undefined)}"
          />
        `;
      }
    };

    // Include <noscript> for server-side rendered components
    const fallbackImageElement = () => {
      if (lazyload && src) {
        return html`
          <noscript>
            <img
              class="${classes}"
              src="${src}"
              alt="${ifDefined(alt ? alt : undefined)}"
              srcset="${ifDefined(!lazyload ? srcset || src : undefined)}"
              data-srcset="${ifDefined(lazyload ? srcset || src : undefined)}"
            />
          </noscript>
        `;
      }
    };

    const imageTemplate = html`
      ${placeholderImageElement()} ${imageElement()} ${fallbackImageElement()}
    `;

    const ratioTemplate = children => {
      return html`
        <bolt-ratio
          aspect-ratio-width="${ratioW * 1}"
          aspect-ratio-height="${ratioH * 1}"
        >
          ${children}
        </bolt-ratio>
      `;
    };

    if (canUseRatio && imageExt === '.jpg' && placeholderColor) {
      this.style.backgroundColor = placeholderColor;
    }

    let renderedImage = this.slot('default');

    if (
      !containsTagName(this.childNodes, 'img') &&
      !containsTagName(this.childNodes, 'bolt-ratio')
    ) {
      if (canUseAspectRatio) {
        renderedImage = ratioTemplate(imageTemplate);
      } else {
        renderedImage = imageTemplate;
      }
    }

    return html`
      ${this.addStyles([imageStyles, ratioStyles])} ${renderedImage}
    `;
  }
}

export { BoltImage };
<commit_msg>feat: add timeout to workaround lazyload render race condition, wip<commit_after>import {
  props,
  define,
  hasNativeShadowDomSupport,
  containsTagName,
} from '@bolt/core/utils';
import { withLitHtml, html } from '@bolt/core/renderers/renderer-lit-html';
import { ifDefined } from 'lit-html/directives/if-defined';
import path from 'path';

import classNames from 'classnames/bind';

import ratioStyles from '@bolt/components-ratio/src/ratio.scss';
import imageStyles from './image.scss';

import schema from '../image.schema.yml';

import './_image-lazy-sizes';

let cx = classNames.bind(imageStyles);

@define
class BoltImage extends withLitHtml() {
  static is = 'bolt-image';

  static props = {
    src: props.string,
    alt: props.string,
    noLazy: props.boolean,
    srcset: props.string,
    sizes: props.string,
    ratio: props.string,
    width: props.string,
    height: props.string,
    placeholderColor: props.string,
    placeholderImage: props.string,
    zoom: props.boolean,
  };

  // https://github.com/WebReflection/document-register-element#upgrading-the-constructor-context
  constructor(self) {
    self = super(self);
    self.useShadow = hasNativeShadowDomSupport;
    self.schema = this.getModifiedSchema(schema);
    return self;
  }

  getModifiedSchema(schema) {
    var modifiedSchema = schema;

    // Remove "lazyload" and "useAspectRatio" from schema, does not apply to web component.
    for (let property in modifiedSchema.properties) {
      if (property === 'lazyload' || property === 'useAspectRatio') {
        delete modifiedSchema.properties[property];
      }
    }

    return modifiedSchema;
  }

  lazyloadImage(image) {
    // console.log('@lazyloadImage');
    if (!this.isLoaded) {
      // Note: This immediately unveils the image. Add intersection observer?
      lazySizes.loader.unveil(image);
      this.isLoaded = true;
    }
  }

  connecting() {
    super.connecting && super.connecting();
    while (this.firstChild) {
      this.removeChild(this.firstChild);
    }
  }

  rendered() {
    super.rendered && super.rendered();

    const lazyImage = this.shadowRoot
      ? this.shadowRoot.querySelector('.js-lazyload')
      : this.querySelector('.js-lazyload');

    if (lazyImage) {
      setTimeout(() => {
        this.lazyloadImage(lazyImage);
      }, 0);
    }
  }

  render() {
    // validate the original prop data passed along -- returns back the validated data w/ added default values
    const {
      src,
      alt,
      noLazy,
      srcset,
      sizes,
      ratio,
      width,
      height,
      placeholderColor,
      placeholderImage,
      zoom,
    } = this.validateProps(this.props);

    // negate and rename variables for readability
    const lazyload = !noLazy;

    // use ratio by default, still depends upon width and height being set
    let useRatio = true;
    let ratioW;
    let ratioH;

    if (ratio) {
      switch (ratio) {
        case 'none':
          useRatio = false;
          break;
        case 'auto':
          useRatio = true;
          break;
        default:
          useRatio = true;
          if (ratio.indexOf(':') > -1) {
            const ratioArr = ratio.split(':');
            ratioW = ratioArr[0];
            ratioH = ratioArr[1];
          }
      }
    }

    const canUseRatio = ratioW > 0 && ratioH > 0 && useRatio;

    const imageExt = path.extname(src);

    const classes = cx('c-bolt-image__image', {
      'c-bolt-image__lazyload': lazyload,
      'c-bolt-image__lazyload--fade': lazyload,
      'c-bolt-image__lazyload--blur': lazyload && imageExt === '.jpg',
      'js-lazyload': lazyload,
    });

    const imageElement = () => {
      if (src) {
        return html`
          <img
            class="${classes}"
            src="${lazyload ? placeholderImage : src}"
            alt="${ifDefined(alt ? alt : undefined)}"
            srcset="${ifDefined(
              !lazyload || this.isLoaded ? srcset || src : undefined,
            )}"
            data-srcset="${ifDefined(lazyload ? srcset || src : undefined)}"
            sizes="${ifDefined(!lazyload || this.isLoaded ? sizes : undefined)}"
            data-sizes="${ifDefined(lazyload ? sizes : undefined)}"
            data-zoom="${ifDefined(zoom ? src : undefined)}"
          />
        `;
      }
    };

    const placeholderImageElement = () => {
      if (canUseRatio && imageExt === '.jpg') {
        return html`
          <img
            class="${cx('c-bolt-image__image-placeholder')}"
            src="${placeholderImage}"
            alt="${ifDefined(alt ? alt : undefined)}"
          />
        `;
      }
    };

    // Include <noscript> for server-side rendered components
    const fallbackImageElement = () => {
      if (lazyload && src) {
        return html`
          <noscript>
            <img
              class="${classes}"
              src="${src}"
              alt="${ifDefined(alt ? alt : undefined)}"
              srcset="${ifDefined(!lazyload ? srcset || src : undefined)}"
              data-srcset="${ifDefined(lazyload ? srcset || src : undefined)}"
            />
          </noscript>
        `;
      }
    };

    const imageTemplate = html`
      ${placeholderImageElement()} ${imageElement()} ${fallbackImageElement()}
    `;

    const ratioTemplate = children => {
      return html`
        <bolt-ratio
          aspect-ratio-width="${ratioW * 1}"
          aspect-ratio-height="${ratioH * 1}"
        >
          ${children}
        </bolt-ratio>
      `;
    };

    if (canUseRatio && imageExt === '.jpg' && placeholderColor) {
      this.style.backgroundColor = placeholderColor;
    }

    let renderedImage = this.slot('default');

    if (
      !containsTagName(this.childNodes, 'img') &&
      !containsTagName(this.childNodes, 'bolt-ratio')
    ) {
      if (canUseAspectRatio) {
        renderedImage = ratioTemplate(imageTemplate);
      } else {
        renderedImage = imageTemplate;
      }
    }

    return html`
      ${this.addStyles([imageStyles, ratioStyles])} ${renderedImage}
    `;
  }
}

export { BoltImage };
<|endoftext|>


<commit_before>/*!
 * angular-katex v0.8.0
 * https://github.com/tfoxy/angular-katex
 *
 * Copyright 2015 Tomás Fox
 * Released under the MIT license
 */
!function(){"use strict";function e(){return"undefined"!=typeof renderMathInElement?renderMathInElement:void 0}function n(e,n){var t={$get:function(){return t},defaultOptions:{},errorElement:'',errorHandler:function(e,n,r){var a=angular.element(t.errorElement);a.textContent=e,r.children().remove(),r.append(a)},render:function(n,r,a,o){try{var i=a||t.defaultOptions;e.render(r||"",n[0],i)}catch(u){o(u,r,n)}},autoRender:function(e,r,a){try{var o=r||t.defaultOptions;n(e[0],o)}catch(i){a(i,null,e)}}};return t}function t(e,n){return{restrict:"AE",compile:function(t,r){var i=a(n,r),u=o(n,r,e);if("katexAutoRender"in r)e.autoRender(t,i,u);else{var c=r.katex||t.text();e.render(t,c,i,u)}}}}function r(e){return{restrict:"A",link:function(n,t,r){var i=o(n,r,e);n.$watch(r.katexBind,function(o){var u=a(n,r);"katexAutoRender"in r?(t.text(o),e.autoRender(t,u,i)):e.render(t,o,u,i)})}}}function a(e,n){var t=n.katexOptions;return t&&e.$eval(t)}function o(e,n,t){return"katexOnError"in n?function(t,r,a){e.$eval(n.katexOnError,{$err:t,$expr:r,$setText:function(e){a.text(e)}})}:t.errorHandler}angular.module("katex",[]).constant("katex",katex).constant("renderMathInElement",e()).provider("katexConfig",n).directive("katex",t).directive("katexBind",r),n.$inject=["katex","renderMathInElement"],t.$inject=["katexConfig","$rootScope"],r.$inject=["katexConfig"]}();<commit_msg>Minify<commit_after>/*!
 * angular-katex v0.8.1
 * https://github.com/tfoxy/angular-katex
 *
 * Copyright 2015 Tomás Fox
 * Released under the MIT license
 */
!function(){"use strict";function e(){return"undefined"!=typeof renderMathInElement?renderMathInElement:void 0}function n(e,n){var t={$get:function(){return t},defaultOptions:{},errorElement:'',errorHandler:function(e,n,r){var a=angular.element(t.errorElement);a.text(e),r.children().remove(),r.append(a)},render:function(n,r,a,o){try{var i=a||t.defaultOptions;e.render(r||"",n[0],i)}catch(u){o(u,r,n)}},autoRender:function(e,r,a){try{var o=r||t.defaultOptions;n(e[0],o)}catch(i){a(i,null,e)}}};return t}function t(e,n){return{restrict:"AE",compile:function(t,r){var i=a(n,r),u=o(n,r,e);if("katexAutoRender"in r)e.autoRender(t,i,u);else{var c=r.katex||t.text();e.render(t,c,i,u)}}}}function r(e){return{restrict:"A",link:function(n,t,r){var i=o(n,r,e);n.$watch(r.katexBind,function(o){var u=a(n,r);"katexAutoRender"in r?(t.text(o),e.autoRender(t,u,i)):e.render(t,o,u,i)})}}}function a(e,n){var t=n.katexOptions;return t&&e.$eval(t)}function o(e,n,t){return"katexOnError"in n?function(t,r,a){e.$eval(n.katexOnError,{$err:t,$expr:r,$setText:function(e){a.text(e)}})}:t.errorHandler}angular.module("katex",[]).constant("katex",katex).constant("renderMathInElement",e()).provider("katexConfig",n).directive("katex",t).directive("katexBind",r),n.$inject=["katex","renderMathInElement"],t.$inject=["katexConfig","$rootScope"],r.$inject=["katexConfig"]}();<|endoftext|>


<commit_before>define(["require", "exports", "res/default", "knockout"], function (require, exports, default_1, ko) {
    exports.text = default_1.default;
    exports.keys = {};
    function addModule(name, newText) {
        exports.text[name] = newText;
    }
    exports.addModule = addModule;
    function register() {
        for (var key in exports.text) {
            var mod = exports.text[key];
            for (var sub in mod) {
                var line = mod[sub];
                exports.keys[key + '.' + sub] = line;
            }
        }
        // A binding handler that set the text content with a format ({n} is replaced by the nth parameter)
        ko.bindingHandlers['locf'] = {
            update: function (element, valueAccessor) {
                var parameters = valueAccessor();
                var text = exports.keys[parameters[0]];
                for (var i = 1; i < parameters.length; i++) {
                    text = text.replace('{' + (i - 1) + '}', ko.unwrap(parameters[i]));
                }
                element.innerHTML = text;
            }
        };
        // A binding handler to set attribute values
        ko.bindingHandlers['loca'] = {
            update: function (element, valueAccessor) {
                var parameters = valueAccessor();
                for (var key in parameters) {
                    var value = parameters[key];
                    element.setAttribute(key, exports.keys[value]);
                }
            }
        };
        ko.bindingProvider.instance['preprocessNode'] = function (node) {
            if (node.nodeType === node.ELEMENT_NODE) {
                var element = node;
                for (var i = 0; i < element.attributes.length; i++) {
                    var attribute = element.attributes[i];
                    var value = attribute.value;
                    if (value.indexOf("{{") == 0) {
                        value = value.substr(2, value.length - 4);
                        element.removeAttribute(attribute.name);
                        if (element.hasAttribute('data-bind')) {
                            element.attributes.getNamedItem('data-bind').value += ',loca: {' + attribute.name + ':"' + value + '"}';
                        }
                        else {
                            element.setAttribute('data-bind', 'loca: {' + attribute.name + ':"' + value + '"}');
                        }
                    }
                }
            }
            if (node.nodeType === 3) {
                if (node.nodeValue && node.nodeValue.indexOf('{{nohtml|') !== -1) {
                    node.nodeValue = node.nodeValue.replace(/{{nohtml\|(.*?)}}/, function (match, id) { return exports.keys[id] || id; });
                    return [node];
                }
                else if (node.nodeValue && node.nodeValue.indexOf('{{') !== -1) {
                    if (node.nodeValue.indexOf(',') !== -1) {
                        var newElement = document.createElement('span');
                        var value = node.nodeValue.match(/{{(.*?)}}/)[1];
                        var parameters = value.split(',');
                        parameters[0] = "'" + parameters[0] + "'";
                        newElement.setAttribute('data-bind', 'locf: [' + parameters.join(',') + ']');
                        node.parentNode.replaceChild(newElement, node);
                        return [newElement];
                    }
                    else {
                        var newElement = document.createElement('span');
                        newElement.innerHTML = node.nodeValue.replace(/{{(.*?)}}/, function (match, id) { return exports.keys[id] || id; });
                        node.parentNode.replaceChild(newElement, node);
                        return [newElement];
                    }
                }
            }
        };
    }
    exports.register = register;
});
<commit_msg>Generate using last version of typescript<commit_after>define(["require", "exports", "res/default", "knockout"], function (require, exports, default_1, ko) {
    "use strict";
    exports.text = default_1["default"];
    exports.keys = {};
    function addModule(name, newText) {
        exports.text[name] = newText;
    }
    exports.addModule = addModule;
    function register() {
        for (var key in exports.text) {
            var mod = exports.text[key];
            for (var sub in mod) {
                var line = mod[sub];
                exports.keys[key + '.' + sub] = line;
            }
        }
        // A binding handler that set the text content with a format ({n} is replaced by the nth parameter)
        ko.bindingHandlers['locf'] = {
            update: function (element, valueAccessor) {
                var parameters = valueAccessor();
                var text = exports.keys[parameters[0]];
                for (var i = 1; i < parameters.length; i++) {
                    text = text.replace('{' + (i - 1) + '}', ko.unwrap(parameters[i]));
                }
                element.innerHTML = text;
            }
        };
        // A binding handler to set attribute values
        ko.bindingHandlers['loca'] = {
            update: function (element, valueAccessor) {
                var parameters = valueAccessor();
                for (var key in parameters) {
                    var value = parameters[key];
                    element.setAttribute(key, exports.keys[value]);
                }
            }
        };
        ko.bindingProvider.instance['preprocessNode'] = function (node) {
            if (node.nodeType === node.ELEMENT_NODE) {
                var element = node;
                for (var i = 0; i < element.attributes.length; i++) {
                    var attribute = element.attributes[i];
                    var value = attribute.value;
                    if (value.indexOf("{{") == 0) {
                        value = value.substr(2, value.length - 4);
                        element.removeAttribute(attribute.name);
                        if (element.hasAttribute('data-bind')) {
                            element.attributes.getNamedItem('data-bind').value += ',loca: {' + attribute.name + ':"' + value + '"}';
                        }
                        else {
                            element.setAttribute('data-bind', 'loca: {' + attribute.name + ':"' + value + '"}');
                        }
                    }
                }
            }
            if (node.nodeType === 3) {
                if (node.nodeValue && node.nodeValue.indexOf('{{nohtml|') !== -1) {
                    node.nodeValue = node.nodeValue.replace(/{{nohtml\|(.*?)}}/, function (match, id) { return exports.keys[id] || id; });
                    return [node];
                }
                else if (node.nodeValue && node.nodeValue.indexOf('{{') !== -1) {
                    if (node.nodeValue.indexOf(',') !== -1) {
                        var newElement = document.createElement('span');
                        var value = node.nodeValue.match(/{{(.*?)}}/)[1];
                        var parameters = value.split(',');
                        parameters[0] = "'" + parameters[0] + "'";
                        newElement.setAttribute('data-bind', 'locf: [' + parameters.join(',') + ']');
                        node.parentNode.replaceChild(newElement, node);
                        return [newElement];
                    }
                    else {
                        var newElement = document.createElement('span');
                        newElement.innerHTML = node.nodeValue.replace(/{{(.*?)}}/, function (match, id) { return exports.keys[id] || id; });
                        node.parentNode.replaceChild(newElement, node);
                        return [newElement];
                    }
                }
            }
        };
    }
    exports.register = register;
});
<|endoftext|>


<commit_before>// create table view data object
var data = [
	{title:'Row 1', hasChild:true},
	{title:'Row 2', hasDetail:true},
	{title:'Append Row with Header'},
	{title:'Append Row & height=100'}

];

// create table view
var tableview = Titanium.UI.createTableView({
	data:data
});

var newRowCount = 1;
var newSectionCount = 1;
// create table view event listener
tableview.addEventListener('click', function(e)
{
	Ti.API.info('clicked received for row ' + e.index);
	// event data
	var index = e.index;
	var section = e.section;
	var row = e.row;
	row.height = 100;
	var rowdata = e.rowData;
	if (index == 2)
	{
		// var row = Ti.UI.createTableViewRow({header:'New Header'});
		// var l = Ti.UI.createLabel({
		//     text:' I am a new row',
		//     height:30,
		//     width:200
		// });
		// row.add(l);
		var data = {title:'New Row ' + newRowCount, header:'New Header '+newSectionCount};

		tableview.appendRow(data);
		newSectionCount++;
		newRowCount++;
	}
	else if (index == 3)
	{
		var data = {title:'New Row ' + newRowCount};
		if (newRowCount == 1)
		{
			tableview.appendRow(data);
		}
		else
		{
			tableview.appendRow(data,{animationStyle:Titanium.UI.iPhone.RowAnimationStyle.LEFT});
		}
		newRowCount++;
	}
	else
	{
		Titanium.UI.createAlertDialog({title:'Table View',message:'row ' + row + ' index ' + index + ' section ' + section  + ' row data ' + rowdata}).show();
	}

});

// add table view to the window
Titanium.UI.currentWindow.add(tableview);
<commit_msg>[#453] Change 'append' test so that one append is a JS object, the other is TableViewRow object.<commit_after>// create table view data object
var data = [
	{title:'Row 1', hasChild:true},
	{title:'Row 2', hasDetail:true},
	{title:'Append Row with Header'},
	{title:'Append Row & height=100'}

];

// create table view
var tableview = Titanium.UI.createTableView({
	data:data
});

var newRowCount = 1;
var newSectionCount = 1;
// create table view event listener
tableview.addEventListener('click', function(e)
{
	Ti.API.info('clicked received for row ' + e.index);
	// event data
	var index = e.index;
	var section = e.section;
	var row = e.row;
	row.height = 100;
	var rowdata = e.rowData;
	if (index == 2)
	{
		// var row = Ti.UI.createTableViewRow({header:'New Header'});
		// var l = Ti.UI.createLabel({
		//     text:' I am a new row',
		//     height:30,
		//     width:200
		// });
		// row.add(l);
		var data = {title:'New Row ' + newRowCount, header:'New Header '+newSectionCount};

		tableview.appendRow(data);
		newSectionCount++;
		newRowCount++;
	}
	else if (index == 3)
	{
		var data = Ti.UI.createTableViewRow({title:'New Row ' + newRowCount});
		if (newRowCount == 1)
		{
			tableview.appendRow(data);
		}
		else
		{
			tableview.appendRow(data,{animationStyle:Titanium.UI.iPhone.RowAnimationStyle.LEFT});
		}
		newRowCount++;
	}
	else
	{
		Titanium.UI.createAlertDialog({title:'Table View',message:'row ' + row + ' index ' + index + ' section ' + section  + ' row data ' + rowdata}).show();
	}

});

// add table view to the window
Titanium.UI.currentWindow.add(tableview);
<|endoftext|>


<commit_before>var fs = require('fs');
var yaml = require('js-yaml');
var exec = require('child_process').exec;
var builder = require('./dockerfileBuilder.js');
var configFile = "lifter.yml";

// execsync may or may not be useful at some point
var execSync = require('exec-sync');

var exitInstructions = [];

// if boot2docker VM doesn't exist: init , else boot
var start_b2d = function() {
  exec('boot2docker info', function(err, stdout, stderr) {
    if (err) {
      if (/machine not exist/.test(stderr)) {
        console.log('boot2docker VM not installed, running boot2docker init');
        exec_b2d_init();
      }
    } else {
      console.log('boot2docker VM exists, checking to see if running...');
      boot_b2d();
    }
  });
};

// create boot2docker VM, then boot
var exec_b2d_init = function() {
  exec('boot2docker init', function(err, stdout, stderr) {
    if (err) console.log(stderr);
    console.log('boot2docker VM created!');
    boot_b2d();
  });
};

// If b2d is powered off, power it on
var boot_b2d = function() {
  exec('boot2docker status', function (err, stdout, stderr) {
    if (err) console.log(err);
    if (/poweroff/.test(stdout)) {
      exec_b2d_Up();
    } else { // if (/running/.test(stdout)) {
      console.log('boot2docker is already running');
      checkHostsFileForDockerhost();
      // TODO: what goes here?
    }
  });
}

var exec_b2d_Up = function() {
  var setEnvs = false;
  var exportCmds = [];
  exec('boot2docker up', function(err, stdout, stderr) {
    if (err) console.log("exec err: ", err);
    console.log('boot2docker VM powered on')
    // check for boot2docker env vars
    if (!process.env.DOCKER_HOST ||
        !process.env.DOCKER_CERT_PATH ||
        !process.env.DOCKER_TLS_VERIFY) {
      setEnvs = true;
      // parse out EXPORT commands
      console.log("environment variables not set... parsing commands and running")
      var cmds = stdout;
      cmds = cmds.split("To connect the Docker client to the Docker daemon, please set:")[1];
      cmds = cmds.replace( /\n/g, "#").split("#");
      cmds = cmds.filter(function(item){
        return item !== '';
      });
      cmds = cmds.map(function(value) {
        return value.trim();
      });
      exportCmds = cmds;
    }

    // set environment variables if necessary,
    // or check if dockerhost is IP correct
    if (setEnvs) {
      setEnvironmentVars(exportCmds);
    } else {
      checkHostsFileForDockerhost();
    }

  });
};

var setEnvironmentVars = function(exportCmds) {
  exportCmds.forEach(function(cmd) {
    exec(cmd, function(err,stdout,stderr) {
      console.log("Executing:", cmd);
      // if (err) console.log("exec err: ", stderr);
    });
  });
  checkHostsFileForDockerhost();
}

// check /etc/hosts for proper dockerhost IP
var checkHostsFileForDockerhost = function() {
  var hosts = fs.readFileSync('/etc/hosts');
  var hostsWritten = /dockerhost/.test(hosts);

  exec('boot2docker ip', function(err, stdout, stderr) {
    if (err) console.log(stderr);
    // grab ip out of stdout
    var ip = /\d*\.\d*\.\d*\.\d*/.exec(stdout)[0];
    var ipRegex = new RegExp(ip);
    // change line if ip not in hosts file

    createShellScript();
    builder.buildDockerFile();

    if (hostsWritten) {
      console.log('dockerhost found in /etc/hosts');
      if (!ipRegex.test(hosts)) {
        console.log('dockerhost IP incorrect... removing');
        // removeIPinHostsFile(ip);
        exitInstructions.push(
          'sed \'/dockerhost/d\' /etc/hosts | sudo tee /etc/hosts');
        exitInstructions.push(
          'echo ' + ip + ' dockerhost | sudo tee -a /etc/hosts');
      } else {
        console.log('dockerhost IP is correct');
      }
    } else {
      console.log('dockerhost not found in /etc/hosts... adding');
      exitInstructions.push(
          'echo ' + ip + ' dockerhost | sudo tee -a /etc/hosts');
      // addDockerhostToHostsFile(ip);
    }
    // console.log(exitInstructions);
    createLocalContainer();
  });

}

var getSettings = function() {
  var yml = fs.readFileSync(configFile);
  return yaml.safeLoad(yml);
}

// create shell script to launch app
var createShellScript = function() {
  if(!fs.existsSync(configFile)) {
    console.log('lifter.yml doesn\'t exist. Please run lifter config');
    process.exit(1);
  }

  fs.readFile(configFile, function (err, data) {
    if (err) throw err;
    settings = yaml.safeLoad(data);

    var shellFileContent = "#!/bin/sh\n";
    shellFileContent += "cd " + settings.launchPath + "\n";
    shellFileContent += settings.launchCommand;

    fs.writeFile("app.sh", shellFileContent, function(err) {
      if (err) console.log(err);
      console.log("Launch script created: app.sh");
    });
  });
}

var createLocalContainer = function() {
  var settings = getSettings();
  //docker build -t username_on_docker_hub/create_new_repo_name .
  var imageName = settings.username + '/' + settings.repoName;
  var dbImageName = imageName + '_db';

  var buildCmd = 'docker build -t '
  + imageName + ' .';
  var mongoRunCmd = 'docker run --restart=always --name '
  + dbImageName + ' mongo:latest'
  var appRunCmd = 'docker run --restart=always -p '
  + settings.portPrivate + ':'
  + settings.portPublic + ' -v '
  + settings.launchPath
  + ':/src:ro sh /src/app.sh';

  console.log('Building application image...');
  execSync(buildCmd);
  console.log('Launching database container...');
  execSync(mongoRunCmd);
  console.log('Launching applicion container...');
  execSync(appRunCmd);

  finishInit();
}

var finishInit = function () {
  console.log("Program container(s) initialized.");
  if (exitInstructions.length > 0) {
    console.log("Run these commands:")
    exitInstructions.forEach(function(str) {
      console.log("    " + str);
    });
  }
}

module.exports = {
  start_b2d: start_b2d
}
<commit_msg>fix bug that doesn't check for all states b2d vm can be in<commit_after>var fs = require('fs');
var yaml = require('js-yaml');
var exec = require('child_process').exec;
var builder = require('./dockerfileBuilder.js');
var configFile = "lifter.yml";

// execsync may or may not be useful at some point
var execSync = require('exec-sync');

var exitInstructions = [];

// if boot2docker VM doesn't exist: init , else boot
var start_b2d = function() {
  exec('boot2docker info', function(err, stdout, stderr) {
    if (err) {
      if (/machine not exist/.test(stderr)) {
        console.log('boot2docker VM not installed, running boot2docker init');
        exec_b2d_init();
      }
    } else {
      console.log('boot2docker VM exists, checking to see if running...');
      boot_b2d();
    }
  });
};

// create boot2docker VM, then boot
var exec_b2d_init = function() {
  exec('boot2docker init', function(err, stdout, stderr) {
    if (err) console.log(stderr);
    console.log('boot2docker VM created!');
    boot_b2d();
  });
};

// If b2d is powered off, power it on
var boot_b2d = function() {
  exec('boot2docker status', function (err, stdout, stderr) {
    if (err) console.log(err);
    if (/running/.test(stdout)) {
      console.log('boot2docker is already running');
      checkHostsFileForDockerhost();
    } else { //if (/poweroff/.test(stdout)) {
      exec_b2d_Up();
    }
  });
}

var exec_b2d_Up = function() {
  var setEnvs = false;
  var exportCmds = [];
  exec('boot2docker up', function(err, stdout, stderr) {
    if (err) console.log("exec err: ", err);
    console.log('boot2docker VM powered on')
    // check for boot2docker env vars
    if (!process.env.DOCKER_HOST ||
        !process.env.DOCKER_CERT_PATH ||
        !process.env.DOCKER_TLS_VERIFY) {
      setEnvs = true;
      // parse out EXPORT commands
      console.log("environment variables not set... parsing commands and running")
      var cmds = stdout;
      cmds = cmds.split("To connect the Docker client to the Docker daemon, please set:")[1];
      cmds = cmds.replace( /\n/g, "#").split("#");
      cmds = cmds.filter(function(item){
        return item !== '';
      });
      cmds = cmds.map(function(value) {
        return value.trim();
      });
      exportCmds = cmds;
    }

    // set environment variables if necessary,
    // or check if dockerhost is IP correct
    if (setEnvs) {
      setEnvironmentVars(exportCmds);
    } else {
      checkHostsFileForDockerhost();
    }

  });
};

var setEnvironmentVars = function(exportCmds) {
  exportCmds.forEach(function(cmd) {
    exec(cmd, function(err,stdout,stderr) {
      console.log("Executing:", cmd);
      // if (err) console.log("exec err: ", stderr);
    });
  });
  checkHostsFileForDockerhost();
}

// check /etc/hosts for proper dockerhost IP
var checkHostsFileForDockerhost = function() {
  var hosts = fs.readFileSync('/etc/hosts');
  var hostsWritten = /dockerhost/.test(hosts);

  exec('boot2docker ip', function(err, stdout, stderr) {
    if (err) console.log(stderr);
    // grab ip out of stdout
    var ip = /\d*\.\d*\.\d*\.\d*/.exec(stdout)[0];
    var ipRegex = new RegExp(ip);
    // change line if ip not in hosts file

    createShellScript();
    builder.buildDockerFile();

    if (hostsWritten) {
      console.log('dockerhost found in /etc/hosts');
      if (!ipRegex.test(hosts)) {
        console.log('dockerhost IP incorrect... removing');
        // removeIPinHostsFile(ip);
        exitInstructions.push(
          'sed \'/dockerhost/d\' /etc/hosts | sudo tee /etc/hosts');
        exitInstructions.push(
          'echo ' + ip + ' dockerhost | sudo tee -a /etc/hosts');
      } else {
        console.log('dockerhost IP is correct');
      }
    } else {
      console.log('dockerhost not found in /etc/hosts... adding');
      exitInstructions.push(
          'echo ' + ip + ' dockerhost | sudo tee -a /etc/hosts');
      // addDockerhostToHostsFile(ip);
    }
    // console.log(exitInstructions);
    createLocalContainer();
  });

}

var getSettings = function() {
  var yml = fs.readFileSync(configFile);
  return yaml.safeLoad(yml);
}

// create shell script to launch app
var createShellScript = function() {
  if(!fs.existsSync(configFile)) {
    console.log('lifter.yml doesn\'t exist. Please run lifter config');
    process.exit(1);
  }

  fs.readFile(configFile, function (err, data) {
    if (err) throw err;
    settings = yaml.safeLoad(data);

    var shellFileContent = "#!/bin/sh\n";
    shellFileContent += "cd " + settings.launchPath + "\n";
    shellFileContent += settings.launchCommand;

    fs.writeFile("app.sh", shellFileContent, function(err) {
      if (err) console.log(err);
      console.log("Launch script created: app.sh");
    });
  });
}

var createLocalContainer = function() {
  var settings = getSettings();
  //docker build -t username_on_docker_hub/create_new_repo_name .
  var imageName = settings.username + '/' + settings.repoName;
  var dbImageName = imageName + '_db';

  var buildCmd = 'docker build -t '
  + imageName + ' .';
  var mongoRunCmd = 'docker run --restart=always --name '
  + dbImageName + ' mongo:latest'
  var appRunCmd = 'docker run --restart=always -p '
  + settings.portPrivate + ':'
  + settings.portPublic + ' -v '
  + settings.launchPath
  + ':/src:ro sh /src/app.sh';

  console.log('Building application image...');
  execSync(buildCmd);
  console.log('Launching database container...');
  execSync(mongoRunCmd);
  console.log('Launching applicion container...');
  execSync(appRunCmd);

  finishInit();
}

var finishInit = function () {
  console.log("Program container(s) initialized.");
  if (exitInstructions.length > 0) {
    console.log("Run these commands:")
    exitInstructions.forEach(function(str) {
      console.log("    " + str);
    });
  }
}

module.exports = {
  start_b2d: start_b2d
}
<|endoftext|>


<commit_before>import TopComponent from '../../components/TopComponent/TopComponent';

export default class GameScene extends TopComponent {
    constructor() {
        super('div', {'class': 'game'});
        this._stage = null;
        this.render();
    }

    setStage(stage) {
        this._stage = stage;
        this._rerender();
    }

    render() {
        if (this._stage) {
            this.append(this._stage.render());
        }
        this.renderTo('content');
    }

    destroy() {
        this._stage = null;
        this.remove();
    }

    _rerender() {
        this.clear();
        this.render();
    }
}
<commit_msg>Fix GameScene<commit_after>import TopComponent from '../../components/TopComponent/TopComponent';

export default class GameScene extends TopComponent {
    constructor() {
        super('div', {'class': 'game'});
        this._stage = null;
        this._render();
    }

    setStage(stage) {
        this._stage = stage;
        this._rerender();
    }

    destroy() {
        this._stage = null;
        this.remove();
    }

    _render() {
        if (this._stage) {
            this.append(this._stage.render());
        }
        this.renderTo('content');
    }

    _rerender() {
        this.clear();
        this._render();
    }
}
<|endoftext|>