text:
@interface SettingsViewController ()

@property (nonatomic) NSInteger minBetValue;
@property (nonatomic) NSInteger maxBetValue;

@end

@implementation SettingsViewController

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
	// Do any additional setup after loading the view.
}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    UserDefaultManager *mgr = [UserDefaultManager sharedInstance];
    self.minBetValue = mgr.minBet;
    self.maxBetValue = mgr.maxBet;

    self.minBetSlider.value = self.minBetValue/MIN_SLIDER_MULTIPLIER;
    self.maxBetSlider.value = self.maxBetValue/MAX_SLIDER_MULTIPLIER/self.minBetSlider.value;

    [self updateValueLabels];
}

- (IBAction)closeButtonTapped {
    [self dismissViewControllerAnimated:YES completion:nil];
}

- (IBAction)saveButtonTapped:(id)sender {
    UserDefaultManager *mgr = [UserDefaultManager sharedInstance];
    [mgr setMaxBet:self.maxBetValue];
    [mgr setMinBet:self.minBetValue];
    [self dismissViewControllerAnimated:YES completion:nil];
}

- (IBAction)minSliderValueChanged:(id)sender {
    float newStep = roundf(self.minBetSlider.value);
    self.minBetSlider.value = newStep;

    self.minBetValue = self.minBetSlider.value * MIN_SLIDER_MULTIPLIER;
    self.maxBetValue = self.minBetValue * self.maxBetSlider.value * MAX_SLIDER_MULTIPLIER;
    [self updateValueLabels];
}

- (IBAction)maxSliderValueChanged:(id)sender {
    float newStep = roundf(self.maxBetSlider.value);
    self.maxBetSlider.value = newStep;
    self.maxBetValue = self.minBetValue * self.maxBetSlider.value * MAX_SLIDER_MULTIPLIER;
    [self updateValueLabels];
}

- (void)updateValueLabels {
    self.minBetLabel.text = [NSString stringWithFormat:@"$ %ld", (long)self.minBetValue];
    self.maxBetLabel.text = [NSString stringWithFormat:@"$ %ld", (long)self.maxBetValue];
}

@end


text:
using System.Collections.Generic;
using System.Runtime.InteropServices;
using System.Threading;
using System.Threading.Tasks;
using Xunit;

namespace System.IO.Tests
{
    public class FileStream_WriteAsync : FileSystemTest
    {
        [Fact]
        public void NullBufferThrows()
        {
            using (FileStream fs = new FileStream(GetTestFilePath(), FileMode.Create))
            {
                Assert.Throws<ArgumentNullException>("buffer", () =>
                    FSAssert.CompletesSynchronously(fs.WriteAsync(null, 0, 1)));
            }
        }

        [Fact]
        public void NegativeOffsetThrows()
        {
            using (FileStream fs = new FileStream(GetTestFilePath(), FileMode.Create))
            {
                Assert.Throws<ArgumentOutOfRangeException>("offset", () =>
                    FSAssert.CompletesSynchronously(fs.WriteAsync(new byte[1], -1, 1)));

                // buffer is checked first
                Assert.Throws<ArgumentNullException>("buffer", () =>
                    FSAssert.CompletesSynchronously(fs.WriteAsync(null, -1, 1)));
            }
        }

        [Fact]
        public void NegativeCountThrows()
        {
            using (FileStream fs = new FileStream(GetTestFilePath(), FileMode.Create))
            {
                Assert.Throws<ArgumentOutOfRangeException>("count", () =>
                    FSAssert.CompletesSynchronously(fs.WriteAsync(new byte[1], 0, -1)));

                // offset is checked before count
                Assert.Throws<ArgumentOutOfRangeException>("offset", () =>
                    FSAssert.CompletesSynchronously(fs.WriteAsync(new byte[1], -1, -1)));

                // buffer is checked first
                Assert.Throws<ArgumentNullException>("buffer", () =>
                    FSAssert.CompletesSynchronously(fs.WriteAsync(null, -1, -1)));
            }
        }

        [Fact]
        public void BufferOutOfBoundsThrows()
        {
            using (FileStream fs = new FileStream(GetTestFilePath(), FileMode.Create))
            {
                // offset out of bounds
                Assert.Throws<ArgumentException>(null, () =>
                    FSAssert.CompletesSynchronously(fs.WriteAsync(new byte[1], 1, 1)));

                // offset out of bounds for 0 count WriteAsync
                Assert.Throws<ArgumentException>(null, () =>
                    FSAssert.CompletesSynchronously(fs.WriteAsync(new byte[1], 2, 0)));

                // offset out of bounds even for 0 length buffer
                Assert.Throws<ArgumentException>(null, () =>
                    FSAssert.CompletesSynchronously(fs.WriteAsync(new byte[0], 1, 0)));

                // combination offset and count out of bounds
                Assert.Throws<ArgumentException>(null, () =>
                    FSAssert.CompletesSynchronously(fs.WriteAsync(new byte[2], 1, 2)));

                // edges
                Assert.Throws<ArgumentException>(null, () =>
                    FSAssert.CompletesSynchronously(fs.WriteAsync(new byte[0], int.MaxValue, 0)));
                Assert.Throws<ArgumentException>(null, () =>
                    FSAssert.CompletesSynchronously(fs.WriteAsync(new byte[0], int.MaxValue, int.MaxValue)));
            }
        }

        [Fact]
        public void WriteAsyncDisposedThrows()
        {
            using (FileStream fs = new FileStream(GetTestFilePath(), FileMode.Create))
            {
                fs.Dispose();
                Assert.Throws<ObjectDisposedException>(() =>
                    FSAssert.CompletesSynchronously(fs.WriteAsync(new byte[1], 0, 1)));
                // even for noop WriteAsync
                Assert.Throws<ObjectDisposedException>(() =>
                    FSAssert.CompletesSynchronously(fs.WriteAsync(new byte[1], 0, 0)));

                // out of bounds checking happens first
                Assert.Throws<ArgumentException>(null, () =>
                    FSAssert.CompletesSynchronously(fs.WriteAsync(new byte[2], 1, 2)));

                // count is checked prior
                Assert.Throws<ArgumentOutOfRangeException>("count", () =>
                    FSAssert.CompletesSynchronously(fs.WriteAsync(new byte[1], 0, -1)));

                // offset is checked prior
                Assert.Throws<ArgumentOutOfRangeException>("offset", () =>
                    FSAssert.CompletesSynchronously(fs.WriteAsync(new byte[1], -1, -1)));

                // buffer is checked first
                Assert.Throws<ArgumentNullException>("buffer", () =>
                    FSAssert.CompletesSynchronously(fs.WriteAsync(null, -1, -1)));
            }
        }

        [Fact]
        public void ReadOnlyThrows()
        {
            string fileName = GetTestFilePath();
            using (FileStream fs = new FileStream(fileName, FileMode.Create))
            { }

            using (FileStream fs = new FileStream(fileName, FileMode.Open, FileAccess.Read))
            {
                Assert.Throws<NotSupportedException>(() =>
                    FSAssert.CompletesSynchronously(fs.WriteAsync(new byte[1], 0, 1)));

                fs.Dispose();
                // Disposed checking happens first
                Assert.Throws<ObjectDisposedException>(() =>
                    FSAssert.CompletesSynchronously(fs.WriteAsync(new byte[1], 0, 1)));

                // out of bounds checking happens first
                Assert.Throws<ArgumentException>(null, () =>
                    FSAssert.CompletesSynchronously(fs.WriteAsync(new byte[2], 1, 2)));

                // count is checked prior
                Assert.Throws<ArgumentOutOfRangeException>("count", () =>
                    FSAssert.CompletesSynchronously(fs.WriteAsync(new byte[1], 0, -1)));

                // offset is checked prior
                Assert.Throws<ArgumentOutOfRangeException>("offset", () =>
                    FSAssert.CompletesSynchronously(fs.WriteAsync(new byte[1], -1, -1)));

                // buffer is checked first
                Assert.Throws<ArgumentNullException>("buffer", () =>
                    FSAssert.CompletesSynchronously(fs.WriteAsync(null, -1, -1)));
            }
        }

