text:
namespace ash {
namespace {

// Shelf item tooltip height.
constexpr int kTooltipHeight = 24;

// The maximum width of the tooltip bubble.  Borrowed the value from
// ash/tooltip/tooltip_controller.cc
constexpr int kTooltipMaxWidth = 250;

// Shelf item tooltip internal text margins.
constexpr int kTooltipTopBottomMargin = 4;
constexpr int kTooltipLeftRightMargin = 8;

// The offset for the tooltip bubble - making sure that the bubble is spaced
// with a fixed gap. The gap is accounted for by the transparent arrow in the
// bubble and an additional 1px padding for the shelf item views.
constexpr int kArrowTopBottomOffset = 1;
constexpr int kArrowLeftRightOffset = 1;

// Padding used to position the tooltip relative to the shelf.
constexpr int kTooltipPaddingHorizontalBottom = 6;

}  // namespace

ShelfTooltipBubble::ShelfTooltipBubble(views::View* anchor,
                                       ShelfAlignment alignment,
                                       SkColor background_color,
                                       const base::string16& text)
    : ShelfBubble(anchor, alignment, background_color) {
  set_margins(gfx::Insets(kTooltipTopBottomMargin, kTooltipLeftRightMargin));
  set_close_on_deactivate(false);
  SetCanActivate(false);
  set_accept_events(false);
  set_shadow(views::BubbleBorder::NO_ASSETS);
  SetLayoutManager(std::make_unique<views::FillLayout>());
  views::Label* label = new views::Label(text);
  label->SetHorizontalAlignment(gfx::ALIGN_LEFT);
  const SkColor tooltip_background = SkColorSetA(gfx::kGoogleGrey900, 0xE6);
  const SkColor tooltip_text = SkColorSetA(gfx::kGoogleGrey200, 0xFF);
  set_color(tooltip_background);
  label->SetEnabledColor(tooltip_text);
  label->SetBackgroundColor(tooltip_background);
  AddChildView(label);

  gfx::Insets insets(kArrowTopBottomOffset, kArrowLeftRightOffset);
  // Adjust the anchor location for asymmetrical borders of shelf item.
  if (anchor->border())
    insets += anchor->border()->GetInsets();
  insets += gfx::Insets(-kTooltipPaddingHorizontalBottom);
  set_anchor_view_insets(insets);

  CreateBubble();
  CollisionDetectionUtils::IgnoreWindowForCollisionDetection(
      GetWidget()->GetNativeWindow());
}

gfx::Size ShelfTooltipBubble::CalculatePreferredSize() const {
  const gfx::Size size = BubbleDialogDelegateView::CalculatePreferredSize();
  const int kTooltipMinHeight = kTooltipHeight - 2 * kTooltipTopBottomMargin;
  return gfx::Size(std::min(size.width(), kTooltipMaxWidth),
                   std::max(size.height(), kTooltipMinHeight));
}

bool ShelfTooltipBubble::ShouldCloseOnPressDown() {
  // Let the manager close us.
  return true;
}

bool ShelfTooltipBubble::ShouldCloseOnMouseExit() {
  return true;
}

}  // namespace ash


text:
/*
 * CHANGE LOG: VERSION 0.3.0 ALPHA 3:
 * ====================================
 *
 *  - Added automatic 'SI/binary prefix' option for k, M, G, etc...
 *
 *  - Added SI/binary prefix support for gauge auto-ranging.
 *
 *  - Added auto-update off CSS from jGauge size settings.
 *
 *  - Added label and ticks.label color setting.
 *
 *  - Fixed findUpperLimit bug (not rounding value up).
 *
 *  - Fixed tick values and needle position when tick.start isn't 0 (zero).
 *
 *  - Fixed needle z-index issue.
 *
 *  - jGauge internals are more object oriented.
 *
 *  - All spelling for functions, vars, etc. changed to American-English from
 *    Australian-English. This is to follow the general code standards and
 *    avoid confusion.
 *
 * CHANGE LOG: VERSION 0.3.0 ALPHA 2:
 * ====================================
 *
 *  - Angles now referenced with 0deg to the right (not to the top). This is the
 *    more common standard.
 *
 *  - Defined 'jG' as base state for 'this' making code simpler and improving
 *    readability.
 *
 *  - Fixed canvas element sizing. Now done through DOM, not CSS which never
 *    worked. This was only noticeable in gauges larger than 300x150 (the canvas
 *    element's default size).
 *    See: http://www.whatwg.org/specs/web-apps/current-work/#the-canvas-element
 *
 *  - All offsets now relative to gauge center point (not upper left corner).
 *    This has made positioning elements more intuative for a dial/circle gauge.
 *
 *  - Finished the .updateRange() function.
 *
 *  - Created the .resetLayers() function to tidy up after gauge changes that
 *    would otherwise bring the modified layer to front causing design problems.
 *
 *  - Consolidated number precision operations into a new .numberPrecision()
 *    function to eliminate code doubling-up.
 *
 *  - The .findUpperLimit() function has been simplified and now allows for a
 *    'multiple' to be specified to round up to.
 *
 *  - Made use of the .getHiddenDimensions() plugin to correctly layout label
 *    elements during initialisation even if the jGauge (or parent) is hidden.
 *
 *  - Various other code tweaks.
 *
 * KNOWN ISSUES:
 * =============
 *
 *  - Canvas not working in Internet Explorer (ticks and range) despite
 *    excanvas.min.js.
 *
 *  - Updating range after initialisation renders arc as black 100% opacity
 *    I've seen this behaviour in Chrome 7.0 and Safari.
 *
 *  - The limitAction only works for the upper bounds, not lower bounds.
 *
 *  - Upon first load (not cached) and using .setValue() for the first time
 *    after .initialize(), the needle animates from 0deg (right-side), not from
 *    the .tickStart value (usually left-side) as it should.
 *
 */

// Global vars...

// Expose the Limit Action Enum globally...
var limitAction =
{
        spin: 0,
        clamp: 1,
        autoRange: 2
};

var autoPrefix =
{
        none: 0, // No SI or binary prefixing, normal comma segmented number.
        si: 1, // SI prefixing (i.e. 1000^n) used for SI units / metric.
        binary: 2 // Binary prefixing (i.e. 1024^n) used for computer units.
};

