text:
<?php

class API {

	/**
	 * API wrapper that all of the calls will go through.
	 *
	 * @var CApiWrapper
	 */
	private static $wrapper;

	/**
	 * Factory for creating API services.
	 *
	 * @var CRegistryFactory
	 */
	private static $apiServiceFactory;

	/**
	 * Sets the API wrapper.
	 *
	 * @param CApiWrapper $wrapper
	 */
	public static function setWrapper(CApiWrapper $wrapper = null) {
		self::$wrapper = $wrapper;
	}

	/**
	 * Set the service factory.
	 *
	 * @param CRegistryFactory $factory
	 */
	public static function setApiServiceFactory(CRegistryFactory $factory) {
		self::$apiServiceFactory = $factory;
	}

	/**
	 * Returns the API wrapper.
	 *
	 * @return CApiWrapper
	 */
	public static function getWrapper() {
		return self::$wrapper;
	}

	/**
	 * Returns an object that can be used for making API calls.  If a wrapper is used, returns a CApiWrapper,
	 * otherwise - returns a CApiService object.
	 *
	 * @param $name
	 *
	 * @return CApiWrapper|CApiService
	 */
	public static function getApi($name) {
		if (self::$wrapper) {
			self::$wrapper->api = $name;

			return self::$wrapper;
		}
		else {
			return self::getApiService($name);
		}
	}

	/**
	 * Returns the CApiInstance object for the requested API.
	 *
	 * NOTE: This method must only be called from other CApiService objects.
	 *
	 * @param string $name
	 *
	 * @return CApiService
	 */
	public static function getApiService($name = null) {
		return self::$apiServiceFactory->getObject($name ? $name : 'api');
	}

	/**
	 * @return CAction
	 */
	public static function Action() {
		return self::getApi('action');
	}

	/**
	 * @return CAlert
	 */
	public static function Alert() {
		return self::getApi('alert');
	}

	/**
	 * @return CAPIInfo
	 */
	public static function APIInfo() {
		return self::getApi('apiinfo');
	}

	/**
	 * @return CApplication
	 */
	public static function Application() {
		return self::getApi('application');
	}

	/**
	 * @return CConfiguration
	 */
	public static function Configuration() {
		return self::getApi('configuration');
	}

	/**
	 * @return CCorrelation
	 */
	public static function Correlation() {
		return self::getApi('correlation');
	}

	/**
	 * @return CDCheck
	 */
	public static function DCheck() {
		return self::getApi('dcheck');
	}

	/**
	 * @return CDHost
	 */
	public static function DHost() {
		return self::getApi('dhost');
	}

	/**
	 * @return CDiscoveryRule
	 */
	public static function DiscoveryRule() {
		return self::getApi('discoveryrule');
	}

	/**
	 * @return CDRule
	 */
	public static function DRule() {
		return self::getApi('drule');
	}

	/**
	 * @return CDService
	 */
	public static function DService() {
		return self::getApi('dservice');
	}

	/**
	 * @return CEvent
	 */
	public static function Event() {
		return self::getApi('event');
	}

	/**
	 * @return CGraph
	 */
	public static function Graph() {
		return self::getApi('graph');
	}

	/**
	 * @return CGraphItem
	 */
	public static function GraphItem() {
		return self::getApi('graphitem');
	}

	/**
	 * @return CGraphPrototype
	 */
	public static function GraphPrototype() {
		return self::getApi('graphprototype');
	}

	/**
	 * @return CHistory
	 */
	public static function History() {
		return self::getApi('history');
	}

	/**
	 * @return CHost
	 */
	public static function Host() {
		return self::getApi('host');
	}

	/**
	 * @return CHostPrototype
	 */
	public static function HostPrototype() {
		return self::getApi('hostprototype');
	}

	/**
	 * @return CHostGroup
	 */
	public static function HostGroup() {
		return self::getApi('hostgroup');
	}

	/**
	 * @return CHostInterface
	 */
	public static function HostInterface() {
		return self::getApi('hostinterface');
	}

	/**
	 * @return CImage
	 */
	public static function Image() {
		return self::getApi('image');
	}

	/**
	 * @return CIconMap
	 */
	public static function IconMap() {
		return self::getApi('iconmap');
	}

	/**
	 * @return CItem
	 */
	public static function Item() {
		return self::getApi('item');
	}

	/**
	 * @return CItemPrototype
	 */
	public static function ItemPrototype() {
		return self::getApi('itemprototype');
	}

	/**
	 * @return CMaintenance
	 */
	public static function Maintenance() {
		return self::getApi('maintenance');
	}

	/**
	 * @return CMap
	 */
	public static function Map() {
		return self::getApi('map');
	}

	/**
	 * @return CMediaType
	 */
	public static function MediaType() {
		return self::getApi('mediatype');
	}

	/**
	 * @return CProblem
	 */
	public static function Problem() {
		return self::getApi('problem');
	}

	/**
	 * @return CProxy
	 */
	public static function Proxy() {
		return self::getApi('proxy');
	}

	/**
	 * @return CService
	 */
	public static function Service() {
		return self::getApi('service');
	}

	/**
	 * @return CScreen
	 */
	public static function Screen() {
		return self::getApi('screen');
	}

	/**
	 * @return CScreenItem
	 */
	public static function ScreenItem() {
		return self::getApi('screenitem');
	}

	/**
	 * @return CScript
	 */
	public static function Script() {
		return self::getApi('script');
	}

	/**
	 * @return CTemplate
	 */
	public static function Template() {
		return self::getApi('template');
	}

	/**
	 * @return CTemplateScreen
	 */
	public static function TemplateScreen() {
		return self::getApi('templatescreen');
	}

	/**
	 * @return CTemplateScreenItem
	 */
	public static function TemplateScreenItem() {
		return self::getApi('templatescreenitem');
	}

	/**
	 * @return CTrend
	 */
	public static function Trend() {
		return self::getApi('trend');
	}

	/**
	 * @return CTrigger
	 */
	public static function Trigger() {
		return self::getApi('trigger');
	}

	/**
	 * @return CTriggerPrototype
	 */
	public static function TriggerPrototype() {
		return self::getApi('triggerprototype');
	}

	/**
	 * @return CUser
	 */
	public static function User() {
		return self::getApi('user');
	}

	/**
	 * @return CUserGroup
	 */
	public static function UserGroup() {
		return self::getApi('usergroup');
	}

	/**
	 * @return CUserMacro
	 */
	public static function UserMacro() {
		return self::getApi('usermacro');
	}

	/**
	 * @return CUserMedia
	 */
	public static function UserMedia() {
		return self::getApi('usermedia');
	}

	/**
	 * @return CValueMap
	 */
	public static function ValueMap() {
		return self::getApi('valuemap');
	}

	/**
	 * @return CHttpTest
	 */
	public static function HttpTest() {
		return self::getApi('httptest');
	}
}


text:
/* Freely adapted from the Aurora version of the terrain compressor.
 * Copyright (c) Contributors, http://aurora-sim.org/, http://opensimulator.org/
 */

using System;
using System.Reflection;

using log4net;

using OpenSim.Framework;
using OpenSim.Region.Framework;
using OpenSim.Region.Framework.Scenes;

using OpenMetaverse;
using OpenMetaverse.Packets;

namespace OpenSim.Region.ClientStack.LindenUDP
{
    public static class OpenSimTerrainCompressor
    {
//        private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);

#pragma warning disable 414
        private static string LogHeader = "[TERRAIN COMPRESSOR]";
#pragma warning restore 414

        public const int END_OF_PATCHES = 97;

        private const float OO_SQRT2 = 0.7071067811865475244008443621049f;
        private const int STRIDE = 264;

        private const int ZERO_CODE = 0x0;
        private const int ZERO_EOB = 0x2;
        private const int POSITIVE_VALUE = 0x6;
        private const int NEGATIVE_VALUE = 0x7;

        private static readonly float[] DequantizeTable16 =
            new float[Constants.TerrainPatchSize*Constants.TerrainPatchSize];

        private static readonly float[] DequantizeTable32 =
            new float[Constants.TerrainPatchSize*Constants.TerrainPatchSize];

        private static readonly float[] CosineTable16 = new float[Constants.TerrainPatchSize*Constants.TerrainPatchSize];
        //private static readonly float[] CosineTable32 = new float[Constants.TerrainPatchSize * Constants.TerrainPatchSize];
        private static readonly int[] CopyMatrix16 = new int[Constants.TerrainPatchSize*Constants.TerrainPatchSize];
        private static readonly int[] CopyMatrix32 = new int[Constants.TerrainPatchSize*Constants.TerrainPatchSize];

        private static readonly float[] QuantizeTable16 =
            new float[Constants.TerrainPatchSize*Constants.TerrainPatchSize];

        static OpenSimTerrainCompressor()
        {
            // Initialize the decompression tables
            BuildDequantizeTable16();
            SetupCosines16();
            BuildCopyMatrix16();
            BuildQuantizeTable16();
        }

        // Used to send cloud and wind patches
        public static LayerDataPacket CreateLayerDataPacket(TerrainPatch[] patches, byte type, int pRegionSizeX,
                                                            int pRegionSizeY)
        {
            LayerDataPacket layer = new LayerDataPacket {LayerID = {Type = type}};

            TerrainPatch.GroupHeader header = new TerrainPatch.GroupHeader
                                                  {Stride = STRIDE, PatchSize = Constants.TerrainPatchSize};

            // Should be enough to fit even the most poorly packed data
            byte[] data = new byte[patches.Length*Constants.TerrainPatchSize*Constants.TerrainPatchSize*2];
            BitPack bitpack = new BitPack(data, 0);
            bitpack.PackBits(header.Stride, 16);
            bitpack.PackBits(header.PatchSize, 8);
            bitpack.PackBits(type, 8);

            foreach (TerrainPatch t in patches)
                CreatePatch(bitpack, t.Data, t.X, t.Y, pRegionSizeX, pRegionSizeY);

            bitpack.PackBits(END_OF_PATCHES, 8);

            layer.LayerData.Data = new byte[bitpack.BytePos + 1];
            Buffer.BlockCopy(bitpack.Data, 0, layer.LayerData.Data, 0, bitpack.BytePos + 1);

            return layer;
        }

        // Create a land packet for a single patch.
        public static LayerDataPacket CreateLandPacket(TerrainData terrData, int patchX, int patchY)
        {
            int[] xPieces = new int[1];
            int[] yPieces = new int[1];
            xPieces[0] = patchX;  // patch X dimension
            yPieces[0] = patchY;

            byte landPacketType = (byte)TerrainPatch.LayerType.Land;
            if (terrData.SizeX > Constants.RegionSize || terrData.SizeY > Constants.RegionSize)
            {
                landPacketType = (byte)TerrainPatch.LayerType.LandExtended;
            }

            return CreateLandPacket(terrData, xPieces, yPieces, landPacketType);
        }