        [Fact]
        public void CancelledTokenFastPath()
        {
            CancellationTokenSource cts = new CancellationTokenSource();
            cts.Cancel();
            CancellationToken cancelledToken = cts.Token;

            string fileName = GetTestFilePath();
            using (FileStream fs = new FileStream(fileName, FileMode.Create))
            {
                FSAssert.IsCancelled(fs.WriteAsync(new byte[1], 0, 1, cancelledToken), cancelledToken);
            }

            using (FileStream fs = new FileStream(fileName, FileMode.Open, FileAccess.Read))
            {
                // before read only check
                FSAssert.IsCancelled(fs.WriteAsync(new byte[1], 0, 1, cancelledToken), cancelledToken);

                fs.Dispose();
                // before disposed check
                FSAssert.IsCancelled(fs.WriteAsync(new byte[1], 0, 1, cancelledToken), cancelledToken);

                // out of bounds checking happens first
                Assert.Throws<ArgumentException>(null, () =>
                    FSAssert.CompletesSynchronously(fs.WriteAsync(new byte[2], 1, 2, cancelledToken)));

                // count is checked prior
                Assert.Throws<ArgumentOutOfRangeException>("count", () =>
                    FSAssert.CompletesSynchronously(fs.WriteAsync(new byte[1], 0, -1, cancelledToken)));

                // offset is checked prior
                Assert.Throws<ArgumentOutOfRangeException>("offset", () =>
                    FSAssert.CompletesSynchronously(fs.WriteAsync(new byte[1], -1, -1, cancelledToken)));

                // buffer is checked first
                Assert.Throws<ArgumentNullException>("buffer", () =>
                    FSAssert.CompletesSynchronously(fs.WriteAsync(null, -1, -1, cancelledToken)));
            }
        }

        [Fact]
        public async Task NoopWriteAsyncsSucceed()
        {
            using (FileStream fs = new FileStream(GetTestFilePath(), FileMode.Create))
            {
                // note that these do not succeed synchronously even though they do nothing.

                await fs.WriteAsync(new byte[0], 0, 0);
                await fs.WriteAsync(new byte[1], 0, 0);
                // even though offset is out of bounds of buffer, this is still allowed
                // for the last element
                await fs.WriteAsync(new byte[1], 1, 0);
                await fs.WriteAsync(new byte[2], 1, 0);
                Assert.Equal(0, fs.Length);
                Assert.Equal(0, fs.Position);
            }
        }

        [Fact]
        public void WriteAsyncBufferedCompletesSynchronously()
        {
            using (FileStream fs = new FileStream(
                GetTestFilePath(), FileMode.Create, FileAccess.ReadWrite, FileShare.ReadWrite | FileShare.Delete,
                TestBuffer.Length * 2, useAsync: true))
            {
                FSAssert.CompletesSynchronously(fs.WriteAsync(new byte[TestBuffer.Length], 0, TestBuffer.Length));
            }
        }

        [Fact]
        public async Task SimpleWriteAsync()
        {
            using (FileStream fs = new FileStream(GetTestFilePath(), FileMode.Create))
            {
                await fs.WriteAsync(TestBuffer, 0, TestBuffer.Length);
                Assert.Equal(TestBuffer.Length, fs.Length);
                Assert.Equal(TestBuffer.Length, fs.Position);

                fs.Position = 0;
                byte[] buffer = new byte[TestBuffer.Length];
                Assert.Equal(TestBuffer.Length, await fs.ReadAsync(buffer, 0, buffer.Length));
                Assert.Equal(TestBuffer, buffer);
            }
        }

        [Fact]
        public async Task WriteAsyncCancelledFile()
        {
            const int writeSize = 1024 * 1024;
            using (FileStream fs = new FileStream(GetTestFilePath(), FileMode.Create))
            {
                byte[] buffer = new byte[writeSize];
                CancellationTokenSource cts = new CancellationTokenSource();
                Task writeTask = fs.WriteAsync(buffer, 0, buffer.Length, cts.Token);
                cts.Cancel();
                try
                {
                    await writeTask;
                }
                catch (OperationCanceledException oce)
                {
                    // Ideally we'd be doing an Assert.Throws<OperationCanceledException>
                    // but since cancellation is a race condition we accept either outcome
                    Assert.Equal(cts.Token, oce.CancellationToken);
                }
            }
        }

        [Fact]
        public async void WriteAsyncInternalBufferOverflow()
        {
            using (FileStream fs = new FileStream(GetTestFilePath(), FileMode.Create, FileAccess.Write, FileShare.None, 3, useAsync: true))
            {
                // Fill buffer; should trigger flush of full buffer, no additional I/O
                await fs.WriteAsync(TestBuffer, 0, 3);
                Assert.True(fs.Length == 3);

                // Add to next buffer
                await fs.WriteAsync(TestBuffer, 0, 1);
                Assert.True(fs.Length == 4);

                // Complete that buffer; should trigger flush of full buffer, no additional I/O
                await fs.WriteAsync(TestBuffer, 0, 2);
                Assert.True(fs.Length == 6);

                // Add to next buffer
                await fs.WriteAsync(TestBuffer, 0, 2);
                Assert.True(fs.Length == 8);

                // Overflow buffer with amount that could fit in a buffer; should trigger a flush, with additional I/O
                await fs.WriteAsync(TestBuffer, 0, 2);
                Assert.True(fs.Length == 10);

                // Overflow buffer with amount that couldn't fit in a buffer; shouldn't be anything to flush, just an additional I/O
                await fs.WriteAsync(TestBuffer, 0, 4);
                Assert.True(fs.Length == 14);
            }
        }

        public static IEnumerable<object[]> MemberData_FileStreamAsyncWriting()
        {
            foreach (bool useAsync in new[] { true, false })
            {
                if (useAsync && !RuntimeInformation.IsOSPlatform(OSPlatform.Windows))
                {
                    // We don't have a special async I/O implementation in FileStream on Unix.
                    continue;
                }

                foreach (bool preSize in new[] { true, false })
                {
                    foreach (bool cancelable in new[] { true, false })
                    {
                        yield return new object[] { useAsync, preSize, false, cancelable, 0x1000, 0x100, 100 };
                        yield return new object[] { useAsync, preSize, false, cancelable, 0x1, 0x1, 1000 };
                        yield return new object[] { useAsync, preSize, true, cancelable, 0x2, 0x100, 100 };
                        yield return new object[] { useAsync, preSize, false, cancelable, 0x4000, 0x10, 100 };
                        yield return new object[] { useAsync, preSize, true, cancelable, 0x1000, 99999, 10 };
                    }
                }
            }
        }

