text:
//==============================================================================

//==============================================================================

//------------------------------------------------------------------------------
#ifndef CTriangleArrayH
#define CTriangleArrayH
//------------------------------------------------------------------------------
#include "graphics/CGenericArray.h"
//------------------------------------------------------------------------------

//------------------------------------------------------------------------------
namespace chai3d {
//------------------------------------------------------------------------------

//==============================================================================
/*!
    \file   CTriangleArray.h

    \brief
    Implements arrays of 3D triangles.
*/
//==============================================================================

//------------------------------------------------------------------------------
class cTriangleArray;
typedef std::shared_ptr<cTriangleArray> cTriangleArrayPtr;
//------------------------------------------------------------------------------

//==============================================================================
/*!
    \class      cTriangleArray
    \ingroup    graphics

    \brief
    This class implements an array of 3D triangles.

    \details
    cTriangleArray defines an array of triangles, typically bound to a mesh for
    describing its geometry.\n

    A triangle array is created by first passing a reference to an array of vertices
    (\ref cVertexArray) from which the triangles are composed. \n

    Every triangle is described by a set of three vertex indices. The indices point
    to the vertices, or points, that describe the shape of the triangle. \n

    For graphic rendering purposes and memory efficiency, triangles are stored
    in large arrays. The number of allocated triangles in an array can be
    retrieved by call \ref getNumElements().\n

    New triangles can be added or removed by calling \ref newTriangle() and
    \ref removeTriangle(). respectively.\n

    When a triangle is removed from the array, the vertex indices are set to zero
    and the triangle index number is added to a list of free triangles for future
    allocation. Triangles are therefore never removed from memory, but become a
    point until they are converted to an active triangle again.\n

    To avoid accumulating large numbers of free triangles, it is possible to
    compress the array by calling \ref compress(). This method removes all
    non used triangles from memory.\n
*/
//==============================================================================
class cTriangleArray : public cGenericArray
{
    //--------------------------------------------------------------------------
    // CONSTRUCTOR & DESTRUCTOR:
    //--------------------------------------------------------------------------

public:

    //--------------------------------------------------------------------------
    /*!
        Constructor of cTriangleArray.

        \param  a_vertexArray  Array of vertices used to describe the triangles.
    */
    //--------------------------------------------------------------------------
    cTriangleArray(cVertexArrayPtr a_vertexArray) : cGenericArray(a_vertexArray)
    {
        // clear all triangles
        clear();

        // store pointer to vertex array
        m_vertices = a_vertexArray;

        // initialize OpenGL buffer ID
        m_elementBuffer         = 0;
    }

    //--------------------------------------------------------------------------
    /*!
        Destructor of cTriangleArray.
    */
    //--------------------------------------------------------------------------
    ~cTriangleArray(){}

    //! Clear all triangles from array.
    void clear()
    {
        m_allocated.clear();
        m_indices.clear();
        m_freeElements.clear();
        m_flagMarkForUpdate     = true;
        m_flagMarkForResize     = true;
    }

    //! Shared cTriangleArray allocator.
    static cTriangleArrayPtr create(cVertexArrayPtr a_vertexArray) { return (std::make_shared<cTriangleArray>(a_vertexArray)); }

    //--------------------------------------------------------------------------
    // PUBLIC METHODS:
    //--------------------------------------------------------------------------

public:

    //! This method returns the number of vertices that compose a triangle.
    virtual unsigned int getNumVerticesPerElement() { return (3); }

    //! This method copies all triangle data and returns a new triangle array.
    cTriangleArrayPtr copy();

    //! This method removes all non allocated triangles.
    void compress();

    //--------------------------------------------------------------------------
    /*!
        This method creates a new triangle.

        \param  a_vertexIndex0  index of vertex 0.
        \param  a_vertexIndex1  index of vertex 1.
        \param  a_vertexIndex2  index of vertex 2.

        \return Index number of new triangle.
    */
    //--------------------------------------------------------------------------
    int newTriangle(const unsigned int a_vertexIndex0,
                    const unsigned int a_vertexIndex1,
                    const unsigned int a_vertexIndex2)
    {
        int index;

        // check if there is an available slot on the free triangle list
        if (m_freeElements.size() > 0)
        {
            index = m_freeElements.front();
            m_allocated[index] = true;
            m_freeElements.pop_front();
            setVertices(index, a_vertexIndex0, a_vertexIndex1, a_vertexIndex2);
        }
        else
        {
            // store new indices
            m_indices.push_back(a_vertexIndex0);
            m_indices.push_back(a_vertexIndex1);
            m_indices.push_back(a_vertexIndex2);
            m_allocated.push_back(true);

            m_flagMarkForResize = true;

            // store index of new triangle
            index = (int)(m_allocated.size())-1;
        }

        // mark for update
        m_flagMarkForUpdate = true;

        // return index to new triangle
        return (index);
    }

    //--------------------------------------------------------------------------
    /*!
        This method deallocates a selected triangle from the array. The three
        vertices of the triangle are set to zero, and the triangle is added to
        the free list for future allocation.\n

        \param  a_triangleIndex  Index of selected triangle.
    */
    //--------------------------------------------------------------------------
    void removeTriangle(const unsigned int a_triangleIndex)
    {
        // sanity check
        if (m_allocated[a_triangleIndex])
        {
            // disable triangle
            m_allocated[a_triangleIndex] = false;

            // reset indices to vertices
            setVertices(a_triangleIndex, 0, 0, 0);

            // add triangle to free list
            m_freeElements.push_back(a_triangleIndex);

            // mark for update
            m_flagMarkForUpdate = true;
        }
    }

    //--------------------------------------------------------------------------
    /*!
        This method set the vertices of a selected triangle by passing their
        index numbers.

        \param  a_triangleIndex  Index of selected triangle.
        \param  a_vertexIndex0   Index of vertex 0.
        \param  a_vertexIndex1   Index of vertex 1.
        \param  a_vertexIndex2   Index of vertex 2.
    */
    //--------------------------------------------------------------------------
    inline void setVertices(const unsigned int a_triangleIndex,
                            const unsigned int a_vertexIndex0,
                            const unsigned int a_vertexIndex1,
                            const unsigned int a_vertexIndex2)
    {
        m_indices[3*a_triangleIndex+0] = a_vertexIndex0;
        m_indices[3*a_triangleIndex+1] = a_vertexIndex1;
        m_indices[3*a_triangleIndex+2] = a_vertexIndex2;

        // mark for update
        m_flagMarkForUpdate = true;
    }

    //--------------------------------------------------------------------------
    /*!
        This method sets vertex 0 of a selected triangle by passing their
        index numbers.

        \param  a_triangleIndex  Index of triangle.
        \param  a_vertexIndex0   Index of vertex 0.
    */
    //--------------------------------------------------------------------------
    inline void setVertexIndex0(const unsigned int a_triangleIndex, const unsigned int a_vertexIndex0)
    {
        m_indices[3 * a_triangleIndex + 0] = a_vertexIndex0;

        // mark for update
        m_flagMarkForUpdate = true;
    };

    //--------------------------------------------------------------------------
    /*!
        This method returns the index of vertex 0 of a selected triangle.

        \param  a_triangleIndex  Index of triangle.

        \return Index to vertex 0.
    */
    //--------------------------------------------------------------------------
    inline unsigned int getVertexIndex0(const unsigned int a_triangleIndex) const
    {
        return (m_indices[3*a_triangleIndex+0]);
    };

    //--------------------------------------------------------------------------
    /*!
        This method sets vertex 1 of a selected triangle by passing their
        index numbers.

        \param  a_triangleIndex  Index of triangle.
        \param  a_vertexIndex1   Index of vertex 1.
    */
    //--------------------------------------------------------------------------
    inline void setVertexIndex1(const unsigned int a_triangleIndex, const unsigned int a_vertexIndex1)
    {
        m_indices[3 * a_triangleIndex + 1] = a_vertexIndex1;

        // mark for update
        m_flagMarkForUpdate = true;
    };

    //--------------------------------------------------------------------------
    /*!
        This method returns the index of vertex 1 of a selected triangle.

        \param  a_triangleIndex  Index of selected triangle.

        \return Index to vertex 1.
    */
    //--------------------------------------------------------------------------
    inline unsigned int getVertexIndex1(const unsigned int a_triangleIndex) const
    {
        return (m_indices[3*a_triangleIndex+1]);
    };

    //--------------------------------------------------------------------------
    /*!
        This method sets vertex 2 of a selected triangle by passing their
        index numbers.

        \param  a_triangleIndex  Index of triangle.
        \param  a_vertexIndex2   Index of vertex 2.
    */
    //--------------------------------------------------------------------------
    inline void setVertexIndex2(const unsigned int a_triangleIndex, const unsigned int a_vertexIndex2)
    {
        m_indices[3 * a_triangleIndex + 2] = a_vertexIndex2;

        // mark for update
        m_flagMarkForUpdate = true;
    };

    //--------------------------------------------------------------------------
    /*!
        This method returns the index of vertex 2 of a selected triangle.

        \param  a_triangleIndex  Index of triangle.

        \return Index to vertex 2.
    */
    //--------------------------------------------------------------------------
    inline unsigned int getVertexIndex2(const unsigned int a_triangleIndex) const
    {
        return (m_indices[3*a_triangleIndex+2]);
    };

    //--------------------------------------------------------------------------
    /*!
         This method returns the index number of a selected vertex for a
         selected triangle. In the case of a triangle a_vertexNumber takes
         either 0, 1 or 2.

        \param  a_elementIndex  Index number of selected triangle.
        \param  a_vertexNumber  Vertex number.

        \return Index number of the requested vertex.
    */
    //--------------------------------------------------------------------------
    virtual unsigned int getVertexIndex(const unsigned int a_elementIndex,
                                        const unsigned int a_vertexNumber) const
    {
        switch (a_vertexNumber)
        {
            case 0: return (m_indices[3*a_elementIndex+0]);
            case 1: return (m_indices[3*a_elementIndex+1]);
            case 2: return (m_indices[3*a_elementIndex+2]);
            default: return (0);
        }
    }

