text:
(function() {
  var $, DEBOUNCE, MIRROR_LR, MIRROR_TB, OFFSET_MAP, Tether, addOffset, attachmentToOffset, autoToFixedAttachment, debounce, getScrollParent, isIE, offsetToPx, parseAttachment, parseOffset, position, tethers,
    __slice = [].slice,
    __bind = function(fn, me){ return function(){ return fn.apply(me, arguments); }; };

  $ = jQuery;

  isIE = /msie [\w.]+/.test(navigator.userAgent.toLowerCase());

  getScrollParent = function($el) {
    var position, scrollParent;
    position = $el.css('position');
    if (position === 'fixed') {
      return $el;
    }
    scrollParent = void 0;
    if (position === 'absolute' || (isIE && (position === 'static' || position === 'relative'))) {
      scrollParent = $el.parents().filter(function() {
        var _ref;
        return ((_ref = $.css(this, 'position')) === 'relative' || _ref === 'absolute' || _ref === 'fixed') && /(auto|scroll)/.test($.css(this, 'overflow') + $.css(this, 'overflow-y') + $.css(this, 'overflow-x'));
      }).first();
    } else {
      scrollParent = $el.parents().filter(function() {
        return /(auto|scroll)/.test($.css(this, 'overflow') + $.css(this, 'overflow-y') + $.css(this, 'overflow-x'));
      }).first();
    }
    if (scrollParent.length) {
      return scrollParent;
    } else {
      return $('html');
    }
  };

  DEBOUNCE = 16;

  debounce = function(fn, time) {
    var pending;
    if (time == null) {
      time = DEBOUNCE;
    }
    pending = false;
    return function() {
      var args,
        _this = this;
      if (pending) {
        return;
      }
      args = arguments;
      pending = true;
      setTimeout(function() {
        pending = false;
        return fn.apply(_this, args);
      }, time);
      return true;
    };
  };

  tethers = [];

  position = function() {
    var tether, _i, _len;
    for (_i = 0, _len = tethers.length; _i < _len; _i++) {
      tether = tethers[_i];
      tether.position();
    }
    return true;
  };

  if (isIE) {
    position = debounce(position);
  }

  $(window).on('resize scroll', position);

  MIRROR_LR = {
    center: 'center',
    left: 'right',
    right: 'left'
  };

  MIRROR_TB = {
    middle: 'middle',
    top: 'bottom',
    bottom: 'top'
  };

  OFFSET_MAP = {
    top: '0',
    left: '0',
    middle: '50%',
    center: '50%',
    bottom: '100%',
    right: '100%'
  };

  autoToFixedAttachment = function(attachment, relativeToAttachment) {
    var left, top;
    left = attachment.left, top = attachment.top;
    if (left === 'auto') {
      left = MIRROR_LR[relativeToAttachment.left];
    }
    if (top === 'auto') {
      top = MIRROR_TB[relativeToAttachment.top];
    }
    return {
      left: left,
      top: top
    };
  };

  attachmentToOffset = function(attachment) {
    var _ref, _ref1;
    return {
      left: (_ref = OFFSET_MAP[attachment.left]) != null ? _ref : attachment.left,
      top: (_ref1 = OFFSET_MAP[attachment.top]) != null ? _ref1 : attachment.top
    };
  };

  addOffset = function() {
    var left, offsets, out, top, _i, _len, _ref;
    offsets = 1 <= arguments.length ? __slice.call(arguments, 0) : [];
    out = {
      top: 0,
      left: 0
    };
    for (_i = 0, _len = offsets.length; _i < _len; _i++) {
      _ref = offsets[_i], top = _ref.top, left = _ref.left;
      if (typeof top === 'string') {
        top = parseFloat(top, 10);
      }
      if (typeof left === 'string') {
        left = parseFloat(left, 10);
      }
      out.top += top;
      out.left += left;
    }
    return out;
  };

  offsetToPx = function(offset, size) {
    if (typeof offset.left === 'string' && offset.left.indexOf('%') !== -1) {
      offset.left = parseFloat(offset.left, 10) / 100 * size.width;
    }
    if (typeof offset.top === 'string' && offset.top.indexOf('%') !== -1) {
      offset.top = parseFloat(offset.top, 10) / 100 * size.height;
    }
    return offset;
  };

  parseAttachment = parseOffset = function(value) {
    var left, top, _ref;
    _ref = value.split(' '), top = _ref[0], left = _ref[1];
    return {
      top: top,
      left: left
    };
  };

  Tether = (function() {
    Tether.modules = [];

    function Tether(options) {
      this.position = __bind(this.position, this);
      var module, _i, _len, _ref, _ref1;
      tethers.push(this);
      this.history = [];
      this.setOptions(options, false);
      _ref = Tether.modules;
      for (_i = 0, _len = _ref.length; _i < _len; _i++) {
        module = _ref[_i];
        if ((_ref1 = module.initialize) != null) {
          _ref1.call(this);
        }
      }
      this.position();
    }

    Tether.prototype.setOptions = function(options, position) {
      var defaults, _ref, _ref1;
      this.options = options;
      if (position == null) {
        position = true;
      }
      defaults = {
        offset: '0 0',
        targetOffset: '0 0',
        targetAttachment: 'auto auto'
      };
      this.options = $.extend(defaults, this.options);
      _ref = this.options, this.element = _ref.element, this.target = _ref.target;
      if (this.element.jquery) {
        this.$element = this.element;
        this.element = this.element[0];
      }
      if (this.target.jquery) {
        this.$target = this.target;
        this.target = this.target[0];
      }
      if (this.$element == null) {
        this.$element = $(this.element);
      }
      if (typeof this.target !== 'string') {
        if (this.$target == null) {
          this.$target = $(this.target);
        }
      }
      this.$element.addClass('tether-element');
      if ((_ref1 = this.$target) != null) {
        _ref1.addClass('tether-target');
      }
      this.targetAttachment = parseAttachment(this.options.targetAttachment);
      this.attachment = parseAttachment(this.options.attachment);
      this.offset = parseOffset(this.options.offset);
      this.targetOffset = parseOffset(this.options.targetOffset);
      if (this.scrollParent != null) {
        this.disable();
      }
      this.scrollParent = getScrollParent($(this.target));
      if (this.options.enabled !== false) {
        return this.enable(position);
      }
    };

    Tether.prototype.getTargetOffset = function() {
      if (typeof this.target === 'string') {
        switch (this.target) {
          case 'viewport':
            return {
              top: pageYOffset,
              left: pageXOffset
            };
          case 'scroll-handle':
            return {
              top: pageYOffset + innerHeight * (pageYOffset / document.body.scrollHeight),
              left: innerWidth - 15
            };
        }
      } else {
        return this.$target.offset();
      }
    };

    Tether.prototype.getTargetSize = function() {
      if (typeof this.target === 'string') {
        switch (this.target) {
          case 'viewport':
            return {
              height: innerHeight,
              width: innerWidth
            };
          case 'scroll-handle':
            return {
              height: innerHeight * 0.98 * (innerHeight / document.body.scrollHeight),
              width: 15
            };
        }
      } else {
        return {
          height: this.cache('target-outerheight', function() {
            return this.target.outerHeight();
          }),
          width: this.cache('target-outerwidth', function() {
            return this.target.outerWidth();
          })
        };
      }
    };

    Tether.prototype.clearCache = function() {
      return this._cache = {};
    };

    Tether.prototype.cache = function(k, getter) {
      if (this._cache == null) {
        this._cache = {};
      }
      if (this._cache[k] == null) {
        this._cache[k] = getter.call(this);
      }
      return this._cache[k];
    };

    Tether.prototype.enable = function(position) {
      if (position == null) {
        position = true;
      }
      this.addClass('tether-enabled');
      this.enabled = true;
      this.scrollParent.on('scroll', this.position);
      if (position) {
        return this.position();
      }
    };

    Tether.prototype.disable = function() {
      this.removeClass('tether-enabled');
      this.enabled = false;
      if (this.scrollParent != null) {
        return this.scrollParent.off('scroll', this.position);
      }
    };

    Tether.prototype.destroy = function() {
      var i, tether, _i, _len, _results;
      this.disable();
      _results = [];
      for (i = _i = 0, _len = tethers.length; _i < _len; i = ++_i) {
        tether = tethers[i];
        if (tether === this) {
          tethers.splice(i, 1);
          break;
        } else {
          _results.push(void 0);
        }
      }
      return _results;
    };

    Tether.prototype.updateAttachClasses = function(elementAttach, targetAttach) {
      var side, sides, _i, _j, _len, _len1;
      if (elementAttach == null) {
        elementAttach = this.attachment;
      }
      if (targetAttach == null) {
        targetAttach = this.targetAttachment;
      }
      sides = ['left', 'top', 'bottom', 'right', 'middle', 'center'];
      for (_i = 0, _len = sides.length; _i < _len; _i++) {
        side = sides[_i];
        this.removeClass("tether-element-attached-" + side);
      }
      if (elementAttach.top) {
        this.addClass("tether-element-attached-" + elementAttach.top);
      }
      if (elementAttach.left) {
        this.addClass("tether-element-attached-" + elementAttach.left);
      }
      for (_j = 0, _len1 = sides.length; _j < _len1; _j++) {
        side = sides[_j];
        this.removeClass("tether-target-attached-" + side);
      }
      if (targetAttach.top) {
        this.addClass("tether-target-attached-" + targetAttach.top);
      }
      if (targetAttach.left) {
        return this.addClass("tether-target-attached-" + targetAttach.left);
      }
    };

    Tether.prototype.addClass = function(classes) {
      var _ref;
      this.$element.addClass(classes);
      return (_ref = this.$target) != null ? _ref.addClass(classes) : void 0;
    };

    Tether.prototype.removeClass = function(classes) {
      var _ref;
      this.$element.removeClass(classes);
      return (_ref = this.$target) != null ? _ref.removeClass(classes) : void 0;
    };

    Tether.prototype.position = function() {
      var $offsetParent, elementPos, height, left, manualOffset, manualTargetOffset, module, next, offset, offsetBorder, offsetPosition, ret, scrollLeft, scrollTop, side, targetAttachment, targetOffset, targetPos, top, width, _i, _j, _len, _len1, _ref, _ref1, _ref2;
      if (!this.enabled) {
        return;
      }
      this.clearCache();
      targetAttachment = autoToFixedAttachment(this.targetAttachment, this.attachment);
      this.updateAttachClasses(this.attachment, targetAttachment);
      width = this.cache('element-outerwidth', function() {
        return this.$element.outerWidth();
      });
      height = this.cache('element-outerheight', function() {
        return this.$element.outerHeight();
      });
      offset = offsetToPx(attachmentToOffset(this.attachment), {
        width: width,
        height: height
      });
      targetOffset = offsetToPx(attachmentToOffset(targetAttachment), this.getTargetSize());
      manualOffset = offsetToPx(this.offset, {
        width: width,
        height: height
      });
      manualTargetOffset = offsetToPx(this.targetOffset, this.getTargetSize());
      offset = addOffset(offset, manualOffset);
      targetOffset = addOffset(targetOffset, manualTargetOffset);
      targetPos = this.getTargetOffset();
      elementPos = this.cache('element-offset', function() {
        return this.$element.offset();
      });
      left = targetPos.left + targetOffset.left - offset.left;
      top = targetPos.top + targetOffset.top - offset.top;
      _ref = Tether.modules;
      for (_i = 0, _len = _ref.length; _i < _len; _i++) {
        module = _ref[_i];
        ret = module.position.call(this, {
          left: left,
          top: top,
          targetAttachment: targetAttachment,
          targetPos: targetPos,
          elementPos: elementPos,
          offset: offset,
          targetOffset: targetOffset,
          manualOffset: manualOffset,
          manualTargetOffset: manualTargetOffset
        });
        if ((ret == null) || typeof ret !== 'object') {
          continue;
        } else if (ret === false) {
          return false;
        } else {
          top = ret.top, left = ret.left;
        }
      }
      next = {
        page: {
          top: top,
          bottom: document.body.scrollHeight - top - height,
          left: left,
          right: document.body.scrollWidth - left - width
        },
        viewport: {
          top: top - pageYOffset,
          bottom: pageYOffset - top - height + innerHeight,
          left: left - pageXOffset,
          right: pageXOffset - left - width + innerWidth
        }
      };
      if (((_ref1 = this.options.optimizations) != null ? _ref1.moveElement : void 0) !== false && (this.$target != null)) {
        $offsetParent = this.cache('target-offsetparent', function() {
          return this.$target.offsetParent();
        });
        offsetPosition = this.cache('target-offsetparent-offset', function() {
          return $offsetParent.offset();
        });
        offsetBorder = {};
        _ref2 = ['top', 'left', 'bottom', 'right'];
        for (_j = 0, _len1 = _ref2.length; _j < _len1; _j++) {
          side = _ref2[_j];
          offsetBorder[side] = parseFloat($offsetParent.css("border-" + side + "-width"));
        }
        offsetPosition.left += offsetBorder.left;
        offsetPosition.top += offsetBorder.top;
        offsetPosition.right = document.body.scrollWidth - offsetPosition.left - $offsetParent.width();
        offsetPosition.bottom = document.body.scrollHeight - offsetPosition.top - $offsetParent.height();
        if (next.page.top >= offsetPosition.top && next.page.bottom >= offsetPosition.bottom) {
          if (next.page.left >= offsetPosition.left && next.page.right >= offsetPosition.right) {
            scrollTop = $offsetParent.scrollTop();
            scrollLeft = $offsetParent.scrollLeft();
            next.offset = {
              top: next.page.top - offsetPosition.top + scrollTop + offsetBorder.top,
              left: next.page.left - offsetPosition.left + scrollLeft + offsetBorder.left,
              right: next.page.right - offsetPosition.right - scrollLeft + offsetBorder.right,
              bottom: next.page.bottom - offsetPosition.bottom - scrollTop + offsetBorder.bottom
            };
          }
        }
      }
      this.move(next);
      this.history.unshift(next);
      if (this.history.length > 3) {
        this.history.pop();
      }
      return true;
    };

    Tether.prototype.move = function(position) {
      var $offsetParent, css, found, key, moved, offset, point, same, side, transcribe, type, val, write, _i, _j, _len, _len1, _ref, _ref1, _ref2;
      same = {};
      for (type in position) {
        same[type] = {};
        for (key in position[type]) {
          found = false;
          _ref = this.history;
          for (_i = 0, _len = _ref.length; _i < _len; _i++) {
            point = _ref[_i];
            if (((_ref1 = point[type]) != null ? _ref1[key] : void 0) !== position[type][key]) {
              found = true;
              break;
            }
          }
          if (!found) {
            same[type][key] = true;
          }
        }
      }
      css = {
        top: '',
        left: '',
        right: '',
        bottom: ''
      };
      transcribe = function(same, pos) {
        if (same.top) {
          css.top = "" + pos.top + "px";
        } else {
          css.bottom = "" + pos.bottom + "px";
        }
        if (same.left) {
          return css.left = "" + pos.left + "px";
        } else {
          return css.right = "" + pos.right + "px";
        }
      };
      moved = false;
      if ((same.page.top || same.page.bottom) && (same.page.left || same.page.right)) {
        css.position = 'absolute';
        transcribe(same.page, position.page);
      } else if ((same.viewport.top || same.viewport.bottom) && (same.viewport.left || same.viewport.right)) {
        css.position = 'fixed';
        transcribe(same.viewport, position.viewport);
      } else if ((same.offset != null) && (same.offset.top || same.offset.bottom) && (same.offset.left || same.offset.right)) {
        css.position = 'absolute';
        $offsetParent = this.getTargetOffset();
        if (this.$element.offsetParent()[0] !== $offsetParent[0]) {
          this.$element.detach();
          $offsetParent.append(this.$element);
        }
        offset = $.extend({}, position.offset);
        _ref2 = ['top', 'left', 'bottom', 'right'];
        for (_j = 0, _len1 = _ref2.length; _j < _len1; _j++) {
          side = _ref2[_j];
          offset[side] -= parseFloat($offsetParent.css("border-" + side + "-width"), 10);
        }
        transcribe(same.offset, offset);
        moved = true;
      } else {
        css.position = 'absolute';
        css.top = "" + position.page.top + "px";
        css.left = "" + position.page.left + "px";
      }
      if (!moved && !this.$element.parent().is('body')) {
        this.$element.detach();
        $(document.body).append(this.$element);
      }
      write = false;
      for (key in css) {
        val = css[key];
        if (this.$element.css(key) !== val) {
          write = true;
          break;
        }
      }
      if (write) {
        return this.$element.css(css);
      }
    };

    return Tether;

  })();

  window.Tether = Tether;

}).call(this);