        /// <summary>
        ///     Creates a LayerData packet for compressed land data given a full
        ///     simulator heightmap and an array of indices of patches to compress
        /// </summary>
        /// <param name="terrData">
        ///     Terrain data that can result in a meter square heightmap.
        /// </param>
        /// <param name="x">
        ///     Array of indexes in the grid of patches
        ///     for this simulator.
        ///     If creating a packet for multiple patches, there will be entries in
        ///     both the X and Y arrays for each of the patches.
        ///     For example if patches 1 and 17 are to be sent,
        ///     x[] = {1,1} and y[] = {0,1} which specifies the patches at
        ///     indexes <1,0> and <1,1> (presuming the terrain size is 16x16 patches).
        /// </param>
        /// <param name="y">
        ///     Array of indexes in the grid of patches.
        /// </param>
        /// <param name="type"></param>
        /// <param name="pRegionSizeX"></param>
        /// <param name="pRegionSizeY"></param>
        /// <returns></returns>
        public static LayerDataPacket CreateLandPacket(TerrainData terrData, int[] x, int[] y, byte type)
        {
            LayerDataPacket layer = new LayerDataPacket {LayerID = {Type = type}};

            TerrainPatch.GroupHeader header = new TerrainPatch.GroupHeader
                                                  {Stride = STRIDE, PatchSize = Constants.TerrainPatchSize};

            byte[] data = new byte[x.Length * Constants.TerrainPatchSize * Constants.TerrainPatchSize * 2];
            BitPack bitpack = new BitPack(data, 0);
            bitpack.PackBits(header.Stride, 16);
            bitpack.PackBits(header.PatchSize, 8);
            bitpack.PackBits(type, 8);

            for (int i = 0; i < x.Length; i++)
                CreatePatchFromHeightmap(bitpack, terrData, x[i], y[i]);

            bitpack.PackBits(END_OF_PATCHES, 8);

            layer.LayerData.Data = new byte[bitpack.BytePos + 1];
            Buffer.BlockCopy(bitpack.Data, 0, layer.LayerData.Data, 0, bitpack.BytePos + 1);

            return layer;
        }

        // Unused: left for historical reference.
        public static void CreatePatch(BitPack output, float[] patchData, int x, int y, int pRegionSizeX, int pRegionSizeY)
        {
            TerrainPatch.Header header = PrescanPatch(patchData);
            header.QuantWBits = 136;
            if (pRegionSizeX > Constants.RegionSize || pRegionSizeY > Constants.RegionSize)
            {
                header.PatchIDs = (y & 0xFFFF);
                header.PatchIDs += (x << 16);
            }
            else
            {
                header.PatchIDs = (y & 0x1F);
                header.PatchIDs += (x << 5);
            }

            // NOTE: No idea what prequant and postquant should be or what they do

            int wbits;
            int[] patch = CompressPatch(patchData, header, 10, out wbits);
            wbits = EncodePatchHeader(output, header, patch, Constants.RegionSize, Constants.RegionSize, wbits);
            EncodePatch(output, patch, 0, wbits);
        }

        /// <summary>
        ///     Add a patch of terrain to a BitPacker
        /// </summary>
        /// <param name="output">BitPacker to write the patch to</param>
        /// <param name="heightmap">
        ///     Heightmap of the simulator. Presumed to be an sizeX*sizeY array.
        /// </param>
        /// <param name="patchX">
        ///     X offset of the patch to create.
        /// </param>
        /// <param name="patchY">
        ///     Y offset of the patch to create.
        /// </param>
        /// <param name="pRegionSizeX"></param>
        /// <param name="pRegionSizeY"></param>
        public static void CreatePatchFromHeightmap(BitPack output, TerrainData terrData, int patchX, int patchY)
        {
            TerrainPatch.Header header = PrescanPatch(terrData, patchX, patchY);
            header.QuantWBits = 136;

            // If larger than legacy region size, pack patch X and Y info differently.
            if (terrData.SizeX > Constants.RegionSize || terrData.SizeY > Constants.RegionSize)
            {
                header.PatchIDs = (patchY & 0xFFFF);
                header.PatchIDs += (patchX << 16);
            }
            else
            {
                header.PatchIDs = (patchY & 0x1F);
                header.PatchIDs += (patchX << 5);
            }

            // m_log.DebugFormat("{0} CreatePatchFromHeightmap. patchX={1}, patchY={2}, DCOffset={3}, range={4}",
            //                         LogHeader, patchX, patchY, header.DCOffset, header.Range);

            // NOTE: No idea what prequant and postquant should be or what they do
            int wbits;
            int[] patch = CompressPatch(terrData, patchX, patchY, header, 10, out wbits);
            wbits = EncodePatchHeader(output, header, patch, (uint)terrData.SizeX, (uint)terrData.SizeY, wbits);
            EncodePatch(output, patch, 0, wbits);
        }

        private static TerrainPatch.Header PrescanPatch(float[] patch)
        {
            TerrainPatch.Header header = new TerrainPatch.Header();
            float zmax = -99999999.0f;
            float zmin = 99999999.0f;

            for (int i = 0; i < Constants.TerrainPatchSize*Constants.TerrainPatchSize; i++)
            {
                float val = patch[i];
                if (val > zmax) zmax = val;
                if (val < zmin) zmin = val;
            }

            header.DCOffset = zmin;
            header.Range = (int) ((zmax - zmin) + 1.0f);

            return header;
        }

        // Scan the height info we're returning and return a patch packet header for this patch.
        private static TerrainPatch.Header PrescanPatch(TerrainData terrData, int patchX, int patchY)
        {
            TerrainPatch.Header header = new TerrainPatch.Header();
            float zmax = -99999999.0f;
            float zmin = 99999999.0f;

            for (int j = patchY*Constants.TerrainPatchSize; j < (patchY + 1)*Constants.TerrainPatchSize; j++)
            {
                for (int i = patchX*Constants.TerrainPatchSize; i < (patchX + 1)*Constants.TerrainPatchSize; i++)
                {
                    float val = terrData[i, j];
                    if (val > zmax) zmax = val;
                    if (val < zmin) zmin = val;
                }
            }

            header.DCOffset = zmin;
            header.Range = (int)((zmax - zmin) + 1.0f);

            return header;
        }

        public static TerrainPatch.Header DecodePatchHeader(BitPack bitpack)
        {
            TerrainPatch.Header header = new TerrainPatch.Header {QuantWBits = bitpack.UnpackBits(8)};

            // Quantized word bits
            if (header.QuantWBits == END_OF_PATCHES)
                return header;

            // DC offset
            header.DCOffset = bitpack.UnpackFloat();

            // Range
            header.Range = bitpack.UnpackBits(16);

            // Patch IDs (10 bits)
            header.PatchIDs = bitpack.UnpackBits(10);

            // Word bits
            header.WordBits = (uint) ((header.QuantWBits & 0x0f) + 2);

            return header;
        }

        private static int EncodePatchHeader(BitPack output, TerrainPatch.Header header, int[] patch, uint pRegionSizeX,
                                             uint pRegionSizeY, int wbits)
        {
            /*
                    int temp;
                    int wbits = (header.QuantWBits & 0x0f) + 2;
                    uint maxWbits = (uint)wbits + 5;
                    uint minWbits = ((uint)wbits >> 1);
                    int wbitsMaxValue;
        */
            // goal is to determ minimum number of bits to use so all data fits
            /*
                    wbits = (int)minWbits;
                    wbitsMaxValue = (1 << wbits);

                    for (int i = 0; i < patch.Length; i++)
                    {
                        temp = patch[i];
                        if (temp != 0)
                        {
                            // Get the absolute value
                            if (temp < 0) temp *= -1;

         no coments..

                            for (int j = (int)maxWbits; j > (int)minWbits; j--)
                            {
                                if ((temp & (1 << j)) != 0)
                                {
                                    if (j > wbits) wbits = j;
                                    break;
                                }
                            }

                            while (temp > wbitsMaxValue)
                                {
                                wbits++;
                                if (wbits == maxWbits)
                                    goto Done;
                                wbitsMaxValue = 1 << wbits;
                                }
                        }
                    }

                Done:

                    //            wbits += 1;
         */
            // better check
            if (wbits > 17)
                wbits = 16;
            else if (wbits < 3)
                wbits = 3;

            header.QuantWBits &= 0xf0;

            header.QuantWBits |= (wbits - 2);

            output.PackBits(header.QuantWBits, 8);
            output.PackFloat(header.DCOffset);
            output.PackBits(header.Range, 16);
            if (pRegionSizeX > Constants.RegionSize || pRegionSizeY > Constants.RegionSize)
                output.PackBits(header.PatchIDs, 32);
            else
                output.PackBits(header.PatchIDs, 10);

            return wbits;
        }

        private static void IDCTColumn16(float[] linein, float[] lineout, int column)
        {
            for (int n = 0; n < Constants.TerrainPatchSize; n++)
            {
                float total = OO_SQRT2*linein[column];

                for (int u = 1; u < Constants.TerrainPatchSize; u++)
                {
                    int usize = u*Constants.TerrainPatchSize;
                    total += linein[usize + column]*CosineTable16[usize + n];
                }

                lineout[Constants.TerrainPatchSize*n + column] = total;
            }
        }

        private static void IDCTLine16(float[] linein, float[] lineout, int line)
        {
            const float oosob = 2.0f/Constants.TerrainPatchSize;
            int lineSize = line*Constants.TerrainPatchSize;

            for (int n = 0; n < Constants.TerrainPatchSize; n++)
            {
                float total = OO_SQRT2*linein[lineSize];

                for (int u = 1; u < Constants.TerrainPatchSize; u++)
                {
                    total += linein[lineSize + u]*CosineTable16[u*Constants.TerrainPatchSize + n];
                }

                lineout[lineSize + n] = total*oosob;
            }
        }

/*
        private static void DCTLine16(float[] linein, float[] lineout, int line)
        {
            float total = 0.0f;
            int lineSize = line * Constants.TerrainPatchSize;

            for (int n = 0; n < Constants.TerrainPatchSize; n++)
            {
                total += linein[lineSize + n];
            }

            lineout[lineSize] = OO_SQRT2 * total;

            int uptr = 0;
            for (int u = 1; u < Constants.TerrainPatchSize; u++)
            {
                total = 0.0f;
                uptr += Constants.TerrainPatchSize;

                for (int n = 0; n < Constants.TerrainPatchSize; n++)
                {
                    total += linein[lineSize + n] * CosineTable16[uptr + n];
                }

                lineout[lineSize + u] = total;
            }
        }
*/

        private static void DCTLine16(float[] linein, float[] lineout, int line)
        {
            // outputs transpose data (lines exchanged with coluns )
            // so to save a bit of cpu when doing coluns
            float total = 0.0f;
            int lineSize = line*Constants.TerrainPatchSize;

            for (int n = 0; n < Constants.TerrainPatchSize; n++)
            {
                total += linein[lineSize + n];
            }

            lineout[line] = OO_SQRT2*total;

            for (int u = Constants.TerrainPatchSize;
                 u < Constants.TerrainPatchSize*Constants.TerrainPatchSize;
                 u += Constants.TerrainPatchSize)
            {
                total = 0.0f;
                for (int ptrn = lineSize, ptru = u; ptrn < lineSize + Constants.TerrainPatchSize; ptrn++,ptru++)
                {
                    total += linein[ptrn]*CosineTable16[ptru];
                }

                lineout[line + u] = total;
            }
        }

