text:
// Copyright (c) 2010-2013 SharpDX - Alexandre Mutel
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
using System;
using System.Runtime.InteropServices;
using SharpDX.Direct3D;
using SharpDX.DXGI;

namespace SharpDX.Direct3D11
{
    public partial class Device
    {
        /// <summary>
        /// Initializes a new instance of the <see cref="Device"/> class.
        /// </summary>
        /// <param name="driverType">
        /// Type of the driver.
        /// </param>
        /// <msdn-id>ff476082</msdn-id>
        /// <unmanaged>HRESULT D3D11CreateDevice([In, Optional] IDXGIAdapter* pAdapter,[In] D3D_DRIVER_TYPE DriverType,[In] HINSTANCE Software,[In] D3D11_CREATE_DEVICE_FLAG Flags,[In, Buffer, Optional] const D3D_FEATURE_LEVEL* pFeatureLevels,[In] unsigned int FeatureLevels,[In] unsigned int SDKVersion,[Out, Fast] ID3D11Device** ppDevice,[Out, Optional] D3D_FEATURE_LEVEL* pFeatureLevel,[Out, Optional] ID3D11DeviceContext** ppImmediateContext)</unmanaged>
        /// <unmanaged-short>D3D11CreateDevice</unmanaged-short>
        public Device(DriverType driverType)
            : this(driverType, DeviceCreationFlags.None)
        {
        }

        /// <summary>
        /// Initializes a new instance of the <see cref="Device"/> class.
        /// </summary>
        /// <param name="adapter">
        /// The adapter.
        /// </param>
        /// <msdn-id>ff476082</msdn-id>
        /// <unmanaged>HRESULT D3D11CreateDevice([In, Optional] IDXGIAdapter* pAdapter,[In] D3D_DRIVER_TYPE DriverType,[In] HINSTANCE Software,[In] D3D11_CREATE_DEVICE_FLAG Flags,[In, Buffer, Optional] const D3D_FEATURE_LEVEL* pFeatureLevels,[In] unsigned int FeatureLevels,[In] unsigned int SDKVersion,[Out, Fast] ID3D11Device** ppDevice,[Out, Optional] D3D_FEATURE_LEVEL* pFeatureLevel,[Out, Optional] ID3D11DeviceContext** ppImmediateContext)</unmanaged>
        /// <unmanaged-short>D3D11CreateDevice</unmanaged-short>
        public Device(Adapter adapter)
            : this(adapter, DeviceCreationFlags.None)
        {
        }

        /// <summary>
        /// Constructor for a D3D11 Device. See <see cref="SharpDX.Direct3D11.D3D11.CreateDevice"/> for more information.
        /// </summary>
        /// <param name="driverType">Type of the driver.</param>
        /// <param name="flags">The flags.</param>
        /// <msdn-id>ff476082</msdn-id>
        /// <unmanaged>HRESULT D3D11CreateDevice([In, Optional] IDXGIAdapter* pAdapter,[In] D3D_DRIVER_TYPE DriverType,[In] HINSTANCE Software,[In] D3D11_CREATE_DEVICE_FLAG Flags,[In, Buffer, Optional] const D3D_FEATURE_LEVEL* pFeatureLevels,[In] unsigned int FeatureLevels,[In] unsigned int SDKVersion,[Out, Fast] ID3D11Device** ppDevice,[Out, Optional] D3D_FEATURE_LEVEL* pFeatureLevel,[Out, Optional] ID3D11DeviceContext** ppImmediateContext)</unmanaged>
        /// <unmanaged-short>D3D11CreateDevice</unmanaged-short>
        public Device(DriverType driverType, DeviceCreationFlags flags)
        {
            CreateDevice(null, driverType, flags, null);
        }

        /// <summary>
        ///   Constructor for a D3D11 Device. See <see cref = "SharpDX.Direct3D11.D3D11.CreateDevice" /> for more information.
        /// </summary>
        /// <param name = "adapter"></param>
        /// <param name = "flags"></param>
        /// <msdn-id>ff476082</msdn-id>
        /// <unmanaged>HRESULT D3D11CreateDevice([In, Optional] IDXGIAdapter* pAdapter,[In] D3D_DRIVER_TYPE DriverType,[In] HINSTANCE Software,[In] D3D11_CREATE_DEVICE_FLAG Flags,[In, Buffer, Optional] const D3D_FEATURE_LEVEL* pFeatureLevels,[In] unsigned int FeatureLevels,[In] unsigned int SDKVersion,[Out, Fast] ID3D11Device** ppDevice,[Out, Optional] D3D_FEATURE_LEVEL* pFeatureLevel,[Out, Optional] ID3D11DeviceContext** ppImmediateContext)</unmanaged>
        /// <unmanaged-short>D3D11CreateDevice</unmanaged-short>
        public Device(Adapter adapter, DeviceCreationFlags flags)
        {
            CreateDevice(adapter, DriverType.Unknown, flags, null);
        }

        /// <summary>
        ///   Constructor for a D3D11 Device. See <see cref = "SharpDX.Direct3D11.D3D11.CreateDevice" /> for more information.
        /// </summary>
        /// <param name = "driverType"></param>
        /// <param name = "flags"></param>
        /// <param name = "featureLevels"></param>
        /// <msdn-id>ff476082</msdn-id>
        /// <unmanaged>HRESULT D3D11CreateDevice([In, Optional] IDXGIAdapter* pAdapter,[In] D3D_DRIVER_TYPE DriverType,[In] HINSTANCE Software,[In] D3D11_CREATE_DEVICE_FLAG Flags,[In, Buffer, Optional] const D3D_FEATURE_LEVEL* pFeatureLevels,[In] unsigned int FeatureLevels,[In] unsigned int SDKVersion,[Out, Fast] ID3D11Device** ppDevice,[Out, Optional] D3D_FEATURE_LEVEL* pFeatureLevel,[Out, Optional] ID3D11DeviceContext** ppImmediateContext)</unmanaged>
        /// <unmanaged-short>D3D11CreateDevice</unmanaged-short>
        public Device(DriverType driverType, DeviceCreationFlags flags, params FeatureLevel[] featureLevels)
        {
            CreateDevice(null, driverType, flags, featureLevels);
        }

        /// <summary>
        ///   Constructor for a D3D11 Device. See <see cref = "SharpDX.Direct3D11.D3D11.CreateDevice" /> for more information.
        /// </summary>
        /// <param name = "adapter"></param>
        /// <param name = "flags"></param>
        /// <param name = "featureLevels"></param>
        /// <msdn-id>ff476082</msdn-id>
        /// <unmanaged>HRESULT D3D11CreateDevice([In, Optional] IDXGIAdapter* pAdapter,[In] D3D_DRIVER_TYPE DriverType,[In] HINSTANCE Software,[In] D3D11_CREATE_DEVICE_FLAG Flags,[In, Buffer, Optional] const D3D_FEATURE_LEVEL* pFeatureLevels,[In] unsigned int FeatureLevels,[In] unsigned int SDKVersion,[Out, Fast] ID3D11Device** ppDevice,[Out, Optional] D3D_FEATURE_LEVEL* pFeatureLevel,[Out, Optional] ID3D11DeviceContext** ppImmediateContext)</unmanaged>
        /// <unmanaged-short>D3D11CreateDevice</unmanaged-short>
        public Device(Adapter adapter, DeviceCreationFlags flags, params FeatureLevel[] featureLevels)
        {
            CreateDevice(adapter, DriverType.Unknown, flags, featureLevels);
        }

#if !W8CORE

        /// <summary>
        ///   Initializes a new instance of the <see cref = "T:SharpDX.Direct3D11.Device" /> class along with a new <see cref = "T:SharpDX.DXGI.SwapChain" /> used for rendering.
        /// </summary>
        /// <param name = "driverType">The type of device to create.</param>
        /// <param name = "flags">A list of runtime layers to enable.</param>
        /// <param name = "swapChainDescription">Details used to create the swap chain.</param>
        /// <param name = "device">When the method completes, contains the created device instance.</param>
        /// <param name = "swapChain">When the method completes, contains the created swap chain instance.</param>
        /// <returns>A <see cref = "T:SharpDX.Result" /> object describing the result of the operation.</returns>
        public static void CreateWithSwapChain(DriverType driverType, DeviceCreationFlags flags,
                                                 SwapChainDescription swapChainDescription, out Device device,
                                                 out SwapChain swapChain)
        {
            CreateWithSwapChain(null, driverType, flags, null, swapChainDescription, out device, out swapChain);
        }

        /// <summary>
        ///   Initializes a new instance of the <see cref = "T:SharpDX.Direct3D11.Device" /> class along with a new <see cref = "T:SharpDX.DXGI.SwapChain" /> used for rendering.
        /// </summary>
        /// <param name = "adapter">The video adapter on which the device should be created.</param>
        /// <param name = "flags">A list of runtime layers to enable.</param>
        /// <param name = "swapChainDescription">Details used to create the swap chain.</param>
        /// <param name = "device">When the method completes, contains the created device instance.</param>
        /// <param name = "swapChain">When the method completes, contains the created swap chain instance.</param>
        /// <returns>A <see cref = "T:SharpDX.Result" /> object describing the result of the operation.</returns>
        public static void CreateWithSwapChain(Adapter adapter, DeviceCreationFlags flags,
                                                 SwapChainDescription swapChainDescription, out Device device,
                                                 out SwapChain swapChain)
        {
            CreateWithSwapChain(adapter, DriverType.Unknown, flags, null, swapChainDescription, out device,
                                       out swapChain);
        }

        /// <summary>
        ///   Initializes a new instance of the <see cref = "T:SharpDX.Direct3D11.Device" /> class along with a new <see cref = "T:SharpDX.DXGI.SwapChain" /> used for rendering.
        /// </summary>
        /// <param name = "driverType">The type of device to create.</param>
        /// <param name = "flags">A list of runtime layers to enable.</param>
        /// <param name = "featureLevels">A list of feature levels which determine the order of feature levels to attempt to create.</param>
        /// <param name = "swapChainDescription">Details used to create the swap chain.</param>
        /// <param name = "device">When the method completes, contains the created device instance.</param>
        /// <param name = "swapChain">When the method completes, contains the created swap chain instance.</param>
        /// <returns>A <see cref = "T:SharpDX.Result" /> object describing the result of the operation.</returns>
        public static void CreateWithSwapChain(DriverType driverType, DeviceCreationFlags flags,
                                                 FeatureLevel[] featureLevels, SwapChainDescription swapChainDescription,
                                                 out Device device, out SwapChain swapChain)
        {
            CreateWithSwapChain(null, driverType, flags, featureLevels, swapChainDescription, out device,
                                       out swapChain);
        }

        /// <summary>
        ///   Initializes a new instance of the <see cref = "T:SharpDX.Direct3D11.Device" /> class along with a new <see cref = "T:SharpDX.DXGI.SwapChain" /> used for rendering.
        /// </summary>
        /// <param name = "adapter">The video adapter on which the device should be created.</param>
        /// <param name = "flags">A list of runtime layers to enable.</param>
        /// <param name = "featureLevels">A list of feature levels which determine the order of feature levels to attempt to create.</param>
        /// <param name = "swapChainDescription">Details used to create the swap chain.</param>
        /// <param name = "device">When the method completes, contains the created device instance.</param>
        /// <param name = "swapChain">When the method completes, contains the created swap chain instance.</param>
        /// <returns>A <see cref = "T:SharpDX.Result" /> object describing the result of the operation.</returns>
        public static void CreateWithSwapChain(Adapter adapter, DeviceCreationFlags flags,
                                                 FeatureLevel[] featureLevels, SwapChainDescription swapChainDescription,
                                                 out Device device, out SwapChain swapChain)
        {
            CreateWithSwapChain(adapter, DriverType.Unknown, flags, featureLevels, swapChainDescription,
                                       out device, out swapChain);
        }