    //--------------------------------------------------------------------------
    /*!
        This method returns the texture coordinate at the nearest point on the
        triangle from an input location.

        \param  a_triangleIndex  Index number of selected triangle.
        \param  a_localPos       Local point on triangle.

        \return Interpolated texture coordinate at desired location.
    */
    //--------------------------------------------------------------------------
    cVector3d getTexCoordAtPosition(const unsigned int a_triangleIndex,
                                    const cVector3d& a_localPos)
    {
        // get vertices of contact triangles
        cVector3d vertex0 = m_vertices->getLocalPos(getVertexIndex0(a_triangleIndex));
        cVector3d vertex1 = m_vertices->getLocalPos(getVertexIndex1(a_triangleIndex));
        cVector3d vertex2 = m_vertices->getLocalPos(getVertexIndex2(a_triangleIndex));

        // project desired point on triangle
        cVector3d vertex = cProjectPointOnTriangle(a_localPos, vertex0, vertex1, vertex2);

        // compute area of triangle
        double area  = cTriangleArea(vertex0, vertex1, vertex2);

        // compute areas of three sub-triangles formed by the three vertices of the triangle and the contact point.
        double area0 = cTriangleArea(vertex, vertex1, vertex2);
        double area1 = cTriangleArea(vertex, vertex0, vertex2);
        double area2 = cTriangleArea(vertex, vertex0, vertex1);

        // compute weights based on position of contact point
        double c0, c1, c2;
        if (area > 0.0)
        {
            c0 = area0/area;
            c1 = area1/area;
            c2 = area2/area;
        }
        else
        {
            c0 = c1 = c2 = (1.0/3.0);
        }

        cVector3d texCoord;

        if (m_vertices->getUseTexCoordData())
        {
            // retrieve the texture coordinate for each triangle vertex
            cVector3d texCoord0 = m_vertices->getTexCoord(getVertexIndex0(a_triangleIndex));
            cVector3d texCoord1 = m_vertices->getTexCoord(getVertexIndex1(a_triangleIndex));
            cVector3d texCoord2 = m_vertices->getTexCoord(getVertexIndex2(a_triangleIndex));

            // compute the exact texture coordinate at the contact point
            texCoord = cAdd( cMul(c0, texCoord0), cMul(c1, texCoord1), cMul(c2, texCoord2));
        }
        else
        {
            texCoord.set(0.0, 0.0, 0.0);
        }

        // return result
        return (texCoord);
    }

    //--------------------------------------------------------------------------
    /*!
        This method flips the vertices of the triangle.

        \param  a_triangleIndex  Index number of selected triangle.
    */
    //--------------------------------------------------------------------------
    void flip(const unsigned int a_triangleIndex)
    {
        // sanity check
        if (m_allocated[a_triangleIndex])
        {
            // get vertices 1 and 2
            unsigned int v1 = getVertexIndex1(a_triangleIndex);
            unsigned int v2 = getVertexIndex2(a_triangleIndex);

            // flip vertices 1 and 2
            setVertexIndex1(a_triangleIndex, v2);
            setVertexIndex2(a_triangleIndex, v1);
        }
    }

    //--------------------------------------------------------------------------
    /*!
         This method computes the normal matrix vectors for all triangles.
    */
    //--------------------------------------------------------------------------
    inline void computeBTN()
    {
        unsigned int numTriangles = getNumElements();
        for (unsigned i=0; i<numTriangles; i++)
        {
            cVector3d T,B;

            unsigned int index0 = getVertexIndex0(i);
            unsigned int index1 = getVertexIndex1(i);
            unsigned int index2 = getVertexIndex2(i);

            // calculate the vectors from the current vertex to the two other vertices in the triangle
            cVector3d v1v0 = m_vertices->getLocalPos(index1) - m_vertices->getLocalPos(index0);
            cVector3d v2v0 = m_vertices->getLocalPos(index2) - m_vertices->getLocalPos(index0);

            cVector3d tex0 = m_vertices->getTexCoord(index0);
            cVector3d tex1 = m_vertices->getTexCoord(index1);
            cVector3d tex2 = m_vertices->getTexCoord(index2);

            // calculate c1c0_T and c1c0_B
            double c1c0_T = tex1.x() - tex0.x();
            double c1c0_B = tex1.y() - tex0.y();

            // calculate c2c0_T and c2c0_B
            double c2c0_T = tex2.x() - tex0.x();
            double c2c0_B = tex2.y() - tex0.y();

            double fDenominator = c1c0_T * c2c0_B - c2c0_T * c1c0_B;
            if (fabs(fDenominator) < C_TINY)
            {
                // we won't risk a divide by zero, so set the tangent matrix to the identity matrix
                T = cVector3d(1.0, 0.0, 0.0);
                B = cVector3d(0.0, 1.0, 0.0);
            }
            else
            {
                // calculate the reciprocal value once and for all (to achieve speed)
                double fScale1 = 1.0f / fDenominator;

                // T and B are calculated just as the equation in the article states
                T = cVector3d((c2c0_B * v1v0.x() - c1c0_B * v2v0.x()) * fScale1,
                              (c2c0_B * v1v0.y() - c1c0_B * v2v0.y()) * fScale1,
                              (c2c0_B * v1v0.z() - c1c0_B * v2v0.z()) * fScale1);

                B = cVector3d((-c2c0_T * v1v0.x() + c1c0_T * v2v0.x()) * fScale1,
                              (-c2c0_T * v1v0.y() + c1c0_T * v2v0.y()) * fScale1,
                              (-c2c0_T * v1v0.z() + c1c0_T * v2v0.z()) * fScale1);

                // Calculate the reciprocal value once and for all (to achieve speed)
                /*
                double fScale2 = 1.0f / ((T.x() * B.y() * N.z() - T.z() * B.y() * N.x()) +
                                         (B.x() * N.y() * T.z() - B.z() * N.y() * T.x()) +
                                         (N.x() * T.y() * B.z() - N.z() * T.y() * B.x()));
                */

                // compute tangent and bi-tangent vector for vertex 0
                cVector3d N0 = m_vertices->getNormal(index0);
                cVector3d T0 = cProjectPointOnPlane(T, cVector3d(0, 0, 0), N0);
                cVector3d B0 = cProjectPointOnPlane(B, cVector3d(0, 0, 0), N0);
                T0.normalize();
                B0.normalize();
                m_vertices->m_tangent[index0] = T0;
                m_vertices->m_bitangent[index0] = B0;

                // compute tangent and bi-tangent vector for vertex 1
                cVector3d N1 = m_vertices->getNormal(index1);
                cVector3d T1 = cProjectPointOnPlane(T, cVector3d(0, 0, 0), N1);
                cVector3d B1 = cProjectPointOnPlane(B, cVector3d(0, 0, 0), N1);
                T1.normalize();
                B1.normalize();
                m_vertices->m_tangent[index1] = T1;
                m_vertices->m_bitangent[index1] = B1;

                // compute tangent and bi-tangent vector for vertex 2
                cVector3d N2 = m_vertices->getNormal(index2);
                cVector3d T2 = cProjectPointOnPlane(T, cVector3d(0, 0, 0), N2);
                cVector3d B2 = cProjectPointOnPlane(B, cVector3d(0, 0, 0), N2);
                T2.normalize();
                B2.normalize();
                m_vertices->m_tangent[index2] = T2;
                m_vertices->m_bitangent[index2] = B2;

                // mark for update
                m_vertices->m_flagTangentData = true;
                m_vertices->m_flagBitangentData = true;
            }
        }
    }

    //--------------------------------------------------------------------------
    /*!
        This method renders the OpenGL vertex buffer object.
    */
    //--------------------------------------------------------------------------
    inline void renderInitialize()
    {
#ifdef C_USE_OPENGL
        unsigned int numtriangles = getNumElements();

        // allocate object and buffers if needed
        if (m_elementBuffer == 0)
        {
            glGenBuffers(1, &m_elementBuffer);
        }

        // bind buffer
        glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, m_elementBuffer);

        // update buffer size if needed
        if (m_flagMarkForResize)
        {
            glBufferData(GL_ELEMENT_ARRAY_BUFFER, 3 * numtriangles * sizeof(unsigned int), &(m_indices[0]), GL_STATIC_DRAW);
            m_flagMarkForResize = true;
        }

        // update data if needed
        if (m_flagMarkForUpdate)
        {
            glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, m_elementBuffer);
            glBufferSubData(GL_ELEMENT_ARRAY_BUFFER, 0, 3 * numtriangles * sizeof(unsigned int), &(m_indices[0]));

            m_flagMarkForUpdate = false;
        }

        // initialize rendering of vertices
        m_vertices->renderInitialize();

        // render object
        glEnableClientState(GL_VERTEX_ARRAY);
        glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, m_elementBuffer);
        glDrawElements(GL_TRIANGLES, 3 * numtriangles, GL_UNSIGNED_INT, (void*)0);
        glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, 0);
#endif
    }

    //--------------------------------------------------------------------------
    /*!
        This method finalizes rendering the OpenGL vertex buffer object.
    */
    //--------------------------------------------------------------------------
    inline void renderFinalize()
    {
#ifdef C_USE_OPENGL
        // finalize rendering
        m_vertices->renderFinalize();
        glDisableClientState(GL_VERTEX_ARRAY);
#endif
    }

    //!  This method checks if the given line segment intersects a selected triangle from this array.
    virtual bool computeCollision(const unsigned int a_elementIndex,
                                  cGenericObject* a_object,
                                  cVector3d& a_segmentPointA,
                                  cVector3d& a_segmentPointB,
                                  cCollisionRecorder& a_recorder,
                                  cCollisionSettings& a_settings) const;

    //--------------------------------------------------------------------------
    /*!
        This method computes and returns the area for a selected  triangle.

        \return Area for selected triangle.
    */
    //--------------------------------------------------------------------------
    inline double computeArea(const unsigned int a_triangleIndex)
    {
        // A = 0.5 * | u x v |
        cVector3d u = m_vertices->getLocalPos(getVertexIndex1(a_triangleIndex)) - m_vertices->getLocalPos(getVertexIndex0(a_triangleIndex));
        cVector3d v = m_vertices->getLocalPos(getVertexIndex2(a_triangleIndex)) - m_vertices->getLocalPos(getVertexIndex0(a_triangleIndex));

        return (0.5 * (cCross(u,v).length()));
    }

    //--------------------------------------------------------------------------
    /*!
        This method computes the surface normal of a triangle and if requested,
        updates the normal of each of the three vertices.

        \param  a_triangleIndex          Index number of selected triangle.
        \param  a_applyNormalToVertices  If __true__, then update normal of each vertex.

        \return Computed surface normal for selected triangle.
    */
    //--------------------------------------------------------------------------
    cVector3d computeNormal(const unsigned int a_triangleIndex,
                            const bool a_applyNormalToVertices)
    {
        // get pointer to vertices
        int vertex0 = getVertexIndex0(a_triangleIndex);
        int vertex1 = getVertexIndex1(a_triangleIndex);
        int vertex2 = getVertexIndex2(a_triangleIndex);

        // retrieve vertex positions
        cVector3d pos0 = m_vertices->getLocalPos(vertex0);
        cVector3d pos1 = m_vertices->getLocalPos(vertex1);
        cVector3d pos2 = m_vertices->getLocalPos(vertex2);

        // compute normal vector
        cVector3d normal, v01, v02;
        pos1.subr(pos0, v01);
        pos2.subr(pos0, v02);
        v01.crossr(v02, normal);
        double length = normal.length();
        if (length > 0.0)
        {
            normal.div(length);
            if (a_applyNormalToVertices)
            {
                m_vertices->setNormal(vertex0, normal);
                m_vertices->setNormal(vertex1, normal);
                m_vertices->setNormal(vertex2, normal);
                m_vertices->m_flagNormalData = true;
            }
            return (normal);
        }

        normal.zero();
        return (normal);
    }
};

