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

using Microsoft.Xna.Framework;

namespace FiniteStateMachine
{
    public class AStar
    {
        public enum SearchType { ShortestPath, SensePropogation };
        SearchType type;

        private float PERCEPTION_THRESHOLD = 6.0f;

        // Generic Node class to be used in AStar
        private class Node
        {
            public Tile tile;
            public Node parent;
            public float G;
            public float H;

            public Node(Tile tile, Vector2 targetPosition, Node parent, SearchType type)
            {
                this.tile = tile;
                this.parent = parent;

                if (this.parent == null)
                    this.G = 0;
                else if (type == SearchType.ShortestPath)
                    this.G = this.parent.G + tile.TileCost * (Math.Abs(this.parent.tile.Position.X - tile.Position.X) + Math.Abs(this.parent.tile.Position.Y - tile.Position.Y));
                else if (type == SearchType.SensePropogation)
                    this.G = this.parent.G + tile.TileAttenuation;

                H = Math.Abs(targetPosition.X - tile.Position.X) + Math.Abs(targetPosition.Y - tile.Position.Y);
            }

            public float GetF()
            {
                return G + H;
            }
        };

        private List<Node> openList;
        private List<Node> closedList;

        public AStar(SearchType searchType = SearchType.ShortestPath)
        {
            openList = new List<Node>();
            closedList = new List<Node>();

            type = searchType;
        }

        // Sense propogation using attenuation properties of the tiles
        public bool PropogateSense(Vector2 startPosition, Vector2 targetPosition)
        {
            Tile startTile = TileMap.Tiles[(int)startPosition.Y][(int)startPosition.X];

            Node startNode = new Node(startTile, targetPosition, null, type);

            openList.Clear();
            closedList.Clear();

            openList.Add(startNode);
            while (openList.Count > 0)
            {
                Node currentNode = null;
                float minF = float.MaxValue;
                for (int i = 0; i < openList.Count; ++i)
                {
                    float F = ((Node)openList[i]).GetF();
                    if (F < minF)
                    {
                        currentNode = (Node)openList[i];
                        minF = F;
                    }
                }

                closedList.Add(currentNode);
                openList.Remove(currentNode);

                // Target reached?
                if (currentNode.tile.Position == targetPosition)
                    return true;
                else if (currentNode.G > PERCEPTION_THRESHOLD) // Target out of perception?
                    return false;

                // Check adjacent nodes
                Tile adjTile;
                Vector2 adjPosition;

                adjPosition = new Vector2(currentNode.tile.Position.X - 1, currentNode.tile.Position.Y);
                if (IsGridReachable(adjPosition))
                {
                    adjTile = TileMap.Tiles[(int)adjPosition.Y][(int)adjPosition.X];
                    CheckAdjacentNode(new Node(adjTile, targetPosition, currentNode, type));
                }

                adjPosition = new Vector2(currentNode.tile.Position.X + 1, currentNode.tile.Position.Y);
                if (IsGridReachable(adjPosition))
                {
                    adjTile = TileMap.Tiles[(int)adjPosition.Y][(int)adjPosition.X];
                    CheckAdjacentNode(new Node(adjTile, targetPosition, currentNode, type));
                }

                adjPosition = new Vector2(currentNode.tile.Position.X, currentNode.tile.Position.Y - 1);
                if (IsGridReachable(adjPosition))
                {
                    adjTile = TileMap.Tiles[(int)adjPosition.Y][(int)adjPosition.X];
                    CheckAdjacentNode(new Node(adjTile, targetPosition, currentNode, type));
                }

                adjPosition = new Vector2(currentNode.tile.Position.X, currentNode.tile.Position.Y + 1);
                if (IsGridReachable(adjPosition))
                {
                    adjTile = TileMap.Tiles[(int)adjPosition.Y][(int)adjPosition.X];
                    CheckAdjacentNode(new Node(adjTile, targetPosition, currentNode, type));
                }
            }

            return false;
        }

        // Finds the shortest path with respect to the given tile costs
        public List<Tile> FindPath(Vector2 startPosition, Vector2 targetPosition)
        {
            Tile startTile = TileMap.Tiles[(int)startPosition.Y][(int)startPosition.X];

            Node startNode = new Node(startTile, targetPosition, null, type);

            openList.Clear();
            closedList.Clear();

            openList.Add(startNode);
            while (openList.Count > 0)
            {
                Node currentNode = null;
                float minF = float.MaxValue;
                for (int i = 0; i < openList.Count; ++i)
                {
                    float F = ((Node)openList[i]).GetF();
                    if (F < minF)
                    {
                        currentNode = (Node)openList[i];
                        minF = F;
                    }
                }

                closedList.Add(currentNode);
                openList.Remove(currentNode);

                // Target reached?
                if (currentNode.tile.Position == targetPosition)
                    return GetPathPositions(currentNode);
                else if (closedList.Count > 500) // just in case (avoid infinite loop)
                    break;

                // Check adjacent nodes
                Tile adjTile;
                Vector2 adjPosition;

                adjPosition = new Vector2(currentNode.tile.Position.X - 1, currentNode.tile.Position.Y);
                if (IsGridReachable(adjPosition))
                {
                    adjTile = TileMap.Tiles[(int)adjPosition.Y][(int)adjPosition.X];
                    CheckAdjacentNode(new Node(adjTile, targetPosition, currentNode, type));
                }

                adjPosition = new Vector2(currentNode.tile.Position.X + 1, currentNode.tile.Position.Y);
                if (IsGridReachable(adjPosition))
                {
                    adjTile = TileMap.Tiles[(int)adjPosition.Y][(int)adjPosition.X];
                    CheckAdjacentNode(new Node(adjTile, targetPosition, currentNode, type));
                }

                adjPosition = new Vector2(currentNode.tile.Position.X, currentNode.tile.Position.Y - 1);
                if (IsGridReachable(adjPosition))
                {
                    adjTile = TileMap.Tiles[(int)adjPosition.Y][(int)adjPosition.X];
                    CheckAdjacentNode(new Node(adjTile, targetPosition, currentNode, type));
                }

                adjPosition = new Vector2(currentNode.tile.Position.X, currentNode.tile.Position.Y + 1);
                if (IsGridReachable(adjPosition))
                {
                    adjTile = TileMap.Tiles[(int)adjPosition.Y][(int)adjPosition.X];
                    CheckAdjacentNode(new Node(adjTile, targetPosition, currentNode, type));
                }
            }

            return GetPathPositions(closedList[closedList.Count - 1]);
        }

        // Checks if the adjacent node is proper
        void CheckAdjacentNode(Node adjNode)
        {
            bool flag = true;

            for (int i = 0; i < openList.Count; ++i)
            {
                if (openList[i].tile == adjNode.tile)
                {
                    if (adjNode.G < openList[i].G)
                    {
                        openList[i] = adjNode;
                    }

                    flag = false;
                    break;
                }
            }
            foreach (Node node in closedList)
            {
                if (adjNode.tile == node.tile)
                {
                    flag = false;
                    break;
                }
            }

            if (flag)
            {
                openList.Add(adjNode);
            }
        }

        // Checks map boundaries
        bool IsGridReachable(Vector2 p)
        {
            int x = (int)p.X;
            int y = (int)p.Y;
            return (x >= 0 && x < TileMap.Width && y >= 0 && y < TileMap.Height);
        }

        // Returns the shortest path as a list
        List<Tile> GetPathPositions(Node node)
        {
            List<Tile> positions = new List<Tile>();

            while (node.parent != null)
            {
                positions.Insert(0, node.tile);
                node = node.parent;
            }

            return positions;
        }
    }
}


text:
package com.nepxion.thunder.common.promise;

import org.jdeferred.FailCallback;

public interface PromiseFail extends FailCallback<Exception> {

}

redpajama_set_name: RedPajamaGithub


text:
/*
 * Author: doe300
 *
 * See the file "LICENSE" for the full license governing this code.
 */

#ifndef VALUES_H
#define VALUES_H

#include "BitMask.h"
#include "Optional.h"
#include "Register.h"
#include "Types.h"
#include "Variant.h"
#include "config.h"

#include <functional>
#include <string>

namespace vc4c
{
    /*
     * The arithmetic type of a literal value
     */
    enum class LiteralType : unsigned char
    {
        INTEGER,
        REAL,
        BOOL,
        // "literal type" indicating no literal present
        TOMBSTONE,
        // special version of "INTEGER" which indicates that the upper word are all ones
        LONG_LEADING_ONES,
    };

    struct SmallImmediate;

    /*
     * A literal value (a constant), directly used as operand.
     *
     * Literals cannot be handled by machine-code and must be converted before code-generation.
     * While "smaller" literal values can be directly used by ALU instructions in form of SmallImmediates,
     * "larger" values need to be loaded via a load-immediate instruction.
     */
    class Literal
    {
    public:
        LiteralType type;

        explicit constexpr Literal(optional_tombstone_tag) noexcept : type(LiteralType::TOMBSTONE), u() {}
        explicit constexpr Literal(int32_t integer) noexcept : type(LiteralType::INTEGER), i(integer) {}
        explicit constexpr Literal(uint32_t integer) noexcept : type(LiteralType::INTEGER), u(integer) {}
        explicit constexpr Literal(float real) noexcept : type(LiteralType::REAL), f(real) {}
        explicit constexpr Literal(bool flag) noexcept : type(LiteralType::BOOL), u(flag) {}
        ~Literal() = default;

        Literal(const Literal&) = default;
        Literal(Literal&&) noexcept = default;

        Literal& operator=(const Literal&) = default;
        Literal& operator=(Literal&&) noexcept = default;

        bool operator==(const Literal& other) const noexcept;
        inline bool operator!=(const Literal& other) const noexcept
        {
            return !(*this == other);
        }
        bool operator<(const Literal& other) const noexcept;

        std::string to_string() const;

        /*
         * Whether this literal represents the boolean value true
         */
        bool isTrue() const noexcept;
        /*
         * Bit-casts the stored value to a floating-point value
         */
        float real() const noexcept;
        float real(DataType floatType) const;
        /*
         * Bit-casts the stored value to a signed value
         */
        int32_t signedInt() const noexcept;
        int32_t signedInt(DataType intType) const;
        /*
         * Bit-casts the stored value to an unsigned value
         */
        uint32_t unsignedInt() const noexcept;
        uint32_t unsignedInt(DataType intType) const;

        /*
         * Converts the stored value to a immediate-value which can be used in a load-immediate instruction.
         */
        uint32_t toImmediate() const noexcept;

        /*
         * A Literal is "undefined" if it is of TOMBSTONE type. the internal value can be any of the 2^32 possible
         * values
         */
        bool isUndefined() const noexcept;

        /**
         * Returns the mask of bits set
         */
        BitMask getBitMask() const noexcept;

    private:
        /*
         * The bit-wise representation of this literal
         */
        union
        {
            int32_t i;
            uint32_t u;
            float f;
        };

        static_assert(sizeof(int32_t) == sizeof(uint32_t) && sizeof(uint32_t) == sizeof(float),
            "Sizes of literal types do not match!");
    };

    /*
     * A literal value with undefined value, doubles as not-set literal for compact optionals
     */
    static constexpr Literal UNDEFINED_LITERAL{optional_tombstone_tag{}};

