text:
#region LGPL License

#endregion LGPL License

#region SVN Version Information

// <file>
//     <license see="http://axiom3d.net/wiki/index.php/license.txt"/>
//     <id value="$Id: TextureManager.cs 2953 2012-01-10 04:44:59Z borrillis $"/>
// </file>

#endregion SVN Version Information

#region Namespace Declarations

using System;

using Disseminate.Graphics;
using Disseminate.Media;
using Disseminate.Math;

#endregion Namespace Declarations

namespace Disseminate.Core
{
    /// <summary>
    ///    Class for loading & managing textures.
    /// </summary>
    /// <remarks>
    ///    Texture manager serves as an abstract singleton for all API specific texture managers.
    ///		When a class inherits from this and is created, a instance of that class (i.e. GLTextureManager)
    ///		is stored in the global singleton instance of the TextureManager.
    ///		Note: This will not take place until the RenderSystem is initialized and at least one RenderWindow
    ///		has been created.
    /// </remarks>
    abstract public class TextureManager : ResourceManager
    {
        #region Singleton implementation

        /// <summary>
        ///     Singleton instance of this class.
        /// </summary>
        private static TextureManager instance;

        /// <summary>
        ///     Internal constructor.  This class cannot be instantiated externally.
        /// </summary>
        /// <remarks>
        ///     Protected internal because this singleton will actually hold the instance of a subclass
        ///     created by a render system plugin.
        /// </remarks>
        protected internal TextureManager()
            : base()
        {
            if (instance == null)
            {
                instance = this;
                ResourceType = "Texture";
                LoadingOrder = 75.0f;
            }
            else
            {
                throw new AxiomException("Cannot create another instance of {0}. Use Instance property instead", this.GetType().Name);
            }
        }

        /// <summary>
        ///     Gets the singleton instance of this class.
        /// </summary>
        public static TextureManager Instance { get { return instance; } }

        #endregion Singleton implementation

        #region Fields and Properties

        #region Is32Bit Property

        /// <summary>
        ///    Flag that indicates whether 32-bit texture are being used.
        /// </summary>
        private bool _is32Bit;

        /// <summary>
        ///    Flag that indicates whether 32-bit texture are being used.
        /// </summary>
        public bool Is32Bit { get { return _is32Bit; } protected set { _is32Bit = value; } }

        #endregion Is32Bit Property

        #region DefaultMipmapCount Property

        /// <summary>
        ///    Default number of mipmaps to be used for loaded textures.
        /// </summary>
        protected int _defaultMipmapCount = 5;

        /// <summary>
        ///    Gets/Sets the default number of mipmaps to be used for loaded textures.
        /// </summary>
        public int DefaultMipmapCount { get { return _defaultMipmapCount; } set { _defaultMipmapCount = value; } }

        #endregion DefaultMipmapCount Property

        #region PreferredXXXBitDepth Properties

        #region PreferredIntegerBitDepth Property

        private ushort _preferredIntegerBitDepth = 0;

        public ushort PreferredIntegerBitDepth { get { return _preferredIntegerBitDepth; } set { SetPreferredIntegerBitDepth(value, false); } }

        public void SetPreferredIntegerBitDepth(ushort bits, bool reloadTextures)
        {
            _preferredIntegerBitDepth = bits;

            if (reloadTextures)
            {
                // Iterate throught all textures
                foreach (Texture texture in Resources)
                {
                    // Reload loaded and reloadable texture only
                    if (texture.IsLoaded && texture.IsReloadable)
                    {
                        texture.Unload();
                        texture.DesiredIntegerBitDepth = bits;
                        texture.Load();
                    }
                    else
                    {
                        texture.DesiredIntegerBitDepth = bits;
                    }
                }
            }
        }

        #endregion PreferredIntegerBitDepth Property

        #region PreferredFloatBitDepth Property

        private ushort _preferredFloatBitDepth = 0;
        public ushort PreferredFloatBitDepth { get { return _preferredFloatBitDepth; } set { SetPreferredFloatBitDepth(value, false); } }

        public void SetPreferredFloatBitDepth(ushort bits, bool reloadTextures)
        {
            _preferredFloatBitDepth = bits;

            if (reloadTextures)
            {
                // Iterate throught all textures
                foreach (Texture texture in Resources)
                {
                    // Reload loaded and reloadable texture only
                    if (texture.IsLoaded && texture.IsReloadable)
                    {
                        texture.Unload();
                        texture.DesiredFloatBitDepth = bits;
                        texture.Load();
                    }
                    else
                    {
                        texture.DesiredFloatBitDepth = bits;
                    }
                }
            }
        }

        #endregion PreferredFloatBitDepth Property

        public void SetPreferredBitDepths(ushort integerBits, ushort floatBits, bool reloadTextures)
        {
            _preferredFloatBitDepth = floatBits;
            _preferredIntegerBitDepth = integerBits;

            if (reloadTextures)
            {
                // Iterate throught all textures
                foreach (Texture texture in Resources)
                {
                    // Reload loaded and reloadable texture only
                    if (texture.IsLoaded && texture.IsReloadable)
                    {
                        texture.Unload();
                        texture.SetDesiredBitDepths(integerBits, floatBits);
                        texture.Load();
                    }
                    else
                    {
                        texture.SetDesiredBitDepths(integerBits, floatBits);
                    }
                }
            }
        }

        #endregion PreferredXXXBitDepth Properties

        #endregion Fields and Properties

        #region Methods

        /// <summary>
        /// Create a manual texture with specified width, height and depth (not loaded from a file).
        /// </summary>
        /// <param name="name">The name to give the resulting texture</param>
        /// <param name="group">The name of the resource group to assign the texture to</param>
        /// <param name="type">The type of texture to load/create, defaults to normal 2D textures</param>
        /// <param name="width">The dimensions of the texture</param>
        /// <param name="height">The dimensions of the texture</param>
        /// <param name="depth">The dimensions of the texture</param>
        /// <param name="numMipMaps">
        /// The number of pre-filtered mipmaps to generate. If left to MIP_DEFAULT then
        /// the TextureManager's default number of mipmaps will be used (see setDefaultNumMipmaps()).
        /// If set to MIP_UNLIMITED mipmaps will be generated until the lowest possible
        /// level, 1x1x1.
        /// </param>
        /// <param name="format">
        /// The internal format you wish to request; the manager reserves
        /// the right to create a different format if the one you select is
        /// not available in this context.
        /// </param>
        /// <param name="usage">
        /// The kind of usage this texture is intended for. It
        /// is a combination of TU_STATIC, TU_DYNAMIC, TU_WRITE_ONLY,
        /// TU_AUTOMIPMAP and TU_RENDERTARGET (see TextureUsage enum). You are
        /// strongly advised to use HBU_STATIC_WRITE_ONLY wherever possible, if you need to
        /// update regularly, consider HBU_DYNAMIC_WRITE_ONLY.
        /// </param>
        /// <param name="loader">
        /// If you intend the contents of the manual texture to be
        /// regularly updated, to the extent that you don't need to recover
        /// the contents if the texture content is lost somehow, you can leave
        /// this parameter as null. However, if you intend to populate the
        /// texture only once, then you should implement ManualResourceLoader
        /// and pass a pointer to it in this parameter; this means that if the
        /// manual texture ever needs to be reloaded, the ManualResourceLoader
        /// will be called to do it.
        /// </param>
        /// <returns></returns>
        public Texture CreateManual(string name, string group, TextureType type, int width, int height, int depth, int numMipMaps, PixelFormat format, TextureUsage usage, IManualResourceLoader loader, bool hwGammaCorrection, int fsaa, string fsaaHint)
        {
            Texture ret = (Texture)Create(name, group, true, loader, null);
            ret.TextureType = type;
            ret.Width = width;
            ret.Height = height;
            ret.Depth = depth;
            ret.MipmapCount = (numMipMaps == -1) ? _defaultMipmapCount : numMipMaps;
            ret.Format = format;
            ret.Usage = usage;
            ret.HardwareGammaEnabled = hwGammaCorrection;
            ret.SetFSAA(fsaa, fsaaHint);
            ret.CreateInternalResources();
            return ret;
        }

        /// <summary>
        /// Create a manual texture with a depth of 1 (not loaded from a file).
        /// </summary>
        /// <param name="name">The name to give the resulting texture</param>
        /// <param name="group">The name of the resource group to assign the texture to</param>
        /// <param name="type">The type of texture to load/create, defaults to normal 2D textures</param>
        /// <param name="width">The dimensions of the texture</param>
        /// <param name="height">The dimensions of the texture</param>
        /// <param name="numMipMaps">
        /// The number of pre-filtered mipmaps to generate. If left to MIP_DEFAULT then
        /// the TextureManager's default number of mipmaps will be used (see setDefaultNumMipmaps()).
        /// If set to MIP_UNLIMITED mipmaps will be generated until the lowest possible
        /// level, 1x1x1.
        /// </param>
        /// <param name="format">
        /// The internal format you wish to request; the manager reserves
        /// the right to create a different format if the one you select is
        /// not available in this context.
        /// </param>
        /// <param name="usage">
        /// The kind of usage this texture is intended for. It
        /// is a combination of TU_STATIC, TU_DYNAMIC, TU_WRITE_ONLY,
        /// TU_AUTOMIPMAP and TU_RENDERTARGET (see TextureUsage enum). You are
        /// strongly advised to use HBU_STATIC_WRITE_ONLY wherever possible, if you need to
        /// update regularly, consider HBU_DYNAMIC_WRITE_ONLY.
        /// </param>
        /// <param name="loader">
        /// If you intend the contents of the manual texture to be
        /// regularly updated, to the extent that you don't need to recover
        /// the contents if the texture content is lost somehow, you can leave
        /// this parameter as null. However, if you intend to populate the
        /// texture only once, then you should implement ManualResourceLoader
        /// and pass a pointer to it in this parameter; this means that if the
        /// manual texture ever needs to be reloaded, the ManualResourceLoader
        /// will be called to do it.
        /// </param>
        /// <returns></returns>
        public Texture CreateManual(string name, string group, TextureType type, int width, int height, int numMipmaps, PixelFormat format, TextureUsage usage, IManualResourceLoader loader)
        {
            return CreateManual(name, group, type, width, height, 1, numMipmaps, format, usage, loader, false, 0, String.Empty);
        }

        /// <summary>
        /// Create a manual texture with a depth of 1 (not loaded from a file).
        /// </summary>
        /// <param name="name">The name to give the resulting texture</param>
        /// <param name="group">The name of the resource group to assign the texture to</param>
        /// <param name="type">The type of texture to load/create, defaults to normal 2D textures</param>
        /// <param name="width">The dimensions of the texture</param>
        /// <param name="height">The dimensions of the texture</param>
        /// <param name="numMipMaps">
        /// The number of pre-filtered mipmaps to generate. If left to MIP_DEFAULT then
        /// the TextureManager's default number of mipmaps will be used (see setDefaultNumMipmaps()).
        /// If set to MIP_UNLIMITED mipmaps will be generated until the lowest possible
        /// level, 1x1x1.
        /// </param>
        /// <param name="format">
        /// The internal format you wish to request; the manager reserves
        /// the right to create a different format if the one you select is
        /// not available in this context.
        /// </param>
        /// <param name="usage">
        /// The kind of usage this texture is intended for. It
        /// is a combination of TU_STATIC, TU_DYNAMIC, TU_WRITE_ONLY,
        /// TU_AUTOMIPMAP and TU_RENDERTARGET (see TextureUsage enum). You are
        /// strongly advised to use HBU_STATIC_WRITE_ONLY wherever possible, if you need to
        /// update regularly, consider HBU_DYNAMIC_WRITE_ONLY.
        /// </param>
        /// <returns></returns>
        public Texture CreateManual(string name, string group, TextureType type, int width, int height, int numMipmaps, PixelFormat format, TextureUsage usage)
        {
            return CreateManual(name, group, type, width, height, 1, numMipmaps, format, usage, null, false, 0, String.Empty);
        }

