text:
/*
 * angular-ui-bootstrap
 * http://angular-ui.github.io/bootstrap/

 * Version: 0.12.0 - 2014-11-16
 * License: MIT
 */
angular.module("ui.bootstrap", ["ui.bootstrap.tpls","ui.bootstrap.datepicker","ui.bootstrap.dateparser","ui.bootstrap.position"]);
angular.module("ui.bootstrap.tpls", ["template/datepicker/datepicker.html","template/datepicker/day.html","template/datepicker/month.html","template/datepicker/popup.html","template/datepicker/year.html"]);
angular.module('ui.bootstrap.datepicker', ['ui.bootstrap.dateparser', 'ui.bootstrap.position'])

.constant('datepickerConfig', {
  formatDay: 'dd',
  formatMonth: 'MMMM',
  formatYear: 'yyyy',
  formatDayHeader: 'EEE',
  formatDayTitle: 'MMMM yyyy',
  formatMonthTitle: 'yyyy',
  datepickerMode: 'day',
  minMode: 'day',
  maxMode: 'year',
  showWeeks: true,
  startingDay: 0,
  yearRange: 20,
  minDate: null,
  maxDate: null
})

.controller('DatepickerController', ['$scope', '$attrs', '$parse', '$interpolate', '$timeout', '$log', 'dateFilter', 'datepickerConfig', function($scope, $attrs, $parse, $interpolate, $timeout, $log, dateFilter, datepickerConfig) {
  var self = this,
      ngModelCtrl = { $setViewValue: angular.noop }; // nullModelCtrl;

  // Modes chain
  this.modes = ['day', 'month', 'year'];

  // Configuration attributes
  angular.forEach(['formatDay', 'formatMonth', 'formatYear', 'formatDayHeader', 'formatDayTitle', 'formatMonthTitle',
                   'minMode', 'maxMode', 'showWeeks', 'startingDay', 'yearRange'], function( key, index ) {
    self[key] = angular.isDefined($attrs[key]) ? (index < 8 ? $interpolate($attrs[key])($scope.$parent) : $scope.$parent.$eval($attrs[key])) : datepickerConfig[key];
  });

  // Watchable date attributes
  angular.forEach(['minDate', 'maxDate'], function( key ) {
    if ( $attrs[key] ) {
      $scope.$parent.$watch($parse($attrs[key]), function(value) {
        self[key] = value ? new Date(value) : null;
        self.refreshView();
      });
    } else {
      self[key] = datepickerConfig[key] ? new Date(datepickerConfig[key]) : null;
    }
  });

  $scope.datepickerMode = $scope.datepickerMode || datepickerConfig.datepickerMode;
  $scope.uniqueId = 'datepicker-' + $scope.$id + '-' + Math.floor(Math.random() * 10000);
  this.activeDate = angular.isDefined($attrs.initDate) ? $scope.$parent.$eval($attrs.initDate) : new Date();

  $scope.isActive = function(dateObject) {
    if (self.compare(dateObject.date, self.activeDate) === 0) {
      $scope.activeDateId = dateObject.uid;
      return true;
    }
    return false;
  };

  this.init = function( ngModelCtrl_ ) {
    ngModelCtrl = ngModelCtrl_;

    ngModelCtrl.$render = function() {
      self.render();
    };
  };

  this.render = function() {
    if ( ngModelCtrl.$modelValue ) {
      var date = new Date( ngModelCtrl.$modelValue ),
          isValid = !isNaN(date);

      if ( isValid ) {
        this.activeDate = date;
      } else {
        $log.error('Datepicker directive: "ng-model" value must be a Date object, a number of milliseconds since 01.01.1970 or a string representing an RFC2822 or ISO 8601 date.');
      }
      ngModelCtrl.$setValidity('date', isValid);
    }
    this.refreshView();
  };

  this.refreshView = function() {
    if ( this.element ) {
      this._refreshView();

      var date = ngModelCtrl.$modelValue ? new Date(ngModelCtrl.$modelValue) : null;
      ngModelCtrl.$setValidity('date-disabled', !date || (this.element && !this.isDisabled(date)));
    }
  };

  this.createDateObject = function(date, format) {
    var model = ngModelCtrl.$modelValue ? new Date(ngModelCtrl.$modelValue) : null;
    return {
      date: date,
      label: dateFilter(date, format),
      selected: model && this.compare(date, model) === 0,
      disabled: this.isDisabled(date),
      current: this.compare(date, new Date()) === 0
    };
  };

  this.isDisabled = function( date ) {
    return ((this.minDate && this.compare(date, this.minDate) < 0) || (this.maxDate && this.compare(date, this.maxDate) > 0) || ($attrs.dateDisabled && $scope.dateDisabled({date: date, mode: $scope.datepickerMode})));
  };

  // Split array into smaller arrays
  this.split = function(arr, size) {
    var arrays = [];
    while (arr.length > 0) {
      arrays.push(arr.splice(0, size));
    }
    return arrays;
  };

  $scope.select = function( date ) {
    if ( $scope.datepickerMode === self.minMode ) {
      var dt = ngModelCtrl.$modelValue ? new Date( ngModelCtrl.$modelValue ) : new Date(0, 0, 0, 0, 0, 0, 0);
      dt.setFullYear( date.getFullYear(), date.getMonth(), date.getDate() );
      ngModelCtrl.$setViewValue( dt );
      ngModelCtrl.$render();
    } else {
      self.activeDate = date;
      $scope.datepickerMode = self.modes[ self.modes.indexOf( $scope.datepickerMode ) - 1 ];
    }
  };

  $scope.move = function( direction ) {
    var year = self.activeDate.getFullYear() + direction * (self.step.years || 0),
        month = self.activeDate.getMonth() + direction * (self.step.months || 0);
    self.activeDate.setFullYear(year, month, 1);
    self.refreshView();
  };

  $scope.toggleMode = function( direction ) {
    direction = direction || 1;

    if (($scope.datepickerMode === self.maxMode && direction === 1) || ($scope.datepickerMode === self.minMode && direction === -1)) {
      return;
    }

    $scope.datepickerMode = self.modes[ self.modes.indexOf( $scope.datepickerMode ) + direction ];
  };

  // Key event mapper
  $scope.keys = { 13:'enter', 32:'space', 33:'pageup', 34:'pagedown', 35:'end', 36:'home', 37:'left', 38:'up', 39:'right', 40:'down' };

  var focusElement = function() {
    $timeout(function() {
      self.element[0].focus();
    }, 0 , false);
  };

  // Listen for focus requests from popup directive
  $scope.$on('datepicker.focus', focusElement);

  $scope.keydown = function( evt ) {
    var key = $scope.keys[evt.which];

    if ( !key || evt.shiftKey || evt.altKey ) {
      return;
    }

    evt.preventDefault();
    evt.stopPropagation();

    if (key === 'enter' || key === 'space') {
      if ( self.isDisabled(self.activeDate)) {
        return; // do nothing
      }
      $scope.select(self.activeDate);
      focusElement();
    } else if (evt.ctrlKey && (key === 'up' || key === 'down')) {
      $scope.toggleMode(key === 'up' ? 1 : -1);
      focusElement();
    } else {
      self.handleKeyDown(key, evt);
      self.refreshView();
    }
  };
}])

.directive( 'datepicker', function () {
  return {
    restrict: 'EA',
    replace: true,
    templateUrl: 'template/datepicker/datepicker.html',
    scope: {
      datepickerMode: '=?',
      dateDisabled: '&'
    },
    require: ['datepicker', '?^ngModel'],
    controller: 'DatepickerController',
    link: function(scope, element, attrs, ctrls) {
      var datepickerCtrl = ctrls[0], ngModelCtrl = ctrls[1];

      if ( ngModelCtrl ) {
        datepickerCtrl.init( ngModelCtrl );
      }
    }
  };
})