function jGauge()
{
        // Define var of current 'this' state (helps prevent 'this' abuse).
        var jG = this;

        jG.version = '0.3.0.3'; // Major, minor, fix, release.

        jG.centerX = 0; // Internal use for positioning elements.
        jG.centerY = 0; // Internal use for positioning elements.

        // DEFAULT PARAMETERS FOR jGAUGE...
        jG.id = ''; // Default: nothing. Must be unique per jGauge instance.
        jG.segmentStart = -200; // Relative to 0deg (3-o-clock position).
        jG.segmentEnd = 20; // Relative to 0deg (3-o-clock position).
        jG.imagePath = 'images/jgauge_face_default.png'; // Background image path.
        jG.width = 160; // Total width of jGauge.
        jG.height = 114; // Total height of jGauge.
        jG.showAlerts = false; // Show error alerts? Useful when debugging.

        jG.autoPrefix = autoPrefix.si; // Automatically assigns prefix on label when approapriate (after value, before suffix) i.e. k, M, G, etc.

        jG.siPrefixes = ['', 'k', 'M', 'G', 'T', 'P', 'E', 'Z', 'Y'];
        jG.binaryPrefixes = jG.siPrefixes;

        // Define the jGauge.needle object...
        function needle()
        {
                var ndl = this;
                ndl.imagePath = 'images/jgauge_needle_default.png'; // Needle image path.
                ndl.limitAction = limitAction.autoRange; // What to do when the needle hits the limit.
                ndl.xOffset = 0; // Shift needle position horizontally from center.
                ndl.yOffset = 24; // Shift needle position vertically from center.
        }

        // Add the needle object to the jGauge object.
        jG.needle = new needle();

        // Define the jGauge.label object...
        function label()
        {
                var lbl = this;
                lbl.color = '#144b66'; // Text color applied as CSS.
                lbl.precision = 1; // Value label rounding decimal places.
                lbl.prefix = ''; // Prefix for the value label (i.e. '$').
                lbl.suffix = ''; // Suffic for the value label (i.e. '°C')
                lbl.xOffset = 0; // Shift label horizontally from center.
                lbl.yOffset = 20; // Shift label vertically from center.
        }

        // Add the label object to the jGauge object.
        jG.label = new label();

        // Define the jGauge.label object...
        function ticks()
        {
                var tks = this;
                tks.count = 11; // Number of tick marks around the gauge face.
                tks.start = 0; // Value of the first tick mark.
                tks.end = 10; // Value of the last tick mark.
                tks.color = 'rgba(255, 255, 255, 1)'; // Tick mark color.
                tks.thickness = 3; // Tick mark thickness.
                tks.radius = 76; // Tick mark radius (from gauge center point).
                tks.labelPrecision = 1; // Rounding decimals for tick labels.
                tks.labelRadius = 63; // Tick label radius (from gauge center).
                tks.labelColor = '#327a9e'; // Text color applied as CSS.
        }

        // Add the ticks object to the jGauge object.
        jG.ticks = new ticks();

        function range()
        {
                var rng = this;
                rng.radius = 55; // Range arc radius (from gauge center).
                rng.thickness = 36; // Range arc thickness (spread of the arc outwards).
                rng.start = -24; // Range start point as an angle relative to 0deg (pointing right).
                rng.end = 25; // Range end point as an angle relative to 0deg (pointing right).
                rng.color = 'rgba(255, 32, 0, 0.2)'; // Color and alpha (opacity) of the range arc.
        }

        jG.range = new range();

        jG.value = 0;

        // Function calls...
        jG.init = init; // Initialises the gauge and puts it on the page.
        jG.setValue = setValue; // Sets or updates the gauge value.
        jG.getValue = getValue; // Gets the current gauge value.
        jG.updateTicks = updateTicks; // Updates the tick marks and tick labels (call after changing tick parameters).
        jG.updateRange = updateRange; // Updates the range (call after changing range parameters).
        jG.resetLayers = resetLayers; // Puts all jGauge elements in the correct order. Intended for internal use.
        jG.prefixNumber = prefixNumber; // Modifies number to SI/binary prefixing (i.e. 5000 becomes 5k).

	/**
	 * Initialises the gauge.
	 * This creates the gauge and placing it on the page ready for use.
	 * @author Darian Cabot
	 */
        function init()
        {
                var labelCssLeft;  // For horizontally positioning label.
                var labelCssTop;   // For vertically positioning label.
                var needleCssLeft; // For horizontally positioning needle.
                var neeldeCssTop;  // For vertically positioning needle.

                // Find center of the gauge for positioning reference...
                // TODO: Verify the .gaugeWidth with the placeholder DIV width (same for height).
                jG.centerX = jG.width / 2;
                jG.centerY = jG.height / 2;

                // Update gauge CSS with set jGauge dimensions.
                $('#' + jG.id).css({'width': jG.width, 'height': jG.height});

                // Wipe the slate clean in case gauge already initialized.
                $('#' + jG.id).children().remove();

                // Add the background image.
                $('#' + jG.id).css('background-image', 'url("' + jG.imagePath + '")');

                // Create the range arcs and put them on the gauge.
                jG.updateRange();

                // Create the ticks and put them on the gauge.
                jG.updateTicks();

                // Add the main label...
                htmlString = '
' +
                        jG.label.prefix + '' + jG.ticks.start +
                        '' + jG.label.suffix + '
';

                $('#' + jG.id).append(htmlString);

                // Position the main label...
                labelCssLeft = Math.round(jG.centerX - $('#' + jG.id + '-label').getHiddenDimensions().w / 2 + jG.label.xOffset) + 'px';
                labelCssTop = Math.round(jG.centerY - $('#' + jG.id + '-label').getHiddenDimensions().h / 2 + jG.label.yOffset) + 'px';
                $('#' + jG.id + '-label').css({'left': labelCssLeft, 'top': labelCssTop});

                // Apply label color...
                $('#' + jG.id + ' .label').css('color', jG.label.color);

                // Label created, so reveal it.
                $('#' + jG.id + '-label').fadeIn('slow');

                // Add the needle...
                htmlString = '';
                $('#' + jG.id).append(htmlString);

                $('#' + jG.id + '-needle').load(function() {
                        // Position needle once it's done loading...
                        needleCssLeft = Math.round(jG.centerX - ($('#' + jG.id + '-needle').getHiddenDimensions().w / 2) + jG.needle.xOffset) + 'px';
                        neeldeCssTop = Math.round(jG.centerY - ($('#' + jG.id + '-needle').getHiddenDimensions().h / 2) + jG.needle.yOffset) + 'px';
                        $('#' + jG.id + '-needle').css({'left': needleCssLeft, 'top': neeldeCssTop});
                });

                // Needle created, so reveal it.
                $('#' + jG.id + '-needle').fadeIn('slow');

                // Ensure everything's in the correct order.
                jG.resetLayers();

                // Set the needle to the lowest value.
                // This is initially run TWICE to stop an animation glitch.
                // If it's run only once, the next value will be animated from the needle in
                // the 3-o-clock position even though it should come from it's initial position.
                // I'll look into this further soon but it *may* be caused by jQueryRotate?
                jG.setValue(jG.ticks.start);
                jG.setValue(jG.ticks.start);
        }

	/**
	 * Puts all of the jGauge elements in the correct order.
	 * This is required because updating a single canvas layer was bringing
	 * that layer to top messing up the design.
	 * @author Darian Cabot
	 */
	function resetLayers()
	{
		$('#' + jG.id).css('z-index', 0);
		$('#' + jG.id + '-canvas-ranges').css('z-index', 1);
		$('#' + jG.id + '-canvas-ticks').css('z-index', 2);
		$('#' + jG.id + ' .tick-label').css('z-index', 3);
		$('#' + jG.id + '-label').css('z-index', 4);
		$('#' + jG.id + '-needle').css('z-index', 5); // This one doesn't work (overwritten by jQueryRotate??).
	}

	/**
	 * Creates the range arcs on the gauge face.
	 * @author Darian Cabot
	 */
	function updateRange()
	{
	        var canvas; // The canvas used for the range.
	        var ctx; // The 2D convas context for drawing.

		// Remove any existing ticks canvas.
		$('#' + jG.id + '-canvas-ranges').remove();

		// Create range arcs by drawing on a new canvas...
		htmlString =  '<canvas id="' + jG.id + '-canvas-ranges"></canvas>';
		$('#' + jG.id).append(htmlString);

		// Reference the canvas element we just created.
		canvas = document.getElementById(jG.id + '-canvas-ranges');

		// Resize canvas...
		canvas.width = jG.width;
		canvas.height = jG.height;

		// Make sure we don't execute when canvas isn't supported.
		if (canvas.getContext)
		{
			// Use getContext to use the canvas for drawing.
			ctx = canvas.getContext('2d');

			ctx.strokeStyle = jG.range.color;
			ctx.lineWidth = jG.range.thickness;

			ctx.beginPath();

			// The canvas arc parameters are as follows:...
			// arc(x, y, radius, startAngle, endAngle, anticlockwise).
			ctx.arc(jG.centerX + jG.needle.xOffset,
				jG.centerY + jG.needle.yOffset,
				jG.range.radius,
				(Math.PI / 180) * jG.range.start,
				(Math.PI / 180) * jG.range.end,
				false);

			// Draw range arc on canvas.
			ctx.stroke();
			jG.resetLayers();
		}
		else
		{
			// Canvas not supported!

			/* @TODO: alert() is a bit blunt, some other notification
			 * should be used instead.
			 */

			if (jG.showAlerts === true)
			{
				alert('Sorry, canvas is not supported by your browser!');
			}
		}
	}

	/**
	 * Creates the tick marks and labels on the gauge face.
	 * @author Darian Cabot
	 */
	function updateTicks()
	{
		var gaugeSegmentStep;
		var htmlString;
		var canvas;
		var ctx;
		var startAngle;
		var endAngle;
		var tickStep;

                var leftOffset;
                var topOffset;
                var tickLabelCssLeft;
                var tickLabelCssTop;

		// FIRST: Draw ticks on gauge...

		// Remove any existing ticks canvas.
		$('#' + jG.id + '-canvas-ticks').remove();

		// Check if there is actually anything to draw...
		if (jG.ticks.count !== 0 || jG.ticks.thickness !== 0)
		{
			// Create ticks by drawing on a canvas...
			htmlString = '<canvas id="' + jG.id + '-canvas-ticks"></canvas>';
			$('#' + jG.id).append(htmlString);

			// Reference the canvas element we just created.
			canvas = document.getElementById(jG.id + '-canvas-ticks');

			// Resize canvas...
			canvas.width = jG.width;
			canvas.height = jG.height;

			// Make sure we don't execute when canvas isn't supported
			if (canvas.getContext)
			{
				// use getContext to use the canvas for drawing
				ctx = canvas.getContext('2d');

				// Draw ticks
				gaugeSegmentStep = Math.abs(jG.segmentStart - jG.segmentEnd) / (jG.ticks.count - 1);
				ctx.strokeStyle = jG.ticks.color;
				ctx.lineWidth = 5;

				for (i = 0; i <= jG.ticks.count - 1; i ++)
				{
					startAngle = (Math.PI / 180) * (jG.segmentStart + (gaugeSegmentStep * i) - (jG.ticks.thickness / 2));
					endAngle = (Math.PI / 180) * (jG.segmentStart + (gaugeSegmentStep * i) + (jG.ticks.thickness / 2));

					ctx.beginPath();

					ctx.arc(jG.centerX + jG.needle.xOffset,
						jG.centerY + jG.needle.yOffset,
						jG.ticks.radius,
						startAngle,
						endAngle,
						false);

					ctx.stroke();
				}
				jG.resetLayers();
			}
			else
			{
				// Canvas not supported!

				/* @TODO: alert() is a bit blunt, some other notification
				 * should be used instead.
				 */

				if (jG.showAlerts === true)
				{
					alert('Sorry, canvas is not supported by your browser!');
				}
			}
		}

		// THIRD: Place tick labels on gauge...

		// Remove the existing tick labels.
		$('#' + jG.id + ' .tick-label').remove();

		// Check if there is actually anything to draw...
		if (jG.tickCount !== 0)
		{
			// Calculate the step value between each tick.
			tickStep = (jG.ticks.end - jG.ticks.start) / (jG.ticks.count - 1);
			gaugeSegmentStep = Math.abs(jG.segmentStart - jG.segmentEnd) / (jG.ticks.count - 1);

			for (i = 0; i <= jG.ticks.count - 1; i ++)
			{
				// Calculate the tick value, round it, stick it in html...
				//var htmlString = '
' + addCommas(numberPrecision((i * tickStep), jG.ticks.labelPrecision)) + '
';
				htmlString = '
' + prefixNumber(jG.ticks.start + i * tickStep, false) + '
';

				// Add the tick label...
				$('#' + jG.id).append(htmlString);

				// Calculate the position of the tick label...
				leftOffset = jG.centerX + jG.needle.xOffset - $('#' + jG.id + ' .tick-label').getHiddenDimensions().w / 2;
				topOffset = jG.centerY + jG.needle.yOffset - $('#' + jG.id + ' .tick-label').getHiddenDimensions().h / 2;
				tickLabelCssLeft = Math.round((jG.ticks.labelRadius * Math.cos((jG.segmentStart + (i * gaugeSegmentStep)) * Math.PI / 180)) + leftOffset) + 'px';
				tickLabelCssTop = Math.round(jG.ticks.labelRadius * Math.sin(Math.PI / 180 * (jG.segmentStart + (i * gaugeSegmentStep))) + topOffset) + 'px';

				$('#' + jG.id + ' p:last').css({'left': tickLabelCssLeft, 'top': tickLabelCssTop});
			}

                        // Apply label color...
                        $('#' + jG.id + ' .tick-label').css('color', jG.ticks.labelColor);

			// Tick labels are all created, so reveal them together.
			$('#' + jG.id + ' .tick-label').fadeIn('slow');
		}
	}

	/**
	 * Changes the gauge value (needle and read-out label).
	 * The gauge must be initialized with createGauge() before this is called.
	 * @author Darian Cabot
	 * @param {Number} newValue The new value for the gauge.
	 */
	function setValue(newValue)
	{
	        var degreesMult;
	        var valueDegrees;
	        var htmlString;
	        var needleCssLeft;
	        var needleCssTop;

		// First set the internal value variable (so we can return if required).
		jG.value = newValue;

		// Scale the 'value' to 'degrees' around the gauge.
		degreesMult = (jG.segmentEnd - jG.segmentStart) / (jG.ticks.end - jG.ticks.start);
		valueDegrees = degreesMult * (newValue - jG.ticks.start);

		// Check the needle is in bounds...
		// TODO: This is only checking the upper limit, we should also be checking the lower limit.
		if (valueDegrees > Math.abs(jG.segmentStart - jG.segmentEnd))
		{
			if (jG.needle.limitAction === limitAction.autoRange)
			{
                                jG.ticks.end = findUpperLimit(newValue, 10);
                                jG.updateTicks();
                                // TODO: update range also (range should be set with gauge values, not degress).

                                // Scale the 'value' to 'degrees' around the gauge AGAIN.
                                valueDegrees = newValue * (jG.segmentEnd - jG.segmentStart) / (jG.ticks.end - jG.ticks.start);
			}
			else if (jG.needle.limitAction === limitAction.clamp)
			{
                                // Clamp needle to gauge limit (stops the needle spinning).
                                valueDegrees = Math.abs(jG.segmentStart - jG.segmentEnd);

                                // Shake the needle to simulate bouncing off the limit...
                                // TODO: wait until needle finished moving before 'bouncing'.
                                $('#' + jG.id + '-needle')
                                        .animate({ top: '+=2', left: '-=2' }, 50)
                                        .animate({ top: '-=2', left: '+=2' }, 50)
                                        .animate({ top: '+=2', left: '-=2' }, 50)
                                        .animate({ top: '-=2', left: '+=2' }, 50);
			}
		}

		// Rotate the needle...
		$('#' + jG.id + '-needle').rotateAnimation(jG.segmentStart + valueDegrees);
		$('#' + jG.id + '-needle').css('position', 'absolute'); // This *MUST* be set after image-rotation!

		// Reposition needle (sometimes the needle moves off axis - witnessed in Firefox 3.6)...
		needleCssLeft = Math.round(jG.centerX - $('#' + jG.id + '-needle').width() / 2 + jG.needle.xOffset) + 'px';
		needleCssTop = Math.round(jG.centerY - $('#' + jG.id + '-needle').height() / 2 + jG.needle.yOffset) + 'px';
		$('#' + jG.id + '-needle').css({'left': needleCssLeft, 'top': needleCssTop});

		// Build the label string (and apply any SI / binary prefix)...
		htmlString = prefixNumber(newValue, true);

		// Update label value...
		$('#' + jG.id + '-label').html(htmlString);
	}

	/**
	 * Gets the gauge value.
	 * @returns The current gauge value.
	 * @type Number
	 */
	function getValue()
	{
		return this.value;
	}

	/**
	 * Returns a SI / binary prefixed string from a number.
	 * @author Darian Cabot
	 * @param {Number} value A number to be rounded.
	 * @param {Boolean} formatting Whether to include prefix/suffix and bold value (usually true for gauge label and false for tick labels).
	 * @returns the SI/binary prefixed number as a string (i.e. 2500 becomes 2.5k).
	 * @type String
	 */
	function prefixNumber(value, formatting)
	{
		var power = 0;
		var prefix = '';

		switch (jG.autoPrefix)
		{
			case autoPrefix.si:

				while (value >= 1000)
				{
					power ++;
					value /= 1000;
				}

				prefix = jG.siPrefixes[power];

				break;

			case autoPrefix.binary:

				while (value >= 1024)
				{
					power ++;
					value /= 1024;
				}

				prefix = jG.binaryPrefixes[power];

				break;
		}

		// Build the label string (and apply any SI / binary prefix)...
		if (formatting === true)
		{
			return jG.label.prefix + '' + addCommas(numberPrecision(value, jG.label.precision)) + ' ' + prefix + jG.label.suffix;
		}
		else
		{
			return addCommas(numberPrecision(value, jG.label.precision)) + prefix;
		}
	}

	/**
	 * Returns an upper limit (range) based on the value and multiple.
	 * It rounds the value up the the closest multiple.
	 * TODO: Factor in the number of ticks and avoid wierd decimal values for ticks.
	 * @author Darian Cabot
	 * @param {Number} value The gauge value that the range is to be suited to.
	 * @param {Number} multiple The multiple to round up to.
	 * @returns the closest multiple above the value.
	 * @type Number
	 */
	function findUpperLimit(value, multiple)
	{

		//return Math.ceil(Math.ceil(value) / multiple) * multiple; // Old method (prior to SI/binary prefixing).

		var power = 0;
		var bump = 0;

		if (jG.autoPrefix === autoPrefix.binary)
		{
			// Special case for binary mode...

			while (value >= 2)
			{
				power ++;
				value /= 2;
			}

			return Math.pow(2, power + 1);
		}
		else
		{
			multiple /= 10;

			while (value >= 10)
			{
				power ++;
				value /= 10;
			}

			while (value > bump)
			{
				bump += multiple;
			}

			// parseInt is used to ensure there aren't any wierd float decimals (i.e. 4.999~ instead of 5).
			return parseInt(bump * Math.pow(10, power), 10);
		}
	}

}

