text:
""" test the scalar Timestamp """

import calendar
from datetime import (
    datetime,
    timedelta,
)
import locale
import unicodedata

from dateutil.tz import tzutc
import numpy as np
import pytest
import pytz
from pytz import (
    timezone,
    utc,
)

from pandas._libs.tslibs.dtypes import NpyDatetimeUnit
from pandas._libs.tslibs.timezones import (
    dateutil_gettz as gettz,
    get_timezone,
    maybe_get_tz,
    tz_compare,
)
from pandas.errors import OutOfBoundsDatetime
import pandas.util._test_decorators as td

from pandas import (
    NaT,
    Timedelta,
    Timestamp,
)
import pandas._testing as tm

from pandas.tseries import offsets
from pandas.tseries.frequencies import to_offset

class TestTimestampProperties:
    def test_properties_business(self):
        freq = to_offset("B")

        ts = Timestamp("2017-10-01")
        assert ts.dayofweek == 6
        assert ts.day_of_week == 6
        assert ts.is_month_start  # not a weekday
        assert not freq.is_month_start(ts)
        assert freq.is_month_start(ts + Timedelta(days=1))
        assert not freq.is_quarter_start(ts)
        assert freq.is_quarter_start(ts + Timedelta(days=1))

        ts = Timestamp("2017-09-30")
        assert ts.dayofweek == 5
        assert ts.day_of_week == 5
        assert ts.is_month_end
        assert not freq.is_month_end(ts)
        assert freq.is_month_end(ts - Timedelta(days=1))
        assert ts.is_quarter_end
        assert not freq.is_quarter_end(ts)
        assert freq.is_quarter_end(ts - Timedelta(days=1))

    @pytest.mark.parametrize(
        "attr, expected",
        [
            ["year", 2014],
            ["month", 12],
            ["day", 31],
            ["hour", 23],
            ["minute", 59],
            ["second", 0],
            ["microsecond", 0],
            ["nanosecond", 0],
            ["dayofweek", 2],
            ["day_of_week", 2],
            ["quarter", 4],
            ["dayofyear", 365],
            ["day_of_year", 365],
            ["week", 1],
            ["daysinmonth", 31],
        ],
    )
    @pytest.mark.parametrize("tz", [None, "US/Eastern"])
    def test_fields(self, attr, expected, tz):
        # GH 10050
        # GH 13303
        ts = Timestamp("2014-12-31 23:59:00", tz=tz)
        result = getattr(ts, attr)
        # that we are int like
        assert isinstance(result, int)
        assert result == expected

    @pytest.mark.parametrize("tz", [None, "US/Eastern"])
    def test_millisecond_raises(self, tz):
        ts = Timestamp("2014-12-31 23:59:00", tz=tz)
        msg = "'Timestamp' object has no attribute 'millisecond'"
        with pytest.raises(AttributeError, match=msg):
            ts.millisecond

    @pytest.mark.parametrize(
        "start", ["is_month_start", "is_quarter_start", "is_year_start"]
    )
    @pytest.mark.parametrize("tz", [None, "US/Eastern"])
    def test_is_start(self, start, tz):
        ts = Timestamp("2014-01-01 00:00:00", tz=tz)
        assert getattr(ts, start)

    @pytest.mark.parametrize("end", ["is_month_end", "is_year_end", "is_quarter_end"])
    @pytest.mark.parametrize("tz", [None, "US/Eastern"])
    def test_is_end(self, end, tz):
        ts = Timestamp("2014-12-31 23:59:59", tz=tz)
        assert getattr(ts, end)

    # GH 12806
    @pytest.mark.parametrize(
        "data",
        [Timestamp("2017-08-28 23:00:00"), Timestamp("2017-08-28 23:00:00", tz="EST")],
    )
    # error: Unsupported operand types for + ("List[None]" and "List[str]")
    @pytest.mark.parametrize(
        "time_locale", [None] + tm.get_locales()  # type: ignore[operator]
    )
    def test_names(self, data, time_locale):
        # GH 17354
        # Test .day_name(), .month_name
        if time_locale is None:
            expected_day = "Monday"
            expected_month = "August"
        else:
            with tm.set_locale(time_locale, locale.LC_TIME):
                expected_day = calendar.day_name[0].capitalize()
                expected_month = calendar.month_name[8].capitalize()

        result_day = data.day_name(time_locale)
        result_month = data.month_name(time_locale)

        # Work around https://github.com/pandas-dev/pandas/issues/22342
        # different normalizations
        expected_day = unicodedata.normalize("NFD", expected_day)
        expected_month = unicodedata.normalize("NFD", expected_month)

        result_day = unicodedata.normalize("NFD", result_day)
        result_month = unicodedata.normalize("NFD", result_month)

        assert result_day == expected_day
        assert result_month == expected_month

        # Test NaT
        nan_ts = Timestamp(NaT)
        assert np.isnan(nan_ts.day_name(time_locale))
        assert np.isnan(nan_ts.month_name(time_locale))

    def test_is_leap_year(self, tz_naive_fixture):
        tz = tz_naive_fixture
        # GH 13727
        dt = Timestamp("2000-01-01 00:00:00", tz=tz)
        assert dt.is_leap_year
        assert isinstance(dt.is_leap_year, bool)

        dt = Timestamp("1999-01-01 00:00:00", tz=tz)
        assert not dt.is_leap_year

        dt = Timestamp("2004-01-01 00:00:00", tz=tz)
        assert dt.is_leap_year

        dt = Timestamp("2100-01-01 00:00:00", tz=tz)
        assert not dt.is_leap_year

    def test_woy_boundary(self):
        # make sure weeks at year boundaries are correct
        d = datetime(2013, 12, 31)
        result = Timestamp(d).week
        expected = 1  # ISO standard
        assert result == expected

        d = datetime(2008, 12, 28)
        result = Timestamp(d).week
        expected = 52  # ISO standard
        assert result == expected

        d = datetime(2009, 12, 31)
        result = Timestamp(d).week
        expected = 53  # ISO standard
        assert result == expected

        d = datetime(2010, 1, 1)
        result = Timestamp(d).week
        expected = 53  # ISO standard
        assert result == expected

        d = datetime(2010, 1, 3)
        result = Timestamp(d).week
        expected = 53  # ISO standard
        assert result == expected

        result = np.array(
            [
                Timestamp(datetime(*args)).week
                for args in [(2000, 1, 1), (2000, 1, 2), (2005, 1, 1), (2005, 1, 2)]
            ]
        )
        assert (result == [52, 52, 53, 53]).all()

    def test_resolution(self):
        # GH#21336, GH#21365
        dt = Timestamp("2100-01-01 00:00:00")
        assert dt.resolution == Timedelta(nanoseconds=1)

        # Check that the attribute is available on the class, mirroring
        #  the stdlib datetime behavior
        assert Timestamp.resolution == Timedelta(nanoseconds=1)