        public Texture CreateManual(string name, string group, TextureType type, int width, int height, int numMipmaps, PixelFormat format)
        {
            return CreateManual(name, group, type, width, height, 1, numMipmaps, format, TextureUsage.Default, null, false, 0, String.Empty);
        }

        public Texture CreateManual(string name, string group, TextureType type, int width, int height, int numMipmaps, PixelFormat format, TextureUsage usage, IManualResourceLoader loader, bool hwGammaCorrection)
        {
            return CreateManual(name, group, type, width, height, numMipmaps, format, usage, loader, hwGammaCorrection, 0, string.Empty);
        }

        public Texture CreateManual(string name, string group, TextureType type, int width, int height, int numMipmaps, PixelFormat format, TextureUsage usage, IManualResourceLoader loader, bool hwGammaCorrection, int fsaa)
        {
            return CreateManual(name, group, type, width, height, numMipmaps, format, usage, loader, hwGammaCorrection, fsaa, string.Empty);
        }

        public Texture CreateManual(string name, string group, TextureType type, int width, int height, int numMipmaps, PixelFormat format, TextureUsage usage, IManualResourceLoader loader, bool hwGammaCorrection, int fsaa, string fsaaHint)
        {
            return CreateManual(name, group, type, width, height, 1, numMipmaps, format, usage, loader, hwGammaCorrection, fsaa, string.Empty);
        }

        public Texture CreateManual(string name, string group, TextureType type, int width, int height, int depth, int numMipmaps, PixelFormat format, TextureUsage usage, IManualResourceLoader loader)
        {
            return CreateManual(name, group, type, width, height, depth, numMipmaps, format, usage, loader, false, 0, string.Empty);
        }

        public Texture CreateManual(string name, string group, TextureType type, int width, int height, int depth, int numMipmaps, PixelFormat format, TextureUsage usage, IManualResourceLoader loader, bool hwGammaCorrection)
        {
            return CreateManual(name, group, type, width, height, depth, numMipmaps, format, usage, loader, hwGammaCorrection, 0, string.Empty);
        }

        public Texture CreateManual(string name, string group, TextureType type, int width, int height, int depth, int numMipmaps, PixelFormat format, TextureUsage usage, IManualResourceLoader loader, bool hwGammaCorrection, int fsaa)
        {
            return CreateManual(name, group, type, width, height, depth, numMipmaps, format, usage, loader, hwGammaCorrection, fsaa, string.Empty);
        }

        /// <summary>
        ///    Loads a texture with the specified name.
        /// </summary>
        /// <param name="name"></param>
        /// <returns></returns>
        public Texture Load(string name, string group)
        {
            return Load(name, group, TextureType.TwoD);
        }

        /// <summary>
        ///
        /// </summary>
        /// <param name="name"></param>
        /// <returns></returns>
        public Texture Load(string name, string group, TextureType type)
        {
            // load the texture by default with -1 mipmaps (uses default), gamma of 1, isAlpha of false
            return Load(name, group, type, -1, 1.0f, false);
        }

        public Texture Load(string name, string group, TextureType type, int numMipMaps)
        {
            // load the texture by default with -1 mipmaps (uses default), gamma of 1, isAlpha of false
            return Load(name, group, type, numMipMaps, 1.0f, false);
        }

        /// <summary>
        ///
        /// </summary>
        /// <param name="name"></param>
        /// <param name="numMipMaps"></param>
        /// <param name="gamma"></param>
        /// <param name="priority"></param>
        /// <returns></returns>
        public Texture Load(string name, string group, TextureType type, int numMipMaps, float gamma, bool isAlpha)
        {
            return Load(name, group, type, numMipMaps, gamma, false, PixelFormat.Unknown);
        }

        /// <summary>
        ///
        /// </summary>
        /// <param name="name"></param>
        /// <param name="group"></param>
        /// <param name="type"></param>
        /// <param name="numMipMaps"></param>
        /// <param name="gamma"></param>
        /// <param name="isAlpha"></param>
        /// <param name="desiredFormat"></param>
        /// <returns></returns>
        public Texture Load(string name, string group, TextureType type, int numMipMaps, float gamma, bool isAlpha, PixelFormat desiredFormat)
        {
            // does this texture exist already?
            Tuple<Resource, bool> result = CreateOrRetrieve(name, group);

            Texture texture = (Texture)result.First;

            // was it created?
            if (result.Second == true)
            {
                texture.TextureType = type;
                texture.MipmapCount = (numMipMaps == -1) ? _defaultMipmapCount : numMipMaps;
                // set bit depth and gamma
                texture.Gamma = gamma;
                texture.TreatLuminanceAsAlpha = isAlpha;
                texture.Format = desiredFormat;
            }
            texture.Load();

            return texture;
        }

        /// <summary>
        /// Loads a pre-existing image into the texture.
        /// </summary>
        /// <param name="name"></param>
        /// <param name="group"></param>
        /// <param name="image"></param>
        /// <returns></returns>
        public Texture LoadImage(string name, string group, Image image)
        {
            return LoadImage(name, group, image, TextureType.TwoD);
        }

        /// <summary>
        /// Loads a pre-existing image into the texture.
        /// </summary>
        /// <param name="name"></param>
        /// <param name="group"></param>
        /// <param name="image"></param>
        /// <param name="texType"></param>
        /// <returns></returns>
        public Texture LoadImage(string name, string group, Image image, TextureType texType)
        {
            return LoadImage(name, group, image, texType, -1, 1.0f, false, PixelFormat.Unknown);
        }

        /// <summary>
        ///		Loads a pre-existing image into the texture.
        /// </summary>
        /// <param name="name"></param>
        /// <param name="image"></param>
        /// <param name="numMipMaps"></param>
        /// <param name="gamma"></param>
        /// <param name="priority"></param>
        /// <returns></returns>
        public Texture LoadImage(string name, string group, Image image, TextureType texType, int numMipMaps, float gamma, bool isAlpha, PixelFormat desiredFormat)
        {
            // create a new texture
            Texture texture = (Texture)Create(name, group, true, null, null);

            texture.TextureType = texType;
            // set the number of mipmaps to use for this texture
            texture.MipmapCount = (numMipMaps == -1) ? _defaultMipmapCount : numMipMaps;

            // set bit depth and gamma
            texture.Gamma = gamma;

            texture.TreatLuminanceAsAlpha = isAlpha;
            texture.Format = desiredFormat;

            // load image data
            texture.LoadImage(image);

            return texture;
        }

        /// <summary>
        ///    Returns an instance of Texture that has the supplied name.
        /// </summary>
        /// <param name="name"></param>
        /// <returns></returns>
        new public Texture this[string name] { get { return (Texture)base[name]; } }

        /// <summary>
        ///     Called when the engine is shutting down.
        /// </summary>
        protected override void dispose(bool disposeManagedResources)
        {
            if (!this.IsDisposed)
            {
                if (disposeManagedResources)
                {
                    if (this == instance)
                    {
                        instance = null;
                    }

                    foreach (Texture texture in Resources)
                    {
                        if (!texture.IsDisposed)
                        {
                            texture.Dispose();
                        }
                    }
                }

                // There are no unmanaged resources to release, but
                // if we add them, they need to be released here.
            }

            // If it is available, make the call to the
            // base class's Dispose(Boolean) method
            base.dispose(disposeManagedResources);
        }

        virtual public PixelFormat GetNativeFormat(TextureType ttype, PixelFormat format,
                                                    TextureUsage usage)
        {
            // Just throw an error, for non-overriders
            throw new NotImplementedException();
        }

        public bool IsFormatSupported(TextureType ttype, PixelFormat format, TextureUsage usage)
        {
            return GetNativeFormat(ttype, format, usage) == format;
        }

        public bool IsEquivalentFormatSupported(TextureType ttype, PixelFormat format, TextureUsage usage)
        {
            PixelFormat supportedFormat = GetNativeFormat(ttype, format, usage);
            // Assume that same or greater number of bits means quality not degraded
            return PixelUtil.GetNumElemBits(supportedFormat) >= PixelUtil.GetNumElemBits(format);
        }

        virtual public int AvailableTextureMemory { get { throw new NotImplementedException(); } }

        #endregion Methods
    }
}


text:
namespace v8 {
namespace internal {

class LazyBuiltinsAssembler : public CodeStubAssembler {
 public:
  using Descriptor = JSTrampolineDescriptor;

  explicit LazyBuiltinsAssembler(compiler::CodeAssemblerState* state)
      : CodeStubAssembler(state) {}

  void GenerateTailCallToJSCode(TNode<Code> code, TNode<JSFunction> function);

  void GenerateTailCallToReturnedCode(Runtime::FunctionId function_id,
                                      TNode<JSFunction> function);
  void TailCallRuntimeIfMarkerEquals(TNode<Smi> marker,
                                     OptimizationMarker expected_marker,
                                     Runtime::FunctionId function_id,
                                     TNode<JSFunction> function);

  void MaybeTailCallOptimizedCodeSlot(TNode<JSFunction> function,
                                      TNode<FeedbackVector> feedback_vector);
  void CompileLazy(TNode<JSFunction> function);
};

}  // namespace internal
}  // namespace v8

#endif  // V8_BUILTINS_BUILTINS_LAZY_GEN_H_

redpajama_set_name: RedPajamaGithub


text:
var ReadStream = require("read-stream")
    , LevelWriteStream = require("level-write-stream")
    , extend = require("xtend")
    , getOptions = require("./utils/getOptions")
    , toKeyBuffer = require("level-encoding/toKeyBuffer")
    , makeStreamData = require("level-encoding/makeStreamData")

module.exports = Streams

function Streams(onReady, db, defaults) {
    return {
        readStream: readStream
        , writeStream: LevelWriteStream(db)
        , keyStream: keyStream
        , valueStream: valueStream
    }

    function readStream(options) {
        options = getOptions(defaults, options)
        var start = options.start
            , end = options.end
            , range = null
            , queue = ReadStream()
            , stream = queue.stream

        onReady(_open)

        return stream

        function _open(idb) {
            if (start || end) {
                range = idb.makeKeyRange({
                    lower: toKeyBuffer(start, options)
                    , upper: toKeyBuffer(end, options)
                })
            }

            idb.iterate(function onItem(value) {
                queue.push(makeStreamData(value, options))
            }, extend({
                keyRange: range
                , order: options.reverse ? "DESC" : "ASC"
                , onEnd: queue.end
                , onError: emit
            }, options))
        }
    }

    function keyStream(options) {
        return readStream(extend(options || {}, {
            keys: true
            , values: false
        }))
    }

    function valueStream(options) {
        return readStream(extend(options || {}, {
            keys: false
            , values: true
        }))
    }

    function emit(err) {
        db.emit("error", err)
    }
}


text:
<resources>
    <string name="app_name">BoxSched</string>
</resources>


text:
module TDev { export module RT {
    //? true or false
    //@ stem("b") icon("CheckBox") immutable isData builtin ctx(general,indexkey,cloudfield,json)
    //@ robust
    export module Boolean_
    {

        //? Indicates that the two values are equal
        export function equals(self:boolean, right:boolean) : boolean { return self === right; }

        //? Negates the boolean expression
        //@ infixPriority(4)
        export function not(self:boolean) : boolean { return !self; }