// Helper functions...

/**
 * Returns a rounded number to the precision specified.
 * @author Darian Cabot
 * @param {Number} value A number to be rounded.
 * @param {Number} decimals The number of decimal places to round to.
 * @returns the value rounded to the number of decimal places specified.
 * @type Number
 */
numberPrecision = function(value, decimals)
{
	return Math.round(value * Math.pow(10, decimals)) / Math.pow(10, decimals);
};

/**
 * Formats a numeric string by adding commas for cosmetic purposes.
 * @author Keith Jenci
 * @see http://www.mredkj.com/javascript/nfbasic.html
 * @param {String} nStr A number with or without decimals.
 * @returns a nicely formatted number.
 * @type String
 */
addCommas = function(nStr)
{
	nStr += '';
	var x = nStr.split('.');
	var x1 = x[0];
	var x2 = x.length > 1 ? '.' + x[1] : '';
	var rgx = /(\d+)(\d{3})/;

	while (rgx.test(x1))
	{
		x1 = x1.replace(rgx, '$1' + ',' + '$2');
	}

	return x1 + x2;
};

(function($)
{
	$.fn.getHiddenDimensions = function(boolOuter)
	{
		var $item = this;
		var props = { position: 'absolute', visibility: 'hidden', display: 'block' };
		var dim = { 'w':0, 'h':0 };
		var $hiddenParents = $item.parents().andSelf().not(':visible');

		var oldProps = [];
		$hiddenParents.each(function()
		{
			var old = {};

			for (var name in props)
			{
				old[ name ] = this.style[ name ];
				this.style[ name ] = props[ name ];
			}

			oldProps.push(old);
		});

		if (!false === boolOuter)
		{
			dim.w = $item.outerWidth();
			dim.h = $item.outerHeight();
		}
		else
		{
			dim.w = $item.width();
			dim.h = $item.height();
		}

		$hiddenParents.each(function(i)
		{
			var old = oldProps[i];
			for (var name in props)
			{
				this.style[ name ] = old[ name ];
			}
		});

		return dim;
	};
}(jQuery));

redpajama_set_name: RedPajamaGithub


text:
package com.mytian.lb;

import android.app.Activity;
import android.app.Application;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.pm.ApplicationInfo;
import android.net.ConnectivityManager;

import com.core.enums.ConfigKeyEnum;
import com.core.manager.ConfigManager;
import com.core.util.FileDataHelper;
import com.core.util.NetworkUtil;
import com.core.util.NetworkUtil.NetworkClassEnum;
import com.core.util.ProcessUtil;
import com.dao.DaoMaster;
import com.dao.DaoMaster.OpenHelper;
import com.dao.DaoSession;
import com.dao.Parent;
import com.dao.ParentDao;
import com.debug.StrictModeWrapper;
import com.google.android.gms.analytics.GoogleAnalytics;
import com.google.android.gms.analytics.Tracker;
import com.mytian.lb.activity.LoginActivity;
import com.mytian.lb.activityexpand.activity.AnimatedRectLayout;
import com.mytian.lb.bean.user.UserResult;
import com.mytian.lb.helper.SharedPreferencesHelper;
import com.mytian.lb.manager.ActivityManager;
import com.mytian.lb.manager.ShareManager;
import com.mytian.lb.manager.UserActionDOManager;
import com.mytian.lb.push.PushHelper;
import com.orhanobut.logger.LogLevel;
import com.orhanobut.logger.Logger;
import com.squareup.leakcanary.LeakCanary;
import com.squareup.leakcanary.RefWatcher;

import java.util.List;

import im.fir.sdk.FIR;

/**
 * App运行时上下文.
 * <p/>
 * 约定: 1)Constant类里保存系统安装之后就一直保持不变的常量;
 * 2)App类里保存系统启动后可变的变量,变量的值一般在系统初始化时保存,和状态相关的量在过程中可变;
 * 3)SharedPeferences对象持久化App里部分的变量, 供App初始化时读取, 其他类统一读取App里的变量,
 * 不访问SharedPerferences, 如果以后更换持久化的方式,例如DB,则仅修改App类就可以.
 *
 * @author bin.teng
 */
public class App extends Application {

    private Tracker mTracker;

    private static final String TAG = App.class.getSimpleName();

    public ActivityManager activityManager = null;

    private Activity currentActivity;

    private static App instance;

    private static DaoMaster daoMaster;

    private static DaoSession daoSession;

    private BroadcastReceiver connectionReceiver;

    private UserResult userResult;

    private String cookie;

    private boolean isNoAccount;

    private String appoint_time;

    private RefWatcher refWatcher;

    public static RefWatcher getRefWatcher(Context context) {
        App application = (App) context.getApplicationContext();
        return application.refWatcher;
    }

    public String getAppoint_time() {
        return appoint_time;
    }

    public void setAppoint_time(String appoint_time) {
        this.appoint_time = appoint_time;
    }

    public Activity getCurrentActivity() {
        return currentActivity;
    }

    public void setCurrentActivity(Activity currentActivity) {
        this.currentActivity = currentActivity;
    }

    public String getCookie() {
        return cookie;
    }

    public void setCookie(String cookie) {
        this.cookie = cookie;
    }

    public UserResult getUserResult() {
        return userResult;
    }

    public void setUserResult(UserResult userResult) {
        this.userResult = userResult;
    }

    public boolean isNoAccount() {
        return isNoAccount;
    }

    public void setIsNoAccount(boolean isNoAccount) {
        this.isNoAccount = isNoAccount;
    }

    /**
     * 获得本类的一个实例
     */
    public static App getInstance() {
        return instance;
    }

    /**
     * 取得DaoMaster
     */
    public static DaoMaster getDaoMaster() {
        if (daoMaster == null) {
            OpenHelper helper = new DaoMaster.DevOpenHelper(App.getInstance(), Constant.DB_NAME, null);
            daoMaster = new DaoMaster(helper.getWritableDatabase());
        }
        return daoMaster;
    }

    /**
     * 取得DaoSession
     */
    public static DaoSession getDaoSession() {
        if (daoSession == null) {
            if (daoMaster == null) {
                daoMaster = getDaoMaster();
            }
            daoSession = daoMaster.newSession();
        }
        return daoSession;
    }

    //---------以下变量存储在APP(内存)中----------//

    /**
     * 当前网络状态
     */
    private static NetworkClassEnum currentNetworkStatus = NetworkClassEnum.UNKNOWN;

    /**
     * @return 返回当前网络状态枚举类(例如: 未知 / 2G/ 3G / 4G / wifi)
     */
    public static NetworkClassEnum getCurrentNetworkStatus() {
        return currentNetworkStatus;
    }

    /**
     * @param currentNetworkStatus 当前网络状态枚举类
     */
    public static void setCurrentNetworkStatus(NetworkClassEnum currentNetworkStatus) {
        App.currentNetworkStatus = currentNetworkStatus;
    }

    public static boolean isNetworkAvailable() {
        return !NetworkClassEnum.UNKNOWN.equals(currentNetworkStatus);
    }

    //---------以下变量由ConfigManager管理----------//

    /**
     * @return 返回硬件设备编号
     */
    public static String getDeviceId() {
        return ConfigManager.getConfigAsString(ConfigKeyEnum.DEVICE_ID);
    }

    /**
     * @return 返回手机型号
     */
    public static String getMobileType() {
        return ConfigManager.getConfigAsString(ConfigKeyEnum.MOBILE_TYPE);
    }

    /**
     * @return 返回屏幕 宽
     */
    public static int getScreenWidth() {
        return ConfigManager.getConfigAsInt(ConfigKeyEnum.SCREEN_WIDTH);
    }

    /**
     * @return 返回屏幕 高
     */
    public static int getScreenHeight() {
        return ConfigManager.getConfigAsInt(ConfigKeyEnum.SCREEN_HEIGHT);
    }

    /**
     * @return 返回APP版本名称
     */
    public static String getAppVersionName() {
        return ConfigManager.getConfigAsString(ConfigKeyEnum.APP_VERSION_NAME);
    }

    /**
     * @return 返回APP版本code
     */
    public static int getAppVersionCode() {
        return ConfigManager.getConfigAsInt(ConfigKeyEnum.APP_VERSION_CODE);
    }

    /**
     * @return 是否第一次启动(某版本)
     */
    public static boolean isFirstLunch() {
        return ConfigManager.getConfigAsBoolean(ConfigKeyEnum.IS_FIRST_LUNCH);
    }

    private static boolean strictModeAvailable;

    static {
        try {
            StrictModeWrapper.checkAvailable();
            strictModeAvailable = true;
        } catch (Throwable throwable) {
            strictModeAvailable = false;
        }
    }

    @Override
    public void onCreate() {
        super.onCreate();

        // 多进程情况只初始化一次
        if (ProcessUtil.isCurMainProcess(getApplicationContext())) {

            instance = this;

            Constant.DEBUG = BuildConfig.CONFIG_DEBUG;

            if (strictModeAvailable) {
                int applicationFlags = getApplicationInfo().flags;
                if (BuildConfig.DEBUG && ((applicationFlags & ApplicationInfo.FLAG_DEBUGGABLE) != 0)) {
                    StrictModeWrapper.enableDefaults();
                }
            }

            if (BuildConfig.CANARY_DEBUG) {
                refWatcher = LeakCanary.install(this);
            }

            FIR.init(this);

            //初始化自定义Activity管理器
            activityManager = ActivityManager.getScreenManager();

            // CHANNEL_ID 是否已经上传成功
            PushHelper.getInstance().UPLOAD_ID_SUCCESS = SharedPreferencesHelper.getBoolean(this, PushHelper.CHANNEL_STATE, false);

            // 初始化日志类,如果不是调试状态则不输出日志
            LogLevel logLevel = BuildConfig.LOG_DEBUG ? LogLevel.FULL : LogLevel.NONE;

            Logger.init("BIN.TENG")               // default PRETTYLOGGER or use just init()
                    .setMethodCount(3)            // default 2
                    .hideThreadInfo()             // default shown
                    .setMethodOffset(2)        // default 0
                    .setLogLevel(logLevel);  // default LogLevel.FULL

            Logger.v(TAG, "成功初始化LOG日志.");

            // 初始化APP相关目录
            FileDataHelper.initDirectory();
            Logger.v(TAG, "成功初始化APP相关目录.");

            //本地数据库
            initDAOData();

            // 保存当前网络状态(在每次网络通信时可能需要判断当前网络状态)
            setCurrentNetworkStatus(NetworkUtil.getCurrentNextworkState(this));
            Logger.v(TAG, "保存当前网络状态:" + getCurrentNetworkStatus());
            //注册网络状态监听广播
            newConnectionReceiver();

            //初始分享
            ShareManager.getInstance().initShare();

        }
    }

    private void initDAOData() {
        // 系统配置业务.
        ConfigManager.init(this);
        //用户信息
        initUserData();
        //用户动作
        UserActionDOManager.getInstance().init(this);
    }

    private void initUserData() {
        userResult = new UserResult();
        ParentDao parentDao = getDaoSession().getParentDao();
        List<Parent> parents = parentDao.loadAll();
        int size = parents == null ? 0 : parents.size();
        if (size > 0) {
            Parent parent = parents.get(0);
            App.getInstance().userResult.setParent(parent);
        }
    }

    //创建并注册网络状态监听广播
    private void newConnectionReceiver() {
        connectionReceiver = new BroadcastReceiver() {
            @Override
            public void onReceive(Context context, Intent intent) {
                setCurrentNetworkStatus(NetworkUtil.getCurrentNextworkState(context));
                if (PushHelper.STATE_NORMAL != PushHelper.getInstance().pushState && !PushHelper.getInstance().UPLOAD_ID_SUCCESS) {
                    PushHelper.getInstance().bindPush(getApplicationContext());
                }
            }
        };
        IntentFilter intentFilter = new IntentFilter();
        intentFilter.addAction(ConnectivityManager.CONNECTIVITY_ACTION);
        registerReceiver(connectionReceiver, intentFilter);
    }

    //销毁网络状态监听广播
    private void unConnectionReceiver() {
        if (connectionReceiver != null) {
            unregisterReceiver(connectionReceiver);
            connectionReceiver = null;
        }
    }

    //退出app
    public void exit() {
        activityManager.popAllActivityExceptOne(this.getClass());
        android.os.Process.killProcess(android.os.Process.myPid());
        System.exit(0);
    }