//------------------------------------------------------------------------------
} // namespace chai3d
//------------------------------------------------------------------------------

//------------------------------------------------------------------------------
#endif
//------------------------------------------------------------------------------


text:
The best jQuery plugin ever.

## Getting Started
Download the [production version][min] or the [development version][max].

[min]: https://raw.github.com/panxuepeng/arttemplate/master/dist/arttemplate.min.js
[max]: https://raw.github.com/panxuepeng/arttemplate/master/dist/arttemplate.js

In your web page:

```html
<script src="jquery.js"></script>
<script src="dist/arttemplate.min.js"></script>
<script>
jQuery(function($) {
  $.awesome(); // "awesome"
});
</script>
```

## Documentation
_(Coming soon)_

## Examples
_(Coming soon)_

## Release History
_(Nothing yet)_

redpajama_set_name: RedPajamaGithub


text:
require 'chef/knife'

class Chef
  class Knife
    class FaiCreate < Knife

      deps do
        require 'knife-fai'
        require 'chef/data_bag_item'
      end

      banner "knife fai create [HOST] (options)"

      option :fai_ip,
      :short => "-i IP",
      :long => "--ip IP",
      :description => "Host ip address"

      option :fai_mac,
      :short => "-m MACADDR",
      :long => "--mac MACADDR",
      :description => "Host mac address"

      option :fai_class,
      :short => "-c CLASS",
      :long => "--class CLASS",
      :description => "FAI CLASS",
      :default => "FAIBASE"

      def run
        ensure_databag()
        @data_bag_item_name = @name_args[0]
        if @data_bag_item_name
          create_object({ "id" => @data_bag_item_name }, "data_bag_item[#{@data_bag_item_name}]") do |output|
            item = Chef::DataBagItem.from_hash(output)
            item.data_bag('hosts')
            item.raw_data[:class] = config[:fai_class]
            item.raw_data[:mac] = config[:fai_mac]
            item.raw_data[:ip] = config[:fai_ip]
            rest.post_rest("data/hosts", item)
          end
        end
      end
    end
  end
end


text:
Using IPv4 module
#################

Assuming that you have Client Factory instantiated (see :ref:`How to Instantiate Client Factory <client-factory>`) at **client** variable, in order to access methods relative to IPv4 module you need to call create_api_ipv4() at **client**.

Example:

.. code-block:: python

   ipv4_module = client.create_api_ipv4()

For more information, please look GloboNetworkAPI documentation.

GET
***

The List of fields available at IPv4 module is:

    * id
    * ip_formated
    * oct1
    * oct2
    * oct3
    * oct4
    * networkipv4
    * description
    * equipments
    * vips
    * server_pool_members

Obtain List of IPv4's through id's
==================================

Here you need to call get() method at ipv4_module.

You can pass up to 5 parameters:
    * **ids**: List containing identifiers of IPv4's.
    * **include**: Array containing fields to include on response.
    * **exclude**: Array containing fields to exclude on response.
    * **fields**: Array containing fields to override default fields.
    * **kind**: string where you can choose between "basic" or "details".

The response will be a dict with a list of IPv4's.

Examples:

.. code-block:: python

    ipv4s = ipv4_module.get(ids=[1, 2, 3])

.. code-block:: python

    ipv4s = ipv4_module.get(ids=[1, 2, 3],
                           include=['oct1', 'oct2'],
                           exclude=['oct3'],
                           kind='details')

.. code-block:: python

    ipv4s = ipv4_module.get(ids=[1, 2, 3],
                           fields=['id', 'oct1', 'oct2', 'networkipv4'])

Obtain List of IPv4's through extended search
=============================================

Here you need to call search() method at ipv4_module.

You can pass up to 5 parameters:
    * **search**: Dict containing QuerySets to find IPv4's.
    * **include**: Array containing fields to include on response.
    * **exclude**: Array containing fields to exclude on response.
    * **fields**: Array containing fields to override default fields.
    * **kind**: string where you can choose between "basic" or "details".

The response will be a dict with a list of IPv4's.

Example:

.. code-block:: python

    search = {
        'extends_search': [{
            {
                'oct1': 10,
            },
            {
                'oct1': 172,
            }
        }],
        'start_record': 0,
        'custom_search': '',
        'end_record': 25,
        'asorting_cols': [],
        'searchable_columns': []}
    fields = ['id', 'oct1', 'oct2', 'vips']

    ipv4s = ipv4_module.search(search=search, fields=fields)

POST
****

The List of fields available for create an IPv4 is:

    * oct1
    * oct2
    * oct3
    * oct4
    * networkipv4 - **Mandatory**
    * description
    * equipments
        * id

Create List of IPv4's
=====================

Here you need to call create() method at ipv4_module.

You need to pass 1 parameter:
    * **ipv4s**: List containing IPv4's that you want to create.

Example:

.. code-block:: python

    ipv4s_to_create = [
        {
            "oct1": 10,
            "oct2": 10,
            "oct3": 0,
            "oct4": 2,
            "description": "IP 2",
            "networkipv4": 1
        },
        {
            "description": "IP 1",
            "networkipv4": 2,
            "equipments": [
                {
                    "id": 1
                },
                {
                    "id": 2
                }
            ]
        }
    ]

    ipv4_module.create(ipv4s=ipv4s_to_create)

PUT
***

The List of fields available for update an IPv4 is:

    * id - **Mandatory**
    * description
    * equipments
        * id

Update List of IPv4's
=====================

Here you need to call update() method at ipv4_module.

You need to pass 1 parameter:
    * **ipv4s**: List containing ipv4s that you want to update.

Example:

.. code-block:: python

    ipv4s_to_update = [
        {
            "id": 1,
            "description": "New-Desc-1"
        },
        {
            "id": 2,
            "equipments": [
                {
                    "id": 1
                },
                {
                    "id": 2
                }
            ]
        }
    ]

    ipv4_module.update(ipv4s=ipv4s_to_update)

DELETE
******

Delete List of IPv4's
=====================

Here you need to call delete() method at ipv4_module.

You need to pass 1 parameter:
    * **ids**: List containing identifiers of IPv4's that you want to delete.

Example:

.. code-block:: python

    ipv4_module.delete(ids=[1, 2, 3])


text:
package monitor

import "github.com/klauspost/intrinsics/x86"

var _ = x86.M64{}  // Make sure we use x86 package

// Skipped: _mm_monitor. Contains pointer parameter.

// Mwait: Hint to the processor that it can enter an
// implementation-dependent-optimized state while waiting for an event or store
// operation to the address range specified by MONITOR.
//
//
//
// Instruction: 'MWAIT'. Intrinsic: '_mm_mwait'.
// Requires MONITOR.
func Mwait(extensions uint, hints uint)  {
	panic("not implemented")
}


text:
package com.intellij.openapi.diagnostic;

public interface ApplicationInfoProvider {

  String getInfo();

}


text:
/**
 * 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 org.apache.aurora.scheduler.storage.mem;

import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.atomic.AtomicLong;
import java.util.logging.Level;
import java.util.logging.Logger;

import com.google.common.base.Function;
import com.google.common.base.Functions;
import com.google.common.base.Optional;
import com.google.common.base.Preconditions;
import com.google.common.base.Predicate;
import com.google.common.base.Predicates;
import com.google.common.collect.FluentIterable;
import com.google.common.collect.HashMultimap;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableSet;
import com.google.common.collect.Iterables;
import com.google.common.collect.Maps;
import com.google.common.collect.Multimap;
import com.google.common.collect.Multimaps;
import com.twitter.common.args.Arg;
import com.twitter.common.args.CmdLine;
import com.twitter.common.base.MorePreconditions;
import com.twitter.common.inject.TimedInterceptor.Timed;
import com.twitter.common.quantity.Amount;
import com.twitter.common.quantity.Time;
import com.twitter.common.stats.Stats;

import org.apache.aurora.gen.ScheduledTask;
import org.apache.aurora.gen.TaskConfig;
import org.apache.aurora.gen.TaskQuery;
import org.apache.aurora.scheduler.base.JobKeys;
import org.apache.aurora.scheduler.base.Query;
import org.apache.aurora.scheduler.base.Tasks;
import org.apache.aurora.scheduler.storage.TaskStore;
import org.apache.aurora.scheduler.storage.entities.IJobKey;
import org.apache.aurora.scheduler.storage.entities.IScheduledTask;
import org.apache.aurora.scheduler.storage.entities.ITaskConfig;
import org.apache.commons.lang.StringUtils;

import static java.util.Objects.requireNonNull;

/**
 * An in-memory task store.
 */
class MemTaskStore implements TaskStore.Mutable {

  private static final Logger LOG = Logger.getLogger(MemTaskStore.class.getName());

  @CmdLine(name = "slow_query_log_threshold",
      help = "Log all queries that take at least this long to execute.")
  private static final Arg<Amount<Long, Time>> SLOW_QUERY_LOG_THRESHOLD =
      Arg.create(Amount.of(25L, Time.MILLISECONDS));

  private final long slowQueryThresholdNanos = SLOW_QUERY_LOG_THRESHOLD.get().as(Time.NANOSECONDS);

  private static final Function<Query.Builder, Optional<Set<IJobKey>>> QUERY_TO_JOB_KEY =
      new Function<Query.Builder, Optional<Set<IJobKey>>>() {
        @Override
        public Optional<Set<IJobKey>> apply(Query.Builder query) {
            return JobKeys.from(query);
        }
      };
  private static final Function<Query.Builder, Optional<Set<String>>> QUERY_TO_SLAVE_HOST =
      new Function<Query.Builder, Optional<Set<String>>>() {
        @Override
        public Optional<Set<String>> apply(Query.Builder query) {
          return Optional.fromNullable(query.get().getSlaveHosts());
        }
      };

  // Since this class operates under the API and umbrella of {@link Storage}, it is expected to be
  // thread-safe but not necessarily strongly-consistent unless the externally-controlled storage
  // lock is secured.  To adhere to that, these data structures are individually thread-safe, but
  // we don't lock across them because of the relaxed consistency guarantees.
  // Note that this behavior makes it possible to receive query results that are not sane,
  // specifically when a secondary key value is changed.  In other words, we currently don't always
  // support the invariant that a query by slave host yields a result with all tasks matching that
  // slave host.  This is deemed acceptable due to the fact that secondary key values are rarely
  // mutated in practice, and mutated in ways that are not impacted by this behavior.
  private final Map<String, Task> tasks = Maps.newConcurrentMap();
  private final List<SecondaryIndex<?>> secondaryIndices = ImmutableList.of(
      new SecondaryIndex<>(
          Tasks.SCHEDULED_TO_JOB_KEY,
          QUERY_TO_JOB_KEY,
          Stats.exportLong("task_queries_by_job")),
      new SecondaryIndex<>(
          Tasks.SCHEDULED_TO_SLAVE_HOST,
          QUERY_TO_SLAVE_HOST,
          Stats.exportLong("task_queries_by_host")));