        //? Builds conjunction
        //@ infixPriority(3)
        export function and(self:boolean, right:boolean) : boolean { return self && right; }
        // not really used

        //? Builds disjunction
        //@ infixPriority(2)
        export function or(self:boolean, right:boolean) : boolean { return self || right; }
        // not really used

        //? Converts a boolean to a string
        export function to_string(self:boolean) : string { return self ? "true" : "false"; }

        //? Converts true to 1 and false to 0
        export function to_number(self:boolean) : number { return self ? 1 : 0; }

        //? Displays the value on the wall
        export function post_to_wall(self:boolean, s:IStackFrame)
        {
            s.rt.postBoxedText(to_string(self), s.pc);
        }

        export function from_string(s: string) { return s === "true"; }

        export function picker()
        {
            var inp = HTML.mkCheckBox(lf("true?"));
            return <IPicker>{
                html: inp,
                validate: () => true,
                get: () => HTML.getCheckboxValue(inp),
                set: (v) => HTML.setCheckboxValue(inp, v)
            };
        }

        //? Converts the value into a json data structure.
        export function to_json(self: boolean): JsonObject {
            return JsonObject.wrap(self);
        }
    }
} }


text:
    <ng-form name="datePickerForm">

            <input name="datepicker" data-format="{{model.config.format}}" id="{{model.alias}}" type="text"
                   ng-model="datetimePickerValue"
                   ng-required="model.validation.mandatory"
                   val-server="value"
                   class="datepickerinput" />

        Required
        {{datePickerForm.datepicker.errorMsg}}
        Invalid date

            <localize key="content_removeDate">Clear date</localize>

    </ng-form>


text:
module.exports = function(grunt) {

  grunt.initConfig({
    pkg: grunt.file.readJSON('package.json'),

    // Compile SASS
    sass: {
      dist: {
        options: {
          style: 'expanded'
        },
        files: {
          'assets/styles/css/main.css': 'assets/styles/_scss/*.scss'       // 'destination': 'source'
        }
      }
    },

    // Live Reload watching for SCSS changes
    watch: {
      sass: {
        files: '**/*.scss',
        tasks: ['sass'],
        options: {
          livereload: true
        }
      }
    }

  });

  grunt.loadNpmTasks('grunt-contrib-sass');
  grunt.loadNpmTasks('grunt-contrib-watch');

  // Default task(s).
  grunt.registerTask('default', ['watch']);

  grunt.registerTask('sass', ['sass']);

};


text:
BIN="stage1"

ASFLAGS="-I../common/"

all:
	nasm $(ASFLAGS) -f bin -o stage1 stage1.s
clean:
	-rm -f stage1 read floppy print

read:
	nasm -f bin -o read read.s

floppy:
	nasm -f bin -o floppy floppy.s

print:
	nasm -f bin -o print print.s

# Dump assembly code and object code so it's easier to see what is taking up
# space. To see a different binary use: make BIN=binary
dump:
	objdump -b binary -D -m i8086 $(BIN)

# make should not check if the file is up to date
.PHONY: all clean read dumpc floppy print


text:
package javax.xml.transform;

/**
 * An object that implements this interface contains the information
 * needed to act as source input (XML source or transformation instructions).
 */
public interface Source {

    /**
     * Set the system identifier for this Source.
     *
     *
The system identifier is optional if the source does not
     * get its data from a URL, but it may still be useful to provide one.
     * The application can use a system identifier, for example, to resolve
     * relative URIs and to include in error messages and warnings.

     *
     * @param systemId The system identifier as a URL string.
     */
    public void setSystemId(String systemId);

    /**
     * Get the system identifier that was set with setSystemId.
     *
     * @return The system identifier that was set with setSystemId, or null
     * if setSystemId was not called.
     */
    public String getSystemId();
}


text:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

#include "unity/examples/unity_config.h"
#include "unity/src/unity.h"
#include "common.h"
#include "../cJSON_Utils.h"

static void cjson_utils_functions_shouldnt_crash_with_null_pointers(void)
{
    cJSON *item = cJSON_CreateString("item");
    TEST_ASSERT_NOT_NULL(item);

    TEST_ASSERT_NULL(cJSONUtils_GetPointer(item, NULL));
    TEST_ASSERT_NULL(cJSONUtils_GetPointer(NULL, "pointer"));
    TEST_ASSERT_NULL(cJSONUtils_GetPointerCaseSensitive(NULL, "pointer"));
    TEST_ASSERT_NULL(cJSONUtils_GetPointerCaseSensitive(item, NULL));
    TEST_ASSERT_NULL(cJSONUtils_GeneratePatches(item, NULL));
    TEST_ASSERT_NULL(cJSONUtils_GeneratePatches(NULL, item));
    TEST_ASSERT_NULL(cJSONUtils_GeneratePatchesCaseSensitive(item, NULL));
    TEST_ASSERT_NULL(cJSONUtils_GeneratePatchesCaseSensitive(NULL, item));
    cJSONUtils_AddPatchToArray(item, "path", "add", NULL);
    cJSONUtils_AddPatchToArray(item, "path", NULL, item);
    cJSONUtils_AddPatchToArray(item, NULL, "add", item);
    cJSONUtils_AddPatchToArray(NULL, "path", "add", item);
    cJSONUtils_ApplyPatches(item, NULL);
    cJSONUtils_ApplyPatches(NULL, item);
    cJSONUtils_ApplyPatchesCaseSensitive(item, NULL);
    cJSONUtils_ApplyPatchesCaseSensitive(NULL, item);
    TEST_ASSERT_NULL(cJSONUtils_MergePatch(item, NULL));
    item = cJSON_CreateString("item");
    TEST_ASSERT_NULL(cJSONUtils_MergePatchCaseSensitive(item, NULL));
    item = cJSON_CreateString("item");
    /* these calls are actually valid */
    /* cJSONUtils_MergePatch(NULL, item); */
    /* cJSONUtils_MergePatchCaseSensitive(NULL, item);*/
    /* cJSONUtils_GenerateMergePatch(item, NULL); */
    /* cJSONUtils_GenerateMergePatch(NULL, item); */
    /* cJSONUtils_GenerateMergePatchCaseSensitive(item, NULL); */
    /* cJSONUtils_GenerateMergePatchCaseSensitive(NULL, item); */

    TEST_ASSERT_NULL(cJSONUtils_FindPointerFromObjectTo(item, NULL));
    TEST_ASSERT_NULL(cJSONUtils_FindPointerFromObjectTo(NULL, item));
    cJSONUtils_SortObject(NULL);
    cJSONUtils_SortObjectCaseSensitive(NULL);

    cJSON_Delete(item);
}

int main(void)
{
    UNITY_BEGIN();

    RUN_TEST(cjson_utils_functions_shouldnt_crash_with_null_pointers);

    return UNITY_END();
}


text:
package ajeetmurty.reference.java.regex;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class FileParse {
	private final Logger logp = LoggerFactory.getLogger(this.getClass().getName());
	private final String inputLogFilePath = "input/regex.log";
	private final String regex = "^(\\S+)\\s(.*)$";

	public static void main(String[] args) {
		new FileParse();
	}

	private FileParse() {
		logp.info("start");
		parseFile();
		logp.info("stop");
	}

	private void parseFile() {
		try {
			logp.info("input log file path: " + inputLogFilePath);
			File inputFile = new File(inputLogFilePath);
			if (inputFile.isFile() && inputFile.canRead()) {
				Pattern pattern = Pattern.compile(regex);
				Matcher matcher = pattern.matcher("");

				BufferedReader br = new BufferedReader(new FileReader(inputFile));
				long linesTotal = 0, linesMatched = 0;
				String line = null;
				while ((line = br.readLine()) != null) {
					linesTotal++;
					if (matcher.reset(line).matches()) {
						linesMatched++;
						logp.info(String.format("line matched & host extracted: >%1$s<", matcher.group(1)));
					} else {
						logp.error("line not matched: " + line);
					}
				}
				br.close();

				logp.info("total lines in file: " + linesTotal);
				logp.info("total matches: " + linesMatched);
				logp.info("match failed: " + (linesTotal - linesMatched));
			} else {
				logp.error("input log file not found / not readable");
			}
		} catch (Exception e) {
			logp.error(e.getMessage(), e);
		}
	}
}


text:
package client

import (
	"context"
	"reflect"
	"testing"
	"time"

	"github.com/golang/protobuf/ptypes/empty"
	"github.com/google/keytransparency/core/testutil"
	"github.com/google/trillian"
	"github.com/google/trillian/types"
	"github.com/kylelemons/godebug/pretty"
	"google.golang.org/grpc/codes"
	"google.golang.org/grpc/status"

	pb "github.com/google/keytransparency/core/api/v1/keytransparency_go_proto"
)

func TestMapRevisionFor(t *testing.T) {
	for _, tc := range []struct {
		treeSize     uint64
		wantRevision uint64
		wantErr      error
	}{
		{treeSize: 1, wantRevision: 0},
		{treeSize: 0, wantRevision: 0, wantErr: ErrLogEmpty},
		{treeSize: ^uint64(0), wantRevision: ^uint64(0) - 1},
	} {
		revision, err := mapRevisionFor(&types.LogRootV1{TreeSize: tc.treeSize})
		if got, want := revision, tc.wantRevision; got != want {
			t.Errorf("mapRevisionFor(%v).Revision: %v, want: %v", tc.treeSize, got, want)
		}
		if got, want := err, tc.wantErr; got != want {
			t.Errorf("mapRevisionFor(%v).err: %v, want: %v", tc.treeSize, got, want)
		}
	}
}

func TestCompressHistory(t *testing.T) {
	for _, tc := range []struct {
		desc    string
		roots   map[uint64][]byte
		want    map[uint64][]byte
		wantErr error
	}{
		{
			desc: "Single",
			roots: map[uint64][]byte{
				1: []byte("a"),
			},
			want: map[uint64][]byte{
				1: []byte("a"),
			},
		},
		{
			desc: "Compress",
			roots: map[uint64][]byte{
				0: []byte("a"),
				1: []byte("a"),
				2: []byte("a"),
			},
			want: map[uint64][]byte{
				0: []byte("a"),
			},
		},
		{
			desc: "Not Contiguous",
			roots: map[uint64][]byte{
				0: []byte("a"),
				2: []byte("a"),
			},
			wantErr: ErrNonContiguous,
		},
		{
			desc: "Complex",
			roots: map[uint64][]byte{
				1: []byte("a"),
				2: []byte("a"),
				3: []byte("b"),
				4: []byte("b"),
				5: []byte("c"),
			},
			want: map[uint64][]byte{
				1: []byte("a"),
				3: []byte("b"),
				5: []byte("c"),
			},
		},
	} {
		t.Run(tc.desc, func(t *testing.T) {
			got, err := CompressHistory(tc.roots)
			if !reflect.DeepEqual(got, tc.want) {
				t.Errorf("compressHistory(): %#v, want %#v", got, tc.want)
			}
			if err != tc.wantErr {
				t.Errorf("compressHistory(): %v, want %v", err, tc.wantErr)
			}
		})
	}
}