.directive('daypicker', ['dateFilter', function (dateFilter) {
  return {
    restrict: 'EA',
    replace: true,
    templateUrl: 'template/datepicker/day.html',
    require: '^datepicker',
    link: function(scope, element, attrs, ctrl) {
      scope.showWeeks = ctrl.showWeeks;

      ctrl.step = { months: 1 };
      ctrl.element = element;

      var DAYS_IN_MONTH = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31];
      function getDaysInMonth( year, month ) {
        return ((month === 1) && (year % 4 === 0) && ((year % 100 !== 0) || (year % 400 === 0))) ? 29 : DAYS_IN_MONTH[month];
      }

      function getDates(startDate, n) {
        var dates = new Array(n), current = new Date(startDate), i = 0;
        current.setHours(12); // Prevent repeated dates because of timezone bug
        while ( i < n ) {
          dates[i++] = new Date(current);
          current.setDate( current.getDate() + 1 );
        }
        return dates;
      }

      ctrl._refreshView = function() {
        var year = ctrl.activeDate.getFullYear(),
          month = ctrl.activeDate.getMonth(),
          firstDayOfMonth = new Date(year, month, 1),
          difference = ctrl.startingDay - firstDayOfMonth.getDay(),
          numDisplayedFromPreviousMonth = (difference > 0) ? 7 - difference : - difference,
          firstDate = new Date(firstDayOfMonth);

        if ( numDisplayedFromPreviousMonth > 0 ) {
          firstDate.setDate( - numDisplayedFromPreviousMonth + 1 );
        }

        // 42 is the number of days on a six-month calendar
        var days = getDates(firstDate, 42);
        for (var i = 0; i < 42; i ++) {
          days[i] = angular.extend(ctrl.createDateObject(days[i], ctrl.formatDay), {
            secondary: days[i].getMonth() !== month,
            uid: scope.uniqueId + '-' + i
          });
        }

        scope.labels = new Array(7);
        for (var j = 0; j < 7; j++) {
          scope.labels[j] = {
            abbr: dateFilter(days[j].date, ctrl.formatDayHeader),
            full: dateFilter(days[j].date, 'EEEE')
          };
        }

        scope.title = dateFilter(ctrl.activeDate, ctrl.formatDayTitle);
        scope.rows = ctrl.split(days, 7);

        if ( scope.showWeeks ) {
          scope.weekNumbers = [];
          var weekNumber = getISO8601WeekNumber( scope.rows[0][0].date ),
              numWeeks = scope.rows.length;
          while( scope.weekNumbers.push(weekNumber++) < numWeeks ) {}
        }
      };

      ctrl.compare = function(date1, date2) {
        return (new Date( date1.getFullYear(), date1.getMonth(), date1.getDate() ) - new Date( date2.getFullYear(), date2.getMonth(), date2.getDate() ) );
      };

      function getISO8601WeekNumber(date) {
        var checkDate = new Date(date);
        checkDate.setDate(checkDate.getDate() + 4 - (checkDate.getDay() || 7)); // Thursday
        var time = checkDate.getTime();
        checkDate.setMonth(0); // Compare with Jan 1
        checkDate.setDate(1);
        return Math.floor(Math.round((time - checkDate) / 86400000) / 7) + 1;
      }

      ctrl.handleKeyDown = function( key, evt ) {
        var date = ctrl.activeDate.getDate();

        if (key === 'left') {
          date = date - 1;   // up
        } else if (key === 'up') {
          date = date - 7;   // down
        } else if (key === 'right') {
          date = date + 1;   // down
        } else if (key === 'down') {
          date = date + 7;
        } else if (key === 'pageup' || key === 'pagedown') {
          var month = ctrl.activeDate.getMonth() + (key === 'pageup' ? - 1 : 1);
          ctrl.activeDate.setMonth(month, 1);
          date = Math.min(getDaysInMonth(ctrl.activeDate.getFullYear(), ctrl.activeDate.getMonth()), date);
        } else if (key === 'home') {
          date = 1;
        } else if (key === 'end') {
          date = getDaysInMonth(ctrl.activeDate.getFullYear(), ctrl.activeDate.getMonth());
        }
        ctrl.activeDate.setDate(date);
      };

      ctrl.refreshView();
    }
  };
}])

.directive('monthpicker', ['dateFilter', function (dateFilter) {
  return {
    restrict: 'EA',
    replace: true,
    templateUrl: 'template/datepicker/month.html',
    require: '^datepicker',
    link: function(scope, element, attrs, ctrl) {
      ctrl.step = { years: 1 };
      ctrl.element = element;

      ctrl._refreshView = function() {
        var months = new Array(12),
            year = ctrl.activeDate.getFullYear();

        for ( var i = 0; i < 12; i++ ) {
          months[i] = angular.extend(ctrl.createDateObject(new Date(year, i, 1), ctrl.formatMonth), {
            uid: scope.uniqueId + '-' + i
          });
        }

        scope.title = dateFilter(ctrl.activeDate, ctrl.formatMonthTitle);
        scope.rows = ctrl.split(months, 3);
      };

      ctrl.compare = function(date1, date2) {
        return new Date( date1.getFullYear(), date1.getMonth() ) - new Date( date2.getFullYear(), date2.getMonth() );
      };

      ctrl.handleKeyDown = function( key, evt ) {
        var date = ctrl.activeDate.getMonth();

        if (key === 'left') {
          date = date - 1;   // up
        } else if (key === 'up') {
          date = date - 3;   // down
        } else if (key === 'right') {
          date = date + 1;   // down
        } else if (key === 'down') {
          date = date + 3;
        } else if (key === 'pageup' || key === 'pagedown') {
          var year = ctrl.activeDate.getFullYear() + (key === 'pageup' ? - 1 : 1);
          ctrl.activeDate.setFullYear(year);
        } else if (key === 'home') {
          date = 0;
        } else if (key === 'end') {
          date = 11;
        }
        ctrl.activeDate.setMonth(date);
      };

      ctrl.refreshView();
    }
  };
}])

.directive('yearpicker', ['dateFilter', function (dateFilter) {
  return {
    restrict: 'EA',
    replace: true,
    templateUrl: 'template/datepicker/year.html',
    require: '^datepicker',
    link: function(scope, element, attrs, ctrl) {
      var range = ctrl.yearRange;

      ctrl.step = { years: range };
      ctrl.element = element;

      function getStartingYear( year ) {
        return parseInt((year - 1) / range, 10) * range + 1;
      }

      ctrl._refreshView = function() {
        var years = new Array(range);

        for ( var i = 0, start = getStartingYear(ctrl.activeDate.getFullYear()); i < range; i++ ) {
          years[i] = angular.extend(ctrl.createDateObject(new Date(start + i, 0, 1), ctrl.formatYear), {
            uid: scope.uniqueId + '-' + i
          });
        }

        scope.title = [years[0].label, years[range - 1].label].join(' - ');
        scope.rows = ctrl.split(years, 5);
      };

      ctrl.compare = function(date1, date2) {
        return date1.getFullYear() - date2.getFullYear();
      };

      ctrl.handleKeyDown = function( key, evt ) {
        var date = ctrl.activeDate.getFullYear();

        if (key === 'left') {
          date = date - 1;   // up
        } else if (key === 'up') {
          date = date - 5;   // down
        } else if (key === 'right') {
          date = date + 1;   // down
        } else if (key === 'down') {
          date = date + 5;
        } else if (key === 'pageup' || key === 'pagedown') {
          date += (key === 'pageup' ? - 1 : 1) * ctrl.step.years;
        } else if (key === 'home') {
          date = getStartingYear( ctrl.activeDate.getFullYear() );
        } else if (key === 'end') {
          date = getStartingYear( ctrl.activeDate.getFullYear() ) + range - 1;
        }
        ctrl.activeDate.setFullYear(date);
      };

      ctrl.refreshView();
    }
  };
}])

.constant('datepickerPopupConfig', {
  datepickerPopup: 'yyyy-MM-dd',
  currentText: 'Today',
  clearText: 'Clear',
  closeText: 'Done',
  closeOnDateSelection: true,
  appendToBody: false,
  showButtonBar: true
})

