text:
import io
import tempfile
import unittest

import numpy

from gensound.sound import *
from gensound.sound import _repeat_array

class SoundUtilsTest(unittest.TestCase):
    def test_repeat_array_single_channel(self):
        array = numpy.array([[1, 2, 3]]).T
        repeated = [1, 2, 3] * 3

        self.assertEqual(tuple(_repeat_array(array, 6).flatten()),
                         tuple(repeated[:6]))

        self.assertEqual(tuple(_repeat_array(array, 8).flatten()),
                         tuple(repeated[:8]))

        self.assertEqual(tuple(_repeat_array(array, 2).flatten()),
                         tuple(repeated[:2]))

    def test_repeat_array_two_channel(self):
        array = numpy.array([[1, 2, 3], [4, 5, 6]]).T
        repeated = numpy.array([[1, 2, 3] * 3, [4, 5, 6] * 3]).T

        six = _repeat_array(array, 6)
        self.assertEqual(six.shape, (6, 2))
        self.assertEqual(six.tolist(), repeated[:6].tolist())

        eight = _repeat_array(array, 8)
        self.assertEqual(eight.shape, (8, 2))
        self.assertEqual(eight.tolist(), repeated[:8].tolist())

        two = _repeat_array(array, 2)
        self.assertEqual(two.shape, (2, 2))
        self.assertEqual(two.tolist(), repeated[:2].tolist())

    def test_repeat_array_invalid_input(self):
        array = numpy.array([[1, 2, 3]])
        null = numpy.array([[]])
        lessdimen = numpy.array([1, 2, 3])
        overdimen = numpy.array([[[1, 2]], [[3, 4]]])

        with self.assertRaises(ValueError) as cm:
            _repeat_array(array, 0)

        self.assertEqual(str(cm.exception),
                         'want_length must be greater than 0 but got 0')

        with self.assertRaises(ValueError) as cm:
            _repeat_array(array, -1)

        self.assertEqual(str(cm.exception),
                         'want_length must be greater than 0 but got -1')

        with self.assertRaises(ValueError) as cm:
            _repeat_array(null, 1)

        self.assertEqual(str(cm.exception),
                         'sound should have least one element')

        with self.assertRaises(ValueError) as cm:
            _repeat_array(lessdimen, 1)

        self.assertEqual(str(cm.exception), 'sound should two dimensions')

        with self.assertRaises(ValueError) as cm:
            _repeat_array(overdimen, 1)

        self.assertEqual(str(cm.exception), 'sound should two dimensions')

    def test_overlay(self):
        a = Sound.from_array([0.0, 0.1], 2)
        b = Sound.from_array([0.2, 0.3], 2)
        c = Sound.from_array([0.4, 0.5], 2)

        self.assertEqual(overlay(a, b, c).samplerate, 2)
        self.assertEqual(overlay(a, b, c).duration, 1)

        self.assertEqual(overlay(a, b, c),
                         Sound.from_array([0.6, 0.9], 2))

        self.assertEqual(overlay(overlay(a, b), c),
                         Sound.from_array([0.6, 0.9], 2))

        self.assertEqual(overlay(a, overlay(b, c)),
                         Sound.from_array([0.6, 0.9], 2))

        self.assertEqual(overlay(overlay(a, c), b),
                         Sound.from_array([0.6, 0.9], 2))

    def test_overlay_different_duration(self):
        a = Sound.from_array([0.0, 0.1], 2)
        b = Sound.from_array([0.2, 0.3], 2)
        c = Sound.from_array([0.4, 0.5, 0.6, 0.7], 2)

        self.assertEqual(overlay(a, b, c).samplerate, 2)
        self.assertEqual(overlay(a, b, c).duration, 2)

        self.assertEqual(overlay(a, b, c),
                         Sound.from_array([0.6, 0.9, 0.6, 0.7], 2))

    def test_overlay_different_samplerate(self):
        a = Sound.from_array([0.0, 0.1], 2)
        b = Sound.from_array([0.2, 0.3], 2)
        c = Sound.from_array([0.4, 0.5], 3)

        with self.assertRaises(DifferentSamplerateError) as cm:
            overlay(a, b, c)

        self.assertEqual(cm.exception.frequency, (2, 2, 3))

    def test_overlay_different_channels(self):
        a = Sound.from_sinwave(220)
        b = Sound.from_sinwave(440)
        c = Sound.from_sinwave(880).as_stereo()

        with self.assertRaises(DifferentChannelsError) as cm:
            overlay(a, b, c)

        self.assertEqual(cm.exception.channels, (1, 1, 2))

    def test_concat(self):
        a = Sound.from_array([0.0, 0.1], 2)
        b = Sound.from_array([0.2, 0.3], 2)
        c = Sound.from_array([0.4, 0.5], 2)

        self.assertEqual(concat(a, b, c).samplerate, 2)
        self.assertEqual(concat(a, b, c).duration, 3)

        self.assertEqual(concat(a, b, c),
                         Sound.from_array([0.0, 0.1, 0.2, 0.3, 0.4, 0.5], 2))

        self.assertEqual(concat(concat(a, b), c),
                         Sound.from_array([0.0, 0.1, 0.2, 0.3, 0.4, 0.5], 2))

        self.assertEqual(concat(a, concat(b, c)),
                         Sound.from_array([0.0, 0.1, 0.2, 0.3, 0.4, 0.5], 2))

        self.assertEqual(concat(c, b, a),
                         Sound.from_array([0.4, 0.5, 0.2, 0.3, 0.0, 0.1], 2))

    def test_concat_different_duration(self):
        a = Sound.from_array([0.0, 0.1], 2)
        b = Sound.from_array([0.2, 0.3], 2)
        c = Sound.from_array([0.4, 0.5, 0.6, 0.7], 2)

        self.assertEqual(concat(a, b, c).samplerate, 2)
        self.assertEqual(concat(a, b, c).duration, 4)

        self.assertEqual(concat(a, b, c), Sound.from_array([
            0.0, 0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7
        ], 2))

    def test_concat_different_samplerate(self):
        a = Sound.from_array([0.0, 0.1], 2)
        b = Sound.from_array([0.2, 0.3], 2)
        c = Sound.from_array([0.4, 0.5], 3)

        with self.assertRaises(DifferentSamplerateError) as cm:
            concat(a, b, c)

        self.assertEqual(cm.exception.frequency, (2, 2, 3))

    def test_concat_different_channels(self):
        a = Sound.from_sinwave(220)
        b = Sound.from_sinwave(440)
        c = Sound.from_sinwave(880).as_stereo()

        with self.assertRaises(DifferentChannelsError) as cm:
            concat(a, b, c)

        self.assertEqual(cm.exception.channels, (1, 1, 2))

    def test_merge_channels(self):
        a = Sound.from_array([0.0, 0.1], 2)
        b = Sound.from_array([0.2, 0.3], 2)
        c = Sound.from_array([0.4, 0.5], 2)
        abc = Sound.from_array([[0.0, 0.2, 0.4], [0.1, 0.3, 0.5]], 2)

        self.assertEqual(merge_channels(a, b, c), abc)

        c_stereo = merge_channels(Sound.from_array([0.3, 0.6], 2),
                                  Sound.from_array([0.5, 0.4], 2))
        self.assertEqual(merge_channels(a, b, c_stereo), abc)