  // An interner is used here to collapse equivalent TaskConfig instances into canonical instances.
  // Ideally this would fall out of the object hierarchy (TaskConfig being associated with the job
  // rather than the task), but we intuit this detail here for performance reasons.
  private final Interner<TaskConfig, String> configInterner = new Interner<>();

  private final AtomicLong taskQueriesById = Stats.exportLong("task_queries_by_id");
  private final AtomicLong taskQueriesAll = Stats.exportLong("task_queries_all");

  @Timed("mem_storage_fetch_tasks")
  @Override
  public ImmutableSet<IScheduledTask> fetchTasks(Query.Builder query) {
    requireNonNull(query);

    long start = System.nanoTime();
    ImmutableSet<IScheduledTask> result = matches(query).transform(TO_SCHEDULED).toSet();
    long durationNanos = System.nanoTime() - start;
    Level level = durationNanos >= slowQueryThresholdNanos ? Level.INFO : Level.FINE;
    if (LOG.isLoggable(level)) {
      Long time = Amount.of(durationNanos, Time.NANOSECONDS).as(Time.MILLISECONDS);
      LOG.log(level, "Query took " + time + " ms: " + query.get());
    }

    return result;
  }

  private final Function<IScheduledTask, Task> toTask =
      new Function<IScheduledTask, Task>() {
        @Override
        public Task apply(IScheduledTask task) {
          return new Task(task, configInterner);
        }
      };

  @Timed("mem_storage_save_tasks")
  @Override
  public void saveTasks(Set<IScheduledTask> newTasks) {
    requireNonNull(newTasks);
    Preconditions.checkState(Tasks.ids(newTasks).size() == newTasks.size(),
        "Proposed new tasks would create task ID collision.");

    Iterable<Task> canonicalized = Iterables.transform(newTasks, toTask);
    tasks.putAll(Maps.uniqueIndex(canonicalized, TO_ID));
    for (SecondaryIndex<?> index : secondaryIndices) {
      index.insert(Iterables.transform(canonicalized, TO_SCHEDULED));
    }
  }

  @Timed("mem_storage_delete_all_tasks")
  @Override
  public void deleteAllTasks() {
    tasks.clear();
    for (SecondaryIndex<?> index : secondaryIndices) {
      index.clear();
    }
    configInterner.clear();
  }

  @Timed("mem_storage_delete_tasks")
  @Override
  public void deleteTasks(Set<String> taskIds) {
    requireNonNull(taskIds);

    for (String id : taskIds) {
      Task removed = tasks.remove(id);
      if (removed != null) {
        for (SecondaryIndex<?> index : secondaryIndices) {
          index.remove(removed.storedTask);
        }
        configInterner.removeAssociation(
            removed.storedTask.getAssignedTask().getTask().newBuilder(),
            id);
      }
    }
  }

  @Timed("mem_storage_mutate_tasks")
  @Override
  public ImmutableSet<IScheduledTask> mutateTasks(
      Query.Builder query,
      Function<IScheduledTask, IScheduledTask> mutator) {

    requireNonNull(query);
    requireNonNull(mutator);

    ImmutableSet.Builder<IScheduledTask> mutated = ImmutableSet.builder();
    for (Task original : matches(query).toList()) {
      IScheduledTask maybeMutated = mutator.apply(original.storedTask);
      if (!original.storedTask.equals(maybeMutated)) {
        Preconditions.checkState(
            Tasks.id(original.storedTask).equals(Tasks.id(maybeMutated)),
            "A task's ID may not be mutated.");
        tasks.put(Tasks.id(maybeMutated), toTask.apply(maybeMutated));
        for (SecondaryIndex<?> index : secondaryIndices) {
          index.replace(original.storedTask, maybeMutated);
        }

        mutated.add(maybeMutated);
      }
    }

    return mutated.build();
  }

  @Timed("mem_storage_unsafe_modify_in_place")
  @Override
  public boolean unsafeModifyInPlace(String taskId, ITaskConfig taskConfiguration) {
    MorePreconditions.checkNotBlank(taskId);
    requireNonNull(taskConfiguration);

    Task stored = tasks.get(taskId);
    if (stored == null) {
      return false;
    } else {
      ScheduledTask updated = stored.storedTask.newBuilder();
      updated.getAssignedTask().setTask(taskConfiguration.newBuilder());
      tasks.put(taskId, toTask.apply(IScheduledTask.build(updated)));
      return true;
    }
  }

  private static Predicate<Task> queryFilter(final TaskQuery query) {
    return new Predicate<Task>() {
      @Override
      public boolean apply(Task canonicalTask) {
        IScheduledTask task = canonicalTask.storedTask;
        ITaskConfig config = task.getAssignedTask().getTask();
        if (query.getOwner() != null) {
          if (!StringUtils.isBlank(query.getOwner().getRole())
              && !query.getOwner().getRole().equals(config.getOwner().getRole())) {
            return false;
          }
          if (!StringUtils.isBlank(query.getOwner().getUser())
              && !query.getOwner().getUser().equals(config.getOwner().getUser())) {
            return false;
          }
        }
        if (query.getEnvironment() != null
            && !query.getEnvironment().equals(config.getEnvironment())) {
          return false;
        }
        if (query.getJobName() != null && !query.getJobName().equals(config.getJobName())) {
          return false;
        }

        if (query.getJobKeysSize() > 0
            && !query.getJobKeys().contains(JobKeys.from(config).newBuilder())) {
          return false;
        }
        if (query.getTaskIds() != null && !query.getTaskIds().contains(Tasks.id(task))) {
            return false;
        }

        if (query.getStatusesSize() > 0 && !query.getStatuses().contains(task.getStatus())) {
          return false;
        }
        if (query.getSlaveHostsSize() > 0
            && !query.getSlaveHosts().contains(task.getAssignedTask().getSlaveHost())) {
          return false;
        }
        if (query.getInstanceIdsSize() > 0
            && !query.getInstanceIds().contains(task.getAssignedTask().getInstanceId())) {
          return false;
        }

        return true;
      }
    };
  }

  private Iterable<Task> fromIdIndex(Iterable<String> taskIds) {
    return FluentIterable.from(taskIds)
        .transform(Functions.forMap(tasks, null))
        .filter(Predicates.notNull())
        .toList();
  }

  private FluentIterable<Task> matches(Query.Builder query) {
    // Apply the query against the working set.
    Optional<? extends Iterable<Task>> from = Optional.absent();
    if (query.get().isSetTaskIds()) {
      taskQueriesById.incrementAndGet();
      from = Optional.of(fromIdIndex(query.get().getTaskIds()));
    } else {
      for (SecondaryIndex<?> index : secondaryIndices) {
        Optional<Iterable<String>> indexMatch = index.getMatches(query);
        if (indexMatch.isPresent()) {
          // Note: we could leverage multiple indexes here if the query applies to them, by
          // choosing to intersect the results.  Given current indexes and query profile, this is
          // unlikely to offer much improvement, though.
          from = Optional.of(fromIdIndex(indexMatch.get()));
          break;
        }
      }

      // No indices match, fall back to a full scan.
      if (!from.isPresent()) {
        taskQueriesAll.incrementAndGet();
        from = Optional.of(tasks.values());
      }
    }

    return FluentIterable.from(from.get()).filter(queryFilter(query.get()));
  }

  private static final Function<Task, IScheduledTask> TO_SCHEDULED =
      new Function<Task, IScheduledTask>() {
        @Override
        public IScheduledTask apply(Task task) {
          return task.storedTask;
        }
      };

  private static final Function<Task, String> TO_ID =
      Functions.compose(Tasks.SCHEDULED_TO_ID, TO_SCHEDULED);

  private static class Task {
    private final IScheduledTask storedTask;

    Task(IScheduledTask storedTask, Interner<TaskConfig, String> interner) {
      interner.removeAssociation(
          storedTask.getAssignedTask().getTask().newBuilder(),
          Tasks.id(storedTask));
      TaskConfig canonical = interner.addAssociation(
          storedTask.getAssignedTask().getTask().newBuilder(),
          Tasks.id(storedTask));
      ScheduledTask builder = storedTask.newBuilder();
      builder.getAssignedTask().setTask(canonical);
      this.storedTask = IScheduledTask.build(builder);
    }

    @Override
    public boolean equals(Object o) {
      if (!(o instanceof Task)) {
        return false;
      }

      Task other = (Task) o;
      return storedTask.equals(other.storedTask);
    }

    @Override
    public int hashCode() {
      return storedTask.hashCode();
    }
  }

  /**
   * A non-unique secondary index on the task store.  Maps a custom key type to a set of task IDs.
   *
   * @param <K> Key type.
   */
  private static class SecondaryIndex<K> {
    private final Multimap<K, String> index =
        Multimaps.synchronizedSetMultimap(HashMultimap.<K, String>create());
    private final Function<IScheduledTask, K> indexer;
    private final Function<Query.Builder, Optional<Set<K>>> queryExtractor;
    private final AtomicLong hitCount;

    /**
     * Creates a secondary index that will extract keys from tasks using the provided indexer.
     *
     * @param indexer Indexing function.
     * @param queryExtractor Function to extract the keys relevant to a query.
     * @param hitCount Counter for number of times the secondary index applies to a query.
     */
    SecondaryIndex(
        Function<IScheduledTask, K> indexer,
        Function<Query.Builder, Optional<Set<K>>> queryExtractor,
        AtomicLong hitCount) {

      this.indexer = indexer;
      this.queryExtractor = queryExtractor;
      this.hitCount = hitCount;
    }

    void insert(Iterable<IScheduledTask> tasks) {
      for (IScheduledTask task : tasks) {
        insert(task);
      }
    }

    void insert(IScheduledTask task) {
      K key = indexer.apply(task);
      if (key != null) {
        index.put(key, Tasks.id(task));
      }
    }

    void clear() {
      index.clear();
    }

    void remove(IScheduledTask task) {
      K key = indexer.apply(task);
      if (key != null) {
        index.remove(key, task);
      }
    }

    void replace(IScheduledTask old, IScheduledTask replacement) {
      synchronized (index) {
        remove(old);
        insert(replacement);
      }
    }

    private final Function<Set<K>, Iterable<String>> lookup =
        new Function<Set<K>, Iterable<String>>() {
          @Override
          public Iterable<String> apply(Set<K> keys) {
            hitCount.incrementAndGet();
            ImmutableSet.Builder<String> builder = ImmutableSet.builder();
            for (K key : keys) {
              builder.addAll(index.get(key));
            }
            return builder.build();
          }
    };

    Optional<Iterable<String>> getMatches(Query.Builder query) {
      return queryExtractor.apply(query).transform(lookup);
    }
  }
}


text:
class ProxyPoolError(Exception):
    """proxypool error base"""

class CrawlerRuleImplementionError(ProxyPoolError):

    def __str__(self):
        return 'crawler rule required "start_url", "ip_xpath" and "port_xpath".'