        [Fact]
        public Task ManyConcurrentWriteAsyncs()
        {
            // For inner loop, just test one case
            return ManyConcurrentWriteAsyncs(
                useAsync: RuntimeInformation.IsOSPlatform(OSPlatform.Windows),
                presize: false,
                exposeHandle: false,
                cancelable: true,
                bufferSize: 4096,
                writeSize: 1024,
                numWrites: 10);
        }

        [Theory]
        [MemberData(nameof(MemberData_FileStreamAsyncWriting))]
        [OuterLoop] // many combinations: we test just one in inner loop and the rest outer
        public async Task ManyConcurrentWriteAsyncs(
            bool useAsync, bool presize, bool exposeHandle, bool cancelable, int bufferSize, int writeSize, int numWrites)
        {
            long totalLength = writeSize * numWrites;
            var expectedData = new byte[totalLength];
            new Random(42).NextBytes(expectedData);
            CancellationToken cancellationToken = cancelable ? new CancellationTokenSource().Token : CancellationToken.None;

            string path = GetTestFilePath();
            using (FileStream fs = new FileStream(path, FileMode.Create, FileAccess.ReadWrite, FileShare.None, bufferSize, useAsync))
            {
                if (presize)
                {
                    fs.SetLength(totalLength);
                }
                if (exposeHandle)
                {
                    var ignored = fs.SafeFileHandle;
                }

                Task[] writes = new Task[numWrites];
                for (int i = 0; i < numWrites; i++)
                {
                    writes[i] = fs.WriteAsync(expectedData, i * writeSize, writeSize, cancellationToken);
                    Assert.Null(writes[i].Exception);
                    if (useAsync)
                    {
                        Assert.Equal((i + 1) * writeSize, fs.Position);
                    }
                }

                await Task.WhenAll(writes);
            }

            byte[] actualData = File.ReadAllBytes(path);
            Assert.Equal(expectedData.Length, actualData.Length);
            Assert.Equal<byte>(expectedData, actualData);
        }

        [Fact]
        public Task CopyToAsyncBetweenFileStreams()
        {
            // For inner loop, just test one case
            return CopyToAsyncBetweenFileStreams(
                useAsync: RuntimeInformation.IsOSPlatform(OSPlatform.Windows),
                preSize: false,
                exposeHandle: false,
                cancelable: true,
                bufferSize: 4096,
                writeSize: 1024,
                numWrites: 10);
        }

        [Fact]
        public void CopyToAsync_InvalidArgs_Throws()
        {
            using (FileStream fs = new FileStream(GetTestFilePath(), FileMode.Create))
            {
                Assert.Throws<ArgumentNullException>("destination", () => { fs.CopyToAsync(null); });
                Assert.Throws<ArgumentOutOfRangeException>("bufferSize", () => { fs.CopyToAsync(new MemoryStream(), 0); });
                Assert.Throws<NotSupportedException>(() => { fs.CopyToAsync(new MemoryStream(new byte[1], writable: false)); });
                fs.Dispose();
                Assert.Throws<ObjectDisposedException>(() => { fs.CopyToAsync(new MemoryStream()); });
            }
            using (FileStream fs = new FileStream(GetTestFilePath(), FileMode.Create, FileAccess.Write))
            {
                Assert.Throws<NotSupportedException>(() => { fs.CopyToAsync(new MemoryStream()); });
            }
        }

        [Theory]
        [MemberData(nameof(MemberData_FileStreamAsyncWriting))]
        [OuterLoop] // many combinations: we test just one in inner loop and the rest outer
        public async Task CopyToAsyncBetweenFileStreams(
            bool useAsync, bool preSize, bool exposeHandle, bool cancelable, int bufferSize, int writeSize, int numWrites)
        {
            long totalLength = writeSize * numWrites;
            var expectedData = new byte[totalLength];
            new Random(42).NextBytes(expectedData);

            string srcPath = GetTestFilePath();
            File.WriteAllBytes(srcPath, expectedData);

            string dstPath = GetTestFilePath();
            using (FileStream src = new FileStream(srcPath, FileMode.Open, FileAccess.Read, FileShare.None, bufferSize, useAsync))
            using (FileStream dst = new FileStream(dstPath, FileMode.Create, FileAccess.Write, FileShare.None, bufferSize, useAsync))
            {
                await src.CopyToAsync(dst, writeSize, cancelable ? new CancellationTokenSource().Token : CancellationToken.None);
            }

            byte[] actualData = File.ReadAllBytes(dstPath);
            Assert.Equal(expectedData.Length, actualData.Length);
            Assert.Equal<byte>(expectedData, actualData);
        }

        [Theory]
        [InlineData(true)]
        [InlineData(false)]
        public async Task BufferCorrectlyMaintainedWhenReadAndWrite(bool useAsync)
        {
            string path = GetTestFilePath();
            File.WriteAllBytes(path, TestBuffer);

            using (FileStream fs = new FileStream(path, FileMode.Open, FileAccess.ReadWrite, FileShare.None, 2, useAsync))
            {
                Assert.Equal(TestBuffer[0], await ReadByteAsync(fs));
                Assert.Equal(TestBuffer[1], await ReadByteAsync(fs));
                Assert.Equal(TestBuffer[2], await ReadByteAsync(fs));
                await fs.WriteAsync(TestBuffer, 0, TestBuffer.Length);

                fs.Position = 0;
                Assert.Equal(TestBuffer[0], await ReadByteAsync(fs));
                Assert.Equal(TestBuffer[1], await ReadByteAsync(fs));
                Assert.Equal(TestBuffer[2], await ReadByteAsync(fs));
                for (int i = 0; i < TestBuffer.Length; i++)
                {
                    Assert.Equal(TestBuffer[i], await ReadByteAsync(fs));
                }
            }
        }

        private static async Task<byte> ReadByteAsync(FileStream fs)
        {
            byte[] oneByte = new byte[1];
            Assert.Equal(1, await fs.ReadAsync(oneByte, 0, 1));
            return oneByte[0];
        }

        [Fact, OuterLoop]
        public async Task WriteAsyncMiniStress()
        {
            TimeSpan testRunTime = TimeSpan.FromSeconds(10);
            const int MaximumWriteSize = 16 * 1024;
            const int NormalWriteSize = 4 * 1024;

            Random rand = new Random();
            DateTime testStartTime = DateTime.UtcNow;

            // Generate data to write (NOTE: Randomizing this is important as some file systems may optimize writing 0s)
            byte[] dataToWrite = new byte[MaximumWriteSize];
            rand.NextBytes(dataToWrite);

            string writeFileName = GetTestFilePath();
            do
            {
                // Create a new token that expires between 100-1000ms
                CancellationTokenSource tokenSource = new CancellationTokenSource();
                tokenSource.CancelAfter(rand.Next(100, 1000));

                using (var stream = new FileStream(writeFileName, FileMode.Create, FileAccess.Write))
                {
                    do
                    {
                        try
                        {
                            // 20%: random write size
                            int bytesToWrite = (rand.NextDouble() < 0.2 ? rand.Next(16, MaximumWriteSize) : NormalWriteSize);

                            if (rand.NextDouble() < 0.1)
                            {
                                // 10%: Sync write
                                stream.Write(dataToWrite, 0, bytesToWrite);
                            }
                            else
                            {
                                // 90%: Async write
                                await stream.WriteAsync(dataToWrite, 0, bytesToWrite, tokenSource.Token);
                            }
                        }
                        catch (TaskCanceledException)
                        {
                            Assert.True(tokenSource.Token.IsCancellationRequested, "Received cancellation exception before token expired");
                        }
                    } while (!tokenSource.Token.IsCancellationRequested);
                }
            } while (DateTime.UtcNow - testStartTime <= testRunTime);
        }
    }
}

