text:
import operator

import numpy as np
import pytest

from pandas._libs.tslibs.period import IncompatibleFrequency
from pandas.errors import PerformanceWarning

import pandas as pd
from pandas import Period, PeriodIndex, Series, period_range
from pandas.core import ops
import pandas.util.testing as tm

from pandas.tseries.frequencies import to_offset

# ------------------------------------------------------------------
# Comparisons

class TestPeriodArrayLikeComparisons:
    # Comparison tests for PeriodDtype vectors fully parametrized over
    #  DataFrame/Series/PeriodIndex/PeriodArray.  Ideally all comparison
    #  tests will eventually end up here.

    def test_compare_zerodim(self, box_with_array):
        # GH#26689 make sure we unbox zero-dimensional arrays
        xbox = box_with_array if box_with_array is not pd.Index else np.ndarray

        pi = pd.period_range('2000', periods=4)
        other = np.array(pi.to_numpy()[0])

        pi = tm.box_expected(pi, box_with_array)
        result = pi <= other
        expected = np.array([True, False, False, False])
        expected = tm.box_expected(expected, xbox)
        tm.assert_equal(result, expected)

class TestPeriodIndexComparisons:
    # TODO: parameterize over boxes

    @pytest.mark.parametrize("other", ["2017", 2017])
    def test_eq(self, other):
        idx = PeriodIndex(['2017', '2017', '2018'], freq="D")
        expected = np.array([True, True, False])
        result = idx == other

        tm.assert_numpy_array_equal(result, expected)

    def test_pi_cmp_period(self):
        idx = period_range('2007-01', periods=20, freq='M')

        result = idx < idx[10]
        exp = idx.values < idx.values[10]
        tm.assert_numpy_array_equal(result, exp)

    # TODO: moved from test_datetime64; de-duplicate with version below
    def test_parr_cmp_period_scalar2(self, box_with_array):
        xbox = box_with_array if box_with_array is not pd.Index else np.ndarray

        pi = pd.period_range('2000-01-01', periods=10, freq='D')

        val = Period('2000-01-04', freq='D')
        expected = [x > val for x in pi]

        ser = tm.box_expected(pi, box_with_array)
        expected = tm.box_expected(expected, xbox)
        result = ser > val
        tm.assert_equal(result, expected)

        val = pi[5]
        result = ser > val
        expected = [x > val for x in pi]
        expected = tm.box_expected(expected, xbox)
        tm.assert_equal(result, expected)

    @pytest.mark.parametrize('freq', ['M', '2M', '3M'])
    def test_parr_cmp_period_scalar(self, freq, box_with_array):
        # GH#13200
        xbox = np.ndarray if box_with_array is pd.Index else box_with_array

        base = PeriodIndex(['2011-01', '2011-02', '2011-03', '2011-04'],
                           freq=freq)
        base = tm.box_expected(base, box_with_array)
        per = Period('2011-02', freq=freq)

        exp = np.array([False, True, False, False])
        exp = tm.box_expected(exp, xbox)
        tm.assert_equal(base == per, exp)
        tm.assert_equal(per == base, exp)

        exp = np.array([True, False, True, True])
        exp = tm.box_expected(exp, xbox)
        tm.assert_equal(base != per, exp)
        tm.assert_equal(per != base, exp)

        exp = np.array([False, False, True, True])
        exp = tm.box_expected(exp, xbox)
        tm.assert_equal(base > per, exp)
        tm.assert_equal(per < base, exp)

        exp = np.array([True, False, False, False])
        exp = tm.box_expected(exp, xbox)
        tm.assert_equal(base < per, exp)
        tm.assert_equal(per > base, exp)

        exp = np.array([False, True, True, True])
        exp = tm.box_expected(exp, xbox)
        tm.assert_equal(base >= per, exp)
        tm.assert_equal(per <= base, exp)

        exp = np.array([True, True, False, False])
        exp = tm.box_expected(exp, xbox)
        tm.assert_equal(base <= per, exp)
        tm.assert_equal(per >= base, exp)

    @pytest.mark.parametrize('freq', ['M', '2M', '3M'])
    def test_parr_cmp_pi(self, freq, box_with_array):
        # GH#13200
        xbox = np.ndarray if box_with_array is pd.Index else box_with_array

        base = PeriodIndex(['2011-01', '2011-02', '2011-03', '2011-04'],
                           freq=freq)
        base = tm.box_expected(base, box_with_array)

        # TODO: could also box idx?
        idx = PeriodIndex(['2011-02', '2011-01', '2011-03', '2011-05'],
                          freq=freq)

        exp = np.array([False, False, True, False])
        exp = tm.box_expected(exp, xbox)
        tm.assert_equal(base == idx, exp)

        exp = np.array([True, True, False, True])
        exp = tm.box_expected(exp, xbox)
        tm.assert_equal(base != idx, exp)

        exp = np.array([False, True, False, False])
        exp = tm.box_expected(exp, xbox)
        tm.assert_equal(base > idx, exp)

        exp = np.array([True, False, False, True])
        exp = tm.box_expected(exp, xbox)
        tm.assert_equal(base < idx, exp)

        exp = np.array([False, True, True, False])
        exp = tm.box_expected(exp, xbox)
        tm.assert_equal(base >= idx, exp)

        exp = np.array([True, False, True, True])
        exp = tm.box_expected(exp, xbox)
        tm.assert_equal(base <= idx, exp)

    @pytest.mark.parametrize('freq', ['M', '2M', '3M'])
    def test_parr_cmp_pi_mismatched_freq_raises(self, freq, box_with_array):
        # GH#13200
        # different base freq
        base = PeriodIndex(['2011-01', '2011-02', '2011-03', '2011-04'],
                           freq=freq)
        base = tm.box_expected(base, box_with_array)

        msg = "Input has different freq=A-DEC from "
        with pytest.raises(IncompatibleFrequency, match=msg):
            base <= Period('2011', freq='A')

        with pytest.raises(IncompatibleFrequency, match=msg):
            Period('2011', freq='A') >= base

        # TODO: Could parametrize over boxes for idx?
        idx = PeriodIndex(['2011', '2012', '2013', '2014'], freq='A')
        rev_msg = (r'Input has different freq=(M|2M|3M) from '
                   r'PeriodArray\(freq=A-DEC\)')
        idx_msg = rev_msg if box_with_array is tm.to_array else msg
        with pytest.raises(IncompatibleFrequency, match=idx_msg):
            base <= idx

        # Different frequency
        msg = "Input has different freq=4M from "
        with pytest.raises(IncompatibleFrequency, match=msg):
            base <= Period('2011', freq='4M')

        with pytest.raises(IncompatibleFrequency, match=msg):
            Period('2011', freq='4M') >= base

        idx = PeriodIndex(['2011', '2012', '2013', '2014'], freq='4M')
        rev_msg = (r'Input has different freq=(M|2M|3M) from '
                   r'PeriodArray\(freq=4M\)')
        idx_msg = rev_msg if box_with_array is tm.to_array else msg
        with pytest.raises(IncompatibleFrequency, match=idx_msg):
            base <= idx

    @pytest.mark.parametrize('freq', ['M', '2M', '3M'])
    def test_pi_cmp_nat(self, freq):
        idx1 = PeriodIndex(['2011-01', '2011-02', 'NaT', '2011-05'], freq=freq)

        result = idx1 > Period('2011-02', freq=freq)
        exp = np.array([False, False, False, True])
        tm.assert_numpy_array_equal(result, exp)
        result = Period('2011-02', freq=freq) < idx1
        tm.assert_numpy_array_equal(result, exp)

        result = idx1 == Period('NaT', freq=freq)
        exp = np.array([False, False, False, False])
        tm.assert_numpy_array_equal(result, exp)
        result = Period('NaT', freq=freq) == idx1
        tm.assert_numpy_array_equal(result, exp)

        result = idx1 != Period('NaT', freq=freq)
        exp = np.array([True, True, True, True])
        tm.assert_numpy_array_equal(result, exp)
        result = Period('NaT', freq=freq) != idx1
        tm.assert_numpy_array_equal(result, exp)

        idx2 = PeriodIndex(['2011-02', '2011-01', '2011-04', 'NaT'], freq=freq)
        result = idx1 < idx2
        exp = np.array([True, False, False, False])
        tm.assert_numpy_array_equal(result, exp)

        result = idx1 == idx2
        exp = np.array([False, False, False, False])
        tm.assert_numpy_array_equal(result, exp)

        result = idx1 != idx2
        exp = np.array([True, True, True, True])
        tm.assert_numpy_array_equal(result, exp)

        result = idx1 == idx1
        exp = np.array([True, True, False, True])
        tm.assert_numpy_array_equal(result, exp)

        result = idx1 != idx1
        exp = np.array([False, False, True, False])
        tm.assert_numpy_array_equal(result, exp)

    @pytest.mark.parametrize('freq', ['M', '2M', '3M'])
    def test_pi_cmp_nat_mismatched_freq_raises(self, freq):
        idx1 = PeriodIndex(['2011-01', '2011-02', 'NaT', '2011-05'], freq=freq)

        diff = PeriodIndex(['2011-02', '2011-01', '2011-04', 'NaT'], freq='4M')
        msg = "Input has different freq=4M from Period(Array|Index)"
        with pytest.raises(IncompatibleFrequency, match=msg):
            idx1 > diff

        with pytest.raises(IncompatibleFrequency, match=msg):
            idx1 == diff

    # TODO: De-duplicate with test_pi_cmp_nat
    @pytest.mark.parametrize('dtype', [object, None])
    def test_comp_nat(self, dtype):
        left = pd.PeriodIndex([pd.Period('2011-01-01'), pd.NaT,
                               pd.Period('2011-01-03')])
        right = pd.PeriodIndex([pd.NaT, pd.NaT, pd.Period('2011-01-03')])

        if dtype is not None:
            left = left.astype(dtype)
            right = right.astype(dtype)

        result = left == right
        expected = np.array([False, False, True])
        tm.assert_numpy_array_equal(result, expected)

        result = left != right
        expected = np.array([True, True, False])
        tm.assert_numpy_array_equal(result, expected)

        expected = np.array([False, False, False])
        tm.assert_numpy_array_equal(left == pd.NaT, expected)
        tm.assert_numpy_array_equal(pd.NaT == right, expected)

        expected = np.array([True, True, True])
        tm.assert_numpy_array_equal(left != pd.NaT, expected)
        tm.assert_numpy_array_equal(pd.NaT != left, expected)

        expected = np.array([False, False, False])
        tm.assert_numpy_array_equal(left < pd.NaT, expected)
        tm.assert_numpy_array_equal(pd.NaT > left, expected)

class TestPeriodSeriesComparisons:
    def test_cmp_series_period_series_mixed_freq(self):
        # GH#13200
        base = Series([Period('2011', freq='A'),
                       Period('2011-02', freq='M'),
                       Period('2013', freq='A'),
                       Period('2011-04', freq='M')])

        ser = Series([Period('2012', freq='A'),
                      Period('2011-01', freq='M'),
                      Period('2013', freq='A'),
                      Period('2011-05', freq='M')])

        exp = Series([False, False, True, False])
        tm.assert_series_equal(base == ser, exp)

        exp = Series([True, True, False, True])
        tm.assert_series_equal(base != ser, exp)

        exp = Series([False, True, False, False])
        tm.assert_series_equal(base > ser, exp)

        exp = Series([True, False, False, True])
        tm.assert_series_equal(base < ser, exp)

        exp = Series([False, True, True, False])
        tm.assert_series_equal(base >= ser, exp)

        exp = Series([True, False, True, True])
        tm.assert_series_equal(base <= ser, exp)