class CrawlerRuleBaseInstantiateError(ProxyPoolError):

    def __str__(self):
        return "crawler rule base class shouldn't be instantiated."

class ProxyPoolEmptyError(ProxyPoolError):

    def __str__(self):
        return 'the proxy pool was empty in a long time.'


text:
<?php

use Fish\Laratabs\HTML\TabBuilder;
class TabBuilderTest extends TabsTester
{
   /**
    * @var \FunctionalTester
    */
    protected $tester;

    /**
     * @var
     */
    protected $builder;

    /**
     * instatiate the class under test
     */
    public function __construct() {

        $this->builder = new TabBuilder();
        parent::__construct();
    }

    protected function _before()
    {
        file_put_contents(base_path() . "/tabs.json",json_encode($this->data));

    }

    protected function _after()
    {
        file_put_contents(base_path() . "/tabs.json","");

    }

    /**
     * @test
     */
    public function generate_tabs_html()
    {

        $obj = $this->builder->get('tabs');
        $actualHtml = $obj->__toString();
        $expectedHtml = file_get_contents(__DIR__ ."/../_support/templates/tabs.txt");

        $actualHtml = preg_replace('/\s+/', '', $actualHtml);

        $this->assertEquals($expectedHtml, $actualHtml);

    }

    /**
     * @test
     */
    public function pass_variables_to_the_tabs() {

        file_put_contents(app_path() . "/views/tabs/tab1.blade.php","{{\$var}}");

        $obj = $this->builder->get('tabs',['var'=>'someTestVar'])->__toString();

        file_put_contents(app_path() . "/views/tabs/tab1.blade.php","tab1.blade.php");

        $this->assertTrue(strpos($obj,'someTestVar')!==false);

    }

    /**
     * @test
     */

    public function override_default_configuration() {

        $options = ['fade'=>false,
                    'direction'=>'vertical',
                    'type'=>'pills'];

        $obj = $this->builder->get('tabs',[],$options)->__toString();

        $this->assertTrue(strpos($obj,'fade')===false);
        $this->assertTrue(strpos($obj,'nav-pills')!==false);
        $this->assertTrue(strpos($obj,'nav-stacked')!==false);

        $obj = $this->builder->get('tabs')->__toString();

        $this->assertTrue(strpos($obj,'fade')!==false);
        $this->assertTrue(strpos($obj,'nav-pills')===false);
        $this->assertTrue(strpos($obj,'nav-stacked')===false);

    }

    /**
     *  @test
     *  @expectedException Fish\Laratabs\HTML\Exceptions\UndefinedKeyException
     */
    public function throw_an_exception_when_the_key_does_not_exist() {
       $this->builder->get('not-existant-key');
    }

    /**
     *  @test
     *  @expectedException Fish\Laratabs\HTML\Exceptions\MissingTabTemplateException
     */
    public function throw_an_exception_when_view_can_not_be_found() {
        $view = app_path()."/views/tabs/tab1.blade.php";
        unlink($view);
        $this->builder->get('tabs');
        file_put_contents($view, 'tab1.blade.php');
    }

    /**
     * @test
     */
    public function generate_tabs_except_for_the_excluded_ones() {

        $view = app_path()."/views/tabs/tab1.blade.php";
        file_put_contents($view, 'tab1.blade.php');
        $tabs = $this->builder->get('tabs',[],['except'=>['tab1','tab4']]);

        $html = $tabs->__toString();

        $includesTabs = strpos($html,'Tab2')!==false;
        $doesntIncludeTabs = strpos($html,'Tab4')===false;

        $this->assertTrue($doesntIncludeTabs);
        $this->assertTrue($includesTabs);
    }

    /**
     * @test
     */
    public function generate_only_included_tabs() {

        $view = app_path()."/views/tabs/tab1.blade.php";
        file_put_contents($view, 'tab1.blade.php');

        $tabs = $this->builder->get('tabs',[],['only'=>['tab4','tab3']]);

        $html = $tabs->__toString();

        $includesTabs = strpos($html,'Tab4')!==false;
        $doesntIncludeTabs = strpos($html,'Tab1')===false;

        $this->assertTrue($includesTabs);
        $this->assertTrue($doesntIncludeTabs);

    }

}


text:
#include <iostream>

#include <getopt.h>
#include <stdlib.h>

#include "globals.h"
#include "helpers.h"
#include "spdi_io.h"
#include "succ.h"
#include "reach.h"

/*
    Andrei Sandler (andrei.sandler@phystech.edu), 2016-2017.
    SPDI solver.
    Everything is given in counter-clockwise order (points in region R, vectors of dynamics on R)
*/

using namespace std;

void PrintUsage() {
    cerr << "Usage:" << endl;
    cerr << "    --spdi path/to/spdi/file" << endl;
    cerr << "    --task path/to/reachability/task" << endl;
    cerr << "    --threads thread_number (optional, default = 1)" << endl;
    cerr << "    --strict (optional): do not allow dynamics collision and parallel flow" << endl;
    cerr << "    --debug (optional): print debug information" << endl;
}

int main(int argc, char** argv) {
    char* spdiPath = NULL;
    char* spdiReachTaskPath = NULL;

    static struct option long_options[] = {
        {"spdi", required_argument, 0, 0},
        {"task", required_argument, 0, 0},
        {"threads", required_argument, 0, 0},
        {"strict", no_argument, 0, 0},
        {"debug", no_argument, 0, 0},
        {0, 0, 0, 0}
    };

    int option_index = 0, c = 0;

    while ((c = getopt_long(argc, argv, "h", long_options, &option_index)) != -1) {
        if (c == 0) {
            switch (option_index) {
                case 0:
                    spdiPath = optarg;
                    break;
                case 1:
                    spdiReachTaskPath = optarg;
                    break;
                case 2:
                    ThreadsNumber = atoi(optarg);
                    FreeThreads = ThreadsNumber - 1;
                    break;
                case 3:
                    Strict = true;
                    break;
                case 4:
                    Debug = true;
                    break;
            }
        } else {
            PrintUsage();
            break;
        }
    }

    if (!spdiPath || !spdiReachTaskPath) {
        PrintUsage();
        return 1;
    }

    ReadAndValidateSPDI(spdiPath, Spdi, Strict);
    ReadStartAndFinalEdgeParts(spdiReachTaskPath, Spdi, ReachTask);

    pthread_mutex_init(&FreeThreadsMutex, NULL);
    pthread_mutex_init(&AnswerMutex, NULL);

    pthread_attr_init(&ThreadAttributes);
    pthread_attr_setdetachstate(&ThreadAttributes, PTHREAD_CREATE_JOINABLE);

    SolveReachTask(Spdi, ReachTask);

    pthread_mutex_destroy(&FreeThreadsMutex);
    pthread_mutex_destroy(&AnswerMutex);

    pthread_exit(NULL);
}


text:
.DV-viewSearch #DV-pages{
  background-color:#999;
}

.DV-viewSearch #DV-textPage{
  background-color:#eee;
}

.DV-viewSearch .DV-zoomControls{
  display:none;
}

.DV-viewSearch #DV-pageCollection{
  cursor: text;
}

.DV-viewSearch #DV-annotations,
.DV-viewSearch #DV-bar{
  display:none;
}

.DV-viewSearch #DV-search,
.DV-viewSearch #DV-searchBar{
  display:block;
}

.DV-viewSearch #DV-totalAnnotations,
.DV-viewSearch #DV-currentAnnotationPrefix{
  display:none;
}

.DV-viewSearch #DV-textPage{
  margin-top:50px;
}

.DV-viewSearch #DV-textCurrentPage{
  top:60px;
}

.DV-viewSearch #DV-sidebar #DV-well .DV-chaptersContainer div.DV-hasChildren div,
.DV-viewSearch #DV-sidebar #DV-well .DV-chaptersContainer span.DV-expander,
.DV-viewSearch .DV-annotationMarker{
  display:none !important;
}

.DV-viewSearch #DV-sidebar #DV-well .DV-chaptersContainer div.DV-hasChildren div.DV-first{
  display:block !important;
}

.DV-viewSearch #DV-sidebar #DV-well .DV-chaptersContainer div.DV-hasChildren div.DV-first span.DV-trigger{
  margin-left:-1px;
}

.DV-viewSearch #DV-textContents,
.DV-viewSearch #DV-textPage{
  background-color:#c5c5c5;
}

.DV-viewSearch .DV-annotationMarker,
.DV-viewSearch .DV-chapter{
  margin-left:14px;
}


text:
<?php

namespace AppBundle\Controller\compras;

use Symfony\Bundle\FrameworkBundle\Controller\Controller;

/**
 * ComprasProveedores controller.
 *
 */
class servicioComprasController extends Controller {
    /* @var $em \Doctrine\ORM\EntityManager */

    protected $em;

    /* @var $mailer \Swift_Mailer */
    protected $mailer;

    protected $templating;

    public function __construct(\Doctrine\ORM\EntityManager $em, \Swift_Mailer $mailer, $templating) {
        $this->em = $em;
        $this->mailer = $mailer;
        $this->templating = $templating;
    }

    public function getDetalleOrdenCompra($id) {
        $detalle = [];

        $detalle['orden'] = $this->em->getRepository('AppBundle:ComprasOrdenes')->find($id);

        $sDql = 'SELECT cop FROM AppBundle:ComprasOrdenesProductos cop JOIN AppBundle:ComprasProductos cprod WITH cop.producto = cprod JOIN AppBundle:ComprasProveedores cp WITH cprod.proveedor = cp WHERE cop.orden = :orden ORDER BY cp.id ASC';
        $detalle['productos'] = $this->em->createQuery($sDql)
                ->setParameter('orden', $id)
                ->getResult();

        return $detalle;
    }

    public function sendNotification($iOrden, $para, $asunto = 'Detalles de compra', $titulo = 'Detalles de compra', $mensaje = '') {

        $orden = $this->getDetalleOrdenCompra($iOrden);

        $asunto .= " | No. $iOrden";

        $message = $this->mailer->createMessage()
                ->setFrom('info@lapizzeria.com')
                ->setSubject($asunto)
                ->setTo(array('vladimiroski@gmail.com' => 'Vladimir Hidalgo'))
                ->setBody(
                $this->templating->render(
                        'AppBundle:Correos:enviarOrden.html.twig', array('orden' => $orden, 'titulo' => $titulo, 'mensaje' => $mensaje)
                ), 'text/html'
        );
        $this->mailer->send($message);
    }

}


text:
package org.Cherry.Modules.Web.Engine;

import static org.Cherry.Modules.Web.MimeAndFileResourcesUtil.getFileResource;
import static org.Cherry.Modules.Web.WebConstants.ROOT_URI;
import static org.Cherry.Modules.Web.WebConstants.URI_TOKEN;
import static org.Cherry.Utils.Utils.failIfEmpty;
import static org.Cherry.Utils.Utils.isEmpty;
import static org.Cherry.Utils.Utils.isNotEmpty;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.lang.ref.WeakReference;
import java.util.StringTokenizer;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;