        /// <summary>
        ///   This overload has been deprecated. Use one of the alternatives that does not take both an adapter and a driver type.
        /// </summary>
        private static void CreateWithSwapChain(Adapter adapter, DriverType driverType, DeviceCreationFlags flags,
                                                 FeatureLevel[] featureLevels, SwapChainDescription swapChainDescription,
                                                 out Device device, out SwapChain swapChain)
        {
            FeatureLevel selectedLevel;
            DeviceContext context;

            D3D11.CreateDeviceAndSwapChain(adapter, driverType, IntPtr.Zero, flags, featureLevels,
                                                           featureLevels == null ? 0 : featureLevels.Length,
                                                           D3D11.SdkVersion,
                                                           ref swapChainDescription, out swapChain, out device,
                                                           out selectedLevel, out context);

            if (context != null)
            {
                // Add a reference when setting the device on the context
                ((IUnknown)device).AddReference();
                context.Device__ = device;
            }

            device.ImmediateContext__ = context;
        }
#endif

        /// <summary>
        /// Get the type, name, units of measure, and a description of an existing counter.
        /// </summary>
        /// <param name="counterDescription">The counter description.</param>
        /// <returns>Description of the counter</returns>
        public CounterMetadata GetCounterMetadata(CounterDescription counterDescription)
        {
            unsafe
            {
                var data = new CounterMetadata();
                CounterType type;
                int hardwareCounterCount;
                int nameLength = 0;
                int unitsLength = 0;
                int descriptionLength = 0;

                // Get Length for strings
                CheckCounter(counterDescription, out type, out hardwareCounterCount, IntPtr.Zero, new IntPtr(&nameLength), IntPtr.Zero, new IntPtr(&unitsLength),
                             IntPtr.Zero, new IntPtr(&descriptionLength));

                sbyte* name = stackalloc sbyte[nameLength];
                sbyte* units = stackalloc sbyte[unitsLength];
                sbyte* description = stackalloc sbyte[descriptionLength];

                // Get strings
                CheckCounter(counterDescription, out type, out hardwareCounterCount, new IntPtr(name), new IntPtr(&nameLength), new IntPtr(units), new IntPtr(&unitsLength),
                             new IntPtr(description), new IntPtr(&descriptionLength));

                data.Type = type;
                data.HardwareCounterCount = hardwareCounterCount;
                data.Name = Marshal.PtrToStringAnsi((IntPtr)name, nameLength);
                data.Units = Marshal.PtrToStringAnsi((IntPtr)units, unitsLength);
                data.Description = Marshal.PtrToStringAnsi((IntPtr)description, descriptionLength);

                return data;
            }
        }

        /// <summary>
        /// Give a device access to a shared resource created on a different Direct3d device.
        /// </summary>
        /// <typeparam name="T">The type of the resource we are gaining access to.</typeparam>
        /// <param name="resourceHandle">A resource handle. See remarks.</param>
        /// <returns>
        /// This method returns a reference to the resource we are gaining access to.
        /// </returns>
        /// <remarks>
        /// To share a resource between two Direct3D 10 devices the resource must have been created with the  <see cref="SharpDX.Direct3D11.ResourceOptionFlags.Shared"/> flag, if it was created using the ID3D10Device interface.  If it was created using the IDXGIDevice interface, then the resource is always shared. The REFIID, or GUID, of the interface to the resource can be obtained by using the __uuidof() macro.  For example, __uuidof(ID3D10Buffer) will get the GUID of the interface to a buffer resource. When sharing a resource between two Direct3D 10 devices the unique handle of the resource can be obtained by querying the resource for the <see cref="SharpDX.DXGI.Resource"/> interface and then calling {{GetSharedHandle}}.
        /// <code> IDXGIResource* pOtherResource(NULL);
        /// hr = pOtherDeviceResource->QueryInterface( __uuidof(IDXGIResource), (void**)&pOtherResource );
        /// HANDLE sharedHandle;
        /// pOtherResource->GetSharedHandle(&sharedHandle); </code>
        /// The only resources that can be shared are 2D non-mipmapped textures. To share a resource between a Direct3D 9 device and a Direct3D 10 device the texture must have been created using  the pSharedHandle argument of {{CreateTexture}}.   The shared Direct3D 9 handle is then passed to OpenSharedResource in the hResource argument. The following code illustrates the method calls involved.
        /// <code> sharedHandle = NULL; // must be set to NULL to create, can use a valid handle here to open in D3D9
        /// pDevice9->CreateTexture(..., pTex2D_9, &sharedHandle);
        /// ...
        /// pDevice10->OpenSharedResource(sharedHandle, __uuidof(ID3D10Resource), (void**)(&tempResource10));
        /// tempResource10->QueryInterface(__uuidof(ID3D10Texture2D), (void**)(&pTex2D_10));
        /// tempResource10->Release();
        /// // now use pTex2D_10 with pDevice10    </code>
        /// Textures being shared from D3D9 to D3D10 have the following restrictions.  Textures must be 2D Only 1 mip level is allowed Texture must have default usage Texture must be write only MSAA textures are not allowed Bind flags must have SHADER_RESOURCE and RENDER_TARGET set Only R10G10B10A2_UNORM, R16G16B16A16_FLOAT and R8G8B8A8_UNORM formats are allowed  If a shared texture is updated on one device <see cref="SharpDX.Direct3D11.DeviceContext.Flush"/> must be called on that device.
        /// </remarks>
        /// <unmanaged>HRESULT ID3D10Device::OpenSharedResource([In] void* hResource,[In] GUID* ReturnedInterface,[Out, Optional] void** ppResource)</unmanaged>
        public T OpenSharedResource<T>(IntPtr resourceHandle) where T : ComObject
        {
            IntPtr temp;
            OpenSharedResource(resourceHandle, Utilities.GetGuidFromType(typeof(T)), out temp);
            return FromPointer<T>(temp);
        }

        /// <summary>
        /// Check if this device is supporting compute shaders for the specified format.
        /// </summary>
        /// <param name="format">The format for which to check support.</param>
        /// <returns>Flags indicating usage contexts in which the specified format is supported.</returns>
	    public ComputeShaderFormatSupport CheckComputeShaderFormatSupport( Format format )
        {
            unsafe
            {
                FeatureDataFormatSupport2 support = default(FeatureDataFormatSupport2);
                support.InFormat = format;
                if (CheckFeatureSupport(Feature.ComputeShaders, new IntPtr(&support), Utilities.SizeOf<FeatureDataFormatSupport2>()).Failure)
                    return ComputeShaderFormatSupport.None;
                return support.OutFormatSupport2;
            }
        }

#if DIRECTX11_1
        /// <summary>
        /// <p>Gets information about the features <see cref="Feature.D3D11Options"/> that are supported by the current graphics driver.</p>
        /// </summary>
        /// <returns>Returns a structure <see cref="FeatureDataD3D11Options"/> </returns>
        /// <msdn-id>ff476497</msdn-id>
        /// <unmanaged>HRESULT ID3D11Device::CheckFeatureSupport([In] D3D11_FEATURE Feature,[Out, Buffer] void* pFeatureSupportData,[In] unsigned int FeatureSupportDataSize)</unmanaged>
        /// <unmanaged-short>ID3D11Device::CheckFeatureSupport</unmanaged-short>
        public FeatureDataD3D11Options CheckD3D11Feature()
        {
            unsafe
            {
                var support = default(FeatureDataD3D11Options);
                if (CheckFeatureSupport(Feature.D3D11Options, new IntPtr(&support), Utilities.SizeOf<FeatureDataD3D11Options>()).Failure)
                    return default(FeatureDataD3D11Options);
                return support;
            }
        }

        /// <summary>
        /// <p>Gets information about the features <see cref="Feature.ShaderMinimumPrecisionSupport"/> that are supported by the current graphics driver.</p>
        /// </summary>
        /// <returns>Returns a structure <see cref="FeatureDataShaderMinimumPrecisionSupport"/> </returns>
        /// <msdn-id>ff476497</msdn-id>
        /// <unmanaged>HRESULT ID3D11Device::CheckFeatureSupport([In] D3D11_FEATURE Feature,[Out, Buffer] void* pFeatureSupportData,[In] unsigned int FeatureSupportDataSize)</unmanaged>
        /// <unmanaged-short>ID3D11Device::CheckFeatureSupport</unmanaged-short>
        public FeatureDataShaderMinimumPrecisionSupport CheckShaderMinimumPrecisionSupport()
        {
            unsafe
            {
                var support = default(FeatureDataShaderMinimumPrecisionSupport);
                if (CheckFeatureSupport(Feature.ShaderMinimumPrecisionSupport, new IntPtr(&support), Utilities.SizeOf<FeatureDataShaderMinimumPrecisionSupport>()).Failure)
                    return default(FeatureDataShaderMinimumPrecisionSupport);
                return support;
            }
        }

        /// <summary>
        /// <p>Gets information about whether the driver supports the nonpowers-of-2-unconditionally feature. <strong>TRUE</strong> for hardware at Direct3D 10 and higher feature levels. </p>
        /// </summary>
        /// <returns>Returns <strong>true</strong> if this hardware supports non-powers-of-2 texture. This returns always true Direct3D 10 and higher feature levels.</returns>
        /// <msdn-id>ff476497</msdn-id>
        /// <unmanaged>HRESULT ID3D11Device::CheckFeatureSupport([In] D3D11_FEATURE Feature,[Out, Buffer] void* pFeatureSupportData,[In] unsigned int FeatureSupportDataSize)</unmanaged>
        /// <unmanaged-short>ID3D11Device::CheckFeatureSupport</unmanaged-short>
        public bool CheckFullNonPow2TextureSupport()
        {
            unsafe
            {
                var support = default(FeatureDataD3D9Options);
                var result = CheckFeatureSupport(Feature.D3D9Options, new IntPtr(&support), Utilities.SizeOf<FeatureDataD3D9Options>());
                if (FeatureLevel <= FeatureLevel.Level_9_3)
                {
                    return result.Failure;
                }
                if (result.Failure)
                    return false;
                return support.FullNonPow2TextureSupport;
            }
        }

        /// <summary>
        /// <p>Gets information about whether a rendering device batches rendering commands and performs multipass rendering into tiles or bins over a render area. Certain API usage patterns that are fine TileBasedDefferredRenderers (TBDRs) can perform worse on non-TBDRs and vice versa.  Applications that are careful about rendering can be friendly to both TBDR and non-TBDR architectures.</p>
        /// </summary>
        /// <returns>Returns <strong>TRUE</strong> if the rendering device batches rendering commands and <strong><see cref="SharpDX.Result.False"/></strong> otherwise.</returns>
        /// <msdn-id>ff476497</msdn-id>
        /// <unmanaged>HRESULT ID3D11Device::CheckFeatureSupport([In] D3D11_FEATURE Feature,[Out, Buffer] void* pFeatureSupportData,[In] unsigned int FeatureSupportDataSize)</unmanaged>
        /// <unmanaged-short>ID3D11Device::CheckFeatureSupport</unmanaged-short>
        public bool CheckTileBasedDeferredRendererSupport()
        {
            unsafe
            {
                var support = default(FeatureDataArchitectureInformation);
                if (CheckFeatureSupport(Feature.ArchitectureInformation, new IntPtr(&support), Utilities.SizeOf<FeatureDataArchitectureInformation>()).Failure)
                    return false;
                return support.TileBasedDeferredRenderer;
            }
        }
#endif

#if DIRECTX11_2
        public FeatureDataD3D11Options1 CheckD3D112Feature()
        {
            unsafe
            {
                var support = default(FeatureDataD3D11Options1);
                if (CheckFeatureSupport(Feature.D3D11Options1, new IntPtr(&support), Utilities.SizeOf<FeatureDataD3D11Options1>()).Failure)
                    return default(FeatureDataD3D11Options1);
                return support;
            }
        }
#endif