.directive('datepickerPopup', ['$compile', '$parse', '$document', '$position', 'dateFilter', 'dateParser', 'datepickerPopupConfig',
function ($compile, $parse, $document, $position, dateFilter, dateParser, datepickerPopupConfig) {
  return {
    restrict: 'EA',
    require: 'ngModel',
    scope: {
      isOpen: '=?',
      currentText: '@',
      clearText: '@',
      closeText: '@',
      dateDisabled: '&'
    },
    link: function(scope, element, attrs, ngModel) {
      var dateFormat,
          closeOnDateSelection = angular.isDefined(attrs.closeOnDateSelection) ? scope.$parent.$eval(attrs.closeOnDateSelection) : datepickerPopupConfig.closeOnDateSelection,
          appendToBody = angular.isDefined(attrs.datepickerAppendToBody) ? scope.$parent.$eval(attrs.datepickerAppendToBody) : datepickerPopupConfig.appendToBody;

      scope.showButtonBar = angular.isDefined(attrs.showButtonBar) ? scope.$parent.$eval(attrs.showButtonBar) : datepickerPopupConfig.showButtonBar;

      scope.getText = function( key ) {
        return scope[key + 'Text'] || datepickerPopupConfig[key + 'Text'];
      };

      attrs.$observe('datepickerPopup', function(value) {
          dateFormat = value || datepickerPopupConfig.datepickerPopup;
          ngModel.$render();
      });

      // popup element used to display calendar
      var popupEl = angular.element('

');
      popupEl.attr({
        'ng-model': 'date',
        'ng-change': 'dateSelection()'
      });

      function cameltoDash( string ){
        return string.replace(/([A-Z])/g, function($1) { return '-' + $1.toLowerCase(); });
      }

      // datepicker element
      var datepickerEl = angular.element(popupEl.children()[0]);
      if ( attrs.datepickerOptions ) {
        angular.forEach(scope.$parent.$eval(attrs.datepickerOptions), function( value, option ) {
          datepickerEl.attr( cameltoDash(option), value );
        });
      }

      scope.watchData = {};
      angular.forEach(['minDate', 'maxDate', 'datepickerMode'], function( key ) {
        if ( attrs[key] ) {
          var getAttribute = $parse(attrs[key]);
          scope.$parent.$watch(getAttribute, function(value){
            scope.watchData[key] = value;
          });
          datepickerEl.attr(cameltoDash(key), 'watchData.' + key);

          // Propagate changes from datepicker to outside
          if ( key === 'datepickerMode' ) {
            var setAttribute = getAttribute.assign;
            scope.$watch('watchData.' + key, function(value, oldvalue) {
              if ( value !== oldvalue ) {
                setAttribute(scope.$parent, value);
              }
            });
          }
        }
      });
      if (attrs.dateDisabled) {
        datepickerEl.attr('date-disabled', 'dateDisabled({ date: date, mode: mode })');
      }

      function parseDate(viewValue) {
        if (!viewValue) {
          ngModel.$setValidity('date', true);
          return null;
        } else if (angular.isDate(viewValue) && !isNaN(viewValue)) {
          ngModel.$setValidity('date', true);
          return viewValue;
        } else if (angular.isString(viewValue)) {
          var date = dateParser.parse(viewValue, dateFormat) || new Date(viewValue);
          if (isNaN(date)) {
            ngModel.$setValidity('date', false);
            return undefined;
          } else {
            ngModel.$setValidity('date', true);
            return date;
          }
        } else {
          ngModel.$setValidity('date', false);
          return undefined;
        }
      }
      ngModel.$parsers.unshift(parseDate);

      // Inner change
      scope.dateSelection = function(dt) {
        if (angular.isDefined(dt)) {
          scope.date = dt;
        }
        ngModel.$setViewValue(scope.date);
        ngModel.$render();

        if ( closeOnDateSelection ) {
          scope.isOpen = false;
          element[0].focus();
        }
      };

      element.bind('input change keyup', function() {
        scope.$apply(function() {
          scope.date = ngModel.$modelValue;
        });
      });

      // Outter change
      ngModel.$render = function() {
        var date = ngModel.$viewValue ? dateFilter(ngModel.$viewValue, dateFormat) : '';
        element.val(date);
        scope.date = parseDate( ngModel.$modelValue );
      };

      var documentClickBind = function(event) {
        if (scope.isOpen && event.target !== element[0]) {
          scope.$apply(function() {
            scope.isOpen = false;
          });
        }
      };

      var keydown = function(evt, noApply) {
        scope.keydown(evt);
      };
      element.bind('keydown', keydown);

      scope.keydown = function(evt) {
        if (evt.which === 27) {
          evt.preventDefault();
          evt.stopPropagation();
          scope.close();
        } else if (evt.which === 40 && !scope.isOpen) {
          scope.isOpen = true;
        }
      };

      scope.$watch('isOpen', function(value) {
        if (value) {
          scope.$broadcast('datepicker.focus');
          scope.position = appendToBody ? $position.offset(element) : $position.position(element);
          scope.position.top = scope.position.top + element.prop('offsetHeight');

          $document.bind('click', documentClickBind);
        } else {
          $document.unbind('click', documentClickBind);
        }
      });

      scope.select = function( date ) {
        if (date === 'today') {
          var today = new Date();
          if (angular.isDate(ngModel.$modelValue)) {
            date = new Date(ngModel.$modelValue);
            date.setFullYear(today.getFullYear(), today.getMonth(), today.getDate());
          } else {
            date = new Date(today.setHours(0, 0, 0, 0));
          }
        }
        scope.dateSelection( date );
      };

      scope.close = function() {
        scope.isOpen = false;
        element[0].focus();
      };

      var $popup = $compile(popupEl)(scope);
      // Prevent jQuery cache memory leak (template is now redundant after linking)
      popupEl.remove();

      if ( appendToBody ) {
        $document.find('body').append($popup);
      } else {
        element.after($popup);
      }

      scope.$on('$destroy', function() {
        $popup.remove();
        element.unbind('keydown', keydown);
        $document.unbind('click', documentClickBind);
      });
    }
  };
}])

.directive('datepickerPopupWrap', function() {
  return {
    restrict:'EA',
    replace: true,
    transclude: true,
    templateUrl: 'template/datepicker/popup.html',
    link:function (scope, element, attrs) {
      element.bind('click', function(event) {
        event.preventDefault();
        event.stopPropagation();
      });
    }
  };
});

angular.module('ui.bootstrap.dateparser', [])

.service('dateParser', ['$locale', 'orderByFilter', function($locale, orderByFilter) {

  this.parsers = {};

  var formatCodeToRegex = {
    'yyyy': {
      regex: '\\d{4}',
      apply: function(value) { this.year = +value; }
    },
    'yy': {
      regex: '\\d{2}',
      apply: function(value) { this.year = +value + 2000; }
    },
    'y': {
      regex: '\\d{1,4}',
      apply: function(value) { this.year = +value; }
    },
    'MMMM': {
      regex: $locale.DATETIME_FORMATS.MONTH.join('|'),
      apply: function(value) { this.month = $locale.DATETIME_FORMATS.MONTH.indexOf(value); }
    },
    'MMM': {
      regex: $locale.DATETIME_FORMATS.SHORTMONTH.join('|'),
      apply: function(value) { this.month = $locale.DATETIME_FORMATS.SHORTMONTH.indexOf(value); }
    },
    'MM': {
      regex: '0[1-9]|1[0-2]',
      apply: function(value) { this.month = value - 1; }
    },
    'M': {
      regex: '[1-9]|1[0-2]',
      apply: function(value) { this.month = value - 1; }
    },
    'dd': {
      regex: '[0-2][0-9]{1}|3[0-1]{1}',
      apply: function(value) { this.date = +value; }
    },
    'd': {
      regex: '[1-2]?[0-9]{1}|3[0-1]{1}',
      apply: function(value) { this.date = +value; }
    },
    'EEEE': {
      regex: $locale.DATETIME_FORMATS.DAY.join('|')
    },
    'EEE': {
      regex: $locale.DATETIME_FORMATS.SHORTDAY.join('|')
    }
  };

  function createParser(format) {
    var map = [], regex = format.split('');

    angular.forEach(formatCodeToRegex, function(data, code) {
      var index = format.indexOf(code);

      if (index > -1) {
        format = format.split('');

        regex[index] = '(' + data.regex + ')';
        format[index] = '$'; // Custom symbol to define consumed part of format
        for (var i = index + 1, n = index + code.length; i < n; i++) {
          regex[i] = '';
          format[i] = '$';
        }
        format = format.join('');

        map.push({ index: index, apply: data.apply });
      }
    });

    return {
      regex: new RegExp('^' + regex.join('') + '$'),
      map: orderByFilter(map, 'index')
    };
  }

  this.parse = function(input, format) {
    if ( !angular.isString(input) || !format ) {
      return input;
    }

    format = $locale.DATETIME_FORMATS[format] || format;

    if ( !this.parsers[format] ) {
      this.parsers[format] = createParser(format);
    }

    var parser = this.parsers[format],
        regex = parser.regex,
        map = parser.map,
        results = input.match(regex);

    if ( results && results.length ) {
      var fields = { year: 1900, month: 0, date: 1, hours: 0 }, dt;

      for( var i = 1, n = results.length; i < n; i++ ) {
        var mapper = map[i-1];
        if ( mapper.apply ) {
          mapper.apply.call(fields, results[i]);
        }
      }

      if ( isValid(fields.year, fields.month, fields.date) ) {
        dt = new Date( fields.year, fields.month, fields.date, fields.hours);
      }

      return dt;
    }
  };

  // Check if date is valid for specific month (and year for February).
  // Month: 0 = Jan, 1 = Feb, etc
  function isValid(year, month, date) {
    if ( month === 1 && date > 28) {
        return date === 29 && ((year % 4 === 0 && year % 100 !== 0) || year % 400 === 0);
    }

    if ( month === 3 || month === 5 || month === 8 || month === 10) {
        return date < 31;
    }

    return true;
  }
}]);

angular.module('ui.bootstrap.position', [])

/**
 * A set of utility methods that can be use to retrieve position of DOM elements.
 * It is meant to be used where we need to absolute-position DOM elements in
 * relation to other, existing elements (this is the case for tooltips, popovers,
 * typeahead suggestions etc.).
 */
  .factory('$position', ['$document', '$window', function ($document, $window) {

    function getStyle(el, cssprop) {
      if (el.currentStyle) { //IE
        return el.currentStyle[cssprop];
      } else if ($window.getComputedStyle) {
        return $window.getComputedStyle(el)[cssprop];
      }
      // finally try and get inline style
      return el.style[cssprop];
    }

    /**
     * Checks if a given element is statically positioned
     * @param element - raw DOM element
     */
    function isStaticPositioned(element) {
      return (getStyle(element, 'position') || 'static' ) === 'static';
    }

    /**
     * returns the closest, non-statically positioned parentOffset of a given element
     * @param element
     */
    var parentOffsetEl = function (element) {
      var docDomEl = $document[0];
      var offsetParent = element.offsetParent || docDomEl;
      while (offsetParent && offsetParent !== docDomEl && isStaticPositioned(offsetParent) ) {
        offsetParent = offsetParent.offsetParent;
      }
      return offsetParent || docDomEl;
    };

    return {
      /**
       * Provides read-only equivalent of jQuery's position function:
       * http://api.jquery.com/position/
       */
      position: function (element) {
        var elBCR = this.offset(element);
        var offsetParentBCR = { top: 0, left: 0 };
        var offsetParentEl = parentOffsetEl(element[0]);
        if (offsetParentEl != $document[0]) {
          offsetParentBCR = this.offset(angular.element(offsetParentEl));
          offsetParentBCR.top += offsetParentEl.clientTop - offsetParentEl.scrollTop;
          offsetParentBCR.left += offsetParentEl.clientLeft - offsetParentEl.scrollLeft;
        }

        var boundingClientRect = element[0].getBoundingClientRect();
        return {
          width: boundingClientRect.width || element.prop('offsetWidth'),
          height: boundingClientRect.height || element.prop('offsetHeight'),
          top: elBCR.top - offsetParentBCR.top,
          left: elBCR.left - offsetParentBCR.left
        };
      },

      /**
       * Provides read-only equivalent of jQuery's offset function:
       * http://api.jquery.com/offset/
       */
      offset: function (element) {
        var boundingClientRect = element[0].getBoundingClientRect();
        return {
          width: boundingClientRect.width || element.prop('offsetWidth'),
          height: boundingClientRect.height || element.prop('offsetHeight'),
          top: boundingClientRect.top + ($window.pageYOffset || $document[0].documentElement.scrollTop),
          left: boundingClientRect.left + ($window.pageXOffset || $document[0].documentElement.scrollLeft)
        };
      },

      /**
       * Provides coordinates for the targetEl in relation to hostEl
       */
      positionElements: function (hostEl, targetEl, positionStr, appendToBody) {

        var positionStrParts = positionStr.split('-');
        var pos0 = positionStrParts[0], pos1 = positionStrParts[1] || 'center';

        var hostElPos,
          targetElWidth,
          targetElHeight,
          targetElPos;

        hostElPos = appendToBody ? this.offset(hostEl) : this.position(hostEl);

        targetElWidth = targetEl.prop('offsetWidth');
        targetElHeight = targetEl.prop('offsetHeight');

        var shiftWidth = {
          center: function () {
            return hostElPos.left + hostElPos.width / 2 - targetElWidth / 2;
          },
          left: function () {
            return hostElPos.left;
          },
          right: function () {
            return hostElPos.left + hostElPos.width;
          }
        };

        var shiftHeight = {
          center: function () {
            return hostElPos.top + hostElPos.height / 2 - targetElHeight / 2;
          },
          top: function () {
            return hostElPos.top;
          },
          bottom: function () {
            return hostElPos.top + hostElPos.height;
          }
        };

        switch (pos0) {
          case 'right':
            targetElPos = {
              top: shiftHeight[pos1](),
              left: shiftWidth[pos0]()
            };
            break;
          case 'left':
            targetElPos = {
              top: shiftHeight[pos1](),
              left: hostElPos.left - targetElWidth
            };
            break;
          case 'bottom':
            targetElPos = {
              top: shiftHeight[pos0](),
              left: shiftWidth[pos1]()
            };
            break;
          default:
            targetElPos = {
              top: hostElPos.top - targetElHeight,
              left: shiftWidth[pos1]()
            };
            break;
        }

        return targetElPos;
      }
    };
  }]);

angular.module("template/datepicker/datepicker.html", []).run(["$templateCache", function($templateCache) {
  $templateCache.put("template/datepicker/datepicker.html",
    "
\n" +
    "  <daypicker ng-switch-when=\"day\" tabindex=\"0\"></daypicker>\n" +
    "  <monthpicker ng-switch-when=\"month\" tabindex=\"0\"></monthpicker>\n" +
    "  <yearpicker ng-switch-when=\"year\" tabindex=\"0\"></yearpicker>\n" +
    "
");
}]);

angular.module("template/datepicker/day.html", []).run(["$templateCache", function($templateCache) {
  $templateCache.put("template/datepicker/day.html",
    "
\n" +
    "
\n" +
    "
\n" +
    "      <button type=\"button\" class=\"btn btn-default btn-sm pull-left\" ng-click=\"move(-1)\" tabindex=\"-1\"></button>	\n" +
    "      <button id=\"{{uniqueId}}-title\" role=\"heading\" aria-live=\"assertive\" aria-atomic=\"true\" type=\"button\" class=\"btn btn-default btn-sm\" ng-click=\"toggleMode()\" tabindex=\"-1\" style=\"width:100%;\">{{title}}</button>	\n" +
    "      <button type=\"button\" class=\"btn btn-default btn-sm pull-right\" ng-click=\"move(1)\" tabindex=\"-1\"></button>	\n" +
    "
\n" +
    "
\n" +
    "      	\n" +
    "      {{label.abbr}}	\n" +
    "
\n" +
    "
\n" +
    "
\n" +
    "
\n" +
    "      {{ weekNumbers[$index] }}	\n" +
    "      \n" +
    "        <button type=\"button\" style=\"width:100%;\" class=\"btn btn-default btn-sm\" ng-class=\"{'btn-info': dt.selected, active: isActive(dt)}\" ng-click=\"select(dt.date)\" ng-disabled=\"dt.disabled\" tabindex=\"-1\">{{dt.label}}</button>\n" +
    "      	\n" +
    "
\n" +
    "
\n" +
    "
\n" +
    "");
}]);

angular.module("template/datepicker/month.html", []).run(["$templateCache", function($templateCache) {
  $templateCache.put("template/datepicker/month.html",
    "
\n" +
    "
\n" +
    "
\n" +
    "      <button type=\"button\" class=\"btn btn-default btn-sm pull-left\" ng-click=\"move(-1)\" tabindex=\"-1\"></button>	\n" +
    "      <button id=\"{{uniqueId}}-title\" role=\"heading\" aria-live=\"assertive\" aria-atomic=\"true\" type=\"button\" class=\"btn btn-default btn-sm\" ng-click=\"toggleMode()\" tabindex=\"-1\" style=\"width:100%;\">{{title}}</button>	\n" +
    "      <button type=\"button\" class=\"btn btn-default btn-sm pull-right\" ng-click=\"move(1)\" tabindex=\"-1\"></button>	\n" +
    "
\n" +
    "
\n" +
    "
\n" +
    "
\n" +
    "      \n" +
    "        <button type=\"button\" style=\"width:100%;\" class=\"btn btn-default\" ng-class=\"{'btn-info': dt.selected, active: isActive(dt)}\" ng-click=\"select(dt.date)\" ng-disabled=\"dt.disabled\" tabindex=\"-1\">{{dt.label}}</button>\n" +
    "      	\n" +
    "
\n" +
    "
\n" +
    "
\n" +
    "");
}]);

angular.module("template/datepicker/popup.html", []).run(["$templateCache", function($templateCache) {
  $templateCache.put("template/datepicker/popup.html",
    "
\n" +
    "

\n" +
    "
\n" +
    "		\n" +
    "			<button type=\"button\" class=\"btn btn-sm btn-info\" ng-click=\"select('today')\">{{ getText('current') }}</button>\n" +
    "			<button type=\"button\" class=\"btn btn-sm btn-danger\" ng-click=\"select(null)\">{{ getText('clear') }}</button>\n" +
    "		\n" +
    "		<button type=\"button\" class=\"btn btn-sm btn-success pull-right\" ng-click=\"close()\">{{ getText('close') }}</button>\n" +
    "
\n" +
    "
\n" +
    "");
}]);

angular.module("template/datepicker/year.html", []).run(["$templateCache", function($templateCache) {
  $templateCache.put("template/datepicker/year.html",
    "
\n" +
    "
\n" +
    "
\n" +
    "      <button type=\"button\" class=\"btn btn-default btn-sm pull-left\" ng-click=\"move(-1)\" tabindex=\"-1\"></button>	\n" +
    "      <button id=\"{{uniqueId}}-title\" role=\"heading\" aria-live=\"assertive\" aria-atomic=\"true\" type=\"button\" class=\"btn btn-default btn-sm\" ng-click=\"toggleMode()\" tabindex=\"-1\" style=\"width:100%;\">{{title}}</button>	\n" +
    "      <button type=\"button\" class=\"btn btn-default btn-sm pull-right\" ng-click=\"move(1)\" tabindex=\"-1\"></button>	\n" +
    "
\n" +
    "
\n" +
    "
\n" +
    "
\n" +
    "      \n" +
    "        <button type=\"button\" style=\"width:100%;\" class=\"btn btn-default\" ng-class=\"{'btn-info': dt.selected, active: isActive(dt)}\" ng-click=\"select(dt.date)\" ng-disabled=\"dt.disabled\" tabindex=\"-1\">{{dt.label}}</button>\n" +
    "      	\n" +
    "
\n" +
    "
\n" +
    "
\n" +
    "");
}]);


text:
<?php

namespace Application\Backend\UserBundle\Service;

use Application\Common\CommonBundle\Service\BaseService;

/**
 * Class UserService.
 *
 * @author  Marcin Jasinski <mkjasinski@gmail.com>
 */
class UserService extends BaseService
{
    /**
     * {@inheritdoc}
     */
    public function create($element)
    {
    }

    /**
     * {@inheritdoc}
     */
    public function update($element)
    {
    }

    /**
     * {@inheritdoc}
     */
    public function delete($id)
    {
    }
}

redpajama_set_name: RedPajamaGithub


text:
'''
"imagen": "http://image.slidesharecdn.com/mapadelasestaciones-150313011821-conversion-gate01/95/mapa-de-las-estaciones-del-ao-en-formato-ppt-1-638.jpg?cb=1426227529",
        "url": "http://es.slideshare.net/JosManuelMarcos/mapa-de-las-estaciones-del-ao-en-formato-ppt",
        "fecha": "13 de marzo de 2015",
        "label": "Mapa de las estaciones del a\u00f1o (en formato ppt).",
        "autor": ["Jos\u00e9 Manuel Marcos Rodrigo"],
        "id": "mapa-de-las-estaciones-del-ao-en-formato-ppt",
        "desc": "Mapa sencillo para explicar el paso de las Estaciones asociado al movimiento de traslaci\u00f3n de la Tierra alrededor del Sol."
    }
    '''

import scrapy

class SlideshareItem(scrapy.Item):
    # define the fields for your item here like:
    # name = scrapy.Field()
    label = scrapy.Field()
    fecha = scrapy.Field()
    url = scrapy.Field()
    autor = scrapy.Field()
    id = scrapy.Field()
    desc = scrapy.Field()
    imagen = scrapy.Field()
    lang = scrapy.Field()
    plays = scrapy.Field()


text:
<?php

use Rize\UriTemplate;
use Rize\UriTemplate\Node;
use Rize\UriTemplate\Operator;
use Rize\UriTemplate\Parser;

class ParserTest extends PHPUnit_Framework_TestCase
{
    protected function service()
    {
        return new Parser;
    }

    public function testParseTemplate()
    {
        $input = 'http://www.example.com/{term:1}/{term}/{test*}/foo{?query,number}';
        $expected = array(
            new Node\Literal('http://www.example.com/'),
            new Node\Expression(
                'term:1',
                Operator\Abstraction::createById(''),
                array(
                    new Node\Variable(
                        'term:1',
                        array(
                            'modifier' => ':',
                            'value'    => 1,
                        )
                    ),
                )
            ),
            new Node\Literal('/'),
            new Node\Expression(
                'term',
                Operator\Abstraction::createById(''),
                array(
                    new Node\Variable(
                        'term',
                        array(
                            'modifier' => null,
                            'value'    => null,
                        )
                    ),
                )
            ),
            new Node\Literal('/'),
            new Node\Expression(
                'test*',
                Operator\Abstraction::createById(''),
                array(
                    new Node\Variable(
                        'test',
                        array(
                            'modifier' => '*',
                            'value'    => null,
                        )
                    ),
                )
            ),
            new Node\Literal('/foo'),
            new Node\Expression(
                'query,number',
                Operator\Abstraction::createById('?'),
                array(
                    new Node\Variable(
                        'query',
                        array(
                            'modifier' => null,
                            'value'    => null,
                        )
                    ),
                    new Node\Variable(
                        'number',
                        array(
                            'modifier' => null,
                            'value'    => null,
                        )
                    ),
                )
            ),
        );

        $service = $this->service();
        $actual  = $service->parse($input);

        $this->assertEquals($expected, $actual);
    }

    public function testParseTemplateWithLiteral()
    {
        // will pass
        $uri = new UriTemplate('http://www.example.com/v1/company/', array());
        $params = $uri->extract('/{countryCode}/{registrationNumber}/test{.format}', '/gb/0123456/test.json');
        static::assertEquals(array('countryCode' => 'gb', 'registrationNumber' => '0123456', 'format' => 'json'), $params);
    }

    /**
     * @depends testParseTemplateWithLiteral
     */
    public function testParseTemplateWithTwoVariablesAndDotBetween()
    {
        // will fail
        $uri = new UriTemplate('http://www.example.com/v1/company/', array());
        $params = $uri->extract('/{countryCode}/{registrationNumber}{.format}', '/gb/0123456.json');
        static::assertEquals(array('countryCode' => 'gb', 'registrationNumber' => '0123456', 'format' => 'json'), $params);
    }

    /**
     * @ depends testParseTemplateWithLiteral
     */
    public function testParseTemplateWithTwoVariablesAndDotBetweenStrict()
    {
        // will fail
        $uri = new UriTemplate('http://www.example.com/v1/company/', array());
        $params = $uri->extract('/{countryCode}/{registrationNumber}{.format}', '/gb/0123456.json', true);
        static::assertEquals(array('countryCode' => 'gb', 'registrationNumber' => '0123456', 'format' => 'json'), $params);
    }

    /**
     * @ depends testParseTemplateWithLiteral
     */
    public function testParseTemplateWithThreeVariablesAndDotBetweenStrict()
    {
        // will fail
        $uri = new UriTemplate('http://www.example.com/v1/company/', array());
        $params = $uri->extract('/{countryCode}/{registrationNumber}{.namespace}{.format}', '/gb/0123456.company.json');
        static::assertEquals(array('countryCode' => 'gb', 'registrationNumber' => '0123456', 'namespace' => 'company', 'format' => 'json'), $params);
    }
}


text:
package org.motechproject.decisiontree.server.service;

import org.apache.commons.lang.StringEscapeUtils;
import org.motechproject.decisiontree.core.DecisionTreeService;
import org.motechproject.decisiontree.core.EndOfCallEvent;
import org.motechproject.decisiontree.core.FlowSession;
import org.motechproject.decisiontree.core.TreeNodeLocator;
import org.motechproject.decisiontree.core.model.CallStatus;
import org.motechproject.decisiontree.core.model.DialStatus;
import org.motechproject.decisiontree.core.model.INodeOperation;
import org.motechproject.decisiontree.core.model.ITransition;
import org.motechproject.decisiontree.core.model.Node;
import org.motechproject.decisiontree.core.model.Transition;
import org.motechproject.decisiontree.server.domain.CallDetailRecord;
import org.motechproject.decisiontree.server.domain.FlowSessionRecord;
import org.motechproject.event.listener.EventRelay;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.stereotype.Service;
import org.springframework.web.servlet.ModelAndView;

import java.util.HashMap;
import java.util.Map;

import static java.lang.String.format;
import static org.apache.commons.lang.StringUtils.isBlank;
import static org.motechproject.commons.date.util.DateUtil.now;

@Service
public class DecisionTreeServerImpl implements org.motechproject.decisiontree.server.service.DecisionTreeServer {

    private Logger logger = LoggerFactory.getLogger((this.getClass()));

    public static final String TEMPLATE_BASE_PATH = "/vm/";
    public static final String NODE_TEMPLATE_NAME = TEMPLATE_BASE_PATH + "node";
    public static final String ERROR_MESSAGE_TEMPLATE_NAME = TEMPLATE_BASE_PATH + "error";
    public static final String EXIT_TEMPLATE_NAME = TEMPLATE_BASE_PATH + "exit";

    public static final Integer MAX_INPUT_DIGITS = 50;
    public static final Integer MAX_INPUT_TIMEOUT = 5000;
    public static final String DEFAULT_END_OF_KEY_MARKER = "#";

    private DecisionTreeService decisionTreeService;
    private TreeEventProcessor treeEventProcessor;
    private ApplicationContext applicationContext;
    private FlowSessionService flowSessionService;
    private EventRelay eventRelay;

    @Autowired
    public DecisionTreeServerImpl(DecisionTreeService decisionTreeService, TreeEventProcessor treeEventProcessor, ApplicationContext applicationContext, FlowSessionService flowSessionService, EventRelay eventRelay) {
        this.decisionTreeService = decisionTreeService;
        this.treeEventProcessor = treeEventProcessor;
        this.applicationContext = applicationContext;
        this.flowSessionService = flowSessionService;
        this.eventRelay = eventRelay;
    }

    @Override
    public ModelAndView getResponse(String flowSessionId, String phoneNumber, String provider, String tree, String transitionKey, String language) {

        FlowSession session = flowSessionService.findOrCreate(flowSessionId, phoneNumber);
        if (language != null) {
            session.setLanguage(language);
        }

        ModelAndView view;
        try {
            view = getModelViewForNextNode(session, provider, tree, transitionKey);
        } catch (DecisionTreeException e) {
            logger.error(e.getMessage(), e);
            view = getErrorModelAndView(e.subject, session, provider);
        } catch (Exception e) {
            logger.error(format("Unexpected exception %s", e.getMessage()), e);
            view = getErrorModelAndView(Error.UNEXPECTED_EXCEPTION, session, provider);
        }
        return view;
    }

    @Override
    public void handleMissedCall(String flowSessionId) {
        FlowSession session = flowSessionService.getSession(flowSessionId);
        CallDetailRecord callDetailRecord = ((FlowSessionRecord) session).getCallDetailRecord().setEndDate(now());
        flowSessionService.updateSession(session);
        eventRelay.sendEventMessage(new EndOfCallEvent(callDetailRecord));
    }

    private ModelAndView getModelViewForNextNode(FlowSession session, String provider, String tree, String transitionKey) {

        if (CallStatus.Hangup.toString().equals(transitionKey) || CallStatus.Disconnect.toString().equals(transitionKey)) {
            CallDetailRecord callDetailRecord = ((FlowSessionRecord) session).getCallDetailRecord().setEndDate(now());
            flowSessionService.updateSession(session);
            eventRelay.sendEventMessage(new EndOfCallEvent(callDetailRecord));
            return new ModelAndView(templateNameFor(provider, EXIT_TEMPLATE_NAME));
        }
        if (isBlank(session.getLanguage()) || isBlank(tree)) {
            logger.error(format("No tree or language specified"));
            return getErrorModelAndView(Error.TREE_OR_LANGUAGE_MISSING, session, provider);
        }

        Node node = getCurrentNode(session);
        try {
            if (node == null) {
                node = decisionTreeService.getRootNode(tree, session);
                autowire(node);
                executeOperations(transitionKey, session, node);
            }

            validateNode(node);

            if (transitionKey == null) {
                return constructModelViewForNode(node, session, provider, tree);
            } else {
                ITransition nextTransition = getTransitionForUserInput(transitionKey, node);
                autowire(nextTransition);

                treeEventProcessor.sendActionsAfter(node, new HashMap<String, Object>());
                if (nextTransition instanceof Transition) {
                    treeEventProcessor.sendTransitionActions((Transition) nextTransition, new HashMap<String, Object>());
                }

                node = nextTransition.getDestinationNode(transitionKey, session);
                autowire(node);

                if (isEmptyNode(node)) {
                    return new ModelAndView(templateNameFor(provider, EXIT_TEMPLATE_NAME));
                } else {
                    executeOperations(transitionKey, session, node);
                    return constructModelViewForNode(node, session, provider, tree);
                }
            }
        } finally {
            flowSessionService.updateSession(session);
        }
    }

    private ModelAndView constructModelViewForNode(Node node, FlowSession session, String provider, String tree) {
        treeEventProcessor.sendActionsBefore(node, new HashMap<String, Object>());

        ModelAndView mav = new ModelAndView();
        mav.setViewName(templateNameFor(provider, NODE_TEMPLATE_NAME));
        mav.addObject("treeName", tree);
        mav.addObject("node", node);
        mav.addObject("provider", provider);
        mav.addObject("language", session.getLanguage());
        mav.addObject("escape", new StringEscapeUtils());
        mav.addObject("maxDigits", maxDigits(node));
        mav.addObject("maxTimeout", maxTimeout(node));
        mav.addObject("transitionKeyEndMarker", transitionKeyEndMarker(node));
        mav.addObject("isUserInputNeeded", isUserInputNeeded(node));
        session.setCurrentNode(node);
        return mav;
    }

    private boolean isEmptyNode(Node node) {
        return node == null || hasNoActionableItems(node);
    }

    private boolean hasNoActionableItems(Node node) {
        return node.getPrompts().isEmpty() && hasNoActions(node) && node.getTransitions().isEmpty();
    }

    private boolean hasNoActions(Node node) {
        return node.getActionsAfter().isEmpty() && node.getActionsBefore().isEmpty();
    }

    private void executeOperations(String transitionKey, FlowSession session, Node node) {
        for (INodeOperation operation : node.getOperations()) {
            operation.perform(transitionKey, session);
        }
    }

    private void autowire(Object transition) {
        applicationContext.getAutowireCapableBeanFactory().autowireBean(transition);
    }

    private Node getCurrentNode(FlowSession session) {
        return session.getCurrentNode();
    }

    private void validateNode(Node node) {
        for (Map.Entry<String, ITransition> transitionEntry : node.getTransitions().entrySet()) {
            final String key = transitionEntry.getKey();

            if (noInput(key) || hasSpecialMeaning(key) || dtmfKey(key)) {
                return;
            }

            if (anyInput(key)) {
                return;
            }

            if (isStatusKey(key)) {
                return;
            }

            try {
                Integer.parseInt(key);
            } catch (NumberFormatException e) {
                throw new DecisionTreeException(Error.INVALID_TRANSITION_KEY, format("Invalid transition key [%s] for node [%s]", key, node), e);
            }

            ITransition transition = transitionEntry.getValue();
            if (transition instanceof Transition && ((Transition) transition).getDestinationNode() == null) {
                throw new DecisionTreeException(Error.NULL_DESTINATION_NODE, format("Missing destination node in the transition for key [%s] on node [%s]: ", key, node));
            }
        }
    }

    private boolean isStatusKey(String key) {
        return DialStatus.isValid(key) || CallStatus.isValid(key);
    }

    private boolean hasSpecialMeaning(String key) {
        return (anyInput(key) || DialStatus.isValid(key));
    }

    private boolean noInput(String key) {
        return TreeNodeLocator.NO_INPUT.equals(key);
    }

    private boolean dtmfKey(String key) {
        return "*#".contains(key);
    }

    private boolean anyInput(String key) {
        return TreeNodeLocator.ANY_KEY.equals(key);
    }

    private ITransition getTransitionForUserInput(String userInput, Node parentNode) {
        ITransition transition = getPreConfiguredTransition(parentNode, userInput);
        if (transition == null) {
            transition = parentNode.getTransitions().get(TreeNodeLocator.ANY_KEY);
        }
        if (transition == null) {
            throw new DecisionTreeException(Error.INVALID_TRANSITION_KEY, "Invalid Transition Key. There is no transition with key: " + userInput + " in the Node: " + parentNode);
        }
        return transition;
    }

    private ITransition getPreConfiguredTransition(Node parentNode, String userInput) {
        return parentNode.getTransitions().get(userInput);
    }

    private Integer maxDigits(Node node) {
        Map<String, ITransition> transitions = node.getTransitions();
        int maxDigits = 1;
        for (String key : transitions.keySet()) {
            if (hasSpecialMeaning(key)) {
                return (node.getMaxTransitionInputDigit() == null) ? MAX_INPUT_DIGITS : node.getMaxTransitionInputDigit();
            }
            if (maxDigits < key.length()) {
                maxDigits = key.length();
            }
        }
        return maxDigits;
    }

    private Integer maxTimeout(Node node) {
        return node.getMaxTransitionTimeout() == null ? MAX_INPUT_TIMEOUT : node.getMaxTransitionTimeout();
    }

    private boolean isUserInputNeeded(Node node) {
        return node.hasTransitions() && !node.hasDialPrompts();
    }

    private String transitionKeyEndMarker(Node node) {
        return node.getTransitionKeyEndMarker() == null ? DEFAULT_END_OF_KEY_MARKER : node.getTransitionKeyEndMarker();
    }

    private String templateNameFor(String type, String templateName) {
        return templateName + "-" + type;
    }

    private ModelAndView getErrorModelAndView(Error error, FlowSession session, String provider) {
        ModelAndView mav = new ModelAndView();
        mav.setViewName(templateNameFor(provider, ERROR_MESSAGE_TEMPLATE_NAME));
        mav.addObject("message", error.toString());
        mav.addObject("language", session.getLanguage());
        return mav;
    }

    private class DecisionTreeException extends RuntimeException {

        private Error subject;

        public DecisionTreeException(Error subject, String description) {
            super(description);
            this.subject = subject;
        }

        public DecisionTreeException(Error subject, String description, Throwable cause) {
            super(description, cause);
            this.subject = subject;
        }
    }
}


text:
cask 'freesmug-chromium' do
  version '80.0.3987.116'
  sha256 '7257979a6fd92c3e34101de0be34d237557e59d496b41f3f791c7e61e51d29be'

  # sourceforge.net/osxportableapps was verified as official when first introduced to the cask
  url "https://downloads.sourceforge.net/osxportableapps/Chromium_OSX_#{version}.dmg"
  appcast 'https://sourceforge.net/projects/osxportableapps/rss?path=/Chromium'
  name 'Chromium'
  homepage 'http://www.freesmug.org/chromium'

  app 'Chromium.app'
end


text:
require 'kramdown/parser/html'

module Kramdown
  module Parser
    class Kramdown

      # Parse the HTML entity at the current location.
      def parse_html_entity
        @src.pos += @src.matched_size
        @tree.children << Element.new(:entity, ::Kramdown::Utils::Entities.entity(@src[1] || (@src[2] && @src[2].to_i) || @src[3].hex),
                                      nil, :original => @src.matched)
      end
      define_parser(:html_entity, Kramdown::Parser::Html::Constants::HTML_ENTITY_RE, '&')

    end
  end
end


text:
Provide helper functions for MongoDriver >= 2.0.0 MongoLibrary
+ use MongoDriver >= 2.0.0
+ have only test MongoDB Server 3.0.5

### Nuget
```
PM> Install-Package Mongo.Net -Pre
```

###### Sample code

Connection String
```
  <connectionStrings>
    <add name="test" connectionString="mongodb://localhost:27017/Test"/>
  </connectionStrings>
```
Define Class, Document
```
    public class MongoTestCollection : Entity
    {
        public string Name { get; set; }
        public int Age { get; set; }
    }
```

Example code for CRUD
```
Mongo db = new Mongo("test");

// add stuff
db.Add<MongoTestCollection>(new MongoTestCollection
{
Name = Guid.NewGuid().ToString(),
Age = 1
});

// get
var result = db.Find<MongoTestCollection>();

// update
result.FirstOrDefault().Age = 100;
db.Update<MongoTestCollection>(result.FirstOrDefault());

// count
var count = db.Count<MongoTestCollection>();

// delete
db.Delete<MongoTestCollection>(x => x.Age == 1);
```


text:
var mongoose = require('mongoose');

var User = mongoose.model('User', {
	username: String,
	password: String,
	fullName: String,
	lfullName: String,
	created: Number,
});

module.exports = User;


text:
<!DOCTYPE html>
<title>The 'load' event on the style element should still fire after mutation</title>
<link rel="help" href="https://crbug.com/1323319">
<script src="/resources/testharness.js"></script>
<script src="/resources/testharnessreport.js"></script>
<script>
promise_test(async () => {
  const style = document.createElement('style');
  document.head.appendChild(style);
  style.appendChild(document.createTextNode('@import url(/support/css-red.txt);'));
  style.appendChild(document.createTextNode('body {color: green; }'));

  // The 'load' event should fire.
  await new Promise(resolve => style.onload = resolve);
});
</script>


text:
package net.krotscheck.kangaroo.common.timedtasks;

import org.glassfish.jersey.internal.inject.AbstractBinder;
import org.glassfish.jersey.internal.inject.InjectionManager;
import org.glassfish.jersey.server.spi.Container;
import org.glassfish.jersey.server.spi.ContainerLifecycleListener;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.inject.Inject;
import javax.inject.Singleton;
import java.util.List;
import java.util.Timer;

/**
 * This lifecycle listener ensures that timed tasks discovered in the service
 * locator are started.
 *
 * @author Michael Krotscheck
 */
public final class TimedTasksLifecycleListener
        implements ContainerLifecycleListener {

    /**
     * Logger instance.
     */
    private static Logger logger = LoggerFactory
            .getLogger(TimedTasksLifecycleListener.class);

    /**
     * The injector.
     */
    private InjectionManager injector;

    /**
     * The timer.
     */
    private Timer timer;

    /**
     * Create a new lifecycle listener.
     *
     * @param injector The injector from which to resolve tasks.
     */
    @Inject
    public TimedTasksLifecycleListener(final InjectionManager injector) {
        this.injector = injector;
    }

    /**
     * Start all timed tasks.
     *
     * @param container container that has been started.
     */
    @Override
    public void onStartup(final Container container) {
        logger.info("Starting timer");
        timer = new Timer(true);

        List<RepeatingTask> tasks =
                injector.getAllInstances(RepeatingTask.class);
        for (RepeatingTask task : tasks) {
            logger.debug(
                    String.format(
                            "Scheduling: %s: %s seconds",
                            task.getClass().getSimpleName(),
                            Math.floor(task.getPeriod() / 1000)
                    ));
            timer.scheduleAtFixedRate(task.getTask(), task.getDelay(),
                    task.getPeriod());
        }
    }

    /**
     * Invoked when the {@link Container container} has been reloaded.
     *
     * @param container container that has been reloaded.
     */
    @Override
    public void onReload(final Container container) {
    }

    /**
     * Stop all the timed tasks.
     *
     * @param container container that has been shut down.
     */
    @Override
    public void onShutdown(final Container container) {
        logger.info("Cancelling timer");
        timer.cancel();
    }

    /**
     * HK2 Binder for our injector context.
     */
    public static final class Binder extends AbstractBinder {
        @Override
        protected void configure() {
            bind(TimedTasksLifecycleListener.class)
                    .to(ContainerLifecycleListener.class)
                    .in(Singleton.class);
        }
    }
}


text:
"use strict"

var React = require('react');

class TodoApp extends React.Component {
  constructor(props) {
    console.log("constructor")
    super(props);
    this.handleChange = this.handleChange.bind(this);
    this.handleSubmit = this.handleSubmit.bind(this);
    this.state = {items: [], text: ''};
  }

  render() {
    return (

TODO

        <TodoList items={this.state.items} />
        <form onSubmit={this.handleSubmit}>
          <input onChange={this.handleChange} value={this.state.text} />
          <button>{'Add #' + (this.state.items.length + 1)}</button>
        </form>

    );
  }

  handleChange(e) {
    console.log("handleChange")
    this.setState({text: e.target.value});
  }

  handleSubmit(e) {
    console.log("handleSubmit")
    e.preventDefault();
    var newItem = {
      text: this.state.text,
      id: Date.now()
    };
    this.setState((prevState) => ({
      items: prevState.items.concat(newItem),
      text: ''
    }));
  }
}

class TodoList extends React.Component {
  render() {
    return (

        {this.props.items.map(item => (

{item.text}

        ))}

    );
  }
}

module.exports = TodoApp;


text:
package org.graphdrawing.graphml;

//@formatter:off

//@formatter:on

import javax.xml.bind.annotation.*;
import javax.xml.bind.annotation.adapters.CollapsedStringAdapter;
import javax.xml.bind.annotation.adapters.XmlJavaTypeAdapter;

/**
 *
 * Complex type for the {@code <endpoint>} element.
 *
 *
 *

 * Java class for endpoint.type complex type.
 *
 *

 * The following schema fragment specifies the expected content contained within
 * this class.
 *
 *

 * <complexType name="endpoint.type">
 *   <complexContent>
 *     <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
 *       <sequence>
 *         <element ref="{http://graphml.graphdrawing.org/xmlns}description" minOccurs="0"/>
 *       </sequence>
 *       <attGroup ref="{http://graphml.graphdrawing.org/xmlns}endpoint.extra.attrib"/>
 *       <attribute name="id" type="{http://www.w3.org/2001/XMLSchema}NMTOKEN" />
 *       <attribute name="portID" type="{http://www.w3.org/2001/XMLSchema}NMTOKEN" />
 *       <attribute name="nodeID" use="required" type="{http://www.w3.org/2001/XMLSchema}NMTOKEN" />
 *       <attribute name="type" type="{http://graphml.graphdrawing.org/xmlns}endpoint.type.type" default="undir" />
 *     </restriction>
 *   </complexContent>
 * </complexType>
 *

 *
 * @author Peter J. Radics
 * @version 1.0.0
 * @since 0.1.0
 */
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "endpoint.type", propOrder = { "description" })
public class Endpoint {

    @XmlElement(name = "desc")
    private String       description;

    @XmlAttribute(name = "id")
    @XmlJavaTypeAdapter(CollapsedStringAdapter.class)
    @XmlSchemaType(name = "NMTOKEN")
    private String       id;

    @XmlAttribute(name = "port")
    @XmlJavaTypeAdapter(CollapsedStringAdapter.class)
    @XmlSchemaType(name = "NMTOKEN")
    private String       portID;

    @XmlAttribute(name = "node", required = true)
    @XmlJavaTypeAdapter(CollapsedStringAdapter.class)
    @XmlSchemaType(name = "NMTOKEN")
    private String       nodeID;

    @XmlAttribute(name = "type")
    private EndpointType type;

    /**
     * Gets the value of the description property.
     *
     * @return possible object is {@link String }
     *
     */
    public String getDescription() {

        return description;
    }

    /**
     * Sets the value of the description property.
     *
     * @param value
     *            allowed object is {@link String }
     *
     */
    public void setDescription(String value) {

        this.description = value;
    }

    /**
     * Gets the value of the id property.
     *
     * @return possible object is {@link String }
     *
     */
    public String getId() {

        return id;
    }

    /**
     * Sets the value of the id property.
     *
     * @param value
     *            allowed object is {@link String }
     *
     */
    public void setId(String value) {

        this.id = value;
    }

    /**
     * Gets the value of the portID property.
     *
     * @return possible object is {@link String }
     *
     */
    public String getPortID() {

        return portID;
    }

    /**
     * Sets the value of the portID property.
     *
     * @param value
     *            allowed object is {@link String }
     *
     */
    public void setPortID(String value) {

        this.portID = value;
    }

    /**
     * Gets the value of the nodeID property.
     *
     * @return possible object is {@link String }
     *
     */
    public String getNodeID() {

        return nodeID;
    }

    /**
     * Sets the value of the nodeID property.
     *
     * @param value
     *            allowed object is {@link String }
     *
     */
    public void setNodeID(String value) {

        this.nodeID = value;
    }

    /**
     * Gets the value of the type property.
     *
     * @return possible object is {@link EndpointType }
     *
     */
    public EndpointType getType() {

        if (type == null) {
            return EndpointType.UNDIRECTED;
        }
        else {
            return type;
        }
    }

    /**
     * Sets the value of the type property.
     *
     * @param value
     *            allowed object is {@link EndpointType }
     *
     */
    public void setType(EndpointType value) {

        this.type = value;
    }

}


text:
package com.heroku.demo.domain;

/**
 * Created by simon.harding on 22.03.2017.
 */
public enum Status {
    INITIAL,
    PROCESSED
}


text:
{% load staticfiles %}<!doctype html>

    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
    <title>{% block title %}Hotline anti-corruption{% endblock %}</title>
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta http-equiv="Content-Language" content="en-en" />
    <link href="http://icons.iconarchive.com/icons/icons8/android/64/Shopping-money-bag-icon.png" rel="icon" type="image/png" />
    <link rel="stylesheet" href="http://netdna.bootstrapcdn.com/bootstrap/3.1.1/css/bootstrap.min.css">
    <link rel="stylesheet" href="http://netdna.bootstrapcdn.com/bootstrap/3.1.1/css/bootstrap-theme.min.css">

MTI/AECOM

Anti-Corruption Hotline

            {% if user.is_authenticated %} Log out ({{ user.username }}){% endif %}
            {% block content %}{% endblock %}


text:
package com.google.api.ads.dfp.jaxws.v201602;

import javax.xml.bind.annotation.XmlEnum;
import javax.xml.bind.annotation.XmlType;

/**
 *
Java class for VideoDeliveryType.
 *
 *
The following schema fragment specifies the expected content contained within this class.
 *

 *

 * <simpleType name="VideoDeliveryType">
 *   <restriction base="{http://www.w3.org/2001/XMLSchema}string">
 *     <enumeration value="UNKNOWN"/>
 *     <enumeration value="PROGRESSIVE"/>
 *     <enumeration value="STREAMING"/>
 *   </restriction>
 * </simpleType>
 *

 *
 */
@XmlType(name = "VideoDeliveryType")
@XmlEnum
public enum VideoDeliveryType {

    /**
     *
     *                 The value returned if the actual value is not exposed by the requested API
     *                 version.
     *
     *
     */
    UNKNOWN,

    /**
     *
     *                 Video will be served through a progressive download.
     *
     *
     */
    PROGRESSIVE,

    /**
     *
     *                 Video will be served via a streaming protocol like RTMP.
     *
     *
     */
    STREAMING;

    public String value() {
        return name();
    }

    public static VideoDeliveryType fromValue(String v) {
        return valueOf(v);
    }

}


text:
package com.digitalBorderlands.cityHall.impl;

import java.io.IOException;
import java.net.URI;
import java.net.URISyntaxException;
import java.util.Map;
import java.util.Map.Entry;

import org.apache.http.HttpHost;
import org.apache.http.HttpResponse;
import org.apache.http.ParseException;
import org.apache.http.client.methods.HttpDelete;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.methods.HttpPut;
import org.apache.http.client.protocol.HttpClientContext;
import org.apache.http.client.utils.URIBuilder;
import org.apache.http.config.SocketConfig;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.impl.conn.PoolingHttpClientConnectionManager;
import org.apache.http.util.EntityUtils;

import com.digitalBorderlands.cityHall.data.comm.Client;
import com.digitalBorderlands.cityHall.data.comm.ClientConfig;
import com.digitalBorderlands.cityHall.data.responses.BaseResponse;
import com.digitalBorderlands.cityHall.exceptions.CityHallException;
import com.digitalBorderlands.cityHall.exceptions.ErrorFromCityHallException;
import com.digitalBorderlands.cityHall.exceptions.InvalidRequestException;
import com.digitalBorderlands.cityHall.exceptions.InvalidResponseException;
import com.digitalBorderlands.cityHall.exceptions.NotLoggedInException;
import com.google.gson.Gson;
import com.google.gson.JsonSyntaxException;;

class ClientImpl implements Client {
	public ClientImpl() {
		this.open = false;
	}

	public void open(ClientConfig config) {
		this.target = null;

		this.apiPath = "";
		String apiUrl = config.getApiUrl();
		String actualUrl = config.getApiUrl();
		if (apiUrl.toLowerCase().startsWith("http://") && apiUrl.substring(7).indexOf('/') > 0) {
			int index = apiUrl.substring(7).indexOf('/');
			this.apiPath = apiUrl.substring(7+index);
			actualUrl = apiUrl.substring(0, 7+index);
		} else if (!apiUrl.toLowerCase().startsWith("http://") && apiUrl.indexOf('/') > 0) {
			int index = apiUrl.indexOf('/');
			this.apiPath = apiUrl.substring(index);
			actualUrl = apiUrl.substring(0, index);
		}

		if (this.apiPath.endsWith("/")) {
			this.apiPath = this.apiPath.substring(0, this.apiPath.length()-1);
		}

		final SocketConfig socketConfig = SocketConfig.custom()
                .setSoTimeout(15000)
                .build();
        this.connManager = new PoolingHttpClientConnectionManager();
        this.clientBuilder = HttpClientBuilder.create()
                .setDefaultSocketConfig(socketConfig)
                .setConnectionManager(this.connManager);
		this.client = this.clientBuilder.build();
		this.target = HttpHost.create(actualUrl);
		this.open = true;
		this.context = HttpClientContext.create();
	}

	public void close() {
		if (!this.isOpen()) {
			return;
		}

		try {
			this.client.close();
			this.open = false;
		} catch (IOException e) {
			// suppress this error
		}
	}

	private static Gson gson = new Gson();
	private HttpHost target;
	private CloseableHttpClient client = null;
	protected Boolean open;
    protected PoolingHttpClientConnectionManager connManager;
    protected HttpClientBuilder clientBuilder;
    protected HttpClientContext context;
    protected String apiPath;

    public Boolean isOpen() {
    	return this.open;
    }

    private interface serverCall {
    	public HttpResponse run() throws Exception;
    }

    private void ensureOpen() throws CityHallException {
    	if (!this.isOpen()) {
    		throw new NotLoggedInException();
    	}
    }

	private URI uriFromParts(String location, Map<String, String> queryParams) throws CityHallException {
		URIBuilder builder;
		try {
			String fullPath = String.format("%s%s", this.apiPath, Path.sanitize(location));
			builder = new URIBuilder(fullPath);

			if (queryParams != null) {
				for (Entry<String, String> entry: queryParams.entrySet()) {
					builder.addParameter(entry.getKey(), entry.getValue());
				}
			}

			return builder.build();
		} catch (URISyntaxException e) {
			throw new InvalidRequestException("Error attempting to build URI to reach", e);
		}
	}

    private <T extends BaseResponse> T run(String location, serverCall call, Class<T> type) throws CityHallException {
    	int status = -1;
    	String message = "";

    	try {
    		final HttpResponse response = call.run();
		    status = response.getStatusLine().getStatusCode();
		    message = EntityUtils.toString(response.getEntity());
    	} catch (Exception e) {
    		throw new InvalidRequestException("Failed trying to reach: "+location, e);
    	}

		if(status != 200) {
        	throw new InvalidRequestException(location.toString(), status);
        }

		try
		{
			T ret = BaseResponse.fromJson(message, type);
	        if (ret.response.equals("Ok")) {
	        	return ret;
	        }

	        throw new ErrorFromCityHallException(ret.message);
		} catch (JsonSyntaxException e) {
	        throw new InvalidResponseException("Failed trying to reach: "+location.toString());
		} catch (ParseException e) {
			throw new InvalidResponseException("Failed trying to reach: "+location.toString()+", unable to get entity from response: "+e.getMessage());
		}
    }

	public <T extends BaseResponse> T post(String location, Map<String,String> body, Class<T> type) throws CityHallException {
		this.ensureOpen();
		return this.post(location, body, null, type);
	}

	public <T extends BaseResponse> T post(String location, Map<String, String> body, Map<String, String> queryParams, Class<T> type) throws CityHallException {
		this.ensureOpen();

		serverCall call = () -> {
			HttpPost httpPost = new HttpPost(this.uriFromParts(location, queryParams));
			String bodyJson = ClientImpl.gson.toJson(body, body.getClass());
			httpPost.setEntity(new StringEntity(bodyJson));
			httpPost.setHeader("Accept", "application/json");
			httpPost.setHeader("Content-Type", "application/json");
			return this.client.execute(this.target, httpPost, this.context);
		};

		return this.run(location, call, type);
	}

	public <T extends BaseResponse> T get(String location, Map<String, String> queryParams, Class<T> type) throws CityHallException {
		this.ensureOpen();

		serverCall call = () -> {
			HttpGet httpGet = new HttpGet(this.uriFromParts(location, queryParams));
			httpGet.setHeader("Accept", "application/json");
			return this.client.execute(this.target, httpGet, this.context);
		};

		return this.run(location, call, type);
	}

	public <T extends BaseResponse> T delete(String location, Class<T> type) throws CityHallException {
		this.ensureOpen();

		serverCall call = () -> {
			HttpDelete httpGet = new HttpDelete(this.uriFromParts(location, null));
			httpGet.setHeader("Accept", "application/json");
			return this.client.execute(this.target, httpGet, this.context);
	    };

	    return this.run(location, call, type);
	}

	public <T extends BaseResponse> T put(String location, Map<String, String> body, Class<T> type) throws CityHallException {
		this.ensureOpen();

		serverCall call = () -> {
			HttpPut httpPut = new HttpPut(this.uriFromParts(location, null));
			String bodyJson = ClientImpl.gson.toJson(body, body.getClass());
			httpPut.setEntity(new StringEntity(bodyJson));
			httpPut.setHeader("Accept", "application/json");
			httpPut.setHeader("Content-Type", "application/json");
			return this.client.execute(this.target, httpPut, this.context);
		};

		return this.run(location, call, type);
	}
}


text:
using System;
using System.Collections.Generic;
using LuaInterface;
using UnityEngine;

namespace SLua
{
    public partial class LuaObject
    {

        static internal int checkDelegate(IntPtr l,int p,out UnityEngine.EventSystems.ExecuteEvents.EventFunction<UnityEngine.EventSystems.IBeginDragHandler> ua) {
            int op = extractFunction(l,p);
			if(LuaDLL.lua_isnil(l,-1)) {
				ua=null;
				return op;
			}
            else if (LuaDLL.lua_isuserdata(l, p)==1)
            {
                ua = (UnityEngine.EventSystems.ExecuteEvents.EventFunction<UnityEngine.EventSystems.IBeginDragHandler>)checkObj(l, p);
                return op;
            }
            int r = LuaDLL.luaS_checkcallback(l, -1);
			if(r<0) LuaDLL.luaL_error(l,"expect function");
			if(getCacheDelegate<UnityEngine.EventSystems.ExecuteEvents.EventFunction<UnityEngine.EventSystems.IBeginDragHandler>>(r,out ua))
				return op;
			LuaDLL.lua_pop(l,1);
            ua = (UnityEngine.EventSystems.IBeginDragHandler a1,UnityEngine.EventSystems.BaseEventData a2) =>
            {
                int error = pushTry(l);
                LuaDLL.lua_getref(l, r);

				pushValue(l,a1);
				pushValue(l,a2);
				if (LuaDLL.lua_pcall(l, 2, -1, error) != 0) {
					LuaDLL.lua_pop(l, 1);
				}
				LuaDLL.lua_settop(l, error-1);
			};
			cacheDelegate(r,ua);
			return op;
		}
	}
}