text:
// disabling eslint for now, going to rewrite this in v5
/* eslint-disable */

import { TEXT_GRADIENT } from '../const';
import { hex2string } from '../utils';

const defaultStyle = {
    align: 'left',
    breakWords: false,
    dropShadow: false,
    dropShadowAlpha: 1,
    dropShadowAngle: Math.PI / 6,
    dropShadowBlur: 0,
    dropShadowColor: 'black',
    dropShadowDistance: 5,
    fill: 'black',
    fillGradientType: TEXT_GRADIENT.LINEAR_VERTICAL,
    fillGradientStops: [],
    fontFamily: 'Arial',
    fontSize: 26,
    fontStyle: 'normal',
    fontVariant: 'normal',
    fontWeight: 'normal',
    letterSpacing: 0,
    lineHeight: 0,
    lineJoin: 'miter',
    miterLimit: 10,
    padding: 0,
    stroke: 'black',
    strokeThickness: 0,
    textBaseline: 'alphabetic',
    trim: false,
    wordWrap: false,
    wordWrapWidth: 100,
    leading: 0,
};

/**
 * A TextStyle Object decorates a Text Object. It can be shared between
 * multiple Text objects. Changing the style will update all text objects using it.
 *
 * @class
 * @memberof PIXI
 */
export default class TextStyle
{
    /**
     * @param {object} [style] - The style parameters
     * @param {string} [style.align='left'] - Alignment for multiline text ('left', 'center' or 'right'),
     *  does not affect single line text
     * @param {boolean} [style.breakWords=false] - Indicates if lines can be wrapped within words, it
     *  needs wordWrap to be set to true
     * @param {boolean} [style.dropShadow=false] - Set a drop shadow for the text
     * @param {number} [style.dropShadowAlpha=1] - Set alpha for the drop shadow
     * @param {number} [style.dropShadowAngle=Math.PI/6] - Set a angle of the drop shadow
     * @param {number} [style.dropShadowBlur=0] - Set a shadow blur radius
     * @param {string|number} [style.dropShadowColor='black'] - A fill style to be used on the dropshadow e.g 'red', '#00FF00'
     * @param {number} [style.dropShadowDistance=5] - Set a distance of the drop shadow
     * @param {string|string[]|number|number[]|CanvasGradient|CanvasPattern} [style.fill='black'] - A canvas
     *  fillstyle that will be used on the text e.g 'red', '#00FF00'. Can be an array to create a gradient
     *  eg ['#000000','#FFFFFF']
     * {@link https://developer.mozilla.org/en-US/docs/Web/API/CanvasRenderingContext2D/fillStyle|MDN}
     * @param {number} [style.fillGradientType=PIXI.TEXT_GRADIENT.LINEAR_VERTICAL] - If fill is an array of colours
     *  to create a gradient, this can change the type/direction of the gradient. See {@link PIXI.TEXT_GRADIENT}
     * @param {number[]} [style.fillGradientStops] - If fill is an array of colours to create a gradient, this array can set
     * the stop points (numbers between 0 and 1) for the color, overriding the default behaviour of evenly spacing them.
     * @param {string|string[]} [style.fontFamily='Arial'] - The font family
     * @param {number|string} [style.fontSize=26] - The font size (as a number it converts to px, but as a string,
     *  equivalents are '26px','20pt','160%' or '1.6em')
     * @param {string} [style.fontStyle='normal'] - The font style ('normal', 'italic' or 'oblique')
     * @param {string} [style.fontVariant='normal'] - The font variant ('normal' or 'small-caps')
     * @param {string} [style.fontWeight='normal'] - The font weight ('normal', 'bold', 'bolder', 'lighter' and '100',
     *  '200', '300', '400', '500', '600', '700', 800' or '900')
     * @param {number} [style.leading=0] - The space between lines
     * @param {number} [style.letterSpacing=0] - The amount of spacing between letters, default is 0
     * @param {number} [style.lineHeight] - The line height, a number that represents the vertical space that a letter uses
     * @param {string} [style.lineJoin='miter'] - The lineJoin property sets the type of corner created, it can resolve
     *      spiked text issues. Possible values "miter" (creates a sharp corner), "round" (creates a round corner) or "bevel"
     *      (creates a squared corner).
     * @param {number} [style.miterLimit=10] - The miter limit to use when using the 'miter' lineJoin mode. This can reduce
     *      or increase the spikiness of rendered text.
     * @param {number} [style.padding=0] - Occasionally some fonts are cropped. Adding some padding will prevent this from
     *     happening by adding padding to all sides of the text.
     * @param {string|number} [style.stroke='black'] - A canvas fillstyle that will be used on the text stroke
     *  e.g 'blue', '#FCFF00'
     * @param {number} [style.strokeThickness=0] - A number that represents the thickness of the stroke.
     *  Default is 0 (no stroke)
     * @param {boolean} [style.trim=false] - Trim transparent borders
     * @param {string} [style.textBaseline='alphabetic'] - The baseline of the text that is rendered.
     * @param {boolean} [style.wordWrap=false] - Indicates if word wrap should be used
     * @param {number} [style.wordWrapWidth=100] - The width at which text will wrap, it needs wordWrap to be set to true
     */
    constructor(style)
    {
        this.styleID = 0;

        this.reset();

        deepCopyProperties(this, style, style);
    }

    /**
     * Creates a new TextStyle object with the same values as this one.
     * Note that the only the properties of the object are cloned.
     *
     * @return {PIXI.TextStyle} New cloned TextStyle object
     */
    clone()
    {
        const clonedProperties = {};

        deepCopyProperties(clonedProperties, this, defaultStyle);

        return new TextStyle(clonedProperties);
    }

    /**
     * Resets all properties to the defaults specified in TextStyle.prototype._default
     */
    reset()
    {
        deepCopyProperties(this, defaultStyle, defaultStyle);
    }

    /**
     * Alignment for multiline text ('left', 'center' or 'right'), does not affect single line text
     *
     * @member {string}
     */
    get align()
    {
        return this._align;
    }
    set align(align) // eslint-disable-line require-jsdoc
    {
        if (this._align !== align)
        {
            this._align = align;
            this.styleID++;
        }
    }

    /**
     * Indicates if lines can be wrapped within words, it needs wordWrap to be set to true
     *
     * @member {boolean}
     */
    get breakWords()
    {
        return this._breakWords;
    }
    set breakWords(breakWords) // eslint-disable-line require-jsdoc
    {
        if (this._breakWords !== breakWords)
        {
            this._breakWords = breakWords;
            this.styleID++;
        }
    }

    /**
     * Set a drop shadow for the text
     *
     * @member {boolean}
     */
    get dropShadow()
    {
        return this._dropShadow;
    }
    set dropShadow(dropShadow) // eslint-disable-line require-jsdoc
    {
        if (this._dropShadow !== dropShadow)
        {
            this._dropShadow = dropShadow;
            this.styleID++;
        }
    }

    /**
     * Set alpha for the drop shadow
     *
     * @member {number}
     */
    get dropShadowAlpha()
    {
        return this._dropShadowAlpha;
    }
    set dropShadowAlpha(dropShadowAlpha) // eslint-disable-line require-jsdoc
    {
        if (this._dropShadowAlpha !== dropShadowAlpha)
        {
            this._dropShadowAlpha = dropShadowAlpha;
            this.styleID++;
        }
    }

    /**
     * Set a angle of the drop shadow
     *
     * @member {number}
     */
    get dropShadowAngle()
    {
        return this._dropShadowAngle;
    }
    set dropShadowAngle(dropShadowAngle) // eslint-disable-line require-jsdoc
    {
        if (this._dropShadowAngle !== dropShadowAngle)
        {
            this._dropShadowAngle = dropShadowAngle;
            this.styleID++;
        }
    }

    /**
     * Set a shadow blur radius
     *
     * @member {number}
     */
    get dropShadowBlur()
    {
        return this._dropShadowBlur;
    }
    set dropShadowBlur(dropShadowBlur) // eslint-disable-line require-jsdoc
    {
        if (this._dropShadowBlur !== dropShadowBlur)
        {
            this._dropShadowBlur = dropShadowBlur;
            this.styleID++;
        }
    }

    /**
     * A fill style to be used on the dropshadow e.g 'red', '#00FF00'
     *
     * @member {string|number}
     */
    get dropShadowColor()
    {
        return this._dropShadowColor;
    }
    set dropShadowColor(dropShadowColor) // eslint-disable-line require-jsdoc
    {
        const outputColor = getColor(dropShadowColor);
        if (this._dropShadowColor !== outputColor)
        {
            this._dropShadowColor = outputColor;
            this.styleID++;
        }
    }

    /**
     * Set a distance of the drop shadow
     *
     * @member {number}
     */
    get dropShadowDistance()
    {
        return this._dropShadowDistance;
    }
    set dropShadowDistance(dropShadowDistance) // eslint-disable-line require-jsdoc
    {
        if (this._dropShadowDistance !== dropShadowDistance)
        {
            this._dropShadowDistance = dropShadowDistance;
            this.styleID++;
        }
    }

    /**
     * A canvas fillstyle that will be used on the text e.g 'red', '#00FF00'.
     * Can be an array to create a gradient eg ['#000000','#FFFFFF']
     * {@link https://developer.mozilla.org/en-US/docs/Web/API/CanvasRenderingContext2D/fillStyle|MDN}
     *
     * @member {string|string[]|number|number[]|CanvasGradient|CanvasPattern}
     */
    get fill()
    {
        return this._fill;
    }
    set fill(fill) // eslint-disable-line require-jsdoc
    {
        const outputColor = getColor(fill);
        if (this._fill !== outputColor)
        {
            this._fill = outputColor;
            this.styleID++;
        }
    }

    /**
     * If fill is an array of colours to create a gradient, this can change the type/direction of the gradient.
     * See {@link PIXI.TEXT_GRADIENT}
     *
     * @member {number}
     */
    get fillGradientType()
    {
        return this._fillGradientType;
    }
    set fillGradientType(fillGradientType) // eslint-disable-line require-jsdoc
    {
        if (this._fillGradientType !== fillGradientType)
        {
            this._fillGradientType = fillGradientType;
            this.styleID++;
        }
    }

    /**
     * If fill is an array of colours to create a gradient, this array can set the stop points
     * (numbers between 0 and 1) for the color, overriding the default behaviour of evenly spacing them.
     *
     * @member {number[]}
     */
    get fillGradientStops()
    {
        return this._fillGradientStops;
    }
    set fillGradientStops(fillGradientStops) // eslint-disable-line require-jsdoc
    {
        if (!areArraysEqual(this._fillGradientStops,fillGradientStops))
        {
            this._fillGradientStops = fillGradientStops;
            this.styleID++;
        }
    }

    /**
     * The font family
     *
     * @member {string|string[]}
     */
    get fontFamily()
    {
        return this._fontFamily;
    }
    set fontFamily(fontFamily) // eslint-disable-line require-jsdoc
    {
        if (this.fontFamily !== fontFamily)
        {
            this._fontFamily = fontFamily;
            this.styleID++;
        }
    }

    /**
     * The font size
     * (as a number it converts to px, but as a string, equivalents are '26px','20pt','160%' or '1.6em')
     *
     * @member {number|string}
     */
    get fontSize()
    {
        return this._fontSize;
    }
    set fontSize(fontSize) // eslint-disable-line require-jsdoc
    {
        if (this._fontSize !== fontSize)
        {
            this._fontSize = fontSize;
            this.styleID++;
        }
    }

    /**
     * The font style
     * ('normal', 'italic' or 'oblique')
     *
     * @member {string}
     */
    get fontStyle()
    {
        return this._fontStyle;
    }
    set fontStyle(fontStyle) // eslint-disable-line require-jsdoc
    {
        if (this._fontStyle !== fontStyle)
        {
            this._fontStyle = fontStyle;
            this.styleID++;
        }
    }

    /**
     * The font variant
     * ('normal' or 'small-caps')
     *
     * @member {string}
     */
    get fontVariant()
    {
        return this._fontVariant;
    }
    set fontVariant(fontVariant) // eslint-disable-line require-jsdoc
    {
        if (this._fontVariant !== fontVariant)
        {
            this._fontVariant = fontVariant;
            this.styleID++;
        }
    }

    /**
     * The font weight
     * ('normal', 'bold', 'bolder', 'lighter' and '100', '200', '300', '400', '500', '600', '700', 800' or '900')
     *
     * @member {string}
     */
    get fontWeight()
    {
        return this._fontWeight;
    }
    set fontWeight(fontWeight) // eslint-disable-line require-jsdoc
    {
        if (this._fontWeight !== fontWeight)
        {
            this._fontWeight = fontWeight;
            this.styleID++;
        }
    }

    /**
     * The amount of spacing between letters, default is 0
     *
     * @member {number}
     */
    get letterSpacing()
    {
        return this._letterSpacing;
    }
    set letterSpacing(letterSpacing) // eslint-disable-line require-jsdoc
    {
        if (this._letterSpacing !== letterSpacing)
        {
            this._letterSpacing = letterSpacing;
            this.styleID++;
        }
    }

    /**
     * The line height, a number that represents the vertical space that a letter uses
     *
     * @member {number}
     */
    get lineHeight()
    {
        return this._lineHeight;
    }
    set lineHeight(lineHeight) // eslint-disable-line require-jsdoc
    {
        if (this._lineHeight !== lineHeight)
        {
            this._lineHeight = lineHeight;
            this.styleID++;
        }
    }