redpajama_set_name: RedPajamaGithub


text:
package org.apache.usergrid.persistence.query.ir;

/**
 * Node where the results need intersected.  Used instead of a SliceNode when one of the children is an operation other
 * than slices.  I.E OR, NOT etc
 *
 * @author tnine
 */
public class AndNode extends BooleanNode {

    /**
     * @param left
     * @param right
     */
    public AndNode( QueryNode left, QueryNode right ) {
        super( left, right );
    }

    /* (non-Javadoc)
     * @see org.apache.usergrid.persistence.query.ir.QueryNode#visit(org.apache.usergrid.persistence.query.ir.NodeVisitor)
     */
    @Override
    public void visit( NodeVisitor visitor ) throws Exception {
        visitor.visit( this );
    }
}


text:
import {assertHttpsUrl, parseQueryString, parseUrl, removeFragment, getOrigin}
    from '../../src/url';

describe('url', () => {

  const currentPort = location.port;

  function compareParse(url, result) {
    // Using JSON string comparison because Chai's deeply equal
    // errors are impossible to debug.
    const parsed = JSON.stringify(parseUrl(url));
    const expected = JSON.stringify(result);
    expect(parsed).to.equal(expected);
  }

  it('should parse correctly', () => {
    compareParse('https://foo.com/abc?123#foo', {
      href: 'https://foo.com/abc?123#foo',
      protocol: 'https:',
      host: 'foo.com',
      hostname: 'foo.com',
      port: '',
      pathname: '/abc',
      search: '?123',
      hash: '#foo',
      origin: 'https://foo.com'
    });
  });
  it('should handle ports', () => {
    compareParse('https://foo.com:123/abc?123#foo', {
      href: 'https://foo.com:123/abc?123#foo',
      protocol: 'https:',
      host: 'foo.com:123',
      hostname: 'foo.com',
      port: '123',
      pathname: '/abc',
      search: '?123',
      hash: '#foo',
      origin: 'https://foo.com:123'
    });
  });
  it('should support http', () => {
    compareParse('http://foo.com:123/abc?123#foo', {
      href: 'http://foo.com:123/abc?123#foo',
      protocol: 'http:',
      host: 'foo.com:123',
      hostname: 'foo.com',
      port: '123',
      pathname: '/abc',
      search: '?123',
      hash: '#foo',
      origin: 'http://foo.com:123'
    });
  });
  it('should resolve relative urls', () => {
    compareParse('./abc?123#foo', {
      href: 'http://localhost:' + currentPort + '/abc?123#foo',
      protocol: 'http:',
      host: 'localhost:' + currentPort,
      hostname: 'localhost',
      port: currentPort,
      pathname: '/abc',
      search: '?123',
      hash: '#foo',
      origin: 'http://localhost:' + currentPort
    });
  });
  it('should resolve path relative urls', () => {
    compareParse('/abc?123#foo', {
      href: 'http://localhost:' + currentPort + '/abc?123#foo',
      protocol: 'http:',
      host: 'localhost:' + currentPort,
      hostname: 'localhost',
      port: currentPort,
      pathname: '/abc',
      search: '?123',
      hash: '#foo',
      origin: 'http://localhost:' + currentPort
    });
  });
  it('should handle URLs with just the domain', () => {
    compareParse('http://foo.com:123', {
      href: 'http://foo.com:123/',
      protocol: 'http:',
      host: 'foo.com:123',
      hostname: 'foo.com',
      port: '123',
      pathname: '/',
      search: '',
      hash: '',
      origin: 'http://foo.com:123'
    });
  });

});

describe('parseQueryString', () => {
  it('should return empty params when query string is empty or null', () => {
    expect(parseQueryString(null)).to.deep.equal({});
    expect(parseQueryString('')).to.deep.equal({});
  });
  it('should parse single key-value', () => {
    expect(parseQueryString('a=1')).to.deep.equal({
      'a': '1'
    });
  });
  it('should parse two key-values', () => {
    expect(parseQueryString('a=1&b=2')).to.deep.equal({
      'a': '1',
      'b': '2'
    });
  });
  it('should ignore leading ?', () => {
    expect(parseQueryString('?a=1&b=2')).to.deep.equal({
      'a': '1',
      'b': '2'
    });
  });
  it('should ignore leading #', () => {
    expect(parseQueryString('#a=1&b=2')).to.deep.equal({
      'a': '1',
      'b': '2'
    });
  });
  it('should parse empty value', () => {
    expect(parseQueryString('a=&b=2')).to.deep.equal({
      'a': '',
      'b': '2'
    });
    expect(parseQueryString('a&b=2')).to.deep.equal({
      'a': '',
      'b': '2'
    });
  });
  it('should decode names and values', () => {
    expect(parseQueryString('a%26=1%26&b=2')).to.deep.equal({
      'a&': '1&',
      'b': '2'
    });
  });
  it('should return last dupe', () => {
    expect(parseQueryString('a=1&b=2&a=3')).to.deep.equal({
      'a': '3',
      'b': '2'
    });
  });
});

describe('assertHttpsUrl', () => {
  const referenceElement = document.createElement('div');
  it('should allow https', () => {
    assertHttpsUrl('https://twitter.com', referenceElement);
  });
  it('should allow protocol relative', () => {
    assertHttpsUrl('//twitter.com', referenceElement);
  });
  it('should allow localhost with http', () => {
    assertHttpsUrl('http://localhost:8000/sfasd', referenceElement);
  });
  it('should allow localhost with http suffix', () => {
    assertHttpsUrl('http://iframe.localhost:8000/sfasd', referenceElement);
  });

  it('should fail on http', () => {
    expect(() => {
      assertHttpsUrl('http://twitter.com', referenceElement);
    }).to.throw(/source must start with/);
  });
  it('should fail on http with localhost in the name', () => {
    expect(() => {
      assertHttpsUrl('http://foolocalhost', referenceElement);
    }).to.throw(/source must start with/);
  });
});

describe('removeFragment', () => {
  it('should remove fragment', () => {
    expect(removeFragment('https://twitter.com/path#abc')).to.equal(
        'https://twitter.com/path');
  });
  it('should remove empty fragment', () => {
    expect(removeFragment('https://twitter.com/path#')).to.equal(
        'https://twitter.com/path');
  });
  it('should ignore when no fragment', () => {
    expect(removeFragment('https://twitter.com/path')).to.equal(
        'https://twitter.com/path');
  });
});

describe('getOrigin', () => {
  it('should parse https://twitter.com/path#abc', () => {
    expect(getOrigin(parseUrl('https://twitter.com/path#abc')))
        .to.equal('https://twitter.com');
    expect(parseUrl('https://twitter.com/path#abc').origin)
        .to.equal('https://twitter.com');
  });

  it('should parse data:12345', () => {
    expect(getOrigin(parseUrl('data:12345')))
        .to.equal('data:12345');
    expect(parseUrl('data:12345').origin)
        .to.equal('data:12345');
  });
});


text:
import type {AnyNativeEvent} from '../events/PluginModuleType';
import type {Container, SuspenseInstance} from '../client/ReactDOMHostConfig';
import type {DOMEventName} from '../events/DOMEventNames';
import type {EventSystemFlags} from './EventSystemFlags';
import type {FiberRoot} from 'react-reconciler/src/ReactInternalTypes';
import type {EventPriority} from 'react-reconciler/src/ReactEventPriorities';

