text:
using System.IO;
using System.Linq;
using System.Net.Test.Common;
using System.Security.Authentication;
using System.Security.Cryptography.X509Certificates;
using System.Text;
using System.Threading;
using System.Threading.Tasks;

using Xunit;

namespace System.Net.Security.Tests
{
    using Configuration = System.Net.Test.Common.Configuration;

    public abstract class SslStreamStreamToStreamTest
    {
        private readonly byte[] _sampleMsg = Encoding.UTF8.GetBytes("Sample Test Message");

        protected abstract Task DoHandshake(SslStream clientSslStream, SslStream serverSslStream);

        protected abstract Task<int> ReadAsync(Stream stream, byte[] buffer, int offset, int count, CancellationToken cancellationToken = default);

        protected abstract Task WriteAsync(Stream stream, byte[] buffer, int offset, int count, CancellationToken cancellationToken = default);

        [Fact]
        public async Task SslStream_StreamToStream_Authentication_Success()
        {
            VirtualNetwork network = new VirtualNetwork();

            using (var clientStream = new VirtualNetworkStream(network, isServer: false))
            using (var serverStream = new VirtualNetworkStream(network, isServer: true))
            using (var client = new SslStream(clientStream, false, AllowAnyServerCertificate))
            using (var server = new SslStream(serverStream))
            using (X509Certificate2 certificate = Configuration.Certificates.GetServerCertificate())
            {
                await DoHandshake(client, server);
                Assert.True(client.IsAuthenticated);
                Assert.True(server.IsAuthenticated);
            }
        }

        [Fact]
        public async Task SslStream_StreamToStream_Authentication_IncorrectServerName_Fail()
        {
            VirtualNetwork network = new VirtualNetwork();

            using (var clientStream = new VirtualNetworkStream(network, isServer: false))
            using (var serverStream = new VirtualNetworkStream(network, isServer: true))
            using (var client = new SslStream(clientStream))
            using (var server = new SslStream(serverStream))
            using (var certificate = Configuration.Certificates.GetServerCertificate())
            {
                Task t1 = client.AuthenticateAsClientAsync("incorrectServer");
                Task t2 = server.AuthenticateAsServerAsync(certificate);

                await Assert.ThrowsAsync<AuthenticationException>(() => t1);
                await t2;
            }
        }

        [Fact]
        public async Task SslStream_ServerLocalCertificateSelectionCallbackReturnsNull_Throw()
        {
            VirtualNetwork network = new VirtualNetwork();

            var selectionCallback = new LocalCertificateSelectionCallback((object sender, string targetHost, X509CertificateCollection localCertificates, X509Certificate remoteCertificate, string[] issuers) =>
            {
                return null;
            });

            using (var clientStream = new VirtualNetworkStream(network, isServer: false))
            using (var serverStream = new VirtualNetworkStream(network, isServer: true))
            using (var client = new SslStream(clientStream, false, AllowAnyServerCertificate))
            using (var server = new SslStream(serverStream, false, null, selectionCallback))
            using (X509Certificate2 certificate = Configuration.Certificates.GetServerCertificate())
            {
                await Assert.ThrowsAsync<NotSupportedException>(async () =>
                    await TestConfiguration.WhenAllOrAnyFailedWithTimeout(client.AuthenticateAsClientAsync(certificate.GetNameInfo(X509NameType.SimpleName, false)), server.AuthenticateAsServerAsync(certificate))
                );
            }
        }

        [SkipOnTargetFramework(TargetFrameworkMonikers.NetFramework, ".NET Framework does not recover well from underlying stream failures")]
        [Fact]
        public async Task Read_CorrectlyUnlocksAfterFailure()
        {
            var network = new VirtualNetwork();
            var clientStream = new ThrowingDelegatingStream(new VirtualNetworkStream(network, isServer: false));
            using (var clientSslStream = new SslStream(clientStream, false, AllowAnyServerCertificate))
            using (var serverSslStream = new SslStream(new VirtualNetworkStream(network, isServer: true)))
            {
                await DoHandshake(clientSslStream, serverSslStream);

                // Throw an exception from the wrapped stream's read operation
                clientStream.ExceptionToThrow = new FormatException();
                IOException thrown = await Assert.ThrowsAsync<IOException>(() => ReadAsync(clientSslStream, new byte[1], 0, 1));
                Assert.Same(clientStream.ExceptionToThrow, thrown.InnerException);
                clientStream.ExceptionToThrow = null;

                // Validate that the SslStream continues to be usable
                for (byte b = 42; b < 52; b++) // arbitrary test values
                {
                    await WriteAsync(serverSslStream, new byte[1] { b }, 0, 1);
                    byte[] buffer = new byte[1];
                    Assert.Equal(1, await ReadAsync(clientSslStream, buffer, 0, 1));
                    Assert.Equal(b, buffer[0]);
                }
            }
        }

        [Fact]
        public async Task Write_CorrectlyUnlocksAfterFailure()
        {
            var network = new VirtualNetwork();
            var clientStream = new ThrowingDelegatingStream(new VirtualNetworkStream(network, isServer: false));
            using (var clientSslStream = new SslStream(clientStream, false, AllowAnyServerCertificate))
            using (var serverSslStream = new SslStream(new VirtualNetworkStream(network, isServer: true)))
            {
                await DoHandshake(clientSslStream, serverSslStream);

                // Throw an exception from the wrapped stream's write operation
                clientStream.ExceptionToThrow = new FormatException();
                IOException thrown = await Assert.ThrowsAsync<IOException>(() => WriteAsync(clientSslStream, new byte[1], 0, 1));
                Assert.Same(clientStream.ExceptionToThrow, thrown.InnerException);
                clientStream.ExceptionToThrow = null;

                // Validate that the SslStream continues to be writable. However, the stream is still largely
                // unusable: because the previously encrypted data won't have been written to the underlying
                // stream and thus not received by the reader, if we tried to validate this data being received
                // by the reader, it would likely fail with a decryption error.
                await WriteAsync(clientSslStream, new byte[1] { 42 }, 0, 1);
            }
        }

        [Fact]
        public async Task Read_InvokedSynchronously()
        {
            var network = new VirtualNetwork();
            var clientStream = new PreReadWriteActionDelegatingStream(new VirtualNetworkStream(network, isServer: false));
            using (var clientSslStream = new SslStream(clientStream, false, AllowAnyServerCertificate))
            using (var serverSslStream = new SslStream(new VirtualNetworkStream(network, isServer: true)))
            {
                await DoHandshake(clientSslStream, serverSslStream);

                // Validate that the read call to the underlying stream is made as part of the
                // synchronous call to the read method on SslStream, even if the method is async.
                using (var tl = new ThreadLocal<int>())
                {
                    await WriteAsync(serverSslStream, new byte[1], 0, 1);
                    tl.Value = 42;
                    clientStream.PreReadWriteAction = () => Assert.Equal(42, tl.Value);
                    Task t = ReadAsync(clientSslStream, new byte[1], 0, 1);
                    tl.Value = 0;
                    await t;
                }
            }
        }

        [Fact]
        public async Task Write_InvokedSynchronously()
        {
            var network = new VirtualNetwork();
            var clientStream = new PreReadWriteActionDelegatingStream(new VirtualNetworkStream(network, isServer: false));
            using (var clientSslStream = new SslStream(clientStream, false, AllowAnyServerCertificate))
            using (var serverSslStream = new SslStream(new VirtualNetworkStream(network, isServer: true)))
            {
                await DoHandshake(clientSslStream, serverSslStream);

                // Validate that the write call to the underlying stream is made as part of the
                // synchronous call to the write method on SslStream, even if the method is async.
                using (var tl = new ThreadLocal<int>())
                {
                    tl.Value = 42;
                    clientStream.PreReadWriteAction = () => Assert.Equal(42, tl.Value);
                    Task t = WriteAsync(clientSslStream, new byte[1], 0, 1);
                    tl.Value = 0;
                    await t;
                }
            }
        }

        [Fact]
        public async Task SslStream_StreamToStream_Successive_ClientWrite_WithZeroBytes_Success()
        {
            byte[] recvBuf = new byte[_sampleMsg.Length];
            VirtualNetwork network = new VirtualNetwork();

            using (var clientStream = new VirtualNetworkStream(network, isServer: false))
            using (var serverStream = new VirtualNetworkStream(network, isServer: true))
            using (var clientSslStream = new SslStream(clientStream, false, AllowAnyServerCertificate))
            using (var serverSslStream = new SslStream(serverStream))
            {
                await DoHandshake(clientSslStream, serverSslStream);

                await WriteAsync(clientSslStream, Array.Empty<byte>(), 0, 0);
                await WriteAsync(clientSslStream, _sampleMsg, 0, _sampleMsg.Length);

                int bytesRead = 0;
                while (bytesRead < _sampleMsg.Length)
                {
                    bytesRead += await ReadAsync(serverSslStream, recvBuf, bytesRead, _sampleMsg.Length - bytesRead);
                }

                Assert.True(VerifyOutput(recvBuf, _sampleMsg), "verify first read data is as expected.");

                await WriteAsync(clientSslStream, _sampleMsg, 0, _sampleMsg.Length);
                await WriteAsync(clientSslStream, Array.Empty<byte>(), 0, 0);

                bytesRead = 0;
                while (bytesRead < _sampleMsg.Length)
                {
                    bytesRead += await ReadAsync(serverSslStream, recvBuf, bytesRead, _sampleMsg.Length - bytesRead);
                }
                Assert.True(VerifyOutput(recvBuf, _sampleMsg), "verify second read data is as expected.");
            }
        }

        [Theory]
        [InlineData(false)]
        [InlineData(true)]
        public async Task SslStream_StreamToStream_LargeWrites_Success(bool randomizedData)
        {
            VirtualNetwork network = new VirtualNetwork();

            using (var clientStream = new VirtualNetworkStream(network, isServer: false))
            using (var serverStream = new VirtualNetworkStream(network, isServer: true))
            using (var clientSslStream = new SslStream(clientStream, false, AllowAnyServerCertificate))
            using (var serverSslStream = new SslStream(serverStream))
            {
                await DoHandshake(clientSslStream, serverSslStream);

                byte[] largeMsg = new byte[4096 * 5]; // length longer than max read chunk size (16K + headers)
                if (randomizedData)
                {
                    new Random().NextBytes(largeMsg); // not very compressible
                }
                else
                {
                    for (int i = 0; i < largeMsg.Length; i++)
                    {
                        largeMsg[i] = unchecked((byte)i); // very compressible
                    }
                }
                byte[] receivedLargeMsg = new byte[largeMsg.Length];

                // First do a large write and read blocks at a time
                await WriteAsync(clientSslStream, largeMsg, 0, largeMsg.Length);
                int bytesRead = 0, totalRead = 0;
                while (totalRead < largeMsg.Length &&
                    (bytesRead = await ReadAsync(serverSslStream, receivedLargeMsg, totalRead, receivedLargeMsg.Length - totalRead)) != 0)
                {
                    totalRead += bytesRead;
                }
                Assert.Equal(receivedLargeMsg.Length, totalRead);
                Assert.Equal(largeMsg, receivedLargeMsg);

                // Then write again and read bytes at a time
                await WriteAsync(clientSslStream, largeMsg, 0, largeMsg.Length);
                foreach (byte b in largeMsg)
                {
                    Assert.Equal(b, serverSslStream.ReadByte());
                }
            }
        }