text:
package com.ibm.bi.dml.runtime.instructions.spark;

import java.util.ArrayList;

import org.apache.spark.api.java.JavaPairRDD;
import org.apache.spark.api.java.function.Function;
import org.apache.spark.api.java.function.PairFlatMapFunction;

import scala.Tuple2;

import com.ibm.bi.dml.runtime.DMLRuntimeException;
import com.ibm.bi.dml.runtime.DMLUnsupportedOperationException;
import com.ibm.bi.dml.runtime.controlprogram.context.ExecutionContext;
import com.ibm.bi.dml.runtime.controlprogram.context.SparkExecutionContext;
import com.ibm.bi.dml.runtime.functionobjects.Builtin;
import com.ibm.bi.dml.runtime.functionobjects.Multiply;
import com.ibm.bi.dml.runtime.functionobjects.Plus;
import com.ibm.bi.dml.runtime.instructions.Instruction;
import com.ibm.bi.dml.runtime.instructions.InstructionUtils;
import com.ibm.bi.dml.runtime.instructions.cp.CPOperand;
import com.ibm.bi.dml.runtime.matrix.MatrixCharacteristics;
import com.ibm.bi.dml.runtime.matrix.data.MatrixBlock;
import com.ibm.bi.dml.runtime.matrix.data.MatrixIndexes;
import com.ibm.bi.dml.runtime.matrix.operators.BinaryOperator;
import com.ibm.bi.dml.runtime.matrix.operators.Operator;
import com.ibm.bi.dml.runtime.matrix.operators.UnaryOperator;

public class CumulativeOffsetSPInstruction extends BinarySPInstruction
{

	private BinaryOperator _bop = null;
	private UnaryOperator _uop = null;
	private double _initValue = 0;

	public CumulativeOffsetSPInstruction(Operator op, CPOperand in1, CPOperand in2, CPOperand out, double init, String opcode, String istr)
	{
		super(op, in1, in2, out, opcode, istr);
		_sptype = SPINSTRUCTION_TYPE.CumsumOffset;

		if( "bcumoffk+".equals(opcode) ) {
			_bop = new BinaryOperator(Plus.getPlusFnObject());
			_uop = new UnaryOperator(Builtin.getBuiltinFnObject("ucumk+"));
		}
		else if( "bcumoff*".equals(opcode) ){
			_bop = new BinaryOperator(Multiply.getMultiplyFnObject());
			_uop = new UnaryOperator(Builtin.getBuiltinFnObject("ucum*"));
		}
		else if( "bcumoffmin".equals(opcode) ){
			_bop = new BinaryOperator(Builtin.getBuiltinFnObject("min"));
			_uop = new UnaryOperator(Builtin.getBuiltinFnObject("ucummin"));
		}
		else if( "bcumoffmax".equals(opcode) ){
			_bop = new BinaryOperator(Builtin.getBuiltinFnObject("max"));
			_uop = new UnaryOperator(Builtin.getBuiltinFnObject("ucummax"));
		}

		_initValue = init;
	}

	/**
	 *
	 * @param str
	 * @return
	 * @throws DMLRuntimeException
	 */
	public static Instruction parseInstruction ( String str )
		throws DMLRuntimeException
	{
		String[] parts = InstructionUtils.getInstructionPartsWithValueType( str );
		InstructionUtils.checkNumFields ( parts, 4 );

		String opcode = parts[0];
		CPOperand in1 = new CPOperand(parts[1]);
		CPOperand in2 = new CPOperand(parts[2]);
		CPOperand out = new CPOperand(parts[3]);
		double init = Double.parseDouble(parts[4]);

		return new CumulativeOffsetSPInstruction(null, in1, in2, out, init, opcode, str);
	}

	@Override
	public void processInstruction(ExecutionContext ec)
		throws DMLRuntimeException, DMLUnsupportedOperationException
	{
		SparkExecutionContext sec = (SparkExecutionContext)ec;
		MatrixCharacteristics mc = sec.getMatrixCharacteristics(input2.getName());
		long rlen = mc.getRows();
		int brlen = mc.getRowsPerBlock();

		//get inputs
		JavaPairRDD<MatrixIndexes,MatrixBlock> inData = sec.getBinaryBlockRDDHandleForVariable( input1.getName() );
		JavaPairRDD<MatrixIndexes,MatrixBlock> inAgg = sec.getBinaryBlockRDDHandleForVariable( input2.getName() );

		//prepare aggregates (cumsplit of offsets)
		inAgg = inAgg.flatMapToPair(new RDDCumSplitFunction(_initValue, rlen, brlen));

		//execute cumulative offset (apply cumulative op w/ offsets)
		JavaPairRDD<MatrixIndexes,MatrixBlock> out =
				inData.join( inAgg )
				      .mapValues(new RDDCumOffsetFunction(_uop, _bop));

		updateUnaryOutputMatrixCharacteristics(sec);
		//put output handle in symbol table
		sec.setRDDHandleForVariable(output.getName(), out);
		sec.addLineageRDD(output.getName(), input1.getName());
		sec.addLineageRDD(output.getName(), input2.getName());
	}

	/**
	 *
	 *
	 */
	private static class RDDCumSplitFunction implements PairFlatMapFunction<Tuple2<MatrixIndexes, MatrixBlock>, MatrixIndexes, MatrixBlock>
	{
		private static final long serialVersionUID = -8407407527406576965L;

		private double _initValue = 0;
		private int _brlen = -1;
		private long _lastRowBlockIndex;

		public RDDCumSplitFunction( double initValue, long rlen, int brlen )
		{
			_initValue = initValue;
			_brlen = brlen;
			_lastRowBlockIndex = (long)Math.ceil((double)rlen/brlen);
		}

