text:
from __future__ import unicode_literals

from pgmagick import Blob, Geometry, Image, ImageType
from pgmagick import InterlaceType, OrientationType
from sorl.thumbnail.engines.base import EngineBase

try:
    from pgmagick._pgmagick import get_blob_data
except ImportError:
    from base64 import b64decode

    def get_blob_data(blob):
        return b64decode(blob.base64())

class Engine(EngineBase):
    def get_image(self, source):
        blob = Blob()
        blob.update(source.read())
        return Image(blob)

    def get_image_size(self, image):
        geometry = image.size()
        return geometry.width(), geometry.height()

    def is_valid_image(self, raw_data):
        blob = Blob()
        blob.update(raw_data)
        im = Image(blob)
        return im.isValid()

    def _cropbox(self, image, x, y, x2, y2):
        geometry = Geometry(x2 - x, y2 - y, x, y)
        image.crop(geometry)
        return image

    def _orientation(self, image):
        orientation = image.orientation()
        if orientation == OrientationType.TopRightOrientation:
            image.flop()
        elif orientation == OrientationType.BottomRightOrientation:
            image.rotate(180)
        elif orientation == OrientationType.BottomLeftOrientation:
            image.flip()
        elif orientation == OrientationType.LeftTopOrientation:
            image.rotate(90)
            image.flop()
        elif orientation == OrientationType.RightTopOrientation:
            image.rotate(90)
        elif orientation == OrientationType.RightBottomOrientation:
            image.rotate(-90)
            image.flop()
        elif orientation == OrientationType.LeftBottomOrientation:
            image.rotate(-90)
        image.orientation(OrientationType.TopLeftOrientation)

        return image

    def _colorspace(self, image, colorspace):
        if colorspace == 'RGB':
            image.type(ImageType.TrueColorMatteType)
        elif colorspace == 'GRAY':
            image.type(ImageType.GrayscaleMatteType)
        else:
            return image
        return image

    def _scale(self, image, width, height):
        geometry = Geometry(width, height)
        image.scale(geometry)
        return image

    def _crop(self, image, width, height, x_offset, y_offset):
        geometry = Geometry(width, height, x_offset, y_offset)
        image.crop(geometry)
        return image

    def _get_raw_data(self, image, format_, quality, image_info=None, progressive=False):
        image.magick(format_.encode('utf8'))
        image.quality(quality)
        if format_ == 'JPEG' and progressive:
            image.interlaceType(InterlaceType.LineInterlace)
        blob = Blob()
        image.write(blob)
        return get_blob_data(blob)


text:
/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package org.plasmarobotics.jim.sensors;

import edu.wpi.first.wpilibj.Encoder;

/**
 * A modified Encoder class that utilizes cool methods
 * @author Jim
 */
public class PlasmaEncoder extends Encoder{

    /**
     * Creates an instance of PlasmaEncoder
     * @param aChannel aChannel on the side car
     * @param bChannel bChannel on the side car
     * @param reverseDirection whether or not the encoders were put on backwards
     * @param encodingType type of encoding
     * @param distancePerPulse constant to determine distance traveled
     */
    public PlasmaEncoder(int aChannel, int bChannel, boolean reverseDirection, EncodingType encodingType, double distancePerPulse) {
        super(aChannel, bChannel, reverseDirection, encodingType);
        this.setDistancePerPulse(.04112);
        this.start();
    }

}

redpajama_set_name: RedPajamaGithub


text:
import { Subscriber } from '../Subscriber';
import { Subscription } from '../Subscription';
import { Observable } from '../Observable';
import { Operator } from '../Operator';
import { Subject } from '../Subject';
import { OperatorFunction } from '../types';

/* tslint:disable:max-line-length */
export function groupBy<T, K>(keySelector: (value: T) => K): OperatorFunction<T, GroupedObservable<K, T>>;
export function groupBy<T, K>(keySelector: (value: T) => K, elementSelector: void, durationSelector: (grouped: GroupedObservable<K, T>) => Observable<any>): OperatorFunction<T, GroupedObservable<K, T>>;
export function groupBy<T, K, R>(keySelector: (value: T) => K, elementSelector?: (value: T) => R, durationSelector?: (grouped: GroupedObservable<K, R>) => Observable<any>): OperatorFunction<T, GroupedObservable<K, R>>;
export function groupBy<T, K, R>(keySelector: (value: T) => K, elementSelector?: (value: T) => R, durationSelector?: (grouped: GroupedObservable<K, R>) => Observable<any>, subjectSelector?: () => Subject<R>): OperatorFunction<T, GroupedObservable<K, R>>;
/* tslint:enable:max-line-length */

/**
 * Groups the items emitted by an Observable according to a specified criterion,
 * and emits these grouped items as `GroupedObservables`, one
 * {@link GroupedObservable} per group.
 *
 * ![](groupBy.png)
 *
 * When the Observable emits an item, a key is computed for this item with the keySelector function.
 *
 * If a {@link GroupedObservable} for this key exists, this {@link GroupedObservable} emits. Otherwise, a new
 * {@link GroupedObservable} for this key is created and emits.
 *
 * A {@link GroupedObservable} represents values belonging to the same group represented by a common key. The common
 * key is available as the key field of a {@link GroupedObservable} instance.
 *
 * The elements emitted by {@link GroupedObservable}s are by default the items emitted by the Observable, or elements
 * returned by the elementSelector function.
 *
 * ## Examples
 *
 * ### Group objects by id and return as array
 *
 * ```ts
 * import { of } from 'rxjs';
 * import { mergeMap, groupBy, reduce } from 'rxjs/operators';
 *
 * of(
 *   {id: 1, name: 'JavaScript'},
 *   {id: 2, name: 'Parcel'},
 *   {id: 2, name: 'webpack'},
 *   {id: 1, name: 'TypeScript'},
 *   {id: 3, name: 'TSLint'}
 * ).pipe(
 *   groupBy(p => p.id),
 *   mergeMap((group$) => group$.pipe(reduce((acc, cur) => [...acc, cur], []))),
 * )
 * .subscribe(p => console.log(p));
 *
 * // displays:
 * // [ { id: 1, name: 'JavaScript'},
 * //   { id: 1, name: 'TypeScript'} ]
 * //
 * // [ { id: 2, name: 'Parcel'},
 * //   { id: 2, name: 'webpack'} ]
 * //
 * // [ { id: 3, name: 'TSLint'} ]
 * ```
 *
 * ### Pivot data on the id field
 *
 * ```ts
 * import { of } from 'rxjs';
 * import { groupBy, map, mergeMap, reduce } from 'rxjs/operators';
 *
 * of(
 *   { id: 1, name: 'JavaScript' },
 *   { id: 2, name: 'Parcel' },
 *   { id: 2, name: 'webpack' },
 *   { id: 1, name: 'TypeScript' },
 *   { id: 3, name: 'TSLint' }
 * )
 *   .pipe(
 *     groupBy(p => p.id, p => p.name),
 *     mergeMap(group$ =>
 *       group$.pipe(reduce((acc, cur) => [...acc, cur], [`${group$.key}`]))
 *     ),
 *     map(arr => ({ id: parseInt(arr[0], 10), values: arr.slice(1) }))
 *  )
 *  .subscribe(p => console.log(p));
 *
 * // displays:
 * // { id: 1, values: [ 'JavaScript', 'TypeScript' ] }
 * // { id: 2, values: [ 'Parcel', 'webpack' ] }
 * // { id: 3, values: [ 'TSLint' ] }
 * ```
 *
 * @param {function(value: T): K} keySelector A function that extracts the key
 * for each item.
 * @param {function(value: T): R} [elementSelector] A function that extracts the
 * return element for each item.
 * @param {function(grouped: GroupedObservable<K,R>): Observable<any>} [durationSelector]
 * A function that returns an Observable to determine how long each group should
 * exist.
 * @return {Observable<GroupedObservable<K,R>>} An Observable that emits
 * GroupedObservables, each of which corresponds to a unique key value and each
 * of which emits those items from the source Observable that share that key
 * value.
 * @method groupBy
 * @owner Observable
 */
export function groupBy<T, K, R>(keySelector: (value: T) => K,
                                 elementSelector?: ((value: T) => R) | void,
                                 durationSelector?: (grouped: GroupedObservable<K, R>) => Observable<any>,
                                 subjectSelector?: () => Subject<R>): OperatorFunction<T, GroupedObservable<K, R>> {
  return (source: Observable<T>) =>
    source.lift(new GroupByOperator(keySelector, elementSelector, durationSelector, subjectSelector));
}

export interface RefCountSubscription {
  count: number;
  unsubscribe: () => void;
  closed: boolean;
  attemptedToUnsubscribe: boolean;
}

class GroupByOperator<T, K, R> implements Operator<T, GroupedObservable<K, R>> {
  constructor(private keySelector: (value: T) => K,
              private elementSelector?: ((value: T) => R) | void,
              private durationSelector?: (grouped: GroupedObservable<K, R>) => Observable<any>,
              private subjectSelector?: () => Subject<R>) {
  }

  call(subscriber: Subscriber<GroupedObservable<K, R>>, source: any): any {
    return source.subscribe(new GroupBySubscriber(
      subscriber, this.keySelector, this.elementSelector, this.durationSelector, this.subjectSelector
    ));
  }
}

/**
 * We need this JSDoc comment for affecting ESDoc.
 * @ignore
 * @extends {Ignored}
 */
class GroupBySubscriber<T, K, R> extends Subscriber<T> implements RefCountSubscription {
  private groups: Map<K, Subject<T | R>> | null = null;
  public attemptedToUnsubscribe: boolean = false;
  public count: number = 0;

  constructor(destination: Subscriber<GroupedObservable<K, R>>,
              private keySelector: (value: T) => K,
              private elementSelector?: ((value: T) => R) | void,
              private durationSelector?: (grouped: GroupedObservable<K, R>) => Observable<any>,
              private subjectSelector?: () => Subject<R>) {
    super(destination);
  }

  protected _next(value: T): void {
    let key: K;
    try {
      key = this.keySelector(value);
    } catch (err) {
      this.error(err);
      return;
    }

    this._group(value, key);
  }

  private _group(value: T, key: K) {
    let groups = this.groups;

    if (!groups) {
      groups = this.groups = new Map<K, Subject<T | R>>();
    }

    let group = groups.get(key);

    let element: R;
    if (this.elementSelector) {
      try {
        element = this.elementSelector(value);
      } catch (err) {
        this.error(err);
      }
    } else {
      element = value as any;
    }

    if (!group) {
      group = (this.subjectSelector ? this.subjectSelector() : new Subject<R>()) as Subject<T | R>;
      groups.set(key, group);
      const groupedObservable = new GroupedObservable(key, group, this);
      this.destination.next(groupedObservable);
      if (this.durationSelector) {
        let duration: any;
        try {
          duration = this.durationSelector(new GroupedObservable<K, R>(key, <Subject<R>>group));
        } catch (err) {
          this.error(err);
          return;
        }
        this.add(duration.subscribe(new GroupDurationSubscriber(key, group, this)));
      }
    }

    if (!group.closed) {
      group.next(element!);
    }
  }

  protected _error(err: any): void {
    const groups = this.groups;
    if (groups) {
      groups.forEach((group, key) => {
        group.error(err);
      });

      groups.clear();
    }
    this.destination.error(err);
  }

  protected _complete(): void {
    const groups = this.groups;
    if (groups) {
      groups.forEach((group, key) => {
        group.complete();
      });

      groups.clear();
    }
    this.destination.complete();
  }