import javax.inject.Inject;
import javax.inject.Singleton;

import org.Cherry.Configuration.ConfigurationService;
import org.Cherry.Core.ServiceTemplate;
import org.Cherry.Modules.Freemarker.DictionaryModel;
import org.Cherry.Modules.Freemarker.Middleware.FreeMarkerService;
import org.Cherry.Modules.JSON.Agents.JSONAgentDefinition;
import org.Cherry.Modules.Jackson.Middleware.ObjectMapperService;
import org.Cherry.Modules.Web.Agents.Standard.HttpStatusCode;
import org.Cherry.Modules.Web.Engine.InvocationContext.Key;
import org.apache.http.HttpEntity;
import org.apache.http.HttpEntityEnclosingRequest;
import org.apache.http.HttpException;
import org.apache.http.HttpRequest;
import org.apache.http.HttpResponse;
import org.apache.http.protocol.HttpContext;

import com.fasterxml.jackson.core.JsonParseException;
import com.fasterxml.jackson.databind.JsonMappingException;

/**
 * @author Cristian.Malinescu
 *
 */
abstract class RequestHandlerTemplate extends ServiceTemplate implements IRequestHandlerEx {
  /*
   * (non-Javadoc)
   *
   * @see org.apache.http.protocol.HttpRequestHandler#handle(org.apache.http.HttpRequest, org.apache.http.HttpResponse, org.apache.http.protocol.HttpContext)
   */
  @Override
  public void handle(final HttpRequest request, final HttpResponse response, final HttpContext context) throws HttpException, IOException {
    Context.instance().getInvocationContext().set(Key.Request, request);

    final RequestCommand command = new RequestCommand(request, response, context, getDocRoot());

    try {
      handle(command);
    } catch (final Throwable t) {
      error(t, t.getMessage());

      if (null != command) {
        command.setStatusCode(HttpStatusCode.InternalServerError);
        handle(command);
      }
    } finally {
      Context.instance().flush();
    }
  }

  static class CallDef {
    private String _controllerUri = ROOT_URI;
    private String _methodUri = ROOT_URI;

    String getControllerURI() {
      return _controllerUri;
    }

    void setControllerURI(final String controllerUri) {
      if (isNotEmpty(controllerUri))
        _controllerUri = controllerUri;
    }

    String getMethodURI() {
      return _methodUri;
    }

    void setMethodURI(final String methodUri) {
      if (isNotEmpty(methodUri))
        _methodUri = methodUri;
    }

    @Override
    public String toString() {
      final StringBuilder sb = new StringBuilder("{'controllerUri':'").append(getControllerURI());
      sb.append("','methodUri':'").append(getMethodURI()).append("'}");

      return sb.toString();
    }

    CallDef(final String controllerUri, final String methodUri) {
    }

    private CallDef() {
    }

    static final CallDef RootCall = new CallDef();
  }

  static CallDef scanRESTBeanURI(final String uri) {
    if (isEmpty(uri) || ROOT_URI.equals(uri))
      return CallDef.RootCall;

    final CallDef call = new CallDef();

    final WeakReference<StringTokenizer> st = new WeakReference<StringTokenizer>(new StringTokenizer(uri, URI_TOKEN));

    if (st.get().hasMoreTokens()) {
      String token = st.get().nextToken();

      if (isNotEmpty(token)) {
        call.setControllerURI(URI_TOKEN + token);

        if (st.get().hasMoreTokens()) {
          token = st.get().nextToken();

          if (isNotEmpty(token))
            call.setMethodURI(URI_TOKEN + token);
        }
      }
    }

    return call;
  }

  protected Object getBeanParameter(final RequestCommand command, final Class<?> beanParameterType) throws JsonParseException, JsonMappingException, IOException {
    Object result = null;

    final HttpRequest request = command.getRequest();

    if (request instanceof HttpEntityEnclosingRequest) {
      final HttpEntity entity = ((HttpEntityEnclosingRequest) request).getEntity();

      final long contentLength = entity.getContentLength();

      if (0 < contentLength) {
        final WeakReference<InputStream> is = new WeakReference<InputStream>(entity.getContent());

        if (0 < is.get().available())
          result = getObjectMapperService().readValue(is.get(), beanParameterType);
      } else warn("{}", "Undefined content/length 0! Did the sender missed it?!");
    } else throw new IllegalArgumentException("Expected request of type [" + HttpEntityEnclosingRequest.class + "] but found [" + request.getClass() + "]");

    return result;
  }

  protected DictionaryModel createModel() {
    return getFreeMarkerService().createModel();
  }

  protected ObjectMapperService getObjectMapperService() {
    assert null != _objectMapperService;
    return _objectMapperService;
  }

  protected FreeMarkerService getFreeMarkerService() {
    assert null != _freeMarkerService;
    return _freeMarkerService;
  }

  protected JSONAgentDefinition getController(final String uri) {
    failIfEmpty(uri);
    return getControllersManagerService().getController(uri);
  }

  protected ControllersManager getControllersManagerService() {
    assert null != _controllersManager;
    return _controllersManager;
  }

  protected File getFile(final String uri) throws UnsupportedEncodingException {
    if (!getFilesCache().containsKey(uri)) {
      final File file = getFileResource(getDocRoot(), uri);
      getFilesCache().putIfAbsent(uri, file);
      return file;
    }

    return getFilesCache().get(uri);
  }

  protected ConcurrentMap<String, File> getFilesCache() {
    return _filesCache;
  }

  @Inject
  @Singleton
  private ControllersManager _controllersManager;

  @Inject
  @Singleton
  private ObjectMapperService _objectMapperService;

  @Inject
  @Singleton
  private FreeMarkerService _freeMarkerService;

  /*
   * (non-Javadoc)
   *
   * @see net.Sabadios.RnD.Http.HttpServer.IHttpRequestHandlerEx#handle(net.Sabadios.RnD.Http.HttpServer.HttpRequestHandlerCommand)
   */
  @Override
  public abstract void handle(RequestCommand command) throws HttpException, IOException;

  protected String getDocRoot() {
    return _configurationService.getDocRoot();
  }

  protected String getWelcomeDoc() {
    return _configurationService.getWelcomeDoc();
  }

  @Inject
  @Singleton
  private ConfigurationService _configurationService;

  private final ConcurrentMap<String, File> _filesCache = new ConcurrentHashMap<String, File>();

  /**
   *
   */
  protected RequestHandlerTemplate() {
  }

  /**
   *
   */
  private static final long serialVersionUID = 1L;
}


text:
namespace absl {

// StrReplaceAll()
//
// Replaces character sequences within a given string with replacements provided
// within an initializer list of key/value pairs. Candidate replacements are
// considered in order as they occur within the string, with earlier matches
// taking precedence, and longer matches taking precedence for candidates
// starting at the same position in the string. Once a substitution is made, the
// replaced text is not considered for any further substitutions.
//
// Example:
//
//   std::string s = absl::StrReplaceAll(
//       "$who bought $count #Noun. Thanks $who!",
//       {{"$count", absl::StrCat(5)},
//        {"$who", "Bob"},
//        {"#Noun", "Apples"}});
//   EXPECT_EQ("Bob bought 5 Apples. Thanks Bob!", s);
ABSL_MUST_USE_RESULT std::string StrReplaceAll(
    absl::string_view s,
    std::initializer_list<std::pair<absl::string_view, absl::string_view>>
        replacements);

// Overload of `StrReplaceAll()` to accept a container of key/value replacement
// pairs (typically either an associative map or a `std::vector` of `std::pair`
// elements). A vector of pairs is generally more efficient.
//
// Examples:
//
//   std::map<const absl::string_view, const absl::string_view> replacements;
//   replacements["$who"] = "Bob";
//   replacements["$count"] = "5";
//   replacements["#Noun"] = "Apples";
//   std::string s = absl::StrReplaceAll(
//       "$who bought $count #Noun. Thanks $who!",
//       replacements);
//   EXPECT_EQ("Bob bought 5 Apples. Thanks Bob!", s);
//
//   // A std::vector of std::pair elements can be more efficient.
//   std::vector<std::pair<const absl::string_view, std::string>> replacements;
//   replacements.push_back({"&", "&"});
//   replacements.push_back({"<", "<"});
//   replacements.push_back({">", ">"});
//   std::string s = absl::StrReplaceAll("if (ptr < &foo)",
//                                  replacements);
//   EXPECT_EQ("if (ptr < &foo)", s);
template <typename StrToStrMapping>
std::string StrReplaceAll(absl::string_view s,
                          const StrToStrMapping& replacements);

// Overload of `StrReplaceAll()` to replace character sequences within a given
// output string *in place* with replacements provided within an initializer
// list of key/value pairs, returning the number of substitutions that occurred.
//
// Example:
//
//   std::string s = std::string("$who bought $count #Noun. Thanks $who!");
//   int count;
//   count = absl::StrReplaceAll({{"$count", absl::StrCat(5)},
//                               {"$who", "Bob"},
//                               {"#Noun", "Apples"}}, &s);
//  EXPECT_EQ(count, 4);
//  EXPECT_EQ("Bob bought 5 Apples. Thanks Bob!", s);
int StrReplaceAll(
    std::initializer_list<std::pair<absl::string_view, absl::string_view>>
        replacements,
    std::string* target);

// Overload of `StrReplaceAll()` to replace patterns within a given output
// string *in place* with replacements provided within a container of key/value
// pairs.
//
// Example:
//
//   std::string s = std::string("if (ptr < &foo)");
//   int count = absl::StrReplaceAll({{"&", "&"},
//                                    {"<", "<"},
//                                    {">", ">"}}, &s);
//  EXPECT_EQ(count, 2);
//  EXPECT_EQ("if (ptr < &foo)", s);
template <typename StrToStrMapping>
int StrReplaceAll(const StrToStrMapping& replacements, std::string* target);

// Implementation details only, past this point.
namespace strings_internal {

struct ViableSubstitution {
  absl::string_view old;
  absl::string_view replacement;
  size_t offset;

  ViableSubstitution(absl::string_view old_str,
                     absl::string_view replacement_str, size_t offset_val)
      : old(old_str), replacement(replacement_str), offset(offset_val) {}