class TestPeriodIndexSeriesComparisonConsistency:
    """ Test PeriodIndex and Period Series Ops consistency """
    # TODO: needs parametrization+de-duplication

    def _check(self, values, func, expected):
        # Test PeriodIndex and Period Series Ops consistency

        idx = pd.PeriodIndex(values)
        result = func(idx)

        # check that we don't pass an unwanted type to tm.assert_equal
        assert isinstance(expected, (pd.Index, np.ndarray))
        tm.assert_equal(result, expected)

        s = pd.Series(values)
        result = func(s)

        exp = pd.Series(expected, name=values.name)
        tm.assert_series_equal(result, exp)

    def test_pi_comp_period(self):
        idx = PeriodIndex(['2011-01', '2011-02', '2011-03',
                           '2011-04'], freq='M', name='idx')

        f = lambda x: x == pd.Period('2011-03', freq='M')
        exp = np.array([False, False, True, False], dtype=np.bool)
        self._check(idx, f, exp)
        f = lambda x: pd.Period('2011-03', freq='M') == x
        self._check(idx, f, exp)

        f = lambda x: x != pd.Period('2011-03', freq='M')
        exp = np.array([True, True, False, True], dtype=np.bool)
        self._check(idx, f, exp)
        f = lambda x: pd.Period('2011-03', freq='M') != x
        self._check(idx, f, exp)

        f = lambda x: pd.Period('2011-03', freq='M') >= x
        exp = np.array([True, True, True, False], dtype=np.bool)
        self._check(idx, f, exp)

        f = lambda x: x > pd.Period('2011-03', freq='M')
        exp = np.array([False, False, False, True], dtype=np.bool)
        self._check(idx, f, exp)

        f = lambda x: pd.Period('2011-03', freq='M') >= x
        exp = np.array([True, True, True, False], dtype=np.bool)
        self._check(idx, f, exp)

    def test_pi_comp_period_nat(self):
        idx = PeriodIndex(['2011-01', 'NaT', '2011-03',
                           '2011-04'], freq='M', name='idx')

        f = lambda x: x == pd.Period('2011-03', freq='M')
        exp = np.array([False, False, True, False], dtype=np.bool)
        self._check(idx, f, exp)
        f = lambda x: pd.Period('2011-03', freq='M') == x
        self._check(idx, f, exp)

        f = lambda x: x == pd.NaT
        exp = np.array([False, False, False, False], dtype=np.bool)
        self._check(idx, f, exp)
        f = lambda x: pd.NaT == x
        self._check(idx, f, exp)

        f = lambda x: x != pd.Period('2011-03', freq='M')
        exp = np.array([True, True, False, True], dtype=np.bool)
        self._check(idx, f, exp)
        f = lambda x: pd.Period('2011-03', freq='M') != x
        self._check(idx, f, exp)

        f = lambda x: x != pd.NaT
        exp = np.array([True, True, True, True], dtype=np.bool)
        self._check(idx, f, exp)
        f = lambda x: pd.NaT != x
        self._check(idx, f, exp)

        f = lambda x: pd.Period('2011-03', freq='M') >= x
        exp = np.array([True, False, True, False], dtype=np.bool)
        self._check(idx, f, exp)

        f = lambda x: x < pd.Period('2011-03', freq='M')
        exp = np.array([True, False, False, False], dtype=np.bool)
        self._check(idx, f, exp)

        f = lambda x: x > pd.NaT
        exp = np.array([False, False, False, False], dtype=np.bool)
        self._check(idx, f, exp)

        f = lambda x: pd.NaT >= x
        exp = np.array([False, False, False, False], dtype=np.bool)
        self._check(idx, f, exp)

# ------------------------------------------------------------------
# Arithmetic

class TestPeriodFrameArithmetic:

    def test_ops_frame_period(self):
        # GH#13043
        df = pd.DataFrame({'A': [pd.Period('2015-01', freq='M'),
                                 pd.Period('2015-02', freq='M')],
                           'B': [pd.Period('2014-01', freq='M'),
                                 pd.Period('2014-02', freq='M')]})
        assert df['A'].dtype == 'Period[M]'
        assert df['B'].dtype == 'Period[M]'

        p = pd.Period('2015-03', freq='M')
        off = p.freq
        # dtype will be object because of original dtype
        exp = pd.DataFrame({'A': np.array([2 * off, 1 * off], dtype=object),
                            'B': np.array([14 * off, 13 * off], dtype=object)})
        tm.assert_frame_equal(p - df, exp)
        tm.assert_frame_equal(df - p, -1 * exp)

        df2 = pd.DataFrame({'A': [pd.Period('2015-05', freq='M'),
                                  pd.Period('2015-06', freq='M')],
                            'B': [pd.Period('2015-05', freq='M'),
                                  pd.Period('2015-06', freq='M')]})
        assert df2['A'].dtype == 'Period[M]'
        assert df2['B'].dtype == 'Period[M]'

        exp = pd.DataFrame({'A': np.array([4 * off, 4 * off], dtype=object),
                            'B': np.array([16 * off, 16 * off], dtype=object)})
        tm.assert_frame_equal(df2 - df, exp)
        tm.assert_frame_equal(df - df2, -1 * exp)