import {enableCapturePhaseSelectiveHydrationWithoutDiscreteEventReplay} from 'shared/ReactFeatureFlags';
import {
  unstable_scheduleCallback as scheduleCallback,
  unstable_NormalPriority as NormalPriority,
} from 'scheduler';
import {
  getNearestMountedFiber,
  getContainerFromFiber,
  getSuspenseInstanceFromFiber,
} from 'react-reconciler/src/ReactFiberTreeReflection';
import {
  findInstanceBlockingEvent,
  return_targetInst,
} from './ReactDOMEventListener';
import {setReplayingEvent, resetReplayingEvent} from './CurrentReplayingEvent';
import {dispatchEventForPluginEventSystem} from './DOMPluginEventSystem';
import {
  getInstanceFromNode,
  getClosestInstanceFromNode,
} from '../client/ReactDOMComponentTree';
import {HostRoot, SuspenseComponent} from 'react-reconciler/src/ReactWorkTags';
import {isHigherEventPriority} from 'react-reconciler/src/ReactEventPriorities';
import {isRootDehydrated} from 'react-reconciler/src/ReactFiberShellHydration';

let _attemptSynchronousHydration: (fiber: Object) => void;

export function setAttemptSynchronousHydration(fn: (fiber: Object) => void) {
  _attemptSynchronousHydration = fn;
}

export function attemptSynchronousHydration(fiber: Object) {
  _attemptSynchronousHydration(fiber);
}

let attemptDiscreteHydration: (fiber: Object) => void;

export function setAttemptDiscreteHydration(fn: (fiber: Object) => void) {
  attemptDiscreteHydration = fn;
}

let attemptContinuousHydration: (fiber: Object) => void;

export function setAttemptContinuousHydration(fn: (fiber: Object) => void) {
  attemptContinuousHydration = fn;
}

let attemptHydrationAtCurrentPriority: (fiber: Object) => void;

export function setAttemptHydrationAtCurrentPriority(
  fn: (fiber: Object) => void,
) {
  attemptHydrationAtCurrentPriority = fn;
}

let getCurrentUpdatePriority: () => EventPriority;

export function setGetCurrentUpdatePriority(fn: () => EventPriority) {
  getCurrentUpdatePriority = fn;
}

let attemptHydrationAtPriority: <T>(priority: EventPriority, fn: () => T) => T;

export function setAttemptHydrationAtPriority(
  fn: <T>(priority: EventPriority, fn: () => T) => T,
) {
  attemptHydrationAtPriority = fn;
}

// TODO: Upgrade this definition once we're on a newer version of Flow that
// has this definition built-in.
type PointerEvent = Event & {
  pointerId: number,
  relatedTarget: EventTarget | null,
  ...
};

type QueuedReplayableEvent = {
  blockedOn: null | Container | SuspenseInstance,
  domEventName: DOMEventName,
  eventSystemFlags: EventSystemFlags,
  nativeEvent: AnyNativeEvent,
  targetContainers: Array<EventTarget>,
};

let hasScheduledReplayAttempt = false;

// The queue of discrete events to be replayed.
const queuedDiscreteEvents: Array<QueuedReplayableEvent> = [];

// Indicates if any continuous event targets are non-null for early bailout.
const hasAnyQueuedContinuousEvents: boolean = false;
// The last of each continuous event type. We only need to replay the last one
// if the last target was dehydrated.
let queuedFocus: null | QueuedReplayableEvent = null;
let queuedDrag: null | QueuedReplayableEvent = null;
let queuedMouse: null | QueuedReplayableEvent = null;
// For pointer events there can be one latest event per pointerId.
const queuedPointers: Map<number, QueuedReplayableEvent> = new Map();
const queuedPointerCaptures: Map<number, QueuedReplayableEvent> = new Map();
// We could consider replaying selectionchange and touchmoves too.

type QueuedHydrationTarget = {
  blockedOn: null | Container | SuspenseInstance,
  target: Node,
  priority: EventPriority,
};
const queuedExplicitHydrationTargets: Array<QueuedHydrationTarget> = [];

export function hasQueuedDiscreteEvents(): boolean {
  return queuedDiscreteEvents.length > 0;
}

export function hasQueuedContinuousEvents(): boolean {
  return hasAnyQueuedContinuousEvents;
}

const discreteReplayableEvents: Array<DOMEventName> = [
  'mousedown',
  'mouseup',
  'touchcancel',
  'touchend',
  'touchstart',
  'auxclick',
  'dblclick',
  'pointercancel',
  'pointerdown',
  'pointerup',
  'dragend',
  'dragstart',
  'drop',
  'compositionend',
  'compositionstart',
  'keydown',
  'keypress',
  'keyup',
  'input',
  'textInput', // Intentionally camelCase
  'copy',
  'cut',
  'paste',
  'click',
  'change',
  'contextmenu',
  'reset',
  'submit',
];

export function isDiscreteEventThatRequiresHydration(
  eventType: DOMEventName,
): boolean {
  return discreteReplayableEvents.indexOf(eventType) > -1;
}

function createQueuedReplayableEvent(
  blockedOn: null | Container | SuspenseInstance,
  domEventName: DOMEventName,
  eventSystemFlags: EventSystemFlags,
  targetContainer: EventTarget,
  nativeEvent: AnyNativeEvent,
): QueuedReplayableEvent {
  return {
    blockedOn,
    domEventName,
    eventSystemFlags,
    nativeEvent,
    targetContainers: [targetContainer],
  };
}

export function queueDiscreteEvent(
  blockedOn: null | Container | SuspenseInstance,
  domEventName: DOMEventName,
  eventSystemFlags: EventSystemFlags,
  targetContainer: EventTarget,
  nativeEvent: AnyNativeEvent,
): void {
  if (enableCapturePhaseSelectiveHydrationWithoutDiscreteEventReplay) {
    return;
  }
  const queuedEvent = createQueuedReplayableEvent(
    blockedOn,
    domEventName,
    eventSystemFlags,
    targetContainer,
    nativeEvent,
  );
  queuedDiscreteEvents.push(queuedEvent);
  if (queuedDiscreteEvents.length === 1) {
    // If this was the first discrete event, we might be able to
    // synchronously unblock it so that preventDefault still works.
    while (queuedEvent.blockedOn !== null) {
      const fiber = getInstanceFromNode(queuedEvent.blockedOn);
      if (fiber === null) {
        break;
      }
      attemptSynchronousHydration(fiber);
      if (queuedEvent.blockedOn === null) {
        // We got unblocked by hydration. Let's try again.
        replayUnblockedEvents();
        // If we're reblocked, on an inner boundary, we might need
        // to attempt hydrating that one.
        continue;
      } else {
        // We're still blocked from hydration, we have to give up
        // and replay later.
        break;
      }
    }
  }
}

// Resets the replaying for this type of continuous event to no event.
export function clearIfContinuousEvent(
  domEventName: DOMEventName,
  nativeEvent: AnyNativeEvent,
): void {
  switch (domEventName) {
    case 'focusin':
    case 'focusout':
      queuedFocus = null;
      break;
    case 'dragenter':
    case 'dragleave':
      queuedDrag = null;
      break;
    case 'mouseover':
    case 'mouseout':
      queuedMouse = null;
      break;
    case 'pointerover':
    case 'pointerout': {
      const pointerId = ((nativeEvent: any): PointerEvent).pointerId;
      queuedPointers.delete(pointerId);
      break;
    }
    case 'gotpointercapture':
    case 'lostpointercapture': {
      const pointerId = ((nativeEvent: any): PointerEvent).pointerId;
      queuedPointerCaptures.delete(pointerId);
      break;
    }
  }
}