  // One substitution occurs "before" another (takes priority) if either
  // it has the lowest offset, or it has the same offset but a larger size.
  bool OccursBefore(const ViableSubstitution& y) const {
    if (offset != y.offset) return offset < y.offset;
    return old.size() > y.old.size();
  }
};

// Build a vector of ViableSubstitutions based on the given list of
// replacements. subs can be implemented as a priority_queue. However, it turns
// out that most callers have small enough a list of substitutions that the
// overhead of such a queue isn't worth it.
template <typename StrToStrMapping>
std::vector<ViableSubstitution> FindSubstitutions(
    absl::string_view s, const StrToStrMapping& replacements) {
  std::vector<ViableSubstitution> subs;
  subs.reserve(replacements.size());

  for (const auto& rep : replacements) {
    using std::get;
    absl::string_view old(get<0>(rep));

    size_t pos = s.find(old);
    if (pos == s.npos) continue;

    // Ignore attempts to replace "". This condition is almost never true,
    // but above condition is frequently true. That's why we test for this
    // now and not before.
    if (old.empty()) continue;

    subs.emplace_back(old, get<1>(rep), pos);

    // Insertion sort to ensure the last ViableSubstitution comes before
    // all the others.
    size_t index = subs.size();
    while (--index && subs[index - 1].OccursBefore(subs[index])) {
      std::swap(subs[index], subs[index - 1]);
    }
  }
  return subs;
}

int ApplySubstitutions(absl::string_view s,
                       std::vector<ViableSubstitution>* subs_ptr,
                       std::string* result_ptr);

}  // namespace strings_internal

template <typename StrToStrMapping>
std::string StrReplaceAll(absl::string_view s,
                          const StrToStrMapping& replacements) {
  auto subs = strings_internal::FindSubstitutions(s, replacements);
  std::string result;
  result.reserve(s.size());
  strings_internal::ApplySubstitutions(s, &subs, &result);
  return result;
}

template <typename StrToStrMapping>
int StrReplaceAll(const StrToStrMapping& replacements, std::string* target) {
  auto subs = strings_internal::FindSubstitutions(*target, replacements);
  if (subs.empty()) return 0;

  std::string result;
  result.reserve(target->size());
  int substitutions =
      strings_internal::ApplySubstitutions(*target, &subs, &result);
  target->swap(result);
  return substitutions;
}

}  // namespace absl

#endif  // ABSL_STRINGS_STR_REPLACE_H_


text:
<?php

namespace DCarbone\PHPFHIRGenerated\R4\FHIRElement\FHIRBackboneElement\FHIRVerificationResult;

use DCarbone\PHPFHIRGenerated\R4\FHIRElement\FHIRBackboneElement;
use DCarbone\PHPFHIRGenerated\R4\FHIRElement\FHIRReference;
use DCarbone\PHPFHIRGenerated\R4\FHIRElement\FHIRSignature;
use DCarbone\PHPFHIRGenerated\R4\FHIRElement\FHIRString;
use DCarbone\PHPFHIRGenerated\R4\PHPFHIRConstants;
use DCarbone\PHPFHIRGenerated\R4\PHPFHIRTypeInterface;

/**
 * Describes validation requirements, source(s), status and dates for one or more
 * elements.
 *
 * Class FHIRVerificationResultValidator
 * @package \DCarbone\PHPFHIRGenerated\R4\FHIRElement\FHIRBackboneElement\FHIRVerificationResult
 */
class FHIRVerificationResultValidator extends FHIRBackboneElement
{
    // name of FHIR type this class describes
    const FHIR_TYPE_NAME = PHPFHIRConstants::TYPE_NAME_VERIFICATION_RESULT_DOT_VALIDATOR;
    const FIELD_ATTESTATION_SIGNATURE = 'attestationSignature';
    const FIELD_IDENTITY_CERTIFICATE = 'identityCertificate';
    const FIELD_IDENTITY_CERTIFICATE_EXT = '_identityCertificate';
    const FIELD_ORGANIZATION = 'organization';

    /** @var string */
    private $_xmlns = 'http://hl7.org/fhir';

    /**
     * A signature along with supporting context. The signature may be a digital
     * signature that is cryptographic in nature, or some other signature acceptable to
     * the domain. This other signature may be as simple as a graphical image
     * representing a hand-written signature, or a signature ceremony Different
     * signature approaches have different utilities.
     * If the element is present, it must have a value for at least one of the defined
     * elements, an \@id referenced from the Narrative, or extensions
     *
     * Signed assertion by the validator that they have validated the information.
     *
     * @var null|\DCarbone\PHPFHIRGenerated\R4\FHIRElement\FHIRSignature
     */
    protected $attestationSignature = null;

    /**
     * A sequence of Unicode characters
     * Note that FHIR strings SHALL NOT exceed 1MB in size
     * If the element is present, it must have either a \@value, an \@id, or extensions
     *
     * A digital identity certificate associated with the validator.
     *
     * @var null|\DCarbone\PHPFHIRGenerated\R4\FHIRElement\FHIRString
     */
    protected $identityCertificate = null;

    /**
     * A reference from one resource to another.
     * If the element is present, it must have a value for at least one of the defined
     * elements, an \@id referenced from the Narrative, or extensions
     *
     * Reference to the organization validating information.
     *
     * @var null|\DCarbone\PHPFHIRGenerated\R4\FHIRElement\FHIRReference
     */
    protected $organization = null;

    /**
     * Validation map for fields in type VerificationResult.Validator
     * @var array
     */
    private static $_validationRules = [    ];

    /**
     * FHIRVerificationResultValidator Constructor
     * @param null|array $data
     */
    public function __construct($data = null)
    {
        if (null === $data || [] === $data) {
            return;
        }
        if (!is_array($data)) {
            throw new \InvalidArgumentException(sprintf(
                'FHIRVerificationResultValidator::_construct - $data expected to be null or array, %s seen',
                gettype($data)
            ));
        }
        parent::__construct($data);
        if (isset($data[self::FIELD_ATTESTATION_SIGNATURE])) {
            if ($data[self::FIELD_ATTESTATION_SIGNATURE] instanceof FHIRSignature) {
                $this->setAttestationSignature($data[self::FIELD_ATTESTATION_SIGNATURE]);
            } else {
                $this->setAttestationSignature(new FHIRSignature($data[self::FIELD_ATTESTATION_SIGNATURE]));
            }
        }
        if (isset($data[self::FIELD_IDENTITY_CERTIFICATE]) || isset($data[self::FIELD_IDENTITY_CERTIFICATE_EXT])) {
            if (isset($data[self::FIELD_IDENTITY_CERTIFICATE])) {
                $value = $data[self::FIELD_IDENTITY_CERTIFICATE];
            } else {
                $value = null;
            }
            if (isset($data[self::FIELD_IDENTITY_CERTIFICATE_EXT]) && is_array($data[self::FIELD_IDENTITY_CERTIFICATE_EXT])) {
                $ext = $data[self::FIELD_IDENTITY_CERTIFICATE_EXT];
            } else {
                $ext = [];
            }
            if (null !== $value) {
                if ($value instanceof FHIRString) {
                    $this->setIdentityCertificate($value);
                } else if (is_array($value)) {
                    $this->setIdentityCertificate(new FHIRString(array_merge($ext, $value)));
                } else {
                    $this->setIdentityCertificate(new FHIRString([FHIRString::FIELD_VALUE => $value] + $ext));
                }
            } else if ([] !== $ext) {
                $this->setIdentityCertificate(new FHIRString($ext));
            }
        }
        if (isset($data[self::FIELD_ORGANIZATION])) {
            if ($data[self::FIELD_ORGANIZATION] instanceof FHIRReference) {
                $this->setOrganization($data[self::FIELD_ORGANIZATION]);
            } else {
                $this->setOrganization(new FHIRReference($data[self::FIELD_ORGANIZATION]));
            }
        }
    }

    /**
     * @return string
     */
    public function _getFHIRTypeName()
    {
        return self::FHIR_TYPE_NAME;
    }

    /**
     * @return string
     */
    public function _getFHIRXMLElementDefinition()
    {
        $xmlns = $this->_getFHIRXMLNamespace();
        if (null !== $xmlns) {
            $xmlns = " xmlns=\"{$xmlns}\"";
        }
        return "<VerificationResultValidator{$xmlns}></VerificationResultValidator>";
    }

    /**
     * A signature along with supporting context. The signature may be a digital
     * signature that is cryptographic in nature, or some other signature acceptable to
     * the domain. This other signature may be as simple as a graphical image
     * representing a hand-written signature, or a signature ceremony Different
     * signature approaches have different utilities.
     * If the element is present, it must have a value for at least one of the defined
     * elements, an \@id referenced from the Narrative, or extensions
     *
     * Signed assertion by the validator that they have validated the information.
     *
     * @return null|\DCarbone\PHPFHIRGenerated\R4\FHIRElement\FHIRSignature
     */
    public function getAttestationSignature()
    {
        return $this->attestationSignature;
    }

    /**
     * A signature along with supporting context. The signature may be a digital
     * signature that is cryptographic in nature, or some other signature acceptable to
     * the domain. This other signature may be as simple as a graphical image
     * representing a hand-written signature, or a signature ceremony Different
     * signature approaches have different utilities.
     * If the element is present, it must have a value for at least one of the defined
     * elements, an \@id referenced from the Narrative, or extensions
     *
     * Signed assertion by the validator that they have validated the information.
     *
     * @param null|\DCarbone\PHPFHIRGenerated\R4\FHIRElement\FHIRSignature $attestationSignature
     * @return static
     */
    public function setAttestationSignature(FHIRSignature $attestationSignature = null)
    {
        $this->attestationSignature = $attestationSignature;
        return $this;
    }

    /**
     * A sequence of Unicode characters
     * Note that FHIR strings SHALL NOT exceed 1MB in size
     * If the element is present, it must have either a \@value, an \@id, or extensions
     *
     * A digital identity certificate associated with the validator.
     *
     * @return null|\DCarbone\PHPFHIRGenerated\R4\FHIRElement\FHIRString
     */
    public function getIdentityCertificate()
    {
        return $this->identityCertificate;
    }

    /**
     * A sequence of Unicode characters
     * Note that FHIR strings SHALL NOT exceed 1MB in size
     * If the element is present, it must have either a \@value, an \@id, or extensions
     *
     * A digital identity certificate associated with the validator.
     *
     * @param null|\DCarbone\PHPFHIRGenerated\R4\FHIRElement\FHIRString $identityCertificate
     * @return static
     */
    public function setIdentityCertificate($identityCertificate = null)
    {
        if (null === $identityCertificate) {
            $this->identityCertificate = null;
            return $this;
        }
        if ($identityCertificate instanceof FHIRString) {
            $this->identityCertificate = $identityCertificate;
            return $this;
        }
        $this->identityCertificate = new FHIRString($identityCertificate);
        return $this;
    }

    /**
     * A reference from one resource to another.
     * If the element is present, it must have a value for at least one of the defined
     * elements, an \@id referenced from the Narrative, or extensions
     *
     * Reference to the organization validating information.
     *
     * @return null|\DCarbone\PHPFHIRGenerated\R4\FHIRElement\FHIRReference
     */
    public function getOrganization()
    {
        return $this->organization;
    }

    /**
     * A reference from one resource to another.
     * If the element is present, it must have a value for at least one of the defined
     * elements, an \@id referenced from the Narrative, or extensions
     *
     * Reference to the organization validating information.
     *
     * @param null|\DCarbone\PHPFHIRGenerated\R4\FHIRElement\FHIRReference $organization
     * @return static
     */
    public function setOrganization(FHIRReference $organization = null)
    {
        $this->organization = $organization;
        return $this;
    }