class SoundTest(unittest.TestCase):
    def test_constructor(self):
        sound = Sound(numpy.array([-1.0, 0.5, 1.0]), 1)

        self.assertEqual(sound.samplerate, 1)
        self.assertEqual(sound.duration, 3)
        self.assertEqual(tuple(sound.data), (-1.0, 0.5, 1.0))

    def test_constructor_clip(self):
        sound = Sound(numpy.array([-1.1, -1.0, 1.0, 1.1]), 2)

        self.assertEqual(sound.samplerate, 2)
        self.assertEqual(sound.duration, 2)
        self.assertEqual(tuple(sound.data), (-1.0, -1.0, 1.0, 1.0))

    def test_constructor_invalid(self):
        with self.assertRaises(InvalidSamplerateError) as cm:
            Sound(numpy.array([0]), 0)

        self.assertEqual(cm.exception.frequency, 0)

        with self.assertRaises(InvalidSamplerateError) as cm:
            Sound(numpy.array([0]), -1)

        self.assertEqual(cm.exception.frequency, -1)

        with self.assertRaises(InvalidDurationError) as cm:
            Sound(numpy.array([]), 1)

        self.assertEqual(cm.exception.duration, 0)

        with self.assertRaises(ValueError) as cm:
            Sound(numpy.array([[[1], [2]], [[3], [4]]]), 1)

        self.assertEqual(str(cm.exception),
                         'data dimensions must be 1 or 2 but got 3')

    def test_equals(self):
        a = Sound.from_array([0.1, 0.2, 0.3], 1)
        b = Sound.from_array([0.4, 0.5, 0.6], 1)

        self.assertEqual(a, a)
        self.assertEqual(b, b)
        self.assertNotEqual(a, b)
        self.assertNotEqual(a, None)
        self.assertNotEqual(a, 1)
        self.assertNotEqual(a, 'a')

    def test_from_array(self):
        self.assertEqual(Sound(numpy.array([-0.5, 0.5]), 44100),
                         Sound.from_array([-0.5, 0.5], 44100))

        self.assertEqual(Sound(numpy.array([0.1, -0.1]), 100),
                         Sound.from_array([0.1, -0.1], 100))

    def test_from_array_invalid(self):
        with self.assertRaises(InvalidDurationError) as cm:
            Sound.from_array([], 44100)

        self.assertEqual(cm.exception.duration, 0)

        with self.assertRaises(InvalidSamplerateError) as cm:
            Sound.from_array([0], 0)

        self.assertEqual(cm.exception.frequency, 0)

    def test_from_sinwave_with_smooth_end(self):
        sound = Sound.from_sinwave(440,
                                   duration=1,
                                   volume=0.5,
                                   samplerate=44100,
                                   smooth_end=True)

        self.assertEqual(sound.samplerate, 44100)
        self.assertAlmostEqual(sound.duration, 1, places=1)
        self.assertAlmostEqual(sound.volume, 0.5, places=4)

        sound = Sound.from_sinwave(880,
                                   duration=2,
                                   volume=0.8,
                                   samplerate=88200,
                                   smooth_end=True)

        self.assertEqual(sound.samplerate, 88200)
        self.assertAlmostEqual(sound.duration, 2, places=1)
        self.assertAlmostEqual(sound.volume, 0.8, places=4)

    def test_from_sinwave_without_smooth_end(self):
        sound = Sound.from_sinwave(440,
                                   duration=1,
                                   volume=0.5,
                                   samplerate=44100,
                                   smooth_end=False)

        self.assertEqual(sound.samplerate, 44100)
        self.assertEqual(sound.duration, 1.0)
        self.assertAlmostEqual(sound.volume, 0.5, places=4)

        sound = Sound.from_sinwave(880,
                                   duration=2,
                                   volume=0.8,
                                   samplerate=88200,
                                   smooth_end=False)

        self.assertEqual(sound.samplerate, 88200)
        self.assertEqual(sound.duration, 2.0)
        self.assertAlmostEqual(sound.volume, 0.8, places=4)

    def test_from_sinwave_invalid(self):
        with self.assertRaises(InvalidFrequencyError) as cm:
            Sound.from_sinwave(0)

        self.assertEqual(cm.exception.frequency, 0)

        with self.assertRaises(InvalidDurationError) as cm:
            Sound.from_sinwave(440, duration=0)

        self.assertEqual(cm.exception.duration, 0)

        with self.assertRaises(InvalidVolumeError) as cm:
            Sound.from_sinwave(440, volume=-0.1)

        self.assertEqual(cm.exception.volume, -0.1)

        with self.assertRaises(InvalidVolumeError) as cm:
            Sound.from_sinwave(440, volume=1.1)

        self.assertEqual(cm.exception.volume, 1.1)

        with self.assertRaises(InvalidSamplerateError) as cm:
            Sound.from_sinwave(440, samplerate=0)

        self.assertEqual(cm.exception.frequency, 0)

    def test_from_sawtoothwave(self):
        sound = Sound.from_sawtoothwave(440,
                                        duration=1,
                                        volume=0.5,
                                        samplerate=44100)

        self.assertEqual(sound.samplerate, 44100)
        self.assertEqual(sound.duration, 1.0)
        self.assertTrue((-0.5 <= sound.data).all())
        self.assertTrue((sound.data <= 0.5).all())
        self.assertEqual(sound.volume, 0.5)

        sound = Sound.from_sawtoothwave(880,
                                        duration=2,
                                        volume=0.8,
                                        samplerate=88200)

        self.assertEqual(sound.samplerate, 88200)
        self.assertTrue(sound.duration, 2.0)
        self.assertTrue((-0.8 <= sound.data).all())
        self.assertTrue((sound.data <= 0.8).all())
        self.assertTrue(sound.volume, 0.8)

        sound = Sound.from_sawtoothwave(1, duration=2, samplerate=3)
        self.assertTrue(numpy.allclose(sound.data[:, 0],
                                       (-1.0, 0.0, 1.0, -1.0, 0.0, 1.0)))

    def test_from_sawtoothwave_invalid(self):
        with self.assertRaises(InvalidFrequencyError) as cm:
            Sound.from_sawtoothwave(0)

        self.assertEqual(cm.exception.frequency, 0)

        with self.assertRaises(InvalidDurationError) as cm:
            Sound.from_sawtoothwave(440, duration=0)

        self.assertEqual(cm.exception.duration, 0)

        with self.assertRaises(InvalidVolumeError) as cm:
            Sound.from_sawtoothwave(440, volume=-0.1)

        self.assertEqual(cm.exception.volume, -0.1)

        with self.assertRaises(InvalidVolumeError) as cm:
            Sound.from_sawtoothwave(440, volume=1.1)

        self.assertEqual(cm.exception.volume, 1.1)

        with self.assertRaises(InvalidSamplerateError) as cm:
            Sound.from_sawtoothwave(440, samplerate=0)

        self.assertEqual(cm.exception.frequency, 0)

    def test_from_squarewave(self):
        sound = Sound.from_squarewave(440,
                                      duration=1,
                                      volume=0.5,
                                      samplerate=44100)

        self.assertEqual(sound.samplerate, 44100)
        self.assertEqual(sound.duration, 1.0)
        self.assertTrue((-0.5 <= sound.data).all())
        self.assertTrue((sound.data <= 0.5).all())
        self.assertEqual(sound.volume, 0.5)

        sound = Sound.from_squarewave(880,
                                      duration=2,
                                      volume=0.8,
                                      samplerate=88200)

        self.assertEqual(sound.samplerate, 88200)
        self.assertTrue(sound.duration, 2.0)
        self.assertTrue((-0.8 <= sound.data).all())
        self.assertTrue((sound.data <= 0.8).all())
        self.assertTrue(sound.volume, 0.8)

        sound = Sound.from_squarewave(1, duration=2, samplerate=4)
        self.assertTrue(numpy.allclose(sound.data[:, 0],
                                       (1, 1, -1, -1, 1, 1, -1, -1)))

    def test_from_squarewave_invalid(self):
        with self.assertRaises(InvalidFrequencyError) as cm:
            Sound.from_squarewave(0)

        self.assertEqual(cm.exception.frequency, 0)

        with self.assertRaises(InvalidDurationError) as cm:
            Sound.from_squarewave(440, duration=0)

        self.assertEqual(cm.exception.duration, 0)

        with self.assertRaises(InvalidVolumeError) as cm:
            Sound.from_squarewave(440, volume=-0.1)

        self.assertEqual(cm.exception.volume, -0.1)

        with self.assertRaises(InvalidVolumeError) as cm:
            Sound.from_squarewave(440, volume=1.1)

        self.assertEqual(cm.exception.volume, 1.1)

        with self.assertRaises(InvalidSamplerateError) as cm:
            Sound.from_squarewave(440, samplerate=0)

        self.assertEqual(cm.exception.frequency, 0)

    def test_silence(self):
        sound = Sound.silence(duration=1.0, samplerate=100)

        self.assertEqual(sound.samplerate, 100)
        self.assertEqual(sound.duration, 1.0)
        self.assertTrue((sound.data == 0).all())

        sound = Sound.silence(duration=2.0, samplerate=20)

        self.assertEqual(sound.samplerate, 20)
        self.assertEqual(sound.duration, 2.0)
        self.assertTrue((sound.data == 0).all())

    def test_silence_invlid(self):
        with self.assertRaises(InvalidDurationError) as cm:
            Sound.silence(duration=0)

        self.assertEqual(cm.exception.duration, 0)

        with self.assertRaises(InvalidSamplerateError) as cm:
            Sound.silence(samplerate=0)

        self.assertEqual(cm.exception.frequency, 0)

    def test_whitenoise(self):
        sound = Sound.from_whitenoise(duration=2, volume=0.1, samplerate=100)

        self.assertEqual(sound.samplerate, 100)
        self.assertEqual(sound.duration, 2)
        self.assertTrue((-0.1 <= sound.data).all())
        self.assertTrue((sound.data <= 0.1).all())

    def test_whitenoise_invalid(self):
        with self.assertRaises(InvalidDurationError) as cm:
            Sound.from_whitenoise(duration=0)

        self.assertEqual(cm.exception.duration, 0)

        with self.assertRaises(InvalidVolumeError) as cm:
            Sound.from_whitenoise(volume=-0.1)

        self.assertEqual(cm.exception.volume, -0.1)

        with self.assertRaises(InvalidVolumeError) as cm:
            Sound.from_whitenoise(volume=1.1)

        self.assertEqual(cm.exception.volume, 1.1)

        with self.assertRaises(InvalidSamplerateError) as cm:
            Sound.from_whitenoise(samplerate=0)

        self.assertEqual(cm.exception.frequency, 0)

    def test_from_fft(self):
        f = numpy.zeros([2, 1024 // 2 + 1, 2], numpy.complex)
        f[:, -1, 0] = 1024 // 2
        f[0, 128, 1] = numpy.complex(0, -numpy.pi)
        f[1, 256, 1] = numpy.complex(0, -numpy.pi)

        s = Sound.from_fft(f)

        self.assertEqual(s.samplerate, 1024)
        self.assertEqual(s.n_channels, 2)
        self.assertEqual(s.duration, 1.0)

        from_sin = merge_channels(Sound.from_sinwave(128, samplerate=1024),
                                  Sound.from_sinwave(256, samplerate=1024))
        self.assertTrue(numpy.allclose(s.data / s.volume,
                                       from_sin.data / from_sin.volume))

    def test_from_fft_invalid(self):
        f = numpy.zeros([1024 // 2 + 1, 2], numpy.complex)

        with self.assertRaises(InvalidSamplerateError) as cm:
            Sound.from_fft(f, samplerate=0)

        self.assertEqual(cm.exception.frequency, 0)

    def test_fft_single_channel(self):
        sound = Sound.from_sinwave(440, duration=0.1)
        f = sound.fft()

        self.assertTrue((0 <= f[:, :, 0]).all())
        self.assertEqual(f.shape[0], 1)
        self.assertEqual(f.shape[2], 2)
        self.assertGreaterEqual(f[:, :, 0].min(), 0)
        self.assertLessEqual(f[:, :, 0].max(), sound.samplerate)
        self.assertEqual(f[0, :, 1].argmax(), abs(f[0, :, 0] - 440).argmin())

    def test_fft_two_channel(self):
        sound = merge_channels(Sound.from_sinwave(440, duration=0.1),
                               Sound.from_sinwave(220, duration=0.1))
        f = sound.fft()

        self.assertTrue((0 <= f[:, :, 0]).all())
        self.assertEqual(f.shape[0], 2)
        self.assertEqual(f.shape[2], 2)
        self.assertGreaterEqual(f[:, :, 0].min(), 0)
        self.assertLessEqual(f[:, :, 0].max(), sound.samplerate)
        self.assertEqual(f[0, :, 1].argmax(), abs(f[0, :, 0] - 440).argmin())
        self.assertEqual(f[1, :, 1].argmax(), abs(f[1, :, 0] - 220).argmin())

    def test_repeat(self):
        sound = Sound.from_array([0.0, 0.1, 0.2], 3)

        self.assertEqual(sound.duration, 1)
        self.assertEqual(tuple(sound.data), (0.0, 0.1, 0.2))

        sound = sound.repeat(2)

        self.assertEqual(sound.duration, 2)
        self.assertEqual(tuple(sound.data), (0.0, 0.1, 0.2, 0.0, 0.1, 0.2))

        sound = sound.repeat(2 / 3)

        self.assertEqual(sound.duration, 2 / 3)
        self.assertEqual(tuple(sound.data), (0.0, 0.1))

    def test_repeat_invalid(self):
        sound = Sound.from_sinwave(440)

        with self.assertRaises(InvalidDurationError) as cm:
            sound.repeat(0)

        self.assertEqual(cm.exception.duration, 0)

    def test_trim_just(self):
        sound = Sound.from_array([[0.0, 0.3], [0.1, 0.4], [0.2, 0.5]], 1)

        self.assertEqual(sound[0.0].n_channels, 2)
        self.assertEqual(tuple(sound[0.0].data[0, :]), (0.0, 0.3))

        self.assertEqual(sound[0.4999999999].n_channels, 2)
        self.assertEqual(tuple(sound[0.4999999999].data[0, :]), (0.0, 0.3))

        self.assertEqual(sound[0.5000000001].n_channels, 2)
        self.assertEqual(tuple(sound[0.5000000001].data[0, :]), (0.1, 0.4))

        self.assertEqual(sound[1.0].n_channels, 2)
        self.assertEqual(tuple(sound[1.0].data[0, :]), (0.1, 0.4))

        self.assertEqual(sound[2.0].n_channels, 2)
        self.assertEqual(tuple(sound[2.0].data[0, :]), (0.2, 0.5))

        self.assertEqual(sound[3.0].n_channels, 2)
        self.assertEqual(tuple(sound[3.0].data[0, :]), (0.2, 0.5))

    def test_trim_just_invalid(self):
        sound = Sound.from_array([0.0, 0.1, 0.2], 3)

        with self.assertRaises(OutOfDurationError) as cm:
            sound[-0.001]

        self.assertEqual(cm.exception.duration, -0.001)
        self.assertEqual(cm.exception.min, 0)
        self.assertEqual(cm.exception.max, 1)

        with self.assertRaises(OutOfDurationError) as cm:
            sound[3.001]

        self.assertEqual(cm.exception.duration, 3.001)
        self.assertEqual(cm.exception.min, 0)
        self.assertEqual(cm.exception.max, 1)

    def test_trim_head(self):
        sound = Sound.from_array([[0.0, 0.3], [0.1, 0.4], [0.2, 0.5]], 3)

        self.assertEqual(sound.duration, 1)
        self.assertEqual(sound.n_channels, 2)
        self.assertEqual(tuple(sound.data[:, 0]), (0.0, 0.1, 0.2))
        self.assertEqual(tuple(sound.data[:, 1]), (0.3, 0.4, 0.5))

        sound = sound[:2 / 3]

        self.assertEqual(sound.duration, 2 / 3)
        self.assertEqual(sound.n_channels, 2)
        self.assertEqual(tuple(sound.data[:, 0]), (0.0, 0.1))
        self.assertEqual(tuple(sound.data[:, 1]), (0.3, 0.4))

        sound = sound[:1 / 3]

        self.assertEqual(sound.duration, 1 / 3)
        self.assertEqual(sound.n_channels, 2)
        self.assertEqual(tuple(sound.data[:, 0]), (0.0, ))
        self.assertEqual(tuple(sound.data[:, 1]), (0.3, ))

    def test_trim_head_by_end(self):
        sound = Sound.from_array([[0.0, 0.3], [0.1, 0.4], [0.2, 0.5]], 3)

        self.assertEqual(sound.duration, 1)
        self.assertEqual(sound.n_channels, 2)
        self.assertEqual(tuple(sound.data[:, 0]), (0.0, 0.1, 0.2))
        self.assertEqual(tuple(sound.data[:, 1]), (0.3, 0.4, 0.5))

        sound = sound[:-1 / 3]

        self.assertEqual(sound.duration, 2 / 3)
        self.assertEqual(sound.n_channels, 2)
        self.assertEqual(tuple(sound.data[:, 0]), (0.0, 0.1))
        self.assertEqual(tuple(sound.data[:, 1]), (0.3, 0.4))

        sound = sound[:-1 / 3]

        self.assertEqual(sound.duration, 1 / 3)
        self.assertEqual(sound.n_channels, 2)
        self.assertEqual(tuple(sound.data[:, 0]), (0.0, ))
        self.assertEqual(tuple(sound.data[:, 1]), (0.3, ))

    def test_trim_tail(self):
        sound = Sound.from_array([[0.0, 0.3], [0.1, 0.4], [0.2, 0.5]], 3)

        self.assertEqual(sound.duration, 1)
        self.assertEqual(sound.n_channels, 2)
        self.assertEqual(tuple(sound.data[:, 0]), (0.0, 0.1, 0.2))
        self.assertEqual(tuple(sound.data[:, 1]), (0.3, 0.4, 0.5))

        sound = sound[1 / 3:]

        self.assertEqual(sound.duration, 2 / 3)
        self.assertEqual(sound.n_channels, 2)
        self.assertEqual(tuple(sound.data[:, 0]), (0.1, 0.2))
        self.assertEqual(tuple(sound.data[:, 1]), (0.4, 0.5))

        sound = sound[1 / 3:]

        self.assertEqual(sound.duration, 1 / 3)
        self.assertEqual(sound.n_channels, 2)
        self.assertEqual(tuple(sound.data[:, 0]), (0.2, ))
        self.assertEqual(tuple(sound.data[:, 1]), (0.5, ))

    def test_trim_tail_by_end(self):
        sound = Sound.from_array([[0.0, 0.3], [0.1, 0.4], [0.2, 0.5]], 3)

        self.assertEqual(sound.duration, 1)
        self.assertEqual(sound.n_channels, 2)
        self.assertEqual(tuple(sound.data[:, 0]), (0.0, 0.1, 0.2))
        self.assertEqual(tuple(sound.data[:, 1]), (0.3, 0.4, 0.5))

        sound = sound[-2 / 3:]

        self.assertEqual(sound.duration, 2 / 3)
        self.assertEqual(sound.n_channels, 2)
        self.assertEqual(tuple(sound.data[:, 0]), (0.1, 0.2))
        self.assertEqual(tuple(sound.data[:, 1]), (0.4, 0.5))

        sound = sound[-1 / 3:]

        self.assertEqual(sound.duration, 1 / 3)
        self.assertEqual(sound.n_channels, 2)
        self.assertEqual(tuple(sound.data[:, 0]), (0.2, ))
        self.assertEqual(tuple(sound.data[:, 1]), (0.5, ))

    def test_trim_between(self):
        sound = Sound.from_array([[0.0, 0.3], [0.1, 0.4], [0.2, 0.5]], 3)

        self.assertEqual(sound.duration, 1)
        self.assertEqual(sound.n_channels, 2)
        self.assertEqual(tuple(sound.data[:, 0]), (0.0, 0.1, 0.2))
        self.assertEqual(tuple(sound.data[:, 1]), (0.3, 0.4, 0.5))

        sound = sound[1 / 3: 2 / 3]

        self.assertEqual(sound.duration, 1 / 3)
        self.assertEqual(sound.n_channels, 2)
        self.assertEqual(tuple(sound.data[:, 0]), (0.1, ))
        self.assertEqual(tuple(sound.data[:, 1]), (0.4, ))

    def test_trim_between_by_end(self):
        sound = Sound.from_array([[0.0, 0.3], [0.1, 0.4], [0.2, 0.5]], 3)

        self.assertEqual(sound.duration, 1)
        self.assertEqual(sound.n_channels, 2)
        self.assertEqual(tuple(sound.data[:, 0]), (0.0, 0.1, 0.2))
        self.assertEqual(tuple(sound.data[:, 1]), (0.3, 0.4, 0.5))

        sound = sound[-2 / 3: -1 / 3]

        self.assertEqual(sound.duration, 1 / 3)
        self.assertEqual(sound.n_channels, 2)
        self.assertEqual(tuple(sound.data[:, 0]), (0.1, ))
        self.assertEqual(tuple(sound.data[:, 1]), (0.4, ))

    def test_trim_between_invalid(self):
        sound = Sound.from_sinwave(440)

        with self.assertRaises(InvalidDurationError):
            sound[0.6:0.5]

        with self.assertRaises(InvalidDurationError):
            sound[0.5:0.5]

    def test_trim_step(self):
        sound = Sound.from_sinwave(440)

        with self.assertRaises(ValueError) as cm:
            sound[::1]

        self.assertEqual(str(cm.exception), 'step is not supported')

    def test_split_channels(self):
        a = Sound.from_array([0.1, 0.2], 2)
        b = Sound.from_array([0.3, 0.4], 2)
        ab = Sound.from_array([[0.1, 0.3], [0.2, 0.4]], 2)

        a_, b_ = ab.split_channels()
        self.assertEqual(a_, a)
        self.assertEqual(b_, b)

    def test_as_monaural(self):
        stereo = Sound.from_array([[0.1, 0.3], [0.2, 0.4]], 2)
        monaural = Sound.from_array([0.2, 0.3], 2)

        self.assertEqual(stereo.as_monaural(), monaural)

        self.assertIs(monaural.as_monaural(), monaural)

    def test_as_stereo(self):
        monaural = Sound.from_array([0.1, 0.2], 2)
        stereo = Sound.from_array([[0.1, 0.1], [0.2, 0.2]], 2)
        triple = Sound.from_array([[0.1, 0.1, 0.1], [0.2, 0.2, 0.2]], 2)

        self.assertEqual(monaural.as_stereo(), stereo)
        self.assertEqual(monaural.as_stereo(channels=3), triple)

        self.assertIs(stereo.as_stereo(), stereo)

    def test_as_stereo_invalid(self):
        stereo = Sound.from_array([[0.1, 0.1], [0.2, 0.2]], 2)

        with self.assertRaises(ValueError) as cm:
            self.assertEqual(stereo.as_stereo(1), stereo)

        self.assertEqual(str(cm.exception),
                         'channels must be 2 or greater but got 1')

    def test_concat(self):
        a = Sound.from_array([0.0, 0.1], 2)
        b = Sound.from_array([0.2, 0.3], 2)

        self.assertEqual(a.concat(b),
                         Sound.from_array([0.0, 0.1, 0.2, 0.3], 2))

        self.assertEqual(b.concat(a),
                         Sound.from_array([0.2, 0.3, 0.0, 0.1], 2))

    def test_concat_different_samplerate(self):
        a = Sound.from_array([0.0, 0.1], 2)
        b = Sound.from_array([0.2, 0.3], 3)

        with self.assertRaises(DifferentSamplerateError) as cm:
            a.concat(b)

        self.assertEqual(cm.exception.frequency, (2, 3))

        with self.assertRaises(DifferentSamplerateError) as cm:
            b.concat(a)

        self.assertEqual(cm.exception.frequency, (3, 2))

    def test_concat_different_channels(self):
        a = Sound.from_sinwave(440)
        b = Sound.from_sinwave(880).as_stereo()

        with self.assertRaises(DifferentChannelsError) as cm:
            a.concat(b)

        self.assertEqual(cm.exception.channels, (1, 2))

        with self.assertRaises(DifferentChannelsError) as cm:
            b.concat(a)

        self.assertEqual(cm.exception.channels, (2, 1))

    def test_overlay(self):
        a = Sound.from_array([0.0, 0.1], 2)
        b = Sound.from_array([0.2, 0.3, 0.4], 2)

        self.assertEqual(a.overlay(b),
                         Sound.from_array([0.2, 0.4, 0.4], 2))

        self.assertEqual(b.overlay(a),
                         Sound.from_array([0.2, 0.4, 0.4], 2))

    def test_overlay_different_samplerate(self):
        a = Sound.from_array([0.0, 0.1], 2)
        b = Sound.from_array([0.2, 0.3], 3)

        with self.assertRaises(DifferentSamplerateError) as cm:
            a.overlay(b)

        self.assertEqual(cm.exception.frequency, (2, 3))

        with self.assertRaises(DifferentSamplerateError) as cm:
            b.overlay(a)

        self.assertEqual(cm.exception.frequency, (3, 2))

    def test_overlay_different_channels(self):
        a = Sound.from_sinwave(440)
        b = Sound.from_sinwave(880).as_stereo()

        with self.assertRaises(DifferentChannelsError) as cm:
            a.overlay(b)

        self.assertEqual(cm.exception.channels, (1, 2))

        with self.assertRaises(DifferentChannelsError) as cm:
            b.overlay(a)

        self.assertEqual(cm.exception.channels, (2, 1))

    def test_save_and_load_file(self):
        original = Sound.from_sinwave(440).concat(Sound.from_sinwave(880))

        with tempfile.NamedTemporaryFile(suffix='.wav') as f:
            original.write(f.name)

            loaded = Sound.from_file(f.name)

        self.assertEqual(original.samplerate, loaded.samplerate)
        self.assertEqual(original.duration, loaded.duration)
        self.assertTrue(numpy.allclose(original.data, loaded.data, rtol=0.01))

    def test_save_and_load_buffer(self):
        original = Sound.from_sinwave(440).concat(Sound.from_sinwave(880))

        with io.BytesIO() as f:
            original.write(f, format_='wav')

            f.seek(0)

            loaded = Sound.from_file(f)

        self.assertEqual(original.samplerate, loaded.samplerate)
        self.assertEqual(original.duration, loaded.duration)
        self.assertTrue(numpy.allclose(original.data, loaded.data, rtol=0.01))


text:
<?xml version="1.0" encoding="UTF-8"?>

<!--
  ~ =============================================================================
  ~
  ~   Copyright (c) 2011-2022, The THYMELEAF team (http://www.thymeleaf.org)
  ~
  ~   Licensed under the Apache License, Version 2.0 (the "License");
  ~   you may not use this file except in compliance with the License.
  ~   You may obtain a copy of the License at
  ~
  ~       http://www.apache.org/licenses/LICENSE-2.0
  ~
  ~   Unless required by applicable law or agreed to in writing, software
  ~   distributed under the License is distributed on an "AS IS" BASIS,
  ~   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  ~   See the License for the specific language governing permissions and
  ~   limitations under the License.
  ~
  ~ =============================================================================
  -->

<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/maven-v4_0_0.xsd">

  <modelVersion>4.0.0</modelVersion>

  <parent>
    <groupId>org.thymeleaf</groupId>
    <artifactId>thymeleaf-lib</artifactId>
    <version>3.1.1-SNAPSHOT</version>
    <relativePath>../pom.xml</relativePath>
  </parent>

  <artifactId>thymeleaf-spring5</artifactId>
  <packaging>jar</packaging>
  <name>thymeleaf-spring5</name>

  <properties>
    <!-- A project-name-based approach is adopted for module name (instead a reverse-DNS).      -->
    <!-- NOTE module name is fixed and not set to project.artifactId because this would not be  -->
    <!-- a valid approach for project names containing hyphens (not allowed in module names).   -->
    <module.name>thymeleaf.spring5</module.name>
  </properties>

  <build>

    <plugins>
      <plugin>
        <groupId>org.apache.maven.plugins</groupId>
        <artifactId>maven-javadoc-plugin</artifactId>
      </plugin>
      <plugin>
        <groupId>org.apache.maven.plugins</groupId>
        <artifactId>maven-source-plugin</artifactId>
      </plugin>
      <plugin>
        <groupId>org.apache.maven.plugins</groupId>
        <artifactId>maven-antrun-plugin</artifactId>
      </plugin>
    </plugins>

  </build>

  <dependencyManagement>
    <dependencies>
      <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-framework-bom</artifactId>
        <version>${spring-framework5.version}</version>
        <type>pom</type>
        <scope>import</scope>
      </dependency>
      <dependency>
        <groupId>org.springframework.webflow</groupId>
        <artifactId>spring-webflow</artifactId>
        <version>${spring-webflow2.version}</version>
      </dependency>
    </dependencies>
  </dependencyManagement>

  <dependencies>

    <dependency>
      <groupId>org.thymeleaf</groupId>
      <artifactId>thymeleaf</artifactId>
      <scope>compile</scope>
      <exclusions>
        <exclusion>
          <groupId>ognl</groupId>
          <artifactId>ognl</artifactId>
        </exclusion>
      </exclusions>
    </dependency>

    <dependency>
      <groupId>javax.servlet</groupId>
      <artifactId>javax.servlet-api</artifactId>
      <scope>provided</scope>
      <optional>true</optional>
    </dependency>

    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-beans</artifactId>
      <scope>provided</scope>
      <optional>true</optional>
    </dependency>

    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-web</artifactId>
      <scope>provided</scope>
      <optional>true</optional>
    </dependency>

    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-webflux</artifactId>
      <scope>provided</scope>
      <optional>true</optional>
    </dependency>

    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-webmvc</artifactId>
      <scope>provided</scope>
      <optional>true</optional>
    </dependency>

    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-expression</artifactId>
      <scope>provided</scope>
      <optional>true</optional>
    </dependency>

    <dependency>
      <groupId>org.springframework.webflow</groupId>
      <artifactId>spring-webflow</artifactId>
      <scope>provided</scope>
      <optional>true</optional>
    </dependency>

    <dependency>
      <groupId>org.slf4j</groupId>
      <artifactId>slf4j-api</artifactId>
    </dependency>

  </dependencies>

</project>

redpajama_set_name: RedPajamaGithub


text:
using Microsoft.EntityFrameworkCore.Migrations;

namespace Microting.eForm.Migrations
{
    public partial class AddingMicrotingUidToInSight : Migration
    {
        protected override void Up(MigrationBuilder migrationBuilder)
        {
            migrationBuilder.AddColumn<int>(
                name: "MicrotingUid",
                table: "QuestionTranslationVersions",
                nullable: true);

            migrationBuilder.AddColumn<int>(
                name: "MicrotingUid",
                table: "QuestionTranslations",
                nullable: true);

            migrationBuilder.AddColumn<int>(
                name: "MicrotingUid",
                table: "OptionTranslationVersions",
                nullable: true);

            migrationBuilder.AddColumn<int>(
                name: "MicrotingUid",
                table: "OptionTranslations",
                nullable: true);

            migrationBuilder.AddColumn<int>(
                name: "MicrotingUid",
                table: "LanguageQuestionSetVersions",
                nullable: true);

            migrationBuilder.AddColumn<int>(
                name: "MicrotingUid",
                table: "LanguageQuestionSets",
                nullable: true);
        }

        protected override void Down(MigrationBuilder migrationBuilder)
        {
            migrationBuilder.DropColumn(
                name: "MicrotingUid",
                table: "QuestionTranslationVersions");

            migrationBuilder.DropColumn(
                name: "MicrotingUid",
                table: "QuestionTranslations");

            migrationBuilder.DropColumn(
                name: "MicrotingUid",
                table: "OptionTranslationVersions");

            migrationBuilder.DropColumn(
                name: "MicrotingUid",
                table: "OptionTranslations");

            migrationBuilder.DropColumn(
                name: "MicrotingUid",
                table: "LanguageQuestionSetVersions");

            migrationBuilder.DropColumn(
                name: "MicrotingUid",
                table: "LanguageQuestionSets");
        }
    }
}


text:
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.

using System;
using System.ComponentModel;
using System.Threading;
using System.Threading.Tasks;
using System.Xml.Linq;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CodeFixes.Configuration;
using Microsoft.CodeAnalysis.Diagnostics;
using Microsoft.Internal.VisualStudio.PlatformUI;
using Microsoft.VisualStudio.Imaging;
using Microsoft.VisualStudio.Imaging.Interop;

namespace Microsoft.VisualStudio.LanguageServices.Implementation.SolutionExplorer
{
    internal partial class DiagnosticItem : BaseItem
    {
        private readonly AnalyzerReference _analyzerReference;
        private readonly IAnalyzersCommandHandler _commandHandler;

        public ProjectId ProjectId { get; }
        public DiagnosticDescriptor Descriptor { get; }
        public ReportDiagnostic EffectiveSeverity { get; private set; }

        public override event PropertyChangedEventHandler? PropertyChanged;

        public DiagnosticItem(ProjectId projectId, AnalyzerReference analyzerReference, DiagnosticDescriptor descriptor, ReportDiagnostic effectiveSeverity, IAnalyzersCommandHandler commandHandler)
            : base(descriptor.Id + ": " + descriptor.Title)
        {
            ProjectId = projectId;
            _analyzerReference = analyzerReference;
            Descriptor = descriptor;
            EffectiveSeverity = effectiveSeverity;
            _commandHandler = commandHandler;
        }

        public override ImageMoniker IconMoniker
            => MapEffectiveSeverityToIconMoniker(EffectiveSeverity);

        public override IContextMenuController ContextMenuController => _commandHandler.DiagnosticContextMenuController;

        public override object GetBrowseObject()
        {
            return new BrowseObject(this);
        }

        internal void UpdateEffectiveSeverity(ReportDiagnostic newEffectiveSeverity)
        {
            if (EffectiveSeverity != newEffectiveSeverity)
            {
                EffectiveSeverity = newEffectiveSeverity;

                NotifyPropertyChanged(nameof(EffectiveSeverity));
                NotifyPropertyChanged(nameof(IconMoniker));
            }
        }

        private static ImageMoniker MapEffectiveSeverityToIconMoniker(ReportDiagnostic effectiveSeverity)
            => effectiveSeverity switch
            {
                ReportDiagnostic.Error => KnownMonikers.CodeErrorRule,
                ReportDiagnostic.Warn => KnownMonikers.CodeWarningRule,
                ReportDiagnostic.Info => KnownMonikers.CodeInformationRule,
                ReportDiagnostic.Hidden => KnownMonikers.CodeHiddenRule,
                ReportDiagnostic.Suppress => KnownMonikers.CodeSuppressedRule,
                _ => default,
            };

        private void NotifyPropertyChanged(string propertyName)
        {
            PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
        }

        internal void SetRuleSetSeverity(ReportDiagnostic value, string pathToRuleSet)
        {
            var ruleSetDocument = XDocument.Load(pathToRuleSet);

            ruleSetDocument.SetSeverity(_analyzerReference.Display, Descriptor.Id, value);

            ruleSetDocument.Save(pathToRuleSet);
        }

        internal Task<Solution> GetSolutionWithUpdatedAnalyzerConfigSeverityAsync(ReportDiagnostic value, Project project, CancellationToken cancellationToken)
        {
            var effectiveSeverity = value.ToDiagnosticSeverity() ?? Descriptor.DefaultSeverity;
            var diagnostic = Diagnostic.Create(Descriptor, Location.None, effectiveSeverity, additionalLocations: null, properties: null);
            return ConfigurationUpdater.ConfigureSeverityAsync(value, diagnostic, project, cancellationToken);
        }
    }
}


text:
using System;
using System.Linq;
using System.Runtime.Serialization;

namespace BL4N
{
    /// <summary> Backlog.jp 向けの接続設定を表します </summary>
    [DataContract]
    public sealed class BacklogJPConnectionSettings : BacklogConnectionSettings
    {
        /// <summary> <see cref="BacklogJPConnectionSettings"/> のインスタンスを初期化します </summary>
        /// <param name="spaceName">スペース名</param>
        /// <param name="apiType">認証方式</param>
        /// <param name="apiKey"> APIKey </param>
        public BacklogJPConnectionSettings(string spaceName, APIType apiType, string apiKey)
            : base(spaceName, apiType, apiKey, spaceName + ".backlog.jp", 443, true)
        {
        }

        /// <inheritdoc/>
        public override bool IsValid()
        {
            // only apikey type support, now
            return APIType == APIType.APIKey
                && (!string.IsNullOrWhiteSpace(SpaceName) && !string.IsNullOrWhiteSpace(APIKey));
        }
    }
}


text:
package org.ehcache.clustered.management;

import org.ehcache.CacheManager;
import org.ehcache.Status;
import org.ehcache.config.units.EntryUnit;
import org.ehcache.config.units.MemoryUnit;
import org.ehcache.management.registry.DefaultManagementRegistryConfiguration;
import org.junit.ClassRule;
import org.junit.Test;
import org.terracotta.management.model.message.Message;
import org.terracotta.management.model.notification.ContextualNotification;
import org.terracotta.testing.rules.Cluster;

import java.io.File;

import static org.ehcache.clustered.client.config.builders.ClusteredResourcePoolBuilder.clusteredDedicated;
import static org.ehcache.clustered.client.config.builders.ClusteringServiceConfigurationBuilder.cluster;
import static org.ehcache.clustered.management.AbstractClusteringManagementTest.createNmsService;
import static org.ehcache.clustered.management.AbstractClusteringManagementTest.nmsService;
import static org.ehcache.config.builders.CacheConfigurationBuilder.newCacheConfigurationBuilder;
import static org.ehcache.config.builders.CacheManagerBuilder.newCacheManagerBuilder;
import static org.ehcache.config.builders.ResourcePoolsBuilder.newResourcePoolsBuilder;
import static org.hamcrest.CoreMatchers.equalTo;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertThat;
import static org.terracotta.testing.rules.BasicExternalClusterBuilder.newCluster;

public class CMClosedEventSentTest {

  private static final String RESOURCE_CONFIG =
    "<config xmlns:ohr='http://www.terracotta.org/config/offheap-resource'>"
      + "<ohr:offheap-resources>"
      + "<ohr:resource name=\"primary-server-resource\" unit=\"MB\">64</ohr:resource>"
      + "<ohr:resource name=\"secondary-server-resource\" unit=\"MB\">64</ohr:resource>"
      + "</ohr:offheap-resources>"
      + "</config>\n"
      + "<service xmlns:lease='http://www.terracotta.org/service/lease'>"
      + "<lease:connection-leasing>"
      + "<lease:lease-length unit='seconds'>5</lease:lease-length>"
      + "</lease:connection-leasing>"
      + "</service>";

  @ClassRule
  public static Cluster CLUSTER = newCluster().in(new File("build/cluster")).withServiceFragment(RESOURCE_CONFIG).build();

  @Test(timeout = 60_000)
  public void test_CACHE_MANAGER_CLOSED() throws Exception {
    createNmsService(CLUSTER);

    try (CacheManager cacheManager = newCacheManagerBuilder().with(cluster(CLUSTER.getConnectionURI().resolve("/my-server-entity-1"))
      .autoCreate()
      .defaultServerResource("primary-server-resource")
      .resourcePool("resource-pool-a", 10, MemoryUnit.MB, "secondary-server-resource") // <2>
      .resourcePool("resource-pool-b", 10, MemoryUnit.MB)) // will take from primary-server-resource
      // management config
      .using(new DefaultManagementRegistryConfiguration()
        .addTags("webapp-1", "server-node-1")
        .setCacheManagerAlias("my-super-cache-manager"))
      // cache config
      .withCache("dedicated-cache-1", newCacheConfigurationBuilder(
        String.class, String.class,
        newResourcePoolsBuilder()
          .heap(10, EntryUnit.ENTRIES)
          .offheap(1, MemoryUnit.MB)
          .with(clusteredDedicated("primary-server-resource", 4, MemoryUnit.MB)))
        .build())
      .build(true)) {

      assertThat(cacheManager.getStatus(), equalTo(Status.AVAILABLE));
      waitFor("CACHE_MANAGER_AVAILABLE");

    }
    waitFor("CACHE_MANAGER_CLOSED");
  }

  private void waitFor(String notifType) throws InterruptedException {
    while (!Thread.currentThread().isInterrupted()) {
      Message message = nmsService.waitForMessage();
      if (message.getType().equals("NOTIFICATION")) {
        ContextualNotification notification = message.unwrap(ContextualNotification.class).get(0);
        if (notification.getType().equals(notifType)) {
          break;
        }
      }
    }
    assertFalse(Thread.currentThread().isInterrupted());
  }

}


text:
#import "PBCodable.h"

#import "NSCopying-Protocol.h"

@class GEOPlaceSearchRequest, GEOPlaceSearchResponse, NSString;

@interface GEORPCorrectedSearch : PBCodable <NSCopying>
{
    unsigned int _correctedSearchResultIndex;
    unsigned int _originalSearchResultIndex;
    GEOPlaceSearchRequest *_placeSearchRequest;
    GEOPlaceSearchResponse *_placeSearchResponse;
    NSString *_preferredSearchDisplayLocation;
    struct {
        unsigned int correctedSearchResultIndex:1;
        unsigned int originalSearchResultIndex:1;
    } _has;
}

@property(retain, nonatomic) NSString *preferredSearchDisplayLocation; // @synthesize preferredSearchDisplayLocation=_preferredSearchDisplayLocation;
@property(nonatomic) unsigned int correctedSearchResultIndex; // @synthesize correctedSearchResultIndex=_correctedSearchResultIndex;
@property(nonatomic) unsigned int originalSearchResultIndex; // @synthesize originalSearchResultIndex=_originalSearchResultIndex;
@property(retain, nonatomic) GEOPlaceSearchResponse *placeSearchResponse; // @synthesize placeSearchResponse=_placeSearchResponse;
@property(retain, nonatomic) GEOPlaceSearchRequest *placeSearchRequest; // @synthesize placeSearchRequest=_placeSearchRequest;
- (unsigned long long)hash;
- (_Bool)isEqual:(id)arg1;
- (id)copyWithZone:(struct _NSZone *)arg1;
- (void)copyTo:(id)arg1;
- (void)writeTo:(id)arg1;
- (_Bool)readFrom:(id)arg1;
- (id)dictionaryRepresentation;
- (id)description;
@property(readonly, nonatomic) _Bool hasPreferredSearchDisplayLocation;
@property(nonatomic) _Bool hasCorrectedSearchResultIndex;
@property(nonatomic) _Bool hasOriginalSearchResultIndex;
@property(readonly, nonatomic) _Bool hasPlaceSearchResponse;
@property(readonly, nonatomic) _Bool hasPlaceSearchRequest;
- (void)dealloc;

@end


text:
package com.kwoak.dev.timerangepicker;

import android.app.Dialog;
import android.content.Context;
import android.graphics.Color;
import android.os.Build;
import android.os.Bundle;
import android.view.View;
import android.view.WindowManager;
import android.widget.TextView;
import android.widget.TimePicker;

import java.util.Calendar;

/**
 * Created by HEEJU on 2016-06-30.
 */
public class DialogTimeRangePicker extends Dialog {

    int nonClickedBackground = Color.rgb(255, 255, 255);
    int clickedBackground = Color.rgb(210, 210, 210);

    TextView buttonFrom;
    TextView buttonTo;
    TextView buttonCancel;
    TextView buttonOk;

    TimePicker pickerFrom;
    TimePicker pickerTo;

    onConfirmListener confirmListener;

    public DialogTimeRangePicker(Context context) {
        super(context, android.R.style.Theme_DeviceDefault_Light_Dialog_NoActionBar);
    }

    public DialogTimeRangePicker(Context context, int theme) {
        super(context, theme);
    }

    /**
     * method for change hour, minute of time picker 'from'
     * this should be called after DialogTimeRangePicker.show()
     * @param hour  hour
     * @param min   minute
     */
    public void setTimeFrom(int hour, int min) {
        if (Build.VERSION.SDK_INT < 23) {
            pickerFrom.setCurrentHour(hour);
            pickerFrom.setCurrentMinute(min);
        } else {
            pickerFrom.setHour(hour);
            pickerFrom.setMinute(min);
        }
    }

    /**
     * method for change hour, minute of time picker 'from'
     * this should be called after DialogTimeRangePicker.show()
     * same as DialogTimeRangePicker.setTimeFrom(int hour, int min)
     * @param calendar
     */
    public void setTimeFrom(Calendar calendar) {
        if (Build.VERSION.SDK_INT < 23) {
            pickerFrom.setCurrentHour(calendar.get(Calendar.HOUR));
            pickerFrom.setCurrentMinute(calendar.get(Calendar.MINUTE));
        } else {
            pickerFrom.setHour(calendar.get(Calendar.HOUR));
            pickerFrom.setMinute(calendar.get(Calendar.MINUTE));
        }
    }

    /**
     * method for change hour, minute of time picker 'to'
     * this should be called after DialogTimeRangePicker.show()
     * @param hour  hour
     * @param min   minute
     */
    public void setTimeTo(int hour, int min) {
        if (Build.VERSION.SDK_INT < 23) {
            pickerTo.setCurrentHour(hour);
            pickerTo.setCurrentMinute(min);
        } else {
            pickerTo.setHour(hour);
            pickerTo.setMinute(min);
        }
    }

    /**
     * method for change hour, minute of time picker 'to'
     * this should be called after DialogTimeRangePicker.show()
     * same as DialogTimeRangePicker.setTimeTo(int hour, int min)
     * @param calendar
     */
    public void setTimeTo(Calendar calendar) {
        if (Build.VERSION.SDK_INT < 23) {
            pickerTo.setCurrentHour(calendar.get(Calendar.HOUR));
            pickerTo.setCurrentMinute(calendar.get(Calendar.MINUTE));
        } else {
            pickerTo.setHour(calendar.get(Calendar.HOUR));
            pickerTo.setMinute(calendar.get(Calendar.MINUTE));
        }
    }

    /**
     * if you want to see time picker 'to' first use this with parameter true
     * @param visible   time picker 'to' visible
     */
    public void setVisibleTo(boolean visible) {
        setButtonColor(!visible);
        if (visible) {
            pickerFrom.setVisibility(View.INVISIBLE);
            pickerTo.setVisibility(View.VISIBLE);
        } else {
            pickerFrom.setVisibility(View.VISIBLE);
            pickerTo.setVisibility(View.INVISIBLE);
        }
    }

    public void setButtonColor(boolean fromClicked) {
        if (fromClicked) {
            buttonFrom.setBackgroundColor(clickedBackground);
            buttonTo.setBackgroundColor(nonClickedBackground);
        } else {
            buttonFrom.setBackgroundColor(nonClickedBackground);
            buttonTo.setBackgroundColor(clickedBackground);
        }
    }

    public interface onConfirmListener {
        /**
         *
         * @param fromHour  time for start hour
         * @param fromMin   time for start minute
         * @param toHour    time for end hour
         * @param toMin     time for end minute
         */
        public void confirmEvent(int fromHour, int fromMin, int toHour, int toMin);
    }

    public void setConfirmListener(onConfirmListener confirmListener) {
        this.confirmListener = confirmListener;
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        WindowManager.LayoutParams lpWindow = new WindowManager.LayoutParams();
        lpWindow.flags = WindowManager.LayoutParams.FLAG_DIM_BEHIND;
        lpWindow.dimAmount = 0.3f;
        getWindow().setAttributes(lpWindow);

        setContentView(R.layout.time_container_layout);

        buttonCancel = (TextView) findViewById(R.id.container_button_cancel);
        buttonCancel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                dismiss();
            }
        });

        buttonOk = (TextView) findViewById(R.id.container_button_ok);
        buttonOk.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (Build.VERSION.SDK_INT < 23) {
                    confirmListener.confirmEvent(
                            pickerFrom.getCurrentHour(), pickerFrom.getCurrentMinute(),
                            pickerTo.getCurrentHour(), pickerTo.getCurrentMinute());
                } else {
                    confirmListener.confirmEvent(
                            pickerFrom.getHour(), pickerFrom.getMinute(),
                            pickerTo.getHour(), pickerTo.getMinute());
                }
                dismiss();
            }
        });

        buttonFrom = (TextView) findViewById(R.id.container_button_from);
        buttonFrom.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                setButtonColor(true);
                pickerFrom.setVisibility(View.VISIBLE);
                pickerTo.setVisibility(View.INVISIBLE);
            }
        });

        buttonTo = (TextView) findViewById(R.id.container_button_to);
        buttonTo.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                setButtonColor(false);
                pickerFrom.setVisibility(View.INVISIBLE);
                pickerTo.setVisibility(View.VISIBLE);
            }
        });

        setButtonColor(true);

        pickerFrom = (TimePicker) findViewById(R.id.container_picker_from);
        pickerTo = (TimePicker) findViewById(R.id.container_picker_to);
    }
}