class TestTimestamp:
    def test_tz(self):
        tstr = "2014-02-01 09:00"
        ts = Timestamp(tstr)
        local = ts.tz_localize("Asia/Tokyo")
        assert local.hour == 9
        assert local == Timestamp(tstr, tz="Asia/Tokyo")
        conv = local.tz_convert("US/Eastern")
        assert conv == Timestamp("2014-01-31 19:00", tz="US/Eastern")
        assert conv.hour == 19

        # preserves nanosecond
        ts = Timestamp(tstr) + offsets.Nano(5)
        local = ts.tz_localize("Asia/Tokyo")
        assert local.hour == 9
        assert local.nanosecond == 5
        conv = local.tz_convert("US/Eastern")
        assert conv.nanosecond == 5
        assert conv.hour == 19

    def test_utc_z_designator(self):
        assert get_timezone(Timestamp("2014-11-02 01:00Z").tzinfo) is utc

    def test_asm8(self):
        np.random.seed(7_960_929)
        ns = [Timestamp.min.value, Timestamp.max.value, 1000]

        for n in ns:
            assert (
                Timestamp(n).asm8.view("i8") == np.datetime64(n, "ns").view("i8") == n
            )

        assert Timestamp("nat").asm8.view("i8") == np.datetime64("nat", "ns").view("i8")

    def test_class_ops_pytz(self):
        def compare(x, y):
            assert int((Timestamp(x).value - Timestamp(y).value) / 1e9) == 0

        compare(Timestamp.now(), datetime.now())
        compare(Timestamp.now("UTC"), datetime.now(timezone("UTC")))
        compare(Timestamp.utcnow(), datetime.utcnow())
        compare(Timestamp.today(), datetime.today())
        current_time = calendar.timegm(datetime.now().utctimetuple())

        ts_utc = Timestamp.utcfromtimestamp(current_time)
        assert ts_utc.timestamp() == current_time
        compare(
            Timestamp.fromtimestamp(current_time), datetime.fromtimestamp(current_time)
        )
        compare(
            # Support tz kwarg in Timestamp.fromtimestamp
            Timestamp.fromtimestamp(current_time, "UTC"),
            datetime.fromtimestamp(current_time, utc),
        )
        compare(
            # Support tz kwarg in Timestamp.fromtimestamp
            Timestamp.fromtimestamp(current_time, tz="UTC"),
            datetime.fromtimestamp(current_time, utc),
        )

        date_component = datetime.utcnow()
        time_component = (date_component + timedelta(minutes=10)).time()
        compare(
            Timestamp.combine(date_component, time_component),
            datetime.combine(date_component, time_component),
        )

    def test_class_ops_dateutil(self):
        def compare(x, y):
            assert (
                int(
                    np.round(Timestamp(x).value / 1e9)
                    - np.round(Timestamp(y).value / 1e9)
                )
                == 0
            )

        compare(Timestamp.now(), datetime.now())
        compare(Timestamp.now("UTC"), datetime.now(tzutc()))
        compare(Timestamp.utcnow(), datetime.utcnow())
        compare(Timestamp.today(), datetime.today())
        current_time = calendar.timegm(datetime.now().utctimetuple())

        ts_utc = Timestamp.utcfromtimestamp(current_time)
        assert ts_utc.timestamp() == current_time

        compare(
            Timestamp.fromtimestamp(current_time), datetime.fromtimestamp(current_time)
        )

        date_component = datetime.utcnow()
        time_component = (date_component + timedelta(minutes=10)).time()
        compare(
            Timestamp.combine(date_component, time_component),
            datetime.combine(date_component, time_component),
        )

    def test_basics_nanos(self):
        val = np.int64(946_684_800_000_000_000).view("M8[ns]")
        stamp = Timestamp(val.view("i8") + 500)
        assert stamp.year == 2000
        assert stamp.month == 1
        assert stamp.microsecond == 0
        assert stamp.nanosecond == 500

        # GH 14415
        val = np.iinfo(np.int64).min + 80_000_000_000_000
        stamp = Timestamp(val)
        assert stamp.year == 1677
        assert stamp.month == 9
        assert stamp.day == 21
        assert stamp.microsecond == 145224
        assert stamp.nanosecond == 192

    @pytest.mark.parametrize(
        "value, check_kwargs",
        [
            [946688461000000000, {}],
            [946688461000000000 / 1000, {"unit": "us"}],
            [946688461000000000 / 1_000_000, {"unit": "ms"}],
            [946688461000000000 / 1_000_000_000, {"unit": "s"}],
            [10957, {"unit": "D", "h": 0}],
            [
                (946688461000000000 + 500000) / 1000000000,
                {"unit": "s", "us": 499, "ns": 964},
            ],
            [
                (946688461000000000 + 500000000) / 1000000000,
                {"unit": "s", "us": 500000},
            ],
            [(946688461000000000 + 500000) / 1000000, {"unit": "ms", "us": 500}],
            [(946688461000000000 + 500000) / 1000, {"unit": "us", "us": 500}],
            [(946688461000000000 + 500000000) / 1000000, {"unit": "ms", "us": 500000}],
            [946688461000000000 / 1000.0 + 5, {"unit": "us", "us": 5}],
            [946688461000000000 / 1000.0 + 5000, {"unit": "us", "us": 5000}],
            [946688461000000000 / 1000000.0 + 0.5, {"unit": "ms", "us": 500}],
            [946688461000000000 / 1000000.0 + 0.005, {"unit": "ms", "us": 5, "ns": 5}],
            [946688461000000000 / 1000000000.0 + 0.5, {"unit": "s", "us": 500000}],
            [10957 + 0.5, {"unit": "D", "h": 12}],
        ],
    )
    def test_unit(self, value, check_kwargs):
        def check(value, unit=None, h=1, s=1, us=0, ns=0):
            stamp = Timestamp(value, unit=unit)
            assert stamp.year == 2000
            assert stamp.month == 1
            assert stamp.day == 1
            assert stamp.hour == h
            if unit != "D":
                assert stamp.minute == 1
                assert stamp.second == s
                assert stamp.microsecond == us
            else:
                assert stamp.minute == 0
                assert stamp.second == 0
                assert stamp.microsecond == 0
            assert stamp.nanosecond == ns

        check(value, **check_kwargs)

    def test_roundtrip(self):

        # test value to string and back conversions
        # further test accessors
        base = Timestamp("20140101 00:00:00")

        result = Timestamp(base.value + Timedelta("5ms").value)
        assert result == Timestamp(f"{base}.005000")
        assert result.microsecond == 5000

        result = Timestamp(base.value + Timedelta("5us").value)
        assert result == Timestamp(f"{base}.000005")
        assert result.microsecond == 5

        result = Timestamp(base.value + Timedelta("5ns").value)
        assert result == Timestamp(f"{base}.000000005")
        assert result.nanosecond == 5
        assert result.microsecond == 0

        result = Timestamp(base.value + Timedelta("6ms 5us").value)
        assert result == Timestamp(f"{base}.006005")
        assert result.microsecond == 5 + 6 * 1000

        result = Timestamp(base.value + Timedelta("200ms 5us").value)
        assert result == Timestamp(f"{base}.200005")
        assert result.microsecond == 5 + 200 * 1000

    def test_hash_equivalent(self):
        d = {datetime(2011, 1, 1): 5}
        stamp = Timestamp(datetime(2011, 1, 1))
        assert d[stamp] == 5

    @pytest.mark.parametrize(
        "timezone, year, month, day, hour",
        [["America/Chicago", 2013, 11, 3, 1], ["America/Santiago", 2021, 4, 3, 23]],
    )
    def test_hash_timestamp_with_fold(self, timezone, year, month, day, hour):
        # see gh-33931
        test_timezone = gettz(timezone)
        transition_1 = Timestamp(
            year=year,
            month=month,
            day=day,
            hour=hour,
            minute=0,
            fold=0,
            tzinfo=test_timezone,
        )
        transition_2 = Timestamp(
            year=year,
            month=month,
            day=day,
            hour=hour,
            minute=0,
            fold=1,
            tzinfo=test_timezone,
        )
        assert hash(transition_1) == hash(transition_2)

class TestTimestampNsOperations:
    def test_nanosecond_string_parsing(self):
        ts = Timestamp("2013-05-01 07:15:45.123456789")
        # GH 7878
        expected_repr = "2013-05-01 07:15:45.123456789"
        expected_value = 1_367_392_545_123_456_789
        assert ts.value == expected_value
        assert expected_repr in repr(ts)

        ts = Timestamp("2013-05-01 07:15:45.123456789+09:00", tz="Asia/Tokyo")
        assert ts.value == expected_value - 9 * 3600 * 1_000_000_000
        assert expected_repr in repr(ts)

        ts = Timestamp("2013-05-01 07:15:45.123456789", tz="UTC")
        assert ts.value == expected_value
        assert expected_repr in repr(ts)

        ts = Timestamp("2013-05-01 07:15:45.123456789", tz="US/Eastern")
        assert ts.value == expected_value + 4 * 3600 * 1_000_000_000
        assert expected_repr in repr(ts)

        # GH 10041
        ts = Timestamp("20130501T071545.123456789")
        assert ts.value == expected_value
        assert expected_repr in repr(ts)

    def test_nanosecond_timestamp(self):
        # GH 7610
        expected = 1_293_840_000_000_000_005
        t = Timestamp("2011-01-01") + offsets.Nano(5)
        assert repr(t) == "Timestamp('2011-01-01 00:00:00.000000005')"
        assert t.value == expected
        assert t.nanosecond == 5

        t = Timestamp(t)
        assert repr(t) == "Timestamp('2011-01-01 00:00:00.000000005')"
        assert t.value == expected
        assert t.nanosecond == 5

        t = Timestamp("2011-01-01 00:00:00.000000005")
        assert repr(t) == "Timestamp('2011-01-01 00:00:00.000000005')"
        assert t.value == expected
        assert t.nanosecond == 5

        expected = 1_293_840_000_000_000_010
        t = t + offsets.Nano(5)
        assert repr(t) == "Timestamp('2011-01-01 00:00:00.000000010')"
        assert t.value == expected
        assert t.nanosecond == 10

        t = Timestamp(t)
        assert repr(t) == "Timestamp('2011-01-01 00:00:00.000000010')"
        assert t.value == expected
        assert t.nanosecond == 10

        t = Timestamp("2011-01-01 00:00:00.000000010")
        assert repr(t) == "Timestamp('2011-01-01 00:00:00.000000010')"
        assert t.value == expected
        assert t.nanosecond == 10

class TestTimestampToJulianDate:
    def test_compare_1700(self):
        r = Timestamp("1700-06-23").to_julian_date()
        assert r == 2_342_145.5

    def test_compare_2000(self):
        r = Timestamp("2000-04-12").to_julian_date()
        assert r == 2_451_646.5

    def test_compare_2100(self):
        r = Timestamp("2100-08-12").to_julian_date()
        assert r == 2_488_292.5

    def test_compare_hour01(self):
        r = Timestamp("2000-08-12T01:00:00").to_julian_date()
        assert r == 2_451_768.5416666666666666

    def test_compare_hour13(self):
        r = Timestamp("2000-08-12T13:00:00").to_julian_date()
        assert r == 2_451_769.0416666666666666

class TestTimestampConversion:
    def test_conversion(self):
        # GH#9255
        ts = Timestamp("2000-01-01")

        result = ts.to_pydatetime()
        expected = datetime(2000, 1, 1)
        assert result == expected
        assert type(result) == type(expected)

        result = ts.to_datetime64()
        expected = np.datetime64(ts.value, "ns")
        assert result == expected
        assert type(result) == type(expected)
        assert result.dtype == expected.dtype

    def test_to_pydatetime_fold(self):
        # GH#45087
        tzstr = "dateutil/usr/share/zoneinfo/America/Chicago"
        ts = Timestamp(year=2013, month=11, day=3, hour=1, minute=0, fold=1, tz=tzstr)
        dt = ts.to_pydatetime()
        assert dt.fold == 1

    def test_to_pydatetime_nonzero_nano(self):
        ts = Timestamp("2011-01-01 9:00:00.123456789")

        # Warn the user of data loss (nanoseconds).
        with tm.assert_produces_warning(UserWarning):
            expected = datetime(2011, 1, 1, 9, 0, 0, 123456)
            result = ts.to_pydatetime()
            assert result == expected

    def test_timestamp_to_datetime(self):
        stamp = Timestamp("20090415", tz="US/Eastern")
        dtval = stamp.to_pydatetime()
        assert stamp == dtval
        assert stamp.tzinfo == dtval.tzinfo

    def test_timestamp_to_datetime_dateutil(self):
        stamp = Timestamp("20090415", tz="dateutil/US/Eastern")
        dtval = stamp.to_pydatetime()
        assert stamp == dtval
        assert stamp.tzinfo == dtval.tzinfo

    def test_timestamp_to_datetime_explicit_pytz(self):
        stamp = Timestamp("20090415", tz=pytz.timezone("US/Eastern"))
        dtval = stamp.to_pydatetime()
        assert stamp == dtval
        assert stamp.tzinfo == dtval.tzinfo

    @td.skip_if_windows
    def test_timestamp_to_datetime_explicit_dateutil(self):
        stamp = Timestamp("20090415", tz=gettz("US/Eastern"))
        dtval = stamp.to_pydatetime()
        assert stamp == dtval
        assert stamp.tzinfo == dtval.tzinfo

    def test_to_datetime_bijective(self):
        # Ensure that converting to datetime and back only loses precision
        # by going from nanoseconds to microseconds.
        exp_warning = None if Timestamp.max.nanosecond == 0 else UserWarning
        with tm.assert_produces_warning(exp_warning):
            pydt_max = Timestamp.max.to_pydatetime()

        assert Timestamp(pydt_max).value / 1000 == Timestamp.max.value / 1000

        exp_warning = None if Timestamp.min.nanosecond == 0 else UserWarning
        with tm.assert_produces_warning(exp_warning):
            pydt_min = Timestamp.min.to_pydatetime()

        # The next assertion can be enabled once GH#39221 is merged
        #  assert pydt_min < Timestamp.min  # this is bc nanos are dropped
        tdus = timedelta(microseconds=1)
        assert pydt_min + tdus > Timestamp.min

        assert Timestamp(pydt_min + tdus).value / 1000 == Timestamp.min.value / 1000

    def test_to_period_tz_warning(self):
        # GH#21333 make sure a warning is issued when timezone
        # info is lost
        ts = Timestamp("2009-04-15 16:17:18", tz="US/Eastern")
        with tm.assert_produces_warning(UserWarning):
            # warning that timezone info will be lost
            ts.to_period("D")

    def test_to_numpy_alias(self):
        # GH 24653: alias .to_numpy() for scalars
        ts = Timestamp(datetime.now())
        assert ts.to_datetime64() == ts.to_numpy()

        # GH#44460
        msg = "dtype and copy arguments are ignored"
        with pytest.raises(ValueError, match=msg):
            ts.to_numpy("M8[s]")
        with pytest.raises(ValueError, match=msg):
            ts.to_numpy(copy=True)