    /**
     * 切换帐号
     *
     * @param isCancle true 清楚数据并跳转至登录界面  false 跳转至登录界面
     */
    public void changeAccount(boolean isCancle) {
        if (isCancle) {
            ParentDao dao = getDaoSession().getParentDao();
            dao.deleteAll();
        }
        PushHelper.getInstance().clearChannelid();
        cookie = null;
        Intent intent = new Intent(currentActivity, LoginActivity.class);
        intent.putExtra("animation_type", AnimatedRectLayout.ANIMATION_WAVE_TL);
        intent.putExtra("login", isCancle);
        currentActivity.startActivity(intent);
        currentActivity.overridePendingTransition(0, 0);
    }

    @Override
    public void onTerminate() {
        unConnectionReceiver();
        super.onTerminate();
    }

    /**
     * Gets the default {@link Tracker} for this {@link Application}.
     *
     * @return tracker
     */
    synchronized public Tracker getDefaultTracker() {
        if (mTracker == null) {
            GoogleAnalytics analytics = GoogleAnalytics.getInstance(this);
            mTracker = analytics.newTracker(R.xml.global_tracker);
        }
        return mTracker;
    }
}


text:
package org.strangeforest.tcb.stats.model;

import java.util.*;

import org.strangeforest.tcb.stats.model.core.*;

import static java.lang.String.*;
import static org.strangeforest.tcb.stats.util.PercentageUtil.*;

public final class H2H {

	public static final H2H EMPTY = new H2H(0.0, 0.0);

	private final double won1;
	private final double won2;

	public H2H(WonLost wonLost) {
		this(wonLost.getWon(), wonLost.getLost());
	}

	public H2H(double won1, double won2) {
		this.won1 = won1;
		this.won2 = won2;
	}

	public H2H(int playerId1, int playerId2, List<Match> matches) {
		int won1 = 0, won2 = 0;
		for (var match : matches) {
			var winnerId = match.getWinner().getId();
			if (winnerId == playerId1)
				won1++;
			if (winnerId == playerId2)
				won2++;
		}
		this.won1 = won1;
		this.won2 = won2;
	}

	public double getWon1() {
		return won1;
	}

	public double getWon2() {
		return won2;
	}

	public double getWonPct1() {
		return pct(won1, getTotal());
	}

	public double getWonPct2() {
		return pct(won2, getTotal());
	}

	public String getWonPctStr1() {
		return formatPct(getWonPct1(), 1);
	}

	public String getWonPctStr2() {
		return formatPct(getWonPct2(), 1);
	}

	private static String formatPct(double pct, int decimals) {
		return format("%." + decimals + "f%%", pct);
	}

	public double getTotal() {
		return won1 + won2;
	}

	public boolean isEmpty() {
		return getTotal() == 0.0;
	}

	public H2H add(H2H h2h) {
		return new H2H(won1 + h2h.won1, won2 + h2h.won2);
	}

	public H2H scale(double value) {
		return new H2H(won1 * value, won2 * value);
	}
}


text:
import { UserData } from '../app/common/user-data';
import { UserSession } from '../app/common/user-session';
import { UserPermission } from '../app/common/user-permission';
import { LoginResult } from '../app/common/login-result';
import { UserAuthenticationServiceBase } from '../app/abstract/user-authentication.service.base';

export class UserAuthServiceMock implements UserAuthenticationServiceBase {

    public loginMethodSpy: jasmine.Spy;
    public loginMethodResult: LoginResult;
    public logoutMethodSpy: jasmine.Spy;
    public failLogin: boolean;
    public failLogout: boolean;

    public setupSpies(): void {
        this.loginMethodSpy = spyOn(this, 'login').and.callThrough();
        let userData = new UserData();
        userData.id = 0;
        userData.userName = "test";
        userData.displayName = "Test User";
        userData.permissions = [new UserPermission(), new UserPermission()];
        userData.permissions[0].permissionId = 1;
        userData.permissions[1].permissionId = 3;
        let userSession = new UserSession();
        userSession.id = 0;
        userSession.token = "Token";
        userSession.tokenExpiration = new Date(Date.now());
        let loginResult = new LoginResult();
        loginResult.userData = userData;
        loginResult.userSession = userSession;
        this.loginMethodResult = loginResult;
        this.logoutMethodSpy = spyOn(this, 'logout').and.callThrough();
    }

    public login(userName: string, password: string): Promise<LoginResult> {
        return new Promise<LoginResult>((resolve, reject) => {
            if (this.failLogin) {
                reject('Invalid username or password');
            }
            else {
                resolve(this.loginMethodResult);
            }
        });
    }

    public logout(token: string): Promise<void> {
        return new Promise<void>((resolve, reject) => {
            if (this.failLogout) {
                reject('Logout failed');
            }
            else {
                resolve();
            }
        });
    }
}


text:
<?php defined('SYSPATH') OR die('No direct access allowed.');

class Kohana_Lieux_MySQL extends Lieux {

    /**
     * Fetches all the contents of a database table.
     *
     * @param    string   database table
     * @return   array    database table
     */
    protected function _fetch_all($table)
    {
        return DB::select()->from($table)->execute()->as_array();
    }

} // End Kohana_Lieux_MySQL


text:
/*
 * MIT License
 *
 * Copyright (c) 2016 Warren Fan
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in all
 * copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
 * SOFTWARE.
 */
package me.ixfan.wechatkit.message.in;

import me.ixfan.wechatkit.WeChatKit;
import me.ixfan.wechatkit.message.in.event.*;
import org.junit.Test;

import java.io.BufferedReader;
import java.io.StringReader;

import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;

/**
 * 解析微信推送的事件消息。
 *
 * @author Warren Fan
 */
public class ParseEventFromWechatTest {
    private final String SUBSCRIBE_EVENT = "<xml><ToUserName><![CDATA[toUser]]></ToUserName><FromUserName><![CDATA[fromUser]]></FromUserName><CreateTime>123456789</CreateTime><MsgType><![CDATA[event]]></MsgType><Event><![CDATA[subscribe]]></Event></xml>";
    private final String UNSUBSCRIBE_EVENT = "<xml><ToUserName><![CDATA[toUser]]></ToUserName><FromUserName><![CDATA[fromUser]]></FromUserName><CreateTime>123456789</CreateTime><MsgType><![CDATA[event]]></MsgType><Event><![CDATA[unsubscribe]]></Event></xml>";
    private final String SCAN_CODE_THEN_FOLLOW_EVENT = "<xml><ToUserName><![CDATA[toUser]]></ToUserName><FromUserName><![CDATA[fromUser]]></FromUserName><CreateTime>123456789</CreateTime><MsgType><![CDATA[event]]></MsgType><Event><![CDATA[subscribe]]></Event><EventKey><![CDATA[qrscene_123123]]></EventKey><Ticket><![CDATA[TICKET]]></Ticket></xml>";
    private final String FOLLOWER_SCAN_CODE_EVENT = "<xml><ToUserName><![CDATA[toUser]]></ToUserName><FromUserName><![CDATA[fromUser]]></FromUserName><CreateTime>123456789</CreateTime><MsgType><![CDATA[event]]></MsgType><Event><![CDATA[SCAN]]></Event><EventKey><![CDATA[SCENE_VALUE]]></EventKey><Ticket><![CDATA[TICKET]]></Ticket></xml>";
    private final String REPORT_LOCATION_EVENT = "<xml><ToUserName><![CDATA[toUser]]></ToUserName><FromUserName><![CDATA[fromUser]]></FromUserName><CreateTime>123456789</CreateTime><MsgType><![CDATA[event]]></MsgType><Event><![CDATA[LOCATION]]></Event><Latitude>23.137466</Latitude><Longitude>113.352425</Longitude><Precision>119.385040</Precision></xml>";
    private final String MENU_CLICK_EVENT = "<xml><ToUserName><![CDATA[toUser]]></ToUserName><FromUserName><![CDATA[fromUser]]></FromUserName><CreateTime>123456789</CreateTime><MsgType><![CDATA[event]]></MsgType><Event><![CDATA[CLICK]]></Event><EventKey><![CDATA[EVENTKEY]]></EventKey></xml>";
    private final String MENU_VIEW_EVENT = "<xml><ToUserName><![CDATA[toUser]]></ToUserName><FromUserName><![CDATA[fromUser]]></FromUserName><CreateTime>123456789</CreateTime><MsgType><![CDATA[event]]></MsgType><Event><![CDATA[VIEW]]></Event><EventKey><![CDATA[www.qq.com]]></EventKey></xml>";
    WeChatKit weChatKit = WeChatKit.build("YOUR_WECHAt_ACCOUNT_ID", "YOUR_APPID", "YOUR_APP_SECRET", null);

    @Test
    public void parseSubscribeEventSuccessfully() {
        ReceivedMsg receivedMsg = weChatKit.messageManager().parseXmlMessage(SUBSCRIBE_EVENT);
        assertEquals("Get wrong <ToUserName>!", "toUser", receivedMsg.getToUserName());
        assertEquals("Get wrong <FromUserName>!", "fromUser", receivedMsg.getFromUserName());
        assertEquals("Get wrong <CreateTime>!", 123456789L, receivedMsg.getCreateTime().longValue());
        assertEquals("Get wrong <MsgType>!", InMessageType.EVENT.stringValue(), receivedMsg.getMsgType());
        assertTrue(receivedMsg instanceof EventMsg);
        assertTrue(receivedMsg instanceof SubscribeEvent);
        SubscribeEvent subscribeEvent = (SubscribeEvent) receivedMsg;
        assertEquals("Get wrong <Event>!", EventType.SUBSCRIBE.stringValue(), subscribeEvent.getEvent());
    }

    @Test
    public void parseUnsubscribeEventSuccessfully() {
        ReceivedMsg receivedMsg = weChatKit.messageManager().parseXmlMessage(UNSUBSCRIBE_EVENT);
        assertEquals("Get wrong <ToUserName>!", "toUser", receivedMsg.getToUserName());
        assertEquals("Get wrong <FromUserName>!", "fromUser", receivedMsg.getFromUserName());
        assertEquals("Get wrong <CreateTime>!", 123456789L, receivedMsg.getCreateTime().longValue());
        assertEquals("Get wrong <MsgType>!", InMessageType.EVENT.stringValue(), receivedMsg.getMsgType());
        assertTrue(receivedMsg instanceof EventMsg);
        assertTrue(receivedMsg instanceof UnsubscribeEvent);
        UnsubscribeEvent unsubscribeEvent = (UnsubscribeEvent) receivedMsg;
        assertEquals("Get wrong <Event>!", EventType.UNSUBSCRIBE.stringValue(), unsubscribeEvent.getEvent());
    }

    @Test
    public void parseScanCodeAndFollowEventSuccessfully() {
        ReceivedMsg receivedMsg = weChatKit.messageManager().parseXmlMessage(SCAN_CODE_THEN_FOLLOW_EVENT);
        assertEquals("Get wrong <ToUserName>!", "toUser", receivedMsg.getToUserName());
        assertEquals("Get wrong <FromUserName>!", "fromUser", receivedMsg.getFromUserName());
        assertEquals("Get wrong <CreateTime>!", 123456789L, receivedMsg.getCreateTime().longValue());
        assertEquals("Get wrong <MsgType>!", InMessageType.EVENT.stringValue(), receivedMsg.getMsgType());
        assertTrue(receivedMsg instanceof EventMsg);
        assertTrue(receivedMsg instanceof SubscribeEvent);
        SubscribeEvent subscribeEvent  = (SubscribeEvent) receivedMsg;
        assertEquals("Get wrong <Event>!", EventType.SUBSCRIBE.stringValue(), subscribeEvent.getEvent());
        assertEquals("Get wrong <EventKey>!", "qrscene_123123", subscribeEvent.getEventKey());
        assertEquals("Get wrong <Ticket>!", "TICKET", subscribeEvent.getTicket());
    }

    @Test
    public void parseFollowerScanCodeEventSuccessfully() {
        ReceivedMsg receivedMsg = weChatKit.messageManager().parseXmlMessage(FOLLOWER_SCAN_CODE_EVENT);
        assertEquals("Get wrong <ToUserName>!", "toUser", receivedMsg.getToUserName());
        assertEquals("Get wrong <FromUserName>!", "fromUser", receivedMsg.getFromUserName());
        assertEquals("Get wrong <CreateTime>!", 123456789L, receivedMsg.getCreateTime().longValue());
        assertEquals("Get wrong <MsgType>!", InMessageType.EVENT.stringValue(), receivedMsg.getMsgType());
        assertTrue(receivedMsg instanceof EventMsg);
        assertTrue(receivedMsg instanceof QrSceneEvent);
        QrSceneEvent qrSceneEvent = (QrSceneEvent) receivedMsg;
        assertEquals("Get wrong <Event>!", EventType.SCAN.stringValue(), qrSceneEvent.getEvent());
        assertEquals("Get wrong <EventKey>!", "SCENE_VALUE", qrSceneEvent.getEventKey());
        assertEquals("Get wrong <Ticket>!", "TICKET", qrSceneEvent.getTicket());
    }