text:
package org.zaproxy.zap.extension.script;

import javax.swing.tree.DefaultMutableTreeNode;

import org.parosproxy.paros.Constant;

/**
 *
 * To change the template for this generated type comment go to
 * Window - Preferences - Java - Code Generation - Code and Comments
 */
public class ScriptNode extends DefaultMutableTreeNode {
	private static final long serialVersionUID = 1L;
	private String nodeName = null;
	private ScriptType type = null;
	private boolean template = false;

	public ScriptNode() {
		// Only use for the root node
        super();
        this.nodeName = Constant.messages.getString("script.tree.root");
    }

	public ScriptNode(boolean template) {
		// Only use for the second level nodes
        this.template = template;
        if (template) {
            this.nodeName = Constant.messages.getString("script.tree.templates");
        } else {
            this.nodeName = Constant.messages.getString("script.tree.scripts");
        }

    }

	public ScriptNode(ScriptType type, boolean template) {
		this.nodeName = Constant.messages.getString(type.getI18nKey());
		this.type = type;
        this.template = template;
	}

	public ScriptNode(String name) {
		this.nodeName = name;
	}

	public ScriptNode(ScriptWrapper script) {
		this(script, false);
	}

	public ScriptNode(ScriptWrapper script, boolean template) {
		this.nodeName = script.getName();
		this.type  = script.getType();
		this.template = template;
		this.setUserObject(script);
	}