		@Override
		public Iterable<Tuple2<MatrixIndexes, MatrixBlock>> call( Tuple2<MatrixIndexes, MatrixBlock> arg0 )
			throws Exception
		{
			ArrayList<Tuple2<MatrixIndexes, MatrixBlock>> ret = new ArrayList<Tuple2<MatrixIndexes, MatrixBlock>>();

			MatrixIndexes ixIn = arg0._1();
			MatrixBlock blkIn = arg0._2();

			long rixOffset = (ixIn.getRowIndex()-1)*_brlen;
			boolean firstBlk = (ixIn.getRowIndex() == 1);
			boolean lastBlk = (ixIn.getRowIndex() == _lastRowBlockIndex );

			//introduce offsets w/ init value for first row
			if( firstBlk ) {
				MatrixIndexes tmpix = new MatrixIndexes(1, ixIn.getColumnIndex());
				MatrixBlock tmpblk = new MatrixBlock(1, blkIn.getNumColumns(), blkIn.isInSparseFormat());
				if( _initValue != 0 ){
					for( int j=0; j<blkIn.getNumColumns(); j++ )
						tmpblk.appendValue(0, j, _initValue);
				}
				ret.add(new Tuple2<MatrixIndexes,MatrixBlock>(tmpix, tmpblk));
			}

			//output splitting (shift by one), preaggregated offset used by subsequent block
			for( int i=0; i<blkIn.getNumRows(); i++ )
				if( !(lastBlk && i==(blkIn.getNumRows()-1)) ) //ignore last row
				{
					MatrixIndexes tmpix = new MatrixIndexes(rixOffset+i+2, ixIn.getColumnIndex());
					MatrixBlock tmpblk = new MatrixBlock(1, blkIn.getNumColumns(), blkIn.isInSparseFormat());
					blkIn.sliceOperations(i, i, 0, blkIn.getNumColumns()-1, tmpblk);
					ret.add(new Tuple2<MatrixIndexes,MatrixBlock>(tmpix, tmpblk));
				}

			return ret;
		}
	}

	/**
	 *
	 */
	private static class RDDCumOffsetFunction implements Function<Tuple2<MatrixBlock, MatrixBlock>, MatrixBlock>
	{
		private static final long serialVersionUID = -5804080263258064743L;

		private UnaryOperator _uop = null;
		private BinaryOperator _bop = null;

		public RDDCumOffsetFunction(UnaryOperator uop, BinaryOperator bop)
		{
			_uop = uop;
			_bop = bop;
		}

		@Override
		public MatrixBlock call(Tuple2<MatrixBlock, MatrixBlock> arg0)
			throws Exception
		{
			//prepare inputs and outputs
			MatrixBlock dblkIn = arg0._1(); //original data
			MatrixBlock oblkIn = arg0._2(); //offset row vector
			MatrixBlock blkOut = new MatrixBlock(dblkIn.getNumRows(), dblkIn.getNumColumns(), dblkIn.isInSparseFormat());

			//blockwise offset aggregation and prefix sum computation
			MatrixBlock data2 = new MatrixBlock(dblkIn); //cp data
			MatrixBlock fdata2 = data2.sliceOperations(0, 0, 0, data2.getNumColumns()-1, new MatrixBlock()); //1-based
			fdata2.binaryOperationsInPlace(_bop, oblkIn); //sum offset to first row
			data2.copy(0, 0, 0, data2.getNumColumns()-1, fdata2, true); //0-based
			data2.unaryOperations(_uop, blkOut); //compute columnwise prefix sums/prod/min/max

			return blkOut;
		}
	}
}

redpajama_set_name: RedPajamaGithub


text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<title>Timer (libgdx API)</title>
<meta name="date" content="2013-05-14">
<link rel="stylesheet" type="text/css" href="../../../../stylesheet.css" title="Style">

JavaScript is disabled on your browser.

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

				libgdx API

Prev Class

Next Class

Frames

No Frames

All Classes

Summary:

Nested |

Field |

Constr |

Method

Detail:

Field |

Constr |

Method

com.badlogic.gdx.utils

Class Timer

java.lang.Object

com.badlogic.gdx.utils.Timer

public class Timer
extends java.lang.Object

Executes tasks in the future on the main loop thread.

Author:

Nathan Sweet

Nested Class Summary

Nested Classes

Modifier and Type
Class and Description

static class
Timer.Task

Runnable with a cancel method.

Field Summary

Fields

Modifier and Type
Field and Description

static Timer
instance

Timer instance for general application wide usage.

Constructor Summary

Constructors

Constructor and Description

Timer()

Method Summary

Methods

Modifier and Type
Method and Description

void
clear()

Cancels all tasks.

static void
post(Timer.Task task)

Schedules a task on instance.

void
postTask(Timer.Task task)

Schedules a task to occur once as soon as possible, but not sooner than the start of the next frame.

static void
schedule(Timer.Task task,
        float delaySeconds)

Schedules a task on instance.

static void
schedule(Timer.Task task,
        float delaySeconds,
        float intervalSeconds)

Schedules a task on instance.

static void
schedule(Timer.Task task,
        float delaySeconds,
        float intervalSeconds,
        int repeatCount)

Schedules a task on instance.

void
scheduleTask(Timer.Task task,
            float delaySeconds)

Schedules a task to occur once after the specified delay.

void
scheduleTask(Timer.Task task,
            float delaySeconds,
            float intervalSeconds)

Schedules a task to occur once after the specified delay and then repeatedly at the specified interval until cancelled.

void
scheduleTask(Timer.Task task,
            float delaySeconds,
            float intervalSeconds,
            int repeatCount)

Schedules a task to occur once after the specified delay and then a number of additional times at the specified interval.

void
start()

Starts the timer if it was stopped.

void
stop()

Stops the timer, tasks will not be executed and time that passes will not be applied to the task delays.

Methods inherited from class java.lang.Object

clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait

Field Detail

instance

public static final Timer instance

Timer instance for general application wide usage. Static methods on Timer make convenient use of this instance.

Constructor Detail

Timer

public Timer()

Method Detail

postTask

public void postTask(Timer.Task task)

Schedules a task to occur once as soon as possible, but not sooner than the start of the next frame.

scheduleTask

public void scheduleTask(Timer.Task task,
                float delaySeconds)

Schedules a task to occur once after the specified delay.

scheduleTask

public void scheduleTask(Timer.Task task,
                float delaySeconds,
                float intervalSeconds)

Schedules a task to occur once after the specified delay and then repeatedly at the specified interval until cancelled.

scheduleTask

public void scheduleTask(Timer.Task task,
                float delaySeconds,
                float intervalSeconds,
                int repeatCount)

Schedules a task to occur once after the specified delay and then a number of additional times at the specified interval.

stop

public void stop()

Stops the timer, tasks will not be executed and time that passes will not be applied to the task delays.

start

public void start()

Starts the timer if it was stopped.

clear

public void clear()

Cancels all tasks.

post

public static void post(Timer.Task task)

Schedules a task on instance.

See Also:

postTask(Task)

schedule

public static void schedule(Timer.Task task,
            float delaySeconds)

Schedules a task on instance.

See Also:

scheduleTask(Task, float)

schedule

public static void schedule(Timer.Task task,
            float delaySeconds,
            float intervalSeconds)

Schedules a task on instance.

See Also:

scheduleTask(Task, float, float)

schedule

public static void schedule(Timer.Task task,
            float delaySeconds,
            float intervalSeconds,
            int repeatCount)

Schedules a task on instance.

See Also:

scheduleTask(Task, float, float, int)

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

libgdx API

Prev Class

Next Class

Frames

No Frames

All Classes

Summary:

Nested |

Field |

Constr |

Method

Detail:

Field |

Constr |

Method

				Copyright © 2010-2013 Mario Zechner (contact@badlogicgames.com), Nathan Sweet (admin@esotericsoftware.com)


text:
import URLRequestHeader from "openfl/net/URLRequestHeader";
import * as assert from "assert";

describe ("ES6 | URLRequestHeader", function () {

	it ("name", function () {

		// TODO: Confirm functionality

		var urlRequestHeader = new URLRequestHeader ();
		var exists = urlRequestHeader.name;

		assert.notEqual (exists, null);

	});

	it ("value", function () {

		// TODO: Confirm functionality

		var urlRequestHeader = new URLRequestHeader ();
		var exists = urlRequestHeader.value;

		assert.notEqual (exists, null);

	});

	it ("new", function () {

		// TODO: Confirm functionality

		var urlRequestHeader = new URLRequestHeader ();
		assert.notEqual (urlRequestHeader, null);

	});

});


text:
"""Command to list the available accounts."""

import collections
import textwrap

from googlecloudsdk.calliope import base
from googlecloudsdk.core import log
from googlecloudsdk.core import properties
from googlecloudsdk.core.console import console_io
from googlecloudsdk.core.credentials import store as c_store

class List(base.Command):
  """List the accounts for known credentials."""

  @staticmethod
  def Args(parser):
    parser.add_argument('--account',
                        help='List only credentials for one account.')

  def Run(self, args):
    """List the account for known credentials."""
    accounts = c_store.AvailableAccounts()

    active_account = properties.VALUES.core.account.Get()

    if args.account:
      if args.account in accounts:
        accounts = [args.account]
      else:
        accounts = []

    auth_info = collections.namedtuple(
        'auth_info',
        ['active_account', 'accounts'])
    return auth_info(active_account, accounts)

  def Display(self, unused_args, result):
    if result.accounts:
      lp = console_io.ListPrinter('Credentialed accounts:')
      lp.Print([account +
                (' (active)' if account == result.active_account else '')
                for account in result.accounts])
      log.err.Print(textwrap.dedent("""
          To set the active account, run:
            $ gcloud config set account ``ACCOUNT''
          """))
    else:
      log.err.Print(textwrap.dedent("""\
          No credentialed accounts.

          To login, run:
            $ gcloud auth login ``ACCOUNT''
          """))


text:
cd ~
git clone -b raspi https://github.com/bokunimowakaru/xbeeCoord.git
cd xbeeCoord/tools
make
~/xbeeCoord/cqpub_pi/practice10.sh


text:
package io.github.varvelworld.var.ioc.aop;

import java.lang.reflect.Method;

/**
 * 后置通知
 * Created by luzhonghao on 2016/12/30.
 */
public interface AfterAdvice extends Advice {
    void after(Method method, Object[] args, Object target, Object returnValue) throws Throwable;
}


text:
package com.rftdevgroup.transporthub.data.dto.auction;

import lombok.Data;
import lombok.NoArgsConstructor;

@Data
@NoArgsConstructor
public class PlaceBidDTO {
    private int amount;
}


text:
import sys
import gzip

if __name__ == "__main__":

    cities = {}

    for line in open("boxes.dat"):
        fields = line.strip().split(',')
        cities[fields[0]] = [float(field) for field in fields[1:]]

    scale = 1000.
    matrix = {}

    city = cities[sys.argv[1].lower()[0]]

    lat_min = city[3]
    lat_max = city[2]
    lon_min = city[1]
    lon_max = city[0]

    for filename in sys.argv[2:]:
        print >> sys.stderr, filename

        for line in gzip.open(filename):
            fields = line.strip().split(';')

            lat = float(fields[2])
            lon = float(fields[3])

            if lat > lat_max or lat < lat_min:
                continue

            if lon > lon_max or lon < lon_min:
                continue

            cell = (int(lat*scale)/scale, int(lon*scale)/scale)

            matrix[cell] = matrix.get(cell, 0) + 1

    for key, value in matrix.iteritems():
        print int((lat_max-key[0])*scale), int((key[1]-lon_min)*scale), value


text:
/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package local;

import network.NetAddress;
import it.sauronsoftware.ftp4j.FTPAbortedException;
import it.sauronsoftware.ftp4j.FTPClient;
import it.sauronsoftware.ftp4j.FTPDataTransferException;
import it.sauronsoftware.ftp4j.FTPException;
import it.sauronsoftware.ftp4j.FTPIllegalReplyException;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Random;
import java.util.concurrent.Callable;
import java.util.logging.Level;
import java.util.logging.Logger;

/**
 * Class provides support for downloading files over ftp.
 * @see FileFtpOperationFuture
 * @author Ivan Straka
 */
