text: Template engine html para nodejs (utilizado para fins de estudo)

redpajama_set_name: RedPajamaGithub


text:
function plotlabOBJ = unitTestRetinalSizeToVisualSize(varargin)
% Plot the correspondence of a constant retinal size (in microns) to the visual
% size (in degrees), and conversely, the correspondence of a constant visual size
% (in degrees) to retinal size (in microns), both as a function of eccentricity

    % Parse input
    p = inputParser;
    p.addParameter('plotlabOBJ', [], @(x)(isempty(x) || isa(x, 'plotlab')));
    p.parse(varargin{:});
    plotlabOBJ = p.Results.plotlabOBJ;

    eccMinDegs = 0.0;
    eccMaxDegs = 100;
    eccSamplesNum = 200;

    eccDegs = linspace(eccMinDegs, eccMaxDegs, eccSamplesNum);
    eccMicrons = 1000 * WatsonRGCModel.rhoDegsToMMs(eccDegs);
    retinalSizeMicrons = 10;
    visualSizeDegs = 1.0;

    % Convert retinal size in microns to visual degrees
    sizeDegs = WatsonRGCModel.sizeRetinalMicronsToSizeDegs(retinalSizeMicrons, eccMicrons);

    % Convert visual size in degrees to retinal microns
    sizeMicrons = WatsonRGCModel.sizeDegsToSizeRetinalMicrons(visualSizeDegs, eccDegs);

    obj = WatsonRGCModel();
    if (isempty(plotlabOBJ))
        plotlabOBJ  = obj.setUpPlotLab();
    end

    hFig = figure(101); clf;
    theAxesGrid = plotlabOBJ.axesGrid(hFig, ...
            'rowsNum', 1, 'colsNum', 2, ...
            'leftMargin', 0.08, ...
            'bottomMargin', 0.18, ...
            'widthMargin', 0.1, ...
            'rightMargin', 0.01, ...
            'topMargin', 0.05);

    % The left plot
    hold(theAxesGrid{1,1}, 'on');

    line(theAxesGrid{1,1}, eccDegs, eccDegs*0 + 60*retinalSizeMicrons/WatsonRGCModel.micronsPerDegreeLinearApproximation, ...
        'LineWidth', 1.5, 'LineStyle', '--', 'Color', 'r');
    line(theAxesGrid{1,1}, eccDegs, sizeDegs*60, 'LineWidth', 1.5, 'Color', 'k');

    axis(theAxesGrid{1,1}, 'square');
    set(theAxesGrid{1,1}, 'XLim', [eccMinDegs eccMaxDegs], 'YLim', [0 5], ...
        'XTick', 0:20:100, ...
        'YTick', 0:1:10);

    % Labels and legends
    xlabel(theAxesGrid{1,1}, 'ecc (deg)');
    ylabel(theAxesGrid{1,1}, 'visual size (arc min)');
    title(theAxesGrid{1,1}, sprintf('%2.0f um retinal size', retinalSizeMicrons));

    % The right plot
    hold(theAxesGrid{1,2}, 'on');
    line(theAxesGrid{1,2}, eccDegs, eccDegs*0 + visualSizeDegs * WatsonRGCModel.micronsPerDegreeLinearApproximation, ...
        'LineWidth', 1.5, 'LineStyle', '--', 'Color', 'r');
    line(theAxesGrid{1,2}, eccDegs, sizeMicrons, 'LineWidth', 1.5, 'Color', 'k');

    % Labels and legends
    xlabel(theAxesGrid{1,2}, 'ecc (deg)');
    ylabel(theAxesGrid{1,2}, 'retinal size (um)');
    title(theAxesGrid{1,2}, sprintf('%2.1f deg visual size', visualSizeDegs));

    axis(theAxesGrid{1,2}, 'square');
    set(theAxesGrid{1,2}, 'XLim', [eccMinDegs eccMaxDegs], 'YLim', [50 300], ...
        'XTick', 0:20:100, ...
        'YTick', 50:50:300);

end

function doIt(obj,eccentricities, eccUnits, spacingUnits, meridianLabeling, figureName, theFileName, plotlabOBJ)

    exportFigure = false;

    hFig = figure(101); clf;
    theAxesGrid = plotlabOBJ.axesGrid(hFig, ...
            'leftMargin', 0.16, ...
            'bottomMargin', 0.18, ...
            'rightMargin', 0.04, ...
            'topMargin', 0.05);
    theAxesGrid = theAxesGrid{1,1};
    hold(theAxesGrid, 'on');

    meridianNames = obj.enumeratedMeridianNames;
    theLegends = cell(numel(meridianNames),1);

    % Loop over meridians
    for k = 1:numel(meridianNames)
        % Compute the data
        rightEyeVisualFieldMeridianName = meridianNames{k};
        [mRGCRFSpacing, mRGCRFDensity] = obj.mRGCRFSpacingAndDensityAlongMeridian(eccentricities, rightEyeVisualFieldMeridianName, eccUnits, sprintf('%s^2',spacingUnits));

        % One class On/OFF assuming equal numerosities
        OnOrOFF_mRGCRFSpacing = sqrt(2.0) * mRGCRFSpacing;
        OnOrOFF_mRGCRFDensity = 0.5 * mRGCRFDensity;

        if (strcmp(spacingUnits, 'deg'))
            % Convert to arcmin from deg
            OnOrOFF_mRGCRFSpacing = OnOrOFF_mRGCRFSpacing*60;
        else
            % Convert to microns from mm
            OnOrOFF_mRGCRFSpacing = OnOrOFF_mRGCRFSpacing*1000;
        end
        plot(theAxesGrid, eccentricities, OnOrOFF_mRGCRFSpacing);
        if (strcmp(meridianLabeling, 'retinal'))
            theLegends{k} = rightEyeRetinalMeridianName;
        else
            theLegends{k} = rightEyeVisualFieldMeridianName;
        end
    end

    % Ticks and Lims
    if (strcmp(eccUnits, 'mm'))
        xLims = obj.rhoDegsToMMs([0.005 100]);
        xTicks = [0.01 0.03 0.1 0.3 1 3 10];
        xLabelString = sprintf('eccentricity (%s)', eccUnits);
    else
        xLims = [0 10];
        xTicks = 0:2:10;
        xLabelString = sprintf('eccentricity (%s)', strrep(eccUnits, 'visual', ''));
    end

    if (strcmp(spacingUnits, 'mm'))
        yLims = [2000 250*1000];
        yTicks = [2000 5*1000 10*1000 20*1000 50*1000 100*1000 200*1000];
        yTicksLabels = {'2k', '5k', '10k', '20k', '50k', '100k', '200K'};
        yLabelString = sprintf('On or OFF spacing (microns)');
    else
        yLims = [0 6];
        yTicks = 0:1:6;
        yTicksLabels = 0:1:6;
        yLabelString = sprintf('spacing (arcmin)');
    end

    % Labels and legends
    xlabel(theAxesGrid, xLabelString);
    ylabel(theAxesGrid, yLabelString);
    legend(theAxesGrid, theLegends, 'Location', 'NorthWest');

    set(theAxesGrid, 'XLim', xLims, 'YLim', yLims, ...
        'XTick', xTicks, ...
        'YTick', yTicks, 'YTickLabel', yTicksLabels);

    % Export figure
    if (exportFigure)
        localDir = fileparts(which(theFileName));
        plotlabOBJ.exportFig(hFig, 'png', figureName, fullfile(localDir, 'exports'));
    end
end


text:
package fake

import (
	config_v1 "github.com/openshift/api/config/v1"
	v1 "k8s.io/apimachinery/pkg/apis/meta/v1"
	labels "k8s.io/apimachinery/pkg/labels"
	schema "k8s.io/apimachinery/pkg/runtime/schema"
	types "k8s.io/apimachinery/pkg/types"
	watch "k8s.io/apimachinery/pkg/watch"
	testing "k8s.io/client-go/testing"
)