        [Fact]
        public async Task SslStream_StreamToStream_Successive_ClientWrite_Success()
        {
            byte[] recvBuf = new byte[_sampleMsg.Length];
            VirtualNetwork network = new VirtualNetwork();

            using (var clientStream = new VirtualNetworkStream(network, isServer: false))
            using (var serverStream = new VirtualNetworkStream(network, isServer: true))
            using (var clientSslStream = new SslStream(clientStream, false, AllowAnyServerCertificate))
            using (var serverSslStream = new SslStream(serverStream))
            {
                await DoHandshake(clientSslStream, serverSslStream);

                await WriteAsync(clientSslStream, _sampleMsg, 0, _sampleMsg.Length)
                    .TimeoutAfter(TestConfiguration.PassingTestTimeoutMilliseconds);

                int bytesRead = 0;
                while (bytesRead < _sampleMsg.Length)
                {
                    bytesRead += await ReadAsync(serverSslStream, recvBuf, bytesRead, _sampleMsg.Length - bytesRead)
                        .TimeoutAfter(TestConfiguration.PassingTestTimeoutMilliseconds);
                }

                Assert.True(VerifyOutput(recvBuf, _sampleMsg), "verify first read data is as expected.");

                await WriteAsync(clientSslStream, _sampleMsg, 0, _sampleMsg.Length)
                    .TimeoutAfter(TestConfiguration.PassingTestTimeoutMilliseconds);

                bytesRead = 0;
                while (bytesRead < _sampleMsg.Length)
                {
                    bytesRead += await ReadAsync(serverSslStream, recvBuf, bytesRead, _sampleMsg.Length - bytesRead)
                        .TimeoutAfter(TestConfiguration.PassingTestTimeoutMilliseconds);
                }

                Assert.True(VerifyOutput(recvBuf, _sampleMsg), "verify second read data is as expected.");
            }
        }

        [Fact]
        public async Task SslStream_StreamToStream_Write_ReadByte_Success()
        {
            VirtualNetwork network = new VirtualNetwork();

            using (var clientStream = new VirtualNetworkStream(network, isServer: false))
            using (var serverStream = new VirtualNetworkStream(network, isServer: true))
            using (var clientSslStream = new SslStream(clientStream, false, AllowAnyServerCertificate))
            using (var serverSslStream = new SslStream(serverStream))
            {
                await DoHandshake(clientSslStream, serverSslStream);

                for (int i = 0; i < 3; i++)
                {
                    await WriteAsync(clientSslStream, _sampleMsg, 0, _sampleMsg.Length);
                    foreach (byte b in _sampleMsg)
                    {
                        Assert.Equal(b, serverSslStream.ReadByte());
                    }
                }
            }
        }

        [Fact]
        public async Task SslStream_StreamToStream_WriteAsync_ReadByte_Success()
        {
            VirtualNetwork network = new VirtualNetwork();

            using (var clientStream = new VirtualNetworkStream(network, isServer: false))
            using (var serverStream = new VirtualNetworkStream(network, isServer: true))
            using (var clientSslStream = new SslStream(clientStream, false, AllowAnyServerCertificate))
            using (var serverSslStream = new SslStream(serverStream))
            {
                await DoHandshake(clientSslStream, serverSslStream);

                for (int i = 0; i < 3; i++)
                {
                    await WriteAsync(clientSslStream, _sampleMsg, 0, _sampleMsg.Length).ConfigureAwait(false);
                    foreach (byte b in _sampleMsg)
                    {
                        Assert.Equal(b, serverSslStream.ReadByte());
                    }
                }
            }
        }

        [Fact]
        public async Task SslStream_StreamToStream_WriteAsync_ReadAsync_Pending_Success()
        {
            if (this is SslStreamStreamToStreamTest_Sync)
            {
                // This test assumes operations complete asynchronously.
                return;
            }

            VirtualNetwork network = new VirtualNetwork();

            using (var clientStream = new VirtualNetworkStream(network, isServer: false))
            using (var serverStream = new NotifyReadVirtualNetworkStream(network, isServer: true))
            using (var clientSslStream = new SslStream(clientStream, false, AllowAnyServerCertificate))
            using (var serverSslStream = new SslStream(serverStream))
            {
                await DoHandshake(clientSslStream, serverSslStream);

                var serverBuffer = new byte[1];
                var tcs = new TaskCompletionSource<object>();
                serverStream.OnRead += (buffer, offset, count) =>
                {
                    tcs.TrySetResult(null);
                };
                Task readTask = ReadAsync(serverSslStream, serverBuffer, 0, serverBuffer.Length);

                // Since the sequence of calls that ends in serverStream.Read() is sync, by now
                // the read task will have acquired the semaphore shared by Stream.BeginReadInternal()
                // and Stream.BeginWriteInternal().
                // But to be sure, we wait until we know we're inside Read().
                await tcs.Task.TimeoutAfter(TestConfiguration.PassingTestTimeoutMilliseconds);

                // Should not hang
                await WriteAsync(serverSslStream, new byte[] { 1 }, 0, 1)
                    .TimeoutAfter(TestConfiguration.PassingTestTimeoutMilliseconds);

                // Read in client
                var clientBuffer = new byte[1];
                await ReadAsync(clientSslStream, clientBuffer, 0, clientBuffer.Length);
                Assert.Equal(1, clientBuffer[0]);

                // Complete server read task
                await WriteAsync(clientSslStream, new byte[] { 2 }, 0, 1);
                await readTask;
                Assert.Equal(2, serverBuffer[0]);
            }
        }

        [Fact]
        public async Task SslStream_ConcurrentBidirectionalReadsWrites_Success()
        {
            VirtualNetwork network = new VirtualNetwork();
            using (var clientSslStream = new SslStream(new VirtualNetworkStream(network, isServer: false), false, AllowAnyServerCertificate))
            using (var serverSslStream = new SslStream(new NotifyReadVirtualNetworkStream(network, isServer: true)))
            {
                await DoHandshake(clientSslStream, serverSslStream);

                const int BytesPerSend = 100;
                DateTime endTime = DateTime.UtcNow + TimeSpan.FromSeconds(3);
                await new Task[]
                {
                    Task.Run(async delegate
                    {
                        var buffer = new byte[BytesPerSend];
                        while (DateTime.UtcNow < endTime)
                        {
                            await WriteAsync(clientSslStream, buffer, 0, buffer.Length);
                            int received = 0, bytesRead = 0;
                            while (received < BytesPerSend && (bytesRead = await ReadAsync(serverSslStream, buffer, 0, buffer.Length)) != 0)
                            {
                                received += bytesRead;
                            }
                            Assert.NotEqual(0, bytesRead);
                        }
                    }),
                    Task.Run(async delegate
                    {
                        var buffer = new byte[BytesPerSend];
                        while (DateTime.UtcNow < endTime)
                        {
                            await WriteAsync(serverSslStream, buffer, 0, buffer.Length);
                            int received = 0, bytesRead = 0;
                            while (received < BytesPerSend && (bytesRead = await ReadAsync(clientSslStream, buffer, 0, buffer.Length)) != 0)
                            {
                                received += bytesRead;
                            }
                            Assert.NotEqual(0, bytesRead);
                        }
                    })
                }.WhenAllOrAnyFailed();
            }
        }

        [Fact]
        public async Task SslStream_StreamToStream_Dispose_Throws()
        {
            if (this is SslStreamStreamToStreamTest_Sync)
            {
                // This test assumes operations complete asynchronously.
                return;
            }

            VirtualNetwork network = new VirtualNetwork()
            {
                DisableConnectionBreaking = true
            };

            using (var clientStream = new VirtualNetworkStream(network, isServer: false))
            using (var serverStream = new VirtualNetworkStream(network, isServer: true))
            using (var clientSslStream = new SslStream(clientStream, false, AllowAnyServerCertificate))
            {
                var serverSslStream = new SslStream(serverStream);
                await DoHandshake(clientSslStream, serverSslStream);

                var serverBuffer = new byte[1];
                Task serverReadTask = ReadAsync(serverSslStream, serverBuffer, 0, serverBuffer.Length);
                await WriteAsync(serverSslStream, new byte[] { 1 }, 0, 1)
                    .TimeoutAfter(TestConfiguration.PassingTestTimeoutMilliseconds);

                // Shouldn't throw, the context is diposed now.
                // Since the server read task is in progress, the read buffer is not returned to ArrayPool.
                serverSslStream.Dispose();

                // Read in client
                var clientBuffer = new byte[1];
                await ReadAsync(clientSslStream, clientBuffer, 0, clientBuffer.Length);
                Assert.Equal(1, clientBuffer[0]);

                await WriteAsync(clientSslStream, new byte[] { 2 }, 0, 1);

                // We're inconsistent as to whether the ObjectDisposedException is thrown directly
                // or wrapped in an IOException.  For Begin/End, it's always wrapped; for Async,
                // it's only wrapped on netfx.
                if (this is SslStreamStreamToStreamTest_BeginEnd || PlatformDetection.IsFullFramework)
                {
                    await Assert.ThrowsAsync<ObjectDisposedException>(() => serverReadTask);
                }
                else
                {
                    IOException serverException = await Assert.ThrowsAsync<IOException>(() => serverReadTask);
                    Assert.IsType<ObjectDisposedException>(serverException.InnerException);
                }

                await Assert.ThrowsAsync<ObjectDisposedException>(() => ReadAsync(serverSslStream, serverBuffer, 0, serverBuffer.Length));

                // Now, there is no pending read, so the internal buffer will be returned to ArrayPool.
                serverSslStream.Dispose();
                await Assert.ThrowsAsync<ObjectDisposedException>(() => ReadAsync(serverSslStream, serverBuffer, 0, serverBuffer.Length));
            }
        }

        [Fact]
        public void SslStream_StreamToStream_Flush_Propagated()
        {
            VirtualNetwork network = new VirtualNetwork();

            using (var stream = new VirtualNetworkStream(network, isServer: false))
            using (var sslStream = new SslStream(stream, false, AllowAnyServerCertificate))
            {
                Assert.False(stream.HasBeenSyncFlushed);
                sslStream.Flush();
                Assert.True(stream.HasBeenSyncFlushed);
            }
        }

        [Fact]
        [SkipOnTargetFramework(TargetFrameworkMonikers.NetFramework, "Relies on FlushAsync override not available in desktop")]
        public void SslStream_StreamToStream_FlushAsync_Propagated()
        {
            VirtualNetwork network = new VirtualNetwork();

            using (var stream = new VirtualNetworkStream(network, isServer: false))
            using (var sslStream = new SslStream(stream, false, AllowAnyServerCertificate))
            {
                Task task = sslStream.FlushAsync();

                Assert.False(task.IsCompleted);
                stream.CompleteAsyncFlush();
                Assert.True(task.IsCompleted);
            }
        }

