text:
"""Tests for pypowervm.tasks.sriov."""

import mock
import testtools

import pypowervm.exceptions as ex
import pypowervm.tasks.sriov as tsriov
import pypowervm.tests.test_fixtures as fx
import pypowervm.tests.test_utils.test_wrapper_abc as twrap
import pypowervm.wrappers.iocard as card
import pypowervm.wrappers.managed_system as ms

def fake_sriov(mode, state, sriov_adap_id, phys_ports):
    return mock.Mock(mode=mode, state=state, sriov_adap_id=sriov_adap_id,
                     phys_loc_code='sriov_loc%d' % sriov_adap_id,
                     phys_ports=phys_ports)

def fake_pport(sriov_adap_id, port_id, cfg_lps, alloc_cap):
    return mock.Mock(sriov_adap_id=sriov_adap_id, port_id=port_id,
                     loc_code='pport_loc%d' % port_id,
                     min_granularity=float(port_id) / 1000,
                     cfg_max_lps=20,
                     cfg_lps=cfg_lps,
                     allocated_capacity=alloc_cap,
                     link_status=True)

def good_sriov(sriov_adap_id, pports):
    return fake_sriov(card.SRIOVAdapterMode.SRIOV,
                      card.SRIOVAdapterState.RUNNING, sriov_adap_id, pports)

ded_sriov = fake_sriov(card.SRIOVAdapterMode.DEDICATED, None, 86, [])
down_sriov = fake_sriov(card.SRIOVAdapterMode.SRIOV,
                        card.SRIOVAdapterState.FAILED, 68, [])

def sys_wrapper(sriovs, vnic_capable=True, vnic_failover_capable=True):
    mock_sys = mock.Mock(asio_config=mock.Mock(sriov_adapters=sriovs))

    def get_cap(cap):
        capabilities = {
            'vnic_capable': vnic_capable,
            'vnic_failover_capable': vnic_failover_capable}
        return capabilities[cap]
    mock_sys.get_capability.side_effect = get_cap

    return mock_sys