        /// <summary>
        /// Check if this device is supporting a feature.
        /// </summary>
        /// <param name="feature">The feature to check.</param>
        /// <returns>
        /// Returns true if this device supports this feature, otherwise false.
        /// </returns>
        public bool CheckFeatureSupport(Feature feature)
        {
            unsafe
            {
                switch (feature)
                {
                    case Feature.ShaderDoubles:
                        {
                            FeatureDataDoubles support;

                            if (CheckFeatureSupport(Feature.ShaderDoubles, new IntPtr(&support), Utilities.SizeOf<FeatureDataDoubles>()).Failure)
                                return false;
                            return support.DoublePrecisionFloatShaderOps;
                        }
                    case Feature.ComputeShaders:
                    case Feature.D3D10XHardwareOptions:
                        {
                            FeatureDataD3D10XHardwareOptions support;
                            if (CheckFeatureSupport(Feature.D3D10XHardwareOptions, new IntPtr(&support), Utilities.SizeOf<FeatureDataD3D10XHardwareOptions>()).Failure)
                                return false;
                            return support.ComputeShadersPlusRawAndStructuredBuffersViaShader4X;
                        }
                    default:
                        throw new SharpDXException("Unsupported Feature. Use specialized CheckXXX methods");
                }
            }
        }

        /// <summary>
        /// Check if this device is supporting threading.
        /// </summary>
        /// <param name="supportsConcurrentResources">Support concurrent resources.</param>
        /// <param name="supportsCommandLists">Support command lists.</param>
        /// <returns>
        /// A <see cref="T:SharpDX.Result"/> object describing the result of the operation.
        /// </returns>
        public Result CheckThreadingSupport( out bool supportsConcurrentResources, out bool supportsCommandLists )
        {
            unsafe
            {
                var support = default(FeatureDataThreading);
                var result = CheckFeatureSupport(Feature.Threading, new IntPtr(&support), Utilities.SizeOf<FeatureDataThreading>());

                if (result.Failure)
                {
                    supportsConcurrentResources = false;
                    supportsCommandLists = false;
                }
                else
                {
                    supportsConcurrentResources = support.DriverConcurrentCreates;
                    supportsCommandLists = support.DriverCommandLists;
                }

                return result;
            }
        }

        /// <summary>
        /// Check if a feature level is supported by a primary adapter.
        /// </summary>
        /// <param name="featureLevel">The feature level.</param>
        /// <returns><c>true</c> if the primary adapter is supporting this feature level; otherwise, <c>false</c>.</returns>
        public static bool IsSupportedFeatureLevel(FeatureLevel featureLevel)
        {
            var device = new Device(IntPtr.Zero);
            DeviceContext context = null;
            try
            {
                FeatureLevel outputLevel;
                var result = D3D11.CreateDevice(null, DriverType.Hardware, IntPtr.Zero, DeviceCreationFlags.None,
                                                new[] {featureLevel}, 1, D3D11.SdkVersion, device, out outputLevel,
                                                out context);
                return result.Success && outputLevel == featureLevel;
            }
            finally
            {
                if (context != null)
                {
                    context.Dispose();
                }

                if (device.NativePointer != IntPtr.Zero)
                {
                    device.Dispose();
                }
            }
        }

        /// <summary>
        /// Check if a feature level is supported by a particular adapter.
        /// </summary>
        /// <param name="adapter">The adapter.</param>
        /// <param name="featureLevel">The feature level.</param>
        /// <returns><c>true</c> if the specified adapter is supporting this feature level; otherwise, <c>false</c>.</returns>
        public static bool IsSupportedFeatureLevel(Adapter adapter, FeatureLevel featureLevel)
        {
            var device = new Device(IntPtr.Zero);
            DeviceContext context = null;
            try
            {
                FeatureLevel outputLevel;
                var result = D3D11.CreateDevice(adapter, DriverType.Unknown, IntPtr.Zero, DeviceCreationFlags.None,
                                                new[] { featureLevel }, 1, D3D11.SdkVersion, device, out outputLevel,
                                                out context);
                return result.Success && outputLevel == featureLevel;
            }
            finally
            {
                if (context != null)
                {
                    context.Dispose();
                }

                if (device.NativePointer != IntPtr.Zero)
                {
                    device.Dispose();
                }
            }
        }

        /// <summary>
        /// Gets the highest supported hardware feature level of the primary adapter.
        /// </summary>
        /// <returns>The highest supported hardware feature level.</returns>
        public static FeatureLevel GetSupportedFeatureLevel()
        {
            FeatureLevel outputLevel;
            var device = new Device(IntPtr.Zero);
            DeviceContext context;
            D3D11.CreateDevice(null, DriverType.Hardware, IntPtr.Zero, DeviceCreationFlags.None, null, 0, D3D11.SdkVersion, device, out outputLevel,
                               out context).CheckError();
            context.Dispose();
            device.Dispose();
            return outputLevel;
        }

        /// <summary>
        /// Gets the highest supported hardware feature level of the primary adapter.
        /// </summary>
        /// <param name="adapter">The adapter.</param>
        /// <returns>
        /// The highest supported hardware feature level.
        /// </returns>
        public static FeatureLevel GetSupportedFeatureLevel(Adapter adapter)
        {
            FeatureLevel outputLevel;
            var device = new Device(IntPtr.Zero);
            DeviceContext context;
            D3D11.CreateDevice(adapter, DriverType.Unknown, IntPtr.Zero, DeviceCreationFlags.None, null, 0, D3D11.SdkVersion, device, out outputLevel,
                               out context).CheckError();
            context.Dispose();
            device.Dispose();
            return outputLevel;
        }
#if !DIRECTX11_1
        /// <summary>
        /// Gets a value indicating whether the current device is using the reference rasterizer.
        /// </summary>
        public bool IsReferenceDevice
        {
            get
            {
                try
                {
                    var switchToRef = QueryInterface<SwitchToRef>();
                    return switchToRef.UseRef;
                }
                catch (SharpDXException)
                {
                    return false;
                }
            }
        }
#endif

        /// <summary>
        /// Gets or sets the debug-name for this object.
        /// </summary>
        /// <value>
        /// The debug name.
        /// </value>
        public string DebugName
        {
            get
            {
                unsafe
                {
                    byte* pname = stackalloc byte[1024];
                    int size = 1024 - 1;
                    if (GetPrivateData(CommonGuid.DebugObjectName, ref size, new IntPtr(pname)).Failure)
                        return string.Empty;
                    pname[size] = 0;
                    return Marshal.PtrToStringAnsi(new IntPtr(pname));
                }
            }

            set
            {
                if (string.IsNullOrEmpty(value))
                {
                    SetPrivateData(CommonGuid.DebugObjectName, 0, IntPtr.Zero);
                }
                else
                {
                    var namePtr = Utilities.StringToHGlobalAnsi(value);
                    SetPrivateData(CommonGuid.DebugObjectName, value.Length, namePtr);
                    // Warning, allocated string should not be released!
                }
            }
        }

        protected override void Dispose(bool disposing)
        {
            if (disposing)
            {
                if (ImmediateContext__ != null)
                {
                    ImmediateContext__.Dispose();
                    ImmediateContext__ = null;
                }
            }
            base.Dispose(disposing);
        }

        /// <summary>
        ///   Internal CreateDevice
        /// </summary>
        /// <param name = "adapter"></param>
        /// <param name = "driverType"></param>
        /// <param name = "flags"></param>
        /// <param name = "featureLevels"></param>
        private void CreateDevice(Adapter adapter, DriverType driverType, DeviceCreationFlags flags,
                                  FeatureLevel[] featureLevels)
        {
            FeatureLevel selectedLevel;
            D3D11.CreateDevice(adapter, driverType, IntPtr.Zero, flags, featureLevels,
                                        featureLevels == null ? 0 : featureLevels.Length, D3D11.SdkVersion, this,
                                        out selectedLevel, out ImmediateContext__).CheckError();

            if (ImmediateContext__ != null)
            {
                // Add a reference when setting the device on the context
                ((IUnknown)this).AddReference();
                ImmediateContext__.Device__ = this;
            }
        }
    }
}


text:
<!DOCTYPE HTML>

<title>TextLine</title>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<meta name="dc.created" content="2020-09-06">
<link rel="stylesheet" type="text/css" href="../../stylesheet.css" title="Style">
<link rel="stylesheet" type="text/css" href="../../jquery/jquery-ui.css" title="Style">

JavaScript is disabled on your browser.

Skip navigation links

Package

Class

Tree

Deprecated

Index

Help

All Classes

SEARCH:
<input type="text" id="search" value="search" disabled="disabled">
<input type="reset" id="reset" value="reset" disabled="disabled">

JavaScript is disabled on your browser.

Summary:

Nested |

Field |

Constr |

Method

Detail:

Field |

Constr |

Method

Package PDFjet.NET

Class TextLine

Object

PDFjet.NET.TextLine

All Implemented Interfaces:

IDrawable

public class TextLine
extends Object
implements IDrawable

Used to create text line objects.

Constructor Summary

Constructors

Constructor
Description

TextLine(Font font)

Constructor for creating text line objects.

TextLine(Font font,
        String text)

Constructor for creating text line objects.

Method Summary

All Methods Instance Methods Concrete Methods

Modifier and Type
Method
Description

float
advance(float leading)

float[]
DrawOn(Page page)

Draws this text line on the specified page.

String
GetActualText()

String
GetAltDescription()

int
GetColor()

Returns the text line color.

float
GetDestinationY()

Returns the y coordinate of the destination.

Font
GetFallbackFont()

Returns the fallback font.

Font
GetFont()

Gets the font to use for this text line.

String
GetGoToAction()

Returns the GoTo action string.

float
GetHeight()

Returns the height of this TextLine.

String
GetLanguage()

boolean
GetStrikeout()

Returns the strikeout flag.

float
getStringWidth(String text)

String
GetText()

Returns the text.

int
GetTextDirection()

Returns the text direction.

int
GetTextEffect()

Returns the text effect.

boolean
GetTrailingSpace()

Returns the trailing space.

boolean
GetUnderline()

Returns the underline flag.

String
GetURIAction()

Returns the action URI.

float
GetVerticalOffset()

Returns the vertical text offset.

float
GetWidth()

Returns the width of this TextLine.

TextLine
PlaceIn(Box box)

Places this text line in the specified box.

TextLine
PlaceIn(Box box,
       double xOffset,
       double yOffset)

Places this text line in the box at the specified offset.

TextLine
PlaceIn(Box box,
       float xOffset,
       float yOffset)

Places this text line in the box at the specified offset.

TextLine
SetActualText(String actualText)

Sets the actual text for this text line.

TextLine
SetAltDescription(String altDescription)

Sets the alternate description of this text line.

TextLine
SetColor(int color)

Sets the color for this text line.

TextLine
SetColor(int[] color)

Sets the pen color.

TextLine
SetFallbackFont(Font fallbackFont)

Sets the fallback font.

TextLine
SetFallbackFontSize(float fallbackFontSize)

Sets the fallback font size to use for this text line.

