text:
using Microsoft.VisualStudio.TestTools.UnitTesting;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace TimeyWimey.Tests
{
	[TestClass]
	public class DateTimeRangeTests
	{

		#region Constructor Tests

		[TestMethod]
		[ExpectedException(typeof(ArgumentException))]
		public void DateTimeRange_Constructor_ThrowsOnToBeforeFrom()
		{
			var r = new DateTimeRange(DateTime.Now.Date.AddDays(1), DateTime.Now.Date);
		}

		[TestMethod]
		public void DateTimeRange_Constructor_ConstructsWithEqualFromAndTo()
		{
			var r = new DateTimeRange(DateTime.Now.Date, DateTime.Now.Date);
			Assert.AreEqual(DateTime.Now.Date, r.Start);
			Assert.AreEqual(DateTime.Now.Date, r.End);
		}

		[TestMethod]
		public void DateTimeRange_Constructor_ConstructsWithToAfterFrom()
		{
			var r = new DateTimeRange(DateTime.Now.Date, DateTime.Now.Date.AddDays(1));
			Assert.AreEqual(DateTime.Now.Date, r.Start);
			Assert.AreEqual(DateTime.Now.Date.AddDays(1), r.End);
		}

		#endregion

		#region Static Create Tests

		[TestMethod]
		public void DateTimeRange_Create_SwapsWhenToBeforeFrom()
		{
			var r = DateTimeRange.Create(DateTime.Now.Date.AddDays(1), DateTime.Now.Date);
			Assert.AreEqual(DateTime.Now.Date, r.Start);
			Assert.AreEqual(DateTime.Now.Date.AddDays(1), r.End);
		}

		[TestMethod]
		public void DateTimeRange_Create_ConstructsWhenFromAndToEqual()
		{
			var r = DateTimeRange.Create(DateTime.Now.Date, DateTime.Now.Date);
			Assert.AreEqual(DateTime.Now.Date, r.Start);
			Assert.AreEqual(DateTime.Now.Date, r.End);
		}

		[TestMethod]
		public void DateTimeRange_Create_ConstructsWhenFromBeforeTo()
		{
			var r = DateTimeRange.Create(DateTime.Now.Date, DateTime.Now.Date.AddDays(1));
			Assert.AreEqual(DateTime.Now.Date, r.Start);
			Assert.AreEqual(DateTime.Now.Date.AddDays(1), r.End);
		}

		#endregion

		#region Static Start At Tests

		[TestMethod]
		public void DateTimeRange_StartAt_ChangesFrom()
		{
			var r = DateTimeRange.Create(DateTime.Now.Date, DateTime.Now.Date);
			r = r.StartAt(DateTime.Now.Date.AddDays(-1));
			Assert.AreEqual(DateTime.Now.Date.AddDays(-1), r.Start);
		}

		[TestMethod]
		[ExpectedException(typeof(ArgumentException))]
		public void DateTimeRange_StartAt_ThrowsIfFromAfterTo()
		{
			var r = DateTimeRange.Create(DateTime.Now.Date, DateTime.Now.Date);
			r.StartAt(DateTime.Now.Date.AddDays(1));
		}

		#endregion

		#region Static End At Tests

		[TestMethod]
		public void DateTimeRange_EndAt_ChangesTo()
		{
			var r = DateTimeRange.Create(DateTime.Now.Date, DateTime.Now.Date);
			r = r.EndAt(DateTime.Now.Date.AddDays(1));
			Assert.AreEqual(DateTime.Now.Date.AddDays(1), r.End);
		}

		[TestMethod]
		[ExpectedException(typeof(ArgumentException))]
		public void DateTimeRange_EndAt_ThrowsIfStartToBeforeFrom()
		{
			var r = DateTimeRange.Create(DateTime.Now.Date, DateTime.Now.Date);
			r.EndAt(DateTime.Now.Date.AddDays(-1));
		}

		#endregion

		#region Contains(DateTimeRange) Tests

		[TestMethod]
		public void DateTimeRange_Contains_ReturnsTrueWhenOtherInsideOuter()
		{
			var outer = DateTimeRange.Create(DateTime.Now.Date.AddDays(-1), DateTime.Now.Date.AddDays(1));
			var inner = DateTimeRange.Create(DateTime.Now.Date, DateTime.Now.Date);
			Assert.IsTrue(outer.Contains(inner));
		}

		[TestMethod]
		public void DateTimeRange_Contains_ReturnsTrueWhenOtherAndInsideEqual()
		{
			var outer = DateTimeRange.Create(DateTime.Now.Date, DateTime.Now.Date);
			var inner = DateTimeRange.Create(DateTime.Now.Date, DateTime.Now.Date);
			Assert.IsTrue(outer.Contains(inner));
		}

		[TestMethod]
		public void DateTimeRange_Contains_ReturnsFalseWhenOtherNotInsideOuter()
		{
			var outer = DateTimeRange.Create(DateTime.Now.Date, DateTime.Now.Date);
			var inner = DateTimeRange.Create(DateTime.Now.Date.AddDays(-1), DateTime.Now.Date.AddDays(1));
			Assert.IsFalse(outer.Contains(inner));
		}

		[TestMethod]
		public void DateTimeRange_Contains_ReturnsFalseWhenNoOverlap()
		{
			var outer = DateTimeRange.Create(DateTime.Now.Date, DateTime.Now.Date);
			var inner = DateTimeRange.Create(UnixTime.UnixEpoch, UnixTime.UnixEpoch);
			Assert.IsFalse(outer.Contains(inner));
		}

		[TestMethod]
		public void DateTimeRange_Contains_ReturnsFalseWhenOverlappedButNotEncompassed()
		{
			var outer = DateTimeRange.Create(DateTime.Now.Date, DateTime.Now.Date);
			var inner = DateTimeRange.Create(DateTime.Now.Date.AddDays(-1), DateTime.Now.Date);
			Assert.IsFalse(outer.Contains(inner));
		}

		#endregion

		#region Contains(DateTime) Tests

		[TestMethod]
		public void DateTimeRange_Contains_TrueForContainedDateTime()
		{
			var r = new DateTimeRange(new DateTime(2017, 03, 1), new DateTime(2017, 03, 31));
			Assert.IsTrue(r.Contains(new DateTime(2017, 03, 10)));
		}

		[TestMethod]
		public void DateTimeRange_Contains_TrueForDateAndTimeEqualToStart()
		{
			var r = new DateTimeRange(new DateTime(2017, 03, 1), new DateTime(2017, 03, 31));
			Assert.IsTrue(r.Contains(new DateTime(2017, 03, 01)));
		}

		[TestMethod]
		public void DateTimeRange_Contains_TrueForDateAndTimeEqualToEnd()
		{
			var r = new DateTimeRange(new DateTime(2017, 03, 1), new DateTime(2017, 03, 31));
			Assert.IsTrue(r.Contains(new DateTime(2017, 03, 31)));
		}

		[TestMethod]
		public void DateTimeRange_Contains_FalseForContainedDateTime()
		{
			var r = new DateTimeRange(new DateTime(2017, 03, 1), new DateTime(2017, 03, 31));
			Assert.IsFalse(r.Contains(new DateTime(2017, 02, 10)));
		}

		#endregion

		#region Overlaps Tests

		[TestMethod]
		public void DateTimeRange_Overlaps_ReturnsTrueWhenInstancesAreEqual()
		{
			var outer = DateTimeRange.Create(DateTime.Now.Date, DateTime.Now.Date);
			var inner = DateTimeRange.Create(DateTime.Now.Date, DateTime.Now.Date);
			Assert.IsTrue(outer.Overlaps(inner));
			Assert.IsTrue(inner.Overlaps(outer));
		}

		[TestMethod]
		public void DateTimeRange_Overlaps_ReturnsTrueWhenStartWithinOuter()
		{
			var outer = DateTimeRange.Create(DateTime.Now.Date, DateTime.Now.Date.AddDays(1));
			var inner = DateTimeRange.Create(DateTime.Now.Date.AddHours(12), DateTime.Now.Date.AddDays(2));
			Assert.IsTrue(outer.Overlaps(inner));
			Assert.IsTrue(inner.Overlaps(outer));
		}

		[TestMethod]
		public void DateTimeRange_Overlaps_ReturnsTrueWhenEndWithinOuter()
		{
			var outer = DateTimeRange.Create(DateTime.Now.Date, DateTime.Now.Date.AddDays(1));
			var inner = DateTimeRange.Create(DateTime.Now.Date.AddDays(-1), DateTime.Now.Date.AddHours(12));
			Assert.IsTrue(outer.Overlaps(inner));
			Assert.IsTrue(inner.Overlaps(outer));
		}

		[TestMethod]
		public void DateTimeRange_Overlaps_ReturnsFalseWhenInnerBeforeOuter()
		{
			var outer = DateTimeRange.Create(DateTime.Now.Date, DateTime.Now.Date);
			var inner = DateTimeRange.Create(DateTime.Now.Date.AddDays(-2), DateTime.Now.Date.AddDays(-1));
			Assert.IsFalse(outer.Overlaps(inner));
			Assert.IsFalse(inner.Overlaps(outer));
		}

		[TestMethod]
		public void DateTimeRange_Overlaps_ReturnsFalseWhenInnerAfterOuter()
		{
			var outer = DateTimeRange.Create(DateTime.Now.Date, DateTime.Now.Date);
			var inner = DateTimeRange.Create(DateTime.Now.Date.AddDays(1), DateTime.Now.Date.AddDays(2));
			Assert.IsFalse(outer.Overlaps(inner));
			Assert.IsFalse(inner.Overlaps(outer));
		}

		#endregion

		#region GetHashCode Tests

		[TestMethod]
		public void DateTimeRange_GetHashCode_EquivalentInstancesGenerateSameCode()
		{
			var outer = DateTimeRange.Create(DateTime.Now.Date, DateTime.Now.Date);
			var inner = DateTimeRange.Create(DateTime.Now.Date, DateTime.Now.Date);
			Assert.AreEqual(outer.GetHashCode(), inner.GetHashCode());
		}

		[TestMethod]
		public void DateTimeRange_GetHashCode_UnequalInstancesGenerateDifferentCode()
		{
			var outer = DateTimeRange.Create(DateTime.Now.Date, DateTime.Now.Date.AddSeconds(1));
			var inner = DateTimeRange.Create(DateTime.Now.Date, DateTime.Now.Date);
			Assert.AreNotEqual(outer.GetHashCode(), inner.GetHashCode());
		}

		[TestMethod]
		public void DateTimeRange_GetHashCode_DoesNotOverflow()
		{
			var outer = DateTimeRange.Create(DateTime.MaxValue, DateTime.MaxValue);
			var inner = DateTimeRange.Create(DateTime.MaxValue, DateTime.MaxValue);
			Assert.AreEqual(outer.GetHashCode(), inner.GetHashCode());
		}

		#endregion

		#region Equality Tests

		#region Equals Tests

		[TestMethod]
		public void DateTimeRange_Equals_EquivalentInstancesAreEqual()
		{
			var outer = DateTimeRange.Create(DateTime.Now.Date, DateTime.Now.Date);
			var inner = DateTimeRange.Create(DateTime.Now.Date, DateTime.Now.Date);
			Assert.IsTrue(outer.Equals((object)inner));
			Assert.IsTrue(inner.Equals((object)outer));
		}

		[TestMethod]
		public void DateTimeRange_Equals_UnequalInstancesAreNotEqual()
		{
			var outer = DateTimeRange.Create(DateTime.Now.Date, DateTime.Now.Date.AddSeconds(1));
			var inner = DateTimeRange.Create(DateTime.Now.Date, DateTime.Now.Date);
			Assert.IsFalse(outer.Equals((object)inner));
			Assert.IsFalse(inner.Equals((object)outer));
		}

		[TestMethod]
		public void DateTimeRange_Equals_NullIsUnequal()
		{
			var outer = DateTimeRange.Create(DateTime.Now.Date, DateTime.Now.Date.AddSeconds(1));
			Assert.IsFalse(outer.Equals(null));
		}

		[TestMethod]
		public void DateTimeRange_Equals_NonDateTimeRangeIsUnequal()
		{
			var outer = DateTimeRange.Create(DateTime.Now.Date, DateTime.Now.Date.AddSeconds(1));
			Assert.IsFalse(outer.Equals(new object()));
		}

		#endregion

		#region IEquatable<T>.Equals Tests

		[TestMethod]
		public void DateTimeRange_IEquatableEquals_EquivalentInstancesAreEquivalent()
		{
			var outer = DateTimeRange.Create(DateTime.Now.Date, DateTime.Now.Date);
			var inner = DateTimeRange.Create(DateTime.Now.Date, DateTime.Now.Date);
			Assert.IsTrue(((IEquatable<DateTimeRange>)outer).Equals(inner));
			Assert.IsTrue(((IEquatable<DateTimeRange>)inner).Equals(outer));
		}

		[TestMethod]
		public void DateTimeRange_IEquatableEquals_UnequalWhenToDifferent()
		{
			var outer = DateTimeRange.Create(DateTime.Now.Date, DateTime.Now.Date.AddSeconds(1));
			var inner = DateTimeRange.Create(DateTime.Now.Date, DateTime.Now.Date);
			Assert.IsFalse(((IEquatable<DateTimeRange>)outer).Equals(inner));
			Assert.IsFalse(((IEquatable<DateTimeRange>)inner).Equals(outer));
		}

		[TestMethod]
		public void DateTimeRange_IEquatableEquals_UnequalWhenFromDifferent()
		{
			var outer = DateTimeRange.Create(DateTime.Now.Date.AddSeconds(1), DateTime.Now.Date);
			var inner = DateTimeRange.Create(DateTime.Now.Date, DateTime.Now.Date);
			Assert.IsFalse(((IEquatable<DateTimeRange>)outer).Equals(inner));
			Assert.IsFalse(((IEquatable<DateTimeRange>)inner).Equals(outer));
		}

		[TestMethod]
		public void DateTimeRange_IEquatableEquals_UnequalWhenFromAndToDifferent()
		{
			var outer = DateTimeRange.Create(DateTime.Now.Date.AddSeconds(1), DateTime.Now.Date.AddSeconds(1));
			var inner = DateTimeRange.Create(DateTime.Now.Date, DateTime.Now.Date);
			Assert.IsFalse(((IEquatable<DateTimeRange>)outer).Equals(inner));
			Assert.IsFalse(((IEquatable<DateTimeRange>)inner).Equals(outer));
		}

		#endregion

		#region EqualsOperator Tests

		[TestMethod]
		public void DateTimeRange_EqualsOperator_EquivalentInstancesAreEqual()
		{
			var outer = DateTimeRange.Create(DateTime.Now.Date, DateTime.Now.Date);
			var inner = DateTimeRange.Create(DateTime.Now.Date, DateTime.Now.Date);
			Assert.IsTrue(outer == inner);
		}

		[TestMethod]
		public void DateTimeRange_EqualsOperator_UnequalInstancesReturnFalse()
		{
			var outer = DateTimeRange.Create(DateTime.Now.Date, DateTime.Now.Date);
			var inner = DateTimeRange.Create(DateTime.Now.Date, DateTime.Now.Date.AddSeconds(1));
			Assert.IsFalse(outer == inner);
		}

		#endregion

		#region NotEqualsOperator Tests

		[TestMethod]
		public void DateTimeRange_NotEqualsOperator_EquivalentInstancesReturnFalse()
		{
			var outer = DateTimeRange.Create(DateTime.Now.Date, DateTime.Now.Date);
			var inner = DateTimeRange.Create(DateTime.Now.Date, DateTime.Now.Date);
			Assert.IsFalse(outer != inner);
		}

		[TestMethod]
		public void DateTimeRange_NotEqualsOperator_UnequalInstancesReturnTrue()
		{
			var outer = DateTimeRange.Create(DateTime.Now.Date, DateTime.Now.Date);
			var inner = DateTimeRange.Create(DateTime.Now.Date, DateTime.Now.Date.AddSeconds(1));
			Assert.IsTrue(outer != inner);
		}

		#endregion

		#endregion

		#region Comparison Tests

		#region CompareTo Tests

		[TestMethod]
		public void DateTimeRange_CompareTo_ReturnsMinus1WithEarlierStart()
		{
			var outer = DateTimeRange.Create(DateTime.Now.Date.AddDays(-1), DateTime.Now.Date);
			var inner = DateTimeRange.Create(DateTime.Now.Date, DateTime.Now.Date);
			Assert.AreEqual(-1, outer.CompareTo(inner));
		}

		[TestMethod]
		public void DateTimeRange_CompareTo_ReturnsMinus1WithEarlierEnd()
		{
			var outer = DateTimeRange.Create(DateTime.Now.Date, DateTime.Now.Date);
			var inner = DateTimeRange.Create(DateTime.Now.Date, DateTime.Now.Date.AddDays(1));
			Assert.AreEqual(-1, outer.CompareTo(inner));
		}

		[TestMethod]
		public void DateTimeRange_CompareTo_Returns1WithLaterStart()
		{
			var outer = DateTimeRange.Create(DateTime.Now.Date, DateTime.Now.Date);
			var inner = DateTimeRange.Create(DateTime.Now.Date.AddDays(-1), DateTime.Now.Date);
			Assert.AreEqual(1, outer.CompareTo(inner));
		}

		[TestMethod]
		public void DateTimeRange_CompareTo_Returns1WithLaterEnd()
		{
			var outer = DateTimeRange.Create(DateTime.Now.Date, DateTime.Now.Date.AddDays(1));
			var inner = DateTimeRange.Create(DateTime.Now.Date, DateTime.Now.Date);
			Assert.AreEqual(1, outer.CompareTo(inner));
		}

		[TestMethod]
		public void DateTimeRange_CompareTo_Returns0WhenEqual()
		{
			var outer = DateTimeRange.Create(DateTime.Now.Date, DateTime.Now.Date);
			var inner = DateTimeRange.Create(DateTime.Now.Date, DateTime.Now.Date);
			Assert.AreEqual(0, outer.CompareTo(inner));
		}

		#endregion

		#region LessThan Operator

		[TestMethod]
		public void DateTimeRange_LessThanOperator_ReturnsTrueWithEarlierStart()
		{
			var outer = DateTimeRange.Create(DateTime.Now.Date.AddDays(-1), DateTime.Now.Date);
			var inner = DateTimeRange.Create(DateTime.Now.Date, DateTime.Now.Date);
			Assert.IsTrue(outer < inner);
		}

		[TestMethod]
		public void DateTimeRange_LessThanOperator_ReturnsTrueWithEarlierEnd()
		{
			var outer = DateTimeRange.Create(DateTime.Now.Date, DateTime.Now.Date);
			var inner = DateTimeRange.Create(DateTime.Now.Date, DateTime.Now.Date.AddDays(1));
			Assert.IsTrue(outer < inner);
		}

		#endregion

		#region GreaterThan Operator

		[TestMethod]
		public void DateTimeRange_GreaterThan_ReturnsTrueWithLaterStart()
		{
			var outer = DateTimeRange.Create(DateTime.Now.Date.AddDays(1), DateTime.Now.Date);
			var inner = DateTimeRange.Create(DateTime.Now.Date, DateTime.Now.Date);
			Assert.IsTrue(outer > inner);
		}

		[TestMethod]
		public void DateTimeRange_GreaterThan_ReturnsTrueWithLaterEnd()
		{
			var outer = DateTimeRange.Create(DateTime.Now.Date, DateTime.Now.Date.AddDays(1));
			var inner = DateTimeRange.Create(DateTime.Now.Date, DateTime.Now.Date);
			Assert.IsTrue(outer > inner);
		}

		#endregion

		#endregion

		#region Length Tests

		[TestMethod]
		public void DateTimeRange_Length_ReturnsZeroForSameStartAndEnd()
		{
			var r = new DateTimeRange(DateTime.Now.Date, DateTime.Now.Date);
			Assert.AreEqual(TimeSpan.Zero, r.Length);
		}

		[TestMethod]
		public void DateTimeRange_Length_ReturnsExpectedNonZeroLength()
		{
			var r = new DateTimeRange(DateTime.Now.Date, DateTime.Now.Date.AddDays(1));
			Assert.AreEqual(TimeSpan.FromDays(1), r.Length);
		}

		#endregion

	}
}