public class FileDownload implements Callable<FileFtpOperationFuture> {

    private final static Logger logger = Logger.getLogger(FileDownload.class.getName());

    static private String downloadDest;

    /**
     * Set downlaod destination.
     */
    static public void setDownloadDest(String path){
        if(!path.endsWith(File.separator)){
            path += File.separatorChar;
        }
        downloadDest = path;
    }

    static private int uniqID = 0;

    /**
     * Set uniq id that will be part of download files.
     */
    static public void setUniqID(int id){
        uniqID = id;
    }

    static private int counter = 0;
    static private Object lock;

    private final FTPClient client;
    private String destFile;
    private final List<NetAddress> files;
    private Random rand;

    /**
     * Compose destination filename.
     * Original filename will be added beyond "pd_corp_" + uniq id +"_" + no. downloaded file + "_"
     * @return destination filename
     */
    private String getNewDestFilename(String srcFilename){
        counter++;
        return downloadDest+"pd_corp_"+uniqID+"_"+counter+"_"+srcFilename.substring(srcFilename.lastIndexOf("/")+1);
    }

    /**
     * Init downloading  file from ftp server
     * @param filename remoee dest
     */
    public FileDownload(String filename, String host, int port){
        this(NetAddress.getAddress(filename, host, port));
    }

    /**
     * Init downloading  file from ftp server.
     */
    public FileDownload(NetAddress file){
        client = new FTPClient();
        files = Arrays.asList(file);
        rand = new Random();
        rand.setSeed(System.currentTimeMillis());
    }

    /**
     * Init downloading file from ftp server.
     * @param ftpFilenames  list od ftp destinations where the file can be downloaded from.
     */
    public FileDownload(List<String> ftpFilenames){
        client = new FTPClient();
        files = new ArrayList<>(ftpFilenames.size());
        for(String ftpFilename: ftpFilenames){
            files.add(NetAddress.getAddress(ftpFilename));
        }
        rand = new Random();
        rand.setSeed(System.currentTimeMillis());
    }

    @Override
    public FileFtpOperationFuture call() {
        // create copy of the array of destinations where the file can be downloaded from
        // if there are more destinations, they will be picked up randomly
        List<NetAddress>filesCopy = files.size() == 1?files:new ArrayList<>(files);
        NetAddress remoteFile;
        int position;
        //infinity loop while there is some destination left
        while(!filesCopy.isEmpty()) {
            // if length of array is 1, there is only one option
            if(files.size() == 1){
                position = 0;
            }
            else{
                position = rand.nextInt(filesCopy.size());
            }
            remoteFile = filesCopy.get(position);
            // download
            try {
                destFile=getNewDestFilename(remoteFile.dest);
                client.connect(remoteFile.hostname, remoteFile.port);
                client.login("pd_corp", "][[asddddddddddd2j9d8238ud");
                client.setType(FTPClient.TYPE_BINARY);
                client.download(remoteFile.dest, new File(destFile));
                //logger.log(Level.INFO, "downloaded {0} from {1}:{2} to {4}", new Object[]{remoteFile.dest, remoteFile.hostname, remoteFile.port, downloadDest, destFile});
                client.disconnect(true);

            // ftp exception, try another destination or return future with ftp code
            } catch(FTPException ex){
                if(files.size() != 1 && !filesCopy.isEmpty()){
                    filesCopy.remove(position);
                    continue;
                }
                else
                    return new FileFtpOperationFuture(ex.getCode());

            // Some other severe exception, try another dest or return future with fatal err code
            } catch (IllegalStateException | IOException | FTPIllegalReplyException  | FTPDataTransferException | FTPAbortedException ex) {
                logger.log(Level.SEVERE, ex.getMessage(), ex);
                if(files.size() != 1 && !filesCopy.isEmpty()){
                    filesCopy.remove(position);
                    continue;
                }
                else
                    return new FileFtpOperationFuture(FileFtpOperationFuture.FATAL);
            }
            return new FileFtpOperationFuture(remoteFile.dest, destFile);
        }
        return new FileFtpOperationFuture(FileFtpOperationFuture.FATAL);
    }
}


text:
<?php

namespace Magento\Ui\Component\Control;

use Magento\Framework\View\Element\Template;
use Magento\Framework\View\Element\UiComponent\Control\ControlInterface;

/**
 * Class Button
 */
class Button extends Template implements ControlInterface
{
    /**
     * Define block template
     *
     * @return void
     */
    protected function _construct()
    {
        $this->setTemplate('Magento_Ui::control/button/default.phtml');
        parent::_construct();
    }

    /**
     * Retrieve button type
     *
     * @return string
     */
    public function getType()
    {
        if (in_array($this->getData('type'), ['reset', 'submit'])) {
            return $this->getData('type');
        }

        return 'button';
    }

    /**
     * Retrieve attributes html
     *
     * @return string
     */
    public function getAttributesHtml()
    {
        $disabled = $this->getDisabled() ? 'disabled' : '';
        $title = $this->getTitle();
        if (empty($title)) {
            $title = $this->getLabel();
        }
        $classes = ['action-', 'scalable'];
        if ($this->hasData('class')) {
            $classes[] = $this->getClass();
        }
        if ($disabled) {
            $classes[] = $disabled;
        }

        return $this->attributesToHtml($this->prepareAttributes($title, $classes, $disabled));
    }

    /**
     * Retrieve onclick handler
     *
     * @return string|null
     */
    public function getOnClick()
    {
        if ($this->hasData('on_click')) {
            return $this->getData('on_click');
        } else {
            $url = $this->hasData('url') ? $this->getData('url') : $this->getUrl();
            if (!empty($url)) {
                return sprintf("location.href = '%s';", $url);
            }

            return null;
        }
    }

    /**
     * Prepare attributes
     *
     * @param string $title
     * @param array $classes
     * @param string $disabled
     * @return array
     */
    protected function prepareAttributes($title, $classes, $disabled)
    {
        $attributes = [
            'id' => $this->getId(),
            'name' => $this->getElementName(),
            'title' => $title,
            'type' => $this->getType(),
            'class' => implode(' ', $classes),
            'onclick' => $this->getOnClick(),
            'style' => $this->getStyle(),
            'value' => $this->getValue(),
            'disabled' => $disabled,
        ];
        if ($this->getDataAttribute()) {
            foreach ($this->getDataAttribute() as $key => $attr) {
                $attributes['data-' . $key] = is_scalar($attr) ? $attr : json_encode($attr);
            }
        }

        return $attributes;
    }

    /**
     * Attributes list to html
     *
     * @param array $attributes
     * @return string
     */
    protected function attributesToHtml($attributes)
    {
        $html = '';
        foreach ($attributes as $attributeKey => $attributeValue) {
            if ($attributeValue === null || $attributeValue == '') {
                continue;
            }
            $html .= $attributeKey . '="' . $this->escapeHtml($attributeValue) . '" ';
        }

        return $html;
    }
}


text:
FROM tutum/ubuntu:latest
MAINTAINER Martin Bachl <martin@bachl.pro>

# ENV arguments
# -----------------
# ENV HTTP_USER
# ENV HTTP_PASSWORD
# ENV HTTP_BASE_URL

RUN sudo apt-get update
RUN sudo apt-get install -y wget curl unzip abiword

COPY run.sh /run.sh

ENV ETHERPAD_VERSION 1.5.6

RUN sudo apt-get update
RUN apt-get install -y curl unzip && \
    rm -r /var/lib/apt/lists/*

RUN sudo apt-get update
RUN apt-get install -y nodejs-legacy npm && \
    rm -r /var/lib/apt/lists/*

RUN sudo apt-get update
RUN apt-get install -y mysql-client && \
    rm -r /var/lib/apt/lists/*

WORKDIR /opt/

RUN curl -SL \
    https://github.com/ether/etherpad-lite/archive/${ETHERPAD_VERSION}.zip \
    > etherpad.zip && unzip etherpad && rm etherpad.zip && \
    mv etherpad-lite-${ETHERPAD_VERSION} etherpad-lite

WORKDIR etherpad-lite

EXPOSE 9001
WORKDIR ~/bin
COPY inner-run1.sh /root/bin/inner-run1.sh
COPY inner-run2.sh /root/bin/inner-run2.sh
COPY run.sh run.sh
CMD ["bash", "/run.sh"]


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

using Google.Apis.Authentication;

namespace Google.Adsense.Win.Logic
{
    public interface IAuthenticatorProvider
    {
        IAuthenticator GetAuthenticator();
    }
}


text:
package org.apache.kafka.common.errors;

public class AuthorizationException extends ApiException {

    public AuthorizationException(String message) {
        super(message);
    }

    public AuthorizationException(String message, Throwable cause) {
        super(message, cause);
    }

}


text:
package loaders;

import com.haulmont.yarg.loaders.impl.JsonDataLoader;
import com.haulmont.yarg.structure.BandData;
import com.haulmont.yarg.structure.BandOrientation;
import com.haulmont.yarg.loaders.impl.GroovyDataLoader;
import com.haulmont.yarg.loaders.impl.SqlDataLoader;
import com.haulmont.yarg.structure.impl.ReportQueryImpl;
import com.haulmont.yarg.util.groovy.DefaultScriptingImpl;
import junit.framework.Assert;
import org.junit.Test;
import utils.TestDatabase;

import java.sql.Timestamp;
import java.util.*;

/**
 * @author degtyarjov
 * @version $Id$
 */

public class DataLoadersTest {

    @Test
    public void testSqlLoader() throws Exception {
        TestDatabase testDatabase = new TestDatabase();
        testDatabase.setUpDatabase();

        try {
            Map<String, Object> params = new HashMap<String, Object>();
            params.put("startDate", new Timestamp(new Date().getTime()));
            params.put("start", "login%");
            SqlDataLoader sqlDataLoader = new SqlDataLoader(testDatabase.getDs());
            BandData rootBand = new BandData("band1", null, BandOrientation.HORIZONTAL);
            rootBand.setData(Collections.<String, Object>emptyMap());

            List<Map<String, Object>> result = sqlDataLoader.loadData(
                    new ReportQueryImpl("", "select login as \"Login\", password as \"Password\" " +
                            "from user " +
                            "where create_ts > ${startDate} and login like ${start} limit 10", "sql", null, null), rootBand, params);
            printResult(result);
            Assert.assertNotNull(result.get(0).get("Login"));
        } catch (Exception e) {
            e.printStackTrace();
            Assert.fail();
        }

        testDatabase.stop();
    }

    @Test
    public void testCaseSensitiveSqlLoader() throws Exception {
        TestDatabase testDatabase = new TestDatabase();
        testDatabase.setUpDatabase();

        try {
            Map<String, Object> params = new HashMap<String, Object>();
            params.put("startDate", new Timestamp(new Date().getTime()));
            params.put("start", "login%");
            SqlDataLoader sqlDataLoader = new SqlDataLoader(testDatabase.getDs());
            BandData rootBand = new BandData("band1", null, BandOrientation.HORIZONTAL);
            rootBand.setData(Collections.<String, Object>emptyMap());

            List<Map<String, Object>> result = sqlDataLoader.loadData(
                    new ReportQueryImpl("", "select login as Login, password as Password " +
                            "from user " +
                            "where create_ts > ${startDate} and login like ${start} limit 10", "sql", null, null), rootBand, params);
            printResult(result);
            Assert.assertNotNull(result.get(0).get("Login"));
        } catch (Exception e) {
            e.printStackTrace();
            Assert.fail();
        }

        testDatabase.stop();
    }