class TestPeriodIndexArithmetic:
    # ---------------------------------------------------------------
    # __add__/__sub__ with PeriodIndex
    # PeriodIndex + other is defined for integers and timedelta-like others
    # PeriodIndex - other is defined for integers, timedelta-like others,
    #   and PeriodIndex (with matching freq)

    def test_parr_add_iadd_parr_raises(self, box_with_array):
        rng = pd.period_range('1/1/2000', freq='D', periods=5)
        other = pd.period_range('1/6/2000', freq='D', periods=5)
        # TODO: parametrize over boxes for other?

        rng = tm.box_expected(rng, box_with_array)
        # An earlier implementation of PeriodIndex addition performed
        # a set operation (union).  This has since been changed to
        # raise a TypeError. See GH#14164 and GH#13077 for historical
        # reference.
        with pytest.raises(TypeError):
            rng + other

        with pytest.raises(TypeError):
            rng += other

    def test_pi_sub_isub_pi(self):
        # GH#20049
        # For historical reference see GH#14164, GH#13077.
        # PeriodIndex subtraction originally performed set difference,
        # then changed to raise TypeError before being implemented in GH#20049
        rng = pd.period_range('1/1/2000', freq='D', periods=5)
        other = pd.period_range('1/6/2000', freq='D', periods=5)

        off = rng.freq
        expected = pd.Index([-5 * off] * 5)
        result = rng - other
        tm.assert_index_equal(result, expected)

        rng -= other
        tm.assert_index_equal(rng, expected)

    def test_pi_sub_pi_with_nat(self):
        rng = pd.period_range('1/1/2000', freq='D', periods=5)
        other = rng[1:].insert(0, pd.NaT)
        assert other[1:].equals(rng[1:])

        result = rng - other
        off = rng.freq
        expected = pd.Index([pd.NaT, 0 * off, 0 * off, 0 * off, 0 * off])
        tm.assert_index_equal(result, expected)

    def test_parr_sub_pi_mismatched_freq(self, box_with_array):
        rng = pd.period_range('1/1/2000', freq='D', periods=5)
        other = pd.period_range('1/6/2000', freq='H', periods=5)
        # TODO: parametrize over boxes for other?

        rng = tm.box_expected(rng, box_with_array)
        with pytest.raises(IncompatibleFrequency):
            rng - other

    @pytest.mark.parametrize('n', [1, 2, 3, 4])
    def test_sub_n_gt_1_ticks(self, tick_classes, n):
        # GH 23878
        p1_d = '19910905'
        p2_d = '19920406'
        p1 = pd.PeriodIndex([p1_d], freq=tick_classes(n))
        p2 = pd.PeriodIndex([p2_d], freq=tick_classes(n))

        expected = (pd.PeriodIndex([p2_d], freq=p2.freq.base)
                    - pd.PeriodIndex([p1_d], freq=p1.freq.base))

        tm.assert_index_equal((p2 - p1), expected)

    @pytest.mark.parametrize('n', [1, 2, 3, 4])
    @pytest.mark.parametrize('offset, kwd_name', [
        (pd.offsets.YearEnd, 'month'),
        (pd.offsets.QuarterEnd, 'startingMonth'),
        (pd.offsets.MonthEnd, None),
        (pd.offsets.Week, 'weekday')
    ])
    def test_sub_n_gt_1_offsets(self, offset, kwd_name, n):
        # GH 23878
        kwds = {kwd_name: 3} if kwd_name is not None else {}
        p1_d = '19910905'
        p2_d = '19920406'
        freq = offset(n, normalize=False, **kwds)
        p1 = pd.PeriodIndex([p1_d], freq=freq)
        p2 = pd.PeriodIndex([p2_d], freq=freq)

        result = p2 - p1
        expected = (pd.PeriodIndex([p2_d], freq=freq.base)
                    - pd.PeriodIndex([p1_d], freq=freq.base))

        tm.assert_index_equal(result, expected)

    # -------------------------------------------------------------
    # Invalid Operations

    @pytest.mark.parametrize('other', [3.14, np.array([2.0, 3.0])])
    @pytest.mark.parametrize('op', [operator.add, ops.radd,
                                    operator.sub, ops.rsub])
    def test_parr_add_sub_float_raises(self, op, other, box_with_array):
        dti = pd.DatetimeIndex(['2011-01-01', '2011-01-02'], freq='D')
        pi = dti.to_period('D')
        pi = tm.box_expected(pi, box_with_array)
        with pytest.raises(TypeError):
            op(pi, other)

    @pytest.mark.parametrize('other', [pd.Timestamp.now(),
                                       pd.Timestamp.now().to_pydatetime(),
                                       pd.Timestamp.now().to_datetime64()])
    def test_parr_add_sub_datetime_scalar(self, other, box_with_array):
        # GH#23215
        rng = pd.period_range('1/1/2000', freq='D', periods=3)
        rng = tm.box_expected(rng, box_with_array)

        with pytest.raises(TypeError):
            rng + other
        with pytest.raises(TypeError):
            other + rng
        with pytest.raises(TypeError):
            rng - other
        with pytest.raises(TypeError):
            other - rng

    # -----------------------------------------------------------------
    # __add__/__sub__ with ndarray[datetime64] and ndarray[timedelta64]

    def test_parr_add_sub_dt64_array_raises(self, box_with_array):
        rng = pd.period_range('1/1/2000', freq='D', periods=3)
        dti = pd.date_range('2016-01-01', periods=3)
        dtarr = dti.values

        rng = tm.box_expected(rng, box_with_array)

        with pytest.raises(TypeError):
            rng + dtarr
        with pytest.raises(TypeError):
            dtarr + rng

        with pytest.raises(TypeError):
            rng - dtarr
        with pytest.raises(TypeError):
            dtarr - rng

    def test_pi_add_sub_td64_array_non_tick_raises(self):
        rng = pd.period_range('1/1/2000', freq='Q', periods=3)
        tdi = pd.TimedeltaIndex(['-1 Day', '-1 Day', '-1 Day'])
        tdarr = tdi.values

        with pytest.raises(IncompatibleFrequency):
            rng + tdarr
        with pytest.raises(IncompatibleFrequency):
            tdarr + rng

        with pytest.raises(IncompatibleFrequency):
            rng - tdarr
        with pytest.raises(TypeError):
            tdarr - rng

    def test_pi_add_sub_td64_array_tick(self):
        # PeriodIndex + Timedelta-like is allowed only with
        #   tick-like frequencies
        rng = pd.period_range('1/1/2000', freq='90D', periods=3)
        tdi = pd.TimedeltaIndex(['-1 Day', '-1 Day', '-1 Day'])
        tdarr = tdi.values

        expected = pd.period_range('12/31/1999', freq='90D', periods=3)
        result = rng + tdi
        tm.assert_index_equal(result, expected)
        result = rng + tdarr
        tm.assert_index_equal(result, expected)
        result = tdi + rng
        tm.assert_index_equal(result, expected)
        result = tdarr + rng
        tm.assert_index_equal(result, expected)

        expected = pd.period_range('1/2/2000', freq='90D', periods=3)

        result = rng - tdi
        tm.assert_index_equal(result, expected)
        result = rng - tdarr
        tm.assert_index_equal(result, expected)

        with pytest.raises(TypeError):
            tdarr - rng

        with pytest.raises(TypeError):
            tdi - rng

    # -----------------------------------------------------------------
    # operations with array/Index of DateOffset objects

    @pytest.mark.parametrize('box', [np.array, pd.Index])
    def test_pi_add_offset_array(self, box):
        # GH#18849
        pi = pd.PeriodIndex([pd.Period('2015Q1'), pd.Period('2016Q2')])
        offs = box([pd.offsets.QuarterEnd(n=1, startingMonth=12),
                    pd.offsets.QuarterEnd(n=-2, startingMonth=12)])
        expected = pd.PeriodIndex([pd.Period('2015Q2'), pd.Period('2015Q4')])

        with tm.assert_produces_warning(PerformanceWarning):
            res = pi + offs
        tm.assert_index_equal(res, expected)

        with tm.assert_produces_warning(PerformanceWarning):
            res2 = offs + pi
        tm.assert_index_equal(res2, expected)

        unanchored = np.array([pd.offsets.Hour(n=1),
                               pd.offsets.Minute(n=-2)])
        # addition/subtraction ops with incompatible offsets should issue
        # a PerformanceWarning and _then_ raise a TypeError.
        with pytest.raises(IncompatibleFrequency):
            with tm.assert_produces_warning(PerformanceWarning):
                pi + unanchored
        with pytest.raises(IncompatibleFrequency):
            with tm.assert_produces_warning(PerformanceWarning):
                unanchored + pi

    @pytest.mark.parametrize('box', [np.array, pd.Index])
    def test_pi_sub_offset_array(self, box):
        # GH#18824
        pi = pd.PeriodIndex([pd.Period('2015Q1'), pd.Period('2016Q2')])
        other = box([pd.offsets.QuarterEnd(n=1, startingMonth=12),
                     pd.offsets.QuarterEnd(n=-2, startingMonth=12)])

        expected = PeriodIndex([pi[n] - other[n] for n in range(len(pi))])

        with tm.assert_produces_warning(PerformanceWarning):
            res = pi - other
        tm.assert_index_equal(res, expected)

        anchored = box([pd.offsets.MonthEnd(), pd.offsets.Day(n=2)])

        # addition/subtraction ops with anchored offsets should issue
        # a PerformanceWarning and _then_ raise a TypeError.
        with pytest.raises(IncompatibleFrequency):
            with tm.assert_produces_warning(PerformanceWarning):
                pi - anchored
        with pytest.raises(IncompatibleFrequency):
            with tm.assert_produces_warning(PerformanceWarning):
                anchored - pi

    def test_pi_add_iadd_int(self, one):
        # Variants of `one` for #19012
        rng = pd.period_range('2000-01-01 09:00', freq='H', periods=10)
        result = rng + one
        expected = pd.period_range('2000-01-01 10:00', freq='H', periods=10)
        tm.assert_index_equal(result, expected)
        rng += one
        tm.assert_index_equal(rng, expected)

    def test_pi_sub_isub_int(self, one):
        """
        PeriodIndex.__sub__ and __isub__ with several representations of
        the integer 1, e.g. int, np.int64, np.uint8, ...
        """
        rng = pd.period_range('2000-01-01 09:00', freq='H', periods=10)
        result = rng - one
        expected = pd.period_range('2000-01-01 08:00', freq='H', periods=10)
        tm.assert_index_equal(result, expected)
        rng -= one
        tm.assert_index_equal(rng, expected)

    @pytest.mark.parametrize('five', [5, np.array(5, dtype=np.int64)])
    def test_pi_sub_intlike(self, five):
        rng = period_range('2007-01', periods=50)

        result = rng - five
        exp = rng + (-five)
        tm.assert_index_equal(result, exp)

    def test_pi_sub_isub_offset(self):
        # offset
        # DateOffset
        rng = pd.period_range('2014', '2024', freq='A')
        result = rng - pd.offsets.YearEnd(5)
        expected = pd.period_range('2009', '2019', freq='A')
        tm.assert_index_equal(result, expected)
        rng -= pd.offsets.YearEnd(5)
        tm.assert_index_equal(rng, expected)

        rng = pd.period_range('2014-01', '2016-12', freq='M')
        result = rng - pd.offsets.MonthEnd(5)
        expected = pd.period_range('2013-08', '2016-07', freq='M')
        tm.assert_index_equal(result, expected)

        rng -= pd.offsets.MonthEnd(5)
        tm.assert_index_equal(rng, expected)

    def test_pi_add_offset_n_gt1(self, box_transpose_fail):
        # GH#23215
        # add offset to PeriodIndex with freq.n > 1
        box, transpose = box_transpose_fail

        per = pd.Period('2016-01', freq='2M')
        pi = pd.PeriodIndex([per])

        expected = pd.PeriodIndex(['2016-03'], freq='2M')

        pi = tm.box_expected(pi, box, transpose=transpose)
        expected = tm.box_expected(expected, box, transpose=transpose)

        result = pi + per.freq
        tm.assert_equal(result, expected)

        result = per.freq + pi
        tm.assert_equal(result, expected)

    def test_pi_add_offset_n_gt1_not_divisible(self, box_with_array):
        # GH#23215
        # PeriodIndex with freq.n > 1 add offset with offset.n % freq.n != 0
        pi = pd.PeriodIndex(['2016-01'], freq='2M')
        expected = pd.PeriodIndex(['2016-04'], freq='2M')

        # FIXME: with transposing these tests fail
        pi = tm.box_expected(pi, box_with_array, transpose=False)
        expected = tm.box_expected(expected, box_with_array, transpose=False)

        result = pi + to_offset('3M')
        tm.assert_equal(result, expected)

        result = to_offset('3M') + pi
        tm.assert_equal(result, expected)

    # ---------------------------------------------------------------
    # __add__/__sub__ with integer arrays

    @pytest.mark.parametrize('int_holder', [np.array, pd.Index])
    @pytest.mark.parametrize('op', [operator.add, ops.radd])
    def test_pi_add_intarray(self, int_holder, op):
        # GH#19959
        pi = pd.PeriodIndex([pd.Period('2015Q1'), pd.Period('NaT')])
        other = int_holder([4, -1])

        result = op(pi, other)
        expected = pd.PeriodIndex([pd.Period('2016Q1'), pd.Period('NaT')])
        tm.assert_index_equal(result, expected)

    @pytest.mark.parametrize('int_holder', [np.array, pd.Index])
    def test_pi_sub_intarray(self, int_holder):
        # GH#19959
        pi = pd.PeriodIndex([pd.Period('2015Q1'), pd.Period('NaT')])
        other = int_holder([4, -1])

        result = pi - other
        expected = pd.PeriodIndex([pd.Period('2014Q1'), pd.Period('NaT')])
        tm.assert_index_equal(result, expected)

        with pytest.raises(TypeError):
            other - pi

    # ---------------------------------------------------------------
    # Timedelta-like (timedelta, timedelta64, Timedelta, Tick)
    # TODO: Some of these are misnomers because of non-Tick DateOffsets

    def test_pi_add_timedeltalike_minute_gt1(self, three_days):
        # GH#23031 adding a time-delta-like offset to a PeriodArray that has
        # minute frequency with n != 1.  A more general case is tested below
        # in test_pi_add_timedeltalike_tick_gt1, but here we write out the
        # expected result more explicitly.
        other = three_days
        rng = pd.period_range('2014-05-01', periods=3, freq='2D')

        expected = pd.PeriodIndex(['2014-05-04', '2014-05-06', '2014-05-08'],
                                  freq='2D')

        result = rng + other
        tm.assert_index_equal(result, expected)

        result = other + rng
        tm.assert_index_equal(result, expected)

        # subtraction
        expected = pd.PeriodIndex(['2014-04-28', '2014-04-30', '2014-05-02'],
                                  freq='2D')
        result = rng - other
        tm.assert_index_equal(result, expected)

        with pytest.raises(TypeError):
            other - rng

    @pytest.mark.parametrize('freqstr', ['5ns', '5us', '5ms',
                                         '5s', '5T', '5h', '5d'])
    def test_pi_add_timedeltalike_tick_gt1(self, three_days, freqstr):
        # GH#23031 adding a time-delta-like offset to a PeriodArray that has
        # tick-like frequency with n != 1
        other = three_days
        rng = pd.period_range('2014-05-01', periods=6, freq=freqstr)

        expected = pd.period_range(rng[0] + other, periods=6, freq=freqstr)

        result = rng + other
        tm.assert_index_equal(result, expected)

        result = other + rng
        tm.assert_index_equal(result, expected)

        # subtraction
        expected = pd.period_range(rng[0] - other, periods=6, freq=freqstr)
        result = rng - other
        tm.assert_index_equal(result, expected)

        with pytest.raises(TypeError):
            other - rng

    def test_pi_add_iadd_timedeltalike_daily(self, three_days):
        # Tick
        other = three_days
        rng = pd.period_range('2014-05-01', '2014-05-15', freq='D')
        expected = pd.period_range('2014-05-04', '2014-05-18', freq='D')

        result = rng + other
        tm.assert_index_equal(result, expected)

        rng += other
        tm.assert_index_equal(rng, expected)

    def test_pi_sub_isub_timedeltalike_daily(self, three_days):
        # Tick-like 3 Days
        other = three_days
        rng = pd.period_range('2014-05-01', '2014-05-15', freq='D')
        expected = pd.period_range('2014-04-28', '2014-05-12', freq='D')

        result = rng - other
        tm.assert_index_equal(result, expected)

        rng -= other
        tm.assert_index_equal(rng, expected)

    def test_pi_add_sub_timedeltalike_freq_mismatch_daily(self, not_daily):
        other = not_daily
        rng = pd.period_range('2014-05-01', '2014-05-15', freq='D')
        msg = 'Input has different freq(=.+)? from Period.*?\\(freq=D\\)'
        with pytest.raises(IncompatibleFrequency, match=msg):
            rng + other
        with pytest.raises(IncompatibleFrequency, match=msg):
            rng += other
        with pytest.raises(IncompatibleFrequency, match=msg):
            rng - other
        with pytest.raises(IncompatibleFrequency, match=msg):
            rng -= other

    def test_pi_add_iadd_timedeltalike_hourly(self, two_hours):
        other = two_hours
        rng = pd.period_range('2014-01-01 10:00', '2014-01-05 10:00', freq='H')
        expected = pd.period_range('2014-01-01 12:00', '2014-01-05 12:00',
                                   freq='H')

        result = rng + other
        tm.assert_index_equal(result, expected)

        rng += other
        tm.assert_index_equal(rng, expected)

    def test_pi_add_timedeltalike_mismatched_freq_hourly(self, not_hourly):
        other = not_hourly
        rng = pd.period_range('2014-01-01 10:00', '2014-01-05 10:00', freq='H')
        msg = 'Input has different freq(=.+)? from Period.*?\\(freq=H\\)'

        with pytest.raises(IncompatibleFrequency, match=msg):
            rng + other

        with pytest.raises(IncompatibleFrequency, match=msg):
            rng += other

    def test_pi_sub_isub_timedeltalike_hourly(self, two_hours):
        other = two_hours
        rng = pd.period_range('2014-01-01 10:00', '2014-01-05 10:00', freq='H')
        expected = pd.period_range('2014-01-01 08:00', '2014-01-05 08:00',
                                   freq='H')

        result = rng - other
        tm.assert_index_equal(result, expected)

        rng -= other
        tm.assert_index_equal(rng, expected)

    def test_add_iadd_timedeltalike_annual(self):
        # offset
        # DateOffset
        rng = pd.period_range('2014', '2024', freq='A')
        result = rng + pd.offsets.YearEnd(5)
        expected = pd.period_range('2019', '2029', freq='A')
        tm.assert_index_equal(result, expected)
        rng += pd.offsets.YearEnd(5)
        tm.assert_index_equal(rng, expected)

    def test_pi_add_sub_timedeltalike_freq_mismatch_annual(self,
                                                           mismatched_freq):
        other = mismatched_freq
        rng = pd.period_range('2014', '2024', freq='A')
        msg = ('Input has different freq(=.+)? '
               'from Period.*?\\(freq=A-DEC\\)')
        with pytest.raises(IncompatibleFrequency, match=msg):
            rng + other
        with pytest.raises(IncompatibleFrequency, match=msg):
            rng += other
        with pytest.raises(IncompatibleFrequency, match=msg):
            rng - other
        with pytest.raises(IncompatibleFrequency, match=msg):
            rng -= other

    def test_pi_add_iadd_timedeltalike_M(self):
        rng = pd.period_range('2014-01', '2016-12', freq='M')
        expected = pd.period_range('2014-06', '2017-05', freq='M')

        result = rng + pd.offsets.MonthEnd(5)
        tm.assert_index_equal(result, expected)

        rng += pd.offsets.MonthEnd(5)
        tm.assert_index_equal(rng, expected)

    def test_pi_add_sub_timedeltalike_freq_mismatch_monthly(self,
                                                            mismatched_freq):
        other = mismatched_freq
        rng = pd.period_range('2014-01', '2016-12', freq='M')
        msg = 'Input has different freq(=.+)? from Period.*?\\(freq=M\\)'
        with pytest.raises(IncompatibleFrequency, match=msg):
            rng + other
        with pytest.raises(IncompatibleFrequency, match=msg):
            rng += other
        with pytest.raises(IncompatibleFrequency, match=msg):
            rng - other
        with pytest.raises(IncompatibleFrequency, match=msg):
            rng -= other

    def test_parr_add_sub_td64_nat(self, box_transpose_fail):
        # GH#23320 special handling for timedelta64("NaT")
        box, transpose = box_transpose_fail

        pi = pd.period_range("1994-04-01", periods=9, freq="19D")
        other = np.timedelta64("NaT")
        expected = pd.PeriodIndex(["NaT"] * 9, freq="19D")

        obj = tm.box_expected(pi, box, transpose=transpose)
        expected = tm.box_expected(expected, box, transpose=transpose)

        result = obj + other
        tm.assert_equal(result, expected)
        result = other + obj
        tm.assert_equal(result, expected)
        result = obj - other
        tm.assert_equal(result, expected)
        with pytest.raises(TypeError):
            other - obj