TextLine
SetFont(Font font)

Sets the font to use for this text line.

TextLine
SetFontSize(float fontSize)

Sets the font size to use for this text line.

TextLine
SetGoToAction(String key)

Sets the destination key for the action.

TextLine
SetLanguage(String language)

TextLine
SetLocation(double x,
           double y)

TextLine
SetLocation(float x,
           float y)

Sets the location where this text line will be drawn on the page.

void
SetPosition(double x,
           double y)

Sets the position where this text line will be drawn on the page.

void
SetPosition(float x,
           float y)

Sets the position where this text line will be drawn on the page.

TextLine
SetStrikeout(boolean strikeout)

Sets the strike variable.

TextLine
SetText(String text)

Sets the text.

TextLine
SetTextDirection(int degrees)

Sets the direction in which to draw the text.

TextLine
SetTextEffect(int textEffect)

Sets the text effect.

TextLine
SetTrailingSpace(boolean trailingSpace)

Sets the trailing space after this text line when used in paragraph.

TextLine
SetUnderline(boolean underline)

Sets the underline variable.

TextLine
SetURIAction(String uri)

Sets the URI for the "click text line" action.

TextLine
SetURIActualText(String uriActualText)

TextLine
SetURIAltDescription(String uriAltDescription)

TextLine
SetURILanguage(String uriLanguage)

TextLine
SetVerticalOffset(float verticalOffset)

Sets the vertical offset of the text.

Methods inherited from class Object

equals, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait

Constructor Detail

TextLine

public TextLine(Font font)

Constructor for creating text line objects.

Parameters:

font - the font to use.

TextLine

public TextLine(Font font,
                String text)

Constructor for creating text line objects.

Parameters:

font - the font to use.

text - the text.

Method Detail

SetText

public TextLine SetText(String text)

Sets the text.

Parameters:

text - the text.

Returns:

this TextLine.

GetText

public String GetText()

Returns the text.

Returns:

the text.

SetPosition

public void SetPosition(float x,
                        float y)

Sets the position where this text line will be drawn on the page.

Specified by:

SetPosition in interface IDrawable

Parameters:

x - the x coordinate of the text line.

y - the y coordinate of the text line.

SetPosition

public void SetPosition(double x,
                        double y)

Sets the position where this text line will be drawn on the page.

Parameters:

x - the x coordinate of the text line.

y - the y coordinate of the text line.

SetLocation

public TextLine SetLocation(float x,
                            float y)

Sets the location where this text line will be drawn on the page.

Parameters:

x - the x coordinate of the text line.

y - the y coordinate of the text line.

Returns:

this TextLine.

SetLocation

public TextLine SetLocation(double x,
                            double y)

advance

public float advance(float leading)

SetFont

public TextLine SetFont(Font font)

Sets the font to use for this text line.

Parameters:

font - the font to use.

Returns:

this TextLine.

GetFont

public Font GetFont()

Gets the font to use for this text line.

Returns:

font the font to use.

SetFontSize

public TextLine SetFontSize(float fontSize)

Sets the font size to use for this text line.

Parameters:

fontSize - the fontSize to use.

Returns:

this TextLine.

SetFallbackFont

public TextLine SetFallbackFont(Font fallbackFont)

Sets the fallback font.

Parameters:

fallbackFont - the fallback font.

Returns:

this TextLine.

SetFallbackFontSize

public TextLine SetFallbackFontSize(float fallbackFontSize)

Sets the fallback font size to use for this text line.

Parameters:

fallbackFontSize - the fallback font size.

Returns:

this TextLine.

GetFallbackFont

public Font GetFallbackFont()

Returns the fallback font.

Returns:

the fallback font.

SetColor

public TextLine SetColor(int color)

Sets the color for this text line.

Parameters:

color - the color is specified as an integer.

Returns:

this TextLine.

SetColor

public TextLine SetColor(int[] color)

Sets the pen color.
  See the Color class for predefined values or define your own using 0x00RRGGBB packed integers.

Parameters:

color - the color.

Returns:

this TextLine.

GetColor

public int GetColor()

Returns the text line color.

Returns:

the text line color.

GetDestinationY

public float GetDestinationY()

Returns the y coordinate of the destination.

Returns:

the y coordinate of the destination.

GetWidth

public float GetWidth()

Returns the width of this TextLine.

Returns:

the width.

getStringWidth

public float getStringWidth(String text)

GetHeight

public float GetHeight()

Returns the height of this TextLine.

Returns:

the height.

SetURIAction

public TextLine SetURIAction(String uri)

Sets the URI for the "click text line" action.

Parameters:

uri - the URI

Returns:

this TextLine.

GetURIAction

public String GetURIAction()

Returns the action URI.

Returns:

the action URI.

SetGoToAction

public TextLine SetGoToAction(String key)

Sets the destination key for the action.

Parameters:

key - the destination name.

Returns:

this TextLine.

GetGoToAction

public String GetGoToAction()

Returns the GoTo action string.

Returns:

the GoTo action string.

SetUnderline

public TextLine SetUnderline(boolean underline)

Sets the underline variable.
  If the value of the underline variable is 'true' - the text is underlined.

Parameters:

underline - the underline flag.

Returns:

this TextLine.

GetUnderline

public boolean GetUnderline()

Returns the underline flag.

Returns:

the underline flag.

SetStrikeout

public TextLine SetStrikeout(boolean strikeout)

Sets the strike variable.
  If the value of the strike variable is 'true' - a strike line is drawn through the text.

Parameters:

strikeout - the strikeout flag.

Returns:

this TextLine.

GetStrikeout

public boolean GetStrikeout()

Returns the strikeout flag.

Returns:

the strikeout flag.

SetTextDirection

public TextLine SetTextDirection(int degrees)

Sets the direction in which to draw the text.

Parameters:

degrees - the number of degrees.

Returns:

this TextLine.

GetTextDirection

public int GetTextDirection()

Returns the text direction.

Returns:

the text direction.

SetTextEffect

public TextLine SetTextEffect(int textEffect)

Sets the text effect.

Parameters:

textEffect - Effect.NORMAL, Effect.SUBSCRIPT or Effect.SUPERSCRIPT.

Returns:

this TextLine.

GetTextEffect

public int GetTextEffect()

Returns the text effect.

Returns:

the text effect.

SetVerticalOffset

public TextLine SetVerticalOffset(float verticalOffset)

Sets the vertical offset of the text.

Parameters:

verticalOffset - the vertical offset.

Returns:

this TextLine.

GetVerticalOffset

public float GetVerticalOffset()

Returns the vertical text offset.

Returns:

the vertical text offset.

SetTrailingSpace

public TextLine SetTrailingSpace(boolean trailingSpace)

Sets the trailing space after this text line when used in paragraph.

Parameters:

trailingSpace - the trailing space.

Returns:

this TextLine.

GetTrailingSpace

public boolean GetTrailingSpace()

Returns the trailing space.

Returns:

the trailing space.

SetLanguage

public TextLine SetLanguage(String language)

GetLanguage

public String GetLanguage()

SetAltDescription

public TextLine SetAltDescription(String altDescription)

Sets the alternate description of this text line.

Parameters:

altDescription - the alternate description of the text line.

Returns:

this TextLine.

GetAltDescription

public String GetAltDescription()

SetActualText

public TextLine SetActualText(String actualText)

Sets the actual text for this text line.

Parameters:

actualText - the actual text for the text line.

Returns:

this TextLine.

GetActualText

public String GetActualText()

SetURILanguage

public TextLine SetURILanguage(String uriLanguage)

SetURIAltDescription

public TextLine SetURIAltDescription(String uriAltDescription)

SetURIActualText

public TextLine SetURIActualText(String uriActualText)

PlaceIn

public TextLine PlaceIn(Box box)

Places this text line in the specified box.

Parameters:

box - the specified box.

Returns:

this TextLine.

PlaceIn

public TextLine PlaceIn(Box box,
                        double xOffset,
                        double yOffset)

Places this text line in the box at the specified offset.

Parameters:

box - the specified box.

xOffset - the x offset from the top left corner of the box.

yOffset - the y offset from the top left corner of the box.

Returns:

this TextLine.

PlaceIn

public TextLine PlaceIn(Box box,
                        float xOffset,
                        float yOffset)

Places this text line in the box at the specified offset.

Parameters:

box - the specified box.

xOffset - the x offset from the top left corner of the box.

yOffset - the y offset from the top left corner of the box.

Returns:

this TextLine.

DrawOn

public float[] DrawOn(Page page)
               throws Exception

Draws this text line on the specified page.

Specified by:

DrawOn in interface IDrawable

Parameters:

page - the page to draw this text line on.

Returns:

float[] with the coordinates of the bottom right corner.

Throws:

Exception - If an input or output exception occurred

Skip navigation links

Package

Class

Tree

Deprecated

Index

Help

All Classes

JavaScript is disabled on your browser.

Summary:

Nested |

Field |

Constr |

Method

Detail:

Field |

Constr |

Method

redpajama_set_name: RedPajamaGithub


text:
package com.github.alezhka.wavesj.node;

import com.github.alezhka.wavesj.errors.ApiError;
import com.github.alezhka.wavesj.transaction.TransferTransaction;

public class BathResult {

    private TransferTransaction transaction;

    private ApiError error;

    public BathResult() {
        transaction = null;
        error = null;
    }

    public TransferTransaction getTransaction() {
        return transaction;
    }

    public void setTransaction(TransferTransaction transaction) {
        this.transaction = transaction;
    }

    public ApiError getError() {
        return error;
    }

    public void setError(ApiError error) {
        this.error = error;
    }
}


text:
@class Book;

@interface BooksTableViewCell : UITableViewCell <BookDelegate>{
    UIImageView *photo;
    UILabel *nameLabel;
    UILabel *authorLabel;
    UILabel *statusLabel;
    Book *book;
    UIActivityIndicatorView *scrollingWheel;
}

@property (nonatomic, retain) Book *book;
@property (nonatomic, retain) UILabel *statusLabel;

- (void)setBook:(Book *)newBook therow:(NSInteger)therow;
- (void)loadImage;

@end


text:
namespace cryptauth {

// Simple interface for fetching the OAuth2 access token that authorizes
// CryptAuth API calls. Do not reuse this after calling FetchAccessToken();
// instead, create a new instance.
class CryptAuthAccessTokenFetcher {
 public:
  virtual ~CryptAuthAccessTokenFetcher() {}

  // Fetches the access token asynchronously, invoking the callback upon
  // completion. If the fetch fails, the callback will be invoked with an empty
  // string.
  typedef base::Callback<void(const std::string&)> AccessTokenCallback;
  virtual void FetchAccessToken(const AccessTokenCallback& callback) = 0;
};

}  // namespace cryptauth

#endif  // COMPONENTS_CRYPTAUTH_CRYPTAUTH_ACCESS_TOKEN_FETCHER_H_


text:
<?php

##|+PRIV
##|*IDENT=page-services-captiveportal-allowedips
##|*NAME=Services: Captive Portal: Allowed IPs
##|*DESCR=Allow access to the 'Services: Captive Portal: Allowed IPs' page.
##|*MATCH=services_captiveportal_ip.php*
##|-PRIV

$directionicons = array('to' => '→', 'from' => '←', 'both' => '⇄');

require_once("guiconfig.inc");
require_once("functions.inc");
require_once("filter.inc");
require_once("shaper.inc");
require_once("captiveportal.inc");

$cpzone = strtolower(htmlspecialchars($_REQUEST['zone']));

if (empty($cpzone) || empty($config['captiveportal'][$cpzone])) {
	header("Location: services_captiveportal_zones.php");
	exit;
}