        /*
                private static void DCTColumn16(float[] linein, int[] lineout, int column)
                {
                    float total = 0.0f;
        //            const float oosob = 2.0f / Constants.TerrainPatchSize;

                    for (int n = 0; n < Constants.TerrainPatchSize; n++)
                    {
                        total += linein[Constants.TerrainPatchSize * n + column];
                    }

        //            lineout[CopyMatrix16[column]] = (int)(OO_SQRT2 * total * oosob * QuantizeTable16[column]);
                    lineout[CopyMatrix16[column]] = (int)(OO_SQRT2 * total * QuantizeTable16[column]);

                    for (int uptr = Constants.TerrainPatchSize; uptr < Constants.TerrainPatchSize * Constants.TerrainPatchSize; uptr += Constants.TerrainPatchSize)
                    {
                        total = 0.0f;

                        for (int n = 0; n < Constants.TerrainPatchSize; n++)
                        {
                            total += linein[Constants.TerrainPatchSize * n + column] * CosineTable16[uptr + n];
                        }

        //                lineout[CopyMatrix16[Constants.TerrainPatchSize * u + column]] = (int)(total * oosob * QuantizeTable16[Constants.TerrainPatchSize * u + column]);
                        lineout[CopyMatrix16[uptr + column]] = (int)(total * QuantizeTable16[uptr + column]);
                        }
                }

        private static void DCTColumn16(float[] linein, int[] lineout, int column)
        {
            // input columns are in fact stored in lines now

            float total = 0.0f;
//            const float oosob = 2.0f / Constants.TerrainPatchSize;
            int inlinesptr = Constants.TerrainPatchSize*column;

            for (int n = 0; n < Constants.TerrainPatchSize; n++)
            {
                total += linein[inlinesptr + n];
            }

            //            lineout[CopyMatrix16[column]] = (int)(OO_SQRT2 * total * oosob * QuantizeTable16[column]);
            lineout[CopyMatrix16[column]] = (int) (OO_SQRT2*total*QuantizeTable16[column]);

            for (int uptr = Constants.TerrainPatchSize;
                 uptr < Constants.TerrainPatchSize*Constants.TerrainPatchSize;
                 uptr += Constants.TerrainPatchSize)
            {
                total = 0.0f;

                for (int n = inlinesptr, ptru = uptr; n < inlinesptr + Constants.TerrainPatchSize; n++, ptru++)
                {
                    total += linein[n]*CosineTable16[ptru];
                }

//                lineout[CopyMatrix16[Constants.TerrainPatchSize * u + column]] = (int)(total * oosob * QuantizeTable16[Constants.TerrainPatchSize * u + column]);
                lineout[CopyMatrix16[uptr + column]] = (int) (total*QuantizeTable16[uptr + column]);
            }
        }
        */

        private static int DCTColumn16Wbits(float[] linein, int[] lineout, int column, int wbits, int maxwbits)
        {
            // input columns are in fact stored in lines now

            bool dowbits = wbits != maxwbits;
            int wbitsMaxValue = 1 << wbits;

            float total = 0.0f;
            //            const float oosob = 2.0f / Constants.TerrainPatchSize;
            int inlinesptr = Constants.TerrainPatchSize*column;

            for (int n = 0; n < Constants.TerrainPatchSize; n++)
            {
                total += linein[inlinesptr + n];
            }

            //            lineout[CopyMatrix16[column]] = (int)(OO_SQRT2 * total * oosob * QuantizeTable16[column]);
            int tmp = (int) (OO_SQRT2*total*QuantizeTable16[column]);
            lineout[CopyMatrix16[column]] = tmp;

            if (dowbits)
            {
                if (tmp < 0) tmp *= -1;
                while (tmp > wbitsMaxValue)
                {
                    wbits++;
                    wbitsMaxValue = 1 << wbits;
                    if (wbits == maxwbits)
                    {
                        dowbits = false;
                        break;
                    }
                }
            }

            for (int uptr = Constants.TerrainPatchSize;
                 uptr < Constants.TerrainPatchSize*Constants.TerrainPatchSize;
                 uptr += Constants.TerrainPatchSize)
            {
                total = 0.0f;

                for (int n = inlinesptr, ptru = uptr; n < inlinesptr + Constants.TerrainPatchSize; n++, ptru++)
                {
                    total += linein[n]*CosineTable16[ptru];
                }

                tmp = (int) (total*QuantizeTable16[uptr + column]);
                lineout[CopyMatrix16[uptr + column]] = tmp;

                if (dowbits)
                {
                    if (tmp < 0) tmp *= -1;
                    while (tmp > wbitsMaxValue)
                    {
                        wbits++;
                        wbitsMaxValue = 1 << wbits;
                        if (wbits == maxwbits)
                        {
                            dowbits = false;
                            break;
                        }
                    }
                }
            }
            return wbits;
        }

        public static void DecodePatch(int[] patches, BitPack bitpack, TerrainPatch.Header header, int size)
        {
            for (int n = 0; n < size*size; n++)
            {
                // ?
                int temp = bitpack.UnpackBits(1);
                if (temp != 0)
                {
                    // Value or EOB
                    temp = bitpack.UnpackBits(1);
                    if (temp != 0)
                    {
                        // Value
                        temp = bitpack.UnpackBits(1);
                        if (temp != 0)
                        {
                            // Negative
                            temp = bitpack.UnpackBits((int) header.WordBits);
                            patches[n] = temp*-1;
                        }
                        else
                        {
                            // Positive
                            temp = bitpack.UnpackBits((int) header.WordBits);
                            patches[n] = temp;
                        }
                    }
                    else
                    {
                        // Set the rest to zero
                        // TODO: This might not be necessary
                        for (int o = n; o < size*size; o++)
                        {
                            patches[o] = 0;
                        }
                        break;
                    }
                }
                else
                {
                    patches[n] = 0;
                }
            }
        }

        private static void EncodePatch(BitPack output, int[] patch, int postquant, int wbits)
        {
            int maxwbitssize = (1 << wbits) - 1;

            if (postquant > Constants.TerrainPatchSize*Constants.TerrainPatchSize || postquant < 0)
            {
                Logger.Log("Postquant is outside the range of allowed values in EncodePatch()", Helpers.LogLevel.Error);
                return;
            }

            if (postquant != 0) patch[Constants.TerrainPatchSize*Constants.TerrainPatchSize - postquant] = 0;

            for (int i = 0; i < Constants.TerrainPatchSize*Constants.TerrainPatchSize; i++)
            {
                int temp = patch[i];

                if (temp == 0)
                {
                    bool eob = true;

                    for (int j = i; j < Constants.TerrainPatchSize*Constants.TerrainPatchSize - postquant; j++)
                    {
                        if (patch[j] != 0)
                        {
                            eob = false;
                            break;
                        }
                    }

                    if (eob)
                    {
                        output.PackBits(ZERO_EOB, 2);
                        return;
                    }
                    output.PackBits(ZERO_CODE, 1);
                }
                else
                {
                    if (temp < 0)
                    {
                        temp *= -1;

                        if (temp > maxwbitssize) temp = maxwbitssize;

                        output.PackBits(NEGATIVE_VALUE, 3);
                        output.PackBits(temp, wbits);
                    }
                    else
                    {
                        if (temp > maxwbitssize) temp = maxwbitssize;

                        output.PackBits(POSITIVE_VALUE, 3);
                        output.PackBits(temp, wbits);
                    }
                }
            }
        }

        public static float[] DecompressPatch(int[] patches, TerrainPatch.Header header, TerrainPatch.GroupHeader group)
        {
            float[] block = new float[group.PatchSize*group.PatchSize];
            float[] output = new float[group.PatchSize*group.PatchSize];
            int prequant = (header.QuantWBits >> 4) + 2;
            int quantize = 1 << prequant;
            float ooq = 1.0f/quantize;
            float mult = ooq*header.Range;
            float addval = mult*(1 << (prequant - 1)) + header.DCOffset;

            if (group.PatchSize == Constants.TerrainPatchSize)
            {
                for (int n = 0; n < Constants.TerrainPatchSize*Constants.TerrainPatchSize; n++)
                {
                    block[n] = patches[CopyMatrix16[n]]*DequantizeTable16[n];
                }

                float[] ftemp = new float[Constants.TerrainPatchSize*Constants.TerrainPatchSize];

                for (int o = 0; o < Constants.TerrainPatchSize; o++)
                    IDCTColumn16(block, ftemp, o);
                for (int o = 0; o < Constants.TerrainPatchSize; o++)
                    IDCTLine16(ftemp, block, o);
            }
            else
            {
                for (int n = 0; n < Constants.TerrainPatchSize*2*Constants.TerrainPatchSize*2; n++)
                {
                    block[n] = patches[CopyMatrix32[n]]*DequantizeTable32[n];
                }

                Logger.Log("Implement IDCTPatchLarge", Helpers.LogLevel.Error);
            }

            for (int j = 0; j < block.Length; j++)
            {
                output[j] = block[j]*mult + addval;
            }

            return output;
        }

        private static int[] CompressPatch(float[] patchData, TerrainPatch.Header header, int prequant, out int wbits)
        {
            float[] block = new float[Constants.TerrainPatchSize*Constants.TerrainPatchSize];
            int wordsize = (prequant - 2) & 0x0f;
            float oozrange = 1.0f/header.Range;
            float range = (1 << prequant);
            float premult = oozrange*range;
            float sub = (1 << (prequant - 1)) + header.DCOffset*premult;

            header.QuantWBits = wordsize;
            header.QuantWBits |= wordsize << 4;

            int k = 0;
            for (int j = 0; j < Constants.TerrainPatchSize; j++)
            {
                for (int i = 0; i < Constants.TerrainPatchSize; i++)
                    block[k++] = patchData[j*Constants.TerrainPatchSize + i]*premult - sub;
            }

            float[] ftemp = new float[Constants.TerrainPatchSize*Constants.TerrainPatchSize];
            int[] itemp = new int[Constants.TerrainPatchSize*Constants.TerrainPatchSize];

            int maxWbits = prequant + 5;
            wbits = (prequant >> 1);

            for (int o = 0; o < Constants.TerrainPatchSize; o++)
                DCTLine16(block, ftemp, o);
            for (int o = 0; o < Constants.TerrainPatchSize; o++)
                wbits = DCTColumn16Wbits(ftemp, itemp, o, wbits, maxWbits);

            return itemp;
        }

        private static int[] CompressPatch(float[,] patchData, TerrainPatch.Header header, int prequant, out int wbits)
        {
            float[] block = new float[Constants.TerrainPatchSize*Constants.TerrainPatchSize];
            float oozrange = 1.0f/header.Range;
            float range = (1 << prequant);
            float premult = oozrange*range;
            float sub = (1 << (prequant - 1)) + header.DCOffset*premult;
            int wordsize = (prequant - 2) & 0x0f;

            header.QuantWBits = wordsize;
            header.QuantWBits |= wordsize << 4;

            int k = 0;
            for (int j = 0; j < Constants.TerrainPatchSize; j++)
            {
                for (int i = 0; i < Constants.TerrainPatchSize; i++)
                    block[k++] = patchData[j, i]*premult - sub;
            }

            float[] ftemp = new float[Constants.TerrainPatchSize*Constants.TerrainPatchSize];
            int[] itemp = new int[Constants.TerrainPatchSize*Constants.TerrainPatchSize];

            int maxWbits = prequant + 5;
            wbits = (prequant >> 1);

            for (int o = 0; o < Constants.TerrainPatchSize; o++)
                DCTLine16(block, ftemp, o);
            for (int o = 0; o < Constants.TerrainPatchSize; o++)
                wbits = DCTColumn16Wbits(ftemp, itemp, o, wbits, maxWbits);

            return itemp;
        }