        [Fact]
        public async Task SslStream_StreamToStream_EOFDuringFrameRead_ThrowsIOException()
        {
            var network = new VirtualNetwork();
            using (var clientNetworkStream = new VirtualNetworkStream(network, isServer: false))
            using (var serverNetworkStream = new VirtualNetworkStream(network, isServer: true))
            {
                int readMode = 0;
                var serverWrappedNetworkStream = new DelegateStream(
                    canWriteFunc: () => true,
                    canReadFunc: () => true,
                    writeFunc: (buffer, offset, count) => serverNetworkStream.Write(buffer, offset, count),
                    writeAsyncFunc: (buffer, offset, count, token) => serverNetworkStream.WriteAsync(buffer, offset, count, token),
                    readFunc: (buffer, offset, count) =>
                    {
                        // Do normal reads as requested until the read mode is set
                        // to 1.  Then do a single read of only 10 bytes to read only
                        // part of the message, and subsequently return EOF.
                        if (readMode == 0)
                        {
                            return serverNetworkStream.Read(buffer, offset, count);
                        }
                        else if (readMode == 1)
                        {
                            readMode = 2;
                            return serverNetworkStream.Read(buffer, offset, 10); // read at least header but less than full frame
                        }
                        else
                        {
                            return 0;
                        }
                    },
                    readAsyncFunc: (buffer, offset, count, token) =>
                    {
                        // Do normal reads as requested until the read mode is set
                        // to 1.  Then do a single read of only 10 bytes to read only
                        // part of the message, and subsequently return EOF.
                        if (readMode == 0)
                        {
                            return serverNetworkStream.ReadAsync(buffer, offset, count);
                        }
                        else if (readMode == 1)
                        {
                            readMode = 2;
                            return serverNetworkStream.ReadAsync(buffer, offset, 10); // read at least header but less than full frame
                        }
                        else
                        {
                            return Task.FromResult(0);
                        }
                    });

                using (var clientSslStream = new SslStream(clientNetworkStream, false, AllowAnyServerCertificate))
                using (var serverSslStream = new SslStream(serverWrappedNetworkStream))
                {
                    await DoHandshake(clientSslStream, serverSslStream);
                    await WriteAsync(clientSslStream, new byte[20], 0, 20);
                    readMode = 1;
                    await Assert.ThrowsAsync<IOException>(() => ReadAsync(serverSslStream, new byte[1], 0, 1));
                }
            }
        }

        private bool VerifyOutput(byte[] actualBuffer, byte[] expectedBuffer)
        {
            return expectedBuffer.SequenceEqual(actualBuffer);
        }

        protected bool AllowAnyServerCertificate(
            object sender,
            X509Certificate certificate,
            X509Chain chain,
            SslPolicyErrors sslPolicyErrors)
        {
            SslPolicyErrors expectedSslPolicyErrors = SslPolicyErrors.None;

            if (!Capability.IsTrustedRootCertificateInstalled())
            {
                expectedSslPolicyErrors = SslPolicyErrors.RemoteCertificateChainErrors;
            }

            Assert.Equal(expectedSslPolicyErrors, sslPolicyErrors);

            if (sslPolicyErrors == expectedSslPolicyErrors)
            {
                return true;
            }
            else
            {
                return false;
            }
        }

        private class PreReadWriteActionDelegatingStream : Stream
        {
            private readonly Stream _stream;

            public PreReadWriteActionDelegatingStream(Stream stream) => _stream = stream;

            public Action PreReadWriteAction { get; set; }

            public override bool CanRead => _stream.CanRead;
            public override bool CanWrite => _stream.CanWrite;
            public override bool CanSeek => _stream.CanSeek;
            protected override void Dispose(bool disposing) => _stream.Dispose();
            public override long Length => _stream.Length;
            public override long Position { get => _stream.Position; set => _stream.Position = value; }
            public override void Flush() => _stream.Flush();
            public override long Seek(long offset, SeekOrigin origin) => _stream.Seek(offset, origin);
            public override void SetLength(long value) => _stream.SetLength(value);

            public override int Read(byte[] buffer, int offset, int count)
            {
                PreReadWriteAction?.Invoke();
                return _stream.Read(buffer, offset, count);
            }

            public override IAsyncResult BeginRead(byte[] buffer, int offset, int count, AsyncCallback callback, object state)
            {
                PreReadWriteAction?.Invoke();
                return _stream.BeginRead(buffer, offset, count, callback, state);
            }

            public override int EndRead(IAsyncResult asyncResult) => _stream.EndRead(asyncResult);

            public override Task<int> ReadAsync(byte[] buffer, int offset, int count, CancellationToken cancellationToken)
            {
                PreReadWriteAction?.Invoke();
                return _stream.ReadAsync(buffer, offset, count, cancellationToken);
            }

            public override void Write(byte[] buffer, int offset, int count)
            {
                PreReadWriteAction?.Invoke();
                _stream.Write(buffer, offset, count);
            }

            public override IAsyncResult BeginWrite(byte[] buffer, int offset, int count, AsyncCallback callback, object state)
            {
                PreReadWriteAction?.Invoke();
                return _stream.BeginWrite(buffer, offset, count, callback, state);
            }

            public override void EndWrite(IAsyncResult asyncResult) => _stream.EndWrite(asyncResult);

            public override Task WriteAsync(byte[] buffer, int offset, int count, CancellationToken cancellationToken)
            {
                PreReadWriteAction?.Invoke();
                return _stream.WriteAsync(buffer, offset, count, cancellationToken);
            }
        }

        private sealed class ThrowingDelegatingStream : PreReadWriteActionDelegatingStream
        {
            public ThrowingDelegatingStream(Stream stream) : base(stream)
            {
                PreReadWriteAction = () =>
                {
                    if (ExceptionToThrow != null)
                    {
                        throw ExceptionToThrow;
                    }
                };
            }

            public Exception ExceptionToThrow { get; set; }
        }
    }

    public sealed class SslStreamStreamToStreamTest_Async : SslStreamStreamToStreamTest
    {
        protected override async Task DoHandshake(SslStream clientSslStream, SslStream serverSslStream)
        {
            using (X509Certificate2 certificate = Configuration.Certificates.GetServerCertificate())
            {
                Task t1 = clientSslStream.AuthenticateAsClientAsync(certificate.GetNameInfo(X509NameType.SimpleName, false));
                Task t2 = serverSslStream.AuthenticateAsServerAsync(certificate);
                await TestConfiguration.WhenAllOrAnyFailedWithTimeout(t1, t2);
            }
        }

        protected override Task<int> ReadAsync(Stream stream, byte[] buffer, int offset, int count, CancellationToken cancellationToken = default(CancellationToken)) =>
            stream.ReadAsync(buffer, offset, count, cancellationToken);

        protected override Task WriteAsync(Stream stream, byte[] buffer, int offset, int count, CancellationToken cancellationToken = default(CancellationToken)) =>
            stream.WriteAsync(buffer, offset, count, cancellationToken);
    }

    public sealed class SslStreamStreamToStreamTest_BeginEnd : SslStreamStreamToStreamTest
    {
        protected override async Task DoHandshake(SslStream clientSslStream, SslStream serverSslStream)
        {
            using (X509Certificate2 certificate = Configuration.Certificates.GetServerCertificate())
            {
                Task t1 = Task.Factory.FromAsync(clientSslStream.BeginAuthenticateAsClient(certificate.GetNameInfo(X509NameType.SimpleName, false), null, null), clientSslStream.EndAuthenticateAsClient);
                Task t2 = Task.Factory.FromAsync(serverSslStream.BeginAuthenticateAsServer(certificate, null, null), serverSslStream.EndAuthenticateAsServer);
                await TestConfiguration.WhenAllOrAnyFailedWithTimeout(t1, t2);
            }
        }

        protected override Task<int> ReadAsync(Stream stream, byte[] buffer, int offset, int count, CancellationToken cancellationToken = default(CancellationToken)) =>
            cancellationToken.IsCancellationRequested ?
                Task.FromCanceled<int>(cancellationToken) :
                Task.Factory.FromAsync(stream.BeginRead, stream.EndRead, buffer, offset, count, null);

        protected override Task WriteAsync(Stream stream, byte[] buffer, int offset, int count, CancellationToken cancellationToken = default(CancellationToken)) =>
            cancellationToken.IsCancellationRequested ?
                Task.FromCanceled<int>(cancellationToken) :
                Task.Factory.FromAsync(stream.BeginWrite, stream.EndWrite, buffer, offset, count, null);
    }

    public sealed class SslStreamStreamToStreamTest_Sync : SslStreamStreamToStreamTest
    {
        protected override async Task DoHandshake(SslStream clientSslStream, SslStream serverSslStream)
        {
            using (X509Certificate2 certificate = Configuration.Certificates.GetServerCertificate())
            {
                Task t1 = Task.Run(() => clientSslStream.AuthenticateAsClient(certificate.GetNameInfo(X509NameType.SimpleName, false)));
                Task t2 = Task.Run(() => serverSslStream.AuthenticateAsServer(certificate));
                await TestConfiguration.WhenAllOrAnyFailedWithTimeout(t1, t2);
            }
        }

        protected override Task<int> ReadAsync(Stream stream, byte[] buffer, int offset, int count, CancellationToken cancellationToken = default(CancellationToken))
        {
            if (cancellationToken.IsCancellationRequested)
            {
                return Task.FromCanceled<int>(cancellationToken);
            }

            try
            {
                return Task.FromResult<int>(stream.Read(buffer, offset, count));
            }
            catch (Exception e)
            {
                return Task.FromException<int>(e);
            }
        }

        protected override Task WriteAsync(Stream stream, byte[] buffer, int offset, int count, CancellationToken cancellationToken = default(CancellationToken))
        {
            if (cancellationToken.IsCancellationRequested)
            {
                return Task.FromCanceled<int>(cancellationToken);
            }

            try
            {
                stream.Write(buffer, offset, count);
                return Task.CompletedTask;
            }
            catch (Exception e)
            {
                return Task.FromException<int>(e);
            }
        }
    }
}


text:
package org.apache.directory.shared.kerberos.codec.types;

/**
 * An enum describing the differnet types of Principal.
 *
 * Here is the list, taken from RFC 4120 :
 *  NT-UNKNOWN        0    Name type not known
 *  NT-PRINCIPAL      1    Just the name of the principal as in DCE,
 *                           or for users
 *  NT-SRV-INST       2    Service and other unique instance (krbtgt)
 *  NT-SRV-HST        3    Service with host name as instance
 *                           (telnet, rcommands)
 *  NT-SRV-XHST       4    Service with host as remaining components
 *  NT-UID            5    Unique ID
 *  NT-X500-PRINCIPAL 6    Encoded X.509 Distinguished name [RFC2253]
 *  NT-SMTP-NAME      7    Name in form of SMTP email name
 *                           (e.g., user@example.com)
 *  NT-ENTERPRISE    10    Enterprise name - may be mapped to principal
 *                           name
 *
 * @author Apache Directory Project
 */
public enum PrincipalNameType
{
    /** Constant for the "Name type not known" principal name type. */
    KRB_NT_UNKNOWN(0),

    /**Constant for the "Just the name of the principal as in DCE, or for users" principal name type. */
    KRB_NT_PRINCIPAL(1),

    /** Constant for the "Service and other unique instance (krbtgt)" principal name type. */
    KRB_NT_SRV_INST(2),

    /** Constant for the "Service with host name as instance (telnet, rcommands)" principal name type. */
    KRB_NT_SRV_HST(3),

    /** Constant for the "Service with host as remaining components" principal name type. */
    KRB_NT_SRV_XHST(4),

    /** Constant for the "Unique ID" principal name type. */
    KRB_NT_UID(5),

    /** Constant for the "Encoded X.509 Distinguished name [RFC2253]" principal name type. */
    KRB_NT_X500_PRINCIPAL(6),