// FakeIngresses implements IngressInterface
type FakeIngresses struct {
	Fake *FakeConfigV1
}

var ingressesResource = schema.GroupVersionResource{Group: "config.openshift.io", Version: "v1", Resource: "ingresses"}

var ingressesKind = schema.GroupVersionKind{Group: "config.openshift.io", Version: "v1", Kind: "Ingress"}

// Get takes name of the ingress, and returns the corresponding ingress object, and an error if there is any.
func (c *FakeIngresses) Get(name string, options v1.GetOptions) (result *config_v1.Ingress, err error) {
	obj, err := c.Fake.
		Invokes(testing.NewRootGetAction(ingressesResource, name), &config_v1.Ingress{})
	if obj == nil {
		return nil, err
	}
	return obj.(*config_v1.Ingress), err
}

// List takes label and field selectors, and returns the list of Ingresses that match those selectors.
func (c *FakeIngresses) List(opts v1.ListOptions) (result *config_v1.IngressList, err error) {
	obj, err := c.Fake.
		Invokes(testing.NewRootListAction(ingressesResource, ingressesKind, opts), &config_v1.IngressList{})
	if obj == nil {
		return nil, err
	}

	label, _, _ := testing.ExtractFromListOptions(opts)
	if label == nil {
		label = labels.Everything()
	}
	list := &config_v1.IngressList{ListMeta: obj.(*config_v1.IngressList).ListMeta}
	for _, item := range obj.(*config_v1.IngressList).Items {
		if label.Matches(labels.Set(item.Labels)) {
			list.Items = append(list.Items, item)
		}
	}
	return list, err
}

// Watch returns a watch.Interface that watches the requested ingresses.
func (c *FakeIngresses) Watch(opts v1.ListOptions) (watch.Interface, error) {
	return c.Fake.
		InvokesWatch(testing.NewRootWatchAction(ingressesResource, opts))
}

// Create takes the representation of a ingress and creates it.  Returns the server's representation of the ingress, and an error, if there is any.
func (c *FakeIngresses) Create(ingress *config_v1.Ingress) (result *config_v1.Ingress, err error) {
	obj, err := c.Fake.
		Invokes(testing.NewRootCreateAction(ingressesResource, ingress), &config_v1.Ingress{})
	if obj == nil {
		return nil, err
	}
	return obj.(*config_v1.Ingress), err
}

// Update takes the representation of a ingress and updates it. Returns the server's representation of the ingress, and an error, if there is any.
func (c *FakeIngresses) Update(ingress *config_v1.Ingress) (result *config_v1.Ingress, err error) {
	obj, err := c.Fake.
		Invokes(testing.NewRootUpdateAction(ingressesResource, ingress), &config_v1.Ingress{})
	if obj == nil {
		return nil, err
	}
	return obj.(*config_v1.Ingress), err
}

// UpdateStatus was generated because the type contains a Status member.
// Add a +genclient:noStatus comment above the type to avoid generating UpdateStatus().
func (c *FakeIngresses) UpdateStatus(ingress *config_v1.Ingress) (*config_v1.Ingress, error) {
	obj, err := c.Fake.
		Invokes(testing.NewRootUpdateSubresourceAction(ingressesResource, "status", ingress), &config_v1.Ingress{})
	if obj == nil {
		return nil, err
	}
	return obj.(*config_v1.Ingress), err
}

// Delete takes name of the ingress and deletes it. Returns an error if one occurs.
func (c *FakeIngresses) Delete(name string, options *v1.DeleteOptions) error {
	_, err := c.Fake.
		Invokes(testing.NewRootDeleteAction(ingressesResource, name), &config_v1.Ingress{})
	return err
}

// DeleteCollection deletes a collection of objects.
func (c *FakeIngresses) DeleteCollection(options *v1.DeleteOptions, listOptions v1.ListOptions) error {
	action := testing.NewRootDeleteCollectionAction(ingressesResource, listOptions)

	_, err := c.Fake.Invokes(action, &config_v1.IngressList{})
	return err
}

// Patch applies the patch and returns the patched ingress.
func (c *FakeIngresses) Patch(name string, pt types.PatchType, data []byte, subresources ...string) (result *config_v1.Ingress, err error) {
	obj, err := c.Fake.
		Invokes(testing.NewRootPatchSubresourceAction(ingressesResource, name, data, subresources...), &config_v1.Ingress{})
	if obj == nil {
		return nil, err
	}
	return obj.(*config_v1.Ingress), err
}


text:
import logging
import sys

from PyMaSC import entrypoint, logging_version
from PyMaSC.utils.parsearg import get_precalc_parser
from PyMaSC.utils.logfmt import set_rootlogger
from PyMaSC.utils.progress import ProgressBase
from PyMaSC.handler.mappability import MappabilityHandler

logger = logging.getLogger(__name__)

@entrypoint(logger)
def main():
    # parse aregs
    parser = get_precalc_parser()

    args = parser.parse_args()
    if not args.mappability:
        parser.error("argument -m/--mappable: expected 1 argument(s)")

    # set up logging
    set_rootlogger(args.color, args.log_level)
    logging_version(logger)

    # check args
    if args.mappability_stats and args.mappability_stats == args.mappability:
        args.mappability_stats = None

    #
    if sys.stderr.isatty() and not args.disable_progress:
        ProgressBase.global_switch = True

    #
    alh = MappabilityHandler(args.mappability, args.max_shift, args.max_readlen,
                             args.mappability_stats, args.process)
    alh.calc_mappability()
    alh.save_mappability_stats()
    alh.close()


text:
import { Util, Collection } from '../Util';
import { Factory } from '../Factory';
import { Shape, ShapeConfig } from '../Shape';
import { Path } from './Path';
import { Text, stringToArray } from './Text';
import { getNumberValidator } from '../Validators';
import { _registerNode } from '../Global';

import { GetSet, Vector2d } from '../types';

export interface TextPathConfig extends ShapeConfig {
  text?: string;
  data?: string;
  fontFamily?: string;
  fontSize?: number;
  fontStyle?: string;
}

var EMPTY_STRING = '',
  NORMAL = 'normal';

function _fillFunc(context) {
  context.fillText(this.partialText, 0, 0);
}
function _strokeFunc(context) {
  context.strokeText(this.partialText, 0, 0);
}

/**
 * Path constructor.
 * @author Jason Follas
 * @constructor
 * @memberof Konva
 * @augments Konva.Shape
 * @param {Object} config
 * @param {String} [config.fontFamily] default is Calibri
 * @param {Number} [config.fontSize] default is 12
 * @param {String} [config.fontStyle] can be normal, bold, or italic.  Default is normal
 * @param {String} [config.fontVariant] can be normal or small-caps.  Default is normal
 * @param {String} [config.textBaseline] Can be 'top', 'bottom', 'middle', 'alphabetic', 'hanging'. Default is middle
 * @param {String} config.text
 * @param {String} config.data SVG data string
 * @param {Function} config.getKerning a getter for kerning values for the specified characters
 * @param {Function} config.kerningFunc a getter for kerning values for the specified characters
 * @@shapeParams
 * @@nodeParams
 * @example
 * var kerningPairs = {
 *   'A': {
 *     ' ': -0.05517578125,
 *     'T': -0.07421875,
 *     'V': -0.07421875
 *   }
 *   'V': {
 *     ',': -0.091796875,
 *     ":": -0.037109375,
 *     ";": -0.037109375,
 *     "A": -0.07421875
 *   }
 * }
 * var textpath = new Konva.TextPath({
 *   x: 100,
 *   y: 50,
 *   fill: '#333',
 *   fontSize: '24',
 *   fontFamily: 'Arial',
 *   text: 'All the world\'s a stage, and all the men and women merely players.',
 *   data: 'M10,10 C0,0 10,150 100,100 S300,150 400,50',
 *   kerningFunc(leftChar, rightChar) {
 *     return kerningPairs.hasOwnProperty(leftChar) ? pairs[leftChar][rightChar] || 0 : 0
 *   }
 * });
 */