    template <>
    struct tombstone_traits<Literal>
    {
        static constexpr bool is_specialized = true;
        static constexpr Literal tombstone = Literal(optional_tombstone_tag{});

        static constexpr bool isTombstone(const Literal& val) noexcept
        {
            return val.type == LiteralType::TOMBSTONE;
        }
    };

    /**
     * Tries to convert the given 64-bit value to a literal.
     *
     * Returns an empty optional on failure
     */
    Optional<Literal> toLongLiteral(uint64_t val);

    /*!
     * A SmallImmediate value is a literal (constant) value which can be loaded directly into an ALU instruction.
     *
     * SmallImmediates are no "standard" integer values, but are mapped to represent some value (e.g. using a
     * SmallImmediate value of 16 actually loads the integer value -15). Additionally, some SmallImmediate values are
     * used to load floating-point constants as well as represent the offset for vector-rotations.
     *
     * "The 6 bit small immediate field encodes either an immediate integer/float value used in place of the register
     * file b input, or a vector rotation to apply to the mul ALU output, according to Table 5."
     * - Broadcom VideoCore IV specification, page 29
     */
    struct SmallImmediate : public InstructionPart<SmallImmediate>
    {
        /*
         * Creates an object with the given field-value (not the value actually loaded!)
         */
        explicit constexpr SmallImmediate(unsigned char val) noexcept : InstructionPart(val) {}

        std::string to_string() const;

        // the "real" values being loaded with this small immediate

        /*
         * Returns the integer-value represented by this object, if this object represents an integer value.
         *
         * The field-values 0 - 15 map to the integer values 0 - 15 correspondingly,
         * the field-values 16 - 31 map to the integer values -16 to -1.
         * So the range [-16, 15] can be represented by SmallImmediate objects.
         */
        Optional<int32_t> getIntegerValue() const noexcept;
        /*
         * Returns the floating-point value represented by this object, if this object represents a floating-point
         * value.
         *
         * The field-values 32 - 29 represent the floating-point constants 1.0, 2.0, 4.0, ..., 128.0,
         * the field-values 40 - 47 represent the constants 1/256.0, 1/128.0, ..., 1/2.
         * So every power of two from 1/256.0 to 128.0 can be represented by SmallImmediates.
         */
        Optional<float> getFloatingValue() const noexcept;
        /*
         * Returns whether the field-value represents a vector-rotation
         */
        bool isVectorRotation() const noexcept;
        /*
         * Returns the constant offset for vector-rotations, if this object represents one.
         *
         * The field-value of VECTOR_ROTATE_R5 represents a vector-rotation by the value stored in SIMD-element 0 of r5,
         * bits [3:0], while the field-values 49 - 63 represent vector-rotations by an offset of 1 - 15 upwards (so
         * element 0 moves to element 1 - 15)
         *
         * NOTE: vector-rotations can only be performed by the multiplication ALU.
         */
        Optional<unsigned char> getRotationOffset() const noexcept;

        /*
         * Returns the Literal value which is represented by this SmallImmediate object.
         *
         * For vector-rotation field-values, no value us returned.
         */
        Optional<Literal> toLiteral() const noexcept;

        /*
         * Tries to create a SmallImmediate object from the given integer-value.
         *
         * Returns a new object for an argument in the range [-16, 15] and an empty optional-value otherwise.
         */
        static Optional<SmallImmediate> fromInteger(signed char val) noexcept;
        /*
         * Creates a new object from the given constant vector-rotation offset.
         *
         * The given vector-rotation offset must lie in the range [1, 15]
         */
        static SmallImmediate fromRotationOffset(unsigned char offset);
    };

    template <>
    struct tombstone_traits<SmallImmediate>
    {
        static constexpr bool is_specialized = true;
        static constexpr SmallImmediate tombstone = SmallImmediate(255);

        static constexpr bool isTombstone(SmallImmediate val) noexcept
        {
            return val.value == 255;
        }
    };

    constexpr SmallImmediate VECTOR_ROTATE_R5{48};

    class Local;
    class SIMDVector;
    namespace intermediate
    {
        class IntermediateInstruction;
    } /* namespace intermediate */

    using LocalUser = intermediate::IntermediateInstruction;

    /*
     * The main type representing all values being operated on
     */
    struct Value
    {
        /*
         * Contains the data actually stored in this Value
         */
        Variant<Literal, Register, Local*, SmallImmediate, const SIMDVector*, VariantNamespace::monostate> data;
        /*
         * The data-type of the Value
         */
        DataType type;

        Value(const Literal& lit, DataType type) noexcept;
        Value(Register reg, DataType type) noexcept;
        Value(const SIMDVector* vector, DataType type);
        Value(const Value& val) = default;
        Value(Value&& val) noexcept = default;
        Value(Local* local, DataType type) noexcept;
        Value(DataType type) noexcept;
        Value(SmallImmediate immediate, DataType type) noexcept;
        ~Value() = default;

        Value& operator=(const Value& right) = default;
        Value& operator=(Value&& right) = default;

        bool operator==(const Value& other) const;
        inline bool operator!=(const Value& other) const
        {
            return !(*this == other);
        }

        /*
         * Returns a pointer to the data of the given type or nullptr if the data is not of the requested type.
         */
        Register* checkRegister() noexcept
        {
            return VariantNamespace::get_if<Register>(&data);
        }

        const Register* checkRegister() const noexcept
        {
            return VariantNamespace::get_if<Register>(&data);
        }

        Literal* checkLiteral() noexcept
        {
            return VariantNamespace::get_if<Literal>(&data);
        }

        const Literal* checkLiteral() const noexcept
        {
            return VariantNamespace::get_if<Literal>(&data);
        }

        SmallImmediate* checkImmediate() noexcept
        {
            return VariantNamespace::get_if<SmallImmediate>(&data);
        }

        const SmallImmediate* checkImmediate() const noexcept
        {
            return VariantNamespace::get_if<SmallImmediate>(&data);
        }

        Local* checkLocal() noexcept
        {
            auto loc = VariantNamespace::get_if<Local*>(&data);
            return loc ? *loc : nullptr;
        }

        const Local* checkLocal() const noexcept
        {
            auto loc = VariantNamespace::get_if<Local*>(&data);
            return loc ? *loc : nullptr;
        }

        const SIMDVector* checkVector() const noexcept
        {
            auto vec = VariantNamespace::get_if<const SIMDVector*>(&data);
            return vec ? *vec : nullptr;
        }

        /*
         * Whether this object has the given local
         */
        bool hasLocal(const Local* local) const;
        /*
         * Whether this object has the given register
         */
        bool hasRegister(Register reg) const;
        /*
         * Whether this object has the given literal value.
         *
         * This function also accepts, if this object contains a SmallImmediate with the same integer- or
         * floating-point-value (depending on the data-type) as the parameter
         */
        bool hasLiteral(const Literal& lit) const;
        /*
         * Whether this object contains the given SmallImmediate value.
         *
         * This function also accepts, if this object contains a Literal with the same integer- or floating-point-value
         * (depending on the data-type) as the parameter
         */
        bool hasImmediate(SmallImmediate immediate) const;

        /*
         * Whether this Value is undefined, e.g. by having the TYPE_UNDEFINED data-type
         */
        bool isUndefined() const;
        /*
         * Whether this object is a constant (scalar or composite) and has the literal-value zero in all its elements
         */
        bool isZeroInitializer() const;
        /*
         * Whether this Value represents a literal value (e.g. contains a Literal or SmallImmediate)
         */
        bool isLiteralValue() const noexcept;
        /*
         * Returns the Literal stored in this Value.
         *
         * This function also converts a stored SmallImmediate into the corresponding Literal value
         */
        Optional<Literal> getLiteralValue() const noexcept;

        std::string to_string(bool writeAccess = false, bool withLiterals = false) const;

        /*
         * Whether this Value can be written to.
         *
         * Constant values of any kind cannot be written to, neither can registers which are not writeable
         */
        bool isWriteable() const;
        /*
         * Whether this object can be read from.
         *
         * Almost all value-types can be read, except for some write-only registers
         */
        bool isReadable() const;
        /*
         * Returns this object, if it is writeable. Throws an exception otherwise
         */
        const Value& assertWriteable() const;
        Value& assertWriteable();
        /*
         * Returns this object if it is readable. Throws an exception otherwise
         */
        const Value& assertReadable() const;
        Value& assertReadable();

        /*
         * Wrapper for Local#getSingleWriter() for easier access
         */
        const LocalUser* getSingleWriter() const;

        /**
         * Return whether this value is guaranteed to be an unsigned (positive) integer.
         *
         * Unsigned integers are among others:
         * - positive integer constants
         * - unsigned registers (QPU number, element number)
         * - locals where all writes are decorated as unsigned
         */
        bool isUnsignedInteger() const;

        /**
         * Returns the constant value "contained" in this value, if any.
         *
         * A value is considered constant, if it matches one of the conditions:
         * - it is a literal value
         * - it is a SIMD vector
         * - it is a small immediate
         * - it is a constant register value
         * - it is a local with a single writer writing a constant value (only if transitive flag set)
         *
         * If the resulting Value is set, it is guaranteed to be either a literal value, a small immediate or a
         * register.
         */
        Optional<Value> getConstantValue(bool transitive = true) const;

        /*
         * Creates a zero-initializer Value for the given data-type.
         *
         * For scalar types, a simple INT_ZERO is returned, for compound types, a container containing the correct
         * amount of zero-elements is created
         */
        static Optional<Value> createZeroInitializer(DataType type);

        /**
         * Returns whether all SIMD elements of this value contain the same value.
         *
         * This is e.g. true for SIMDVectors with identical elements, literal values, SmallImmediates and some
         * registers.
         */
        bool isAllSame() const;

        /**
         * Returns the mask of (possible) non-zero bits in this value when read
         */
        BitMask getReadMask() const noexcept;

        /*
         * Returns the stored data of the given type, if it matches the stored type.
         * Throws error otherwise
         */
        Literal& literal()
        {
            return VariantNamespace::get<Literal>(data);
        }

        const Literal& literal() const
        {
            return VariantNamespace::get<Literal>(data);
        }

        Register& reg()
        {
            return VariantNamespace::get<Register>(data);
        }

        const Register& reg() const
        {
            return VariantNamespace::get<Register>(data);
        }

        Local*& local()
        {
            return VariantNamespace::get<Local*>(data);
        }

        Local* const& local() const
        {
            return VariantNamespace::get<Local*>(data);
        }

        SmallImmediate& immediate()
        {
            return VariantNamespace::get<SmallImmediate>(data);
        }

        const SmallImmediate& immediate() const
        {
            return VariantNamespace::get<SmallImmediate>(data);
        }

        const SIMDVector& vector() const
        {
            return *VariantNamespace::get<const SIMDVector*>(data);
        }
    };