class TestPeriodSeriesArithmetic:
    def test_ops_series_timedelta(self):
        # GH#13043
        ser = pd.Series([pd.Period('2015-01-01', freq='D'),
                         pd.Period('2015-01-02', freq='D')], name='xxx')
        assert ser.dtype == 'Period[D]'

        expected = pd.Series([pd.Period('2015-01-02', freq='D'),
                              pd.Period('2015-01-03', freq='D')], name='xxx')

        result = ser + pd.Timedelta('1 days')
        tm.assert_series_equal(result, expected)

        result = pd.Timedelta('1 days') + ser
        tm.assert_series_equal(result, expected)

        result = ser + pd.tseries.offsets.Day()
        tm.assert_series_equal(result, expected)

        result = pd.tseries.offsets.Day() + ser
        tm.assert_series_equal(result, expected)

    def test_ops_series_period(self):
        # GH#13043
        ser = pd.Series([pd.Period('2015-01-01', freq='D'),
                         pd.Period('2015-01-02', freq='D')], name='xxx')
        assert ser.dtype == "Period[D]"

        per = pd.Period('2015-01-10', freq='D')
        off = per.freq
        # dtype will be object because of original dtype
        expected = pd.Series([9 * off, 8 * off], name='xxx', dtype=object)
        tm.assert_series_equal(per - ser, expected)
        tm.assert_series_equal(ser - per, -1 * expected)

        s2 = pd.Series([pd.Period('2015-01-05', freq='D'),
                        pd.Period('2015-01-04', freq='D')], name='xxx')
        assert s2.dtype == "Period[D]"

        expected = pd.Series([4 * off, 2 * off], name='xxx', dtype=object)
        tm.assert_series_equal(s2 - ser, expected)
        tm.assert_series_equal(ser - s2, -1 * expected)

class TestPeriodIndexSeriesMethods:
    """ Test PeriodIndex and Period Series Ops consistency """

    def _check(self, values, func, expected):
        idx = pd.PeriodIndex(values)
        result = func(idx)
        tm.assert_equal(result, expected)

        ser = pd.Series(values)
        result = func(ser)

        exp = pd.Series(expected, name=values.name)
        tm.assert_series_equal(result, exp)

    def test_pi_ops(self):
        idx = PeriodIndex(['2011-01', '2011-02', '2011-03', '2011-04'],
                          freq='M', name='idx')

        expected = PeriodIndex(['2011-03', '2011-04', '2011-05', '2011-06'],
                               freq='M', name='idx')

        self._check(idx, lambda x: x + 2, expected)
        self._check(idx, lambda x: 2 + x, expected)

        self._check(idx + 2, lambda x: x - 2, idx)

        result = idx - Period('2011-01', freq='M')
        off = idx.freq
        exp = pd.Index([0 * off, 1 * off, 2 * off, 3 * off], name='idx')
        tm.assert_index_equal(result, exp)

        result = Period('2011-01', freq='M') - idx
        exp = pd.Index([0 * off, -1 * off, -2 * off, -3 * off], name='idx')
        tm.assert_index_equal(result, exp)

    @pytest.mark.parametrize("ng", ["str", 1.5])
    @pytest.mark.parametrize("func", [
        lambda obj, ng: obj + ng,
        lambda obj, ng: ng + obj,
        lambda obj, ng: obj - ng,
        lambda obj, ng: ng - obj,
        lambda obj, ng: np.add(obj, ng),
        lambda obj, ng: np.add(ng, obj),
        lambda obj, ng: np.subtract(obj, ng),
        lambda obj, ng: np.subtract(ng, obj),
    ])
    def test_parr_ops_errors(self, ng, func, box_with_array):
        idx = PeriodIndex(["2011-01", "2011-02", "2011-03", "2011-04"],
                          freq="M", name="idx")
        obj = tm.box_expected(idx, box_with_array)
        msg = (r"unsupported operand type\(s\)|can only concatenate|"
               r"must be str|object to str implicitly")

        with pytest.raises(TypeError, match=msg):
            func(obj, ng)

    def test_pi_ops_nat(self):
        idx = PeriodIndex(['2011-01', '2011-02', 'NaT', '2011-04'],
                          freq='M', name='idx')
        expected = PeriodIndex(['2011-03', '2011-04', 'NaT', '2011-06'],
                               freq='M', name='idx')

        self._check(idx, lambda x: x + 2, expected)
        self._check(idx, lambda x: 2 + x, expected)
        self._check(idx, lambda x: np.add(x, 2), expected)

        self._check(idx + 2, lambda x: x - 2, idx)
        self._check(idx + 2, lambda x: np.subtract(x, 2), idx)

        # freq with mult
        idx = PeriodIndex(['2011-01', '2011-02', 'NaT', '2011-04'],
                          freq='2M', name='idx')
        expected = PeriodIndex(['2011-07', '2011-08', 'NaT', '2011-10'],
                               freq='2M', name='idx')

        self._check(idx, lambda x: x + 3, expected)
        self._check(idx, lambda x: 3 + x, expected)
        self._check(idx, lambda x: np.add(x, 3), expected)

        self._check(idx + 3, lambda x: x - 3, idx)
        self._check(idx + 3, lambda x: np.subtract(x, 3), idx)

    def test_pi_ops_array_int(self):

        idx = PeriodIndex(['2011-01', '2011-02', 'NaT', '2011-04'],
                          freq='M', name='idx')
        f = lambda x: x + np.array([1, 2, 3, 4])
        exp = PeriodIndex(['2011-02', '2011-04', 'NaT', '2011-08'],
                          freq='M', name='idx')
        self._check(idx, f, exp)

        f = lambda x: np.add(x, np.array([4, -1, 1, 2]))
        exp = PeriodIndex(['2011-05', '2011-01', 'NaT', '2011-06'],
                          freq='M', name='idx')
        self._check(idx, f, exp)

        f = lambda x: x - np.array([1, 2, 3, 4])
        exp = PeriodIndex(['2010-12', '2010-12', 'NaT', '2010-12'],
                          freq='M', name='idx')
        self._check(idx, f, exp)

        f = lambda x: np.subtract(x, np.array([3, 2, 3, -2]))
        exp = PeriodIndex(['2010-10', '2010-12', 'NaT', '2011-06'],
                          freq='M', name='idx')
        self._check(idx, f, exp)

    def test_pi_ops_offset(self):
        idx = PeriodIndex(['2011-01-01', '2011-02-01', '2011-03-01',
                           '2011-04-01'], freq='D', name='idx')
        f = lambda x: x + pd.offsets.Day()
        exp = PeriodIndex(['2011-01-02', '2011-02-02', '2011-03-02',
                           '2011-04-02'], freq='D', name='idx')
        self._check(idx, f, exp)

        f = lambda x: x + pd.offsets.Day(2)
        exp = PeriodIndex(['2011-01-03', '2011-02-03', '2011-03-03',
                           '2011-04-03'], freq='D', name='idx')
        self._check(idx, f, exp)

        f = lambda x: x - pd.offsets.Day(2)
        exp = PeriodIndex(['2010-12-30', '2011-01-30', '2011-02-27',
                           '2011-03-30'], freq='D', name='idx')
        self._check(idx, f, exp)

    def test_pi_offset_errors(self):
        idx = PeriodIndex(['2011-01-01', '2011-02-01', '2011-03-01',
                           '2011-04-01'], freq='D', name='idx')
        ser = pd.Series(idx)

        # Series op is applied per Period instance, thus error is raised
        # from Period
        for obj in [idx, ser]:
            msg = r"Input has different freq=2H from Period.*?\(freq=D\)"
            with pytest.raises(IncompatibleFrequency, match=msg):
                obj + pd.offsets.Hour(2)

            with pytest.raises(IncompatibleFrequency, match=msg):
                pd.offsets.Hour(2) + obj

            msg = r"Input has different freq=-2H from Period.*?\(freq=D\)"
            with pytest.raises(IncompatibleFrequency, match=msg):
                obj - pd.offsets.Hour(2)

    def test_pi_sub_period(self):
        # GH#13071
        idx = PeriodIndex(['2011-01', '2011-02', '2011-03', '2011-04'],
                          freq='M', name='idx')

        result = idx - pd.Period('2012-01', freq='M')
        off = idx.freq
        exp = pd.Index([-12 * off, -11 * off, -10 * off, -9 * off], name='idx')
        tm.assert_index_equal(result, exp)

        result = np.subtract(idx, pd.Period('2012-01', freq='M'))
        tm.assert_index_equal(result, exp)

        result = pd.Period('2012-01', freq='M') - idx
        exp = pd.Index([12 * off, 11 * off, 10 * off, 9 * off], name='idx')
        tm.assert_index_equal(result, exp)

        result = np.subtract(pd.Period('2012-01', freq='M'), idx)
        tm.assert_index_equal(result, exp)

        exp = pd.TimedeltaIndex([np.nan, np.nan, np.nan, np.nan], name='idx')
        tm.assert_index_equal(idx - pd.Period('NaT', freq='M'), exp)
        tm.assert_index_equal(pd.Period('NaT', freq='M') - idx, exp)

    def test_pi_sub_pdnat(self):
        # GH#13071
        idx = PeriodIndex(['2011-01', '2011-02', 'NaT', '2011-04'],
                          freq='M', name='idx')
        exp = pd.TimedeltaIndex([pd.NaT] * 4, name='idx')
        tm.assert_index_equal(pd.NaT - idx, exp)
        tm.assert_index_equal(idx - pd.NaT, exp)

    def test_pi_sub_period_nat(self):
        # GH#13071
        idx = PeriodIndex(['2011-01', 'NaT', '2011-03', '2011-04'],
                          freq='M', name='idx')

        result = idx - pd.Period('2012-01', freq='M')
        off = idx.freq
        exp = pd.Index([-12 * off, pd.NaT, -10 * off, -9 * off], name='idx')
        tm.assert_index_equal(result, exp)

        result = pd.Period('2012-01', freq='M') - idx
        exp = pd.Index([12 * off, pd.NaT, 10 * off, 9 * off], name='idx')
        tm.assert_index_equal(result, exp)

        exp = pd.TimedeltaIndex([np.nan, np.nan, np.nan, np.nan], name='idx')
        tm.assert_index_equal(idx - pd.Period('NaT', freq='M'), exp)
        tm.assert_index_equal(pd.Period('NaT', freq='M') - idx, exp)


text:
namespace SoftUni.WebServer.Server
{
    using System;
    using System.Net;
    using System.Net.Sockets;
    using System.Threading.Tasks;
    using Handlers;
    using Interfaces;

    public class WebServer : IRunnable
    {
        private const string LocalhostIPAddress = "127.0.0.1";

        private readonly int port;
        private readonly IHttpRequestHandler mvcRequestHandler;
        private readonly IHttpRequestHandler fileHandler;
        private readonly TcpListener listener;

        private bool isRunning;

        public WebServer(int port, IHttpRequestHandler mvcRequestHandler, IHttpRequestHandler fileHandler)
        {
            this.port = port;
            this.listener = new TcpListener(IPAddress.Parse(LocalhostIPAddress), port);

            this.mvcRequestHandler = mvcRequestHandler;
            this.fileHandler = fileHandler;
        }

        public void Run()
        {
            this.listener.Start();
            this.isRunning = true;

            Console.WriteLine($"Server started at http://{LocalhostIPAddress}:{port}");

            var task = Task.Run(this.ListenLoop);
            task.Wait();
        }

        public async Task ListenLoop()
        {
            while (this.isRunning)
            {
                var client = await this.listener.AcceptSocketAsync();
                var connectionHandler = new ConnectionHandler(client, this.mvcRequestHandler, this.fileHandler);
                var responseTask = connectionHandler.ProcessRequestAsync();
                responseTask.Wait();
            }
        }
    }
}

redpajama_set_name: RedPajamaGithub


text:
powershell "Reboots the system" do

  # Create the powershell script
  powershell_script = <<'POWERSHELL_SCRIPT'
    $computer = get-content env:computername
    $system = Get-WmiObject Win32_OperatingSystem -ComputerName $computer
    $system.psbase.Scope.Options.EnablePrivileges = $true
    #redirecting the output to $null to avoid script failure
    $system.Reboot() > $null
    Write-Output "Reboot signal sent!"
POWERSHELL_SCRIPT

  source(powershell_script)
end


text:
package mysqldriver