export class TextPath extends Shape<TextPathConfig> {
  dummyCanvas = Util.createCanvasElement();
  dataArray = [];
  glyphInfo: Array<{
    transposeX: number;
    transposeY: number;
    text: string;
    rotation: number;
    p0: Vector2d;
    p1: Vector2d;
  }>;
  partialText: string;
  textWidth: number;
  textHeight: number;

  constructor(config?: TextPathConfig) {
    // call super constructor
    super(config);

    this.dataArray = Path.parsePathData(this.attrs.data);
    this.on('dataChange.konva', function () {
      this.dataArray = Path.parsePathData(this.attrs.data);
      this._setTextData();
    });

    // update text data for certain attr changes
    this.on(
      'textChange.konva alignChange.konva letterSpacingChange.konva kerningFuncChange.konva',
      this._setTextData
    );

    if (config && config['getKerning']) {
      Util.warn(
        'getKerning TextPath API is deprecated. Please use "kerningFunc" instead.'
      );
      this.kerningFunc(config['getKerning']);
    }

    this._setTextData();
  }

  _sceneFunc(context) {
    context.setAttr('font', this._getContextFont());
    context.setAttr('textBaseline', this.textBaseline());
    context.setAttr('textAlign', 'left');
    context.save();

    var textDecoration = this.textDecoration();
    var fill = this.fill();
    var fontSize = this.fontSize();

    var glyphInfo = this.glyphInfo;
    if (textDecoration === 'underline') {
      context.beginPath();
    }
    for (var i = 0; i < glyphInfo.length; i++) {
      context.save();

      var p0 = glyphInfo[i].p0;

      context.translate(p0.x, p0.y);
      context.rotate(glyphInfo[i].rotation);
      this.partialText = glyphInfo[i].text;

      context.fillStrokeShape(this);
      if (textDecoration === 'underline') {
        if (i === 0) {
          context.moveTo(0, fontSize / 2 + 1);
        }

        context.lineTo(fontSize, fontSize / 2 + 1);
      }
      context.restore();

      //// To assist with debugging visually, uncomment following
      //
      // if (i % 2) context.strokeStyle = 'cyan';
      // else context.strokeStyle = 'green';
      // var p1 = glyphInfo[i].p1;
      // context.moveTo(p0.x, p0.y);
      // context.lineTo(p1.x, p1.y);
      // context.stroke();
    }
    if (textDecoration === 'underline') {
      context.strokeStyle = fill;
      context.lineWidth = fontSize / 20;
      context.stroke();
    }

    context.restore();
  }
  _hitFunc(context) {
    context.beginPath();

    var glyphInfo = this.glyphInfo;
    if (glyphInfo.length >= 1) {
      var p0 = glyphInfo[0].p0;
      context.moveTo(p0.x, p0.y);
    }
    for (var i = 0; i < glyphInfo.length; i++) {
      var p1 = glyphInfo[i].p1;
      context.lineTo(p1.x, p1.y);
    }
    context.setAttr('lineWidth', this.fontSize());
    context.setAttr('strokeStyle', this.colorKey);
    context.stroke();
  }
  /**
   * get text width in pixels
   * @method
   * @name Konva.TextPath#getTextWidth
   */
  getTextWidth() {
    return this.textWidth;
  }
  getTextHeight() {
    Util.warn(
      'text.getTextHeight() method is deprecated. Use text.height() - for full height and text.fontSize() - for one line height.'
    );
    return this.textHeight;
  }
  setText(text) {
    return Text.prototype.setText.call(this, text);
  }

  _getContextFont() {
    return Text.prototype._getContextFont.call(this);
  }