    @Override
    public String toString() {
        return nodeName;
    }

	public String getNodeName() {
		return nodeName;
	}

	public void setNodeName(String name) {
		this.nodeName = name;
	}

	@Override
	public ScriptNode getParent() {
		return (ScriptNode) super.getParent();
	}

	public ScriptType getType() {
		return type;
	}

	public boolean isTemplate() {
		return template;
	}
}


text:
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<title>{% if page.title %}{{ page.title }} | {% endif %}{{ site.title }}</title>
<meta name="description" content="{% if page.description %}{{ page.description }}{% else %}{{ site.description }}{% endif %}">
{% if page.tags %}<meta name="keywords" content="{{ page.tags | join: ', ' }}">{% endif %}
<meta name="author" content="{{ site.author.name }}">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="cleartype" content="on">


text:
namespace subresource_filter {

namespace proto = url_pattern_index::proto;

namespace {

// The methods below assume that char and uint8_t are interchangeable.
static_assert(CHAR_BIT == 8, "Assumed char was 8 bits.");

void WriteRulesetContents(const std::vector<uint8_t>& contents,
                          base::FilePath path) {
  base::ScopedAllowBlockingForTesting allow_blocking;
  int ruleset_size_as_int = base::checked_cast<int>(contents.size());
  int num_bytes_written =
      base::WriteFile(path, reinterpret_cast<const char*>(contents.data()),
                      ruleset_size_as_int);
  ASSERT_EQ(ruleset_size_as_int, num_bytes_written);
}

std::vector<uint8_t> SerializeUnindexedRulesetWithMultipleRules(
    const std::vector<proto::UrlRule>& rules) {
  std::string ruleset_contents;
  google::protobuf::io::StringOutputStream output(&ruleset_contents);
  UnindexedRulesetWriter ruleset_writer(&output);
  for (const auto& rule : rules)
    ruleset_writer.AddUrlRule(rule);
  ruleset_writer.Finish();

  auto* data = reinterpret_cast<const uint8_t*>(ruleset_contents.data());
  return std::vector<uint8_t>(data, data + ruleset_contents.size());
}

std::vector<uint8_t> SerializeIndexedRulesetWithMultipleRules(
    const std::vector<proto::UrlRule>& rules) {
  RulesetIndexer indexer;
  for (const auto& rule : rules)
    EXPECT_TRUE(indexer.AddUrlRule(rule));
  indexer.Finish();
  return std::vector<uint8_t>(indexer.data(), indexer.data() + indexer.size());
}

}  // namespace

namespace testing {

// TestRuleset -----------------------------------------------------------------

TestRuleset::TestRuleset() = default;
TestRuleset::~TestRuleset() = default;

// static
base::File TestRuleset::Open(const TestRuleset& ruleset) {
  base::ScopedAllowBlockingForTesting allow_blocking;
  base::File file;
  file.Initialize(ruleset.path, base::File::FLAG_OPEN | base::File::FLAG_READ |
                                    base::File::FLAG_WIN_SHARE_DELETE);
  return file;
}

// static
void TestRuleset::CorruptByTruncating(const TestRuleset& ruleset,
                                      size_t tail_size) {
  ASSERT_GT(tail_size, 0u);
  ASSERT_FALSE(ruleset.contents.empty());
  std::vector<uint8_t> new_contents = ruleset.contents;

  const size_t new_size =
      tail_size < new_contents.size() ? new_contents.size() - tail_size : 0;
  new_contents.resize(new_size);
  WriteRulesetContents(new_contents, ruleset.path);
}

// static
void TestRuleset::CorruptByFilling(const TestRuleset& ruleset,
                                   size_t from,
                                   size_t to,
                                   uint8_t fill_with) {
  ASSERT_LT(from, to);
  ASSERT_LE(to, ruleset.contents.size());

  std::vector<uint8_t> new_contents = ruleset.contents;
  for (size_t i = from; i < to; ++i)
    new_contents[i] = fill_with;
  WriteRulesetContents(new_contents, ruleset.path);
}

// TestRulesetPair -------------------------------------------------------------

TestRulesetPair::TestRulesetPair() = default;
TestRulesetPair::~TestRulesetPair() = default;

// TestRulesetCreator ----------------------------------------------------------

TestRulesetCreator::TestRulesetCreator()
    : scoped_temp_dir_(std::make_unique<base::ScopedTempDir>()) {}

TestRulesetCreator::~TestRulesetCreator() {
  base::ScopedAllowBlockingForTesting allow_blocking;
  scoped_temp_dir_.reset();
}

void TestRulesetCreator::CreateRulesetToDisallowURLsWithPathSuffix(
    base::StringPiece suffix,
    TestRulesetPair* test_ruleset_pair) {
  DCHECK(test_ruleset_pair);
  proto::UrlRule suffix_rule = CreateSuffixRule(suffix);
  CreateRulesetWithRules({suffix_rule}, test_ruleset_pair);
}

void TestRulesetCreator::CreateUnindexedRulesetToDisallowURLsWithPathSuffix(
    base::StringPiece suffix,
    TestRuleset* test_unindexed_ruleset) {
  DCHECK(test_unindexed_ruleset);
  proto::UrlRule suffix_rule = CreateSuffixRule(suffix);
  ASSERT_NO_FATAL_FAILURE(
      CreateUnindexedRulesetWithRules({suffix_rule}, test_unindexed_ruleset));
}

void TestRulesetCreator::CreateRulesetToDisallowURLWithSubstrings(
    std::vector<base::StringPiece> substrings,
    TestRulesetPair* test_ruleset_pair) {
  DCHECK(test_ruleset_pair);
  std::vector<proto::UrlRule> url_rules;
  for (const auto& substring : substrings)
    url_rules.push_back(CreateSubstringRule(substring));
  CreateRulesetWithRules(url_rules, test_ruleset_pair);
}

void TestRulesetCreator::CreateRulesetToDisallowURLsWithManySuffixes(
    base::StringPiece suffix,
    int num_of_suffixes,
    TestRulesetPair* test_ruleset_pair) {
  DCHECK(test_ruleset_pair);

  std::vector<proto::UrlRule> rules;
  for (int i = 0; i < num_of_suffixes; ++i) {
    std::string current_suffix =
        std::string(suffix) + '_' + base::NumberToString(i);
    rules.push_back(CreateSuffixRule(current_suffix));
  }
  CreateRulesetWithRules(rules, test_ruleset_pair);
}

void TestRulesetCreator::CreateRulesetWithRules(
    const std::vector<proto::UrlRule>& rules,
    TestRulesetPair* test_ruleset_pair) {
  ASSERT_NO_FATAL_FAILURE(CreateTestRulesetFromContents(
      SerializeUnindexedRulesetWithMultipleRules(rules),
      &test_ruleset_pair->unindexed));
  ASSERT_NO_FATAL_FAILURE(CreateTestRulesetFromContents(
      SerializeIndexedRulesetWithMultipleRules(rules),
      &test_ruleset_pair->indexed));
}

void TestRulesetCreator::CreateUnindexedRulesetWithRules(
    const std::vector<proto::UrlRule>& rules,
    TestRuleset* test_unindexed_ruleset) {
  ASSERT_NO_FATAL_FAILURE(CreateTestRulesetFromContents(
      SerializeUnindexedRulesetWithMultipleRules(rules),
      test_unindexed_ruleset));
}

void TestRulesetCreator::GetUniqueTemporaryPath(base::FilePath* path) {
  DCHECK(path);
  base::ScopedAllowBlockingForTesting allow_blocking;
  ASSERT_TRUE(scoped_temp_dir_->IsValid() ||
              scoped_temp_dir_->CreateUniqueTempDir());
  *path = scoped_temp_dir_->GetPath().AppendASCII(
      base::NumberToString(next_unique_file_suffix++));
}

void TestRulesetCreator::CreateTestRulesetFromContents(
    std::vector<uint8_t> ruleset_contents,
    TestRuleset* ruleset) {
  DCHECK(ruleset);

  ruleset->contents = std::move(ruleset_contents);
  ASSERT_NO_FATAL_FAILURE(GetUniqueTemporaryPath(&ruleset->path));
  WriteRulesetContents(ruleset->contents, ruleset->path);
}

}  // namespace testing
}  // namespace subresource_filter