    /** Constant for the "Name in form of SMTP email name (e.g., user@example.com)" principal name type. */
    KRB_NT_SMTP_NAME(7),

    /** Constant for the "Enterprise name; may be mapped to principal name" principal name type. */
    KRB_NT_ENTERPRISE(10);

    /**
     * The value/code for the principal name type.
     */
    private final int value;

    /**
     * Private constructor prevents construction outside of this class.
     */
    private PrincipalNameType( int value )
    {
        this.value = value;
    }

    /**
     * Returns the principal name type when specified by its ordinal.
     *
     * @param type
     * @return The principal name type.
     */
    public static PrincipalNameType getTypeByValue( int type )
    {
        switch ( type )
        {
            case 0:
                return KRB_NT_UNKNOWN;
            case 1:
                return KRB_NT_PRINCIPAL;
            case 2:
                return KRB_NT_SRV_INST;
            case 3:
                return KRB_NT_SRV_HST;
            case 4:
                return KRB_NT_SRV_XHST;
            case 5:
                return KRB_NT_UID;
            case 6:
                return KRB_NT_X500_PRINCIPAL;
            case 7:
                return KRB_NT_SMTP_NAME;
            case 10:
                return KRB_NT_ENTERPRISE;
            default:
                return KRB_NT_UNKNOWN;
        }
    }

    /**
     * Returns the number associated with this principal name type.
     *
     * @return The principal name type ordinal.
     */
    public int getValue()
    {
        return value;
    }

    /**
     * @see Object#toString()
     */
    @Override
    public String toString()
    {
        switch ( this )
        {
            case KRB_NT_UNKNOWN:
                return "Name type not known" + "(" + value + ")";

            case KRB_NT_PRINCIPAL:
                return "Just the name of the principal as in DCE, or for users" + "(" + value + ")";

            case KRB_NT_SRV_INST:
                return "Service and other unique instance (krbtgt)" + "(" + value + ")";

            case KRB_NT_SRV_HST:
                return "Service with host name as instance (telnet, rcommands)" + "(" + value + ")";

            case KRB_NT_SRV_XHST:
                return "Service with host as remaining components" + "(" + value + ")";

            case KRB_NT_UID:
                return "Unique ID" + "(" + value + ")";

            case KRB_NT_X500_PRINCIPAL:
                return "Encoded X.509 Distinguished name [RFC2253]" + "(" + value + ")";

            case KRB_NT_SMTP_NAME:
                return "Name in form of SMTP email name (e.g., user@example.com)" + "(" + value + ")";

            case KRB_NT_ENTERPRISE:
                return "Enterprise name; may be mapped to principal name" + "(" + value + ")";

            default:
                return "unknown name type" + "(" + value + ")";
        }
    }
}

redpajama_set_name: RedPajamaGithub


text:
<!DOCTYPE html><html><head><meta charset="utf-8" />
<meta http-equiv="refresh" content="0;url=/place/burkina-faso/legislation/" />
</head></html>


text:
from django.db import models
from django.utils.translation import ugettext_lazy as _
from django.utils.encoding import python_2_unicode_compatible

@python_2_unicode_compatible
class Author(models.Model):

    first_name = models.CharField(_('first name'), max_length=30)
    last_name = models.CharField(_('last name'), max_length=30)
    biography = models.TextField(_('biography'), blank=True)

    def __str__(self):
        return '%s %s' % (self.first_name, self.last_name)


text:
package org.apache.commons.scxml2.model;

import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.scxml2.ActionExecutionContext;
import org.apache.commons.scxml2.Context;
import org.apache.commons.scxml2.Evaluator;
import org.apache.commons.scxml2.EventBuilder;
import org.apache.commons.scxml2.SCXMLExpressionException;
import org.apache.commons.scxml2.SCXMLIOProcessor;
import org.apache.commons.scxml2.SCXMLSystemContext;
import org.apache.commons.scxml2.TriggerEvent;
import org.apache.commons.scxml2.semantics.ErrorConstants;

/**
 * The class in this SCXML object model that corresponds to the
 * <send> SCXML element.
 *
 */
public class Send extends Action implements ContentContainer, ParamsContainer {

    /**
     * Serial version UID.
     */
    private static final long serialVersionUID = 1L;

    /**
     * The suffix in the delay string for milliseconds.
     */
    private static final String MILLIS = "ms";

    /**
     * The suffix in the delay string for seconds.
     */
    private static final String SECONDS = "s";

    /**
     * The suffix in the delay string for minutes.
     */
    private static final String MINUTES = "m";

    /**
     * The number of milliseconds in a second.
     */
    private static final long MILLIS_IN_A_SECOND = 1000L;

    /**
     * The number of milliseconds in a minute.
     */
    private static final long MILLIS_IN_A_MINUTE = 60000L;

    /**
     * The ID of the send message.
     */
    private String id;

    /**
     * Path expression evaluating to a location within a previously defined XML data tree.
     */
    private String idlocation;

    /**
     * The target location of the event.
     */
    private String target;

    /**
     * An expression specifying the target location of the event.
     */
    private String targetexpr;

    /**
     * The type of the Event I/O Processor that the event should be dispatched to.
     */
    private String type;

    /**
     * An expression defining the type of the Event I/O Processor that the event should be dispatched to.
     */
    private String typeexpr;

    /**
     * The delay the event is dispatched after.
     */
    private String delay;

    /**
     * An expression defining the delay the event is dispatched after.
     */
    private String delayexpr;

    /**
     * The data containing information which may be used by the implementing platform to configure the event processor.
     */
    private String hints;

    /**
     * The type of event being generated.
     */
    private String event;

    /**
     * An expression defining the type of event being generated.
     */
    private String eventexpr;

    /**
     * The <content/> of this send
     */
    private Content content;

    /**
     * The List of the params to be sent
     */
    private final List<Param> paramsList = new ArrayList<>();

    /**
     * The namelist.
     */
    private String namelist;

    /**
     * Constructor.
     */
    public Send() {
    }

    /**
     * @return the idlocation
     */
    public String getIdlocation() {
        return idlocation;
    }

    /**
     * Set the idlocation expression
     *
     * @param idlocation The idlocation expression
     */
    public void setIdlocation(final String idlocation) {
        this.idlocation = idlocation;
    }

    /**
     * Get the delay.
     *
     * @return Returns the delay.
     */
    public final String getDelay() {
        return delay;
    }

    /**
     * Set the delay.
     *
     * @param delay The delay to set.
     */
    public final void setDelay(final String delay) {
        this.delay = delay;
    }

    /**
     * @return The delay expression
     */
    public String getDelayexpr() {
        return delayexpr;
    }

    /**
     * Set the delay expression
     *
     * @param delayexpr The delay expression to set
     */
    public void setDelayexpr(final String delayexpr) {
        this.delayexpr = delayexpr;
    }

    /**
     * Get the hints for this <send> element.
     *
     * @return String Returns the hints.
     */
    public final String getHints() {
        return hints;
    }

    /**
     * Set the hints for this <send> element.
     *
     * @param hints The hints to set.
     */
    public final void setHints(final String hints) {
        this.hints = hints;
    }

    /**
     * Get the identifier for this <send> element.
     *
     * @return String Returns the id.
     */
    public final String getId() {
        return id;
    }

    /**
     * Set the identifier for this <send> element.
     *
     * @param id The id to set.
     */
    public final void setId(final String id) {
        this.id = id;
    }

    /**
     * Get the target for this <send> element.
     *
     * @return String Returns the target.
     */
    public final String getTarget() {
        return target;
    }

    /**
     * Set the target for this <send> element.
     *
     * @param target The target to set.
     */
    public final void setTarget(final String target) {
        this.target = target;
    }

    /**
     * @return The target expression
     */
    public String getTargetexpr() {
        return targetexpr;
    }

    /**
     * Set the target expression
     *
     * @param targetexpr The target expression to set
     */
    public void setTargetexpr(final String targetexpr) {
        this.targetexpr = targetexpr;
    }

    /**
     * Get the type for this <send> element.
     *
     * @return String Returns the type.
     */
    public final String getType() {
        return type;
    }

    /**
     * Set the type for this <send> element.
     *
     * @param type The type to set.
     */
    public final void setType(final String type) {
        this.type = type;
    }

    /**
     * @return The type expression
     */
    public String getTypeexpr() {
        return typeexpr;
    }

    /**
     * Sets the type expression
     *
     * @param typeexpr The type expression to set
     */
    public void setTypeexpr(final String typeexpr) {
        this.typeexpr = typeexpr;
    }

    /**
     * Get the event to send.
     *
     * @param event The event to set.
     */
    public final void setEvent(final String event) {
        this.event = event;
    }

    /**
     * Set the event to send.
     *
     * @return String Returns the event.
     */
    public final String getEvent() {
        return event;
    }

    /**
     * @return The event expression
     */
    public String getEventexpr() {
        return eventexpr;
    }

    /**
     * Sets the event expression
     *
     * @param eventexpr The event expression to set
     */
    public void setEventexpr(final String eventexpr) {
        this.eventexpr = eventexpr;
    }

    /**
     * Returns the content
     *
     * @return the content
     */
    public Content getContent() {
        return content;
    }

    /**
     * Sets the content
     *
     * @param content the content to set
     */
    public void setContent(final Content content) {
        this.content = content;
    }

    /**
     * Get the list of {@link Param}s.
     *
     * @return List The params list.
     */
    public List<Param> getParams() {
        return paramsList;
    }

    /**
     * Get the namelist.
     *
     * @return String Returns the namelist.
     */
    public final String getNamelist() {
        return namelist;
    }

    /**
     * Set the namelist.
     *
     * @param namelist The namelist to set.
     */
    public final void setNamelist(final String namelist) {
        this.namelist = namelist;
    }