  _getTextSize(text) {
    var dummyCanvas = this.dummyCanvas;
    var _context = dummyCanvas.getContext('2d');

    _context.save();

    _context.font = this._getContextFont();
    var metrics = _context.measureText(text);

    _context.restore();

    return {
      width: metrics.width,
      height: parseInt(this.attrs.fontSize, 10),
    };
  }
  _setTextData() {
    var that = this;
    var size = this._getTextSize(this.attrs.text);
    var letterSpacing = this.letterSpacing();
    var align = this.align();
    var kerningFunc = this.kerningFunc();

    this.textWidth = size.width;
    this.textHeight = size.height;

    var textFullWidth = Math.max(
      this.textWidth + ((this.attrs.text || '').length - 1) * letterSpacing,
      0
    );

    this.glyphInfo = [];

    var fullPathWidth = 0;
    for (var l = 0; l < that.dataArray.length; l++) {
      if (that.dataArray[l].pathLength > 0) {
        fullPathWidth += that.dataArray[l].pathLength;
      }
    }

    var offset = 0;
    if (align === 'center') {
      offset = Math.max(0, fullPathWidth / 2 - textFullWidth / 2);
    }
    if (align === 'right') {
      offset = Math.max(0, fullPathWidth - textFullWidth);
    }

    var charArr = stringToArray(this.text());
    var spacesNumber = this.text().split(' ').length - 1;

    var p0, p1, pathCmd;

    var pIndex = -1;
    var currentT = 0;
    // var sumLength = 0;
    // for(var j = 0; j < that.dataArray.length; j++) {
    //   if(that.dataArray[j].pathLength > 0) {
    //
    //     if (sumLength + that.dataArray[j].pathLength > offset) {}
    //       fullPathWidth += that.dataArray[j].pathLength;
    //   }
    // }

    var getNextPathSegment = function () {
      currentT = 0;
      var pathData = that.dataArray;

      for (var j = pIndex + 1; j < pathData.length; j++) {
        if (pathData[j].pathLength > 0) {
          pIndex = j;

          return pathData[j];
        } else if (pathData[j].command === 'M') {
          p0 = {
            x: pathData[j].points[0],
            y: pathData[j].points[1],
          };
        }
      }

      return {};
    };

    var findSegmentToFitCharacter = function (c) {
      var glyphWidth = that._getTextSize(c).width + letterSpacing;

      if (c === ' ' && align === 'justify') {
        glyphWidth += (fullPathWidth - textFullWidth) / spacesNumber;
      }

      var currLen = 0;
      var attempts = 0;

      p1 = undefined;
      while (
        Math.abs(glyphWidth - currLen) / glyphWidth > 0.01 &&
        attempts < 20
      ) {
        attempts++;
        var cumulativePathLength = currLen;
        while (pathCmd === undefined) {
          pathCmd = getNextPathSegment();

          if (
            pathCmd &&
            cumulativePathLength + pathCmd.pathLength < glyphWidth
          ) {
            cumulativePathLength += pathCmd.pathLength;
            pathCmd = undefined;
          }
        }

        if (pathCmd === {} || p0 === undefined) {
          return undefined;
        }

        var needNewSegment = false;

        switch (pathCmd.command) {
          case 'L':
            if (
              Path.getLineLength(
                p0.x,
                p0.y,
                pathCmd.points[0],
                pathCmd.points[1]
              ) > glyphWidth
            ) {
              p1 = Path.getPointOnLine(
                glyphWidth,
                p0.x,
                p0.y,
                pathCmd.points[0],
                pathCmd.points[1],
                p0.x,
                p0.y
              );
            } else {
              pathCmd = undefined;
            }
            break;
          case 'A':
            var start = pathCmd.points[4];
            // 4 = theta
            var dTheta = pathCmd.points[5];
            // 5 = dTheta
            var end = pathCmd.points[4] + dTheta;

            if (currentT === 0) {
              currentT = start + 0.00000001;
            } else if (glyphWidth > currLen) {
              // Just in case start is 0
              currentT += ((Math.PI / 180.0) * dTheta) / Math.abs(dTheta);
            } else {
              currentT -= ((Math.PI / 360.0) * dTheta) / Math.abs(dTheta);
            }

            // Credit for bug fix: @therth https://github.com/ericdrowell/KonvaJS/issues/249
            // Old code failed to render text along arc of this path: "M 50 50 a 150 50 0 0 1 250 50 l 50 0"
            if (
              (dTheta < 0 && currentT < end) ||
              (dTheta >= 0 && currentT > end)
            ) {
              currentT = end;
              needNewSegment = true;
            }
            p1 = Path.getPointOnEllipticalArc(
              pathCmd.points[0],
              pathCmd.points[1],
              pathCmd.points[2],
              pathCmd.points[3],
              currentT,
              pathCmd.points[6]
            );
            break;
          case 'C':
            if (currentT === 0) {
              if (glyphWidth > pathCmd.pathLength) {
                currentT = 0.00000001;
              } else {
                currentT = glyphWidth / pathCmd.pathLength;
              }
            } else if (glyphWidth > currLen) {
              currentT += (glyphWidth - currLen) / pathCmd.pathLength / 2;
            } else {
              currentT = Math.max(
                currentT - (currLen - glyphWidth) / pathCmd.pathLength / 2,
                0
              );
            }

            if (currentT > 1.0) {
              currentT = 1.0;
              needNewSegment = true;
            }
            p1 = Path.getPointOnCubicBezier(
              currentT,
              pathCmd.start.x,
              pathCmd.start.y,
              pathCmd.points[0],
              pathCmd.points[1],
              pathCmd.points[2],
              pathCmd.points[3],
              pathCmd.points[4],
              pathCmd.points[5]
            );
            break;
          case 'Q':
            if (currentT === 0) {
              currentT = glyphWidth / pathCmd.pathLength;
            } else if (glyphWidth > currLen) {
              currentT += (glyphWidth - currLen) / pathCmd.pathLength;
            } else {
              currentT -= (currLen - glyphWidth) / pathCmd.pathLength;
            }

            if (currentT > 1.0) {
              currentT = 1.0;
              needNewSegment = true;
            }
            p1 = Path.getPointOnQuadraticBezier(
              currentT,
              pathCmd.start.x,
              pathCmd.start.y,
              pathCmd.points[0],
              pathCmd.points[1],
              pathCmd.points[2],
              pathCmd.points[3]
            );
            break;
        }

        if (p1 !== undefined) {
          currLen = Path.getLineLength(p0.x, p0.y, p1.x, p1.y);
        }

        if (needNewSegment) {
          needNewSegment = false;
          pathCmd = undefined;
        }
      }
    };

    // fake search for offset, this is the best approach
    var testChar = 'C';
    var glyphWidth = that._getTextSize(testChar).width + letterSpacing;
    var lettersInOffset = offset / glyphWidth - 1;
    // the idea is simple
    // try to draw testChar until we fill offset
    for (var k = 0; k < lettersInOffset; k++) {
      findSegmentToFitCharacter(testChar);
      if (p0 === undefined || p1 === undefined) {
        break;
      }
      p0 = p1;
    }

    for (var i = 0; i < charArr.length; i++) {
      // Find p1 such that line segment between p0 and p1 is approx. width of glyph
      findSegmentToFitCharacter(charArr[i]);

      if (p0 === undefined || p1 === undefined) {
        break;
      }

      var width = Path.getLineLength(p0.x, p0.y, p1.x, p1.y);

      var kern = 0;
      if (kerningFunc) {
        try {
          // getKerning is a user provided getter. Make sure it never breaks our logic
          kern = kerningFunc(charArr[i - 1], charArr[i]) * this.fontSize();
        } catch (e) {
          kern = 0;
        }
      }

      p0.x += kern;
      p1.x += kern;
      this.textWidth += kern;

      var midpoint = Path.getPointOnLine(
        kern + width / 2.0,
        p0.x,
        p0.y,
        p1.x,
        p1.y
      );

      var rotation = Math.atan2(p1.y - p0.y, p1.x - p0.x);
      this.glyphInfo.push({
        transposeX: midpoint.x,
        transposeY: midpoint.y,
        text: charArr[i],
        rotation: rotation,
        p0: p0,
        p1: p1,
      });
      p0 = p1;
    }
  }
  getSelfRect() {
    if (!this.glyphInfo.length) {
      return {
        x: 0,
        y: 0,
        width: 0,
        height: 0,
      };
    }
    var points = [];

    this.glyphInfo.forEach(function (info) {
      points.push(info.p0.x);
      points.push(info.p0.y);
      points.push(info.p1.x);
      points.push(info.p1.y);
    });
    var minX = points[0] || 0;
    var maxX = points[0] || 0;
    var minY = points[1] || 0;
    var maxY = points[1] || 0;
    var x, y;
    for (var i = 0; i < points.length / 2; i++) {
      x = points[i * 2];
      y = points[i * 2 + 1];
      minX = Math.min(minX, x);
      maxX = Math.max(maxX, x);
      minY = Math.min(minY, y);
      maxY = Math.max(maxY, y);
    }
    var fontSize = this.fontSize();
    return {
      x: minX - fontSize / 2,
      y: minY - fontSize / 2,
      width: maxX - minX + fontSize,
      height: maxY - minY + fontSize,
    };
  }

  fontFamily: GetSet<string, this>;
  fontSize: GetSet<number, this>;
  fontStyle: GetSet<string, this>;
  fontVariant: GetSet<string, this>;
  align: GetSet<string, this>;
  letterSpacing: GetSet<number, this>;
  text: GetSet<string, this>;
  data: GetSet<string, this>;

  kerningFunc: GetSet<(leftChar: string, rightChar: string) => number, this>;
  textBaseline: GetSet<string, this>;
  textDecoration: GetSet<string, this>;
}

TextPath.prototype._fillFunc = _fillFunc;
TextPath.prototype._strokeFunc = _strokeFunc;
TextPath.prototype._fillFuncHit = _fillFunc;
TextPath.prototype._strokeFuncHit = _strokeFunc;
TextPath.prototype.className = 'TextPath';
TextPath.prototype._attrsAffectingSize = ['text', 'fontSize', 'data'];
_registerNode(TextPath);

/**
 * get/set SVG path data string.  This method
 *  also automatically parses the data string
 *  into a data array.  Currently supported SVG data:
 *  M, m, L, l, H, h, V, v, Q, q, T, t, C, c, S, s, A, a, Z, z
 * @name Konva.TextPath#data
 * @method
 * @param {String} data svg path string
 * @returns {String}
 * @example
 * // get data
 * var data = shape.data();
 *
 * // set data
 * shape.data('M200,100h100v50z');
 */
Factory.addGetterSetter(TextPath, 'data');

/**
 * get/set font family
 * @name Konva.TextPath#fontFamily
 * @method
 * @param {String} fontFamily
 * @returns {String}
 * @example
 * // get font family
 * var fontFamily = shape.fontFamily();
 *
 * // set font family
 * shape.fontFamily('Arial');
 */
Factory.addGetterSetter(TextPath, 'fontFamily', 'Arial');

/**
 * get/set font size in pixels
 * @name Konva.TextPath#fontSize
 * @method
 * @param {Number} fontSize
 * @returns {Number}
 * @example
 * // get font size
 * var fontSize = shape.fontSize();
 *
 * // set font size to 22px
 * shape.fontSize(22);
 */

Factory.addGetterSetter(TextPath, 'fontSize', 12, getNumberValidator());

/**
 * get/set font style.  Can be 'normal', 'italic', or 'bold'.  'normal' is the default.
 * @name Konva.TextPath#fontStyle
 * @method
 * @param {String} fontStyle
 * @returns {String}
 * @example
 * // get font style
 * var fontStyle = shape.fontStyle();
 *
 * // set font style
 * shape.fontStyle('bold');
 */

Factory.addGetterSetter(TextPath, 'fontStyle', NORMAL);

/**
 * get/set horizontal align of text.  Can be 'left', 'center', 'right' or 'justify'
 * @name Konva.TextPath#align
 * @method
 * @param {String} align
 * @returns {String}
 * @example
 * // get text align
 * var align = text.align();
 *
 * // center text
 * text.align('center');
 *
 * // align text to right
 * text.align('right');
 */
Factory.addGetterSetter(TextPath, 'align', 'left');