text:
require 'test_helper'

class InstituicaoTest < ActiveSupport::TestCase
  # test "the truth" do
  #   assert true
  # end
end


text:
package server

import (
	"net/http"
	"path/filepath"
)

var mimeTypes = map[string]string{
	".js":  "application/javascript",
	".css": "text/css",
	".png": "image/png",
	".jpg": "image/jpeg",
	".gif": "image/gif",
}

func StaticFileServer(root http.FileSystem) http.Handler {
	return http.HandlerFunc(
		func(w http.ResponseWriter, r *http.Request) {
			fileExt := filepath.Ext(r.URL.Path)

			if t, ok := mimeTypes[fileExt]; ok {
				w.Header().Set("Content-Type", t)
			}

			http.FileServer(root).ServeHTTP(w, r)
		},
	)
}


text:
<!DOCTYPE html>

    <meta charset="utf-8" />
    <meta name="format-detection" content="telephone=no" />
    <meta name="msapplication-tap-highlight" content="no" />
    <meta name="viewport" content="user-scalable=no, initial-scale=1, maximum-scale=1, minimum-scale=1, width=device-width, height=device-height" />

    <link rel="stylesheet" type="text/css" href="css/index.css" />
    <link rel="stylesheet" href="http://code.jquery.com/mobile/1.4.5/jquery.mobile-1.4.5.min.css" />
    <link href="https://fonts.googleapis.com/css?family=Varela+Round" rel="stylesheet">

    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.2.0/css/bootstrap.min.css">
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.2.0/css/bootstrap-theme.min.css">

  <title>get_to_know</title>