text:
import {
  updateCommission,
  applyCommission,
  checkOddsConsistency
} from '/client/collections/checks_local_methods.js';

global._dep = new Deps.Dependency();

/*****************************************************************************/
/* Step1: Event Handlers */
/*****************************************************************************/
Template.Step1.events({
  'click #js-add-outcome': () => ChecksCollection.update(
    {_id: Session.get('activeCheck')},
    {$push: {oddsChecked: emptyOdds, oddsAverages: emptyOdds, oddsCompeting: emptyOdds}}),
  'click #js-remove-outcome': () => ChecksCollection.update(
    {_id: Session.get('activeCheck')},
    {$pop: {oddsChecked: 1, oddsAverages: 1, oddsCompeting: 1}}),
  'click #reset': function (event, template) {
    reset();
    $('#container-data-processing-step1').hide();
    template.processingTitle.set(null);
  },
  'focus #commission': function (event) {
    event.target.select()
  },
  'change #commission': function (event, template) {
    var value = event.currentTarget.value;
    value = value.replace('%', '');
    if (value.substr(0, 2) !== '0.')
      value = value.replace(/^[0]+/g, "")
    if (event.keyCode == 8)
      value = value.slice(0, -1);
    let valueFloat = parseFloat(value);
    isNaN(valueFloat) ? updateCommission('oddsChecked', 0) : updateCommission('oddsChecked', valueFloat);
    if (value === '')
      value = '0%';
    else
      value += '%';
    template.$('#commission').val(value);
    setCaretToPos(template.$('#commission')[0], value.length - 1);
  },
  'click .dropdown-menu li a': function (event, template) {
    var action = $(event.currentTarget).text();

    if (action == 'Apply Commission') {
      applyCommission('oddsChecked');
    }
    else {
      let commission = ({
          Matchbook: 1.5,
          Betfair: 5,
          Smarkets: 2,
          BETDAQ: 5,
          Betsson: 4,
        })[action] || 0;

      updateCommission('oddsChecked', parseFloat(commission));
      $('#commission').val(commission += '%')
    }
  }
});