/**
 * get/set letter spacing.  The default is 0.
 * @name Konva.TextPath#letterSpacing
 * @method
 * @param {Number} letterSpacing
 * @returns {Number}
 * @example
 * // get line height
 * var letterSpacing = shape.letterSpacing();
 *
 * // set the line height
 * shape.letterSpacing(2);
 */

Factory.addGetterSetter(TextPath, 'letterSpacing', 0, getNumberValidator());

/**
 * get/set text baseline.  The default is 'middle'. Can be 'top', 'bottom', 'middle', 'alphabetic', 'hanging'
 * @name Konva.TextPath#textBaseline
 * @method
 * @param {String} textBaseline
 * @returns {String}
 * @example
 * // get line height
 * var textBaseline = shape.textBaseline();
 *
 * // set the line height
 * shape.textBaseline('top');
 */
Factory.addGetterSetter(TextPath, 'textBaseline', 'middle');

/**
 * get/set font variant.  Can be 'normal' or 'small-caps'.  'normal' is the default.
 * @name Konva.TextPath#fontVariant
 * @method
 * @param {String} fontVariant
 * @returns {String}
 * @example
 * // get font variant
 * var fontVariant = shape.fontVariant();
 *
 * // set font variant
 * shape.fontVariant('small-caps');
 */
Factory.addGetterSetter(TextPath, 'fontVariant', NORMAL);

/**
 * get/set text
 * @name Konva.TextPath#getText
 * @method
 * @param {String} text
 * @returns {String}
 * @example
 * // get text
 * var text = text.text();
 *
 * // set text
 * text.text('Hello world!');
 */
Factory.addGetterSetter(TextPath, 'text', EMPTY_STRING);

/**
 * get/set text decoration of a text.  Can be '' or 'underline'.
 * @name Konva.TextPath#textDecoration
 * @method
 * @param {String} textDecoration
 * @returns {String}
 * @example
 * // get text decoration
 * var textDecoration = shape.textDecoration();
 *
 * // underline text
 * shape.textDecoration('underline');
 */
Factory.addGetterSetter(TextPath, 'textDecoration', null);

/**
 * get/set kerning function.
 * @name Konva.TextPath#kerningFunc
 * @method
 * @param {String} kerningFunc
 * @returns {String}
 * @example
 * // get text decoration
 * var kerningFunc = text.kerningFunc();
 *
 * // center text
 * text.kerningFunc(function(leftChar, rightChar) {
 *   return 1;
 * });
 */
Factory.addGetterSetter(TextPath, 'kerningFunc', null);

Collection.mapMethods(TextPath);


text:
.PHONY: all test

all: test

test:
	python setup.py test


text:
import {
    isBlock,
    isIfStatement,
    isIterationStatement,
    isSameLine,
} from "tsutils";
import * as ts from "typescript";
import * as Lint from "../index";
import { codeExamples } from "./code-examples/curly.examples";

const OPTION_AS_NEEDED = "as-needed";
const OPTION_IGNORE_SAME_LINE = "ignore-same-line";

interface Options {
    ignoreSameLine: boolean;
}

export class Rule extends Lint.Rules.AbstractRule {
    /* tslint:disable:object-literal-sort-keys */
    public static metadata: Lint.IRuleMetadata = {
        ruleName: "curly",
        description: "Enforces braces for `if`/`for`/`do`/`while` statements.",
        rationale: Lint.Utils.dedent`
            \`\`\`ts
            if (foo === bar)
                foo++;
                bar++;
            \`\`\`

            In the code above, the author almost certainly meant for both \`foo++\` and \`bar++\`
            to be executed only if \`foo === bar\`. However, they forgot braces and \`bar++\` will be executed
            no matter what. This rule could prevent such a mistake.`,
        optionsDescription: Lint.Utils.dedent`
            One of the following options may be provided:

            * \`"${OPTION_AS_NEEDED}"\` forbids any unnecessary curly braces.
            * \`"${OPTION_IGNORE_SAME_LINE}"\` skips checking braces for control-flow statements
            that are on one line and start on the same line as their control-flow keyword
        `,
        options: {
            type: "array",
            items: {
                type: "string",
                enum: [
                    OPTION_AS_NEEDED,
                    OPTION_IGNORE_SAME_LINE,
                ],
            },
        },
        optionExamples: [
            true,
            [true, OPTION_IGNORE_SAME_LINE],
            [true, OPTION_AS_NEEDED],
        ],
        type: "functionality",
        typescriptOnly: false,
        hasFix: true,
        codeExamples,
    };
    /* tslint:enable:object-literal-sort-keys */

    public static FAILURE_STRING_AS_NEEDED = "Block contains only one statement; remove the curly braces.";
    public static FAILURE_STRING_FACTORY(kind: string) {
        return `${kind} statements must be braced`;
    }

    public apply(sourceFile: ts.SourceFile): Lint.RuleFailure[] {
        if (this.ruleArguments.indexOf(OPTION_AS_NEEDED) !== -1) {
            return this.applyWithFunction(sourceFile, walkAsNeeded);
        }

        return this.applyWithWalker(new CurlyWalker(sourceFile, this.ruleName, {
            ignoreSameLine: this.ruleArguments.indexOf(OPTION_IGNORE_SAME_LINE) !== -1,
        }));
    }
}

function walkAsNeeded(ctx: Lint.WalkContext<void>): void {
    ts.forEachChild(ctx.sourceFile, function cb(node) {
        if (isBlock(node) && isBlockUnnecessary(node)) {
            ctx.addFailureAt(node.statements.pos - 1, 1, Rule.FAILURE_STRING_AS_NEEDED);
        }
        ts.forEachChild(node, cb);
    });
}

function isBlockUnnecessary(node: ts.Block): boolean {
    const parent = node.parent!;
    if (node.statements.length !== 1) { return false; }
    const statement = node.statements[0];
    if (isIterationStatement(parent)) { return true; }
    /*
    Watch out for this case:
    if (so) {
        if (also)
            foo();
    } else
        bar();
    */
    return isIfStatement(parent) && !(isIfStatement(statement)
        && statement.elseStatement === undefined
        && parent.thenStatement === node
        && parent.elseStatement !== undefined);
}

class CurlyWalker extends Lint.AbstractWalker<Options> {
    public walk(sourceFile: ts.SourceFile) {
        const cb = (node: ts.Node): void => {
            if (isIterationStatement(node)) {
                this.checkStatement(node.statement, node, 0, node.end);
            } else if (isIfStatement(node)) {
                this.checkStatement(node.thenStatement, node, 0);
                if (node.elseStatement !== undefined && node.elseStatement.kind !== ts.SyntaxKind.IfStatement) {
                    this.checkStatement(node.elseStatement, node, 5);
                }
            }
            return ts.forEachChild(node, cb);
        };
        return ts.forEachChild(sourceFile, cb);
    }

    private checkStatement(statement: ts.Statement, node: ts.IterationStatement | ts.IfStatement, childIndex: number, end = statement.end) {
        const sameLine = isSameLine(this.sourceFile, statement.pos, statement.end);
        if (statement.kind !== ts.SyntaxKind.Block &&
            !(this.options.ignoreSameLine && sameLine)) {
            const token = node.getChildAt(childIndex, this.sourceFile);
            const tokenText = ts.tokenToString(token.kind)!;
            this.addFailure(
                token.end - tokenText.length, end, Rule.FAILURE_STRING_FACTORY(tokenText),
                this.createMissingBraceFix(statement, node, sameLine));
        }
    }