  removeGroup(key: K): void {
    this.groups!.delete(key);
  }

  unsubscribe() {
    if (!this.closed) {
      this.attemptedToUnsubscribe = true;
      if (this.count === 0) {
        super.unsubscribe();
      }
    }
  }
}

/**
 * We need this JSDoc comment for affecting ESDoc.
 * @ignore
 * @extends {Ignored}
 */
class GroupDurationSubscriber<K, T> extends Subscriber<T> {
  constructor(private key: K,
              private group: Subject<T>,
              private parent: GroupBySubscriber<any, K, T | any>) {
    super(group);
  }

  protected _next(value: T): void {
    this.complete();
  }

  /** @deprecated This is an internal implementation detail, do not use. */
  _unsubscribe() {
    const { parent, key } = this;
    this.key = this.parent = null!;
    if (parent) {
      parent.removeGroup(key);
    }
  }
}

/**
 * An Observable representing values belonging to the same group represented by
 * a common key. The values emitted by a GroupedObservable come from the source
 * Observable. The common key is available as the field `key` on a
 * GroupedObservable instance.
 *
 * @class GroupedObservable<K, T>
 */
export class GroupedObservable<K, T> extends Observable<T> {
  /** @deprecated Do not construct this type. Internal use only */
  constructor(public key: K,
              private groupSubject: Subject<T>,
              private refCountSubscription?: RefCountSubscription) {
    super();
  }

  /** @deprecated This is an internal implementation detail, do not use. */
  _subscribe(subscriber: Subscriber<T>) {
    const subscription = new Subscription();
    const { refCountSubscription, groupSubject } = this;
    if (refCountSubscription && !refCountSubscription.closed) {
      subscription.add(new InnerRefCountSubscription(refCountSubscription));
    }
    subscription.add(groupSubject.subscribe(subscriber));
    return subscription;
  }
}

/**
 * We need this JSDoc comment for affecting ESDoc.
 * @ignore
 * @extends {Ignored}
 */
class InnerRefCountSubscription extends Subscription {
  constructor(private parent: RefCountSubscription) {
    super();
    parent.count++;
  }

  unsubscribe() {
    const parent = this.parent;
    if (!parent.closed && !this.closed) {
      super.unsubscribe();
      parent.count -= 1;
      if (parent.count === 0 && parent.attemptedToUnsubscribe) {
        parent.unsubscribe();
      }
    }
  }
}