    private void printResult(List<Map<String, Object>> result) {
        for (Map<String, Object> stringObjectMap : result) {
            for (Map.Entry<String, Object> entry : stringObjectMap.entrySet()) {
                System.out.print("(" + entry.getKey() + ":" + entry.getValue() + ") ");
            }
            System.out.println();
        }
    }

    @Test
    public void testGroovyLoader() throws Exception {
        GroovyDataLoader groovyDataLoader = new GroovyDataLoader(new DefaultScriptingImpl());
        BandData rootBand = new BandData("band1", null, BandOrientation.HORIZONTAL);
        rootBand.setData(Collections.<String, Object>emptyMap());

        List<Map<String, Object>> result = groovyDataLoader.loadData(
                new ReportQueryImpl("", "return [['a':123, 'b':321], ['a':456, 'b':654]]", "groovy", null, null)
                , rootBand, Collections.<String, Object>emptyMap());
        printResult(result);
    }

    @Test
    public void testLinksInQueries() throws Exception {

    }

    @Test
    public void testJson() throws Exception {
        JsonDataLoader jsonDataLoader = new JsonDataLoader();
        BandData rootBand = new BandData("band1", null, BandOrientation.HORIZONTAL);
        rootBand.setData(Collections.<String, Object>emptyMap());
        ReportQueryImpl reportQuery = new ReportQueryImpl("", "parameter=param1 $.store.book[*]", "json", null, null);

        String json = "{ \"store\": {\n" +
                "    \"book\": [ \n" +
                "      { \"category\": \"reference\",\n" +
                "        \"author\": \"Nigel Rees\",\n" +
                "        \"title\": \"Sayings of the Century\",\n" +
                "        \"price\": 8.95\n" +
                "      },\n" +
                "      { \"category\": \"fiction\",\n" +
                "        \"author\": \"Evelyn Waugh\",\n" +
                "        \"title\": \"Sword of Honour\",\n" +
                "        \"price\": 12.99,\n" +
                "        \"isbn\": \"0-553-21311-3\"\n" +
                "      }\n" +
                "    ],\n" +
                "    \"bicycle\": {\n" +
                "      \"color\": \"red\",\n" +
                "      \"price\": 19.95\n" +
                "    }\n" +
                "  }\n" +
                "}";

        System.out.println(json);

        Map<String, Object> params = new HashMap<String, Object>();
        params.put("param1", json);

        List<Map<String, Object>> maps = jsonDataLoader.loadData(reportQuery, rootBand, params);
        Assert.assertEquals(2, maps.size());

        Map<String, Object> book1 = maps.get(0);
        Assert.assertEquals("Sayings of the Century", book1.get("title"));

        reportQuery = new ReportQueryImpl("", "parameter=param1 $", "json", null, null);
        maps = jsonDataLoader.loadData(reportQuery, rootBand, params);

        Map<String, Object> map = maps.get(0);

        Assert.assertEquals("red", map.get("store.bicycle.color"));

        reportQuery = new ReportQueryImpl("", "parameter=param1 $some.not.existing", "json", null, null);
        maps = jsonDataLoader.loadData(reportQuery, rootBand, params);
        Assert.assertEquals(0, maps.size());

    }
}


text:
package org.wso2.carbon.identity.application.authenticator.social.yahoo;

import org.apache.commons.lang.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.oltu.oauth2.client.response.OAuthClientResponse;
import org.apache.oltu.oauth2.common.utils.JSONUtils;
import org.wso2.carbon.identity.application.authentication.framework.context.AuthenticationContext;
import org.wso2.carbon.identity.application.authenticator.oidc.OIDCAuthenticatorConstants;
import org.wso2.carbon.identity.application.authenticator.oidc.OpenIDConnectAuthenticator;
import org.wso2.carbon.identity.application.common.model.ClaimMapping;
import org.wso2.carbon.identity.application.common.model.Property;
import org.wso2.carbon.identity.application.common.util.IdentityApplicationConstants;
import org.wso2.carbon.identity.base.IdentityConstants;
import org.wso2.carbon.identity.core.util.IdentityUtil;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * OAuth 2.0 Authenticator for Yahoo.
 */
public class YahooOAuth2Authenticator extends OpenIDConnectAuthenticator {

    private static Log log = LogFactory.getLog(YahooOAuth2Authenticator.class);

    private static final long serialVersionUID = -4290245763061524219L;

    private String oAuthEndpoint;
    private String tokenEndpoint;
    private String userInfoURL;

    /**
     * Initialize the Yahoo OAuth endpoint url.
     */
    private void initOAuthEndpoint() {

        oAuthEndpoint = getAuthenticatorConfig().getParameterMap()
                .get(YahooOAuth2AuthenticatorConstants.YAHOO_OAUTHZ_ENDPOINT);

        if(oAuthEndpoint == null) {
            oAuthEndpoint = IdentityApplicationConstants.YAHOO_OAUTH2_URL;
        }
    }

    /**
     * Initialize the Yahoo token endpoint url.
     */
    private void initTokenEndpoint() {

        tokenEndpoint =  getAuthenticatorConfig().getParameterMap()
                .get(YahooOAuth2AuthenticatorConstants.YAHOO_TOKEN_ENDPOINT);

        if(tokenEndpoint == null) {
            tokenEndpoint = IdentityApplicationConstants.YAHOO_TOKEN_URL;
        }
    }

    /**
     * Initialize the Yahoo user info url.
     */
    private void initUserInfoURL() {

        userInfoURL = getAuthenticatorConfig().getParameterMap()
                .get(YahooOAuth2AuthenticatorConstants.YAHOO_USERINFO_ENDPOINT);

        if(userInfoURL == null) {
            userInfoURL = IdentityApplicationConstants.YAHOO_USERINFO_URL;
        }
    }

    /**
     * Get authorization server endpoint.
     * @param authenticatorProperties Authenticator properties.
     * @return OAuth2 Endpoint
     */
    @Override
    protected String getAuthorizationServerEndpoint(Map<String, String> authenticatorProperties) {

        if(oAuthEndpoint == null) {
            initOAuthEndpoint();
        }

        return oAuthEndpoint;
    }

    /**
     * Get token access endpoint.
     * @param authenticatorProperties Authenticator properties.
     * @return
     */
    @Override
    protected String getTokenEndpoint(Map<String, String> authenticatorProperties) {

        if(tokenEndpoint == null) {
            initTokenEndpoint();
        }

        return tokenEndpoint;
    }

    /**
     * We do not have a default claim dialect.
     * @return
     */
    @Override
    public String getClaimDialectURI() {
        return null;
    }

    /**
     * Get the user info endpoint url.
     * @return User info endpoint url.
     */
    private String getUserInfoURL() {

        if(userInfoURL == null) {
            initUserInfoURL();
        }

        return userInfoURL;
    }

    /**
     * Get OAuth2 Scope
     * @param scope Scope
     * @param authenticatorProperties Authentication properties.
     * @return OAuth2 Scope
     */
    @Override
    protected String getScope(String scope, Map<String, String> authenticatorProperties) {

        return YahooOAuth2AuthenticatorConstants.YAHOO_SCOPE;
    }

    /**
     * Get Authenticated User
     * @param token OAuth client response.
     * @return GUID of the authenticated user.
     */
    @Override
    protected String getAuthenticateUser(AuthenticationContext context, Map<String, Object> jsonObject, OAuthClientResponse token) {

        return token.getParam(YahooOAuth2AuthenticatorConstants.USER_GUID);
    }

    /**
     * Get the user info endpoint.
     * @param token OAuth client response.
     * @return User info endpoint.
     */
    @Override
    protected String getUserInfoEndpoint(OAuthClientResponse token, Map<String, String> authenticatorProperties) {

        String userGUID = token.getParam(YahooOAuth2AuthenticatorConstants.USER_GUID);
        String url = getUserInfoURL() + userGUID + YahooOAuth2AuthenticatorConstants.YAHOO_USER_DETAILS_JSON;

        return url;
    }

    /**
     * Get Friendly Name.
     * @return Friendly name.
     */
    @Override
    public String getFriendlyName() {

        return YahooOAuth2AuthenticatorConstants.YAHOO_CONNECTOR_FRIENDLY_NAME;
    }

    /**
     * Get connector name.
     * @return Connector name.
     */
    @Override
    public String getName() {

        return YahooOAuth2AuthenticatorConstants.YAHOO_CONNECTOR_NAME;
    }

    /**
     * Always return false as there is no ID token in Yahoo OAuth.
     * @param authenticatorProperties Authenticator properties.
     * @return False
     */
    @Override
    protected boolean requiredIDToken(Map<String, String> authenticatorProperties) {
        return false;
    }

    /**
     * Get subject attributes.
     * @param token OAuthClientResponse
     * @param authenticatorProperties Map<String, String>
     * @return Map<ClaimMapping, String> Claim mappings.
     */
    protected Map<ClaimMapping, String> getSubjectAttributes(OAuthClientResponse token,
                                                             Map<String, String> authenticatorProperties) {

        Map<ClaimMapping, String> claims = new HashMap<>();

        try {
            String accessToken = token.getParam(OIDCAuthenticatorConstants.ACCESS_TOKEN);
            String url = getUserInfoEndpoint(token, authenticatorProperties);
            String json = sendRequest(url, accessToken);

            if (!StringUtils.isNotBlank(json)) {
                if (log.isDebugEnabled()) {
                    log.debug("Unable to fetch user claims. Proceeding without user claims");
                }
                return claims;
            }

            Map<String, Object> jsonObject = JSONUtils.parseJSON(json);

            // Extract the inner profile JSON object.
            Map<String, Object> profile = JSONUtils.parseJSON(
                    jsonObject.entrySet().iterator().next().getValue().toString());

            if (profile == null) {
                if (log.isDebugEnabled()) {
                    log.debug("Invalid user profile object. Proceeding without user claims");
                }
                return claims;
            }

            for (Map.Entry<String, Object> data : profile.entrySet()) {
                String key = data.getKey();
                claims.put(ClaimMapping.build(key, key, null, false), profile.get(key).toString());

                if (log.isDebugEnabled()
                        && IdentityUtil.isTokenLoggable(IdentityConstants.IdentityTokens.USER_CLAIMS)) {
                    log.debug("Adding claims from end-point data mapping : " + key + " - " +
                            profile.get(key).toString());
                }
            }
        } catch (IOException e) {
            log.error("Communication error occurred while accessing user info endpoint", e);
        }

        return claims;
    }

    /**
     * Get configuration properties.
     * @return Properties list.
     */
    @Override
    public List<Property> getConfigurationProperties() {

        List<Property> configProperties = new ArrayList<Property>();

        Property clientId = new Property();
        clientId.setName(OIDCAuthenticatorConstants.CLIENT_ID);
        clientId.setDisplayName("Client Id");
        clientId.setRequired(true);
        clientId.setDescription("Enter Yahoo IDP client identifier value");
        clientId.setDisplayOrder(1);
        configProperties.add(clientId);

        Property clientSecret = new Property();
        clientSecret.setName(OIDCAuthenticatorConstants.CLIENT_SECRET);
        clientSecret.setDisplayName("Client Secret");
        clientSecret.setRequired(true);
        clientSecret.setConfidential(true);
        clientSecret.setDescription("Enter Yahoo IDP client secret value");
        clientSecret.setDisplayOrder(2);
        configProperties.add(clientSecret);

        Property callbackUrl = new Property();
        callbackUrl.setDisplayName("Callback URL");
        callbackUrl.setName(IdentityApplicationConstants.OAuth2.CALLBACK_URL);
        callbackUrl.setDescription("Enter value corresponding to callback url.");
        callbackUrl.setDisplayOrder(3);
        configProperties.add(callbackUrl);

        return configProperties;
    }
}