← Get to know

Lesson 1/4

In this lesson
you will learn
 how to
 get to know a Finn

Length of the lesson: 2 min

Lesson 2/4

In this lesson
you will learn
 how to
 get to know a Finn

Length of the lesson: 2 min

Lesson 3/4

Sorry! this features is
 coming soon.

Lesson 4/4

Sorry! this features is
 coming soon.

       ×

       <progress value="0.5" max="100" id="p0" class="progress" ></progress>

Stereotype of a Finn is silent introvert that's keeping his head down in shame.

They got it all wrong.

Because of the harsh weather conditions, we don't have the luxury to gather in cafes and parks and socialize.

But Finns can be open, friendly and very humorous.
They just need some more time
to get started and get to know you. Or booze.
That will change everything.

Finns do love their personal space.
In fact, they would rather stand while riding a bus than sit with another person close to them.

Finns place great value on words and they avoid 'unnecessary' small talk.
That doesn't mean they are rude.

If you promise something to a Finn, you should do that with no excuse,  or you will lose person's respect.

So mean what you say.

  <audio id="audio_click" src="img/pickup.wav" ></audio>

Even they may seem shy,
 they actually like to talk and help foreigners.

Get to know a Finn

  Congratulations! You are now 6% finn!

       ×

       <progress value="0.5" max="100" id="p1" class="progressbar0" ></progress>

Gender equality has always been important in Finland.

      It's the first country in the world to give women both the right to vote and stand for election.

Finns are law-abinding.
 If the traffic light for pedestrians is red but there are no vehicles, Finns still wait for the green light.

Finns stick to rules and laws. They are the 'Apt pupils of EU'.
 So if you don't want to stick out, wait for the green light.

Finns dress super-casual. Wearing sneakers and jeans in work or about anywhere is OK.
Suit or fancy dress is for weddings and funerals.

The main color in clothing is black.

And in music.

when they use some color in their shell suits (tuulipuku), well…

Let's say that Finns don't get to be in cover of Vogue that often.

  <audio id="audio_click" src="img/pickup.wav" ></audio>

Finns are not afraid to take their clothes off.
Wether it's in sauna, locker room or sometimes even the streets  (nude run is called "Viuhahdus"), Finns feel comfortable when naked.

Get to know a Finn

  Congratulations! You are now 8% finn!


text:
package com.opengamma.core.position.impl;

import static org.testng.AssertJUnit.assertEquals;
import static org.testng.AssertJUnit.assertFalse;
import static org.testng.AssertJUnit.assertNull;
import static org.testng.AssertJUnit.assertSame;
import static org.testng.AssertJUnit.assertTrue;

import java.math.BigDecimal;

import org.testng.annotations.Test;
import org.threeten.bp.OffsetDateTime;

import com.google.common.collect.Lists;
import com.opengamma.core.position.Counterparty;
import com.opengamma.core.security.Security;
import com.opengamma.core.security.SecurityLink;
import com.opengamma.core.security.impl.SimpleSecurity;
import com.opengamma.core.security.impl.SimpleSecurityLink;
import com.opengamma.id.ExternalId;
import com.opengamma.id.ExternalIdBundle;
import com.opengamma.id.UniqueId;
import com.opengamma.util.test.TestGroup;

/**
 * Test {@link SimplePosition}.
 */
@Test(groups = TestGroup.UNIT)
public class SimplePositionTest {

  private static final Counterparty COUNTERPARTY = new SimpleCounterparty(ExternalId.of("CPARTY", "C100"));
  private static final OffsetDateTime TRADE_OFFSET_DATETIME = OffsetDateTime.now();

  public void test_construction_BigDecimal_ExternalId() {
    SimplePosition test = new SimplePosition(BigDecimal.ONE, ExternalId.of("A", "B"));
    assertEquals(null, test.getUniqueId());
    assertEquals(BigDecimal.ONE, test.getQuantity());
    assertEquals(1, test.getSecurityLink().getExternalId().size());
    assertEquals(ExternalId.of("A", "B"), test.getSecurityLink().getExternalId().iterator().next());
    assertEquals("Position[, 1 Bundle[A~B]]", test.toString());
  }

  @Test(expectedExceptions=IllegalArgumentException.class)
  public void test_construction_BigDecimal_ExternalId_nullBigDecimal() {
    new SimplePosition(null, ExternalId.of("A", "B"));
  }

  @Test(expectedExceptions=IllegalArgumentException.class)
  public void test_construction_BigDecimal_ExternalId_nullExternalId() {
    new SimplePosition(BigDecimal.ONE, (ExternalId) null);
  }

  //-------------------------------------------------------------------------
  public void test_construction_BigDecimal_ExternalIdBundle() {
    SimplePosition test = new SimplePosition(BigDecimal.ONE, ExternalIdBundle.of(ExternalId.of("A", "B")));
    assertEquals(null, test.getUniqueId());
    assertEquals(BigDecimal.ONE, test.getQuantity());
    assertEquals(1, test.getSecurityLink().getExternalId().size());
    assertEquals(ExternalId.of("A", "B"), test.getSecurityLink().getExternalId().iterator().next());
    assertEquals("Position[, 1 Bundle[A~B]]", test.toString());
  }