text:
module.exports =
/******/ (function(modules) { // webpackBootstrap
/******/ 	// The module cache
/******/ 	var installedModules = {};

/******/ 	// The require function
/******/ 	function __webpack_require__(moduleId) {

/******/ 		// Check if module is in cache
/******/ 		if(installedModules[moduleId])
/******/ 			return installedModules[moduleId].exports;

/******/ 		// Create a new module (and put it into the cache)
/******/ 		var module = installedModules[moduleId] = {
/******/ 			exports: {},
/******/ 			id: moduleId,
/******/ 			loaded: false
/******/ 		};

/******/ 		// Execute the module function
/******/ 		modules[moduleId].call(module.exports, module, module.exports, __webpack_require__);

/******/ 		// Flag the module as loaded
/******/ 		module.loaded = true;

/******/ 		// Return the exports of the module
/******/ 		return module.exports;
/******/ 	}

/******/ 	// expose the modules object (__webpack_modules__)
/******/ 	__webpack_require__.m = modules;

/******/ 	// expose the module cache
/******/ 	__webpack_require__.c = installedModules;

/******/ 	// __webpack_public_path__
/******/ 	__webpack_require__.p = "";

/******/ 	// Load entry module and return exports
/******/ 	return __webpack_require__(0);
/******/ })
/************************************************************************/
/******/ ({

/***/ 0:
/***/ (function(module, exports, __webpack_require__) {

	module.exports = __webpack_require__(673);

/***/ }),

/***/ 3:
/***/ (function(module, exports) {

	module.exports = function() { throw new Error("define cannot be used indirect"); };

/***/ }),

/***/ 582:
/***/ (function(module, exports) {

	module.exports = require("./kendo.data");

/***/ }),

/***/ 599:
/***/ (function(module, exports) {

	module.exports = require("./kendo.userevents");

/***/ }),

/***/ 622:
/***/ (function(module, exports) {

	module.exports = require("./kendo.dataviz.themes");

/***/ }),

/***/ 673:
/***/ (function(module, exports, __webpack_require__) {

	var __WEBPACK_AMD_DEFINE_FACTORY__, __WEBPACK_AMD_DEFINE_ARRAY__, __WEBPACK_AMD_DEFINE_RESULT__;(function(f, define){
	    !(__WEBPACK_AMD_DEFINE_ARRAY__ = [ __webpack_require__(582), __webpack_require__(599), __webpack_require__(622) ], __WEBPACK_AMD_DEFINE_FACTORY__ = (f), __WEBPACK_AMD_DEFINE_RESULT__ = (typeof __WEBPACK_AMD_DEFINE_FACTORY__ === 'function' ? (__WEBPACK_AMD_DEFINE_FACTORY__.apply(exports, __WEBPACK_AMD_DEFINE_ARRAY__)) : __WEBPACK_AMD_DEFINE_FACTORY__), __WEBPACK_AMD_DEFINE_RESULT__ !== undefined && (module.exports = __WEBPACK_AMD_DEFINE_RESULT__));
	})(function(){

	var __meta__ = { // jshint ignore:line
	    id: "dataviz.treeMap",
	    name: "TreeMap",
	    category: "dataviz",
	    description: "The Kendo DataViz TreeMap",
	    depends: [ "data", "userevents", "dataviz.themes" ]
	};

	(function($, undefined) {
	    var math = Math,

	        proxy = $.proxy,
	        isArray = $.isArray,

	        kendo = window.kendo,
	        outerHeight = kendo._outerHeight,
	        outerWidth = kendo._outerWidth,
	        Class = kendo.Class,
	        Widget = kendo.ui.Widget,
	        template = kendo.template,
	        deepExtend = kendo.deepExtend,
	        HierarchicalDataSource = kendo.data.HierarchicalDataSource,
	        getter = kendo.getter,

	        dataviz = kendo.dataviz;

	    var NS = ".kendoTreeMap",
	        CHANGE = "change",
	        DATA_BOUND = "dataBound",
	        ITEM_CREATED = "itemCreated",
	        MAX_VALUE = Number.MAX_VALUE,
	        MOUSEOVER_NS = "mouseover" + NS,
	        MOUSELEAVE_NS = "mouseleave" + NS,
	        UNDEFINED = "undefined";

	    var TreeMap = Widget.extend({
	        init: function(element, options) {
	            kendo.destroy(element);
	            $(element).empty();

	            Widget.fn.init.call(this, element, options);
	            this.wrapper = this.element;

	            this._initTheme(this.options);

	            this.element.addClass("k-widget k-treemap");

	            this._setLayout();

	            this._originalOptions = deepExtend({}, this.options);

	            this._initDataSource();

	            this._attachEvents();

	            kendo.notify(this, dataviz.ui);
	        },

	        options: {
	            name: "TreeMap",
	            theme: "default",
	            autoBind: true,
	            textField: "text",
	            valueField: "value",
	            colorField: "color"
	        },

	        events: [DATA_BOUND, ITEM_CREATED],

	        _initTheme: function(options) {
	            var that = this,
	                themes = dataviz.ui.themes || {},
	                themeName = ((options || {}).theme || "").toLowerCase(),
	                themeOptions = (themes[themeName] || {}).treeMap;

	            that.options = deepExtend({}, themeOptions, options);
	        },

	        _attachEvents: function() {
	            this.element
	                .on(MOUSEOVER_NS, proxy(this._mouseover, this))
	                .on(MOUSELEAVE_NS, proxy(this._mouseleave, this));

	            this._resizeHandler = proxy(this.resize, this, false);
	            kendo.onResize(this._resizeHandler);
	        },

	        _setLayout: function() {
	            if (this.options.type === "horizontal") {
	                this._layout = new SliceAndDice(false);
	                this._view = new SliceAndDiceView(this, this.options);
	            } else if (this.options.type === "vertical") {
	                this._layout = new SliceAndDice(true);
	                this._view = new SliceAndDiceView(this, this.options);
	            } else {
	                this._layout = new Squarified();
	                this._view = new SquarifiedView(this, this.options);
	            }
	        },

	        _initDataSource: function() {
	            var that = this,
	                options = that.options,
	                dataSource = options.dataSource;

	            that._dataChangeHandler = proxy(that._onDataChange, that);

	            that.dataSource = HierarchicalDataSource
	                .create(dataSource)
	                .bind(CHANGE, that._dataChangeHandler);

	            if (dataSource) {
	                if (that.options.autoBind) {
	                    that.dataSource.fetch();
	                }
	            }
	        },

	        setDataSource: function(dataSource) {
	            var that = this;
	            that.dataSource.unbind(CHANGE, that._dataChangeHandler);
	            that.dataSource = dataSource
	                    .bind(CHANGE, that._dataChangeHandler);

	            if (dataSource) {
	                if (that.options.autoBind) {
	                    that.dataSource.fetch();
	                }
	            }
	        },

	        _onDataChange: function(e) {
	            var node = e.node;
	            var items = e.items;
	            var options = this.options;
	            var item, i;

	            if (!node) {
	                this._cleanItems();
	                this.element.empty();
	                item = this._wrapItem(items[0]);
	                this._layout.createRoot(
	                    item,
	                    outerWidth(this.element),
	                    outerHeight(this.element),
	                    this.options.type === "vertical"
	                );
	                this._view.createRoot(item);
	                // Reference of the root
	                this._root = item;
	                this._colorIdx = 0;
	            } else {
	                if (items.length) {
	                    var root = this._getByUid(node.uid);
	                    root.children = [];
	                    items = new kendo.data.Query(items)._sortForGrouping(options.valueField, "desc");

	                    for (i = 0; i < items.length; i++) {
	                        item = items[i];
	                        root.children.push(this._wrapItem(item));
	                    }

	                    var htmlSize = this._view.htmlSize(root);
	                    this._layout.compute(root.children, root.coord, htmlSize);

	                    this._setColors(root.children);
	                    this._view.render(root);
	                }
	            }

	            for (i = 0; i < items.length; i++) {
	                items[i].load();
	            }

	            if (node) {
	                this.trigger(DATA_BOUND, {
	                    node: node
	                });
	            }
	        },

	        _cleanItems: function() {
	            var that = this;
	            that.angular("cleanup", function() {
	               return { elements: that.element.find(".k-leaf div,.k-treemap-title,.k-treemap-title-vertical") };
	            });
	        },

	        _setColors: function(items) {
	            var colors = this.options.colors;
	            var colorIdx = this._colorIdx;
	            var color = colors[colorIdx % colors.length];
	            var colorRange, item;
	            if (isArray(color)) {
	                colorRange = colorsByLength(color[0], color[1], items.length);
	            }

	            var leafNodes = false;
	            for (var i = 0; i < items.length; i++) {
	                item = items[i];

	                if (!defined(item.color)) {
	                    if (colorRange) {
	                        item.color = colorRange[i];
	                    } else {
	                        item.color = color;
	                    }
	                }
	                if (!item.dataItem.hasChildren) {
	                    leafNodes = true;
	                }
	            }

	            if (leafNodes) {
	                this._colorIdx++;
	            }
	        },

	        _contentSize: function(root) {
	            this.view.renderHeight(root);
	        },

	        _wrapItem: function(item) {
	            var wrap = {};

	            if (defined(this.options.valueField)) {
	                wrap.value = getField(this.options.valueField, item);
	            }

	            if (defined(this.options.colorField)) {
	                wrap.color = getField(this.options.colorField, item);
	            }

	            if (defined(this.options.textField)) {
	                wrap.text = getField(this.options.textField, item);
	            }

	            wrap.level = item.level();

	            wrap.dataItem = item;

	            return wrap;
	        },

	        _getByUid: function(uid) {
	            var items = [this._root];
	            var item;

	            while (items.length) {
	                item = items.pop();
	                if (item.dataItem.uid === uid) {
	                    return item;
	                }

	                if (item.children) {
	                    items = items.concat(item.children);
	                }
	            }
	        },

	        dataItem: function(node) {
	            var uid = $(node).attr(kendo.attr("uid")),
	                dataSource = this.dataSource;

	            return dataSource && dataSource.getByUid(uid);
	        },

	        findByUid: function(uid) {
	            return this.element.find(".k-treemap-tile[" + kendo.attr("uid") + "='" + uid + "']");
	        },

	        _mouseover: function(e) {
	            var target = $(e.target);
	            if (target.hasClass("k-leaf")) {
	                this._removeActiveState();
	                target
	                    .removeClass("k-state-hover")
	                    .addClass("k-state-hover");
	            }
	        },

	        _removeActiveState: function() {
	            this.element
	                .find(".k-state-hover")
	                .removeClass("k-state-hover");
	        },

	        _mouseleave: function() {
	            this._removeActiveState();
	        },

	        destroy: function() {
	            Widget.fn.destroy.call(this);
	            this.element.off(NS);

	            if (this.dataSource) {
	                this.dataSource.unbind(CHANGE, this._dataChangeHandler);
	            }

	            this._root = null;
	            kendo.unbindResize(this._resizeHandler);

	            kendo.destroy(this.element);
	        },

	        items: function() {
	            return $();
	        },

	        getSize: function() {
	            return kendo.dimensions(this.element);
	        },

	        _resize: function() {
	            var root = this._root;
	            if (root) {
	                var element = this.element;
	                var rootElement = element.children();
	                root.coord.width = outerWidth(element);
	                root.coord.height = outerHeight(element);

	                rootElement.css({
	                    width: root.coord.width,
	                    height: root.coord.height
	                });

	                this._resizeItems(root, rootElement);
	            }
	        },

	        _resizeItems: function(root, element) {
	            if (root.children && root.children.length) {
	                var elements = element.children(".k-treemap-wrap").children();
	                var child, childElement;

	                this._layout.compute(root.children, root.coord, {text: this._view.titleSize(root, element)});
	                for (var idx = 0; idx < root.children.length; idx++) {
	                    child = root.children[idx];
	                    childElement = elements.filter("[" + kendo.attr("uid") + "='" + child.dataItem.uid + "']");
	                    this._view.setItemSize(child, childElement);
	                    this._resizeItems(child, childElement);
	                }
	            }
	        },

	        setOptions: function(options) {
	            var dataSource = options.dataSource;

	            options.dataSource = undefined;
	            this._originalOptions = deepExtend(this._originalOptions, options);
	            this.options = deepExtend({}, this._originalOptions);
	            this._setLayout();
	            this._initTheme(this.options);

	            Widget.fn._setEvents.call(this, options);

	            if (dataSource) {
	                this.setDataSource(HierarchicalDataSource.create(dataSource));
	            }

	            if (this.options.autoBind) {
	                this.dataSource.fetch();
	            }
	        }
	    });

	    var Squarified = Class.extend({
	        createRoot: function(root, width, height) {
	            root.coord = {
	                width: width,
	                height: height,
	                top: 0,
	                left: 0
	            };
	        },

	        leaf: function(tree) {
	            return !tree.children;
	        },

	        layoutChildren: function(items, coord) {
	            var parentArea = coord.width * coord.height;
	            var totalArea = 0,
	                itemsArea = [],
	                i;

	            for (i = 0; i < items.length; i++) {
	                itemsArea[i] = parseFloat(items[i].value);
	                totalArea += itemsArea[i];
	            }

	            for (i = 0; i < itemsArea.length; i++) {
	                items[i].area = parentArea * itemsArea[i] / totalArea;
	            }

	            var minimumSideValue = this.layoutHorizontal() ? coord.height : coord.width;

	            var firstElement = [items[0]];
	            var tail = items.slice(1);
	            this.squarify(tail, firstElement, minimumSideValue, coord);
	        },

	        squarify: function(tail, initElement, width, coord) {
	            this.computeDim(tail, initElement, width, coord);
	        },

	        computeDim: function(tail, initElement, width, coord) {
	            if (tail.length + initElement.length == 1) {
	                var element = tail.length == 1 ? tail : initElement;
	                this.layoutLast(element, width, coord);
	                return;
	            }

	            if (tail.length >= 2 && initElement.length === 0) {
	                initElement = [tail[0]];
	                tail = tail.slice(1);
	            }

	            if (tail.length === 0) {
	                if (initElement.length > 0) {
	                    this.layoutRow(initElement, width, coord);
	                }
	                return;
	            }

	            var firstElement = tail[0];

	            if (this.worstAspectRatio(initElement, width) >= this.worstAspectRatio([firstElement].concat(initElement), width)) {
	                this.computeDim(tail.slice(1), initElement.concat([firstElement]), width, coord);
	            } else {
	                var newCoords = this.layoutRow(initElement, width, coord);
	                this.computeDim(tail, [], newCoords.dim, newCoords);
	            }
	        },

	        layoutLast: function(items, w, coord) {
	            items[0].coord = coord;
	        },

	        layoutRow: function(items, width, coord) {
	            if (this.layoutHorizontal()) {
	                return this.layoutV(items, width, coord);
	            } else {
	                return this.layoutH(items, width, coord);
	            }
	        },

	        orientation: "h",

	        layoutVertical: function() {
	            return this.orientation === "v";
	        },

	        layoutHorizontal: function() {
	            return this.orientation === "h";
	        },

	        layoutChange: function() {
	            this.orientation = this.layoutVertical() ? "h" : "v";
	        },

	        worstAspectRatio: function(items, width) {
	            if (!items || items.length === 0) {
	                return MAX_VALUE;
	            }

	            var areaSum = 0,
	                maxArea = 0,
	                minArea = MAX_VALUE;

	            for (var i = 0; i < items.length; i++) {
	                var area = items[i].area;
	                areaSum += area;
	                minArea = (minArea < area) ? minArea : area;
	                maxArea = (maxArea > area) ? maxArea : area;
	            }

	            return math.max(
	                (width * width * maxArea) / (areaSum * areaSum),
	                (areaSum * areaSum) / (width * width * minArea)
	            );
	        },

	        compute: function(children, rootCoord, htmlSize) {
	            if (!(rootCoord.width >= rootCoord.height && this.layoutHorizontal())) {
	                this.layoutChange();
	            }

	            if (children && children.length > 0) {
	                var newRootCoord = {
	                    width: rootCoord.width,
	                    height: rootCoord.height - htmlSize.text,
	                    top: 0,
	                    left: 0
	                };

	                this.layoutChildren(children, newRootCoord);
	            }
	        },

	        layoutV: function(items, width, coord) {
	            var totalArea = this._totalArea(items),
	                top =  0;

	            width = round(totalArea / width);

	            for (var i = 0; i < items.length; i++) {
	                var height = round(items[i].area / width);
	                items[i].coord = {
	                    height: height,
	                    width: width,
	                    top: coord.top + top,
	                    left: coord.left
	                };

	                top += height;
	            }

	            var ans = {
	                height: coord.height,
	                width: coord.width - width,
	                top: coord.top,
	                left: coord.left + width
	            };

	            ans.dim = math.min(ans.width, ans.height);

	            if (ans.dim != ans.height) {
	                this.layoutChange();
	            }

	            return ans;
	        },

	        layoutH: function(items, width, coord) {
	            var totalArea = this._totalArea(items);

	            var height = round(totalArea / width),
	                top = coord.top,
	                left = 0;

	            for (var i=0; i<items.length; i++) {
	                items[i].coord = {
	                    height: height,
	                    width: round(items[i].area / height),
	                    top: top,
	                    left: coord.left + left
	                };
	                left += items[i].coord.width;
	            }

	            var ans = {
	                height: coord.height - height,
	                width: coord.width,
	                top: coord.top + height,
	                left: coord.left
	            };

	            ans.dim = math.min(ans.width, ans.height);

	            if (ans.dim != ans.width) {
	                this.layoutChange();
	            }

	            return ans;
	        },

	        _totalArea: function(items) {
	            var total = 0;

	            for (var i = 0; i < items.length; i++) {
	                total += items[i].area;
	            }

	            return total;
	        }
	    });

	    var SquarifiedView = Class.extend({
	        init: function(treeMap, options) {
	            this.options = deepExtend({}, this.options, options);
	            this.treeMap = treeMap;
	            this.element = $(treeMap.element);

	            this.offset = 0;
	        },

	        titleSize: function(item, element) {
	            var text = element.children(".k-treemap-title");
	            return text.height();
	        },

	        htmlSize: function(root) {
	            var rootElement = this._getByUid(root.dataItem.uid);
	            var htmlSize = {
	                text: 0
	            };

	            if (root.children) {
	                this._clean(rootElement);

	                var text = this._getText(root);
	                if (text) {
	                    var title = this._createTitle(root);
	                    rootElement.append(title);

	                    this._compile(title, root.dataItem);

	                    htmlSize.text = title.height();
	                }

	                rootElement.append(this._createWrap());

	                this.offset = (outerWidth(rootElement) - rootElement.innerWidth()) / 2;
	            }

	            return htmlSize;
	        },

	        _compile: function(element, dataItem) {
	            this.treeMap.angular("compile", function(){
	                return {
	                    elements: element,
	                    data: [ { dataItem: dataItem } ]
	                };
	            });
	        },

	        _getByUid: function(uid) {
	            return this.element.find(".k-treemap-tile[" + kendo.attr("uid") + "='" + uid + "']");
	        },

	        render: function(root) {
	            var rootElement = this._getByUid(root.dataItem.uid);
	            var children = root.children;
	            if (children) {
	                var rootWrap = rootElement.find(".k-treemap-wrap");

	                for (var i = 0; i < children.length; i++) {
	                    var leaf = children[i];
	                    var htmlElement = this._createLeaf(leaf);
	                    rootWrap.append(htmlElement);

	                    this._compile(htmlElement.children(), leaf.dataItem);

	                    this.treeMap.trigger(ITEM_CREATED, {
	                        element: htmlElement
	                    });
	                }
	            }
	        },

	        createRoot: function(root) {
	            var htmlElement = this._createLeaf(root);
	            this.element.append(htmlElement);
	            this._compile(htmlElement.children(), root.dataItem);

	            this.treeMap.trigger(ITEM_CREATED, {
	                element: htmlElement
	            });
	        },

	        _clean: function(root) {
	            this.treeMap.angular("cleanup", function() {
	                return {
	                    elements: root.children(":not(.k-treemap-wrap)")
	                };
	            });

	            root.css("background-color", "");
	            root.removeClass("k-leaf");
	            root.removeClass("k-inverse");
	            root.empty();
	        },

	        _createLeaf: function(item) {
	            return this._createTile(item)
	                    .css("background-color", item.color)
	                    .addClass("k-leaf")
	                    .toggleClass(
	                        "k-inverse",
	                        this._tileColorBrightness(item) > 180
	                    )
	                    .append($("<div></div>")
	                    .html(this._getText(item)));
	        },

	        _createTile: function(item) {
	            var tile = $("<div class='k-treemap-tile'></div>");
	            this.setItemSize(item, tile);

	            if (defined(item.dataItem) && defined(item.dataItem.uid)) {
	                tile.attr(kendo.attr("uid"), item.dataItem.uid);
	            }

	            return tile;
	        },

	        _itemCoordinates: function(item) {
	            var coordinates = {
	                width: item.coord.width,
	                height: item.coord.height,
	                left: item.coord.left,
	                top: item.coord.top
	            };

	            if (coordinates.left && this.offset) {
	                coordinates.width += this.offset * 2;
	            } else {
	                coordinates.width += this.offset;
	            }

	            if (coordinates.top) {
	                coordinates.height += this.offset * 2;
	            } else {
	                coordinates.height += this.offset;
	            }

	            return coordinates;
	        },

	        setItemSize: function(item, element) {
	            var coordinates = this._itemCoordinates(item);
	            element.css({
	                width: coordinates.width,
	                height: coordinates.height,
	                left: coordinates.left,
	                top: coordinates.top
	            });
	        },

	        _getText: function(item) {
	            var text = item.text;

	            if (this.options.template) {
	                text = this._renderTemplate(item);
	            }

	            return text;
	        },

	        _renderTemplate: function(item) {
	            var titleTemplate = template(this.options.template);
	            return titleTemplate({
	                dataItem: item.dataItem,
	                text: item.text
	            });
	        },

	        _createTitle: function(item) {
	            return $("<div class='k-treemap-title'></div>")
	                    .append($("<div></div>").html(this._getText(item)));
	        },

	        _createWrap: function() {
	            return $("<div class='k-treemap-wrap'></div>");
	        },

	        _tileColorBrightness: function(item) {
	            return colorBrightness(item.color);
	        }
	    });

	    var SliceAndDice = Class.extend({
	        createRoot: function(root, width, height, vertical) {
	            root.coord = {
	                width: width,
	                height: height,
	                top: 0,
	                left: 0
	            };
	            root.vertical = vertical;
	        },

	        init: function(vertical) {
	            this.vertical = vertical;
	            this.quotient = vertical ? 1 : 0;
	        },

	        compute: function(children, rootCoord, htmlSize) {
	            if (children.length > 0) {
	                var width = rootCoord.width;
	                var height = rootCoord.height;

	                if (this.vertical) {
	                    height -= htmlSize.text;
	                } else {
	                    width -= htmlSize.text;
	                }

	                var newRootCoord = {
	                    width: width,
	                    height: height,
	                    top: 0,
	                    left: 0
	                };

	                this.layoutChildren(children, newRootCoord);
	            }
	        },

	        layoutChildren: function(items, coord) {
	            var parentArea = coord.width * coord.height;
	            var totalArea = 0;
	            var itemsArea = [];
	            var i;

	            for (i = 0; i < items.length; i++) {
	                var item = items[i];
	                itemsArea[i] = parseFloat(items[i].value);
	                totalArea += itemsArea[i];
	                item.vertical = this.vertical;
	            }

	            for (i = 0; i < itemsArea.length; i++) {
	                items[i].area = parentArea * itemsArea[i] / totalArea;
	            }

	            this.sliceAndDice(items, coord);
	        },

	        sliceAndDice: function(items, coord) {
	            var totalArea = this._totalArea(items);
	            if (items[0].level % 2 === this.quotient) {
	                this.layoutHorizontal(items, coord, totalArea);
	            } else {
	                this.layoutVertical(items, coord, totalArea);
	            }
	        },

	        layoutHorizontal: function(items, coord, totalArea) {
	            var left = 0;

	            for (var i = 0; i < items.length; i++) {
	                var item = items[i];
	                var width = item.area / (totalArea / coord.width);
	                item.coord = {
	                    height: coord.height,
	                    width: width,
	                    top: coord.top,
	                    left: coord.left + left
	                };

	                left += width;
	            }
	        },

	        layoutVertical: function(items, coord, totalArea) {
	            var top = 0;

	            for (var i = 0; i < items.length; i++) {
	                var item = items[i];
	                var height = item.area / (totalArea / coord.height);
	                item.coord = {
	                    height: height,
	                    width: coord.width,
	                    top: coord.top + top,
	                    left: coord.left
	                };

	                top += height;
	            }
	        },

	        _totalArea: function(items) {
	            var total = 0;

	            for (var i = 0; i < items.length; i++) {
	                total += items[i].area;
	            }

	            return total;
	        }
	    });

	    var SliceAndDiceView = SquarifiedView.extend({
	        htmlSize: function(root) {
	            var rootElement = this._getByUid(root.dataItem.uid);
	            var htmlSize = {
	                text: 0,
	                offset: 0
	            };

	            if (root.children) {
	                this._clean(rootElement);

	                var text = this._getText(root);
	                if (text) {
	                    var title = this._createTitle(root);
	                    rootElement.append(title);
	                    this._compile(title, root.dataItem);

	                    if (root.vertical) {
	                        htmlSize.text = title.height();
	                    } else {
	                        htmlSize.text = title.width();
	                    }
	                }

	                rootElement.append(this._createWrap());

	                this.offset = (outerWidth(rootElement) - rootElement.innerWidth()) / 2;
	            }

	            return htmlSize;
	        },

	        titleSize: function(item, element) {
	            var size;
	            if (item.vertical) {
	               size = element.children(".k-treemap-title").height();
	            } else {
	               size = element.children(".k-treemap-title-vertical").width();
	            }
	            return size;
	        },

	        _createTitle: function(item) {
	            var title;
	            if (item.vertical) {
	                title = $("<div class='k-treemap-title'></div>");
	            } else {
	                title = $("<div class='k-treemap-title-vertical'></div>");
	            }

	            return title.append($("<div></div>").html(this._getText(item)));
	        }
	    });

	    function getField(field, row) {
	        if (row === null) {
	            return row;
	        }

	        var get = getter(field, true);
	        return get(row);
	    }

	    function defined(value) {
	        return typeof value !== UNDEFINED;
	    }

	    function colorsByLength(min, max, length) {
	        var minRGBtoDecimal = rgbToDecimal(min);
	        var maxRGBtoDecimal = rgbToDecimal(max);
	        var isDarker = colorBrightness(min) - colorBrightness(max) < 0;
	        var colors = [];

	        colors.push(min);

	        for (var i = 0; i < length; i++) {
	            var rgbColor = {
	                r: colorByIndex(minRGBtoDecimal.r, maxRGBtoDecimal.r, i, length, isDarker),
	                g: colorByIndex(minRGBtoDecimal.g, maxRGBtoDecimal.g, i, length, isDarker),
	                b: colorByIndex(minRGBtoDecimal.b, maxRGBtoDecimal.b, i, length, isDarker)
	            };
	            colors.push(buildColorFromRGB(rgbColor));
	        }

	        colors.push(max);

	        return colors;
	    }

	    function colorByIndex(min, max, index, length, isDarker) {
	        var minColor = math.min(math.abs(min), math.abs(max));
	        var maxColor = math.max(math.abs(min), math.abs(max));
	        var step = (maxColor - minColor) / (length + 1);
	        var currentStep = step * (index + 1);
	        var color;

	        if (isDarker) {
	            color = minColor + currentStep;
	        } else {
	            color = maxColor - currentStep;
	        }

	        return color;
	    }

	    function buildColorFromRGB(color) {
	        return "#" + decimalToRgb(color.r) + decimalToRgb(color.g) + decimalToRgb(color.b);
	    }

	    function rgbToDecimal(color) {
	        color = color.replace("#", "");
	        var rgbColor = colorToRGB(color);

	        return {
	            r: rgbToHex(rgbColor.r),
	            g: rgbToHex(rgbColor.g),
	            b: rgbToHex(rgbColor.b)
	        };
	    }

	    function decimalToRgb(number) {
	        var result = math.round(number).toString(16).toUpperCase();

	        if (result.length === 1) {
	            result = "0" + result;
	        }

	        return result;
	    }

	    function colorToRGB(color) {
	        var colorLength = color.length;
	        var rgbColor = {};
	        if (colorLength === 3) {
	            rgbColor.r = color[0];
	            rgbColor.g = color[1];
	            rgbColor.b = color[2];
	        } else {
	            rgbColor.r = color.substring(0, 2);
	            rgbColor.g = color.substring(2, 4);
	            rgbColor.b = color.substring(4, 6);
	        }

	        return rgbColor;
	    }

	    function rgbToHex(rgb) {
	        return parseInt(rgb.toString(16), 16);
	    }

	    function colorBrightness(color) {
	        var brightness = 0;
	        if (color) {
	            color = rgbToDecimal(color);
	            brightness = math.sqrt(0.241 * color.r * color.r + 0.691 * color.g * color.g + 0.068 * color.b * color.b);
	        }

	        return brightness;
	    }

	    function round(value) {
	        var power = math.pow(10, 4);
	        return math.round(value * power) / power;
	    }

	    dataviz.ui.plugin(TreeMap);

	})(window.kendo.jQuery);

	return window.kendo;

	}, __webpack_require__(3));

/***/ })

/******/ });