class TestSriov(testtools.TestCase):

    def setUp(self):
        super(TestSriov, self).setUp()
        self.adpt = self.useFixture(fx.AdapterFx()).adpt
        self.fake_sriovs = [
            good_sriov(1, [fake_pport(1, pid, lps, cap) for pid, lps, cap in (
                (11, 0, 0.95), (12, 9, 0.0), (13, 5, 0.03), (14, 20, 0.987))]),
            ded_sriov,
            good_sriov(2, [fake_pport(2, 21, 19, 0.3)]),
            down_sriov,
            good_sriov(3, []),
            good_sriov(4, [fake_pport(4, pid, 1, cap) for pid, cap in (
                (41, 0.02), (42, 0.01))]),
            good_sriov(5, [fake_pport(5, pid, lps, cap) for pid, lps, cap in (
                (51, 17, 0.49), (52, 3, 0.0), (53, 50, 0.05), (54, 11, 0.0),
                (55, 6, 0.4), (56, 13, 0.1), (57, 0, 0.15), (58, 7, 1.0))])]
        # Mark link status down on 5/55.
        self.fake_sriovs[6].phys_ports[4].link_status = False

    def test_get_good_sriovs(self):
        """Test _get_good_sriovs helper."""
        sriovs = tsriov._get_good_sriovs(self.fake_sriovs)
        self.assertEqual(5, len(sriovs))
        self.assertEqual(['sriov_loc%d' % x for x in range(1, 6)],
                         [sriov.phys_loc_code for sriov in sriovs])

        # Error case: none found.
        self.assertRaises(ex.NoRunningSharedSriovAdapters,
                          tsriov._get_good_sriovs, [ded_sriov, down_sriov])

    def test_get_good_pport_list(self):
        """Test _get_good_pport_list helper."""
        def validate_pports(pports, ids):
            # List of phys locs
            self.assertSetEqual({'pport_loc%d' % x for x in ids},
                                {pport.loc_code for pport in pports})
            # We added the appropriate sriov_adap_id
            for pport in pports:
                # Set up such that port ID xy always sits on adapter with ID x
                self.assertEqual(pport.port_id // 10, pport.sriov_adap_id)

        # Base case: no hits
        self.assertEqual([], tsriov._get_good_pport_list(
            self.fake_sriovs, ['nowt', 'to', 'see', 'here'], None, 0, False))
        # Validate redundancy - same thing but with nonzero redundancy
        self.assertRaises(
            ex.InsufficientSRIOVCapacity, tsriov._get_good_pport_list,
            self.fake_sriovs, ['nothing', 'to', 'see', 'here'], None, 1, False)
        # Make sure we can get the ones we specify, that are actually there.
        pports = tsriov._get_good_pport_list(
            self.fake_sriovs, ['pport_loc%d' % x for x in {
                51, 13, 68, 123, 21, 57, 42}], None, 4, False)
        validate_pports(pports, {42, 13, 57, 21, 51})
        # Make sure we can filter by saturation (capacity/LPs).  14, 53, and 58
        # should filter themselves - they're already too full for their
        # min_granularity and/or configured LPs.
        pports = tsriov._get_good_pport_list(
            self.fake_sriovs, ['pport_loc%d' % x for x in {
                58, 52, 14, 11, 53}], None, 0, False)
        validate_pports(pports, (52, 11))
        # Now specify capacity higher than 11 can handle - it should drop off
        pports = tsriov._get_good_pport_list(
            self.fake_sriovs, ['pport_loc%d' % x for x in {
                58, 52, 14, 11, 53}], 0.06, 0, False)
        validate_pports(pports, {52})
        # Filter link-down ports.  14, 53, and 58 don't appear because they're
        # saturated by capacity and/or configured LPs.  55 doesn't appear
        # because it's link-down.
        pports = tsriov._get_good_pport_list(
            self.fake_sriovs, ['pport_loc%d' % x for x in range(60)], None, 0,
            True)
        validate_pports(pports, {12, 52, 54, 42, 13, 41, 56, 57, 21, 51, 11})

    @mock.patch('pypowervm.wrappers.managed_system.System.get')
    def test_check_sys_vnic_capabilities(self, mock_sys_get):
        sys_yes_yes = sys_wrapper(None)
        sys_yes_no = sys_wrapper(None, vnic_failover_capable=False)
        sys_no_yes = sys_wrapper(None, vnic_capable=False)
        sys_no_no = sys_wrapper(None, vnic_capable=False,
                                vnic_failover_capable=False)
        # With sys param None, does a get; vnic & failover checks pass
        mock_sys_get.return_value = [sys_yes_yes]
        self.assertEqual(sys_yes_yes,
                         tsriov._check_sys_vnic_capabilities('adap', None, 2))
        mock_sys_get.assert_called_once_with('adap')

        mock_sys_get.reset_mock()

        # No get; vnic & !failover ok
        self.assertEqual(
            sys_yes_no,
            tsriov._check_sys_vnic_capabilities('adap', sys_yes_no, 1))
        mock_sys_get.assert_not_called()

        # Same, but 0 is a valid min
        self.assertEqual(
            sys_yes_no,
            tsriov._check_sys_vnic_capabilities('adap', sys_yes_no, 0))

        # vnic & !failover !ok
        self.assertRaises(
            ex.VNICFailoverNotSupportedSys,
            tsriov._check_sys_vnic_capabilities, 'adap', sys_yes_no, 2)

        # !vnic !ok even if failover ok (which would really never happen)
        self.assertRaises(
            ex.SystemNotVNICCapable,
            tsriov._check_sys_vnic_capabilities, 'adap', sys_no_yes, 2)

        # !vnic !failover !ok
        self.assertRaises(
            ex.SystemNotVNICCapable,
            tsriov._check_sys_vnic_capabilities, 'adap', sys_no_no, 1)

    @mock.patch('pypowervm.tasks.partition.get_active_vioses')
    def test_check_and_filter_vioses(self, mock_vioget):
        vios_yes_yes = mock.Mock(vnic_capable=True, vnic_failover_capable=True)
        vios_yes_no = mock.Mock(vnic_capable=True, vnic_failover_capable=False)
        vios_no_yes = mock.Mock(vnic_capable=False, vnic_failover_capable=True)
        vios_no_no = mock.Mock(vnic_capable=False, vnic_failover_capable=False)

        # No redundancy, no pre-seeded list.
        violist = [vios_yes_yes, vios_yes_no, vios_no_yes, vios_no_no]
        mock_vioget.return_value = violist
        # Because at least one VIOS was failover-capable, the non-capable one
        # is excluded.
        self.assertEqual([vios_yes_yes],
                         tsriov._check_and_filter_vioses('adap', None, 1))
        mock_vioget.assert_called_once_with('adap', xag=[], vios_wraps=None,
                                            find_min=1)

        mock_vioget.reset_mock()

        # With redundancy, pre-seeded list
        self.assertEqual([vios_yes_yes], tsriov._check_and_filter_vioses(
            'adap', violist, 2))
        mock_vioget.assert_called_once_with('adap', xag=[],
                                            vios_wraps=violist, find_min=1)

        # None capable
        violist = [vios_no_yes, vios_no_no]
        mock_vioget.return_value = violist
        self.assertRaises(ex.NoVNICCapableVIOSes,
                          tsriov._check_and_filter_vioses, 'adap', None, 1)

        # None redundancy capable
        violist = [vios_yes_no, vios_no_yes, vios_no_no]
        mock_vioget.return_value = violist
        self.assertRaises(ex.VNICFailoverNotSupportedVIOS,
                          tsriov._check_and_filter_vioses, 'adap', None, 2)

    @mock.patch('pypowervm.tasks.sriov._check_and_filter_vioses')
    def test_set_vnic_back_devs_max_less_than_capacity(self, mock_vioget):
        """Test set_vnic_back_devs with max capacity less than min capacity"""
        mock_sys = sys_wrapper(self.fake_sriovs)
        mock_vioget.return_value = [mock.Mock(uuid='vios_uuid1')]
        self.adpt.build_href.side_effect = lambda *a, **k: str(a[1])
        vnic = card.VNIC.bld(self.adpt, pvid=5)
        self.assertEqual(0, len(vnic.back_devs))
        # Should raise ValueError 'Maximum capacity cannot be less
        # than min capacity'
        self.assertRaises(
            ValueError, tsriov.set_vnic_back_devs, vnic, [],
            sys_w=mock_sys, max_capacity=0.1, capacity=0.5)

    @mock.patch('pypowervm.tasks.sriov._check_and_filter_vioses')
    def test_set_vnic_back_devs_max_greaterthan_100(self, mock_vioget):
        """Test set_vnic_back_devs with max capacity greater than 1"""
        mock_sys = sys_wrapper(self.fake_sriovs)
        mock_vioget.return_value = [mock.Mock(uuid='vios_uuid1')]
        self.adpt.build_href.side_effect = lambda *a, **k: '%s' % a[1]
        vnic = card.VNIC.bld(self.adpt, pvid=5)
        self.assertEqual(0, len(vnic.back_devs))
        # Should raise ValueError 'Maximum capacity cannot be greater
        # than 100 percent'
        self.assertRaises(
            ValueError, tsriov.set_vnic_back_devs, vnic, [],
            max_capacity=1.1, sys_w=mock_sys)

    @mock.patch('pypowervm.tasks.sriov._check_and_filter_vioses')
    @mock.patch('random.shuffle')
    def test_set_vnic_back_devs(self, mock_shuffle, mock_vioget):
        """Test set_vnic_back_devs."""
        mock_sys = sys_wrapper(self.fake_sriovs)
        mock_vioget.return_value = [mock.Mock(uuid='vios_uuid1'),
                                    mock.Mock(uuid='vios_uuid2'),
                                    mock.Mock(uuid='vios_uuid3')]
        self.adpt.build_href.side_effect = lambda *a, **k: '%s' % a[1]
        vnic = card.VNIC.bld(self.adpt, pvid=5)
        self.assertEqual(0, len(vnic.back_devs))
        # Silly case: redundancy of zero
        tsriov.set_vnic_back_devs(vnic, [], sys_w=mock_sys, redundancy=0)
        self.assertEqual(0, len(vnic.back_devs))
        mock_vioget.assert_called_once_with(self.adpt, None, 0)

        cap = 0.019
        # Things to note about the following:
        # - VIOSes rotate.  1, 2, 3, repeat.  If we hadn't mocked shuffle, the
        #   base order would be random, but they would still rotate in whatever
        #   that shuffled order was.
        # - The least-used (emptiest) physical ports come first...
        # - ...except (e.g. 21) we force distribution across cards, so...
        # - ...cards alternate until exhausted; hence 5 repeated at the end.
        # - Capacity set across the board according to the parameter.
        all_back_devs = [('vios_uuid1', 1, 12, cap),
                         ('vios_uuid2', 5, 52, cap),
                         ('vios_uuid3', 4, 42, cap),
                         ('vios_uuid1', 2, 21, cap),
                         ('vios_uuid2', 5, 54, cap),
                         ('vios_uuid3', 4, 41, cap),
                         ('vios_uuid1', 1, 13, cap),
                         ('vios_uuid2', 5, 56, cap),
                         ('vios_uuid3', 1, 11, cap),
                         ('vios_uuid1', 5, 57, cap),
                         ('vios_uuid2', 5, 55, cap),
                         ('vios_uuid3', 5, 51, cap)]
        # 5/55 is link-down.  When it drops off, the last one moves to VIOS 2.
        live_back_devs = all_back_devs[:10] + [('vios_uuid2', 5, 51, cap)]

        # Use 'em all
        tsriov.set_vnic_back_devs(vnic, ['pport_loc%d' % x for x in range(60)],
                                  sys_w=mock_sys, capacity=cap, redundancy=12)
        self.assertEqual(all_back_devs,
                         [(bd.vios_href, bd.sriov_adap_id, bd.pport_id,
                           bd.capacity) for bd in vnic.back_devs])

        # Check port status - 55 drops off
        tsriov.set_vnic_back_devs(vnic, ['pport_loc%d' % x for x in range(60)],
                                  sys_w=mock_sys, capacity=cap, redundancy=11,
                                  check_port_status=True)
        self.assertEqual(live_back_devs,
                         [(bd.vios_href, bd.sriov_adap_id, bd.pport_id,
                           bd.capacity) for bd in vnic.back_devs])

        # Fail if we can't satisfy redundancy
        self.assertRaises(
            ex.InsufficientSRIOVCapacity, tsriov.set_vnic_back_devs, vnic,
            ['pport_loc%d' % x for x in range(60)],
            sys_w=mock_sys, capacity=cap, redundancy=13)

        # The passed-in wrapper isn't modified if the method raises.
        self.assertEqual(live_back_devs,
                         [(bd.vios_href, bd.sriov_adap_id, bd.pport_id,
                           bd.capacity) for bd in vnic.back_devs])

        # Make sure redundancy caps it.
        # By reusing vnic without resetting its back_devs, we're proving the
        # documented behavior that the method clears first.
        tsriov.set_vnic_back_devs(vnic, ['pport_loc%d' % x for x in range(60)],
                                  sys_w=mock_sys, capacity=cap, redundancy=5)
        self.assertEqual(all_back_devs[:5],
                         [(bd.vios_href, bd.sriov_adap_id, bd.pport_id,
                           bd.capacity) for bd in vnic.back_devs])

        self.assertEqual(5, mock_shuffle.call_count)

        # When max capacity is not specified during set_vnic_back_devs,
        # max_capacity should be None
        self.assertEqual(None, vnic.back_devs[0].max_capacity)

    @mock.patch('pypowervm.tasks.sriov._check_and_filter_vioses')
    def test_set_vnic_back_devs_max_capacity_invoked(self, mock_vioget):
        mock_sys = sys_wrapper(self.fake_sriovs)
        mock_vioget.return_value = [mock.Mock(uuid='vios_uuid1')]
        self.adpt.build_href.side_effect = lambda *a, **k: '%s' % a[1]
        vnic = card.VNIC.bld(self.adpt, pvid=5)
        self.assertEqual(0, len(vnic.back_devs))
        tsriov.set_vnic_back_devs(vnic, ['pport_loc%d' % x for x in range(60)],
                                  sys_w=mock_sys, capacity=0.02, redundancy=1,
                                  max_capacity=0.75)
        # Ensure that the max and min capacities attached to back_devices as
        # expected
        self.assertEqual(0.02, vnic.back_devs[0].capacity)
        self.assertEqual(0.75, vnic.back_devs[0].max_capacity)

    @mock.patch('pypowervm.wrappers.managed_system.System.get')
    def test_find_pports_for_portlabel(self, mock_sys_get):
        physnet = 'default'
        sriov_adaps = [
            mock.Mock(phys_ports=[
                mock.Mock(loc_code='port1', label='default'),
                mock.Mock(loc_code='port3', label='data1')]),
            mock.Mock(phys_ports=[
                mock.Mock(loc_code='port4', label='data2'),
                mock.Mock(loc_code='port2', label='default')])]
        sys = mock.Mock(asio_config=mock.Mock(sriov_adapters=sriov_adaps))
        mock_sys_get.return_value = [sys]
        pports = tsriov.find_pports_for_portlabel(physnet, sriov_adaps)
        self.assertEqual({'port1', 'port2'},
                         {pport.loc_code for pport in pports})

    @mock.patch('pypowervm.wrappers.managed_system.System.get')
    def test_find_pports_for_portlabel_blank(self, mock_sys_get):
        physnet = 'default'
        sriov_adaps = [
            mock.Mock(phys_ports=[
                mock.Mock(loc_code='port1', label=''),
                mock.Mock(loc_code='port3', label='data1')]),
            mock.Mock(phys_ports=[
                mock.Mock(loc_code='port4', label='data2'),
                mock.Mock(loc_code='port2', label='')])]
        sys = mock.Mock(asio_config=mock.Mock(sriov_adapters=sriov_adaps))
        mock_sys_get.return_value = [sys]
        pports = tsriov.find_pports_for_portlabel(physnet, sriov_adaps)
        self.assertEqual({'port1', 'port2'},
                         {pport.loc_code for pport in pports})

class TestSafeUpdatePPort(testtools.TestCase):

    @mock.patch('pypowervm.tasks.partition.get_partitions')
    @mock.patch('pypowervm.wrappers.iocard.VNIC.get')
    def test_get_lpar_vnics(self, mock_vnics, mock_get_pars):
        lpars = ['lpar1', 'lpar2', 'lpar3']
        mock_get_pars.return_value = lpars
        mock_vnics.side_effect = ['list1', 'list2', 'list3']
        self.assertEqual({'lpar%d' % i: 'list%d' % i for i in (1, 2, 3)},
                         tsriov.get_lpar_vnics('adap'))
        mock_get_pars.assert_called_once_with('adap', lpars=True, vioses=False)
        for lpar in lpars:
            mock_vnics.assert_any_call('adap', parent=lpar)

    def test_vnics_using_pport(self):
        lpar1 = mock.Mock()
        lpar1.configure_mock(name='lpar1', uuid='lpar_uuid1')
        lpar2 = mock.Mock()
        lpar2.configure_mock(name='lpar2', uuid='lpar_uuid2')
        vnic1 = mock.Mock(uuid='vnic_uuid1', back_devs=[
            mock.Mock(sriov_adap_id=1, pport_id=1),
            mock.Mock(sriov_adap_id=2, pport_id=2)])
        vnic2 = mock.Mock(uuid='vnic_uuid2', back_devs=[
            mock.Mock(sriov_adap_id=1, pport_id=2),
            mock.Mock(sriov_adap_id=2, pport_id=1)])
        vnic3 = mock.Mock(uuid='vnic_uuid3', back_devs=[
            mock.Mock(sriov_adap_id=3, pport_id=1),
            mock.Mock(sriov_adap_id=4, pport_id=2)])
        vnic4 = mock.Mock(uuid='vnic_uuid4', back_devs=[
            mock.Mock(sriov_adap_id=1, pport_id=2),
            mock.Mock(sriov_adap_id=4, pport_id=2)])
        lpar2vnics = {lpar1: [vnic1, vnic2], lpar2: [vnic3, vnic4]}
        # Not in use
        self.assertEqual([], tsriov._vnics_using_pport(mock.Mock(
            sriov_adap_id=1, port_id=3, loc_code='not_used'), lpar2vnics))
        # Used once
        ret = tsriov._vnics_using_pport(mock.Mock(
            sriov_adap_id=1, port_id=1, loc_code='loc1'), lpar2vnics)
        self.assertEqual(1, len(ret))
        # loc1 backs vNIC for LPAR lpar1 (lpar_uuid1 / vnic_uuid1)
        self.assertIn('loc1', ret[0])
        self.assertIn('lpar1', ret[0])
        self.assertIn('lpar_uuid1', ret[0])
        self.assertIn('vnic_uuid1', ret[0])
        # Used twice
        ret = tsriov._vnics_using_pport(mock.Mock(
            sriov_adap_id=1, port_id=2, loc_code='loc2'), lpar2vnics)
        self.assertEqual(2, len(ret))
        # Order of the return is not deterministic.  Reverse if necessary
        if 'lpar1' not in ret[0]:
            ret = ret[::-1]
        # loc2 backs vNIC for LPAR lpar1 (lpar_uuid1 / vnic_uuid2)
        self.assertIn('loc2', ret[0])
        self.assertIn('lpar1', ret[0])
        self.assertIn('lpar_uuid1', ret[0])
        self.assertIn('vnic_uuid2', ret[0])
        # loc2 backs vNIC for LPAR lpar2 (lpar_uuid2 / vnic_uuid4)
        self.assertIn('loc2', ret[1])
        self.assertIn('lpar2', ret[1])
        self.assertIn('lpar_uuid2', ret[1])
        self.assertIn('vnic_uuid4', ret[1])

    @mock.patch('pypowervm.tasks.sriov.get_lpar_vnics')
    @mock.patch('pypowervm.tasks.sriov._vnics_using_pport')
    def test_vet_port_usage(self, mock_vup, mock_glv):
        label_index = {'loc1': 'pre_label1', 'loc2': '', 'loc3': 'pre_label3',
                       'loc4': 'pre_label4'}
        # No LPs
        pport1 = mock.Mock(cfg_lps=0, loc_code='loc1', label='post_label1')
        # Pre-label empty, but label changed
        pport2 = mock.Mock(loc_code='loc2', label='post_label2')
        # Pre-label matches post-label
        pport3 = mock.Mock(loc_code='loc3', label='pre_label3')
        # Label changed
        pport4 = mock.Mock(loc_code='loc4', label='post_label4')
        pport5 = mock.Mock(loc_code='loc3', label='post_label3')
        # PPorts that hit the first three criteria (no LPs, label originally
        # unset, label unchanged) don't trigger expensive get_lpar_vnics or
        # _vnics_using_pport.
        sriov1 = mock.Mock(phys_ports=[pport1, pport2])
        sriov2 = mock.Mock(phys_ports=[pport3])
        ret = tsriov._vet_port_usage(
            mock.Mock(asio_config=mock.Mock(sriov_adapters=[sriov1, sriov2])),
            label_index)
        self.assertEqual([], ret)
        mock_vup.assert_not_called()
        mock_glv.assert_not_called()
        # Multiple pports that pass the easy criteria; get_lpar_vnics only
        # called once.
        mock_vup.side_effect = [1], [2]
        sriov3 = mock.Mock(phys_ports=[pport4, pport5])
        ret = tsriov._vet_port_usage(mock.Mock(
            adapter='adap', asio_config=mock.Mock(
                sriov_adapters=[sriov1, sriov3])), label_index)
        mock_glv.assert_called_once_with('adap')
        self.assertEqual([1, 2], ret)
        mock_vup.assert_has_calls([mock.call(pport4, mock_glv.return_value),
                                   mock.call(pport5, mock_glv.return_value)])

    @mock.patch('pypowervm.tasks.sriov._vet_port_usage')
    @mock.patch('pypowervm.tasks.sriov.LOG.warning')
    @mock.patch('fasteners.lock.ReaderWriterLock.write_lock')
    @mock.patch('pypowervm.wrappers.managed_system.System.getter')
    def test_safe_update_pports(self, mock_getter, mock_lock, mock_warn,
                                mock_vpu):
        mock_sys = mock.Mock(asio_config=mock.Mock(sriov_adapters=[
            mock.Mock(phys_ports=[mock.Mock(loc_code='loc1', label='label1'),
                                  mock.Mock(loc_code='loc2', label='label2')]),
            mock.Mock(phys_ports=[
                mock.Mock(loc_code='loc3', label='label3')])]))

        def changes_func(ret_bool):
            def changes(sys_w):
                mock_lock.assert_called()
                mock_lock.reset_mock()
                return ret_bool
            return changes

        # No force, no warnings, update requested
        mock_vpu.return_value = []
        self.assertEqual(mock_sys.update.return_value,
                         tsriov.safe_update_pports(
                             mock_sys, changes_func(True)))
        mock_warn.assert_not_called()
        # No force, no in-use, no update, use a getter: runs but doesn't update
        mock_sys.update.reset_mock()
        self.assertEqual(mock_getter.return_value, tsriov.safe_update_pports(
            ms.System.getter('adap'), changes_func(False)))
        mock_warn.assert_not_called()
        mock_getter.return_value.update.assert_not_called()
        # Update requested, some in-use, no force - raises
        mock_vpu.reset_mock()
        mock_vpu.return_value = [1]
        self.assertRaises(ex.CantUpdatePPortsInUse, tsriov.safe_update_pports,
                          mock_sys, changes_func(True), force=False)
        mock_warn.assert_not_called()
        mock_sys.update.assert_not_called()
        # Update requested, some in-use, force - runs & warns
        mock_vpu.reset_mock()
        mock_vpu.return_value = ['one', 'two']
        self.assertEqual(mock_sys.update.return_value,
                         tsriov.safe_update_pports(
                             mock_sys, changes_func(True), force=True))
        mock_warn.assert_has_calls([mock.call(mock.ANY), mock.call('one'),
                                    mock.call('two')])

class TestMisc(twrap.TestWrapper):
    file = 'sys_with_sriov.txt'
    wrapper_class_to_test = ms.System

    def test_find_pport(self):
        self.assertIsNone(tsriov.find_pport(self.dwrap, 'bogus'))
        pport = tsriov.find_pport(self.dwrap, 'U78C7.001.RCH0004-P1-C8-T2')
        self.assertEqual('U78C7.001.RCH0004-P1-C8',
                         pport.sriov_adap.phys_loc_code)
        self.assertEqual(1, pport.sriov_adap_id)
        # It's a converged port...
        self.assertIsInstance(pport, card.SRIOVConvPPort)
        # ...which is also an ethernet port
        self.assertIsInstance(pport, card.SRIOVEthPPort)
        self.assertEqual('U78C7.001.RCH0004-P1-C8-T2', pport.loc_code)
        self.assertEqual(1, pport.port_id)


text:
package com.haringeymobile.ukweather.database;

import android.app.SearchManager;
import android.content.ContentProvider;
import android.content.ContentResolver;
import android.content.ContentUris;
import android.content.ContentValues;
import android.content.UriMatcher;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteException;
import android.database.sqlite.SQLiteQueryBuilder;
import android.net.Uri;
import android.text.TextUtils;

import java.util.HashMap;

public class WeatherContentProvider extends ContentProvider {

    private DatabaseHelper databaseHelper;

    // Used for the UriMatcher
    private static final int CITIES_ALL_ROWS = 1;
    private static final int CITIES_SINGLE_ROW = 2;
    private static final int CITIES_SEARCH = 3;

    public static final String AUTHORITY = "com.haringeymobile.ukweather.provider";

    private static final String PATH_CITY_RECORDS = CityTable.TABLE_CITIES;

    public static final Uri CONTENT_URI_CITY_RECORDS = Uri.parse("content://" + AUTHORITY + "/" +
            PATH_CITY_RECORDS);

    private static final String PROVIDER_SPECIFIC_SUBTYPE_FOR_CITY_RECORDS = "/vnd." + AUTHORITY +
            "." + CityTable.TABLE_CITIES;

    public static final String CONTENT_TYPE_CITY_RECORDS = ContentResolver.CURSOR_DIR_BASE_TYPE +
            PROVIDER_SPECIFIC_SUBTYPE_FOR_CITY_RECORDS;
    public static final String CONTENT_ITEM_TYPE_CITY_RECORDS =
            ContentResolver.CURSOR_ITEM_BASE_TYPE + PROVIDER_SPECIFIC_SUBTYPE_FOR_CITY_RECORDS;

    private static final UriMatcher myURIMatcher;

    static {
        myURIMatcher = new UriMatcher(UriMatcher.NO_MATCH);
        myURIMatcher.addURI(AUTHORITY, PATH_CITY_RECORDS, CITIES_ALL_ROWS);
        myURIMatcher.addURI(AUTHORITY, PATH_CITY_RECORDS + "/#", CITIES_SINGLE_ROW);
        myURIMatcher.addURI(AUTHORITY, SearchManager.SUGGEST_URI_PATH_QUERY, CITIES_SEARCH);
        myURIMatcher.addURI(AUTHORITY, SearchManager.SUGGEST_URI_PATH_QUERY + "/*", CITIES_SEARCH);
    }

    /**
     * Used to define aliases for column names, and must include all columns, even if the value is
     * the key. See http://developer.android.com/guide/topics/search/adding-custom-suggestions.html#SuggestionTable
     * for more info.
     */
    private static final HashMap<String, String> SEARCH_SUGGEST_PROJECTION_MAP;

    static {
        SEARCH_SUGGEST_PROJECTION_MAP = new HashMap<>();
        SEARCH_SUGGEST_PROJECTION_MAP.put("_id", CityTable._ID + " AS " + "_id");
        SEARCH_SUGGEST_PROJECTION_MAP.put(SearchManager.SUGGEST_COLUMN_TEXT_1,
                CityTable.COLUMN_NAME + " AS " + SearchManager.SUGGEST_COLUMN_TEXT_1);
        SEARCH_SUGGEST_PROJECTION_MAP.put(SearchManager.SUGGEST_COLUMN_INTENT_DATA_ID,
                CityTable._ID + " AS " + SearchManager.SUGGEST_COLUMN_INTENT_DATA_ID);
    }

    @Override
    public boolean onCreate() {
        databaseHelper = new DatabaseHelper(getContext());
        return true;
    }

    @Override
    public Cursor query(Uri uri, String[] projection, String selection, String[] selectionArgs,
                        String sortOrder) {
        SQLiteDatabase db;
        try {
            db = databaseHelper.getWritableDatabase();
        } catch (SQLiteException ex) {
            db = databaseHelper.getReadableDatabase();
        }

        String groupBy = null;
        String having = null;
        SQLiteQueryBuilder queryBuilder = new SQLiteQueryBuilder();

        switch (myURIMatcher.match(uri)) {
            case CITIES_SINGLE_ROW:
                queryBuilder.appendWhere(CityTable._ID + "=" + uri.getLastPathSegment());
                // fall through
            case CITIES_ALL_ROWS:
                queryBuilder.setTables(CityTable.TABLE_CITIES);
                break;
            case CITIES_SEARCH:
                queryBuilder.appendWhere(CityTable.COLUMN_NAME + " LIKE \"" +
                        uri.getLastPathSegment() + "%\"");
                queryBuilder.setProjectionMap(SEARCH_SUGGEST_PROJECTION_MAP);
                queryBuilder.setTables(CityTable.TABLE_CITIES);
                break;
            default:
                throw new IllegalArgumentException("Unsupported URI: " + uri);
        }

        Cursor cursor = queryBuilder.query(db, projection, selection, selectionArgs, groupBy,
                having, sortOrder);
        cursor.setNotificationUri(getContext().getContentResolver(), uri);
        return cursor;
    }

    @Override
    public String getType(Uri uri) {
        switch (myURIMatcher.match(uri)) {
            case CITIES_SINGLE_ROW:
                return CONTENT_ITEM_TYPE_CITY_RECORDS;
            case CITIES_ALL_ROWS:
                return CONTENT_TYPE_CITY_RECORDS;
            case CITIES_SEARCH:
                return SearchManager.SUGGEST_MIME_TYPE;
            default:
                throw new IllegalArgumentException("Unsupported URI: " + uri);
        }
    }

    @Override
    public Uri insert(Uri uri, ContentValues values) {
        SQLiteDatabase db = databaseHelper.getWritableDatabase();
        String nullColumnHack = null;
        long id;
        switch (myURIMatcher.match(uri)) {
            case CITIES_ALL_ROWS:
                id = db.insert(CityTable.TABLE_CITIES, nullColumnHack, values);
                break;
            default:
                throw new IllegalArgumentException("Unsupported URI: " + uri);
        }

        if (id > -1) {
            Uri insertedIdUri = ContentUris.withAppendedId(uri, id);
            getContext().getContentResolver().notifyChange(insertedIdUri, null);
            return insertedIdUri;
        }

        throw new SQLException("Could not insert into table for uri: " + uri);
    }

    @Override
    public int delete(Uri uri, String selection, String[] selectionArgs) {
        SQLiteDatabase db = databaseHelper.getWritableDatabase();
        int rowsDeleted = 0;
        switch (myURIMatcher.match(uri)) {
            case CITIES_SINGLE_ROW:
                String id_rec = uri.getLastPathSegment();
                if (TextUtils.isEmpty(selection)) {
                    rowsDeleted = db.delete(CityTable.TABLE_CITIES, CityTable._ID + "=" + id_rec,
                            null);
                } else {
                    rowsDeleted = db.delete(CityTable.TABLE_CITIES, CityTable._ID + "=" + id_rec +
                            " and " + selection, selectionArgs);
                }
                break;
            case CITIES_ALL_ROWS:
                rowsDeleted = db.delete(CityTable.TABLE_CITIES, selection, selectionArgs);
                break;
            default:
                throw new IllegalArgumentException("Unsupported URI: " + uri);
        }
        getContext().getContentResolver().notifyChange(uri, null);
        return rowsDeleted;
    }

    @Override
    public int update(Uri uri, ContentValues values, String selection, String[] selectionArgs) {
        SQLiteDatabase db = databaseHelper.getWritableDatabase();
        int rowsUpdated;
        switch (myURIMatcher.match(uri)) {
            case CITIES_SINGLE_ROW:
                String id_rec = uri.getLastPathSegment();
                if (TextUtils.isEmpty(selection)) {
                    rowsUpdated = db.update(CityTable.TABLE_CITIES, values, CityTable._ID + "=" +
                            id_rec, null);
                } else {
                    rowsUpdated = db.update(CityTable.TABLE_CITIES, values, CityTable._ID + "=" +
                            id_rec + " and " + selection, selectionArgs);
                }
                break;
            case CITIES_ALL_ROWS:
                rowsUpdated = db.update(CityTable.TABLE_CITIES, values, selection, selectionArgs);
                break;
            default:
                throw new IllegalArgumentException("Unsupported URI: " + uri);
        }
        getContext().getContentResolver().notifyChange(uri, null);
        return rowsUpdated;
    }

    /**
     * A test package can call this to get a handle to the database underlying
     * WeatherContentProvider, so it can insert test data into the database. The test case class
     * is responsible for instantiating the provider in a test context;
     * {@link android.test.ProviderTestCase2} does this during the call to setUp()
     *
     * @return a handle to the database helper object for the provider's data.
     */
    public DatabaseHelper getOpenHelperForTest() {
        return databaseHelper;
    }

}

redpajama_set_name: RedPajamaGithub


text:
#ifndef _ASM_IA64_TIMEX_H
#define _ASM_IA64_TIMEX_H

/*
 * 2001/01/18 davidm	Removed CLOCK_TICK_RATE.  It makes no sense on IA-64.
 *			Also removed cacheflush_time as it's entirely unused.
 */

#include <asm/intrinsics.h>
#include <asm/processor.h>

typedef unsigned long cycles_t;

extern void (*ia64_udelay)(unsigned long usecs);

/*
 * For performance reasons, we don't want to define CLOCK_TICK_TRATE as
 * local_cpu_data->itc_rate.  Fortunately, we don't have to, either: according to George
 * Anzinger, 1/CLOCK_TICK_RATE is taken as the resolution of the timer clock.  The time
 * calculation assumes that you will use enough of these so that your tick size <= 1/HZ.
 * If the calculation shows that your CLOCK_TICK_RATE can not supply exactly 1/HZ ticks,
 * the actual value is calculated and used to update the wall clock each jiffie.  Setting
 * the CLOCK_TICK_RATE to x*HZ insures that the calculation will find no errors.  Hence we
 * pick a multiple of HZ which gives us a (totally virtual) CLOCK_TICK_RATE of about
 * 100MHz.
 */
#define CLOCK_TICK_RATE		(HZ * 100000UL)

static inline cycles_t
get_cycles (void)
{
	cycles_t ret;

	ret = ia64_getreg(_IA64_REG_AR_ITC);
	return ret;
}

#endif /* _ASM_IA64_TIMEX_H */


text:
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
// Code generated by Microsoft (R) AutoRest Code Generator.

package com.azure.resourcemanager.containerregistry.models;

import com.azure.core.annotation.Fluent;
import com.azure.core.util.logging.ClientLogger;
import com.fasterxml.jackson.annotation.JsonIgnore;
import com.fasterxml.jackson.annotation.JsonProperty;

/** The properties of a overridable value that can be passed to a task template. */
@Fluent
public final class SetValue {
    @JsonIgnore private final ClientLogger logger = new ClientLogger(SetValue.class);

    /*
     * The name of the overridable value.
     */
    @JsonProperty(value = "name", required = true)
    private String name;

    /*
     * The overridable value.
     */
    @JsonProperty(value = "value", required = true)
    private String value;

    /*
     * Flag to indicate whether the value represents a secret or not.
     */
    @JsonProperty(value = "isSecret")
    private Boolean isSecret;

    /**
     * Get the name property: The name of the overridable value.
     *
     * @return the name value.
     */
    public String name() {
        return this.name;
    }

    /**
     * Set the name property: The name of the overridable value.
     *
     * @param name the name value to set.
     * @return the SetValue object itself.
     */
    public SetValue withName(String name) {
        this.name = name;
        return this;
    }

    /**
     * Get the value property: The overridable value.
     *
     * @return the value value.
     */
    public String value() {
        return this.value;
    }

    /**
     * Set the value property: The overridable value.
     *
     * @param value the value value to set.
     * @return the SetValue object itself.
     */
    public SetValue withValue(String value) {
        this.value = value;
        return this;
    }

    /**
     * Get the isSecret property: Flag to indicate whether the value represents a secret or not.
     *
     * @return the isSecret value.
     */
    public Boolean isSecret() {
        return this.isSecret;
    }

    /**
     * Set the isSecret property: Flag to indicate whether the value represents a secret or not.
     *
     * @param isSecret the isSecret value to set.
     * @return the SetValue object itself.
     */
    public SetValue withIsSecret(Boolean isSecret) {
        this.isSecret = isSecret;
        return this;
    }

    /**
     * Validates the instance.
     *
     * @throws IllegalArgumentException thrown if the instance is not valid.
     */
    public void validate() {
        if (name() == null) {
            throw logger
                .logExceptionAsError(new IllegalArgumentException("Missing required property name in model SetValue"));
        }
        if (value() == null) {
            throw logger
                .logExceptionAsError(new IllegalArgumentException("Missing required property value in model SetValue"));
        }
    }
}


text:
using System;
using System.Collections.Generic;
using System.IO;
using Jive.Linq.Proxy;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;

namespace Jive.Linq.Serialization
{
	public class JsonSerializer<T> : ISerialize<T>
	{
		private readonly IEntityMemberProvider<T> _memberProvider;

		public JsonSerializer(IEntityMemberProvider<T> provider)
		{
			if (provider == null)
			{
				throw new ArgumentNullException("provider");
			}
			_memberProvider = provider;
		}

		public byte[] ByteSerialize(T entity)
		{
			var json = StringSerialize(entity);
			var bytes = new byte[json.Length * sizeof(char)];
			System.Buffer.BlockCopy(json.ToCharArray(), 0, bytes, 0, bytes.Length);
			return bytes;
		}

		public string StringSerialize(T entity)
		{
			var dict = new Dictionary<string, object>();
			foreach (var member in _memberProvider.MembersToSerialize(entity))
			{
				dict[member.Property] =  member.Value();
			}
			return JsonConvert.SerializeObject(dict);
		}
	}
}


text:
goog.provide('lf.cache.ConstraintChecker');

goog.require('lf.Exception');
/** @suppress {extraRequire} */
goog.require('lf.cache.Modification');
goog.require('lf.service');
goog.require('lf.structs.map');

goog.forwardDeclare('lf.Global');
goog.forwardDeclare('lf.schema.Column');
goog.forwardDeclare('lf.schema.ForeignKeySpec');
goog.forwardDeclare('lf.schema.IndexedColumn');
goog.forwardDeclare('lf.schema.Table');

/**
 * A helper class for performing various constraint checks.
 *
 * @constructor
 * @struct
 *
 * @param {!lf.Global} global
 */
lf.cache.ConstraintChecker = function(global) {
  /** @private {!lf.index.IndexStore} */
  this.indexStore_ = global.getService(lf.service.INDEX_STORE);

  /** @private {!lf.schema.Database} */
  this.schema_ = global.getService(lf.service.SCHEMA);

  /**
   * A map where the keys are normalized lf.schema.ForeignKeySpec names, and the
   * values are corresponding parent column indices. The map is used such that
   * this association does not have to be detected more than once.
   * @private {?lf.structs.Map<name, !lf.index.Index>}
   */
  this.foreignKeysParentIndices_ = null;
};

/**
 * Finds if any row with the same primary key exists in the primary key index.
 * @param {!lf.schema.Table} table The table where the row belongs.
 * @param {!lf.Row} row The row whose primary key needs to checked.
 * @return {?number} The row ID of an existing row that has the same primary
 *     key as the input row, on null if no existing row was found.
 */
lf.cache.ConstraintChecker.prototype.findExistingRowIdInPkIndex = function(
    table, row) {
  var pkIndexSchema = table.getConstraint().getPrimaryKey();
  if (goog.isNull(pkIndexSchema)) {
    // There is no primary key for the given table.
    return null;
  }
  return this.findExistingRowIdInIndex_(pkIndexSchema, row);
};

/**
 * Finds if any row with the same index key exists in the given index.
 * @param {!lf.schema.Index} indexSchema The index to check.
 * @param {!lf.Row} row The row whose index key needs to checked.
 * @return {?number} The row ID of an existing row that has the same index
 *     key as the input row, on null if no existing row was found.
 * @private
 */
lf.cache.ConstraintChecker.prototype.findExistingRowIdInIndex_ = function(
    indexSchema, row) {
  var indexName = indexSchema.getNormalizedName();
  var indexKey = row.keyOfIndex(indexName);
  var index = this.indexStore_.get(indexName);

  var rowIds = index.get(/** @type {!lf.index.Index.Key} */ (indexKey));
  return rowIds.length == 0 ? null : rowIds[0];
};

/**
 * Checks whether any not-nullable constraint violation occurs as a result of
 * inserting/updating the given set of rows.
 * @param {!lf.schema.Table} table The table where the rows belong.
 * @param {!Array<!lf.Row>} rows The rows being inserted.
 * @throws {!lf.Exception}
 */
lf.cache.ConstraintChecker.prototype.checkNotNullable = function(table, rows) {
  var notNullable = table.getConstraint().getNotNullable();
  rows.forEach(function(row) {
    notNullable.forEach(
        /** @param {!lf.schema.Column} column */
        function(column) {
          if (!goog.isDefAndNotNull(row.payload()[column.getName()])) {
            // 202: Attempted to insert NULL value to non-nullable field {0}.
            throw new lf.Exception(202, column.getNormalizedName());
          }
        }, this);
  }, this);
};

/**
 * Checks that all referred keys in the given rows actually exist.
 * @param {!lf.schema.Table} table
 * @param {!Array<!lf.cache.Modification>} modifications
 * @param {!lf.ConstraintTiming} constraintTiming Only constraints with this
 *     timing will be checked.
 * @throws {!lf.Exception}
 * @private
 */
lf.cache.ConstraintChecker.prototype.checkReferredKeys_ = function(
    table, modifications, constraintTiming) {
  var foreignKeySpecs = table.getConstraint().getForeignKeys();
  foreignKeySpecs.forEach(function(foreignKeySpec) {
    if (foreignKeySpec.timing == constraintTiming) {
      this.checkReferredKey_(foreignKeySpec, modifications);
    }
  }, this);
};

/**
 * @param {!lf.schema.ForeignKeySpec} foreignKeySpec
 * @param {!Array<!lf.cache.Modification>} modifications
 * @throws {!lf.Exception}
 * @private
 */
lf.cache.ConstraintChecker.prototype.checkReferredKey_ = function(
    foreignKeySpec, modifications) {
  var parentIndex = this.getParentIndex_(foreignKeySpec);
  modifications.forEach(function(modification) {
    var didColumnValueChange = lf.cache.ConstraintChecker.didColumnValueChange_(
        modification[0], modification[1], foreignKeySpec.name);

    if (didColumnValueChange) {
      var rowAfter = modification[1];
      var parentKey = rowAfter.payload()[foreignKeySpec.childColumn];
      // A null value in the child column implies to ignore it, and not consider
      // it as a constraint violation.
      if (!goog.isNull(parentKey) && !parentIndex.containsKey(parentKey)) {
        // 203: Foreign key constraint violation on constraint {0}.
        throw new lf.Exception(203, foreignKeySpec.name);
      }
    }
  }, this);
};

/**
 * Finds the index corresponding to the parent column of the given foreign key,
 * by querying the schema and the IndexStore.
 * @param {!lf.schema.ForeignKeySpec} foreignKeySpec
 * @return {!lf.index.Index} The index corresponding to the parent column of the
 *     given foreign key constraint.
 * @private
 */
lf.cache.ConstraintChecker.prototype.findParentIndex_ = function(
    foreignKeySpec) {
  var parentTable = this.schema_.table(foreignKeySpec.parentTable);
  var parentColumn = /** @type {!lf.schema.Column} */ (
      parentTable[foreignKeySpec.parentColumn]);
  // getIndex() must find an index since the parent of a foreign key constraint
  // must have a dedicated index.
  var parentIndexSchema = /** @type {!lf.schema.Index} */ (
      parentColumn.getIndex());
  return /** @type {!lf.index.Index} */ (
      this.indexStore_.get(parentIndexSchema.getNormalizedName()));
};

/**
 * Gets the index corresponding to the parent column of the given foreign key.
 * Leverages this.foreignKeysParentIndices_ map, such that the work for finding
 * the parent index happens only once per foreign key.
 * @param {!lf.schema.ForeignKeySpec} foreignKeySpec
 * @return {!lf.index.Index} The index corresponding to the parent column of the
 *     given foreign key constraint.
 * @private
 */
lf.cache.ConstraintChecker.prototype.getParentIndex_ = function(
    foreignKeySpec) {
  if (goog.isNull(this.foreignKeysParentIndices_)) {
    this.foreignKeysParentIndices_ = lf.structs.map.create();
  }

  var parentIndex =
      this.foreignKeysParentIndices_.get(foreignKeySpec.name) || null;
  if (goog.isNull(parentIndex)) {
    parentIndex = this.findParentIndex_(foreignKeySpec);
    this.foreignKeysParentIndices_.set(foreignKeySpec.name, parentIndex);
  }

  return parentIndex;
};

/**
 * @param {?lf.Row} rowBefore
 * @param {?lf.Row} rowAfter
 * @param {string} indexName
 * @return {boolean}
 * @private
 */
lf.cache.ConstraintChecker.didColumnValueChange_ = function(
    rowBefore, rowAfter, indexName) {
  var deletionOrAddition = (goog.isNull(rowBefore) ? !goog.isNull(rowAfter) :
      goog.isNull(rowAfter));
  return deletionOrAddition ||
      (rowBefore.keyOfIndex(indexName) != rowAfter.keyOfIndex(indexName));
};

/**
 * Checks that no referring keys exist for the given rows.
 * @param {!lf.schema.Table} table
 * @param {!Array<!lf.cache.Modification>} modifications
 * @param {!lf.ConstraintTiming} constraintTiming Only constraints with this
 *     timing will be checked.
 * @throws {!lf.Exception}
 * @private
 */
lf.cache.ConstraintChecker.prototype.checkReferringKeys_ = function(
    table, modifications, constraintTiming) {
  var parentForeignKeys =
      this.schema_.info().getReferencingForeignKeys(table.getName());
  if (!goog.isDefAndNotNull(parentForeignKeys)) {
    return;
  }

  parentForeignKeys.forEach(
      /** @param {!lf.schema.ForeignKeySpec} foreignKeySpec */
      function(foreignKeySpec) {
        if (foreignKeySpec.timing != constraintTiming) {
          return;
        }
        var childIndex = this.indexStore_.get(foreignKeySpec.name);
        var parentIndex = this.getParentIndex_(foreignKeySpec);
        modifications.forEach(function(modification) {
          var didColumnValueChange =
              lf.cache.ConstraintChecker.didColumnValueChange_(
                  modification[0], modification[1], parentIndex.getName());

          if (didColumnValueChange) {
            var rowBefore = modification[0];
            var parentKey = rowBefore.payload()[foreignKeySpec.parentColumn];
            if (childIndex.containsKey(parentKey)) {
              // 203: Foreign key constraint violation on constraint {0}.
              throw new lf.Exception(203, foreignKeySpec.name);
            }
          }
        }, this);
      }, this);
};

/**
 * Performs all necessary foreign key constraint checks for the case where new
 * rows are inserted.
 * @param {!lf.schema.Table} table
 * @param {!Array<!lf.Row>} rows
 * @param {!lf.ConstraintTiming} constraintTiming Only constraints with this
 *     timing will be checked.
 * @throws {!lf.Exception}
 */
lf.cache.ConstraintChecker.prototype.checkForeignKeysForInsert = function(
    table, rows, constraintTiming) {
  if (rows.length == 0) {
    return;
  }

  var modifications = rows.map(function(row) {
    return [null /* rowBefore */, row /* rowNow */];
  });
  this.checkReferredKeys_(table, modifications, constraintTiming);
};

/**
 * Performs all necessary foreign key constraint checks for the case of existing
 * rows being updated.
 * @param {!lf.schema.Table} table
 * @param {!Array<!lf.cache.Modification>} modifications
 * @param {!lf.ConstraintTiming} constraintTiming Only constraints with this
 *     timing will be checked.
 * @throws {!lf.Exception}
 */
lf.cache.ConstraintChecker.prototype.checkForeignKeysForUpdate = function(
    table, modifications, constraintTiming) {
  if (modifications.length == 0) {
    return;
  }

  this.checkReferredKeys_(table, modifications, constraintTiming);
  this.checkReferringKeys_(table, modifications, constraintTiming);
};

/**
 * Performs all necessary foreign key constraint checks for the case of rows
 * being deleted.
 * @param {!lf.schema.Table} table
 * @param {!Array<!lf.Row>} rows
 * @param {!lf.ConstraintTiming} constraintTiming Only constraints with this
 *     timing will be checked.
 * @throws {!lf.Exception}
 */
lf.cache.ConstraintChecker.prototype.checkForeignKeysForDelete = function(
    table, rows, constraintTiming) {
  if (rows.length == 0) {
    return;
  }

  var modifications = rows.map(function(row) {
    return [row /* rowBefore */, null /* rowNow */];
  });
  this.checkReferringKeys_(table, modifications, constraintTiming);
};


text:
package org.archive.extract;

import java.net.MalformedURLException;
import java.net.URI;
import java.net.URISyntaxException;
import java.net.URL;
import java.net.URLEncoder;

import junit.framework.TestCase;

public class RealCDXExtractorOutputTest extends TestCase {

    public void testEscapeResolvedUrl() throws Exception {
	String context ="http://www.uni-giessen.de/cms/studium/dateien/informationberatung/merkblattpdf";
	String spec = "http://fss.plone.uni-giessen.de/fß/studium/dateien/informationberatung/merkblattpdf/file/Mérkblatt zur Gestaltung von Nachteilsausgleichen.pdf?föo=bar#änchor";
	String escaped = RealCDXExtractorOutput.resolve(context, spec);
	assertTrue(escaped.indexOf(" ") < 0);
	URI parsed = new URI(escaped);
	assertEquals("änchor", parsed.getFragment());
    }

    public void testNoDoubleEscaping() throws Exception {
	String spec = "https://www.google.com/search?q=java+escape+url+spaces&ie=utf-8&oe=utf-8";
	String resolved = RealCDXExtractorOutput.resolve(spec, spec);
	assertTrue(spec.equals(resolved));
    }
}


text:
package org.scalafmt.util

case class FormatException(exc: Throwable, code: String) extends Exception(exc)


text:
package com.ibm.jbatch.container.impl;

import java.io.ByteArrayInputStream;
import java.io.PrintWriter;
import java.io.Serializable;
import java.io.StringWriter;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.BlockingQueue;
import java.util.logging.Level;
import java.util.logging.Logger;

import javax.batch.api.chunk.CheckpointAlgorithm;
import javax.batch.runtime.BatchStatus;

import com.ibm.jbatch.container.artifact.proxy.CheckpointAlgorithmProxy;
import com.ibm.jbatch.container.artifact.proxy.ChunkListenerProxy;
import com.ibm.jbatch.container.artifact.proxy.InjectionReferences;
import com.ibm.jbatch.container.artifact.proxy.ItemProcessListenerProxy;
import com.ibm.jbatch.container.artifact.proxy.ItemProcessorProxy;
import com.ibm.jbatch.container.artifact.proxy.ItemReadListenerProxy;
import com.ibm.jbatch.container.artifact.proxy.ItemReaderProxy;
import com.ibm.jbatch.container.artifact.proxy.ItemWriteListenerProxy;
import com.ibm.jbatch.container.artifact.proxy.ItemWriterProxy;
import com.ibm.jbatch.container.artifact.proxy.ProxyFactory;
import com.ibm.jbatch.container.artifact.proxy.RetryProcessListenerProxy;
import com.ibm.jbatch.container.artifact.proxy.RetryReadListenerProxy;
import com.ibm.jbatch.container.artifact.proxy.RetryWriteListenerProxy;
import com.ibm.jbatch.container.artifact.proxy.SkipProcessListenerProxy;
import com.ibm.jbatch.container.artifact.proxy.SkipReadListenerProxy;
import com.ibm.jbatch.container.artifact.proxy.SkipWriteListenerProxy;
import com.ibm.jbatch.container.context.impl.MetricImpl;
import com.ibm.jbatch.container.context.impl.StepContextImpl;
import com.ibm.jbatch.container.exception.BatchContainerRuntimeException;
import com.ibm.jbatch.container.exception.BatchContainerServiceException;
import com.ibm.jbatch.container.jobinstance.RuntimeJobExecution;
import com.ibm.jbatch.container.persistence.CheckpointAlgorithmFactory;
import com.ibm.jbatch.container.persistence.CheckpointData;
import com.ibm.jbatch.container.persistence.CheckpointDataKey;
import com.ibm.jbatch.container.persistence.CheckpointManager;
import com.ibm.jbatch.container.persistence.ItemCheckpointAlgorithm;
import com.ibm.jbatch.container.services.IPersistenceManagerService;
import com.ibm.jbatch.container.servicesmanager.ServicesManager;
import com.ibm.jbatch.container.servicesmanager.ServicesManagerImpl;
import com.ibm.jbatch.container.util.PartitionDataWrapper;
import com.ibm.jbatch.container.util.TCCLObjectInputStream;
import com.ibm.jbatch.container.validation.ArtifactValidationException;
import com.ibm.jbatch.jsl.model.Chunk;
import com.ibm.jbatch.jsl.model.ItemProcessor;
import com.ibm.jbatch.jsl.model.ItemReader;
import com.ibm.jbatch.jsl.model.ItemWriter;
import com.ibm.jbatch.jsl.model.Property;
import com.ibm.jbatch.jsl.model.Step;

public class ChunkStepControllerImpl extends SingleThreadedStepControllerImpl {

	private final static String sourceClass = ChunkStepControllerImpl.class.getName();
	private final static Logger logger = Logger.getLogger(sourceClass);

	private Chunk chunk = null;
	private ItemReaderProxy readerProxy = null;
	private ItemProcessorProxy processorProxy = null;
	private ItemWriterProxy writerProxy = null;
	private CheckpointAlgorithmProxy checkpointProxy = null;
	private CheckpointAlgorithm chkptAlg = null;
	private CheckpointManager checkpointManager;
	private ServicesManager servicesManager = ServicesManagerImpl.getInstance();
	private IPersistenceManagerService _persistenceManagerService = null;
	private SkipHandler skipHandler = null;
	CheckpointDataKey readerChkptDK, writerChkptDK = null;
	CheckpointData readerChkptData = null;
	CheckpointData writerChkptData = null;
	List<ChunkListenerProxy> chunkListeners = null;
	List<SkipProcessListenerProxy> skipProcessListeners = null;
	List<SkipReadListenerProxy> skipReadListeners = null;
	List<SkipWriteListenerProxy> skipWriteListeners = null;
	List<RetryProcessListenerProxy> retryProcessListeners = null;
	List<RetryReadListenerProxy> retryReadListeners = null;
	List<RetryWriteListenerProxy> retryWriteListeners = null;
	List<ItemReadListenerProxy> itemReadListeners = null;
	List<ItemProcessListenerProxy> itemProcessListeners = null;
	List<ItemWriteListenerProxy> itemWriteListeners = null;
	private RetryHandler retryHandler;

	// metrics
	long readCount = 0;
	long writeCount = 0;
	long readSkipCount = 0;
	long processSkipCount = 0;
	long writeSkipCount = 0;
	boolean rollbackRetry = false;

	public ChunkStepControllerImpl(RuntimeJobExecution jobExecutionImpl, Step step, StepContextImpl stepContext, long rootJobExecutionId, BlockingQueue<PartitionDataWrapper> analyzerStatusQueue) {
		super(jobExecutionImpl, step, stepContext, rootJobExecutionId, analyzerStatusQueue);
	}

	/**
	 * Utility Class to hold statuses at each level of Read-Process-Write loop
	 *
	 */
	private class ItemStatus {

		public boolean isSkipped() {
			return skipped;
		}

		public void setSkipped(boolean skipped) {
			this.skipped = skipped;
		}

		public boolean isFiltered() {
			return filtered;
		}

		public void setFiltered(boolean filtered) {
			this.filtered = filtered;
		}

		public boolean isCheckPointed() {
			return checkPointed;
		}

		public void setCheckPointed(boolean checkPointed) {
			this.checkPointed = checkPointed;
		}

		public boolean isFinished() {
			return finished;
		}

		public void setFinished(boolean finished) {
			this.finished = finished;
		}

		public boolean isRetry() {
			return retry;
		}

		public void setRetry(boolean retry) {
			this.retry = retry;
		}

		public boolean isRollback() {
			return rollback;
		}

		public void setRollback(boolean rollback) {
			this.rollback = rollback;
		}

		private boolean skipped = false;
		private boolean filtered = false;
		private boolean finished = false;
		private boolean checkPointed = false;
		private boolean retry = false;
		private boolean rollback = false;

	}

	/**
	 * We read and process one item at a time but write in chunks (group of
	 * items). So, this method loops until we either reached the end of the
	 * reader (not more items to read), or the writer buffer is full or a
	 * checkpoint is triggered.
	 *
	 * @param chunkSize
	 *            write buffer size
	 * @param theStatus
	 *            flags when the read-process reached the last record or a
	 *            checkpoint is required
	 * @return an array list of objects to write
	 */
	private List<Object> readAndProcess(int chunkSize, ItemStatus theStatus) {
		logger.entering(sourceClass, "readAndProcess", new Object[] { chunkSize, theStatus });

		List<Object> chunkToWrite = new ArrayList<Object>();
		Object itemRead = null;
		Object itemProcessed = null;
		int readProcessedCount = 0;

		while (true) {
			ItemStatus status = new ItemStatus();
			itemRead = readItem(status);

			if (status.isRollback()) {
				theStatus.setRollback(true);
				// inc rollbackCount
				stepContext.getMetric(MetricImpl.MetricType.ROLLBACK_COUNT).incValue();
				break;
			}

			if (!status.isSkipped() && !status.isFinished()) {
				itemProcessed = processItem(itemRead, status);

				if (status.isRollback()) {
					theStatus.setRollback(true);
					// inc rollbackCount
					stepContext.getMetric(MetricImpl.MetricType.ROLLBACK_COUNT).incValue();
					break;
				}

				if (!status.isSkipped() && !status.isFiltered()) {
					chunkToWrite.add(itemProcessed);
					readProcessedCount++;
				}
			}

			theStatus.setFinished(status.isFinished());
			theStatus.setCheckPointed(checkpointManager.ApplyCheckPointPolicy());

			// This will force the current item to finish processing on a stop
			// request
			if (stepContext.getBatchStatus().equals(BatchStatus.STOPPING)) {
				theStatus.setFinished(true);
			}

			// write buffer size reached
			if ((readProcessedCount == chunkSize) && (checkpointProxy.getCheckpointType() != "custom")) {
				break;
			}

			// checkpoint reached
			if (theStatus.isCheckPointed()) {
				break;
			}

			// last record in readerProxy reached
			if (theStatus.isFinished()) {
				break;
			}

		}
		logger.exiting(sourceClass, "readAndProcess", chunkToWrite);
		return chunkToWrite;
	}

	/**
	 * Reads an item from the reader
	 *
	 * @param status
	 *            flags the current read status
	 * @return the item read
	 */
	private Object readItem(ItemStatus status) {
		logger.entering(sourceClass, "readItem", status);
		Object itemRead = null;

		try {
			// call read listeners before and after the actual read
			for (ItemReadListenerProxy readListenerProxy : itemReadListeners) {
				readListenerProxy.beforeRead();
			}

			itemRead = readerProxy.readItem();

			for (ItemReadListenerProxy readListenerProxy : itemReadListeners) {
				readListenerProxy.afterRead(itemRead);
			}

			// itemRead == null means we reached the end of
			// the readerProxy "resultset"
			status.setFinished(itemRead == null);
			if (!status.isFinished()) {
				stepContext.getMetric(MetricImpl.MetricType.READ_COUNT).incValue();
			}
		} catch (Exception e) {
			stepContext.setException(e);
			for (ItemReadListenerProxy readListenerProxy : itemReadListeners) {
				readListenerProxy.onReadError(e);
			}
			if(!rollbackRetry) {
				if (retryReadException(e)) {
					for (ItemReadListenerProxy readListenerProxy : itemReadListeners) {
						readListenerProxy.onReadError(e);
					}
					// if not a rollback exception, just retry the current item
					if (!retryHandler.isRollbackException(e)) {
						itemRead = readItem(status);
					} else {
						status.setRollback(true);
						rollbackRetry = true;
						// inc rollbackCount
						stepContext.getMetric(MetricImpl.MetricType.ROLLBACK_COUNT).incValue();
					}
				}
				else if(skipReadException(e)) {
					status.setSkipped(true);
					stepContext.getMetric(MetricImpl.MetricType.READ_SKIP_COUNT).incValue();

				}
				else {
					throw new BatchContainerRuntimeException(e);
				}
			}
			else {
				// coming from a rollback retry
				if(skipReadException(e)) {
					status.setSkipped(true);
					stepContext.getMetric(MetricImpl.MetricType.READ_SKIP_COUNT).incValue();

				}
				else if (retryReadException(e)) {
					if (!retryHandler.isRollbackException(e)) {
						itemRead = readItem(status);
					}
					else {
						status.setRollback(true);
						// inc rollbackCount
						stepContext.getMetric(MetricImpl.MetricType.ROLLBACK_COUNT).incValue();
					}
				}
				else {
					throw new BatchContainerRuntimeException(e);
				}
			}

		} catch (Throwable e) {
			throw new BatchContainerRuntimeException(e);
		}

		logger.exiting(sourceClass, "readItem", itemRead==null ? "<null>" : itemRead);
		return itemRead;
	}

	/**
	 * Process an item previously read by the reader
	 *
	 * @param itemRead
	 *            the item read
	 * @param status
	 *            flags the current process status
	 * @return the processed item
	 */
	private Object processItem(Object itemRead, ItemStatus status) {
		logger.entering(sourceClass, "processItem", new Object[] { itemRead, status });
		Object processedItem = null;

		// if no processor defined for this chunk
		if (processorProxy == null){
			return itemRead;
		}

		try {

			// call process listeners before and after the actual process call
			for (ItemProcessListenerProxy processListenerProxy : itemProcessListeners) {
				processListenerProxy.beforeProcess(itemRead);
			}

			processedItem = processorProxy.processItem(itemRead);

			if (processedItem == null) {
				// inc filterCount
				stepContext.getMetric(MetricImpl.MetricType.FILTER_COUNT).incValue();
				status.setFiltered(true);
			}

			for (ItemProcessListenerProxy processListenerProxy : itemProcessListeners) {
				processListenerProxy.afterProcess(itemRead, processedItem);
			}
		} catch (Exception e) {
			for (ItemProcessListenerProxy processListenerProxy : itemProcessListeners) {
				processListenerProxy.onProcessError(processedItem, e);
			}
			if(!rollbackRetry) {
				if (retryProcessException(e, itemRead)) {
					if (!retryHandler.isRollbackException(e)) {
						// call process listeners before and after the actual
						// process call
						for (ItemProcessListenerProxy processListenerProxy : itemProcessListeners) {
							processListenerProxy.beforeProcess(itemRead);
						}
						processedItem = processItem(itemRead, status);
						if (processedItem == null) {
							// inc filterCount
							stepContext.getMetric(MetricImpl.MetricType.FILTER_COUNT).incValue();
							status.setFiltered(true);
						}

						for (ItemProcessListenerProxy processListenerProxy : itemProcessListeners) {
							processListenerProxy.afterProcess(itemRead, processedItem);
						}
					} else {
						status.setRollback(true);
						rollbackRetry = true;
						// inc rollbackCount
						stepContext.getMetric(MetricImpl.MetricType.ROLLBACK_COUNT).incValue();
					}
				}
				else if (skipProcessException(e, itemRead)) {
					status.setSkipped(true);
					stepContext.getMetric(MetricImpl.MetricType.PROCESS_SKIP_COUNT).incValue();
				}
				else {
					throw new BatchContainerRuntimeException(e);
				}
			}
			else {
				if (skipProcessException(e, itemRead)) {
					status.setSkipped(true);
					stepContext.getMetric(MetricImpl.MetricType.PROCESS_SKIP_COUNT).incValue();
				} else if (retryProcessException(e, itemRead)) {
					if (!retryHandler.isRollbackException(e)) {
						// call process listeners before and after the actual
						// process call
						for (ItemProcessListenerProxy processListenerProxy : itemProcessListeners) {
							processListenerProxy.beforeProcess(itemRead);
						}
						processedItem = processItem(itemRead, status);
						if (processedItem == null) {
							// inc filterCount
							stepContext.getMetric(MetricImpl.MetricType.FILTER_COUNT).incValue();
							status.setFiltered(true);
						}

						for (ItemProcessListenerProxy processListenerProxy : itemProcessListeners) {
							processListenerProxy.afterProcess(itemRead, processedItem);
						}
					} else {
						status.setRollback(true);
						rollbackRetry = true;
						// inc rollbackCount
						stepContext.getMetric(MetricImpl.MetricType.ROLLBACK_COUNT).incValue();
					}
				} else {
					throw new BatchContainerRuntimeException(e);
				}
			}

		} catch (Throwable e) {
			throw new BatchContainerRuntimeException(e);
		}

		logger.exiting(sourceClass, "processItem", processedItem==null ? "<null>" : processedItem);
		return processedItem;
	}

	/**
	 * Writes items
	 *
	 * @param theChunk
	 *            the array list with all items processed ready to be written
	 */
	private void writeChunk(List<Object> theChunk, ItemStatus status) {
		logger.entering(sourceClass, "writeChunk", theChunk);
		if (!theChunk.isEmpty()) {
			try {

				// call read listeners before and after the actual read
				for (ItemWriteListenerProxy writeListenerProxy : itemWriteListeners) {
					writeListenerProxy.beforeWrite(theChunk);
				}

				writerProxy.writeItems(theChunk);

				for (ItemWriteListenerProxy writeListenerProxy : itemWriteListeners) {
					writeListenerProxy.afterWrite(theChunk);
				}
				stepContext.getMetric(MetricImpl.MetricType.WRITE_COUNT).incValueBy(theChunk.size());
			} catch (Exception e) {
				this.stepContext.setException(e);
				for (ItemWriteListenerProxy writeListenerProxy : itemWriteListeners) {
					writeListenerProxy.onWriteError(theChunk, e);
				}
				if(!rollbackRetry)
				{
					if (retryWriteException(e, theChunk)) {
						if (!retryHandler.isRollbackException(e)) {
							writeChunk(theChunk, status);
						} else {
							rollbackRetry = true;
							status.setRollback(true);
							// inc rollbackCount
							stepContext.getMetric(MetricImpl.MetricType.ROLLBACK_COUNT).incValue();
						}
					} else if (skipWriteException(e, theChunk)) {
						stepContext.getMetric(MetricImpl.MetricType.WRITE_SKIP_COUNT).incValueBy(1);
					} else {
						throw new BatchContainerRuntimeException(e);
					}

				}
				else {
					if (skipWriteException(e, theChunk)) {
						stepContext.getMetric(MetricImpl.MetricType.WRITE_SKIP_COUNT).incValueBy(1);
					} else if (retryWriteException(e, theChunk)) {
						if (!retryHandler.isRollbackException(e)) {
							status.setRetry(true);
							writeChunk(theChunk, status);
						} else {
							rollbackRetry = true;
							status.setRollback(true);
							// inc rollbackCount
							stepContext.getMetric(MetricImpl.MetricType.ROLLBACK_COUNT).incValue();
						}
					} else {
						throw new BatchContainerRuntimeException(e);
					}
				}

			} catch (Throwable e) {
				throw new BatchContainerRuntimeException(e);
			}
		}
		logger.exiting(sourceClass, "writeChunk");
	}

	/**
	 * Main Read-Process-Write loop
	 *
	 * @throws Exception
	 */
	private void invokeChunk() {
		logger.entering(sourceClass, "invokeChunk2");

		int itemCount = ChunkHelper.getItemCount(chunk);
		int timeInterval = ChunkHelper.getTimeLimit(chunk);
		List<Object> chunkToWrite = new ArrayList<Object>();
		boolean checkPointed = true;
		boolean rollback = false;
		Throwable caughtThrowable = null;

		// begin new transaction at first iteration or after a checkpoint commit

		try {
			transactionManager.begin();
			this.openReaderAndWriter();
			transactionManager.commit();

			while (true) {

				if (checkPointed || rollback) {
					if (this.checkpointProxy.getCheckpointType() == "custom" ){
						int newtimeOut = this.checkpointManager.checkpointTimeout();
						transactionManager.setTransactionTimeout(newtimeOut);
					}
					transactionManager.begin();
					for (ChunkListenerProxy chunkProxy : chunkListeners) {
						chunkProxy.beforeChunk();
					}

					if (rollback) {
						positionReaderAtCheckpoint();
						positionWriterAtCheckpoint();
						checkpointManager = new CheckpointManager(readerProxy, writerProxy,
								getCheckpointAlgorithm(itemCount, timeInterval), jobExecutionImpl.getExecutionId(), jobExecutionImpl
								.getJobInstance().getInstanceId(), step.getId());
					}
				}

				ItemStatus status = new ItemStatus();

				if (rollback) {
					rollback = false;
				}

				chunkToWrite = readAndProcess(itemCount, status);

				if (status.isRollback()) {
					itemCount = 1;
					rollback = true;

					readerProxy.close();
					writerProxy.close();

					transactionManager.rollback();

					continue;
				}

				writeChunk(chunkToWrite, status);

				if (status.isRollback()) {
					itemCount = 1;
					rollback = true;

					readerProxy.close();
					writerProxy.close();

					transactionManager.rollback();

					continue;
				}
				checkPointed = status.isCheckPointed();

				// we could finish the chunk in 3 conditions: buffer is full,
				// checkpoint, not more input
				if (status.isCheckPointed() || status.isFinished()) {
					// TODO: missing before checkpoint listeners
					// 1.- check if spec list proper steps for before checkpoint
					// 2.- ask Andy about retry
					// 3.- when do we stop?

							checkpointManager.checkpoint();

							for (ChunkListenerProxy chunkProxy : chunkListeners) {
								chunkProxy.afterChunk();
							}

							this.persistUserData();

							this.chkptAlg.beginCheckpoint();

							transactionManager.commit();

							this.chkptAlg.endCheckpoint();

							invokeCollectorIfPresent();

							// exit loop when last record is written
							if (status.isFinished()) {
								transactionManager.begin();

								readerProxy.close();
								writerProxy.close();

								transactionManager.commit();
								// increment commitCount
								stepContext.getMetric(MetricImpl.MetricType.COMMIT_COUNT).incValue();
								break;
							} else {
								// increment commitCount
								stepContext.getMetric(MetricImpl.MetricType.COMMIT_COUNT).incValue();
							}

				}

			}
		} catch (Exception e) {
			caughtThrowable = e;
			logger.log(Level.SEVERE, "Failure in Read-Process-Write Loop", e);
			// Only try to call onError() if we have an Exception, but not an Error.
			for (ChunkListenerProxy chunkProxy : chunkListeners) {
				try {
					chunkProxy.onError(e);
				} catch (Exception e1) {
					StringWriter sw = new StringWriter();
					PrintWriter pw = new PrintWriter(sw);
					e1.printStackTrace(pw);
					logger.warning("Caught secondary exception when calling chunk listener onError() with stack trace: " + sw.toString() + "\n. Will continue to remaining chunk listeners (if any) and rethrow wrapping the primary exception.");
				}
			}
		} catch (Throwable t) {
			caughtThrowable = t;
			logger.log(Level.SEVERE, "Failure in Read-Process-Write Loop", t);
		} finally {
			if (caughtThrowable != null) {
				transactionManager.setRollbackOnly();
				logger.warning("Caught throwable in chunk processing. Attempting to close all readers and writers.");
				readerProxy.close();
				writerProxy.close();
				transactionManager.rollback();
				logger.exiting(sourceClass, "invokeChunk");
				throw new BatchContainerRuntimeException("Failure in Read-Process-Write Loop", caughtThrowable);
			} else {
				logger.finest("Exiting normally");
				logger.exiting(sourceClass, "invokeChunk");
			}
		}
	}

	protected void invokeCoreStep() throws BatchContainerServiceException {

		this.chunk = step.getChunk();

		initializeChunkArtifacts();

		invokeChunk();
	}

	private CheckpointAlgorithm getCheckpointAlgorithm(int itemCount, int timeInterval) {
		CheckpointAlgorithm alg = null;

		if (checkpointProxy.getCheckpointType() == "item") {
			alg = new ItemCheckpointAlgorithm();
			((ItemCheckpointAlgorithm) alg).setThresholds(itemCount, timeInterval);
		} else { // custom chkpt alg
			alg = (CheckpointAlgorithm) checkpointProxy;
		}

		return alg;
	}

	/*
	 * Initialize itemreader, itemwriter, and item processor checkpoint
	 */
	private void initializeChunkArtifacts() {
		String sourceMethod = "initializeChunkArtifacts";
		if (logger.isLoggable(Level.FINE))
			logger.entering(sourceClass, sourceMethod);

		int itemCount = ChunkHelper.getItemCount(chunk);
		int timeInterval = ChunkHelper.getTimeLimit(chunk);
		String checkpointPolicy = ChunkHelper.getCheckpointPolicy(chunk);

		ItemReader itemReader = chunk.getReader();
		List<Property> itemReaderProps = itemReader.getProperties() == null ? null : itemReader.getProperties().getPropertyList();
		try {
			InjectionReferences injectionRef = new InjectionReferences(jobExecutionImpl.getJobContext(), stepContext,
					itemReaderProps);

			readerProxy = ProxyFactory.createItemReaderProxy(itemReader.getRef(), injectionRef, stepContext);

			if (logger.isLoggable(Level.FINE)) {
				logger.fine("Created ItemReaderProxy for " + itemReader.getRef());
			}
		} catch (ArtifactValidationException e) {
			throw new BatchContainerServiceException("Cannot create the ItemReader [" + itemReader.getRef() + "]", e);
		}

		ItemProcessor itemProcessor = chunk.getProcessor();
		if (itemProcessor != null){
			List<Property> itemProcessorProps = itemProcessor.getProperties() == null ? null : itemProcessor.getProperties().getPropertyList();
			try {

				InjectionReferences injectionRef = new InjectionReferences(jobExecutionImpl.getJobContext(), stepContext,
						itemProcessorProps);

				processorProxy = ProxyFactory.createItemProcessorProxy(itemProcessor.getRef(), injectionRef, stepContext);
				if (logger.isLoggable(Level.FINE)) {
					logger.fine("Created ItemProcessorProxy for " + itemProcessor.getRef());
				}
			} catch (ArtifactValidationException e) {
				throw new BatchContainerServiceException("Cannot create the ItemProcessor [" + itemProcessor.getRef() + "]", e);
			}
		}

		ItemWriter itemWriter = chunk.getWriter();
		List<Property> itemWriterProps = itemWriter.getProperties() == null ? null : itemWriter.getProperties().getPropertyList();
		try {
			InjectionReferences injectionRef = new InjectionReferences(jobExecutionImpl.getJobContext(), stepContext,
					itemWriterProps);

			writerProxy = ProxyFactory.createItemWriterProxy(itemWriter.getRef(), injectionRef, stepContext);
			if (logger.isLoggable(Level.FINE)) {
				logger.fine("Created ItemWriterProxy for " + itemWriter.getRef());
			}
		} catch (ArtifactValidationException e) {
			throw new BatchContainerServiceException("Cannot create the ItemWriter [" + itemWriter.getRef() + "]", e);
		}

		try {
			List<Property> propList = null;

			if (chunk.getCheckpointAlgorithm() != null) {

				propList = (chunk.getCheckpointAlgorithm().getProperties() == null) ? null : chunk.getCheckpointAlgorithm().getProperties()
						.getPropertyList();
			}

			InjectionReferences injectionRef = new InjectionReferences(jobExecutionImpl.getJobContext(), stepContext,
					propList);

			checkpointProxy = CheckpointAlgorithmFactory.getCheckpointAlgorithmProxy(step, injectionRef, stepContext);
			if (logger.isLoggable(Level.FINE)) {
				logger.fine("Created CheckpointAlgorithmProxy for policy [" + checkpointPolicy + "]");
			}
		} catch (ArtifactValidationException e) {
			throw new BatchContainerServiceException("Cannot create the CheckpointAlgorithm for policy [" + chunk.getCheckpointPolicy()
					+ "]", e);
		}

		InjectionReferences injectionRef = new InjectionReferences(jobExecutionImpl.getJobContext(), stepContext,
				null);

		this.chunkListeners = jobExecutionImpl.getListenerFactory().getChunkListeners(step, injectionRef, stepContext);
		this.skipProcessListeners = jobExecutionImpl.getListenerFactory().getSkipProcessListeners(step, injectionRef, stepContext);
		this.skipReadListeners = jobExecutionImpl.getListenerFactory().getSkipReadListeners(step, injectionRef, stepContext);
		this.skipWriteListeners = jobExecutionImpl.getListenerFactory().getSkipWriteListeners(step, injectionRef, stepContext);
		this.retryProcessListeners = jobExecutionImpl.getListenerFactory().getRetryProcessListeners(step, injectionRef, stepContext);
		this.retryReadListeners = jobExecutionImpl.getListenerFactory().getRetryReadListeners(step, injectionRef, stepContext);
		this.retryWriteListeners = jobExecutionImpl.getListenerFactory().getRetryWriteListeners(step, injectionRef, stepContext);
		this.itemReadListeners = jobExecutionImpl.getListenerFactory().getItemReadListeners(step, injectionRef, stepContext);
		this.itemProcessListeners = jobExecutionImpl.getListenerFactory().getItemProcessListeners(step, injectionRef, stepContext);
		this.itemWriteListeners = jobExecutionImpl.getListenerFactory().getItemWriteListeners(step, injectionRef, stepContext);

		if (checkpointProxy.getCheckpointType() == "item") {
			chkptAlg = new ItemCheckpointAlgorithm();
			((ItemCheckpointAlgorithm) chkptAlg).setThresholds(itemCount, timeInterval);
		} else { // custom chkpt alg
			chkptAlg = (CheckpointAlgorithm) checkpointProxy;
		}

		if (logger.isLoggable(Level.FINE)) {
			logger.fine("Setting contexts for chunk artifacts");
		}

		if (logger.isLoggable(Level.FINE))
			logger.fine("Initialize checkpoint manager with item-count=" + itemCount);
		logger.fine("Initialize checkpoint manager with time-interval=" + timeInterval);

		checkpointManager = new CheckpointManager(readerProxy, writerProxy, chkptAlg, jobExecutionImpl.getExecutionId(), jobExecutionImpl
				.getJobInstance().getInstanceId(), step.getId());

		skipHandler = new SkipHandler(chunk, jobExecutionImpl.getJobInstance().getInstanceId(), step.getId());
		skipHandler.addSkipProcessListener(skipProcessListeners);
		skipHandler.addSkipReadListener(skipReadListeners);
		skipHandler.addSkipWriteListener(skipWriteListeners);

		retryHandler = new RetryHandler(chunk, jobExecutionImpl.getJobInstance().getInstanceId(), step.getId());

		retryHandler.addRetryProcessListener(retryProcessListeners);
		retryHandler.addRetryReadListener(retryReadListeners);
		retryHandler.addRetryWriteListener(retryWriteListeners);

		if (logger.isLoggable(Level.FINE))
			logger.exiting(sourceClass, sourceMethod);
	}

	private void openReaderAndWriter() {
		String sourceMethod = "openReaderAndWriter";

		if (logger.isLoggable(Level.FINE))
			logger.entering(sourceClass, sourceMethod);

		_persistenceManagerService = servicesManager.getPersistenceManagerService();
		readerChkptDK = new CheckpointDataKey(jobExecutionImpl.getJobInstance().getInstanceId(), step.getId(), "READER");
		CheckpointData readerChkptData = _persistenceManagerService.getCheckpointData(readerChkptDK);
		try {

			// check for data in backing store
			if (readerChkptData != null) {

				byte[] readertoken = readerChkptData.getRestartToken();
				ByteArrayInputStream readerChkptBA = new ByteArrayInputStream(readertoken);
				TCCLObjectInputStream readerOIS = null;
				try {
					readerOIS = new TCCLObjectInputStream(readerChkptBA);
					readerProxy.open((Serializable) readerOIS.readObject());
					readerOIS.close();
				} catch (Exception ex) {
					// is this what I should be throwing here?
							throw new BatchContainerServiceException("Cannot persist the checkpoint data for [" + step.getId() + "]", ex);
				}
			} else {
				// no chkpt data exists in the backing store
				readerChkptData = null;
				readerProxy.open(null);
			}
		} catch (ClassCastException e) {
			logger.warning("Expected CheckpointData but found" + readerChkptData );
			throw new IllegalStateException("Expected CheckpointData but found" + readerChkptData );
		}

		writerChkptDK = new CheckpointDataKey(jobExecutionImpl.getJobInstance().getInstanceId(), step.getId(), "WRITER");
		CheckpointData writerChkptData = _persistenceManagerService.getCheckpointData(writerChkptDK);

		try {
			// check for data in backing store
			if (writerChkptData != null) {
				byte[] writertoken = writerChkptData.getRestartToken();
				ByteArrayInputStream writerChkptBA = new ByteArrayInputStream(writertoken);
				TCCLObjectInputStream writerOIS = null;
				try {
					writerOIS = new TCCLObjectInputStream(writerChkptBA);
					writerProxy.open((Serializable) writerOIS.readObject());
					writerOIS.close();
				} catch (Exception ex) {
					// is this what I should be throwing here?
							throw new BatchContainerServiceException("Cannot persist the checkpoint data for [" + step.getId() + "]", ex);
				}
			} else {
				// no chkpt data exists in the backing store
				writerChkptData = null;
				writerProxy.open(null);
			}
		} catch (ClassCastException e) {
			logger.warning("Expected Checkpoint but found" + writerChkptData);
			throw new IllegalStateException("Expected Checkpoint but found" + writerChkptData);
		}

		// set up metrics
		// stepContext.addMetric(MetricImpl.Counter.valueOf("READ_COUNT"), 0);
		// stepContext.addMetric(MetricImpl.Counter.valueOf("WRITE_COUNT"), 0);
		// stepContext.addMetric(MetricImpl.Counter.valueOf("READ_SKIP_COUNT"),
		// 0);
		// stepContext.addMetric(MetricImpl.Counter.valueOf("PROCESS_SKIP_COUNT"),
		// 0);
		// stepContext.addMetric(MetricImpl.Counter.valueOf("WRITE_SKIP_COUNT"),
		// 0);

		if (logger.isLoggable(Level.FINE))
			logger.exiting(sourceClass, sourceMethod);
	}

	@Override
	public void stop() {
		stepContext.setBatchStatus(BatchStatus.STOPPING);

		// we don't need to call stop on the chunk implementation here since a
		// chunk always returns control to
		// the batch container after every item.

	}

	boolean skipReadException(Exception e) {

		try {
			skipHandler.handleExceptionRead(e);
		} catch (BatchContainerRuntimeException bcre) {
			return false;
		}

		return true;

	}

	boolean retryReadException(Exception e) {

		try {
			retryHandler.handleExceptionRead(e);
		} catch (BatchContainerRuntimeException bcre) {
			return false;
		}

		return true;

	}

	boolean skipProcessException(Exception e, Object record) {

		try {
			skipHandler.handleExceptionWithRecordProcess(e, record);
		} catch (BatchContainerRuntimeException bcre) {
			return false;
		}

		return true;

	}

	boolean retryProcessException(Exception e, Object record) {

		try {
			retryHandler.handleExceptionProcess(e, record);
		} catch (BatchContainerRuntimeException bcre) {
			return false;
		}

		return true;

	}

	boolean skipWriteException(Exception e, List<Object> chunkToWrite) {

		try {
			skipHandler.handleExceptionWithRecordListWrite(e, chunkToWrite);
		} catch (BatchContainerRuntimeException bcre) {
			return false;
		}

		return true;

	}

	boolean retryWriteException(Exception e, List<Object> chunkToWrite) {

		try {
			retryHandler.handleExceptionWrite(e, chunkToWrite);
		} catch (BatchContainerRuntimeException bcre) {
			return false;
		}

		return true;

	}

	private void positionReaderAtCheckpoint() {
		_persistenceManagerService = servicesManager.getPersistenceManagerService();
		readerChkptDK = new CheckpointDataKey(jobExecutionImpl.getJobInstance().getInstanceId(), step.getId(), "READER");

		CheckpointData readerData = _persistenceManagerService.getCheckpointData(readerChkptDK);
		try {
			// check for data in backing store
			if (readerData != null) {
				byte[] readertoken = readerData.getRestartToken();
				ByteArrayInputStream readerChkptBA = new ByteArrayInputStream(readertoken);
				TCCLObjectInputStream readerOIS = null;
				try {
					readerOIS = new TCCLObjectInputStream(readerChkptBA);
					readerProxy.open((Serializable) readerOIS.readObject());
					readerOIS.close();
				} catch (Exception ex) {
					// is this what I should be throwing here?
							throw new BatchContainerServiceException("Cannot persist the checkpoint data for [" + step.getId() + "]", ex);
				}
			} else {
				// no chkpt data exists in the backing store
				readerData = null;
				readerProxy.open(null);
			}
		} catch (ClassCastException e) {
			throw new IllegalStateException("Expected CheckpointData but found" + readerData);
		}
	}

	private void positionWriterAtCheckpoint() {
		_persistenceManagerService = servicesManager.getPersistenceManagerService();
		writerChkptDK = new CheckpointDataKey(jobExecutionImpl.getJobInstance().getInstanceId(), step.getId(), "WRITER");

		CheckpointData writerData =  _persistenceManagerService.getCheckpointData(writerChkptDK);

		try {
			// check for data in backing store
			if (writerData != null) {
				byte[] writertoken = writerData.getRestartToken();
				ByteArrayInputStream writerChkptBA = new ByteArrayInputStream(writertoken);
				TCCLObjectInputStream writerOIS = null;
				try {
					writerOIS = new TCCLObjectInputStream(writerChkptBA);
					writerProxy.open((Serializable) writerOIS.readObject());
					writerOIS.close();
				} catch (Exception ex) {
					// is this what I should be throwing here?
							throw new BatchContainerServiceException("Cannot persist the checkpoint data for [" + step.getId() + "]", ex);
				}
			} else {
				// no chkpt data exists in the backing store
				writerData = null;
				writerProxy.open(null);
			}
		} catch (ClassCastException e) {
			throw new IllegalStateException("Expected CheckpointData but found" + writerData);
		}
	}
}


text:
"use strict";
var express = require('express')
  , routes = require('./routes')
  , http = require('http')
  , path = require('path');

var app = express();

app.configure(function(){
  app.set('port', process.env.PORT || 3000);
  app.set('views', __dirname + '/views');
  app.set('view engine', 'ejs');
  app.use(express.favicon());
  app.use(express.logger('dev'));
  app.use(express.bodyParser());
  app.use(express.methodOverride());
  app.use(app.router);
  app.use(require('less-middleware')(path.join(__dirname, 'public')));
  app.use(express.static(path.join(__dirname, 'public')));
});

app.configure('development', function(){
  app.use(express.errorHandler());
});

app.get('/', routes.index);

var server = http.createServer(app);

var mongoose = require('mongoose');

//localhostのnode_memo_demoのデータベースに接続。
var db = mongoose.connect('mongodb://localhost/node_memo_demo');
//メモのスキーマを宣言。
var MemoSchema = new mongoose.Schema({
	text:{type:String}
	,position:{
		left:Number
		,top:Number
	}
});
//スキーマからモデルを生成。
var Memo = db.model('memo',MemoSchema);

server.listen(app.get('port'), function(){
  console.log("Express server listening on port " + app.get('port'));
});

var io = require('socket.io').listen(server);

io.sockets.on('connection',function(socket){
	Memo.find(function(err,items){
		if(err){console.log(err);}
		//接続したユーザにメモのデータを送る。
		socket.emit('create',items);
	});
	//createイベントを受信した時、データベースにMemoを追加する。
	//memoDataは{text:String,position:{left:Number,top:Number}}の型
	socket.on('create',function(memoData){
		//モデルからインスタンス作成
		var memo = new Memo(memoData);
		//データベースに保存。
		memo.save(function(err){
			if(err){ return; }
			socket.broadcast.json.emit('create',[memo]);
			socket.emit('create',[memo]);
		});
	});
	//moveイベントを受信した時、Memoのpositionをアップデートする。
	socket.on('move',function(data){
		//データベースから_idが一致するデータを検索
		Memo.findOne({_id:data._id},function(err,memo){
			if(err || memo === null){return;}
			memo.position = data.position;
			memo.save();
			//他のクライアントにイベントを伝えるためにbroadcastで送信する。
			socket.broadcast.json.emit('move',data);
		});
	});
	//update-textイベントを受信した時、Memoのtextをアップデートする。
	socket.on('update-text',function(data){
		Memo.findOne({_id:data._id},function(err,memo){
			if(err || memo === null){return;}
			memo.text = data.text;
			memo.save();
			socket.broadcast.json.emit('update-text',data);
		});
	});
	//removeイベントを受信した時、データベースから削除する。
	socket.on('remove',function(data){
		Memo.findOne({_id:data._id},function(err,memo){
			if(err || memo === null){return;}
			memo.remove();
			socket.broadcast.json.emit('remove',data);
		});
	});
});


text:
'use strict';

angular.module('com.teachscape.coding')
	.factory('http_restaurants', [ '$http', function( $http ){
		var data = false; //cache

		function Restaurants( inits ){
			angular.extend( this, inits );
			return this;
		}

		angular.extend( Restaurants.prototype, {
			getRestaurantById: function( id ){
				var restaurants = this.restaurants;
				for( var i = 0, l = restaurants.length; i < l; i++ ){
					if( restaurants[ i ].id == id ){
						return restaurants[ i ];
					}
				}
			}
		} );

		return function( cb ){
			if( data ){
				return cb( data );
			} else {
				$http.get('data/restaurants.json' )
					.success( function( transport ){
						data = new Restaurants( transport );
						cb( data );
					} )
					.error( function(){
						//TODO: friendly service error message
					} )
				;
			}
		};
	}])
;


text:
package org.loon.framework.javase.game.action;

import org.loon.framework.javase.game.core.geom.RectBox;
import org.loon.framework.javase.game.core.graphics.component.ActorLayer;

public class JumpTo extends ActionEvent {

	private float moveY;

	private float moveX;

	private int moveJump;

	private float g;

	public JumpTo(int m, float g) {
		this.moveJump = m;
		this.g = g;
	}

	public boolean isComplete() {
		return isComplete;
	}

	public void onLoad() {
		this.moveY = moveJump;
	}

	public float getMoveX() {
		return moveX;
	}

	public void setMoveX(float moveX) {
		this.moveX = moveX;
	}

	public float getMoveY() {
		return moveY;
	}

	public void setMoveY(float moveY) {
		this.moveY = moveY;
	}

	public void update(long elapsedTime) {
		if (moveJump < 0) {
			if (this.moveY > -(moveJump)) {
				this.moveY = -moveJump;
			}
		} else {
			if (this.moveY > (moveJump)) {
				this.moveY = moveJump;
			}
		}
		original.setLocation(original.getX() + (int) this.moveX, original
				.getY()
				+ (int) this.moveY);
		if (moveJump < 0) {
			this.moveY += g;
		} else {
			this.moveY -= g;
		}
		ActorLayer layer = original.getLLayer();
		if (moveJump > 0) {
			if (original.getY() + original.getHeight() > layer.getHeight()
					+ original.getHeight()) {
				isComplete = true;
			}
		} else if (original.getY() + original.getHeight() < 0) {
			isComplete = true;
		}
		boolean isLimit = layer.isBounded();
		if (isLimit) {
			RectBox rect = original.getRectBox();
			int limitWidth = layer.getWidth() - rect.getWidth();
			int limitHeight = rect.getHeight();
			if (original.getX() > limitWidth) {
				original.setLocation(limitWidth, original.getY());
				isComplete = true;
			} else if (original.getX() < 0) {
				original.setLocation(0, original.getY());
				isComplete = true;
			}
			if (original.getY() < 0) {
				original.setLocation(original.getX(), limitHeight);
				isComplete = true;
			} else if (original.getY() > layer.getHeight() - limitHeight) {
				original.setLocation(original.getX(), layer.getHeight()
						- limitHeight);
				isComplete = true;
			}
		}
	}

}


text:
'use strict';
const winston = require('winston');

module.exports = {
  up: (queryInterface, Sequelize) => {
    return Promise.all([
      queryInterface.removeColumn('vod_stream', 'stream_mode'),
      queryInterface.sequelize.query("Update vod_stream SET stream_type='regular' WHERE stream_type = ''")
    ])
  },

  down: (queryInterface, Sequelize) => {
    return Promise.all([
      queryInterface.addColumn('vod_stream', 'stream_mode', {
        type: Sequelize.STRING(20),
        allowNull: false,
        unique: 'vodstream_mode'
      }).catch(function (err) {
        winston.error(err);
      }),
      queryInterface.addColumn('vod_stream', 'stream_type', {
        type: Sequelize.STRING(20),
        allowNull: false,
        defaultValue: 'regular'
      }).catch(function (err) {
        winston.error(err);
      })
    ])
  }
};


text:
use {Response, NickelError, MiddlewareResult, Halt, Continue};
use hyper::status::{StatusCode, StatusClass};
use hyper::header;
use serialize::json;
use mimes::MediaType;
use std::io::Write;

/// This trait provides convenience for translating a number
/// of common return types into a `MiddlewareResult` while
/// also modifying the `Response` as required.
///
/// Please see the examples for some uses.
pub trait Responder<D> {
    fn respond<'a>(self, Response<'a, D>) -> MiddlewareResult<'a, D>;
}