/*****************************************************************************/
/* Step1: Helpers */
/*****************************************************************************/
Template.Step1.helpers({
  showProcessingTitle: () => Template.instance().processingTitle.get(),
  showProcessingBody: () => Template.instance().processingBody.get(),
  isResetButtonDisabled: () => ChecksCollection.findOne({
    _id: Session.get('activeCheck'),
    'oddsChecked.asOriginalInput': {$gt: ''}
  }) ? '' : 'disabled',
  isRemoveButtonDisabled: () => ChecksCollection.findOne({
    _id: Session.get('activeCheck'),
    oddsChecked: {$size: 2}
  }) ? 'disabled' : '',
  isNextButtonEnabled: function () {
    instance = Template.instance();
    _dep.depend();
    let checks = ChecksCollection.findOne(Session.get('activeCheck'));
    if (checks.oddsChecked.every((odd) => odd.isValidFormat)) {
      if (checkOddsConsistency(checks)) {
        let overround = checks.oddsChecked.reduce((memo, num) => memo + num.asExact, 0);
        if (overround >= 1 && overround < 1.1) {
          $('#commission-group').fadeIn(1000, "linear");
          shownNotifications.map((notificationId) => Notifications.remove({_id: notificationId}));
          // step1_data_processing(checks, percentage);

          let vigorish = (overround - 1) / overround;
          Session.set('CurrentVigorish', vigorish);
          let vigorish_percentual = showAsPercentage(vigorish);
          let overround_percentual = showAsPercentage(overround - 1);
          let return_of_investment_percentual = showAsPercentage(1 - vigorish);
          let vigorish_color = 'DarkRed';
          let affiliate_text = `The bookmaker's theoretical hold (aka vigorish) is ${vigorish_percentual}. This means that in the long run, for every such bet you would only get ${return_of_investment_percentual} of your stake back.`;
          vigorish *= 100;

          if (vigorish > 4)
            affiliate_text = "These odds are quite bad and you might be using a bad sportsbook. If you're not doing it already," +
              ' create an account with a real bookmaker like Pinnacle and' +
              ' read here' +
              ' or here why it is the best. If you are from a country not allowed on Pinnacle (for example USA), the best option I can think of is BetOnline.';
          if (vigorish > 5)
            affiliate_text = "The best punters in the world wouldn't make a profit with such odds and you're probably not one of them if you even consider such a bad offer." +
              ' Create an account with a real bookmaker like Pinnacle and' +
              ' read here' +
              ' or here why it is the best. If you are from a country not allowed on Pinnacle (for example USA), the best option I can think of is BetOnline.';
          instance.processingTitle.set(`Vigorish: ${vigorish_percentual}; Overround: ${overround_percentual}`);
          instance.processingBody.set(affiliate_text);
          if (vigorish <= 5) vigorish_color = 'Chocolate';
          if (vigorish <= 4) vigorish_color = 'Goldenrod';
          if (vigorish <= 3) vigorish_color = '#6cb247';
          if (vigorish <= 2) vigorish_color = '#3eb200';
          if (vigorish <= 1) vigorish_color = 'Lime';
          $('#container-data-processing-step1').show();
          $('#container-data-processing-step1').highcharts({
            chart: {
              type: 'pie',
              options3d: {
                enabled: true,
                alpha: 45,
                beta: 0
              }
            },
            title: {
              text: '',
              useHTML: true
            },
            tooltip: {
              pointFormat: '{series.name}: {point.percentage:.1f}%'
            },
            plotOptions: {
              pie: {
                allowPointSelect: true,
                cursor: 'pointer',
                depth: 35,
                dataLabels: {
                  enabled: true,
                  format: '{point.name}'
                }
              }
            },
            series: [{
              type: 'pie',
              name: 'Share of your stake',
              data: [
                ['You', 100 - vigorish],
                {
                  name: 'Bookmaker',
                  y: vigorish,
                  sliced: true,
                  selected: true,
                  color: vigorish_color
                }
              ]
            }]
          });

          for (let i = 0; i<checks.oddsChecked.length; i++)
          {
            let exact = checks.oddsChecked[i].asExact;
            let location = 'oddsChecked.' + i + '.asTruthier';
            var objectForSet = {};
            objectForSet[location] = exact / overround;
            ChecksCollection.update(
              {_id: Session.get('activeCheck')},
              {$set: objectForSet});
          }

          return '';
        }
      }
    }
    return 'disabled';
  },
  reactiveTableSettings: function () {
    return {
      collection: ChecksCollection.findOne(Session.get('activeCheck')).oddsChecked,
      showFilter: false,
      sortable: false,
      showNavigation: 'auto',
      fields: [
        {key: 'asOriginalInput', label: 'Odds'},
        {key: 'asPercentage', label: 'Implied Probability'},
        {key: 'asTruthier', label: 'Truthier Probability', fn: (value) => value ? showAsPercentage(value) : ''},
        // {key: 'asFlbAdjusted', label: 'FLB-adjusted Probability', fn: (value) => value ? showAsPercentage(value) : ''}
      ]
    }
  }
});

/*****************************************************************************/
/* Step1: Lifecycle Hooks */
/*****************************************************************************/
Template.Step1.onCreated(function () {
  let instance = this;

  instance.processingTitle = new ReactiveVar(null);
  instance.processingBody = new ReactiveVar(null);
});

Template.Step1.onRendered(function () {
  this.$('input:first').focus();
  _dep.changed();
});

Template.Step1.onDestroyed(function () {
});

redpajama_set_name: RedPajamaGithub


text:
`look` is the core function which wraps an existing React Component in order to resolve plugins and mixins. <br>
Optionally pass some configuration which will get merged with the global configuration and be active **only** within the wrapped `Component`.