function accumulateOrCreateContinuousQueuedReplayableEvent(
  existingQueuedEvent: null | QueuedReplayableEvent,
  blockedOn: null | Container | SuspenseInstance,
  domEventName: DOMEventName,
  eventSystemFlags: EventSystemFlags,
  targetContainer: EventTarget,
  nativeEvent: AnyNativeEvent,
): QueuedReplayableEvent {
  if (
    existingQueuedEvent === null ||
    existingQueuedEvent.nativeEvent !== nativeEvent
  ) {
    const queuedEvent = createQueuedReplayableEvent(
      blockedOn,
      domEventName,
      eventSystemFlags,
      targetContainer,
      nativeEvent,
    );
    if (blockedOn !== null) {
      const fiber = getInstanceFromNode(blockedOn);
      if (fiber !== null) {
        // Attempt to increase the priority of this target.
        attemptContinuousHydration(fiber);
      }
    }
    return queuedEvent;
  }
  // If we have already queued this exact event, then it's because
  // the different event systems have different DOM event listeners.
  // We can accumulate the flags, and the targetContainers, and
  // store a single event to be replayed.
  existingQueuedEvent.eventSystemFlags |= eventSystemFlags;
  const targetContainers = existingQueuedEvent.targetContainers;
  if (
    targetContainer !== null &&
    targetContainers.indexOf(targetContainer) === -1
  ) {
    targetContainers.push(targetContainer);
  }
  return existingQueuedEvent;
}

export function queueIfContinuousEvent(
  blockedOn: null | Container | SuspenseInstance,
  domEventName: DOMEventName,
  eventSystemFlags: EventSystemFlags,
  targetContainer: EventTarget,
  nativeEvent: AnyNativeEvent,
): boolean {
  // These set relatedTarget to null because the replayed event will be treated as if we
  // moved from outside the window (no target) onto the target once it hydrates.
  // Instead of mutating we could clone the event.
  switch (domEventName) {
    case 'focusin': {
      const focusEvent = ((nativeEvent: any): FocusEvent);
      queuedFocus = accumulateOrCreateContinuousQueuedReplayableEvent(
        queuedFocus,
        blockedOn,
        domEventName,
        eventSystemFlags,
        targetContainer,
        focusEvent,
      );
      return true;
    }
    case 'dragenter': {
      const dragEvent = ((nativeEvent: any): DragEvent);
      queuedDrag = accumulateOrCreateContinuousQueuedReplayableEvent(
        queuedDrag,
        blockedOn,
        domEventName,
        eventSystemFlags,
        targetContainer,
        dragEvent,
      );
      return true;
    }
    case 'mouseover': {
      const mouseEvent = ((nativeEvent: any): MouseEvent);
      queuedMouse = accumulateOrCreateContinuousQueuedReplayableEvent(
        queuedMouse,
        blockedOn,
        domEventName,
        eventSystemFlags,
        targetContainer,
        mouseEvent,
      );
      return true;
    }
    case 'pointerover': {
      const pointerEvent = ((nativeEvent: any): PointerEvent);
      const pointerId = pointerEvent.pointerId;
      queuedPointers.set(
        pointerId,
        accumulateOrCreateContinuousQueuedReplayableEvent(
          queuedPointers.get(pointerId) || null,
          blockedOn,
          domEventName,
          eventSystemFlags,
          targetContainer,
          pointerEvent,
        ),
      );
      return true;
    }
    case 'gotpointercapture': {
      const pointerEvent = ((nativeEvent: any): PointerEvent);
      const pointerId = pointerEvent.pointerId;
      queuedPointerCaptures.set(
        pointerId,
        accumulateOrCreateContinuousQueuedReplayableEvent(
          queuedPointerCaptures.get(pointerId) || null,
          blockedOn,
          domEventName,
          eventSystemFlags,
          targetContainer,
          pointerEvent,
        ),
      );
      return true;
    }
  }
  return false;
}

// Check if this target is unblocked. Returns true if it's unblocked.
function attemptExplicitHydrationTarget(
  queuedTarget: QueuedHydrationTarget,
): void {
  // TODO: This function shares a lot of logic with findInstanceBlockingEvent.
  // Try to unify them. It's a bit tricky since it would require two return
  // values.
  const targetInst = getClosestInstanceFromNode(queuedTarget.target);
  if (targetInst !== null) {
    const nearestMounted = getNearestMountedFiber(targetInst);
    if (nearestMounted !== null) {
      const tag = nearestMounted.tag;
      if (tag === SuspenseComponent) {
        const instance = getSuspenseInstanceFromFiber(nearestMounted);
        if (instance !== null) {
          // We're blocked on hydrating this boundary.
          // Increase its priority.
          queuedTarget.blockedOn = instance;
          attemptHydrationAtPriority(queuedTarget.priority, () => {
            attemptHydrationAtCurrentPriority(nearestMounted);
          });

          return;
        }
      } else if (tag === HostRoot) {
        const root: FiberRoot = nearestMounted.stateNode;
        if (isRootDehydrated(root)) {
          queuedTarget.blockedOn = getContainerFromFiber(nearestMounted);
          // We don't currently have a way to increase the priority of
          // a root other than sync.
          return;
        }
      }
    }
  }
  queuedTarget.blockedOn = null;
}

export function queueExplicitHydrationTarget(target: Node): void {
  // TODO: This will read the priority if it's dispatched by the React
  // event system but not native events. Should read window.event.type, like
  // we do for updates (getCurrentEventPriority).
  const updatePriority = getCurrentUpdatePriority();
  const queuedTarget: QueuedHydrationTarget = {
    blockedOn: null,
    target: target,
    priority: updatePriority,
  };
  let i = 0;
  for (; i < queuedExplicitHydrationTargets.length; i++) {
    // Stop once we hit the first target with lower priority than
    if (
      !isHigherEventPriority(
        updatePriority,
        queuedExplicitHydrationTargets[i].priority,
      )
    ) {
      break;
    }
  }
  queuedExplicitHydrationTargets.splice(i, 0, queuedTarget);
  if (i === 0) {
    attemptExplicitHydrationTarget(queuedTarget);
  }
}

function attemptReplayContinuousQueuedEvent(
  queuedEvent: QueuedReplayableEvent,
): boolean {
  if (queuedEvent.blockedOn !== null) {
    return false;
  }
  const targetContainers = queuedEvent.targetContainers;
  while (targetContainers.length > 0) {
    const targetContainer = targetContainers[0];
    const nextBlockedOn = findInstanceBlockingEvent(
      queuedEvent.domEventName,
      queuedEvent.eventSystemFlags,
      targetContainer,
      queuedEvent.nativeEvent,
    );
    if (nextBlockedOn === null) {
      if (enableCapturePhaseSelectiveHydrationWithoutDiscreteEventReplay) {
        const nativeEvent = queuedEvent.nativeEvent;
        const nativeEventClone = new nativeEvent.constructor(
          nativeEvent.type,
          (nativeEvent: any),
        );
        setReplayingEvent(nativeEventClone);
        nativeEvent.target.dispatchEvent(nativeEventClone);
        resetReplayingEvent();
      } else {
        setReplayingEvent(queuedEvent.nativeEvent);
        dispatchEventForPluginEventSystem(
          queuedEvent.domEventName,
          queuedEvent.eventSystemFlags,
          queuedEvent.nativeEvent,
          return_targetInst,
          targetContainer,
        );
        resetReplayingEvent();
      }
    } else {
      // We're still blocked. Try again later.
      const fiber = getInstanceFromNode(nextBlockedOn);
      if (fiber !== null) {
        attemptContinuousHydration(fiber);
      }
      queuedEvent.blockedOn = nextBlockedOn;
      return false;
    }
    // This target container was successfully dispatched. Try the next.
    targetContainers.shift();
  }
  return true;
}