class SubDatetime(datetime):
    pass

@pytest.mark.parametrize(
    "lh,rh",
    [
        (SubDatetime(2000, 1, 1), Timedelta(hours=1)),
        (Timedelta(hours=1), SubDatetime(2000, 1, 1)),
    ],
)
def test_dt_subclass_add_timedelta(lh, rh):
    # GH#25851
    # ensure that subclassed datetime works for
    # Timedelta operations
    result = lh + rh
    expected = SubDatetime(2000, 1, 1, 1)
    assert result == expected

class TestNonNano:
    @pytest.fixture(params=["s", "ms", "us"])
    def reso(self, request):
        return request.param

    @pytest.fixture
    def dt64(self, reso):
        # cases that are in-bounds for nanosecond, so we can compare against
        #  the existing implementation.
        return np.datetime64("2016-01-01", reso)

    @pytest.fixture
    def ts(self, dt64):
        return Timestamp._from_dt64(dt64)

    @pytest.fixture
    def ts_tz(self, ts, tz_aware_fixture):
        tz = maybe_get_tz(tz_aware_fixture)
        return Timestamp._from_value_and_reso(ts.value, ts._creso, tz)

    def test_non_nano_construction(self, dt64, ts, reso):
        assert ts.value == dt64.view("i8")

        if reso == "s":
            assert ts._creso == NpyDatetimeUnit.NPY_FR_s.value
        elif reso == "ms":
            assert ts._creso == NpyDatetimeUnit.NPY_FR_ms.value
        elif reso == "us":
            assert ts._creso == NpyDatetimeUnit.NPY_FR_us.value

    def test_non_nano_fields(self, dt64, ts):
        alt = Timestamp(dt64)

        assert ts.year == alt.year
        assert ts.month == alt.month
        assert ts.day == alt.day
        assert ts.hour == ts.minute == ts.second == ts.microsecond == 0
        assert ts.nanosecond == 0

        assert ts.to_julian_date() == alt.to_julian_date()
        assert ts.weekday() == alt.weekday()
        assert ts.isoweekday() == alt.isoweekday()

    def test_start_end_fields(self, ts):
        assert ts.is_year_start
        assert ts.is_quarter_start
        assert ts.is_month_start
        assert not ts.is_year_end
        assert not ts.is_month_end
        assert not ts.is_month_end

        # 2016-01-01 is a Friday, so is year/quarter/month start with this freq
        assert ts.is_year_start
        assert ts.is_quarter_start
        assert ts.is_month_start
        assert not ts.is_year_end
        assert not ts.is_month_end
        assert not ts.is_month_end

    def test_day_name(self, dt64, ts):
        alt = Timestamp(dt64)
        assert ts.day_name() == alt.day_name()

    def test_month_name(self, dt64, ts):
        alt = Timestamp(dt64)
        assert ts.month_name() == alt.month_name()

    def test_tz_convert(self, ts):
        ts = Timestamp._from_value_and_reso(ts.value, ts._creso, utc)

        tz = pytz.timezone("US/Pacific")
        result = ts.tz_convert(tz)

        assert isinstance(result, Timestamp)
        assert result._creso == ts._creso
        assert tz_compare(result.tz, tz)

    def test_repr(self, dt64, ts):
        alt = Timestamp(dt64)

        assert str(ts) == str(alt)
        assert repr(ts) == repr(alt)

    def test_comparison(self, dt64, ts):
        alt = Timestamp(dt64)

        assert ts == dt64
        assert dt64 == ts
        assert ts == alt
        assert alt == ts

        assert not ts != dt64
        assert not dt64 != ts
        assert not ts != alt
        assert not alt != ts

        assert not ts < dt64
        assert not dt64 < ts
        assert not ts < alt
        assert not alt < ts

        assert not ts > dt64
        assert not dt64 > ts
        assert not ts > alt
        assert not alt > ts

        assert ts >= dt64
        assert dt64 >= ts
        assert ts >= alt
        assert alt >= ts

        assert ts <= dt64
        assert dt64 <= ts
        assert ts <= alt
        assert alt <= ts

    def test_cmp_cross_reso(self):
        # numpy gets this wrong because of silent overflow
        dt64 = np.datetime64(9223372800, "s")  # won't fit in M8[ns]
        ts = Timestamp._from_dt64(dt64)

        # subtracting 3600*24 gives a datetime64 that _can_ fit inside the
        #  nanosecond implementation bounds.
        other = Timestamp(dt64 - 3600 * 24).as_unit("ns")
        assert other < ts
        assert other.asm8 > ts.asm8  # <- numpy gets this wrong
        assert ts > other
        assert ts.asm8 < other.asm8  # <- numpy gets this wrong
        assert not other == ts
        assert ts != other

    @pytest.mark.xfail(reason="Dispatches to np.datetime64 which is wrong")
    def test_cmp_cross_reso_reversed_dt64(self):
        dt64 = np.datetime64(106752, "D")  # won't fit in M8[ns]
        ts = Timestamp._from_dt64(dt64)
        other = Timestamp(dt64 - 1)

        assert other.asm8 < ts

    def test_pickle(self, ts, tz_aware_fixture):
        tz = tz_aware_fixture
        tz = maybe_get_tz(tz)
        ts = Timestamp._from_value_and_reso(ts.value, ts._creso, tz)
        rt = tm.round_trip_pickle(ts)
        assert rt._creso == ts._creso
        assert rt == ts

    def test_normalize(self, dt64, ts):
        alt = Timestamp(dt64)
        result = ts.normalize()
        assert result._creso == ts._creso
        assert result == alt.normalize()

    def test_asm8(self, dt64, ts):
        rt = ts.asm8
        assert rt == dt64
        assert rt.dtype == dt64.dtype

    def test_to_numpy(self, dt64, ts):
        res = ts.to_numpy()
        assert res == dt64
        assert res.dtype == dt64.dtype

    def test_to_datetime64(self, dt64, ts):
        res = ts.to_datetime64()
        assert res == dt64
        assert res.dtype == dt64.dtype

    def test_timestamp(self, dt64, ts):
        alt = Timestamp(dt64)
        assert ts.timestamp() == alt.timestamp()

    def test_to_period(self, dt64, ts):
        alt = Timestamp(dt64)
        assert ts.to_period("D") == alt.to_period("D")

    @pytest.mark.parametrize(
        "td", [timedelta(days=4), Timedelta(days=4), np.timedelta64(4, "D")]
    )
    def test_addsub_timedeltalike_non_nano(self, dt64, ts, td):

        exp_reso = max(ts._creso, Timedelta(td)._creso)

        result = ts - td
        expected = Timestamp(dt64) - td
        assert isinstance(result, Timestamp)
        assert result._creso == exp_reso
        assert result == expected

        result = ts + td
        expected = Timestamp(dt64) + td
        assert isinstance(result, Timestamp)
        assert result._creso == exp_reso
        assert result == expected

        result = td + ts
        expected = td + Timestamp(dt64)
        assert isinstance(result, Timestamp)
        assert result._creso == exp_reso
        assert result == expected

    def test_addsub_offset(self, ts_tz):
        # specifically non-Tick offset
        off = offsets.YearEnd(1)
        result = ts_tz + off

        assert isinstance(result, Timestamp)
        assert result._creso == ts_tz._creso
        if ts_tz.month == 12 and ts_tz.day == 31:
            assert result.year == ts_tz.year + 1
        else:
            assert result.year == ts_tz.year
        assert result.day == 31
        assert result.month == 12
        assert tz_compare(result.tz, ts_tz.tz)

        result = ts_tz - off

        assert isinstance(result, Timestamp)
        assert result._creso == ts_tz._creso
        assert result.year == ts_tz.year - 1
        assert result.day == 31
        assert result.month == 12
        assert tz_compare(result.tz, ts_tz.tz)

    def test_sub_datetimelike_mismatched_reso(self, ts_tz):
        # case with non-lossy rounding
        ts = ts_tz

        # choose a unit for `other` that doesn't match ts_tz's;
        #  this construction ensures we get cases with other._creso < ts._creso
        #  and cases with other._creso > ts._creso
        unit = {
            NpyDatetimeUnit.NPY_FR_us.value: "ms",
            NpyDatetimeUnit.NPY_FR_ms.value: "s",
            NpyDatetimeUnit.NPY_FR_s.value: "us",
        }[ts._creso]
        other = ts.as_unit(unit)
        assert other._creso != ts._creso

        result = ts - other
        assert isinstance(result, Timedelta)
        assert result.value == 0
        assert result._creso == max(ts._creso, other._creso)

        result = other - ts
        assert isinstance(result, Timedelta)
        assert result.value == 0
        assert result._creso == max(ts._creso, other._creso)

        if ts._creso < other._creso:
            # Case where rounding is lossy
            other2 = other + Timedelta._from_value_and_reso(1, other._creso)
            exp = ts.as_unit(other.unit) - other2

            res = ts - other2
            assert res == exp
            assert res._creso == max(ts._creso, other._creso)

            res = other2 - ts
            assert res == -exp
            assert res._creso == max(ts._creso, other._creso)
        else:
            ts2 = ts + Timedelta._from_value_and_reso(1, ts._creso)
            exp = ts2 - other.as_unit(ts2.unit)

            res = ts2 - other
            assert res == exp
            assert res._creso == max(ts._creso, other._creso)
            res = other - ts2
            assert res == -exp
            assert res._creso == max(ts._creso, other._creso)

    def test_sub_timedeltalike_mismatched_reso(self, ts_tz):
        # case with non-lossy rounding
        ts = ts_tz

        # choose a unit for `other` that doesn't match ts_tz's;
        #  this construction ensures we get cases with other._creso < ts._creso
        #  and cases with other._creso > ts._creso
        unit = {
            NpyDatetimeUnit.NPY_FR_us.value: "ms",
            NpyDatetimeUnit.NPY_FR_ms.value: "s",
            NpyDatetimeUnit.NPY_FR_s.value: "us",
        }[ts._creso]
        other = Timedelta(0).as_unit(unit)
        assert other._creso != ts._creso

        result = ts + other
        assert isinstance(result, Timestamp)
        assert result == ts
        assert result._creso == max(ts._creso, other._creso)

        result = other + ts
        assert isinstance(result, Timestamp)
        assert result == ts
        assert result._creso == max(ts._creso, other._creso)

        if ts._creso < other._creso:
            # Case where rounding is lossy
            other2 = other + Timedelta._from_value_and_reso(1, other._creso)
            exp = ts.as_unit(other.unit) + other2
            res = ts + other2
            assert res == exp
            assert res._creso == max(ts._creso, other._creso)
            res = other2 + ts
            assert res == exp
            assert res._creso == max(ts._creso, other._creso)
        else:
            ts2 = ts + Timedelta._from_value_and_reso(1, ts._creso)
            exp = ts2 + other.as_unit(ts2.unit)

            res = ts2 + other
            assert res == exp
            assert res._creso == max(ts._creso, other._creso)
            res = other + ts2
            assert res == exp
            assert res._creso == max(ts._creso, other._creso)

    def test_addition_doesnt_downcast_reso(self):
        # https://github.com/pandas-dev/pandas/pull/48748#pullrequestreview-1122635413
        ts = Timestamp(year=2022, month=1, day=1, microsecond=999999).as_unit("us")
        td = Timedelta(microseconds=1).as_unit("us")
        res = ts + td
        assert res._creso == ts._creso

    def test_sub_timedelta64_mismatched_reso(self, ts_tz):
        ts = ts_tz

        res = ts + np.timedelta64(1, "ns")
        exp = ts.as_unit("ns") + np.timedelta64(1, "ns")
        assert exp == res
        assert exp._creso == NpyDatetimeUnit.NPY_FR_ns.value

    def test_min(self, ts):
        assert ts.min <= ts
        assert ts.min._creso == ts._creso
        assert ts.min.value == NaT.value + 1

    def test_max(self, ts):
        assert ts.max >= ts
        assert ts.max._creso == ts._creso
        assert ts.max.value == np.iinfo(np.int64).max

    def test_resolution(self, ts):
        expected = Timedelta._from_value_and_reso(1, ts._creso)
        result = ts.resolution
        assert result == expected
        assert result._creso == expected._creso