    /**
     * {@inheritDoc}
     */
    @SuppressWarnings("unchecked")
    @Override
    public void execute(final ActionExecutionContext exctx) throws ModelException, SCXMLExpressionException {
        // Send attributes evaluation
        final EnterableState parentState = getParentEnterableState();
        final Context ctx = exctx.getContext(parentState);
        final Evaluator eval = exctx.getEvaluator();
        // Most attributes of <send> are expressions so need to be
        // evaluated before the EventDispatcher callback
        Object hintsValue = null;
        if (hints != null) {
            hintsValue = eval.eval(ctx, hints);
        }
        if (idlocation != null) {
            if (id == null) {
                id = ctx.getSystemContext().generateSessionId();
            }
            eval.evalAssign(ctx, idlocation, id);
        }
        String targetValue = target;
        if (targetValue == null && targetexpr != null) {
            targetValue = (String)eval.eval(ctx, targetexpr);
            if ((targetValue == null || targetValue.trim().isEmpty())
                    && exctx.getAppLog().isWarnEnabled()) {
                exctx.getAppLog().warn("<send>: target expression \"" + targetexpr
                        + "\" evaluated to null or empty String");
            }
        }
        String typeValue = type;
        if (typeValue == null && typeexpr != null) {
            typeValue = (String)eval.eval(ctx, typeexpr);
            if ((typeValue == null || typeValue.trim().isEmpty())
                    && exctx.getAppLog().isWarnEnabled()) {
                exctx.getAppLog().warn("<send>: type expression \"" + typeexpr
                        + "\" evaluated to null or empty String");
            }
        }
        if (typeValue == null) {
            // must default to 'scxml' when unspecified
            typeValue = SCXMLIOProcessor.DEFAULT_EVENT_PROCESSOR;
        } else if (!SCXMLIOProcessor.DEFAULT_EVENT_PROCESSOR.equals(typeValue) && typeValue.trim().equalsIgnoreCase(SCXMLIOProcessor.SCXML_EVENT_PROCESSOR)) {
            typeValue = SCXMLIOProcessor.DEFAULT_EVENT_PROCESSOR;
        }
        Object payload = null;
        final Map<String, Object> payloadDataMap = new LinkedHashMap<>();
        PayloadBuilder.addNamelistDataToPayload(parentState, ctx, eval, exctx.getErrorReporter(), namelist, payloadDataMap);
        PayloadBuilder.addParamsToPayload(ctx, eval, paramsList, payloadDataMap);
        if (!payloadDataMap.isEmpty()) {
            payload = payloadDataMap;
        }
        else if (content != null) {
            if (content.getExpr() != null) {
                Object evalResult;
                try {
                    evalResult = eval.eval(ctx, content.getExpr());
                } catch (final SCXMLExpressionException e) {
                    exctx.getInternalIOProcessor().addEvent(new EventBuilder(TriggerEvent.ERROR_EXECUTION,
                            TriggerEvent.ERROR_EVENT).build());
                    exctx.getErrorReporter().onError(ErrorConstants.EXPRESSION_ERROR,
                            "Failed to evaluate <send> <content> expression due to error: "+ e.getMessage()
                                    + ", Using empty value instead.", getParent());
                    evalResult = "";
                }
                payload = eval.cloneData(evalResult);
            } else if (content.getParsedValue() != null) {
                payload = content.getParsedValue().getValue();
            }
        }
        long wait = 0L;
        String delayString = delay;
        if (delayString == null && delayexpr != null) {
            final Object delayValue = eval.eval(ctx, delayexpr);
            if (delayValue != null) {
                delayString = delayValue.toString();
            }
        }
        if (delayString != null) {
            wait = parseDelay(delayString, delayexpr != null, delayexpr != null ? delayexpr : delay);
        }
        String eventValue = event;
        if (eventValue == null && eventexpr != null) {
            eventValue = (String)eval.eval(ctx, eventexpr);
            if ((eventValue == null)) {
                throw new SCXMLExpressionException("<send>: event expression \"" + eventexpr
                        + "\" evaluated to null");
            }
        }
        final Map<String, SCXMLIOProcessor> ioProcessors = (Map<String, SCXMLIOProcessor>) ctx.get(SCXMLSystemContext.IOPROCESSORS_KEY);
        if (exctx.getAppLog().isDebugEnabled()) {
            exctx.getAppLog().debug("<send>: Dispatching event '" + eventValue
                    + "' to target '" + targetValue + "' of target type '"
                    + typeValue + "' with suggested delay of " + wait
                    + "ms");
        }
        exctx.getEventDispatcher().send(ioProcessors, id, targetValue, typeValue, eventValue,
                payload, hintsValue, wait);
    }

    /**
     * Parse delay.
     *
     * @param delayString The String value of the delay, in CSS2 format
     * @param expression indicates if this is for a delayexpr or delay attribute
     * @param delayStringSource the original delayString source (delayString might be different in case of a delayexpr)
     * @return The parsed delay in milliseconds
     * @throws SCXMLExpressionException If the delay cannot be parsed
     */
    static long parseDelay(final String delayString, final boolean expression, final String delayStringSource)
            throws SCXMLExpressionException {

        long wait = 0L;
        long multiplier = 1L;

        if (delayString != null && !delayString.trim().isEmpty()) {

            try {
                final String trimDelay = delayString.trim();
                String numericDelay = trimDelay;
                if (trimDelay.endsWith(MILLIS)) {
                    numericDelay = trimDelay.substring(0, trimDelay.length() - 2);
                } else if (trimDelay.endsWith(SECONDS)) {
                    multiplier = multiplier*MILLIS_IN_A_SECOND;
                    numericDelay = trimDelay.substring(0, trimDelay.length() - 1);
                } else if (trimDelay.endsWith(MINUTES)) { // Not CSS2
                    multiplier = multiplier*MILLIS_IN_A_MINUTE;
                    numericDelay = trimDelay.substring(0, trimDelay.length() - 1);
                }
                final int fractionIndex = numericDelay.indexOf('.');
                if (fractionIndex > -1) {
                    if (fractionIndex > 0) {
                        wait = Long.parseLong(numericDelay.substring(0, fractionIndex));
                        wait *= multiplier;
                    }
                    numericDelay = numericDelay.substring(fractionIndex+1);
                    multiplier /= Math.pow(10, numericDelay.length());
                }
                if (!numericDelay.isEmpty()) {
                    wait += Long.parseLong(numericDelay) * multiplier;
                }
            } catch (final NumberFormatException nfe) {
                throw new SCXMLExpressionException("<send>: invalid " + (expression ? "delayexpr=\"" : "delay=\"") + delayStringSource +"\"");
            }
        }
        return wait;
    }
}


text:
lgtv = require("lgtv");
/*---------------------------------------------------------------------------*/
var args = process.argv.slice(2);
var vol = 10;
if (args.length > 0) {
  try {
    vol = parseInt(args[0]);
  } catch(error) {
  }
}

var retry_timeout = 10;
var run_test = function() {
    lgtv.discover_ip(retry_timeout, function(err, ipaddr) {
      if (err) {
        console.log("Failed to find TV IP address on the LAN. Verify that TV is on, and that you are on the same LAN/Wifi.");

      } else {
        console.log("Found TV at address " + ipaddr + ", running example.");
        lgtv.connect(ipaddr, function(err, response){
          if (!err) {
            console.log("setting volume to:" + vol);
            lgtv.set_volume(vol, function(err, response){
              lgtv.disconnect();
            });
          }
        });
      }
    });
};

run_test();


text:
"""
    productporter.user.views
    ~~~~~~~~~~~~~~~~~~~~~~~~

    This view provides user authentication, registration and a view for
    resetting the password of a user if he has lost his password

    :copyright: (c) 2014 by the ProductPorter Team.
    :license: BSD, see LICENSE for more details.
"""
from flask import Blueprint, flash, redirect, url_for, request, current_app
from flask.ext.login import (current_user, login_user, login_required,
                             logout_user, confirm_login, login_fresh)

from productporter.utils.helper import render_template, send_reset_token
from productporter.user.forms import (LoginForm, ReauthForm, ForgotPasswordForm,
                                ResetPasswordForm, RegisterForm,
                                ChangeUserProfileForm, ChangeEmailForm,
                                ChangePasswordForm)
from productporter.user.models import User
from productporter.user.weibo import APIClient

user = Blueprint("user", __name__)

@user.route("/<username>")
def profile(username):
    """ user profile """
    user = User.query.filter_by(username=username).first_or_404()
    return render_template("user/profile.jinja.html", user=user)

@user.route("/login", methods=["GET", "POST"])
def login():
    """
    Logs the user in
    """
    form = LoginForm(request.form)
    if form.validate_on_submit():
        user, authenticated = User.authenticate(form.login.data,
                                                form.password.data)
        if user and authenticated:
            login_user(user, remember=form.remember_me.data)
            flash(("Sign in successful"), "success")
            return redirect(request.args.get("next") or
                            url_for("product.posts"))

        flash(("Username or password error"), "danger")
    return render_template("user/login.jinja.html", form=form)

@user.route("/reauth", methods=["GET", "POST"])
@login_required
def reauth():
    """
    Reauthenticates a user
    """

    if not login_fresh():
        form = ReauthForm(request.form)
        if form.validate_on_submit():
            confirm_login()
            flash(("Reauthenticates success"), "success")
            return redirect(request.args.get("next") or
                url_for("user.profile", username=current_user.username))
        return render_template("user/reauth.jinja.html", form=form)
    return redirect(request.args.get("next") or
                    url_for("user.profile", username=current_user.username))

@user.route("/logout")
@login_required
def logout():
    logout_user()
    flash(("Logged out"), "success")
    return redirect(url_for("product.posts"))

@user.route("/register", methods=["GET", "POST"])
def register():
    """
    Register a new user
    """
    form = RegisterForm(request.form)

    if form.validate_on_submit():
        user = form.save()
        login_user(user)

        flash(("Thanks for registering"), "success")
        return redirect(url_for("user.profile", username=current_user.username))
    return render_template("user/register.jinja.html", form=form)

@user.route('/resetpassword', methods=["GET", "POST"])
def forgot_password():
    """
    Sends a reset password token to the user.
    """
    form = ForgotPasswordForm()
    if form.validate_on_submit():
        user = User.query.filter_by(email=form.email.data).first()

        if user:
            token = user.make_reset_token()
            send_reset_token(user, token=token)

            flash(("E-Mail sent! Please check your inbox."), "info")
            return redirect(url_for("user.login"))
        else:
            flash(("E-mail not exist!"), "danger")
    return render_template("user/forgot_password.jinja.html", form=form)

@user.route("/resetpassword/<token>", methods=["GET", "POST"])
def reset_password(token):
    """
    Handles the reset password process.
    """
    form = ResetPasswordForm()
    if form.validate_on_submit():
        user = User.query.filter_by(email=form.email.data).first()
        expired, invalid, data = user.verify_reset_token(form.token.data)

        if invalid:
            flash(("Your password token is invalid."), "danger")
            return redirect(url_for("user.forgot_password"))

        if expired:
            flash(("Your password is expired."), "danger")
            return redirect(url_for("user.forgot_password"))

        if user and data:
            user.password = form.password.data
            user.save()
            flash(("Your password has been updated."), "success")
            return redirect(url_for("user.login"))

    form.token.data = token
    return render_template("user/reset_password.jinja.html", form=form)

@user.route("/collections", methods=['GET'])
def collections():
    """show user collections"""
    return redirect(url_for("product.posts"))

@user.route("/translations", methods=['GET'])
def translations():
    """show user translations"""
    return redirect(url_for("product.posts"))

@user.route("/settings/profile", methods=['GET', 'POST'])
@login_required
def settings():
    """user settings"""
    form = ChangeUserProfileForm(obj=current_user)

    if form.validate_on_submit():
        form.populate_obj(current_user)
        current_user.save()

        flash("Your profile have been updated!", "success")

    return render_template("user/settings_profile.jinja.html", form=form)

@user.route("/settings/email", methods=['GET', 'POST'])
@login_required
def settings_email():
    """setting email"""

    form = ChangeEmailForm(current_user)
    if form.validate_on_submit():
        current_user.email = form.new_email.data
        current_user.save()

        flash("Your email have been updated!", "success")
    return render_template("user/settings_email.jinja.html", form=form)

@user.route("/settings/password", methods=["POST", "GET"])
@login_required
def settings_password():
    form = ChangePasswordForm(current_user)
    if form.validate_on_submit():
        current_user.password = form.new_password.data
        current_user.save()

        flash("Your password have been updated!", "success")
    return render_template("user/settings_password.jinja.html", form=form)

@user.route("/weiboauth", methods=["GET"])
def weibo_auth():
    """ login with weibo """
    key = current_app.config['WEIBO_APP_KEY']
    secret = current_app.config['WEIBO_APP_SECRET']
    callback = url_for('user.weibo_auth_callback', _external=True)
    client = APIClient(app_key=key, app_secret=secret, redirect_uri=callback)
    return redirect(client.get_authorize_url())