function attemptReplayContinuousQueuedEventInMap(
  queuedEvent: QueuedReplayableEvent,
  key: number,
  map: Map<number, QueuedReplayableEvent>,
): void {
  if (attemptReplayContinuousQueuedEvent(queuedEvent)) {
    map.delete(key);
  }
}

function replayUnblockedEvents() {
  hasScheduledReplayAttempt = false;
  if (!enableCapturePhaseSelectiveHydrationWithoutDiscreteEventReplay) {
    // First replay discrete events.
    while (queuedDiscreteEvents.length > 0) {
      const nextDiscreteEvent = queuedDiscreteEvents[0];
      if (nextDiscreteEvent.blockedOn !== null) {
        // We're still blocked.
        // Increase the priority of this boundary to unblock
        // the next discrete event.
        const fiber = getInstanceFromNode(nextDiscreteEvent.blockedOn);
        if (fiber !== null) {
          attemptDiscreteHydration(fiber);
        }
        break;
      }
      const targetContainers = nextDiscreteEvent.targetContainers;
      while (targetContainers.length > 0) {
        const targetContainer = targetContainers[0];
        const nextBlockedOn = findInstanceBlockingEvent(
          nextDiscreteEvent.domEventName,
          nextDiscreteEvent.eventSystemFlags,
          targetContainer,
          nextDiscreteEvent.nativeEvent,
        );
        if (nextBlockedOn === null) {
          // This whole function is in !enableCapturePhaseSelectiveHydrationWithoutDiscreteEventReplay,
          // so we don't need the new replay behavior code branch.
          setReplayingEvent(nextDiscreteEvent.nativeEvent);
          dispatchEventForPluginEventSystem(
            nextDiscreteEvent.domEventName,
            nextDiscreteEvent.eventSystemFlags,
            nextDiscreteEvent.nativeEvent,
            return_targetInst,
            targetContainer,
          );
          resetReplayingEvent();
        } else {
          // We're still blocked. Try again later.
          nextDiscreteEvent.blockedOn = nextBlockedOn;
          break;
        }
        // This target container was successfully dispatched. Try the next.
        targetContainers.shift();
      }
      if (nextDiscreteEvent.blockedOn === null) {
        // We've successfully replayed the first event. Let's try the next one.
        queuedDiscreteEvents.shift();
      }
    }
  }
  // Next replay any continuous events.
  if (queuedFocus !== null && attemptReplayContinuousQueuedEvent(queuedFocus)) {
    queuedFocus = null;
  }
  if (queuedDrag !== null && attemptReplayContinuousQueuedEvent(queuedDrag)) {
    queuedDrag = null;
  }
  if (queuedMouse !== null && attemptReplayContinuousQueuedEvent(queuedMouse)) {
    queuedMouse = null;
  }
  queuedPointers.forEach(attemptReplayContinuousQueuedEventInMap);
  queuedPointerCaptures.forEach(attemptReplayContinuousQueuedEventInMap);
}

function scheduleCallbackIfUnblocked(
  queuedEvent: QueuedReplayableEvent,
  unblocked: Container | SuspenseInstance,
) {
  if (queuedEvent.blockedOn === unblocked) {
    queuedEvent.blockedOn = null;
    if (!hasScheduledReplayAttempt) {
      hasScheduledReplayAttempt = true;
      // Schedule a callback to attempt replaying as many events as are
      // now unblocked. This first might not actually be unblocked yet.
      // We could check it early to avoid scheduling an unnecessary callback.
      scheduleCallback(NormalPriority, replayUnblockedEvents);
    }
  }
}

export function retryIfBlockedOn(
  unblocked: Container | SuspenseInstance,
): void {
  // Mark anything that was blocked on this as no longer blocked
  // and eligible for a replay.
  if (queuedDiscreteEvents.length > 0) {
    scheduleCallbackIfUnblocked(queuedDiscreteEvents[0], unblocked);
    // This is a exponential search for each boundary that commits. I think it's
    // worth it because we expect very few discrete events to queue up and once
    // we are actually fully unblocked it will be fast to replay them.
    for (let i = 1; i < queuedDiscreteEvents.length; i++) {
      const queuedEvent = queuedDiscreteEvents[i];
      if (queuedEvent.blockedOn === unblocked) {
        queuedEvent.blockedOn = null;
      }
    }
  }

  if (queuedFocus !== null) {
    scheduleCallbackIfUnblocked(queuedFocus, unblocked);
  }
  if (queuedDrag !== null) {
    scheduleCallbackIfUnblocked(queuedDrag, unblocked);
  }
  if (queuedMouse !== null) {
    scheduleCallbackIfUnblocked(queuedMouse, unblocked);
  }
  const unblock = queuedEvent =>
    scheduleCallbackIfUnblocked(queuedEvent, unblocked);
  queuedPointers.forEach(unblock);
  queuedPointerCaptures.forEach(unblock);

  for (let i = 0; i < queuedExplicitHydrationTargets.length; i++) {
    const queuedTarget = queuedExplicitHydrationTargets[i];
    if (queuedTarget.blockedOn === unblocked) {
      queuedTarget.blockedOn = null;
    }
  }

  while (queuedExplicitHydrationTargets.length > 0) {
    const nextExplicitTarget = queuedExplicitHydrationTargets[0];
    if (nextExplicitTarget.blockedOn !== null) {
      // We're still blocked.
      break;
    } else {
      attemptExplicitHydrationTarget(nextExplicitTarget);
      if (nextExplicitTarget.blockedOn === null) {
        // We're unblocked.
        queuedExplicitHydrationTargets.shift();
      }
    }
  }
}


text:
from django.contrib import admin
from models import Lobbyist, LobbyistCorporation, LobbyistsChange
from django.contrib.contenttypes import generic
from links.models import Link

class LinksInline(generic.GenericTabularInline):
    model = Link
    ct_fk_field = 'object_pk'
    extra = 1

class LobbyistAdmin(admin.ModelAdmin):
    fields = ('person', 'description', 'image_url', 'large_image_url',)
    readonly_fields = ('person',)
    inlines = (LinksInline,)

class LobbyistCorporationAdmin(admin.ModelAdmin):
    fields = ('name', 'description',)
    readonly_fields = ('name',)
    inlines = (LinksInline,)

class LobbyistsChangeAdmin(admin.ModelAdmin):
    list_display = ('date', 'type', 'content_type', 'object_id', 'content_object')

admin.site.register(Lobbyist, LobbyistAdmin)
admin.site.register(LobbyistCorporation, LobbyistCorporationAdmin)
admin.site.register(LobbyistsChange, LobbyistsChangeAdmin)