def test_timestamp_class_min_max_resolution():
    # when accessed on the class (as opposed to an instance), we default
    #  to nanoseconds
    assert Timestamp.min == Timestamp(NaT.value + 1)
    assert Timestamp.min._creso == NpyDatetimeUnit.NPY_FR_ns.value

    assert Timestamp.max == Timestamp(np.iinfo(np.int64).max)
    assert Timestamp.max._creso == NpyDatetimeUnit.NPY_FR_ns.value

    assert Timestamp.resolution == Timedelta(1)
    assert Timestamp.resolution._creso == NpyDatetimeUnit.NPY_FR_ns.value

class TestAsUnit:
    def test_as_unit(self):
        ts = Timestamp("1970-01-01")

        assert ts.as_unit("ns") is ts

        res = ts.as_unit("us")
        assert res.value == ts.value // 1000
        assert res._creso == NpyDatetimeUnit.NPY_FR_us.value

        rt = res.as_unit("ns")
        assert rt.value == ts.value
        assert rt._creso == ts._creso

        res = ts.as_unit("ms")
        assert res.value == ts.value // 1_000_000
        assert res._creso == NpyDatetimeUnit.NPY_FR_ms.value

        rt = res.as_unit("ns")
        assert rt.value == ts.value
        assert rt._creso == ts._creso

        res = ts.as_unit("s")
        assert res.value == ts.value // 1_000_000_000
        assert res._creso == NpyDatetimeUnit.NPY_FR_s.value

        rt = res.as_unit("ns")
        assert rt.value == ts.value
        assert rt._creso == ts._creso

    def test_as_unit_overflows(self):
        # microsecond that would be just out of bounds for nano
        us = 9223372800000000
        ts = Timestamp._from_value_and_reso(us, NpyDatetimeUnit.NPY_FR_us.value, None)

        msg = "Cannot cast 2262-04-12 00:00:00 to unit='ns' without overflow"
        with pytest.raises(OutOfBoundsDatetime, match=msg):
            ts.as_unit("ns")

        res = ts.as_unit("ms")
        assert res.value == us // 1000
        assert res._creso == NpyDatetimeUnit.NPY_FR_ms.value

    def test_as_unit_rounding(self):
        ts = Timestamp(1_500_000)  # i.e. 1500 microseconds
        res = ts.as_unit("ms")

        expected = Timestamp(1_000_000)  # i.e. 1 millisecond
        assert res == expected

        assert res._creso == NpyDatetimeUnit.NPY_FR_ms.value
        assert res.value == 1

        with pytest.raises(ValueError, match="Cannot losslessly convert units"):
            ts.as_unit("ms", round_ok=False)

    def test_as_unit_non_nano(self):
        # case where we are going neither to nor from nano
        ts = Timestamp("1970-01-02").as_unit("ms")
        assert ts.year == 1970
        assert ts.month == 1
        assert ts.day == 2
        assert ts.hour == ts.minute == ts.second == ts.microsecond == ts.nanosecond == 0

        res = ts.as_unit("s")
        assert res.value == 24 * 3600
        assert res.year == 1970
        assert res.month == 1
        assert res.day == 2
        assert (
            res.hour
            == res.minute
            == res.second
            == res.microsecond
            == res.nanosecond
            == 0
        )


text:
#include "TestSceneBase.h"

class PartialDamageAnimation;

static TestScene::Registrar _PartialDamage(TestScene::Info{
    "partialdamage",
    "Tests the partial invalidation path. Draws a grid of rects and animates 1 "
    "of them, should be low CPU & GPU load if EGL_EXT_buffer_age or "
    "EGL_KHR_partial_update is supported by the device & are enabled in hwui.",
    TestScene::simpleCreateScene<PartialDamageAnimation>
});

class PartialDamageAnimation : public TestScene {
public:
    std::vector< sp<RenderNode> > cards;
    void createContent(int width, int height, TestCanvas& canvas) override {
        static SkColor COLORS[] = {
                0xFFF44336,
                0xFF9C27B0,
                0xFF2196F3,
                0xFF4CAF50,
        };

        canvas.drawColor(0xFFFFFFFF, SkXfermode::kSrcOver_Mode);

        for (int x = dp(16); x < (width - dp(116)); x += dp(116)) {
            for (int y = dp(16); y < (height - dp(116)); y += dp(116)) {
                SkColor color = COLORS[static_cast<int>((y / dp(116))) % 4];
                sp<RenderNode> card = TestUtils::createNode(x, y,
                        x + dp(100), y + dp(100),
                        [color](RenderProperties& props, TestCanvas& canvas) {
                    canvas.drawColor(color, SkXfermode::kSrcOver_Mode);
                });
                canvas.drawRenderNode(card.get());
                cards.push_back(card);
            }
        }
    }
    void doFrame(int frameNr) override {
        int curFrame = frameNr % 150;
        cards[0]->mutateStagingProperties().setTranslationX(curFrame);
        cards[0]->mutateStagingProperties().setTranslationY(curFrame);
        cards[0]->setPropertyFieldsDirty(RenderNode::X | RenderNode::Y);

        TestUtils::recordNode(*cards[0], [curFrame](TestCanvas& canvas) {
            SkColor color = TestUtils::interpolateColor(
                    curFrame / 150.0f, 0xFFF44336, 0xFFF8BBD0);
            canvas.drawColor(color, SkXfermode::kSrcOver_Mode);
        });
    }
};

redpajama_set_name: RedPajamaGithub


text:
<?php

namespace Sonata\AdminBundle\Filter;
use Sonata\AdminBundle\Datagrid\ProxyQueryInterface;

interface FilterInterface
{
    const CONDITION_OR = 'OR';

    const CONDITION_AND = 'AND';

    /**
     * Apply the filter to the QueryBuilder instance
     *
     * @param ProxyQueryInterface $queryBuilder
     * @param string              $alias
     * @param string              $field
     * @param string              $value
     *
     * @return void
     */
    public function filter(ProxyQueryInterface $queryBuilder, $alias, $field, $value);

    /**
     * @param mixed $query
     * @param mixed $value
     */
    public function apply($query, $value);

    /**
     * Returns the filter name
     *
     * @return string
     */
    public function getName();

    /**
     * Returns the filter form name
     *
     * @return string
     */
    public function getFormName();

    /**
     * Returns the label name
     *
     * @return string
     */
    public function getLabel();

    /**
     * @param string $label
     */
    public function setLabel($label);

    /**
     * @return array
     */
    public function getDefaultOptions();

    /**
     * @param string $name
     * @param null   $default
     *
     * @return mixed
     */
    public function getOption($name, $default = null);

    /**
     * @param string $name
     * @param mixed  $value
     */
    public function setOption($name, $value);

    /**
     * @param string $name
     * @param array  $options
     *
     * @return void
     */
    public function initialize($name, array $options = array());

    /**
     * @return string
     */
    public function getFieldName();

    /**
     * @return array of mappings
     */
    public function getParentAssociationMappings();

    /**
     * @return array field mapping
     */
    public function getFieldMapping();

    /**
     * @return array association mapping
     */
    public function getAssociationMapping();

    /**
     * @return array
     */
    public function getFieldOptions();

    /**
     * @return string
     */
    public function getFieldType();

    /**
     * Returns the main widget used to render the filter
     *
     * @return array
     */
    public function getRenderSettings();

    /**
     * Returns true if filter is active
     *
     * @return boolean
     */
    public function isActive();

    /**
     * Set the condition to use with the left side of the query : OR or AND
     *
     * @param string $condition
     */
    public function setCondition($condition);

    /**
     * @return string
     */
    public function getCondition();
}


text:
<!--
  ~ Copyright (c) 2010-2017 Evolveum and contributors
  ~
  ~ This work is dual-licensed under the Apache License 2.0
  ~ and European Union Public License. See LICENSE file for details.
  -->
<role oid="4838ce2c-5250-4d9c-b5cc-b6b946852806"
      xmlns="http://midpoint.evolveum.com/xml/ns/public/common/common-3">
    <!-- This is a hidden thief; not directly listed in criminal-exclusion participants. But should be excluded nevertheless. -->
    <name>Respectable</name>
    <inducement>
        <targetRef oid="b189fcb8-1ff9-11e5-8912-001e8c717e5b" type="RoleType"/>         <!-- Thief -->
    </inducement>
</role>


text:
<?php

namespace Tsp\FrontBundle\Resources\forms;

use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilder;

class formRegister extends AbstractType
{
    public function buildForm(FormBuilder $builder, array $options)
    {
        $builder
            ->add('email', 'email', array('required' => true))
            ->add('username', 'text', array('required' => true))
            ->add('password', 'password', array('required' => true))
            ->getForm();
    }

    public function getName()
    {
        return 'username';
    }
}


text:
package com.thoughtworks.go.serverhealth;

import java.util.List;

import org.hamcrest.Description;
import org.hamcrest.Matcher;
import org.hamcrest.TypeSafeMatcher;

public class ServerHealthMatcher {

    public static Matcher<ServerHealthService> containsState(final HealthStateType type) {
        return containsState(type, null, null);
    }