## `look(Component [, config])`
| Parameter | Description |
| --------- | ----------- |
| Component | Valid React Component you want to enhance with styles |
| config    | An object containing all [configuration settings](https://github.com/rofrischmann/react-look/blob/develop/packages/react-look/docs/guides/configureLook.md) |


text:
dojo.provide("aim.widget.AimMenu");

dojo.require("aim._AimTemplatedWidget");
dojo.require("dijit._Container");
dojo.require("aim.html");
dojo.require("aim.string");
dojo.require("aim.widget.DefaultTextbox");
dojo.require("aim.widget.popup");

dojo.declare("aim.widget.AimMenu", [aim._AimTemplatedWidget, dijit._Container], {
		templateString: '
' +
						'
' +
						'

' +
						'
' +
						'
',

		startup: function() {
			dojo.forEach(this.getChildren(), function(child){ child.startup(); });

			dojo.subscribe("Menu/Close", this, function() {
				if (this.domNode.style.display != "none")
					this.close();
			});

			this._started = true;
		},

		open: function(around, parent, orient) {
			var x, y;
			if (typeof around == "number") {
				x = around;
				y = parent;
				parent = orient;
				orient = arguments[3];
				around = null;
			}

			aim.widget.popup({
				popup: this,
				x: x,
				y: y,
				around: around,
				orient: orient,
				parent: parent
			});
		},
		onOpen: function() {
			// Clip the menu to the window height, if necessary.
			this.domNode.style.height = "";
			var menuSize = dojo.marginBox(this.domNode);
			var windowHeight = dijit.getViewport().h;
			if (menuSize.h > windowHeight)
				dojo.marginBox(this.domNode, {h: windowHeight, w: menuSize.w + aim.html.getScrollbar().w});
		},

		close: function() {
			aim.widget.popup.close(this);
		},
		onClose: function () {},

		bindDomNode: function(node, parentWidget) {
			this.boundNode = node;
			this.boundParentWidget = parentWidget;
			this.connect(node, "onclick", "openMyself");
		},
		openMyself: function(e) {
			if (this.isShowing())
				return this.close();

			this.open(this.boundNode, this.boundParentWidget);
		},

		getBorderBoxWidth: function() {
			if (this.isShowing())
				return dojo.marginBox(this.domNode).w;

			// Browsers return 0 for offsetWidth if the menu is display:none,
			// so we have to briefly show the menu to calculate its width.
			this.domNode.style.position = "absolute";
			this.domNode.style.left = "-9999px";
			this.domNode.style.top = "-9999px";
			this.domNode.style.display = "";

			var ret = dojo.marginBox(this.domNode).w;

			this.domNode.style.position = "";
			this.domNode.style.left = "";
			this.domNode.style.top = "";
			this.domNode.style.display = "none";

			return ret;
		},

		processKey: function(evt){
			var item = dojo.filter(this.getChildren(), function(w) {
				return w.shortCutKey && (w.shortCutKey.toLowerCase() == evt.keyChar.toLowerCase());
			})[0];

			if (item) {
				item._onClick();
				dojo.stopEvent(evt);
			}
		}
	}
);

dojo.declare("aim.widget.AimMenuItem", [aim._AimTemplatedWidget, dijit._Contained], {
		templateString:
			'
' +
			'		' +
			'		' +
			'
',

		checkOnClass: "ckonCol",
		checkOffClass: "ckoffCol",
		width: 0,
		caption: "",
		title: "",
		shortCutKey: null,
		disabled: false,

		startup: function() {
			dojo.setSelectable(this.domNode, false);
			this.domNode.title = this.title;
			// If a width is specified, apply it and allow the text to wrap.
			if (this.width) {
				this.labelNode.style.width = this.width + "px";
				this.domNode.style.whiteSpace = "normal";
			}

			this.setChecked();
			this.updateDisabled();

			this.labelNode.innerHTML = this.caption;
			aim.html.addHoverClass(this.domNode, "aimMenuItemHover");
		},

		_onClick: function(evt) {
			if (!this.disabled) {
				this.onClick();
				if (this.domNode)	// in case the onClick destroyed the menu
					this.getParent().close();
			}
			dojo.stopEvent(evt);
		},
		onClick: function() {},

		enable: function() {
			this.disabled = false;
			this.updateDisabled();
		},
		disable: function() {
			this.disabled = true;
			this.updateDisabled();
		},
		updateDisabled: function() {
			dojo.toggleClass(this.domNode, "aimMenuItemDisabled", !!this.disabled);
		},

		setChecked: function(isChecked) {
			if (typeof(isChecked) != "undefined")
				this.checked = isChecked;

			if (typeof(this.checked) != "undefined") {
				dojo.toggleClass(this.checkNode, this.checkOnClass, this.checked);
				dojo.toggleClass(this.checkNode, this.checkOffClass, !this.checked);
			}
		},

		setCaption: function(caption) {
			this.labelNode.innerHTML = caption;
		}
	}
);

dojo.declare("aim.widget.AimInputableMenuItem", aim.widget.AimMenuItem, {
	templateString:
		 '
'
		+'	'
		+'
'
		+'

'
		+'			'
		+'
'
		+'		'
		+'
',
	widgetsInTemplate: true,

	// Properties that can be overwritten during initialization.
	okCB: null,					// Callback to handle the user's input.
	originalMenuItem: null,		// Reference to another Menu Item, usually the one that this one replaces in the menu list.
	defaultValue: "",			// Default text value for the DefaultTextBox.
	inputClassName: "newInput",	// CSS class used for the DefaultTextBox.
	maxlength: 255,

	startup: function() {
		if (dojo.isMoz)
		{	// Fix Firefox cursor and text selection problem in the input field of the DefaultTextBox widget by setting its position to fixed.
			// Other changes to the surrounding elements were also required to accomodate this.
			var itemWidth = dojo.marginBox(this.input.domNode).w + dojo.marginBox(this.newButton).w + 2;
			this.inputContainer.style.width = itemWidth + "px";
			this.input.textbox.style.position = "fixed";
			dojo.addClass(this.newButton, "newButtonFF");
		}

		dojo.connect(this.getParent(), "onClose", this, "restore");
	},

	setCaption: function(caption)
	{
		this.labelNode.innerHTML = caption;
	},

	initializeText: function(defaultText)
	{
		// If defaultText equals the DefaultTextBox's defaultValue, any onFocus event on the input element clears the input.
		// Doing a select() on the input text also triggers a focus event, so in this case we need to work around clearing the input.
		if (defaultText && defaultText == this.input.defaultValue)
		{
			var tempValue = this.input.defaultValue;
			this.input.defaultValue = "";
			this.input.setValue(defaultText);
			this.input.textbox.select();
			// IE fix for selecting the text: Ensure that DefaultTextBox's _onFocus() runs its course before setting the defaultValue.
			setTimeout(dojo.hitch(this, function() {
				this.input.defaultValue = tempValue;
			}), 0);
		}
		else // If defaultText does not equal the DefaultTextBox's defaultValue we are fine.
		{
			this.input.setValue(defaultText ? defaultText : "");
			this.input.textbox.select();
		}
	},

	// Override the AimMenuItem's _onClick() that hides the menu.
	_onClick: function(evt) {},

	_onKeyPress: function(evt)
	{
		if (evt.keyCode == dojo.keys.ENTER) {
			if(this.okCB) {
				var keepMenuOpen = false;
				keepMenuOpen = this.okCB({newName: this.input.getValue()});
				this.restore();
				if (!keepMenuOpen)
					this.getParent().close();
			}
		} else if (evt.keyCode == dojo.keys.ESCAPE) {
			this.restore(true);
		}

		evt.stopPropagation();
	},

	onAdd: function(evt) {
		var value = this.input.getValue();
		if(value) {
			var keepMenuOpen = false;
			if(this.okCB)
				keepMenuOpen = this.okCB({newName: value});
			this.restore();
			if (!keepMenuOpen)
				this.getParent().close();
		}
		evt.stopPropagation();
	},

	restore: function(hover) {
		if (this.originalMenuItem) {
			this.originalMenuItem.show();
		}
		this.hide();
	}
});

dojo.declare("aim.widget.AimMenuSeparator", aim.widget.AimMenuItem, {
	templateString:
		'
' +
		'	' +
		'

' +
		'

' +
		'		' +
		'
',

	startup: function() {}
});


text:
package org.yukatan.rapid.core.handler;

import org.springframework.web.servlet.mvc.method.RequestMappingInfo;
import org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping;

import java.lang.reflect.Method;

/**
 * Created by Jesus Barquín on 5/03/16.
 */
public class RapidRequestHandler extends RequestMappingHandlerMapping {

    public RapidRequestHandler() {
        super.setOrder(Integer.MIN_VALUE);
    }

    @Override
    protected void registerHandlerMethod(Object handler, Method method, RequestMappingInfo mapping) {
        super.registerHandlerMethod(handler, method, mapping);
    }

}


text:
import uuid

import pytest

from kazoo.testing import KazooTestCase
from kazoo.tests.util import CI_ZK_VERSION

class KazooQueueTests(KazooTestCase):
    def _makeOne(self):
        path = "/" + uuid.uuid4().hex
        return self.client.Queue(path)

    def test_queue_validation(self):
        queue = self._makeOne()
        with pytest.raises(TypeError):
            queue.put({})
        with pytest.raises(TypeError):
            queue.put(b"one", b"100")
        with pytest.raises(TypeError):
            queue.put(b"one", 10.0)
        with pytest.raises(ValueError):
            queue.put(b"one", -100)
        with pytest.raises(ValueError):
            queue.put(b"one", 100000)

    def test_empty_queue(self):
        queue = self._makeOne()
        assert len(queue) == 0
        assert queue.get() is None
        assert len(queue) == 0

    def test_queue(self):
        queue = self._makeOne()
        queue.put(b"one")
        queue.put(b"two")
        queue.put(b"three")
        assert len(queue) == 3

        assert queue.get() == b"one"
        assert queue.get() == b"two"
        assert queue.get() == b"three"
        assert len(queue) == 0

    def test_priority(self):
        queue = self._makeOne()
        queue.put(b"four", priority=101)
        queue.put(b"one", priority=0)
        queue.put(b"two", priority=0)
        queue.put(b"three", priority=10)

        assert queue.get() == b"one"
        assert queue.get() == b"two"
        assert queue.get() == b"three"
        assert queue.get() == b"four"

class KazooLockingQueueTests(KazooTestCase):
    def setUp(self):
        KazooTestCase.setUp(self)
        skip = False
        if CI_ZK_VERSION and CI_ZK_VERSION < (3, 4):
            skip = True
        elif CI_ZK_VERSION and CI_ZK_VERSION >= (3, 4):
            skip = False
        else:
            ver = self.client.server_version()
            if ver[1] < 4:
                skip = True
        if skip:
            pytest.skip("Must use Zookeeper 3.4 or above")

    def _makeOne(self):
        path = "/" + uuid.uuid4().hex
        return self.client.LockingQueue(path)

    def test_queue_validation(self):
        queue = self._makeOne()
        with pytest.raises(TypeError):
            queue.put({})
        with pytest.raises(TypeError):
            queue.put(b"one", b"100")
        with pytest.raises(TypeError):
            queue.put(b"one", 10.0)
        with pytest.raises(ValueError):
            queue.put(b"one", -100)
        with pytest.raises(ValueError):
            queue.put(b"one", 100000)
        with pytest.raises(TypeError):
            queue.put_all({})
        with pytest.raises(TypeError):
            queue.put_all([{}])
        with pytest.raises(TypeError):
            queue.put_all([b"one"], b"100")
        with pytest.raises(TypeError):
            queue.put_all([b"one"], 10.0)
        with pytest.raises(ValueError):
            queue.put_all([b"one"], -100)
        with pytest.raises(ValueError):
            queue.put_all([b"one"], 100000)

    def test_empty_queue(self):
        queue = self._makeOne()
        assert len(queue) == 0
        assert queue.get(0) is None
        assert len(queue) == 0

    def test_queue(self):
        queue = self._makeOne()
        queue.put(b"one")
        queue.put_all([b"two", b"three"])
        assert len(queue) == 3

        assert not queue.consume()
        assert not queue.holds_lock()
        assert queue.get(1) == b"one"
        assert queue.holds_lock()
        # Without consuming, should return the same element
        assert queue.get(1) == b"one"
        assert queue.consume()
        assert not queue.holds_lock()
        assert queue.get(1) == b"two"
        assert queue.holds_lock()
        assert queue.consume()
        assert not queue.holds_lock()
        assert queue.get(1) == b"three"
        assert queue.holds_lock()
        assert queue.consume()
        assert not queue.holds_lock()
        assert not queue.consume()
        assert len(queue) == 0

    def test_consume(self):
        queue = self._makeOne()

        queue.put(b"one")
        assert not queue.consume()
        queue.get(0.1)
        assert queue.consume()
        assert not queue.consume()

    def test_release(self):
        queue = self._makeOne()

        queue.put(b"one")
        assert queue.get(1) == b"one"
        assert queue.holds_lock()
        assert queue.release()
        assert not queue.holds_lock()
        assert queue.get(1) == b"one"
        assert queue.consume()
        assert not queue.release()
        assert len(queue) == 0

    def test_holds_lock(self):
        queue = self._makeOne()

        assert not queue.holds_lock()
        queue.put(b"one")
        queue.get(0.1)
        assert queue.holds_lock()
        queue.consume()
        assert not queue.holds_lock()

    def test_priority(self):
        queue = self._makeOne()
        queue.put(b"four", priority=101)
        queue.put(b"one", priority=0)
        queue.put(b"two", priority=0)
        queue.put(b"three", priority=10)

        assert queue.get(1) == b"one"
        assert queue.consume()
        assert queue.get(1) == b"two"
        assert queue.consume()
        assert queue.get(1) == b"three"
        assert queue.consume()
        assert queue.get(1) == b"four"
        assert queue.consume()

    def test_concurrent_execution(self):
        queue = self._makeOne()
        value1 = []
        value2 = []
        value3 = []
        event1 = self.client.handler.event_object()
        event2 = self.client.handler.event_object()
        event3 = self.client.handler.event_object()

        def get_concurrently(value, event):
            q = self.client.LockingQueue(queue.path)
            value.append(q.get(0.1))
            event.set()

        self.client.handler.spawn(get_concurrently, value1, event1)
        self.client.handler.spawn(get_concurrently, value2, event2)
        self.client.handler.spawn(get_concurrently, value3, event3)
        queue.put(b"one")
        event1.wait(0.2)
        event2.wait(0.2)
        event3.wait(0.2)

        result = value1 + value2 + value3
        assert result.count(b"one") == 1
        assert result.count(None) == 2


text:
SANI_FORWARD_DECLARE_2(sani, rtti, Object);

namespace sani {
	namespace rtti {
		class Argument {
		public:
			/// Constructs invalid argument
			Argument();
			/// Constructs copy of argument
			Argument(const Argument& rhs);

			template <class T>
			Argument(const T& data);

			/// Copies the argument
			Argument& operator=(const Argument& rhs);

			/// Gets the argument type
			Type getType() const;

			/// Gets the pointer to data
			void* getPointer() const;

			/// Gets the value of argument
			template <class T>
			T& getValue() const;
		private:
			const Type type;
			const void* ptr;
		};
	}
}

#include "inl/argument.inl"


text:
from django.contrib.auth.models import User
from django.core.signing import BadSignature, SignatureExpired
from django import forms

from nightreads.emails.models import Tag
from . import user_service

class SubscribeForm(forms.Form):
    email = forms.EmailField()

    def clean(self):
        cleaned_data = super(SubscribeForm, self).clean()
        all_tag, _ = Tag.objects.get_or_create(name='all')
        cleaned_data['tags'] = [all_tag, ]
        return cleaned_data

class UnsubscribeForm(forms.Form):
    email = forms.EmailField()

class ConfirmEmailForm(forms.Form):
    user = forms.IntegerField()
    subscribe = forms.IntegerField()
    code = forms.CharField(max_length=80)

    def clean_subscribe(self):
        value = bool(self.cleaned_data['subscribe'])
        self.cleaned_data['subscribe'] = value
        return value

    def clean(self):
        cleaned_data = super(ConfirmEmailForm, self).clean()
        if self.errors:
            return cleaned_data
        user_id = cleaned_data['user']
        code = cleaned_data['code']
        for_subscription = cleaned_data['subscribe']
        user = User.objects.filter(id=user_id).first()
        if not user:
            raise forms.ValidationError('Invalid Link')
        self.cleaned_data['user'] = user
        try:
            user_service.validate_key(key=code, user=user,
                                      for_subscription=for_subscription)
        except BadSignature:
            raise forms.ValidationError('Invalid Link')
        except SignatureExpired:
            raise forms.ValidationError('Link expired, please regenerate')
        return cleaned_data


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

using MySharpServer.Common;
using MySharpServer.Framework;

namespace MySharpServerExample.ServerApp
{
    public static class CommonLog
    {
        static readonly ServerFormLogger m_Logger = null;

        static CommonLog()
        {
            m_Logger = new ServerFormLogger();
        }

        public static IServerLogger GetLogger()
        {
            return m_Logger;
        }

        public static void Info(string msg)
        {
            if (m_Logger != null) m_Logger.Info(msg);
        }

        public static void Debug(string msg)
        {
            if (m_Logger != null) m_Logger.Debug(msg);
        }

        public static void Warn(string msg)
        {
            if (m_Logger != null) m_Logger.Warn(msg);
        }

        public static void Error(string msg)
        {
            if (m_Logger != null) m_Logger.Error(msg);
        }
    }

    public class ServerFormLogger : ServerLogger
    {

        private void TryToSendLogToConsole(string msg)
        {
            //try
            //{
            //    Console.WriteLine("[" + DateTime.Now.ToString("HH:mm:ss") + "]" + msg);
            //}
            //catch { }
        }

        public override void Info(string msg)
        {
            base.Info(msg);
            TryToSendLogToConsole("[INFO] " + msg);
        }

        public override void Debug(string msg)
        {
            base.Debug(msg);
            TryToSendLogToConsole("[DEBUG] " + msg);
        }

        public override void Warn(string msg)
        {
            base.Warn(msg);
            TryToSendLogToConsole("[WARN] " + msg);
        }

        public override void Error(string msg)
        {
            base.Error(msg);
            TryToSendLogToConsole("[ERROR] " + msg);
        }
    }
}


text:
// Provides the JSON model implementation of a list binding
sap.ui.define(['jquery.sap.global', 'sap/ui/model/ClientTreeBinding'],
	function(jQuery, ClientTreeBinding) {
	"use strict";

	/**
	 * Creates a new JSONListBinding.
	 *
	 * This constructor should only be called by subclasses or model implementations, not by application or control code.
	 * Such code should use {@link sap.ui.model.json.JSONModel#bindTree JSONModel#bindTree} on the corresponding model instance instead.
	 *
	 * @param {sap.ui.model.json.JSONModel}
	 *         oModel Model instance that this binding is created for and that it belongs to
	 * @param {string}
	 *         sPath Path pointing to the tree or array that should be bound
	 * @param {object}
	 *         [oContext=null] Context object for this binding, mandatory when a relative binding path is given
	 * @param {sap.ui.model.Filter|sap.ui.model.Filter[]}
	 *         [aFilters=null] Predefined filters contained in an array
	 * @param {object}
	 *         [mParameters=null] Additional model-specific parameters
	 * @param {string[]} [mParameters.arrayNames]
	 * 			Keys of arrays to be used for building the tree structure. If not specified, all arrays and objects in the bound data will be used.
	 *			Note that for arrays nested inside differently named arrays, you need to add both to arrayNames. You always have to add the complete parent chain.
	 *			If any array is ignored, its child arrays will be ignored as well even if they have been added to arrayNames.
	 * @throws {Error} When one of the filters uses an operator that is not supported by the underlying model implementation
	 *
	 *
	 * @class
	 * Tree binding implementation for JSON format.
	 *
	 * The bound data can contain JSON objects and arrays. Both will be used to build the tree structure.
	 * You can optionally define a set of arrays to be used for the tree structure in the parameter arrayNames.
	 * If this parameter is set, all other objects and arrays will be ignored.
	 *
	 * @protected
	 * @alias sap.ui.model.json.JSONTreeBinding
	 * @extends sap.ui.model.ClientTreeBinding
	 */
	var JSONTreeBinding = ClientTreeBinding.extend("sap.ui.model.json.JSONTreeBinding");

	JSONTreeBinding.prototype._saveSubContext = function(oNode, aContexts, sContextPath, sName) {
		// only collect node if it is defined (and not null), because typeof null == "object"!
		if (oNode && typeof oNode == "object") {
			var oNodeContext = this.oModel.getContext(sContextPath + sName);
			// check if there is a filter on this level applied
			if (this.aAllFilters && !this.bIsFiltering) {
				if (jQuery.inArray(oNodeContext, this.filterInfo.aFilteredContexts) != -1) {
					aContexts.push(oNodeContext);
				}
			} else {
				aContexts.push(oNodeContext);
			}
		}
	};

	return JSONTreeBinding;

});


text:
set -e

current="$(HEAD -E 'https://mms.mongodb.com/download/agent/monitoring/mongodb-mms-monitoring-agent_latest_amd64.deb' | grep -m1 '^Location:' | cut -d_ -f2)"

set -x
sed -ri 's/^(ENV MMS_VERSION) .*/\1 '"$current"'/' Dockerfile


text:
import './identification';
import './type-hinting';
import './overloading';


text:
var _ = require('underscore'), Backbone = require('backbone');
var BaseView = require('./base');
var Tabled = require('../../../tabled');
var Table = BaseView.extend({

    render: function() {

        this.$el.html('');

        // create bc of data
        this.bcData = new Backbone.Collection([]);

        // create tabled
        this.subview('tabled', new Tabled({
            columns: [
                { id: this.idAttribute , label: this.idAttribute , key: this.idAttribute, filter: 'like', sort: 'string', format: function(val, row) {
                    return ' ' + val ;
                } },
                { id: this.valAttribute, label: this.valAttribute, key: this.valAttribute, filter: 'number', sort: 'number', sort_value: 'd' }
            ],
            collection: this.bcData,
            save_state: true,
            el: this.el,
            id: 'topn.table.' + this.widgetView.compId(),
            col_sorts: [this.valAttribute]
        }).render());

        this.onResize();

        return this;

    },

    onData: function(data) {
        BaseView.prototype.onData.call(this, data);
        this.bcData.set(data);
    },

    onResize: function() {
        this.subview('tabled').resizeTableToCtnr();
    }

});
exports = module.exports = Table;


text:
* Template modules now take `only` and `except` options to only display on specific routes.
* Now only caching first 15 days of `posts_daily` view.
* Added `okgrow:iron-router-autoscroll` package.
* Small tweaks to search UX.
* [BREAKING] Use collection helpers instead of `postLink` and `target` in `post_title` and `post_thumbnail`.
* [BREAKING] Use collection helpers instead of `pathFor` in `post_comments_link` and `post_discuss`.
* Added new i18n strings.
* Modified custom template prefix system to accept multiple prefixes.
* [BREAKING] Changed `Telescope.config.customPrefix = "foo"` to `Telescope.config.addCustomPrefix("foo")`.
* Added new `facebookPage` setting.
* Added category description to category menu, when it exists.
* Fixed post category and post thumbnail CSS classes.
* Switched back to `aldeed:autoform` instead of `sacha:autoform`.
* Updated to Meteor 1.1.0.3.
* Added support for menu hierarchies.
* Added hierarchical categories.
* Now only showing "play" button for actual videos.
* Not subscribing to `postsListUsers` on user profile page anymore.
* Added per-category RSS routes (thanks @lewisnyman!)
* Now showing top comments in email newsletter (thanks @sungwoncho!)
* Fixed blank URL edit bug (thanks @johnthepink!)
* Added `.posts-day` wrapper in `posts-daily` template.
* [BREAKING] menu label template must now be specified using `menuLabelTemplate` option in menu component.
* Menu label template data context can now be specified using `menuLabelData` option.
* `user_menu` template and its helpers moved from `telescope:core` to `telescope:users`.
* Now recalculating email hash whenever email changes.
* Added user avatar to user menu in nav.

## v0.22.2

* Made `approvePost` and `unapprovePost` methods take `postId` instead of `post` as argument and fixed approve/unapprove bug.
* Now sorting email newsletter posts by `baseScore` (time-independent), not `score`.

## v0.22.1 "DebugScope"

* Introduced new [template debug mode](http://docs.telescopeapp.org/docs/debug-mode).
* Fixed invites bugs (thanks @badibouteraa!).
* Made hero modules full width (thanks @jshimko!).
* Renamed `nav` template to `header`.
* Renamed `postsListTop` zone to `top`.
* Renamed `footer` template to `footer_code`, which is part of the `footer` module zone.
* Any template can now be used as menu label in menu component.
* Added `Telescope.menuItems.removeAll()`
* Number of columns in Hubble grid layout now adapts to viewport width.
* Added image support to RSS feed and API.
* Added setting for pointing RSS feed to discussion pages.
* Made video lightbox responsive and made video stop on lightbox close.
* Simplified template modules markup structure.
* Fixed bug preventing non-logged-in users from signing up to newsletter (thanks @frabrunelle!).
* Moved errors and banners styles to base theme.
* Updated Kadira package.
* Implemented post-specific SEO logic for generating Open Graph and Twitter meta tags.

## v0.21.2 "FastScope"

* Added day by day settings for newsletter frequency (thanks @johnthepink!).
* Implemented Subs Manager.
* Implemented FastRender.
* Now using `check` for methods.

## v0.21.1 "SlugScope"

* Added URL slugs for posts (i.e. `/posts/xyz/my-post-slug`).
* i18n files clean-up.
* Added post downvote setting.
* Renamed `post_upvote` template to `post_vote`.
* Refactored notifications code.
* Added `kadira-debug` package.
* Fixed avatar bug.
* Fixed screen refresh bug on post page.
* Fixed security issue (thanks @delgermurun).
* Fixed security issue (thanks @pcorey).
* Added Swedish translation (thanks @Alekzanther).
* Improved French translation (thanks @camilleroux).

## v0.20.6 "AutoScope"

* Added Extra CSS field (thanks @johnthepink!).
* Fixed security issue with Settings (thanks @jshimko!).
* Added automatic template replacement.

## v0.20.5 "MinorScope"

Just a couple minor bug fixes.

* Changed how email template customization works (see [documentation](http://docs.telescopeapp.org/v0.20/docs/custom-templates#email-templates)).
* Ensure email uniqueness and keep it in sync.
* Improve profile completion screen validation & errors.
* Generate public user properties list from schema.
* Fixed video lightbox issue.
* Updated Getting Started content.
* Enforcing better URL formatting for Site URL setting.
* Fixed notification settings.
* Reworked user settings.

## v0.20.4 "RefactorScope"

See [blog](http://telescopeapp.org/blog/telescope-v020-refactorscope/) for more details.

## v0.15.1 "PageScope"

* Settings now have their own `telescope-settings` package (thanks @delgermurun!).
* Swedish translation (thanks @Alekzanther!)
* Various fixes (thanks @azizur, @ndarilek, @kai101, @saimeunt, @Kikobeats!).
* Added `telescope-pages` module for managing static pages.

## v0.15 "SideScope"

#### Layout

* Added new `postListTop` zone that only appears on post lists.
* Now showing tagline on every post list.
* Added the Side Nav layout.
* New Admin menu layout.

#### Settings

* Added the Post Views setting.
* Changed color settings names.
* Added field for optional category image (thanks @dtsepelev!).

#### SEO

* Added `telescope-sitemap` package (thanks @yourcelf!).
* Added improved SEO support (thanks @yourcelf!).
* Added field for SEO site image.

#### Other

* Improved performance when loading comments for long threads (thanks @dandv!).
* Usernames are now case and space insensitive. `John Smith`, `JohnSmith`, and `johnsmith` are now all considered to be the same username (thanks @splendido!).
* Now using `feedparser` instead of `htmlparser2` to parse RSS feeds (thanks @delgermurun!).
* Now supporting RSS categories (thanks @delgermurun).
* Refactored dropdowns into menu components.
* New `{{{icon}}}` helper for icons, using FontAwesome.
* New accent color customization API.
* Fixed various bugs (thanks @webyak, @yourcelf, @ywang28, @delgermurun!).
* Now publishing upvoters and downvoters on single post page.

#### Internationalization

* Added Arabic translation (thanks @nwabdou85!).
* Added missing translations in Brazilian Portuguese (thanks @alanmeira!).
* Improved French translation (thanks @klamzo!).
* Romanian translation (thanks @razvansky!).
* Added Dutch translation (thanks @reneras!).

## v0.14.3 "TableScope"

* Implemented Reactive Table for the Users dashboard (thanks @jshimko!).
* Upgraded Herald package (thanks @kestanous!).
* Upgraded Avatar package (thanks @bengott!).
* Upgraded Autoform package.
* Added Greek translation (thanks @portokallidis!).
* Improved Spanish translation (thanks @brayancruces!).
* Added new callbacks for upvoting and downvoting (thanks @Baxter900 !).
* OP comments now get the `author-comment` CSS class.

## v0.14.2 "FaviconScope"

* Added settings for auth methods.
* Added setting for external fonts.
* Use site tagline as homepage title.
* Make favicon customizable.
* Making webfont customizable. To get previous font back, use: `https://fonts.googleapis.com/css?family=Source+Sans+Pro:400,700,400italic,700italic`.
* Fix juice issue.
* Non-admins should not be able to access rejected posts.
* Bulgarian translation (thanks @durrrr91!)

## v0.14.1 "TaglineScope"

* Fix double notification bug.
* Fix singleday view bug.
* Fix post approval date bug.
* Don't let non-admins access pending posts.
* Give search field a border on white backgrounds.
* Spanish, Brazilian, Turkish, Vietnamese, Polish translations (thanks everybody!).
* Do not put comment reply page behind log-in wall.
* Various CSS tweaks.
* Added tagline banner package.
* You can now assign a category to posts generated from feeds (thanks @Accentax!).
* Use tagline as title on homepage.
* Refactor default view route controller code.
* Fixed security issue with post editing.

## v0.14.0 "GridScope"

* Added Grid Layout option.
* Cleaned up vote click handling functions and added tests (thanks @anthonymayer!).
* Added `threadModules` zone.
* Added `upvoteCallbacks` and `downvoteCallbacks` callback arrays.
* Fix "post awaiting moderation" message bug.
* You can now subscribe to comment threads (thanks @delgermurun!).
* Added `postApproveCallbacks` callback array.
* Added notifications for pending and approved posts, for admins and end users.
* Renaming "digest" view to "singleday".
* Make sure only valid properties can be added to posts and comments.
* Added newsletter time setting (thanks @anthonymayer!).
* Change "sign up" to "register" (thanks @Kikobeats!).

## v0.13.0 "ComponentScope"

* Tweaked comments layout in Hubbble theme.
* Added Bulgarian translation (thanks @toome123!).
* Cleaned up permission functions (thanks @anthonymayer!).
* Various fixes (thanks @comerc and @Kikobeats!).
* Stopped synced-cron message logging.
* Limit all posts lists to 200 posts.
* Refactored posts lists to use the template-level subscription pattern when appropriate.
* Refactored `single day` and `daily` packages.
* Footer field now accepts Markdown instead of HTML.
* Feeds can now be assigned to a user.
* Various CSS tweaks.
* Fixing newsletter issue.
* Post rank now has its own module.
* Changed how field label i18n works.

## v0.12.0 "DummyScope"

**Important: existing newsletters and feeds need to be manually enabled in the Settings panel**

* Added "Enable Newsletter" setting. Note: existing newsletters must be re-enabled.
* Added "Enable Feeds" settings. Note: existing feeds must be re-enabled.
* Now showing release notes for latest version right inside the app.
* Added dummy posts, users, and comments.
* Added new Events collection for keeping track of important events.
* Log first run event.
* `MAIL_URL` environment variable can now be set from Settings.
* Renamed `viewNav` to `viewsMenu`.
* Renamed `adminNav` to `adminMenu`.
* Improvements to the Post by Feed package.
* Added tests for nav bar (thanks @anthonymayer!).
* **New and improved [documentation](http://telesc.pe/docs).**

## v0.11.1 "FeedScope"

* Post submit and edit forms now submit to their respective methods directly.
* Removed `postSubmitRenderedCallbacks` and `postEditRenderedCallbacks`.
* `telescope-post-by-feed` package now lets you import posts from RSS feeds.
* Adding limit of 200 posts to post list request.
* Refactoring post and comment submit to fix latency compensation issues.
* Tags package now using Autoform.

## v0.11.0 "AvatarScope"

* Added new `userCreatedCallbacks` callback hook.
* Added new setting to subscribe new user to mailing list automatically.
* Added new `debug` setting.
* `siteUrl` setting now affects `Meteor.absoluteUrl()`.
* Added new `Telescope.log` function that only logs if `debug` setting is true.
* Simplified post module system, modules are not split in three zones anymore.
* Added new `postThumbnail` hook to show Embedly thumbnail.
* Simplified Hubble theme CSS for both desktop and mobile.
* Many CSS tweaks for Hubble mobile.
* Show author and commenters avatars on post item.
* Adding description to post list pages and showing them in menus.
* Improved Russian translation (thanks @Viktorminator!).
* Now using `editorconfig` (thanks @erasaur!).
* Upgraded to `useraccounts:unstyled@1.4.0` (thanks @splendido!).

## v0.10.0 "RefactorScope"

* Renaming Errors to Messages (thanks @yourcelf!).
* Adding `fast-render` (thanks @arunoda!).
* Extracted digest into its own package.
* Adding "scheduled" view that shows upcoming scheduled posts.
* Bringing back "delete post" link that was removed by mistake.
* Made user profile display page modular.
* Made user profile edit page modular.
* Started extracting invites into their own package.

## v0.9.11 "FormScope"

* Now using [Autoform](https://github.com/aldeed/meteor-autoform/)'s **quickform** feature to generate post submit and edit forms.
* Various fixes by [@anthonymayer](https://github.com/anthonymayer).
* Now using [fourseven:scss](https://github.com/fourseven/meteor-scss) to directly compile SCSS files.
* Renamed `post` method to `submitPost`.
* Post editing now happens via a `postEdit` method.
* Categories are now normalized (only the `_id` is stored on the post object, not the whole category object).
* Refactored Embedly package; now fills in description as well (thanks [@kvindasAB](https://github.com/kvindasAB)!).
* Thumbnail height and width are now customizable in settings panel.
* Settings and Post forms now i18n'ized.

## v0.9.10 "i18nScope"

* Now using [tap:i18n](https://github.com/TAPevents/tap-i18n) for internationalization (thanks a ton to @theosp).
* Each package is now i18n'd invididually.
* Chinese i18n code is now `zh-CN`, not `zh`.
* Various fixes (thanks @anthonymayer).
* Upgrade Avatar package (thanks @bengott).

## v0.9.9

* Updating to Meteor 1.0.
* Updating to Iron Router 1.0.
* Adding view counter (thanks @steffenstraetz! See [PR #489](https://github.com/TelescopeJS/Telescope/pull/489))
* Splitting out `router.js` in multiple files.
* URL can now be removed when editing a post (thanks @massimilianomarini! See [PR 484](https://github.com/TelescopeJS/Telescope/pull/484)).
* Now waiting on `allUsersAdmin` subscription for post submit page (thanks @kai101! See [PR 508](https://github.com/TelescopeJS/Telescope/pull/508))
* Putting server-side routes for email template tests in their own respective packages.

## v0.9.8

* Fixing #457 (pending posts view not working).
* Added German translation (thanks @Helmi!).
* Added `?q=` parameter to searches (thanks @yourcelf!).
* Abstracting `isAdmin` (thanks @yourcelsf!).
* Refactoring `getPostsParameters` (thanks @delgermurun!).
* Using `bengott:avatar` package for avatars (thanks @bengott!).
* Upgrading to Meteor 0.9.3.1.

## v0.9.7 "SettingsScope"

* Updating to Meteor 0.9.3.
* Improving RSS feed (thanks @delgermurun!).
* Fixed redirection issues on sign-up (thanks @steffenstraetz!)
* Fixed bug on Twitter sign-in.
* Splitting up the settings form into sub-sections.
* Adding help text to settings form.
* Fixing problem with daily view theming.
* Improving avatar stuff (thanks @shaialon and @bengott!).

## v0.9.6

* Fixed security hole in user update.
* Kadira is now included by default.
* Comments now have their own feed (thanks @delgermurun!).
* Fixed URL collision bug (thanks @GoodEveningMiss!).
* Now using [`account-templates`](https://github.com/splendido/accounts-templates-core) (thanks @splendido!).
* Retinizing avatar sizes (thanks @shaialon!).

## v0.9.5 "FixScope"

* Fixed `/settings` bug (thanks @steffenstraetz!).
* Code cleanup (thanks @wulfmeister!).
* Fixed upvote/downvote concurrency bug (thanks @spifd!).
* Renamed `SubmitServerCallbacks` to `SubmitMethodCallbacks` for posts and comments.
* Added `AfterSubmitMethodCallbacks` for posts and comments.
* Made notifications into their own `telescope-notifications` package.
* `telescope-update-prompt` package now sends user, post, and comment count when phoning home.

## v0.9.4 "UpdateScope"

* Removed unneeded allow insert on Posts and Comments.
* Renaming `postMeta` template to `postInfo` to avoid ambiguity.
* Fixing avatar code.
* Adding update prompt package.
* Upgrading to Meteor 0.9.2.
* Do not remove deleted comments from database, use `isDeleted` flag instead.
* Now showing "X new posts" instead of just displaying them. Thanks @dburles!

## v0.9.3 "DailyScope"

* Show user comments on user profile page.
* Move votes to their own `user.votes` object.
* Add daily view.
* Default root view is now customizable.
* Updated app to 0.9.0.
* Updated all packages to be 0.9.0-compatible.
* Fixed XSS bug (CVE ID: CVE-2014-5144) by sanitizing user input server-side.
* Now storing both markdown and HTML versions of content.

## v0.9.2.6 "InviteScope"

* Added new invite features (thanks [@callmephilip](https://github.com/callmephilip)!)
* Changed `navItems` to `primaryNav` and added `secondaryNav`.
* Added new `themeSettings` object for storing theme-level settings.
* Notifications is now a nav menu item.
* Renamed `comments` to `commentsCount` on `Post` model.
* Now tracking list of commenters `_id`s on `Post` model.
* Rerun interrupted migrations.

## v0.9.2.5 "AccountScope"

* Now keeping track of upvoted/downvoted posts & comments.
* Using [accounts-entry](https://github.com/Differential/accounts-entry/) for accounts stuff.
* Split out part of the Hubble theme into a new "base" theme.

## v0.9.2 "MailScope"

* Use [handlebars-server](https://github.com/EventedMind/meteor-handlebars-server) for all email templates.
* Refactored email system to use global HTML email wrapper.
* Added routes to preview email templates.
* Changed how notifications are stored in db.
* Added `deleteNotifications` migration to delete all existing notifications.
* Now using templates for on-site notifications too.
* Added `heroModules` and `footerModules` hooks.
* Added [telescope-newsletter](https://github.com/TelescopeJS/Telescope-Newsletter) package.
* Sending emails from within `setTimeout`s to fix latency compensation issue.

## v0.9.1.2

* Added `lastCommentedAt` property to posts.
* Added hooks to `post_edit` and `post_submit`'s `rendered` callback.
* Embedly module now supports video embedding in a lightbox.
* Updated to Meteor 0.8.3.
* Updated packages.

## v0.9.1

* Using Arunoda's [Subscription Manager](https://github.com/meteorhacks/subs-manager).
* Updating mobile version.
* Made the background color setting into a more general background CSS setting.
* Added `postHeading` and `postMeta` hooks.

## v0.9

* See [blog post](http://telesc.pe/blog/telescope-v09-modulescope) for changelog.

## v0.8.3 "CleanScope"

* Refactored the way dating and timestamping works with pending/approved posts.
* Cleaned up unused/old third-party code.
* Migrated "submitted" property to "postedAt".
* Added a "postedAt" property to comments.

## v0.8.2 "SchemaScope"

* Improved migrations with timestamps and number of rows affected.
* Created `telescope-lib` and `telescope-base` pacakge.
* Pulled out search into its own `telescope-search` package.
* Made menu and views modular.
* Using SimpleSchema and Collection2 for models.

## v0.8.1 "FlexScope"

* Extracted part of the tags feature into its own package.
* Made subscription preloader more flexible.
* Made navigation menu dynamic.

## v0.8 "BlazeScope"

* Updated for Meteor 0.8.1.1/Blaze compatibility.
* Using Collection2/SimpleSchema/Autoforms for Settings form.

## v0.7.4 "InterScope"

* Added basic internationalization (thanks Toam!).
* Added search logging.

## v0.7.3

* Refactored notifications.
* Added notifications for new users creation.

## v0.7.2

* Added basic search (thanks Ry!).

## v0.7.1

* Added karma redistribution.
* Improved user dashboard.
* Improved user profiles.

Note: run the "update user profile" script from the toolbox after updating.

## v0.7 "IronScope"

#### Huge update!

* Switched to IronRouter.
* Added new invite system.
* Made nested comments optional.
* Reworked notifications settings.
* Stopped publishing all users.
* Added URL slugs for user profiles.
* Using nProgress to show loading.
* Paginating users dashboard.
* Filtering users dashboard.

Note: If you're upgrading from a previous version of Telescope, you'll need to run the "update user slugs" method from within the Admin Toolbox panel inside the web app to get user profiles to work.

## v0.6.2

* Fixed bug where anybody could delete any comment.
* Added option to add new users to a MailChimp list.

## v0.6.1

* Added Bitly integration.
* Fixed Twitter avatars.
* Refactoring allow/deny code.
* Added click tracking on links.
* Refactoring RSS and API code to use server-side routing.

## v0.6

* Added categories
* Cleaned up file structure.

## v0.5.6

* Added simple JSON API showing the 100 last posts.

## v0.5.5

* Added Google Analytics pageview tracking.
* Added RSS feed for /new

## v0.5.4

* Added email notifications for approved users.
* Added delete users link.

## v0.5.3

* Added basic color customization.
* Fixed Flush bug.

## v0.5.2

* Added email notifications of new comments and new replies for all users (along with unsubcribe link) and notifications of new posts for admin users.

## v0.5.1

* Added a second `createdAt` timestamp. Score calculations still use the `submitted` timestamp, but it only gets set when (if) a post gets approved.

* Started keeping track of versions and changes.


text:
<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android">
    <item
        android:id="@+id/action_order"
        android:orderInCategory="100"
        android:showAsAction="always|withText"
        android:title="@string/action_order" />
</menu>


text:
package javax.swing;

/**
 * A SizeSequence object
 * efficiently maintains an ordered list
 * of sizes and corresponding positions.
 * One situation for which SizeSequence
 * might be appropriate is in a component
 * that displays multiple rows of unequal size.
 * In this case, a single SizeSequence
 * object could be used to track the heights
 * and Y positions of all rows.
 *

 * Another example would be a multi-column component,
 * such as a JTable,
 * in which the column sizes are not all equal.
 * The JTable might use a single
 * SizeSequence object
 * to store the widths and X positions of all the columns.
 * The JTable could then use the
 * SizeSequence object
 * to find the column corresponding to a certain position.
 * The JTable could update the
 * SizeSequence object
 * whenever one or more column sizes changed.
 *
 *

 * The following figure shows the relationship between size and position data
 * for a multi-column component.
 *

 *
 *
 *
 *

 * In the figure, the first index (0) corresponds to the first column,
 * the second index (1) to the second column, and so on.
 * The first column's position starts at 0,
 * and the column occupies size0 pixels,
 * where size0 is the value returned by
 * getSize(0).
 * Thus, the first column ends at size0 - 1.
 * The second column then begins at
 * the position size0
 * and occupies size1 (getSize(1)) pixels.
 *

 * Note that a SizeSequence object simply represents intervals
 * along an axis.
 * In our examples, the intervals represent height or width in pixels.
 * However, any other unit of measure (for example, time in days)
 * could be just as valid.
 *
 *

 *
 *
Implementation Notes

 *
 * Normally when storing the size and position of entries,
 * one would choose between
 * storing the sizes or storing their positions
 * instead. The two common operations that are needed during
 * rendering are: getIndex(position)
 * and setSize(index, size).
 * Whichever choice of internal format is made one of these
 * operations is costly when the number of entries becomes large.
 * If sizes are stored, finding the index of the entry
 * that encloses a particular position is linear in the
 * number of entries. If positions are stored instead, setting
 * the size of an entry at a particular index requires updating
 * the positions of the affected entries, which is also a linear
 * calculation.
 *

 * Like the above techniques this class holds an array of N integers
 * internally but uses a hybrid encoding, which is halfway
 * between the size-based and positional-based approaches.
 * The result is a data structure that takes the same space to store
 * the information but can perform most operations in Log(N) time
 * instead of O(N), where N is the number of entries in the list.
 *

 * Two operations that remain O(N) in the number of entries are
 * the insertEntries
 * and removeEntries methods, both
 * of which are implemented by converting the internal array to
 * a set of integer sizes, copying it into the new array, and then
 * reforming the hybrid representation in place.
 *
 * @author Philip Milne
 * @since 1.3
 */

/*
 *   Each method is implemented by taking the minimum and
 *   maximum of the range of integers that need to be operated
 *   upon. All the algorithms work by dividing this range
 *   into two smaller ranges and recursing. The recursion
 *   is terminated when the upper and lower bounds are equal.
 */

public class SizeSequence {

    private static int[] emptyArray = new int[0];
    private int a[];

    /**
     * Creates a new SizeSequence object
     * that contains no entries.  To add entries, you
     * can use insertEntries or setSizes.
     *
     * @see #insertEntries
     * @see #setSizes
     */
    public SizeSequence() {
        a = emptyArray;
    }

    /**
     * Creates a new SizeSequence object
     * that contains the specified number of entries,
     * all initialized to have size 0.
     *
     * @param numEntries  the number of sizes to track
     * @exception NegativeArraySizeException if
     *    numEntries < 0
     */
    public SizeSequence(int numEntries) {
        this(numEntries, 0);
    }

    /**
     * Creates a new SizeSequence object
     * that contains the specified number of entries,
     * all initialized to have size value.
     *
     * @param numEntries  the number of sizes to track
     * @param value       the initial value of each size
     */
    public SizeSequence(int numEntries, int value) {
        this();
        insertEntries(0, numEntries, value);
    }

    /**
     * Creates a new SizeSequence object
     * that contains the specified sizes.
     *
     * @param sizes  the array of sizes to be contained in
     *               the SizeSequence
     */
    public SizeSequence(int[] sizes) {
        this();
        setSizes(sizes);
    }

    /**
     * Resets the size sequence to contain length items
     * all with a size of size.
     */
    void setSizes(int length, int size) {
        if (a.length != length) {
            a = new int[length];
        }
        setSizes(0, length, size);
    }

    private int setSizes(int from, int to, int size) {
        if (to <= from) {
            return 0;
        }
        int m = (from + to)/2;
        a[m] = size + setSizes(from, m, size);
        return a[m] + setSizes(m + 1, to, size);
    }

    /**
     * Resets this SizeSequence object,
     * using the data in the sizes argument.
     * This method reinitializes this object so that it
     * contains as many entries as the sizes array.
     * Each entry's size is initialized to the value of the
     * corresponding item in sizes.
     *
     * @param sizes  the array of sizes to be contained in
     *               this SizeSequence
     */
    public void setSizes(int[] sizes) {
        if (a.length != sizes.length) {
            a = new int[sizes.length];
        }
        setSizes(0, a.length, sizes);
    }

    private int setSizes(int from, int to, int[] sizes) {
        if (to <= from) {
            return 0;
        }
        int m = (from + to)/2;
        a[m] = sizes[m] + setSizes(from, m, sizes);
        return a[m] + setSizes(m + 1, to, sizes);
    }

    /**
     * Returns the size of all entries.
     *
     * @return  a new array containing the sizes in this object
     */
    public int[] getSizes() {
        int n = a.length;
        int[] sizes = new int[n];
        getSizes(0, n, sizes);
        return sizes;
    }

    private int getSizes(int from, int to, int[] sizes) {
        if (to <= from) {
            return 0;
        }
        int m = (from + to)/2;
        sizes[m] = a[m] - getSizes(from, m, sizes);
        return a[m] + getSizes(m + 1, to, sizes);
    }

    /**
     * Returns the start position for the specified entry.
     * For example, getPosition(0) returns 0,
     * getPosition(1) is equal to
     *   getSize(0),
     * getPosition(2) is equal to
     *   getSize(0) + getSize(1),
     * and so on.
     *
Note that if index is greater than
     * length the value returned may
     * be meaningless.
     *
     * @param index  the index of the entry whose position is desired
     * @return       the starting position of the specified entry
     */
    public int getPosition(int index) {
        return getPosition(0, a.length, index);
    }

    private int getPosition(int from, int to, int index) {
        if (to <= from) {
            return 0;
        }
        int m = (from + to)/2;
        if (index <= m) {
            return getPosition(from, m, index);
        }
        else {
            return a[m] + getPosition(m + 1, to, index);
        }
    }

    /**
     * Returns the index of the entry
     * that corresponds to the specified position.
     * For example, getIndex(0) is 0,
     * since the first entry always starts at position 0.
     *
     * @param position  the position of the entry
     * @return  the index of the entry that occupies the specified position
     */
    public int getIndex(int position) {
        return getIndex(0, a.length, position);
    }

    private int getIndex(int from, int to, int position) {
        if (to <= from) {
            return from;
        }
        int m = (from + to)/2;
        int pivot = a[m];
        if (position < pivot) {
           return getIndex(from, m, position);
        }
        else {
            return getIndex(m + 1, to, position - pivot);
        }
    }

    /**
     * Returns the size of the specified entry.
     * If index is out of the range
     * (0 <= index < getSizes().length)
     * the behavior is unspecified.
     *
     * @param index  the index corresponding to the entry
     * @return  the size of the entry
     */
    public int getSize(int index) {
        return getPosition(index + 1) - getPosition(index);
    }

    /**
     * Sets the size of the specified entry.
     * Note that if the value of index
     * does not fall in the range:
     * (0 <= index < getSizes().length)
     * the behavior is unspecified.
     *
     * @param index  the index corresponding to the entry
     * @param size   the size of the entry
     */
    public void setSize(int index, int size) {
        changeSize(0, a.length, index, size - getSize(index));
    }

    private void changeSize(int from, int to, int index, int delta) {
        if (to <= from) {
            return;
        }
        int m = (from + to)/2;
        if (index <= m) {
            a[m] += delta;
            changeSize(from, m, index, delta);
        }
        else {
            changeSize(m + 1, to, index, delta);
        }
    }

    /**
     * Adds a contiguous group of entries to this SizeSequence.
     * Note that the values of start and
     * length must satisfy the following
     * conditions:  (0 <= start < getSizes().length)
     * AND (length >= 0).  If these conditions are
     * not met, the behavior is unspecified and an exception
     * may be thrown.
     *
     * @param start   the index to be assigned to the first entry
     *                in the group
     * @param length  the number of entries in the group
     * @param value   the size to be assigned to each new entry
     * @exception ArrayIndexOutOfBoundsException if the parameters
     *   are outside of the range:
     *   (0 <= start < (getSizes().length)) AND (length >= 0)
     */
    public void insertEntries(int start, int length, int value) {
        int sizes[] = getSizes();
        int end = start + length;
        int n = a.length + length;
        a = new int[n];
        for (int i = 0; i < start; i++) {
            a[i] = sizes[i] ;
        }
        for (int i = start; i < end; i++) {
            a[i] = value ;
        }
        for (int i = end; i < n; i++) {
            a[i] = sizes[i-length] ;
        }
        setSizes(a);
    }

    /**
     * Removes a contiguous group of entries
     * from this SizeSequence.
     * Note that the values of start and
     * length must satisfy the following
     * conditions:  (0 <= start < getSizes().length)
     * AND (length >= 0).  If these conditions are
     * not met, the behavior is unspecified and an exception
     * may be thrown.
     *
     * @param start   the index of the first entry to be removed
     * @param length  the number of entries to be removed
     */
    public void removeEntries(int start, int length) {
        int sizes[] = getSizes();
        int end = start + length;
        int n = a.length - length;
        a = new int[n];
        for (int i = 0; i < start; i++) {
            a[i] = sizes[i] ;
        }
        for (int i = start; i < n; i++) {
            a[i] = sizes[i+length] ;
        }
        setSizes(a);
    }
}


text:
"""ardbeg

Usage:
  ardbeg develop [--port=<port>]
  ardbeg publish
  ardbeg init
  ardbeg (-h | --help) --pagepath=<pagepath>
  ardbeg --version

Options:
  -h --help     Show this screen.
  --version     Show version.

"""
from docopt import docopt
import os
import sys
from ardbeg import directoryCheck, argCheck, make_publisher, initialize, getSettings

def start():
    global docArgs
    docArgs = docopt(__doc__, version='ardbeg 0.0.1')

    #Must be run from root of project directory
    ROOT = os.getcwd()

    develop = docArgs['develop']
    publish = docArgs['publish']
    init = docArgs['init']

    if init:
    	initialize()
    else:
      getSettings()
      templatePath = argCheck('templatePath')
      staticPath = argCheck('staticPath')
      contentPath = argCheck('contentPath')
      outputPath = argCheck('outputPath')
      dataPath = argCheck('dataPath')

      if docArgs['--port'] == None:
          devPort = '8000'
      else:
          devPort = docArgs['--port']

      publisher = make_publisher(
	    templatePath = templatePath,
	    staticPath   = staticPath  ,
	    outputPath   = outputPath  ,
	    contentPath  = contentPath ,
	    dataPath     = dataPath    ,
      devPort      = devPort     ,
	    )

      publisher.run(develop=develop,publish=publish)

if __name__ == '__main__':
    start()


text:
package se.claremont.taf.core.testcase;

import org.junit.runner.Description;
import org.junit.runner.notification.RunListener;

class TafParallelTestListener extends RunListener {

    @Override
    public void testStarted(Description description){
        System.out.println("Starting: " +description.getClassName() + "." + description.getMethodName());
    }
}


text:
<!DOCTYPE html>

    <title>TodoMVC Application</title>

    <link rel="stylesheet" href="./css/lib/bootstrap.min.css">
    <link rel="stylesheet" href="./css/lib/bootstrap-theme.min.css">
    <link rel="stylesheet" href="./css/lib/bootstrap-datetimepicker.min.css">

    <link rel="stylesheet" href="./css/main.css">

                <button type="button" class="navbar-toggle" data-toggle="collapse" data-target=".navbar-collapse">
                    Toggle navigation

                </button>
                TodoListMVC

Home

Create List


text:
#pragma once

/**
 * @file FindExitSensor.h
 * @brief Simple sensor to get an Exit.
 *
 * @author Michael Albers
 */

#include "Sensor.h"

namespace QS
{
  class Exit;

  /**
   * Pulls the first Exit out of the Sensable data, if there are Exits in the
   * Sensable data.
   */
  class FindExitSensor : public Sensor
  {
    public:

    /**
     * Default constructor.
     */
    FindExitSensor() = delete;

    /**
     * Constructor
     *
     * @param theProperties
     *           properties for the sensor
     * @param theTag
     *          optional user-defined tag for differentiating Sensors of the
     *          same type
     */
    FindExitSensor(const Properties &theProperties, const std::string &theTag);

    /**
     * Copy constructor.
     */
    FindExitSensor(const FindExitSensor&) = default;

    /**
     * Move constructor.
     */
    FindExitSensor(FindExitSensor&&) = default;

    /**
     * Destructor.
     */
    virtual ~FindExitSensor() = default;

    /**
     * Returns the Exit or nullptr if no Exit was found.
     *
     * @return exit or nullptr
     */
    const Exit* getExit() const noexcept;

    /**
     * Copy assignment operator.
     */
    FindExitSensor& operator=(const FindExitSensor&) = default;

    /**
     * Move assignment operator
     */
    FindExitSensor& operator=(FindExitSensor&&) = default;

    /**
     * Pulls an Exit from the Sensable data.
     *
     * @param theSensable
     *          object containing all that is able to be sensed within the
     *          simulation world.
     */
    virtual void sense(const Sensable &theSensable) override;

    protected:

    private:

    /** Exit from Sensable. */
    const Exit *myExit = nullptr;
  };
}


text:
using Nethereum.Contracts.CQS;
using Nethereum.RPC.Eth.DTOs;

namespace Nethereum.Contracts.MessageEncodingServices
{
    public interface IContractMessageTransactionInputCreator<TContractMessage>: IDefaultAddressService
        where TContractMessage : ContractMessageBase
    {
        TransactionInput CreateTransactionInput(TContractMessage contractMessage);
        CallInput CreateCallInput(TContractMessage contractMessage);
    }

    public interface IDefaultAddressService
    {
        string DefaultAddressFrom { get; set; }
    }
}


text:
package org.zstack.storage.primary.local;

/**
 * Created by frank on 10/16/2015.
 */
public interface LocalStorageReserveHostCapacityExtensionPoint {
    void beforeReserveLocalStorageCapacityOnHost(LocalStorageHostCapacityStruct struct);
}


text:
const chai = require('chai'),
  expect = chai.expect,
  sinon = require('sinon')

const postsService = require('../services/posts')

describe('posts service tests', () => {
  const obj = {
    data: 'ok'
  }

  const postSpy = {
    _Posts: {
      fetchAll: sinon.stub().returns(Promise.resolve(obj)),
      patch: sinon.stub(),
      forge: sinon.stub().returns({
        fetch: sinon.stub().returns(Promise.resolve(obj)),
        save: sinon.spy(),
        destroy: sinon.spy()
      })
    }
  }

  it('getAll is called', () => {
    postsService
      .getAll
      .call(postSpy)
      .then(response => {
        expect(response).to.be.equal(obj)
        expect(postSpy._Posts.fetchAll.calledOnce).to.be.true
      })
  })

  it('getOneById is called with proper id', () => {
    const id = {id: 1}

    postsService
      .getOneById
      .apply(postSpy, [id])
      .then(response => {
        expect(postSpy._Posts.forge.args[0][0]['id']).to.be.equal(id)
        expect(postSpy._Posts.forge.calledOnce).to.be.true

        expect(postSpy._Posts.forge().fetch.calledAfter(postSpy._Posts.forge))
        expect(postSpy._Posts.forge().fetch.calledOnce).to.be.true

        expect(response).to.be.equal(obj)
      })

  })
})


text:
var map = require('map-stream');
var gs = require('glob-stream');

var File = require('gulp-util').File;
var getContents = require('./getContents');
var getStats = require('./getStats');

module.exports = function(glob, opt) {
  if (!opt) opt = {};
  if (typeof opt.read !== 'boolean') opt.read = true;
  if (typeof opt.buffer !== 'boolean') opt.buffer = true;

  var globStream = gs.create(glob, opt);
  var formatStream = map(function(file, cb){
    cb(null, new File(file));
  });

  var stream = globStream.pipe(formatStream);

  return stream
    .pipe(getStats(opt))
    .pipe(getContents(opt));
};


text:
namespace CohesionAndCoupling
{
    using System;

    public static class RectangularCuboid
    {
        public static double Width
        {
            get;
            set;
        }

        public static double Height
        {
            get;
            set;
        }

        public static double Depth
        {
            get;
            set;
        }

        public static double CalcVolume()
        {
            double volume = Width * Height * Depth;
            return volume;
        }

        public static double CalcDiagonalXYZ()
        {
            double distance = MathUtils.CalcDistance3D(0, 0, 0, Width, Height, Depth);
            return distance;
        }

        public static double CalcDiagonalXY()
        {
            double distance = MathUtils.CalcDistance2D(0, 0, Width, Height);
            return distance;
        }

        public static double CalcDiagonalXZ()
        {
            double distance = MathUtils.CalcDistance2D(0, 0, Width, Depth);
            return distance;
        }

        public static double CalcDiagonalYZ()
        {
            double distance = MathUtils.CalcDistance2D(0, 0, Height, Depth);
            return distance;
        }
    }
}


text:
namespace AVRDisassembler.InstructionSet.OpCodes.DataTransfer
{
    public class STS16 : OpCode
    {
        public override string Name => "STS";
        public override string Comment => "Store Direct to Data Space";
    }
}


text:
**Namespace:** [OfficeDevPnP.Core.Framework.Provisioning.Providers.Xml.V201512](OfficeDevPnP.Core.Framework.Provisioning.Providers.Xml.V201512.md)
**Assembly:** OfficeDevPnP.Core.dll
## Syntax
```C#
public Provider[] Providers { get; set; }
```

### Property Value
Type: [OfficeDevPnP.Core.Framework.Provisioning.Providers.Xml.V201512.Provider[]](OfficeDevPnP.Core.Framework.Provisioning.Providers.Xml.V201512.Provider.md)

## See also
- [ProvisioningTemplate](OfficeDevPnP.Core.Framework.Provisioning.Providers.Xml.V201512.ProvisioningTemplate.md)
- [OfficeDevPnP.Core.Framework.Provisioning.Providers.Xml.V201512](OfficeDevPnP.Core.Framework.Provisioning.Providers.Xml.V201512.md)


text:
myAppModule.factory('factorys',['$http','$window','$timeout',function($http,$window,$timeout){    //公用
    return {
        praise : function(data,callback){
            if(typeof data.praiseNum == "object"){
                data.praiseNum = 0;
            }
            data.praiseNum++;
            $http({
                method:'POST',
                url: '/addArticle/praise',
                cache: false,
                data:data
            }).success(function(data, status) {
                callback(data)
            }).error(function(data,status,headers,config){
                $.messageBox({message:'请求视图信息出错!'})
            })
        }
    }
}]);


text:
layout: post
title:  "Tooltips"
categories: components
permalink: /components/tooltips/
---

Toolips are useful for adding in extra information, that doesn't make sense always showing.

    <button class="btn btn--primary">Hover Me</button>

``` html
<span class="tooltip" data-tooltip-title="We aim to respond to support queries within 72 hours">
  <button class="btn btn--primary">Hover Me</button>
</span>
```

    <button class="btn btn--primary">Hover Me</button>

``` html
<span class="tooltip tooltip--light" data-tooltip-title="We aim to respond to support queries within 72 hours">
  <button class="btn btn--primary">Hover Me</button>
</span>
```


text:
[鳥哥的 Linux 私房菜](http://linux.vbird.org/)

[Linux工具快速教程](https://linuxtools-rst.readthedocs.io/zh_CN/latest/index.html)

[systemctl](https://www.digitalocean.com/community/tutorials/how-to-use-systemctl-to-manage-systemd-services-and-units)


text:
namespace UnicornHack.Utils.MessagingECS;

public class EntityMatcher<TEntity> where TEntity : Entity
{
    private int[]? _allOfIds;
    private int[]? _anyOfIds;
    private int[]? _noneOfIds;

    public EntityMatcher<TEntity> AllOf(params int[] ids)
    {
        _allOfIds = Merge(_allOfIds, ids);
        return this;
    }

    public EntityMatcher<TEntity> AnyOf(params int[] ids)
    {
        _anyOfIds = Merge(_anyOfIds, ids);
        return this;
    }

    public EntityMatcher<TEntity> NoneOf(params int[] ids)
    {
        _noneOfIds = Merge(_noneOfIds, ids);
        return this;
    }

    public bool Matches(TEntity entity)
        => (_noneOfIds == null || !entity.HasAnyComponent(_noneOfIds))
           && (_allOfIds == null || entity.HasComponents(_allOfIds))
           && (_anyOfIds == null || entity.HasAnyComponent(_anyOfIds));

    public IEnumerable<int> GetAllIds()
        => (_allOfIds ?? Enumerable.Empty<int>())
            .Concat(_anyOfIds ?? Enumerable.Empty<int>())
            .Concat(_noneOfIds ?? Enumerable.Empty<int>())
            .Distinct();

    private static int[] Merge(int[]? firstArray, int[] secondArray)
        => firstArray?.Concat(secondArray).Distinct().OrderBy(id => id).ToArray()
           ?? secondArray;
}


text:
<meta charset="UTF-8">
<title>Pos - library</title>
<link rel="stylesheet" href="../../../style.css">

library / org.akop.ararat.core / Pos

Pos

data class Pos

Constructors

<init>

Pos(<span class="identifier" id="org.akop.ararat.core.Pos$<init>(kotlin.Int, kotlin.Int)/r">r: Int = 0, <span class="identifier" id="org.akop.ararat.core.Pos$<init>(kotlin.Int, kotlin.Int)/c">c: Int = 0)

Properties

c

var c: Int

r

var r: Int

Functions

set

fun set(r: Int, c: Int): Unit


text:
import * as React from 'react';

import { StandardProps } from '@material-ui/core';

export interface ToggleButtonGroupProps
  extends StandardProps<
    React.HTMLAttributes<HTMLDivElement>,
    ToggleButtonGroupClassKey,
    'onChange' | 'children'
  > {
  /**
   * The content of the button.
   */
  children?: React.ReactNode;
  /**
   * If `true`, only allow one of the child ToggleButton values to be selected.
   */
  exclusive?: boolean;
  /**
   * Callback fired when the value changes.
   *
   * @param {object} event The event source of the callback.
   * @param {any} value of the selected buttons. When `exclusive` is true
   * this is a single value; when false an array of selected values. If no value
   * is selected and `exclusive` is true the value is null; when false an empty array.
   */
  onChange?: (event: React.MouseEvent<HTMLElement>, value: any) => void;
  /**
   * The group orientation (layout flow direction).
   */
  orientation?: 'horizontal' | 'vertical';
  /**
   * The size of the buttons.
   */
  size?: 'small' | 'medium' | 'large';
  /**
   * The currently selected value within the group or an array of selected
   * values when `exclusive` is false.
   *
   * The value must have reference equality with the option in order to be selected.
   */
  value?: any;
}

export type ToggleButtonGroupClassKey =
  | 'root'
  | 'vertical'
  | 'grouped'
  | 'groupedHorizontal'
  | 'groupedVertical';

/**
 *
 * Demos:
 *
 * - [Toggle Button](https://material-ui.com/components/toggle-button/)
 *
 * API:
 *
 * - [ToggleButtonGroup API](https://material-ui.com/api/toggle-button-group/)
 */
export default function ToggleButtonGroup(props: ToggleButtonGroupProps): JSX.Element;