    @Test
    public void parseLocationReportEventSuccessfully() {
        ReceivedMsg receivedMsg = weChatKit.messageManager().parseXmlMessage(REPORT_LOCATION_EVENT);
        assertEquals("Get wrong <ToUserName>!", "toUser", receivedMsg.getToUserName());
        assertEquals("Get wrong <FromUserName>!", "fromUser", receivedMsg.getFromUserName());
        assertEquals("Get wrong <CreateTime>!", 123456789L, receivedMsg.getCreateTime().longValue());
        assertEquals("Get wrong <MsgType>!", InMessageType.EVENT.stringValue(), receivedMsg.getMsgType());
        assertTrue(receivedMsg instanceof EventMsg);
        assertTrue(receivedMsg instanceof LocationEvent);
        LocationEvent locationEvent = (LocationEvent) receivedMsg;
        assertEquals("Get wrong <Event>!", EventType.LOCATION.stringValue(), locationEvent.getEvent());
        assertEquals("Get wrong <Latitude>!", 23.137466D, locationEvent.getLatitude(), 0D);
        assertEquals("Get wrong <Longitude>!", 113.352425D, locationEvent.getLongitude(), 0D);
        assertEquals("Get wrong <Precision>!", 119.385040D, locationEvent.getPrecision(), 0D);
    }

    @Test
    public void parseMenuClickEventSuccessfully() {
        ReceivedMsg receivedMsg = weChatKit.messageManager().parseXmlMessage(MENU_CLICK_EVENT);
        assertEquals("Get wrong <ToUserName>!", "toUser", receivedMsg.getToUserName());
        assertEquals("Get wrong <FromUserName>!", "fromUser", receivedMsg.getFromUserName());
        assertEquals("Get wrong <CreateTime>!", 123456789L, receivedMsg.getCreateTime().longValue());
        assertEquals("Get wrong <MsgType>!", InMessageType.EVENT.stringValue(), receivedMsg.getMsgType());
        assertTrue(receivedMsg instanceof EventMsg);
        assertTrue(receivedMsg instanceof MenuClickEvent);
        MenuClickEvent menuClickEvent = (MenuClickEvent) receivedMsg;
        assertEquals("Get wrong <Event>!", EventType.MENU_CLICK.stringValue(), menuClickEvent.getEvent());
        assertEquals("Get wrong <EventKey>!", "EVENTKEY", menuClickEvent.getEventKey());
    }

    @Test
    public void parseMenuViewEventSuccessfully() {
        ReceivedMsg receivedMsg = weChatKit.messageManager().parseXmlMessage(MENU_VIEW_EVENT);
        assertEquals("Get wrong <ToUserName>!", "toUser", receivedMsg.getToUserName());
        assertEquals("Get wrong <FromUserName>!", "fromUser", receivedMsg.getFromUserName());
        assertEquals("Get wrong <CreateTime>!", 123456789L, receivedMsg.getCreateTime().longValue());
        assertEquals("Get wrong <MsgType>!", InMessageType.EVENT.stringValue(), receivedMsg.getMsgType());
        assertTrue(receivedMsg instanceof EventMsg);
        assertTrue(receivedMsg instanceof MenuViewEvent);
        MenuViewEvent menuViewEvent = (MenuViewEvent) receivedMsg;
        assertEquals("Get wrong <Event>!", EventType.MENU_VIEW.stringValue(), menuViewEvent.getEvent());
        assertEquals("Get wrong <EventKey>!", "www.qq.com", menuViewEvent.getEventKey());
    }
}


text:
package com.ning.pummel.cli;

import com.google.common.collect.ImmutableMap;
import com.google.common.collect.Lists;
import org.apache.commons.math.stat.descriptive.DescriptiveStatistics;
import org.mvel.MVEL;
import org.skife.cli.Arguments;
import org.skife.cli.Command;
import org.skife.cli.Option;
import com.ning.pummel.Fight;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStreamReader;
import java.util.List;
import java.util.Map;
import java.util.concurrent.Callable;

@Command(name = "step")
public class Step implements Callable<Void>
{
    @Option(name = {"-m", "--max"}, title = "max-requests", description = "Maximum number of requests to execute")
    public int maxRequests = -1;

    @Option(name = {"-s", "--start"}, description = "initial concurrency level, defaults to 100")
    public int start = 1;

    @Option(name = "--step", title = "step-function", description = "clojure function to apply to generate next step, default is 'c + 1'")
    public String stepFunction = "c + 1";

    @Option(name = {"-l", "--labels"}, description = "Show column labels")
    public boolean labels = false;

    @Option(name = {"-L", "--limit"}, description = "concurrency limit to stop at, default is " + Integer.MAX_VALUE)
    public int limit = Integer.MAX_VALUE;

    @Option(name = {"-p", "--percentile"}, description = "Percentile to try to target, default is 99th percentile")
    public double percentile = 99.0;

    @Arguments(title = "url file", description = "input file to pull urls from, otherwise will use stdin")
    public File urlFile;

    public Void call() throws Exception
    {
        List<String> urls = Lists.newArrayList();
        final BufferedReader in;
        if (urlFile != null) {
            in = new BufferedReader(new InputStreamReader(new FileInputStream(urlFile)));
        }
        else {
            in = new BufferedReader(new InputStreamReader(System.in));
        }
        for (String line = in.readLine(); line != null; line = in.readLine()) {
            if (maxRequests >= 0) {
                if (maxRequests == 0) {
                    break;
                }
                else if (maxRequests > 0) {
                    maxRequests--;
                }
            }
            urls.add(line);
        }

        if (labels) {System.out.printf("clients\ttp%.1f\tmean\treqs/sec\n", percentile);}
        int concurrency = start;
        do {
            DescriptiveStatistics stats = new Fight(concurrency, urls).call();
            System.out.printf("%d\t%.2f\t%.2f\t%.2f\n",
                              concurrency,
                              stats.getPercentile(percentile),
                              stats.getMean(),
                              (1000 / stats.getMean()) * concurrency);
            Map<String, Integer> vals = ImmutableMap.of("c", concurrency);
            concurrency = (Integer) MVEL.eval(stepFunction, vals);
        }
        while (concurrency < limit);
        return null;
    }
}


text:
package io.github.mzmine.modules.visualization.featurelisttable_modular;

import io.github.mzmine.datamodel.features.types.modifiers.GraphicalColumType;
import io.github.mzmine.parameters.Parameter;
import io.github.mzmine.parameters.impl.SimpleParameterSet;
import io.github.mzmine.parameters.parametertypes.BooleanParameter;
import io.github.mzmine.parameters.parametertypes.datatype.DataTypeCheckListParameter;

public class FeatureTableFXParameters extends SimpleParameterSet {

  public static final DataTypeCheckListParameter showRowTypeColumns = new DataTypeCheckListParameter(
      "Row type columns",
      "Specify which data type columns shall be displayed in the feature list table");

  public static final DataTypeCheckListParameter showFeatureTypeColumns = new DataTypeCheckListParameter(
      "Feature type columns",
      "Specify which data type columns shall be displayed in the feature list table");

  public static final BooleanParameter lockImagesToAspectRatio = new BooleanParameter(
      "Lock images to aspect ratio",
      "If enabled, the width of the column will be determined by the lateral width of "
          + "the image.\nNevertheless, this options is capped to a maximum width of "
          + GraphicalColumType.MAXIMUM_GRAPHICAL_CELL_WIDTH + " pixels.", false);

  public static final BooleanParameter hideImageAxes = new BooleanParameter("Hide image axes",
      "If ticked, the axes of image plots will be hidden.", false);

  public FeatureTableFXParameters() {
    super(new Parameter[]{showRowTypeColumns, showFeatureTypeColumns, lockImagesToAspectRatio,
        hideImageAxes});
  }

}


text:
module.exports = {
  routes: {
    posts_page: {
      route_base: '/posts',
      controller: 'welcome-page-controller'
    },
    post_page: {
      route_base: '/post',
      controller: 'random-post-controller'
    },
    search_page: {
      route_base: '/search',
      controller: 'search-posts-controller'
    },
    user_page: {
      route_base: '/user',
      controller: 'user-profile-controller'
    },
    mixcloud_page: {
      route_base: '/mixcloud',
      controller: 'mixcloud-controller'
    },
  },
  index: '/posts'
}


text:
#import "NSMenu.h"

@interface NSMenu (PBXExtensions)
- (unsigned long long)insertEnabledItems:(id)arg1 atIndex:(unsigned long long)arg2;
- (void)insertItems:(id)arg1 atIndex:(unsigned long long)arg2;
- (void)addItems:(id)arg1;
@end


text:
var path = require('path');
var fs = require('fs');

module.exports = function(karma) {
  var common = require('../../tools/test/karma-common.conf.js');
  var componentPath = path.normalize(__dirname + '/../');

  var preprocessors = {};
  preprocessors[componentPath + 'text/fixtures/*.html'] = ['html2js'];

  var componentNameFile = __dirname + '/../tools/' + 'component-name.js';
  fs.writeFileSync(componentNameFile, 'window.__karmaHtmlBase__ = "base/' + path.basename(componentPath) + '/";', 'utf8');

  karma.set(common.mixin_common_opts(karma, {

    // base path, that will be used to resolve files and exclude
    basePath: '../../',

    preprocessors: preprocessors,

    // list of files / patterns to load in the browser  ORDER MATTERS
    files: [
      componentPath + 'tools/component-name.js',
      componentPath + 'tools/harness-utils.js',
      componentPath + 'tools/iframe-utils.js',
      componentPath + 'conf/mocha.conf.js',
      'appmaker/public/vendor/polymer/polymer.min.js',
      'appmaker/public/vendor/mocha/mocha.js',
      'tools/test/chai/chai.js',
      componentPath + 'test/js/tests.js',
      {pattern: 'appmaker/public/ceci/*.html', included: false},
      {pattern: 'appmaker/public/ceci/test/fixtures/*.html', included: false},
      {pattern: componentPath + 'test/**/*.js', included: false},
      {pattern: componentPath + 'test/**/*.html', included: false},
      {pattern: componentPath + '*.html', included: false},
      {pattern: componentPath + '*.js', included: false},
      {pattern: componentPath + '*.css', included: false},
      {pattern: 'tools/**/*.js', included: false},
    ]
  }));
};


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
Sydowia 12: 454 (1959)

#### Original name
Meliola meliosmae Petr.

### Remarks
null


text:
No connection

				Please set connection string in Config first.

{{mashing.name}}

{{mashing.temperature | number:1}}°C

						{{rest.name}} ({{rest.temperature}}°C / {{rest.duration}} min)

						 0"> {{rest.heating | date:'H:mm:ss'}}
						 0"> -  {{rest.active | date:'H:mm:ss'}}
						 0"> -  {{rest.completed | date:'H:mm:ss'}}

						Hysteresis: {{mashing.hysteresis | number:1}}°C

						<button ng-if="rest.status == 'WAITING_COMPLETE'" ng-click="mashingContinue()" class="submit fa fa-play-circle-o text-primary"></button>

				<button ng-click="mashingStart()"  class="submit fa fa-play-circle-o text-primary"></button>

					{{rest.name}} ({{rest.temperature}}°C / {{rest.duration}} min)

					 0"> {{rest.heating | date:'H:mm:ss'}}
					 0"> -  {{rest.active | date:'H:mm:ss'}}
					 0"> -  {{rest.completed | date:'H:mm:ss'}}


text:
//
//   Copyright 2015 Blu Age Corporation - Plano, Texas
//
//   Licensed under the Apache License, Version 2.0 (the "License");
//   you may not use this file except in compliance with the License.
//   You may obtain a copy of the License at
//
//       http://www.apache.org/licenses/LICENSE-2.0
//
//   Unless required by applicable law or agreed to in writing, software
//  distributed under the License is distributed on an "AS IS" BASIS,
//   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
//   See the License for the specific language governing permissions and
//   limitations under the License.
using System;
using System.Collections.Generic;
using Microsoft.Practices.ObjectBuilder2;
using Microsoft.Practices.Unity;