    public static Matcher<ServerHealthService> containsState(final HealthStateType healthStateType,
                                                        final HealthStateLevel healthStateLevel,
                                                        final String message) {
        return new TypeSafeMatcher<ServerHealthService>() {
            private List<ServerHealthState> allLogs;
            private ServerHealthState entry;
            private boolean levelMatches;
            private boolean messageMatches;

            public boolean matchesSafely(ServerHealthService item) {
                allLogs = item.logs();
                for (ServerHealthState serverHealthState : allLogs) {
                    if (serverHealthState.getType().equals(healthStateType)) {
                        entry = serverHealthState;
                    }
                }
                if (!(entry != null)) {
                    return false;
                } else {
                    levelMatches = healthStateLevel == null || healthStateLevel.equals(entry.getLogLevel());
                    messageMatches = message == null || message.equals(entry.getMessage());
                    return levelMatches && messageMatches;
                }
            }

            public void describeTo(Description description) {
                if (entry == null) {
                    description.appendText("Can not find result with " + healthStateType + " in all logs: " + allLogs);
                } else {
                    if (!levelMatches) {
                        description.appendText("Level was " + entry.getLogLevel() + " instead of " + healthStateLevel);
                    }
                    if (!messageMatches) {
                        description.appendText("Message was: \n" + entry.getMessage() + "\n instead of:\n" + message);
                    }
                }
            }
        };
    }

    public static Matcher<ServerHealthService> doesNotContainState(final HealthStateType healthStateType) {
        return new TypeSafeMatcher<ServerHealthService>() {
            private ServerHealthState entry;

            public boolean matchesSafely(ServerHealthService item) {
                for (ServerHealthState serverHealthState : item.logs()) {
                    if (serverHealthState.getType().equals(healthStateType)) {
                        entry = serverHealthState;
                        return false;
                    }
                }
                return true;
            }

            public void describeTo(Description description) {
                description.appendText("HealthStateType " + healthStateType + " contains: " + entry + "\n" + "With level: " + entry.getLogLevel());
            }
        };
    }

}


text:
import codecs
import os
import datetime
from yozuch.rstparser import RstParser
from tests import YozuchTestCase