init_config_arr(array('captiveportal'));
$a_cp = &$config['captiveportal'];
$cpzoneid = $a_cp[$cpzone]['zoneid'];

$pgtitle = array(gettext("Services"), gettext("Captive Portal"), $a_cp[$cpzone]['zone'], gettext("Allowed IP Addresses"));
$pglinks = array("", "services_captiveportal_zones.php", "services_captiveportal.php?zone=" . $cpzone, "@self");
$shortcut_section = "captiveportal";

if ($_POST['act'] == "del" && !empty($cpzone)) {
	init_config_arr(array('captiveportal', $cpzone, 'allowedip'));
	$a_allowedips = &$config['captiveportal'][$cpzone]['allowedip'];

	if ($a_allowedips[$_POST['id']]) {
		$ipent = $a_allowedips[$_POST['id']];

		if (isset($config['captiveportal'][$cpzone]['enable'])) {
			captiveportal_ether_delete_entry($ipent, 'allowedhosts');
		}

		unset($a_allowedips[$_POST['id']]);
		write_config("Captive portal allowed IPs saved");
		header("Location: services_captiveportal_ip.php?zone={$cpzone}");
		exit;
	}
}

include("head.inc");

$tab_array = array();
$tab_array[] = array(gettext("Configuration"), false, "services_captiveportal.php?zone={$cpzone}");
$tab_array[] = array(gettext("MACs"), false, "services_captiveportal_mac.php?zone={$cpzone}");
$tab_array[] = array(gettext("Allowed IP Addresses"), true, "services_captiveportal_ip.php?zone={$cpzone}");
$tab_array[] = array(gettext("Allowed Hostnames"), false, "services_captiveportal_hostname.php?zone={$cpzone}");
$tab_array[] = array(gettext("Vouchers"), false, "services_captiveportal_vouchers.php?zone={$cpzone}");
$tab_array[] = array(gettext("High Availability"), false, "services_captiveportal_hasync.php?zone={$cpzone}");
$tab_array[] = array(gettext("File Manager"), false, "services_captiveportal_filemanager.php?zone={$cpzone}");
display_top_tabs($tab_array, true);

?>

				<?=gettext("IP Addresses"); ?>
				<?=gettext("Description"); ?>
				<?=gettext("Actions"); ?>

<?php
if (is_array($a_cp[$cpzone]['allowedip'])): ?>

<?php
	$i = 0;
	foreach ($a_cp[$cpzone]['allowedip'] as $ip): ?>

					<?=$directionicons[$ip['dir']]?> <?=$ip['ip']?>
					<?=($ip['sn'] != "32" && is_numeric($ip['sn'])) ? '/' . $ip['sn'] : ''?>

					<?=htmlspecialchars($ip['descr'])?>

					<a class="fa fa-pencil"	title="<?=gettext("Edit IP"); ?>" href="services_captiveportal_ip_edit.php?zone=<?=$cpzone?>&id=<?=$i?>">
					<a class="fa fa-trash"	title="<?=gettext("Delete IP")?>" href="services_captiveportal_ip.php?zone=<?=$cpzone?>&act=del&id=<?=$i?>" usepost>

<?php
	$i++;
	endforeach; ?>

	<?=$directionicons['to']   . ' = ' . sprintf(gettext('All connections %1$sto%2$s the address are allowed'), '', '') . ', '?>
	<?=$directionicons['from'] . ' = ' . sprintf(gettext('All connections %1$sfrom%2$s the address are allowed'), '', '') . ', '?>
	<?=$directionicons['both'] . ' = ' . sprintf(gettext('All connections %1$sto or from%2$s are allowed'), '', '')?>
<?php
else:
?>

<?php
endif;
?>

	<a href="services_captiveportal_ip_edit.php?zone=<?=$cpzone?>&act=add" class="btn btn-success btn-sm">

		<?=gettext("Add")?>

<?php print_info_box(gettext('Adding allowed IP addresses will allow IP access to/from these addresses through the captive portal without being taken to the portal page. ' .
					   'This can be used for a web server serving images for the portal page or a DNS server on another network, for example.'), 'info', false); ?>

<?php
include("foot.inc");


text:
/**
 * @param {*} element Element to check
 * @returns {boolean} true if element is Null or Undefined / false otherwise
 */
const isNil = (element) => element == null

/**
 * Returns a new object with only NotNil properties.
 * Performs the check recursively.
 *
 * Notice:
 * - `undefined` or `null` elements inside an Array will be kept.
 * - Object elements inside an Array will also be cleaned.
 * - If something that is not an array or an object is passed, it's returned as is.
 *
 * @param {*} obj Object to clean up
 * @returns {*} Object with NotNill properties
 */
const pickNotNil = (obj) => {
  if (Array.isArray(obj)) {
    return obj.map((element) => pickNotNil(element))
  }

  if (typeof obj !== 'object' || isNil(obj)) {
    return obj
  }

  const keys = Object.keys(obj)
  let copy = {}
  keys.filter((key) => !isNil(obj[key])).forEach((key) => {
    copy[key] = pickNotNil(obj[key])
  })
  return copy
}

module.exports = {
	isNil,
	pickNotNil
}


text:
from __future__ import annotations

import base64
import binascii
import email.utils
import http
from typing import Generator, List, Optional, Sequence, Tuple, cast

from .connection import CONNECTING, OPEN, SERVER, Connection, State
from .datastructures import Headers, MultipleValuesError
from .exceptions import (
    InvalidHandshake,
    InvalidHeader,
    InvalidHeaderValue,
    InvalidOrigin,
    InvalidStatus,
    InvalidUpgrade,
    NegotiationError,
)
from .extensions import Extension, ServerExtensionFactory
from .headers import (
    build_extension,
    parse_connection,
    parse_extension,
    parse_subprotocol,
    parse_upgrade,
)
from .http11 import Request, Response
from .typing import (
    ConnectionOption,
    ExtensionHeader,
    LoggerLike,
    Origin,
    Subprotocol,
    UpgradeProtocol,
)
from .utils import accept_key

# See #940 for why lazy_import isn't used here for backwards compatibility.
from .legacy.server import *  # isort:skip  # noqa

__all__ = ["ServerConnection"]