func TestPaginateHistory(t *testing.T) {
	ctx, cancel := context.WithTimeout(context.Background(), 2*time.Second)
	defer cancel()
	userID := "fakeuser"

	srv := &fakeKeyServer{
		revisions: map[int64]*pb.GetUserResponse{
			0:  {Revision: &pb.Revision{MapRoot: &pb.MapRoot{MapRoot: &trillian.SignedMapRoot{MapRoot: []byte{0}}}}},
			1:  {Revision: &pb.Revision{MapRoot: &pb.MapRoot{MapRoot: &trillian.SignedMapRoot{MapRoot: []byte{1}}}}},
			2:  {Revision: &pb.Revision{MapRoot: &pb.MapRoot{MapRoot: &trillian.SignedMapRoot{MapRoot: []byte{2}}}}},
			3:  {Revision: &pb.Revision{MapRoot: &pb.MapRoot{MapRoot: &trillian.SignedMapRoot{MapRoot: []byte{3}}}}},
			4:  {Revision: &pb.Revision{MapRoot: &pb.MapRoot{MapRoot: &trillian.SignedMapRoot{MapRoot: []byte{4}}}}},
			5:  {Revision: &pb.Revision{MapRoot: &pb.MapRoot{MapRoot: &trillian.SignedMapRoot{MapRoot: []byte{5}}}}},
			6:  {Revision: &pb.Revision{MapRoot: &pb.MapRoot{MapRoot: &trillian.SignedMapRoot{MapRoot: []byte{6}}}}},
			7:  {Revision: &pb.Revision{MapRoot: &pb.MapRoot{MapRoot: &trillian.SignedMapRoot{MapRoot: []byte{7}}}}},
			8:  {Revision: &pb.Revision{MapRoot: &pb.MapRoot{MapRoot: &trillian.SignedMapRoot{MapRoot: []byte{8}}}}},
			9:  {Revision: &pb.Revision{MapRoot: &pb.MapRoot{MapRoot: &trillian.SignedMapRoot{MapRoot: []byte{9}}}}},
			10: {Revision: &pb.Revision{MapRoot: &pb.MapRoot{MapRoot: &trillian.SignedMapRoot{MapRoot: []byte{10}}}}},
		},
	}
	s, stop, err := testutil.NewFakeKT(srv)
	if err != nil {
		t.Fatalf("NewFakeKT(): %v", err)
	}
	defer stop()

	for _, tc := range []struct {
		desc       string
		start, end int64
		wantErr    error
		wantValues map[uint64][]byte
	}{
		{
			desc:    "incomplete",
			start:   9,
			end:     15,
			wantErr: ErrIncomplete,
		},
		{
			desc: "1Item",
			end:  0,
			wantValues: map[uint64][]byte{
				0: nil,
			},
		},
		{
			desc: "2Items",
			end:  1,
			wantValues: map[uint64][]byte{
				0: nil,
				1: nil,
			},
		},
		{
			desc:  "3Times",
			start: 0,
			end:   10,
			wantValues: map[uint64][]byte{
				0:  nil,
				1:  nil,
				2:  nil,
				3:  nil,
				4:  nil,
				5:  nil,
				6:  nil,
				7:  nil,
				8:  nil,
				9:  nil,
				10: nil,
			},
		},
		{
			desc:  "pageSize",
			start: 0,
			end:   5,
			wantValues: map[uint64][]byte{
				0: nil,
				1: nil,
				2: nil,
				3: nil,
				4: nil,
				5: nil,
			},
		},
	} {
		t.Run(tc.desc, func(t *testing.T) {
			c := Client{
				VerifierInterface: &fakeVerifier{},
				cli:               s.Client,
			}

			_, values, err := c.PaginateHistory(ctx, userID, tc.start, tc.end)
			if err != tc.wantErr {
				t.Errorf("PaginateHistory(): %v, want %v", err, tc.wantErr)
			}
			if got, want := values, tc.wantValues; !reflect.DeepEqual(got, want) {
				t.Errorf("PaginateHistory().values: \n%#v, want \n%#v, diff: \n%v",
					got, want, pretty.Compare(got, want))
			}
		})
	}
}

type fakeKeyServer struct {
	revisions map[int64]*pb.GetUserResponse
}

func (f *fakeKeyServer) ListEntryHistory(ctx context.Context, in *pb.ListEntryHistoryRequest) (*pb.ListEntryHistoryResponse, error) {
	currentRevision := int64(len(f.revisions)) - 1 // len(1) contains map revision 0.
	if in.PageSize > 5 || in.PageSize == 0 {
		in.PageSize = 5 // Test maximum page size limits.
	}
	if in.Start+int64(in.PageSize) > currentRevision {
		in.PageSize = int32(currentRevision - in.Start + 1)
	}

	values := make([]*pb.GetUserResponse, in.PageSize)
	for i := range values {
		values[i] = f.revisions[in.Start+int64(i)]
	}
	next := in.Start + int64(len(values))
	if next > currentRevision {
		next = 0 // no more!
	}

	return &pb.ListEntryHistoryResponse{
		Values:    values,
		NextStart: next,
	}, nil
}

func (f *fakeKeyServer) ListUserRevisions(ctx context.Context, in *pb.ListUserRevisionsRequest) (
	*pb.ListUserRevisionsResponse, error) {
	return nil, status.Error(codes.Unimplemented, "not implemented")
}

func (f *fakeKeyServer) BatchListUserRevisions(ctx context.Context, in *pb.BatchListUserRevisionsRequest) (
	*pb.BatchListUserRevisionsResponse, error) {
	return nil, status.Error(codes.Unimplemented, "not implemented")
}

func (f *fakeKeyServer) GetDirectory(context.Context, *pb.GetDirectoryRequest) (*pb.Directory, error) {
	return nil, status.Error(codes.Unimplemented, "not implemented")
}

func (f *fakeKeyServer) GetRevision(context.Context, *pb.GetRevisionRequest) (*pb.Revision, error) {
	return nil, status.Error(codes.Unimplemented, "not implemented")
}

func (f *fakeKeyServer) GetLatestRevision(context.Context, *pb.GetLatestRevisionRequest) (*pb.Revision, error) {
	return nil, status.Error(codes.Unimplemented, "not implemented")
}

func (f *fakeKeyServer) GetRevisionStream(*pb.GetRevisionRequest, pb.KeyTransparency_GetRevisionStreamServer) error {
	return status.Error(codes.Unimplemented, "not implemented")
}

func (f *fakeKeyServer) ListMutations(context.Context, *pb.ListMutationsRequest) (*pb.ListMutationsResponse, error) {
	return nil, status.Error(codes.Unimplemented, "not implemented")
}

func (f *fakeKeyServer) ListMutationsStream(*pb.ListMutationsRequest, pb.KeyTransparency_ListMutationsStreamServer) error {
	return status.Error(codes.Unimplemented, "not implemented")
}

func (f *fakeKeyServer) GetUser(context.Context, *pb.GetUserRequest) (*pb.GetUserResponse, error) {
	return nil, status.Error(codes.Unimplemented, "not implemented")
}

func (f *fakeKeyServer) BatchGetUser(context.Context, *pb.BatchGetUserRequest) (*pb.BatchGetUserResponse, error) {
	return nil, status.Error(codes.Unimplemented, "not implemented")
}

func (f *fakeKeyServer) BatchGetUserIndex(context.Context,
	*pb.BatchGetUserIndexRequest) (*pb.BatchGetUserIndexResponse, error) {
	return nil, status.Error(codes.Unimplemented, "not implemented")
}

func (f *fakeKeyServer) QueueEntryUpdate(context.Context, *pb.UpdateEntryRequest) (*empty.Empty, error) {
	return nil, status.Error(codes.Unimplemented, "not implemented")
}

func (f *fakeKeyServer) BatchQueueUserUpdate(context.Context, *pb.BatchQueueUserUpdateRequest) (*empty.Empty, error) {
	return nil, status.Error(codes.Unimplemented, "not implemented")
}

type fakeVerifier struct{}

func (f *fakeVerifier) Index(vrfProof []byte, directoryID, userID string) ([]byte, error) {
	return make([]byte, 32), nil
}

func (f *fakeVerifier) LastVerifiedLogRoot() *pb.LogRootRequest {
	return &pb.LogRootRequest{}
}

func (f *fakeVerifier) VerifyLogRoot(req *pb.LogRootRequest, slr *pb.LogRoot) (*types.LogRootV1, error) {
	return &types.LogRootV1{}, nil
}

func (f *fakeVerifier) VerifyMapRevision(logRoot *types.LogRootV1, smr *pb.MapRoot) (*types.MapRootV1, error) {
	return &types.MapRootV1{Revision: uint64(smr.MapRoot.MapRoot[0])}, nil
}

func (f *fakeVerifier) VerifyMapLeaf(directoryID, userID string,
	in *pb.MapLeaf, smr *types.MapRootV1) error {
	return nil
}

func (f *fakeVerifier) VerifyGetUser(req *pb.GetUserRequest, resp *pb.GetUserResponse) error {
	return nil
}

func (f *fakeVerifier) VerifyBatchGetUser(req *pb.BatchGetUserRequest, resp *pb.BatchGetUserResponse) error {
	return nil
}


text:
package com.google.tsunami.plugins.detectors.directorytraversal.genericpathtraversaldetector;

import static com.google.common.truth.Truth.assertThat;
import static com.google.common.truth.Truth8.assertThat;

import com.google.common.collect.ImmutableList;
import com.google.tsunami.common.net.http.HttpRequest;
import com.google.tsunami.proto.NetworkService;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;

/** Unit tests for {@link GetParameterInjection}. */
@RunWith(JUnit4.class)
public final class GetParameterInjectionTest {
  private static final GetParameterInjection INJECTION_POINT = new GetParameterInjection();

  private static final HttpRequest REQUEST_WITHOUT_GET_PARAMETERS =
      HttpRequest.get("https://google.com").withEmptyHeaders().build();
  private static final HttpRequest REQUEST_WITH_GET_PARAMETERS =
      HttpRequest.get("https://google.com?key=value&other=test").withEmptyHeaders().build();
  private static final NetworkService MINIMAL_NETWORK_SERVICE =
      NetworkService.newBuilder().setServiceName("http").build();
  private static final String PAYLOAD = "../../../../etc/passwd";

  @Test
  public void injectPayload_onRelativePathTraversalPayloadWithGetParameters_generatesExploits() {
    ImmutableList<PotentialExploit> exploitsWithPayloadInGetParameters =
        ImmutableList.of(
            PotentialExploit.create(
                MINIMAL_NETWORK_SERVICE,
                HttpRequest.get("https://google.com?key=" + PAYLOAD + "&other=test")
                    .withEmptyHeaders()
                    .build(),
                PAYLOAD,
                PotentialExploit.Priority.LOW),
            PotentialExploit.create(
                MINIMAL_NETWORK_SERVICE,
                HttpRequest.get("https://google.com?key=value&other=" + PAYLOAD)
                    .withEmptyHeaders()
                    .build(),
                PAYLOAD,
                PotentialExploit.Priority.LOW));

    assertThat(
            INJECTION_POINT.injectPayload(
                MINIMAL_NETWORK_SERVICE, REQUEST_WITH_GET_PARAMETERS, PAYLOAD))
        .containsAtLeastElementsIn(exploitsWithPayloadInGetParameters);
  }

  @Test
  public void
      injectPayload_whenGetParameterHasFileExtensionAndPrefix_generatesExploitsWithFileExtensionAndPrefix() {
    HttpRequest requestWIthFileExtensionAndPrefix =
        HttpRequest.get("https://google.com?key=value.jpg&other=resources/test")
            .withEmptyHeaders()
            .build();
    ImmutableList<PotentialExploit> exploitsWithFileExtensionAndPrefix =
        ImmutableList.of(
            PotentialExploit.create(
                MINIMAL_NETWORK_SERVICE,
                HttpRequest.get(
                        "https://google.com?key=" + PAYLOAD + "%00.jpg&other=resources/test")
                    .withEmptyHeaders()
                    .build(),
                PAYLOAD,
                PotentialExploit.Priority.LOW),
            PotentialExploit.create(
                MINIMAL_NETWORK_SERVICE,
                HttpRequest.get("https://google.com?key=value.jpg&other=resources/" + PAYLOAD)
                    .withEmptyHeaders()
                    .build(),
                PAYLOAD,
                PotentialExploit.Priority.LOW));

    assertThat(
            INJECTION_POINT.injectPayload(
                MINIMAL_NETWORK_SERVICE, requestWIthFileExtensionAndPrefix, PAYLOAD))
        .containsAtLeastElementsIn(exploitsWithFileExtensionAndPrefix);
  }