@user.route("/weiboauthcb", methods=["GET"])
def weibo_auth_callback():
    """ weibo auth callback"""
    code = request.args.get('code')
    key = current_app.config['WEIBO_APP_KEY']
    secret = current_app.config['WEIBO_APP_SECRET']
    callback = url_for('product.posts', _external=True)
    client = APIClient(app_key=key, app_secret=secret, redirect_uri=callback)
    r = client.request_access_token(code)
    client.set_access_token(r.access_token, r.expires_in)

    # get weibo uid and check if the user is signed up already
    uid = client.account.get_uid.get()
    wbuid = str(uid['uid'])
    user = User.query.filter(User.wbuid==wbuid).first()
    if not user:
        userinfo = client.users.show.get(uid=uid['uid'])
        user = User.from_json(userinfo)
        user.save()

    login_user(user, remember=True)
    flash(("Sign in successful"), "success")
    return redirect(request.args.get("next") or
        url_for("product.posts"))


text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<TITLE>
Uses of Package therapeuticskeleton
</TITLE>

<META NAME="date" CONTENT="2013-05-15">

<LINK REL ="stylesheet" TYPE="text/css" HREF="../stylesheet.css" TITLE="Style">

      Package
      Class
    Use
      Tree
      Deprecated
      Index
      Help

 PREV
 NEXT

  FRAMES
 NO FRAMES

  All Classes

Uses of Package
therapeuticskeleton

Classes in therapeuticskeleton used by therapeuticskeleton

Skeleton

          Skeleton represents a humanoid skeleton in 3d space that is tracked by Microsoft Kinect/Primensense sensor, openNI driver and SimpleOpenNI Java Library.

SkeletonStatistics

      Package
      Class
    Use
      Tree
      Deprecated
      Index
      Help

 PREV
 NEXT

  FRAMES
 NO FRAMES

  All Classes


text:
namespace HiRezApi.Common
{
    internal class Constants
    {
        public const int SESSION_EXPIRATION_TIME_MINUTES = 15;

        public const string SESSION_APPROVED_RET_MSG = "Approved";

        public const string SESSION_EXCEPTION_DEVELOPER_ACCESS_RET_MSG = "Exception while validating developer access.Invalid signature.";

        public const string SESSION_REQUEST_LIMIT_REACHED_RET_MSG = "Daily request limit reached";

        public const string SESSION_INVALID_SESSION_ID_RET_MSG = "Invalid session id.";

        public const string SESSION_TIMESTAMP_INVALID_RET_MSG = "Error while comparing Server and Client timestamp";
    }
}


text:
#pragma once
#include <aws/macie2/Macie2_EXPORTS.h>
#include <aws/core/utils/memory/stl/AWSVector.h>
#include <aws/core/utils/memory/stl/AWSString.h>
#include <utility>

namespace Aws
{
namespace Utils
{
namespace Json
{
  class JsonValue;
  class JsonView;
} // namespace Json
} // namespace Utils
namespace Macie2
{
namespace Model
{

  /**
   *
Specifies the operator to use in a property-based condition that filters the
   * results of a query for findings. For detailed information and examples of each
   * operator, see Fundamentals
   * of filtering findings in the Amazon Macie User Guide.

See
   * Also:
   AWS
   * API Reference

   */
  class AWS_MACIE2_API CriterionAdditionalProperties
  {
  public:
    CriterionAdditionalProperties();
    CriterionAdditionalProperties(Aws::Utils::Json::JsonView jsonValue);
    CriterionAdditionalProperties& operator=(Aws::Utils::Json::JsonView jsonValue);
    Aws::Utils::Json::JsonValue Jsonize() const;

    /**
     *
The value for the property matches (equals) the specified value. If you
     * specify multiple values, Macie uses OR logic to join the values.

     */
    inline const Aws::Vector<Aws::String>& GetEq() const{ return m_eq; }

    /**
     *
The value for the property matches (equals) the specified value. If you
     * specify multiple values, Macie uses OR logic to join the values.

     */
    inline bool EqHasBeenSet() const { return m_eqHasBeenSet; }

    /**
     *
The value for the property matches (equals) the specified value. If you
     * specify multiple values, Macie uses OR logic to join the values.

     */
    inline void SetEq(const Aws::Vector<Aws::String>& value) { m_eqHasBeenSet = true; m_eq = value; }

    /**
     *
The value for the property matches (equals) the specified value. If you
     * specify multiple values, Macie uses OR logic to join the values.

     */
    inline void SetEq(Aws::Vector<Aws::String>&& value) { m_eqHasBeenSet = true; m_eq = std::move(value); }

    /**
     *
The value for the property matches (equals) the specified value. If you
     * specify multiple values, Macie uses OR logic to join the values.

     */
    inline CriterionAdditionalProperties& WithEq(const Aws::Vector<Aws::String>& value) { SetEq(value); return *this;}

    /**
     *
The value for the property matches (equals) the specified value. If you
     * specify multiple values, Macie uses OR logic to join the values.

     */
    inline CriterionAdditionalProperties& WithEq(Aws::Vector<Aws::String>&& value) { SetEq(std::move(value)); return *this;}

    /**
     *
The value for the property matches (equals) the specified value. If you
     * specify multiple values, Macie uses OR logic to join the values.

     */
    inline CriterionAdditionalProperties& AddEq(const Aws::String& value) { m_eqHasBeenSet = true; m_eq.push_back(value); return *this; }

    /**
     *
The value for the property matches (equals) the specified value. If you
     * specify multiple values, Macie uses OR logic to join the values.

     */
    inline CriterionAdditionalProperties& AddEq(Aws::String&& value) { m_eqHasBeenSet = true; m_eq.push_back(std::move(value)); return *this; }

    /**
     *
The value for the property matches (equals) the specified value. If you
     * specify multiple values, Macie uses OR logic to join the values.

     */
    inline CriterionAdditionalProperties& AddEq(const char* value) { m_eqHasBeenSet = true; m_eq.push_back(value); return *this; }

    /**
     *
The value for the property exclusively matches (equals an exact match for)
     * all the specified values. If you specify multiple values, Amazon Macie uses AND
     * logic to join the values.

You can use this operator with the following
     * properties: customDataIdentifiers.detections.arn,
     * customDataIdentifiers.detections.name, resourcesAffected.s3Bucket.tags.key,
     * resourcesAffected.s3Bucket.tags.value, resourcesAffected.s3Object.tags.key,
     * resourcesAffected.s3Object.tags.value, sensitiveData.category, and
     * sensitiveData.detections.type.

     */
    inline const Aws::Vector<Aws::String>& GetEqExactMatch() const{ return m_eqExactMatch; }

    /**
     *
The value for the property exclusively matches (equals an exact match for)
     * all the specified values. If you specify multiple values, Amazon Macie uses AND
     * logic to join the values.

You can use this operator with the following
     * properties: customDataIdentifiers.detections.arn,
     * customDataIdentifiers.detections.name, resourcesAffected.s3Bucket.tags.key,
     * resourcesAffected.s3Bucket.tags.value, resourcesAffected.s3Object.tags.key,
     * resourcesAffected.s3Object.tags.value, sensitiveData.category, and
     * sensitiveData.detections.type.

     */
    inline bool EqExactMatchHasBeenSet() const { return m_eqExactMatchHasBeenSet; }

    /**
     *
The value for the property exclusively matches (equals an exact match for)
     * all the specified values. If you specify multiple values, Amazon Macie uses AND
     * logic to join the values.

You can use this operator with the following
     * properties: customDataIdentifiers.detections.arn,
     * customDataIdentifiers.detections.name, resourcesAffected.s3Bucket.tags.key,
     * resourcesAffected.s3Bucket.tags.value, resourcesAffected.s3Object.tags.key,
     * resourcesAffected.s3Object.tags.value, sensitiveData.category, and
     * sensitiveData.detections.type.

     */
    inline void SetEqExactMatch(const Aws::Vector<Aws::String>& value) { m_eqExactMatchHasBeenSet = true; m_eqExactMatch = value; }

    /**
     *
The value for the property exclusively matches (equals an exact match for)
     * all the specified values. If you specify multiple values, Amazon Macie uses AND
     * logic to join the values.

You can use this operator with the following
     * properties: customDataIdentifiers.detections.arn,
     * customDataIdentifiers.detections.name, resourcesAffected.s3Bucket.tags.key,
     * resourcesAffected.s3Bucket.tags.value, resourcesAffected.s3Object.tags.key,
     * resourcesAffected.s3Object.tags.value, sensitiveData.category, and
     * sensitiveData.detections.type.

     */
    inline void SetEqExactMatch(Aws::Vector<Aws::String>&& value) { m_eqExactMatchHasBeenSet = true; m_eqExactMatch = std::move(value); }

    /**
     *
The value for the property exclusively matches (equals an exact match for)
     * all the specified values. If you specify multiple values, Amazon Macie uses AND
     * logic to join the values.

You can use this operator with the following
     * properties: customDataIdentifiers.detections.arn,
     * customDataIdentifiers.detections.name, resourcesAffected.s3Bucket.tags.key,
     * resourcesAffected.s3Bucket.tags.value, resourcesAffected.s3Object.tags.key,
     * resourcesAffected.s3Object.tags.value, sensitiveData.category, and
     * sensitiveData.detections.type.

     */
    inline CriterionAdditionalProperties& WithEqExactMatch(const Aws::Vector<Aws::String>& value) { SetEqExactMatch(value); return *this;}

    /**
     *
The value for the property exclusively matches (equals an exact match for)
     * all the specified values. If you specify multiple values, Amazon Macie uses AND
     * logic to join the values.

You can use this operator with the following
     * properties: customDataIdentifiers.detections.arn,
     * customDataIdentifiers.detections.name, resourcesAffected.s3Bucket.tags.key,
     * resourcesAffected.s3Bucket.tags.value, resourcesAffected.s3Object.tags.key,
     * resourcesAffected.s3Object.tags.value, sensitiveData.category, and
     * sensitiveData.detections.type.

     */
    inline CriterionAdditionalProperties& WithEqExactMatch(Aws::Vector<Aws::String>&& value) { SetEqExactMatch(std::move(value)); return *this;}

    /**
     *
The value for the property exclusively matches (equals an exact match for)
     * all the specified values. If you specify multiple values, Amazon Macie uses AND
     * logic to join the values.

You can use this operator with the following
     * properties: customDataIdentifiers.detections.arn,
     * customDataIdentifiers.detections.name, resourcesAffected.s3Bucket.tags.key,
     * resourcesAffected.s3Bucket.tags.value, resourcesAffected.s3Object.tags.key,
     * resourcesAffected.s3Object.tags.value, sensitiveData.category, and
     * sensitiveData.detections.type.

     */
    inline CriterionAdditionalProperties& AddEqExactMatch(const Aws::String& value) { m_eqExactMatchHasBeenSet = true; m_eqExactMatch.push_back(value); return *this; }