    /** Generate the necessary replacement to add braces to a statement that needs them. */
    private createMissingBraceFix(statement: ts.Statement, node: ts.IterationStatement | ts.IfStatement, sameLine: boolean) {
        if (sameLine) {
            return [
                Lint.Replacement.appendText(statement.pos, " {"),
                Lint.Replacement.appendText(statement.end, " }"),
            ];
        } else {
            const match = /\n([\t ])/.exec(node.getFullText(this.sourceFile)); // determine which character to use (tab or space)
            const indentation = match === null ?
                "" :
                // indentation should match start of statement
                match[1].repeat(ts.getLineAndCharacterOfPosition(this.sourceFile, node.getStart(this.sourceFile)).character);

            const maybeCarriageReturn = this.sourceFile.text[this.sourceFile.getLineEndOfPosition(node.pos) - 1] === "\r" ? "\r" : "";

            return [
                Lint.Replacement.appendText(statement.pos, " {"),
                Lint.Replacement.appendText(statement.end, `${maybeCarriageReturn}\n${indentation}}`),
            ];
        }
    }
}


text:
package com.suscipio_solutions.consecro_mud.Abilities.Prayers;
import java.util.Vector;

import com.suscipio_solutions.consecro_mud.Abilities.interfaces.Ability;
import com.suscipio_solutions.consecro_mud.Common.interfaces.CMMsg;
import com.suscipio_solutions.consecro_mud.Items.interfaces.DeadBody;
import com.suscipio_solutions.consecro_mud.Items.interfaces.Item;
import com.suscipio_solutions.consecro_mud.Locales.interfaces.Room;
import com.suscipio_solutions.consecro_mud.MOBS.interfaces.MOB;
import com.suscipio_solutions.consecro_mud.core.CMClass;
import com.suscipio_solutions.consecro_mud.core.CMLib;
import com.suscipio_solutions.consecro_mud.core.CMProps;
import com.suscipio_solutions.consecro_mud.core.interfaces.Physical;
import com.suscipio_solutions.consecro_mud.core.interfaces.Tickable;

@SuppressWarnings("rawtypes")
public class Prayer_Haunted extends Prayer
{
	@Override public String ID() { return "Prayer_Haunted"; }
	private final static String localizedName = CMLib.lang().L("Haunted");
	@Override public String name() { return localizedName; }
	private final static String localizedStaticDisplay = CMLib.lang().L("(Haunted)");
	@Override public String displayText() { return localizedStaticDisplay; }
	@Override protected int canAffectCode(){return Ability.CAN_ROOMS;}
	@Override protected int canTargetCode(){return Ability.CAN_ROOMS;}
	@Override public int abstractQuality(){ return Ability.QUALITY_MALICIOUS;}
	@Override public int classificationCode(){return Ability.ACODE_PRAYER|Ability.DOMAIN_DEATHLORE;}
	@Override public long flags(){return Ability.FLAG_UNHOLY;}
	protected int level=14;
	protected int numDone=0;
	protected int numMax=Integer.MAX_VALUE;

	@Override
	public void unInvoke()
	{
		// undo the affects of this spell
		if((affected==null)||(!(affected instanceof Room)))
		{
			super.unInvoke();
			return;
		}
		final Room  R=(Room)affected;

		super.unInvoke();

		if((canBeUninvoked())&&(R!=null))
		   R.showHappens(CMMsg.MSG_OK_VISUAL,L("The haunted aura fades."));
	}

	@Override
	public boolean tick(Tickable ticking, int tickID)
	{
		if((affected!=null)&&(affected instanceof Room)&&(numDone<numMax))
		{
			final Room R=(Room)affected;
			DeadBody B=null;
			for(int i=0;i<R.numItems();i++)
			{
				final Item I=R.getItem(i);
				if((I instanceof DeadBody)
				&&(I.container()==null)
				&&(!((DeadBody)I).playerCorpse())
				&&(((DeadBody)I).mobName().length()>0))
				{
					B=(DeadBody)I;
					break;
				}
			}
			if(B!=null)
			{
				new Prayer_AnimateGhost().makeGhostFrom(R,B,null,level);
				B.destroy();
				level+=5;
				numDone++;
			}
		}
		return super.tick(ticking,tickID);
	}

	@Override
	public boolean invoke(MOB mob, Vector commands, Physical givenTarget, boolean auto, int asLevel)
	{
		final Room target=mob.location();
		if(target==null) return false;
		if(target.fetchEffect(ID())!=null)
		{
			mob.tell(L("This place is already haunted."));
			return false;
		}

		if(!super.invoke(mob,commands,givenTarget,auto,asLevel))
			return false;

		final boolean success=proficiencyCheck(mob,0,auto);

		if(success)
		{
			// it worked, so build a copy of this ability,
			// and add it to the affects list of the
			// affected MOB.  Then tell everyone else
			// what happened.
			final CMMsg msg=CMClass.getMsg(mob,target,this,verbalCastCode(mob,target,auto),auto?"":L("^S<S-NAME> @x1 to haunt this place.^?",prayWord(mob)));
			if(mob.location().okMessage(mob,msg))
			{
				mob.location().send(mob,msg);
				level=14;
				numDone=0;
				numMax=(mob.phyStats().level()+(2*super.getXLEVELLevel(mob)))/8;
				if(CMLib.law().doesOwnThisProperty(mob,target))
				{
					target.addNonUninvokableEffect((Ability)this.copyOf());
					CMLib.database().DBUpdateRoom(target);
				}
				else
					beneficialAffect(mob,target,asLevel,(CMProps.getIntVar(CMProps.Int.TICKSPERMUDMONTH)));
			}
		}
		else
			return beneficialWordsFizzle(mob,target,L("<S-NAME> @x1 for a haunting, but <S-HIS-HER> plea is not answered.",prayWord(mob)));

		// return whether it worked
		return success;
	}
}


text:
	.global BulbPixels
	.global BulbPixelsSize

	.global AudioPixels
	.global AudioPixelsSize

	.global FlagPixels
	.global FlagPixelsSize

	.global DocPixels
	.global DocPixelsSize

	.global GlobePixels
	.global GlobePixelsSize

BulbPixels:
	.incbin "lzg/ili9481/bulb.ili9481.64.lzg"
	BulbPixelsSize=.-BulbPixels

AudioPixels:
	.incbin "lzg/ili9481/audio.ili9481.64.lzg"
	AudioPixelsSize=.-AudioPixels

FlagPixels:
	.incbin "lzg/ili9481/flag.ili9481.64.lzg"
	FlagPixelsSize=.-FlagPixels

DocPixels:
	.incbin "lzg/ili9481/doc.ili9481.64.lzg"
	DocPixelsSize=.-DocPixels

GlobePixels:
	.incbin "lzg/ili9481/globe.ili9481.64.lzg"
	GlobePixelsSize=.-GlobePixels


text:
package com.design.patterns.creational.abstractfactory;

public class KDEUIFactory extends UIFactory {

	class KDEWindow implements Window {

		@Override
		public void draw() {
			System.out.println("KDE Window :: draw()");
		}
	}

	class KDEScrollBar implements ScrollBar {

		@Override
		public void draw() {
			System.out.println("KDE ScrollBar :: draw()");
		}
	}

	@Override
	public Window getWindow() {
		return new KDEWindow();
	}

	@Override
	public ScrollBar getScrollBar() {
		return new KDEScrollBar();
	}

}


text:
#include "testing/gunit.h"
#include <boost/lexical_cast.hpp>
#include <boost/uuid/uuid.hpp>
#include <boost/uuid/random_generator.hpp>

#include <base/logging.h>
#include <sandesh/sandesh_message_builder.h>

#include "../viz_message.h"
#include "collector_uve_types.h"

using namespace pugi;

class VizMessageTest : public ::testing::Test {
public:
    VizMessageTest() :
        builder_(SandeshXMLMessageTestBuilder::GetInstance()) {
    }

    virtual void SetUp() {
    }

    virtual void TearDown() {
    }

    class SandeshXMLMessageTest : public SandeshXMLMessage {
    public:
        SandeshXMLMessageTest() {}
        virtual ~SandeshXMLMessageTest() {}