        private static int[] CompressPatch(TerrainData terrData, int patchX, int patchY, TerrainPatch.Header header,
                                                               int prequant, out int wbits)
        {
            float[] block = new float[Constants.TerrainPatchSize*Constants.TerrainPatchSize];
            int wordsize = prequant;
            float oozrange = 1.0f/header.Range;
            float range = (1 << prequant);
            float premult = oozrange*range;
            float sub = (1 << (prequant - 1)) + header.DCOffset*premult;

            header.QuantWBits = wordsize - 2;
            header.QuantWBits |= (prequant - 2) << 4;

            int k = 0;

            int yPatchLimit = patchY >= (terrData.SizeY / Constants.TerrainPatchSize) ?
                            (terrData.SizeY - Constants.TerrainPatchSize) / Constants.TerrainPatchSize : patchY;
            yPatchLimit = (yPatchLimit + 1) * Constants.TerrainPatchSize;

            int xPatchLimit = patchX >= (terrData.SizeX / Constants.TerrainPatchSize) ?
                            (terrData.SizeX - Constants.TerrainPatchSize) / Constants.TerrainPatchSize : patchX;
            xPatchLimit = (xPatchLimit + 1) * Constants.TerrainPatchSize;

            for (int yy = patchY * Constants.TerrainPatchSize; yy < yPatchLimit; yy++)
            {
                for (int xx = patchX * Constants.TerrainPatchSize; xx < xPatchLimit; xx++)
                {
                    block[k++] = terrData[xx, yy] * premult - sub;
                }
            }

            float[] ftemp = new float[Constants.TerrainPatchSize*Constants.TerrainPatchSize];
            int[] itemp = new int[Constants.TerrainPatchSize*Constants.TerrainPatchSize];

            int maxWbits = prequant + 5;
            wbits = (prequant >> 1);

            for (int o = 0; o < Constants.TerrainPatchSize; o++)
                DCTLine16(block, ftemp, o);
            for (int o = 0; o < Constants.TerrainPatchSize; o++)
                wbits = DCTColumn16Wbits(ftemp, itemp, o, wbits, maxWbits);

            return itemp;
        }

        #region Initialization

        private static void BuildDequantizeTable16()
        {
            for (int j = 0; j < Constants.TerrainPatchSize; j++)
            {
                for (int i = 0; i < Constants.TerrainPatchSize; i++)
                {
                    DequantizeTable16[j*Constants.TerrainPatchSize + i] = 1.0f + 2.0f*(i + j);
                }
            }
        }

        private static void BuildQuantizeTable16()
        {
            const float oosob = 2.0f/Constants.TerrainPatchSize;
            for (int j = 0; j < Constants.TerrainPatchSize; j++)
            {
                for (int i = 0; i < Constants.TerrainPatchSize; i++)
                {
//                    QuantizeTable16[j * Constants.TerrainPatchSize + i] = 1.0f / (1.0f + 2.0f * ((float)i + (float)j));
                    QuantizeTable16[j*Constants.TerrainPatchSize + i] = oosob/(1.0f + 2.0f*(i + (float) j));
                }
            }
        }

        private static void SetupCosines16()
        {
            const float hposz = (float) Math.PI*0.5f/Constants.TerrainPatchSize;

            for (int u = 0; u < Constants.TerrainPatchSize; u++)
            {
                for (int n = 0; n < Constants.TerrainPatchSize; n++)
                {
                    CosineTable16[u*Constants.TerrainPatchSize + n] = (float) Math.Cos((2.0f*n + 1.0f)*u*hposz);
                }
            }
        }

        private static void BuildCopyMatrix16()
        {
            bool diag = false;
            bool right = true;
            int i = 0;
            int j = 0;
            int count = 0;

            while (i < Constants.TerrainPatchSize && j < Constants.TerrainPatchSize)
            {
                CopyMatrix16[j*Constants.TerrainPatchSize + i] = count++;

                if (!diag)
                {
                    if (right)
                    {
                        if (i < Constants.TerrainPatchSize - 1) i++;
                        else j++;

                        right = false;
                        diag = true;
                    }
                    else
                    {
                        if (j < Constants.TerrainPatchSize - 1) j++;
                        else i++;

                        right = true;
                        diag = true;
                    }
                }
                else
                {
                    if (right)
                    {
                        i++;
                        j--;
                        if (i == Constants.TerrainPatchSize - 1 || j == 0) diag = false;
                    }
                    else
                    {
                        i--;
                        j++;
                        if (j == Constants.TerrainPatchSize - 1 || i == 0) diag = false;
                    }
                }
            }
        }

        #endregion Initialization
    }
}

redpajama_set_name: RedPajamaGithub


text:
const mockMark = jest.fn();
const mockUnmark = jest.fn();

jest.mock('mark.js', () => () => ({
  mark: mockMark,
  unmark: mockUnmark,
}));

import { MarkerService } from '../MarkerService';

describe('Marker service', () => {
  let marker: MarkerService;
  const element = document.createElement('span');

  beforeEach(() => {
    marker = new MarkerService();
    mockMark.mockClear();
    mockUnmark.mockClear();
  });

  test('add element to Map', () => {
    marker.add(element);
    expect(marker.map.size).toBeGreaterThan(0);
  });

  test('delete element from Map', () => {
    marker.add(element);
    marker.delete(element);

    expect(marker.map.size).toEqual(0);
  });

  test('addOnly: should unmark and remove old elements', () => {
    const e1 = document.createElement('span');
    const e2 = document.createElement('span');
    const e3 = document.createElement('span');

    marker.add(e1);
    marker.add(e2);

    marker.addOnly([element, e2, e3]);

    expect(mockUnmark).toHaveBeenCalledTimes(1);
    expect(marker.map.size).toEqual(3);
  });

  test('unmark: should unmark all elements', () => {
    const e1 = document.createElement('span');
    const e2 = document.createElement('span');
    marker.add(e1);
    marker.add(e2);
    marker.add(element);

    marker.unmark();

    expect(mockUnmark).toHaveBeenCalledTimes(3);
    expect(mockMark).not.toHaveBeenCalled();
  });
  test('clearAll: should unmark and remove all elements', () => {
    const e1 = document.createElement('span');
    const e2 = document.createElement('span');
    marker.add(e1);
    marker.add(e2);
    marker.add(element);

    marker.clearAll();

    expect(mockUnmark).toHaveBeenCalledTimes(3);
    expect(mockMark).not.toHaveBeenCalled();
    expect(marker.map.size).toEqual(0);
  });

  test('mark: should unmark and mark again each element', () => {
    const e1 = document.createElement('span');
    const e2 = document.createElement('span');
    marker.add(e1);
    marker.add(e2);
    marker.add(element);

    marker.mark('test');

    expect(mockUnmark).toHaveBeenCalledTimes(3);
    expect(mockMark).toHaveBeenCalledTimes(3);
    expect(mockMark).toHaveBeenCalledWith('test');
    expect(marker.map.size).toEqual(3);
  });

  test('mark: should do nothing if no term provided', () => {
    marker.add(element);
    marker.mark();

    expect(mockMark).not.toHaveBeenCalled();
  });
  test('mark: should save previous marked term and use it if no term is provided', () => {
    marker.add(element);
    marker.mark('test');
    marker.mark();

    expect(mockMark).toHaveBeenLastCalledWith('test');
  });
});


text:
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');

class Home_body_model extends CI_Model {

    public function select_home_body()
    {
        $sql="SELECT * from tbl_home_body ORDER by home_body_id ";
        $this->db->query("set character_set_results='utf8'");
        $result=$this->db->query($sql);
        return $result->result_array();
    }
    public function update_home_body($data)
    {

        $data['bn_body_header']=$this->input->post('bn_body_header');
        $data['en_body_header']=$this->input->post('en_body_header');
        $data['bn_body_text']=$this->input->post('bn_body_text');
        $data['en_body_text']=$this->input->post('en_body_text');
        $data1 = array(
            'bn_body_header' =>  $data['bn_body_header'],
            'en_body_header' =>  $data['en_body_header'],
            'bn_body_text' => $data['bn_body_text'],
            'en_body_text' => $data['en_body_text']
        );
        $this->db->where('home_body_id', $data['home_body_id']);
        $this->db->update('tbl_home_body', $data1);
        return 1;
    }
}


text:
/*
char *ip_address;
char *uri;

ip_address = sapi_getenv("HTTP_X_FORWARDED_FOR", 20 TSRMLS_CC);
if (ip_address == NULL) {
  ip_address = sapi_getenv("REMOTE_ADDR", 11 TSRMLS_CC);
  if (ip_address == NULL) {
    ip_address = "no_ip_address";
  }
}

uri = sapi_getenv("REQUEST_URI", 11 TSRMLS_CC);
if (uri == NULL) {
  uri = "no_uri";
}

php_syslog(LOG_NOTICE, "%.500s [ip:%s][uri:%s]", log_message, ip_address, uri);
 */

PHP_METHOD(Sleepy, test)
{
    /*
     * From: [main/php_variables.c - php_register_server_variables()]
     *
     * We need to have the $_SERVER superglobals initialized to read them and
     * if it is not invoked via the callee PHP script than we need to do it
     * manually.
     */

    zval *array_ptr = NULL;

    ALLOC_ZVAL(array_ptr);
    array_init(array_ptr);
    INIT_PZVAL(array_ptr);

    if (PG(http_globals)[TRACK_VARS_SERVER]) {
            zval_ptr_dtor(&PG(http_globals)[TRACK_VARS_SERVER]);
    }

    PG(http_globals)[TRACK_VARS_SERVER] = array_ptr;

    if (sapi_module.register_server_variables) {
        sapi_module.register_server_variables(array_ptr TSRMLS_CC);
    }

    /*
     * End super hacky server super global invocation from
     * [main/php_variables.c - php_register_server_variables()]
     */

    //zend_auto_global_disable_jit("_SERVER", sizeof("_SERVER")-1 TSRMLS_DC);
    //zend_activate_auto_globals(TSRMLS_DC);

    zend_llist_position pos;
    sapi_header_struct* h;

    for (h = (sapi_header_struct*)zend_llist_get_first_ex(&SG(sapi_headers).headers, &pos);
         h;
         h = (sapi_header_struct*)zend_llist_get_next_ex(&SG(sapi_headers).headers, &pos))
    {
        php_printf("SAPI! %.*s <br/>", h->header_len, h->header);
    }

    zval **http_user_agent;

    /* This only works if the $_SERVER super global is invoked beforehand. */
    if ( zend_hash_exists(HASH_OF(PG(http_globals)[TRACK_VARS_SERVER]), ZEND_STRS("HTTP_USER_AGENT")) ) {
        /* FYI, zend_hash_exists() returns "1" upon success so you can't use the "SUCCESS" macro which expands to "0" */
        zend_hash_find(HASH_OF(PG(http_globals)[TRACK_VARS_SERVER]), ZEND_STRS("HTTP_USER_AGENT"), (void **)&http_user_agent);
        php_printf("User Agent 007: %s\n", Z_STRVAL_PP(http_user_agent));
    } else {
        php_printf("No user agent found :(\n");
    }

    zval **http_accept;

    if ( zend_hash_exists(HASH_OF(PG(http_globals)[TRACK_VARS_SERVER]), ZEND_STRS("HTTP_ACCEPT")) ) {
        /* FYI, zend_hash_exists() returns "1" upon success so you can't use the "SUCCESS" macro which expands to "0" */
        zend_hash_find(HASH_OF(PG(http_globals)[TRACK_VARS_SERVER]), ZEND_STRS("HTTP_ACCEPT"), (void **)&http_accept);
        php_printf("Acceptance!!!: %s\n", Z_STRVAL_PP(http_accept));
    } else {
        php_printf("No acceptance :(\n");
    }

    /* Setting of status code from (which has a lot of good stuff...)
     * [main/SAPI.c - sapi_update_response_code()
     * sapi_update_response_code(int ncode TSRMLS_DC)
     */
    //int ncode = 202;

    /* if the status code did not change, we do not want
       to change the status line, and no need to change the code */
    //if (SG(sapi_headers).http_response_code == ncode) {
    //    return;
    //}
    //if (SG(sapi_headers).http_status_line) {
    //    efree(SG(sapi_headers).http_status_line);
    //    SG(sapi_headers).http_status_line = NULL;
    //}
    //SG(sapi_headers).http_response_code = ncode;

    //if ( zend_hash_exists(HASH_OF(PG(http_globals)[TRACK_VARS_SERVER]), ZEND_STRS("HTTP_USER_AGENT")) ) {

    /*
     * The Z_STRLEN & Z_STRVAL variadic macros expand into the command below. For the "_PP" variants they would presumably prepend "**" to said non-expanded macros.
     *
     * php_printf("|||%.*s|||\n", Z_STRLEN_PP(http_user_agent), Z_STRVAL_PP(http_user_agent));
     * php_printf("|||%.*s|||\n", http_user_agent->value.str.len, http_user_agent->value.str.val);
     */

}