    /**
     *
The value for the property exclusively matches (equals an exact match for)
     * all the specified values. If you specify multiple values, Amazon Macie uses AND
     * logic to join the values.

You can use this operator with the following
     * properties: customDataIdentifiers.detections.arn,
     * customDataIdentifiers.detections.name, resourcesAffected.s3Bucket.tags.key,
     * resourcesAffected.s3Bucket.tags.value, resourcesAffected.s3Object.tags.key,
     * resourcesAffected.s3Object.tags.value, sensitiveData.category, and
     * sensitiveData.detections.type.

     */
    inline CriterionAdditionalProperties& AddEqExactMatch(Aws::String&& value) { m_eqExactMatchHasBeenSet = true; m_eqExactMatch.push_back(std::move(value)); return *this; }

    /**
     *
The value for the property exclusively matches (equals an exact match for)
     * all the specified values. If you specify multiple values, Amazon Macie uses AND
     * logic to join the values.

You can use this operator with the following
     * properties: customDataIdentifiers.detections.arn,
     * customDataIdentifiers.detections.name, resourcesAffected.s3Bucket.tags.key,
     * resourcesAffected.s3Bucket.tags.value, resourcesAffected.s3Object.tags.key,
     * resourcesAffected.s3Object.tags.value, sensitiveData.category, and
     * sensitiveData.detections.type.

     */
    inline CriterionAdditionalProperties& AddEqExactMatch(const char* value) { m_eqExactMatchHasBeenSet = true; m_eqExactMatch.push_back(value); return *this; }

    /**
     *
The value for the property is greater than the specified value.

     */
    inline long long GetGt() const{ return m_gt; }

    /**
     *
The value for the property is greater than the specified value.

     */
    inline bool GtHasBeenSet() const { return m_gtHasBeenSet; }

    /**
     *
The value for the property is greater than the specified value.

     */
    inline void SetGt(long long value) { m_gtHasBeenSet = true; m_gt = value; }

    /**
     *
The value for the property is greater than the specified value.

     */
    inline CriterionAdditionalProperties& WithGt(long long value) { SetGt(value); return *this;}

    /**
     *
The value for the property is greater than or equal to the specified
     * value.

     */
    inline long long GetGte() const{ return m_gte; }

    /**
     *
The value for the property is greater than or equal to the specified
     * value.

     */
    inline bool GteHasBeenSet() const { return m_gteHasBeenSet; }

    /**
     *
The value for the property is greater than or equal to the specified
     * value.

     */
    inline void SetGte(long long value) { m_gteHasBeenSet = true; m_gte = value; }

    /**
     *
The value for the property is greater than or equal to the specified
     * value.

     */
    inline CriterionAdditionalProperties& WithGte(long long value) { SetGte(value); return *this;}

    /**
     *
The value for the property is less than the specified value.

     */
    inline long long GetLt() const{ return m_lt; }

    /**
     *
The value for the property is less than the specified value.

     */
    inline bool LtHasBeenSet() const { return m_ltHasBeenSet; }

    /**
     *
The value for the property is less than the specified value.

     */
    inline void SetLt(long long value) { m_ltHasBeenSet = true; m_lt = value; }

    /**
     *
The value for the property is less than the specified value.

     */
    inline CriterionAdditionalProperties& WithLt(long long value) { SetLt(value); return *this;}

    /**
     *
The value for the property is less than or equal to the specified value.

     */
    inline long long GetLte() const{ return m_lte; }

    /**
     *
The value for the property is less than or equal to the specified value.

     */
    inline bool LteHasBeenSet() const { return m_lteHasBeenSet; }

    /**
     *
The value for the property is less than or equal to the specified value.

     */
    inline void SetLte(long long value) { m_lteHasBeenSet = true; m_lte = value; }

    /**
     *
The value for the property is less than or equal to the specified value.

     */
    inline CriterionAdditionalProperties& WithLte(long long value) { SetLte(value); return *this;}

    /**
     *
The value for the property doesn't match (doesn't equal) the specified value.
     * If you specify multiple values, Macie uses OR logic to join the values.

     */
    inline const Aws::Vector<Aws::String>& GetNeq() const{ return m_neq; }

    /**
     *
The value for the property doesn't match (doesn't equal) the specified value.
     * If you specify multiple values, Macie uses OR logic to join the values.

     */
    inline bool NeqHasBeenSet() const { return m_neqHasBeenSet; }

    /**
     *
The value for the property doesn't match (doesn't equal) the specified value.
     * If you specify multiple values, Macie uses OR logic to join the values.

     */
    inline void SetNeq(const Aws::Vector<Aws::String>& value) { m_neqHasBeenSet = true; m_neq = value; }

    /**
     *
The value for the property doesn't match (doesn't equal) the specified value.
     * If you specify multiple values, Macie uses OR logic to join the values.

     */
    inline void SetNeq(Aws::Vector<Aws::String>&& value) { m_neqHasBeenSet = true; m_neq = std::move(value); }

    /**
     *
The value for the property doesn't match (doesn't equal) the specified value.
     * If you specify multiple values, Macie uses OR logic to join the values.

     */
    inline CriterionAdditionalProperties& WithNeq(const Aws::Vector<Aws::String>& value) { SetNeq(value); return *this;}

    /**
     *
The value for the property doesn't match (doesn't equal) the specified value.
     * If you specify multiple values, Macie uses OR logic to join the values.

     */
    inline CriterionAdditionalProperties& WithNeq(Aws::Vector<Aws::String>&& value) { SetNeq(std::move(value)); return *this;}

    /**
     *
The value for the property doesn't match (doesn't equal) the specified value.
     * If you specify multiple values, Macie uses OR logic to join the values.

     */
    inline CriterionAdditionalProperties& AddNeq(const Aws::String& value) { m_neqHasBeenSet = true; m_neq.push_back(value); return *this; }

    /**
     *
The value for the property doesn't match (doesn't equal) the specified value.
     * If you specify multiple values, Macie uses OR logic to join the values.

     */
    inline CriterionAdditionalProperties& AddNeq(Aws::String&& value) { m_neqHasBeenSet = true; m_neq.push_back(std::move(value)); return *this; }

    /**
     *
The value for the property doesn't match (doesn't equal) the specified value.
     * If you specify multiple values, Macie uses OR logic to join the values.

     */
    inline CriterionAdditionalProperties& AddNeq(const char* value) { m_neqHasBeenSet = true; m_neq.push_back(value); return *this; }

  private:

    Aws::Vector<Aws::String> m_eq;
    bool m_eqHasBeenSet;

    Aws::Vector<Aws::String> m_eqExactMatch;
    bool m_eqExactMatchHasBeenSet;

    long long m_gt;
    bool m_gtHasBeenSet;

    long long m_gte;
    bool m_gteHasBeenSet;

    long long m_lt;
    bool m_ltHasBeenSet;

    long long m_lte;
    bool m_lteHasBeenSet;

    Aws::Vector<Aws::String> m_neq;
    bool m_neqHasBeenSet;
  };

} // namespace Model
} // namespace Macie2
} // namespace Aws


text:
<?xml version="1.0" encoding="iso-8859-1"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

			<title></title>
			<link rel="stylesheet" href="media/stylesheet.css" />
			<meta http-equiv='Content-Type' content='text/html; charset=iso-8859-1'/>

Root interface Apache_Solr_HttpTransport_Interface

Apache_Solr_HttpTransport_Interface

Root class Apache_Solr_Document

Apache_Solr_Document

Root class Apache_Solr_HttpTransport_Abstract

Apache_Solr_HttpTransport_Abstract (implements Apache_Solr_HttpTransport_Interface)

Apache_Solr_HttpTransport_Curl

Apache_Solr_HttpTransport_CurlNoReuse

Apache_Solr_HttpTransport_FileGetContents

Root class Apache_Solr_HttpTransport_Response

Apache_Solr_HttpTransport_Response

Root class Apache_Solr_Response

Apache_Solr_Response

Root class Apache_Solr_Service

Apache_Solr_Service

Root class Apache_Solr_Service_Balancer

Apache_Solr_Service_Balancer

Root class Exception

Apache_Solr_Exception

Apache_Solr_HttpTransportException

Apache_Solr_InvalidArgumentException

Apache_Solr_NoServiceAvailableException

Apache_Solr_ParserException

		Documentation generated on Wed, 04 May 2011 11:01:08 -0400 by phpDocumentor 1.4.3


text:
<?php

use yii\db\Migration;

/**
 * Handles the addition of column 'enabled' to table `content_type`.
 */
// @codingStandardsIgnoreLine
class m161212_094350_add_column_contenttype_enabled extends Migration
{
    public function up()
    {
        $this->addColumn('content_type', 'enabled', $this->boolean()->notNull()->defaultValue(true));
    }

    public function down()
    {
        $this->dropColumn('content_type', 'enabled');
    }
}


text: alias gn='geeknote'


text:
<?xml version='1.0' encoding='utf-8'?>
<widget id="com.app.lab46" version="0.0.1" xmlns="http://www.w3.org/ns/widgets" xmlns:cdv="http://cordova.apache.org/ns/1.0">
    <preference name="loglevel" value="DEBUG" />
    <allow-intent href="market:*" />
    <name>Lab46</name>
    <description>
        A sample Apache Cordova application that responds to the deviceready event.
    </description>
    <author email="dev@cordova.apache.org" href="http://cordova.io">
        Apache Cordova Team
    </author>
    <content src="index.html" />
    <access origin="*" />
    <allow-intent href="http://*/*" />
    <allow-intent href="https://*/*" />
    <allow-intent href="tel:*" />
    <allow-intent href="sms:*" />
    <allow-intent href="mailto:*" />
    <allow-intent href="geo:*" />
    <feature name="Whitelist">
        <param name="android-package" value="org.apache.cordova.whitelist.WhitelistPlugin" />
        <param name="onload" value="true" />
    </feature>
    <feature name="File">
        <param name="android-package" value="org.apache.cordova.file.FileUtils" />
        <param name="onload" value="true" />
    </feature>
    <feature name="Capture">
        <param name="android-package" value="org.apache.cordova.mediacapture.Capture" />
    </feature>
</widget>


text:
package main

import (
	"io"
	"net"
	"os"
	"sync/atomic"
	"testing"
	"time"

	"github.com/flynn/flynn/discoverd/cache"
	"github.com/flynn/flynn/discoverd/client"
	"github.com/flynn/flynn/discoverd/testutil"
	"github.com/flynn/flynn/pkg/postgres"
	"github.com/flynn/flynn/pkg/testutils/postgres"
	"github.com/flynn/flynn/router/schema"
	"github.com/flynn/flynn/router/types"
	. "github.com/flynn/go-check"
	"github.com/jackc/pgx"
)

func init() {
	listenFunc = net.Listen
}

type discoverdClient interface {
	DiscoverdClient
	AddServiceAndRegister(string, string) (discoverd.Heartbeater, error)
}

// discoverdWrapper wraps a discoverd client to expose Close method that closes
// all heartbeaters
type discoverdWrapper struct {
	discoverdClient
	hbs []io.Closer
}

func (d *discoverdWrapper) AddServiceAndRegister(service, addr string) (discoverd.Heartbeater, error) {
	hb, err := d.discoverdClient.AddServiceAndRegister(service, addr)
	if err != nil {
		return nil, err
	}
	d.hbs = append(d.hbs, hb)
	return hb, nil
}

func (d *discoverdWrapper) Cleanup() {
	for _, hb := range d.hbs {
		hb.Close()
	}
	d.hbs = nil
}