    /*
     * The boolean-value true
     */
    const Value BOOL_TRUE(Literal(true), TYPE_BOOL);
    /*
     * The boolean-value false
     */
    const Value BOOL_FALSE(Literal(false), TYPE_BOOL);
    /*
     * The integer value of zero
     */
    const Value INT_ZERO(Literal(static_cast<uint32_t>(0)), TYPE_INT8);
    /*
     * The integer value of one
     */
    const Value INT_ONE(Literal(static_cast<uint32_t>(1)), TYPE_INT8);
    /*
     * The integer value of minus one
     */
    const Value INT_MINUS_ONE(Literal(static_cast<uint32_t>(0xFFFFFFFF)), TYPE_INT32);
    /*
     * The floating-point value of zero
     */
    const Value FLOAT_ZERO(Literal(0.0f), TYPE_FLOAT);
    /*
     * The floating-point value of one
     */
    const Value FLOAT_ONE(Literal(1.0f), TYPE_FLOAT);
    /*
     * The floating-point constant representing INF
     */
    const Value FLOAT_INF(Literal(static_cast<uint32_t>(0x7F800000)), TYPE_FLOAT);
    /*
     * The floating-point constant representing -INF
     */
    const Value FLOAT_NEG_INF(Literal(static_cast<uint32_t>(0xFF800000)), TYPE_FLOAT);
    /*
     * The floating-point constant representing NAN
     *
     * NOTE: There are different representations of a NaN!
     */
    const Value FLOAT_NAN(Literal(static_cast<uint32_t>(0x7FFFFFFF)), TYPE_FLOAT);
    /*
     * A undefined value
     */
    const Value UNDEFINED_VALUE(TYPE_UNKNOWN);
    /*
     * A constant Optional value containing no value
     */
    const Optional<Value> NO_VALUE;
    /*
     * All 32 bits are set
     */
    const Value VALUE_ALL_BITS_SET = INT_MINUS_ONE;

    /*
     * The Value representing the REG_UNIFORM register to read UNIFORMs
     */
    const Value UNIFORM_REGISTER(REG_UNIFORM, TYPE_INT32.toVectorType(16));
    /*
     * The Value representing the NOP-register
     */
    const Value NOP_REGISTER(REG_NOP, TYPE_UNKNOWN);
    /*
     * The Value representing the REG_ELEMENT_NUMBER
     */
    const Value ELEMENT_NUMBER_REGISTER(REG_ELEMENT_NUMBER, TYPE_INT8.toVectorType(16));
    /*
     * The element numbers (0, 1, 2, 3, ...) returned when querying the element-number register
     */
    extern const Value ELEMENT_NUMBERS;
    /*
     * The Value representing the r5 rotation offset register
     */
    const Value ROTATION_REGISTER(REG_ACC5, TYPE_INT8);

} /* namespace vc4c */

namespace std
{
    template <>
    struct hash<vc4c::Literal> : public std::hash<int32_t>
    {
        inline size_t operator()(const vc4c::Literal& lit) const noexcept
        {
            return std::hash<int32_t>::operator()(lit.signedInt());
        }
    };

    template <>
    struct hash<vc4c::SmallImmediate> : public std::hash<unsigned char>
    {
        inline size_t operator()(const vc4c::SmallImmediate& val) const noexcept
        {
            return std::hash<unsigned char>::operator()(val.value);
        }
    };

    template <>
    struct hash<vc4c::Value>
    {
        size_t operator()(const vc4c::Value& val) const noexcept;
    };
} /* namespace std */

#endif /* VALUES_H */


text:
/*                     __                                               *\
**     ________ ___   / /  ___     Scala API                            **
**    / __/ __// _ | / /  / _ |    (c) 2003-2010, LAMP/EPFL             **
**  __\ \/ /__/ __ |/ /__/ __ |    http://scala-lang.org/               **
** /____/\___/_/ |_/____/_/ | |                                         **
**                          |/                                          **
\*                                                                      */

package scala.xml

import Utility.{ isNameStart }

/** Essentially, every method in here is a dummy, returning Zero[T].
 *  It provides a backstop for the unusual collection defined by MetaData,
 *  sort of a linked list of tails.
 */
case object Null extends MetaData {
  override def iterator = Iterator.empty
  override def append(m: MetaData, scope: NamespaceBinding = TopScope): MetaData = m
  override def filter(f: MetaData => Boolean): MetaData = this

  def copy(next: MetaData) = next
  def getNamespace(owner: Node) = null

  override def hasNext = false
  def next = null
  def key = null
  def value = null
  def isPrefixed = false

  override def length = 0
  override def length(i: Int) = i

  override def strict_==(other: Equality) = other match {
    case x: MetaData  => x.length == 0
    case _            => false
  }
  override def basisForHashCode: Seq[Any] = Nil

  def apply(namespace: String, scope: NamespaceBinding, key: String) = null
  def apply(key: String) = {
    if (!isNameStart(key.head))
      throw new IllegalArgumentException("not a valid attribute name '"+key+"', so can never match !")

    null
  }

  def toString1(sb: StringBuilder) = ()
  override def toString1(): String = ""
  override def toString(): String = ""

  override def buildString(sb: StringBuilder): StringBuilder = sb
  override def wellformed(scope: NamespaceBinding) = true

  def remove(key: String) = this
  def remove(namespace: String, scope: NamespaceBinding, key: String) = this
}


text:
public String plusOut(String str, String word) {
  StringBuilder sb = new StringBuilder();

  int wordIndex = str.indexOf(word);
  int i = 0;

  while (i < str.length()) {
    if (i == wordIndex) {
      sb.append(word);
      i += word.length();
      wordIndex = str.indexOf(word, wordIndex + word.length());
    }
    else {
      sb.append('+');
      i++;
    }
  }

  return sb.toString();
}


text:
        Tagungstechnik und Equipment

❯


text:
<!DOCTYPE html>

    <meta charset="utf-8">
    <title>QR Code Scanner</title>
    <meta http-equiv=X-UA-Compatible content="IE=edge">
    <meta name=description content="QR Code Scanner is the fastest and most user-friendly web application.">
    <meta name="viewport" content="width=device-width,initial-scale=1.0">
    <meta name="mobile-web-app-capable" content="yes">
    <meta name="apple-mobile-web-app-title" content="QR Scanner"/>
    <meta name="apple-mobile-web-app-status-bar-style" content="#e4e4e4">
    <meta name="apple-mobile-web-app-capable" content="yes">
    <meta name="application-name" content="QR Scanner"/>
    <meta name="msapplication-TileColor" content="#e4e4e4"/>
    <meta name="msapplication-TileImage" content="/images/touch/mstile-150x150.png"/>
    <meta name="theme-color" content="#fff"/>
    <link rel="apple-touch-icon" href="/images/touch/apple-touch-icon.jpg"/>
    <link rel="icon" type="image/png" href="/images/touch/favicon-32x32.png" sizes="32x32"/>
    <link rel="icon" type="image/png" href="/images/touch/favicon-16x16.png" sizes="16x16"/>
    <link rel="shortcut icon" href="/images/touch/favicon.ico">
    <link rel="manifest" href="/manifest.json">

          <svg fill="#FFFFFF" height="27" viewBox="0 0 24 24" width="27" xmlns="http://www.w3.org/2000/svg">
            <path d="M0 0h24v24H0z" fill="none"/>
            <path d="M11 17h2v-6h-2v6zm1-15C6.48 2 2 6.48 2 12s4.48 10 10 10 10-4.48 10-10S17.52 2 12 2zm0 18c-4.41 0-8-3.59-8-8s3.59-8 8-8 8 3.59 8 8-3.59 8-8 8zM11 9h2V7h-2v2z"/>
          </svg>

        <video autoplay></video>

Tech:IRL Attendee

            <input type="text" id="result">

            <button type="button" class="app__dialog-open">Open</button>
            <button type="button" class="app__dialog-close">Submit</button>

Point your camera at a QR Code

Select from photos


text:
package jp.sfapps.partialmatchsearchinarrayadapter;

import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.text.Editable;
import android.text.TextWatcher;
import android.widget.EditText;
import android.widget.ListView;

public class MainActivity extends AppCompatActivity implements TextWatcher {

    ListView mListView;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        mListView = (ListView) findViewById(R.id.listView);
        SearchableArrayAdapter<String> adapter = new SearchableArrayAdapter<String>(this, android.R.layout.simple_list_item_1);
        adapter.add("Red");
        adapter.add("Blue");
        adapter.add("Yellow");
        adapter.add("Green");
        adapter.add("Pink");
        adapter.add("Orange");
        adapter.add("Purple");
        adapter.add("Gray");
        adapter.add("Black");
        adapter.add("White");
        mListView.setAdapter(adapter);
        ((EditText) findViewById(R.id.editText)).addTextChangedListener(this);
    }

    @Override
    public void beforeTextChanged(CharSequence s, int start, int count, int after) {

    }

    @Override
    public void onTextChanged(CharSequence s, int start, int before, int count) {
        ((SearchableArrayAdapter) mListView.getAdapter()).getFilter().filter(s.toString());
    }

    @Override
    public void afterTextChanged(Editable s) {

    }
}


text:
title: Page not found
layout: page
permalink: /404.html
---

Sorry, but the page you were trying to view has moved or does not exist.


text:
package com.popumovies.utils;

import android.content.Context;
import android.content.res.TypedArray;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.AttributeSet;

import com.popumovies.R;

public class AutofitRecyclerView extends RecyclerView {
  private GridLayoutManager manager;
  private int columnWidth = -1;

  public AutofitRecyclerView(Context context) {
    super(context);
    init(context, null);
  }

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

  public AutofitRecyclerView(Context context, AttributeSet attrs, int defStyle) {
    super(context, attrs, defStyle);
    init(context, attrs);
  }

  private void init(Context context, AttributeSet attrs) {
    if (attrs != null) {
      int[] attrsArray = {
          android.R.attr.columnWidth
      };
      TypedArray array = context.obtainStyledAttributes(attrs, attrsArray);
      columnWidth = array.getDimensionPixelSize(0, -1);
      array.recycle();
    }

    manager = new GridLayoutManager(getContext(), 1);
    setLayoutManager(manager);
  }

  @Override
  protected void onMeasure(int widthSpec, int heightSpec) {
    super.onMeasure(widthSpec, heightSpec);
    if (columnWidth > 0) {
      int spanCount = Math.max(getResources().getInteger(R.integer.min_col_list), getMeasuredWidth() / columnWidth);
      manager.setSpanCount(spanCount);
    }
  }
}


text:
post '/user/identity/hide' do
  user = User.find(session[:user_id])
  user.fixed_identity = false
  user.save

  if request.xhr?
    erb :'/user/_identity', layout: false
  else
    redirect('/')
  end
end

post '/user/identity/reveal' do
  user = User.find(session[:user_id])
  user.fixed_identity = true
  user.save

  if request.xhr?
    erb :'/user/_identity', layout: false
  else
    redirect('/')
  end
end


text:
@interface XOManagedObject : NSManagedObject

+ (id)objectWithId:(id)identifier inContext:(NSManagedObjectContext *)context;

- (void)unpackDictionary:(NSDictionary *)dictionary inContext:(NSManagedObjectContext *)context;

@end


text:
<Record>
<Term>Metformin-rosiglitazone</Term>
<SemanticType>Pharmacologic Substance</SemanticType>
<SemanticType>Organic Chemical</SemanticType>
<Synonym>Metformin hydrochloride;rosiglitazone maleate</Synonym>
<Synonym>Rosiglitazone maleate; metformin hydrochloride</Synonym>
<Synonym>Avandamet</Synonym>
<Synonym>Rosiglitazone-metformin</Synonym>
<Synonym>Metformin-rosiglitazone</Synonym>
<Source>FDA Registry</Source>
</Record>