    /**
     * The space between lines
     *
     * @member {number}
     */
    get leading()
    {
        return this._leading;
    }
    set leading(leading) // eslint-disable-line require-jsdoc
    {
        if (this._leading !== leading)
        {
            this._leading = leading;
            this.styleID++;
        }
    }

    /**
     * The lineJoin property sets the type of corner created, it can resolve spiked text issues.
     * Default is 'miter' (creates a sharp corner).
     *
     * @member {string}
     */
    get lineJoin()
    {
        return this._lineJoin;
    }
    set lineJoin(lineJoin) // eslint-disable-line require-jsdoc
    {
        if (this._lineJoin !== lineJoin)
        {
            this._lineJoin = lineJoin;
            this.styleID++;
        }
    }

    /**
     * The miter limit to use when using the 'miter' lineJoin mode
     * This can reduce or increase the spikiness of rendered text.
     *
     * @member {number}
     */
    get miterLimit()
    {
        return this._miterLimit;
    }
    set miterLimit(miterLimit) // eslint-disable-line require-jsdoc
    {
        if (this._miterLimit !== miterLimit)
        {
            this._miterLimit = miterLimit;
            this.styleID++;
        }
    }

    /**
     * Occasionally some fonts are cropped. Adding some padding will prevent this from happening
     * by adding padding to all sides of the text.
     *
     * @member {number}
     */
    get padding()
    {
        return this._padding;
    }
    set padding(padding) // eslint-disable-line require-jsdoc
    {
        if (this._padding !== padding)
        {
            this._padding = padding;
            this.styleID++;
        }
    }

    /**
     * A canvas fillstyle that will be used on the text stroke
     * e.g 'blue', '#FCFF00'
     *
     * @member {string|number}
     */
    get stroke()
    {
        return this._stroke;
    }
    set stroke(stroke) // eslint-disable-line require-jsdoc
    {
        const outputColor = getColor(stroke);
        if (this._stroke !== outputColor)
        {
            this._stroke = outputColor;
            this.styleID++;
        }
    }

    /**
     * A number that represents the thickness of the stroke.
     * Default is 0 (no stroke)
     *
     * @member {number}
     */
    get strokeThickness()
    {
        return this._strokeThickness;
    }
    set strokeThickness(strokeThickness) // eslint-disable-line require-jsdoc
    {
        if (this._strokeThickness !== strokeThickness)
        {
            this._strokeThickness = strokeThickness;
            this.styleID++;
        }
    }

    /**
     * The baseline of the text that is rendered.
     *
     * @member {string}
     */
    get textBaseline()
    {
        return this._textBaseline;
    }
    set textBaseline(textBaseline) // eslint-disable-line require-jsdoc
    {
        if (this._textBaseline !== textBaseline)
        {
            this._textBaseline = textBaseline;
            this.styleID++;
        }
    }

    /**
     * Trim transparent borders
     *
     * @member {boolean}
     */
    get trim()
    {
        return this._trim;
    }
    set trim(trim) // eslint-disable-line require-jsdoc
    {
        if (this._trim !== trim)
        {
            this._trim = trim;
            this.styleID++;
        }
    }

    /**
     * Indicates if word wrap should be used
     *
     * @member {boolean}
     */
    get wordWrap()
    {
        return this._wordWrap;
    }
    set wordWrap(wordWrap) // eslint-disable-line require-jsdoc
    {
        if (this._wordWrap !== wordWrap)
        {
            this._wordWrap = wordWrap;
            this.styleID++;
        }
    }

    /**
     * The width at which text will wrap, it needs wordWrap to be set to true
     *
     * @member {number}
     */
    get wordWrapWidth()
    {
        return this._wordWrapWidth;
    }
    set wordWrapWidth(wordWrapWidth) // eslint-disable-line require-jsdoc
    {
        if (this._wordWrapWidth !== wordWrapWidth)
        {
            this._wordWrapWidth = wordWrapWidth;
            this.styleID++;
        }
    }