class ServerConnection(Connection):
    """
    Sans-I/O implementation of a WebSocket server connection.

    Args:
        origins: acceptable values of the ``Origin`` header; include
            :obj:`None` in the list if the lack of an origin is acceptable.
            This is useful for defending against Cross-Site WebSocket
            Hijacking attacks.
        extensions: list of supported extensions, in order in which they
            should be tried.
        subprotocols: list of supported subprotocols, in order of decreasing
            preference.
        state: initial state of the WebSocket connection.
        max_size: maximum size of incoming messages in bytes;
            :obj:`None` to disable the limit.
        logger: logger for this connection;
            defaults to ``logging.getLogger("websockets.client")``;
            see the :doc:`logging guide <../topics/logging>` for details.

    """

    def __init__(
        self,
        origins: Optional[Sequence[Optional[Origin]]] = None,
        extensions: Optional[Sequence[ServerExtensionFactory]] = None,
        subprotocols: Optional[Sequence[Subprotocol]] = None,
        state: State = CONNECTING,
        max_size: Optional[int] = 2**20,
        logger: Optional[LoggerLike] = None,
    ):
        super().__init__(
            side=SERVER,
            state=state,
            max_size=max_size,
            logger=logger,
        )
        self.origins = origins
        self.available_extensions = extensions
        self.available_subprotocols = subprotocols

    def accept(self, request: Request) -> Response:
        """
        Create a handshake response to accept the connection.

        If the connection cannot be established, the handshake response
        actually rejects the handshake.

        You must send the handshake response with :meth:`send_response`.

        You can modify it before sending it, for example to add HTTP headers.

        Args:
            request: WebSocket handshake request event received from the client.

        Returns:
            Response: WebSocket handshake response event to send to the client.

        """
        try:
            (
                accept_header,
                extensions_header,
                protocol_header,
            ) = self.process_request(request)
        except InvalidOrigin as exc:
            request._exception = exc
            self.handshake_exc = exc
            if self.debug:
                self.logger.debug("! invalid origin", exc_info=True)
            return self.reject(
                http.HTTPStatus.FORBIDDEN,
                f"Failed to open a WebSocket connection: {exc}.\n",
            )
        except InvalidUpgrade as exc:
            request._exception = exc
            self.handshake_exc = exc
            if self.debug:
                self.logger.debug("! invalid upgrade", exc_info=True)
            response = self.reject(
                http.HTTPStatus.UPGRADE_REQUIRED,
                (
                    f"Failed to open a WebSocket connection: {exc}.\n"
                    f"\n"
                    f"You cannot access a WebSocket server directly "
                    f"with a browser. You need a WebSocket client.\n"
                ),
            )
            response.headers["Upgrade"] = "websocket"
            return response
        except InvalidHandshake as exc:
            request._exception = exc
            self.handshake_exc = exc
            if self.debug:
                self.logger.debug("! invalid handshake", exc_info=True)
            return self.reject(
                http.HTTPStatus.BAD_REQUEST,
                f"Failed to open a WebSocket connection: {exc}.\n",
            )
        except Exception as exc:
            request._exception = exc
            self.handshake_exc = exc
            self.logger.error("opening handshake failed", exc_info=True)
            return self.reject(
                http.HTTPStatus.INTERNAL_SERVER_ERROR,
                (
                    "Failed to open a WebSocket connection.\n"
                    "See server log for more information.\n"
                ),
            )

        headers = Headers()

        headers["Date"] = email.utils.formatdate(usegmt=True)

        headers["Upgrade"] = "websocket"
        headers["Connection"] = "Upgrade"
        headers["Sec-WebSocket-Accept"] = accept_header

        if extensions_header is not None:
            headers["Sec-WebSocket-Extensions"] = extensions_header

        if protocol_header is not None:
            headers["Sec-WebSocket-Protocol"] = protocol_header

        self.logger.info("connection open")
        return Response(101, "Switching Protocols", headers)

    def process_request(
        self, request: Request
    ) -> Tuple[str, Optional[str], Optional[str]]:
        """
        Check a handshake request and negotiate extensions and subprotocol.

        This function doesn't verify that the request is an HTTP/1.1 or higher
        GET request and doesn't check the ``Host`` header. These controls are
        usually performed earlier in the HTTP request handling code. They're
        the responsibility of the caller.

        Args:
            request: WebSocket handshake request received from the client.

        Returns:
            Tuple[str, Optional[str], Optional[str]]:
            ``Sec-WebSocket-Accept``, ``Sec-WebSocket-Extensions``, and
            ``Sec-WebSocket-Protocol`` headers for the handshake response.

        Raises:
            InvalidHandshake: if the handshake request is invalid;
                then the server must return 400 Bad Request error.

        """
        headers = request.headers

        connection: List[ConnectionOption] = sum(
            [parse_connection(value) for value in headers.get_all("Connection")], []
        )

        if not any(value.lower() == "upgrade" for value in connection):
            raise InvalidUpgrade(
                "Connection", ", ".join(connection) if connection else None
            )

        upgrade: List[UpgradeProtocol] = sum(
            [parse_upgrade(value) for value in headers.get_all("Upgrade")], []
        )

        # For compatibility with non-strict implementations, ignore case when
        # checking the Upgrade header. The RFC always uses "websocket", except
        # in section 11.2. (IANA registration) where it uses "WebSocket".
        if not (len(upgrade) == 1 and upgrade[0].lower() == "websocket"):
            raise InvalidUpgrade("Upgrade", ", ".join(upgrade) if upgrade else None)

        try:
            key = headers["Sec-WebSocket-Key"]
        except KeyError as exc:
            raise InvalidHeader("Sec-WebSocket-Key") from exc
        except MultipleValuesError as exc:
            raise InvalidHeader(
                "Sec-WebSocket-Key", "more than one Sec-WebSocket-Key header found"
            ) from exc

        try:
            raw_key = base64.b64decode(key.encode(), validate=True)
        except binascii.Error as exc:
            raise InvalidHeaderValue("Sec-WebSocket-Key", key) from exc
        if len(raw_key) != 16:
            raise InvalidHeaderValue("Sec-WebSocket-Key", key)

        try:
            version = headers["Sec-WebSocket-Version"]
        except KeyError as exc:
            raise InvalidHeader("Sec-WebSocket-Version") from exc
        except MultipleValuesError as exc:
            raise InvalidHeader(
                "Sec-WebSocket-Version",
                "more than one Sec-WebSocket-Version header found",
            ) from exc

        if version != "13":
            raise InvalidHeaderValue("Sec-WebSocket-Version", version)

        accept_header = accept_key(key)

        self.origin = self.process_origin(headers)

        extensions_header, self.extensions = self.process_extensions(headers)

        protocol_header = self.subprotocol = self.process_subprotocol(headers)

        return (
            accept_header,
            extensions_header,
            protocol_header,
        )

    def process_origin(self, headers: Headers) -> Optional[Origin]:
        """
        Handle the Origin HTTP request header.

        Args:
            headers: WebSocket handshake request headers.

        Returns:
           Optional[Origin]: origin, if it is acceptable.

        Raises:
            InvalidOrigin: if the origin isn't acceptable.

        """
        # "The user agent MUST NOT include more than one Origin header field"
        # per https://www.rfc-editor.org/rfc/rfc6454.html#section-7.3.
        try:
            origin = cast(Optional[Origin], headers.get("Origin"))
        except MultipleValuesError as exc:
            raise InvalidHeader("Origin", "more than one Origin header found") from exc
        if self.origins is not None:
            if origin not in self.origins:
                raise InvalidOrigin(origin)
        return origin

    def process_extensions(
        self,
        headers: Headers,
    ) -> Tuple[Optional[str], List[Extension]]:
        """
        Handle the Sec-WebSocket-Extensions HTTP request header.

        Accept or reject each extension proposed in the client request.
        Negotiate parameters for accepted extensions.

        :rfc:`6455` leaves the rules up to the specification of each
        :extension.

        To provide this level of flexibility, for each extension proposed by
        the client, we check for a match with each extension available in the
        server configuration. If no match is found, the extension is ignored.

        If several variants of the same extension are proposed by the client,
        it may be accepted several times, which won't make sense in general.
        Extensions must implement their own requirements. For this purpose,
        the list of previously accepted extensions is provided.

        This process doesn't allow the server to reorder extensions. It can
        only select a subset of the extensions proposed by the client.

        Other requirements, for example related to mandatory extensions or the
        order of extensions, may be implemented by overriding this method.

        Args:
            headers: WebSocket handshake request headers.

        Returns:
            Tuple[Optional[str], List[Extension]]: ``Sec-WebSocket-Extensions``
            HTTP response header and list of accepted extensions.

        Raises:
            InvalidHandshake: to abort the handshake with an HTTP 400 error.

        """
        response_header_value: Optional[str] = None

        extension_headers: List[ExtensionHeader] = []
        accepted_extensions: List[Extension] = []

        header_values = headers.get_all("Sec-WebSocket-Extensions")

        if header_values and self.available_extensions:

            parsed_header_values: List[ExtensionHeader] = sum(
                [parse_extension(header_value) for header_value in header_values], []
            )

            for name, request_params in parsed_header_values:

                for ext_factory in self.available_extensions:

                    # Skip non-matching extensions based on their name.
                    if ext_factory.name != name:
                        continue

                    # Skip non-matching extensions based on their params.
                    try:
                        response_params, extension = ext_factory.process_request_params(
                            request_params, accepted_extensions
                        )
                    except NegotiationError:
                        continue

                    # Add matching extension to the final list.
                    extension_headers.append((name, response_params))
                    accepted_extensions.append(extension)

                    # Break out of the loop once we have a match.
                    break

                # If we didn't break from the loop, no extension in our list
                # matched what the client sent. The extension is declined.

        # Serialize extension header.
        if extension_headers:
            response_header_value = build_extension(extension_headers)

        return response_header_value, accepted_extensions

    def process_subprotocol(self, headers: Headers) -> Optional[Subprotocol]:
        """
        Handle the Sec-WebSocket-Protocol HTTP request header.

        Args:
            headers: WebSocket handshake request headers.

        Returns:
           Optional[Subprotocol]: Subprotocol, if one was selected; this is
           also the value of the ``Sec-WebSocket-Protocol`` response header.

        Raises:
            InvalidHandshake: to abort the handshake with an HTTP 400 error.

        """
        subprotocol: Optional[Subprotocol] = None

        header_values = headers.get_all("Sec-WebSocket-Protocol")

        if header_values and self.available_subprotocols:

            parsed_header_values: List[Subprotocol] = sum(
                [parse_subprotocol(header_value) for header_value in header_values], []
            )

            subprotocol = self.select_subprotocol(
                parsed_header_values, self.available_subprotocols
            )

        return subprotocol

    def select_subprotocol(
        self,
        client_subprotocols: Sequence[Subprotocol],
        server_subprotocols: Sequence[Subprotocol],
    ) -> Optional[Subprotocol]:
        """
        Pick a subprotocol among those offered by the client.

        If several subprotocols are supported by the client and the server,
        the default implementation selects the preferred subprotocols by
        giving equal value to the priorities of the client and the server.

        If no common subprotocol is supported by the client and the server, it
        proceeds without a subprotocol.

        This is unlikely to be the most useful implementation in practice, as
        many servers providing a subprotocol will require that the client uses
        that subprotocol.

        Args:
            client_subprotocols: list of subprotocols offered by the client.
            server_subprotocols: list of subprotocols available on the server.

        Returns:
            Optional[Subprotocol]: Subprotocol, if a common subprotocol was
            found.

        """
        subprotocols = set(client_subprotocols) & set(server_subprotocols)
        if not subprotocols:
            return None
        priority = lambda p: (
            client_subprotocols.index(p) + server_subprotocols.index(p)
        )
        return sorted(subprotocols, key=priority)[0]

    def reject(
        self,
        status: http.HTTPStatus,
        text: str,
    ) -> Response:
        """
        Create a handshake response to reject the connection.

        A short plain text response is the best fallback when failing to
        establish a WebSocket connection.

        You must send the handshake response with :meth:`send_response`.

        You can modify it before sending it, for example to alter HTTP headers.

        Args:
            status: HTTP status code.
            text: HTTP response body; will be encoded to UTF-8.

        Returns:
            Response: WebSocket handshake response event to send to the client.

        """
        body = text.encode()
        headers = Headers(
            [
                ("Date", email.utils.formatdate(usegmt=True)),
                ("Connection", "close"),
                ("Content-Length", str(len(body))),
                ("Content-Type", "text/plain; charset=utf-8"),
            ]
        )
        response = Response(status.value, status.phrase, headers, body)
        # When reject() is called from accept(), handshake_exc is already set.
        # If a user calls reject(), set handshake_exc to guarantee invariant:
        # "handshake_exc is None if and only if opening handshake succeded."
        if self.handshake_exc is None:
            self.handshake_exc = InvalidStatus(response)
        self.logger.info("connection failed (%d %s)", status.value, status.phrase)
        return response

    def send_response(self, response: Response) -> None:
        """
        Send a handshake response to the client.

        Args:
            response: WebSocket handshake response event to send.

        """
        if self.debug:
            code, phrase = response.status_code, response.reason_phrase
            self.logger.debug("> HTTP/1.1 %d %s", code, phrase)
            for key, value in response.headers.raw_items():
                self.logger.debug("> %s: %s", key, value)
            if response.body is not None:
                self.logger.debug("> [body] (%d bytes)", len(response.body))

        self.writes.append(response.serialize())

        if response.status_code == 101:
            assert self.state is CONNECTING
            self.state = OPEN
        else:
            self.send_eof()
            self.parser = self.discard()
            next(self.parser)  # start coroutine

    def parse(self) -> Generator[None, None, None]:
        if self.state is CONNECTING:
            request = yield from Request.parse(self.reader.read_line)

            if self.debug:
                self.logger.debug("< GET %s HTTP/1.1", request.path)
                for key, value in request.headers.raw_items():
                    self.logger.debug("< %s: %s", key, value)

            self.events.append(request)

        yield from super().parse()


text:
#pragma once

#include <medToolBox.h>
#include <medCoreExport.h>

class medCompositeDataSetImporterSelectorToolBox;
class medCompositeDataSetImporterAbstractToolBoxPrivate;
class dtkAbstractProcess;
class medAbstractData;

class MEDCORE_EXPORT medCompositeDataSetImporterAbstractToolBox : public medToolBox
{
    Q_OBJECT
public:
             medCompositeDataSetImporterAbstractToolBox(QWidget *parent = 0);
    virtual ~medCompositeDataSetImporterAbstractToolBox();
    virtual void setCompositeDataSetImporterToolBox(medCompositeDataSetImporterSelectorToolBox *toolbox);

    virtual QString description() const = 0;

    virtual medAbstractData *output() const;

public slots:
    virtual bool import() = 0;
    virtual void reset()  {};
    virtual void load() {};

protected:
    medCompositeDataSetImporterSelectorToolBox *parent();

protected:
    medCompositeDataSetImporterAbstractToolBoxPrivate *d;
};