  @Test(expectedExceptions=IllegalArgumentException.class)
  public void test_construction_BigDecimal_ExternalIdBundle_nullBigDecimal() {
    new SimplePosition(null, ExternalIdBundle.of(ExternalId.of("A", "B")));
  }

  @Test(expectedExceptions=IllegalArgumentException.class)
  public void test_construction_BigDecimal_ExternalIdBundle_nullExternalId() {
    new SimplePosition(BigDecimal.ONE, (ExternalIdBundle) null);
  }

  //-------------------------------------------------------------------------
  public void test_construction_UniqueId_BigDecimal_ExternalId() {
    SimplePosition test = new SimplePosition(UniqueId.of("B", "C"), BigDecimal.ONE, ExternalId.of("A", "B"));
    assertEquals(UniqueId.of("B", "C"), test.getUniqueId());
    assertEquals(BigDecimal.ONE, test.getQuantity());
    assertEquals(1, test.getSecurityLink().getExternalId().size());
    assertEquals(ExternalId.of("A", "B"), test.getSecurityLink().getExternalId().iterator().next());
    assertEquals("Position[B~C, 1 Bundle[A~B]]", test.toString());
  }

  @Test(expectedExceptions=IllegalArgumentException.class)
  public void test_construction_UniqueId_BigDecimal_ExternalId_nullUniqueId() {
    new SimplePosition(null, BigDecimal.ONE, ExternalId.of("A", "B"));
  }

  @Test(expectedExceptions=IllegalArgumentException.class)
  public void test_construction_UniqueId_BigDecimal_ExternalId_nullBigDecimal() {
    new SimplePosition(UniqueId.of("B", "C"), null, ExternalId.of("A", "B"));
  }

  @Test(expectedExceptions=IllegalArgumentException.class)
  public void test_construction_UniqueId_BigDecimal_ExternalId_nullExternalId() {
    new SimplePosition(UniqueId.of("B", "C"), BigDecimal.ONE, (ExternalId) null);
  }

  //-------------------------------------------------------------------------
  public void test_construction_UniqueId_BigDecimal_ExternalIdBundle() {
    SimplePosition test = new SimplePosition(UniqueId.of("B", "C"), BigDecimal.ONE, ExternalIdBundle.of(ExternalId.of("A", "B")));
    assertEquals(UniqueId.of("B", "C"), test.getUniqueId());
    assertEquals(BigDecimal.ONE, test.getQuantity());
    assertEquals(1, test.getSecurityLink().getExternalId().size());
    assertEquals(ExternalId.of("A", "B"), test.getSecurityLink().getExternalId().iterator().next());
    assertEquals("Position[B~C, 1 Bundle[A~B]]", test.toString());
  }

  @Test(expectedExceptions=IllegalArgumentException.class)
  public void test_construction_UniqueId_BigDecimal_ExternalIdBundle_nullUniqueId() {
    new SimplePosition(null, BigDecimal.ONE, ExternalId.of("A", "B"));
  }

  @Test(expectedExceptions=IllegalArgumentException.class)
  public void test_construction_UniqueId_BigDecimal_ExternalIdBundle_nullBigDecimal() {
    new SimplePosition(UniqueId.of("B", "C"), null, ExternalIdBundle.of(ExternalId.of("A", "B")));
  }

  @Test(expectedExceptions=IllegalArgumentException.class)
  public void test_construction_UniqueId_BigDecimal_ExternalIdBundle_nullExternalIdBundle() {
    new SimplePosition(UniqueId.of("B", "C"), BigDecimal.ONE, (ExternalIdBundle) null);
  }

  //-------------------------------------------------------------------------
  public void test_construction_UniqueId_BigDecimal_Security() {
    SimpleSecurity sec = new SimpleSecurity("A");
    sec.setExternalIdBundle(ExternalIdBundle.of(ExternalId.of("A", "B")));
    SimplePosition test = new SimplePosition(UniqueId.of("B", "C"), BigDecimal.ONE, sec);
    assertEquals(UniqueId.of("B", "C"), test.getUniqueId());
    assertEquals(BigDecimal.ONE, test.getQuantity());
    assertEquals(1, test.getSecurityLink().getExternalId().size());
    assertEquals(ExternalId.of("A", "B"), test.getSecurityLink().getExternalId().iterator().next());
    assertEquals(true, test.toString().startsWith("Position[B~C, 1"));
  }

  @Test(expectedExceptions=IllegalArgumentException.class)
  public void test_construction_UniqueId_BigDecimal_Security_nullUniqueId() {
    new SimplePosition(null, BigDecimal.ONE, ExternalId.of("A", "B"));
  }

  @Test(expectedExceptions=IllegalArgumentException.class)
  public void test_construction_UniqueId_BigDecimal_Security_nullBigDecimal() {
    new SimplePosition(UniqueId.of("B", "C"), null, ExternalIdBundle.of(ExternalId.of("A", "B")));
  }

  @Test(expectedExceptions=IllegalArgumentException.class)
  public void test_construction_UniqueId_BigDecimal_Security_nullSecurity() {
    new SimplePosition(UniqueId.of("B", "C"), BigDecimal.ONE, (Security) null);
  }

  public void test_construction_copyFromPosition() {
    SimplePosition position = new SimplePosition(UniqueId.of("B", "C"), BigDecimal.ONE, ExternalId.of("A", "B"));
    position.addAttribute("A", "B");
    position.addAttribute("C", "D");

    SimplePosition copy = new SimplePosition(position);
    assertEquals(copy, position);
  }

  //-------------------------------------------------------------------------
  public void test_setUniqueId() {
    SimplePosition test = new SimplePosition(UniqueId.of("B", "C"), BigDecimal.ONE, ExternalId.of("A", "B"));
    test.setUniqueId(UniqueId.of("B", "D"));
    assertEquals(UniqueId.of("B", "D"), test.getUniqueId());
  }

  @Test(expectedExceptions=IllegalArgumentException.class)
  public void test_setUniqueId_null() {
    SimplePosition test = new SimplePosition(UniqueId.of("B", "C"), BigDecimal.ONE, ExternalId.of("A", "B"));
    test.setUniqueId(null);
  }

  //-------------------------------------------------------------------------
  public void test_setQuantity() {
    SimplePosition test = new SimplePosition(UniqueId.of("B", "C"), BigDecimal.ONE, ExternalId.of("A", "B"));
    test.setQuantity(BigDecimal.ZERO);
    assertSame(BigDecimal.ZERO, test.getQuantity());
  }

  @Test(expectedExceptions=IllegalArgumentException.class)
  public void test_setQuantity_null() {
    SimplePosition test = new SimplePosition(UniqueId.of("B", "C"), BigDecimal.ONE, ExternalId.of("A", "B"));
    test.setQuantity(null);
  }

  //-------------------------------------------------------------------------
  public void test_setSecurityLink() {
    SimplePosition test = new SimplePosition(UniqueId.of("B", "C"), BigDecimal.ONE, ExternalId.of("A", "B"));
    test.setSecurityLink(new SimpleSecurityLink());
    assertEquals(new SimpleSecurityLink(), test.getSecurityLink());
  }

  @Test(expectedExceptions=IllegalArgumentException.class)
  public void test_setSecurityKey_null() {
    SimplePosition test = new SimplePosition(UniqueId.of("B", "C"), BigDecimal.ONE, ExternalId.of("A", "B"));
    test.setSecurityLink(null);
  }

  //-------------------------------------------------------------------------
  public void test_addTrade() {
    SimplePosition testPosition = new SimplePosition(UniqueId.of("B", "C"), BigDecimal.ONE, ExternalId.of("A", "B"));
    assertTrue(testPosition.getTrades().isEmpty());
    SimpleTrade testTrade1 = new SimpleTrade(createLink("A", "B"), BigDecimal.ONE, COUNTERPARTY, TRADE_OFFSET_DATETIME.toLocalDate(), TRADE_OFFSET_DATETIME.toOffsetTime());
    testPosition.addTrade(testTrade1);

    SimpleTrade testTrade2 = new SimpleTrade(createLink("C", "D"), BigDecimal.ONE, COUNTERPARTY, TRADE_OFFSET_DATETIME.toLocalDate(), TRADE_OFFSET_DATETIME.toOffsetTime());
    testPosition.addTrade(testTrade2);

    assertEquals(2, testPosition.getTrades().size());
    assertTrue(testPosition.getTrades().containsAll(Lists.newArrayList(testTrade1, testTrade2)));
  }

  @Test(expectedExceptions=IllegalArgumentException.class)
  public void test_addTrade_null() {
    SimplePosition test = new SimplePosition(UniqueId.of("B", "C"), BigDecimal.ONE, ExternalId.of("A", "B"));
    test.addTrade(null);
  }

  //-------------------------------------------------------------------------
  public void test_removeTrade() {
    SimplePosition testPosition = new SimplePosition(UniqueId.of("B", "C"), BigDecimal.ONE, ExternalId.of("A", "B"));
    assertTrue(testPosition.getTrades().isEmpty());
    SimpleTrade testTrade1 = new SimpleTrade(createLink("A", "B"), BigDecimal.ONE, COUNTERPARTY, TRADE_OFFSET_DATETIME.toLocalDate(), TRADE_OFFSET_DATETIME.toOffsetTime());
    testPosition.addTrade(testTrade1);
    SimpleTrade testTrade2 = new SimpleTrade(createLink("C", "D"), BigDecimal.ONE, COUNTERPARTY, TRADE_OFFSET_DATETIME.toLocalDate(), TRADE_OFFSET_DATETIME.toOffsetTime());
    testPosition.addTrade(testTrade2);

    SimpleTrade testTrade3 = new SimpleTrade(createLink("E", "F"), BigDecimal.ONE, COUNTERPARTY, TRADE_OFFSET_DATETIME.toLocalDate(), TRADE_OFFSET_DATETIME.toOffsetTime());

    assertTrue(testPosition.removeTrade(testTrade1));
    assertTrue(testPosition.removeTrade(testTrade2));
    assertFalse(testPosition.removeTrade(testTrade3));
    assertTrue(testPosition.getTrades().isEmpty());
  }

  //------------------------------------------------------------------------
  @Test(expectedExceptions=IllegalArgumentException.class)
  public void test_addAttribute_null_key() {
    SimplePosition testPosition = new SimplePosition(UniqueId.of("B", "C"), BigDecimal.ONE, ExternalId.of("A", "B"));
    assertTrue(testPosition.getAttributes().isEmpty());
    testPosition.addAttribute(null, "B");
  }

  @Test(expectedExceptions=IllegalArgumentException.class)
  public void test_addAttribute_null_value() {
    SimplePosition testPosition = new SimplePosition(UniqueId.of("B", "C"), BigDecimal.ONE, ExternalId.of("A", "B"));
    assertTrue(testPosition.getAttributes().isEmpty());
    testPosition.addAttribute("A", null);
  }

  public void test_addAttribute() {
    SimplePosition testPosition = new SimplePosition(UniqueId.of("B", "C"), BigDecimal.ONE, ExternalId.of("A", "B"));
    assertTrue(testPosition.getAttributes().isEmpty());
    testPosition.addAttribute("A", "B");
    assertEquals(1, testPosition.getAttributes().size());
    assertEquals("B", testPosition.getAttributes().get("A"));
    testPosition.addAttribute("C", "D");
    assertEquals(2, testPosition.getAttributes().size());
    assertEquals("D", testPosition.getAttributes().get("C"));
  }

  public void test_removeAttribute() {
    SimplePosition testPosition = new SimplePosition(UniqueId.of("B", "C"), BigDecimal.ONE, ExternalId.of("A", "B"));
    assertTrue(testPosition.getAttributes().isEmpty());
    testPosition.addAttribute("A", "B");
    testPosition.addAttribute("C", "D");
    assertEquals(2, testPosition.getAttributes().size());
    testPosition.removeAttribute("A");
    assertEquals(1, testPosition.getAttributes().size());
    assertNull(testPosition.getAttributes().get("A"));
  }

  private SecurityLink createLink(String scheme, String value) {
    return new SimpleSecurityLink(ExternalId.of(scheme, value));
  }

}


text:
/* @flow */

import {execSync} from 'child_process';
import {randomBytes} from 'crypto';
import {tmpdir} from 'os';
import {basename, dirname, extname, join} from 'path';
import {format} from 'util';