text:
<ehcache xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:noNamespaceSchemaLocation="http://ehcache.org/ehcache.xsd" name="openAksessCache">

    <defaultCache
            maxElementsInMemory="100"
            eternal="false"
            timeToIdleSeconds="120"
            timeToLiveSeconds="120"
            overflowToDisk="true"
            memoryStoreEvictionPolicy="LRU"
            statistics="false"/>

    <cache name="AliasCache"
           maxElementsInMemory="1000"
           eternal="false"
           overflowToDisk="false"
           timeToIdleSeconds="300"
           timeToLiveSeconds="300"
           memoryStoreEvictionPolicy="LFU"
           statistics="true">
            <cacheDecoratorFactory properties="metric-registry-name=oa-metric-registry" class="com.codahale.metrics.ehcache.InstrumentedCacheDecoratorFactory" />
    </cache>

    <cache name="ContentCache"
           maxElementsInMemory="500"
           eternal="false"
           overflowToDisk="false"
           timeToIdleSeconds="300"
           timeToLiveSeconds="300"
           memoryStoreEvictionPolicy="LFU"
           statistics="true">
        <cacheDecoratorFactory properties="metric-registry-name=oa-metric-registry" class="com.codahale.metrics.ehcache.InstrumentedCacheDecoratorFactory" />
    </cache>

    <cache name="ContentListCache"
           maxElementsInMemory="50"
           eternal="false"
           overflowToDisk="false"
           timeToIdleSeconds="300"
           timeToLiveSeconds="300"
           memoryStoreEvictionPolicy="LFU"
           statistics="true">
        <cacheDecoratorFactory properties="metric-registry-name=oa-metric-registry" class="com.codahale.metrics.ehcache.InstrumentedCacheDecoratorFactory" />
    </cache>

    <cache name="SiteMapCache"
           maxElementsInMemory="50"
           eternal="false"
           overflowToDisk="false"
           timeToIdleSeconds="300"
           timeToLiveSeconds="300"
           memoryStoreEvictionPolicy="LFU"
           statistics="true">
        <cacheDecoratorFactory properties="metric-registry-name=oa-metric-registry" class="com.codahale.metrics.ehcache.InstrumentedCacheDecoratorFactory" />
    </cache>

    <cache name="XmlCache"
           maxElementsInMemory="10"
           eternal="false"
           overflowToDisk="true"
           timeToIdleSeconds="300"
           timeToLiveSeconds="300"
           memoryStoreEvictionPolicy="LFU"
           statistics="true">
        <cacheDecoratorFactory properties="metric-registry-name=oa-metric-registry" class="com.codahale.metrics.ehcache.InstrumentedCacheDecoratorFactory" />
    </cache>

    <cache name="FacetLabelCache"
           maxElementsInMemory="30"
           eternal="false"
           overflowToDisk="false"
           timeToIdleSeconds="600"
           timeToLiveSeconds="600"
           memoryStoreEvictionPolicy="LFU"
           statistics="true">
        <cacheDecoratorFactory properties="metric-registry-name=oa-metric-registry" class="com.codahale.metrics.ehcache.InstrumentedCacheDecoratorFactory" />
    </cache>

    <cache name="ContentUrlCache"
           maxElementsInMemory="100"
           eternal="false"
           overflowToDisk="false"
           timeToIdleSeconds="600"
           timeToLiveSeconds="600"
           memoryStoreEvictionPolicy="LFU"
           statistics="true">
        <cacheDecoratorFactory properties="metric-registry-name=oa-metric-registry" class="com.codahale.metrics.ehcache.InstrumentedCacheDecoratorFactory" />
    </cache>

    <cache name="ContentIdentifierCache"
           maxElementsInMemory="100"
           eternal="false"
           overflowToDisk="false"
           timeToIdleSeconds="600"
           timeToLiveSeconds="600"
           memoryStoreEvictionPolicy="LFU"
           statistics="true">
        <cacheDecoratorFactory properties="metric-registry-name=oa-metric-registry" class="com.codahale.metrics.ehcache.InstrumentedCacheDecoratorFactory" />
    </cache>

    <cache name="UserCache"
           maxElementsInMemory="100"
           eternal="false"
           overflowToDisk="false"
           timeToIdleSeconds="600"
           timeToLiveSeconds="600"
           memoryStoreEvictionPolicy="LFU"
           statistics="true">
        <cacheDecoratorFactory properties="metric-registry-name=oa-metric-registry" class="com.codahale.metrics.ehcache.InstrumentedCacheDecoratorFactory" />
    </cache>

    <cache name="ImageCache"
           maxElementsInMemory="100"
           eternal="true"
           overflowToDisk="true"
           memoryStoreEvictionPolicy="LFU"
           maxElementsOnDisk="10000"
           diskPersistent="true"
           statistics="true" >
        <cacheDecoratorFactory properties="metric-registry-name=oa-metric-registry" class="com.codahale.metrics.ehcache.InstrumentedCacheDecoratorFactory" />
    </cache>

    <cache name="MultimediaCache"
           maxElementsInMemory="100"
           eternal="true"
           overflowToDisk="true"
           memoryStoreEvictionPolicy="LFU"
           maxElementsOnDisk="10000"
           diskPersistent="true"
           statistics="true" >
        <cacheDecoratorFactory properties="metric-registry-name=oa-metric-registry" class="com.codahale.metrics.ehcache.InstrumentedCacheDecoratorFactory" />
    </cache>

    <cache name="permissionCache"
           maxElementsInMemory="100"
           eternal="false"
           overflowToDisk="true"
           timeToIdleSeconds="600"
           timeToLiveSeconds="600"
           memoryStoreEvictionPolicy="LFU"
           diskPersistent="true"
           statistics="true" >
        <cacheDecoratorFactory properties="metric-registry-name=oa-metric-registry" class="com.codahale.metrics.ehcache.InstrumentedCacheDecoratorFactory" />
    </cache>