class RstParserTest(YozuchTestCase):

    def read_file(self, filename):
        path = os.path.join(self.ROOT_DIR, 'data', filename)
        with codecs.open(path, 'r', 'utf-8-sig') as f:
            return path, f.read()

    def parse(self, filename, **kwargs):
        path, text = self.read_file(filename)
        doc = self.parser.parse(text, path, **kwargs)
        if doc is not None:
            self.parser.publish(doc)
        return doc

    def setUp(self):
        super(RstParserTest, self).setUp()
        self.parser = RstParser(self.config['RST_OPTIONS'])

    def test_post(self):
        doc = self.parse(os.path.join('posts', 'post.rst'))
        self.assertEqual(doc.title, '测试')
        self.assertEqual(doc.summary, None)
        self.assertEqual(doc.date, datetime.datetime(2013, 10, 2))
        self.assertEqual(doc.metadata['tags'], ['tag1'])
        self.assertEqual(doc.author, 'author1')
        self.assertEqual(doc.metadata['author'], 'author1')
        self.assertFalse(self._is_logger_errors())

    def test_post_additional_meta(self):
        doc = self.parse(os.path.join('posts', '2013-09-20-post-file-metadata.rst'),
                         additional_meta={'date': datetime.datetime(2013, 9, 20), 'slug': 'post-file-metadata'})
        self.assertEqual(doc.title, 'Title')
        self.assertEqual(doc.slug, 'post-file-metadata')
        self.assertEqual(doc.content, '
Content.
\n')
        self.assertEqual(doc.summary, None)
        self.assertEqual(doc.date, datetime.datetime(2013, 9, 20))
        self.assertEqual(doc.metadata['category'], 'cat2')
        self.assertEqual(doc.metadata['tags'], ['tag1', 'tag 2'])
        self.assertFalse(self._is_logger_errors())

    def test_post_additional_default_meta(self):
        doc = self.parse(os.path.join('posts', 'post-readmore.rst'), additional_meta={'category': 'additional'})
        self.assertEqual(doc.metadata['category'], 'additional')
        self.assertFalse(self._is_logger_errors())

    def test_post_readmore(self):
        doc = self.parse(os.path.join('posts', 'post-readmore.rst'))
        self.assertEqual(doc.title, 'ReadMore')
        self.assertEqual(doc.content, '
foo
\n
\n
Section¶
\n
bar
\n
baz
\n
\n')
        self.assertEqual(doc.summary, '
foo
\n
\n
Section¶
\n
bar
\n
')
        self.assertEqual(doc.date, datetime.datetime(2011, 1, 1))
        self.assertFalse(self._is_logger_errors())

    def test_post_error(self):
        doc = self.parse(os.path.join('posts', 'post-error.rst'))
        self.assertEqual(doc, None)
        self.assertEqual(len(self.logger_handler.messages['error']), 1)

    def test_page(self):
        doc = self.parse(os.path.join('documents', 'page.rst'))
        self.assertEqual(doc.title, 'Заголовок')
        self.assertEqual(doc.slug, None)
        self.assertEqual(doc.content, '
Содержимое
\n')
        self.assertEqual(doc.summary, None)
        self.assertFalse(self._is_logger_errors())


text:
require 'rubygems'
require 'pushmeup'

APNS.host = 'gateway.sandbox.push.apple.com'
APNS.port = 2195
APNS.pem  = '</path/to/my/certificate/ck.pem>'
APNS.pass = '<myCertificatePassword>'

device_token = '<device token gleaned from xcode console>'
# APNS.send_notification(device_token, 'Hello iPhone!' )
APNS.send_notification(device_token, :alert => 'PushPlugin works!!', :badge => 1, :sound => 'beep.wav')
/*email to provide support at vancekingsaxbe@powerdominionenterprise.com, businessaffairs@powerdominionenterprise.com, For donations please write to fundraising@powerdominionenterprise.com*/


text:
<?xml version="1.0" encoding="utf-8"?>
<!--
  ~ Copyright (C) 2015 Next Poor Slob Productions
  ~
  ~ 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.
  ~
  -->

<RelativeLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    app:layout_behavior="@string/appbar_scrolling_view_behavior"
    tools:context="com.nextpoorslob.basictasklist.TaskDetail"
    tools:showIn="@layout/activity_task_detail">

    <CheckBox
        android:id="@+id/taskdetail_complete"
        android:textAppearance="?android:attr/textAppearanceMedium"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginTop="26dp"
        android:checked="false"
        android:text="@string/taskdetail_complete"
        android:layout_alignParentTop="true"
        android:layout_alignLeft="@+id/taskdetail_ok_button"
        android:layout_alignStart="@+id/taskdetail_ok_button"/>

    <CheckBox
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textAppearance="?android:attr/textAppearanceMedium"
        android:text="@string/taskdetail_delete"
        android:id="@+id/taskdetail_delete"
        android:layout_alignTop="@id/taskdetail_complete"
        android:layout_alignRight="@+id/taskdetail_title"
        android:layout_alignEnd="@id/taskdetail_title"
        android:onClick="onClickConfirmDelete"/>

    <TextView
        android:id="@+id/taskdetail_title_label"
        android:textAppearance="?android:attr/textAppearanceMedium"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentLeft="true"
        android:layout_below="@id/taskdetail_complete"
        android:layout_marginTop="10dp"
        android:text="@string/taskdetail_title_hint"/>

    <EditText
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@+id/taskdetail_title"
        android:hint="@string/taskdetail_title_hint"
        android:layout_alignBaseline="@+id/taskdetail_title_label"
        android:layout_alignParentRight="true"
        android:layout_alignParentEnd="true"
        android:layout_toRightOf="@+id/taskdetail_title_label"
        android:layout_toEndOf="@+id/taskdetail_title_label"/>

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textAppearance="?android:attr/textAppearanceMedium"
        android:text="@string/taskdetail_description_label"
        android:id="@+id/taskdetail_description_label"
        android:layout_below="@id/taskdetail_title_label"
        android:layout_alignParentLeft="true"
        android:layout_marginTop="10dp"/>

    <EditText
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:inputType="textMultiLine"
        android:ems="10"
        android:id="@+id/taskdetail_description"
        android:layout_below="@id/taskdetail_description_label"
        android:layout_alignParentLeft="true"
        android:layout_alignParentStart="true"
        android:layout_above="@id/taskdetail_ok_button"
        android:layout_alignRight="@+id/taskdetail_cancel_button"
        android:layout_alignEnd="@+id/taskdetail_cancel_button"
        android:gravity="left"
        android:hint="@string/taskdetail_description_label"/>

    <Button
        android:id="@+id/taskdetail_ok_button"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentBottom="true"
        android:layout_alignParentLeft="true"
        android:layout_margin="5dp"
        android:onClick="onButtonClickOk"
        android:text="@string/taskdetai_ok_button"
        />

    <Button
        android:id="@+id/taskdetail_cancel_button"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentBottom="true"
        android:layout_alignParentRight="true"
        android:clickable="true"
        android:onClick="onButtonClickCancel"
        android:text="@string/taskdetail_cancel_button"
        />

</RelativeLayout>


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
Hedwigia 42: 80 (1903)

#### Original name
Cucurbitaria pritzeliana Henn.

### Remarks
null


text:
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<Root><page><content><locatieblok><locatie label="Locatie">EXAMPLE</locatie>
<straat label="Straat">EXAMPLE</straat>
<postcode label="Postcode">EXAMPLE</postcode> <plaats label="Plaats">EXAMPLE</plaats>

<telomschrijving label="Telefoon omschrijving">T.</telomschrijving> <telefoon label="Telefoon">EXAMPLE</telefoon>

<internet label="Internet">EXAMPLE</internet></locatieblok><naamblok><aanhefnaam label="Aanhef Naam Achternaam">Aanhef Naam Achternaam</aanhefnaam>
<functie label="Functie">Functie</functie>
<mobielomschr label="Mobiel omschrijving">M.</mobielomschr>	<mobiel label="Mobiel">EXAMPLE</mobiel>
<emailomschr label="Email omschrijving">E.</emailomschr>	<email label="Email">EXAMPLE</email></naamblok></content></page></Root>


text:
require 'virtus'
require 'virtus/relations/version'

module Virtus
  def self.relations(params = {})
    rel_name = params.fetch(:as, :parent)
    fail TypeError, 'Symbol expected' unless rel_name.is_a?(Symbol)

    mod = Module.new
    mod.instance_variable_set(:@rel_name, rel_name)

    mod.module_eval do
      def self.class_methods
        Module.new do
          # During instantiation, .relation_attributes is called
          # If class was instantiated before, just return the list of related
          # attributes
          #
          # If instantiated for the first time, then monkey-patch some instance
          # methods to allow relation attributes to work with accessor methods.
          #
          #
          # patch Model#attribute=
          #
          #   1. create {list}
          #   2. for each {attribute} in {list}
          #   2.1. patch the accessor method
          #   2.2. patch the lazy initializer method (if any)
          #
          def relation_attributes
            @relation_attributes ||= attribute_set.select do |attribute|
              next unless attribute.options[:relation] == true

              patch_accessor_method(attribute)
              patch_lazy_initializer(attribute)
              true
            end
          end

          #
          # When the original method returns something, we need to
          # actually set ourselves as its parent
          # If that something is a collection, do it for each element
          #
          def relate(object, method_return)
            if object.kind_of?(Array)
              object.each { |o| relate(o, method_return) }
            else
              object.define_singleton_method(relation_name) { method_return }
              object
            end
          end

          protected
          #   1. rename method "{attribute}=" to "{attribute}_not_related="
          #   2. define method "{attribute}=", which:
          #     2.1. calls "{attribute}_not_related=", takes the {return_object}
          #     2.2. defines {return_object}.parent which returns self
          #     2.3. returns {return_object}
          #   3. return the list
          def patch_accessor_method(attribute)
            if [Numeric, Symbol].any? { |c| attribute.primitive.ancestors.include?(c) }
              fail "Relations don't work with Numeric and Symbol types"
            end

            old_method = "#{attribute.name}_not_related="
            new_method = "#{attribute.name}="

            # Suffix the original method with '_not_related'
            define_method(old_method, instance_method(new_method))
            define_method(new_method) do |value|
              return_value = send(old_method, value)
              self.class.relate(return_value, self)
            end

            private old_method
            visibility = attribute.options[:writer]
            send(visibility, new_method)
          end

          # (see above for the explanation of step 2.)
          #   Wrap the original method/proc into a new one, which:
          #   1. calls the original one, takes the {return_object}
          #   2. coerces {return_object}
          #   3. defines {return_object}.parent which returns self
          #   4. returns {return_object}
          #
          def patch_lazy_initializer(attribute)
            return unless attribute.lazy?

            case attribute.default_value.value
            when Proc
              old_proc = attribute.default_value.value
              new_proc = proc do |object, *args|
                return_value = attribute.coerce(old_proc.call(*[object, *args]))
                object.class.relate(return_value, object)
              end

              attribute.default_value.instance_variable_set(:@value, new_proc)
            else
              old_method = "#{attribute.default_value.value}_not_related"
              new_method = attribute.default_value.value
              visibility = if private_method_defined?(new_method)
                             :private
                           elsif protected_method_defined?(new_method)
                             :protected
                           else
                             :public
                           end

              define_method(old_method, instance_method(new_method))
              define_method(new_method) do
                return_value = attribute.coerce(send(old_method))
                self.class.relate(return_value, self)
                return_value
              end

              private old_method
              send(visibility, new_method)
            end
          end
        end # Module.new
      end # def

      def self.instance_methods
        Module.new do
          #
          # Enhance the initialize process to allow
          # related attributes to work with mass-assignment
          #
          def initialize(mass_assignment_attributes = {})
            super

            self.class.relation_attributes.each do |ra|
              # set self as the child's parent only if child was mass-
              # assigned during self.initialize (e.g. hash has child's key)
              # This prevents children from doing this against the parents
              # when they also have relation: true on their attributes
              # (since their initializers will not receive the parent as
              #  a part of the mass-assignment)

              if mass_assignment_attributes.key?(ra.name)
                self.class.relate(ra.get(self), self)
              end
            end
          end

          alias_method :dup_not_related, :dup

          # Add #parent to duped objects, when available
          def dup
            rel = self.class.relation_name
            if respond_to?(rel)
              self.class.relate(dup_not_related, rel)
            else
              dup_not_related
            end
          end
        end # Module.new
      end # def

      def self.included(base)
        required = [
          Virtus::InstanceMethods::MassAssignment,
          Virtus::InstanceMethods::Constructor
        ]

        unless required.all? { |mod| base.included_modules.include?(mod) }
          fail 'Virtus.model must be included prior to Virtus.relations'
        end

        # Using a local variable in the parent scope
        # with the same name as the singleton method
        # prevents recursion
        relation_name = @rel_name
        base.define_singleton_method(:relation_name) { relation_name }

        base.send(:include, instance_methods)
        base.extend(class_methods)
      end

      mod
    end
  end
end


text:
namespace DhammaTalks.Infrastructure.Ninject
{
    using global::Ninject;

    public class NinjectDependencyProvider : IDependencyProvider
    {
        private readonly IKernel kernel;

        public NinjectDependencyProvider(IKernel kernel)
        {
            this.kernel = kernel;
        }

        public T Get<T>()
        {
            return this.kernel.Get<T>();
        }
    }
}


text:
<?php

/*# declare(strict_types=1); */

namespace Phossa\Logger\Exception;

/**
 * Exception marker for phossa-logger
 *
 * @interface
 * @package Phossa\Logger
 * @author  Hong Zhang <phossa@126.com>
 * @see     \Phossa\Shared\Exception\ExceptionInterface
 * @version 1.0.4
 * @since   1.0.0 added
 */
interface ExceptionInterface extends \Phossa\Shared\Exception\ExceptionInterface
{
}


text:
<?php

namespace DvsaEntitiesTest\DqlBuilder\SearchParam;

use DvsaEntities\DqlBuilder\SearchParam\TransactionSearchParam;

/**
 * Class OrgSlotUsageParamTest.
 *
 * @author Jakub Igla <jakub.igla@valtech.co.uk>
 */
class TransactionSearchParamTest extends \PHPUnit\Framework\TestCase
{
    /**
     * @var TransactionSearchParam
     */
    private $param;

    public function setUp()
    {
        $this->param = new TransactionSearchParam();
    }

    /**
     * @dataProvider providerOrganisationId
     */
    public function testOrganisationId($input, $output)
    {
        $this->param->setOrganisationId($input);
        $this->assertEquals($output, $this->param->getOrganisationId());
    }

    public function providerOrganisationId()
    {
        return array(
            array(1, 1),
            array(999, 999),
        );
    }

    /**
     * @dataProvider providerDateFrom
     */
    public function testDateFrom($input, $output)
    {
        $this->param->setDateFrom($input);
        $this->assertEquals($output, $this->param->getDateFrom());
    }

    public function providerDateFrom()
    {
        return array(
            array('2014-01-01', '2014-01-01'),
        );
    }

    /**
     * @dataProvider providerDateTo
     */
    public function testDateTo($input, $output)
    {
        $this->param->setDateTo($input);
        $this->assertEquals($output, $this->param->getDateTo());
    }

    public function providerDateTo()
    {
        return array(
            array('2014-01-01', '2014-01-01'),
        );
    }

    /**
     * @dataProvider providerStatus
     */
    public function testStatus($input, $output)
    {
        $this->param->setStatus($input);
        $this->assertEquals($output, $this->param->getStatus());
    }

    public function providerStatus()
    {
        return array(
            array('ok', 'ok'),
            array(true, true),
        );
    }

    public function testGetSortName()
    {
        $this->param->setSortColumnId('completedOn');
        $sortName = $this->param->getSortName();
        $this->assertEquals('completedOn', $sortName);
    }

    public function testGetSortNameWithDefault()
    {
        $this->param->setSortColumnId('not_existing_sort_col');
        $sortName = $this->param->getSortName();
        $this->assertEquals(TransactionSearchParam::DEFAULT_SORT_COL, $sortName);
    }

    public function testProcess()
    {
        $this->param->setOrganisationId(1);
        $return = $this->param->process();
        $this->assertEquals($this->param, $return);
    }

    /**
     * @expectedException \UnexpectedValueException
     */
    public function testProcessWithNoOrganisation()
    {
        $this->param->process();
    }

    public function testToArray()
    {
        $data = $this->param->toArray();
        $this->assertArrayHasKey('organisationId', $data);
        $this->assertArrayHasKey('status', $data);
        $this->assertArrayHasKey('dateFrom', $data);
        $this->assertArrayHasKey('dateTo', $data);
    }
}


text:
using System;
using System.Threading;
using System.Threading.Tasks;

namespace PenguinUpload.Infrastructure.Concurrency
{
    public class UserLock
    {
        private readonly AutoResetEvent _readFree = new AutoResetEvent(true);
        private readonly AutoResetEvent _writeFree = new AutoResetEvent(true);

        #region Basic Functionality

        public void ObtainExclusiveWrite()
        {
            // Wait for exclusive read and write
            _writeFree.WaitOne();
            _readFree.WaitOne();
        }

        public async Task ObtainExclusiveWriteAsync()
        {
            await Task.Run(() => ObtainExclusiveWrite());
        }

        public void ReleaseExclusiveWrite()
        {
            // Release exclusive read and write
            _writeFree.Set();
            _readFree.Set();
        }

        public void ObtainExclusiveRead()
        {
            _readFree.WaitOne();
        }

        public async Task ObtainExclusiveReadAsync()
        {
            await Task.Run(() => ObtainExclusiveRead());
        }

        public void ReleaseExclusiveRead()
        {
            _readFree.Set();
        }

        public void ObtainConcurrentRead()
        {
            // Lock writing, and allow multiple concurrent reads
            _writeFree.WaitOne();
        }

        public async Task ObtainConcurrentReadAsync()
        {
            await Task.Run(() => ObtainConcurrentRead());
        }

        public void ReleaseConcurrentRead()
        {
            // Allow writing again
            _writeFree.Set();
        }

        #endregion Basic Functionality

        #region Nicer API

        public async Task WithExclusiveWriteAsync(Task action)
        {
            await ObtainExclusiveWriteAsync();
            await action;
            ReleaseExclusiveWrite();
        }

        public async Task WithExclusiveWriteAsync(Func<Task> action)
        {
            await ObtainExclusiveWriteAsync();
            await action();
            ReleaseExclusiveWrite();
        }

        public async Task WithExclusiveReadAsync(Task action)
        {
            await ObtainExclusiveReadAsync();
            await action;
            ReleaseExclusiveRead();
        }

        public async Task WithExclusiveReadAsync(Func<Task> action)
        {
            await ObtainExclusiveReadAsync();
            await action();
            ReleaseExclusiveRead();
        }

        public async Task WithConcurrentReadAsync(Task action)
        {
            await ObtainConcurrentReadAsync();
            await action;
            ReleaseConcurrentRead();
        }

        public async Task WithConcurrentReadAsync(Func<Task> action)
        {
            await ObtainConcurrentReadAsync();
            await action();
            ReleaseConcurrentRead();
        }

        #endregion Nicer API
    }
}


text:
"""Categorical vocabulary tests."""

from __future__ import absolute_import
from __future__ import division
from __future__ import print_function

from tensorflow.contrib.learn.python.learn.preprocessing import categorical_vocabulary
from tensorflow.python.platform import test

class CategoricalVocabularyTest(test.TestCase):
  """Categorical vocabulary tests."""

  def testIntVocabulary(self):
    vocab = categorical_vocabulary.CategoricalVocabulary()
    self.assertEqual(vocab.get(1), 1)
    self.assertEqual(vocab.get(3), 2)
    self.assertEqual(vocab.get(2), 3)
    self.assertEqual(vocab.get(3), 2)
    # This vocab doesn't handle nan specially.
    self.assertEqual(vocab.get(float('nan')), 4)
    self.assertEqual(len(vocab), 5)

  def testWordVocabulary(self):
    vocab = categorical_vocabulary.CategoricalVocabulary()
    self.assertEqual(vocab.get('a'), 1)
    self.assertEqual(vocab.get('b'), 2)
    self.assertEqual(vocab.get('a'), 1)
    self.assertEqual(vocab.get('b'), 2)

  def testCountsTrim(self):
    vocab = categorical_vocabulary.CategoricalVocabulary()
    vocab.get('c')
    vocab.add('c', 5)
    vocab.get('a')
    vocab.add('a', 10)
    # not in vocab yet, skips.
    vocab.add('b', 5)
    vocab.add('d', 12)
    vocab.trim(7, 11)
    vocab.freeze()
    self.assertEqual(vocab.get('b'), 0)
    self.assertEqual(vocab.get('c'), 0)
    self.assertEqual(len(vocab), 2)
    self.assertEqual(vocab.get('a'), 1)

if __name__ == '__main__':
  test.main()


text:
class AddOperatersHeader < ActiveRecord::Migration
  def self.up
  	add_column :cm_db_operates, :user_id, :string
  	add_column :cm_db_operates, :response_header, :text
  	add_column :cm_db_operates, :url, :string
  	add_column :cm_db_operates, :request_header, :text
  end

  def self.down
    remove_column :cm_db_operates, :user_id
    remove_column :cm_db_operates, :response_header
    remove_column :cm_db_operates, :url
    remove_column :cm_db_operates, :request_header
  end
end


text:
layout: page
title: Bradley 45th Anniversary
date: 2016-05-24
author: Michael Villanueva
tags: weekly links, java
status: published
summary: Nunc a auctor nisi. Sed quis sem dolor. Praesent euismod.
banner: images/banner/leisure-04.jpg
booking:
  startDate: 06/23/2018
  endDate: 06/27/2018
  ctyhocn: AISHSHX
  groupCode: B4A
published: true
---
Maecenas dictum, lorem non vestibulum euismod, sapien leo tincidunt sapien, ut venenatis purus leo non urna. Nullam malesuada ex risus, quis mollis lorem condimentum eget. Aenean faucibus mollis neque venenatis fringilla. Sed efficitur turpis eget eleifend consectetur. Nam quam lectus, feugiat vel neque quis, scelerisque imperdiet nibh. Proin ornare gravida enim, eget tempor justo ullamcorper et. Morbi congue aliquam lectus at fermentum. Nulla facilisi. Curabitur eget quam in ipsum convallis tincidunt. Sed tempor nec lectus non condimentum. Sed pulvinar arcu eu massa gravida, id convallis tortor placerat. Lorem ipsum dolor sit amet, consectetur adipiscing elit. Fusce dignissim auctor est ac posuere. Nam sit amet tincidunt augue. Cras aliquam facilisis consectetur. Suspendisse egestas pharetra eros, in vestibulum dui blandit id.

* Donec dictum erat ac dictum pharetra
* Cras aliquet sem mattis arcu hendrerit feugiat
* Ut non ligula blandit, auctor elit a, varius urna
* Suspendisse viverra mauris id dignissim bibendum
* Sed vehicula nulla eu tortor sollicitudin ultrices a condimentum enim.

Vivamus et magna nibh. Sed viverra lectus vitae semper blandit. Vivamus sit amet est rhoncus sapien sollicitudin dignissim. Praesent nec sagittis ipsum. Vivamus sit amet porta leo. Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas. Sed congue nunc ut rhoncus dictum. Nam sed massa ut ipsum interdum iaculis. Sed mi mi, sollicitudin vel mi et, porttitor rhoncus elit. Morbi consequat dolor hendrerit, fermentum dolor eget, auctor urna.


text:
package org.librairy.modeler.w2v.services;

import org.librairy.modeler.w2v.helper.ModelingHelper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.concurrent.ThreadPoolTaskScheduler;

import javax.annotation.PostConstruct;
import java.text.SimpleDateFormat;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ScheduledFuture;

/**
 * Created by cbadenes on 11/01/16.
 */
public abstract class AbstractService {

    private static final Logger LOG = LoggerFactory.getLogger(AbstractService.class);

    protected ConcurrentHashMap<String,ScheduledFuture<?>> tasks;

    protected ThreadPoolTaskScheduler threadpool;

    @Autowired
    protected ModelingHelper helper;

    protected SimpleDateFormat timeFormatter = new SimpleDateFormat("HH:mm:ssZ");

    @PostConstruct
    public void setup(){
        this.tasks = new ConcurrentHashMap<>();

        this.threadpool = new ThreadPoolTaskScheduler();
        this.threadpool.setPoolSize(1);
        this.threadpool.initialize();

    }

}


text:
<?php get_header( 'buddypress' ); ?>

		<?php do_action( 'bp_before_activation_page' ); ?>

<?php if ( bp_account_was_activated() ) :
				_e( 'Account Activated', 'vibe' );
			else :
				_e( 'Activate your Account', 'vibe' );
			endif; ?>

			<?php do_action( 'template_notices' ); ?>

			<?php do_action( 'bp_before_activate_content' ); ?>

			<?php if ( bp_account_was_activated() ) : ?>

				<?php if ( isset( $_GET['e'] ) ) : ?>

<?php _e( 'Your account was activated successfully! Your account details have been sent to you in a separate email.', 'vibe' ); ?>

				<?php else : ?>

<?php printf( __( 'Your account was activated successfully! You can now log in with the username and password you provided when you signed up.', 'vibe' ), wp_login_url( bp_get_root_domain() ) ); ?>

				<?php endif; ?>

			<?php else : ?>

<?php _e( 'Please provide a valid activation key.', 'vibe' ); ?>

				<form action="" method="get" class="standard-form" id="activation-form">

					<?php _e( 'Activation Key:', 'vibe' ); ?>
					<input type="text" name="key" id="key" value="" />

						<input type="submit" name="submit" class="button" value="<?php _e( 'Activate', 'vibe' ); ?>" />

				</form>

			<?php endif; ?>

			<?php do_action( 'bp_after_activate_content' ); ?>

		<?php do_action( 'bp_after_activation_page' ); ?>

			<?php
		 		$sidebar = apply_filters('wplms_sidebar','buddypress',get_the_ID());
                if ( !function_exists('dynamic_sidebar')|| !dynamic_sidebar($sidebar) ) : ?>
           	<?php endif; ?>

<?php get_footer( 'buddypress' ); ?>


text:
<?xml version="1.0" encoding="UTF-8"?>
<testsuite name="Safari_6533185_Mac_OS.NLBServer_url" errors="0" failures="0" tests="3" time="0.0020">
<testcase classname="Safari_6533185_Mac_OS.NLBServer_url" name="test this.server with base url, empty argument url and no parameters" time="0.0010"/>
<testcase classname="Safari_6533185_Mac_OS.NLBServer_url" name="test this.server with base url, argument url and no parameters" time="0.0"/>
<testcase classname="Safari_6533185_Mac_OS.NLBServer_url" name="test base url and no parameters" time="0.0010"/>
</testsuite>


text:
package graphtest

import (
	"bytes"
	"io/ioutil"
	"math/rand"
	"os"
	"path"
	"reflect"
	"testing"
	"unsafe"

	"github.com/docker/docker/daemon/graphdriver"
	"github.com/docker/docker/daemon/graphdriver/quota"
	"github.com/docker/docker/pkg/stringid"
	"github.com/docker/go-units"
	"github.com/stretchr/testify/assert"
	"github.com/stretchr/testify/require"
	"golang.org/x/sys/unix"
)

var (
	drv *Driver
)

// Driver conforms to graphdriver.Driver interface and
// contains information such as root and reference count of the number of clients using it.
// This helps in testing drivers added into the framework.
type Driver struct {
	graphdriver.Driver
	root     string
	refCount int
}

func newDriver(t testing.TB, name string, options []string) *Driver {
	root, err := ioutil.TempDir("", "docker-graphtest-")
	require.NoError(t, err)

	require.NoError(t, os.MkdirAll(root, 0755))
	d, err := graphdriver.GetDriver(name, nil, graphdriver.Options{DriverOptions: options, Root: root})
	if err != nil {
		t.Logf("graphdriver: %v\n", err)
		if graphdriver.IsDriverNotSupported(err) {
			t.Skipf("Driver %s not supported", name)
		}
		t.Fatal(err)
	}
	return &Driver{d, root, 1}
}

func cleanup(t testing.TB, d *Driver) {
	if err := drv.Cleanup(); err != nil {
		t.Fatal(err)
	}
	os.RemoveAll(d.root)
}

// GetDriver create a new driver with given name or return an existing driver with the name updating the reference count.
func GetDriver(t testing.TB, name string, options ...string) graphdriver.Driver {
	if drv == nil {
		drv = newDriver(t, name, options)
	} else {
		drv.refCount++
	}
	return drv
}

// PutDriver removes the driver if it is no longer used and updates the reference count.
func PutDriver(t testing.TB) {
	if drv == nil {
		t.Skip("No driver to put!")
	}
	drv.refCount--
	if drv.refCount == 0 {
		cleanup(t, drv)
		drv = nil
	}
}

// DriverTestCreateEmpty creates a new image and verifies it is empty and the right metadata
func DriverTestCreateEmpty(t testing.TB, drivername string, driverOptions ...string) {
	driver := GetDriver(t, drivername, driverOptions...)
	defer PutDriver(t)

	err := driver.Create("empty", "", nil)
	require.NoError(t, err)

	defer func() {
		require.NoError(t, driver.Remove("empty"))
	}()

	if !driver.Exists("empty") {
		t.Fatal("Newly created image doesn't exist")
	}

	dir, err := driver.Get("empty", "")
	require.NoError(t, err)

	verifyFile(t, dir.Path(), 0755|os.ModeDir, 0, 0)

	// Verify that the directory is empty
	fis, err := readDir(dir, dir.Path())
	require.NoError(t, err)
	assert.Len(t, fis, 0)

	driver.Put("empty")
}

// DriverTestCreateBase create a base driver and verify.
func DriverTestCreateBase(t testing.TB, drivername string, driverOptions ...string) {
	driver := GetDriver(t, drivername, driverOptions...)
	defer PutDriver(t)

	createBase(t, driver, "Base")
	defer func() {
		require.NoError(t, driver.Remove("Base"))
	}()
	verifyBase(t, driver, "Base")
}

// DriverTestCreateSnap Create a driver and snap and verify.
func DriverTestCreateSnap(t testing.TB, drivername string, driverOptions ...string) {
	driver := GetDriver(t, drivername, driverOptions...)
	defer PutDriver(t)

	createBase(t, driver, "Base")
	defer func() {
		require.NoError(t, driver.Remove("Base"))
	}()

	err := driver.Create("Snap", "Base", nil)
	require.NoError(t, err)
	defer func() {
		require.NoError(t, driver.Remove("Snap"))
	}()

	verifyBase(t, driver, "Snap")
}

// DriverTestDeepLayerRead reads a file from a lower layer under a given number of layers
func DriverTestDeepLayerRead(t testing.TB, layerCount int, drivername string, driverOptions ...string) {
	driver := GetDriver(t, drivername, driverOptions...)
	defer PutDriver(t)

	base := stringid.GenerateRandomID()
	if err := driver.Create(base, "", nil); err != nil {
		t.Fatal(err)
	}

	content := []byte("test content")
	if err := addFile(driver, base, "testfile.txt", content); err != nil {
		t.Fatal(err)
	}

	topLayer, err := addManyLayers(driver, base, layerCount)
	if err != nil {
		t.Fatal(err)
	}

	err = checkManyLayers(driver, topLayer, layerCount)
	if err != nil {
		t.Fatal(err)
	}

	if err := checkFile(driver, topLayer, "testfile.txt", content); err != nil {
		t.Fatal(err)
	}
}

// DriverTestDiffApply tests diffing and applying produces the same layer
func DriverTestDiffApply(t testing.TB, fileCount int, drivername string, driverOptions ...string) {
	driver := GetDriver(t, drivername, driverOptions...)
	defer PutDriver(t)
	base := stringid.GenerateRandomID()
	upper := stringid.GenerateRandomID()
	deleteFile := "file-remove.txt"
	deleteFileContent := []byte("This file should get removed in upper!")
	deleteDir := "var/lib"

	if err := driver.Create(base, "", nil); err != nil {
		t.Fatal(err)
	}

	if err := addManyFiles(driver, base, fileCount, 3); err != nil {
		t.Fatal(err)
	}

	if err := addFile(driver, base, deleteFile, deleteFileContent); err != nil {
		t.Fatal(err)
	}

	if err := addDirectory(driver, base, deleteDir); err != nil {
		t.Fatal(err)
	}

	if err := driver.Create(upper, base, nil); err != nil {
		t.Fatal(err)
	}

	if err := addManyFiles(driver, upper, fileCount, 6); err != nil {
		t.Fatal(err)
	}

	if err := removeAll(driver, upper, deleteFile, deleteDir); err != nil {
		t.Fatal(err)
	}

	diffSize, err := driver.DiffSize(upper, "")
	if err != nil {
		t.Fatal(err)
	}

	diff := stringid.GenerateRandomID()
	if err := driver.Create(diff, base, nil); err != nil {
		t.Fatal(err)
	}

	if err := checkManyFiles(driver, diff, fileCount, 3); err != nil {
		t.Fatal(err)
	}

	if err := checkFile(driver, diff, deleteFile, deleteFileContent); err != nil {
		t.Fatal(err)
	}

	arch, err := driver.Diff(upper, base)
	if err != nil {
		t.Fatal(err)
	}

	buf := bytes.NewBuffer(nil)
	if _, err := buf.ReadFrom(arch); err != nil {
		t.Fatal(err)
	}
	if err := arch.Close(); err != nil {
		t.Fatal(err)
	}

	applyDiffSize, err := driver.ApplyDiff(diff, base, bytes.NewReader(buf.Bytes()))
	if err != nil {
		t.Fatal(err)
	}

	if applyDiffSize != diffSize {
		t.Fatalf("Apply diff size different, got %d, expected %d", applyDiffSize, diffSize)
	}

	if err := checkManyFiles(driver, diff, fileCount, 6); err != nil {
		t.Fatal(err)
	}

	if err := checkFileRemoved(driver, diff, deleteFile); err != nil {
		t.Fatal(err)
	}

	if err := checkFileRemoved(driver, diff, deleteDir); err != nil {
		t.Fatal(err)
	}
}

// DriverTestChanges tests computed changes on a layer matches changes made
func DriverTestChanges(t testing.TB, drivername string, driverOptions ...string) {
	driver := GetDriver(t, drivername, driverOptions...)
	defer PutDriver(t)
	base := stringid.GenerateRandomID()
	upper := stringid.GenerateRandomID()
	if err := driver.Create(base, "", nil); err != nil {
		t.Fatal(err)
	}

	if err := addManyFiles(driver, base, 20, 3); err != nil {
		t.Fatal(err)
	}

	if err := driver.Create(upper, base, nil); err != nil {
		t.Fatal(err)
	}

	expectedChanges, err := changeManyFiles(driver, upper, 20, 6)
	if err != nil {
		t.Fatal(err)
	}

	changes, err := driver.Changes(upper, base)
	if err != nil {
		t.Fatal(err)
	}

	if err = checkChanges(expectedChanges, changes); err != nil {
		t.Fatal(err)
	}
}

func writeRandomFile(path string, size uint64) error {
	buf := make([]int64, size/8)

	r := rand.NewSource(0)
	for i := range buf {
		buf[i] = r.Int63()
	}

	// Cast to []byte
	header := *(*reflect.SliceHeader)(unsafe.Pointer(&buf))
	header.Len *= 8
	header.Cap *= 8
	data := *(*[]byte)(unsafe.Pointer(&header))

	return ioutil.WriteFile(path, data, 0700)
}

// DriverTestSetQuota Create a driver and test setting quota.
func DriverTestSetQuota(t *testing.T, drivername string, required bool) {
	driver := GetDriver(t, drivername)
	defer PutDriver(t)

	createBase(t, driver, "Base")
	createOpts := &graphdriver.CreateOpts{}
	createOpts.StorageOpt = make(map[string]string, 1)
	createOpts.StorageOpt["size"] = "50M"
	layerName := drivername + "Test"
	if err := driver.CreateReadWrite(layerName, "Base", createOpts); err == quota.ErrQuotaNotSupported && !required {
		t.Skipf("Quota not supported on underlying filesystem: %v", err)
	} else if err != nil {
		t.Fatal(err)
	}

	mountPath, err := driver.Get(layerName, "")
	if err != nil {
		t.Fatal(err)
	}

	quota := uint64(50 * units.MiB)

	// Try to write a file smaller than quota, and ensure it works
	err = writeRandomFile(path.Join(mountPath.Path(), "smallfile"), quota/2)
	if err != nil {
		t.Fatal(err)
	}
	defer os.Remove(path.Join(mountPath.Path(), "smallfile"))

	// Try to write a file bigger than quota. We've already filled up half the quota, so hitting the limit should be easy
	err = writeRandomFile(path.Join(mountPath.Path(), "bigfile"), quota)
	if err == nil {
		t.Fatalf("expected write to fail(), instead had success")
	}
	if pathError, ok := err.(*os.PathError); ok && pathError.Err != unix.EDQUOT && pathError.Err != unix.ENOSPC {
		os.Remove(path.Join(mountPath.Path(), "bigfile"))
		t.Fatalf("expect write() to fail with %v or %v, got %v", unix.EDQUOT, unix.ENOSPC, pathError.Err)
	}
}


text:
using GS.Contract.DataFeed;
using GS.iFX.Common;
using GS.iFX.TestUI;
using GS.Proxy.DataFeed;
using System;

namespace GS.Test.Client.DataSourceSimulator
{
    public class Program
    {
        private static string m_ThisName = "DataSourceSimulatorClient";
        private static int m_MsgSeqNumber;
        private static int m_SourceId;
        private static int m_SourceGroupId;

        public static void Main(string[] args)
        {
            Console.Title = m_ThisName;
            Console.WriteLine("{0}.Main(): Press <ENTER> to ENQUEUE one", m_ThisName);
            Console.WriteLine("  test message to SB queue '{0}' via WCF NetMessagingBinding",
                               ConstantsNEnums.IngestionQueueName);
            InitSourceIds(args);

            while (true)
            {
                string userInput = PauseTillUserPressesEnter_StatisticsOnS_ExitOnX().ToLower();
                if (userInput == "x")
                {
                    break;
                }
                else
                {
                    try
                    {
                        // Assume the queue exists, having been previously provisioned in Azure Portal.
                        Console.WriteLine("{0}.Main(): Enqueueing test message..", m_ThisName);

                        TestMessage msg = MakeTestMessage(m_SourceGroupId, m_SourceId, ++m_MsgSeqNumber);
                        IngestTestData(msg, ConstantsNEnums.IngestionQueueEndpointName);
                    }
                    catch (Exception ex)
                    {
                        Console.WriteLine("{0}.Main(): IngestTestData() proxy threw exception\n {1}.", m_ThisName, ex);
                    }
                }
            }
        }

        private static void InitSourceIds(string[] args)
        {
            // TODO 5-9-15 parse args for the source ids
            m_SourceId = 9;
            m_SourceGroupId = 99;
        }

        public static TestMessage MakeTestMessage(int sourceGroupId, int sourceId, int sourceSeqNo)
        {
            TestMessage msg = new TestMessage
            {
                MessageId = Guid.NewGuid(),
                SourceMsgSeqNumber = sourceSeqNo,
                SourceId = sourceId,
                SourceGroupId = sourceGroupId,
                MsgBody = "Testing, testing...."
            };
            return msg;
        }

        private static void IngestTestData(TestMessage msg, string queueName)
        {
            // Allow calculation of elapsed time: From proxy instantiation
            // till the message is received by the instantiated service instance.
            msg.MessageSendDateTime = DateTime.Now;

            // "Programming WCF Services" 3rd edition by Juval Lowy pp 259-260 recommends the
            // following form when needing to catch exceptions near the SendQueuedTestMessage().
            DataFeedsClient proxy = new DataFeedsClient(queueName);
            try
            {
                proxy.IngestTestData(msg);
                proxy.Close();
                Console.WriteLine("{0}.IngestTestData(): Test message enqueued Ok.", m_ThisName);
                ConsoleNTraceHelpers.DisplayTestMessage(msg);
            }
            catch (Exception ex)
            {
                ConsoleNTraceHelpers.DisplayExToConsoleNTrace(m_ThisName + ".IngestTestData(): ", ex);
                proxy.Abort();
            }
        }

        private static string PauseTillUserPressesEnter_StatisticsOnS_ExitOnX()
        {
            Console.WriteLine("Press <ENTER> to ENQUEUE an item, OR enter 'x'<ENTER> to EXIT....");
            string userInput = Console.ReadLine();
            return userInput;
        }
    }
}