text:
/* --------------------------------

Primary style

-------------------------------- */
html * {
  -webkit-font-smoothing: antialiased;
  -moz-osx-font-smoothing: grayscale;
}

*, *::after, *::before {
  -webkit-box-sizing: border-box;
  -moz-box-sizing: border-box;
  box-sizing: border-box;
}

*::after, *::before {
  content: '';
}

body {
  font-size: 100%;
  font-family: "Roboto", sans-serif;
  color: white;
  background-color: #3489DA;
}

a {
  color: #f58780;
  text-decoration: none;
}

img {
  max-width: 100%;
}

h1, h2 {
  color: #ffffff;
}

/* --------------------------------

Modules - reusable parts of our design

-------------------------------- */
.btn {
  display: inline-block;
  text-align: center;
  text-transform: uppercase;
  font-weight: bold;
  font-size: 12px;
  font-size: 0.75rem;
  color: #ffffff;
  background-color: black;
  box-shadow: 0 1px 6px rgba(0, 0, 0, 0.1), inset 0 1px 0 rgba(255, 255, 255, 0.2);
  -webkit-transition: background-color 0.2s;
  -moz-transition: background-color 0.2s;
  transition: background-color 0.2s;
}
.no-touch .btn:hover {
  background-color: grey;
}
.btn.salmon {
  background-color: black;
}
.no-touch .btn.salmon:hover {
  background-color: grey;
}
@media only screen and (min-width: 1070px) {
  .btn {
    font-size: 14px;
    font-size: 0.875rem;
    letter-spacing: 2px;
  }
}

/* --------------------------------

Main components

-------------------------------- */
html, body {
  /* important for .cd-main-content 100% height to work */
  height: 100%;
}

.cd-header {
  position: fixed;
  top: 0;
  left: 0;
  z-index: 3;
  width: 100%;
  height: 50px;
  background-color: #2b2d40;
  overflow: hidden;
  /* Force Hardware Acceleration in WebKit */
  -webkit-transform: translateZ(0);
  -moz-transform: translateZ(0);
  -ms-transform: translateZ(0);
  -o-transform: translateZ(0);
  transform: translateZ(0);
  -webkit-backface-visibility: hidden;
  backface-visibility: hidden;
  -webkit-transform: translateY(-100%);
  -moz-transform: translateY(-100%);
  -ms-transform: translateY(-100%);
  -o-transform: translateY(-100%);
  transform: translateY(-100%);
  -webkit-transition: -webkit-transform 0.3s;
  -moz-transition: -moz-transform 0.3s;
  transition: transform 0.3s;
}
.cd-header:after {
  content: "";
  display: table;
  clear: both;
}
.cd-header #cd-logo {
  float: left;
  margin: 18px 0 0 5%;
}
.cd-header #cd-logo img {
  display: block;

}
.cd-header #cd-action {
  display: inline-block;
  float: right;
  margin: 10px 5% 0 0;
}
.cd-header .btn {
  height: 30px;
  line-height: 30px;
  padding: 0 2em;
}
.cd-header.slide-down {
  -webkit-transform: translateY(0);
  -moz-transform: translateY(0);
  -ms-transform: translateY(0);
  -o-transform: translateY(0);
  transform: translateY(0);
}
@media only screen and (min-width: 1070px) {
  .cd-header {
    height: 90px;
    background-color: transparent;
  }
  .cd-header #cd-logo {

  }
  .cd-header #cd-logo img {

  }
  .cd-header #cd-action {
    margin: 20px 5% 0 0;
  }
  .cd-header .btn {
    height: 50px;
    line-height: 50px;
  }
}

.cd-main-content {
  overflow: hidden;
  max-width: 1440px;
  margin: 0 auto;
}
@media only screen and (min-width: 1070px) {
  .cd-main-content {
    position: relative;
    height: 100%;
    min-height: 500px;
    padding: 0 10%;
  }
}

.cd-product-intro {
  padding: 50px 5%;
  text-align: center;
}
.cd-product-intro h1 {
  margin-bottom: 10px;
  font-weight: 100;
  font-size: 25px;
  font-size: 1.5625rem;
  font-weight: 700;
  line-height: 1.2;
}
.cd-product-intro p {
  padding: 0 0 20px;
  font-size: 14px;
  font-size: 0.875rem;
  line-height: 1.8;
  max-width: 560px;
  margin: 0 auto;
}
.cd-product-intro .cd-triggers:after {
  content: "";
  display: table;
  clear: both;
}
.cd-product-intro .btn {
  width: 120px;
  height: 40px;
  line-height: 40px;
  margin-right: 8px;
}
@media only screen and (min-width: 480px) {
  .cd-product-intro {
    padding: 50px 10%;
  }
}
@media only screen and (min-width: 850px) {
  .cd-product-intro {
    padding: 50px 15%;
  }
}
@media only screen and (min-width: 1070px) {
  .cd-product-intro {
    /* Force Hardware Acceleration in WebKit */
    -webkit-transform: translateZ(0);
    -moz-transform: translateZ(0);
    -ms-transform: translateZ(0);
    -o-transform: translateZ(0);
    transform: translateZ(0);
    -webkit-backface-visibility: hidden;
    backface-visibility: hidden;
    position: absolute;
    top: 50%;
    -webkit-transform: translateY(-50%);
    -moz-transform: translateY(-50%);
    -ms-transform: translateY(-50%);
    -o-transform: translateY(-50%);
    transform: translateY(-50%);
    left: 10%;
    width: 50%;
    padding: 0;
    text-align: left;
    -webkit-transition: -webkit-transform 0.3s, opacity 0.3s;
    -moz-transition: -moz-transform 0.3s 0s, opacity 0.3s;
    transition: transform 0.3s, opacity 0.3s;
  }
  .is-product-tour .cd-product-intro {
    opacity: 0;
    -webkit-transform: translateY(-50%) translateX(-50%);
    -moz-transform: translateY(-50%) translateX(-50%);
    -ms-transform: translateY(-50%) translateX(-50%);
    -o-transform: translateY(-50%) translateX(-50%);
    transform: translateY(-50%) translateX(-50%);
  }
  .cd-product-intro h1 {
    font-size: 50px;
    font-size: 3.125rem;
  }
  .cd-product-intro p {
    font-size: 16px;
    font-size: 1rem;
    padding: 10px 0 44px;
    margin: 0;
  }
  .cd-product-intro .btn {
    margin-right: 15px;
    width: 190px;
    height: 60px;
    line-height: 60px;
  }
}

#cd-product-tour {
  position: relative;
}
@media only screen and (min-width: 1070px) {
  #cd-product-tour {
    width: 100%;
    max-width: 850px;
    margin: 0 auto;
    height: 500px;
    top: 50%;
    left: 0;
    -webkit-transform: translateZ(0);
    -moz-transform: translateZ(0);
    -ms-transform: translateZ(0);
    -o-transform: translateZ(0);
    transform: translateZ(0);
    -webkit-transform: translateY(-50%) translateX(75%);
    -moz-transform: translateY(-50%) translateX(75%);
    -ms-transform: translateY(-50%) translateX(75%);
    -o-transform: translateY(-50%) translateX(75%);
    transform: translateY(-50%) translateX(75%);
    -webkit-transition: -webkit-transform 0.3s;
    -moz-transition: -moz-transform 0.3s;
    transition: transform 0.3s;
  }
  .is-product-tour #cd-product-tour {
    -webkit-transform: translateY(-50%) translateX(0);
    -moz-transform: translateY(-50%) translateX(0);
    -ms-transform: translateY(-50%) translateX(0);
    -o-transform: translateY(-50%) translateX(0);
    transform: translateY(-50%) translateX(0);
  }
  #cd-product-tour > ul {
    height: 100%;
    width: 100%;
  }
}

.cd-single-item {
  /* product tour - single list item */
  padding: 50px 5% 120px;
  width: 100%;
  text-align: center;
  border-top: 1px solid #494e6e;
}
.cd-single-item h2 {
  margin-bottom: 15px;
  font-size: 22px;
  font-size: 1.375rem;
}
.cd-single-item p {
  padding: 10px 0 50px;
  font-size: 14px;
  font-size: 0.875rem;
  line-height: 1.6;
}
@media only screen and (min-width: 480px) {
  .cd-single-item {
    padding: 50px 10% 120px;
  }
}
@media only screen and (min-width: 850px) {
  .cd-single-item {
    padding: 50px 15% 120px;
  }
  .cd-single-item:after {
    content: "";
    display: table;
    clear: both;
  }
  .cd-single-item .cd-caption {
    width: 50%;
    float: left;
    margin-top: 180px;
  }
  .cd-single-item:nth-child(2n) .cd-caption {
    float: right;
  }
}
@media only screen and (min-width: 1070px) {
  .cd-single-item {
    position: absolute;
    top: 50%;
    -webkit-transform: translateY(-50%);
    -moz-transform: translateY(-50%);
    -ms-transform: translateY(-50%);
    -o-transform: translateY(-50%);
    transform: translateY(-50%);
    left: 0;
    text-align: left;
    border-top: none;
    padding: 0;
    visibility: visible;
  }
  .cd-single-item.cd-not-visible {
    /*need to create a specific class to change visibility value due to a Firefox bug*/
    /*CSS transition/animation fails when parent element changes visibility attribute*/
    visibility: hidden;
  }
  .cd-single-item h2 {
    font-size: 48px;
    font-size: 3rem;
    font-weight: 300;
  }
  .cd-single-item p {
    font-size: 16px;
    font-size: 1rem;
    line-height: 1.5;
    max-width: 600px;
  }
  .cd-single-item .cd-caption {
    width: 60%;
    float: right;
    margin: 80px 0 0 5%;
    opacity: 0;
    -webkit-transform: translateZ(0);
    -moz-transform: translateZ(0);
    -ms-transform: translateZ(0);
    -o-transform: translateZ(0);
    transform: translateZ(0);
    -webkit-transition: -webkit-transform 0.3s, opacity 0.3s;
    -moz-transition: -moz-transform 0.3s 0s, opacity 0.3s;
    transition: transform 0.3s, opacity 0.3s;
  }
  .is-product-tour .cd-single-item.cd-active .cd-caption {
    opacity: 1;
  }
  .cd-single-item.cd-move-right .cd-caption {
    -webkit-transform: translateX(100px);
    -moz-transform: translateX(100px);
    -ms-transform: translateX(100px);
    -o-transform: translateX(100px);
    transform: translateX(100px);
  }
}