    /**
     * Generates a font style string to use for `TextMetrics.measureFont()`.
     *
     * @return {string} Font style string, for passing to `TextMetrics.measureFont()`
     */
    toFontString()
    {
        // build canvas api font setting from individual components. Convert a numeric this.fontSize to px
        const fontSizeString = (typeof this.fontSize === 'number') ? `${this.fontSize}px` : this.fontSize;

        // Clean-up fontFamily property by quoting each font name
        // this will support font names with spaces
        let fontFamilies = this.fontFamily;

        if (!Array.isArray(this.fontFamily))
        {
            fontFamilies = this.fontFamily.split(',');
        }

        for (let i = fontFamilies.length - 1; i >= 0; i--)
        {
            // Trim any extra white-space
            let fontFamily = fontFamilies[i].trim();

            // Check if font already contains strings
            if (!(/([\"\'])[^\'\"]+\1/).test(fontFamily))
            {
                fontFamily = `"${fontFamily}"`;
            }
            fontFamilies[i] = fontFamily;
        }

        return `${this.fontStyle} ${this.fontVariant} ${this.fontWeight} ${fontSizeString} ${fontFamilies.join(',')}`;
    }
}

/**
 * Utility function to convert hexadecimal colors to strings, and simply return the color if it's a string.
 * @private
 * @param {number|number[]} color
 * @return {string} The color as a string.
 */
function getSingleColor(color)
{
    if (typeof color === 'number')
    {
        return hex2string(color);
    }
    else if ( typeof color === 'string' )
    {
        if ( color.indexOf('0x') === 0 )
        {
            color = color.replace('0x', '#');
        }
    }

    return color;
}

/**
 * Utility function to convert hexadecimal colors to strings, and simply return the color if it's a string.
 * This version can also convert array of colors
 * @private
 * @param {number|number[]} color
 * @return {string} The color as a string.
 */
function getColor(color)
{
    if (!Array.isArray(color))
    {
        return getSingleColor(color);
    }
    else
    {
        for (let i = 0; i < color.length; ++i)
        {
            color[i] = getSingleColor(color[i]);
        }

        return color;
    }
}

/**
 * Utility function to convert hexadecimal colors to strings, and simply return the color if it's a string.
 * This version can also convert array of colors
 * @private
 * @param {Array} array1 First array to compare
 * @param {Array} array2 Second array to compare
 * @return {boolean} Do the arrays contain the same values in the same order
 */
function areArraysEqual(array1, array2)
{
    if (!Array.isArray(array1) || !Array.isArray(array2))
    {
        return false;
    }

    if (array1.length !== array2.length)
    {
        return false;
    }

    for (let i = 0; i < array1.length; ++i)
    {
        if (array1[i] !== array2[i])
        {
            return false;
        }
    }

    return true;
}

/**
 * Utility function to ensure that object properties are copied by value, and not by reference
 * @private
 * @param {Object} target Target object to copy properties into
 * @param {Object} source Source object for the proporties to copy
 * @param {string} propertyObj Object containing properties names we want to loop over
 */
function deepCopyProperties(target, source, propertyObj) {
    for (const prop in propertyObj) {
        if (Array.isArray(source[prop])) {
            target[prop] = source[prop].slice();
        } else {
            target[prop] = source[prop];
        }
    }
}


text:
package io.skysail.ext.oauth2.instagram.resources

import org.json.JSONObject
import io.skysail.ext.oauth2.domain.Token

case class TokenResponse(accessToken: String) extends Token

object TokenResponse {
  def apply(json: JSONObject): TokenResponse = {
    new TokenResponse(
      json.getString("access_token"))
  }
}

redpajama_set_name: RedPajamaGithub


text:
#include "EfiShellLib.h"

MTD_NAME  mMTDName[] = {
  {
    MTDTypeUnknown,
    L"f"
  },
  {
    MTDTypeFloppy,
    L"fp"
  },
  {
    MTDTypeHardDisk,
    L"hd"
  },
  {
    MTDTypeCDRom,
    L"cd"
  },
  {
    MTDTypeEnd,
    NULL
  }
};

VOID
AppendCSDNum2 (
  IN OUT POOL_PRINT       *Str,
  IN UINT64               Num
  )
{
  UINT64  Result;
  UINTN   Rem;

  ASSERT(Str != NULL);

  Result = DivU64x32 (Num, 25, &Rem);
  if (Result > 0) {
    AppendCSDNum2 (Str, Result);
  }

  CatPrint (Str, L"%c", Rem + 'a');
}

VOID
AppendCSDNum (
  DEVICE_CONSIST_MAPPING_INFO            *MappingItem,
  UINT64                                 Num
  )
{
  ASSERT(MappingItem != NULL);

  if (MappingItem->Digital) {
    CatPrint (&MappingItem->CSD, L"%ld", Num);
  } else {
    AppendCSDNum2 (&MappingItem->CSD, Num);
  }

  MappingItem->Digital = (BOOLEAN)!(MappingItem->Digital);
}

VOID
AppendCSDStr (
  DEVICE_CONSIST_MAPPING_INFO            *MappingItem,
  CHAR16                                 *Str
  )
{
  CHAR16  *Index;

  ASSERT(Str != NULL);
  ASSERT(MappingItem != NULL);

  if (MappingItem->Digital) {
    //
    // To aVOID mult-meaning, the mapping is:
    //  0  1  2  3  4  5  6  7  8  9  a  b  c  d  e  f
    //  0  16 2  3  4  5  6  7  8  9  10 11 12 13 14 15
    //
    for (Index = Str; *Index != 0; Index++) {
      switch (*Index) {
      case '0':
      case '2':
      case '3':
      case '4':
      case '5':
      case '6':
      case '7':
      case '8':
      case '9':
        CatPrint (&MappingItem->CSD, L"%c", *Index);
        break;

      case '1':
        CatPrint (&MappingItem->CSD, L"16");
        break;

      case 'a':
      case 'b':
      case 'c':
      case 'd':
      case 'e':
      case 'f':
        CatPrint (&MappingItem->CSD, L"1%c", *Index - 'a' + '0');
        break;

      case 'A':
      case 'B':
      case 'C':
      case 'D':
      case 'E':
      case 'F':
        CatPrint (&MappingItem->CSD, L"1%c", *Index - 'A' + '0');
        break;
      }
    }
  } else {
    for (Index = Str; *Index != 0; Index++) {
      //
      //  The mapping is:
      //  0  1  2  3  4  5  6  7  8  9  a  b  c  d  e  f
      //  a  b  c  d  e  f  g  h  i  j  k  l  m  n  o  p
      //
      if (*Index >= '0' && *Index <= '9') {
        CatPrint (&MappingItem->CSD, L"%c", *Index - '0' + 'a');
      } else if (*Index >= 'a' && *Index <= 'f') {
        CatPrint (&MappingItem->CSD, L"%c", *Index - 'a' + 'k');
      } else if (*Index >= 'A' && *Index <= 'F') {
        CatPrint (&MappingItem->CSD, L"%c", *Index - 'A' + 'k');
      }
    }
  }

  MappingItem->Digital = (BOOLEAN)!(MappingItem->Digital);
}

VOID
AppendCSDGuid (
  DEVICE_CONSIST_MAPPING_INFO            *MappingItem,
  EFI_GUID                               *Guid
  )
{
  CHAR16  Buffer[64];
  ASSERT(Guid != NULL);
  ASSERT(MappingItem != NULL);

  SPrint (
    Buffer,
    0,
    L"%08x%04x%04x%02x%02x%02x%02x%02x%02x%02x%02x",
    (UINTN) Guid->Data1,
    (UINTN) Guid->Data2,
    (UINTN) Guid->Data3,
    (UINTN) Guid->Data4[0],
    (UINTN) Guid->Data4[1],
    (UINTN) Guid->Data4[2],
    (UINTN) Guid->Data4[3],
    (UINTN) Guid->Data4[4],
    (UINTN) Guid->Data4[5],
    (UINTN) Guid->Data4[6],
    (UINTN) Guid->Data4[7]
    );
  StrLwr (Buffer);
  AppendCSDStr (MappingItem, Buffer);
}

INTN
_DevPathCompareAcpi (
  IN EFI_DEVICE_PATH_PROTOCOL       *DevicePath1,
  IN EFI_DEVICE_PATH_PROTOCOL       *DevicePath2
  )
{
  ACPI_HID_DEVICE_PATH  *Acpi1;
  ACPI_HID_DEVICE_PATH  *Acpi2;

  ASSERT(DevicePath1 != NULL);
  ASSERT(DevicePath2 != NULL);

  Acpi1 = (ACPI_HID_DEVICE_PATH *) DevicePath1;
  Acpi2 = (ACPI_HID_DEVICE_PATH *) DevicePath2;
  if (Acpi1->HID > Acpi2->HID || (Acpi1->HID == Acpi2->HID && Acpi1->UID > Acpi2->UID)) {
    return 1;
  }

  if (Acpi1->HID == Acpi2->HID && Acpi1->UID == Acpi2->UID) {
    return 0;
  }

  return -1;
}

INTN
_DevPathComparePci (
  IN EFI_DEVICE_PATH_PROTOCOL       *DevicePath1,
  IN EFI_DEVICE_PATH_PROTOCOL       *DevicePath2
  )
{
  PCI_DEVICE_PATH *Pci1;
  PCI_DEVICE_PATH *Pci2;

  ASSERT(DevicePath1 != NULL);
  ASSERT(DevicePath2 != NULL);

  Pci1  = (PCI_DEVICE_PATH *) DevicePath1;
  Pci2  = (PCI_DEVICE_PATH *) DevicePath2;
  if (Pci1->Device > Pci2->Device || (Pci1->Device == Pci2->Device && Pci1->Function > Pci2->Function)) {
    return 1;
  }

  if (Pci1->Device == Pci2->Device && Pci1->Function == Pci2->Function) {
    return 0;
  }

  return -1;
}

INTN
_DevPathCompareDefault (
  IN EFI_DEVICE_PATH_PROTOCOL       *DevicePath1,
  IN EFI_DEVICE_PATH_PROTOCOL       *DevicePath2
  )
{
  UINTN DevPathSize1;
  UINTN DevPathSize2;

  ASSERT(DevicePath1 != NULL);
  ASSERT(DevicePath2 != NULL);

  DevPathSize1  = DevicePathNodeLength (DevicePath1);
  DevPathSize2  = DevicePathNodeLength (DevicePath2);
  if (DevPathSize1 > DevPathSize2) {
    return 1;
  } else if (DevPathSize1 < DevPathSize2) {
    return -1;
  } else {
    return CompareMem (DevicePath1, DevicePath2, DevPathSize1);
  }
}

VOID
_DevPathSerialHardDrive (
  IN EFI_DEVICE_PATH_PROTOCOL     *DevicePathNode,
  IN DEVICE_CONSIST_MAPPING_INFO  *MappingItem
  )
{
  HARDDRIVE_DEVICE_PATH *Hd;

  ASSERT(DevicePathNode != NULL);
  ASSERT(MappingItem != NULL);

  Hd = (HARDDRIVE_DEVICE_PATH *) DevicePathNode;
  if (MappingItem->MTD == MTDTypeUnknown) {
    MappingItem->MTD = MTDTypeHardDisk;
  }

  AppendCSDNum (MappingItem, Hd->PartitionNumber);
}

VOID
_DevPathSerialAtapi (
  IN EFI_DEVICE_PATH_PROTOCOL     *DevicePathNode,
  IN DEVICE_CONSIST_MAPPING_INFO  *MappingItem
  )
{
  ATAPI_DEVICE_PATH *Atapi;

  ASSERT(DevicePathNode != NULL);
  ASSERT(MappingItem != NULL);

  Atapi = (ATAPI_DEVICE_PATH *) DevicePathNode;
  AppendCSDNum (MappingItem, (Atapi->PrimarySecondary * 2 + Atapi->SlaveMaster));
}

VOID
_DevPathSerialCDROM (
  IN EFI_DEVICE_PATH_PROTOCOL     *DevicePathNode,
  IN DEVICE_CONSIST_MAPPING_INFO  *MappingItem
  )
{
  CDROM_DEVICE_PATH *Cd;

  ASSERT(DevicePathNode != NULL);
  ASSERT(MappingItem != NULL);

  Cd                = (CDROM_DEVICE_PATH *) DevicePathNode;
  MappingItem->MTD  = MTDTypeCDRom;
  AppendCSDNum (MappingItem, Cd->BootEntry);
}

VOID
_DevPathSerialFibre (
  IN EFI_DEVICE_PATH_PROTOCOL     *DevicePathNode,
  IN DEVICE_CONSIST_MAPPING_INFO  *MappingItem
  )
{
  FIBRECHANNEL_DEVICE_PATH  *Fibre;

  ASSERT(DevicePathNode != NULL);
  ASSERT(MappingItem != NULL);

  Fibre = (FIBRECHANNEL_DEVICE_PATH *) DevicePathNode;
  AppendCSDNum (MappingItem, Fibre->WWN);
  AppendCSDNum (MappingItem, Fibre->Lun);
}

VOID
_DevPathSerialUart (
  IN EFI_DEVICE_PATH_PROTOCOL     *DevicePathNode,
  IN DEVICE_CONSIST_MAPPING_INFO  *MappingItem
  )
{
  UART_DEVICE_PATH  *Uart;

  ASSERT(DevicePathNode != NULL);
  ASSERT(MappingItem != NULL);

  Uart = (UART_DEVICE_PATH *) DevicePathNode;
  AppendCSDNum (MappingItem, Uart->BaudRate);
  AppendCSDNum (MappingItem, Uart->DataBits);
  AppendCSDNum (MappingItem, Uart->Parity);
  AppendCSDNum (MappingItem, Uart->StopBits);
}

VOID
_DevPathSerialUsb (
  IN EFI_DEVICE_PATH_PROTOCOL     *DevicePathNode,
  IN DEVICE_CONSIST_MAPPING_INFO  *MappingItem
  )
{
  USB_DEVICE_PATH *Usb;

  ASSERT(DevicePathNode != NULL);
  ASSERT(MappingItem != NULL);

  Usb = (USB_DEVICE_PATH *) DevicePathNode;
  AppendCSDNum (MappingItem, Usb->ParentPortNumber);
  AppendCSDNum (MappingItem, Usb->InterfaceNumber);
}

VOID
_DevPathSerialVendor (
  IN EFI_DEVICE_PATH_PROTOCOL     *DevicePathNode,
  IN DEVICE_CONSIST_MAPPING_INFO  *MappingItem
  )
{
  VENDOR_DEVICE_PATH  *Vendor;

  ASSERT(DevicePathNode != NULL);
  ASSERT(MappingItem != NULL);

  Vendor = (VENDOR_DEVICE_PATH *) DevicePathNode;
  AppendCSDGuid (MappingItem, &Vendor->Guid);
}

VOID
_DevPathSerialI2O (
  IN EFI_DEVICE_PATH_PROTOCOL     *DevicePathNode,
  IN DEVICE_CONSIST_MAPPING_INFO  *MappingItem
  )
{
  I2O_DEVICE_PATH *I2O;

  ASSERT(DevicePathNode != NULL);
  ASSERT(MappingItem != NULL);

  I2O = (I2O_DEVICE_PATH *) DevicePathNode;
  AppendCSDNum (MappingItem, I2O->Tid);
}

VOID
_DevPathSerialMacAddr (
  IN EFI_DEVICE_PATH_PROTOCOL     *DevicePathNode,
  IN DEVICE_CONSIST_MAPPING_INFO  *MappingItem
  )
{
  MAC_ADDR_DEVICE_PATH  *MAC;
  UINTN                 HwAddressSize;
  UINTN                 Index;
  CHAR16                Buffer[64];
  CHAR16                *PBuffer;

  ASSERT(DevicePathNode != NULL);
  ASSERT(MappingItem != NULL);

  MAC           = (MAC_ADDR_DEVICE_PATH *) DevicePathNode;

  HwAddressSize = sizeof (EFI_MAC_ADDRESS);
  if (MAC->IfType == 0x01 || MAC->IfType == 0x00) {
    HwAddressSize = 6;
  }

  for (Index = 0, PBuffer = Buffer; Index < HwAddressSize; Index++, PBuffer += 2) {
    SPrint (PBuffer, 0, L"%02x", (UINTN) MAC->MacAddress.Addr[Index]);
  }

  AppendCSDStr (MappingItem, Buffer);
}

VOID
_DevPathSerialInfiniBand (
  IN EFI_DEVICE_PATH_PROTOCOL     *DevicePathNode,
  IN DEVICE_CONSIST_MAPPING_INFO  *MappingItem
  )
{
  INFINIBAND_DEVICE_PATH  *InfiniBand;
  UINTN                   Index;
  CHAR16                  Buffer[64];
  CHAR16                  *PBuffer;

  ASSERT(DevicePathNode != NULL);
  ASSERT(MappingItem != NULL);

  InfiniBand = (INFINIBAND_DEVICE_PATH *) DevicePathNode;
  for (Index = 0, PBuffer = Buffer; Index < 16; Index++, PBuffer += 2) {
    SPrint (PBuffer, 0, L"%02x", (UINTN) InfiniBand->PortGid[Index]);
  }

  AppendCSDStr (MappingItem, Buffer);
  AppendCSDNum (MappingItem, InfiniBand->ServiceId);
  AppendCSDNum (MappingItem, InfiniBand->TargetPortId);
  AppendCSDNum (MappingItem, InfiniBand->DeviceId);
}

VOID
_DevPathSerialIPv4 (
  IN EFI_DEVICE_PATH_PROTOCOL     *DevicePathNode,
  IN DEVICE_CONSIST_MAPPING_INFO  *MappingItem
  )
{
  IPv4_DEVICE_PATH  *IP;
  CHAR16            Buffer[10];

  ASSERT(DevicePathNode != NULL);
  ASSERT(MappingItem != NULL);

  IP = (IPv4_DEVICE_PATH *) DevicePathNode;
  SPrint (
    Buffer,
    0,
    L"%02x%02x%02x%02x",
    (UINTN) IP->LocalIpAddress.Addr[0],
    (UINTN) IP->LocalIpAddress.Addr[1],
    (UINTN) IP->LocalIpAddress.Addr[2],
    (UINTN) IP->LocalIpAddress.Addr[3]
    );
  AppendCSDStr (MappingItem, Buffer);
  AppendCSDNum (MappingItem, IP->LocalPort);
  SPrint (
    Buffer,
    0,
    L"%02x%02x%02x%02x",
    (UINTN) IP->RemoteIpAddress.Addr[0],
    (UINTN) IP->RemoteIpAddress.Addr[1],
    (UINTN) IP->RemoteIpAddress.Addr[2],
    (UINTN) IP->RemoteIpAddress.Addr[3]
    );
  AppendCSDStr (MappingItem, Buffer);
  AppendCSDNum (MappingItem, IP->RemotePort);
}

VOID
_DevPathSerialIPv6 (
  IN EFI_DEVICE_PATH_PROTOCOL     *DevicePathNode,
  IN DEVICE_CONSIST_MAPPING_INFO  *MappingItem
  )
{
  IPv6_DEVICE_PATH  *IP;
  UINTN             Index;
  CHAR16            Buffer[64];
  CHAR16            *PBuffer;

  ASSERT(DevicePathNode != NULL);
  ASSERT(MappingItem != NULL);

  IP = (IPv6_DEVICE_PATH *) DevicePathNode;
  for (Index = 0, PBuffer = Buffer; Index < 16; Index++, PBuffer += 2) {
    SPrint (PBuffer, 0, L"%02x", (UINTN) IP->LocalIpAddress.Addr[Index]);
  }

  AppendCSDStr (MappingItem, Buffer);
  AppendCSDNum (MappingItem, IP->LocalPort);
  for (Index = 0, PBuffer = Buffer; Index < 16; Index++, PBuffer += 2) {
    SPrint (PBuffer, 0, L"%02x", (UINTN) IP->RemoteIpAddress.Addr[Index]);
  }

  AppendCSDStr (MappingItem, Buffer);
  AppendCSDNum (MappingItem, IP->RemotePort);
}

VOID
_DevPathSerialScsi (
  IN EFI_DEVICE_PATH_PROTOCOL     *DevicePathNode,
  IN DEVICE_CONSIST_MAPPING_INFO  *MappingItem
  )
{
  SCSI_DEVICE_PATH  *Scsi;

  ASSERT(DevicePathNode != NULL);
  ASSERT(MappingItem != NULL);

  Scsi = (SCSI_DEVICE_PATH *) DevicePathNode;
  AppendCSDNum (MappingItem, Scsi->Pun);
  AppendCSDNum (MappingItem, Scsi->Lun);
}

VOID
_DevPathSerial1394 (
  IN EFI_DEVICE_PATH_PROTOCOL     *DevicePathNode,
  IN DEVICE_CONSIST_MAPPING_INFO  *MappingItem
  )
{
  F1394_DEVICE_PATH *F1394;
  CHAR16            Buffer[20];

  ASSERT(DevicePathNode != NULL);
  ASSERT(MappingItem != NULL);

  F1394 = (F1394_DEVICE_PATH *) DevicePathNode;
  SPrint (Buffer, 0, L"%lx", F1394->Guid);
  AppendCSDStr (MappingItem, Buffer);
}

VOID
_DevPathSerialAcpi (
  IN EFI_DEVICE_PATH_PROTOCOL     *DevicePathNode,
  IN DEVICE_CONSIST_MAPPING_INFO  *MappingItem
  )
{
  ACPI_HID_DEVICE_PATH  *Acpi;

  ASSERT(DevicePathNode != NULL);
  ASSERT(MappingItem != NULL);

  Acpi = (ACPI_HID_DEVICE_PATH *) DevicePathNode;
  if ((Acpi->HID & PNP_EISA_ID_MASK) == PNP_EISA_ID_CONST) {
    if (EISA_ID_TO_NUM (Acpi->HID) == 0x0604) {
      MappingItem->MTD = MTDTypeFloppy;
      AppendCSDNum (MappingItem, Acpi->UID);
    }
  }
}

VOID
_DevPathSerialDefault (
  IN EFI_DEVICE_PATH_PROTOCOL     *DevicePathNode,
  IN DEVICE_CONSIST_MAPPING_INFO  *MappingItem
  )
{
}

DEV_PATH_CONSIST_MAPPING_TABLE  DevPathConsistMappingTable[] = {
  HARDWARE_DEVICE_PATH,
  HW_PCI_DP,
  _DevPathSerialDefault,
  _DevPathComparePci,
  HARDWARE_DEVICE_PATH,
  HW_PCCARD_DP,
  _DevPathSerialDefault,
  _DevPathCompareDefault,
  HARDWARE_DEVICE_PATH,
  HW_MEMMAP_DP,
  _DevPathSerialDefault,
  _DevPathCompareDefault,
  HARDWARE_DEVICE_PATH,
  HW_VENDOR_DP,
  _DevPathSerialDefault,
  _DevPathCompareDefault,
  HARDWARE_DEVICE_PATH,
  HW_CONTROLLER_DP,
  _DevPathSerialDefault,
  _DevPathCompareDefault,
  ACPI_DEVICE_PATH,
  ACPI_DP,
  _DevPathSerialAcpi,
  _DevPathCompareAcpi,
  MESSAGING_DEVICE_PATH,
  MSG_ATAPI_DP,
  _DevPathSerialAtapi,
  _DevPathCompareDefault,
  MESSAGING_DEVICE_PATH,
  MSG_SCSI_DP,
  _DevPathSerialScsi,
  _DevPathCompareDefault,
  MESSAGING_DEVICE_PATH,
  MSG_FIBRECHANNEL_DP,
  _DevPathSerialFibre,
  _DevPathCompareDefault,
  MESSAGING_DEVICE_PATH,
  MSG_1394_DP,
  _DevPathSerial1394,
  _DevPathCompareDefault,
  MESSAGING_DEVICE_PATH,
  MSG_USB_DP,
  _DevPathSerialUsb,
  _DevPathCompareDefault,
  MESSAGING_DEVICE_PATH,
  MSG_USB_CLASS_DP,
  _DevPathSerialDefault,
  _DevPathCompareDefault,
  MESSAGING_DEVICE_PATH,
  MSG_I2O_DP,
  _DevPathSerialI2O,
  _DevPathCompareDefault,
  MESSAGING_DEVICE_PATH,
  MSG_MAC_ADDR_DP,
  _DevPathSerialMacAddr,
  _DevPathCompareDefault,
  MESSAGING_DEVICE_PATH,
  MSG_IPv4_DP,
  _DevPathSerialIPv4,
  _DevPathCompareDefault,
  MESSAGING_DEVICE_PATH,
  MSG_IPv6_DP,
  _DevPathSerialIPv6,
  _DevPathCompareDefault,
  MESSAGING_DEVICE_PATH,
  MSG_INFINIBAND_DP,
  _DevPathSerialInfiniBand,
  _DevPathCompareDefault,
  MESSAGING_DEVICE_PATH,
  MSG_UART_DP,
  _DevPathSerialUart,
  _DevPathCompareDefault,
  MESSAGING_DEVICE_PATH,
  MSG_VENDOR_DP,
  _DevPathSerialVendor,
  _DevPathCompareDefault,
  MEDIA_DEVICE_PATH,
  MEDIA_HARDDRIVE_DP,
  _DevPathSerialHardDrive,
  _DevPathCompareDefault,
  MEDIA_DEVICE_PATH,
  MEDIA_CDROM_DP,
  _DevPathSerialCDROM,
  _DevPathCompareDefault,
  MEDIA_DEVICE_PATH,
  MEDIA_VENDOR_DP,
  _DevPathSerialVendor,
  _DevPathCompareDefault,
  MEDIA_DEVICE_PATH,
  MEDIA_FILEPATH_DP,
  _DevPathSerialDefault,
  _DevPathCompareDefault,
  MEDIA_DEVICE_PATH,
  MEDIA_PROTOCOL_DP,
  _DevPathSerialDefault,
  _DevPathCompareDefault,
#if (EFI_SPECIFICATION_VERSION < 0x00020000)
  MEDIA_DEVICE_PATH,
  MEDIA_FV_FILEPATH_DP,
  _DevPathSerialDefault,
  _DevPathCompareDefault,
#endif
  BBS_DEVICE_PATH,
  BBS_BBS_DP,
  _DevPathSerialDefault,
  _DevPathCompareDefault,
  END_DEVICE_PATH_TYPE,
  END_INSTANCE_DEVICE_PATH_SUBTYPE,
  _DevPathSerialDefault,
  _DevPathCompareDefault,
  0,
  0,
  NULL,
  NULL
};

INTN
DevicePathConsistMappingCompare (
  IN  VOID             *Buffer1,
  IN  VOID             *Buffer2
  )
{
  UINTN                     Index;
  INTN                      CompareResult;
  EFI_DEVICE_PATH_PROTOCOL  *DevicePath1 = *(EFI_DEVICE_PATH_PROTOCOL**)Buffer1;
  EFI_DEVICE_PATH_PROTOCOL  *DevicePath2 = *(EFI_DEVICE_PATH_PROTOCOL**)Buffer2;
  INTN                      (*CompareFun)(EFI_DEVICE_PATH_PROTOCOL *, EFI_DEVICE_PATH_PROTOCOL *);

  if (DevicePath1 == NULL) {
    if (DevicePath2 == NULL) {
      return 0;
    }

    return -1;
  }

  if (DevicePath2 == NULL) {
    return 1;
  }

  while (!(IsDevicePathEnd (DevicePath1) || IsDevicePathEnd (DevicePath2))) {
    CompareResult = DevicePathType (DevicePath1) - DevicePathType (DevicePath2);
    if (CompareResult != 0) {
      return CompareResult;
    }

    CompareResult = DevicePathSubType (DevicePath1) - DevicePathSubType (DevicePath2);
    if (CompareResult != 0) {
      return CompareResult;
    }

    CompareFun = NULL;
    for (Index = 0; DevPathConsistMappingTable[Index].CompareFun; Index += 1) {
      if (DevicePathType (DevicePath1) == DevPathConsistMappingTable[Index].Type &&
          DevicePathSubType (DevicePath1) == DevPathConsistMappingTable[Index].SubType
          ) {
        CompareFun = DevPathConsistMappingTable[Index].CompareFun;
        break;
      }
    }
    //
    // If not found, use a default function
    //
    if (!CompareFun) {
      CompareFun = _DevPathCompareDefault;
    }

    CompareResult = CompareFun (DevicePath1, DevicePath2);
    if (CompareResult != 0) {
      return CompareResult;
    }

    DevicePath1 = (EFI_DEVICE_PATH_PROTOCOL *) NextDevicePathNode (DevicePath1);
    DevicePath2 = (EFI_DEVICE_PATH_PROTOCOL *) NextDevicePathNode (DevicePath2);
  }

  if (IsDevicePathEnd (DevicePath1)) {
    if (IsDevicePathEnd (DevicePath2)) {
      return 0;
    }

    return -1;
  }

  return 1;
}

EFI_STATUS
DevicePathConsistMappingSort (
  IN  EFI_DEVICE_PATH_PROTOCOL **DevicePathBuffer,
  IN  UINTN                    DevicePathNum
  )
{
  QSort (DevicePathBuffer, DevicePathNum, sizeof (EFI_DEVICE_PATH_PROTOCOL *), DevicePathConsistMappingCompare);
  return EFI_SUCCESS;
}

BOOLEAN
IsHIDevicePathNode (
  EFI_DEVICE_PATH_PROTOCOL *DevicePathNode
  )
{
  ACPI_HID_DEVICE_PATH  *Acpi;

  ASSERT(DevicePathNode != NULL);

  if (DevicePathNode->Type == HARDWARE_DEVICE_PATH) {
    return TRUE;
  }

  if (DevicePathNode->Type == ACPI_DEVICE_PATH) {
    Acpi = (ACPI_HID_DEVICE_PATH *) DevicePathNode;
    switch (EISA_ID_TO_NUM (Acpi->HID)) {
    case 0x0301:
    case 0x0401:
    case 0x0501:
    case 0x0604:
      return FALSE;
    }

    return TRUE;
  }

  return FALSE;
}

EFI_DEVICE_PATH_PROTOCOL *
GetHIDevicePath (
  EFI_DEVICE_PATH_PROTOCOL        *DevicePath
  )
{
  UINTN                     NonHIDevicePathNodeCount;
  UINTN                     Index;
  EFI_DEV_PATH              Node;
  EFI_DEVICE_PATH_PROTOCOL  *HIDevicePath;
  EFI_DEVICE_PATH_PROTOCOL  *TempDevicePath;

  ASSERT(DevicePath != NULL);

  NonHIDevicePathNodeCount  = 0;

  HIDevicePath              = AllocatePool (sizeof (EFI_DEVICE_PATH_PROTOCOL));
  SetDevicePathEndNode (HIDevicePath);

  Node.DevPath.Type       = END_DEVICE_PATH_TYPE;
  Node.DevPath.SubType    = END_INSTANCE_DEVICE_PATH_SUBTYPE;
  Node.DevPath.Length[0]  = sizeof (EFI_DEVICE_PATH_PROTOCOL);
  Node.DevPath.Length[1]  = 0;

  while (!IsDevicePathEnd (DevicePath)) {
    if (IsHIDevicePathNode (DevicePath)) {
      for (Index = 0; Index < NonHIDevicePathNodeCount; Index++) {
        TempDevicePath = AppendDevicePathNode (HIDevicePath, &Node.DevPath);
        FreePool (HIDevicePath);
        HIDevicePath = TempDevicePath;
      }

      TempDevicePath = AppendDevicePathNode (HIDevicePath, DevicePath);
      FreePool (HIDevicePath);
      HIDevicePath = TempDevicePath;
    } else {
      NonHIDevicePathNodeCount++;
    }
    //
    // Next device path node
    //
    DevicePath = (EFI_DEVICE_PATH_PROTOCOL *) NextDevicePathNode (DevicePath);
  }

  return HIDevicePath;
}

EFI_STATUS
GetDeviceConsistMappingInfo (
  DEVICE_CONSIST_MAPPING_INFO    *MappingItem,
  EFI_DEVICE_PATH_PROTOCOL       *DevicePath
  )
{
  VOID (*SerialFun) (EFI_DEVICE_PATH_PROTOCOL *, DEVICE_CONSIST_MAPPING_INFO *);

  UINTN Index;

  ASSERT(DevicePath != NULL);
  ASSERT(MappingItem != NULL);

  SetMem (&MappingItem->CSD, sizeof (POOL_PRINT), 0);

  while (!IsDevicePathEnd (DevicePath)) {
    //
    // Find the handler to dump this device path node
    //
    SerialFun = NULL;
    for (Index = 0; DevPathConsistMappingTable[Index].SerialFun; Index += 1) {

      if (DevicePathType (DevicePath) == DevPathConsistMappingTable[Index].Type &&
          DevicePathSubType (DevicePath) == DevPathConsistMappingTable[Index].SubType
          ) {
        SerialFun = DevPathConsistMappingTable[Index].SerialFun;
        break;
      }
    }
    //
    // If not found, use a generic function
    //
    if (!SerialFun) {
      SerialFun = _DevPathSerialDefault;
    }

    SerialFun (DevicePath, MappingItem);

    //
    // Next device path node
    //
    DevicePath = (EFI_DEVICE_PATH_PROTOCOL *) NextDevicePathNode (DevicePath);
  }

  return EFI_SUCCESS;
}

EFI_STATUS
ConsistMappingCreateHIDevicePathTable (
  EFI_DEVICE_PATH_PROTOCOL           ***HIDevicePathTable
  )
/*++

Routine Description:

  Create the empty mapping table.

Arguments:

  HIDevicePathTable - The device table

Returns:
  EFI_OUT_OF_RESOURCES - Out of resources
  EFI_SUCCESS          - Success

--*/
{
  EFI_HANDLE                *Handle;
  UINTN                     HandleNum;
  EFI_DEVICE_PATH_PROTOCOL  **Table;
  EFI_DEVICE_PATH_PROTOCOL  *DevicePath;
  EFI_DEVICE_PATH_PROTOCOL  *HIDevicePath;
  UINTN                     Index;

  Handle = NULL;

  ShellInitHandleEnumerator ();
  HandleNum = ShellGetHandleNum ();
  Table     = AllocateZeroPool ((HandleNum + 1) * sizeof (EFI_DEVICE_PATH_PROTOCOL *));
  if (HIDevicePathTable == NULL) {
    ShellCloseHandleEnumerator ();
    return EFI_OUT_OF_RESOURCES;
  }

  for (ShellNextHandle (&Handle); Handle != NULL; ShellNextHandle (&Handle)) {
    DevicePath = DevicePathFromHandle (*Handle);
    if (DevicePath == NULL) {
      continue;
    }

    HIDevicePath = GetHIDevicePath (DevicePath);
    if (HIDevicePath == NULL) {
      continue;
    }

    for (Index = 0; Table[Index] != NULL; Index++) {
      if (DevicePathCompare (Table[Index], HIDevicePath) == 0) {
        FreePool (HIDevicePath);
        break;
      }
    }

    if (Table[Index] == NULL) {
      Table[Index] = HIDevicePath;
    }
  }

  ShellCloseHandleEnumerator ();
  for (Index = 0; Table[Index] != NULL; Index++)
    ;
  DevicePathConsistMappingSort (Table, Index);
  *HIDevicePathTable = Table;
  return EFI_SUCCESS;
}

EFI_STATUS
ConsistMappingFreeHIDevicePathTable (
  EFI_DEVICE_PATH_PROTOCOL **HIDevicePathTable
  )
{
  UINTN Index;
  for (Index = 0; HIDevicePathTable[Index] != NULL; Index++) {
    FreePool (HIDevicePathTable[Index]);
  }

  FreePool (HIDevicePathTable);
  return EFI_SUCCESS;
}

CHAR16 *
ConsistMappingGenMappingName (
  EFI_DEVICE_PATH_PROTOCOL    *DevicePath,
  EFI_DEVICE_PATH_PROTOCOL    **HIDevicePathTable
  )
{
  POOL_PRINT                  Str;
  DEVICE_CONSIST_MAPPING_INFO MappingInfo;
  EFI_DEVICE_PATH_PROTOCOL    *HIDevicePath;
  UINTN                       Index;
  UINTN                       NewSize;
  HIDevicePath = GetHIDevicePath (DevicePath);
  if (HIDevicePath == NULL) {
    return NULL;
  }

  for (Index = 0; HIDevicePathTable[Index] != NULL; Index++) {
    if (DevicePathCompare (HIDevicePathTable[Index], HIDevicePath) == 0) {
      break;
    }
  }

  FreePool (HIDevicePath);
  if (HIDevicePathTable[Index] == NULL) {
    return NULL;
  }

  MappingInfo.HI      = Index;
  MappingInfo.MTD     = MTDTypeUnknown;
  MappingInfo.Digital = FALSE;

  GetDeviceConsistMappingInfo (&MappingInfo, DevicePath);

  SetMem (&Str, sizeof (Str), 0);
  for (Index = 0; mMTDName[Index].MTDType != MTDTypeEnd; Index++) {
    if (MappingInfo.MTD == mMTDName[Index].MTDType) {
      break;
    }
  }

  if (mMTDName[Index].MTDType != MTDTypeEnd) {
    CatPrint (&Str, L"%s", mMTDName[Index].Name);
  }

  CatPrint (&Str, L"%d", (UINTN) MappingInfo.HI);
  if (MappingInfo.CSD.str != NULL) {
    CatPrint (&Str, L"%s", MappingInfo.CSD.str);
  }

  NewSize           = (Str.len + 1) * sizeof (CHAR16);
  Str.str           = ReallocatePool (Str.str, NewSize, NewSize);
  Str.str[Str.len]  = 0;
  return Str.str;
}

BOOLEAN
DevicePathIsChildDevice (
  IN  EFI_DEVICE_PATH_PROTOCOL *ParentDevicePath,
  IN  EFI_DEVICE_PATH_PROTOCOL *ChildDevicePath
  )
{
  if (ParentDevicePath == NULL || ParentDevicePath == NULL) {
    return FALSE;
  }

  while (!(IsDevicePathEnd (ParentDevicePath) || IsDevicePathEnd (ChildDevicePath))) {
    if (_DevPathCompareDefault (ParentDevicePath, ChildDevicePath) != 0) {
      return FALSE;
    }

    ParentDevicePath  = (EFI_DEVICE_PATH_PROTOCOL *) NextDevicePathNode (ParentDevicePath);
    ChildDevicePath   = (EFI_DEVICE_PATH_PROTOCOL *) NextDevicePathNode (ChildDevicePath);
  }

  if (IsDevicePathEnd (ParentDevicePath)) {
    return TRUE;
  }

  return FALSE;
}


text:
import React, { PropTypes } from 'react';
import { connect } from 'react-redux';
import {
  CellsTitle,
  Button,
  Form,
  FormCell,
  CellHeader,
  CellBody,
  CellFooter,
  Label,
  Input,
  Icon,
} from 'react-weui';
import './style.less';
import {
  TitleLengthConstraint,
  DescriptionLengthConstraint,
  LocationLengthConstraint,
} from '../../constants';
import {
  nextStep,
  changeTitle,
  changeDescription,
  changeLocation,
  checkTitle,
} from '../../redux/actions/edit';

const mapStateToProps = state => ({
  title: state.create.get('title'),
  description: state.create.get('description'),
  location: state.create.get('location'),
  titleErr: state.create.get('titleErr'),
  virgin: state.create.get('virgin'),
});
class Step1 extends React.Component {
  constructor(props) {
    super(props);
    this.onChangeTitleInput = this.onChangeTitleInput.bind(this);
    this.onChangeDescriptionInput = this.onChangeDescriptionInput.bind(this);
    this.onChangeLocationInput = this.onChangeLocationInput.bind(this);
    this.onBlurCheckTitle = this.onBlurCheckTitle.bind(this);
  }
  onChangeTitleInput(e) {
    this.props.dispatch(changeTitle(e.currentTarget.value));
  }

  onChangeDescriptionInput(e) {
    this.props.dispatch(changeDescription(e.currentTarget.value));
  }

  onChangeLocationInput(e) {
    this.props.dispatch(changeLocation(e.currentTarget.value));
  }

  onBlurCheckTitle(e) {
    this.props.dispatch(checkTitle(e.currentTarget.value));
  }

  get tips() {
    const res = {};
    if (this.props.title.length > TitleLengthConstraint) {
      res.titleTip = (

            *标题过长, 请保持在{TitleLengthConstraint}字之内

      );
    }
    if (this.props.description.length > DescriptionLengthConstraint) {
      res.descriptionTip = (

            *附加信息过长, 请保持在{DescriptionLengthConstraint}字之内

      );
    }
    if (this.props.location.length > LocationLengthConstraint) {
      res.locationTip = (

            *地址过长, 请保持在{LocationLengthConstraint}字之内

      );
    }
    return res;
  }

  render() {
    const { titleTip, descriptionTip, locationTip } = this.tips;
    return (

        <CellsTitle>填写聚会基本信息</CellsTitle>
        <Form>
          <FormCell warn={this.props.titleErr || !!titleTip}>
            <CellHeader>
              标题
            </CellHeader>
            <CellBody>
              <Input
                type="text"
                placeholder={this.props.titleErr ? '标题为必填项' : '周末出来嗨'}
                onChange={this.onChangeTitleInput}
                onBlur={this.onBlurCheckTitle}
                value={this.props.title}
              />
            </CellBody>
            {this.props.titleErr || titleTip ?
              (<CellFooter><Icon value="warn" /></CellFooter>) : null
            }
          </FormCell>
          <FormCell warn={!!descriptionTip}>
            <CellHeader>
              附加信息
            </CellHeader>
            <CellBody>
              <Input
                type="text"
                placeholder="中午12点"
                onChange={this.onChangeDescriptionInput}
                value={this.props.description}
              />
            </CellBody>
            {descriptionTip ?
              (<CellFooter><Icon value="warn" /></CellFooter>) : null
            }
          </FormCell>
          <FormCell warn={!!locationTip}>
            <CellHeader>
              地址
            </CellHeader>
            <CellBody>
              <Input
                type="text"
                placeholder="国贸"
                onChange={this.onChangeLocationInput}
                value={this.props.location}
              />
            </CellBody>
            {locationTip ?
              (<CellFooter><Icon value="warn" /></CellFooter>) : null
            }
          </FormCell>
        </Form>
        {titleTip}
        {descriptionTip}
        {locationTip}

          <Button
            onClick={() => { this.props.dispatch(nextStep()); }}
            disabled={this.props.titleErr
            || this.props.virgin
            || !!titleTip
            || !!descriptionTip
            || !!locationTip}
          >
            下一步
          </Button>

    );
  }
}

Step1.propTypes = {
  title: PropTypes.string,
  description: PropTypes.string,
  location: PropTypes.string,
  titleErr: PropTypes.bool,
  virgin: PropTypes.bool,
  dispatch: PropTypes.func.isRequired,
};

export default connect(mapStateToProps)(Step1);


text:
import {Component, View} from 'angular2/angular2';
import {Router} from 'angular2/router';
import {ParseManager} from '../Model/ParseManager';

let template = require('./catCreate.html');
let styles   = require('./catCreate.css');

@Component({
  selector: 'products'
})

@View({
  styles: [ styles ],
  template: template,
})

export class CatCreate {

    constructor(public router: Router, public parseManager: ParseManager) {

    }

    createCat (event, name)
    {
        event.preventDefault();

        this.parseManager.createCategory(name, (category)=>{this.router.parent.navigate('/products');});

    }
}


text:
import-module au

function global:au_SearchReplace {
    @{
        'resharper-clt.nuspec' = @{
            "(^.+version=`")(\[.*\])(`".+$)"   = "`$1[$($Latest.MarketingVersion)]`$3"
        }
     }
}

. ..\resharper-platform\common.ps1

function global:au_GetLatest {

    return GetJetbrainsProductLatest
}

update -ChecksumFor none


text:
using System;
using System.Collections.Generic;
using Twilio;
using Twilio.Rest.Notify.V1.Service;

public class Example
{
    public static void Main(string[] args)
    {
        // Find your Account SID and Auth Token at twilio.com/console
        const string accountSid = "ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX";
        const string authToken = "your_auth_token";
        const string serviceSid = "ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX";

        TwilioClient.Init(accountSid, authToken);

        var notification = NotificationResource.Create(
            serviceSid,
            toBinding: new List<string> { "{\"binding_type\":\"sms\",\"address\":\"+15555555555\"}",
            "{\"binding_type\":\"facebook-messenger\",\"address\":\"123456789123\"}" },
            body: "Hello Bob");

        Console.WriteLine(notification.Sid);
    }
}


text:
package org.apache.isis.viewer.wicket.ui.components.collectioncontents.ajaxtable.columns;

import org.apache.wicket.Component;
import org.apache.wicket.extensions.markup.html.repeater.data.grid.ICellPopulator;
import org.apache.wicket.markup.html.basic.Label;
import org.apache.wicket.markup.repeater.Item;
import org.apache.wicket.model.IModel;

import org.apache.isis.core.metamodel.adapter.ObjectAdapter;
import org.apache.isis.core.metamodel.spec.feature.OneToOneAssociation;
import org.apache.isis.viewer.wicket.model.mementos.PropertyMemento;
import org.apache.isis.viewer.wicket.model.models.EntityModel;
import org.apache.isis.viewer.wicket.model.models.EntityModel.RenderingHint;
import org.apache.isis.viewer.wicket.model.models.ScalarModel;
import org.apache.isis.viewer.wicket.ui.ComponentFactory;
import org.apache.isis.viewer.wicket.ui.ComponentType;
import org.apache.isis.viewer.wicket.ui.app.registry.ComponentFactoryRegistry;
import org.apache.isis.viewer.wicket.ui.components.collectioncontents.ajaxtable.CollectionContentsAsAjaxTablePanel;

/**
 * A {@link ColumnAbstract column} within a
 * {@link CollectionContentsAsAjaxTablePanel} representing a single property of the
 * provided {@link ObjectAdapter}.
 *
 * <p>
 * Looks up the {@link ComponentFactory} to render the property from the
 * {@link ComponentFactoryRegistry}.
 */
public final class ObjectAdapterPropertyColumn extends ColumnAbstract<ObjectAdapter> {

    private static final long serialVersionUID = 1L;

    private final String propertyExpression;
    private final boolean escaped;

    public ObjectAdapterPropertyColumn(
            final IModel<String> columnNameModel,
            final String sortProperty,
            final String propertyName,
            final boolean escaped) {
        super(columnNameModel, sortProperty);
        this.propertyExpression = propertyName;
        this.escaped = escaped;
    }

    public Component getHeader(final String componentId)
    {
        final Label label = new Label(componentId, getDisplayModel());
        label.setEscapeModelStrings(escaped);
        return label;
    }

    @Override
    public String getCssClass() {
        final String cssClass = super.getCssClass();
        return (cssClass != null ? (cssClass + " ") : "") + propertyExpression;
    }

    @Override
    public void populateItem(final Item<ICellPopulator<ObjectAdapter>> cellItem, final String componentId, final IModel<ObjectAdapter> rowModel) {
        final Component component = createComponent(componentId, rowModel);
        cellItem.add(component);
    }

    private Component createComponent(final String id, final IModel<ObjectAdapter> rowModel) {

        final ObjectAdapter adapter = rowModel.getObject();
        final EntityModel entityModel = new EntityModel(adapter);
        final OneToOneAssociation property = (OneToOneAssociation) adapter.getSpecification().getAssociation(propertyExpression);
        final PropertyMemento pm = new PropertyMemento(property, entityModel.getIsisSessionFactory());
        final ScalarModel scalarModel = entityModel.getPropertyModel(pm);

        scalarModel.setRenderingHint(RenderingHint.PROPERTY_COLUMN);
        scalarModel.toViewMode();

        final ComponentFactory componentFactory = findComponentFactory(ComponentType.SCALAR_NAME_AND_VALUE, scalarModel);
        final Component component = componentFactory.createComponent(id, scalarModel);

        return component;
    }

}


text:
docker build -t skibuddy-live .
docker run -dt --name skibuddy-server -p 8282:8282 skibuddy-live


text:
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Net;
using System.Reflection;
using System.Text;
using System.Threading;
using System.Web;

namespace SelfServe
{
    public class HttpServer : IDisposable
    {
        public event EventHandler<RequestReceivedArgs> RequestReceived;
        public event EventHandler<ExceptionCaughtEventArgs> ExceptionCaught;
        protected readonly string RootPath;
        private readonly HttpListener Listener;
        public HttpServerConfig Config { get; private set; }

        public HttpServer(HttpServerConfig config)
        {
            Config = config;
            Listener = new HttpListener();
            Config.Bindings.ToList().ForEach(x => Listener.Prefixes.Add(x));
            RootPath = config.RootPath;
            AddFirewallAuthorization();
        }

        public void Start()
        {
            Listener.Start();

            new Action(ListenerLoop).BeginInvoke(null, null);

            Log("OK, server is ready!");
        }

        private void ListenerLoop()
        {
            while (Listener.IsListening)
            {
                IAsyncResult result = Listener.BeginGetContext(new AsyncCallback(ListenerCallback), Listener);
                result.AsyncWaitHandle.WaitOne();
            }
        }

        private void ListenerCallback(IAsyncResult result)
        {
            if (Listener.IsListening)
            {
                HttpListener listener = (HttpListener)result.AsyncState;
                HttpListenerContext context = listener.EndGetContext(result);

                using (context.Response)
                {
                    try
                    {
                        ProccessContext(context);
                    }
                    catch (Exception ex)
                    {
                        ProcessException(context, ex);
                    }
                }
            }
        }

        protected void AddFirewallAuthorization()
        {
            if (Config.AddFirewallAuthorization)
            {
                var currentLocation = System.Reflection.Assembly.GetEntryAssembly().Location;

                if (!FirewallHelper.Instance.HasAuthorization(currentLocation))
                    FirewallHelper.Instance.GrantAuthorization(currentLocation, AppDomain.CurrentDomain.FriendlyName);
            }
        }

        protected void RemoveFirewallAuthorization()
        {
            var currentLocation = System.Reflection.Assembly.GetEntryAssembly().Location;

            if (FirewallHelper.Instance.HasAuthorization(currentLocation))
                FirewallHelper.Instance.RemoveAuthorization(currentLocation);
        }

        protected virtual void ProccessContext(HttpListenerContext context)
        {
            RequestReceived.Fire(this, new RequestReceivedArgs(context));
        }

        protected virtual void ProcessException(HttpListenerContext context, Exception ex)
        {
            ExceptionCaught.Fire(this, new ExceptionCaughtEventArgs(context, ex));

            OnException(context.Request, context.Response, ex);
        }

        protected virtual void OnException(HttpListenerRequest request, HttpListenerResponse response, Exception ex)
        {
            Log("Exception has been caught... {0}", ex.Message);
        }

        protected virtual void Log(string message, params object[] args)
        {
            Console.WriteLine(message, args);
        }

        public virtual void Dispose()
        {
            try
            {
                Listener.Stop();
                Listener.Close();

                Log("Server has stopped!");
            }
            catch (Exception ex)
            {
                Log("The following issue was encountered when stopping the server: {0}", ex);
            }
            finally
            {
                RemoveFirewallAuthorization();
            }
        }
    }
}


text:
#ifndef AVCODEC_ROQVIDEO_H
#define AVCODEC_ROQVIDEO_H

#include "libavutil/lfg.h"
#include "avcodec.h"
#include "bytestream.h"

typedef struct roq_cell {
    unsigned char y[4];
    unsigned char u, v;
} roq_cell;

typedef struct roq_qcell {
    int idx[4];
} roq_qcell;

typedef struct motion_vect {
    int d[2];
} motion_vect;

struct RoqTempData;

typedef struct RoqContext {

    AVCodecContext *avctx;
    AVFrame frames[2];
    AVFrame *last_frame;
    AVFrame *current_frame;
    int first_frame;

    roq_cell cb2x2[256];
    roq_qcell cb4x4[256];

    GetByteContext gb;
    int width, height;

    /* Encoder only data */
    AVLFG randctx;
    uint64_t lambda;

    motion_vect *this_motion4;
    motion_vect *last_motion4;

    motion_vect *this_motion8;
    motion_vect *last_motion8;

    unsigned int framesSinceKeyframe;

    const AVFrame *frame_to_enc;
    uint8_t *out_buf;
    struct RoqTempData *tmpData;
} RoqContext;

#define RoQ_INFO              0x1001
#define RoQ_QUAD_CODEBOOK     0x1002
#define RoQ_QUAD_VQ           0x1011
#define RoQ_SOUND_MONO        0x1020
#define RoQ_SOUND_STEREO      0x1021

#define RoQ_ID_MOT              0x00
#define RoQ_ID_FCC              0x01
#define RoQ_ID_SLD              0x02
#define RoQ_ID_CCC              0x03

void ff_apply_vector_2x2(RoqContext *ri, int x, int y, roq_cell *cell);
void ff_apply_vector_4x4(RoqContext *ri, int x, int y, roq_cell *cell);

void ff_apply_motion_4x4(RoqContext *ri, int x, int y, int deltax, int deltay);

void ff_apply_motion_8x8(RoqContext *ri, int x, int y, int deltax, int deltay);

#endif /* AVCODEC_ROQVIDEO_H */


text:
package org.apache.hadoop.hdfs.protocolPB;

import java.io.Closeable;
import java.io.IOException;
import java.util.List;

import org.apache.hadoop.classification.InterfaceAudience;
import org.apache.hadoop.classification.InterfaceStability;
import org.apache.hadoop.hdfs.protocol.DatanodeID;
import org.apache.hadoop.hdfs.protocol.DatanodeInfo;
import org.apache.hadoop.hdfs.protocol.proto.HdfsProtos.VersionRequestProto;
import org.apache.hadoop.hdfs.protocol.proto.MomoNamenodeProtocolProtos.InformActiveToAddJNRequestProto;
import org.apache.hadoop.hdfs.protocol.proto.MomoNamenodeProtocolProtos.InformActiveToAddJNResponseProto;
import org.apache.hadoop.hdfs.protocol.proto.MomoNamenodeProtocolProtos.InformActiveToRemoveJNRequestProto;
import org.apache.hadoop.hdfs.protocol.proto.MomoNamenodeProtocolProtos.InformActiveToRemoveJNResponseProto;
import org.apache.hadoop.hdfs.protocol.proto.MomoNamenodeProtocolProtos.InformStandbyToRemoveJNRequestProto;
import org.apache.hadoop.hdfs.protocol.proto.MomoNamenodeProtocolProtos.InformStandbyToRemoveJNResponseProto;
import org.apache.hadoop.hdfs.protocol.proto.MomoNamenodeProtocolProtos.InformStandbyToAddJNRequestProto;
import org.apache.hadoop.hdfs.protocol.proto.MomoNamenodeProtocolProtos.InformStandbyToAddJNResponseProto;
import org.apache.hadoop.hdfs.server.protocol.MomoNamenodeProtocol;
import org.apache.hadoop.hdfs.protocolPB.MomoNamenodeProtocolPB;
import org.apache.hadoop.hdfs.server.protocol.*;
import org.apache.hadoop.ipc.ProtobufHelper;
import org.apache.hadoop.ipc.ProtocolMetaInterface;
import org.apache.hadoop.ipc.ProtocolTranslator;
import org.apache.hadoop.ipc.RPC;
import org.apache.hadoop.ipc.RpcClientUtil;

import com.google.protobuf.RpcController;
import com.google.protobuf.ServiceException;

/**
 * Created by kangkai on 17/6/12.
 */
@InterfaceAudience.Private
@InterfaceStability.Stable
public class MomoNamenodeProtocolTranslatorPB implements MomoNamenodeProtocol,
        ProtocolMetaInterface, Closeable, ProtocolTranslator {

    private final static RpcController NULL_CONTROLLER = null;
    final private MomoNamenodeProtocolPB rpcProxy;

    public MomoNamenodeProtocolTranslatorPB(MomoNamenodeProtocolPB rpcProxy) {
        this.rpcProxy = rpcProxy;
    }

    @Override
    public void close() throws IOException {
        RPC.stopProxy(this.rpcProxy);
    }

    @Override
    public List<UpdateJournalNodeResult> informActiveToAddJN(List<UpdateJournalNode> journalNodeList, boolean isFormatted) throws IOException {
        InformActiveToAddJNRequestProto.Builder builder  = InformActiveToAddJNRequestProto.newBuilder();
        if (journalNodeList != null) {
            builder.addAllJournalNodes(PBHelper.convertUpdateJournalNodeProto(journalNodeList));
        }
        builder.setIsFormatted(isFormatted);
        InformActiveToAddJNRequestProto req = builder.build();
        try {
            return PBHelper.convert(rpcProxy.informActiveToAddJN(NULL_CONTROLLER, req));
        } catch (ServiceException e) {
            throw ProtobufHelper.getRemoteException(e);
        }
    }

    @Override
    public List<UpdateJournalNodeResult> informActiveToRemoveJN(List<UpdateJournalNode> journalNodeList) throws IOException {
        InformActiveToRemoveJNRequestProto.Builder builder = InformActiveToRemoveJNRequestProto.newBuilder();
        if (journalNodeList != null) {
            builder.addAllJournalNodes(PBHelper.convertUpdateJournalNodeProto(journalNodeList));
        }
        InformActiveToRemoveJNRequestProto req = builder.build();
        try {
            return PBHelper.convert(rpcProxy.informActiveToRemoveJN(NULL_CONTROLLER, req));
        } catch (ServiceException e) {
            throw ProtobufHelper.getRemoteException(e);
        }
    }

    @Override
    public List<UpdateJournalNodeResult> informStandbyToAddJN(List<UpdateJournalNode> journalNodeList) throws IOException {
        InformStandbyToAddJNRequestProto.Builder builder = InformStandbyToAddJNRequestProto.newBuilder();
        if (journalNodeList != null) {
            builder.addAllJournalNodes(PBHelper.convertUpdateJournalNodeProto(journalNodeList));
        }
        InformStandbyToAddJNRequestProto req = builder.build();
        try {
            return PBHelper.convert(rpcProxy.informStandbyToAddJN(NULL_CONTROLLER, req));
        } catch (ServiceException e) {
            throw ProtobufHelper.getRemoteException(e);
        }
    }

    @Override
    public List<UpdateJournalNodeResult> informStandbyToRemoveJN(List<UpdateJournalNode> journalNodeList) throws IOException {
        InformStandbyToRemoveJNRequestProto.Builder builder = InformStandbyToRemoveJNRequestProto.newBuilder();
        if (journalNodeList != null) {
            builder.addAllJournalNodes(PBHelper.convertUpdateJournalNodeProto(journalNodeList));
        }
        InformStandbyToRemoveJNRequestProto req = builder.build();
        try {
            return PBHelper.convert(rpcProxy.informStandbyToRemoveJN(NULL_CONTROLLER, req));
        } catch (ServiceException e) {
            throw ProtobufHelper.getRemoteException(e);
        }
    }

    @Override
    public boolean isMethodSupported(String methodName) throws IOException {
        return RpcClientUtil.isMethodSupported(rpcProxy, MomoNamenodeProtocolPB.class,
                RPC.RpcKind.RPC_PROTOCOL_BUFFER,
                RPC.getProtocolVersion(MomoNamenodeProtocolPB.class), methodName);
    }

    @Override
    public Object getUnderlyingProxyObject() {
        return rpcProxy;
    }
}


text:
'use strict';
var path = require('path');
var glob = require('glob-concat');

class Files {
    get(cfg, cwd) {
        var files = glob.sync(path.join(cwd, cfg.src, '**/*.md'));
        return files;
    }
}

module.exports = new Files();


text:
package io.sundr.model;

public interface ParameterReference {
}


text:
namespace Kuno.Services
{
    /// <summary>
    /// Contains information about an event that has occurred.
    /// </summary>
    public abstract class Event
    {
    }
}


text:
class PivotTablesResponse(object):
    """NOTE: This class is auto generated by the swagger code generator program.
    Do not edit the class manually."""

    def __init__(self):
        """
        Attributes:
          swaggerTypes (dict): The key is attribute name and the value is attribute type.
          attributeMap (dict): The key is attribute name and the value is json key in definition.
        """
        self.swaggerTypes = {
            'PivotTables': 'PivotTables',
            'Code': 'str',
            'Status': 'str'

        }

        self.attributeMap = {
            'PivotTables': 'PivotTables','Code': 'Code','Status': 'Status'}

        self.PivotTables = None # PivotTables
        self.Code = None # str
        self.Status = None # str


text:
START_ATF_NAMESPACE
    struct CMonsterHierarchyVtbl
    {
        void *(WINAPIV *__vecDelDtor)(struct CMonsterHierarchy *_this, unsigned int);
    };
END_ATF_NAMESPACE


text:
use strict;
use strict;
use Cwd 'abs_path';
use File::Basename;
use File::Find;
use Module::Load;

## find the full path to the directory that this script is executing in
our $dirname;
BEGIN {
  $dirname  = dirname(abs_path($0));
}
use lib "$dirname/../modules";
use lib "$dirname/../gff-parser";
use EasyImport::Core;
use EasyImport::Compara;

## load parameters from an INI-style config file
my %sections = (
  'ENSEMBL' =>	{ 	'LOCAL' => 1
          },
  'DATABASE_COMPARA' =>	{ 	'NAME' => 1,
              'HOST' => 1,
              'PORT' => 1,
              'RW_USER' => 1,
              'RW_PASS' => 1,
              'RO_USER' => 1
            },
    'TAXA' => {},
    'ORTHOGROUP' => {  'PREFIX' => 1,
  	           'PROTEIN' => 1,
  	           'PROTEIN_ALIGN' => 1,
  	           'PROTEIN_TRIMMED' => 1,
  	           'FNAFILE' => 1,
  	           'BOUNDEDFILE' => 1,
  	           'TREE' => 1
            }
  );
## check that all required parameters have been defined in the config file
die "ERROR: you must specify at least one ini file\n",usage(),"\n" unless $ARGV[0];
my %params;
my $params = \%params;
while (my $ini_file = shift @ARGV){
	load_ini($params,$ini_file,\%sections);
}

my $lib = $params->{'ENSEMBL'}{'LOCAL'}.'/ensembl/modules';
my $comparalib = $params->{'ENSEMBL'}{'LOCAL'}.'/ensembl-compara/modules';
push @INC, $lib;
push @INC, $comparalib;
load Bio::EnsEMBL::Compara::DBSQL::DBAdaptor;
load Bio::EnsEMBL::Compara::Graph::NewickParser;
load Bio::EnsEMBL::Compara::GeneTreeNode;
load Bio::EnsEMBL::Compara::GeneTreeMember;
load Bio::EnsEMBL::Compara::SpeciesTreeNode;
load Bio::EnsEMBL::Compara::SpeciesTree;
load Bio::EnsEMBL::Compara::DBSQL::NCBITaxonAdaptor;

my $dbh = compara_db_connect($params);

our $prefix = $params->{'ORTHOGROUP'}{'PREFIX'};
# this is the current version prefix, trim the version digits at the end
$prefix =~ s/\d*$//;

my $taxlist;
foreach my $key (keys %{$params->{'TAXA'}}){
  $taxlist .= $key.'|';
}
chop $taxlist;
$params->{'ORTHOGROUP'}{'TAXA'} = $taxlist;

my ($st_nodes,$core_dbs) = fetch_species_tree_nodes($params,$dbh);

find({wanted => sub {
  my $file = $File::Find::name;
  if (!-d $file){
    if ($file =~ m/$prefix\w+$/){
      warn "importing $file\n";
      load_sequences($dbh,$params,$st_nodes,$core_dbs,$file);
    }
  }
},
no_chdir => 1},'.');

sub usage {
        return "USAGE: perl -I /path/to/dir/containing/Ensembl_Import.pm /path/to/import_homologues.pl ini_file";
}


text:
<!doctype html>

        <title>Demo: jquery-focus-exit</title>
        <meta name="viewport" content="width=device-width, initial-scale=1"/>

Demo: jquery-focus-exit

The dotted border marks the confines of the widget. Background will be grey whilst focus remains on or inside widget.

Open developer console to view debug output.

Test Area

            <input placeholder="input before widget">

text before widget

                <input placeholder="input inside widget">
                text inside widget
                <input placeholder="input inside widget">

text after widget


text:
SITENAME="https://elcri.men/"
SITENAME_NO_SLASH="https://elcri.men"

module.exports = {
  siteMetadata: {
    title: 'Delincuencia en México - El Crimen',
    author: 'Diego Valle-Jones',
    description: 'Descubre estadísticas de la delincuencia en tu estado y municipio con este mapa interactivo y reporte mensual de homicidios, secuestros, robos y más en México',
    baseUrl: `${SITENAME}`,
    siteUrl: `${SITENAME}`,
    twitterHandle: '@diegovalle',
    preliminaryINEGI: false,
    monthsPreliminaryINEGI: 12
  },
  plugins: [
    {
      resolve: `gatsby-plugin-react-helmet-canonical-urls`,
      options: {
        siteUrl: `${SITENAME_NO_SLASH}`,
      },
    },
    {
      resolve: `gatsby-plugin-netlify`,
      options: {
        headers: {
          '/elcrimen-json/*': [
            'cache-control: public',
            'cache-control: max-age=0',
            'cache-control: must-revalidate',
          ],
          '/*': [
            'Strict-Transport-Security: max-age=31536000',
            "Feature-Policy: microphone 'none'; camera 'none'; gyroscope 'none'; usb 'none'",
          ],
          '/*.html': [
            'cache-control: public',
            'cache-control: max-age=0',
            'cache-control: must-revalidate',
          ],
          '/page-data/*': [
            'cache-control: public',
            'cache-control: max-age=0',
            'cache-control: must-revalidate',
          ],
          '/en/images/infographics/fulls/*': [
            'cache-control: public',
            'cache-control: max-age=2592000',
          ],
          '/es/images/infographics/fulls/*': [
            'cache-control: public',
            'cache-control: max-age=2592000',
          ],
          '/tiles/*': [
            'Access-Control-Allow-Origin: https://elcri.men',
            'cache-control: public',
            'cache-control: max-age=2592000',
          ]
        }, // option to add more headers. `Link` headers are transformed by the below criteria
      },
    },
    {
      resolve: `gatsby-plugin-sitemap`,
      options: {
        // Exclude specific pages or groups of pages using glob parameters
        // See: https://github.com/isaacs/minimatch
        // The example below will exclude the single `path/to/page` and all routes beginning with `category`
        exclude: ['/category/*', `/en`],
        query: `
        {
          site {
            siteMetadata {
              siteUrl
            }
          }

          allSitePage {
            edges {
              node {
                path
              }
            }
          }
      }`,
        serialize: ({site, allSitePage}) =>
          allSitePage.edges.map (edge => {
            return {
              url: site.siteMetadata.siteUrl + edge.node.path,
              changefreq: `monthly`,
              priority: 0.7,
            };
          }),
      },
    },
    `gatsby-plugin-layout`,
    //`gatsby-plugin-preload-fonts`,
    // {
    //   resolve: 'gatsby-plugin-webpack-bundle-analyzer',
    //   options: {
    //     production: true,
    //   },
    // },
    // {
    //   resolve: "gatsby-plugin-guess-js",
    //   options: {
    //     // Find the view id in the GA admin in a section labeled "views"
    //     GAViewID: ``,
    //     // Add a JWT to get data from GA
    //     jwt: {
    //       client_email: `GOOGLE_SERVICE_ACCOUNT_EMAIL`,
    //       private_key: `GOOGLE_SERVICE_ACCOUNT_PRIVATE_KEY`,
    //     },
    //     minimumThreshold: 0.03,
    //     // The "period" for fetching analytic data.
    //     period: {
    //       startDate: new Date("2018-1-1"),
    //       endDate: new Date(),
    //     },
    //   },
    // },
    {
      resolve: `gatsby-source-filesystem`,
      options: {
        name: `infographics_en`,
        path: `${__dirname}/static/en/images/infographics/fulls/`,
      },
    },
    {
      resolve: `gatsby-source-filesystem`,
      options: {
        name: `infographics_es`,
        path: `${__dirname}/static/es/images/infographics/fulls/`,
      },
    },
    {
      resolve: `gatsby-source-filesystem`,
      options: {
        name: `images`,
        path: `${__dirname}/src/assets/images/`,
      },
    },
    `gatsby-transformer-json`,
    {
      resolve: `gatsby-source-filesystem`,
      options: {
        name: 'data',
        path: `${__dirname}/src/data`,
      },
    },
    `gatsby-transformer-sharp`,
    `gatsby-plugin-sharp`,
    'gatsby-plugin-react-helmet',
    {
      resolve: `gatsby-plugin-manifest`,
      options: {
        name: 'ElCri.men',
        short_name: 'elcrimen',
        start_url: '/',
        background_color: '#ffffff',
        theme_color: '#ffffff',
        display: 'minimal-ui',
        icon: `src/favicon.png`,
      },
    },
    'gatsby-plugin-sass',
    {
      resolve: `gatsby-plugin-sitemap`,
      options: {
        exclude: [`/admin`, `/tags/links`],
      },
    },
    {
      resolve: 'gatsby-plugin-robots-txt',
      options: {
        policy: [{userAgent: '*', allow: '/'}],
      },
    },
    {
      resolve: `gatsby-plugin-google-gtag`,
      options: {
        // selfHostedOrigin: "YOUR_SELF_HOSTED_ORIGIN",
        // You can add multiple tracking ids and a pageview event will be fired for all of them.
        trackingIds: [
          "G-SMLSV8EVFV", // Google Analytics / GA
        ],
      },
    },
    `gatsby-plugin-favicon`,
    /* 'gatsby-plugin-offline',*/
    {
      resolve: `gatsby-plugin-purgecss`,
      options: {
        //printRejected: true, // Print removed selectors and processed file names
        whitelistPatterns: [/.*mg-.*/, /metricsGraphicsCon/, /metrics.*/, /inegi/],
        //ignore: ['metricsgraphics.css', 'react-tabs.css'],
        purgeOnly: ['scss/style.scss', '_datepicker.css', 'top50.css','mapbox-gl.css'],
        //develop: true, // Enable while using `gatsby develop`
        // tailwind: true, // Enable tailwindcss support
        // whitelist: ['whitelist'], // Don't remove this selector
        // ignore: ['/ignored.css', 'prismjs/', 'docsearch.js/'], // Ignore files/folders
        // purgeOnly : ['components/', '/main.css', 'bootstrap/'], // Purge only these files/folders
      },
    },
  ],
};


text:
package com.skysport.interfaces.engine.listener;

import org.activiti.engine.delegate.DelegateExecution;
import org.activiti.engine.delegate.JavaDelegate;

/**
 * 说明:
 * Created by zhangjh on 2016-05-11.
 */
public abstract class EventPassListener implements JavaDelegate {

    @Override
    public void execute(DelegateExecution execution) throws Exception {
        this.executeBefore(execution);
        this.executeEnd(execution);
    }

    public void executeBefore(DelegateExecution execution) {

    }

    public void executeEnd(DelegateExecution execution) {

    }
}


text:
<?xml version="1.0" encoding="utf-8"?>
<resources>
    <string name="app_name">Phonebook</string>
    <string name="title_detail">Detail Contact</string>
    <string name="title_create">Create Contact</string>
    <string name="text_firstname">Firstname</string>
    <string name="text_lastname">Lastname</string>
    <string name="text_email">Email</string>
    <string name="text_phonenumber">Phone Number</string>
    <string name="hint_firstname">Input your firstname</string>
    <string name="hint_lastname">Input your lastname</string>
    <string name="hint_email">Input your email</string>
    <string name="hint_phonenumber">Input your phone number</string>
</resources>


text:
<!DOCTYPE html>

    <meta charset="utf-8" />
    <title>mne.split_label — MNE 0.18.2 documentation</title>
    <link rel="stylesheet" href="../_static/bootstrap-sphinx.css" type="text/css" />
    <link rel="stylesheet" href="../_static/pygments.css" type="text/css" />
    <link rel="stylesheet" type="text/css" href="../_static/gallery.css" />
    <link rel="stylesheet" type="text/css" href="../_static/bootstrap_divs.css" />
    <link rel="stylesheet" href="../_static/reset-syntax.css" type="text/css" />

    <link rel="shortcut icon" href="../_static/favicon.ico"/>
    <link rel="index" title="Index" href="../genindex.html" />
    <link rel="search" title="Search" href="../search.html" />

    <link rel="stylesheet" href="../_static/style.css " type="text/css" />
    <link rel="stylesheet" href="../_static/font-awesome.css" type="text/css" />
    <link rel="stylesheet" href="../_static/flag-icon.css" type="text/css" />

<meta charset='utf-8'>
<meta http-equiv='X-UA-Compatible' content='IE=edge,chrome=1'>
<meta name='viewport' content='width=device-width, initial-scale=1.0, maximum-scale=1'>
<meta name="apple-mobile-web-app-capable" content="yes">

  <link rel="canonical" href="https://mne.tools/stable/index.html" />

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

        </button>

        0.18.2

Install

Documentation

API

Glossary

Examples

Contribute

  Site

  <button type="button" class="btn btn-primary navbar-btn dropdown-toggle" id="dropdownMenu1" data-toggle="dropdown">
    v0.18.2

  </button>

Development

v0.18 (stable)

v0.17

v0.16

v0.15

v0.14

v0.13

v0.12

v0.11

<form class="navbar-form navbar-right" action="../search.html" method="get">

  <input type="text" name="q" class="form-control" placeholder="Search" />

  <input type="hidden" name="check_keywords" value="yes" />
  <input type="hidden" name="area" value="default" />
</form>

mne.split_label

<form action="../search.html" method="get">

  <input type="text" name="q" class="form-control" placeholder="Search" />

  <input type="hidden" name="check_keywords" value="yes" />
  <input type="hidden" name="area" value="default" />
</form>

mne.split_label¶

mne.split_label(label, parts=2, subject=None, subjects_dir=None, freesurfer=False)[source]¶

Split a Label into two or more parts.

Parameters

labelLabel | str

Label which is to be split (Label object or path to a label file).

partsint >= 2 | tuple of str

A sequence of strings specifying label names for the new labels (from
posterior to anterior), or the number of new labels to create (default
is 2). If a number is specified, names of the new labels will be the
input label's name with div1, div2 etc. appended.

subjectNone | str

Subject which this label belongs to (needed to locate surface file;
should only be specified if it is not specified in the label).

subjects_dirNone | str

Path to SUBJECTS_DIR if it is not set in the environment.

freesurferbool

By default (False) split_label uses an algorithm that is
slightly optimized for performance and numerical precision. Set
freesurfer to True in order to replicate label splits from
FreeSurfer's mris_divide_parcellation.

Returns

labelslist of Label, shape (n_parts,)

The labels, starting from the lowest to the highest end of the
projection axis.

Notes

Works by finding the label's principal eigen-axis on the spherical surface,
projecting all label vertex coordinates onto this axis and dividing them at
regular spatial intervals.

GitHub

·

Mailing list

·

Gitter

·

What's new

·

Cite MNE

Back to top

© Copyright 2012-2019, MNE Developers. Last updated on 2019-07-11.


text:
//////////////////// Macros / Defines /////////////////////////////////////////

#if _MSC_VER > 1000
#pragma once
#endif

#ifndef __AAVSOP87_URA_H__
#define __AAVSOP87_URA_H__

#ifndef AAPLUS_EXT_CLASS
#define AAPLUS_EXT_CLASS
#endif

//////////////////// Classes //////////////////////////////////////////////////

class AAPLUS_EXT_CLASS CAAVSOP87_Uranus
{
public:
  static double A(double JD) noexcept;
  static double L(double JD) noexcept;
  static double K(double JD) noexcept;
  static double H(double JD) noexcept;
  static double Q(double JD) noexcept;
  static double P(double JD) noexcept;
};

#endif //#ifndef __AAVSOP87_URA_H_


text:
package jp.co.ixui.controller.book;

import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.*;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.*;

import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.test.context.junit4.SpringRunner;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.ResultActions;
import org.springframework.test.web.servlet.setup.MockMvcBuilders;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.context.WebApplicationContext;

import jp.co.ixui.LoginUserDetails;
import jp.co.ixui.domain.MstBook;
import jp.co.ixui.domain.MstBookStock;
import jp.co.ixui.domain.MstEmp;
import jp.co.ixui.service.BookService;

/**
 * {@link BookController}のユニットテストです。

 * POSTメソッドに正常にアクセスできるかを確認しています
 * @author NAKAJIMA
 *
 */
@RunWith(SpringRunner.class)
@SpringBootTest
public class BookControllerPostTest {

	/**
	 * MockMvcのオブジェクトを作成するのに必要なアプリケーション設定
	 */
	@Autowired
	private WebApplicationContext context;

	/**
     * モックオブジェクト
     */
	private MockMvc mockMvc;

	/**
	 * テスト対象クラス
	 */
	@InjectMocks
	BookController controller;

	/**
	 * 書籍の処理クラス

	 * モック
	 */
	@Mock
	BookService service;

	/**
	 * 書籍

	 * モック
	 */
	@Mock
	MstBook mstBook;

	/**
	 * 蔵書
	 */
	MstBookStock mstBookStock = new MstBookStock();

	/**
	 * 社員
	 */
	MstEmp mstEmp = new MstEmp();

	/**
	 * MockMvcの初期設定

	 * ユーザ/蔵書の値を設定
	 */
	@Before
	public void 事前処理() throws Exception{
        this.mockMvc = MockMvcBuilders.webAppContextSetup(this.context) //モックの初期化
        		.build();

    	//ユーザ
		mstEmp.setEmpName("test");
		mstEmp.setAdminFrag("1");
		mstEmp.setEmpNum(5010);
		mstEmp.setMailAddress("test@tosyo.co.jp");
		mstEmp.setPassword("test");

		//蔵書
		mstBookStock.setBookStockId(10);
		mstBookStock.setIsbn("123-1230123011");
		mstBookStock.setOwnerEmpNum(9999);
	}

	/**
	 * 書籍の登録ページからPOSTができるかを確認しています
	 * @throws Exception
	 */
	@Test
	@Transactional
	public void 書籍登録フォーム送信できるか確認() throws Exception{

	LoginUserDetails user = new LoginUserDetails(mstEmp);
	Authentication auth = new UsernamePasswordAuthenticationToken(user, null);
	SecurityContextHolder.getContext().setAuthentication(auth);

	this.mockMvc.perform(post("/admin/book")
			.param("author",  "author")
			.param("publisher", "publishe")
			.param("publishDate", "2015/8/25")
			.param("content", "Test")
			.param("isbn",  "132-1234567890")
			.param("bookName", "TEST"))
			.andExpect(status().isFound())
			.andExpect(redirectedUrl("/admin/book"))
    		.andExpect(model().hasNoErrors());
	}

	/**
	 * 貸出ページからPOSTし、完了画面への遷移が行われているか確認しています。
	 * @throws Exception
	 */
	@Test
	@Transactional
	public void 貸出完了後の画面遷移の確認() throws Exception{

		String isbn = "123-1230123011";

	    //認証処理
		LoginUserDetails user = new LoginUserDetails(mstEmp);
		Authentication auth = new UsernamePasswordAuthenticationToken(user, null);
		SecurityContextHolder.getContext().setAuthentication(auth);

		//登録処理
	    ResultActions resultActions = mockMvc.perform(post("/admin/book")
	    		.param("bookName", "TEST")
	    		.param("author", "author")
	    		.param("publisher", "publish")
	    		.param("isbn", isbn)
	    		.param("publishDate", "2015/8/25")
	    		.param("content", "Test"));

	    //貸出完了
		mockMvc.perform(post("/reserve/{isbn}", isbn)
				.param("returnDueDate", "2017/1/13"))
			.andExpect(status().isOk())
			.andExpect(model().hasNoErrors());
	}
}


text:
<?php

namespace Symfony\Bundle\FrameworkBundle\CacheWarmer;

use Symfony\Component\Filesystem\Filesystem;
use Symfony\Component\HttpKernel\CacheWarmer\CacheWarmer;
use Symfony\Bundle\FrameworkBundle\Templating\Loader\TemplateLocator;

/**
 * Computes the association between template names and their paths on the disk.
 *
 * @author Fabien Potencier <fabien@symfony.com>
 */
class TemplatePathsCacheWarmer extends CacheWarmer
{
    protected $finder;
    protected $locator;

    /**
     * Constructor.
     *
     * @param TemplateFinderInterface $finder  A template finder
     * @param TemplateLocator         $locator The template locator
     */
    public function __construct(TemplateFinderInterface $finder, TemplateLocator $locator)
    {
        $this->finder = $finder;
        $this->locator = $locator;
    }

    /**
     * Warms up the cache.
     *
     * @param string $cacheDir The cache directory
     */
    public function warmUp($cacheDir)
    {
        $filesystem = new Filesystem();
        $templates = array();

        foreach ($this->finder->findAllTemplates() as $template) {
            $templates[$template->getLogicalName()] = rtrim($filesystem->makePathRelative($this->locator->locate($template), $cacheDir), '/');
        }

        $templates = str_replace("' => '", "' => __DIR__.'/", var_export($templates, true));

        $this->writeCacheFile($cacheDir.'/templates.php', sprintf("<?php return %s;\n", $templates));
    }

    /**
     * Checks whether this warmer is optional or not.
     *
     * @return bool always true
     */
    public function isOptional()
    {
        return true;
    }
}


text:
package com.logscale.agent;

import com.logscale.logger.Logger;
import com.sun.akuma.CLibrary;
import org.apache.commons.io.FileUtils;
import org.apache.logging.log4j.*;
import org.bouncycastle.jce.provider.BouncyCastleProvider;
import org.yaml.snakeyaml.Yaml;
import org.yaml.snakeyaml.constructor.Constructor;
import sun.misc.Signal;

import java.io.*;
import java.net.*;
import java.security.Security;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.concurrent.*;
import java.util.concurrent.atomic.AtomicBoolean;

public class Main {
    private static final String MAIN_PROPERTIES_RESOURCE = "com/logscale/agent/main.properties";

    public static final int EXIT_CODE_USAGE = 2;
    public static final int EXIT_CODE_BAD_URL = 3;
    public static final int EXIT_CODE_UNEXPECTED_FAIL = 4;

    private static final int[] FETCH_RETRY_DELAYS_SEC = {1, 2, 5, 10, 20, 30};

    private final Logger log = Logger.getLogger();

    private final URL url;

    private final AtomicBoolean isShutdown = new AtomicBoolean(false);
    private final AtomicBoolean doReload = new AtomicBoolean(false);
    private final CountDownLatch shutdownLatch = new CountDownLatch(1);

    public Main(URL url) {
        if (url == null) throw new IllegalArgumentException("null url");
        this.url = url;
    }

    private int loop() {
        log.banner(Level.INFO, () -> "starting loop: " + url.toString());

        Runtime.getRuntime().addShutdownHook(new Thread(this::shutdown, "shutdown-hook"));
        Signal.handle(new Signal("HUP"), this::signal);

        int fetchAttempt = 0;
        while (!isShutdown.get()) {
            if (doReload.get()) {
                log.debug("got reload flag: resetting...");
                fetchAttempt = 0;
            }

            doReload.set(false);
            Agent agent;
            try {
                agent = fetch();
            } catch (Exception e) {
                int delaySec = FETCH_RETRY_DELAYS_SEC[Integer.min(fetchAttempt++, FETCH_RETRY_DELAYS_SEC.length - 1)];
                log.error("trouble with fetch attempt #" + fetchAttempt + ", sleeping " + delaySec + "s before retry" + e.getMessage());
                log.trace(e);
                try {
                    for (int i = (int) (TimeUnit.SECONDS.toMillis(delaySec) / 200); i > 0 && !doReload.get(); i--) {
                        Thread.sleep(200);
                    }
                } catch (InterruptedException ie) {
                    log.warn("interrupted, shutting down", ie);
                    isShutdown.set(true);
                }
                continue;
            }
            fetchAttempt = 0;
            log.info("starting agent:\n%s", agent);
            agent.start();
            long nextHeartbeat = System.currentTimeMillis() + 30000;
            while (!doReload.get() && !isShutdown.get()) {
                if (System.currentTimeMillis() >= nextHeartbeat) {
                    log.debug("heartbeat");
                    nextHeartbeat = System.currentTimeMillis() + 30000;
                }

                try {
                    Thread.sleep(200);
                } catch (InterruptedException e) {
                    log.warn("interrupted, shutting down", e);
                    isShutdown.set(true);
                }
            }
            agent.stop();
        }

        consoleLog("loop exiting");
        shutdownLatch.countDown();
        return 0;
    }

    public void shutdown() {
        log.warn("shutdown hook called");
        ThreadContext.push("shutdown");
        try {
            isShutdown.set(true);

            consoleLog("waiting for shutdown latch");
            try {
                if (shutdownLatch.await(20, TimeUnit.SECONDS)) {
                    consoleLog("got to shutdown latch");
                } else {
                    consoleLog("timed out waiting for shutdown latch");
                }
            } catch (InterruptedException e) {
                consoleLog("WARN: got interrupted waiting for shutdown latch");
            }

            File pidfile = new File(System.getenv().getOrDefault("PIDFILE", "log/logscale-agent.pid"));
            if (!pidfile.exists()) {
                consoleLog("WARN: missing PIDFILE: " + pidfile);
            } else if (pidfile.delete()) {
                consoleLog("deleted PIDFILE: " + pidfile);
            } else {
                consoleLog("WARN: unable to delete PIDFILE: " + pidfile);
            }
        } finally {
            ThreadContext.pop();
        }

        log.warn("shutdown hook completed");
    }

    public void signal(Signal signal) {
        log.info("received signal %s", signal);
        if ("HUP".equals(signal.getName())) {
            doReload.set(true);
            log.info("set reload flag");
        } else {
            log.warn("ignoring unexpected SIG%s", signal.getName());
        }
    }

    private Agent fetch() {
        log.info("fetching: %s", url);
        try (InputStream in = url.openStream()) {
            Yaml yml = new Yaml(new Constructor(Agent.class));
            Object v = yml.load(in);
            if (v == null) {
                throw new RuntimeException("unexpected null agent config at URL " + url);
            }
            if (!v.getClass().isAssignableFrom(Agent.class)) {
                throw new RuntimeException("unexpected class (" + v.getClass() + ") from agent config at URL " + url + ": " + v);
            }
            return (Agent) v;
        } catch (IOException e) {
            throw new UncheckedIOException(e);
        }
    }

    static {
        try {
            try (InputStream is = Thread.currentThread().getContextClassLoader().getResourceAsStream(MAIN_PROPERTIES_RESOURCE)) {
                System.getProperties().load(is);
            }
        } catch (IOException e) {
            throw new UncheckedIOException("could not load main properties resource: " + MAIN_PROPERTIES_RESOURCE, e);
        }

        ThreadContext.put("pid", String.valueOf(CLibrary.LIBC.getpid()));

        Security.addProvider(new BouncyCastleProvider());
    }

    private static void writePidfile() throws Exception {
        File pidfile = new File(System.getenv().getOrDefault("PIDFILE", "log/logscale-agent.pid"));
        if (pidfile.exists()) {
            consoleLog("WARN: existing PIDFILE: " + pidfile);
        }

        String pid = String.valueOf(CLibrary.LIBC.getpid());
        FileUtils.write(pidfile, pid);
        consoleLog("wrote pid (" + pid + ") to PIDFILE (" + pidfile + ")");
    }

    public static void main(String ... args) {
        int status;
        try {

            if (args.length != 1) {
                System.err.println("Usage: logscale-agent <config-url>");
                System.err.println();
                System.err.println("   or  logscale-agent --version");
                System.err.println();
                status = EXIT_CODE_USAGE;
            } else if ("--version".equals(args[0])) {
                System.out.println("logscale-agent version " + System.getProperty("logscale.agent.version"));
                status = 0;
            } else {
                URL url = new URL(args[0]);
                writePidfile();
                status = new Main(url).loop();
            }
        } catch (MalformedURLException e) {
            System.err.println("illegal config-url: " + e.getMessage());
            status = EXIT_CODE_BAD_URL;
        } catch (Throwable t) {
            consoleLog("FATAL: unexpected failure");
            t.printStackTrace();
            try { Thread.sleep(2000); } catch (InterruptedException ignore) { }
            status = EXIT_CODE_UNEXPECTED_FAIL;
        }
        System.exit(status);
    }

    private static synchronized void consoleLog(String message) {
        String date = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss,SSS").format(new Date());
        System.err.printf("%s %s\n", date, message);
    }
}