import {appendFile, exec, execManual, mkdirp, readdir, readFile, writeFile} from '../async';
import {testsDir} from '../constants';

type CheckCommand = 'check' | 'status';

export class TestBuilder {
  bin: string;
  dir: string;
  errorCheckCommand: CheckCommand;
  flowConfigFilename: string;
  server: ?number;
  sourceDir: string;
  suiteName: string;
  tmpDir: string;

  constructor(
    bin: string,
    errorCheckCommand: CheckCommand,
    baseDir: string,
    suiteName: string,
    testNum: number,
    flowConfigFilename: string,
  ) {
    this.bin = bin;
    this.errorCheckCommand = errorCheckCommand;
    this.suiteName = suiteName;
    this.dir = join(
      baseDir,
      suiteName.replace("/", "zS"),
      String(testNum),
    );
    this.sourceDir = join(
      testsDir,
      suiteName
    );
    this.tmpDir = join(
      baseDir,
      suiteName.replace("/", "zS"),
      "tmp",
      String(testNum),
    );
    this.flowConfigFilename = flowConfigFilename;
  }

  getFileName(): string {
    return join(this.dir, 'test.js');
  }

  async createFreshDir(): Promise<void> {
    await mkdirp(this.dir);
    await mkdirp(this.tmpDir);

    let configBuffer = null;
    const files = await readdir(this.sourceDir);
    for (const file of files) {
      if (basename(file) === this.flowConfigFilename) {
        configBuffer = await readFile(join(this.sourceDir, file));
      }
    }

    // We need to set the temp_dir option in the config. If there is no config,
    // that is easy. Otherwise we need to read the config. If temp_dir is
    // already set, then we default to that. Otherwise, we need to set it.
    if (configBuffer != null) {
      let config = configBuffer.toString().split("\n");
      let temp_dir = null;
      let options_index = null;
      config.forEach((line, index) => {
        const match = line.trim().match("^temp_dir=(.*)$");
        match != null && (temp_dir = match[1])
        line.trim() == "[options]" && (options_index = index);
      });

      if (temp_dir == null) {
        if (options_index == null) {
          config.push("[options]");
          options_index = config.length - 1;
        }
        config.splice(options_index + 1, 0, "temp_dir=" + this.tmpDir);
      } else {
        this.tmpDir = temp_dir;
      }
      await writeFile(join(this.dir, ".flowconfig"), config.join("\n"));
    } else {
      await exec(
        format(
          "%s init --options 'all=true;temp_dir=%s' %s",
          this.bin,
          this.tmpDir,
          this.dir,
        ),
        {cwd: __dirname},
      );
    }
    await writeFile(this.getFileName(), "/* @flow */\n");
  }

  async addCode(code: string): Promise<void> {
    await appendFile(this.getFileName(), "\n"+code+"\n");
  }

  async addFile(source: string, dest: string): Promise<void> {
    source = join(this.sourceDir, source);
    dest = join(this.dir, dest);
    const contents_buffer = await readFile(source);
    let contents = contents_buffer.toString();
    if (contents.match(/@thisWillBeFlowInTest/)) {
      // Undo what the convert command did
      contents = contents.replace(/@thisWillBeFlowInTest/, "@flow");
    }
    await mkdirp(dirname(dest));
    await writeFile(dest, contents);
  }

  async addFiles(sources: Array<string>): Promise<void> {
    await Promise.all(
      sources.map(source => this.addFile(source, source))
    );
  }

  async flowCmd(args: Array<string>, stdinFile?: string): Promise<[number, string, string]> {
    let cmd = format(
      "%s %s %s",
      this.bin,
      args.map(arg => format('"%s"', arg)).join(" "),
      stdinFile == null ? "" : format("< %s", stdinFile),
    );
    const [err, stdout, stderr] = await execManual(cmd, {cwd: this.dir});
    const code = err == null ? 0 : err.code;

    return [code, stdout.toString(), stderr.toString()];
  }

  async getFlowErrors(retry?: bool = true): Promise<Object> {
    let cmd;
    if (this.errorCheckCommand === 'check') {
      cmd = format(
        "%s check --strip-root --temp-dir %s --json %s",
        this.bin,
        this.tmpDir,
        this.dir,
      );
    } else {
      // No-op if it's already running
      await this.startFlowServer();
      cmd = format(
        "%s status --no-auto-start --strip-root --temp-dir %s --json %s",
        this.bin,
        this.tmpDir,
        this.dir,
      );
    }

    const [err, stdout, stderr] = await execManual(cmd, {cwd: __dirname});

    // 0 - no errors
    // 2 - Some errors
    if (err == null || err.code === 2) {
      return JSON.parse(stdout.toString());
    }

    throw new Error(format('Flow check failed!', err, stdout, stderr));
  }

  async startFlowServer(): Promise<void> {
    const [err, stdout, stderr] = await execManual(format(
      "%s start --json --strip-root --temp-dir %s --wait %s",
      this.bin,
      this.tmpDir,
      this.dir,
    ));

    if (!err) {
      const response = JSON.parse(stdout.toString());
      this.server = response.pid;
    } else if (err.code === 11) {
      // Already a server running...that's cool
    } else {
      throw new Error(format('Flow start failed!', err, stdout, stderr));
    }
  }

  async stopFlowServer(): Promise<void> {
    const server = this.server;
    if (server != null ) {
      this.server = null;
      const [err, stdout, stderr] = await execManual(format(
        "%s stop %s",
        this.bin,
        this.dir,
      ));

      if (err != null) {
        try {
          process.kill(server);
        } catch (e) {
          console.log("Failed to kill server %s", server);
        }
      }
    }
  }

  stopFlowServerSync(): void {
    const server = this.server;
    if (server != null) {
      this.server = null;
      try {
        execSync(format("%s stop %s", this.bin, this.dir));
      } catch (e) {
        try {
          process.kill(server);
        } catch (e) {
          console.log("Failed to kill server %s", server);
        }
      }
    }
  }
}

export default class Builder {
  dir: string;
  errorCheckCommand: CheckCommand;

  static builders: Array<TestBuilder> = [];

  constructor(errorCheckCommand: CheckCommand) {
    this.errorCheckCommand = errorCheckCommand;
    const id = randomBytes(5).toString('hex');
    this.dir = join(tmpdir(), 'fbcode/flow/tests', id);
    process.stderr.write(format("Tests will be built in %s\n", this.dir));

    // If something weird happens, lets make sure to stop all the flow servers
    // we started
    process.on('exit', () => {
      Builder.builders.forEach(builder => builder.stopFlowServerSync());
    });
  }

  async createFreshTest(
    bin: string,
    suiteName: string,
    testNum: number,
    flowConfigFilename: string,
  ): Promise<TestBuilder> {
    const testBuilder = new TestBuilder(
      bin,
      this.errorCheckCommand,
      this.dir,
      suiteName,
      testNum,
      flowConfigFilename,
    );
    Builder.builders.push(testBuilder);
    await testBuilder.createFreshDir(suiteName);
    return testBuilder;
  }
}


text:
package com.endusersoft.svnconverter.model.drawing;

/**
 * Created by Oblio.Leitch on 2/15/14.
 */
public abstract class AbstractKhanObject {

    public abstract String toString();

    static String fmt(double d) {
        if (d == (int) d)
            return String.format("%d", (int) d);
        else
            return String.format("%s", d);
    }
}


text:
var split$ = ''.split;
module.exports = function(LiveScript){
  var fs, path;
  fs = require('fs');
  path = require('path');
  LiveScript.run = function(code, options, js){
    var filename, main, dirname, ref$, e;
    if (options != null) {
      filename = options.filename;
    }
    main = require.main;
    if (filename) {
      dirname = path.dirname(fs.realpathSync(filename = process.argv[1] = path.resolve(filename)));
    } else {
      dirname = filename = '.';
    }
    main.paths = main.constructor._nodeModulePaths(dirname);
    main.filename = filename;
    js || (code = LiveScript.compile(code, (ref$ = {}, import$(ref$, options), ref$.bare = true, ref$)));
    try {
      return main._compile(code, filename);
    } catch (e$) {
      e = e$;
      throw hackTrace(e, code, filename);
    }
  };
  importAll$(LiveScript, require('events').EventEmitter.prototype);
  require.extensions['.ls'] = function(module, filename){
    var js, e;
    js = LiveScript.compile(fs.readFileSync(filename, 'utf8'), {
      filename: filename,
      bare: true
    });
    try {
      return module._compile(js, filename);
    } catch (e$) {
      e = e$;
      throw hackTrace(e, js, filename);
    }
  };
};
function hackTrace(error, js, filename){
  var stack, traces, i, len$, trace, index, lno, end, length, lines, n, ref$;
  if (error != null) {
    stack = error.stack;
  }
  if (!stack) {
    return error;
  }
  traces = split$.call(stack, '\n');
  if (!(traces.length > 1)) {
    return error;
  }
  for (i = 0, len$ = traces.length; i < len$; ++i) {
    trace = traces[i];
    if (0 > (index = trace.indexOf("(" + filename + ":"))) {
      continue;
    }
    lno = (/:(\d+):/.exec(trace.slice(index + filename.length)) || '')[1];
    if (!(lno = +lno)) {
      continue;
    }
    length = ('' + (end = lno + 4)).length;
    lines || (lines = split$.call(js, '\n'));
    for (n = 1 > (ref$ = lno - 4) ? 1 : ref$; n <= end; ++n) {
      traces[i] += "\n" + ('    ' + n).slice(-length) + "" + '|+'.charAt(n === lno) + " " + [lines[n - 1]];
    }
  }
  return error.stack = traces.join('\n'), error;
}
function import$(obj, src){
  var own = {}.hasOwnProperty;
  for (var key in src) if (own.call(src, key)) obj[key] = src[key];
  return obj;
}
function importAll$(obj, src){
  for (var key in src) obj[key] = src[key];
  return obj;
}


text:
'use strict';

var asyncreduce = require('asyncreduce')
  , resolveBin = require('resolve-bin')
  , spawn = require('child_process').spawn
  , format = require('util').format
  , PORT = 5557

function getZuluPort(args) {
  var local = args.indexOf('--local');

  // pick default port and insert it into zuul args if none was provided
  if (!~local) {
    args.unshift(PORT);
    args.unshift('--local');
    return PORT;
  }
  return args[local + 1];
}

function resolveBins(names, cb) {
  asyncreduce(
      names
    , {}
    , function (acc, name, cb_) {
        resolveBin(name, function (err, dir) {
          if (err) return cb_(err);
          acc[name] = dir;
          cb_(null, acc);
        });
      }
    , cb
  )
}

function run(bin, args, cwd, cb) {
  var prog = spawn(
      bin
    , args
    , { cwd: cwd }
  )

  prog.stdout.pipe(process.stdout);
  prog.stderr.pipe(process.stderr);

  prog.on('close', function (code) {
    if (code !== 0) return cb(new Error('prog ' + args.join(' ') + ' returned with code ' + code), code);
    cb(null, code);
  })

  return prog;
}

/**
 * Starts up a zuul server and runs mocha-phantomjs against it.
 *
 * @name zuulmp
 * @function
 * @param {Array.<String>} args arguments passed to zuul and phantomjs
 * @param {String} cwd working directory to be used for zuul and mocha-phantomjs
 * @param {Function(Error, Number)} cb called back with eventual error and the exit code (0 if all went good)
 */
var go = module.exports = function (args, cwd, cb) {
  var port = getZuluPort(args);
  if (!port) return cb(new Error('Please provide a port for the zulu server, i.e. --local 3000'), -1);

  var route = format('http://localhost:%d/__zuul', port);

  resolveBins([ 'zuul', 'mocha-phantomjs'], function (err, bins) {
    if (err) return cb(err);

    var zuul = run(bins.zuul, args, cwd, function (err, code) {
      if (err) return cb(err, code);
    });

    // wait for zuul to start up and tell us to point our browser at the url
    zuul.stdout.once('data', function () {
      run(bins['mocha-phantomjs'], [route].concat(args), cwd, function (err, code) {
        zuul.kill();
        cb(err, code);
      });
    });
  });
};