.cd-image-container {
  /*wrapper for image (and video - desktop only)*/
  max-width: 226px;
  margin: 0 auto;
  padding-top: 50px;
}
.cd-image-container > div {
  position: relative;
}
.cd-image-container img {
  display: block;
}
.cd-image-container video {
  display: none;
}
@media only screen and (min-width: 850px) {
  .cd-image-container {
    float: right;
  }
  .cd-single-item:nth-child(2n) .cd-image-container {
    float: left;
  }
}
@media only screen and (min-width: 1070px) {
  .cd-image-container {
    height: 402px;
    width: 35%;
    float: left;
    max-width: none;
    padding-top: 0;
  }
  .cd-image-container > div {
    display: inline-block;
    max-width: 100%;
    max-height: 100%;
  }
  .cd-image-container img {
    height: 382px;
    -webkit-transition: -webkit-transform 0.3s;
    -moz-transition: -moz-transform 0.3s;
    transition: transform 0.3s;
    -webkit-transform: translateZ(0);
    -moz-transform: translateZ(0);
    -ms-transform: translateZ(0);
    -o-transform: translateZ(0);
    transform: translateZ(0);
  }
  .cd-image-container video {
    /*not inserted in html - will be loaded through jQuery*/
    display: block;
    position: absolute;
    width: 402px;
    left: 50%;
    top: 50%;
    bottom: auto;
    right: auto;
    z-index: 1;
    -webkit-transition: -webkit-transform 0.3s;
    -moz-transition: -moz-transform 0.3s;
    transition: transform 0.3s;
    -webkit-transform: translateZ(0);
    -moz-transform: translateZ(0);
    -ms-transform: translateZ(0);
    -o-transform: translateZ(0);
    transform: translateZ(0);
    -webkit-transform: translateX(-50%) translateY(-50%) rotate(-90deg);
    -moz-transform: translateX(-50%) translateY(-50%) rotate(-90deg);
    -ms-transform: translateX(-50%) translateY(-50%) rotate(-90deg);
    -o-transform: translateX(-50%) translateY(-50%) rotate(-90deg);
    transform: translateX(-50%) translateY(-50%) rotate(-90deg);
  }
  .cd-move-right .cd-image-container img {
    -webkit-transform: translateX(100%);
    -moz-transform: translateX(100%);
    -ms-transform: translateX(100%);
    -o-transform: translateX(100%);
    transform: translateX(100%);
  }
  .cd-move-right .cd-image-container video {
    -webkit-transform: translateX(50%) translateY(-50%) rotate(-90deg);
    -moz-transform: translateX(50%) translateY(-50%) rotate(-90deg);
    -ms-transform: translateX(50%) translateY(-50%) rotate(-90deg);
    -o-transform: translateX(50%) translateY(-50%) rotate(-90deg);
    transform: translateX(50%) translateY(-50%) rotate(-90deg);
  }
}

.cd-phone-frame {
  /* Phone in CSS */
  -webkit-box-sizing: content-box;
  -moz-box-sizing: content-box;
  box-sizing: content-box;
  position: absolute;
  top: -45px;
  left: -10px;
  width: 100%;
  height: 100%;
  border-color: black;
  border-style: solid;
  border-width: 45px 10px;
  border-radius: 2.5em;
  -webkit-backface-visibility: hidden;
  backface-visibility: hidden;
}
.cd-phone-frame::after, .cd-phone-frame::before {
  /*these are the iPhone circle elements*/
  position: absolute;
  left: 50%;
  right: auto;
  -webkit-transform: translateX(-50%);
  -moz-transform: translateX(-50%);
  -ms-transform: translateX(-50%);
  -o-transform: translateX(-50%);
  transform: translateX(-50%);
  -webkit-backface-visibility: hidden;
  backface-visibility: hidden;
  background-color: #202331;
  border-radius: 50%;
}
.cd-phone-frame::before {
  height: 11px;
  width: 11px;
  top: -28px;
}
.cd-phone-frame::after {
  height: 31px;
  width: 31px;
  bottom: -38px;
}

.cd-image-wrapper {
  position: relative;
  overflow: hidden;
  z-index: 2;
}

.cd-slider-nav {
  /* product discover slider navigation */
  display: none;
  position: fixed;
  bottom: 0;
  left: 0;
  z-index: 1;
  width: 100%;
  height: 80px;
}
.cd-slider-nav:after {
  content: "";
  display: table;
  clear: both;
}
.cd-slider-nav a {
  position: relative;
  display: block;
  height: 100%;
  width: 50%;
  float: left;
  overflow: hidden;
  text-indent: 100%;
  white-space: nowrap;
  color: transparent;
  background: black;
}
.no-touch .cd-slider-nav a:hover {
  background: grey;
}
.cd-slider-nav a::before {
  /*this is the bacground arrow - we have been used a before element to change the opacity on hover*/
  position: absolute;
  left: 50%;
  top: 50%;
  bottom: auto;
  right: auto;
  -webkit-transform: translateX(-50%) translateY(-50%);
  -moz-transform: translateX(-50%) translateY(-50%);
  -ms-transform: translateX(-50%) translateY(-50%);
  -o-transform: translateX(-50%) translateY(-50%);
  transform: translateX(-50%) translateY(-50%);
  width: 24px;
  height: 16px;
  opacity: .2;
  background: url(../img/cd-arrow.svg) no-repeat center center;
  -webkit-backface-visibility: hidden;
  backface-visibility: hidden;
  -webkit-transition: opacity 0.2s;
  -moz-transition: opacity 0.2s;
  transition: opacity 0.2s;
}
.no-touch .cd-slider-nav a:hover::before {
  opacity: 1;
}
.cd-slider-nav .cd-next {
  border-left: 1px solid #3f435f;
}
.cd-slider-nav .cd-next::before {
  -webkit-transform: translateX(-50%) translateY(-50%) rotate(180deg);
  -moz-transform: translateX(-50%) translateY(-50%) rotate(180deg);
  -ms-transform: translateX(-50%) translateY(-50%) rotate(180deg);
  -o-transform: translateX(-50%) translateY(-50%) rotate(180deg);
  transform: translateX(-50%) translateY(-50%) rotate(180deg);
}
@media only screen and (min-width: 1070px) {
  .cd-slider-nav {
    display: block;
  }
  .cd-slider-nav a {
    visibility: hidden;
    opacity: 0;
    -webkit-transition: opacity 0.3s 0s, visibility 0s 0.3s, background 0.2s;
    -moz-transition: opacity 0.3s 0s, visibility 0s 0.3s, background 0.2s;
    transition: opacity 0.3s 0s, visibility 0s 0.3s, background 0.2s;
  }
  .is-product-tour .cd-slider-nav a {
    visibility: visible;
    opacity: 1;
    -webkit-transition: opacity 0.3s 0s, visibility 0s 0s, background 0.2s;
    -moz-transition: opacity 0.3s 0s, visibility 0s 0s, background 0.2s;
    transition: opacity 0.3s 0s, visibility 0s 0s, background 0.2s;
  }
  .is-product-tour .cd-slider-nav a.cd-inactive {
    visibility: hidden;
    opacity: 0;
    -webkit-transition: opacity 0.3s 0s, visibility 0s 0.3s, background 0.2s;
    -moz-transition: opacity 0.3s 0s, visibility 0s 0.3s, background 0.2s;
    transition: opacity 0.3s 0s, visibility 0s 0.3s, background 0.2s;
  }
}

.cd-loader {
  /*top loading bar*/
  position: fixed;
  top: 0;
  left: 0;
  height: 3px;
  width: 0;
  background-color: #f58780;
  display: none;
}


text:
<TITLE>Review for Hearts of Darkness: A Filmmaker's Apocalypse (1991)</TITLE>
<LINK REL="STYLESHEET" TYPE="text/css" HREF="/ramr.css">

Hearts of Darkness: A Filmmaker's Apocalypse (1991)

reviewed by
Eugene Miya

                             HEARTS OF DARKNESS
                       A film review by Eugene N. Miya
                       (a review in the public domain)

HEARTS OF DARKNESS (rated R)

     HEARTS OF DARKNESS is a two-hour documentary on the making of the
film APOCALYPSE NOW (by Francis Ford Coppola) by Francis' wife.

     Background: At the time it was released, APOCALYPSE NOW was the
most expensive film ever made.  Cost was not an issue as much until then
for this $30M film.  At the time, prior to release, I was helping a
friend with a struggling movie company (they made three films before
folding) as an unpaid consultant on the side.  Movies were pollyanna
artsy things.  Then a daily was released from APOCALYPSE NOW showing a
real Huey helicopter (hovering 10 feet off the ground) all of a sudden
blowing up.  What was that film?????!!!!  Of course now this is all old
hat.  APOCALYPSE NOW attracted a lot of attention (as some of this is
covered in the film).  APOCALYPSE NOW got my vote for picture of the
year in 1979 as well as my vote to cinematographer (the only two
categories I could vote).

     HEARTS OF DARKNESS was Francis Coppola's vision of adapting Joseph
Conrad's HEART OF DARKNESS (which I have to admit I only recently read).
It came about because Coppola, George Lucas, and John Milius had all
read Conrad and thought it was the best book they had ever read.  The
film features interviews with all three.  Lucas eventually bowed out;
Milius unhappily went off and produced an even more controversial war
film.

     The idea was born in the late 1960s, shelved as American Zoetrope
made a name for itself, then taken a look at again.  The film presents a
little insight into Coppola's (not necessarily the rest of the film
industry's) process.  Of course no one wanted to touch Vietnam war films
at the time.

     The documentary is not a great film, but it shows some of the