text:
namespace System.Data.Entity.Hooks.Fluent
{
    /// <summary>
    /// Setup for a hook, that should be called for entity of specified type.
    /// </summary>
    /// <typeparam name="T"></typeparam>
    public interface ITypedHookSetup<out T> : IInvokeSetup<T> where T : class
    {
        /// <summary>
        /// Spicifies the setup for a hook, that should be called when entity satisfies specified condition.
        /// </summary>
        /// <param name="predicate">The predicate.</param>
        /// <returns>
        /// The setup for a hook.
        /// </returns>
        IConditionalSetup<T> When(Predicate<T> predicate);
    }
}


text:
using System.IO;

namespace Umbraco.Core.Media.TypeDetector
{
    public class JPEGDetector : RasterizedTypeDetector
    {
        public static bool IsOfType(Stream fileStream)
        {
            var header = GetFileHeader(fileStream);

            return header[0] == 0xff && header[1] == 0xD8;
        }
    }
}


text:
package exercise.task2_kingsGambit.entities;

public enum State {
    DEFEND;
}


text:
import * as React from 'react';

export const CodeIcon = () => {
  return (

  );
}


text:
class CoinBehavior extends Sup.Behavior {
  private player:Sup.Actor;
  private catched:boolean;
  public slack:boolean;

  awake() {
    this.player = Sup.getActor("Player");
    this.actor.arcadeBody2D.setEnabled(false);
    this.catched = false;
  }

  catchIt() {
    // The coin is catched
    this.catched = true;

    // The coin is masked
    if (this.actor.spriteRenderer.getOpacity() != 0) {
      this.actor.spriteRenderer.setOpacity(0);
    }

    // The message is printed
    this.actor.textRenderer.setText(messagesManager.getMessage(this.actor.getName()));

    // The score is added
    scoreManager.addScore(this.slack);
  }

  update() {
    if (!this.catched) {
      if(Sup.ArcadePhysics2D.intersects(this.actor.arcadeBody2D, this.player.arcadeBody2D)) {
        this.catchIt();
      }
    }
  }
}
Sup.registerBehavior(CoinBehavior);


text:
package org.mule.transport.siebel.config;

import org.mule.config.spring.handlers.AbstractMuleNamespaceHandler;
import org.mule.config.spring.parsers.generic.MuleOrphanDefinitionParser;
import org.mule.config.spring.parsers.specific.MessageProcessorDefinitionParser;
import org.mule.endpoint.URIBuilder;
import org.mule.transport.siebel.SiebelConnector;
import org.mule.transport.siebel.SiebelPollingConnector;
import org.mule.transport.siebel.transformers.EncodedStringToSiebelPropertySet;
import org.mule.transport.siebel.transformers.SiebelPropertySetToEncodedString;
import org.mule.transport.siebel.transformers.SiebelPropertySetToXmlString;
import org.mule.transport.siebel.transformers.SiebelPropertySetToXmlStringRemote;
import org.mule.transport.siebel.transformers.XmlStringToSiebelPropertySet;
import org.mule.transport.siebel.transformers.XmlStringToSiebelPropertySetRemote;

/**
 * Registers a Bean Definition Parser for handling <siebel:connector> and <siebel:polling-connector> elements
 * and supporting endpoint elements.
 */
public class SiebelNamespaceHandler extends AbstractMuleNamespaceHandler
{
    public void init()
    {
        registerStandardTransportEndpoints(SiebelConnector.SIEBEL, URIBuilder.PATH_ATTRIBUTES);

        registerConnectorDefinitionParser(SiebelPollingConnector.class);
        registerConnectorDefinitionParser(SiebelConnector.class);
        registerBeanDefinitionParser("polling-connector", new MuleOrphanDefinitionParser(SiebelPollingConnector.class, true));
        registerBeanDefinitionParser("xml-string-to-propset-transformer", new MessageProcessorDefinitionParser(XmlStringToSiebelPropertySet.class));
        registerBeanDefinitionParser("xml-string-to-propset-remote-transformer", new MessageProcessorDefinitionParser(XmlStringToSiebelPropertySetRemote.class));
        registerBeanDefinitionParser("encoded-string-to-propset-transformer", new MessageProcessorDefinitionParser(EncodedStringToSiebelPropertySet.class));
        registerBeanDefinitionParser("propset-to-xml-string-transformer", new MessageProcessorDefinitionParser(SiebelPropertySetToXmlString.class));
        registerBeanDefinitionParser("propset-to-xml-string-remote-transformer", new MessageProcessorDefinitionParser(SiebelPropertySetToXmlStringRemote.class));
        registerBeanDefinitionParser("propset-to-encoded-string-transformer", new MessageProcessorDefinitionParser(SiebelPropertySetToEncodedString.class));

    }
}


text:
export default interface OrderState {
  last_order_confirmation: any,
  session_order_hashes: string[]
}


text:
.class public Lcom/android/gallery3d/common/BlobCache$LookupRequest;
.super Ljava/lang/Object;
.source "BlobCache.java"

# annotations
.annotation system Ldalvik/annotation/EnclosingClass;
    value = Lcom/android/gallery3d/common/BlobCache;
.end annotation

.annotation system Ldalvik/annotation/InnerClass;
    accessFlags = 0x9
    name = "LookupRequest"
.end annotation

# instance fields
.field public buffer:[B

.field public key:J

.field public length:I

# direct methods
.method public constructor <init>()V
    .locals 0

    .prologue
    .line 412
    invoke-direct {p0}, Ljava/lang/Object;-><init>()V

    return-void
.end method


text:
using System.ComponentModel;
using System.Windows.Forms.Design;

namespace BB.Common.WinForms
{
    /// <summary>
    /// The designer for the <see cref="ScrollBarEx"/> control.
    /// </summary>
    public class ScrollBarControlDesigner : ControlDesigner
    {
        /// <summary>
        /// Gets the <see cref="SelectionRules"/> for the control.
        /// </summary>
        public override SelectionRules SelectionRules
        {
            get
            {
                // gets the property descriptor for the property "Orientation"
                PropertyDescriptor propDescriptor =
                   TypeDescriptor.GetProperties(this.Component)["Orientation"];

                // if not null - we can read the current orientation of the scroll bar
                if (propDescriptor != null)
                {
                    // get the current orientation
                    ScrollBarOrientation orientation =
                       (ScrollBarOrientation)propDescriptor.GetValue(this.Component);

                    // if vertical orientation
                    if (orientation == ScrollBarOrientation.Vertical)
                    {
                        return SelectionRules.Visible
                           | SelectionRules.Moveable
                           | SelectionRules.BottomSizeable
                           | SelectionRules.TopSizeable;
                    }

                    return SelectionRules.Visible | SelectionRules.Moveable
                       | SelectionRules.LeftSizeable | SelectionRules.RightSizeable;
                }

                return base.SelectionRules;
            }
        }

        /// <summary>
        /// Prefilters the properties so that unnecessary properties are hidden
        /// in the property browser of Visual Studio.
        /// </summary>
        /// <param name="properties">The property dictionary.</param>
        protected override void PreFilterProperties(
           System.Collections.IDictionary properties)
        {
            properties.Remove("Text");
            properties.Remove("BackgroundImage");
            properties.Remove("ForeColor");
            properties.Remove("ImeMode");
            properties.Remove("Padding");
            properties.Remove("BackgroundImageLayout");
            properties.Remove("BackColor");
            properties.Remove("Font");
            properties.Remove("RightToLeft");

            base.PreFilterProperties(properties);
        }
    }
}