    /**
     * Returns the validation rules that this type's fields must comply with to be considered "valid"
     * The returned array is in ["fieldname[.offset]" => ["rule" => {constraint}]]
     *
     * @return array
     */
    public function _getValidationRules()
    {
        return self::$_validationRules;
    }

    /**
     * Validates that this type conforms to the specifications set forth for it by FHIR.  An empty array must be seen as
     * passing.
     *
     * @return array
     */
    public function _getValidationErrors()
    {
        $errs = parent::_getValidationErrors();
        $validationRules = $this->_getValidationRules();
        if (null !== ($v = $this->getAttestationSignature())) {
            if ([] !== ($fieldErrs = $v->_getValidationErrors())) {
                $errs[self::FIELD_ATTESTATION_SIGNATURE] = $fieldErrs;
            }
        }
        if (null !== ($v = $this->getIdentityCertificate())) {
            if ([] !== ($fieldErrs = $v->_getValidationErrors())) {
                $errs[self::FIELD_IDENTITY_CERTIFICATE] = $fieldErrs;
            }
        }
        if (null !== ($v = $this->getOrganization())) {
            if ([] !== ($fieldErrs = $v->_getValidationErrors())) {
                $errs[self::FIELD_ORGANIZATION] = $fieldErrs;
            }
        }
        if (isset($validationRules[self::FIELD_ATTESTATION_SIGNATURE])) {
            $v = $this->getAttestationSignature();
            foreach($validationRules[self::FIELD_ATTESTATION_SIGNATURE] as $rule => $constraint) {
                $err = $this->_performValidation(PHPFHIRConstants::TYPE_NAME_VERIFICATION_RESULT_DOT_VALIDATOR, self::FIELD_ATTESTATION_SIGNATURE, $rule, $constraint, $v);
                if (null !== $err) {
                    if (!isset($errs[self::FIELD_ATTESTATION_SIGNATURE])) {
                        $errs[self::FIELD_ATTESTATION_SIGNATURE] = [];
                    }
                    $errs[self::FIELD_ATTESTATION_SIGNATURE][$rule] = $err;
                }
            }
        }
        if (isset($validationRules[self::FIELD_IDENTITY_CERTIFICATE])) {
            $v = $this->getIdentityCertificate();
            foreach($validationRules[self::FIELD_IDENTITY_CERTIFICATE] as $rule => $constraint) {
                $err = $this->_performValidation(PHPFHIRConstants::TYPE_NAME_VERIFICATION_RESULT_DOT_VALIDATOR, self::FIELD_IDENTITY_CERTIFICATE, $rule, $constraint, $v);
                if (null !== $err) {
                    if (!isset($errs[self::FIELD_IDENTITY_CERTIFICATE])) {
                        $errs[self::FIELD_IDENTITY_CERTIFICATE] = [];
                    }
                    $errs[self::FIELD_IDENTITY_CERTIFICATE][$rule] = $err;
                }
            }
        }
        if (isset($validationRules[self::FIELD_ORGANIZATION])) {
            $v = $this->getOrganization();
            foreach($validationRules[self::FIELD_ORGANIZATION] as $rule => $constraint) {
                $err = $this->_performValidation(PHPFHIRConstants::TYPE_NAME_VERIFICATION_RESULT_DOT_VALIDATOR, self::FIELD_ORGANIZATION, $rule, $constraint, $v);
                if (null !== $err) {
                    if (!isset($errs[self::FIELD_ORGANIZATION])) {
                        $errs[self::FIELD_ORGANIZATION] = [];
                    }
                    $errs[self::FIELD_ORGANIZATION][$rule] = $err;
                }
            }
        }
        if (isset($validationRules[self::FIELD_MODIFIER_EXTENSION])) {
            $v = $this->getModifierExtension();
            foreach($validationRules[self::FIELD_MODIFIER_EXTENSION] as $rule => $constraint) {
                $err = $this->_performValidation(PHPFHIRConstants::TYPE_NAME_BACKBONE_ELEMENT, self::FIELD_MODIFIER_EXTENSION, $rule, $constraint, $v);
                if (null !== $err) {
                    if (!isset($errs[self::FIELD_MODIFIER_EXTENSION])) {
                        $errs[self::FIELD_MODIFIER_EXTENSION] = [];
                    }
                    $errs[self::FIELD_MODIFIER_EXTENSION][$rule] = $err;
                }
            }
        }
        if (isset($validationRules[self::FIELD_EXTENSION])) {
            $v = $this->getExtension();
            foreach($validationRules[self::FIELD_EXTENSION] as $rule => $constraint) {
                $err = $this->_performValidation(PHPFHIRConstants::TYPE_NAME_ELEMENT, self::FIELD_EXTENSION, $rule, $constraint, $v);
                if (null !== $err) {
                    if (!isset($errs[self::FIELD_EXTENSION])) {
                        $errs[self::FIELD_EXTENSION] = [];
                    }
                    $errs[self::FIELD_EXTENSION][$rule] = $err;
                }
            }
        }
        if (isset($validationRules[self::FIELD_ID])) {
            $v = $this->getId();
            foreach($validationRules[self::FIELD_ID] as $rule => $constraint) {
                $err = $this->_performValidation(PHPFHIRConstants::TYPE_NAME_ELEMENT, self::FIELD_ID, $rule, $constraint, $v);
                if (null !== $err) {
                    if (!isset($errs[self::FIELD_ID])) {
                        $errs[self::FIELD_ID] = [];
                    }
                    $errs[self::FIELD_ID][$rule] = $err;
                }
            }
        }
        return $errs;
    }

    /**
     * @param \SimpleXMLElement|string|null $sxe
     * @param null|\DCarbone\PHPFHIRGenerated\R4\FHIRElement\FHIRBackboneElement\FHIRVerificationResult\FHIRVerificationResultValidator $type
     * @param null|int $libxmlOpts
     * @return null|\DCarbone\PHPFHIRGenerated\R4\FHIRElement\FHIRBackboneElement\FHIRVerificationResult\FHIRVerificationResultValidator
     */
    public static function xmlUnserialize($sxe = null, PHPFHIRTypeInterface $type = null, $libxmlOpts = 591872)
    {
        if (null === $sxe) {
            return null;
        }
        if (is_string($sxe)) {
            libxml_use_internal_errors(true);
            $sxe = new \SimpleXMLElement($sxe, $libxmlOpts, false);
            if ($sxe === false) {
                throw new \DomainException(sprintf('FHIRVerificationResultValidator::xmlUnserialize - String provided is not parseable as XML: %s', implode(', ', array_map(function(\libXMLError $err) { return $err->message; }, libxml_get_errors()))));
            }
            libxml_use_internal_errors(false);
        }
        if (!($sxe instanceof \SimpleXMLElement)) {
            throw new \InvalidArgumentException(sprintf('FHIRVerificationResultValidator::xmlUnserialize - $sxe value must be null, \\SimpleXMLElement, or valid XML string, %s seen', gettype($sxe)));
        }
        if (null === $type) {
            $type = new FHIRVerificationResultValidator;
        } elseif (!is_object($type) || !($type instanceof FHIRVerificationResultValidator)) {
            throw new \RuntimeException(sprintf(
                'FHIRVerificationResultValidator::xmlUnserialize - $type must be instance of \DCarbone\PHPFHIRGenerated\R4\FHIRElement\FHIRBackboneElement\FHIRVerificationResult\FHIRVerificationResultValidator or null, %s seen.',
                is_object($type) ? get_class($type) : gettype($type)
            ));
        }
        FHIRBackboneElement::xmlUnserialize($sxe, $type);
        $xmlNamespaces = $sxe->getDocNamespaces(false, false);
        if ([] !== $xmlNamespaces) {
            $ns = reset($xmlNamespaces);
            if (false !== $ns && '' !== $ns) {
                $type->_xmlns = $ns;
            }
        }
        $attributes = $sxe->attributes();
        $children = $sxe->children();
        if (isset($children->attestationSignature)) {
            $type->setAttestationSignature(FHIRSignature::xmlUnserialize($children->attestationSignature));
        }
        if (isset($children->identityCertificate)) {
            $type->setIdentityCertificate(FHIRString::xmlUnserialize($children->identityCertificate));
        }
        if (isset($attributes->identityCertificate)) {
            $pt = $type->getIdentityCertificate();
            if (null !== $pt) {
                $pt->setValue((string)$attributes->identityCertificate);
            } else {
                $type->setIdentityCertificate((string)$attributes->identityCertificate);
            }
        }
        if (isset($children->organization)) {
            $type->setOrganization(FHIRReference::xmlUnserialize($children->organization));
        }
        return $type;
    }

    /**
     * @param null|\SimpleXMLElement $sxe
     * @param null|int $libxmlOpts
     * @return \SimpleXMLElement
     */
    public function xmlSerialize(\SimpleXMLElement $sxe = null, $libxmlOpts = 591872)
    {
        if (null === $sxe) {
            $sxe = new \SimpleXMLElement($this->_getFHIRXMLElementDefinition(), $libxmlOpts, false);
        }
        parent::xmlSerialize($sxe);
        if (null !== ($v = $this->getAttestationSignature())) {
            $v->xmlSerialize($sxe->addChild(self::FIELD_ATTESTATION_SIGNATURE, null, $v->_getFHIRXMLNamespace()));
        }
        if (null !== ($v = $this->getIdentityCertificate())) {
            $v->xmlSerialize($sxe->addChild(self::FIELD_IDENTITY_CERTIFICATE, null, $v->_getFHIRXMLNamespace()));
        }
        if (null !== ($v = $this->getOrganization())) {
            $v->xmlSerialize($sxe->addChild(self::FIELD_ORGANIZATION, null, $v->_getFHIRXMLNamespace()));
        }
        return $sxe;
    }

    /**
     * @return array
     */
    public function jsonSerialize()
    {
        $a = parent::jsonSerialize();
        if (null !== ($v = $this->getAttestationSignature())) {
            $a[self::FIELD_ATTESTATION_SIGNATURE] = $v;
        }
        if (null !== ($v = $this->getIdentityCertificate())) {
            $a[self::FIELD_IDENTITY_CERTIFICATE] = $v->getValue();
            $enc = $v->jsonSerialize();
            $cnt = count($enc);
            if (0 < $cnt && (1 !== $cnt || (1 === $cnt && !array_key_exists(FHIRString::FIELD_VALUE, $enc)))) {
                unset($enc[FHIRString::FIELD_VALUE]);
                $a[self::FIELD_IDENTITY_CERTIFICATE_EXT] = $enc;
            }
        }
        if (null !== ($v = $this->getOrganization())) {
            $a[self::FIELD_ORGANIZATION] = $v;
        }
        if ([] !== ($vs = $this->_getFHIRComments())) {
            $a[PHPFHIRConstants::JSON_FIELD_FHIR_COMMENTS] = $vs;
        }
        return $a;
    }

    /**
     * @return string
     */
    public function __toString()
    {
        return self::FHIR_TYPE_NAME;
    }
}