impl<D> Responder<D> for () {
    fn respond<'a>(self, res: Response<'a, D>) -> MiddlewareResult<'a, D> {
        Ok(Continue(res))
    }
}

impl<D> Responder<D> for json::Json {
    fn respond<'a>(self, mut res: Response<'a, D>) -> MiddlewareResult<'a, D> {
        maybe_set_type(&mut res, MediaType::Json);
        res.send(json::encode(&self)
                      .map_err(|e| format!("Failed to parse JSON: {}", e)))
    }
}

impl<T, E, D> Responder<D> for Result<T, E>
        where T: Responder<D>,
              for<'e> NickelError<'e, D>: From<(Response<'e, D>, E)> {
    fn respond<'a>(self, res: Response<'a, D>) -> MiddlewareResult<'a, D> {
        let data = try_with!(res, self);
        res.send(data)
    }
}

macro_rules! dual_impl {
    ($view:ty, $alloc:ty, |$s:ident, $res:ident| $b:block) => (
        impl<'a, D> Responder<D> for $view {
            #[allow(unused_mut)]
            #[inline]
            fn respond<'c>($s, mut $res: Response<'c, D>) -> MiddlewareResult<'c, D> $b
        }

        impl<'a, D> Responder<D> for $alloc {
            #[allow(unused_mut)]
            #[inline]
            fn respond<'c>($s, mut $res: Response<'c, D>) -> MiddlewareResult<'c, D> $b
        }
    )
}