  @Test
  public void
      injectPayload_onRelativePathTraversalPayloadWithoutGetParameters_generatesNoExploits() {
    assertThat(
            INJECTION_POINT.injectPayload(
                MINIMAL_NETWORK_SERVICE, REQUEST_WITHOUT_GET_PARAMETERS, PAYLOAD))
        .isEmpty();
  }

  @Test
  public void injectPayload_whenPromisingParameterName_assignsHighPriority() {
    HttpRequest requestWithPromisingParameterName =
        HttpRequest.get("https://google.com?file=test").withEmptyHeaders().build();
    ImmutableList<PotentialExploit> exploits =
        INJECTION_POINT.injectPayload(
            MINIMAL_NETWORK_SERVICE, requestWithPromisingParameterName, PAYLOAD);

    for (PotentialExploit exploit : exploits) {
      assertThat(exploit.priority()).isEqualTo(PotentialExploit.Priority.HIGH);
    }
  }

  @Test
  public void
      injectPayload_whenPromisingParameterNameIsSnakeCase_normalizesValueAndAssignsHighPriority() {
    HttpRequest requestWithPromisingParameterName =
        HttpRequest.get("https://google.com?file_name=test").withEmptyHeaders().build();
    ImmutableList<PotentialExploit> exploits =
        INJECTION_POINT.injectPayload(
            MINIMAL_NETWORK_SERVICE, requestWithPromisingParameterName, PAYLOAD);

    for (PotentialExploit exploit : exploits) {
      assertThat(exploit.priority()).isEqualTo(PotentialExploit.Priority.HIGH);
    }
  }

  @Test
  public void injectPayload_whenPromisingParameterName_assignsPriorityOnlyToPromisingParameter() {
    HttpRequest requestWithPromisingParameterName =
        HttpRequest.get("https://google.com?file=test&notfile=nottest").withEmptyHeaders().build();
    ImmutableList<PotentialExploit> exploits =
        INJECTION_POINT.injectPayload(
            MINIMAL_NETWORK_SERVICE, requestWithPromisingParameterName, PAYLOAD);

    assertThat(exploits.stream().map(PotentialExploit::priority))
        .containsExactly(PotentialExploit.Priority.LOW, PotentialExploit.Priority.HIGH);
  }

  @Test
  public void injectPayload_whenParameterValueRepresentsPath_assignsHighPriority() {
    HttpRequest requestWithPromisingParameterName =
        HttpRequest.get("https://google.com?key=path/to/file").withEmptyHeaders().build();
    ImmutableList<PotentialExploit> exploits =
        INJECTION_POINT.injectPayload(
            MINIMAL_NETWORK_SERVICE, requestWithPromisingParameterName, PAYLOAD);

    for (PotentialExploit exploit : exploits) {
      assertThat(exploit.priority()).isEqualTo(PotentialExploit.Priority.HIGH);
    }
  }

  @Test
  public void injectPayload_whenParameterValueRepresentsEncodedPath_assignsHighPriority() {
    HttpRequest requestWithPromisingParameterName =
        HttpRequest.get("https://google.com?key=path%2Fto%2ffile").withEmptyHeaders().build();
    ImmutableList<PotentialExploit> exploits =
        INJECTION_POINT.injectPayload(
            MINIMAL_NETWORK_SERVICE, requestWithPromisingParameterName, PAYLOAD);

    for (PotentialExploit exploit : exploits) {
      assertThat(exploit.priority()).isEqualTo(PotentialExploit.Priority.HIGH);
    }
  }

  @Test
  public void injectPayload_whenParameterValueHasFileExtension_assignsHighPriority() {
    HttpRequest requestWithPromisingParameterName =
        HttpRequest.get("https://google.com?key=img.jpg").withEmptyHeaders().build();
    ImmutableList<PotentialExploit> exploits =
        INJECTION_POINT.injectPayload(
            MINIMAL_NETWORK_SERVICE, requestWithPromisingParameterName, PAYLOAD);

    for (PotentialExploit exploit : exploits) {
      assertThat(exploit.priority()).isEqualTo(PotentialExploit.Priority.HIGH);
    }
  }
}


text:
layout: page
title: Seattle Police Officer 5360 Michael J. Galarita
permalink: /information/agencies/city_of_seattle/seattle_police_department/copbook/5360/
---

**Age as of Feb. 24, 2016:** 50


text:
from __future__ import absolute_import
from ...base.events import BaseEvent

class InspectionCreatedEvent(BaseEvent):
    def process(self, request, body):

        if body.get('metadata', {}).get('branch') not in self.config.get('notify_branches'):
            return False

        if 'inspection.created' not in self.config.get('events'):
            return False

        inspection = body.get('uuid', '').split('-')[-1]
        inspection_link = 'https://scrutinizer-ci.com' + body.get('_links', {}) \
            .get('self', {}).get('href').replace(
            '/api/repositories', '')
        repo_link = body.get('_embedded', {}).get('repository', {}).get('login', '') + '/' + \
            body.get('_embedded', {}).get('repository', {}).get('name')
        commit = body.get('metadata', {}).get('source_reference', '')[0:7].replace('[', '\[')

        message = '⚒ Inspection [{inspection}]({inspection_url}) ' \
                  '*created* for {repository}@{branch}\n' \
                  'Commits: \n' \
                  '- {commit} - {commit_msg}'

        message = message.format(
            inspection=inspection,
            inspection_url=inspection_link,
            branch=body.get('metadata', {}).get('branch', ''),
            commit=commit,
            repository=repo_link,
            commit_msg=body.get('metadata', {}).get('title', ''))

        return {"default": message}


text:
package cn.workcenter.common;

import cn.workcenter.common.constant.WebConstant;

public enum WorkcenterOperationEnum implements WebConstant {
	//{001,workcenter 002,admin}

	;

	String operationCode;
	String operationEn;
	String operationCh;

	WorkcenterOperationEnum(String code, String en, String ch) {
		operationCode = code;
		operationEn = en;
		operationCh = ch;
	}

	public String getOperationCode() {
		return operationCode;
	}
	public String getOperationEn() {
		return operationEn;
	}

	public String getOperationCh() {
		return operationCh;
	}

}


text:
<?php
    /**
     * Main Controller
     *
     * @package     MagicPHP
     * @author      André Ferreira <andrehrf@gmail.com>
     * @link        https://github.com/magicphp/magicphp MagicPHP(tm)
     * @license     MIT License (http://www.opensource.org/licenses/mit-license.php)
     */

    if(file_exists(__DIR__ . DIRECTORY_SEPARATOR . "vendor" . DIRECTORY_SEPARATOR . "autoload.php"))
        require_once(__DIR__ . DIRECTORY_SEPARATOR . "vendor" . DIRECTORY_SEPARATOR . "autoload.php");

    require_once(__DIR__ . DIRECTORY_SEPARATOR . "bootstrap.php");
    Bootstrap::Start();

    if(file_exists(__DIR__ . DIRECTORY_SEPARATOR . "routes.php"))
        require_once(__DIR__ . DIRECTORY_SEPARATOR . "routes.php");

    Bootstrap::AutoLoad("settings");
    Routes::Parse();


text:
"""
  Copyright 2015 Netflix, Inc.

     Licensed under the Apache License, Version 2.0 (the "License");
     you may not use this file except in compliance with the License.
     You may obtain a copy of the License at

         http://www.apache.org/licenses/LICENSE-2.0

     Unless required by applicable law or agreed to in writing, software
     distributed under the License is distributed on an "AS IS" BASIS,
     WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
     See the License for the specific language governing permissions and
     limitations under the License.
"""
import logging
import threading
import time
import urllib2
import genie2.client.api_client
import genie2.client.V2Api

__author__ = 'jcistaro'

DEBUG = logging.getLogger(__name__).debug
ERROR = logging.getLogger(__name__).error
INFO = logging.getLogger(__name__).info
WARN = logging.getLogger(__name__).warn

class Genie2(object):  # pylint: disable=R0903
    """Wrapper for Genie V2Api"""

    def __init__(self, service_base_url, retry_policy=None):
        # pylint: disable=R0913
        self._lock = threading.RLock()
        self._service_base_url = service_base_url
        self._cached_url = None
        self._retry_policy = retry_policy if retry_policy is not None else \
            RetryPolicy(tries=1)

    def __getattr__(self, name):  # pylint: disable=R0912
        if name.startswith('__'):
            raise AttributeError
        parts = name.split('_')
        if len(parts) == 0:
            camel = ''
        else:
            camel = parts[0]
            for part in parts[1:]:
                camel += part.capitalize()

        def wrap(*args, **kwargs):
            """Wrap the function"""
            # pylint: disable=R0912
            if 'retry_policy' in kwargs:
                retry_policy = kwargs['retry_policy']
                del kwargs['retry_policy']
            else:
                retry_policy = self._retry_policy
            delay = retry_policy.delay
            for remaining in range(retry_policy.tries - 1, -1, -1):
                try:
                    service_base_url = self.get_service_base_url()
                    client = genie2.client.api_client.ApiClient(
                        api_server=service_base_url)
                    api = genie2.client.V2Api.V2Api(client)
                    if not hasattr(api, camel):
                        raise AttributeError(
                            ('genie2.client.V2Api.V2Api object has no ' +
                             "attribute '%s' to be wrapped by '%s'" %
                             (camel, name)))
                    return getattr(api, camel)(*args, **kwargs)
                except AttributeError:
                    raise
                except urllib2.HTTPError as http_error:
                    DEBUG(http_error)
                    if http_error.code == 404 and retry_policy.none_on_404 is True:
                        return None
                    if http_error.code in range(500, 600):
                        self.reset_service_base_url()
                    if remaining < 1 or http_error.code in \
                            retry_policy.no_retry_http_codes:
                        raise Exception(
                            ('V2Api call to %s failed due to ' +
                             'error code=[%s] because=[%s]') %
                            (camel, str(http_error.code), http_error.read())
                        )
                except urllib2.URLError as url_error:
                    DEBUG(url_error)
                    self.reset_service_base_url()
                    if remaining < 1:
                        raise Exception(
                            'V2Api call to %s failed with reason=[%s]' %
                            (camel, url_error.reason))
                except Exception as error:  # pylint: disable=W0703
                    DEBUG(error)
                    self.reset_service_base_url()
                    if remaining < 1:
                        raise
                time.sleep(delay)  # wait...
                delay *= retry_policy.backoff  # make future wait longer

        return wrap

    def get_service_base_url(self):
        """Get service base url."""
        with self._lock:
            if not hasattr(self._service_base_url, '__call__'):
                return self._service_base_url
            else:
                if self._cached_url is None:
                    self._cached_url = self._service_base_url()
                return self._cached_url

    def reset_service_base_url(self):
        """Get service base url."""
        with self._lock:
            if hasattr(self._service_base_url, '__call__'):
                self._cached_url = None