        virtual bool Parse(const uint8_t *xml_msg, size_t size) {
            xml_parse_result result = xdoc_.load_buffer(xml_msg, size,
                parse_default & ~parse_escapes);
            if (!result) {
                LOG(ERROR, __func__ << ": Unable to load Sandesh XML Test." <<
                    "(status=" << result.status << ", offset=" <<
                    result.offset << "): " << xml_msg);
                return false;
            }
            message_node_ = xdoc_.first_child();
            message_type_ = message_node_.name();
            size_ = size;
            return true;
        }

        void SetHeader(const SandeshHeader &header) { header_ = header; }
    };

    class SandeshXMLMessageTestBuilder : public SandeshMessageBuilder {
    public:
        SandeshXMLMessageTestBuilder() {}

        virtual SandeshMessage *Create(const uint8_t *xml_msg,
            size_t size) const {
            SandeshXMLMessageTest *msg = new SandeshXMLMessageTest;
            msg->Parse(xml_msg, size);
            return msg;
        }

        static SandeshXMLMessageTestBuilder *GetInstance() {
            return &instance_;
        }

    private:
        static SandeshXMLMessageTestBuilder instance_;
    };

protected:
    SandeshMessageBuilder *builder_;
    boost::uuids::random_generator rgen_;
    VizMsgStatistics stats_;
};

VizMessageTest::SandeshXMLMessageTestBuilder
    VizMessageTest::SandeshXMLMessageTestBuilder::instance_;

TEST_F(VizMessageTest, RuleMsg) {
    SandeshHeader hdr;
    std::string xmlmessage = "<Sandesh><VNSwitchErrorMsg type=\"sandesh\"><length type=\"i32\">0000000020</length><field1 type=\"string\">field1_value</field1><field2 type=\"struct\"><field21 type=\"i16\">21</field21><field22 type=\"string\">string22</field22></field2><field3 type=\"i32\">3</field3></VNSwitchErrorMsg></Sandesh>";
    boost::uuids::uuid unm(rgen_());
    SandeshXMLMessageTest *msg = dynamic_cast<SandeshXMLMessageTest *>(
        builder_->Create(
        reinterpret_cast<const uint8_t *>(xmlmessage.c_str()),
        xmlmessage.size()));
    msg->SetHeader(hdr);
    VizMsg vmsgp(msg, unm);
    RuleMsg rmsg(&vmsgp);
    int ret;
    std::string type, value;

    ret = rmsg.field_value("field2.field21", type, value);
    EXPECT_EQ(ret, 0);
    EXPECT_EQ(type, "i16");
    EXPECT_EQ(boost::lexical_cast<int>(value), boost::lexical_cast<int>("21"));

    ret = rmsg.field_value("field2.field22", type, value);
    EXPECT_EQ(ret, 0);
    EXPECT_EQ(type, "string");
    EXPECT_EQ(value, "string22");

    ret = rmsg.field_value("field3", type, value);
    EXPECT_EQ(ret, 0);
    EXPECT_EQ(type, "i32");
    EXPECT_EQ(boost::lexical_cast<int>(value), boost::lexical_cast<int>("003"));

    RuleMsg::RuleMsgPredicate p1("First");
    p1 = std::string("Second");
    EXPECT_EQ(p1.tmp_, "Second");

    vmsgp.msg = NULL;
    delete msg;
}

TEST_F(VizMessageTest, Stats) {
    // Send SYSTEM sandesh at SYS_DEBUG
    SandeshHeader hdr;
    hdr.set_Level(static_cast<int32_t>(SandeshLevel::SYS_DEBUG));
    hdr.set_Type(SandeshType::SYSTEM);
    std::string xmlmessage = "<VNSwitchErrorMsg type=\"sandesh\"><length type=\"i32\">0000000020</length><field1 type=\"string\">field1_value</field1><field2 type=\"struct\"><field21 type=\"i16\">21</field21><field22 type=\"string\">string22</field22></field2><field3 type=\"i32\">3</field3></VNSwitchErrorMsg>";
    boost::uuids::uuid unm(rgen_());
    SandeshXMLMessageTest *msg = dynamic_cast<SandeshXMLMessageTest *>(
        builder_->Create(
        reinterpret_cast<const uint8_t *>(xmlmessage.c_str()),
        xmlmessage.size()));
    msg->SetHeader(hdr);
    VizMsg vmsgp(msg, unm);
    // Update stats
    stats_.Update(&vmsgp);
    // Verify Gets - SandeshStats, SandeshLogLevelStats, SandeshMessageInfo
    std::vector<SandeshStats> vsstats;
    stats_.Get(vsstats);
    ASSERT_EQ(1, vsstats.size());
    EXPECT_STREQ("VNSwitchErrorMsg", vsstats[0].get_message_type().c_str());
    EXPECT_EQ(1, vsstats[0].get_messages());
    EXPECT_EQ(xmlmessage.size(), vsstats[0].get_bytes());
    vsstats.clear();
    std::vector<SandeshLogLevelStats> vsllstats;
    stats_.Get(vsllstats);
    ASSERT_EQ(1, vsllstats.size());
    EXPECT_STREQ("SYS_DEBUG", vsllstats[0].get_level().c_str());
    EXPECT_EQ(1, vsllstats[0].get_messages());
    EXPECT_EQ(xmlmessage.size(), vsllstats[0].get_bytes());
    vsllstats.clear();
    std::vector<SandeshMessageInfo> vsmi;
    stats_.Get(vsmi);
    ASSERT_EQ(1, vsmi.size());
    EXPECT_STREQ("VNSwitchErrorMsg", vsmi[0].get_type().c_str());
    EXPECT_STREQ("SYS_DEBUG", vsmi[0].get_level().c_str());
    EXPECT_EQ(1, vsmi[0].get_messages());
    EXPECT_EQ(xmlmessage.size(), vsmi[0].get_bytes());
    vsmi.clear();
    // Send same message, update stats
    stats_.Update(&vmsgp);
    // Verify updates
    stats_.Get(vsstats);
    ASSERT_EQ(1, vsstats.size());
    EXPECT_STREQ("VNSwitchErrorMsg", vsstats[0].get_message_type().c_str());
    EXPECT_EQ(2, vsstats[0].get_messages());
    EXPECT_EQ(xmlmessage.size() * 2, vsstats[0].get_bytes());
    vsstats.clear();
    stats_.Get(vsllstats);
    ASSERT_EQ(1, vsllstats.size());
    EXPECT_STREQ("SYS_DEBUG", vsllstats[0].get_level().c_str());
    EXPECT_EQ(2, vsllstats[0].get_messages());
    EXPECT_EQ(xmlmessage.size() * 2, vsllstats[0].get_bytes());
    vsllstats.clear();
    stats_.Get(vsmi);
    ASSERT_EQ(1, vsmi.size());
    EXPECT_STREQ("VNSwitchErrorMsg", vsmi[0].get_type().c_str());
    EXPECT_STREQ("SYS_DEBUG", vsmi[0].get_level().c_str());
    // Diffs
    EXPECT_EQ(1, vsmi[0].get_messages());
    EXPECT_EQ(xmlmessage.size(), vsmi[0].get_bytes());
    vsmi.clear();
    // Delete message
    vmsgp.msg = NULL;
    delete msg;
    msg = NULL;
    // Send OBJECT sandesh at SYS_INVALID
    hdr.set_Level(static_cast<int32_t>(SandeshLevel::INVALID));
    hdr.set_Type(SandeshType::OBJECT);
    std::string xmlmessage_object = "<VNSwitchErrorMsgObject type=\"sandesh\"><length type=\"i32\">0000000020</length><field1 type=\"string\">field1_value</field1><field2 type=\"struct\"><field21 type=\"i16\">21</field21><field22 type=\"string\">string22</field22></field2><field3 type=\"i32\">3</field3></VNSwitchErrorMsgObject>";
    unm = rgen_();
    msg = dynamic_cast<SandeshXMLMessageTest *>(
        builder_->Create(
        reinterpret_cast<const uint8_t *>(xmlmessage_object.c_str()),
        xmlmessage_object.size()));
    msg->SetHeader(hdr);
    VizMsg vmsgp_object(msg, unm);
    // Update stats
    stats_.Update(&vmsgp_object);
    // Verify Gets - SandeshStats, SandeshLogLevelStats, SandeshMessageInfo
    stats_.Get(vsstats);
    ASSERT_EQ(2, vsstats.size());
    EXPECT_STREQ("VNSwitchErrorMsg", vsstats[0].get_message_type().c_str());
    EXPECT_STREQ("VNSwitchErrorMsgObject", vsstats[1].get_message_type().c_str());
    EXPECT_EQ(2, vsstats[0].get_messages());
    EXPECT_EQ(1, vsstats[1].get_messages());
    EXPECT_EQ(xmlmessage.size() * 2, vsstats[0].get_bytes());
    EXPECT_EQ(xmlmessage_object.size(), vsstats[1].get_bytes());
    vsstats.clear();
    // Only SYSTEM and SYSLOG have level
    stats_.Get(vsllstats);
    ASSERT_EQ(1, vsllstats.size());
    EXPECT_STREQ("SYS_DEBUG", vsllstats[0].get_level().c_str());
    EXPECT_EQ(2, vsllstats[0].get_messages());
    EXPECT_EQ(xmlmessage.size() * 2, vsllstats[0].get_bytes());
    vsllstats.clear();
    stats_.Get(vsmi);
    ASSERT_EQ(2, vsmi.size());
    EXPECT_STREQ("VNSwitchErrorMsg", vsmi[0].get_type().c_str());
    EXPECT_STREQ("SYS_DEBUG", vsmi[0].get_level().c_str());
    // Diffs
    EXPECT_EQ(0, vsmi[0].get_messages());
    EXPECT_EQ(0, vsmi[0].get_bytes());
    EXPECT_STREQ("VNSwitchErrorMsgObject", vsmi[1].get_type().c_str());
    EXPECT_STREQ("INVALID", vsmi[1].get_level().c_str());
    EXPECT_EQ(1, vsmi[1].get_messages());
    EXPECT_EQ(xmlmessage_object.size(), vsmi[1].get_bytes());
    vsmi.clear();
    // Delete message
    vmsgp_object.msg = NULL;
    delete msg;
    msg = NULL;
}