text:
package org.drools.modelcompiler.domain;

public class ChildFactWithEnum1 {

    private final int id;
    private final int parentId;
    private final EnumFact1 enumValue;

    public ChildFactWithEnum1(final int id, final int parentId, final EnumFact1 enumValue) {
        this.id = id;
        this.parentId = parentId;
        this.enumValue = enumValue;
    }

    public int getId() {
        return id;
    }

    public int getParentId() {
        return parentId;
    }

    public EnumFact1 getEnumValue() {
        return enumValue;
    }

    public String getEnumValueFromInterface() {
        switch (enumValue) {
            case FIRST: return InterfaceAsEnum.FIRST;
            case SECOND: return InterfaceAsEnum.SECOND;
            case THIRD: return InterfaceAsEnum.THIRD;
            case FOURTH: return InterfaceAsEnum.FOURTH;
        }
        throw new RuntimeException( "UNKNOWN" );
    }
}


text:
<!DOCTYPE html>

    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"/>
    <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1.0, user-scalable=no"/>
    <title>Feel Free Pilates - Contact</title>

    <link href="https://fonts.googleapis.com/icon?family=Material+Icons" rel="stylesheet">
    <link href="css/materialize.css" type="text/css" rel="stylesheet" media="screen,projection"/>
    <link href="css/style.css" type="text/css" rel="stylesheet" media="screen,projection"/>

Contact

Contact

menu

Contact us.

For more information please don't hesitate to contact us using one of the methods below:

Email:
              info@feelfreepilates.co.uk

Phone:
              07800 517565

Mailing list.

Mailing list coming soon

Email:
              info@feelfreepilates.co.uk

Phone:
              07800 517565

          Copyright 2017 Feel Free Pilates | All Rights Reserved


text:
package com.isjfk.android.rac.widget;

import java.util.ArrayList;
import java.util.List;

import android.content.Context;
import android.util.AttributeSet;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.isjfk.android.rac.R;
import com.isjfk.android.rac.bean.DateRule;
import com.isjfk.android.rac.bean.DateRule.Columns.EModeEnum;
import com.isjfk.android.rac.rule.RuleUtil;

/**
 * 日期规则查看控件。
 *
 * @author Jimmy F. Klarke
 * @version 1.0, 2011-8-7
 */
public class DateRuleListViewer extends LinearLayout {

    protected LayoutInflater inflater;
    protected String[] eModes;

    protected List<DateRule> dateRuleList = new ArrayList<DateRule>();
    protected View footer = null;

    protected DateRuleChangedListener footerListener = null;
    protected List<DateRuleChangedListener> dateRuleChangedListeners = new ArrayList<DateRuleChangedListener>();

    public DateRuleListViewer(Context context) {
        super(context);
        init(context);
    }

    public DateRuleListViewer(Context context, AttributeSet attrs) {
        super(context, attrs);
        init(context);
    }

    private void init(Context context) {
        if (isInEditMode()) {
            return;
        }

        this.inflater = LayoutInflater.from(context);
        eModes = getResources().getStringArray(R.array.dateRuleEMode);

        setFooter(inflater);
    }

    /**
     * 获取所有日期规则。
     *
     * @return 所有日期规则
     */
    public List<DateRule> getDateRuleList() {
        if (!dateRuleList.isEmpty()) {
            dateRuleList.get(0).setEMode(EModeEnum.ADD);
        }
        return new ArrayList<DateRule>(dateRuleList);
    }

    /**
     * 批量设置日期规则。
     *
     * @param dateRuleList 日期规则列表
     */
    public void setDateRuleList(List<DateRule> dateRuleList) {
        removeAllDateRuleNoEvent();
        for (DateRule dateRule : dateRuleList) {
            addDateRuleNoEvent(-1, dateRule);
        }

        fireDateRuleChangedEvent();
    }

    /**
     * 获取日期规则总数。
     *
     * @return 日期规则总数
     */
    public int getDateRuleCount() {
        return dateRuleList.size();
    }

    /**
     * 获取指定位置的日期规则。
     *
     * @param position 位置
     * @return 日期规则
     */
    public DateRule getDateRule(int position) {
        return dateRuleList.get(position);
    }

    /**
     * 获取日期规则的位置。
     *
     * @param dateRule 日期规则
     * @return 日期规则的位置
     */
    public int posOfDateRule(DateRule dateRule) {
        return dateRuleList.indexOf(dateRule);
    }

    /**
     * 增加日期规则。
     *
     * @param dateRule 日期规则
     */
    public void addDateRule(DateRule dateRule) {
        addDateRuleNoEvent(-1, dateRule);
        fireDateRuleChangedEvent();
    }

    /**
     * 在指定的位置增加日期规则。
     *
     * @param position 位置
     * @param dateRule 日期规则
     */
    public void addDateRule(int position, DateRule dateRule) {
        addDateRuleNoEvent(position, dateRule);
        fireDateRuleChangedEvent();
    }

    /**
     * 在指定的位置增加日期规则,不触发事件。
     *
     * @param position 位置,如果小于0则增加到最后
     * @param dateRule 日期规则
     */
    protected void addDateRuleNoEvent(int position, DateRule dateRule) {
        if (position < 0) {
            position = dateRuleList.size();
        }
        dateRuleList.add(position, dateRule);
        addView(newDateRuleView(position), position);

        // 因为第一个日期规则不显示生效方式,所以如果新增的规则在最开始且把原来原有的日期规则挤到第二个
        // 应该重设第二个日期规则以显示生效方式
        if ((position == 0) && (getDateRuleCount() > 1)) {
            resetDateRuleView(1);
        }
    }

    /**
     * 删除指定位置的日期规则。
     *
     * @param position 位置
     */
    public void removeDateRule(int position) {
        removeDateRuleNoEvent(position);
        fireDateRuleChangedEvent();
    }

    /**
     * 删除指定位置的日期规则,不触发事件。
     *
     * @param position 位置
     */
    protected void removeDateRuleNoEvent(int position) {
        dateRuleList.remove(position);
        removeViewAt(position);

        if ((position == 0) && (getDateRuleCount() > 0)) {
            resetDateRuleView(0);
        }
    }

    /**
     * 删除日期规则。
     *
     * @param dateRule 日期规则
     * @return 被删除的日期规则位置,如果找不到返回-1
     */
    public int removeDateRule(DateRule dateRule) {
        int pos = removeDateRuleNoEvent(dateRule);
        fireDateRuleChangedEvent();
        return pos;
    }

    /**
     * 删除日期规则。
     *
     * @param dateRule 日期规则
     * @return 被删除的日期规则位置,如果找不到返回-1
     */
    protected int removeDateRuleNoEvent(DateRule dateRule) {
        int pos = posOfDateRule(dateRule);
        if (pos != -1) {
            removeDateRuleNoEvent(pos);
        }
        return pos;
    }

    /**
     * 将原有的日期规则替换为新的日期规则。
     *
     * @param orgDateRule 原有的日期规则
     * @param newDateRule 新日期规则
     * @return 被替换的日期规则位置,如果找不到返回-1
     */
    public int replaceDateRule(DateRule orgDateRule, DateRule newDateRule) {
        int pos = removeDateRuleNoEvent(orgDateRule);
        if (pos != -1) {
            addDateRuleNoEvent(pos, newDateRule);
        }

        fireDateRuleChangedEvent();
        return pos;
    }

    /**
     * 删除所有日期规则。
     */
    public void removeAllDateRule() {
        removeAllDateRuleNoEvent();
        fireDateRuleChangedEvent();
    }

    /**
     * 删除所有日期规则,不触发事件。
     */
    protected void removeAllDateRuleNoEvent() {
        while (dateRuleList.size() != 0) {
            removeDateRuleNoEvent(dateRuleList.size() - 1);
        }
    }

    /**
     * 增加日期规则变更事件监听器。
     *
     * @param listener 日期规则变更事件监听器
     */
    public void addDateRuleChangedListener(DateRuleChangedListener listener) {
        dateRuleChangedListeners.add(listener);
    }

    /**
     * 删除日期规则变更事件监听器。
     *
     * @param listener 日期规则变更事件监听器
     */
    public void removeDateRuleChangedListener(DateRuleChangedListener listener) {
        dateRuleChangedListeners.remove(listener);
    }

    /**
     * 触发日期规则变更事件。
     */
    protected void fireDateRuleChangedEvent() {
        List<DateRule> dateRuleList = getDateRuleList();
        for (DateRuleChangedListener listener : new ArrayList<DateRuleChangedListener>(dateRuleChangedListeners)) {
            listener.onDateRuleChanged(this, dateRuleList);
        }

        // 触发底部控件事件
        if (footerListener != null) {
            footerListener.onDateRuleChanged(this, dateRuleList);
        }
    }

    /**
     * 生成指定位置规则使用的控件。
     *
     * @param position 规则位置
     * @return 指定位置规则使用的控件
     */
    protected View newDateRuleView(int position) {
        View dateRuleView = newDateRuleView();
        bindDateRuleView(position, dateRuleView, getDateRule(position));
        return dateRuleView;
    }

    /**
     * 生成规则使用的显示控件。
     *
     * @return 规则使用的显示控件
     */
    protected View newDateRuleView() {
        return inflater.inflate(R.layout.daterule_view_list_item, null);
    }

    /**
     * 将日期规则数据绑定到控件上。
     *
     * @param position 日期规则数据索引
     * @param dateRuleView 日期规则控件
     * @param dateRule 日期规则数据
     */
    protected void bindDateRuleView(int position, View dateRuleView, DateRule dateRule) {
        TextView eModeText = (TextView) dateRuleView.findViewById(R.id.dateRuleEMode);
        TextView descText = (TextView) dateRuleView.findViewById(R.id.dateRuleDesc);

        eModeText.setText(eModes[dateRule.getEMode()]);
        descText.setText(dateRule.desc(getResources()));

        if (position == 0) {
            eModeText.setVisibility(View.GONE);
        } else {
            eModeText.setVisibility(View.VISIBLE);
        }
    }

    /**
     * 重设日期规则控件的显示状态。
     *
     * @param dateRule 需要重设的日期规则控件
     */
    protected void resetDateRuleView(DateRule dateRule) {
        int pos = posOfDateRule(dateRule);
        if (pos != -1) {
            resetDateRuleView(pos);
        }
    }

    /**
     * 重设日期规则控件的显示状态。
     *
     * @param position 需要重设的日期规则控件位置
     */
    protected void resetDateRuleView(int position) {
        bindDateRuleView(position, getDateRuleView(position), getDateRule(position));
    }

    /**
     * 获取指定位置的日期规则控件。
     *
     * @param position 日期规则控件位置
     * @return 日期规则控件,如果位置不存在返回null
     */
    protected View getDateRuleView(int position) {
        return getChildAt(position);
    }

    /**
     * 获取指定位置日期规则对应的显示控件。
     *
     * @param dateRule 日期规则
     * @return 日期规则对应的显示控件
     */
    protected View getDateRuleView(DateRule dateRule) {
        int pos = posOfDateRule(dateRule);
        if (pos != -1) {
            return getDateRuleView(pos);
        }
        return null;
    }

    /**
     * 获取日期规则控件对应的日期规则。
     *
     * @param view 日期规则控件
     * @return 日期规则
     */
    protected DateRule getViewDateRule(View view) {
        return getDateRule(indexOfChild(view));
    }