class RetryPolicy(object):
    """Retry Policy."""
    # pylint: disable=R0903

    tries = property(lambda self: getattr(self, '_tries'))
    delay = property(lambda self: getattr(self, '_delay'))
    backoff = property(lambda self: getattr(self, '_backoff'))
    no_retry_http_codes = property(
        lambda self: getattr(self, '_no_retry_http_codes'))
    none_on_404 = property(lambda self: getattr(self, '_none_on_404'))

    def __init__(self, tries=6, delay=3, backoff=2, no_retry_http_codes=None,
                 none_on_404=False):
        # pylint: disable=R0913
        if not isinstance(backoff, (int, long)) or backoff <= 1:
            raise ValueError('backoff must be an integer greater than 1')
        if not isinstance(tries, (int, long)) or tries <= 0:
            raise ValueError('tries must an integer greater than 0')
        if not isinstance(delay, (int, long)) or delay <= 0:
            raise ValueError("delay must be greater than 0")
        self._tries = tries
        self._delay = delay
        self._backoff = backoff
        self._no_retry_http_codes = no_retry_http_codes \
            if no_retry_http_codes is not None else []
        self._none_on_404 = none_on_404


text:
u32 FClassInfo::IdentifierGenerator = 0;

FClassInfo::FClassInfo(const char* PrintName)
{
	// Note: this is not thread safe at all.
	this->PrintName = PrintName;
	this->Identifier = IdentifierGenerator++;
}

FClassInfo::~FClassInfo()
{

}


text:
I am the working directory log strategy. I write logs in the working directory, which is the default way to log in Pharo.

To use me, add in the command line just after the image:
	workingDirectory