int main(int argc, char **argv) {
    LoggingInit();
    ::testing::InitGoogleTest(&argc, argv);
    return RUN_ALL_TESTS();
}


text:
package de.hshannover.f4.trust.iron.mapserver.datamodel.identifiers;

import org.w3c.dom.Document;

import de.hshannover.f4.trust.iron.mapserver.datamodel.DataModelService;
import de.hshannover.f4.trust.iron.mapserver.datamodel.SimpleSearchAbleImpl;
import de.hshannover.f4.trust.iron.mapserver.exceptions.SystemErrorException;
import de.hshannover.f4.trust.iron.mapserver.provider.DataModelServerConfigurationProvider;
import de.hshannover.f4.trust.iron.mapserver.utils.NullCheck;

/**
 * @since 0.3.0
 * @author aw
 */
abstract class IdentifierImpl extends SimpleSearchAbleImpl implements Identifier {

	private final String mIdentifierType;

	private String mPrintableString;
	private int mHashValue;
	private boolean mHashCached;
	private Document mXmlDocument;

	/**
	 * Some {@link Identifier} impelmentations need this for {@link #equals(Object)}
	 */
	protected static DataModelServerConfigurationProvider mConf;
	static {
		mConf = DataModelService.getServerConfiguration();
	}

	IdentifierImpl(String type) {
		NullCheck.check(type, "identifier type is null");
		mIdentifierType = type;
		mXmlDocument = null;
	}

	/* (non-Javadoc)
	 * @see de.hshannover.f4.trust.iron.mapserver.datamodel.identifiers.Identifier#getTypeString()
	 */
	@Override
	public final String getTypeString() {
		return mIdentifierType;
	}

	/* (non-Javadoc)
	 * @see java.lang.Object#toString()
	 */
	@Override
	public final String toString() {
		if (mPrintableString == null) {
			mPrintableString = getPrintableString();
			if (mPrintableString == null) {
				throw new SystemErrorException("Could not build string for"
						+ mIdentifierType);
			}
		}
		return mPrintableString;
	}

	/**
	 * Helper function for toString()-Method
	 * @return string representation of identifier
	 */
	protected abstract String getPrintableString();

	/* (non-Javadoc)
	 * @see java.lang.Object#equals(java.lang.Object)
	 */
	@Override
	public abstract boolean equals(Object o);

	/* (non-Javadoc)
	 * @see java.lang.Object#hashCode(java.lang.Object)
	 */
	@Override
	public final int hashCode() {
		if (!mHashCached) {
			mHashValue = getHashCode();
			mHashCached = true;
		}
		return mHashValue;
	}

	/**
	 * Generate hash code based in identifier type
	 * @return hash value
	 */
	protected int getHashCode() {
		return 67 * 41 + mIdentifierType.hashCode();
	}

	@Override
	public Document getXmlDocument() {

		if (mXmlDocument == null) {
			throw new SystemErrorException("called getXmlDocument() " +
						"before setXmlDocument()");
		}

		return mXmlDocument;
	}

	@Override
	public void setXmlDocument(Document doc) {

		NullCheck.check(doc, "doc is null");

		if (mXmlDocument != null) {
			throw new SystemErrorException("called setXmlDocument() twice");
		}

		mXmlDocument = doc;
	}
}


text:
<!DOCTYPE html>

    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1, user-scalable=no">
    <meta http-equiv="pragma" content="no-cache">
    <meta http-equiv="cache-control" content="no-cache">
    <meta http-equiv="expires" content="-1">
    <title>Dialogs</title>

    <link rel="stylesheet" href="../lib/pip-webui-lib.css"/>
    <link rel="stylesheet" href="../lib/pip-webui-themes.css"/>
    <link rel="stylesheet" href="../lib/pip-webui-layouts.css"/>

    <link rel="stylesheet" href="../dist/pip-webui-dialogs.css"/>
    <link rel="stylesheet" href="../lib/pip-webui-buttons.css"/>
    <link rel="stylesheet" href="styles.css"/>
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/prism/1.5.1/themes/prism.css">
    <link rel="stylesheet" href="https://fonts.googleapis.com/css?family=Roboto:300,400,500,700,400italic">

<md-toolbar >

        <md-button class="md-icon-button" aria-label="MENU" ng-if="!$mdMedia('gt-sm')" ng-click="onToggleMenu()">
            <md-icon md-svg-icon="icons:menu" ></md-icon>
            </md-button>

Dialogs

        <md-menu md-position-mode="target-right target" ng-if="isTheme">

                        {{ $theme | translate}}

                    <md-icon md-svg-icon="icons:triangle-down"></md-icon>

                <md-menu-content width="3">
                    <md-menu-item ng-repeat="theme in themes">
                        <md-button ng-click="onThemeClick(theme)">{{theme | translate}}</md-button>
                    </md-menu-item>
                </md-menu-content>
            </md-menu>

        <md-menu md-position-mode="target-right target" ng-if="isTranslated">

                        {{ $language | translate}}

                    <md-icon md-svg-icon="icons:triangle-down"></md-icon>

                <md-menu-content width="3">
                    <md-menu-item ng-repeat="lang in languages">
                        <md-button ng-click="onLanguageClick(lang)">{{lang | translate}}</md-button>
                    </md-menu-item>
                </md-menu-content>
            </md-menu>

</md-toolbar>

    <md-sidenav md-component-id="left" md-is-locked-open="$mdMedia('gt-sm')"
                class="md-whiteframe-z2 md-sidenav-left layout-column color-content-bg">
        <md-list>
            <md-list-item ng-repeat="contentItem in content"
                          ng-click="onSwitchPage(contentItem.state)"
                          ng-class="{ 'selected-state': isActiveState(contentItem.state) }">

{{contentItem.title}}

            </md-list-item>
        </md-list>
    </md-sidenav>

    <md-content id="content" class="document-padding flex">

    </md-content>