text:
[![Build Status](https://secure.travis-ci.org/alexfernandez/simplecached.png)](http://travis-ci.org/alexfernandez/simplecached)

# simplecached

Simplified version of memcached, useful for didactic purposes.

## Installation

Just run:

    npm install simplecached

or add it to your dependencies in package.json:

    "dependencies": {
        "simplecached": "*",
        ...
    },

## Server

To start a server, just require simplecached and create a server:

    var simplecached = require('simplecached');
    var server = new simplecached.Server();

To start the server on a port different than the default (11311),
add it to the Server constructor:

    var server = simplecached.Server(port);

Also a callback can be added to be notified when the server has started:

    var server = simplecached.Server(port, function(error, result) {
        console.log('Server started');
    });

To stop the server, call close() on it:

    server.close();

## Client

To create a client for a simplecached server, just create it.

    var simplecached = require('simplecached');
    var client = new simplecached.Client();

### new Client(options, callback);

The client constructor accepts an options object with port and host.
Also, an optional callback can be added to be notified when the client is connected.

    var options = {
        port: 11312,
        host: '192.168.1.15'
    };
    var client = new simplecached.Client(options, function(error) {
        console.log('Connected');
    });

The following functions can be called on the client.

### client.get(key, callback);

Get a key from the remote simplecached.
The callback is a `function(error, result)` that will be called either with an error or the result,
or null if the value was not found.

### client.set(key, value, callback);

Set a value into the remote simplecached.
The callback is a `function(error, result)` that will be called with an error or a result.
The `result` can be true if the value was stored, false otherwise.

### client.delete(key, callback);

Delete a value from the remote simplecached.
The callback is a `function(error, result)` that will be called with an error or a result.
The `result` can be true if the value was deleted, false if not found.

### client.close(callback);

Close the connection. The optional callback will be called after the connection is actually closed.

### Example

The following code opens a connection to a remote simplecached server.
Then it sets a key, retrieves it and checks that the value is correct.
Then it closes the connection.

    var simplecached = require('simplecached');
    var options = {
        port: 11312,
        host: '192.168.1.15'
    };
    var client = new client.Client(options, function(error) {
        console.assert(!error, 'Could not open connection');
        var key = 'testing';
        var value = 'real value';
        client.set(key, value, function(error, result) {
            console.assert(!error, 'Error setting key');
            console.assert(result, 'Could not set key');
            client.get(key, function(error, result) {
                console.assert(!error, 'Error getting key');
                console.assert(result == value, 'Invalid get key');
                client.delete(key, function(error, result) {
                    console.assert(!error, 'Error deleting key');
                    console.assert(result, 'Could not delete key');
                    client.close(function(error) {
                        console.assert(!error, 'Error closing client');
                    });
                });
            });
        });
    });

The pyramid of callbacks can be avoided with a few named functions.

## Protocol

The line protocol for simplecached is a simplified version of memcached's.

### `get <key>\r\n`

Gets a key from the cache. The response can be either:

    VALUE <value>\r\n

when a value is found, or

    END\r\n

if the value was not found.

### `set <key> <value>\r\n`

Sets a value in the cache, always a string (without line feeds).
The response can be either:

    STORED\r\n

if the value was stored, or

    NOT_STORED\r\n

otherwise.

### `delete <key>\r\n`

Deletes a value from the cache.
The response can be either:

    DELETED\r\n

if the value was stored, or

    NOT_FOUND\r\n

otherwise.

### `quit\r\n`

Close the connection.

## License

Simplecached is licensed under the MIT license.
Please consult the LICENSE file for details.


text:
package barcodekey.bck_messager;

import android.app.Application;
import android.test.ActivityInstrumentationTestCase2;
import android.test.ApplicationTestCase;

import app.security.Main;

/**
 * Testing Fundamentals
 */
public class ApplicationTest extends ActivityInstrumentationTestCase2 {
    public ApplicationTest() {
        super(Main.class);
    }
    public void testEncrypt(){
        System.out.println("testaa");
    }
    public void testDecrypt(){
        System.out.println("testaa");
    }
}


text:
This dataset contains images and a set of labels that expose certain
characterisitics of that images, such as *varroa-mite* infections, bees carrying
*pollen-packets* or bee that are *cooling the hive* by flappingn their wings.
Additionally, this dataset contains images of *wasps* to be able to distinguish
bees and wasps.

The images of the bees are taken from above and rotated. The bee is vertical and
either its head or the trunk is on top. All images were taken with a green
background and the distance to the bees was always the same, thus all bees have
the same size.

Each image can have multiple labels assigned to it. E.g. a bee can be cooling
the hive and have a varrio-mite infection at the same time.

This dataset is designed as mutli-label dataset, where each label, e.g.
*varroa_output*, contains 1 if the characterisitic was present in the image and
a 0 if it wasn't. All images are provided by 300 pixel height and 150 pixel
witdh. As default the dataset provides the images as 150x75 (h,w) pixel. You can
select 300 pixel height by loading the datset with the name
"bee_dataset/bee_dataset_300" and with 200 pixel height by
"bee_dataset/bee_dataset_200".

License: GNU GENERAL PUBLIC LICENSE

Author: Fabian Hickert <Fabian.Hickert@raspbee.de>


text:
[Akaros](http://akaros.cs.berkeley.edu/) support is *incomplete*.

See [Akaros getting started](https://github.com/brho/akaros/blob/master/GETTING_STARTED.md)
re kernel building/running.

Akaros does not support Go at the moment (except for a broken
[1.3 port](https://github.com/akaros/go-akaros)). Full Go support is planned
for Akaros. Until that happens running on Akaros is challening. However,
`syz-stress` can be run as follows:

```shell
make TARGETOS=linux syz-stress
make TARGETOS=akaros SOURCEDIR=/akaros/checkout executor
scp -P 5555 -i akaros_id_rsa -o IdentitiesOnly=yes bin/akaros_amd64/syz-executor  root@localhost:/
bin/linux_amd64/syz-stress -os=akaros -ipc=pipe -procs=8 -executor "/usr/bin/ssh -p 5555 -i akaros_id_rsa -o IdentitiesOnly=yes root@localhost /syz-executor"
```


text:
package com.adioss.bootstrap.web.rest;

import com.adioss.bootstrap.domain.Language;
import com.adioss.bootstrap.domain.Role;
import com.adioss.bootstrap.domain.User;
import com.adioss.bootstrap.repository.UserRepository;
import com.adioss.bootstrap.web.dto.UserPasswordDTO;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.http.MediaType;
import org.springframework.security.test.context.support.WithMockUser;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.test.context.web.WebAppConfiguration;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.ResultActions;
import org.springframework.test.web.servlet.request.MockMvcRequestBuilders;
import org.springframework.test.web.servlet.setup.MockMvcBuilders;
import org.springframework.web.context.WebApplicationContext;

import java.util.Arrays;

import static java.util.Collections.singletonList;
import static org.springframework.security.test.web.servlet.request.SecurityMockMvcRequestPostProcessors.csrf;
import static org.springframework.security.test.web.servlet.setup.SecurityMockMvcConfigurers.springSecurity;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;

@SuppressWarnings("SpringJavaAutowiredMembersInspection")
@RunWith(SpringJUnit4ClassRunner.class)
@SpringBootTest
@WebAppConfiguration
public class ProfileResourceTest {
    private static final String BASIC_USER_USERNAME = "test";
    @Autowired
    private WebApplicationContext webApplicationContext;
    @Autowired
    private UserRepository userRepository;
    private MockMvc mockMvc;

    @Before
    public void setUp() {
        this.mockMvc = MockMvcBuilders.webAppContextSetup(webApplicationContext).apply(springSecurity()).build();
        userRepository.deleteAll();
    }

    @Test
    @WithMockUser(username = BASIC_USER_USERNAME)
    public void shouldUpdateUserProfile() throws Exception {
        // Given
        User savedUser = userRepository.save(getUser());
        String expectedEmail = "new@email.com";
        savedUser.setEmail(expectedEmail);
        savedUser.setRoles(Arrays.asList(Role.USER, Role.ADMIN));
        String content = new ObjectMapper().writeValueAsString(savedUser);

        // When
        ResultActions perform = this.mockMvc.perform(MockMvcRequestBuilders.put("/api/profile")
                .contentType(MediaType.APPLICATION_JSON_VALUE).with(csrf())
                .content(content));

        // Then
        perform.andExpect(status().isOk());
        User updatedUser = userRepository.findOne(savedUser.getId());
        Assert.assertEquals(getUser().getRoles(), updatedUser.getRoles());
        Assert.assertEquals(expectedEmail, updatedUser.getEmail());
    }

    @Test
    @WithMockUser(username = "Other")
    public void shouldRejectUpdateUserProfileIfNotPrincipal() throws Exception {
        // Given
        User savedUser = userRepository.save(getUser());
        String content = new ObjectMapper().writeValueAsString(savedUser);

        // When
        try {
            this.mockMvc.perform(MockMvcRequestBuilders.put("/api/profile")
                    .contentType(MediaType.APPLICATION_JSON_VALUE).with(csrf())
                    .content(content));
        } catch (Exception e) {
            // Then
            Assert.assertTrue(true);
            return;
        }
        //noinspection ConstantConditions
        Assert.assertTrue(false);
    }

    @Test
    @WithMockUser(username = BASIC_USER_USERNAME)
    public void shouldChangePassword() throws Exception {
        // Given
        userRepository.save(getUser());
        String content = new ObjectMapper().writeValueAsString(new UserPasswordDTO("pass", "pass"));

        // When
        ResultActions perform = this.mockMvc
                .perform(MockMvcRequestBuilders.post("/api/profile/changePassword")
                        .contentType(MediaType.APPLICATION_JSON_VALUE).with(csrf())
                        .content(content));

        // Then
        perform.andExpect(status().isOk());
    }

    @Test
    @WithMockUser(username = "Other")
    public void shouldRejectPasswordModificationIfNotPrincipal() throws Exception {
        // Given
        userRepository.save(getUser());
        String content = new ObjectMapper().writeValueAsString(new UserPasswordDTO("pass", "pass"));

        // When
        try {
            this.mockMvc.perform(MockMvcRequestBuilders.post("/api/profile/changePassword")
                    .contentType(MediaType.APPLICATION_JSON_VALUE).with(csrf())
                    .content(content));
        } catch (Exception e) {
            // Then
            Assert.assertTrue(true);
            return;
        }
        //noinspection ConstantConditions
        Assert.assertTrue(false);
    }

    @Test
    @WithMockUser(username = BASIC_USER_USERNAME)
    public void shouldRejectPasswordModificationIfNotValidated() throws Exception {
        // Given
        userRepository.save(getUser());
        String content = new ObjectMapper().writeValueAsString(new UserPasswordDTO("pass", "noequals"));

        try {
            this.mockMvc.perform(MockMvcRequestBuilders.post("/api/profile/changePassword")
                    .contentType(MediaType.APPLICATION_JSON_VALUE).with(csrf())
                    .content(content));
        } catch (Exception e) {
            // Then
            Assert.assertTrue(true);
            return;
        }
        //noinspection ConstantConditions
        Assert.assertTrue(false);
    }

    public User getUser() {
        return new User(BASIC_USER_USERNAME, "test@mail.com", "test", Language.ENGLISH, singletonList(Role.USER));
    }
}


text:
class Teacher < ActiveRecord::Base

  has_many :groups

  has_secure_password

end


text:
<?xml version="1.0" encoding="UTF-8"?>
<sem:triples uri="http://www.lds.org/vrl/people/organizations-and-groups/church-related-organizations/mormon-tabernacle-choir" xmlns:sem="http://marklogic.com/semantics">
  <sem:triple>
    <sem:subject>http://www.lds.org/vrl/people/organizations-and-groups/church-related-organizations/mormon-tabernacle-choir</sem:subject>
    <sem:predicate>http://www.w3.org/2004/02/skos/core#prefLabel</sem:predicate>
    <sem:object datatype="xsd:string" xml:lang="eng">Mormon Tabernacle Choir</sem:object>
  </sem:triple>
  <sem:triple>
    <sem:subject>http://www.lds.org/vrl/people/organizations-and-groups/church-related-organizations/mormon-tabernacle-choir</sem:subject>
    <sem:predicate>http://www.w3.org/2004/02/skos/core#inScheme</sem:predicate>
    <sem:object datatype="sem:iri">http://www.lds.org/concept-scheme/vrl</sem:object>
  </sem:triple>
  <sem:triple>
    <sem:subject>http://www.lds.org/vrl/people/organizations-and-groups/church-related-organizations/mormon-tabernacle-choir</sem:subject>
    <sem:predicate>http://www.lds.org/core#entityType</sem:predicate>
    <sem:object datatype="sem:iri">http://www.schema.org/Place</sem:object>
  </sem:triple>
</sem:triples>


text:
#include <string.h>  // for strdup
#include <algorithm>
#include <stdexcept>
#include <string>

#include "paddle/fluid/framework/operator.h"
#include "paddle/fluid/platform/cpu_helper.h"
#include "paddle/fluid/platform/cpu_info.h"
#include "paddle/fluid/platform/device_context.h"
#include "paddle/fluid/platform/init.h"
#include "paddle/fluid/platform/place.h"
#include "paddle/fluid/string/piece.h"

DEFINE_int32(paddle_num_threads, 1,
             "Number of threads for each paddle instance.");

namespace paddle {
namespace framework {

std::once_flag gflags_init_flag;
std::once_flag p2p_init_flag;

void InitGflags(std::vector<std::string> argv) {
  std::call_once(gflags_init_flag, [&]() {
    argv.insert(argv.begin(), "dummy");
    int argc = argv.size();
    char **arr = new char *[argv.size()];
    std::string line;
    for (size_t i = 0; i < argv.size(); i++) {
      arr[i] = &argv[i][0];
      line += argv[i];
      line += ' ';
    }
    google::ParseCommandLineFlags(&argc, &arr, true);
    VLOG(1) << "Init commandline: " << line;
  });
}

void InitP2P(std::vector<int> devices) {
#ifdef PADDLE_WITH_CUDA
  std::call_once(p2p_init_flag, [&]() {
    int count = devices.size();
    for (int i = 0; i < count; ++i) {
      for (int j = 0; j < count; ++j) {
        if (devices[i] == devices[j]) continue;
        int can_acess = -1;
        PADDLE_ENFORCE(
            cudaDeviceCanAccessPeer(&can_acess, devices[i], devices[j]),
            "Failed to test P2P access.");
        if (can_acess != 1) {
          LOG(WARNING) << "Cannot enable P2P access from " << devices[i]
                       << " to " << devices[j];
        } else {
          cudaSetDevice(devices[i]);
          cudaDeviceEnablePeerAccess(devices[j], 0);
        }
      }
    }
  });
#endif
}

void InitDevices(bool init_p2p) {
  /*Init all available devices by default */
  std::vector<int> devices;
#ifdef PADDLE_WITH_CUDA
  try {
    int count = platform::GetCUDADeviceCount();
    for (int i = 0; i < count; ++i) {
      devices.push_back(i);
    }
  } catch (const std::exception &exp) {
    LOG(WARNING) << "Compiled with WITH_GPU, but no GPU found in runtime.";
  }
#endif
  InitDevices(init_p2p, devices);
}

void InitDevices(bool init_p2p, const std::vector<int> devices) {
  std::vector<platform::Place> places;
  int count = 0;
#ifdef PADDLE_WITH_CUDA
  try {
    count = platform::GetCUDADeviceCount();
  } catch (const std::exception &exp) {
    LOG(WARNING) << "Compiled with WITH_GPU, but no GPU found in runtime.";
  }
#endif

  for (size_t i = 0; i < devices.size(); ++i) {
    if (devices[i] >= count || devices[i] < 0) {
      LOG(WARNING) << "Invalid devices id.";
      continue;
    }
    places.emplace_back(platform::CUDAPlace(devices[i]));
  }
  if (init_p2p) {
    InitP2P(devices);
  }
  places.emplace_back(platform::CPUPlace());
  platform::DeviceContextPool::Init(places);
#ifndef PADDLE_WITH_MKLDNN
  platform::SetNumThreads(FLAGS_paddle_num_threads);
#endif

  if (platform::jit::MayIUse(platform::jit::avx)) {
#ifndef __AVX__
    LOG(WARNING) << "AVX is available, Please re-compile on local machine";
#endif
  }

// Throw some informations when CPU instructions mismatch.
#define AVX_GUIDE(compiletime, runtime)                                     \
  LOG(FATAL)                                                                \
      << "This version is compiled on higher instruction(" #compiletime     \
         ") system, you may encounter illegal instruction error running on" \
         " your local CPU machine. Please reinstall the " #runtime          \
         " version or compile from source code."

#ifdef __AVX512F__
  if (!platform::jit::MayIUse(platform::jit::avx512f)) {
    if (platform::jit::MayIUse(platform::jit::avx2)) {
      AVX_GUIDE(AVX512, AVX2);
    } else if (platform::jit::MayIUse(platform::jit::avx)) {
      AVX_GUIDE(AVX512, AVX);
    } else {
      AVX_GUIDE(AVX512, NonAVX);
    }
  }
#endif

#ifdef __AVX2__
  if (!platform::jit::MayIUse(platform::jit::avx2)) {
    if (platform::jit::MayIUse(platform::jit::avx)) {
      AVX_GUIDE(AVX2, AVX);
    } else {
      AVX_GUIDE(AVX2, NonAVX);
    }
  }
#endif

#ifdef __AVX__
  if (!platform::jit::MayIUse(platform::jit::avx)) {
    AVX_GUIDE(AVX, NonAVX);
  }
#endif

#undef AVX_GUIDE
}

void InitGLOG(const std::string &prog_name) {
  // glog will not hold the ARGV[0] inside.
  // Use strdup to alloc a new string.
  google::InitGoogleLogging(strdup(prog_name.c_str()));
  google::InstallFailureSignalHandler();
}

}  // namespace framework
}  // namespace paddle


text:
package ar.com.larreta.compiler.reservedwords;

public class RWDenier extends ReservedWord {
	private static final String EXPRESSION = "!";

	public RWDenier() {
		super(EXPRESSION);
	}
}


text:
package vellum.crypto.asymmetricstore;

import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.security.PrivateKey;
import java.security.PublicKey;
import javax.crypto.Cipher;

/**
 *
 * @author evan.summers
 */
public class RsaStore {

    private final int VERSION = 0xbeaa0001;
    private final String alg = "RSA";
    private String transform = "RSA/ECB/PKCS1Padding";

    public void store(OutputStream stream, String type, String alias,
            byte[] bytes, PublicKey publicKey)
            throws Exception {
        bytes = encrypt(bytes, publicKey);
        DataOutputStream dos = new DataOutputStream(stream);
        dos.writeInt(VERSION);
        dos.writeUTF(alg);
        dos.writeUTF(transform);
        dos.writeUTF(type);
        dos.writeUTF(alias);
        dos.writeInt(bytes.length);
        dos.write(bytes);
    }

    public byte[] load(InputStream stream, String type, String alias,
            PrivateKey privateKey) throws Exception {
        DataInputStream dis = new DataInputStream(stream);
        if (dis.readInt() != VERSION) {
            throw new Exception("Invalid version");
        }
        if (!dis.readUTF().equals(alg)) {
            throw new Exception("Invalid algorithm");
        }
        transform = dis.readUTF();
        if (!dis.readUTF().equals(type)) {
            throw new Exception("Invalid type");
        }
        String string = dis.readUTF();
        if (!string.equals(alias)) {
            throw new Exception("Invalid alias " + string);
        }
        byte[] bytes = new byte[dis.readInt()];
        dis.readFully(bytes);
        bytes = decrypt(bytes, privateKey);
        return bytes;
    }

    private byte[] encrypt(byte[] bytes, PublicKey key) throws Exception {
        Cipher cipher = Cipher.getInstance(transform);
        cipher.init(Cipher.ENCRYPT_MODE, key);
        return cipher.doFinal(bytes);
    }

    private byte[] decrypt(byte[] bytes, PrivateKey key) throws Exception {
        Cipher cipher = Cipher.getInstance(transform);
        cipher.init(Cipher.DECRYPT_MODE, key);
        return cipher.doFinal(bytes);
    }
}


text:
package org.apache.flink.core.memory;

import org.apache.flink.annotation.Public;

import java.io.DataOutput;
import java.io.IOException;

/**
 * This interface defines a view over some memory that can be used to sequentially write contents to the memory.
 * The view is typically backed by one or more {@link org.apache.flink.core.memory.MemorySegment}.
 */
@Public
public interface DataOutputView extends DataOutput {

	/**
	 * Skips {@code numBytes} bytes memory. If some program reads the memory that was skipped over, the
	 * results are undefined.
	 *
	 * @param numBytes The number of bytes to skip.
	 *
	 * @throws IOException Thrown, if any I/O related problem occurred such that the view could not
	 *                     be advanced to the desired position.
	 */
	public void skipBytesToWrite(int numBytes) throws IOException;

	/**
	 * Copies {@code numBytes} bytes from the source to this view.
	 *
	 * @param source The source to copy the bytes from.
	 * @param numBytes The number of bytes to copy.
	 *
	 * @throws IOException Thrown, if any I/O related problem occurred, such that either the input view
	 *                     could not be read, or the output could not be written.
	 */
	public void write(DataInputView source, int numBytes) throws IOException;
}


text:
layout: base
title:  'Statistics of PUNCT in UD_Tamil'
udver: '2'
---

## Treebank Statistics: UD_Tamil: POS Tags: `PUNCT`

There are 13 `PUNCT` lemmas (1%), 13 `PUNCT` types (0%) and 1000 `PUNCT` tokens (10%).
Out of 14 observed tags, the rank of `PUNCT` is: 11 in number of lemmas, 12 in number of types and 4 in number of tokens.

The 10 most frequent `PUNCT` lemmas: ., ,, -, :, (, ), ", ரூ, ரூ., ;

The 10 most frequent `PUNCT` types:  ., ,, -, :, (, ), ", ரூ, ரூ., ;

The 10 most frequent ambiguous lemmas:

The 10 most frequent ambiguous types:

## Morphology

The form / lemma ratio of `PUNCT` is 1.000000 (the average of all parts of speech is 1.558463).

The 1st highest number of forms (1) was observed with the lemma """: ".

The 2nd highest number of forms (1) was observed with the lemma "(": (.

The 3rd highest number of forms (1) was observed with the lemma ")": ).

`PUNCT` occurs with 1 features: <tt>PunctType</tt> (1000; 100% instances)

`PUNCT` occurs with 2 feature-value pairs: `PunctType=Comm`, `PunctType=Peri`

`PUNCT` occurs with 2 feature combinations.
The most frequent feature combination is `PunctType=Peri` (600 tokens).
Examples: .

## Relations

`PUNCT` nodes are attached to their parents using 1 different relations: <tt>punct</tt> (1000; 100% instances)

Parents of `PUNCT` nodes belong to 8 different parts of speech: <tt>VERB</tt> (711; 71% instances), <tt>NOUN</tt> (157; 16% instances), <tt>PROPN</tt> (77; 8% instances), <tt>AUX</tt> (18; 2% instances), <tt>NUM</tt> (16; 2% instances), <tt>PART</tt> (8; 1% instances), <tt>ADJ</tt> (7; 1% instances), <tt>PRON</tt> (6; 1% instances)

1000 (100%) `PUNCT` nodes are leaves.

The highest child degree of a `PUNCT` node is 0.


text:
<?php

namespace Superbalist\Money;

class CurrencyNotSupportedException extends \Exception
{
}


text:
package com.arcfalt.extendahand.packet;

import net.minecraft.util.math.BlockPos;
import net.minecraft.util.EnumFacing;
import net.minecraftforge.fml.common.network.NetworkRegistry;
import net.minecraftforge.fml.common.network.simpleimpl.SimpleNetworkWrapper;
import net.minecraftforge.fml.relauncher.Side;
import net.minecraftforge.fml.relauncher.SideOnly;

public class PacketHandler
{
	public static final SimpleNetworkWrapper INSTANCE = NetworkRegistry.INSTANCE.newSimpleChannel("arcfextendahand");

	public static void registerPackets()
	{
		INSTANCE.registerMessage(ExtendoPlaceHandler.class, ExtendoPlaceMessage.class, 0, Side.SERVER);
		INSTANCE.registerMessage(ExtendoNBTHandler.class, ExtendoNBTMessage.class, 1, Side.SERVER);
	}

	@SideOnly(Side.CLIENT)
	public static void sendExtendoPlacement(BlockPos target, EnumFacing side)
	{
		INSTANCE.sendToServer(new ExtendoPlaceMessage(target, side));
	}

	@SideOnly(Side.CLIENT)
	public static void sendExtendoNBT(BlockPos target)
	{
		INSTANCE.sendToServer(new ExtendoNBTMessage(target));
	}
}