dual_impl!(&'a [u8],
           Vec<u8>,
            |self, res| {
                maybe_set_type(&mut res, MediaType::Bin);

                let mut stream = try!(res.start());
                match stream.write_all(&self[..]) {
                    Ok(()) => Ok(Halt(stream)),
                    Err(e) => stream.bail(format!("Failed to send: {}", e))
                }
            });

dual_impl!(&'a str,
           String,
            |self, res| {
                maybe_set_type(&mut res, MediaType::Html);
                res.send(self.as_bytes())
            });

dual_impl!((StatusCode, &'static str),
           (StatusCode, String),
            |self, res| {
                let (status, message) = self;

                match status.class() {
                    StatusClass::ClientError | StatusClass::ServerError => {
                        res.error(status, message)
                    },
                    _ => {
                        res.set(status);
                        res.send(message)
                    }
                }
            });

impl<'a, D> Responder<D> for StatusCode {
    #[inline]
    fn respond<'c>(self, res: Response<'c, D>) -> MiddlewareResult<'c, D> {
        res.send((self, ""))
    }
}

dual_impl!(&'a [&'a str],
           &'a [String],
            |self, res| {
                maybe_set_type(&mut res, MediaType::Html);

                let mut stream = try!(res.start());
                for ref s in self.iter() {
                    if let Err(e) = stream.write_all(s.as_bytes()) {
                        return stream.bail(format!("Failed to write to stream: {}", e))
                    }
                }
                Ok(Halt(stream))
            });