import (
	"strconv"

	"github.com/pubnative/mysqlproto-go"
)

// Rows represents result set of SELECT query
type Rows struct {
	resultSet mysqlproto.ResultSet
	packet    []byte
	offset    uint64
	eof       bool

	errRead  error // error reading from the stream
	errParse error // error parsing the value

	columns     map[string]columnValue
	readColumns int
}

type columnValue struct {
	data []byte
	null bool
}

// Next moves cursor to the next unread row.
// It returns false when there are no more rows left
// or an error occurred during reading rows (see LastError() function)
// This function must be called before reading first row
// and continue being called until it returns false.
//  rows, _ := conn.Query("SELECT * FROM people LIMIT 2")
//  rows.Next() // move cursor to the first row
//  // read values from the first row
//  rows.Next() // move cursor to the second row
//  // read values from the second row
//  rows.Next() // drain the stream
// Best practice is to call Next() function in a loop:
//  rows, _ := conn.Query("SELECT * FROM people")
//  for rows.Next() {
//  	// read values from the row
//  }
// It's required to read all rows before performing another query
// because connection contains sequential stream of rows.
//  rows, _ := conn.Query("SELECT name FROM dogs LIMIT 1")
//  rows.Next()   // move cursor to the first row
//  rows.String() // dog's name
//  rows, _ = conn.Query("SELECT name FROM cats LIMIT 2")
//  rows.Next()   // move cursor to the second row of first query
//  rows.String() // still dog's name
//  rows.Next()   // returns false. closes the first stream of rows
//  rows.Next()   // move cursor to the first row of second query
//  rows.String() // cat's name
//  rows.Next()   // returns false. closes the second stream of rows
func (r *Rows) Next() bool {
	if r.eof {
		return false
	}

	// stop execution if stream is broken
	if r.errRead != nil {
		return false
	}

	packet, err := r.resultSet.Row()
	if err != nil {
		r.errRead = err
		return false
	}

	if packet == nil {
		r.eof = true
		return false
	} else {
		r.packet = packet
		r.offset = 0
		r.readColumns = 0
		return true
	}
}

// Bytes returns value as slice of bytes.
// NULL value is represented as empty slice.
func (r *Rows) Bytes() []byte {
	value, _ := r.NullBytes()
	return value
}

// NullBytes returns value as a slice of bytes
// and NULL indicator. When value is NULL, second parameter is true.
// All other type-specific functions are based on this one.
// NullBytes shouldn't be invoked after all columns are read.
// Calling it after reading all values of the row
// will return nil value with NULL flag
func (r *Rows) NullBytes() ([]byte, bool) {
	if r.readColumns == len(r.resultSet.Columns) {
		return nil, true
	}

	value, offset, null := mysqlproto.ReadRowValue(r.packet, r.offset)
	r.offset = offset

	name := r.resultSet.Columns[r.readColumns].Name
	r.columns[name] = columnValue{
		data: value,
		null: null,
	}
	r.readColumns += 1

	return value, null
}

// String returns value as a string.
// NULL value is represented as an empty string.
func (r *Rows) String() string {
	value, _ := r.NullString()
	return value
}

// NullString returns string as a value and
// NULL indicator. When value is NULL, second parameter is true.
func (r *Rows) NullString() (string, bool) {
	data, null := r.NullBytes()
	return string(data), null
}

// Int returns value as an int.
// NULL value is represented as 0.
// Int method uses strconv.Atoi to convert string into int.
// (see https://golang.org/pkg/strconv/#Atoi)
func (r *Rows) Int() int {
	num, _ := r.NullInt()
	return num
}

// NullInt returns value as an int and NULL indicator.
// When value is NULL, second parameter is true.
// NullInt method uses strconv.Atoi to convert string into int.
// (see https://golang.org/pkg/strconv/#Atoi)
func (r *Rows) NullInt() (int, bool) {
	str, null := r.NullBytes()
	if null {
		return 0, true
	}

	num, err := atoi(str)
	if err != nil {
		r.errParse = err
	}

	return num, false
}

// Int8 returns value as an int8.
// NULL value is represented as 0.
// Int8 method uses strconv.ParseInt to convert string into int8.
// (see https://golang.org/pkg/strconv/#ParseInt)
func (r *Rows) Int8() int8 {
	num, _ := r.NullInt8()
	return num
}

// NullInt8 returns value as an int8 and NULL indicator.
// When value is NULL, second parameter is true.
// NullInt8 method uses strconv.ParseInt to convert string into int8.
// (see https://golang.org/pkg/strconv/#ParseInt)
func (r *Rows) NullInt8() (int8, bool) {
	str, null := r.NullString()
	if null {
		return 0, true
	}

	num, err := strconv.ParseInt(str, 10, 8)
	if err != nil {
		r.errParse = err
	}

	return int8(num), false
}

// Int16 returns value as an int16.
// NULL value is represented as 0.
// Int16 method uses strconv.ParseInt to convert string into int16.
// (see https://golang.org/pkg/strconv/#ParseInt)
func (r *Rows) Int16() int16 {
	num, _ := r.NullInt16()
	return num
}

// NullInt16 returns value as an int8 and NULL indicator.
// When value is NULL, second parameter is true.
// NullInt16 method uses strconv.ParseInt to convert string into int16.
// (see https://golang.org/pkg/strconv/#ParseInt)
func (r *Rows) NullInt16() (int16, bool) {
	str, null := r.NullString()
	if null {
		return 0, true
	}

	num, err := strconv.ParseInt(str, 10, 16)
	if err != nil {
		r.errParse = err
	}

	return int16(num), false
}

// Int32 returns value as an int32.
// NULL value is represented as 0.
// Int32 method uses strconv.ParseInt to convert string into int32.
// (see https://golang.org/pkg/strconv/#ParseInt)
func (r *Rows) Int32() int32 {
	num, _ := r.NullInt32()
	return num
}

// NullInt32 returns value as an int32 and NULL indicator.
// When value is NULL, second parameter is true.
// NullInt32 method uses strconv.ParseInt to convert string into int32.
// (see https://golang.org/pkg/strconv/#ParseInt)
func (r *Rows) NullInt32() (int32, bool) {
	str, null := r.NullString()
	if null {
		return 0, true
	}

	num, err := strconv.ParseInt(str, 10, 32)
	if err != nil {
		r.errParse = err
	}

	return int32(num), false
}

// Int64 returns value as an int64.
// NULL value is represented as 0.
// Int64 method uses strconv.ParseInt to convert string into int64.
// (see https://golang.org/pkg/strconv/#ParseInt)
func (r *Rows) Int64() int64 {
	num, _ := r.NullInt64()
	return num
}

// NullInt64 returns value as an int64 and NULL indicator.
// When value is NULL, second parameter is true.
// NullInt64 method uses strconv.ParseInt to convert string into int64.
// (see https://golang.org/pkg/strconv/#ParseInt)
func (r *Rows) NullInt64() (int64, bool) {
	str, null := r.NullString()
	if null {
		return 0, true
	}

	num, err := strconv.ParseInt(str, 10, 64)
	if err != nil {
		r.errParse = err
	}

	return int64(num), false
}

// Float32 returns value as a float32.
// NULL value is represented as 0.0.
// Float32 method uses strconv.ParseFloat to convert string into float32.
// (see https://golang.org/pkg/strconv/#ParseFloat)
func (r *Rows) Float32() float32 {
	num, _ := r.NullFloat32()
	return num
}

// NullFloat32 returns value as a float32 and NULL indicator.
// When value is NULL, second parameter is true.
// NullFloat32 method uses strconv.ParseFloat to convert string into float32.
// (see https://golang.org/pkg/strconv/#ParseFloat)
func (r *Rows) NullFloat32() (float32, bool) {
	str, null := r.NullString()
	if null {
		return 0, true
	}

	num, err := strconv.ParseFloat(str, 32)
	if err != nil {
		r.errParse = err
	}

	return float32(num), false
}

// Float64 returns value as a float64.
// NULL value is represented as 0.0.
// Float64 method uses strconv.ParseFloat to convert string into float64.
// (see https://golang.org/pkg/strconv/#ParseFloat)
func (r *Rows) Float64() float64 {
	num, _ := r.NullFloat64()
	return num
}

// NullFloat64 returns value as a float64 and NULL indicator.
// When value is NULL, second parameter is true.
// NullFloat64 method uses strconv.ParseFloat to convert string into float64.
// (see https://golang.org/pkg/strconv/#ParseFloat)
func (r *Rows) NullFloat64() (float64, bool) {
	str, null := r.NullString()
	if null {
		return 0, true
	}

	num, err := strconv.ParseFloat(str, 64)
	if err != nil {
		r.errParse = err
	}

	return num, false
}

// Bool returns value as a bool.
// NULL value is represented as false.
// Bool method uses strconv.ParseBool to convert string into bool.
// (see https://golang.org/pkg/strconv/#ParseBool)
func (r *Rows) Bool() bool {
	b, _ := r.NullBool()
	return b
}

// NullBool returns value as a bool and NULL indicator.
// When value is NULL, second parameter is true.
// NullBool method uses strconv.ParseBool to convert string into bool.
// (see https://golang.org/pkg/strconv/#ParseBool)
func (r *Rows) NullBool() (bool, bool) {
	str, null := r.NullBytes()
	if null {
		return false, true
	}

	b, err := parseBool(str)
	if err != nil {
		r.errParse = err
	}
	return b, false
}

// LastError returns the error if any occurred during
// reading result set of SELECT query. This method should
// be always called after reading all rows.
//  rows, err := conn.Query("SELECT * FROM dogs")
//  if err != nil {
//  	// handle error
//  }
//  for rows.Next() {
//  	// read values
//  }
//  if err = rows.LastError(); err != nil {
//  	// handle error
//  }
func (r *Rows) LastError() error {
	if r.errRead != nil {
		return r.errRead
	}

	return r.errParse
}

// Query function is used only for SELECT query.
// For all other queries and commands see func (c Conn) Exec
func (c *Conn) Query(sql string) (*Rows, error) {
	req := mysqlproto.ComQueryRequest([]byte(sql))
	if _, err := c.conn.Write(req); err != nil {
		c.valid = false
		return nil, err
	}

	resultSet, err := mysqlproto.ComQueryResponse(c.conn)
	if err != nil {
		if _, ok := err.(mysqlproto.ERRPacket); !ok {
			c.valid = false
		}
		return nil, err
	}

	rows := &Rows{
		resultSet: resultSet,
		columns:   make(map[string]columnValue, len(resultSet.Columns)),
	}
	return rows, nil
}

// Exec executes queries or other commands which expect to return OK_PACKET
// including INSERT/UPDATE/DELETE queries. For SELECT query see func (Conn) Query
//  okPacket, err := conn.Exec("DELETE FROM dogs WHERE id = 1")
//	if err == nil {
//  	return nil // query was performed successfully
//  }
//  if errPacket, ok := err.(mysqlproto.ERRPacket); ok {
//  	return errPacket // retrieve more information about the error
//  } else {
//  	return err // generic error
//  }
func (c *Conn) Exec(sql string) (mysqlproto.OKPacket, error) {
	req := mysqlproto.ComQueryRequest([]byte(sql))
	if _, err := c.conn.Write(req); err != nil {
		c.valid = false
		return mysqlproto.OKPacket{}, err
	}

	packet, err := c.conn.NextPacket()
	if err != nil {
		c.valid = false
		return mysqlproto.OKPacket{}, err
	}

	if packet.Payload[0] == mysqlproto.OK_PACKET {
		pkt, err := mysqlproto.ParseOKPacket(packet.Payload, c.conn.CapabilityFlags)
		return pkt, err
	} else {
		pkt, err := mysqlproto.ParseERRPacket(packet.Payload, c.conn.CapabilityFlags)
		if err == nil {
			return mysqlproto.OKPacket{}, pkt
		} else {
			return mysqlproto.OKPacket{}, err
		}
	}
}


text:
package wats

import (
	. "github.com/onsi/ginkgo"
	. "github.com/onsi/gomega"
	. "github.com/onsi/gomega/gbytes"
	. "github.com/onsi/gomega/gexec"

	"github.com/cloudfoundry-incubator/cf-test-helpers/cf"
)