text:
// Authors: Jorge. A Navas, Peter Schachte, Harald Sondergaard, and
//          Peter J. Stuckey.
// The University of Melbourne 2012.
#ifndef __ABSTRACT_VALUE_H__
#define __ABSTRACT_VALUE_H__
////////////////////////////////////////////////////////////////////////////
/// \file AbstractValue.h
///       Abstract Lattice Value Interface.
///
/// This file contains the declaration of the AbstractValue
/// class, which is the base class to represent an element of an
/// abstract state.
///
/// An abstract state is a set of pairs <Var,Value_{bottom}> were
/// Value_{bottom} is the abstract value extended with the symbol
/// bottom. The set itself cannot be bottom.  Therefore if a block is
/// unreachable we may have multiple abstract states that represent
/// it.
////////////////////////////////////////////////////////////////////////////

#include "Support/TBool.h"
#include "llvm/Value.h"
#include "llvm/Constants.h"
#include "llvm/Type.h"
#include "llvm/ADT/SmallPtrSet.h"
#include "llvm/ADT/DenseMap.h"
#include "llvm/Support/raw_ostream.h"
#include "llvm/Support/Debug.h"

using namespace llvm;
namespace unimelb {

  /// Hierarchy members that can be instantiated
  typedef enum {
    RangeId               = 0, //!< classical range analysis.
    WrappedRangeId        = 1  //!< wrapped range analysis.
  } BaseId ;

  /// Class that represents an abstract value.
  class AbstractValue {
  protected:
    Value *var;           //!< variable associated with the abstract value.
    unsigned numOfChanges;//!< how many times the abstract value has been changed.
    /// Block where the variable is defined. If a formal parameter
    /// then B is the first block of the function.
    BasicBlock *B;        //!< needed only if FixpointSSI
    bool IsLattice;       //!< whether the abstract domain is a lattice or not.
  public:
    virtual BaseId getValueID() const = 0;

    /// Constructor of the class
    AbstractValue(Value *v, bool isLattice = true):
      var(v), numOfChanges(0), B(NULL), IsLattice(isLattice){}
    /// Constructor of the class. Only for temporary computations.
    AbstractValue(bool isLattice = true):
      var(NULL), numOfChanges(0), IsLattice(isLattice){}
    /// Copy constructor of the class
    AbstractValue(const AbstractValue&  other) {
      var          = other.var;
      numOfChanges = other.numOfChanges;
      B            = other.B;
      IsLattice    = other.IsLattice;
    }
    /// Make a clone of the abstract value
    virtual AbstractValue* clone() = 0;
    /// Destructor of the class
    virtual ~AbstractValue(){}

    /// Return the number of times the variable has changed.
    inline unsigned  getNumOfChanges(){ return numOfChanges; }
    /// Return a pointer to the Value associated with the abstract
    /// value. Return NULL if the value is a constant.
    inline Value*    getValue()         { return var; }
    inline Value*    getValue()   const { return var; }
    /// Return true if the variable is a constant.
    inline bool      isConstant() const { return (var == NULL); }
    /// Return true if the abstract domain is a lattice.
    inline bool      isLattice() const {
      /// Currently, we return always true even if the underlying
      /// domain is not actually a lattice. This is sound but it may
      /// have negative consequences in terms of precision and
      /// termination during the fixpoint computation. For now, we
      /// take the risk.
      return true /*IsLattice*/;
    }
    /// Return basic block associated with the variable (if fixpointSSI)
    inline BasicBlock* getBasicBlock() { return B;}

    /// Increment by one the number of changes.
    inline void incNumOfChanges(){ numOfChanges++;  }
    /// Reset to zero the number of changes.
    inline void resetNumOfChanges(){ numOfChanges=0;  }
    /// Method for support type inquiry through isa, cast, and
    /// dyn_cast.
    /// Set the basic block associated with the variable (if fixpointSSI)
    inline void setBasicBlock(BasicBlock *_B) { assert(!B); B=_B;}

    static inline bool classof(const AbstractValue *) { return true;}

    //////
    /// Standard abstract domain operations
    //////

    /// Return true if |gamma(a)| = 1 where a is an abstract element.
    virtual bool isGammaSingleton() const = 0 ;

    /// Return true if the abstract value is bottom.
    virtual bool isBot() const = 0 ;
    /// Return true if the abstract value is top.
    virtual bool IsTop() const = 0 ;
    /// Make bottom the abstract value.
    virtual void makeBot() = 0;
    /// Make top the abstract value.
    virtual void makeTop() = 0;
    /// Join the abstract value V and this and store the result in
    /// this.
    virtual void join(AbstractValue * V) = 0;
    /// Special version to join multiple values if non-lattice domain.
    virtual void GeneralizedJoin(std::vector<AbstractValue *>) = 0;
    /// Meet two abstract values V1 and V2 and store the result in
    /// this.
    /// \todo It would be more convenient to be a friend
    virtual void meet(AbstractValue *V1, AbstractValue *V2) = 0;
    /// Return true if this is less or equal than V.
    virtual bool lessOrEqual(AbstractValue *V) = 0;
    /// Return true if this is equal to V.
    virtual bool isEqual(AbstractValue *V) = 0;
    /// Widen this by using V, and optionally a jump-set J.
    /// lessOrEqual(V) must return true.
    virtual void widening(AbstractValue *V, const std::vector<int64_t> &J) = 0;
    /// Pretty-printer of the abstract value.
    virtual void print(raw_ostream &Out) const{
      if (!isConstant()){
	if (var->hasName()) Out << var->getName() << "=" ;
      }
    }

    /// Return true if this is syntactically equal to V.
    virtual bool isIdentical(AbstractValue *V) = 0;

    // Specific transfer functions

    /// Execute an arithmetic operation in the abstract domain.
    virtual AbstractValue * visitArithBinaryOp(AbstractValue *, AbstractValue *,
					       unsigned, const char *) = 0;
    /// Execute a bitwise operation in the abstract domain.
    virtual AbstractValue * visitBitwiseBinaryOp(AbstractValue *, AbstractValue *,
						 const Type *,const Type *, unsigned, const char *) = 0;
    /// Execute a casting operation in the abstract domain.
    virtual AbstractValue * visitCast(Instruction &, AbstractValue *, TBool*, bool) = 0;

    // Methods to evaluate a guard
    virtual bool comparisonSle(AbstractValue *) = 0;
    virtual bool comparisonSlt(AbstractValue *) = 0;
    virtual bool comparisonUle(AbstractValue *) = 0;
    virtual bool comparisonUlt(AbstractValue *) = 0;
    // Method to refine the abstract value using a conditional
    virtual void filterSigma(unsigned, AbstractValue*, AbstractValue*) = 0;

  };
} // End llvm namespace

#endif


text:
@interface JxbHttpVC ()<UITableViewDataSource,UITableViewDelegate>
@property(nonatomic,strong)UITableView  *tableView;
@property(nonatomic,strong)NSArray      *listData;
@end

@implementation JxbHttpVC

- (void)dealloc {
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    [self.navigationItem setTitle:@"Http"];

    UIButton *btnclose = [[UIButton alloc] initWithFrame:CGRectMake(0, 0, 44, 44)];
    btnclose.titleLabel.font = [UIFont systemFontOfSize:13];
    [btnclose setTitle:@"关闭" forState:UIControlStateNormal];
    [btnclose addTarget:self action:@selector(dismissViewController) forControlEvents:UIControlEventTouchUpInside];
    [btnclose setTitleColor:[JxbDebugTool shareInstance].mainColor forState:UIControlStateNormal];

    UIBarButtonItem *btnleft = [[UIBarButtonItem alloc] initWithCustomView:btnclose];
    self.navigationItem.leftBarButtonItem = btnleft;

    UIButton *btnclear = [[UIButton alloc] initWithFrame:CGRectMake(0, 0, 44, 44)];
    btnclear.titleLabel.font = [UIFont systemFontOfSize:13];
    [btnclear setTitle:@"清空" forState:UIControlStateNormal];
    [btnclear addTarget:self action:@selector(clearAction) forControlEvents:UIControlEventTouchUpInside];
    [btnclear setTitleColor:[JxbDebugTool shareInstance].mainColor forState:UIControlStateNormal];

    UIBarButtonItem *btnright = [[UIBarButtonItem alloc] initWithCustomView:btnclear];
    self.navigationItem.rightBarButtonItem = btnright;

    self.tableView = [[UITableView alloc] initWithFrame:self.view.bounds style:UITableViewStyleGrouped];
    self.tableView.backgroundColor = [UIColor clearColor];
    self.tableView.delegate = self;
    self.tableView.dataSource = self;
    self.tableView.separatorStyle = UITableViewCellSeparatorStyleSingleLine;
    self.tableView.autoresizingMask = UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight;
    [self.view addSubview:self.tableView];

    [self reloadHttp];

    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(reloadHttp) name:kNotifyKeyReloadHttp object:nil];
}

- (void)dismissViewController {
    [self dismissViewControllerAnimated:YES completion:nil];
}

- (void)clearAction {
    [[JxbHttpDatasource shareInstance] clear];
    self.listData = nil;
    [self.tableView reloadData];
}

- (void)reloadHttp {
    self.listData = [[[JxbHttpDatasource shareInstance] httpArray] copy];
    [self.tableView reloadData];
}

#pragma mark - UITableView Delegate
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return self.listData.count;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    return 55;
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    return 0.1;
}

- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section {
    return 0.1;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    static NSString *identifer = @"httpcell";
    JxbHttpCell *cell = [tableView dequeueReusableCellWithIdentifier:identifer];
    if (!cell) {
        cell = [[JxbHttpCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:identifer];
    }
    JxbHttpModel* model = [self.listData objectAtIndex:indexPath.row];
    [cell setTitle:model.url.host value:model.url.path];
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    JxbHttpModel* model = [self.listData objectAtIndex:indexPath.row];
    JxbHttpDetailVC* vc = [[JxbHttpDetailVC alloc] init];
    vc.hidesBottomBarWhenPushed = YES;
    vc.detail = model;
    [self.navigationController pushViewController:vc animated:YES];
}
@end


text:
"""Helper classes and functions needed to globally enable/disable sound"""
import pygame
from pygame.mixer import Sound as OldSound

import config

# Cannot use inheritance or decorator because pygame.mixer.Sound is a C-extension.
class Sound:
    """Class wrapping ``pygame.mixer.Sound`` with the ability to enable/disable sound globally

    Use this instead of ``pygame.mixer.Sound``. The interface is fully transparent.
    """
    def __init__(self, source):
        if config.SOUND:
            self.sound = OldSound(source)

    def play(self, loops=0, maxtime=0, fade_ms=0):
        if config.SOUND:
            self.sound.play(loops, maxtime, fade_ms)

    def stop(self):
        if config.SOUND:
            self.sound.stop()

    def fadeout(self, time):
        if config.SOUND:
            self.sound.fadeout(time)

    def set_volume(self, value):
        if config.SOUND:
            self.sound.set_volume(value)

    def get_volume(self):
        if config.SOUND:
            return self.sound.get_volume()

    def get_num_channels(self):
        if config.SOUND:
            return self.sound.get_num_channels()

    def get_length(self):
        if config.SOUND:
            return self.get_length()

    def get_raw(self):
        if config.SOUND:
            return self.sound.get_raw()

def init(audio_params):
    """Use this instead of ``pygame.mixer.init``"""
    if config.SOUND:
        pygame.mixer.init(audio_params[0], audio_params[1], audio_params[2], audio_params[3])


text:
class NotificationPreference < ActiveRecord::Base
  belongs_to :user

  validates :user, presence: true
  validates :notification_type, presence: true
end


text:
import angular from "angular";
import * as DatabaseStore from "./services/database-store";
import * as DatabaseUsageStore from "./services/database-usage-store";
import {registerComponents, registerStores} from "../common/module-utils";
import DatabasePies from "./components/database-pies/database-pies";
import Routes from "../databases/routes";
import DatabaseView from "../databases/pages/view/database-view";
import DatabaseOverview from "../databases/components/overview/database-overview";

export default () => {

    const module = angular.module("waltz.databases", []);

    module.config(Routes);

    registerComponents(module, [
        DatabaseView,
        DatabaseOverview
    ]);

    module
        .component("waltzDatabasePies", DatabasePies);

    registerStores(module, [DatabaseStore, DatabaseUsageStore]);

    return module.name;
};


text:
{{ site.data.ui-text[site.locale].contact }}

{{ site.data.ui-text[site.locale].findus }}

			<form method="POST" action="http://formspree.io/{{ site.email }}">

				{{ site.data.ui-text[site.locale].name }} *
				<input name="Name" type="text" id="contactName" size="30" value="" />

				{{ site.data.ui-text[site.locale].email }} *
				<input name="Email" type="email" id="contactEmail" size="30" value="" />

				{{ site.data.ui-text[site.locale].message }} *
				<textarea name="Message" id="contactMessage" rows="6" cols="7"></textarea>

				<button type="submit">{{ site.data.ui-text[site.locale].submit }}</button>

			</form>

{{ site.data.ui-text[site.locale].where }}

{{ site.where }}

{{ site.data.ui-text[site.locale].address }}

						{{ site.address }}

{{ site.data.ui-text[site.locale].email }}

						{{ site.formspree_email }}


text:
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
// Code generated by Microsoft (R) AutoRest Code Generator.

package com.azure.resourcemanager.sql.generated;

import com.azure.core.util.Context;

/** Samples for Databases Get. */
public final class DatabasesGetSamples {
    /*
     * x-ms-original-file: specification/sql/resource-manager/Microsoft.Sql/preview/2017-10-01-preview/examples/GetVCoreDatabase.json
     */
    /**
     * Sample code: Gets a database.
     *
     * @param azure The entry point for accessing resource management APIs in Azure.
     */
    public static void getsADatabase(com.azure.resourcemanager.AzureResourceManager azure) {
        azure
            .sqlServers()
            .manager()
            .serviceClient()
            .getDatabases()
            .getWithResponse("Default-SQL-SouthEastAsia", "testsvr", "testdb", Context.NONE);
    }
}


text:
layout: single
title: caffe源码阅读
categories:
  - AI
tags:
  - caffe
---

* content
{:toc}
## 一、caffe::Net

#### 1、NetParameter定义

其中DEPRECATED已经去除

```protobuf
message NetParameter {
  optional string name = 1; // consider giving the network a name
  optional bool force_backward = 5 [default = false];
  optional NetState state = 6;
  optional bool debug_info = 7 [default = false];
  repeated LayerParameter layer = 100;  // ID 100 so layers are printed last.
}
```

<!--more-->

#### 2、重要成员变量

* `string name_` : 表示网络名称
* `Phase phase_` : 表示TEST或者TRAIN
* `vector<shared_ptr<Layer<Dtype> > > layers_` : 存储每层Layer的结构体指针
* `vector<string> layer_names_` : 存储每层Layer的名称
* `vector<shared_ptr<Blob<Dtype> > > blobs_` : 存放Layer之间的结果数据,即每层的输入输出
* `vector<string> blob_names_` : 存储blob的名称
* `vector<vector<Blob<Dtype>*> > bottom_vecs_` : 存储每层Layer的输入,数据在`blobs_`中
* `vector<vector<Blob<Dtype>*> > top_vecs_` : 存储每层Layer的输出,输在在`blobs_`中
* `vector<shared_ptr<Blob<Dtype> > > params_` : 存储每层Layer的参数

#### 3、主要代码逻辑

###### 构造函数

`explicit Net(const string& param_file, Phase phase, const int level = 0, const vector<string>* stages = NULL)`

* `param_file`指定prototxt文件,phase指定TRAIN或者TEST

* 通过protobuf接口解析prototxt后得到NetParameter,再将NetParameter转化成各个私有成员变量

* 私有成员变量的赋值过程如下:

  ```c++
  // 遍历所有的layer
  for (int layer_id = 0; layer_id < param.layer_size(); ++layer_id) {
    const LayerParameter& layer_param = param.layer(layer_id); // 当前layer引用
    layers_.push_back(LayerRegistry<Dtype>::CreateLayer(layer_param)); // layers_
    layer_names_.push_back(layer_param.name()); // layer_names_
    for(layer_param.bottom) AppendBottom(...); // bottom_vecs_/bottom_id_vecs_
    ......
  }
  ```

###### 关于LayerRegistry

* 其核心为`static CreatorRegistry* g_registry_`,类型是`typedef std::map<string, Creator> CreatorRegistry`,它是Layer的类型名称与Layer的构建方法的对应表。
* 对应表由`AddCreator`生成,并封装在`LayerRegisterer`中,并进一步封装在`REGISTER_LAYER_CLASS`中,生成static的全局类,所以在main之前就会被调用产生对应。
* `REGISTER_LAYER_CLASS`内会生成Creator接口(也就是调用new生成类),并构建对应表。
* `CreateLayer`以protobuf定义的`LayerParameter`为参数,先判断它的type在对应表中是否存在,然后调用这个type对应的Create接口,生成Layer类。

###### CopyTrainedLayersFrom

`void CopyTrainedLayersFrom(const string& trained_filename)`

* `trained_filename`对应caffemodel文件

* 通过protobuf接口解析caffemodel后得到NetParameter

* 将每一层LayerParameter的Blob全部拷贝到`layers_`的blob中,基本代码如下:

  ```c++
  auto & target_blobs = layers_[target_layer_id]->blobs();
  for (int j = 0; j < target_blobs.size(); ++j) {
    target_blobs[j]->FromProto(source_layer.blobs(j), false);
  }
  ```

## 二、caffe::Layer

#### 1、LayerParameter定义

```protobuf
message LayerParameter {
  optional string name = 1; // the layer name
  optional string type = 2; // the layer type
  repeated string bottom = 3; // the name of each bottom blob
  repeated string top = 4; // the name of each top blob
  optional Phase phase = 10;
  repeated float loss_weight = 5;
  repeated ParamSpec param = 6;
  repeated BlobProto blobs = 7;
  repeated bool propagate_down = 11;
  repeated NetStateRule include = 8;
  repeated NetStateRule exclude = 9;
  optional TransformationParameter transform_param = 100;
  optional LossParameter loss_param = 101;
  optional AccuracyParameter accuracy_param = 102;
  optional AnnotatedDataParameter annotated_data_param = 200;
  optional ArgMaxParameter argmax_param = 103;
  ......
}
```

#### 2、重要成员变量

* `LayerParameter layer_param_` : 记录protobuf中的layer param定义
* `Phase phase_` : TRAIN 或者 TEST
* `vector<shared_ptr<Blob<Dtype> > > blobs_` : 存储每层网络的训练参数。通常`blobs_[0]`存储该层网络的weight,`blobs_[1]`存储该层网络的bias。
* `vector<bool> param_propagate_down_` : 标记是否要对param blob计算diff
* `vector<Dtype> loss_` : 存储该层网络的loss,通常loss layer外都为0

## 三、Layer衍生类

#### 1、caffe::BaseConvolutionLayer

* `int bottom_dim_` : 输入数据的维度
* `int top_dim_` : 输出数据的维度
* `int num_` : batch大小
* `int out_spatial_dim_` : 经过卷积后的维度

#### 2、caffe::PoolingLayer

* `int height_, width_` : 输入的图像的尺寸
* `int pooled_height_, pooled_width_` : 输出图像的尺寸
* `int kernel_h_, kernel_w_` : 采样核的尺寸
* `int channels_` : 卷积核的数目

#### 3、caffe::InnerProductLayer

* 运算为`output=input*weight+bias`
* `int M_` 表示input矩阵的行数目
* `int K_` 表示input矩阵的列数目
* `int N_` 表示output的列数


text:
//===========================================================================
//    Copyright 2014 Delving B.V.
//
//    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.
//===========================================================================
package eu.delving.x3ml.engine;

import org.w3c.dom.NamedNodeMap;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;

import javax.xml.namespace.NamespaceContext;
import javax.xml.xpath.XPath;
import javax.xml.xpath.XPathConstants;
import javax.xml.xpath.XPathExpression;
import javax.xml.xpath.XPathExpressionException;
import javax.xml.xpath.XPathFactory;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;

import static eu.delving.x3ml.X3MLEngine.exception;
import static eu.delving.x3ml.engine.X3ML.GeneratorElement;
import static eu.delving.x3ml.engine.X3ML.Helper.argVal;
import static eu.delving.x3ml.engine.X3ML.SourceType;

/**
 * The source data is accessed using xpath to fetch nodes from a DOM tree.
 * <p/>
 * Here we have tools for evaluating xpaths in various contexts.
 *
 * @author Gerald de Jong <gerald@delving.eu>
 */
public class XPathInput {

    private final XPathFactory pathFactory = net.sf.saxon.xpath.XPathFactoryImpl.newInstance();
    private final NamespaceContext namespaceContext;
    private final String languageFromMapping;
    private final Node rootNode;
    private Map<String, Map<String, List<Node>>> rangeMapCache = new TreeMap<String, Map<String, List<Node>>>();

    public XPathInput(Node rootNode, NamespaceContext namespaceContext, String languageFromMapping) {
        this.rootNode = rootNode;
        this.namespaceContext = namespaceContext;
        this.languageFromMapping = languageFromMapping;
    }

    public X3ML.ArgValue evaluateArgument(Node node, int index, GeneratorElement generatorElement, String argName, SourceType defaultType) {
        X3ML.GeneratorArg foundArg = null;
        SourceType type = defaultType;
        if (generatorElement.args != null) {
            for (X3ML.GeneratorArg arg : generatorElement.args) {
                if (arg.name == null) {
//                    throw exception("Argument needs a name in generator "+generatorElement.name);
                    arg.name = "text";
                }
                if (arg.name.equals(argName)) {
                    foundArg = arg;
                    type = sourceType(arg.type, defaultType);
                }
            }

        }
        X3ML.ArgValue value = null;
        switch (type) {

            case xpath:
                if (foundArg == null) {
                    return null;
                }
                String lang = getLanguageFromSource(node);
                if (lang == null) {
                    lang = languageFromMapping;
                }
                if (!foundArg.value.isEmpty()) {
                    value = argVal(valueAt(node, foundArg.value), lang);
                    if (value.string.isEmpty()) {
                        throw exception("Empty result for arg " + foundArg.name + " at node " + node.getNodeName() + " in generator\n" + generatorElement);
                    }
                }
                break;
            case constant:
                if (foundArg == null) {
                    return null;
                }
                value = argVal(foundArg.value, languageFromMapping);
                break;
            case position:
                value = argVal(String.valueOf(index), null);
                break;
            default:
                throw new RuntimeException("Not implemented");
        }
        return value;
    }

    public String valueAt(Node node, String expression) {
        List<Node> nodes = nodeList(node, expression);
        if (nodes.isEmpty()) {
            return "";
        }
        String value = nodes.get(0).getNodeValue();
        if (value == null) {
            return "";
        }
        return value.trim();
    }

    public int countNodes(Node node, String expression) {
        List<Node> nodes = nodeList(node, expression);
        return nodes.size();
    }

    public List<Node> nodeList(Node node, X3ML.Source source) {
        if (source != null) {
            return nodeList(node, source.expression);
        } else {
            List<Node> list = new ArrayList<Node>(1);
            list.add(node);
            return list;
        }
    }

    public List<Node> nodeList(Node context, String expression) {

        if (expression == null || expression.length() == 0) {
            List<Node> list = new ArrayList<Node>(1);
            list.add(context);
            return list;
        }
        try {
            XPathExpression xe = xpath().compile(expression);

            NodeList nodeList = (NodeList) xe.evaluate(context, XPathConstants.NODESET);
            int nodesReturned = nodeList.getLength();
            List<Node> list = new ArrayList<Node>(nodesReturned);
            for (int index = 0; index < nodesReturned; index++) {
                list.add(nodeList.item(index));
            }
            return list;
        } catch (XPathExpressionException e) {
            throw new RuntimeException("XPath Problem: " + expression, e);
        }
    }

    public List<Node> rootNodeList(
            String domainExpression,
            String pathExpression,
            String domainValue,
            String rangeExpression,
            String rangeKeyPath
    ) {
        if (rangeExpression == null || rangeExpression.length() == 0) {
            throw exception("Range expression missing");
        }
        Map<String, List<Node>> rangeMap = getRangeMap(
                rootNode,
                domainExpression,
                pathExpression,
                rangeExpression,
                rangeKeyPath
        );

        return rangeMap.get(domainValue);
    }

    private Map<String, List<Node>> getRangeMap(
            Node context,
            String domainExpression,
            String pathExpression,
            String rangeExpression,
            String rangeKeyPath
    ) {
        String mapName = domainExpression + "|" + pathExpression + "|" + rangeExpression;

        Map<String, List<Node>> map = rangeMapCache.get(mapName);
        if (map == null) {
            map = new HashMap<String, List<Node>>();
            rangeMapCache.put(mapName, map);
            for (Node node : nodeList(context, rangeExpression)) {
                String key = valueAt(node, rangeKeyPath);
                List<Node> value = map.get(key);

                if (value == null) {
                    value = new ArrayList<Node>();
                    map.put(key, value);
                }
                value.add(node);

            }
//            Logger log = Logger.getLogger("getRangeMap");
//            log.info("Built Map! " + mapName);
//            for (Map.Entry<String, List<Node>> entry : map.entrySet()) {
//                for (Node node : entry.getValue()) {
//                    log.info("\n" + entry.getKey() + ":=" + $(node).content());
//                }
//            }
        }
        return map;
    }

    private static String getLanguageFromSource(Node node) {
        Node walkNode = node;
        while (walkNode != null) {
            NamedNodeMap attributes = walkNode.getAttributes();
            if (attributes != null) {
                Node lang = attributes.getNamedItemNS("http://www.w3.org/XML/1998/namespace", "lang");
                if (lang != null) {
                    return lang.getNodeValue();
                }
            }
            walkNode = walkNode.getParentNode();
        }
        return null;
    }

    private SourceType sourceType(String value, SourceType defaultType) {
        if (value == null) {
            return defaultType;
        } else {
            return SourceType.valueOf(value);
        }
    }

    private XPath xpath() {
        XPath path = pathFactory.newXPath();
        path.setNamespaceContext(namespaceContext);
        return path;
    }

}


text:
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.

using System;
using System.Collections.Generic;
using System.Linq;
using Cake.Core.Diagnostics;

namespace Cake.Common.Tools.MSBuild
{
    /// <summary>
    /// Contains functionality related to MSBuild settings.
    /// </summary>
    public static class MSBuildSettingsExtensions
    {
        /// <summary>
        /// Adds a MSBuild target to the configuration.
        /// </summary>
        /// <param name="settings">The settings.</param>
        /// <param name="target">The MSBuild target.</param>
        /// <returns>The same <see cref="MSBuildSettings"/> instance so that multiple calls can be chained.</returns>
        public static MSBuildSettings WithTarget(this MSBuildSettings settings, string target)
        {
            if (settings == null)
            {
                throw new ArgumentNullException(nameof(settings));
            }
            settings.Targets.Add(target);
            return settings;
        }

        /// <summary>
        /// Sets the tool version.
        /// </summary>
        /// <param name="settings">The settings.</param>
        /// <param name="version">The version.</param>
        /// <returns>The same <see cref="MSBuildSettings"/> instance so that multiple calls can be chained.</returns>
        public static MSBuildSettings UseToolVersion(this MSBuildSettings settings, MSBuildToolVersion version)
        {
            if (settings == null)
            {
                throw new ArgumentNullException(nameof(settings));
            }
            settings.ToolVersion = version;
            return settings;
        }

        /// <summary>
        /// Sets the platform target.
        /// </summary>
        /// <param name="settings">The settings.</param>
        /// <param name="target">The target.</param>
        /// <returns>The same <see cref="MSBuildSettings"/> instance so that multiple calls can be chained.</returns>
        public static MSBuildSettings SetPlatformTarget(this MSBuildSettings settings, PlatformTarget target)
        {
            if (settings == null)
            {
                throw new ArgumentNullException(nameof(settings));
            }
            settings.PlatformTarget = target;
            return settings;
        }

        /// <summary>
        /// Sets the MSBuild platform.
        /// </summary>
        /// <param name="settings">The settings.</param>
        /// <param name="platform">The platform.</param>
        /// <returns>The same <see cref="MSBuildSettings"/> instance so that multiple calls can be chained.</returns>
        public static MSBuildSettings SetMSBuildPlatform(this MSBuildSettings settings, MSBuildPlatform platform)
        {
            if (settings == null)
            {
                throw new ArgumentNullException(nameof(settings));
            }
            settings.MSBuildPlatform = platform;
            return settings;
        }

        /// <summary>
        /// Adds a property to the configuration.
        /// </summary>
        /// <param name="settings">The settings.</param>
        /// <param name="name">The property name.</param>
        /// <param name="values">The property values.</param>
        /// <returns>The same <see cref="MSBuildSettings"/> instance so that multiple calls can be chained.</returns>
        public static MSBuildSettings WithProperty(this MSBuildSettings settings, string name, params string[] values)
        {
            if (settings == null)
            {
                throw new ArgumentNullException(nameof(settings));
            }

            IList<string> currentValue;
            currentValue = new List<string>(
                settings.Properties.TryGetValue(name, out currentValue) && currentValue != null
                    ? currentValue.Concat(values)
                    : values);

            settings.Properties[name] = currentValue;

            return settings;
        }

        /// <summary>
        /// Sets the configuration.
        /// </summary>
        /// <param name="settings">The settings.</param>
        /// <param name="configuration">The configuration.</param>
        /// <returns>The same <see cref="MSBuildSettings"/> instance so that multiple calls can be chained.</returns>
        public static MSBuildSettings SetConfiguration(this MSBuildSettings settings, string configuration)
        {
            if (settings == null)
            {
                throw new ArgumentNullException(nameof(settings));
            }
            settings.Configuration = configuration;
            return settings;
        }

        /// <summary>
        /// Sets the maximum CPU count. Without this set MSBuild will compile projects in this solution one at a time.
        /// </summary>
        /// <param name="settings">The settings.</param>
        /// <param name="maxCpuCount">The maximum CPU count. Set this value to zero to use as many MSBuild processes as available CPUs.</param>
        /// <returns>The same <see cref="MSBuildSettings"/> instance so that multiple calls can be chained.</returns>
        public static MSBuildSettings SetMaxCpuCount(this MSBuildSettings settings, int? maxCpuCount)
        {
            if (settings == null)
            {
                throw new ArgumentNullException(nameof(settings));
            }
            if (maxCpuCount.HasValue)
            {
                settings.MaxCpuCount = Math.Max(0, maxCpuCount.Value);
            }
            else
            {
                settings.MaxCpuCount = null;
            }
            return settings;
        }

        /// <summary>
        /// Sets whether or not node reuse should be enabled.
        /// </summary>
        /// <param name="settings">The settings.</param>
        /// <param name="reuse"><c>true</c> if node reuse should be enabled; otherwise <c>false</c>.</param>
        /// <returns>The same <see cref="MSBuildSettings"/> instance so that multiple calls can be chained.</returns>
        public static MSBuildSettings SetNodeReuse(this MSBuildSettings settings, bool reuse)
        {
            if (settings == null)
            {
                throw new ArgumentNullException(nameof(settings));
            }
            settings.NodeReuse = reuse;
            return settings;
        }

        /// <summary>
        /// Sets whether or not detailed summary should be enabled.
        /// </summary>
        /// <param name="settings">The settings.</param>
        /// <param name="detailedSummary"><c>true</c> if detailed summary should be enabled; otherwise <c>false</c>.</param>
        /// <returns>The same <see cref="MSBuildSettings"/> instance so that multiple calls can be chained.</returns>
        public static MSBuildSettings SetDetailedSummary(this MSBuildSettings settings, bool detailedSummary)
        {
            if (settings == null)
            {
                throw new ArgumentNullException(nameof(settings));
            }
            settings.DetailedSummary = detailedSummary;
            return settings;
        }

        /// <summary>
        /// Sets whether or not no console logging should be enabled.
        /// </summary>
        /// <param name="settings">The settings.</param>
        /// <param name="noConsoleLog"><c>true</c> if no console log should be enabled; otherwise <c>false</c>.</param>
        /// <returns>The same <see cref="MSBuildSettings"/> instance so that multiple calls can be chained.</returns>
        public static MSBuildSettings SetNoConsoleLogger(this MSBuildSettings settings, bool noConsoleLog)
        {
            if (settings == null)
            {
                throw new ArgumentNullException(nameof(settings));
            }
            settings.NoConsoleLogger = noConsoleLog;
            return settings;
        }

        /// <summary>
        /// Sets the build log verbosity.
        /// </summary>
        /// <param name="settings">The settings.</param>
        /// <param name="verbosity">The build log verbosity.</param>
        /// <returns>The same <see cref="MSBuildSettings"/> instance so that multiple calls can be chained.</returns>
        public static MSBuildSettings SetVerbosity(this MSBuildSettings settings, Verbosity verbosity)
        {
            if (settings == null)
            {
                throw new ArgumentNullException(nameof(settings));
            }
            settings.Verbosity = verbosity;
            return settings;
        }

        /// <summary>
        /// Adds a custom logger.
        /// </summary>
        /// <param name="settings">The settings.</param>
        /// <param name="loggerAssembly">The assembly containing the logger. Should match the format {AssemblyName[,StrongName] | AssemblyFile}</param>
        /// <param name="loggerClass">The class implementing the logger. Should match the format [PartialOrFullNamespace.]LoggerClassName. If the assembly contains only one logger, class does not need to be specified.</param>
        /// <param name="loggerParameters">Parameters to be passed to the logger.</param>
        /// <returns>The same <see cref="MSBuildSettings"/> instance so that multiple calls can be chained.</returns>
        public static MSBuildSettings WithLogger(this MSBuildSettings settings, string loggerAssembly, string loggerClass = null, string loggerParameters = null)
        {
            if (settings == null)
            {
                throw new ArgumentNullException(nameof(settings));
            }
            if (string.IsNullOrWhiteSpace(loggerAssembly))
            {
                throw new ArgumentException(nameof(loggerAssembly));
            }
            settings.Loggers.Add(new MSBuildLogger
            {
                Assembly = loggerAssembly,
                Class = loggerClass,
                Parameters = loggerParameters
            });
            return settings;
        }

        /// <summary>
        /// Adds a file logger.
        /// Each file logger will be declared in the order added.
        /// The first file logger will match up to the /fl parameter.
        /// The next nine (max) file loggers will match up to the /fl1 through /fl9 respectively.
        /// </summary>
        /// <param name="settings">The settings.</param>
        /// <param name="fileLoggerParameters">Parameters to be passed to the logger.</param>
        /// <returns>The same <see cref="MSBuildSettings"/> instance so that multiple calls can be chained.</returns>
        public static MSBuildSettings AddFileLogger(this MSBuildSettings settings, MSBuildFileLogger fileLoggerParameters)
        {
            if (settings == null)
            {
                throw new ArgumentNullException(nameof(settings));
            }
            if (fileLoggerParameters == null)
            {
                throw new ArgumentNullException(nameof(fileLoggerParameters));
            }
            settings.FileLoggers.Add(fileLoggerParameters);

            return settings;
        }

        /// <summary>
        /// Adds a file logger with all the default settings.
        /// Each file logger will be declared in the order added.
        /// The first file logger will match up to the /fl parameter.
        /// The next nine (max) file loggers will match up to the /fl1 through /fl9 respectively.
        /// </summary>
        /// <param name="settings">The settings.</param>
        /// <returns>The same <see cref="MSBuildSettings"/> instance so that multiple calls can be chained.</returns>
        public static MSBuildSettings AddFileLogger(this MSBuildSettings settings)
        {
            if (settings == null)
            {
                throw new ArgumentNullException(nameof(settings));
            }

            settings.FileLoggers.Add(new MSBuildFileLogger());
            return settings;
        }
    }
}


text:
package xmetricstest

import (
	"testing"

	"github.com/stretchr/testify/assert"
	"github.com/stretchr/testify/mock"
	"github.com/stretchr/testify/require"
	"github.com/xmidt-org/webpa-common/xmetrics"
)

func testNewProviderDefault(t *testing.T) {
	assert := assert.New(t)
	assert.NotNil(NewProvider(nil))
}

func testNewProviderGoodConfiguration(t *testing.T) {
	assert := assert.New(t)
	assert.NotNil(NewProvider(
		&xmetrics.Options{
			Metrics: []xmetrics.Metric{
				{Name: "Injected", Type: "counter"},
			},
		},
		func() []xmetrics.Metric {
			return []xmetrics.Metric{
				{Name: "FromModule", Type: "gauge"},
			}
		},
	))
}

func testNewProviderBadConfiguration(t *testing.T) {
	assert := assert.New(t)
	assert.Panics(func() {
		NewProvider(nil, func() []xmetrics.Metric {
			return []xmetrics.Metric{
				{Name: "duplicate", Type: "counter"},
				{Name: "duplicate", Type: "counter"},
			}
		})
	})
}

func testNewProviderUnsupportedType(t *testing.T) {
	assert := assert.New(t)
	assert.Panics(func() {
		NewProvider(nil, func() []xmetrics.Metric {
			return []xmetrics.Metric{
				{Name: "unsupported", Type: "asdfasdfasdfasdf"},
			}
		})
	})
}

func TestNewProvider(t *testing.T) {
	t.Run("Default", testNewProviderDefault)
	t.Run("GoodConfiguration", testNewProviderGoodConfiguration)
	t.Run("BadConfiguration", testNewProviderBadConfiguration)
	t.Run("UnsupportedType", testNewProviderUnsupportedType)
}

func testProviderNewCounter(t *testing.T) {
	var (
		assert  = assert.New(t)
		require = require.New(t)

		p = NewProvider(nil, func() []xmetrics.Metric {
			return []xmetrics.Metric{
				{Name: "preregistered", Type: "counter"},
				{Name: "gauge", Type: "gauge"},
			}
		})
	)

	require.NotNil(p)

	{
		preregistered := p.NewCounter("preregistered")
		require.NotNil(preregistered)
		assert.Implements((*xmetrics.Valuer)(nil), preregistered)
		assert.Implements((*Labeled)(nil), preregistered)
		assert.True(preregistered == p.NewCounter("preregistered"))
	}

	{
		adhoc := p.NewCounter("adhoc")
		require.NotNil(adhoc)
		assert.Implements((*xmetrics.Valuer)(nil), adhoc)
		assert.Implements((*Labeled)(nil), adhoc)
		assert.True(adhoc != p.NewCounter("preregistered"))
		assert.True(adhoc == p.NewCounter("adhoc"))
	}

	assert.Panics(func() {
		p.NewCounter("gauge")
	})
}

func testProviderNewGauge(t *testing.T) {
	var (
		assert  = assert.New(t)
		require = require.New(t)

		p = NewProvider(nil, func() []xmetrics.Metric {
			return []xmetrics.Metric{
				{Name: "preregistered", Type: "gauge"},
				{Name: "counter", Type: "counter"},
			}
		})
	)

	require.NotNil(p)

	{
		preregistered := p.NewGauge("preregistered")
		require.NotNil(preregistered)
		assert.Implements((*xmetrics.Valuer)(nil), preregistered)
		assert.Implements((*Labeled)(nil), preregistered)
		assert.True(preregistered == p.NewGauge("preregistered"))
	}

	{
		adhoc := p.NewGauge("adhoc")
		require.NotNil(adhoc)
		assert.Implements((*xmetrics.Valuer)(nil), adhoc)
		assert.Implements((*Labeled)(nil), adhoc)
		assert.True(adhoc != p.NewGauge("preregistered"))
		assert.True(adhoc == p.NewGauge("adhoc"))
	}

	assert.Panics(func() {
		p.NewGauge("counter")
	})
}

func testProviderNewHistogram(t *testing.T) {
	var (
		assert  = assert.New(t)
		require = require.New(t)

		p = NewProvider(nil, func() []xmetrics.Metric {
			return []xmetrics.Metric{
				{Name: "preregistered", Type: "histogram"},
				{Name: "counter", Type: "counter"},
			}
		})
	)

	require.NotNil(p)

	{
		preregistered := p.NewHistogram("preregistered", 2)
		require.NotNil(preregistered)
		assert.Implements((*Labeled)(nil), preregistered)
		assert.True(preregistered == p.NewHistogram("preregistered", 4))
	}

	{
		adhoc := p.NewHistogram("adhoc", 5)
		require.NotNil(adhoc)
		assert.Implements((*Labeled)(nil), adhoc)
		assert.True(adhoc != p.NewHistogram("preregistered", 2))
		assert.True(adhoc == p.NewHistogram("adhoc", 6))
	}

	assert.Panics(func() {
		p.NewHistogram("counter", 3)
	})
}

func testProviderStop(t *testing.T) {
	var (
		assert = assert.New(t)
		p      = NewProvider(nil)
	)

	assert.NotPanics(p.Stop)
}

func testProviderExpect(t *testing.T) {
	t.Run("BadLabelsAndValues", func(t *testing.T) {
		var (
			assert = assert.New(t)
			p      = NewProvider(nil)
		)

		assert.Panics(func() {
			p.Expect("test", "one")
		})
	})
}

func testProviderAssert(t *testing.T) {
	t.Run("BadLabelsAndValues", func(t *testing.T) {
		var (
			assert   = assert.New(t)
			testingT = new(mockTestingT)

			p = NewProvider(nil)
		)

		assert.Panics(func() {
			p.Assert(testingT, "counter", "one")
		})

		testingT.AssertExpectations(t)
	})

	t.Run("Success", func(t *testing.T) {
		var (
			assert  = assert.New(t)
			require = require.New(t)

			firstCalled = false
			first       = func(testingT, string, interface{}) bool {
				firstCalled = true
				return true
			}

			lastCalled = false
			last       = func(testingT, string, interface{}) bool {
				lastCalled = true
				return true
			}

			testingT = new(mockTestingT)

			p = NewProvider(nil, func() []xmetrics.Metric {
				return []xmetrics.Metric{
					{Name: "preregistered_counter", Type: "counter"},
					{Name: "preregistered_gauge", Type: "gauge"},
					{Name: "preregistered_histogram", Type: "histogram"},
				}
			})
		)

		require.NotPanics(func() {
			p.NewCounter("preregistered_counter").Add(1.0)
			p.NewCounter("preregistered_counter").With("code", "500", "method", "POST").Add(2.0)
			p.NewGauge("preregistered_gauge").Set(15.0)
			p.NewCounter("adhoc_counter").Add(2.0)
		})

		assert.True(p.Assert(testingT, "preregistered_counter")(first, Counter, Value(1.0), last))
		assert.True(firstCalled)
		assert.True(lastCalled)
		firstCalled = false
		lastCalled = false

		assert.True(p.Assert(testingT, "preregistered_counter", "method", "POST", "code", "500")(first, Counter, Value(2.0), last))
		assert.True(firstCalled)
		assert.True(lastCalled)
		firstCalled = false
		lastCalled = false

		assert.True(p.Assert(testingT, "preregistered_gauge")(first, Gauge, last))
		assert.True(firstCalled)
		assert.True(lastCalled)
		firstCalled = false
		lastCalled = false

		assert.True(p.Assert(testingT, "preregistered_gauge")(first, Value(15.0), last))
		assert.True(firstCalled)
		assert.True(lastCalled)
		firstCalled = false
		lastCalled = false

		assert.True(p.Assert(testingT, "preregistered_histogram")(first, Histogram, last))
		assert.True(firstCalled)
		assert.True(lastCalled)
		firstCalled = false
		lastCalled = false

		assert.True(p.Assert(testingT, "adhoc_counter")(first, Counter, Value(2.0), last))
		assert.True(firstCalled)
		assert.True(lastCalled)
		firstCalled = false
		lastCalled = false

		testingT.AssertExpectations(t)
	})

	t.Run("Fail", func(t *testing.T) {
		var (
			assert = assert.New(t)

			firstCalled = false
			first       = func(testingT, string, interface{}) bool {
				firstCalled = true
				return true
			}

			lastCalled = false
			last       = func(testingT, string, interface{}) bool {
				lastCalled = true
				return true
			}

			nosuch = func(testingT, string, interface{}) bool {
				assert.Fail("nosuch should not have been called")
				return false
			}

			testingT = new(mockTestingT)

			p = NewProvider(nil, func() []xmetrics.Metric {
				return []xmetrics.Metric{
					{Name: "preregistered_counter", Type: "counter"},
				}
			})
		)

		testingT.On("Errorf", mock.MatchedBy(AnyMessage), mock.MatchedBy(AnyArguments)).Times(3)

		p.Assert(testingT, "nosuch")(nosuch)
		testingT.AssertNumberOfCalls(t, "Errorf", 1)

		assert.False(p.Assert(testingT, "preregistered_counter")(first, Gauge, Value(568.2), last))
		assert.True(firstCalled)
		assert.True(lastCalled)
		firstCalled = false
		lastCalled = false

		testingT.AssertExpectations(t)
	})
}

func testProviderAssertExpectations(t *testing.T) {
	t.Run("Success", func(t *testing.T) {
		var (
			assert  = assert.New(t)
			require = require.New(t)

			firstCalled = false
			first       = func(testingT, string, interface{}) bool {
				firstCalled = true
				return true
			}

			lastCalled = false
			last       = func(testingT, string, interface{}) bool {
				lastCalled = true
				return true
			}

			testingT = new(mockTestingT)

			p = NewProvider(nil, func() []xmetrics.Metric {
				return []xmetrics.Metric{
					{Name: "preregistered_counter", Type: "counter"},
					{Name: "preregistered_gauge", Type: "gauge"},
					{Name: "preregistered_histogram", Type: "histogram"},
				}
			})
		)

		// no expect calls yet
		assert.True(p.AssertExpectations(t))

		p.Expect("preregistered_counter")(first).
			Expect("preregistered_counter")(Counter, Value(1.0)).
			Expect("preregistered_counter", "method", "POST", "code", "500")(Counter, Value(2.0)).
			Expect("preregistered_gauge")(Gauge).
			Expect("preregistered_gauge")(Value(15.0)).
			Expect("preregistered_histogram")(Histogram).
			Expect("adhoc_counter")(Counter, Value(2.0)).
			Expect("adhoc_counter")(last)

		require.NotPanics(func() {
			p.NewCounter("preregistered_counter").Add(1.0)
			p.NewCounter("preregistered_counter").With("code", "500", "method", "POST").Add(2.0)
			p.NewGauge("preregistered_gauge").Set(15.0)
			p.NewCounter("adhoc_counter").Add(2.0)
		})

		assert.True(p.AssertExpectations(testingT))
		assert.True(firstCalled)
		assert.True(lastCalled)
		testingT.AssertExpectations(t)
	})

	t.Run("Fail", func(t *testing.T) {
		var (
			assert = assert.New(t)

			firstCalled = false
			first       = func(testingT, string, interface{}) bool {
				firstCalled = true
				return true
			}

			lastCalled = false
			last       = func(testingT, string, interface{}) bool {
				lastCalled = true
				return true
			}

			nosuch = func(testingT, string, interface{}) bool {
				assert.Fail("nosuch should not have been called")
				return true
			}

			testingT = new(mockTestingT)

			p = NewProvider(nil, func() []xmetrics.Metric {
				return []xmetrics.Metric{
					{Name: "preregistered_counter", Type: "counter"},
				}
			})
		)

		p.Expect("preregistered_counter")(first).
			Expect("nosuch")(nosuch).
			Expect("preregistered_counter")(Gauge, Value(568.2)).
			Expect("preregistered_counter")(last)

		testingT.On("Errorf", mock.MatchedBy(AnyMessage), mock.MatchedBy(AnyArguments)).Times(3)
		assert.False(p.AssertExpectations(testingT))
		assert.True(firstCalled)
		assert.True(lastCalled)
		testingT.AssertExpectations(t)
	})
}

func TestProvider(t *testing.T) {
	t.Run("NewCounter", testProviderNewCounter)
	t.Run("NewGauge", testProviderNewGauge)
	t.Run("NewHistogram", testProviderNewHistogram)
	t.Run("Stop", testProviderStop)
	t.Run("Expect", testProviderExpect)
	t.Run("Assert", testProviderAssert)
	t.Run("AssertExpectations", testProviderAssertExpectations)
}


text:
package de.madcyph3r.example.example.headItemTypes;

import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.os.Bundle;
import android.support.v4.app.Fragment;

import com.amulyakhare.textdrawable.TextDrawable;

import de.madcyph3r.example.R;
import de.madcyph3r.example.example.FragmentDummy;
import de.madcyph3r.example.example.FragmentInstruction;
import de.madcyph3r.materialnavigationdrawer.MaterialNavigationDrawer;
import de.madcyph3r.materialnavigationdrawer.activity.MaterialNavHeadItemActivity;
import de.madcyph3r.materialnavigationdrawer.menu.head.MaterialHeadItem;
import de.madcyph3r.materialnavigationdrawer.menu.MaterialMenu;
import de.madcyph3r.materialnavigationdrawer.menu.item.section.MaterialItemSectionFragment;
import de.madcyph3r.materialnavigationdrawer.tools.RoundedCornersDrawable;

public class HeadItemThreeDontCloseOnChangeActivity extends MaterialNavHeadItemActivity {

    MaterialNavigationDrawer drawer = null;

    @Override
    protected boolean finishActivityOnNewIntent() {
        return false;
    }

    @Override
    protected int getNewIntentRequestCode(Class clazz) {
        return 0;
    }

    @Override
    public void init(Bundle savedInstanceState) {

        drawer = this;

        // add head Item (menu will be loaded automatically)
        this.addHeadItem(getHeadItem2());
        this.addHeadItem(getHeadItem3());
        this.addHeadItem(getHeadItem1());

        // load menu
        this.loadMenu(getCurrentHeadItem().getMenu());

        // load the MaterialItemSectionFragment, from the given startIndex
        this.loadStartFragmentFromMenu(getCurrentHeadItem().getMenu());
    }

    private MaterialHeadItem getHeadItem1() {

        // information text for the fragment
        Bundle bundle = new Bundle();
        bundle.putString("instruction", "This example shows the head item style with three items. \" +\n" +
                "                \"If a new head item is chosen, the drawer will not close. \" +\n" +
                "                \"See the method headerType in the source code.");

        Fragment fragmentInstruction = new FragmentInstruction();
        fragmentInstruction.setArguments(bundle);

        // create menu
        MaterialMenu menu = new MaterialMenu();
        menu.add(new MaterialItemSectionFragment(this, "Instruction", fragmentInstruction, "Don't Close Drawer On HeadItem Change (Three Items)"));
        menu.add(new MaterialItemSectionFragment(this, "Section 1", new FragmentDummy(), "Section 1"));
        menu.add(new MaterialItemSectionFragment(this, "Section 2", new FragmentDummy(), "Section 2"));
        menu.add(new MaterialItemSectionFragment(this, "Section 3", new FragmentDummy(), "Section 3"));

        // create Head Item
        // use bitmap and make a circle photo
        final Bitmap bitmap = BitmapFactory.decodeResource(getResources(), R.drawable.head_item_icon);
        final RoundedCornersDrawable drawableAppIcon = new RoundedCornersDrawable(getResources(), bitmap);
        MaterialHeadItem headItem = new MaterialHeadItem(this, "A HeadItem", "A Subtitle", drawableAppIcon, R.drawable.mat1, menu);
        headItem.setCloseDrawerOnChanged(false); // don't close the drawer, if this head item chosen

        return headItem;
    }

    private MaterialHeadItem getHeadItem2() {

        // create menu
        MaterialMenu menu = new MaterialMenu();
        menu.add(new MaterialItemSectionFragment(this, "Section 1 (Head 2)", new FragmentDummy(), "Section 1 (Head 2)"));
        menu.add(new MaterialItemSectionFragment(this, "Section 2", new FragmentDummy(), "Section 2"));

        // create Head Item
        TextDrawable.Builder headPhoto = new TextDrawable.Builder();
        headPhoto.setColor(Color.GREEN);
        headPhoto.setText("B");
        headPhoto.setShape(TextDrawable.DRAWABLE_SHAPE_ROUND_RECT);
        headPhoto.setBorderThickness(3);
        TextDrawable icon = headPhoto.build();

        MaterialHeadItem headItem = new MaterialHeadItem(this, "B HeadItem", "B Subtitle", icon, R.drawable.mat6, menu);
        headItem.setCloseDrawerOnChanged(false); // don't close the drawer, if this head item chosen

        return headItem;
    }

    private MaterialHeadItem getHeadItem3() {

        // create menu
        MaterialMenu menu = new MaterialMenu();
        menu.add(new MaterialItemSectionFragment(this, "Section 1 (Head 3)", new FragmentDummy(), "Section 1 (Head 3)"));
        menu.add(new MaterialItemSectionFragment(this, "Section 2", new FragmentDummy(), "Section 2"));

        // create Head Item
        TextDrawable.Builder headPhoto = new TextDrawable.Builder();
        headPhoto.setColor(Color.GREEN);
        headPhoto.setText("G");
        headPhoto.setShape(TextDrawable.DRAWABLE_SHAPE_ROUND_RECT);
        headPhoto.setBorderThickness(3);
        TextDrawable icon = headPhoto.build();

        MaterialHeadItem headItem = new MaterialHeadItem(this, "C HeadItem", "C Subtitle", icon, R.drawable.mat6, menu);
        headItem.setCloseDrawerOnChanged(false); // don't close the drawer, if this head item chosen

        return headItem;
    }

    @Override
    public void afterInit(Bundle savedInstanceState) {

    }
}


text:
{% load cog_utils %}

{% with proj|get_external_urls:external_url_type as external_urls %}

		{% if group_title %}

{{group_title}}

		{% else %}

				Title
				URL
				Description

		{% endif %}
		{% for exturl in external_urls %}

				{{exturl.title}}

				{{ exturl.url|urlizetrunc:40 }}
				{{exturl.description|urlizetrunc:40|linebreaksbr}}

		{% endfor %}

{% endwith %}


text:
import React, {Component} from 'react'

export default class App extends Component {
  render() {
    throw new Error('Error test!')
    return
BORELA!

  }
}


text:
<!DOCTYPE html>

    <title>CSS Reftest Reference</title>
    <link rel="author" title="Dirk Schulze" href="mailto:dschulze@adobe.com">

The test passes if the top half of the site is white and the bottom half of the site is green.


text:
<?php

declare(strict_types=1);

namespace Valkyrja\SMS\Adapters;

use Exception;
use Nexmo\Client as Nexmo;
use Valkyrja\SMS\Message;
use Valkyrja\SMS\NexmoAdapter as Contract;

/**
 * Class NexmoAdapter.
 *
 * @author Melech Mizrachi
 */
class NexmoAdapter implements Contract
{
    /**
     * The Nexmo client.
     *
     * @var Nexmo
     */
    protected Nexmo $nexmo;

    /**
     * NexmoMessage constructor.
     *
     * @param Nexmo $nexmo The Nexmo client
     */
    public function __construct(Nexmo $nexmo)
    {
        $this->nexmo = $nexmo;
    }

    /**
     * @inheritDoc
     *
     * @throws Exception
     */
    public function send(Message $message): void
    {
        $this->nexmo->message()->send(
            [
                'to'   => $message->getTo(),
                'from' => $message->getFrom(),
                'text' => $message->getText(),
                'type' => $message->isUnicode() ? 'unicode' : null,
            ]
        );
    }
}