behind the scenes for the construction of the temples, the extensive
napalm and pyrotechnics, the orchestration of the helichoppers
(Philippine Air Force which were called away at a moment's notice when
they needed to be used against real guerillas [the expression on
Coppola's face is great]).  This is not like one of those shorty
documentaries used to describe the making of TERMINATOR 2, or ROBOCOP.

     We see the change of script when Martin Sheen is brought in to
replace an earlier leading man.  His heart attack is covered.  The toll
this film took upon the film crew over years, tropical storms, money
problems was amazing.  The film includes interviews with the actors
(Larry Fishburne, Sam Bottoms, etc.) that make you wonder where the
black actors are today.  The only person not interviewed is Marlon
Brando.

     The spoofs on APOCALYPSE NOW are noted (like one on SATURDAY NIGHT
LIVE with Martin Sheen).

     The R rating is due to several scenes on which the final water
buffalo sacrifice scene is based.  This is not for the squeamish.  It
happens more than once.  (first when Coppola's wife first finds the
ritual, then during filming.)

     Coppola is clearly one of these most important forces in American
movie making.  Other interviews include members of his family (noting
changes in hair length and fashion).  The film goes on and on, like
APOCALYPSE NOW, and we get "sucked up the river."  It gets kind of
decadent and boring toward the end.

     The film closes noting that APOCALYPSE NOW has made some $135M.
Won numerous awards, and so forth.  This film is not SLEEPING BEAUTY,
but if you have worked for the business, you might find it intense and
dull.  Remember it is a documentary.

--eugene miya, NASA Ames Research Center, eugene@orville.nas.nasa.gov
  {uunet,mailrus,other gateways}!ames!eugene

.

The review above was posted to the
rec.arts.movies.reviews newsgroup (de.rec.film.kritiken for German reviews).

The Internet Movie Database accepts no responsibility for the contents of the
review and has no editorial control. Unless stated otherwise, the copyright
belongs to the author.

Please direct comments/criticisms of the review to relevant newsgroups.

Broken URLs inthe reviews are the responsibility of the author.

The formatting of the review is likely to differ from the original due
to ASCII to HTML conversion.

Related links: index of all rec.arts.movies.reviews reviews


text:
"""CLI entry point for sending Slack notifications.

Help: ``python -m src.foremast.slacknotify -h``
"""
import argparse
import logging

from ..args import add_app, add_debug, add_env, add_properties
from ..consts import LOGGING_FORMAT
from .slack_notification import SlackNotification

def main():
    """Send Slack notification to a configured channel."""
    logging.basicConfig(format=LOGGING_FORMAT)
    log = logging.getLogger(__name__)

    parser = argparse.ArgumentParser()
    add_debug(parser)
    add_app(parser)
    add_env(parser)
    add_properties(parser)

    args = parser.parse_args()

    logging.getLogger(__package__.split(".")[0]).setLevel(args.debug)
    log.debug('Parsed arguements: %s', args)

    if "prod" not in args.env:
        log.info('No slack message sent, not a production environment')
    else:
        log.info("Sending slack message, production environment")
        slacknotify = SlackNotification(app=args.app, env=args.env, prop_path=args.properties)
        slacknotify.post_message()

if __name__ == "__main__":
    main()


text:
<?php

/**
 * This file is part of the PHP Generics package.
 *
 * @package Generics
 */
namespace Generics\Client;

use Generics\GenericsException;

/**
 * Derived exception used for HTTP exceptions
 *
 * @author Maik Greubel <greubel@nkey.de>
 */
class HttpException extends GenericsException
{
}


text:
using System;
using System.Collections;
using System.Windows.Forms;

namespace SampleApp
{
	public class FolderItemSorter : IComparer
	{
		private string _mode;
		private SortOrder _order;

		public FolderItemSorter(string mode, SortOrder order)
		{
			_mode = mode;
			_order = order;
		}

		public int Compare(object x, object y)
		{
			BaseItem a = x as BaseItem;
			BaseItem b = y as BaseItem;
			int res = 0;

			if (_mode == "Date")
				res = DateTime.Compare(a.Date, b.Date);
			else if (_mode == "Size")
			{
				if (a.Size < b.Size)
					res = -1;
				else if (a.Size > b.Size)
					res = 1;
			}
			else
				res = string.Compare(a.Name, b.Name);

			if (_order == SortOrder.Ascending)
				return -res;
			else
				return res;
		}

		private string GetData(object x)
		{
			return (x as BaseItem).Name;
		}
	}
}


text:
"""VIF drivers for VMware."""

from oslo_log import log as logging
from oslo_utils import versionutils
from oslo_vmware import vim_util

import nova.conf
from nova import exception
from nova.i18n import _
from nova.network import model
from nova.virt.vmwareapi import constants
from nova.virt.vmwareapi import network_util
from nova.virt.vmwareapi import vm_util

LOG = logging.getLogger(__name__)
CONF = nova.conf.CONF

def _get_associated_vswitch_for_interface(session, interface, cluster=None):
    # Check if the physical network adapter exists on the host.
    if not network_util.check_if_vlan_interface_exists(session,
                                        interface, cluster):
        raise exception.NetworkAdapterNotFound(adapter=interface)
    # Get the vSwitch associated with the Physical Adapter
    vswitch_associated = network_util.get_vswitch_for_vlan_interface(
                                    session, interface, cluster)
    if not vswitch_associated:
        raise exception.SwitchNotFoundForNetworkAdapter(adapter=interface)
    return vswitch_associated

def ensure_vlan_bridge(session, vif, cluster=None, create_vlan=True):
    """Create a vlan and bridge unless they already exist."""
    vlan_num = vif['network'].get_meta('vlan')
    bridge = vif['network']['bridge']
    vlan_interface = CONF.vmware.vlan_interface

    network_ref = network_util.get_network_with_the_name(session, bridge,
                                                         cluster)
    if network_ref and network_ref['type'] == 'DistributedVirtualPortgroup':
        return network_ref

    if not network_ref:
        # Create a port group on the vSwitch associated with the
        # vlan_interface corresponding physical network adapter on the ESX
        # host.
        vswitch_associated = _get_associated_vswitch_for_interface(session,
                                 vlan_interface, cluster)
        network_util.create_port_group(session, bridge,
                                       vswitch_associated,
                                       vlan_num if create_vlan else 0,
                                       cluster)
        network_ref = network_util.get_network_with_the_name(session,
                                                             bridge,
                                                             cluster)
    elif create_vlan:
        # Get the vSwitch associated with the Physical Adapter
        vswitch_associated = _get_associated_vswitch_for_interface(session,
                                 vlan_interface, cluster)
        # Get the vlan id and vswitch corresponding to the port group
        _get_pg_info = network_util.get_vlanid_and_vswitch_for_portgroup
        pg_vlanid, pg_vswitch = _get_pg_info(session, bridge, cluster)

        # Check if the vswitch associated is proper
        if pg_vswitch != vswitch_associated:
            raise exception.InvalidVLANPortGroup(
                bridge=bridge, expected=vswitch_associated,
                actual=pg_vswitch)

        # Check if the vlan id is proper for the port group
        if pg_vlanid != vlan_num:
            raise exception.InvalidVLANTag(bridge=bridge, tag=vlan_num,
                                           pgroup=pg_vlanid)
    return network_ref

def _check_ovs_supported_version(session):
    # The port type 'ovs' is only support by the VC version 5.5 onwards
    min_version = versionutils.convert_version_to_int(
        constants.MIN_VC_OVS_VERSION)
    vc_version = versionutils.convert_version_to_int(
        vim_util.get_vc_version(session))
    if vc_version < min_version:
        LOG.warning('VMware vCenter version less than %(version)s '
                    'does not support the \'ovs\' port type.',
                    {'version': constants.MIN_VC_OVS_VERSION})

def _get_neutron_network(session, cluster, vif):
    if vif['type'] == model.VIF_TYPE_OVS:
        _check_ovs_supported_version(session)
        # Check if this is the NSX-MH plugin is used
        if CONF.vmware.integration_bridge:
            net_id = CONF.vmware.integration_bridge
            use_external_id = False
            network_type = 'opaque'
        else:
            # The NSX|V3 plugin will pass the nsx-logical-switch-id as part
            # of the port details. This will enable the VC to connect to
            # that specific opaque network
            net_id = (vif.get('details') and
                      vif['details'].get('nsx-logical-switch-id'))
            if not net_id:
                # Make use of the original one, in the event that the
                # plugin does not pass the aforementioned id
                LOG.info('NSX Logical switch ID is not present. '
                         'Using network ID to attach to the '
                         'opaque network.')
                net_id = vif['network']['id']
            use_external_id = True
            network_type = 'nsx.LogicalSwitch'
        network_ref = {'type': 'OpaqueNetwork',
                       'network-id': net_id,
                       'network-type': network_type,
                       'use-external-id': use_external_id}
    elif vif['type'] == model.VIF_TYPE_DVS:
        # Port binding for DVS VIF types may pass the name
        # of the port group, so use it if present
        network_id = vif.get('details', {}).get('dvs_port_group_name')
        if network_id is None:
            # Make use of the original one, in the event that the
            # port binding does not provide this key in VIF details
            network_id = vif['network']['bridge']
        network_ref = network_util.get_network_with_the_name(
                session, network_id, cluster)
        if not network_ref:
            # We may have a provider network for a portgroup. The portgroup
            # will have the same name as the network 'label'. This is enforced
            # when the provider network is created
            network_id = vif['network']['label']
            network_ref = network_util.get_network_with_the_name(
                    session, network_id, cluster)
        if not network_ref:
            raise exception.NetworkNotFoundForBridge(bridge=network_id)
        if vif.get('details') and vif['details'].get('dvs_port_key'):
            network_ref['dvs_port_key'] = vif['details']['dvs_port_key']
    else:
        reason = _('vif type %s not supported') % vif['type']
        raise exception.InvalidInput(reason=reason)
    return network_ref

def get_network_ref(session, cluster, vif, is_neutron):
    if is_neutron:
        network_ref = _get_neutron_network(session, cluster, vif)
    else:
        create_vlan = vif['network'].get_meta('should_create_vlan', False)
        network_ref = ensure_vlan_bridge(session, vif, cluster=cluster,
                                         create_vlan=create_vlan)
    return network_ref

def get_vif_dict(session, cluster, vif_model, is_neutron, vif):
    mac = vif['address']
    name = vif['network']['bridge'] or CONF.vmware.integration_bridge
    ref = get_network_ref(session, cluster, vif, is_neutron)
    return {'network_name': name,
            'mac_address': mac,
            'network_ref': ref,
            'iface_id': vif['id'],
            'vif_model': vif_model}

def get_vif_info(session, cluster, is_neutron, vif_model, network_info):
    vif_infos = []
    if network_info is None:
        return vif_infos
    for vif in network_info:
        vif_infos.append(get_vif_dict(session, cluster, vif_model,
                         is_neutron, vif))
    return vif_infos

def get_network_device(hardware_devices, mac_address):
    """Return the network device with MAC 'mac_address'."""
    if hardware_devices.__class__.__name__ == "ArrayOfVirtualDevice":
        hardware_devices = hardware_devices.VirtualDevice
    for device in hardware_devices:
        if device.__class__.__name__ in vm_util.ALL_SUPPORTED_NETWORK_DEVICES:
            if hasattr(device, 'macAddress'):
                if device.macAddress == mac_address:
                    return device


text:
<?php
/**
 * Created by PhpStorm.
 * User: Hamaryuginh
 * Date: 21/11/2014
 * Time: 13:27
 */

namespace Hamaryuginh\MandrillBundle\Model\Response\Url;

/**
 * Class UrlEntry
 * @package Hamaryuginh\MandrillBundle\Model\Response\Url
 *
 * @method UrlEntry setUrl(string $url)
 * @method string getUrl()
 */
class UrlEntry extends AbstractUrlStat { }


text:
package org.elasticsearch.xpack.watcher.notification.pagerduty;

import org.elasticsearch.ElasticsearchParseException;
import org.elasticsearch.common.Nullable;
import org.elasticsearch.common.ParseField;
import org.elasticsearch.common.Strings;
import org.elasticsearch.common.xcontent.ToXContentObject;
import org.elasticsearch.common.xcontent.XContentBuilder;
import org.elasticsearch.common.xcontent.XContentParser;
import org.elasticsearch.xpack.watcher.common.text.TextTemplate;
import org.elasticsearch.xpack.watcher.common.text.TextTemplateEngine;

import java.io.IOException;
import java.util.Locale;
import java.util.Map;
import java.util.Objects;

public class IncidentEventContext implements ToXContentObject {

    enum Type {
        LINK, IMAGE
    }

    final Type type;
    final String href;
    final String text;
    final String src;
    final String alt;

    public static IncidentEventContext link(String href, @Nullable String text) {
        assert href != null;
        return new IncidentEventContext(Type.LINK, href, text, null, null);
    }

    public static IncidentEventContext image(String src, @Nullable String href, @Nullable String alt) {
        assert src != null;
        return new IncidentEventContext(Type.IMAGE, href, null, src, alt);
    }

    private IncidentEventContext(Type type, String href, String text, String src, String alt) {
        this.type = type;
        this.href = href;
        this.text = text;
        this.src = src;
        this.alt = alt;
    }

    @Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if (o == null || getClass() != o.getClass()) return false;

        IncidentEventContext that = (IncidentEventContext) o;

        return Objects.equals(type, that.type) &&
                Objects.equals(href, that.href) &&
                Objects.equals(text, that.text) &&
                Objects.equals(src, that.src) &&
                Objects.equals(alt, that.alt);
    }

    @Override
    public int hashCode() {
        return Objects.hash(type, href, text, src, alt);
    }

    @Override
    public XContentBuilder toXContent(XContentBuilder builder, Params params) throws IOException {
        builder.startObject();
        builder.field(XField.TYPE.getPreferredName(), type.name().toLowerCase(Locale.ROOT));
        switch (type) {
            case LINK:
                builder.field(XField.HREF.getPreferredName(), href);
                if (text != null) {
                    builder.field(XField.TEXT.getPreferredName(), text);
                }
                break;
            case IMAGE:
                builder.field(XField.SRC.getPreferredName(), src);
                if (href != null) {
                    builder.field(XField.HREF.getPreferredName(), href);
                }
                if (alt != null) {
                    builder.field(XField.ALT.getPreferredName(), alt);
                }
        }
        return builder.endObject();
    }

    public static IncidentEventContext parse(XContentParser parser) throws IOException {
        Type type = null;
        String href = null;
        String text = null;
        String src = null;
        String alt = null;

        String currentFieldName = null;
        XContentParser.Token token;
        while ((token = parser.nextToken()) != XContentParser.Token.END_OBJECT) {
            if (token == XContentParser.Token.FIELD_NAME) {
                currentFieldName = parser.currentName();
            } else if (Strings.hasLength(currentFieldName)) {
                if (XField.TYPE.match(currentFieldName, parser.getDeprecationHandler())) {
                    try {
                        type = Type.valueOf(parser.text().toUpperCase(Locale.ROOT));
                    } catch (IllegalArgumentException e) {
                        String msg = "could not parse trigger incident event context. unknown context type [{}]";
                        throw new ElasticsearchParseException(msg, parser.text());
                    }
                } else {
                    if (XField.HREF.match(currentFieldName, parser.getDeprecationHandler())) {
                        href = parser.text();
                    } else if (XField.TEXT.match(currentFieldName, parser.getDeprecationHandler())) {
                        text = parser.text();
                    } else if (XField.SRC.match(currentFieldName, parser.getDeprecationHandler())) {
                        src = parser.text();
                    } else if (XField.ALT.match(currentFieldName, parser.getDeprecationHandler())) {
                        alt = parser.text();
                    } else {
                        String msg = "could not parse trigger incident event context. unknown field [{}]";
                        throw new ElasticsearchParseException(msg, currentFieldName);
                    }
                }
            }
        }

        return createAndValidateTemplate(type, href, src, alt, text);
    }

    private static IncidentEventContext createAndValidateTemplate(Type type, String href, String src, String alt,
                                                      String text) {
        if (type == null) {
            throw new ElasticsearchParseException("could not parse trigger incident event context. missing required field [{}]",
                XField.TYPE.getPreferredName());
        }

        switch (type) {
            case LINK:
                if (href == null) {
                    throw new ElasticsearchParseException("could not parse trigger incident event context. missing required field " +
                        "[{}] for [{}] context", XField.HREF.getPreferredName(), Type.LINK.name().toLowerCase(Locale.ROOT));
                }
                if (src != null) {
                    throw new ElasticsearchParseException("could not parse trigger incident event context. unexpected field [{}] for " +
                        "[{}] context", XField.SRC.getPreferredName(), Type.LINK.name().toLowerCase(Locale.ROOT));
                }
                if (alt != null) {
                    throw new ElasticsearchParseException("could not parse trigger incident event context. unexpected field [{}] for " +
                        "[{}] context", XField.ALT.getPreferredName(), Type.LINK.name().toLowerCase(Locale.ROOT));
                }
                return link(href, text);
            case IMAGE:
                if (src == null) {
                    throw new ElasticsearchParseException("could not parse trigger incident event context. missing required field " +
                        "[{}] for [{}] context", XField.SRC.getPreferredName(), Type.IMAGE.name().toLowerCase(Locale.ROOT));
                }
                if (text != null) {
                    throw new ElasticsearchParseException("could not parse trigger incident event context. unexpected field [{}] for " +
                        "[{}] context", XField.TEXT.getPreferredName(), Type.IMAGE.name().toLowerCase(Locale.ROOT));
                }
                return image(src, href, alt);
            default:
                throw new ElasticsearchParseException("could not parse trigger incident event context. unknown context type [{}]",
                    type);
        }
    }

    public static class Template implements ToXContentObject {

        final Type type;
        final TextTemplate href;
        final TextTemplate text;
        final TextTemplate src;
        final TextTemplate alt;

        public static Template link(TextTemplate href, @Nullable TextTemplate text) {
            if (href == null) {
                throw new IllegalStateException("could not create link context for pager duty trigger incident event. missing required " +
                        "[href] setting");
            }
            return new Template(Type.LINK, href, text, null, null);
        }

        public static Template image(TextTemplate src, @Nullable TextTemplate href, @Nullable TextTemplate alt) {
            if (src == null) {
                throw new IllegalStateException("could not create link context for pager duty trigger incident event. missing required " +
                        "[src] setting");
            }
            return new Template(Type.IMAGE, href, null, src, alt);
        }

        private Template(Type type, TextTemplate href, TextTemplate text, TextTemplate src, TextTemplate alt) {
            this.type = type;
            this.href = href;
            this.text = text;
            this.src = src;
            this.alt = alt;
        }

        @Override
        public boolean equals(Object o) {
            if (this == o) return true;
            if (o == null || getClass() != o.getClass()) return false;

            Template that = (Template) o;
            return Objects.equals(type, that.type) &&
                    Objects.equals(href, that.href) &&
                    Objects.equals(text, that.text) &&
                    Objects.equals(src, that.src) &&
                    Objects.equals(alt, that.alt);
        }

        @Override
        public int hashCode() {
            return Objects.hash(type, href, text, src, alt);
        }

        public IncidentEventContext render(TextTemplateEngine engine, Map<String, Object> model, IncidentEventDefaults defaults) {
            switch (type) {
                case LINK:
                    String href = this.href != null ? engine.render(this.href, model) : defaults.link.href;
                    String text = this.text != null ? engine.render(this.text, model) : defaults.link.text;
                    return IncidentEventContext.link(href, text);

                default:
                    assert type == Type.IMAGE;
                    String src = this.src != null ? engine.render(this.src, model) : defaults.image.src;
                    href = this.href != null ? engine.render(this.href, model) : defaults.image.href;
                    String alt = this.alt != null ? engine.render(this.alt, model) : defaults.image.alt;
                    return IncidentEventContext.image(src, href, alt);
            }
        }

        @Override
        public XContentBuilder toXContent(XContentBuilder builder, Params params) throws IOException {
            builder.startObject();
            builder.field(XField.TYPE.getPreferredName(), type.name().toLowerCase(Locale.ROOT));
            switch (type) {
                case LINK:
                    builder.field(XField.HREF.getPreferredName(), href, params);
                    if (text != null) {
                        builder.field(XField.TEXT.getPreferredName(), text, params);
                    }
                    break;
                case IMAGE:
                    builder.field(XField.SRC.getPreferredName(), src, params);
                    if (href != null) {
                        builder.field(XField.HREF.getPreferredName(), href, params);
                    }
                    if (alt != null) {
                        builder.field(XField.ALT.getPreferredName(), alt, params);
                    }
            }
            return builder.endObject();
        }

        public static Template parse(XContentParser parser) throws IOException {
            Type type = null;
            TextTemplate href = null;
            TextTemplate text = null;
            TextTemplate src = null;
            TextTemplate alt = null;

            String currentFieldName = null;
            XContentParser.Token token;
            while ((token = parser.nextToken()) != XContentParser.Token.END_OBJECT) {
                if (token == XContentParser.Token.FIELD_NAME) {
                    currentFieldName = parser.currentName();
                } else if (Strings.hasLength(currentFieldName)) {
                    if (XField.TYPE.match(currentFieldName, parser.getDeprecationHandler())) {
                        try {
                            type = Type.valueOf(parser.text().toUpperCase(Locale.ROOT));
                        } catch (IllegalArgumentException e) {
                            String msg = "could not parse trigger incident event context. unknown context type [{}]";
                            throw new ElasticsearchParseException(msg, parser.text());
                        }
                    } else {
                        TextTemplate parsedTemplate;
                        try {
                            parsedTemplate = TextTemplate.parse(parser);
                        } catch (ElasticsearchParseException e) {
                            String msg = "could not parse trigger incident event context. failed to parse [{}] field";
                            throw new ElasticsearchParseException(msg, e, currentFieldName);
                        }

                        if (XField.HREF.match(currentFieldName, parser.getDeprecationHandler())) {
                            href = parsedTemplate;
                        } else if (XField.TEXT.match(currentFieldName, parser.getDeprecationHandler())) {
                            text = parsedTemplate;
                        } else if (XField.SRC.match(currentFieldName, parser.getDeprecationHandler())) {
                            src = parsedTemplate;
                        } else if (XField.ALT.match(currentFieldName, parser.getDeprecationHandler())) {
                            alt = parsedTemplate;
                        } else {
                            String msg = "could not parse trigger incident event context. unknown field [{}]";
                            throw new ElasticsearchParseException(msg, currentFieldName);
                        }
                    }
                }
            }

            return createAndValidateTemplate(type, href, src, alt, text);
        }

        private static Template createAndValidateTemplate(Type type, TextTemplate href, TextTemplate src, TextTemplate alt,
                                                          TextTemplate text) {
            if (type == null) {
                throw new ElasticsearchParseException("could not parse trigger incident event context. missing required field [{}]",
                        XField.TYPE.getPreferredName());
            }

            switch (type) {
                case LINK:
                    if (href == null) {
                        throw new ElasticsearchParseException("could not parse trigger incident event context. missing required field " +
                                "[{}] for [{}] context", XField.HREF.getPreferredName(), Type.LINK.name().toLowerCase(Locale.ROOT));
                    }
                    if (src != null) {
                        throw new ElasticsearchParseException("could not parse trigger incident event context. unexpected field [{}] for " +
                                "[{}] context", XField.SRC.getPreferredName(), Type.LINK.name().toLowerCase(Locale.ROOT));
                    }
                    if (alt != null) {
                        throw new ElasticsearchParseException("could not parse trigger incident event context. unexpected field [{}] for " +
                                "[{}] context", XField.ALT.getPreferredName(), Type.LINK.name().toLowerCase(Locale.ROOT));
                    }
                    return link(href, text);
                case IMAGE:
                    if (src == null) {
                        throw new ElasticsearchParseException("could not parse trigger incident event context. missing required field " +
                                "[{}] for [{}] context", XField.SRC.getPreferredName(), Type.IMAGE.name().toLowerCase(Locale.ROOT));
                    }
                    if (text != null) {
                        throw new ElasticsearchParseException("could not parse trigger incident event context. unexpected field [{}] for " +
                                "[{}] context", XField.TEXT.getPreferredName(), Type.IMAGE.name().toLowerCase(Locale.ROOT));
                    }
                    return image(src, href, alt);
                default:
                    throw new ElasticsearchParseException("could not parse trigger incident event context. unknown context type [{}]",
                            type);
            }
        }

    }

    interface XField {
        ParseField TYPE = new ParseField("type");
        ParseField HREF = new ParseField("href");

        // "link" context fields
        ParseField TEXT = new ParseField("text");

        // "image" context fields
        ParseField SRC = new ParseField("src");
        ParseField ALT = new ParseField("alt");

    }
}