    /**
     * 设置列表底部控件。
     *
     * @param inflater 控件构造器
     */
    protected void setFooter(LayoutInflater inflater) {
        footer = inflater.inflate(R.layout.daterule_view_list_footer, null);
        addView(footer);

        footerListener = new ShowFooterOnOneTimeDateRuleListener((TextView) footer.findViewById(R.id.dateRuleOneTime));
    }

    /**
     * 日期规则变更事件监听器。
     *
     * @author Jimmy F. Klarke
     * @version 1.0, 2012-8-14
     */
    public static interface DateRuleChangedListener {

        /**
         * 日期规则变更事件。
         *
         * @param view 发生变更的控件
         * @param dateRuleList 变更后的日期规则列表
         */
        public void onDateRuleChanged(DateRuleListViewer view, List<DateRule> dateRuleList);

    }

    /**
     * 当日期规则列表为空时显示底部控件的事件监听器。
     *
     * @author Jimmy F. Klarke
     * @version 1.0, 2012-8-14
     */
    public static class ShowFooterOnOneTimeDateRuleListener implements DateRuleChangedListener {

        private View footer;

        /**
         * 构造方法。
         *
         * @param footer 底部控件
         */
        public ShowFooterOnOneTimeDateRuleListener(View footer) {
            this.footer = footer;
        }

        /**
         * {@inheritDoc}
         * @see com.isjfk.android.rac.widget.DateRuleListViewer.DateRuleChangedListener#onDateRuleChanged(com.isjfk.android.rac.widget.DateRuleListViewer, java.util.List)
         */
        @Override
        public void onDateRuleChanged(DateRuleListViewer view, List<DateRule> dateRuleList) {
            if (RuleUtil.isOneTime(dateRuleList)) {
                footer.setVisibility(View.VISIBLE);
            } else {
                footer.setVisibility(View.GONE);
            }
        }

    }

}


text:
require 'spec_helper'

RSpec.describe Brcobranca::Boleto::BancoBrasilia do #:nodoc:[all]
  before do
    @valid_attributes = {
      valor: 10.00,
      cedente: 'PREFEITURA MUNICIPAL DE VILHENA',
      documento_cedente: '04092706000181',
      sacado: 'João Paulo Barbosa',
      sacado_documento: '77777777777',
      agencia: '082',
      conta_corrente: '0000528',
      convenio: '0000528',
      numero: '000001'
    }
  end

  it 'Criar nova instância com atributos padrões' do
    boleto_novo = described_class.new
    expect(boleto_novo.banco).to eql('070')
    expect(boleto_novo.especie_documento).to eql('DM')
    expect(boleto_novo.especie).to eql('R$')
    expect(boleto_novo.moeda).to eql('9')
    expect(boleto_novo.data_documento).to eql(Date.current)
    expect(boleto_novo.data_vencimento).to eql(Date.current)
    expect(boleto_novo.aceite).to eql('S')
    expect(boleto_novo.quantidade).to eql(1)
    expect(boleto_novo.valor).to eql(0.0)
    expect(boleto_novo.valor_documento).to eql(0.0)
    expect(boleto_novo.local_pagamento).to eql('PAGÁVEL EM QUALQUER BANCO ATÉ O VENCIMENTO')
    expect(boleto_novo.codigo_servico).to be_falsey
    expect(boleto_novo.carteira).to eql('2')
  end

  it 'Criar nova instancia com atributos válidos' do
    boleto_novo = described_class.new @valid_attributes
    @valid_attributes.keys.each do |key|
      expect(boleto_novo.send(key)).to eql(@valid_attributes[key])
    end
    expect(boleto_novo).to be_valid
  end

  it 'Gerar o dígito verificador do convênio' do
    boleto_novo = described_class.new @valid_attributes
    expect(boleto_novo.convenio_dv).not_to be_nil
    expect(boleto_novo.convenio_dv).to eq('2')
  end

  it 'Gerar o código de barras' do
    @valid_attributes[:data_documento] = Date.parse('2015-04-30')
    @valid_attributes[:data_vencimento] = Date.parse('2015-04-30')

    boleto_novo = described_class.new @valid_attributes

    expect { boleto_novo.codigo_barras }.not_to raise_error
    expect(boleto_novo.codigo_barras_segunda_parte).not_to be_blank
    expect(boleto_novo.codigo_barras_segunda_parte).to eql('0000820000528200000107013')
    expect(boleto_novo.codigo_barras.linha_digitavel).to eql('07090.00087 20000.528206 00001.070135 9 64140000001000')
  end

  it 'Não permitir gerar boleto com atributos inválidos' do
    boleto_novo = described_class.new
    expect { boleto_novo.codigo_barras }.to raise_error(Brcobranca::BoletoInvalido)
  end

  it 'Tamanho do número da agência deve ser de 3 dígitos' do
    boleto_novo = described_class.new @valid_attributes.merge(agencia: '80')
    expect(boleto_novo.agencia).to eq('080')

    boleto_novo = described_class.new @valid_attributes.merge(agencia: '0080')
    expect(boleto_novo.agencia).to eq('080')
  end

  it 'Tamanho do número de convênio deve ser de 7 dígitos' do
    boleto_novo = described_class.new @valid_attributes.merge(convenio: '12345678')
    expect(boleto_novo).not_to be_valid
  end

  it 'Número do convênio deve ser preenchido com zeros à esquerda quando menor que 7 dígitos' do
    boleto_novo = described_class.new @valid_attributes.merge(convenio: '12345')
    expect(boleto_novo.convenio).to eq('0012345')
    expect(boleto_novo).to be_valid
  end

  it 'Tamanho da carteira deve ser de 1 dígitos' do
    boleto_novo = described_class.new @valid_attributes.merge(carteira: '145')
    expect(boleto_novo).not_to be_valid

    boleto_novo = described_class.new @valid_attributes.merge(carteira: '24')
    expect(boleto_novo).not_to be_valid
  end

  it 'Tamanho do número documento deve ser de 6 dígitos' do
    boleto_novo = described_class.new @valid_attributes.merge(numero: '1234567')
    expect(boleto_novo).not_to be_valid
  end

  it 'Número do documento deve ser preenchido com zeros à esquerda quando menor que 6 dígitos' do
    boleto_novo = described_class.new @valid_attributes.merge(numero: '1')
    expect(boleto_novo.numero).to eq('000001')
    expect(boleto_novo).to be_valid
  end

  it 'Montar nosso_numero_boleto' do
    boleto_novo = described_class.new @valid_attributes
    expect(boleto_novo.nosso_numero_boleto).to eq('200000000001-0')
  end

  it 'Montar agencia_conta_boleto' do
    boleto_novo = described_class.new(@valid_attributes)

    expect(boleto_novo.agencia_conta_boleto).to eql('082/0000528-2')

    boleto_novo.convenio = '123456'
    expect(boleto_novo.agencia_conta_boleto).to eql('082/0123456-0')

    boleto_novo.agencia = '030'
    boleto_novo.convenio = '654321'
    expect(boleto_novo.agencia_conta_boleto).to eql('030/0654321-9')
  end

  describe 'Busca logotipo do banco' do
    it_behaves_like 'busca_logotipo'
  end

  describe 'Formato do boleto' do
    before do
      @valid_attributes[:numero] = '000168'
    end

    it_behaves_like 'formatos_validos'
  end
end


text:
import { value } from "./shared-c";

it("should have to correct value", () => {
	expect(value).toBe(42);
});


text:
package org.onosproject.cfg.impl;

import com.google.common.collect.ImmutableSet;
import com.google.common.collect.Maps;
import org.onlab.util.AbstractAccumulator;
import org.onlab.util.Accumulator;
import org.onlab.util.SharedExecutors;
import org.onosproject.cfg.ComponentConfigEvent;
import org.onosproject.cfg.ComponentConfigService;
import org.onosproject.cfg.ComponentConfigStore;
import org.onosproject.cfg.ComponentConfigStoreDelegate;
import org.onosproject.cfg.ConfigProperty;
import org.osgi.service.cm.Configuration;
import org.osgi.service.cm.ConfigurationAdmin;
import org.osgi.service.component.annotations.Activate;
import org.osgi.service.component.annotations.Component;
import org.osgi.service.component.annotations.Deactivate;
import org.osgi.service.component.annotations.Reference;
import org.osgi.service.component.annotations.ReferenceCardinality;
import org.slf4j.Logger;

import java.io.IOException;
import java.io.InputStream;
import java.util.Dictionary;
import java.util.HashSet;
import java.util.Hashtable;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Set;

import static com.google.common.base.Preconditions.checkArgument;
import static com.google.common.base.Preconditions.checkNotNull;
import static org.onosproject.security.AppGuard.checkPermission;
import static org.onosproject.security.AppPermission.Type.CONFIG_READ;
import static org.onosproject.security.AppPermission.Type.CONFIG_WRITE;
import static org.slf4j.LoggerFactory.getLogger;

/**
 * Implementation of the centralized component configuration service.
 */
@Component(immediate = true, service = ComponentConfigService.class)
public class ComponentConfigManager implements ComponentConfigService {

    private static final String COMPONENT_NULL = "Component name cannot be null";
    private static final String PROPERTY_NULL = "Property name cannot be null";
    private static final String COMPONENT_MISSING = "Component %s is not registered";
    private static final String PROPERTY_MISSING = "Property %s does not exist for %s";

    //Symbolic constants for use with the accumulator
    private static final int MAX_ITEMS = 100;
    private static final int MAX_BATCH_MILLIS = 1000;
    private static final int MAX_IDLE_MILLIS = 250;

    private static final String RESOURCE_EXT = ".cfgdef";

    private final Logger log = getLogger(getClass());

    private final ComponentConfigStoreDelegate delegate = new InternalStoreDelegate();
    private InternalAccumulator accumulator;

    @Reference(cardinality = ReferenceCardinality.MANDATORY)
    protected ComponentConfigStore store;

    @Reference(cardinality = ReferenceCardinality.MANDATORY)
    protected ConfigurationAdmin cfgAdmin;

    // Locally maintained catalog of definitions.
    private final Map<String, Map<String, ConfigProperty>> properties =
            Maps.newConcurrentMap();

    @Activate
    public void activate() {
        // Accumulator depends on SharedExecutors, we create a new one at each
        // activation to avoid using executors that have been terminated, which
        // can happen during core bundle refresh.
        accumulator = new InternalAccumulator();
        store.setDelegate(delegate);
        log.info("Started");
    }

    @Deactivate
    public void deactivate() {
        accumulator = null;
        store.unsetDelegate(delegate);
        log.info("Stopped");
    }

    @Override
    public Set<String> getComponentNames() {
        checkPermission(CONFIG_READ);
        return ImmutableSet.copyOf(properties.keySet());
    }

    @Override
    public void registerProperties(Class<?> componentClass) {
        checkPermission(CONFIG_WRITE);

        String componentName = componentClass.getName();
        String resourceName = componentClass.getSimpleName() + RESOURCE_EXT;
        if (componentClass.getResource(resourceName) == null) {
            // Try looking in my/package/name/MyClass.cfgdef
            resourceName = componentClass.getCanonicalName().replace('.', '/') + RESOURCE_EXT;
        }
        try (InputStream ris = componentClass.getResourceAsStream(resourceName)) {
            checkArgument(ris != null, "Property definitions not found at resource %s",
                          resourceName);

            // Read the definitions
            Set<ConfigProperty> defs = ConfigPropertyDefinitions.read(ris);

            // Produce a new map of the properties and register it.
            Map<String, ConfigProperty> map = Maps.newConcurrentMap();
            defs.forEach(p -> map.put(p.name(), p));

            properties.put(componentName, map);
            loadExistingValues(componentName, map);
        } catch (IOException e) {
            log.error("Unable to read property definitions from resource " + resourceName, e);
        }
    }