var _ = Describe("Setting an app's start command", func() {
	Describe("staged on Diego and running on Diego", func() {
		It("exercises the app through its lifecycle", func() {
			By("pushing it", func() {
				Eventually(cf.Cf(
					"push", appName,
					"-p", "../../assets/batch-script",
					"--no-start",
					"--no-route",
					"-b", binaryBuildPackURL,
					"-s", config.GetStack(),
					"-c", "loop.bat Hi there!!!"), CF_PUSH_TIMEOUT).Should(Exit(0))
			})

			By("staging and running it on Diego", func() {
				disableHealthCheck(appName)
				session := cf.Cf("start", appName)
				Eventually(session, CF_PUSH_TIMEOUT).Should(Exit(0))
			})

			By("verifying it's up", func() {
				output := func() *Buffer {
					session := cf.Cf("logs", appName, "--recent")
					Eventually(session).Should(Exit(0))
					return session.Out
				}
				// OUT... to make sure we don't match the Launcher line: Running `loop.bat Hi there!!!'
				Eventually(output).Should(Say("OUT Hi there!!!"))
			})
		})
	})
})


text:
import logging
import re

from ema.emaproto  import SPCB, SPCE, SPAB, SPAE
from ema.parameter import Parameter
from ema.vector    import Vector
from ema.device    import Device

log = logging.getLogger('pluviomet')

def setLogLevel(level):
    log.setLevel(level)

CALIBRATION = {
    'name': 'Pluviometer Calibration constant',
    'logger': 'pluviomet',
    'mult': 1.0,                # multiplier to internal value
    'unit': 'l',
    'get' : '(p)',              # string format for GET request
    'set' : '(P%03d)',          # string format for SET request
    'pat' :  '\(P(\d{3})\)',    # pattern to recognize as response
    'grp' : 1,                  # group to extract value and compare
}

class Pluviometer(Device):

    CURRENT     = 'current'
    ACCUMULATED = 'accumulated'

    def __init__(self, ema, parser, N):
        lvl         = parser.get("PLUVIOMETER", "pluv_log")
        log.setLevel(lvl)
        publish_where    = parser.get("PLUVIOMETER","pluv_publish_where").split(',')
        publish_what     = parser.get("PLUVIOMETER","pluv_publish_what").split(',')
        calibration = parser.getfloat("PLUVIOMETER", "pluv_calib")
        Device.__init__(self, publish_where, publish_what)
        self.calibration   = Parameter(ema, calibration, **CALIBRATION)
        self.instant       = Vector(N)
        self.accumulated   = Vector(N)
        ema.addSync(self.calibration)
        ema.subscribeStatus(self)
        ema.addCurrent(self)
        ema.addAverage(self)
        ema.addParameter(self)

    def onStatus(self, message):
        self.instant.append(int(message[SPCB:SPCE]))
        self.accumulated.append(int(message[SPAB:SPAE]))

    @property
    def current(self):
        '''Return dictionary with current measured values'''
        return {
            Pluviometer.CURRENT:     (self.instant.last() / 10.0  , "mm"),
            Pluviometer.ACCUMULATED: (float(self.accumulated.last())  , "mm"),
        }

    @property
    def average(self):
        '''Return dictionary averaged values over a period of N samples'''
        accum, n = self.instant.sum()
        av1 = (accum/(10.0*n), "mm")
        accum, n = self.accumulated.sum()
        av2 = (float(accum)/n, "mm")
        return { Pluviometer.CURRENT: av1, 'accumulated': av2 }

    @property
    def parameter(self):
        '''Return tdictionary with calibration constants'''
        return {
            self.calibration.name: (self.calibration.value / self.calibration.mult, self.calibration.unit )
        }