</ehcache>


text:
class WordCountMap: public HadoopPipes::Mapper {
public:
  WordCountMap(HadoopPipes::TaskContext& context){}
  void map(HadoopPipes::MapContext& context) {
    std::vector<std::string> words =
      HadoopUtils::splitString(context.getInputValue(), " ");
    for(unsigned int i=0; i < words.size(); ++i) {
      context.emit(words[i], "1");
    }
  }
};

class WordCountReduce: public HadoopPipes::Reducer {
public:
  WordCountReduce(HadoopPipes::TaskContext& context){}
  void reduce(HadoopPipes::ReduceContext& context) {
    int sum = 0;
    while (context.nextValue()) {
      sum += HadoopUtils::toInt(context.getInputValue());
    }
    context.emit(context.getInputKey(), HadoopUtils::toString(sum));
  }
};

int main(int argc, char *argv[]) {
  return HadoopPipes::runTask(HadoopPipes::TemplateFactory<WordCountMap,
                              WordCountReduce>());
}


text:
import * as React from 'react';
import { Route, RouteProps } from 'react-router';
import Main from '../components/Main';

export default (
    <Route path="/" component={Main} />
) as React.ComponentElement<RouteProps, React.Component<RouteProps, any>>;


text:
package com.alibaba.json.bvt.issue_2300;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.parser.Feature;
import junit.framework.TestCase;

public class Issue2387 extends TestCase
{
    public void test_for_issue() throws Exception {
        String jsonStr = "{id:\"ss\",ddd:\"sdfsd\",name:\"hh\"}";
        TestEntity news = JSON.parseObject(jsonStr, TestEntity.class, Feature.InitStringFieldAsEmpty);
        assertEquals("{\"ddd\":\"sdfsd\",\"id\":\"ss\",\"name\":\"hh\"}", JSON.toJSONString(news));
    }

    public static class TestEntity {
        private String id;
        private String ddd;
        private String name;

        public String getId()
        {
            return id;
        }

        public void setId(String id)
        {
            this.id = id;
        }

        public String getDdd()
        {
            return ddd;
        }

        public void setDdd(String ddd)
        {
            this.ddd = ddd;
        }

        public String getName()
        {
            return name;
        }

        public void setName(String name)
        {
            this.name = name;
        }
    }
}


text:
Navy.Class = function(var_args){
  var className;
  var protoObj;
  var superClass;

  switch (arguments.length) {
  case 2:
    superClass = Navy.Class._RootClass;
    className = arguments[0];
    protoObj = arguments[1];
    break;
  case 3:
    if (typeof arguments[1] === 'function') {
      superClass = arguments[1];
    } else {
      superClass = arguments[1].constructor;
    }
    className = arguments[0];
    protoObj = arguments[2];
    break;
  default:
    throw new Error('arguments of Navy.Class is 2 or 3.');
  }

  var _class = Navy.Class._create(className, superClass, protoObj);
  Navy.Class._setByReflection(className, _class);
  return _class;
};

Navy.Class.instance = function instance(var_args) {
  var _class = Navy.Class.apply(Navy, arguments);
  _class.__manualInitialize__ = true;
  var obj = new _class();
  var className = arguments[0];
  Navy.Class._setByReflection(className, obj);

  return obj;
};

/**
 * スーパークラスを指定せずにクラスを生成したときのクラス.
 */
Navy.Class._RootClass = function _RootClass() {};
Navy.Class._RootClass.prototype.initialize = function() {};

Navy.Class._getByReflection = function _getByReflection(propertyName) {
  var names = propertyName.split('.');

  var obj = window;
  for (var i = 0; i < names.length; i++) {
    obj = obj[names[i]];
  }

  return obj;
};

Navy.Class._setByReflection = function _setByReflection(propertyName, value) {
  var names = propertyName.split('.');

  var obj = window;
  for (var i = 0; i < names.length - 1; i++) {
    if (!(names[i] in obj)) {
      obj[names[i]] = {};
    }

    obj = obj[names[i]];
  }

  obj[names[i]] = value;
};

Navy.Class._create = function _create(className, superClass, protoObj){
  var name = className.replace(/[.]/g, '$');
  var Constructor = new Function("return function " +  name + " () { if (typeof this.initialize === 'function' && !this.constructor.__manualInitialize__) { this.initialize.apply(this, arguments); } }")();

  function EmptySuperClass(){}
  EmptySuperClass.prototype = superClass.prototype;
  var superObj = new EmptySuperClass();
  var superObjForWrap = new EmptySuperClass();

  Constructor.prototype = superObj;

  var key;
  var value;

  if (protoObj.$static) {
    for (key in protoObj.$static) {
      var value = protoObj.$static[key];
      if (typeof value === 'function') {
        if (Navy.Class._argumentNames(value)[0] === '$super') {
          value = Navy.Class._wrapFunction(superClass, key, value);
        }
      }
      Constructor[key] = value;
    }

    delete protoObj.$static;
  }

  for (key in protoObj) {
    value = protoObj[key];

    if (typeof value === 'object' && value !== null) {
      if (key !== '$static') {
        throw new Error('object property must be primitive type. property = ' + key);
      }
    }

    if (typeof value === 'function') {
      if (Navy.Class._argumentNames(value)[0] === '$super') {
        value = Navy.Class._wrapFunction(superObjForWrap, key, value);
      }
    }
    Constructor.prototype[key] = value;
  }

  Constructor.prototype.constructor = Constructor;
  Constructor.prototype.$className = className;
  Constructor.prototype.$class = Constructor;

  return Constructor;
};

/**
 * 関数の仮引数名のリストを取得する.
 * @param {function} func 対象とする関数.
 * @return {string[]} 仮引数名の配列.
 */