namespace Summer.Batch.Core.Unity.StepScope
{
    /// <summary>
    /// Implementation of <see cref="ResolverOverride"/> that overrides dependencies in the step scope.
    /// </summary>
    public class StepScopeOverride : ResolverOverride
    {
        private readonly IDictionary<string, StepScopeDependency> _constructorParameters;
        private readonly IDictionary<string, StepScopeDependency> _properties;
        private readonly IDictionary<Tuple<string, string>, IList<StepScopeDependency>> _methodParameters;
        private readonly IDictionary<Tuple<string, string>, int> _methodCalls = new Dictionary<Tuple<string, string>, int>();

        /// <summary>
        /// Creates a new <see cref="StepScopeOverride"/>.
        /// </summary>
        /// <param name="constructorParameters">the constructor parameter injections to override</param>
        /// <param name="properties">the properties injection to override</param>
        /// <param name="methodParameters">the method parameter injections to override</param>
        public StepScopeOverride(IDictionary<string, StepScopeDependency> constructorParameters,
                                 IDictionary<string, StepScopeDependency> properties,
                                 IDictionary<Tuple<string, string>, IList<StepScopeDependency>> methodParameters)
        {
            _constructorParameters = constructorParameters;
            _properties = properties;
            _methodParameters = methodParameters;
        }

        /// <summary>
        /// Returns a <see cref="StepScopeResolverPolicy"/> for dependencies in the step scope.
        /// </summary>
        /// <param name="context">the current build context</param>
        /// <param name="dependencyType">the type of dependency</param>
        /// <returns>a <see cref="StepScopeResolverPolicy"/> if the dependency being resolved in is step scope; null otherwise</returns>
        public override IDependencyResolverPolicy GetResolver(IBuilderContext context, Type dependencyType)
        {
            var constructorParameterOperation = context.CurrentOperation as ConstructorArgumentResolveOperation;
            StepScopeDependency dependency;
            if (constructorParameterOperation != null &&
                _constructorParameters.TryGetValue(constructorParameterOperation.ParameterName, out dependency))
            {
                return new StepScopeResolverPolicy(dependency);
            }

            var propertyValueOperation = context.CurrentOperation as ResolvingPropertyValueOperation;
            if (propertyValueOperation != null && _properties.TryGetValue(propertyValueOperation.PropertyName, out dependency))
            {
                return new StepScopeResolverPolicy(dependency);
            }

            var methodParameterOperation = context.CurrentOperation as MethodArgumentResolveOperation;
            if (methodParameterOperation != null &&
                TryGetMethodParameterDependency(
                    new Tuple<string, string>(methodParameterOperation.MethodSignature, methodParameterOperation.ParameterName),
                    out dependency))
            {
                return new StepScopeResolverPolicy(dependency);
            }

            return null;
        }

        private bool TryGetMethodParameterDependency(Tuple<string, string> key, out StepScopeDependency dependency)
        {
            int callNb;
            if (!_methodCalls.TryGetValue(key, out callNb))
            {
                callNb = 0;
            }
            var found = false;
            IList<StepScopeDependency> dependencies;
            if (_methodParameters.TryGetValue(key, out dependencies) && dependencies.Count > callNb)
            {
                found = true;
                dependency = dependencies[callNb];
            }
            else
            {
                dependency = default(StepScopeDependency);
            }
            _methodCalls[key] = callNb + 1;
            return found;
        }
    }
}


text:
/* You can add global styles to this file, and also import other style files */
@import "~@angular/material/prebuilt-themes/deeppurple-amber.css";

body {
  margin: 0;
}

.content-margin {
  margin-left: 8px;
  margin-right: 8px;
}


text:
<!doctype html>

  <title>explore</title>
  <meta http-equiv="content-type" value="text/html;utf-8">
  <link rel="stylesheet" type="text/css" href="../static/style.css">

explore

Browse an installed package

SYNOPSIS

npm.commands.explore(args, callback)

DESCRIPTION

Spawn a subshell in the directory of the installed package specified.

If a command is specified, then it is run in the subshell, which then
immediately terminates.

Note that the package is not automatically rebuilt afterwards, so be
sure to use npm rebuild <pkg> if you make any changes.

The first element in the 'args' parameter must be a package name.  After that is the optional command, which can be any number of strings. All of the strings will be combined into one, space-delimited command.

explore — npm@1.2.23


text:
node_version=0.10.26
node_name=node-v${node_version}-linux-x64
node_dir=~/jenkins/node

mkdir -p $node_dir

test -f ${node_dir}/${node_name}.tar.gz ||  wget -P $node_dir http://nodejs.org/dist/v${node_version}/${node_name}.tar.gz
test -f ${node_dir}/${node_name}/bin/node || tar -zxvf ${node_dir}/${node_name}.tar.gz  -C $node_dir

export PATH=${node_dir}/${node_name}/bin:$PATH

npm update
npm install
npm install grunt
npm install grunt-cli

export PATH=$PATH:node_modules/grunt-cli/bin/

grunt test


text:
package io.joynr.generator.versioning;

import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;

import java.util.Map;

import org.junit.Test;

import io.joynr.generator.AbstractJoynrJavaGeneratorTest;

public class GeneratorVersioningTest extends AbstractJoynrJavaGeneratorTest {

    private void expectVersioning(Map<String, String> result, String typeCollection) {
        boolean versionedStructOfTypeCollectionGenerated = false;
        for (Map.Entry<String, String> entry : result.entrySet()) {
            if (!entry.getKey().contains("/v2/")) {
                fail("File without package version found: " + entry.getKey());
            }
            if (!entry.getKey().contains("/joynr/tests/v2/")) {
                fail("File generated in wrong package: " + entry.getKey());
            }
            if (entry.getKey().contains(typeCollection + "/VersionedStruct")) {
                versionedStructOfTypeCollectionGenerated = true;
            }
        }
        assertTrue(versionedStructOfTypeCollectionGenerated);
    }

    private void expectNoVersioning(Map<String, String> result, String typeCollection) {
        boolean versionedStructOfTypeCollectionGenerated = false;
        for (Map.Entry<String, String> entry : result.entrySet()) {
            if (!entry.getKey().contains("/joynr/tests/")) {
                fail("File generated in wrong package: " + entry.getKey());
            }
            if (entry.getKey().contains("/v2/")) {
                fail("File with package version found: " + entry.getKey());
            }
            if (entry.getKey().contains(typeCollection + "/VersionedStruct")) {
                versionedStructOfTypeCollectionGenerated = true;
            }
        }
        assertTrue(versionedStructOfTypeCollectionGenerated);
    }

    @Test
    public void generateWithNoVersionComment_withoutAddVersion() throws Exception {
        final boolean generateProxy = true;
        final boolean generateProvider = true;
        final boolean packageVersioning = false;
        final boolean useComment = false;
        super.setup(generateProxy, generateProvider, packageVersioning, useComment);

        Map<String, String> result = generate("test-with-noversiongeneration-comment.fidl", true);
        expectNoVersioning(result, "NoVersionGenerationTypeCollection");
    }

    @Test
    public void generateWithoutNoVersionComment_withoutAddVersion() throws Exception {
        final boolean generateProxy = true;
        final boolean generateProvider = true;
        final boolean packageVersioning = false;
        final boolean useComment = false;
        super.setup(generateProxy, generateProvider, packageVersioning, useComment);

        Map<String, String> result = generate("test-without-noversiongeneration-comment.fidl", true);
        expectNoVersioning(result, "PackageVersionedTypeCollection");
    }

    @Test
    public void generateWithoutNoVersionComment_withAddVersion() throws Exception {
        final boolean generateProxy = true;
        final boolean generateProvider = true;
        final boolean packageVersioning = true;
        final boolean useComment = false;
        super.setup(generateProxy, generateProvider, packageVersioning, useComment);

        Map<String, String> result = generate("test-without-noversiongeneration-comment.fidl", true);
        expectVersioning(result, "PackageVersionedTypeCollection");
    }

    @Test
    public void generateWithNoVersionComment_withAddVersion() throws Exception {
        final boolean generateProxy = true;
        final boolean generateProvider = true;
        final boolean packageVersioning = true;
        final boolean useComment = false;
        super.setup(generateProxy, generateProvider, packageVersioning, useComment);

        Map<String, String> result = generate("test-with-noversiongeneration-comment.fidl", true);
        expectVersioning(result, "NoVersionGenerationTypeCollection");
    }

    @Test
    public void generateWithoutNoVersionComment_useComment() throws Exception {
        final boolean generateProxy = true;
        final boolean generateProvider = true;
        final boolean packageVersioning = false;
        final boolean useComment = true;
        super.setup(generateProxy, generateProvider, packageVersioning, useComment);

        Map<String, String> result = generate("test-without-noversiongeneration-comment.fidl", true);
        expectVersioning(result, "PackageVersionedTypeCollection");
    }

    @Test
    public void generateWithNoVersionComment_useComment() throws Exception {
        final boolean generateProxy = true;
        final boolean generateProvider = true;
        final boolean packageVersioning = true;
        final boolean useComment = true;
        super.setup(generateProxy, generateProvider, packageVersioning, useComment);

        Map<String, String> result = generate("test-with-noversiongeneration-comment.fidl", true);
        expectNoVersioning(result, "NoVersionGenerationTypeCollection");
    }
}


text:
'use strict';

angular.module('myApp.routes', ['ngRoute']);

// Declare app level module which depends on filters, and services
angular.module('myApp', ['myApp.filters', 'myApp.services', 'myApp.directives', 'myApp.routes'])
.config(['$routeProvider', '$locationProvider', function($routeProvider, $locationProvider) {
    $routeProvider.
      when('/team', {
        templateUrl: '/team/partials/users',
        controller: TeamCtrl
      }).
      otherwise({
        redirectTo: '/'
      });
    $locationProvider.html5Mode(true);
  }]);


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace DumbCrawler.Helpers
{
    public class UriDatabase : MemoryDatabase<Uri, long>
    {
        public long DistinctCount()
        {
            return base.Count();
        }

        public long TotalCount()
        {
            return base.AsQueryable().ToList().Sum(pair => pair.Value);
        }

        public IDictionary<Uri, long> Top10()
        {
            return base.AsQueryable().OrderByDescending(pair => pair.Value).Take(10).ToDictionary(pair => pair.Key, pair => pair.Value);
        }

        public IDictionary<Uri, long> Dump()
        {
            var copy = new Dictionary<Uri, long>(SoftDump());

            base.Clear();

            return copy;
        }

        public IDictionary<Uri, long> SoftDump()
        {
            var dump = base.ToDictionary();

            return dump;
        }

        public async Task Merge(IDictionary<Uri, long> urls)
        {
            await base.MergeAsync(urls, (l, l1) => l + l1);
        }
    }
}


text:
require 'active_support/values/time_zone'
require 'active_support/core_ext/object/acts_like'
require 'active_support/core_ext/date_and_time/compatibility'