text:
{-# LANGUAGE GADTs #-}
{-# LANGUAGE TypeFamilies #-}

--
-- Copyright (c) 2009-2011, ERICSSON AB
-- All rights reserved.
--
-- Redistribution and use in source and binary forms, with or without
-- modification, are permitted provided that the following conditions are met:
--
--     * Redistributions of source code must retain the above copyright notice,
--       this list of conditions and the following disclaimer.
--     * Redistributions in binary form must reproduce the above copyright
--       notice, this list of conditions and the following disclaimer in the
--       documentation and/or other materials provided with the distribution.
--     * Neither the name of the ERICSSON AB nor the names of its contributors
--       may be used to endorse or promote products derived from this software
--       without specific prior written permission.
--
-- THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
-- AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
-- IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
-- DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
-- FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
-- DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
-- SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
-- CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
-- OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
-- OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
--

module Feldspar.Stream
    (Stream
    ,head
    ,tail
    ,map,mapNth
    ,maps
    ,intersperse
    ,interleave
    ,downsample
    ,duplicate
    ,scan, scan1
    ,mapAccum
    ,iterate
    ,repeat
    ,unfold
    ,drop
    ,zip,zipWith
    ,unzip
    ,take
    ,splitAt
    ,cycle
    ,streamAsVector, streamAsVectorSize
    ,recurrenceO, recurrenceI, recurrenceIO, recurrenceIIO
    ,slidingAvg
    ,iir,fir
    )
    where

import qualified Prelude as P

import Feldspar
import Feldspar.Vector.Internal
         (Vector, Vector1
         ,freezeVector,indexed
         ,sum,length,replicate,scalarProd)

-- | Infinite streams.
data Stream a where
  Stream :: Syntax state => (state -> M a) -> M state -> Stream a

type instance Elem      (Stream a) = a
type instance CollIndex (Stream a) = Data Index

-- | Take the first element of a stream
head :: Syntax a => Stream a -> a
head (Stream next init) = runMutable (init >>= next)

-- | Drop the first element of a stream
tail :: Syntax a => Stream a -> Stream a
tail (Stream next init) = Stream next (init >>= \st -> next st >> return st)

-- | 'map f str' transforms every element of the stream 'str' using the
--   function 'f'
map :: (Syntax a, Syntax b) =>
       (a -> b) -> Stream a -> Stream b
map f (Stream next init) = Stream newNext init
  where newNext st = do a <- next st
                        return (f a)

-- | 'mapNth f n k str' transforms every 'n'th element with offset 'k'
--    of the stream 'str' using the function 'f'
mapNth :: (Syntax a) =>
          (a -> a) -> Data Index -> Data Index -> Stream a -> Stream a
mapNth f n k (Stream next init) = Stream newNext newInit
  where
    newInit = do st <- init
                 r  <- newRef (0 :: Data WordN)
                 return (st,r)
    newNext (st,r) = do a <- next st
                        i <- getRef r
                        setRef r ((i+1) `mod` n)
                        return (i==k ? f a $ a)

-- | 'maps fs str' uses one of the functions from 'fs' successively to modify
--   the elements of 'str'
maps :: (Syntax a) =>
        [a -> a] -> Stream a -> Stream a
maps fs (Stream next initial) = Stream newNext newInit
  where
    newInit = do
      r  <- newRef (0 :: Data Index)
      st <- initial
      return (r,st)

    newNext (r,st) = do
      a <- next st
      i <- getRef r
      setRef r ((i+1) `mod` P.fromIntegral (P.length fs))
      return $
        (P.foldr (\ (k,f) x ->
                            i==(P.fromIntegral k) ? f a $ x))
         a (P.zip [1..] fs)

-- | 'intersperse a str' inserts an 'a' between each element of the stream
--    'str'.
intersperse :: Syntax a => a -> Stream a -> Stream a
intersperse a s = interleave s (repeat a)

-- | Create a new stream by alternating between the elements from
--   the two input streams
interleave :: Syntax a => Stream a -> Stream a -> Stream a
interleave (Stream next1 init1) (Stream next2 init2)
    = Stream next init
  where
    init = do st1 <- init1
              st2 <- init2
              r   <- newRef true
              return (r,st1,st2)
    next (r,st1,st2) = do b <- getRef r
                          setRef r (not b)
                          ifM b (next1 st1) (next2 st2)

-- | 'downsample n str' takes every 'n'th element of the input stream
downsample :: Syntax a => Data Index -> Stream a -> Stream a
downsample n (Stream next init) = Stream newNext init
  where newNext st = do forM (n-1) (\_ -> next st)
                        next st

-- | 'duplicate n str' stretches the stream by duplicating the elements 'n' times
duplicate :: Syntax a => Data Index -> Stream a -> Stream a
duplicate n (Stream next init) = Stream newNext newInit
  where
    newInit = do st <- init
                 a  <- next st
                 r1 <- newRef a
                 r2 <- newRef (1 :: Data Index)
                 return (st,r1,r2)
    newNext (st,r1,r2) = do i <- getRef r2
                            setRef r2 ((i+1)`mod`n)
                            ifM (i==0)
                              (do a <- next st
                                  setRef r1 a
                                  return a)
                              (getRef r1)

-- | 'scan f a str' produces a stream by successively applying 'f' to
--   each element of the input stream 'str' and the previous element of
--   the output stream.
scan :: Syntax a => (a -> b -> a) -> a -> Stream b -> Stream a
scan f a (Stream next init) = Stream newNext newInit
  where
    newInit = do st <- init
                 r  <- newRef a
                 return (st,r)
    newNext (st,r) = do x   <- next st
                        acc <- getRef r
                        setRef r (f acc x)
                        return acc

-- | A scan but without an initial element.
scan1 :: Syntax a => (a -> a -> a) -> Stream a -> Stream a
scan1 f (Stream next init)
    = Stream newNext newInit
  where
    newInit = do
      st <- init
      a  <- next st
      r  <- newRef a
      return (st,r)
    newNext (st,r) = do
      a <- getRef r
      b <- next st
      let c = f a b
      setRef r c
      return c

-- | Maps a function over a stream using an accumulator.
mapAccum :: (Syntax acc, Syntax b) =>
            (acc -> a -> (acc,b)) -> acc -> Stream a -> Stream b
mapAccum f acc (Stream next init)
    = Stream newNext newInit
  where
    newInit = do
      st <- init
      r  <- newRef acc
      return (st,r)
    newNext (st,r) = do
      x <- getRef r
      a <- next st
      let (acc',b) = f x a
      setRef r acc'
      return b

-- | Iteratively applies a function to a starting element. All the successive
--   results are used to create a stream.
--
-- @iterate f a == [a, f a, f (f a), f (f (f a)) ...]@
iterate :: Syntax a => (a -> a) -> a -> Stream a
iterate f a = Stream next init
  where
    init = newRef a
    next r = do x <- getRef r
                setRef r (f x)
                return x

-- | Repeat an element indefinitely.
--
-- @repeat a = [a, a, a, ...]@
repeat :: Syntax a => a -> Stream a
repeat a = Stream return (return a)

-- | @unfold f acc@ creates a new stream by successively applying 'f' to
--   to the accumulator 'acc'.
unfold :: (Syntax a, Syntax c) => (c -> (a,c)) -> c -> Stream a
unfold next init = Stream newNext newInit
  where
    newInit = newRef init
    newNext r = do c <- getRef r
                   let (a,c') = next c
                   setRef r c'
                   return a

-- | Drop a number of elements from the front of a stream
drop :: Syntax a => Data Length -> Stream a -> Stream a
drop i (Stream next init) = Stream next newInit
  where newInit = do st <- init
                     forM i (\_ -> next st)
                     return st

-- | Pairs together two streams into one.
zip :: Stream a -> Stream b -> Stream (a,b)
zip = zipWith (,)

-- | Pairs together two streams using a function to combine the
--   corresponding elements.
zipWith :: (a -> b -> c) -> Stream a -> Stream b -> Stream c
zipWith f (Stream next1 init1) (Stream next2 init2) = Stream next init
  where
    init = do st1 <- init1
              st2 <- init2
              return (st1,st2)
    next (st1,st2) = do a <- next1 st1
                        b <- next2 st2
                        return (f a b)

-- | Given a stream of pairs, split it into two stream.
unzip :: (Syntax a, Syntax b) => Stream (a,b) -> (Stream a, Stream b)
unzip stream = (map fst stream, map snd stream)

instance Syntax a => Indexed (Stream a) where
  (Stream next init) ! n = runMutable $ do
                             st <- init
                             forM (n-1) (\_ -> next st)
                             next st

-- | 'take n str' allocates 'n' elements from the stream 'str' into a
--   core array.
take :: (Syntax a) => Data Length -> Stream a -> Data [Internal a]
take n (Stream next init)
    = runMutableArray $ do
        marr <- newArr_ n
        st   <- init
        forM n $ \ix -> do
          a <- next st
          setArr marr ix (desugar a)
        return marr

-- | 'splitAt n str' allocates 'n' elements from the stream 'str' into a
--   core array and returns the rest of the stream continuing from
--   element 'n+1'.
splitAt :: (Syntax a) =>
           Data Length -> Stream a -> (Data [Internal a], Stream a)
splitAt n stream = (take n stream,drop n stream)

-- | Loops through a vector indefinitely to produce a stream.
cycle :: Syntax a => Vector a -> Stream a
cycle vec = Stream next init
  where
    init = newRef (0 :: Data Index)
    next r = do i <- getRef r
                setRef r ((i + 1) `rem` length vec)
                return (vec ! i)

unsafeVectorToStream :: Syntax a => Vector a -> Stream a
unsafeVectorToStream vec = Stream next init
  where
    init = newRef (0 :: Data Index)
    next r = do i <- getRef r
                setRef r (i + 1)
                return (vec ! i)

-- | A convenience function for translating an algorithm on streams to an algorithm on vectors.
--   The result vector will have the same length as the input vector.
--   It is important that the stream function doesn't drop any elements of
--   the input stream.
--
--   This function allocates memory for the output vector.
streamAsVector :: (Syntax a, Syntax b) =>
                  (Stream a -> Stream b)
               -> (Vector a -> Vector b)
streamAsVector f v = sugar $ take (length v) $ f $ unsafeVectorToStream v

-- | Similar to 'streamAsVector' except the size of the output array is computed by the second argument
--   which is given the size of the input vector as a result.
streamAsVectorSize :: (Syntax a, Syntax b) =>
                      (Stream a -> Stream b) -> (Data Length -> Data Length)
                   -> (Vector a -> Vector b)
streamAsVectorSize f s v = sugar $ take (s $ length v) $ f $ cycle v

-- | A combinator for descibing recurrence equations, or feedback loops.
--   The recurrence equation may refer to previous outputs of the stream,
--   but only as many as the length of the input stream
--   It uses memory proportional to the input vector.
--
-- For exaple one can define the fibonacci sequence as follows:
--
-- > fib = recurrenceO (vector [0,1]) (\fib -> fib!0 + fib!1)
--
-- The expressions @fib!0@ and @fib!1@ refer to previous elements in the
-- stream defined one step back and two steps back respectively.
recurrenceO :: Type a =>
               Vector1 a ->
               (Vector1 a -> Data a) ->
               Stream (Data a)
recurrenceO initV mkExpr = Stream next init
  where
    len  = length initV
    init = do
      buf <- thawArray (freezeVector initV)
      r   <- newRef (0 :: Data Index)
      return (buf,r)

    next (buf,r) = do
      ix <- getRef r
      setRef r (ix + 1)
      a <- withArray buf
           (\ibuf -> return $ mkExpr
                     (indexed len (\i -> getIx ibuf ((i + ix) `rem` len))))
      result <- getArr buf (ix `rem` len)
      setArr buf (ix `rem` len) a
      return result

-- | A recurrence combinator with input. The function 'recurrenceI' is
--   similar to 'recurrenceO'. The difference is that that it has an input
--   stream, and that the recurrence equation may only refer to previous
--   inputs, it may not refer to previous outputs.
--
-- The sliding average of a stream can easily be implemented using
-- 'recurrenceI'.
--
-- > slidingAvg :: Data WordN -> Stream (Data WordN) -> Stream (Data WordN)
-- > slidingAvg n str = recurrenceI (replicate n 0) str
-- >                    (\input -> sum input `quot` n)
recurrenceI :: (Type a, Type b) =>
               Vector1 a -> Stream (Data a) ->
               (Vector1 a -> Data b) ->
               Stream (Data b)
recurrenceI ii stream mkExpr
    = recurrenceIO ii stream (value []) (\i _ -> mkExpr i)

-- | 'recurrenceIO' is a combination of 'recurrenceO' and 'recurrenceI'. It
--   has an input stream and the recurrence equation may refer both to
--   previous inputs and outputs.
--
--   'recurrenceIO' is used when defining the 'iir' filter.
recurrenceIO :: (Type a, Type b) =>
                Vector1 a -> Stream (Data a) -> Vector1 b ->
                (Vector1 a -> Vector1 b -> Data b) ->
                Stream (Data b)
recurrenceIO ii (Stream nxt int) io mkExpr
    = Stream next init
  where
    lenI = length ii
    lenO = length io
    init = do
      ibuf <- thawArray (freezeVector ii)
      obuf <- thawArray (freezeVector io)
      st   <- int
      r    <- newRef (0 :: Data Index)
      return (ibuf,obuf,st,r)
    next (ibuf,obuf,st,r) = do
      ix <- getRef r
      setRef r (ix + 1)
      a <- nxt st
      when (lenI /= 0) $ setArr ibuf (ix `rem` lenI) a
      b <- withArray ibuf (\ib ->
             withArray obuf (\ob ->
               return $ mkExpr
                          (indexed lenI (\i -> getIx ib ((i + ix) `rem` lenI)))
                          (indexed lenO (\i -> getIx ob ((i + ix - 1) `rem` lenO)))
                            ))
      ifM (lenO /= 0)
        (do o <- getArr obuf (ix `rem` lenO)
            setArr obuf (ix `rem` lenO) b
            return o)
        (return b)

-- | Similar to 'recurrenceIO' but takes two input streams.
recurrenceIIO :: (Type a, Type b, Type c) =>
                 Vector1 a -> Stream (Data a) -> Vector1 b -> Stream (Data b) ->
                 Vector1 c ->
                 (Vector1 a -> Vector1 b -> Vector1 c -> Data c) ->
                 Stream (Data c)
recurrenceIIO i1 (Stream next1 init1) i2 (Stream next2 init2) io mkExpr
    = Stream next init
  where
    len1 = length i1
    len2 = length i2
    lenO = length io
    init = do
      ibuf1 <- thawArray (freezeVector i1)
      st1   <- init1
      ibuf2 <- thawArray (freezeVector i2)
      st2   <- init2
      obuf  <- thawArray (freezeVector io)
      c     <- newRef (0 :: Data Index)
      return (ibuf1,st1,ibuf2,st2,obuf,c)
    next (ibuf1,st1,ibuf2,st2,obuf,c) = do
      ix <- getRef c
      setRef c (ix + 1)
      a <- next1 st1
      b <- next2 st2
      when (len1 /= 0) $ setArr ibuf1 (ix `rem` len1) a
      when (len2 /= 0) $ setArr ibuf2 (ix `rem` len2) b
      out <- withArray ibuf1 (\ib1 ->
               withArray ibuf2 (\ib2 ->
                 withArray obuf (\ob ->
                   return $ mkExpr (indexed len1 (\i -> getIx ib1 ((i + ix) `rem` len1)))
                                   (indexed len2 (\i -> getIx ib2 ((i + ix) `rem` len2)))
                                   (indexed lenO (\i -> getIx ob  ((i + ix) `rem` lenO)))
                                )))
      ifM (lenO /= 0)
          (do o <- getArr obuf (ix `rem` lenO)
              setArr obuf (ix `rem` lenO) out
              return o)
          (return out)

slidingAvg :: Data WordN -> Stream (Data WordN) -> Stream (Data WordN)
slidingAvg n str = recurrenceI (replicate n 0) str
                   (\input -> sum input `quot` n)

-- | A fir filter on streams
fir :: Vector1 Float ->
       Stream (Data Float) -> Stream (Data Float)
fir b inp =
    recurrenceI (replicate (length b) 0) inp
                (scalarProd b)

-- | An iir filter on streams
iir :: Data Float -> Vector1 Float -> Vector1 Float ->
       Stream (Data Float) -> Stream (Data Float)
iir a0 a b inp =
    recurrenceIO (replicate (length b) 0) inp
                 (replicate (length a) 0)
      (\i o -> 1 / a0 * ( scalarProd b i
                        - scalarProd a o)
      )


text:
SPARQL Query Benchmarker uses a multi-module maven build.

Running `mvn package` in this directory will build all components.  You will
find the API under `core/target` and the CLI under `cmd/target`

The CLI builds as a shaded JAR incorporating all dependencies so can
be run directly without needing to provide the dependencies directly.  See the
various scripts for different ways of invoking this.

## Building for an alternate Java Version

By default the project is set up to build for Java 7.
You can change what version it is built for by setting the `jdk.target` property, for example
to build for Java 8:

    mvn package -Djdk.target=1.8

Note that the mimimum Java version supported is Java 7 since some of our dependencies require
Java 7

## Scripts

`makeSrcDistro` will generate a tar ball of this folder and all subfolders that
excludes any built artifacts (the target directories)

# License

Copyright 2011-2014 Cray Inc. All Rights Reserved

Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are
met:

* Redistributions of source code must retain the above copyright
  notice, this list of conditions and the following disclaimer.

* Redistributions in binary form must reproduce the above copyright
  notice, this list of conditions and the following disclaimer in the
  documentation and/or other materials provided with the distribution.

* Neither the name Cray Inc. nor the names of its contributors may be
  used to endorse or promote products derived from this software
  without specific prior written permission.

THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

# Acknowledgments

SPARQL Query Benchmarker uses the the Apache Jena ARQ query engine for issuing queries
and parsing the results - http://jena.apache.org

Uses SP2B queries under the BSD license from http://dbis.informatik.uni-freiburg.de/forschung/projekte/SP2B/

Uses LUBM queries from academic paper:

GUO, Y., PAN, Z., HEFLIN, J.. LUBM: A Benchmark for OWL Knowledge Base Systems. Web Semantics: Science, Services
and Agents on the World Wide Web, North America, 3, mar. 2011.
Available at: <http://www.websemanticsjournal.org/index.php/ps/article/view/70/68>. Date accessed: 01 Jun. 2012.


text:
local singlelineW = require 'watchlog.watchlogfilesingleline'
local tableutil = require 'util.tableutil'
local json = require 'rapidjson'

local watchlogfilesinglelinejson = {
    ---- CONSTANTS ----
    ---- Core Data ----
    ---- Temp Data ----
}

setmetatable(watchlogfilesinglelinejson , singlelineW)
watchlogfilesinglelinejson.__index = watchlogfilesinglelinejson

function watchlogfilesinglelinejson:new(task, customParserConfig, tunningConfig, first)
    local self = {}
    self = singlelineW:new(task, customParserConfig, tunningConfig, first)
    setmetatable(self ,  watchlogfilesinglelinejson)
  return self
end

function watchlogfilesinglelinejson:handleEvent(kafkaClient , topic , msg)
    self.count = self.count + 1
    local status , jsn = pcall(json.decode , msg)
    if status then
        tableutil.simpleCopy(jsn , self.EVENT_CONTAINER)
        kafkaClient.safeSendMsg(topic , self.tempKafkaKey , json.encode(self.EVENT_CONTAINER) , 10)
    else
        print(msg)
    end
end

return watchlogfilesinglelinejson


text:
package kantan.codecs.enumeratum

import kantan.codecs.enumeratum.laws.discipline.Enumerated
import kantan.codecs.enumeratum.laws.discipline.arbitrary._
import kantan.codecs.laws.discipline.{StringCodecTests, StringDecoderTests, StringEncoderTests}
import kantan.codecs.laws.discipline.DisciplineSuite

class EnumCodecTests extends DisciplineSuite {

  checkAll("StringDecoder[Enumerated]", StringDecoderTests[Enumerated].decoder[Int, Int])
  checkAll("StringEncoder[Enumerated]", StringEncoderTests[Enumerated].encoder[Int, Int])
  checkAll("StringCodec[Enumerated]", StringCodecTests[Enumerated].codec[Int, Int])

}


text:
package info.tregmine.commands;

import info.tregmine.Tregmine;
import info.tregmine.api.GenericPlayer;

/**
 * Created by ericrabil on 4/2/17.
 */
public class VersionCommand extends AbstractCommand {

    private Tregmine plugin;

    public VersionCommand(Tregmine tregmine) {
        super(tregmine, "version");
        this.plugin = tregmine;
    }

    @Override
    public boolean handlePlayer(GenericPlayer player, String[] args) {
        player.sendMessage(this.plugin.version);
        return true;
    }
}


text:
    <mat-spinner *ngIf="isLoadingResults"></mat-spinner>

      GitHub's API rate limit has been reached. It will be reset in one minute.

      <ng-container matColumnDef="number">
        #
        {{ row.number }}
      </ng-container>

      <ng-container matColumnDef="title">
        Title
        {{ row.title }}
      </ng-container>

      <ng-container matColumnDef="state">
        State
        {{ row.state }}
      </ng-container>

      <ng-container matColumnDef="created">

          Created

        {{ row.created_at | date }}
      </ng-container>

  <mat-paginator [length]="resultsLength" [pageSize]="30"></mat-paginator>


text:
<?php

declare(strict_types=1);

namespace Sylius\Component\Shipping\Resolver;

use Sylius\Component\Shipping\Model\ShippingMethodInterface;
use Sylius\Component\Shipping\Model\ShippingSubjectInterface;

interface ShippingMethodsResolverInterface
{
    /**
     * @return ShippingMethodInterface[]
     */
    public function getSupportedMethods(ShippingSubjectInterface $subject): array;

    public function supports(ShippingSubjectInterface $subject): bool;
}


text:
<?php

class Mock_Database_Drivers_Mysql extends Mock_Database_DB_Driver {

	/**
	 * Instantiate the database driver
	 *
	 * @param	array	DB configuration to set
	 * @return	void
	 */
	public function __construct($config = array())
	{
		parent::__construct('CI_DB_mysql_driver', $config);
	}

}


text:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

    <meta http-equiv="content-type" content="text/html; charset=utf-8"/>
    <title>Statistics of DET in UD_Akkadian-PISANDUB</title>
    <link rel="root" href=""/>
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/font-awesome/4.4.0/css/font-awesome.min.css">
    <link rel="stylesheet" type="text/css" href="../../css/jquery-ui-redmond.css"/>
    <link rel="stylesheet" type="text/css" href="../../css/style.css"/>
    <link rel="stylesheet" type="text/css" href="../../css/style-vis.css"/>
    <link rel="stylesheet" type="text/css" href="../../css/hint.css"/>

          home

          edit page
          issue tracker

          <gcse:search></gcse:search>

        This page pertains to UD version 2.

            It appears that you have Javascript disabled.
            Please consider enabling Javascript for this page to see the visualizations.

Treebank Statistics: UD_Akkadian-PISANDUB: POS Tags: DET

There are 2 DET lemmas (0%), 3 DET types (0%) and 10 DET tokens (1%).
Out of 13 observed tags, the rank of DET is: 12 in number of lemmas, 13 in number of types and 13 in number of tokens.

The 10 most frequent DET lemmas: ša, _

The 10 most frequent DET types:  ša, KAM, šá

The 10 most frequent ambiguous lemmas: ša (<tt>ADP</tt> 36, <tt>SCONJ</tt> 27, <tt>DET</tt> 8, <tt>PRON</tt> 1), _ (<tt>X</tt> 30, <tt>NUM</tt> 4, <tt>DET</tt> 2, <tt>ADP</tt> 1, <tt>PROPN</tt> 1)

The 10 most frequent ambiguous types:  ša (<tt>ADP</tt> 20, <tt>SCONJ</tt> 20, <tt>DET</tt> 6), šá (<tt>ADP</tt> 15, <tt>SCONJ</tt> 8, <tt>DET</tt> 2, <tt>PRON</tt> 1)

ša

<tt>ADP</tt> 20: 1 BÁN 6 1/2 NINDA ša É-GAL LÚ-dAMAR-UTU LUGAL

<tt>SCONJ</tt> 20: [xx la ú-ša-as-ḫi-ru URU] ⸢a⸣-na ki-da-a-ni ša LUGAL ma-aḫ-ra la i-pu-šu

<tt>DET</tt> 6: Ina ITI ŠE UD 20 KAM MU 43 KAM uš-šu ša é-zi-da É ki-i-ni É d-AG šá qé-reb bar-sìp-KI ad-de-e uš-ši -šu

šá

<tt>ADP</tt> 15: xx] ⸢ši⸣-ṭi-ir šu-mu šá d-AN-ŠÁR-DÙ-IBILA LUGAL a-lik maḫ-ri -[ia šá qer-ba -šu ap-pa]-⸢al⸣-sa [xx a-na áš]-⸢ri -šú⸣

<tt>SCONJ</tt> 8: i-na qí-bit d-AMAR-UTU EN GAL-i šá la in-nen-nu-ú qí-bit -sú zi-ki-ir šu-mì -ka liš-šá-kin ana u₄-me da-ru-tú

<tt>DET</tt> 2: Ina ITI ŠE UD 20 KAM MU 43 KAM uš-šu ša é-zi-da É ki-i-ni É d-AG šá qé-reb bar-sìp-KI ad-de-e uš-ši -šu

<tt>PRON</tt> 1: d-AMAR-UTU EN i-ḫa-ṭu pi-i i-bar-ri ŠÀ šá KI d-EN ki-num i-ku-un-na iš-da -šú šá KI DUMU d-EN ki-num ú-la-bar a-na da-ra-ti

Morphology

The form / lemma ratio of DET is 1.500000 (the average of all parts of speech is 1.690167).

The 1st highest number of forms (2) was observed with the lemma "ša": ša, šá.

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

DET does not occur with any features.

Relations

DET nodes are attached to their parents using 2 different relations: <tt>det</tt> (8; 80% instances), <tt>flat</tt> (2; 20% instances)

Parents of DET nodes belong to 3 different parts of speech: <tt>PROPN</tt> (6; 60% instances), <tt>NOUN</tt> (2; 20% instances), <tt>NUM</tt> (2; 20% instances)

10 (100%) DET nodes are leaves.

The highest child degree of a DET node is 0.

© 2014–2021
            Universal Dependencies contributors.
            Site powered by Annodoc and brat
.


text:
package org.apache.sling.scripting.sightly.impl.filter;

import java.util.Dictionary;
import java.util.HashMap;
import java.util.Map;

import org.apache.felix.scr.annotations.Activate;
import org.apache.sling.commons.osgi.PropertiesUtil;
import org.apache.sling.scripting.sightly.impl.compiler.expression.Expression;
import org.apache.sling.scripting.sightly.impl.compiler.expression.ExpressionNode;
import org.osgi.service.component.ComponentContext;

/**
 * Filters implemented as components.
 */
public abstract class FilterComponent implements Filter {

    public static final String PRIORITY = "org.apache.sling.scripting.sightly.impl.filter.priority";
    public static final int DEFAULT_PRIORITY = 100;

    private int priority = DEFAULT_PRIORITY;

    @Override
    public int priority() {
        return priority;
    }

    @Override
    public int compareTo(Filter o) {
        if (this.priority < o.priority()) {
            return -1;
        } else if (this.priority == o.priority()) {
            return 0;
        }
        return 1;
    }

    @Activate
    protected void activate(ComponentContext componentContext) {
        Dictionary properties = componentContext.getProperties();
        priority = PropertiesUtil.toInteger(properties.get(PRIORITY), DEFAULT_PRIORITY);
    }

    /**
     * Collects the options passed in the {@code options} array into a new map while removing them from the original expression.
     * @param expression the expression providing the options to be processed
     * @param options the options of interest for the {@link Filter}
     * @return a map with the retrieved options; the map can be empty if none of the options were found
     */
    protected Map<String, ExpressionNode> getFilterOptions(Expression expression, String... options) {
        Map<String, ExpressionNode> collector = new HashMap<String, ExpressionNode>();
        for (String option : options) {
            ExpressionNode optionNode = expression.removeOption(option);
            if (optionNode != null) {
                collector.put(option, optionNode);
            }
        }
        return collector;
    }
}


text:
======================
Dropwizard +Guice + Redis + Jobs + Guava

### About

[Dropwizard](http://dropwizard.io/) 1.0.2 [guice](https://github.com/google/guice) (4.1.0) integration.

This is an REST service Framework using Dropwizard.
It can help to build with [Gradle](https://gradle.org/) and auto build fat jar.
Resource Auto Inject and Configure the DB WITH READ WRITE split.

Features:
* [Guice](https://github.com/google/guice) injector created on run phase
* [Hikaricp](https://github.com/brettwooldridge/HikariCP) DataBase Pool Manager,Read From Config File Or From URL,Read Write Split
* [Redis](http://redis.io/) redis config support ,to cache data with redis.
* [Quartz](http://www.quartz-scheduler.org/) Schedule Job Support,help to do jobs in framework
* [JWTAuth](https://jwt.io/) Json Web Token Auth Support,Custome Your Auth System
* [Guava](https://github.com/google/guava) Google Help Libs with cache and events
* [JDBI](http://www.jdbi.org/) DB Util Method to operate with mysql
* [OkHttp](http://square.github.io/okhttp/) Use OKHTTP to Deal With HTTP(GET OR POST)

### moonsmile.core
It is the core frame wrapper with dropwizard and It has many useful method to help develop.
* `FrameBridge` Use this to get the config or enviroment
* `DBPoolCenter` Use this to manager the db pool and read write
* `DBExecutor` Use this to help you to execute sql with mysql
* `EncryptUtils` For Safety to save db password
* `PBKDF2ForPasswordHash` Encrypt the user password to save into database
* `RedisPoolCenter` To Connect redis use pool manager
* `HttpManager` To send get or post method with http
* `GeneralFormator` Convert JSON to Object OR Protobuf to json

### moonsmile.cache
Example Project
It is compile with the moonsmile.core,And You can see how to use core method and service
* Schedule Job with Quartz
* Schedule Job To Save Into Redis
* Read Data From Redis

### moonsmile.rest
Example Project
It is compile with the moonsmile.core,And You can see how to use core method and service
* Database Operate With DBCenter
* Simple Say HelloWorld

### moonsmile.setting
Example Project
It is compile with the moonsmile.core,And You can see how to use core method and service
* Database Center Manager,Read DB Config From Url Or File

### Setup

#### The Project Use IDEA AND GRADLE
1. General the idea project
`gradlew idea`
2. Build The Project to download libs
`gradlew build`

#### How to run the project
1. Run/Debug Configuration,Select the Application
2. Setting the vmoptions And Other MainClass,Module
`-Ddropwizard.config=src/main/resources/cache_config.yml`
3. Run
![image](https://github.com/kissfocus/MoonSmileFramework/raw/master/doc/project-setting.png)

In Resources Folder,It has an yml config file,need to config something like redis ,port
Open the WebSite,`http://localhost:8081/pageobject/hello`

# 基本信息
这是一个很小的示例程序,主要是用来学习使用dropwizard框架。
它也可以作为一个项目模板,可以快速的作为一个新的项目并运行。
集成了最常用的框架,适用于`Restfull` 架构风格`Web Service`接口开发。
项目使用最灵活的构建工具-`gradle`,加入了常用的gradle插件。

# 功能信息

本项目是基于Gradle进行构建,并搭建了适合大型构建项目的子模块系统,环境变量,自动合并不同环境的配置文件。
主要特点如下:
1、基于Gradle构建,自动完成打包和单元测试。
2、分离配置文件,基于环境变量进行切换。
3、子模块系统,每个子模块单独构建,并继承相应的配置。
4、Protobuf自动构建
5、JSON和Protobuf协议输出
6、基于Dropwizard框架
7、集成capsule,自动生成jar包
8、集成远程调试功能

# 主要框架信息

## Jetty
-利用Jetty作为webapp和后端服务的容器
-作为Dropwizard的承载程序,使的运行和调试非常容易

## Dropwizard
- 创建RESTful (JSON)服务,使用jersery和jackson,protobuf,并包含健康检查
- 通过JDBI创建持久层逻辑

## [Gradle](http://www.gradle.org)
- 基于Gradle的构建,使用Groovy语法,集成了最新的3.0版本

## hikaricp
- 目前最好用,性能最高的数据库连接池组件

## protobuf
- 基于谷歌的二进制传输协议,提高接口传输,减少流量

## guava
- 谷歌的一个很有用的类库

## JWT(JSON WEB TOKEN) AUTH
- 集成了JWT,通过Oauth的请求头进行验证

### 下载项目后如何构建
本项目是使用idea,如何是使用eclipse,第二条命令要改改
1. 打开命令行,进入到项目目录./gradlew build`
2. 生成相应的依赖和项目文件./gradlew idea`

### 如何基于gradle运行该程序
1. 打开命令行,进入到项目目录./gradlew run`
2. 设置VMOptions:-Ddropwizard.config=src/main/resources/metaengine_config.yml
每个项目不同,根据具体的设置

第一次打开该项目构建时,会进行相应的gradle文件下载,以及类库下载。

License
-------

Copyright (c) 2016 KissFocus

This library is licensed under the Apache License, Version 2.0.

See http://www.apache.org/licenses/LICENSE-2.0.html or the LICENSE file in this repository for the full license text.ICENSE-2.0.html or the LICENSE file in this repository for the full license text.


text:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
                android:layout_width="match_parent"
                android:layout_height="45dp"
                android:background="@color/default_titleBgColor">
    <ImageView
        android:id="@+id/iv_my_back"
        android:layout_width="wrap_content"
        android:layout_height="45dp"
        android:paddingLeft="15dp"
        android:paddingRight="15dp"
        android:gravity="center"
        android:src="@mipmap/icon_arrow_left"/>

    <TextView
        android:id="@+id/tv_my_title"
        android:layout_width="wrap_content"
        android:layout_height="45dp"
        android:layout_centerHorizontal="true"
        android:singleLine="true"
        android:ellipsize="end"
        android:gravity="center"
        android:textColor="#ffffffff"
        android:textSize="18sp"
        android:text="HALO  CITY"/>

</RelativeLayout>