func setup(t testutil.TestingT) (*discoverdWrapper, func()) {
	dc, killDiscoverd := testutil.BootDiscoverd(t, "")
	dw := &discoverdWrapper{discoverdClient: dc}

	return dw, func() {
		killDiscoverd()
	}
}

// Hook gocheck up to the "go test" runner
func Test(t *testing.T) { TestingT(t) }

type S struct {
	discoverd *discoverdWrapper
	cleanup   func()
	pgx       *pgx.ConnPool
}

var _ = Suite(&S{})

const dbname = "routertest"

func (s *S) SetUpSuite(c *C) {
	s.discoverd, s.cleanup = setup(c)

	if err := pgtestutils.SetupPostgres(dbname); err != nil {
		c.Fatal(err)
	}
	pgxConfig := newPgxConnPoolConfig()
	pgxpool, err := pgx.NewConnPool(pgxConfig)
	if err != nil {
		c.Fatal(err)
	}
	db := postgres.New(pgxpool, nil)

	if err = migrateDB(db); err != nil {
		c.Fatal(err)
	}
	db.Close()

	// reconnect with prepared statements
	pgxConfig.AfterConnect = schema.PrepareStatements
	pgxpool, err = pgx.NewConnPool(pgxConfig)
	if err != nil {
		c.Fatal(err)
	}
	db = postgres.New(pgxpool, nil)

	s.pgx = db.ConnPool
	s.pgx.Exec(sqlCreateTruncateTables)
}

func newPgxConnPoolConfig() pgx.ConnPoolConfig {
	return pgx.ConnPoolConfig{
		ConnConfig: pgx.ConnConfig{
			Host:     os.Getenv("PGHOST"),
			Database: dbname,
		},
	}
}

func (s *S) TearDownSuite(c *C) {
	s.cleanup()
}

func (s *S) TearDownTest(c *C) {
	s.discoverd.Cleanup()
	s.pgx.Exec("SELECT truncate_tables()")
}

const waitTimeout = time.Second

func waitForEvent(c *C, w Watcher, event router.EventType, id string) func() *router.Event {
	ch := make(chan *router.Event)
	w.Watch(ch, false)
	return func() *router.Event {
		defer w.Unwatch(ch)
		for {
			timeout := time.After(waitTimeout)
			select {
			case e := <-ch:
				if e.Event == event && (id == "" || e.ID == id) {
					return e
				}
			case <-timeout:
				c.Fatalf("timeout exceeded waiting for %s %s", event, id)
				return nil
			}
		}
	}
}

func discoverdRegisterTCP(c *C, l *TCPListener, addr string) func() {
	return discoverdRegisterTCPService(c, l, "test", addr)
}

func discoverdRegisterTCPService(c *C, l *TCPListener, name, addr string) func() {
	dc := l.discoverd.(discoverdClient)
	sc := l.services[name].sc
	return discoverdRegister(c, dc, sc, name, addr)
}

func discoverdRegisterHTTP(c *C, l *HTTPListener, addr string) func() {
	return discoverdRegisterHTTPService(c, l, "test", addr)
}

func discoverdRegisterHTTPService(c *C, l *HTTPListener, name, addr string) func() {
	dc := l.discoverd.(discoverdClient)
	sc := l.services[name].sc
	return discoverdRegister(c, dc, sc, name, addr)
}

func discoverdSetLeaderHTTP(c *C, l *HTTPListener, name, id string) {
	dc := l.discoverd.(discoverdClient)
	sc := l.services[name].sc
	discoverdSetLeader(c, dc, sc, name, id)
}

func discoverdSetLeaderTCP(c *C, l *TCPListener, name, id string) {
	dc := l.discoverd.(discoverdClient)
	sc := l.services[name].sc
	discoverdSetLeader(c, dc, sc, name, id)
}

func discoverdSetLeader(c *C, dc discoverdClient, sc *cache.ServiceCache, name, id string) {
	done := make(chan struct{})
	go func() {
		events := make(chan *discoverd.Event)
		stream := sc.Watch(events, true)
		defer stream.Close()
		for event := range events {
			if event.Kind == discoverd.EventKindLeader && event.Instance.ID == id {
				close(done)
				return
			}
		}
	}()
	err := dc.Service(name).SetLeader(id)
	c.Assert(err, IsNil)
	select {
	case <-done:
	case <-time.After(10 * time.Second):
		c.Fatal("timed out waiting for discoverd leader change")
	}
}

func discoverdRegister(c *C, dc discoverdClient, sc *cache.ServiceCache, name, addr string) func() {
	done := make(chan struct{})
	go func() {
		events := make(chan *discoverd.Event)
		stream := sc.Watch(events, true)
		defer stream.Close()
		for event := range events {
			if event.Kind == discoverd.EventKindUp && event.Instance.Addr == addr {
				close(done)
				return
			}
		}
	}()
	hb, err := dc.AddServiceAndRegister(name, addr)
	c.Assert(err, IsNil)
	select {
	case <-done:
	case <-time.After(10 * time.Second):
		c.Fatal("timed out waiting for discoverd registration")
	}
	return discoverdUnregisterFunc(c, hb, sc)
}

func discoverdUnregisterFunc(c *C, hb discoverd.Heartbeater, sc *cache.ServiceCache) func() {
	return func() {
		done := make(chan struct{})
		started := make(chan struct{})
		go func() {
			events := make(chan *discoverd.Event)
			stream := sc.Watch(events, false)
			defer stream.Close()
			close(started)
			for event := range events {
				if event.Kind == discoverd.EventKindDown && event.Instance.Addr == hb.Addr() {
					close(done)
					return
				}
			}
		}()
		<-started
		c.Assert(hb.Close(), IsNil)
		select {
		case <-done:
		case <-time.After(10 * time.Second):
			c.Fatal("timed out waiting for discoverd unregister")
		}
	}
}

func addRoute(c *C, l Listener, r *router.Route) *router.Route {
	wait := waitForEvent(c, l, "set", "")
	err := l.AddRoute(r)
	c.Assert(err, IsNil)
	wait()
	return r
}

func addRouteAssertErr(c *C, l Listener, r *router.Route) error {
	err := l.AddRoute(r)
	c.Assert(err, NotNil)
	return err
}

const sqlCreateTruncateTables = `
CREATE OR REPLACE FUNCTION truncate_tables() RETURNS void AS $$
DECLARE
    statements CURSOR FOR
        SELECT tablename FROM pg_tables
        WHERE tablename != 'schema_migrations'
          AND tableowner = session_user
          AND schemaname = 'public';
BEGIN
    FOR stmt IN statements LOOP
        EXECUTE 'TRUNCATE TABLE ' || quote_ident(stmt.tablename) || ' CASCADE;';
    END LOOP;
END;
$$ LANGUAGE plpgsql;
`

func removeRoute(c *C, l Listener, id string) {
	wait := waitForEvent(c, l, "remove", "")
	err := l.RemoveRoute(id)
	c.Assert(err, IsNil)
	wait()
}

func removeRouteAssertErr(c *C, l Listener, id string) error {
	err := l.RemoveRoute(id)
	c.Assert(err, NotNil)
	return err
}

var portAlloc uint32 = 4500

func allocatePort() int {
	return int(atomic.AddUint32(&portAlloc, 1))
}

func allocatePortRange(count int) (int, int) {
	max := int(atomic.AddUint32(&portAlloc, uint32(count)))
	return max - (count - 1), max
}


text:
require "datagrid/utils"
class Datagrid::Filters::BooleanFilter < Datagrid::Filters::BaseFilter

  def format(value)
    Datagrid::Utils.booleanize(value)
  end

end


text:
package au.com.codeka.warworlds.server.monitor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import au.com.codeka.warworlds.server.Session;

/**
 * Abstract base class for monitors. We implement all the methods so individual monitors can just
 * override the ones they're interested in.
 */
public abstract class Monitor {
  /** Called before the request is processed. */
  public void onBeginRequest(Session session, HttpServletRequest request,
      HttpServletResponse response) {
  }

  /** Called after the request was processed. */
  public void onEndRequest(Session session, HttpServletRequest request,
      HttpServletResponse response) {
  }
}


text:
import { toArray } from './asyncIterable';

describe('asyncIterable', () => {
    test('toArray', async () => {
        const r = toArray(emit([1, 2, 3, Promise.resolve(4), 5]));
        await expect(r).resolves.toEqual([1, 2, 3, 4, 5]);
    });
});

async function* emit<T>(values: Iterable<T | Promise<T>>): AsyncIterableIterator<T> {
    for await (const v of values) {
        yield v;
    }
}


text:
button:active, button:focus, .btn, .active { outline:0!important; }

label { display:inline!important; }

input[type=checkbox] { vertical-align: middle!important; display:inline!important;
    margin-top:-0.2em; margin-right:0.2em; border:none!important; outline:none!important; }

select { outline:none!important;}

table.dataframe, table.dataframe * { border-left:0;border-right:0;border-top:0; }

table.dataTable thead th { padding-left:8px; }

li.paginate_button { margin:0 0 -8px -2px!important; padding:0!important; background:transparent!important; }

li.paginate_button a:hover { background-color:#f5f5f5!important; }

li.paginate_button.disabled a:hover { background-color:transparent!important; }

li.paginate_button:hover { border-color:transparent!important; }

.formfield ul, ul#filter, ul#output_columns, ul#anomaly-query { list-style:none!important; margin:0 0 0.5em 0; padding:0; }

.formfield li, ul#filter li, ul#output_columns li, ul#anomaly-query li { list-style:none!important; padding-left:1.4em; text-indent:-1.4em; }

#output_columns, #filter, #anomaly-query { -webkit-column-gap:15px;-moz-column-gap:15px;-ms-column-gap:15px;-o-column-gap:15px;column-gap:15px; }

input[type=radio] { vertical-align: middle!important; margin-top:-0.2em!important;
    margin-right:0.2em!important; border:none!important; outline:none!important; }

#anomaly-logic li { display:inline; }

@media (min-width: 1200px) {
    #filter {
        height:auto;-webkit-column-count:7;-moz-column-count:7;-ms-column-count:7;
        -o-column-count:7;column-count:7;columns:7;
    }
    #output_columns, #anomaly-query {
        height:auto;-webkit-column-count:5;-moz-column-count:5;-ms-column-count:5;
        -o-column-count:5;column-count:5;columns:5;
    }
}

@media (min-width: 768px) and (max-width: 1199px) {
    #filter {
        height:auto;-webkit-column-count:6;-moz-column-count:6;-ms-column-count:6;
        -o-column-count:6;column-count:6;columns:6;
    }
    #output_columns, #anomaly-query {
        height:auto;-webkit-column-count:5;-moz-column-count:5;-ms-column-count:5;
        -o-column-count:5;column-count:5;columns:5;
    }
}

@media (max-width: 767px) {
    #filter {
        height:auto;-webkit-column-count:4;-moz-column-count:4;-ms-column-count:4;
        -o-column-count:4;column-count:4;columns:4;
    }
    #output_columns, #anomaly-query {
        height:auto;-webkit-column-count:3;-moz-column-count:3;-ms-column-count:3;
        -o-column-count:3;column-count:3;columns:3;
    }
}

.alert { width:auto;display:inline-block;margin:0; }


text:
import Vector from './Vector.js';
import Vectors from './Vectors.js';
import Line from './Line.js';
import Polygon from './Polygon.js';
import Polygons from './Polygons.js';

export { Vector, Vectors, Line, Polygon, Polygons };