dual_impl!((u16, &'static str),
           (u16, String),
           |self, res| {
                let (status, message) = self;
                res.send((StatusCode::from_u16(status), message))
            });

// FIXME: Hyper uses traits for headers, so this needs to be a Vec of
// trait objects. But, a trait object is unable to have Foo + Bar as a bound.
//
// A better/faster solution would be to impl this for tuples,
// where each tuple element implements the Header trait, which would give a
// static dispatch.
// dual_impl!((StatusCode, &'a str, Vec<Box<ResponseHeader>>),
//            (StatusCode, String, Vec<Box<ResponseHeader>>)
//            |self, res| {
//                 let (status, data, headers) = self;

//                 res.origin.status = status;
//                 for header in headers.into_iter() {
//                     res.origin.headers_mut().set(header);
//                 }
//                 maybe_set_type(&mut res, MediaType::Html);
//                 res.send(data);
//                 Ok(Halt)
//             })

fn maybe_set_type<D>(res: &mut Response<D>, mime: MediaType) {
    res.set_header_fallback(|| header::ContentType(mime.into()));
}


text: Información sobre hacer que escuelas completas participen en la Hora de Programación irá aquí.


text:
<?php
/**
 * 家族扩展信息
 * the last known user to change this file in the repository  <$LastChangedBy: hexin $>
 * @author He xin <hexin@pipi.cn>
 * @version $Id: 2013-8-6 下午3:28:20 hexin $
 * @package
 */
class FamilyExtendModel extends PipiActiveRecord {
	/**
	 *
	 * @param string $className
	 * @return FamilyExtendModel
	 */
	public static function model($className = __CLASS__){
		return parent::model($className);
	}

	public function tableName(){
		return '{{family_extend}}';
	}

	public function getDbConnection(){
		return Yii::app()->db_family;
	}

	public function rules(){
		return array(
			array('announcement', 'length', 'min' => 2, 'max' => 250, 'message'=>'250字以内'),
		);
	}

	public function attributeLabels(){
		return array(
			'announcement'	=> '公告内容'
		);
	}

	/**
	 * 删除家族扩展信息
	 * @param int $family_id
	 * @return boolean
	 */
	public function deleteExtend($family_id){
		$criteria = $this->getCommandBuilder()->createCriteria();
		$criteria->condition = 'family_id='.$family_id;
		if($this->getCommandBuilder()->createDeleteCommand($this->tableName(), $criteria)->execute())
			return true;
		else return false;
	}
}