(Notice that this is the default logging strategy and so it's not necessary to explicitly call it with the command line)

or during execution :
SystemLog uniqueInstance beWorkingDirectory


text:
<?php

namespace Scribe\Teavee\HtmlGeneratorBundle\Manager;

use Scribe\Teavee\ObjectCacheBundle\Component\Manager\CacheManagerInterface;
use Scribe\Teavee\ObjectCacheBundle\DependencyInjection\Aware\CacheManagerAwareTrait;
use Scribe\Teavee\HtmlGeneratorBundle\Generator\GeneratorInterface;
use Scribe\Teavee\HtmlGeneratorBundle\Provider\ProviderInterface;
use Scribe\Wonka\Exception\RuntimeException;

/**
 * Class AbstractManager.
 */
abstract class AbstractManager implements ManagerInterface
{
    use CacheManagerAwareTrait;

    /**
     * @var ProviderInterface
     */
    protected $provider;

    /**
     * @var GeneratorInterface
     */
    protected $generator;

    /**
     * @var string
     */
    protected $errorStrategy;

    /**
     * @var bool
     */
    protected $lastResponseFromCache;

    /**
     * @var int
     */
    protected $ttlForResponseCache;

    /**
     * @param ProviderInterface  $provider
     * @param GeneratorInterface $generator
     */
    public function __construct(ProviderInterface $provider, GeneratorInterface $generator, $errorStrategy = null)
    {
        $this->provider = $provider;
        $this->generator = $generator;

        $this->registerErrorStrategy($errorStrategy);
    }

    /**
     * @param mixed   $subject
     * @param mixed[] $ops
     *
     * @return $this
     */
    public function render($subject, array $ops = [])
    {
        if (null === ($response = $this->getCacheResponse($subject, $ops))) {
            try {
                $provided = (array) $this->provider->find($ops, $subject);
                $response = (string) $this->generator->make($ops, $subject, ...$provided);
            } catch (\Exception $e) {
                return $this->renderError($e);
            }
        }

        return $this->setCacheResponse($response, $subject, $ops);
    }

    /**
     * @return bool
     */
    public function isLastResponseFromCache()
    {
        return (bool) ($this->lastResponseFromCache === true);
    }

    /**
     * @param \Twig_Environment $environment
     *
     * @return $this
     */
    public function registerTwigEnvironment(\Twig_Environment $environment = null)
    {
        if ($this->generator !== null) {
            $this->generator->setTwigEnvironment($environment);
        }

        return $this;
    }

    /**
     * @param CacheManagerInterface|null $manager
     * @param bool|false                 $enabled
     * @param int                        $ttl
     *
     * @return $this
     */
    public function registerCacheManager(CacheManagerInterface $manager = null, $enabled = false, $ttl = 0)
    {
        if ($enabled !== true) {
            $manager = null;
        }

        $this->setCacheManager($manager);
        $this->ttlForResponseCache = (int) $ttl;

        return $this;
    }

    /**
     * @param string|null $strategy
     *
     * @return $this
     */
    public function registerErrorStrategy($strategy = null)
    {
        $available = [self::ERR_ST_EXC, self::ERR_ST_NULL, self::ERR_ST_BOOL];
        $selection = current($available);

        array_walk($available, function ($s) use ($strategy, &$selection) {
            if ($strategy === $s) {
                $selection = $s;
            }
        });

        $this->errorStrategy = $selection;

        return $this;
    }

    /**
     * @param string    $response
     * @param mixed,... $for
     *
     * @return mixed
     */
    protected function setCacheResponse($response, ...$for)
    {
        if (true === $this->isCacheAvailable()) {
            $this
                ->getCache()
                ->setTtl($this->ttlForResponseCache)
                ->set($response, ...$for);

            $this->getCache()->resetTtl();
        }

        return $response;
    }

    /**
     * @param mixed,... $for
     *
     * @return mixed
     */
    protected function getCacheResponse(...$for)
    {
        $this->lastResponseFromCache = false;

        if (true === $this->isCacheAvailable() && null !== ($response = $this->getCache()->get(...$for))) {
            $this->lastResponseFromCache = true;

            return $response;
        }

        return;
    }

    /**
     * @param \Exception $e
     *
     * @throws RuntimeException
     *
     * @return bool|null
     */
    protected function renderError(\Exception $e)
    {
        switch ($this->errorStrategy) {
            case self::ERR_ST_BOOL:
                return false;

            case self::ERR_ST_NULL:
                return;
        }

        throw new RuntimeException('Could not render requested component.', null, $e);
    }
}

/* EOF */


text:
module.exports = require('../../../../../../../').defineCommandHandler({
  name: 'enterNewSpecialPerson'//,  // optional, default is file name without extension
  // version: 1, // optional, default 0
  // payload: 'payload' // if not defined it will pass the whole command...
}, function (aggId, cmd, commandHandler, callback) {

  commandHandler.loadAggregate(aggId, function (err, aggregate, stream) {
    if (err) {
      return callback(err);
    }

    callback(null, [{ my: 'special', ev: 'ent' }]);

//    // check if destroyed, check revision, validate command
//    var err = commandHandler.verifyAggregate(aggregate, cmd);
//    if (err) {
//      return callback(err);
//    }
//
//    // call api or emit a command or whatever...
//    // and at the end perhaps you call: commandHandler.handle(cmd, callback);
  });
});


text:
@interface LoginVC ()

@property (weak, nonatomic) IBOutlet UITextField *nameTextField;

@end

@implementation LoginVC

- (void)viewDidLoad
{
    [super viewDidLoad];
    self.nameTextField.text = [Login currentAuthorName];
}

- (void)loginComplete
{
    if (self.delegate && [self.delegate respondsToSelector:@selector(loginVCDidCompleteLogin:)]) {
        [self.delegate loginVCDidCompleteLogin:self];
    }
}

- (IBAction)loginAuthor:(UIButton *)sender
{
    NSString *name = self.nameTextField.text;
    name = [name stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];
    if ([name isEqualToString:@""]) return;

    if (![name isEqualToString:[Login currentAuthorName]]) {
        // Create or update current author:
        Author *author = [Author authorWithName:name inManagedObjectContext:self.managedObjectContext];
        [Login setCurrentAuthorName:author.name];
    }
    [self loginComplete];
}

@end


text:
/** Notice of modification as required by the LGPL
 *  This file was modified by Gemstone Systems Inc. on
 *  $Date$
 **/
// $Id: MessageDispatcher.java,v 1.44 2005/11/12 06:39:02 belaban Exp $

package com.gemstone.org.jgroups.blocks;

import com.gemstone.org.jgroups.util.GemFireTracer;
import com.gemstone.org.jgroups.util.ExternalStrings;
import com.gemstone.org.jgroups.*;
import com.gemstone.org.jgroups.stack.Protocol;
import com.gemstone.org.jgroups.util.*;

import java.io.Serializable;
import java.util.Vector;
import java.util.Collection;
import java.util.TreeSet;

/**
 * Provides synchronous and asynchronous message sending with request-response
 * correlation; i.e., matching responses with the original request.
 * It also offers push-style message reception (by internally using the PullPushAdapter).
 *

 * Channels are simple patterns to asynchronously send a receive messages.
 * However, a significant number of communication patterns in group communication
 * require synchronous communication. For example, a sender would like to send a
 * message to the group and wait for all responses. Or another application would
 * like to send a message to the group and wait only until the majority of the
 * receivers have sent a response, or until a timeout occurred.  MessageDispatcher
 * offers a combination of the above pattern with other patterns.
 *

 * Used on top of channel to implement group requests. Client's handle()
 * method is called when request is received. Is the equivalent of RpcProtocol on
 * the application instead of protocol level.
 *
 * @author Bela Ban
 */
public class MessageDispatcher implements RequestHandler {
    protected Channel channel=null;
    protected RequestCorrelator corr=null;
    protected MessageListener msg_listener=null;
    protected MembershipListener membership_listener=null;
    protected RequestHandler req_handler=null;
    protected ProtocolAdapter prot_adapter=null;
    protected TransportAdapter transport_adapter=null;
    protected final Collection members=new TreeSet();
    protected Address local_addr=null;
    protected boolean deadlock_detection=false;
    protected PullPushAdapter adapter=null;
    protected Serializable id=null;
    protected final GemFireTracer log = GemFireTracer.getLog(getClass());

    /**
     * Process items on the queue concurrently (RequestCorrelator). The default is to wait until the processing of an
     * item has completed before fetching the next item from the queue. Note that setting this to true may destroy the
     * properties of a protocol stack, e.g total or causal order may not be guaranteed. Set this to true only if you
     * know what you're doing !
     */
    protected boolean concurrent_processing=false;

    public MessageDispatcher(Channel channel, MessageListener l, MembershipListener l2) {
        this.channel=channel;
        prot_adapter=new ProtocolAdapter();
        if(channel != null) {
            local_addr=channel.getLocalAddress();
            channel.setOpt(Channel.GET_STATE_EVENTS, Boolean.TRUE);
        }
        setMessageListener(l);
        setMembershipListener(l2);
        if(channel != null) {
            channel.setUpHandler(prot_adapter);
        }
        start();
    }

    public MessageDispatcher(Channel channel, MessageListener l, MembershipListener l2, boolean deadlock_detection) {
        this.channel=channel;
        this.deadlock_detection=deadlock_detection;
        prot_adapter=new ProtocolAdapter();
        if(channel != null) {
            local_addr=channel.getLocalAddress();
            channel.setOpt(Channel.GET_STATE_EVENTS, Boolean.TRUE);
        }
        setMessageListener(l);
        setMembershipListener(l2);
        if(channel != null) {
            channel.setUpHandler(prot_adapter);
        }
        start();
    }

    public MessageDispatcher(Channel channel, MessageListener l, MembershipListener l2,
                             boolean deadlock_detection, boolean concurrent_processing) {
        this.channel=channel;
        this.deadlock_detection=deadlock_detection;
        this.concurrent_processing=concurrent_processing;
        prot_adapter=new ProtocolAdapter();
        if(channel != null) {
            local_addr=channel.getLocalAddress();
            channel.setOpt(Channel.GET_STATE_EVENTS, Boolean.TRUE);
        }
        setMessageListener(l);
        setMembershipListener(l2);
        if(channel != null) {
            channel.setUpHandler(prot_adapter);
        }
        start();
    }

    public MessageDispatcher(Channel channel, MessageListener l, MembershipListener l2, RequestHandler req_handler) {
        this(channel, l, l2);
        setRequestHandler(req_handler);
    }

    public MessageDispatcher(Channel channel, MessageListener l, MembershipListener l2, RequestHandler req_handler,
                             boolean deadlock_detection) {
        this(channel, l, l2);
        this.deadlock_detection=deadlock_detection;
        setRequestHandler(req_handler);
    }

    public MessageDispatcher(Channel channel, MessageListener l, MembershipListener l2, RequestHandler req_handler,
                             boolean deadlock_detection, boolean concurrent_processing) {
        this(channel, l, l2);
        this.deadlock_detection=deadlock_detection;
        this.concurrent_processing=concurrent_processing;
        setRequestHandler(req_handler);
    }

    /*
     * Uses a user-provided PullPushAdapter rather than a Channel as transport. If id is non-null, it will be
     * used to register under that id. This is typically used when another building block is already using
     * PullPushAdapter, and we want to add this building block in addition. The id is the used to discriminate
     * between messages for the various blocks on top of PullPushAdapter. If null, we will assume we are the
     * first block created on PullPushAdapter.
     * @param adapter The PullPushAdapter which to use as underlying transport
     * @param id A serializable object (e.g. an Integer) used to discriminate (multiplex/demultiplex) between
     *           requests/responses for different building blocks on top of PullPushAdapter.
     */
    public MessageDispatcher(PullPushAdapter adapter, Serializable id,
                             MessageListener l, MembershipListener l2) {
        this.adapter=adapter;
        this.id=id;
        setMembers(((Channel) adapter.getTransport()).getView().getMembers());
        setMessageListener(l);
        setMembershipListener(l2);
        PullPushHandler handler=new PullPushHandler();
        Transport tp;

        transport_adapter=new TransportAdapter();
        adapter.addMembershipListener(handler);
        if(id == null) // no other building block around, let's become the main consumer of this PullPushAdapter
        {
            adapter.setListener(handler);
        }
        else {
            adapter.registerListener(id, handler);
        }

        if((tp=adapter.getTransport()) instanceof Channel) {
            ((Channel) tp).setOpt(Channel.GET_STATE_EVENTS, Boolean.TRUE);
            local_addr=((Channel) tp).getLocalAddress();
        }
        start();
    }

    /*
     * Uses a user-provided PullPushAdapter rather than a Channel as transport. If id is non-null, it will be
     * used to register under that id. This is typically used when another building block is already using
     * PullPushAdapter, and we want to add this building block in addition. The id is the used to discriminate
     * between messages for the various blocks on top of PullPushAdapter. If null, we will assume we are the
     * first block created on PullPushAdapter.
     * @param adapter The PullPushAdapter which to use as underlying transport
     * @param id A serializable object (e.g. an Integer) used to discriminate (multiplex/demultiplex) between
     *           requests/responses for different building blocks on top of PullPushAdapter.
     * @param req_handler The object implementing RequestHandler. It will be called when a request is received
     */
    public MessageDispatcher(PullPushAdapter adapter, Serializable id,
                             MessageListener l, MembershipListener l2,
                             RequestHandler req_handler) {
        this.adapter=adapter;
        this.id=id;
        setMembers(((Channel) adapter.getTransport()).getView().getMembers());
        setRequestHandler(req_handler);
        setMessageListener(l);
        setMembershipListener(l2);
        PullPushHandler handler=new PullPushHandler();
        Transport tp;

        transport_adapter=new TransportAdapter();
        adapter.addMembershipListener(handler);
        if(id == null) // no other building block around, let's become the main consumer of this PullPushAdapter
        {
            adapter.setListener(handler);
        }
        else {
            adapter.registerListener(id, handler);
        }

        if((tp=adapter.getTransport()) instanceof Channel) {
            ((Channel) tp).setOpt(Channel.GET_STATE_EVENTS, Boolean.TRUE);
            local_addr=((Channel) tp).getLocalAddress(); // fixed bug #800774
        }

        start();
    }

    public MessageDispatcher(PullPushAdapter adapter, Serializable id,
                             MessageListener l, MembershipListener l2,
                             RequestHandler req_handler, boolean concurrent_processing) {
        this.concurrent_processing=concurrent_processing;
        this.adapter=adapter;
        this.id=id;
        setMembers(((Channel) adapter.getTransport()).getView().getMembers());
        setRequestHandler(req_handler);
        setMessageListener(l);
        setMembershipListener(l2);
        PullPushHandler handler=new PullPushHandler();
        Transport tp;

        transport_adapter=new TransportAdapter();
        adapter.addMembershipListener(handler);
        if(id == null) // no other building block around, let's become the main consumer of this PullPushAdapter
        {
            adapter.setListener(handler);
        }
        else {
            adapter.registerListener(id, handler);
        }

        if((tp=adapter.getTransport()) instanceof Channel) {
            ((Channel) tp).setOpt(Channel.GET_STATE_EVENTS, Boolean.TRUE);
            local_addr=((Channel) tp).getLocalAddress(); // fixed bug #800774
        }

        start();
    }

    /**
     * If this dispatcher is using a user-provided PullPushAdapter, then need to set the members from the adapter
     * initially since viewChange has most likely already been called in PullPushAdapter.
     */
    protected/*GemStoneAddition*/ void setMembers(Vector new_mbrs) {
        if(new_mbrs != null) {
            synchronized(members) {
                members.clear();
                members.addAll(new_mbrs);
            }
        }
    }

    public void setDeadlockDetection(boolean flag) {
        deadlock_detection=flag;
        if(corr != null)
            corr.setDeadlockDetection(flag);
    }

    public void setConcurrentProcessing(boolean flag) {
        this.concurrent_processing=flag;
    }

    public void start() {
        if(corr == null) {
            if(transport_adapter != null) {
                corr=new RequestCorrelator("MessageDispatcher", transport_adapter,
                                           this, deadlock_detection, local_addr, concurrent_processing);
            }
            else {
                corr=new RequestCorrelator("MessageDispatcher", prot_adapter,
                                           this, deadlock_detection, local_addr, concurrent_processing);
            }
        }
        corr.start();
        if(channel != null) {
            Vector tmp_mbrs=channel.getView() != null ? channel.getView().getMembers() : null;
            setMembers(tmp_mbrs);
        }
    }

    public void stop() {
        if(corr != null) {
            corr.stop();
        }
    }

    public void setMessageListener(MessageListener l) {
        msg_listener=l;
    }

    /**
     * Gives access to the currently configured MessageListener. Returns null if there is no
     * configured MessageListener.
     */
    public MessageListener getMessageListener() {
        return msg_listener;
    }

    public void setMembershipListener(MembershipListener l) {
        membership_listener=l;
    }

    public void setRequestHandler(RequestHandler rh) {
        req_handler=rh;
    }

    /**
     * Offers access to the underlying Channel.
     * @return a reference to the underlying Channel.
     */
    public Channel getChannel() {
        return channel;
    }

    public void send(Message msg) throws ChannelNotConnectedException, ChannelClosedException {
        if(channel != null) {
            channel.send(msg);
        }
        else
            if(adapter != null) {
                try {
                    if(id != null) {
                        adapter.send(id, msg);
                    }
                    else {
                        adapter.send(msg);
                    }
                }
            catch(Throwable ex) {
                    if(log.isErrorEnabled()) {
                        log.error(ExternalStrings.MessageDispatcher_EXCEPTION_0, Util.print(ex));
                    }
                }
            }
            else {
                if(log.isErrorEnabled()) {
                    log.error(ExternalStrings.MessageDispatcher_CHANNEL__NULL);
                }
            }
    }

    /**
     * Cast a message to all members, and wait for mode responses. The responses are returned in a response
     * list, where each response is associated with its sender.
 Uses GroupRequest.
     *
     * @param dests   The members to which the message is to be sent. If it is null, then the message is sent to all
     *                members
     * @param msg     The message to be sent to n members
     * @param mode    Defined in GroupRequest. The number of responses to wait for:

GET_FIRST:
     *                return the first response received.
GET_ALL: wait for all responses (minus the ones from
     *                suspected members)
GET_MAJORITY: wait for a majority of all responses (relative to the grp
     *                size)
GET_ABS_MAJORITY: wait for majority (absolute, computed once)
GET_N: wait for n
     *                responses (may block if n > group size)
GET_NONE: wait for no responses, return immediately
     *                (non-blocking)

     * @param timeout If 0: wait forever. Otherwise, wait for mode responses or timeout time.
     * @return RspList A list of responses. Each response is an Object and associated to its sender.
     */
    public RspList castMessage(final Vector dests, Message msg, int mode, long timeout) {
        GroupRequest _req=null;
        Vector real_dests;
        Channel tmp;

        // we need to clone because we don't want to modify the original
        // (we remove ourselves if LOCAL is false, see below) !
        // real_dests=dests != null ? (Vector) dests.clone() : (members != null ? new Vector(members) : null);
        if(dests != null) {
            real_dests=(Vector)dests.clone();
        }
        else {
            synchronized(members) {
                real_dests=new Vector(members);
            }
        }

        // if local delivery is off, then we should not wait for the message from the local member.
        // therefore remove it from the membership
        tmp=channel;
        if(tmp == null) {
            if(adapter != null && adapter.getTransport() instanceof Channel) {
                tmp=(Channel) adapter.getTransport();
            }
        }

        if(tmp != null && tmp.getOpt(Channel.LOCAL).equals(Boolean.FALSE)) {
            if(local_addr == null) {
                local_addr=tmp.getLocalAddress();
            }
            if(local_addr != null && real_dests != null) {
                real_dests.removeElement(local_addr);
            }
        }

        // don't even send the message if the destination list is empty
        if(log.isTraceEnabled())
            log.trace("real_dests=" + real_dests);

        if(real_dests == null || real_dests.size() == 0) {
            if(log.isTraceEnabled())
                log.trace("destination list is empty, won't send message");
            return new RspList(); // return empty response list
        }

        _req=new GroupRequest(msg, corr, real_dests, mode, timeout, 0);
        _req.setCaller(this.local_addr);
        _req.execute();

        return _req.getResults();
    }

    /**
     * Multicast a message request to all members in dests and receive responses via the RspCollector
     * interface. When done receiving the required number of responses, the caller has to call done(req_id) on the
     * underlyinh RequestCorrelator, so that the resources allocated to that request can be freed.
     *
     * @param dests  The list of members from which to receive responses. Null means all members
     * @param req_id The ID of the request. Used by the underlying RequestCorrelator to correlate responses with
     *               requests
     * @param msg    The request to be sent
     * @param coll   The sender needs to provide this interface to collect responses. Call will return immediately if
     *               this is null
     */
    public void castMessage(final Vector dests, long req_id, Message msg, RspCollector coll) {
        Vector real_dests;
        Channel tmp;

        if(msg == null) {
            if(log.isErrorEnabled())
                log.error(ExternalStrings.MessageDispatcher_REQUEST_IS_NULL);
            return;
        }

        if(coll == null) {
            if(log.isErrorEnabled())
                log.error(ExternalStrings.MessageDispatcher_RESPONSE_COLLECTOR_IS_NULL_MUST_BE_NONNULL);
            return;
        }

        // we need to clone because we don't want to modify the original
        // (we remove ourselves if LOCAL is false, see below) !
        //real_dests=dests != null ? (Vector) dests.clone() : (Vector) members.clone();
        if(dests != null) {
            real_dests=(Vector)dests.clone();
        }
        else {
            synchronized(members) {
                real_dests=new Vector(members);
            }
        }

        // if local delivery is off, then we should not wait for the message from the local member.
        // therefore remove it from the membership
        tmp=channel;
        if(tmp == null) {
            if(adapter != null && adapter.getTransport() instanceof Channel) {
                tmp=(Channel) adapter.getTransport();
            }
        }

        if(tmp != null && tmp.getOpt(Channel.LOCAL).equals(Boolean.FALSE)) {
            if(local_addr == null) {
                local_addr=tmp.getLocalAddress();
            }
            if(local_addr != null) {
                real_dests.removeElement(local_addr);
            }
        }

        // don't even send the message if the destination list is empty
        if(real_dests.size() == 0) {
            if(log.isDebugEnabled())
                log.debug("destination list is empty, won't send message");
            return;
        }

        corr.sendRequest(req_id, real_dests, msg, coll);
    }

    public void done(long req_id) {
        corr.done(req_id);
    }

    /**
     * Sends a message to a single member (destination = msg.dest) and returns the response. The message's destination
     * must be non-zero !
     */
    public Object sendMessage(Message msg, int mode, long timeout) throws TimeoutException, SuspectedException {
        Vector mbrs=new Vector();
        RspList rsp_list=null;
        Object dest=msg.getDest();
        Rsp rsp;
        GroupRequest _req=null;

        if(dest == null) {
            if(log.isErrorEnabled())
                log.error("the message's destination is null, " +
                        "cannot send message");
            return null;
        }

        mbrs.addElement(dest);   // dummy membership (of destination address)

        _req=new GroupRequest(msg, corr, mbrs, mode, timeout, 0);
        _req.setCaller(local_addr);
        _req.execute();

        if(mode == GroupRequest.GET_NONE) {
            return null;
        }

        rsp_list=_req.getResults();

        if(rsp_list.size() == 0) {
            if(log.isWarnEnabled())
                log.warn(" response list is empty");
            return null;
        }
        if(rsp_list.size() > 1) {
            if(log.isWarnEnabled())
                log.warn("response list contains more that 1 response; returning first response !");
        }
        rsp=(Rsp) rsp_list.elementAt(0);
        if(rsp.wasSuspected()) {
            throw new SuspectedException(dest);
        }
        if(!rsp.wasReceived()) {
            throw new TimeoutException();
        }
        return rsp.getValue();
    }

//    public void channelConnected(Channel channel) {
//        if(channel != null) {
//            Address new_local_addr=channel.getLocalAddress();
//            if(new_local_addr != null) {
//                this.local_addr=new_local_addr;
//
//                    if(log.isInfoEnabled()) log.info("MessageDispatcher.channelConnected()", "new local address is " + this.local_addr);
//            }
//        }
//    }
//
//    public void channelDisconnected(Channel channel) {
//    }
//
//    public void channelClosed(Channel channel) {
//    }
//
//    public void channelShunned() {
//    }
//
//    public void channelReconnected(Address addr) {
//        if(channel != null) {
//            Address new_local_addr=channel.getLocalAddress();
//            if(new_local_addr != null) {
//                this.local_addr=new_local_addr;
//
//                    if(log.isInfoEnabled()) log.info("MessageDispatcher.channelReconnected()", "new local address is " + this.local_addr);
//            }
//        }
//    }

    /* ------------------------ RequestHandler Interface ---------------------- */
    public Object handle(Message msg) {
        if(req_handler != null) {
            return req_handler.handle(msg);
        }
        else {
            return null;
        }
    }
    /* -------------------- End of RequestHandler Interface ------------------- */

    class ProtocolAdapter extends Protocol implements UpHandler {

        /* ------------------------- Protocol Interface --------------------------- */

      @Override // GemStoneAddition
        public String getName() {
            return "MessageDispatcher";
        }

      @Override // GemStoneAddition
        public void startUpHandler() {
            // do nothing, DON'T REMOVE !!!!
        }

      @Override // GemStoneAddition
        public void startDownHandler() {
            // do nothing, DON'T REMOVE !!!!
        }

      @Override // GemStoneAddition
        public void stopInternal() {
            // do nothing, DON'T REMOVE !!!!
        }

      @Override // GemStoneAddition
        protected void receiveUpEvent(Event evt) {
        }

      @Override // GemStoneAddition
        protected void receiveDownEvent(Event evt) {
        }

        /**
         * Called by request correlator when message was not generated by it. We handle it and call the message
         * listener's corresponding methods
         */
      @Override // GemStoneAddition
        public void passUp(Event evt) {
            byte[] tmp_state=null;
            switch(evt.getType()) {
                case Event.MSG:
                    if(msg_listener != null) {
                        msg_listener.receive((Message) evt.getArg());
                    }
                    break;

                case Event.GET_APPLSTATE: // reply with GET_APPLSTATE_OK
                    if(msg_listener != null) {
                        try {
                            tmp_state=msg_listener.getState();
                        }
                        catch(Throwable t) {
                            MessageDispatcher.this.log.error(ExternalStrings.MessageDispatcher_FAILED_GETTING_STATE_FROM_MESSAGE_LISTENER__0, msg_listener, t);
                        }
                    }
                    channel.returnState(tmp_state);
                    break;

                case Event.GET_STATE_OK:
                    if(msg_listener != null) {
                        try {
                            msg_listener.setState((byte[]) evt.getArg());
                        }
                        catch(ClassCastException cast_ex) {
                            if(this.log.isErrorEnabled())
                                this.log.error("received SetStateEvent, but argument " +
                                        evt.getArg() + " is not serializable. Discarding message.");
                        }
                    }
                    break;

                case Event.VIEW_CHANGE:
                    View v=(View) evt.getArg();
                    Vector new_mbrs=v.getMembers();
                    setMembers(new_mbrs);
                    if(membership_listener != null) {
                        membership_listener.viewAccepted(v);
                    }
                    break;

                case Event.SET_LOCAL_ADDRESS:
                    if(log.isTraceEnabled())
                        log.trace("setting local_addr (" + local_addr + ") to " + evt.getArg());
                    local_addr=(Address)evt.getArg();
                    break;

                case Event.SUSPECT:
                    if(membership_listener != null) {
                        membership_listener.suspect((SuspectMember)evt.getArg()); // GemStoneAddition SuspectMember struct
                    }
                    break;

                case Event.BLOCK:
                    if(membership_listener != null) {
                        membership_listener.block();
                    }
                    break;
            }
        }

      @Override // GemStoneAddition
        public void passDown(Event evt) {
            down(evt);
        }

        /**
         * Called by channel (we registered before) when event is received. This is the UpHandler interface.
         */
      @Override // GemStoneAddition
        public void up(Event evt) {
            if(corr != null) {
                corr.receive(evt); // calls passUp()
            }
            else {
                if(log.isErrorEnabled()) { //Something is seriously wrong, correlator should not be null since latch is not locked!
                    log.error(ExternalStrings.MessageDispatcher_CORRELATOR_IS_NULL_EVENT_WILL_BE_IGNORED_EVT_0_, evt);
                }
            }
        }

        @Override // GemStoneAddition
        public void down(Event evt) {
            if(channel != null) {
                channel.down(evt);
            }
            else
                if(this.log.isWarnEnabled()) {
                    this.log.warn("channel is null, discarding event " + evt);
                }
        }
        /* ----------------------- End of Protocol Interface ------------------------ */

    }

    class TransportAdapter implements Transport {

        public void send(Message msg) throws Exception {
            if(channel != null) {
                channel.send(msg);
            }
            else
                if(adapter != null) {
                    try {
                        if(id != null) {
                            adapter.send(id, msg);
                        }
                        else {
                            adapter.send(msg);
                        }
                    }
                    catch(Throwable ex) {
                        if(log.isErrorEnabled()) {
                            log.error(ExternalStrings.MessageDispatcher_EXCEPTION_0, Util.print(ex));
                        }
                    }
                }
                else {
                    if(log.isErrorEnabled()) {
                        log.error(ExternalStrings.MessageDispatcher_CHANNEL__NULL);
                    }
                }
        }

        public Object receive(long timeout) throws Exception {
            // @todo: implement
            return null;
        }
    }

    class PullPushHandler implements MessageListener, MembershipListener {

        /* ------------------------- MessageListener interface ---------------------- */
        public void receive(Message msg) {
            boolean pass_up=true;
            if(corr != null) {
                pass_up=corr.receiveMessage(msg);
            }

            if(pass_up) {   // pass on to MessageListener
                if(msg_listener != null) {
                    msg_listener.receive(msg);
                }
            }
        }

        public byte[] getState() {
            return msg_listener != null ? msg_listener.getState() : null;
        }

        public void setState(byte[] state) {
            if(msg_listener != null) {
                msg_listener.setState(state);
            }
        }
        /* --------------------- End of MessageListener interface ------------------- */

        /* ------------------------ MembershipListener interface -------------------- */
        public void viewAccepted(View v) {
            if(corr != null) {
                corr.receiveView(v);
            }

            Vector new_mbrs=v.getMembers();
            setMembers(new_mbrs);
            if(membership_listener != null) {
                membership_listener.viewAccepted(v);
            }
        }

        public void suspect(SuspectMember suspected_mbr) { // GemStoneAddition SuspectMember struct
            if(corr != null) {
                corr.receiveSuspect(suspected_mbr.suspectedMember);
            }
            if(membership_listener != null) {
                membership_listener.suspect(suspected_mbr);
            }
        }

        public void block() {
            if(membership_listener != null) {
                membership_listener.block();
            }
        }

        public void channelClosing(Channel c, Exception e) {} // GemStoneAddition

        /* --------------------- End of MembershipListener interface ---------------- */

        // @todo: receive SET_LOCAL_ADDR event and call corr.setLocalAddress(addr)

    }

}


text:
/* $Id: AFMWritingDirectionMetrics.java 679326 2008-07-24 09:35:34Z vhennebert $ */

package org.apache.fop.fonts.type1;

/**
 * Represents a writing direction metrics section from an AFM file.
 */
public class AFMWritingDirectionMetrics {

    private Number underlinePosition;
    private Number underlineThickness;
    private double italicAngle;
    private boolean isFixedPitch;

    /**
     * Returns the UnderlinePosition value.
     * @return the underlinePosition
     */
    public Number getUnderlinePosition() {
        return underlinePosition;
    }

    /**
     * Sets the UnderlinePosition value.
     * @param underlinePosition the underlinePosition to set
     */
    public void setUnderlinePosition(Number underlinePosition) {
        this.underlinePosition = underlinePosition;
    }

    /**
     * Returns the UnderlineThickness value.
     * @return the underlineThickness
     */
    public Number getUnderlineThickness() {
        return underlineThickness;
    }

    /**
     * Sets the UnderlineThickness value.
     * @param underlineThickness the underlineThickness to set
     */
    public void setUnderlineThickness(Number underlineThickness) {
        this.underlineThickness = underlineThickness;
    }

    /**
     * Returns the ItalicAngle value.
     * @return the italicAngle
     */
    public double getItalicAngle() {
        return italicAngle;
    }

    /**
     * Sets the ItalicAngle value.
     * @param italicAngle the italicAngle to set
     */
    public void setItalicAngle(double italicAngle) {
        this.italicAngle = italicAngle;
    }

    /**
     * Returns the IsFixedPitch value.
     * @return the isFixedPitch
     */
    public boolean isFixedPitch() {
        return isFixedPitch;
    }

    /**
     * Set the IsFixedPitch value.
     * @param value the isFixedPitch to set
     */
    public void setFixedPitch(boolean value) {
        this.isFixedPitch = value;
    }

}