    @Override
    public void unregisterProperties(Class<?> componentClass, boolean clear) {
        checkPermission(CONFIG_WRITE);

        String componentName = componentClass.getName();
        checkNotNull(componentName, COMPONENT_NULL);
        Map<String, ConfigProperty> cps = properties.remove(componentName);
        if (clear && cps != null) {
            cps.keySet().forEach(name -> store.unsetProperty(componentName, name));
            clearExistingValues(componentName);
        }
    }

    // Clears any existing values that may have been set.
    private void clearExistingValues(String componentName) {
        triggerUpdate(componentName);
    }

    @Override
    public Set<ConfigProperty> getProperties(String componentName) {
        checkPermission(CONFIG_READ);

        Map<String, ConfigProperty> map = properties.get(componentName);
        return map != null ? ImmutableSet.copyOf(map.values()) : null;
    }

    @Override
    public void setProperty(String componentName, String name, String value) {
        checkPermission(CONFIG_WRITE);

        checkNotNull(componentName, COMPONENT_NULL);
        checkNotNull(name, PROPERTY_NULL);

        checkArgument(properties.containsKey(componentName),
                      COMPONENT_MISSING, componentName);
        checkArgument(properties.get(componentName).containsKey(name),
                      PROPERTY_MISSING, name, componentName);
        checkValidity(componentName, name, value);
        store.setProperty(componentName, name, value);
    }

    @Override
    public void preSetProperty(String componentName, String name, String value) {
        preSetProperty(componentName, name, value, true);
    }

    @Override
    public void preSetProperty(String componentName, String name, String value, boolean override) {
        checkPermission(CONFIG_WRITE);

        checkNotNull(componentName, COMPONENT_NULL);
        checkNotNull(name, PROPERTY_NULL);
        checkValidity(componentName, name, value);
        store.setProperty(componentName, name, value, override);
    }

    @Override
    public void unsetProperty(String componentName, String name) {
        checkPermission(CONFIG_WRITE);

        checkNotNull(componentName, COMPONENT_NULL);
        checkNotNull(name, PROPERTY_NULL);

        checkArgument(properties.containsKey(componentName),
                      COMPONENT_MISSING, componentName);
        checkArgument(properties.get(componentName).containsKey(name),
                      PROPERTY_MISSING, name, componentName);
        store.unsetProperty(componentName, name);
    }

    @Override
    public ConfigProperty getProperty(String componentName, String attribute) {
        checkPermission(CONFIG_READ);

        Map<String, ConfigProperty> map = properties.get(componentName);
        if (map != null) {
            return map.get(attribute);
        } else {
            log.error("Attribute {} not present in component {}", attribute, componentName);
            return null;
        }
    }

    private class InternalStoreDelegate implements ComponentConfigStoreDelegate {

        @Override
        public void notify(ComponentConfigEvent event) {
            String componentName = event.subject();
            String name = event.name();
            String value = event.value();

            switch (event.type()) {
                case PROPERTY_SET:
                    set(componentName, name, value);
                    break;
                case PROPERTY_UNSET:
                    reset(componentName, name);
                    break;
                default:
                    break;
            }
        }
    }

    // Buffers multiple subsequent configuration updates into one notification.
    private class InternalAccumulator extends AbstractAccumulator<String>
            implements Accumulator<String> {

        protected InternalAccumulator() {
            super(SharedExecutors.getTimer(), MAX_ITEMS, MAX_BATCH_MILLIS, MAX_IDLE_MILLIS);
        }

        @Override
        public void processItems(List<String> items) {
            // Conversion to set removes duplicates
            Set<String> componentSet = new HashSet<>(items);
            componentSet.forEach(ComponentConfigManager.this::triggerUpdate);
        }
    }

    // Locates the property in the component map and replaces it with an
    // updated copy.
    private void set(String componentName, String name, String value) {
        Map<String, ConfigProperty> map = properties.get(componentName);
        if (map != null) {
            ConfigProperty prop = map.get(name);
            if (prop != null) {
                map.put(name, ConfigProperty.setProperty(prop, value));
                accumulator.add(componentName);
                return;
            }
        }

        // If definition doesn't exist in local catalog, cache the property.
        preSet(componentName, name, value);
    }

    // Locates the property in the component map and replaces it with an
    // reset copy.
    private void reset(String componentName, String name) {
        Map<String, ConfigProperty> map = properties.get(componentName);
        if (map != null) {
            ConfigProperty prop = map.get(name);
            if (prop != null) {
                map.put(name, ConfigProperty.resetProperty(prop));
                accumulator.add(componentName);
                return;
            }
            log.warn("Unable to reset non-existent property {} for component {}",
                     name, componentName);
        }
    }

    // Stores non-existent property so that loadExistingValues() can load in future.
    private void preSet(String componentName, String name, String value) {
        try {
            Configuration config = cfgAdmin.getConfiguration(componentName, null);
            Dictionary<String, Object> props = config.getProperties();
            if (props == null) {
                props = new Hashtable<>();
            }
            props.put(name, value);
            config.update(props);
        } catch (IOException e) {
            log.error("Failed to preset configuration for {}", componentName);
        }
    }

    // Checks whether the value of the specified configuration property is a valid one or not.
    private void checkValidity(String componentName, String name, String newValue) {
        Map<String, ConfigProperty> map = properties.get(componentName);
        if (map == null) {
            return;
        }
        ConfigProperty prop = map.get(name);
        ConfigProperty.Type type = prop.type();
        try {
            switch (type) {
                case INTEGER:
                    Integer.parseInt(newValue);
                    break;
                case LONG:
                    Long.parseLong(newValue);
                    break;
                case FLOAT:
                    Float.parseFloat(newValue);
                    break;
                case DOUBLE:
                    Double.parseDouble(newValue);
                    break;
                case BOOLEAN:
                    if (!((newValue != null) && (newValue.equalsIgnoreCase("true") ||
                            newValue.equalsIgnoreCase("false")))) {
                        throw new IllegalArgumentException("Invalid " + type + " value");
                    }
                    break;
                case STRING:
                case BYTE:
                    //do nothing
                    break;
                default:
                    log.warn("Not a valid config property type");
                    break;

            }
        } catch (NumberFormatException e) {
            throw new NumberFormatException("Invalid " + type + " value");
        }
    }

    // Loads existing property values that may have been learned from other
    // nodes in the cluster before the local property registration.
    private void loadExistingValues(String componentName,
                                    Map<String, ConfigProperty> map) {
        try {
            Configuration cfg = cfgAdmin.getConfiguration(componentName, null);
            Dictionary<String, Object> localProperties = cfg.getProperties();

            // Iterate over all registered config properties...
            for (ConfigProperty p : ImmutableSet.copyOf(map.values())) {
                String name = p.name();
                String globalValue = store.getProperty(componentName, name);
                String localValue = localProperties != null ? (String) localProperties.get(name) : null;

                log.debug("Processing {} property {}; global {}; local {}",
                          componentName, name, globalValue, localValue);
                try {
                    // 1) If the global value is the same as default, or
                    // 2) if it is not set explicitly, but the local value is
                    // not the same as the default, reset local value to default.
                    if (Objects.equals(globalValue, p.defaultValue()) ||
                            (globalValue == null &&
                                    !Objects.equals(localValue, p.defaultValue()))) {
                        log.debug("Resetting {} property {}; value same as default",
                                  componentName, name);
                        reset(componentName, name);

                    } else if (!Objects.equals(globalValue, localValue)) {
                        // If the local value is different from global value
                        // validate the global value and apply it locally.
                        String newValue;
                        if (globalValue != null) {
                            newValue = globalValue;
                        } else {
                            newValue = localValue;
                        }
                        log.debug("Setting {} property {} to {}",
                                  componentName, name, newValue);
                        checkValidity(componentName, name, newValue);
                        set(componentName, name, newValue);

                    } else {
                        // Otherwise, simply update the registered property
                        // with the global value.
                        log.debug("Syncing {} property {} to {}",
                                  componentName, name, globalValue);
                        map.put(name, ConfigProperty.setProperty(p, globalValue));
                    }
                } catch (IllegalArgumentException e) {
                    log.warn("Value {} for property {} is not a valid {}; using default",
                             globalValue, name, p.type());
                    reset(componentName, name);
                }
            }
        } catch (IOException e) {
            log.error("Unable to get configuration for " + componentName, e);
        }
    }

    private void triggerUpdate(String componentName) {
        try {
            Configuration cfg = cfgAdmin.getConfiguration(componentName, null);
            Map<String, ConfigProperty> map = properties.get(componentName);
            if (map == null) {
                //  Prevent NPE if the component isn't there
                log.warn("Component not found for " + componentName);
                return;
            }
            Dictionary<String, Object> props = new Hashtable<>();
            map.values().stream().filter(p -> p.value() != null)
                    .forEach(p -> props.put(p.name(), p.value()));
            cfg.update(props);
        } catch (IOException e) {
            log.warn("Unable to update configuration for " + componentName, e);
        }
    }
}


text:
layout: post
typo_id: 56
title: "Ruby & Rails: Resources"
---

I should really spend more time learning Ruby and Rails. I am really hooked by the claims that people are making. Here are two newly discovered resources:

slash7.com

rails.homelinux.org

It does seem that I am easily swayed toward some new technology depending on how passionate its users are talking/ blogging about it.


text:
SYNONYM

#### According to
The Catalogue of Life, 3rd January 2011

#### Published in
Bot. Mag. 77: t. 4594. 1851

#### Original name
null

### Remarks
null


text:
package com.jcalc.pkg;

import org.junit.Test;

import javafx.application.Platform;
import javafx.embed.swing.JFXPanel;
import javafx.stage.Stage;

public class MainTest {

	@Test
	public void javaFXTest1() throws InterruptedException {
		Thread thread = new Thread(new Runnable() {

			@Override
			public void run() {
				new JFXPanel();
				Platform.runLater(new Runnable() {

					@Override
					public void run() {
						new Main().start(new Stage());
					}
				});
			}
		});
		thread.start();
		Thread.sleep(10000);
	}

}


text:
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
	<modelVersion>4.0.0</modelVersion>

	<groupId>io.springside</groupId>
	<artifactId>springtime-project</artifactId>
	<version>master-SNAPSHOT</version>
	<packaging>pom</packaging>
	<name>springtime-project</name>

	<modules>
		<module>springtime</module>
		<module>examples/hello-service</module>
	</modules>
</project>


text:
name: Feature request
about: Suggest an idea for this project
title: "[REQUEST]"
labels: enhancement
---

## What problem are you trying to solve?
<!-- A concise description of what the problem is that this project should help solve -->

## Describe the solution you'd like
<!-- What should the API and behavior look like to address that problem? -->

## Describe alternatives you've considered
<!-- Are there any alternative solutions or features you've considered that are inadequate for solving this problem? -->

## Additional context
<!-- Any other context, examples, or adoptions paths to share? -->


text:
from __future__ import unicode_literals

from django.db import models, migrations

class Migration(migrations.Migration):

    dependencies = [
        ('gym', '0005_auto_20150401_1535'),
    ]

    operations = [
        migrations.AlterField(
            model_name='fitnesslisting',
            name='address',
            field=models.CharField(max_length=500),
            preserve_default=True,
        ),
        migrations.AlterField(
            model_name='fitnesslisting',
            name='description',
            field=models.TextField(),
            preserve_default=True,
        ),
    ]