module ActiveSupport
  # A Time-like class that can represent a time in any time zone. Necessary
  # because standard Ruby Time instances are limited to UTC and the
  # system's <tt>ENV['TZ']</tt> zone.
  #
  # You shouldn't ever need to create a TimeWithZone instance directly via +new+.
  # Instead use methods +local+, +parse+, +at+ and +now+ on TimeZone instances,
  # and +in_time_zone+ on Time and DateTime instances.
  #
  #   Time.zone = 'Eastern Time (US & Canada)'        # => 'Eastern Time (US & Canada)'
  #   Time.zone.local(2007, 2, 10, 15, 30, 45)        # => Sat, 10 Feb 2007 15:30:45 EST -05:00
  #   Time.zone.parse('2007-02-10 15:30:45')          # => Sat, 10 Feb 2007 15:30:45 EST -05:00
  #   Time.zone.at(1170361845)                        # => Sat, 10 Feb 2007 15:30:45 EST -05:00
  #   Time.zone.now                                   # => Sun, 18 May 2008 13:07:55 EDT -04:00
  #   Time.utc(2007, 2, 10, 20, 30, 45).in_time_zone  # => Sat, 10 Feb 2007 15:30:45 EST -05:00
  #
  # See Time and TimeZone for further documentation of these methods.
  #
  # TimeWithZone instances implement the same API as Ruby Time instances, so
  # that Time and TimeWithZone instances are interchangeable.
  #
  #   t = Time.zone.now                     # => Sun, 18 May 2008 13:27:25 EDT -04:00
  #   t.hour                                # => 13
  #   t.dst?                                # => true
  #   t.utc_offset                          # => -14400
  #   t.zone                                # => "EDT"
  #   t.to_s(:rfc822)                       # => "Sun, 18 May 2008 13:27:25 -0400"
  #   t + 1.day                             # => Mon, 19 May 2008 13:27:25 EDT -04:00
  #   t.beginning_of_year                   # => Tue, 01 Jan 2008 00:00:00 EST -05:00
  #   t > Time.utc(1999)                    # => true
  #   t.is_a?(Time)                         # => true
  #   t.is_a?(ActiveSupport::TimeWithZone)  # => true
  class TimeWithZone

    # Report class name as 'Time' to thwart type checking.
    def self.name
      'Time'
    end

    include Comparable, DateAndTime::Compatibility
    attr_reader :time_zone

    def initialize(utc_time, time_zone, local_time = nil, period = nil)
      @utc = utc_time ? transfer_time_values_to_utc_constructor(utc_time) : nil
      @time_zone, @time = time_zone, local_time
      @period = @utc ? period : get_period_and_ensure_valid_local_time(period)
    end

    # Returns a <tt>Time</tt> instance that represents the time in +time_zone+.
    def time
      @time ||= period.to_local(@utc)
    end

    # Returns a <tt>Time</tt> instance of the simultaneous time in the UTC timezone.
    def utc
      @utc ||= period.to_utc(@time)
    end
    alias_method :comparable_time, :utc
    alias_method :getgm, :utc
    alias_method :getutc, :utc
    alias_method :gmtime, :utc

    # Returns the underlying TZInfo::TimezonePeriod.
    def period
      @period ||= time_zone.period_for_utc(@utc)
    end

    # Returns the simultaneous time in <tt>Time.zone</tt>, or the specified zone.
    def in_time_zone(new_zone = ::Time.zone)
      return self if time_zone == new_zone
      utc.in_time_zone(new_zone)
    end

    # Returns a <tt>Time</tt> instance of the simultaneous time in the system timezone.
    def localtime(utc_offset = nil)
      utc.getlocal(utc_offset)
    end
    alias_method :getlocal, :localtime

    # Returns true if the current time is within Daylight Savings Time for the
    # specified time zone.
    #
    #   Time.zone = 'Eastern Time (US & Canada)'    # => 'Eastern Time (US & Canada)'
    #   Time.zone.parse("2012-5-30").dst?           # => true
    #   Time.zone.parse("2012-11-30").dst?          # => false
    def dst?
      period.dst?
    end
    alias_method :isdst, :dst?

    # Returns true if the current time zone is set to UTC.
    #
    #   Time.zone = 'UTC'                           # => 'UTC'
    #   Time.zone.now.utc?                          # => true
    #   Time.zone = 'Eastern Time (US & Canada)'    # => 'Eastern Time (US & Canada)'
    #   Time.zone.now.utc?                          # => false
    def utc?
      time_zone.name == 'UTC'
    end
    alias_method :gmt?, :utc?

    # Returns the offset from current time to UTC time in seconds.
    def utc_offset
      period.utc_total_offset
    end
    alias_method :gmt_offset, :utc_offset
    alias_method :gmtoff, :utc_offset

    # Returns a formatted string of the offset from UTC, or an alternative
    # string if the time zone is already UTC.
    #
    #   Time.zone = 'Eastern Time (US & Canada)'   # => "Eastern Time (US & Canada)"
    #   Time.zone.now.formatted_offset(true)       # => "-05:00"
    #   Time.zone.now.formatted_offset(false)      # => "-0500"
    #   Time.zone = 'UTC'                          # => "UTC"
    #   Time.zone.now.formatted_offset(true, "0")  # => "0"
    def formatted_offset(colon = true, alternate_utc_string = nil)
      utc? && alternate_utc_string || TimeZone.seconds_to_utc_offset(utc_offset, colon)
    end

    # Time uses +zone+ to display the time zone abbreviation, so we're
    # duck-typing it.
    def zone
      period.zone_identifier.to_s
    end

    def inspect
      "#{time.strftime('%a, %d %b %Y %H:%M:%S')} #{zone} #{formatted_offset}"
    end

    def xmlschema(fraction_digits = 0)
      fraction = if fraction_digits.to_i > 0
        (".%06i" % time.usec)[0, fraction_digits.to_i + 1]
      end

      "#{time.strftime("%Y-%m-%dT%H:%M:%S")}#{fraction}#{formatted_offset(true, 'Z')}"
    end
    alias_method :iso8601, :xmlschema

    # Coerces time to a string for JSON encoding. The default format is ISO 8601.
    # You can get %Y/%m/%d %H:%M:%S +offset style by setting
    # <tt>ActiveSupport::JSON::Encoding.use_standard_json_time_format</tt>
    # to +false+.
    #
    #   # With ActiveSupport::JSON::Encoding.use_standard_json_time_format = true
    #   Time.utc(2005,2,1,15,15,10).in_time_zone("Hawaii").to_json
    #   # => "2005-02-01T05:15:10.000-10:00"
    #
    #   # With ActiveSupport::JSON::Encoding.use_standard_json_time_format = false
    #   Time.utc(2005,2,1,15,15,10).in_time_zone("Hawaii").to_json
    #   # => "2005/02/01 05:15:10 -1000"
    def as_json(options = nil)
      if ActiveSupport::JSON::Encoding.use_standard_json_time_format
        xmlschema(ActiveSupport::JSON::Encoding.time_precision)
      else
        %(#{time.strftime("%Y/%m/%d %H:%M:%S")} #{formatted_offset(false)})
      end
    end

    def init_with(coder) #:nodoc:
      initialize(coder['utc'], coder['zone'], coder['time'])
    end

    def encode_with(coder) #:nodoc:
      if coder.respond_to?(:represent_object)
        coder.represent_object(nil, utc)
      else
        coder.represent_scalar(nil, utc.strftime("%Y-%m-%d %H:%M:%S.%9NZ"))
      end
    end

    # Returns a string of the object's date and time in the format used by
    # HTTP requests.
    #
    #   Time.zone.now.httpdate  # => "Tue, 01 Jan 2013 04:39:43 GMT"
    def httpdate
      utc.httpdate
    end

    # Returns a string of the object's date and time in the RFC 2822 standard
    # format.
    #
    #   Time.zone.now.rfc2822  # => "Tue, 01 Jan 2013 04:51:39 +0000"
    def rfc2822
      to_s(:rfc822)
    end
    alias_method :rfc822, :rfc2822

    # Returns a string of the object's date and time.
    # Accepts an optional <tt>format</tt>:
    # * <tt>:default</tt> - default value, mimics Ruby 1.9 Time#to_s format.
    # * <tt>:db</tt> - format outputs time in UTC :db time. See Time#to_formatted_s(:db).
    # * Any key in <tt>Time::DATE_FORMATS</tt> can be used. See active_support/core_ext/time/conversions.rb.
    def to_s(format = :default)
      if format == :db
        utc.to_s(format)
      elsif formatter = ::Time::DATE_FORMATS[format]
        formatter.respond_to?(:call) ? formatter.call(self).to_s : strftime(formatter)
      else
        "#{time.strftime("%Y-%m-%d %H:%M:%S")} #{formatted_offset(false, 'UTC')}" # mimicking Ruby 1.9 Time#to_s format
      end
    end
    alias_method :to_formatted_s, :to_s

    # Replaces <tt>%Z</tt> directive with +zone before passing to Time#strftime,
    # so that zone information is correct.
    def strftime(format)
      format = format.gsub(/((?:\A|[^%])(?:%%)*)%Z/, "\\1#{zone}")
      getlocal(utc_offset).strftime(format)
    end

    # Use the time in UTC for comparisons.
    def <=>(other)
      utc <=> other
    end

    # Returns true if the current object's time is within the specified
    # +min+ and +max+ time.
    def between?(min, max)
      utc.between?(min, max)
    end

    # Returns true if the current object's time is in the past.
    def past?
      utc.past?
    end

    # Returns true if the current object's time falls within
    # the current day.
    def today?
      time.today?
    end

    # Returns true if the current object's time is in the future.
    def future?
      utc.future?
    end

    def eql?(other)
      other.eql?(utc)
    end

    def hash
      utc.hash
    end

    def +(other)
      # If we're adding a Duration of variable length (i.e., years, months, days), move forward from #time,
      # otherwise move forward from #utc, for accuracy when moving across DST boundaries
      if duration_of_variable_length?(other)
        method_missing(:+, other)
      else
        result = utc.acts_like?(:date) ? utc.since(other) : utc + other rescue utc.since(other)
        result.in_time_zone(time_zone)
      end
    end

    def -(other)
      # If we're subtracting a Duration of variable length (i.e., years, months, days), move backwards from #time,
      # otherwise move backwards #utc, for accuracy when moving across DST boundaries
      if other.acts_like?(:time)
        to_time - other.to_time
      elsif duration_of_variable_length?(other)
        method_missing(:-, other)
      else
        result = utc.acts_like?(:date) ? utc.ago(other) : utc - other rescue utc.ago(other)
        result.in_time_zone(time_zone)
      end
    end

    def since(other)
      # If we're adding a Duration of variable length (i.e., years, months, days), move forward from #time,
      # otherwise move forward from #utc, for accuracy when moving across DST boundaries
      if duration_of_variable_length?(other)
        method_missing(:since, other)
      else
        utc.since(other).in_time_zone(time_zone)
      end
    end
    alias_method :in, :since

    def ago(other)
      since(-other)
    end

    def advance(options)
      # If we're advancing a value of variable length (i.e., years, weeks, months, days), advance from #time,
      # otherwise advance from #utc, for accuracy when moving across DST boundaries
      if options.values_at(:years, :weeks, :months, :days).any?
        method_missing(:advance, options)
      else
        utc.advance(options).in_time_zone(time_zone)
      end
    end

    %w(year mon month day mday wday yday hour min sec usec nsec to_date).each do |method_name|
      class_eval <<-EOV, __FILE__, __LINE__ + 1
        def #{method_name}    # def month
          time.#{method_name} #   time.month
        end                   # end
      EOV
    end

    def to_a
      [time.sec, time.min, time.hour, time.day, time.mon, time.year, time.wday, time.yday, dst?, zone]
    end

    def to_f
      utc.to_f
    end

    def to_i
      utc.to_i
    end
    alias_method :tv_sec, :to_i

    def to_r
      utc.to_r
    end

    def to_datetime
      @to_datetime ||= utc.to_datetime.new_offset(Rational(utc_offset, 86_400))
    end

    # So that +self+ <tt>acts_like?(:time)</tt>.
    def acts_like_time?
      true
    end

    # Say we're a Time to thwart type checking.
    def is_a?(klass)
      klass == ::Time || super
    end
    alias_method :kind_of?, :is_a?

    def freeze
      period; utc; time # preload instance variables before freezing
      super
    end

    def marshal_dump
      [utc, time_zone.name, time]
    end

    def marshal_load(variables)
      initialize(variables[0].utc, ::Time.find_zone(variables[1]), variables[2].utc)
    end

    # respond_to_missing? is not called in some cases, such as when type conversion is
    # performed with Kernel#String
    def respond_to?(sym, include_priv = false)
      # ensure that we're not going to throw and rescue from NoMethodError in method_missing which is slow
      return false if sym.to_sym == :to_str
      super
    end

    # Ensure proxy class responds to all methods that underlying time instance
    # responds to.
    def respond_to_missing?(sym, include_priv)
      return false if sym.to_sym == :acts_like_date?
      time.respond_to?(sym, include_priv)
    end

    # Send the missing method to +time+ instance, and wrap result in a new
    # TimeWithZone with the existing +time_zone+.
    def method_missing(sym, *args, &block)
      wrap_with_time_zone time.__send__(sym, *args, &block)
    rescue NoMethodError => e
      raise e, e.message.sub(time.inspect, self.inspect), e.backtrace
    end

    private
      def get_period_and_ensure_valid_local_time(period)
        # we don't want a Time.local instance enforcing its own DST rules as well,
        # so transfer time values to a utc constructor if necessary
        @time = transfer_time_values_to_utc_constructor(@time) unless @time.utc?
        begin
          period || @time_zone.period_for_local(@time)
        rescue ::TZInfo::PeriodNotFound
          # time is in the "spring forward" hour gap, so we're moving the time forward one hour and trying again
          @time += 1.hour
          retry
        end
      end

      def transfer_time_values_to_utc_constructor(time)
        ::Time.utc(time.year, time.month, time.day, time.hour, time.min, time.sec + time.subsec)
      end

      def duration_of_variable_length?(obj)
        ActiveSupport::Duration === obj && obj.parts.any? {|p| [:years, :months, :days].include?(p[0]) }
      end

      def wrap_with_time_zone(time)
        if time.acts_like?(:time)
          periods = time_zone.periods_for_local(time)
          self.class.new(nil, time_zone, time, periods.include?(period) ? period : nil)
        elsif time.is_a?(Range)
          wrap_with_time_zone(time.begin)..wrap_with_time_zone(time.end)
        else
          time
        end
      end
  end
end


text:
#include "CAVectorUnit.h"

#if !TARGET_OS_WIN32
	#include <sys/sysctl.h>
#elif HAS_IPP
	#include "ippdefs.h"
	#include "ippcore.h"
#endif

int gCAVectorUnitType = kVecUninitialized;

#if TARGET_OS_WIN32
// Use cpuid to check if SSE2 is available.
// Before calling this function make sure cpuid is available
static SInt32 IsSSE2Available()
{
	int return_value;

	{
		int r_edx;
		_asm
		{
			mov eax, 0x01
			cpuid
			mov r_edx, edx
		}
		return_value = (r_edx >> 26) & 0x1;
	}
	return return_value;
}

// Use cpuid to check if SSE3 is available.
// Before calling this function make sure cpuid is available
static SInt32 IsSSE3Available()
{
	SInt32 return_value;

	{
		SInt32 r_ecx;
		_asm
		{
			mov eax, 0x01
			cpuid
			mov r_ecx, ecx
		}
		return_value = r_ecx & 0x1;
	}
	return return_value;
}

// Return true if the cpuid instruction is available.
// The cpuid instruction is available if bit 21 in the EFLAGS register can be changed
// This function may not work on Intel CPUs prior to Pentium (didn't test)
static bool IsCpuidAvailable()
{
	SInt32 return_value = 0x0;
	_asm{
		pushfd    ;			//push original EFLAGS
		pop eax   ;			//get original EFLAGS
		mov ecx, eax   ;	//save original EFLAGS
		xor eax, 200000h  ; //flip ID bit in EFLAGS
		push eax   ;		//save new EFLAGS value on stack
		popfd    ;			//replace current EFLAGS value
		pushfd    ;			//get new EFLAGS
		pop eax   ;			//store new EFLAGS in EAX
		xor eax, ecx   ;
		je end_cpuid_identify  ; //can't toggle ID bit
		mov return_value, 0x1;
end_cpuid_identify:
		nop;
		}
		return return_value;
}

#endif

SInt32	CAVectorUnit_Examine()
{
	int result = kVecNone;

#if TARGET_OS_WIN32
#if HAS_IPP
	// Initialize the static IPP library! This needs to be done before
	// any IPP function calls, otherwise we may have a performance penalty
	int status = ippStaticInit();
	if ( status == ippStsNonIntelCpu )
	{
		IppCpuType cpuType = ippGetCpuType();
		if ( cpuType >= ippCpuSSE || cpuType <= ippCpuSSE42 )
			ippStaticInitCpu( cpuType );
	}
#endif
	{
		// On Windows we use cpuid to detect the vector unit because it works on Intel and AMD.
		// The IPP library does not detect SSE on AMD processors.
		if (IsCpuidAvailable())
		{
			if(IsSSE3Available())
			{
				result = kVecSSE3;
			}
			else if(IsSSE2Available())
			{
				result = kVecSSE2;
			}
		}
	}
#elif TARGET_OS_MAC
#if DEBUG
	if (getenv("CA_NoVector")) {
		fprintf(stderr, "CA_NoVector set; Vector unit optimized routines will be bypassed\n");
		return result;
	}
	else
#endif
	{
	#if (TARGET_CPU_PPC || TARGET_CPU_PPC64)
		int sels[2] = { CTL_HW, HW_VECTORUNIT };
		int vType = 0; //0 == scalar only
		size_t length = sizeof(vType);
		int error = sysctl(sels, 2, &vType, &length, NULL, 0);
		if (!error && vType > 0)
			result = kVecAltivec;
	#elif (TARGET_CPU_X86 || TARGET_CPU_X86_64)
		int answer = 0;
		size_t length = sizeof(answer);
		int error = sysctlbyname("hw.optional.sse3", &answer, &length, NULL, 0);
		if (!error && answer)
			result = kVecSSE3;
		else {
			answer = 0;
			length = sizeof(answer);
			error = sysctlbyname("hw.optional.sse2", &answer, &length, NULL, 0);
			if (!error && answer)
				result = kVecSSE2;
		}
	#elif (TARGET_CPU_ARM) && defined(_ARM_ARCH_7)
		result = kVecNeon;
	#endif
	}
#endif
	gCAVectorUnitType = result;
	return result;
}


text:
;(function($) {

function load(settings, root, child, container) {
	function createNode(parent) {
		var id_category = this.id_category;
		var checked = false;
		$('input[name="'+inputName+'"][type=hidden]').each( function () {
			if ($(this).attr('value') == id_category)
			{
				checked = true;
				$(this).remove();
			}
		});
		var current = $("
").attr("id", this.id_category || "").html(" <input type=\""+(!use_radio ? 'checkbox' : 'radio')+"\" value=\""+this.id_category+"\"/ name=\""+inputName+"\" "+(checked ? 'checked' : '')+" onclick=\"clickOnCategoryBox($(this));\"/> " + this.name +" " + this.level_depth +" ("+this.nbSelectedSubCat+" "+selectedLabel+")").appendTo(parent);
		if (this.classes) {
			current.children("span").addClass(this.classes);
		}
		if (this.has_children > 0) {
			var branch = $("
").hide().appendTo(current);
			current.addClass("hasChildren");
			createNode.call({
				classes: "placeholder",
				name: " ",
				children:[]
			}, branch);
			branch.children().children('.nb_sub_cat_selected').remove();
		}
	}
	$.ajax($.extend(true, {
		url: settings.url,
		dataType: "json",
		data: {
			id_category_parent: root
		},
		success: function(response) {
			child.empty();
			$.each(response, createNode, [child]);
	        $(container).treeview({
	        	add: child
	        });
			readyToExpand = true;
	    }
	}, settings.ajax));
}

var proxied = $.fn.treeview;
$.fn.treeview = function(settings) {
	if (!settings.url) {
		return proxied.apply(this, arguments);
	}
	var container = this;
	if (!container.children().size())
		load(settings, "source", this, container);
	var userToggle = settings.toggle;
	return proxied.call(this, $.extend({}, settings, {
		collapsed: true,
		toggle: function() {
			var $this = $(this);
			if ($this.hasClass("hasChildren")) {
				var childList = $this.removeClass("hasChildren").find("ul");
				load(settings, this.id, childList, container);
			}
			if (userToggle) {
				userToggle.apply(this, arguments);
			}
		}
	}));
};

})(jQuery);


text:
Settings

    <form>

      <input id="value" type="search" {% if term %}value="{{term}}"{% endif %}>
      <select id="site">
        <optgroup label="Sites">
          {% for newznab in newznab_sites %}
            <option value="{{newznab.id}}" {% if site == newznab.id %}selected{%endif%}>{{newznab.name}}</option>
          {% endfor %}
      	</optgroup >
      </select>
      {% if categories|length %}
        <select id="category">
          {% for cat in categories %}
            {% if cat.label %}
              <option {% if "%s"|format(cat.id) == category %}selected{% endif %} value="{{cat.id}}">{{cat.label}}</option>
              {% for subcat in cat.value %}
                <option {% if "%s"|format(subcat.id) == category %}selected{% endif %} value="{{subcat.id}}">- {{subcat.name}}</option>
              {% endfor %}
            {% else %}
              <option value="{{cat.id}}">{{cat.name}}</option>
            {% endif %}
          {% endfor %}
        </select>
      {% endif %}
      <input id="maxage" type="number" placeholder="Max Age (Days)" {% if maxage > 1 %}value="{{maxage}}"{% endif %}>
    </form>

    {% block results %}{% endblock %}


text:
package pubsub

import (
	"context"
	"fmt"
	"testing"
	"time"

	"cloud.google.com/go/internal/testutil"
	"google.golang.org/api/iterator"
	"google.golang.org/api/option"
	pubsubpb "google.golang.org/genproto/googleapis/pubsub/v1"
	"google.golang.org/grpc"
	"google.golang.org/grpc/codes"
	"google.golang.org/grpc/status"
)

func checkTopicListing(t *testing.T, c *Client, want []string) {
	topics, err := slurpTopics(c.Topics(context.Background()))
	if err != nil {
		t.Fatalf("error listing topics: %v", err)
	}
	var got []string
	for _, topic := range topics {
		got = append(got, topic.ID())
	}
	if !testutil.Equal(got, want) {
		t.Errorf("topic list: got: %v, want: %v", got, want)
	}
}

// All returns the remaining topics from this iterator.
func slurpTopics(it *TopicIterator) ([]*Topic, error) {
	var topics []*Topic
	for {
		switch topic, err := it.Next(); err {
		case nil:
			topics = append(topics, topic)
		case iterator.Done:
			return topics, nil
		default:
			return nil, err
		}
	}
}

func TestTopicID(t *testing.T) {
	const id = "id"
	c, srv := newFake(t)
	defer c.Close()
	defer srv.Close()

	s := c.Topic(id)
	if got, want := s.ID(), id; got != want {
		t.Errorf("Token.ID() = %q; want %q", got, want)
	}
}

func TestListTopics(t *testing.T) {
	c, srv := newFake(t)
	defer c.Close()
	defer srv.Close()

	var ids []string
	for i := 1; i <= 4; i++ {
		id := fmt.Sprintf("t%d", i)
		ids = append(ids, id)
		mustCreateTopic(t, c, id)
	}
	checkTopicListing(t, c, ids)
}

func TestListCompletelyEmptyTopics(t *testing.T) {
	c, srv := newFake(t)
	defer c.Close()
	defer srv.Close()

	checkTopicListing(t, c, nil)
}

func TestStopPublishOrder(t *testing.T) {
	// Check that Stop doesn't panic if called before Publish.
	// Also that Publish after Stop returns the right error.
	ctx := context.Background()
	c := &Client{projectID: "projid"}
	topic := c.Topic("t")
	topic.Stop()
	r := topic.Publish(ctx, &Message{})
	_, err := r.Get(ctx)
	if err != errTopicStopped {
		t.Errorf("got %v, want errTopicStopped", err)
	}
}

func TestPublishTimeout(t *testing.T) {
	ctx := context.Background()
	serv, err := testutil.NewServer()
	if err != nil {
		t.Fatal(err)
	}
	pubsubpb.RegisterPublisherServer(serv.Gsrv, &alwaysFailPublish{})
	conn, err := grpc.Dial(serv.Addr, grpc.WithInsecure())
	if err != nil {
		t.Fatal(err)
	}
	c, err := NewClient(ctx, "projectID", option.WithGRPCConn(conn))
	if err != nil {
		t.Fatal(err)
	}
	topic := c.Topic("t")
	topic.PublishSettings.Timeout = 3 * time.Second
	r := topic.Publish(ctx, &Message{})
	defer topic.Stop()
	select {
	case <-r.Ready():
		_, err = r.Get(ctx)
		if err != context.DeadlineExceeded {
			t.Fatalf("got %v, want context.DeadlineExceeded", err)
		}
	case <-time.After(2 * topic.PublishSettings.Timeout):
		t.Fatal("timed out")
	}
}

func TestUpdateTopic(t *testing.T) {
	ctx := context.Background()
	client, srv := newFake(t)
	defer client.Close()
	defer srv.Close()

	topic := mustCreateTopic(t, client, "T")
	config, err := topic.Config(ctx)
	if err != nil {
		t.Fatal(err)
	}
	want := TopicConfig{}
	if !testutil.Equal(config, want) {
		t.Errorf("got %+v, want %+v", config, want)
	}

	// replace labels
	labels := map[string]string{"label": "value"}
	config2, err := topic.Update(ctx, TopicConfigToUpdate{Labels: labels})
	if err != nil {
		t.Fatal(err)
	}
	want = TopicConfig{
		Labels:               labels,
		MessageStoragePolicy: MessageStoragePolicy{[]string{"US"}},
	}
	if !testutil.Equal(config2, want) {
		t.Errorf("got %+v, want %+v", config2, want)
	}

	// delete all labels
	labels = map[string]string{}
	config3, err := topic.Update(ctx, TopicConfigToUpdate{Labels: labels})
	if err != nil {
		t.Fatal(err)
	}
	want.Labels = nil
	if !testutil.Equal(config3, want) {
		t.Errorf("got %+v, want %+v", config3, want)
	}
}

type alwaysFailPublish struct {
	pubsubpb.PublisherServer
}

func (s *alwaysFailPublish) Publish(ctx context.Context, req *pubsubpb.PublishRequest) (*pubsubpb.PublishResponse, error) {
	return nil, status.Errorf(codes.Unavailable, "try again")
}

func mustCreateTopic(t *testing.T, c *Client, id string) *Topic {
	topic, err := c.CreateTopic(context.Background(), id)
	if err != nil {
		t.Fatal(err)
	}
	return topic
}