Navy.Class._argumentNames = function _argumentNames(func) {
  var names = func.toString().match(/^[\s\(]*function[^(]*\(([^)]*)\)/)[1]
    .replace(/\/\/.*?[\r\n]|\/\*(?:.|[\r\n])*?\*\//g, '')
    .replace(/\s+/g, '').split(',');
  return names.length == 1 && !names[0] ? [] : names;
};

/**
 * 引数にスーパークラスの関数が渡されるように元の関数をラップして返す。
 * @param {Object} superObj スーパークラスのオブジェクト.
 * @param {string} funcname ラップする関数の名前.
 * @param {function} func ラップする関数.
 * @return {function} ラップした関数.
 */
Navy.Class._wrapFunction = function _wrapFunction(superObj, funcname, func) {
  if (typeof superObj[funcname] !== 'function') {
    throw new Error('override method must be function. function = ' + funcname);
  }

  return function() {
    var _this = this;
    var $super = function() { return superObj[funcname].apply(_this, arguments); };
    var arg = [$super].concat(Array.prototype.slice.call(arguments, 0));
    return func.apply(this, arg);
  };
};


text:
var constants = require('../../../constants');

module.exports = function(Client){
	return Client.sub({
		getValidationResults :Client.method({
			method: constants.verbs.GET,
			url: '{+tenantPod}api/commerce/orders/{orderId}/validationresults'
		}),
		addValidationResult :Client.method({
			method: constants.verbs.PUT,
			url: '{+tenantPod}api/commerce/orders/{orderId}/validationresults?responseFields={responseFields}'
		})
	});
};


text:
namespace NativeCode.Mobile.Core.XamarinForms.Controls
{
    using NativeCode.Mobile.Core.XamarinForms.Controls.ContentProviders;

    using Xamarin.Forms;

    [ContentProperty("Views")]
    public class FlipView : ContentView
    {
        public static readonly BindableProperty FlipViewStyleProperty = BindableProperty.Create<FlipView, FlipViewStyle>(
            x => x.FlipViewStyle,
            default(FlipViewStyle));

        public static readonly BindableProperty ContentProviderProperty =
            BindableProperty.Create<FlipView, IContentViewProvider<FlipViewContent>>(x => x.ContentProvider, default(IContentViewProvider<FlipViewContent>));

        public IContentViewProvider<FlipViewContent> ContentProvider
        {
            get { return (IContentViewProvider<FlipViewContent>)this.GetValue(ContentProviderProperty); }
            set { this.SetValue(ContentProviderProperty, value); }
        }

        public FlipViewStyle FlipViewStyle
        {
            get { return (FlipViewStyle)this.GetValue(FlipViewStyleProperty); }
            set { this.SetValue(FlipViewStyleProperty, value); }
        }
    }
}


text:
"""P-specific operations."""

from paxes_cinder.k2aclient import _
import paxes_cinder.k2aclient.exceptions as k2aexc

import glob
import time

def _fvt_hook(test):
    while True:
        try:
            with open('/tmp/fvt-ssp.txt') as f:
                data = f.read()
                if not data.find(test) < 0:
                    time.sleep(2)
                else:
                    return
        except IOError:
            return

def _enum(**enums):
    return type('Enum', (), enums)

# Status of test
Status = _enum(NOT_ATTEMPTED="NOT_ATTEMPTED",
               SUCCESS="SUCCESS",
               FAILED_WITH_EXCEPTION="FAILED_WITH_EXCEPTION",
               FAILED_WITH_UNEXPECTED_RESULT="FAILED_WITH_UNEXPECTED_RESULT")

class PowerVcClusterCheck(object):
    """For tracking a test result"""
    def __init__(self, title, description, cluster_id):
        self._title = title
        self._description = description

        self._cluster_id = cluster_id

        self._status = Status.NOT_ATTEMPTED
        self._message = "MSG500"
        self._params = None
        self._exception = None
        self._response = None

    @property
    def title(self):
        return self._title

    @property
    def description(self):
        return self._description

    @property
    def cluster_id(self):
        return self._cluster_id

    @property
    def status(self):
        return self._status

    @property
    def message(self):
        return self._message

    @property
    def params(self):
        return self._params

    @property
    def exception(self):
        return self._exception

    @property
    def response(self):
        return self._response

    def setSuccess(self, message, params):
        self._status = Status.SUCCESS
        self._message = message
        self._params = params

    def setFailedWithException(self, exception, message, params, response):
        self._status = Status.FAILED_WITH_EXCEPTION
        self._exception = _("%s") % exception
        self._message = message
        self._params = params
        self._response = response

    def setFailedWithUnexpectedResult(self, message, params, response):
        self._status = Status.FAILED_WITH_UNEXPECTED_RESULT
        self._message = message
        self._params = params
        self._response = response

MESSAGES = {
    "MSG010": _("SharedStoragePool: While attempting to access Cluster: >%s<, "
    "unable to connect to HMC: >%s<"),
    "MSG020": _("Check the HMC and its configuration."),
    "MSG030": _("SharedStoragePool: Able to connect to HMC: >%s< "
    "for Cluster: >%s<"),
    "MSG040": _("SharedStoragePool: Couldn't access Cluster: >%s<"),
    "MSG050": _("Check the PowerVC SharedStoragePool configuration"),
    "MSG060": _("SharedStoragePool: Couldn't access SharedStoragePool "
    "in Cluster: >%s<"),
    "MSG070": _("Diagnose and repair Cluster"),
    "MSG080": _("SharedStoragePool: Successfully accessed SharedStoragePool "
    "in Cluster: >%s<"),
    "MSG090": _("SharedStoragePool: Unable to create LogicalUnits "
    "in Cluster: >%s<"),
    "MSG100": _("Diagnose and repair Cluster"),
    "MSG110": _("SharedStoragePool: LogicalUnit creation functional "
    "in Cluster: >%s<"),
    "MSG120": _("SharedStoragePool: Unable to clone LogicalUnits "
    "in Cluster: >%s<"),
    "MSG130": _("Diagnose and repair Cluster"),
    "MSG140": _("SharedStoragePool: Unable to clone LogicalUnits "
    "in Cluster: >%s<, status: >%s<"),
    "MSG150": _("Clone functional in Cluster: >%s<"),
    "MSG160": _("SharedStoragePool: Unable to delete LogicalUnits "
    "in Cluster: >%s<"),
    "MSG170": _("Diagnose and repair Cluster"),
    "MSG180": _("SharedStoragePool: LogicalUnit deletion functional "
    "in Cluster: >%s<"),
    "MSG500": _("SharedStoragePool: Not Attempted")
}

# Testset is an ordered list of PowerVcClusterCheck, if a test
# fails subsequent tests should have status of Status.NOT_ATTEMPTED
# _TESTS contains order list of PowrVcClusterCheck constructor input
_TESTS = [("connect_to_hmc",
           (_("HMC connectivity"),
            _("Test connection to an HMC managing the SharedStoragePool"))
           ),
          ("access_cluster",
           (_("Cluster and SharedStoragePool accessibility"),
            _("Test the accessibility of a SharedStoragePool"))
           ),
          ("create_logicalunits",
           (_("Create SharedStoragePool LogicalUnits"),
            _("Test the capability to create SharedStoragePool LogicalUnits"))
           ),
          ("clone",
           (_("Clone LogicalUnits"),
            _("Test the capability to perform a clone"))
           ),
          ("delete_logicalunits",
           (_("Delete SharedStoragePool LogicalUnits"),
            _("Test the capability to delete SharedStoragePool LogicalUnits"))
           )]

# _TESTLOOKUP permits accessing ordered list of tests by name
_TESTLOOKUP = {}
for (i, (key, _)) in enumerate(_TESTS):
    _TESTLOOKUP[key] = i

def _perform_test_on_conf(tests, cs, conf, cid, hdn):
    """For a given configuration file perform the tests"""
    # initiate tests
    curtests = []
    for _, (title, descr) in _TESTS:
        curtests.append(PowerVcClusterCheck(title,
                                            descr,
                                            cid))
    tests.append((conf, cs.client.k2_url, hdn, curtests))

    ########
    # test_connect_to_hmc
    _fvt_hook("connect_to_hmc")
    curtest = curtests[_TESTLOOKUP["connect_to_hmc"]]
    failed = None
    try:
        cs.client.authenticate()
    except Exception as failed:
        pass
    if failed is not None:
        curtest.setFailedWithException(failed,
                                       "MSG010",
                                       [hdn, cs.client.k2_url],
                                       "MSG020")
        return
    curtest.setSuccess("MSG030",
                       [cs.client.k2_url, hdn])

    ########
    # access_cluster
    _fvt_hook("access_cluster")
    curtest = curtests[_TESTLOOKUP["access_cluster"]]
    failed = None
    try:
        cluster = cs.cluster.get(cid)
    except Exception as failed:
        pass

    if isinstance(failed, k2aexc.K2aK2ErrorNotFound):
        curtest.setFailedWithUnexpectedResult("MSG040",
                                              [hdn],
                                              "MSG050")
        return
    elif failed is not None:
        curtest.setFailedWithException(failed,
                                       "MSG040",
                                       [hdn],
                                       "MSG050")

        return
    ssp_id = cluster.cluster_shared_storage_pool.split("/")[-1]
    if len(ssp_id) != 36:
        curtest.setFailedWithUnexpectedResult("MSG040",
                                              [hdn],
                                              "MSG050")
        return

    failed = None
    try:
        ssp = cs.sharedstoragepool.get(ssp_id)
    except Exception as failed:
        pass

    if isinstance(failed, k2aexc.K2aK2ErrorNotFound):
        curtest.setFailedWithUnexpectedResult("MSG040",
                                              [hdn],
                                              "MSG050")
        return
    elif failed is not None:
        curtest.setFailedWithException(failed,
                                       "MSG060",
                                       [hdn],
                                       "MSG070")
        return

    curtest.setSuccess("MSG080",
                       [hdn])

    ########
    # create_logicalunits
    _fvt_hook("create_logicalunits")
    curtest = curtests[_TESTLOOKUP["create_logicalunits"]]
    failed = None
    try:
        n = cs.sharedstoragepool.create_unique_name
#         (status, source_udid, job_id) = cluster.lu_create(
#             n("DELETEME-TEST-SOURCE"),
#             "0.001",
#             thin=True)
#         (status, source_udid, job_id) = cluster.lu_create(
#             n("DELETEME-TEST-TARGET"),
#             "0.001",
#             thin=True)
        (source_lus, ssp) = ssp.update_append_lus([(n("DELETEME-TEST-SOURCE"),
                                                  "0.001",
                                                  True)])
        (target_lus, ssp) = ssp.update_append_lus([(n("DELETEME-TEST-TARGET"),
                                                  "0.001",
                                                  True)])
        source_lu = source_lus[0]
        target_lu = target_lus[0]
    except Exception as failed:
        pass
    if failed is not None:
        curtest.setFailedWithException(failed,
                                       "MSG090",
                                       [hdn],
                                       "MSG100")
        return
    curtest.setSuccess("MSG110",
                       [hdn])

    ########
    # clone
    _fvt_hook("clone")
    curtest = curtests[_TESTLOOKUP["clone"]]
    failed = None
    try:
        status, job_id = cluster.lu_linked_clone(
            source_lu.unique_device_id,
            target_lu.unique_device_id)
    except Exception as failed:
        pass
    if failed is not None:
        curtest.setFailedWithException(failed,
                                       "MSG120",
                                       [hdn],
                                       "MSG130")
        return
    if status != "COMPLETED_OK":
        curtest.setFailedWithUnexpectedResult("MSG140",
                                              [hdn, status],
                                              "MSG130")
        return

    curtest.setSuccess("MSG150",
                       [hdn])

    ########
    # delete_logicalunits
    _fvt_hook("delete_logicalunits")
    curtest = curtests[_TESTLOOKUP["delete_logicalunits"]]
    failed = None
    try:
        ssp = ssp.update_del_lus([target_lu.unique_device_id])
        ssp = ssp.update_del_lus([source_lu.unique_device_id])
    except Exception as failed:
        pass
    if failed is not None:
        curtest.setFailedWithException(failed,
                                       "MSG160",
                                       [hdn],
                                       "MSG170")
        return
    curtest.setSuccess("MSG180",
                       [hdn])

    # append test
#     tests.append((conf, cs.client.k2_url, curtests))

class PowerVcManager(object):
    """Perform PowerVc-specific operations."""

    def __init__(self, api):
        self.api = api

    def check_ssp_conf(self, confdir):
        """verify ssp is accessible and functional"""

        testset = []
        for conf, cid, hdn in _get_clusters():
            _perform_test_on_conf(testset, self.api, conf, cid, hdn)
        return testset

    @staticmethod
    def result_output_as_dict(testset):
        """return representation of tests suitable for output"""
        #
        # tforj = [{"conf_filespec": "<conf-filespec>",
        #           "tests":
        #             [
        #               {"title": "<title>",
        #                "description": "<description>",
        #                "cluster_id": "<cluster_id>",
        #                "status": "<status>",
        #                "msg": "<msg>",
        #                "exception_msg: "<exception_msg>", (if present)
        #                "response": <response>" (if present)
        #               }
        #             ]
        #          },
        #         ]
        tforj = {}
        for config_file, k2_url, host_display_name, ts in testset:
            cdict = {}
            cdict["configuration_file"] = config_file
            cdict["hmc_ip"] = k2_url
            tlist = []
            for t in ts:
                tdict = {}
                tdict["title"] = t.title
                tdict["description"] = t.description
                tdict["configuration_file"] = config_file
                tdict["hmc_ip"] = k2_url
                tdict["storage_host"] = host_display_name
                tdict["cluster_id"] = t.cluster_id
                tdict["status"] = t.status
                if t.params is not None:
                    tdict["msg"] = MESSAGES[t.message] % tuple(t.params)
                else:
                    tdict["msg"] = MESSAGES[t.message]
                if t.exception is not None:
                    tdict["exception"] = t.exception
                if t.response is not None:
                    tdict["response"] = MESSAGES[t.response]
                tlist.append(tdict)
            cdict["tests"] = tlist
            tforj[config_file] = cdict

        return tforj

    @staticmethod
    def result_output_for_ttv(testset):
        """return representation of tests suitable for ttv"""
        tforj = {}
        for config_file, k2_url, host_display_name, ts in testset:
            cdict = {}
            cdict["configuration_file"] = config_file
            cdict["hmc_ip"] = k2_url
            tlist = []
            for t in ts:
                if t.status is Status.NOT_ATTEMPTED:
                    break
                tdict = {}
                tdict["title"] = t.title
                tdict["description"] = t.description
                tdict["configuration_file"] = config_file
                tdict["hmc_ip"] = k2_url
                tdict["storage_host"] = host_display_name
                tdict["cluster_id"] = t.cluster_id
                tdict["status"] = "SUCCESS"
                if t.status is not Status.SUCCESS:
                    tdict["status"] = "FAIL"
                tdict["message"] = t.message
                tdict["params"] = t.params
                if t.exception is not None:
                    tdict["exception"] = t.exception
                if t.response is not None:
                    tdict["response"] = t.response
                tlist.append(tdict)
            cdict["tests"] = tlist
            tforj[config_file] = cdict

        return tforj

def _get_clusters():
    """Retrieve ssp clusters for health checks
    TODO: TTV Team: Fix this when you port to TTV"""
    # cinder.conf file(s)
    clusters = []
    for conf in glob.glob("/etc/cinder/cinder-*.conf"):
        powervm_mgr_cluster = None
        with open(conf) as f:
            for line in f:
                if line.strip().startswith("powervm_mgr_cluster = "):
                    parts = line.split("=")
                    if len(parts) == 2:
                        powervm_mgr_cluster = parts[1].strip()
                if line.strip().startswith("host_display_name = "):
                    parts = line.split("=")
                    if len(parts) == 2:
                        host_display_name = parts[1].strip()

        if powervm_mgr_cluster is not None and host_display_name is not None:
            clusters.append((conf, powervm_mgr_cluster, host_display_name))

    return clusters

# if __name__ == '__main__':
#     powervm_mgr_clusters = _get_clusters()
#     print powervm_mgr_clusters


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

namespace Ecosim.SceneData
{

/**
 * Stores tile parameter data for one data type (e.g. pH or salinity)
 */
	public class HeightMap : Data
	{
		public const float HEIGHT_PER_UNIT = 0.01f; // one unit is 0.01 meter
		public const float VERTICAL_HEIGHT = 655.35f; // makes one unit == 0.01 meter

		public HeightMap (Scene scene)
		: base(scene)
		{

			data = new ushort[width * height];
		}

		HeightMap (Scene scene, ushort[] data)
		: base(scene)
		{
			this.data = data;
		}

		// we made it public so code can use it directly for performance reasons
		public ushort[] data;

		public override void Save(BinaryWriter writer, Progression progression) {
			writer.Write("HeightMap");
			writer.Write(width);
			writer.Write(height);
			for (int i = 0; i < data.Length; i++) {
				writer.Write(data[i]);
			}
		}

		static HeightMap LoadInternal(BinaryReader reader, Progression progression) {
			int width = reader.ReadInt32();
			int height = reader.ReadInt32();
			EnforceValidSize (progression.scene, width, height);
			int len = width * height; // len in shorts instead of bytes
			ushort[] data = new ushort[len];
			for (int i = 0; i < len; i++) {
				data[i] = reader.ReadUInt16();
			}
			return new HeightMap(progression.scene, data);
		}

		/**
		 * Sets all values in bitmap to zero
		 */
		public override void Clear ()
		{
			for (int i = data.Length - 1; i >= 0; i--) {
				data [i] = 0;
			}
		}

		/**
		 * set data value val at x, y
		 */
		public override void Set (int x, int y, int val)
		{
			data [y * width + x] = (ushort)val;
			hasChanged = true;
		}

		/**
		 * get data value at x, y
		 */
		public override int Get (int x, int y)
		{
			return data [y * width + x];
		}

		/**
		 * Gets height at x, y, height is a float between 0 and VERTICAL_HEIGHT
		 */
		public float GetHeight (int x, int y) {
			return HEIGHT_PER_UNIT * data [y * width + x];
		}

		/**
		 * Gets height using interpolation between tiles. It won't match the real terrain perfectly
		 * but it should be close enough to be usable. Doesn't take canals into account.
		 * x and y are real world terrain coordinates instead of tile coordinates. x and y will be clamped.
		 */
		public float GetInterpolatedHeight (float x, float y) {
			x = Mathf.Clamp(x / TerrainMgr.TERRAIN_SCALE - 0.5f, 0f, width - 1.01f);
			y = Mathf.Clamp(y / TerrainMgr.TERRAIN_SCALE - 0.5f, 0f, height - 1.01f);
			int xInt = (int) x;
			int yInt = (int) y;
			float xFraq = x - xInt;
			float yFraq = y - yInt;
			int v00 = data [yInt * width + xInt];
			int v10 = data [yInt * width + xInt + 1];
			int v01 = data [yInt * width + xInt + width];
			int v11 = data [yInt * width + xInt + width + 1];
			float result = v00 * (1f - xFraq) * (1f - yFraq) + v10 * xFraq * (1f - yFraq) + v01 * (1f - xFraq) * yFraq + v11 * xFraq * yFraq;
			return HEIGHT_PER_UNIT * result;
		}

		/**
		 * Sets height at x, y, height will be clamped 0 and VERTICAL_HEIGHT and stored in its internal ushort representation
		 */
		public void SetHeight (int x, int y, float height) {
			 data [y * width + x] = (ushort) UnityEngine.Mathf.Clamp ((int) (height / HEIGHT_PER_UNIT), 0, 65535);
		}

		/**
		 * copy data from src to data
		 */
		public void CopyFrom (HeightMap src)
		{
			System.Array.Copy (src.data, data, data.Length);
			hasChanged = true;
		}

		/**
		 * copy data from src to data
		 */
		public void CopyFrom (BitMap16 src)
		{
			System.Array.Copy (src.data, data, data.Length);
			hasChanged = true;
		}

		public void ClearData ()
		{
			System.Array.Clear (data, 0, data.Length);
			hasChanged = true;
		}

		public override int GetMin() { return 0; }
		public override int GetMax() { return 65535; }

		/**
		 * Copies this instance data to 'toData'
		 * This overridden version has a fast copy if toData is same data type, otherwise
		 * it falls back to base implementation
		 */
		public override void CopyTo(Data toData) {
			if (toData is HeightMap) {
				// data is of same type
				if ((toData.width != width) || (toData.height != height)) {
					throw new EcoException("size mismatch, toData needs to be same size as data");
				}
				// we can quickly copy array data....
				data.CopyTo(((HeightMap) toData).data, 0);
			}
			else if (toData is BitMap16) {
				// data is of same type
				if ((toData.width != width) || (toData.height != height)) {
					throw new EcoException("size mismatch, toData needs to be same size as data");
				}
				// we can quickly copy array data....
				data.CopyTo(((BitMap16) toData).data, 0);
			}
			else if (toData is VegetationData) {
				// data is of same type
				if ((toData.width != width) || (toData.height != height)) {
					throw new EcoException("size mismatch, toData needs to be same size as data");
				}
				// we can quickly copy array data....
				data.CopyTo(((VegetationData) toData).data, 0);
			}
			else {
				// fall back on normal simple CopyTo
				base.CopyTo(toData);
			}
		}
	}
}


text:
package org.mifos.accounts.struts.actionforms;

import static org.mifos.framework.util.helpers.DateUtils.getDateAsSentFromBrowser;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.apache.commons.lang.StringUtils;
import org.apache.struts.action.ActionErrors;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.action.ActionMessage;
import org.mifos.accounts.util.helpers.AccountConstants;
import org.mifos.application.admin.servicefacade.InvalidDateException;
import org.mifos.application.master.business.MifosCurrency;
import org.mifos.config.AccountingRules;
import org.mifos.dto.domain.AdjustedPaymentDto;
import org.mifos.dto.screen.GroupLoanMemberAdjustmentDto;
import org.mifos.framework.struts.actionforms.BaseActionForm;
import org.mifos.framework.util.helpers.Constants;
import org.mifos.framework.util.helpers.DateUtils;
import org.mifos.framework.util.helpers.DoubleConversionResult;
import org.mifos.security.login.util.helpers.LoginConstants;
import org.mifos.security.util.UserContext;

import com.ibm.icu.math.BigDecimal;

/**
 * This class is the action form for Applying adjustments.
 */
public class ApplyAdjustmentActionForm extends BaseActionForm {

    private static final long serialVersionUID = -5747465818008310010L;

    private String input;

    private String adjustmentNote;

    private Integer accountId;

    private String globalAccountNum;

    private boolean adjustcheckbox;

    private Integer paymentId;

    private String amount;

    private String paymentType;

    private Short currencyId;

    private String transactionDateDD;

    private String transactionDateMM;

    private String transactionDateYY;

    private boolean adjustData;

    private Date previousPaymentDate;

    private Date nextPaymentDate;

    private List<GroupLoanMemberAdjustmentDto> memberAdjustmentDtoList;

    /**
     * member adjustment new amounts
     * Key - Member Account Id
     * Value - Member New Amount
     */
    private Map<Integer, String> newAmounts = new HashMap<Integer, String>();

    /**
     * NOT-GLIM new group loan member flag
     */
    private boolean groupLoanMember;

    public Date getPreviousPaymentDate() {
        return previousPaymentDate;
    }

    public void setPreviousPaymentDate(Date previousPaymentDate) {
        this.previousPaymentDate = previousPaymentDate;
    }

    public Date getNextPaymentDate() {
        return nextPaymentDate;
    }

    public void setNextPaymentDate(Date nextPaymentDate) {
        this.nextPaymentDate = nextPaymentDate;
    }

    public boolean isAdjustData() {
        return adjustData;
    }

    public void setAdjustData(boolean adjustData) {
        this.adjustData = adjustData;
    }

    public Short getCurrencyId() {
        return currencyId;
    }

    public void setCurrencyId(Short currencyId) {
        this.currencyId = currencyId;
    }

    public Integer getPaymentId() {
        return paymentId;
    }

    public void setPaymentId(Integer paymentId) {
        this.paymentId = paymentId;
    }

    public String getInput() {
        return input;
    }

    public void setInput(String input) {
        this.input = input;
    }

    public String getAdjustmentNote() {
        return adjustmentNote;
    }

    public void setAdjustmentNote(String adjustmentNote) {
        this.adjustmentNote = adjustmentNote;
    }

    public Integer getAccountId() {
        return accountId;
    }

    public void setAccountId(Integer accountId) {
        this.accountId = accountId;
    }

    public String getGlobalAccountNum() {
        return globalAccountNum;
    }

    public void setGlobalAccountNum(String globalAccountNum) {
        this.globalAccountNum = globalAccountNum;
    }

    public boolean getAdjustcheckbox() {
        return adjustcheckbox;
    }

    public void setAdjustcheckbox(boolean adjustcheckbox) {
        this.adjustcheckbox = adjustcheckbox;

    }

    public String getAmount() {
        return amount;
    }

    public void setAmount(String amount) {
        this.amount = amount;
    }

    public String getPaymentType() {
        return paymentType;
    }

    public void setPaymentType(String paymentType) {
        this.paymentType = paymentType;
    }

    public String getTransactionDateDD() {
        return transactionDateDD;
    }

    public void setTransactionDateDD(String transactionDateDD) {
        this.transactionDateDD = transactionDateDD;
    }

    public String getTransactionDateMM() {
        return transactionDateMM;
    }

    public void setTransactionDateMM(String transactionDateMM) {
        this.transactionDateMM = transactionDateMM;
    }

    public String getTransactionDateYY() {
        return transactionDateYY;
    }

    public void setTransactionDateYY(String transactionDateYY) {
        this.transactionDateYY = transactionDateYY;
    }

    public List<GroupLoanMemberAdjustmentDto> getMemberAdjustmentDtoList() {
        return memberAdjustmentDtoList;
    }

    public void setMemberAdjustmentDtoList(List<GroupLoanMemberAdjustmentDto> memberAdjustmentDtoList) {
        this.memberAdjustmentDtoList = memberAdjustmentDtoList;
    }

    public Map<Integer, String> getNewAmounts() {
        return newAmounts;
    }

    public void setNewAmount(String accountId, String newAmount){
        this.newAmounts.put(Integer.valueOf(accountId), newAmount);
    }

    public boolean isGroupLoanMember() {
        return groupLoanMember;
    }

    public void setGroupLoanMember(boolean groupLoanMemberFlag) {
        this.groupLoanMember = groupLoanMemberFlag;
    }

    protected Locale getUserLocale(HttpServletRequest request) {
        Locale locale = null;
        HttpSession session = request.getSession();
        if (session != null) {
            UserContext userContext = (UserContext) session.getAttribute(LoginConstants.USERCONTEXT);
            if (null != userContext) {
                locale = userContext.getCurrentLocale();

            }
        }
        return locale;
    }

    public String getTransactionDate() {
        return compileDateString(transactionDateDD, transactionDateMM, transactionDateYY);
    }

    @Override
    public void reset(ActionMapping actionMapping, HttpServletRequest request) {
        this.adjustcheckbox = false;
    }

    @Override
    public ActionErrors validate(ActionMapping actionMapping, HttpServletRequest request) {
        if (null == request.getAttribute(Constants.CURRENTFLOWKEY)) {
            request.setAttribute(Constants.CURRENTFLOWKEY, request.getParameter(Constants.CURRENTFLOWKEY));
        }
        ActionErrors actionErrors = new ActionErrors();
        String method = request.getParameter("method");
        if (null != method && method.equals("previewAdjustment")) {
/*            if (!adjustcheckbox) {
                request.setAttribute("method", "loadAdjustment");
                actionErrors.add("", new ActionMessage("errors.mandatorycheckbox"));
            }*/
            if (!adjustcheckbox) {
                validateAmount(actionErrors);
                validatePaymentType(actionErrors);
                validateTransactionDate(actionErrors);
            }
            if (adjustmentNote == null || adjustmentNote.trim() == "") {
                request.setAttribute("method", "loadAdjustment");
                actionErrors.add("", new ActionMessage("errors.mandatorytextarea"));
            } else if (adjustmentNote.length() > 300) {
                request.setAttribute("method", "loadAdjustment");
                actionErrors.add("", new ActionMessage("errors.adjustmentNoteTooBig"));
            }
            if (!actionErrors.isEmpty()) {
                request.setAttribute("method", "loadAdjustment");
                return actionErrors;
            }
        }
        return actionErrors;
    }

    protected void validateAmount(ActionErrors errors) {
        MifosCurrency currency = null;
        if (getCurrencyId() != null && AccountingRules.isMultiCurrencyEnabled()) {
            currency = AccountingRules.getCurrencyByCurrencyId(getCurrencyId());
        }
        DoubleConversionResult conversionResult = validateAmount(getAmount(), currency , AccountConstants.ACCOUNT_AMOUNT, errors, "");
        if (conversionResult.getErrors().size() == 0 && !(conversionResult.getDoubleValue() > 0.0)) {
            addError(errors, AccountConstants.ACCOUNT_AMOUNT, AccountConstants.ERRORS_MUST_BE_GREATER_THAN_ZERO,
                    getLocalizedMessage(AccountConstants.ACCOUNT_AMOUNT));
        }
    }

    private void validateTransactionDate(ActionErrors errors) {
        String fieldName = "accounts.date_of_trxn";
        ActionErrors validationErrors = validateDate(getTransactionDate(), getLocalizedMessage(fieldName));

        if (null != validationErrors && !validationErrors.isEmpty()) {
            errors.add(validationErrors);
        }
    }

    private void validatePaymentType(ActionErrors errors) {
        if (StringUtils.isEmpty(getPaymentType())) {
            errors.add(AccountConstants.ERROR_MANDATORY, new ActionMessage(AccountConstants.ERROR_MANDATORY,
                    getLocalizedMessage("accounts.mode_of_payment")));
        }
    }

    protected ActionErrors validateDate(String date, String fieldName) {
        ActionErrors errors = null;
        java.sql.Date sqlDate = null;
        if (date != null && !date.equals("")) {
            try {
                sqlDate = getDateAsSentFromBrowser(date);
                if (DateUtils.whichDirection(sqlDate) > 0) {
                    errors = new ActionErrors();
                    errors.add(AccountConstants.ERROR_FUTUREDATE, new ActionMessage(AccountConstants.ERROR_FUTUREDATE,
                            fieldName));
                } else if (previousPaymentDate != null && sqlDate.compareTo(previousPaymentDate) < 0) {
                    errors = new ActionErrors();
                    errors.add(AccountConstants.ERROR_ADJUSTMENT_PREVIOUS_DATE, new ActionMessage(AccountConstants.ERROR_ADJUSTMENT_PREVIOUS_DATE,
                            fieldName));
                } else if (nextPaymentDate != null && sqlDate.compareTo(nextPaymentDate) > 0) {
                    errors = new ActionErrors();
                    errors.add(AccountConstants.ERROR_ADJUSTMENT_NEXT_DATE, new ActionMessage(AccountConstants.ERROR_ADJUSTMENT_NEXT_DATE,
                            fieldName));
                }
            } catch (InvalidDateException ide) {
                errors = new ActionErrors();
                errors.add(AccountConstants.ERROR_INVALIDDATE, new ActionMessage(AccountConstants.ERROR_INVALIDDATE,
                        fieldName));
            }
        } else {
            errors = new ActionErrors();
            errors.add(AccountConstants.ERROR_MANDATORY, new ActionMessage(AccountConstants.ERROR_MANDATORY,
                            fieldName));
        }

        return errors;
    }

    public Date getTrxnDate() throws InvalidDateException {
        return getDateAsSentFromBrowser(getTransactionDate());
    }

    public void setTrxnDate(Date date) {
        if (date == null) {
            transactionDateDD = null;
            transactionDateMM = null;
            transactionDateYY = null;
        } else {
            Calendar cal = GregorianCalendar.getInstance();
            cal.setTime(date);
            transactionDateDD = Integer.toString(cal.get(Calendar.DAY_OF_MONTH));
            transactionDateMM = Integer.toString(cal.get(Calendar.MONTH) + 1);
            transactionDateYY = Integer.toString(cal.get(Calendar.YEAR));
        }
    }

    public AdjustedPaymentDto getPaymentData() throws InvalidDateException {
        AdjustedPaymentDto adjustedPaymentDto = null;
        if (adjustData || isGroupLoanMember()) {
            List<AdjustedPaymentDto> membersAdjustedPaymentDtoList = new ArrayList<AdjustedPaymentDto>();
            for (Map.Entry<Integer, String> member : this.newAmounts.entrySet()) {
                membersAdjustedPaymentDtoList.add(new AdjustedPaymentDto(member.getValue(), getTrxnDate(), Short.parseShort(paymentType), member.getKey()));
            }
            String newAmount = (adjustData) ? amount : BigDecimal.ZERO.toString();
            adjustedPaymentDto = new AdjustedPaymentDto(newAmount, getTrxnDate(), Short.parseShort(paymentType), this.accountId, membersAdjustedPaymentDtoList);
        }
        return adjustedPaymentDto;
    }
}


text:
var
    async = require('async'),
    error = require('./../../error'),
    response = require('./../../util/response.js'),
    emitter = require('./../../events');

// @todo: move decision var to config
// @todo: add state

module.exports = function(req, res, client, scope, user, redirectUri) {

    var
        accessTokenValue;

    async.waterfall([
        // Check user decision
        function(cb) {
            if (!req.body || typeof(req.body['decision']) == 'undefined')
                cb(new error.invalidRequest('No decision parameter passed'));
            else if (req.body['decision'] == 0)
                cb(new error.accessDenied('User denied the access to the resource'));
            else {
                req.oauth2.logger.debug('Decision check passed');
                cb();
            }
        },
        // Generate new accessToken and save it
        function(cb) {
            req.oauth2.model.accessToken.create(req.oauth2.model.user.getId(user), req.oauth2.model.client.getId(client), scope, req.oauth2.model.accessToken.ttl, function(err, data) {
                if (err)
                    cb(new error.serverError('Failed to call accessToken::save method'));
                else {
                    accessTokenValue = data;
                    req.oauth2.logger.debug('Access token saved: ', accessTokenValue);
                    cb();
                }
            });
        }
    ],
    function(err) {
        if (err) response.error(req, res, err, redirectUri);
        else {
            var responseObj = {
                token_type:    "bearer",
                access_token:  accessTokenValue,
                expires_in:    req.oauth2.model.accessToken.ttl
            };
            emitter.authorization_implicit_granted(req, responseObj);
            response.data(req, res, responseObj, redirectUri, true);
        }
    });
};


text:
import graphene

from graphene_mongodb.fields import convert_fields
from graphene_mongodb.query import resolver_query
from graphene_mongodb.mutation import gen_mutation

class ModelSchema:
    def __init__(self, model, attrs_mongo_doc, mutate, validator):
        self.model = model
        self.mutate_func = mutate  # mutate function that user specified
        self.validator = validator

        self.fields, self.fields_mutation, self.operators_mutation,\
            self.operators_single, self.operators_list = convert_fields(attrs_mongo_doc)

        self.schema = type(self.model.__name__ + 'Graphene', (graphene.ObjectType,), self.fields.copy())

    def to_attrs(self):
        return {
            'single': self.single(),
            'list': self.list(),
            'fields': self.fields,
            'model': self.model,
            'mutate': self.mutate().Field()
        }

    def mutate(self):
        return gen_mutation(self.model, self.schema, self.operators_mutation, self.fields_mutation, self.mutate_func,
                            self.validator)

    def single(self):
        return ModelSchema.resolver(self.schema, self.model, operators_single=self.operators_single,
                                    validator=self.validator)

    def list(self):
        return ModelSchema.resolver(self.schema, self.model, operators_list=self.operators_list,
                                    validator=self.validator, is_list=True)

    @staticmethod
    def resolver(g_schema, mongo_doc, operators_single=None, operators_list=None, is_list=False, validator=None):
        def auto_resolver(root, info, **kwargs):
            return resolver_query(g_schema, mongo_doc, kwargs, info, is_list=is_list, validator=validator)

        if is_list:
            return graphene.List(g_schema, **operators_list, resolver=auto_resolver)
        else:
            return graphene.Field(g_schema, **operators_single, resolver=auto_resolver)