text:
import asyncio
import hashlib
import datetime
from unittest import mock
from datetime import timezone as tz

import synapse.exc as s_exc
import synapse.common as s_common
import synapse.tests.utils as s_t_utils

import synapse.lib.hive as s_hive
import synapse.lib.lmdbslab as s_lmdbslab

import synapse.lib.agenda as s_agenda
from synapse.lib.agenda import TimeUnit as s_tu

class AgendaTest(s_t_utils.SynTest):
    def test_apptreq(self):

        # Invalid combinations
        self.raises(s_exc.BadTime, s_agenda.ApptRec, {s_tu.DAYOFWEEK: 3, s_tu.DAYOFMONTH: 4})
        self.raises(s_exc.BadTime, s_agenda.ApptRec, {s_tu.HOUR: 1}, s_tu.MINUTE)
        self.raises(s_exc.BadTime, s_agenda.ApptRec, {}, None)
        self.raises(s_exc.BadTime, s_agenda.ApptRec, {}, s_tu.DAYOFMONTH)
        self.raises(s_exc.BadTime, s_agenda.ApptRec, {s_tu.HOUR: -99}, s_tu.MINUTE)
        self.raises(s_exc.BadTime, s_agenda.ApptRec, {}, s_tu.YEAR, -1)
        self.raises(s_exc.BadTime, s_agenda.ApptRec, {'day': 4}, s_tu.YEAR, -1)

        ###############################

        # incunit = None, i.e. one-shot

        self.raises(s_exc.BadTime, s_agenda.ApptRec, {s_tu.DAY: 15})

        # No inc, year req: One shot in 2017.  It is 2018
        now = datetime.datetime(year=2018, month=12, day=3, hour=2, minute=2, tzinfo=tz.utc).timestamp()  # Monday
        ar = s_agenda.ApptRec({s_tu.YEAR: 2017})
        newts = ar.nexttime(now)
        self.eq(newts, 0.0)

        # one shot in 2019.
        ar = s_agenda.ApptRec({s_tu.YEAR: 2019})
        newts = ar.nexttime(now)
        self.eq(newts, datetime.datetime(year=2019, month=12, day=3, hour=2, minute=2, tzinfo=tz.utc).timestamp())

        # It is leap day 2020, one shot next year
        now = datetime.datetime(year=2020, month=2, day=29, hour=2, minute=2, tzinfo=tz.utc).timestamp()  # Monday
        ar = s_agenda.ApptRec({s_tu.YEAR: 2021})
        newts = ar.nexttime(now)
        self.eq(newts, datetime.datetime(year=2021, month=2, day=28, hour=2, minute=2, tzinfo=tz.utc).timestamp())

        # It is leap day 2020, one shot next year, Halloween
        now = datetime.datetime(year=2020, month=2, day=29, hour=2, minute=2, tzinfo=tz.utc).timestamp()  # Monday
        ar = s_agenda.ApptRec({s_tu.DAYOFMONTH: 31, s_tu.YEAR: 2021, s_tu.MONTH: 10})
        newts = ar.nexttime(now)
        self.eq(newts, datetime.datetime(year=2021, month=10, day=31, hour=2, minute=2, tzinfo=tz.utc).timestamp())

        # No inc, month req: One shot in July
        ar = s_agenda.ApptRec({s_tu.MONTH: 7})
        now = datetime.datetime(year=2018, month=12, day=3, hour=2, minute=2, tzinfo=tz.utc).timestamp()  # Monday
        newts = ar.nexttime(now)
        self.eq(newts, datetime.datetime(year=2019, month=7, day=3, hour=2, minute=2, tzinfo=tz.utc).timestamp())

        # No inc, day of month req: one shot on the 3rd of the month at 1:01am
        ar = s_agenda.ApptRec({s_tu.DAYOFMONTH: 3, s_tu.HOUR: 1, s_tu.MINUTE: 1})
        now = datetime.datetime(year=2018, month=12, day=4, hour=2, minute=2, tzinfo=tz.utc).timestamp()  # Monday
        newts = ar.nexttime(now)
        self.eq(newts, datetime.datetime(year=2019, month=1, day=3, hour=1, minute=1, tzinfo=tz.utc).timestamp())

        # No inc, day of week req: One shot next Monday at 1:01 am
        ar = s_agenda.ApptRec({s_tu.DAYOFWEEK: 0, s_tu.HOUR: 1, s_tu.MINUTE: 1})
        now = datetime.datetime(year=2018, month=12, day=31, hour=2, minute=2, tzinfo=tz.utc).timestamp()  # Monday
        newts = ar.nexttime(now)
        self.eq(newts, datetime.datetime(year=2019, month=1, day=7, hour=1, minute=1, tzinfo=tz.utc).timestamp())

        # No inc, hour req:  One shot at 4pm.  It is 5pm, last day of the year.
        ar = s_agenda.ApptRec({s_tu.HOUR: 16})
        now = datetime.datetime(year=2018, month=12, day=31, hour=17, minute=2, tzinfo=tz.utc).timestamp()  # Monday
        newts = ar.nexttime(now)
        self.eq(newts, datetime.datetime(year=2019, month=1, day=1, hour=16, minute=2, tzinfo=tz.utc).timestamp())

        ################

        # incunit = Year

        # Year inc, day of month req:  every year on the 15th of the month
        ar = s_agenda.ApptRec({s_tu.DAYOFMONTH: 15}, s_tu.YEAR, 1)

        # before the target matches the target
        now = datetime.datetime(year=2018, month=3, day=1, tzinfo=tz.utc).timestamp()
        newts = ar.nexttime(now)
        self.eq(newts, datetime.datetime(year=2018, month=3, day=15, tzinfo=tz.utc).timestamp())

        # at the appointment advances
        now = datetime.datetime(year=2018, month=3, day=15, tzinfo=tz.utc).timestamp()
        newts = ar.nexttime(now)
        self.eq(newts, datetime.datetime(year=2019, month=3, day=15, tzinfo=tz.utc).timestamp())

        # past the appointment advances
        now = datetime.datetime(year=2018, month=3, day=15, tzinfo=tz.utc).timestamp()
        newts = ar.nexttime(now)
        self.eq(newts, datetime.datetime(year=2019, month=3, day=15, tzinfo=tz.utc).timestamp())

        # Year inc, month req:  every other year in February
        ar = s_agenda.ApptRec({s_tu.MONTH: 2}, s_tu.YEAR, 2)
        now = datetime.datetime(year=2018, month=12, day=31, hour=17, minute=2, tzinfo=tz.utc).timestamp()  # Monday
        newts = ar.nexttime(now)
        self.eq(newts, datetime.datetime(year=2020, month=2, day=28, hour=17, minute=2, tzinfo=tz.utc).timestamp())

        # Year inc, day of week req:  every other year on a Friday:  not supported
        self.raises(s_exc.BadTime, s_agenda.ApptRec, {s_tu.DAYOFWEEK: 4}, s_tu.YEAR, 2)

        # Year inc, hour req
        ar = s_agenda.ApptRec({s_tu.HOUR: 10}, s_tu.YEAR, 2)
        now = datetime.datetime(year=2018, month=12, day=31, hour=17, minute=2, tzinfo=tz.utc).timestamp()  # Monday
        newts = ar.nexttime(now)
        self.eq(newts, datetime.datetime(year=2020, month=12, day=31, hour=10, minute=2, tzinfo=tz.utc).timestamp())

        #################

        # incunit = Month

        # Month inc, minute req: When the minute hand hits 30 every 14 months
        ar = s_agenda.ApptRec({s_tu.MINUTE: 30}, s_tu.MONTH, 14)
        now = datetime.datetime(year=2017, month=12, day=30, hour=0, minute=30, tzinfo=tz.utc).timestamp()
        newts = ar.nexttime(now)
        self.eq(newts, datetime.datetime(year=2019, month=2, day=28, hour=0, minute=30, tzinfo=tz.utc).timestamp())

        # Month inc, day of month req:  every other month on the 4th
        ar = s_agenda.ApptRec({s_tu.DAYOFMONTH: 4}, s_tu.MONTH, 2)
        now = datetime.datetime(year=2017, month=12, day=30, hour=0, minute=30, tzinfo=tz.utc).timestamp()
        newts = ar.nexttime(now)
        self.eq(newts, datetime.datetime(2018, 2, 4, 0, 30, tzinfo=tz.utc).timestamp())

        # Month inc, day of week fail
        self.raises(s_exc.BadTime, s_agenda.ApptRec, {s_tu.DAYOFWEEK: 4}, s_tu.MONTH, 2)

        ###############

        # incunit = Day

        # Day inc, minute req:  Every day some time when the minute hand hits 30
        ar = s_agenda.ApptRec({s_tu.MINUTE: 30}, s_tu.DAY, 1)
        now = datetime.datetime(year=2019, month=2, day=1, hour=0, minute=2, tzinfo=tz.utc).timestamp()
        newts = ar.nexttime(now)
        self.eq(newts, datetime.datetime(year=2019, month=2, day=1, hour=0, minute=30, tzinfo=tz.utc).timestamp())

        ###############

        # incunit = DayOfWeek

        # Day of week inc, hour req: Every Wednesday at 7pm
        ar = s_agenda.ApptRec({s_tu.HOUR: 7}, s_tu.DAYOFWEEK, 2)
        now = datetime.datetime(year=2018, month=12, day=3, hour=2, minute=2, tzinfo=tz.utc).timestamp()  # Monday
        newts = ar.nexttime(now)
        self.eq(newts, datetime.datetime(year=2018, month=12, day=5, hour=7, minute=2, tzinfo=tz.utc).timestamp())

    async def test_agenda(self):
        MONO_DELT = 1543827303.0
        unixtime = datetime.datetime(year=2018, month=12, day=5, hour=7, minute=0, tzinfo=tz.utc).timestamp()

        def timetime():
            return unixtime

        def looptime():
            return unixtime - MONO_DELT

        loop = asyncio.get_running_loop()
        with mock.patch.object(loop, 'time', looptime), mock.patch('time.time', timetime), self.getTestDir() as dirn:

            async with self.getTestCore() as core:

                visi = await core.auth.addUser('visi')
                await visi.setAdmin(True)

                agenda = core.agenda
                await agenda.start()  # make sure it doesn't blow up

                self.eq([], agenda.list())

                # Missing reqs
                cdef = {'creator': core.auth.rootuser.iden, 'iden': 'fakeiden', 'storm': 'foo'}
                await self.asyncraises(ValueError, agenda.add(cdef))

                # Missing creator
                cdef = {'iden': 'fakeiden', 'storm': 'foo',
                        'reqs': {s_agenda.TimeUnit.MINUTE: 1}}
                await self.asyncraises(ValueError, agenda.add(cdef))

                # Missing storm
                cdef = {'creator': core.auth.rootuser.iden, 'iden': 'fakeiden',
                        'reqs': {s_agenda.TimeUnit.MINUTE: 1}}
                await self.asyncraises(ValueError, agenda.add(cdef))
                await self.asyncraises(s_exc.NoSuchIden, agenda.get('newp'))

                # Missing incvals
                cdef = {'creator': core.auth.rootuser.iden, 'iden': 'DOIT', 'storm': '[test:str=doit]',
                        'reqs': {s_agenda.TimeUnit.NOW: True},
                        'incunit': s_agenda.TimeUnit.MONTH}
                await self.asyncraises(ValueError, agenda.add(cdef))

                # Cannot schedule a recurring job with 'now'
                cdef = {'creator': core.auth.rootuser.iden, 'iden': 'DOIT', 'storm': '[test:str=doit]',
                        'reqs': {s_agenda.TimeUnit.NOW: True},
                        'incunit': s_agenda.TimeUnit.MONTH,
                        'incvals': 1}
                await self.asyncraises(ValueError, agenda.add(cdef))
                await self.asyncraises(s_exc.NoSuchIden, agenda.get('DOIT'))

                # Schedule a one-shot to run immediately
                doit = s_common.guid()
                cdef = {'creator': core.auth.rootuser.iden, 'iden': doit,
                        'storm': '$lib.queue.gen(visi).put(woot)',
                        'reqs': {s_agenda.TimeUnit.NOW: True}}
                await agenda.add(cdef)

                # Can't have two with the same iden
                await self.asyncraises(s_exc.DupIden, agenda.add(cdef))

                self.eq((0, 'woot'), await asyncio.wait_for(core.callStorm('return($lib.queue.gen(visi).pop(wait=$lib.true))'), timeout=5))

                appts = agenda.list()
                self.len(1, appts)
                self.eq(appts[0][1].startcount, 1)
                self.eq(appts[0][1].nexttime, None)
                await agenda.delete(doit)

                # Schedule a one-shot 1 minute from now
                cdef = {'creator': core.auth.rootuser.iden, 'iden': s_common.guid(), 'storm': '$lib.queue.gen(visi).put(woot)',
                        'reqs': {s_agenda.TimeUnit.MINUTE: 1}}
                await agenda.add(cdef)
                unixtime += 61
                self.eq((1, 'woot'), await asyncio.wait_for(core.callStorm('return($lib.queue.gen(visi).pop(wait=$lib.true))'), timeout=5))

                appts = agenda.list()
                self.len(1, appts)
                self.eq(appts[0][1].startcount, 1)
                self.eq(appts[0][1].nexttime, None)

                # Schedule a query to run every Wednesday and Friday at 10:15am
                cdef = {'creator': core.auth.rootuser.iden, 'iden': s_common.guid(), 'storm': '$lib.queue.gen(visi).put(bar)',
                        'reqs': {s_tu.HOUR: 10, s_tu.MINUTE: 15},
                        'incunit': s_agenda.TimeUnit.DAYOFWEEK,
                        'incvals': (2, 4)}
                adef = await agenda.add(cdef)
                guid = adef.get('iden')

                # every 6th of the month at 7am and 8am (the 6th is a Thursday)
                cdef = {'creator': core.auth.rootuser.iden, 'iden': s_common.guid(), 'storm': '$lib.queue.gen(visi).put(baz)',
                        'reqs': {s_tu.HOUR: (7, 8), s_tu.MINUTE: 0, s_tu.DAYOFMONTH: 6},
                        'incunit': s_agenda.TimeUnit.MONTH,
                        'incvals': 1}
                adef = await agenda.add(cdef)
                guid2 = adef.get('iden')

                xmas = {s_tu.DAYOFMONTH: 25, s_tu.MONTH: 12, s_tu.YEAR: 2018}
                lasthanu = {s_tu.DAYOFMONTH: 10, s_tu.MONTH: 12, s_tu.YEAR: 2018}

                # And one-shots for Christmas and last day of Hanukkah of 2018
                cdef = {'creator': core.auth.rootuser.iden, 'iden': s_common.guid(), 'storm': '$lib.queue.gen(visi).put(happyholidays)',
                        'reqs': (xmas, lasthanu)}
                await agenda.add(cdef)

                unixtime += 1
                await asyncio.sleep(0)
                self.none(await asyncio.wait_for(core.callStorm('return($lib.queue.gen(visi).pop())'), timeout=5))

                # Advance to the first event on Wednesday the 5th
                unixtime = datetime.datetime(year=2018, month=12, day=5, hour=10, minute=16, tzinfo=tz.utc).timestamp()
                self.eq((2, 'bar'), await asyncio.wait_for(core.callStorm('return($lib.queue.gen(visi).pop(wait=$lib.true))'), timeout=5))

                # Then two on the 6th
                unixtime = datetime.datetime(year=2018, month=12, day=6, hour=7, minute=15, tzinfo=tz.utc).timestamp()
                self.eq((3, 'baz'), await asyncio.wait_for(core.callStorm('return($lib.queue.gen(visi).pop(wait=$lib.true))'), timeout=5))

                unixtime = datetime.datetime(year=2018, month=12, day=6, hour=8, minute=15, tzinfo=tz.utc).timestamp()
                self.eq((4, 'baz'), await asyncio.wait_for(core.callStorm('return($lib.queue.gen(visi).pop(wait=$lib.true))'), timeout=5))

                # Then back to the 10:15 on Friday
                unixtime = datetime.datetime(year=2018, month=12, day=7, hour=10, minute=16, tzinfo=tz.utc).timestamp()
                self.eq((5, 'bar'), await asyncio.wait_for(core.callStorm('return($lib.queue.gen(visi).pop(wait=$lib.true))'), timeout=5))

                # Then Dec 10
                unixtime = datetime.datetime(year=2018, month=12, day=10, hour=10, minute=16, tzinfo=tz.utc).timestamp()
                self.eq((6, 'happyholidays'), await asyncio.wait_for(core.callStorm('return($lib.queue.gen(visi).pop(wait=$lib.true))'), timeout=5))

                # Then the Wednesday again
                unixtime = datetime.datetime(year=2018, month=12, day=12, hour=10, minute=16, tzinfo=tz.utc).timestamp()
                self.eq((7, 'bar'), await asyncio.wait_for(core.callStorm('return($lib.queue.gen(visi).pop(wait=$lib.true))'), timeout=5))

                # Cancel the Wednesday/Friday appt
                await agenda.delete(guid)
                await self.asyncraises(s_exc.NoSuchIden, agenda.delete(b'1234'))

                # Then Dec 25
                unixtime = datetime.datetime(year=2018, month=12, day=25, hour=10, minute=16, tzinfo=tz.utc).timestamp()
                self.eq((8, 'happyholidays'), await asyncio.wait_for(core.callStorm('return($lib.queue.gen(visi).pop(wait=$lib.true))'), timeout=5))

                # Then Jan 6
                unixtime = datetime.datetime(year=2019, month=1, day=6, hour=10, minute=16, tzinfo=tz.utc).timestamp()
                self.eq((9, 'baz'), await asyncio.wait_for(core.callStorm('return($lib.queue.gen(visi).pop(wait=$lib.true))'), timeout=5))

                # Modify the last appointment
                await self.asyncraises(ValueError, agenda.mod(guid2, '', ))
                await agenda.mod(guid2, '#baz')
                self.eq(agenda.appts[guid2].query, '#baz')

                # Delete the other recurring appointment
                await agenda.delete(guid2)

                # Then nothing left scheduled
                self.len(0, agenda.apptheap)

                # Test that isrunning updated, cancelling works
                cdef = {'creator': core.auth.rootuser.iden, 'iden': s_common.guid(),
                        'storm': '$lib.queue.gen(visi).put(sleep) [ inet:ipv4=1 ] | sleep 120',
                        'reqs': {}, 'incunit': s_agenda.TimeUnit.MINUTE, 'incvals': 1}
                adef = await agenda.add(cdef)
                guid = adef.get('iden')

                unixtime += 60
                self.eq((10, 'sleep'), await asyncio.wait_for(core.callStorm('return($lib.queue.gen(visi).pop(wait=$lib.true))'), timeout=5))

                appt = await agenda.get(guid)
                self.eq(appt.isrunning, True)
                await appt.task.kill()

                appt = await agenda.get(guid)
                self.eq(appt.isrunning, False)
                self.eq(appt.lastresult, 'cancelled')
                await agenda.delete(guid)

                # Test bad queries record exception
                cdef = {'creator': core.auth.rootuser.iden, 'iden': s_common.guid(),
                        'storm': '$lib.queue.gen(visi).put(boom) $lib.raise(OmgWtfBbq, boom)',
                        'reqs': {}, 'incunit': s_agenda.TimeUnit.MINUTE,
                        'incvals': 1}
                adef = await agenda.add(cdef)
                guid = adef.get('iden')

                # bypass the API because it would actually syntax check
                unixtime += 60
                self.eq((11, 'boom'), await asyncio.wait_for(core.callStorm('return($lib.queue.gen(visi).pop(wait=$lib.true))'), timeout=5))

                appt = await agenda.get(guid)
                self.eq(appt.isrunning, False)
                self.eq(appt.lastresult, "raised exception StormRaise: errname='OmgWtfBbq' mesg='boom'")

                # Test setting the global enable/disable flag
                # reset
                await agenda.delete(guid)
                self.len(0, agenda.apptheap)

                agenda._schedtask.cancel()
                agenda._schedtask = agenda.schedCoro(agenda._scheduleLoop())

                # schedule a query to run every Wednesday and Friday at 10:15am
                cdef = {'creator': visi.iden, 'iden': s_common.guid(), 'storm': '$lib.queue.gen(visi).put(bar)',
                        'reqs': {s_tu.HOUR: 10, s_tu.MINUTE: 15},
                        'incunit': s_agenda.TimeUnit.DAYOFWEEK,
                        'incvals': (2, 4)}
                adef = await agenda.add(cdef)
                guid = adef.get('iden')

                self.len(1, agenda.apptheap)

                # disable crons and advance time
                agenda.enabled = False

                unixtime = datetime.datetime(year=2019, month=2, day=6, hour=10, minute=16, tzinfo=tz.utc).timestamp()
                nexttime = datetime.datetime(year=2019, month=2, day=8, hour=10, minute=15, tzinfo=tz.utc).timestamp()

                await asyncio.sleep(0)

                appt = await agenda.get(guid)
                self.eq(nexttime, appt.nexttime)
                self.true(appt.enabled)
                self.eq(0, appt.startcount)

                # enable crons and advance time
                agenda.enabled = True

                unixtime = datetime.datetime(year=2019, month=2, day=13, hour=10, minute=16, tzinfo=tz.utc).timestamp()
                self.eq((12, 'bar'), await asyncio.wait_for(core.callStorm('return($lib.queue.gen(visi).pop(wait=$lib.true))'), timeout=5))

                self.eq(1, appt.startcount)

                cdef = {'creator': visi.iden, 'iden': s_common.guid(), 'storm': '[test:str=foo2]',
                        'reqs': {s_agenda.TimeUnit.MINUTE: 1}}

                await agenda.add(cdef)

                # Lock user and advance time
                await visi.setLocked(True)

                with self.getLoggerStream('synapse.lib.agenda', 'locked') as stream:
                    unixtime = datetime.datetime(year=2019, month=2, day=16, hour=10, minute=16, tzinfo=tz.utc).timestamp()

                    # pump the ioloop via sleep(0) until the log message appears
                    while not stream.wait(0.1):
                        await asyncio.sleep(0)

                    self.eq(2, appt.startcount)

    async def test_agenda_persistence(self):
        ''' Test we can make/change/delete appointments and they are persisted to storage '''
        with self.getTestDir() as fdir:

            core = mock.Mock()

            def raiseOnBadStorm(q):
                ''' Just enough storm parsing for this test '''
                # TODO: Async this and use AsyncMock when Python 3.8+ only
                f = asyncio.Future()
                if (q[0] == '[') != (q[-1] == ']'):
                    f.set_exception(s_exc.BadSyntax(mesg='mismatched braces'))
                else:
                    f.set_result('all good')
                return f

            core.getStormQuery = raiseOnBadStorm

            async with await s_lmdbslab.Slab.anit(fdir, map_size=100000) as slab:
                db = slab.initdb('hive')
                hive = await s_hive.SlabHive.anit(slab, db=db)
                core.hive = hive

                async with await s_agenda.Agenda.anit(core) as agenda:
                    await agenda.start()
                    # Schedule a query to run every Wednesday and Friday at 10:15am
                    cdef = {'creator': 'visi', 'iden': 'IDEN1', 'storm': '[test:str=bar]',
                            'reqs': {s_tu.HOUR: 10, s_tu.MINUTE: 15},
                            'incunit': s_agenda.TimeUnit.DAYOFWEEK,
                            'incvals': (2, 4)}
                    adef = await agenda.add(cdef)
                    guid1 = adef.get('iden')

                    # every 6th of the month at 7am and 8am (the 6th is a Thursday)
                    cdef = {'creator': 'visi', 'iden': 'IDEN2', 'storm': '[test:str=baz]',
                            'reqs': {s_tu.HOUR: (7, 8), s_tu.MINUTE: 0, s_tu.DAYOFMONTH: 6},
                            'incunit': s_agenda.TimeUnit.MONTH,
                            'incvals': 1}
                    adef = await agenda.add(cdef)

                    guid2 = adef.get('iden')
                    appt = agenda.appts[guid2]
                    appt.lasterrs.append('error happened')
                    await agenda._storeAppt(appt)

                    # Add an appt with an invalid query
                    cdef = {'creator': 'visi', 'iden': 'BAD1', 'storm': '[test:str=',
                            'reqs': {s_tu.HOUR: (7, 8)},
                            'incunit': s_agenda.TimeUnit.MONTH,
                            'incvals': 1}
                    adef = await agenda.add(cdef)
                    badguid1 = adef.get('iden')

                    # Add an appt with a bad version in storage
                    cdef = {'creator': 'visi', 'iden': 'BAD2', 'storm': '[test:str=foo]',
                            'reqs': {s_tu.HOUR: (7, 8)},
                            'incunit': s_agenda.TimeUnit.MONTH,
                            'incvals': 1}
                    adef = await agenda.add(cdef)
                    badguid2 = adef.get('iden')

                    adef['ver'] = 1337
                    full = agenda._hivenode.full + (badguid2,)
                    await agenda.core.hive.set(full, adef)

                    xmas = {s_tu.DAYOFMONTH: 25, s_tu.MONTH: 12, s_tu.YEAR: 2099}
                    lasthanu = {s_tu.DAYOFMONTH: 10, s_tu.MONTH: 12, s_tu.YEAR: 2099}

                    await agenda.delete(guid1)

                    # And one-shots for Christmas and last day of Hanukkah of 2018
                    cdef = {'creator': 'visi', 'iden': 'IDEN3', 'storm': '#happyholidays',
                            'reqs': (xmas, lasthanu)}

                    adef = await agenda.add(cdef)
                    guid3 = adef.get('iden')

                    await agenda.mod(guid3, '#bahhumbug')

                async with await s_agenda.Agenda.anit(core) as agenda:
                    await agenda.start()
                    agenda.enabled = True

                    appts = agenda.list()
                    self.len(3, appts)

                    last_appt = [appt for (iden, appt) in appts if iden == guid3][0]
                    self.eq(last_appt.query, '#bahhumbug')

                    bad_appt = [appt for (iden, appt) in appts if iden == badguid1][0]
                    self.false(bad_appt.enabled)

                    self.len(0, [appt for (iden, appt) in appts if iden == badguid2])

    async def test_cron_perms(self):

        async with self.getTestCore() as core:

            visi = await core.auth.addUser('visi')
            newb = await core.auth.addUser('newb')
            async with core.getLocalProxy(user='visi') as proxy:

                cdef = {'storm': 'inet:ipv4', 'reqs': {'hour': 2}}
                with self.raises(s_exc.AuthDeny):
                    await proxy.addCronJob(cdef)

                await visi.addRule((True, ('cron', 'add')))
                cron0 = await proxy.addCronJob(cdef)
                cron0_iden = cron0.get('iden')

                cdef = {'storm': 'inet:ipv6', 'reqs': {'hour': 2}}
                cron1 = await proxy.addCronJob(cdef)
                cron1_iden = cron1.get('iden')

                await proxy.delCronJob(cron0_iden)

                cdef = {'storm': '[test:str=foo]', 'reqs': {'now': True},
                        'incunit': 'month',
                        'incvals': 1}
                await self.asyncraises(s_exc.BadConfValu, proxy.addCronJob(cdef))

            async with core.getLocalProxy(user='newb') as proxy:

                with self.raises(s_exc.AuthDeny):
                    await proxy.delCronJob(cron1_iden)

                self.eq(await proxy.listCronJobs(), ())
                await newb.addRule((True, ('cron', 'get')))
                self.len(1, await proxy.listCronJobs())

                with self.raises(s_exc.AuthDeny):
                    await proxy.disableCronJob(cron1_iden)

                await newb.addRule((True, ('cron', 'set')))
                self.none(await proxy.disableCronJob(cron1_iden))

                await newb.addRule((True, ('cron', 'del')))
                await proxy.delCronJob(cron1_iden)

    async def test_agenda_stop(self):

        async with self.getTestCore() as core:
            await core.callStorm('$lib.queue.add(foo)')
            await core.callStorm('cron.add --minute +1 { $lib.queue.get(foo).put((99)) $lib.time.sleep(10) }')
            appts = core.agenda.list()
            await core.agenda._execute(appts[0][1])
            self.eq((0, 99), await core.callStorm('return($lib.queue.get(foo).get())'))

            appts[0][1].creator = 'fakeuser'
            await core.agenda._execute(appts[0][1])
            self.eq(appts[0][1].lastresult, 'Failed due to unknown user')

            await core.agenda.stop()
            self.false(core.agenda.enabled)

    async def test_agenda_custom_view(self):

        async with self.getTestCoreAndProxy() as (core, prox):
            # no existing view
            await core.callStorm('$lib.queue.add(testq)')
            defview = core.getView()
            fakeiden = hashlib.md5(defview.iden.encode('utf-8')).hexdigest()
            opts = {'vars': {'fakeiden': fakeiden}}
            with self.raises(s_exc.NoSuchView):
                await prox.callStorm('cron.add --view $fakeiden --minute +2 { $lib.queue.get(testq).put((43)) }', opts=opts)

            fail = await core.auth.addUser('fail')

            # can't move a thing that doesn't exist
            with self.raises(s_exc.StormRuntimeError):
                await core.callStorm('cron.move $fakeiden $fakeiden', opts=opts)

            with self.raises(s_exc.NoSuchIden):
                await core.moveCronJob(fail.iden, 'NoSuchCronJob', defview.iden)

            with self.raises(s_exc.NoSuchIden):
                await core.agenda.move('StillDoesNotExist', defview.iden)

            # make a new view
            ldef = await core.addLayer()
            newlayr = core.getLayer(ldef.get('iden'))
            newview = await core.callStorm(f'return($lib.view.add(({newlayr.iden},)).iden)')

            # no perms to write to that view
            asfail = {'user': fail.iden, 'vars': {'newview': newview}}
            with self.raises(s_exc.AuthDeny):
                await prox.callStorm('cron.add --view $newview --minute +2 { $lib.queue.get(testq).put(lolnope) }', opts=asfail)

            # and just to be sure
            msgs = await core.stormlist('cron.list')
            self.stormIsInPrint('No cron jobs found', msgs)

            # no --view means it goes in the default view for the user, which fail doesn't have rights to
            with self.raises(s_exc.AuthDeny):
                await core.callStorm('cron.add --minute +1 { $lib.queue.get(testq).put((44)) }', opts=asfail)

            # let's give fail permissions to do some things, but not in our super special view (fail is missing
            # the view read perm for the special view)
            await fail.addRule((True, ('cron', 'add')))

            # But we should still fail on this:
            with self.raises(s_exc.AuthDeny):
                await core.callStorm('cron.add --view $newview --minute +2 { $lib.queue.get(testq).put(lolnope)}', opts=asfail)

            # and again, just to be sure
            msgs = await core.stormlist('cron.list')
            self.stormIsInPrint('No cron jobs found', msgs)

            # Now let's give him perms to do things
            await fail.addRule((True, ('view', 'read')), gateiden=newview)
            await fail.addRule((True, ('queue', 'get')), gateiden='queue:testq')
            await fail.addRule((True, ('queue', 'put')), gateiden='queue:testq')
            await fail.addRule((True, ('node', 'add')))
            await fail.addRule((True, ('cron', 'get')))

            # but should work on the default view
            opts = {'user': fail.iden, 'view': defview.iden, 'vars': {'defview': defview.iden}}
            await prox.callStorm('cron.at --view $defview --minute +1 { $lib.queue.get(testq).put((44)) }', opts=opts)

            jobs = await core.callStorm('return($lib.cron.list())')
            self.len(1, jobs)
            self.eq(defview.iden, jobs[0]['view'])

            core.agenda._addTickOff(60)
            retn = await core.callStorm('return($lib.queue.get(testq).get())', opts=asfail)
            self.eq((0, 44), retn)

            await core.callStorm('cron.del $croniden', opts={'vars': {'croniden': jobs[0]['iden']}})
            await core.callStorm('$lib.queue.get(testq).cull(0)')

            opts = {'vars': {'newview': newview}}
            await prox.callStorm('cron.add --minute +1 --view $newview { [test:guid=$lib.guid()] | $lib.queue.get(testq).put($node) }', opts=opts)

            jobs = await core.callStorm('return($lib.cron.list())')
            self.len(1, jobs)
            self.eq(newview, jobs[0]['view'])

            core.agenda._addTickOff(60)
            retn = await core.callStorm('return($lib.queue.get(testq).get())')
            await core.callStorm('$lib.queue.get(testq).cull(1)')

            # That node had better have been made in the new view
            guidnode = await core.nodes('test:guid', opts={'view': newview})
            self.len(1, guidnode)
            self.eq(('test:guid', retn[1]), guidnode[0].ndef)

            # and definitely not in the base view
            nonode = await core.nodes('test:guid', opts={'view': defview.iden})
            self.len(0, nonode)

            # no permission yet
            opts = {'user': fail.iden, 'vars': {'croniden': jobs[0]['iden'], 'viewiden': defview.iden}}
            with self.raises(s_exc.StormRuntimeError):
                await core.callStorm('cron.move $croniden $viewiden', opts=opts)

            await fail.addRule((True, ('cron', 'set')))
            # try and fail to move to a view that doesn't exist
            opts = {'user': fail.iden, 'vars': {'croniden': jobs[0]['iden'], 'viewiden': fakeiden}}
            with self.raises(s_exc.NoSuchView):
                await core.callStorm('cron.move $croniden $viewiden', opts=opts)

            croniden = jobs[0]['iden']
            # now to test that we can move from the new layer to the base layer
            opts = {'user': fail.iden, 'vars': {'croniden': croniden, 'viewiden': defview.iden}}
            await core.callStorm('cron.move $croniden $viewiden', opts=opts)

            jobs = await core.callStorm('return($lib.cron.list())')
            self.len(1, jobs)
            self.eq(defview.iden, jobs[0]['view'])

            # moving to the same view shouldn't do much
            await core.moveCronJob(fail.iden, croniden, defview.iden)

            samejobs = await core.callStorm('return($lib.cron.list())')
            self.len(1, jobs)
            self.eq(jobs, samejobs)

            core.agenda._addTickOff(60)
            retn = await core.callStorm('return($lib.queue.get(testq).get())', opts=asfail)
            await core.callStorm('$lib.queue.get(testq).cull(2)')

            node = await core.nodes('test:guid', opts={'view': defview.iden})
            self.len(1, node)
            self.eq(('test:guid', retn[1]), node[0].ndef)
            self.ne(guidnode[0].ndef, node[0].ndef)

            # reach in, monkey with the view a bit
            appt = core.agenda.appts.get(croniden)
            appt.view = "ThisViewStillDoesntExist"
            await core.agenda._execute(appt)
            self.eq(appt.lastresult, 'Failed due to unknown view')

            await core.callStorm('cron.del $croniden', opts={'vars': {'croniden': croniden}})

            opts = {'vars': {'newview': newview}}
            await prox.callStorm('cron.at --now --view $newview { [test:str=gotcha] | $lib.queue.get(testq).put($node) }', opts=opts)
            retn = await core.callStorm('return($lib.queue.get(testq).get())', opts=asfail)
            self.eq((3, 'gotcha'), retn)
            await core.callStorm('$lib.queue.get(testq).cull(3)')
            atjob = await core.callStorm('return($lib.cron.list())')
            self.len(1, atjob)
            self.eq(atjob[0]['view'], newview)

            nodes = await core.nodes('test:str', opts={'view': defview.iden})
            self.len(0, nodes)
            nodes = await core.nodes('test:str', opts={'view': newview})
            self.len(1, nodes)

            croniden = atjob[0]['iden']
            await core.callStorm('cron.del $croniden', opts={'vars': {'croniden': croniden}})

            await prox.callStorm('cron.at --now { [test:int=97] | $lib.queue.get(testq).put($node) }')
            retn = await core.callStorm('return($lib.queue.get(testq).get())', opts=asfail)
            await core.callStorm('$lib.queue.get(testq).cull(4)')
            self.eq((4, 97), retn)

            nodes = await core.nodes('test:int=97', opts={'view': defview.iden})
            self.len(1, nodes)
            nodes = await core.nodes('test:int=97', opts={'view': newview})
            self.len(0, nodes)

    async def test_agenda_custom_view(self):

        async with self.getTestCore() as core:

            derp = await core.auth.addUser('derp')

            msgs = await core.stormlist('cron.add --hourly 32 { $lib.print(woot) }')
            self.stormHasNoWarnErr(msgs)

            cdef = await core.callStorm('for $cron in $lib.cron.list() { return($cron) }')
            self.eq(cdef['creator'], core.auth.rootuser.iden)

            opts = {'vars': {'derp': derp.iden}}
            cdef = await core.callStorm('for $cron in $lib.cron.list() { return($cron.set(creator, $derp)) }', opts=opts)

            self.eq(cdef['creator'], derp.iden)

            async with core.getLocalProxy(user='derp') as proxy:
                with self.raises(s_exc.AuthDeny):
                    await proxy.editCronJob(cdef.get('iden'), 'creator', derp.iden)


text:
package com.intellij.util;

import junit.framework.TestCase;

/**
 * @author Sergey.Malenkov
 */
public class VectorTest extends TestCase {
  public void testCreate() {
    Vector vector = Vector.create(0, 1, 2, 3, 4);
    int size = vector.getSize();
    assertEquals(5, size);
    for (int i = 0; i < size; i++) {
      assertEquals((double)i, vector.get(i));
    }
  }

  public void testCreateEmpty() {
    try {
      fail("Created " + Vector.create());
    }
    catch (Exception ignored) {
    }
  }

  public void testCreateNull() {
    try {
      fail("Created " + Vector.create((double[])null));
    }
    catch (Exception ignored) {
    }
  }

  public void testPlus() {
    // see http://ru.onlinemschool.com/math/library/vector/add_subtract/
    assertEquals(Vector.create(5, 10), Vector.create(1, 2).plus(Vector.create(4, 8)));
    assertEquals(Vector.create(5, 10, 6), Vector.create(1, 2, 5).plus(Vector.create(4, 8, 1)));
    assertEquals(Vector.create(5, 10, 6, -11), Vector.create(1, 2, 5, 9).plus(Vector.create(4, 8, 1, -20)));
  }

  public void testPlusWrong() {
    try {
      fail("Created " + Vector.create(1, 2).plus(Vector.create(1, 2, 3)));
    }
    catch (Exception ignored) {
    }
  }

  public void testMinus() {
    // see http://ru.onlinemschool.com/math/library/vector/add_subtract/
    assertEquals(Vector.create(-3, -6), Vector.create(1, 2).minus(Vector.create(4, 8)));
    assertEquals(Vector.create(-3, -6, 4), Vector.create(1, 2, 5).minus(Vector.create(4, 8, 1)));
    assertEquals(Vector.create(-3, -6, 4, 0, 3), Vector.create(1, 2, 5, -1, 5).minus(Vector.create(4, 8, 1, -1, 2)));
  }

  public void testMinusWrong() {
    try {
      fail("Created " + Vector.create(1, 2).minus(Vector.create(1, 2, 3)));
    }
    catch (Exception ignored) {
    }
  }

  public void testMultiplyByValue() {
    // see http://ru.onlinemschool.com/math/library/vector/multiply3/
    assertEquals(Vector.create(3, 6), Vector.create(1, 2).multiply(3));
    assertEquals(Vector.create(-2, -4, 10), Vector.create(1, 2, -5).multiply(-2));
  }

  public void testMultiplyByMatrix() {
    Vector vector = Vector.create(1, 2, 3);
    assertEquals(vector, vector.multiply(Matrix.createIdentity(3)));

    Matrix matrix = Matrix.create(3, /*row:*/ 11, 21, /*row:*/ 12, 22, /*row:*/ 13, 23);
    Vector result = vector.multiply(matrix);
    assertEquals(Vector.create(74, 134), result);
    assertEquals(matrix.getColumns(), result.getSize());
    assertEquals(Matrix.createRow(result), Matrix.createRow(vector).multiply(matrix));
  }

  public void testMultiplyByVector() {
    assertEquals(Vector.create(4, 8).multiply(Vector.create(1, 2)), Vector.create(1, 2).multiply(Vector.create(4, 8)));
    // see http://ru.onlinemschool.com/math/library/vector/multiply/
    assertEquals(20.0, Vector.create(1, 2).multiply(Vector.create(4, 8)));
    assertEquals(15.0, Vector.create(1, 2, -5).multiply(Vector.create(4, 8, 1)));
    assertEquals(11.0, Vector.create(1, 2, -5, 2).multiply(Vector.create(4, 8, 1, -2)));
  }

  public void testMultiplyByVectorWrong() {
    try {
      fail("Created " + Vector.create(1, 2).minus(Vector.create(1, 2, 3)));
    }
    catch (Exception ignored) {
    }
  }

  public void testLength() {
    // see http://ru.onlinemschool.com/math/library/vector/length/
    assertEquals(5.0, Vector.create(3, -4).length());
    assertEquals(6.0, Vector.create(2, 4, 4).length());
  }
}

redpajama_set_name: RedPajamaGithub


text:
<?php

namespace backend\controllers;

use backend\models\ContProjProjetos;
use Yii;
use backend\models\ContProjProrrogacoes;
use backend\models\ContProjProrrogacoesSearch;
use yii\base\Exception;
use yii\web\Controller;
use yii\web\NotFoundHttpException;
use yii\filters\VerbFilter;

/**
 * ContProjProrrogacoesController implements the CRUD actions for ContProjProrrogacoes model.
 */
class ContProjProrrogacoesController extends Controller
{
    /**
     * @inheritdoc
     */
    public function behaviors()
    {
        return [
            'verbs' => [
                'class' => VerbFilter::className(),
                'actions' => [
                    'delete' => ['POST'],
                ],
            ],
        ];
    }

    /**
     * Lists all ContProjProrrogacoes models.
     * @return mixed
     */
    public function actionIndex()
    {
        $searchModel = new ContProjProrrogacoesSearch();
        $dataProvider = $searchModel->search(Yii::$app->request->queryParams);

        return $this->render('index', [
            'searchModel' => $searchModel,
            'dataProvider' => $dataProvider,
        ]);
    }

    /**
     * Displays a single ContProjProrrogacoes model.
     * @param integer $id
     * @return mixed
     */
    public function actionView($id)
    {
        return $this->render('view', [
            'model' => $this->findModel($id),
        ]);
    }

    public function dataFinalAlterada($idProjeto, ContProjProrrogacoes $model){
        $transaction = Yii::$app->db->beginTransaction();
        try {
            $model->data_fim_alterada = date('Y-m-d', strtotime($model->data_fim_alterada));
            $projeto = ContProjProjetos::find()->select("*")->where("id=$idProjeto")->one();
            $projeto->data_fim_alterada = $model->data_fim_alterada;
            //$projeto->data_fim=  $model->data_fim_alterada;
            $projeto->save(false);
            $model->save(false);
            $transaction->commit();
            return true;
        } catch (Exception $e) {
            Yii::error($e->getMessage());
            $transaction->rollBack();
            return false;
        }
    }

    /**
     * Creates a new ContProjProrrogacoes model.
     * If creation is successful, the browser will be redirected to the 'view' page.
     * @return mixed
     */
    public function actionCreate()
    {
        $idProjeto = Yii::$app->request->get('idProjeto');
        $model = new ContProjProrrogacoes();
        if ($model->load(Yii::$app->request->post()) && $model->validate()) {
            $model->data_fim_alterada = date('Y-m-d', strtotime($model->data_fim_alterada));
            $this->dataFinalAlterada($idProjeto,$model);
            $this->mensagens('success', 'Data Final', 'Nova data final cadastrada com sucesso!');
            return $this->redirect(['index', 'idProjeto' => $idProjeto]);
        } else {
            return $this->render('create', [
                'model' => $model,
                'idProjeto'=> $idProjeto,
            ]);
        }
    }

    /**
     * Updates an existing ContProjProrrogacoes model.
     * If update is successful, the browser will be redirected to the 'view' page.
     * @param integer $id
     * @return mixed
     */
    public function actionUpdate($id)
    {
        $idProjeto = Yii::$app->request->get('idProjeto');
        $model = $this->findModel($id);
        $model->data_fim_alterada = date('d-m-Y', strtotime($model->data_fim_alterada));
        if ($model->load(Yii::$app->request->post()) && $model->validate()) {
            $this->dataFinalAlterada($idProjeto,$model);
            $this->mensagens('success', 'Data Final', 'Data final editada com sucesso!');
            return $this->redirect(['index','idProjeto'=> $idProjeto]);
        } else {
            return $this->render('update', [
                'model' => $model,
                'idProjeto'=> $idProjeto,
            ]);
        }
    }

    /**
     * Deletes an existing ContProjProrrogacoes model.
     * If deletion is successful, the browser will be redirected to the 'index' page.
     * @param integer $id
     * @return mixed
     */

    function debug_to_console( $data ) {

        if ( is_array( $data ) )
            $output = "<script>console.log( 'Debug Objects: " . implode( ',', $data) . "' );</script>";
        else
            $output = "<script>console.log( 'Debug Objects: " . $data . "' );</script>";

        echo $output;
    }

    public function actionDelete($id)
    {
        $idProjeto = Yii::$app->request->get('idProjeto');
        $this->findModel($id)->delete();
        $transaction = Yii::$app->db->beginTransaction();
        try {
            $data_fim_alterada = ContProjProrrogacoes::find()->select("data_fim_alterada")->max('data_Fim_alterada');
            $this->debug_to_console($data_fim_alterada);
            if ($data_fim_alterada == null) {
                $projeto = ContProjProjetos::find()->select("*")->where("id=$idProjeto")->one();
                $projeto->data_fim_alterada = $projeto->data_fim;

            } else {
                $projeto = ContProjProjetos::find()->select("*")->where("id=$idProjeto")->one();
                $projeto->data_fim_alterada = $data_fim_alterada;
            }
            $projeto->save(false);
            $transaction->commit();
        } catch (Exception $e) {
            Yii::error($e->getMessage());
            $transaction->rollBack();
        }
        $this->mensagens('success', 'Exclusão da Data', 'Exclusão bem sucedida!');
        return $this->redirect(['index','idProjeto'=> $idProjeto]);
    }

    /**
     * Finds the ContProjProrrogacoes model based on its primary key value.
     * If the model is not found, a 404 HTTP exception will be thrown.
     * @param integer $id
     * @return ContProjProrrogacoes the loaded model
     * @throws NotFoundHttpException if the model cannot be found
     */
    protected function findModel($id)
    {
        if (($model = ContProjProrrogacoes::findOne($id)) !== null) {
            return $model;
        } else {
            throw new NotFoundHttpException('The requested page does not exist.');
        }
    }

    protected function mensagens($tipo, $titulo, $mensagem)
    {
        Yii::$app->session->setFlash($tipo, [
            'type' => $tipo,
            'icon' => 'home',
            'duration' => 5000,
            'message' => $mensagem,
            'title' => $titulo,
            'positonY' => 'top',
            'positonX' => 'center',
            'showProgressbar' => true,
        ]);
    }

}


text:
<?php
/** xmlwriter Functions.

See: {@link http://www.php.net/manual/en/ref.xmlwriter.php}
@package xmlwriter
*/

/*. bool .*/ function xmlwriter_set_indent(/*. resource .*/ $xmlwriter, /*. bool .*/ $indent){}
/*. bool .*/ function xmlwriter_set_indent_string(/*. resource .*/ $xmlwriter, /*. string .*/ $indentstring){}
/*. bool .*/ function xmlwriter_start_attribute(/*. resource .*/ $xmlwriter, /*. string .*/ $name){}
/*. bool .*/ function xmlwriter_end_attribute(/*. resource .*/ $xmlwriter){}
/*. bool .*/ function xmlwriter_start_attribute_ns(/*. resource .*/ $xmlwriter, /*. string .*/ $prefix, /*. string .*/ $name, /*. string .*/ $uri){}
/*. bool .*/ function xmlwriter_write_attribute(/*. resource .*/ $xmlwriter, /*. string .*/ $name, /*. string .*/ $content){}
/*. bool .*/ function xmlwriter_write_attribute_ns(/*. resource .*/ $xmlwriter, /*. string .*/ $prefix, /*. string .*/ $name, /*. string .*/ $uri, /*. string .*/ $content){}
/*. bool .*/ function xmlwriter_start_element(/*. resource .*/ $xmlwriter, /*. string .*/ $name){}
/*. bool .*/ function xmlwriter_start_element_ns(/*. resource .*/ $xmlwriter, /*. string .*/ $prefix, /*. string .*/ $name, /*. string .*/ $uri){}
/*. bool .*/ function xmlwriter_end_element(/*. resource .*/ $xmlwriter){}
/*. bool .*/ function xmlwriter_full_end_element(/*. resource .*/ $xmlwriter){}
/*. bool .*/ function xmlwriter_write_element(/*. resource .*/ $xmlwriter, /*. string .*/ $name, /*. string .*/ $content){}
/*. bool .*/ function xmlwriter_write_element_ns(/*. resource .*/ $xmlwriter, /*. string .*/ $prefix, /*. string .*/ $name, /*. string .*/ $uri, /*. string .*/ $content){}
/*. bool .*/ function xmlwriter_start_pi(/*. resource .*/ $xmlwriter, /*. string .*/ $target){}
/*. bool .*/ function xmlwriter_end_pi(/*. resource .*/ $xmlwriter){}
/*. bool .*/ function xmlwriter_write_pi(/*. resource .*/ $xmlwriter, /*. string .*/ $target, /*. string .*/ $content){}
/*. bool .*/ function xmlwriter_start_cdata(/*. resource .*/ $xmlwriter){}
/*. bool .*/ function xmlwriter_end_cdata(/*. resource .*/ $xmlwriter){}
/*. bool .*/ function xmlwriter_write_cdata(/*. resource .*/ $xmlwriter, /*. string .*/ $content){}
/*. bool .*/ function xmlwriter_write_raw(/*. resource .*/ $xmlwriter, /*. string .*/ $content){}
/*. bool .*/ function xmlwriter_text(/*. resource .*/ $xmlwriter, /*. string .*/ $content){}
/*. bool .*/ function xmlwriter_start_comment(/*. resource .*/ $xmlwriter){}
/*. bool .*/ function xmlwriter_end_comment(/*. resource .*/ $xmlwriter){}
/*. bool .*/ function xmlwriter_write_comment(/*. resource .*/ $xmlwriter, /*. string .*/ $content){}
/*. bool .*/ function xmlwriter_start_document(/*. resource .*/ $xmlwriter, /*. string .*/ $version, /*. string .*/ $encoding, /*. string .*/ $standalone){}
/*. bool .*/ function xmlwriter_end_document(/*. resource .*/ $xmlwriter){}
/*. bool .*/ function xmlwriter_start_dtd(/*. resource .*/ $xmlwriter, /*. string .*/ $name, /*. string .*/ $pubid, /*. string .*/ $sysid){}
/*. bool .*/ function xmlwriter_end_dtd(/*. resource .*/ $xmlwriter){}
/*. bool .*/ function xmlwriter_write_dtd(/*. resource .*/ $xmlwriter, /*. string .*/ $name, /*. string .*/ $pubid, /*. string .*/ $sysid, /*. string .*/ $subset){}
/*. bool .*/ function xmlwriter_start_dtd_element(/*. resource .*/ $xmlwriter, /*. string .*/ $name){}
/*. bool .*/ function xmlwriter_end_dtd_element(/*. resource .*/ $xmlwriter){}
/*. bool .*/ function xmlwriter_write_dtd_element(/*. resource .*/ $xmlwriter, /*. string .*/ $name, /*. string .*/ $content){}
/*. bool .*/ function xmlwriter_start_dtd_attlist(/*. resource .*/ $xmlwriter, /*. string .*/ $name){}
/*. bool .*/ function xmlwriter_end_dtd_attlist(/*. resource .*/ $xmlwriter){}
/*. bool .*/ function xmlwriter_write_dtd_attlist(/*. resource .*/ $xmlwriter, /*. string .*/ $name, /*. string .*/ $content){}
/*. bool .*/ function xmlwriter_start_dtd_entity(/*. resource .*/ $xmlwriter, /*. string .*/ $name, /*. bool .*/ $isparam){}
/*. bool .*/ function xmlwriter_end_dtd_entity(/*. resource .*/ $xmlwriter){}
/*. bool .*/ function xmlwriter_write_dtd_entity(/*. resource .*/ $xmlwriter, /*. string .*/ $name, /*. string .*/ $content){}
/*. resource .*/ function xmlwriter_open_uri(/*. resource .*/ $xmlwriter, /*. string .*/ $source){}
/*. resource .*/ function xmlwriter_open_memory(){}
/*. string .*/ function xmlwriter_output_memory(/*. resource .*/ $xmlwriter /*. , args .*/){}
/*. mixed .*/ function xmlwriter_flush(/*. resource .*/ $xmlwriter, $flush = TRUE){}

class XMLWriter
{
	/*. bool .*/ function setIndent(/*. bool .*/ $indent){}
	/*. bool .*/ function setIndentString(/*. string .*/ $indentstring){}
	/*. bool .*/ function startAttribute(/*. string .*/ $name){}
	/*. bool .*/ function endAttribute(){}
	/*. bool .*/ function startAttributeNs(/*. string .*/ $prefix, /*. string .*/ $name, /*. string .*/ $uri){}
	/*. bool .*/ function writeAttribute(/*. string .*/ $name, /*. string .*/ $content){}
	/*. bool .*/ function writeAttributeNs(/*. string .*/ $prefix, /*. string .*/ $name, /*. string .*/ $uri, /*. string .*/ $content){}
	/*. bool .*/ function startElement(/*. string .*/ $name){}
	/*. bool .*/ function startElementNs(/*. string .*/ $prefix, /*. string .*/ $name, /*. string .*/ $uri){}
	/*. bool .*/ function endElement(){}
	/*. bool .*/ function fullEndElement(){}
	/*. bool .*/ function writeElement(/*. string .*/ $name, /*. string .*/ $content){}
	/*. bool .*/ function writeElementNs(/*. string .*/ $prefix, /*. string .*/ $name, /*. string .*/ $uri, /*. string .*/ $content){}
	/*. bool .*/ function startPi(/*. string .*/ $target){}
	/*. bool .*/ function endPi(){}
	/*. bool .*/ function writePi(/*. string .*/ $target, /*. string .*/ $content){}
	/*. bool .*/ function startCdata(){}
	/*. bool .*/ function endCdata(){}
	/*. bool .*/ function writeCdata(/*. string .*/ $content){}
	/*. bool .*/ function writeRaw(/*. string .*/ $content){}
	/*. bool .*/ function text(/*. string .*/ $content){}
	/*. bool .*/ function startComment(){}
	/*. bool .*/ function endComment(){}
	/*. bool .*/ function writeComment(/*. string .*/ $content){}
	/*. bool .*/ function startDocument(/*. string .*/ $version /*. , args .*/){}
	/*. bool .*/ function endDocument(){}
	/*. bool .*/ function startDtd(/*. string .*/ $name, /*. string .*/ $pubid, /*. string .*/ $sysid){}
	/*. bool .*/ function endDtd(){}
	/*. bool .*/ function writeDtd(/*. string .*/ $name, /*. string .*/ $pubid, /*. string .*/ $sysid, /*. string .*/ $subset){}
	/*. bool .*/ function startDtdDlement(/*. string .*/ $name){}
	/*. bool .*/ function endDtdElement(){}
	/*. bool .*/ function writeDtdElement(/*. string .*/ $name, /*. string .*/ $content){}
	/*. bool .*/ function startDtdAttlist(/*. string .*/ $name){}
	/*. bool .*/ function endDtdAttlist(){}
	/*. bool .*/ function writeDtdAttlist(/*. string .*/ $name, /*. string .*/ $content){}
	/*. bool .*/ function startDtdEntity(/*. string .*/ $name, /*. bool .*/ $isparam){}
	/*. bool .*/ function endDtdEntity(){}
	/*. bool .*/ function writeDtdEntity(/*. string .*/ $name, /*. string .*/ $content){}
	/*. resource .*/ function openURI(/*. string .*/ $source){}
	/*. resource .*/ function openMemory(){}
	/*. string .*/ function outputMemory($flush = TRUE){}
	/*. mixed .*/ function flush($empty = TRUE){}
}


text:
import React from 'react';
import { Route, Redirect } from 'react-router';
import NoMatch from '../../components/NoMatch';
import ReactLayout from '../../components/layouts/ReactLayout';
import ReactDocContent from '../../views/ReactDocContent';

export default function () {
  return (
    <Route component={ ReactLayout }>
      <Route path='/(docs)/react(/:group)(/:component)(/:target)' component={ ReactDocContent } />
      <Redirect from="/" to="/docs" />
      <Route path="*" component={ NoMatch } />
    </Route>
  );
}


text:
package flag

import (
	"fmt"
	"os"
	"strings"

	flags "github.com/jessevdk/go-flags"
)

type EnvironmentVariable string

func (_ EnvironmentVariable) Complete(prefix string) []flags.Completion {
	if prefix == "" || prefix[0] != '$' {
		return nil
	}

	keyValPairs := os.Environ()
	envVars := make([]string, len(keyValPairs))
	for i, keyValPair := range keyValPairs {
		envVars[i] = fmt.Sprintf("$%s", strings.Split(keyValPair, "=")[0])
	}

	return completions(envVars, prefix, true)
}


text:
package com.onebitmedia.jsend;

public class JSendErrorException extends JSendException {

    public JSendErrorException(String detailMessage) {
        super(detailMessage);
    }

    public JSendErrorException(String detailMessage, Throwable throwable) {
        super(detailMessage, throwable);
    }

    public JSendErrorException(Throwable throwable) {
        super(throwable);
    }
}


text:
package daemon

import (
	"context"
	"fmt"
	"github.com/aaronland/go-http-server"
	"github.com/whosonfirst/go-webhookd/v3"
	"github.com/whosonfirst/go-webhookd/v3/config"
	"github.com/whosonfirst/go-webhookd/v3/dispatcher"
	"github.com/whosonfirst/go-webhookd/v3/receiver"
	"github.com/whosonfirst/go-webhookd/v3/transformation"
	"github.com/whosonfirst/go-webhookd/v3/webhook"
	"log"
	"net/http"
	"net/url"
	"strconv"
	"strings"
	"sync"
	"time"
)

// type WebhookDaemon is a struct that implements a long-running daemon to listen for	and process webhooks.
type WebhookDaemon struct {
	// server is a `aaronland/go-http-server.Server` instance that handles HTTP requests and responses.
	server server.Server
	// webhooks is a dictionary of URIs and their corresponding `webhookd.WebhookHandler` instances.
	webhooks map[string]webhookd.WebhookHandler
	// AllowDebug is a boolean flag to enable debugging reporting in webhook responses.
	AllowDebug bool
}

// NewWebhookDaemonFromConfig() returns a new `WebhookDaemon` derived from configuration data in 'cfg'.
func NewWebhookDaemonFromConfig(ctx context.Context, cfg *config.WebhookConfig) (*WebhookDaemon, error) {

	d, err := NewWebhookDaemon(ctx, cfg.Daemon)

	if err != nil {
		return nil, fmt.Errorf("Failed to create new webhookd daemon, %w", err)
	}

	err = d.AddWebhooksFromConfig(ctx, cfg)

	if err != nil {
		return nil, fmt.Errorf("Failed to add webhooks to daemon, %w", err)
	}

	return d, nil
}

// NewWebhookDaemon() returns a `WebhookDaemon` instance derived from 'uri' which is expected to take
// the form of any valid `aaronland/go-http-server.Server` URI with the following parameters:
// * `?allow_debug=` An optional boolean flag to enable debugging output in webhook responses.
func NewWebhookDaemon(ctx context.Context, uri string) (*WebhookDaemon, error) {

	u, err := url.Parse(uri)

	if err != nil {
		return nil, fmt.Errorf("Failed to parse daemon URI, %w", err)
	}

	q := u.Query()

	str_debug := q.Get("allow_debug")

	allow_debug := false

	if str_debug != "" {

		v, err := strconv.ParseBool(str_debug)

		if err != nil {
			return nil, fmt.Errorf("Invalid ?allow_debug parameter, %w", err)
		}

		allow_debug = v
	}

	srv, err := server.NewServer(ctx, uri)

	if err != nil {
		return nil, fmt.Errorf("Failed to create new server instance, %w", err)
	}

	webhooks := make(map[string]webhookd.WebhookHandler)

	d := WebhookDaemon{
		server:     srv,
		webhooks:   webhooks,
		AllowDebug: allow_debug,
	}

	return &d, nil
}

// AddWebhooksFromConfig() appends the webhooks defined in 'cfg' to 'd'.
func (d *WebhookDaemon) AddWebhooksFromConfig(ctx context.Context, cfg *config.WebhookConfig) error {

	if len(cfg.Webhooks) == 0 {
		return fmt.Errorf("No webhooks defined")
	}

	for i, hook := range cfg.Webhooks {

		if hook.Endpoint == "" {
			return fmt.Errorf("Missing endpoint at offset %d", i+1)
		}

		if hook.Receiver == "" {
			return fmt.Errorf("Missing receiver at offset %d", i+1)
		}

		if len(hook.Dispatchers) == 0 {
			return fmt.Errorf("Missing dispatchers at offset %d", i+1)
		}

		receiver_uri, err := cfg.GetReceiverConfigByName(hook.Receiver)

		if err != nil {
			return fmt.Errorf("Failed to get receiver config for '%s', %w", hook.Receiver, err)
		}

		receiver, err := receiver.NewReceiver(ctx, receiver_uri)

		if err != nil {
			return fmt.Errorf("Failed to add receiver '%s', %w", receiver_uri, err)
		}

		var steps []webhookd.WebhookTransformation

		for _, name := range hook.Transformations {

			if strings.HasPrefix(name, "#") {
				continue
			}

			transformation_uri, err := cfg.GetTransformationConfigByName(name)

			if err != nil {
				return fmt.Errorf("Failed to get transformation configuration for '%s', %w", name, err)
			}

			step, err := transformation.NewTransformation(ctx, transformation_uri)

			if err != nil {
				return fmt.Errorf("Failed to create new transformation for '%s', %w", transformation_uri, err)
			}

			steps = append(steps, step)
		}

		var sendto []webhookd.WebhookDispatcher

		for _, name := range hook.Dispatchers {

			if strings.HasPrefix(name, "#") {
				continue
			}

			dispatcher_uri, err := cfg.GetDispatcherConfigByName(name)

			if err != nil {
				return fmt.Errorf("Failed to get dispatcher configuration for '%s', %w", name, err)
			}

			dispatcher, err := dispatcher.NewDispatcher(ctx, dispatcher_uri)

			if err != nil {
				return fmt.Errorf("Failed to create dispatcher for '%s', %w", dispatcher_uri, err)
			}

			sendto = append(sendto, dispatcher)
		}

		wh, err := webhook.NewWebhook(ctx, hook.Endpoint, receiver, steps, sendto)

		if err != nil {
			return fmt.Errorf("Failed to create new webhook for '%s', %w", hook.Endpoint, err)
		}

		err = d.AddWebhook(ctx, wh)

		if err != nil {
			return fmt.Errorf("Failed to add new webhook for '%s', %w", hook.Endpoint, err)
		}

	}

	return nil
}

// AddWebhook() adds 'wh' to 'd'.
func (d *WebhookDaemon) AddWebhook(ctx context.Context, wh webhook.Webhook) error {

	endpoint := wh.Endpoint()
	_, ok := d.webhooks[endpoint]

	if ok {
		return fmt.Errorf("endpoint already configured")
	}

	d.webhooks[endpoint] = wh
	return nil
}

// HandlerFunc() returns a `http.HandlerFunc` that handles HTTP (webhook) requests and response for 'd'.
func (d *WebhookDaemon) HandlerFunc() (http.HandlerFunc, error) {
	logger := log.Default()
	return d.HandlerFuncWithLogger(logger)
}

// HandlerFuncWithLogger() returns a `http.HandlerFunc` that handles HTTP (webhook) requests and response for 'd'
// logging events to 'logger'.
func (d *WebhookDaemon) HandlerFuncWithLogger(logger *log.Logger) (http.HandlerFunc, error) {

	handler := func(rsp http.ResponseWriter, req *http.Request) {

		ctx := req.Context()

		ctx, cancel := context.WithCancel(ctx)
		defer cancel()

		endpoint := req.URL.Path

		wh, ok := d.webhooks[endpoint]

		if !ok {
			http.Error(rsp, "404 Not found", http.StatusNotFound)
			return
		}

		t1 := time.Now()

		var ta time.Time
		var tb time.Duration

		var ttr time.Duration // time to receive
		var ttt time.Duration // time to transform
		var ttd time.Duration // time to dispatch

		ta = time.Now()

		rcvr := wh.Receiver()

		body, err := rcvr.Receive(ctx, req)

		// we use -1 to signal that this is an unhandled event but
		// not an error, for example when github sends a ping message
		// (20190212/thisisaaronland)

		if err != nil && err.Code == -1 {
			return
		}

		if err != nil {
			http.Error(rsp, err.Error(), err.Code)
			return
		}

		tb = time.Since(ta)

		ttr = tb

		ta = time.Now()

		for _, step := range wh.Transformations() {

			body, err = step.Transform(ctx, body)

			if err != nil {
				http.Error(rsp, err.Error(), err.Code)
				return
			}

			// check to see if there is anything left the transformation
			// https://github.com/whosonfirst/go-webhookd/v3/issues/7
		}

		tb = time.Since(ta)
		ttt = tb

		// check to see if there is anything to dispatch
		// https://github.com/whosonfirst/go-webhookd/v3/issues/7

		ta = time.Now()

		wg := new(sync.WaitGroup)
		ch := make(chan *webhookd.WebhookError)

		for _, d := range wh.Dispatchers() {

			wg.Add(1)

			go func(d webhookd.WebhookDispatcher, body []byte) {

				defer wg.Done()

				err = d.Dispatch(ctx, body)

				if err != nil {
					logger.Printf("FAILED TO DISPATCH W/ %T, %v\n", d, err)
					ch <- err
				}

			}(d, body)
		}

		// https://github.com/whosonfirst/go-webhookd/issues/14
		// this is broken as in len(errors) will always be zero even if
		// there are errors (20190214/thisisaaronland)

		errors := make([]string, 0)

		go func() {

			for e := range ch {
				errors = append(errors, e.Error())
			}
		}()

		wg.Wait()

		if len(errors) > 0 {

			msg := strings.Join(errors, "\n\n")
			http.Error(rsp, msg, http.StatusInternalServerError)
			return
		}

		tb = time.Since(ta)
		ttd = tb

		t2 := time.Since(t1)

		rsp.Header().Set("X-Webhookd-Time-To-Receive", fmt.Sprintf("%v", ttr))
		rsp.Header().Set("X-Webhookd-Time-To-Transform", fmt.Sprintf("%v", ttt))
		rsp.Header().Set("X-Webhookd-Time-To-Dispatch", fmt.Sprintf("%v", ttd))
		rsp.Header().Set("X-Webhookd-Time-To-Process", fmt.Sprintf("%v", t2))

		if d.AllowDebug {

			query := req.URL.Query()
			debug := query.Get("debug")

			if debug != "" {
				rsp.Header().Set("Content-Type", "text/plain")
				rsp.Header().Set("Access-Control-Allow-Origin", "*")
				rsp.Write(body)
			}
		}

		return
	}

	return http.HandlerFunc(handler), nil
}

// Start() causes 'd' to listen for, and process, requests.
func (d *WebhookDaemon) Start(ctx context.Context) error {
	logger := log.Default()
	return d.StartWithLogger(ctx, logger)
}

// StartWithLogger() causes 'd' to listen for, and process, requests logging events to 'logger'.
func (d *WebhookDaemon) StartWithLogger(ctx context.Context, logger *log.Logger) error {

	handler, err := d.HandlerFuncWithLogger(logger)

	if err != nil {
		return fmt.Errorf("Failed to create handler func, %w", err)
	}

	mux := http.NewServeMux()
	mux.HandleFunc("/", handler)

	svr := d.server

	logger.Printf("webhookd listening for requests on %s\n", svr.Address())

	err = svr.ListenAndServe(ctx, mux)

	if err != nil {
		return fmt.Errorf("Failed to listen for requests, %w", err)
	}

	return nil
}


text:
#include <stdlib.h>
#include <stdio.h>
#include <assert.h>
#include <ctype.h>
#include <string.h>
#include "dbus/dbus.h"
#include "cdbus/cdbus.h"
#include "l2dbus_compat.h"
#include "l2dbus_serviceobject.h"
#include "l2dbus_interface.h"
#include "l2dbus_connection.h"
#include "l2dbus_core.h"
#include "l2dbus_object.h"
#include "l2dbus_util.h"
#include "l2dbus_trace.h"
#include "l2dbus_debug.h"
#include "l2dbus_types.h"
#include "l2dbus_alloc.h"
#include "l2dbus_message.h"
#include "l2dbus_dbuscompat.h"
#include "lualib.h"

/**
 L2DBUS ServiceObject

 This section describes a Lua ServiceObject class.

 A D-Bus service object is an instance of a D-Bus object that appears
 on the bus with a specific object path. Typically a service object will
 implement one or more @{l2dbus.Interface|interfaces} which define the
 methods, properties, and signals exposed by the service (e.g. its
 application programming interface, or API). The handling of requests for a
 service object from client applications can be delegated to the interfaces
 themselves since they can handle request from more than one service object.
 Interfaces can be *shared* by multiple service objects. Likewise service
 object themselves can be *shared* across more than one
 @{l2dbus.Connection|connection}. In this way it's possible for a service
 object to span multiple buses (e.g. have the same object appear on both a
 @{l2dbus.Dbus.BUS_SYSTEM|system} and @{l2dbus.Dbus.BUS_SESSION|session} bus).

 If the interfaces themselves don't have handlers to process requests (or
 they chose not to handle a specific request) then any registered *object*
 handler gets the opportunity to process the request. If no suitable handler
 is found then an appropriate error message is returned to the client
 application.

 **Note:** Although possible, a more convenient method is available to
 implement custom D-Bus services. The @{l2dbus.service} module provides a
 friendlier interface for instantiating D-Bus services and internally leverages
 the ServiceObject. It is recommended that new services are implemented
 using @{l2dbus.service} methods instead.

 @namespace l2dbus.ServiceObject
 */

/**
 @brief Handles and processes requests to the service object.

 This function will try to deliver a callback to a Lua handler function
 when invoked. The handler itself will determine whether or not it
 can handle the request.

 @param [in] obj      The CDBUS service object.
 @param [in] conn     The CDBUS connection associated with this object.
 @param [in] msg      The D-Bus request message (e.g. method call).

 @return A suitable DBusHandlerResult value. Returning
 DBUS_HANDLER_RESULT_HANDLED indicates the object handler processed
 the request. Otherwise a suitable D-Bus error message is ultimately
 returned to the client application.
 */
static DBusHandlerResult
l2dbus_serviceObjectHandler
    (
        struct cdbus_Object*        obj,
        struct cdbus_Connection*    conn,
        DBusMessage*                msg
    )
{
    lua_State* L = l2dbus_callbackGetThread();
    const char* errMsg = "";
    DBusHandlerResult rc = DBUS_HANDLER_RESULT_NOT_YET_HANDLED;
    l2dbus_ServiceObject* ud;

    /* Leaves the userdata sitting on the top of the stack */
    ud = l2dbus_objectRegistryGet(L, obj);

    /* Nil or the ServiceObject userdata is sitting at the top of the
     * stack at this point.
     */

    assert( NULL != ud );
    assert( NULL != L );

    /* If the watch userdata has been GC'ed then ... */
    if ( NULL == ud )
    {
        L2DBUS_TRACE((L2DBUS_TRC_WARN,
            "Cannot call handler because service object has been GC'ed"));
    }
    /* Else if a default callback function was provided then ... */
    else if ( LUA_NOREF != ud->cbCtx.funcRef )
    {
        /* Push function and user value on the stack and execute the callback */
        lua_rawgeti(L, LUA_REGISTRYINDEX, ud->cbCtx.funcRef);
        /* Push the service object userdata */
        lua_pushvalue(L, -2 /* Service object ud */);
        /* Push the associated Lua connection userdata wrapper on the stack */
        l2dbus_objectRegistryGet(L, conn);
        if ( lua_isnil(L, -1) )
        {
            L2DBUS_TRACE((L2DBUS_TRC_WARN,
                        "Cannot call object handler because connection has been GC'ed"));
        }
        else
        {
            /* Push a Lua wrapper around the message */
            l2dbus_messageWrap(L, msg, L2DBUS_TRUE);

            /* Push the user provided value on the stack */
            lua_rawgeti(L, LUA_REGISTRYINDEX, ud->cbCtx.userRef);

            if ( 0 != lua_pcall(L, 4 /* nArgs */, 1 /* nResults */, 0) )
            {
                if ( lua_isstring(L, -1) )
                {
                    errMsg = lua_tostring(L, -1);
                }
                L2DBUS_TRACE((L2DBUS_TRC_ERROR, "Service object callback error: %s", errMsg));
            }
            else
            {
                if ( lua_isnumber(L, -1) )
                {
                    rc = lua_tointeger(L, -1);
                    switch ( rc )
                    {
                        case DBUS_HANDLER_RESULT_HANDLED:
                        case DBUS_HANDLER_RESULT_NOT_YET_HANDLED:
                        case DBUS_HANDLER_RESULT_NEED_MEMORY:
                            /* These are understood */
                            break;

                        default:
                            L2DBUS_TRACE((L2DBUS_TRC_ERROR,
                                "Unknown service object callback return code (%d)", rc));
                            rc = DBUS_HANDLER_RESULT_NOT_YET_HANDLED;
                            break;
                    }
                }
            }
        }
    }

    /* Clean up the thread stack */
    lua_settop(L, 0);

    /* The return value is unused by CDBUS */
    return rc;
}

/**
 @brief Removes an interface from the underlying CDBUS object.

 @param [in] item       The Lua Interface userdata.
 @param [in] userdata   The Lua ServiceObject userdata.
 */
static void
l2dbus_serviceObjectFreeObject
    (
    void*   item,
    void*   userdata
    )
{
    l2dbus_Interface* intfUd = (l2dbus_Interface*)item;
    l2dbus_ServiceObject* svcObjUd = (l2dbus_ServiceObject*)userdata;

    if ( !cdbus_objectRemoveInterface(svcObjUd->obj, cdbus_interfaceGetName(intfUd->intf)) )
    {
        L2DBUS_TRACE((L2DBUS_TRC_WARN,
            "Failed to removed interface '%s' from service object",
            cdbus_interfaceGetName(intfUd->intf)));
    }
}

/**
 @function new

 Creates a new ServiceObject.

 Creates a new service object used to implement a D-Bus object that can
 respond to requests, emit signals, and expose properties. The service object
 can be associated a handler that can process client requests. The signature of
 the handler has the form:

     DBusHandlerResult function onRequest(svcObj, conn, msg, userToken)

 Where:

*svcObj*     - The D-Bus service object

*conn*       - The D-Bus connection from which the request was received

*msg*        - The D-Bus request message

*userToken*  - A value specified by the user when the object was created.

 The handler function should return one of the following values:

@{l2dbus.Dbus.HANDLER_RESULT_HANDLED|HANDLER_RESULT_HANDLED} - Request handled

@{l2dbus.Dbus.HANDLER_RESULT_NOT_YET_HANDLED|HANDLER_RESULT_NOT_YET_HANDLED} - Request **not** handled

@{l2dbus.Dbus.HANDLER_RESULT_NEED_MEMORY|HANDLER_RESULT_NEED_MEMORY} - Request **not** handled due to lack of memory

 For all cases except @{l2dbus.Dbus.HANDLER_RESULT_HANDLED|HANDLER_RESULT_HANDLED}
 the client application will receive an appropriate error message for an
 unhandled request.

 @tparam string objPath A valid D-Bus object path.
 @tparam ?func|nil handler An optional object handler function or **nil** if none desired.
 @tparam ?any userToken Optional client data associated with the handler. Will be passed
 to the handler when its invoked.
 @treturn userdata The userdata object representing the ServiceObject.
 */
static int
l2dbus_newServiceObject
    (
    lua_State*  L
    )
{
    l2dbus_ServiceObject* svcObjUd;
    const char* path = NULL;
    int funcIdx = L2DBUS_CALLBACK_NOREF_NEEDED;
    int userIdx = L2DBUS_CALLBACK_NOREF_NEEDED;
    int nArgs;

    L2DBUS_TRACE((L2DBUS_TRC_TRACE, "Create: service object"));

    /* Make sure the module is initialized */
    l2dbus_checkModuleInitialized(L);
    nArgs = lua_gettop(L);

    path = luaL_checkstring(L, 1);
    if ( !l2dbus_validatePath(path) )
    {
        luaL_error(L, "invalid D-Bus object path");
    }

    /* Check for a handler function */
    if ( (nArgs >= 2) &&  (LUA_TFUNCTION == lua_type(L, 2)) )
    {
        funcIdx = 2;
    }

    /* See if an optional user value is provided */
    if ( nArgs >  2 )
    {
        userIdx = 3;
    }

    svcObjUd = (l2dbus_ServiceObject*)l2dbus_objectNew(L, sizeof(*svcObjUd),
                                             L2DBUS_SERVICE_OBJECT_TYPE_ID);
    L2DBUS_TRACE((L2DBUS_TRC_TRACE, "Service object userdata=%p", svcObjUd));

    if ( NULL == svcObjUd )
    {
        luaL_error(L, "Failed to create service object userdata!");
    }
    else
    {
        /* Reset the userdata structure */
        l2dbus_callbackInit(&svcObjUd->cbCtx);
        l2dbus_refListInit(&svcObjUd->interfaces);

        l2dbus_callbackRef(L, funcIdx, userIdx, &svcObjUd->cbCtx);
        svcObjUd->obj = cdbus_objectNew(path, l2dbus_serviceObjectHandler, svcObjUd);

        if ( NULL == svcObjUd->obj )
        {
            /* Release any references we may still have */
            l2dbus_callbackUnref(L, &svcObjUd->cbCtx);
            l2dbus_refListFree(&svcObjUd->interfaces, L, NULL, NULL);
            luaL_error(L, "Failed to allocate service object");
        }
        else
        {
            /* Create a (weak) mapping between the CDBUS object pointer and
             * the Lua userdata wrapper.
             */
            l2dbus_objectRegistryAdd(L, svcObjUd->obj, -1);
        }
    }

    return 1;
}

/**
 * @brief Called by Lua VM to GC/reclaim the ServiceObject userdata.
 *
 * This method is called by the Lua VM to reclaim the ServiceObject
 * userdata.
 *
 * @return nil
 *
 */
static int
l2dbus_serviceObjectDispose
    (
    lua_State*  L
    )
{
    l2dbus_ServiceObject* ud = (l2dbus_ServiceObject*)luaL_checkudata(L, -1,
                                        L2DBUS_SERVICE_OBJECT_MTBL_NAME);

    L2DBUS_TRACE((L2DBUS_TRC_TRACE, "GC: service object (userdata=%p)", ud));

    l2dbus_refListFree(&ud->interfaces, L, l2dbus_serviceObjectFreeObject, ud);

    if ( ud->obj != NULL )
    {
        /* Remove the weak association from CDBUS object to the Lua
         * userdata object wrapper.
         */
        l2dbus_objectRegistryRemove(L, ud->obj);
        cdbus_objectUnref(ud->obj);
    }

    /* Unreference the function/data associated with a callback */
    l2dbus_callbackUnref(L, &ud->cbCtx);

    return 0;
}

/**
 * The L2DBUS ServiceObject class.
 * @type ServiceObject
 */

/**
 @function path
 @within ServiceObject

 Returns the object path associated with the object.

 @tparam userdata object The userdata representing the ServiceObject.
 @treturn ?string|nil A string with the object path or **nil** if it
 is unset.
 */
static int
l2dbus_serviceObjectGetPath
    (
    lua_State*  L
    )
{
    const char* path;
    l2dbus_ServiceObject* ud = (l2dbus_ServiceObject*)luaL_checkudata(L, 1,
                                        L2DBUS_SERVICE_OBJECT_MTBL_NAME);

    /* Make sure the module is initialized */
    l2dbus_checkModuleInitialized(L);

    path = cdbus_objectGetPath(ud->obj);
    if ( NULL != path )
    {
        lua_pushstring(L, path);
    }
    else
    {
        lua_pushnil(L);
    }

    return 1;
}

/**
 @function setData
 @within ServiceObject

 Sets the user data to be passed back in the object request handler.

 @tparam userdata object The userdata representing the ServiceObject.
 @tparam any userToken A value to pass back in the object request handler callback.
 */
static int
l2dbus_serviceObjectSetData
    (
    lua_State*  L
    )
{
    l2dbus_ServiceObject* ud = (l2dbus_ServiceObject*)luaL_checkudata(L, 1,
                                        L2DBUS_SERVICE_OBJECT_MTBL_NAME);

    /* Make sure the module is initialized */
    l2dbus_checkModuleInitialized(L);

    luaL_checkany(L, -1);

    /* Unreference the previous value */
    luaL_unref(L, LUA_REGISTRYINDEX, ud->cbCtx.userRef);

    /* On the top of the stack should be the client's user data value.
     * We'll keep a reference to that for safe-keeping.
     */
    ud->cbCtx.userRef = luaL_ref(L, LUA_REGISTRYINDEX);

    return 0;
}

/**
 @function data
 @within ServiceObject

 Retrieves the data that will be passed to the object request handler.

 @tparam userdata object The userdata representing the ServiceObject.
 @treturn any The value that will be returned in the object request handler
 callback.
 */
static int
l2dbus_serviceObjectGetData
    (
    lua_State*  L
    )
{
    l2dbus_ServiceObject* ud = (l2dbus_ServiceObject*)luaL_checkudata(L, 1,
                                        L2DBUS_SERVICE_OBJECT_MTBL_NAME);

    /* Make sure the module is initialized */
    l2dbus_checkModuleInitialized(L);

    lua_rawgeti(L, LUA_REGISTRYINDEX, ud->cbCtx.userRef);

    return 1;
}

/**
 @function addInterface
 @within ServiceObject

 Adds an @{l2dbus.Interface|interface} to the service object.

 A service object can implement more than one interface but the interface
 names must be unique (e.g. no two interfaces with the same name). This
 method will fail if you try to add the same interface twice.

 @tparam userdata object The userdata representing the ServiceObject.
 @tparam userdata interface The @{l2dbus.Interface|interface} to add to
 the object.
 @treturn bool Returns **true** if the interface was added successfully or
 **false** otherwise.
 */
static int
l2dbus_serviceObjectAddInterface
    (
    lua_State*  L
    )
{
    l2dbus_Bool isAdded = L2DBUS_FALSE;

    l2dbus_ServiceObject* objUd = (l2dbus_ServiceObject*)luaL_checkudata(L, 1,
                                        L2DBUS_SERVICE_OBJECT_MTBL_NAME);
    l2dbus_Interface* ifUd = (l2dbus_Interface*)luaL_checkudata(L, 2,
                                        L2DBUS_INTERFACE_MTBL_NAME);

    /* Make sure the module is initialized */
    l2dbus_checkModuleInitialized(L);

    if ( cdbus_objectAddInterface(objUd->obj, ifUd->intf) )
    {
        /* Add a strong reference to the Lua userdata wrapping
         *  the D-Bus interface
         */
        if ( LUA_NOREF == l2dbus_refListRef(&objUd->interfaces, L, 2) )
        {
            /* Failed adding the reference - remove the interface */
            cdbus_objectRemoveInterface(objUd->obj, cdbus_interfaceGetName(ifUd->intf));
        }
        else
        {
            isAdded = L2DBUS_TRUE;
        }
    }

    lua_pushboolean(L, isAdded);

    return 1;
}

/**
 @function removeInterface
 @within ServiceObject

 Removes an @{l2dbus.Interface|interface} from the service object.

 The same interface instance that was originally @{addInterface|added} must be
 used to remove it since the framework keeps a strong reference to that
 interface until it is removed. If the same instance is not used (e.g.
 different interface instance with the same name) then the Lua VM will never
 be able to garbage collect the original interface.

 @tparam userdata object The userdata representing the ServiceObject.
 @tparam userdata interface The @{l2dbus.Interface|interface} to remove from
 the object.
 @treturn bool Returns **true** if the interface was removed successfully or
 **false** otherwise.
 */
static int
l2dbus_serviceObjectRemoveInterface
    (
    lua_State*  L
    )
{
    l2dbus_Bool removed = L2DBUS_FALSE;
    l2dbus_RefListIter iter;

    l2dbus_ServiceObject* objUd = (l2dbus_ServiceObject*)luaL_checkudata(L, 1,
                                        L2DBUS_SERVICE_OBJECT_MTBL_NAME);
    l2dbus_Interface* intfUd = (l2dbus_Interface*)luaL_checkudata(L, 2,
                                            L2DBUS_INTERFACE_MTBL_NAME);

    /* Make sure the module is initialized */
    l2dbus_checkModuleInitialized(L);

    if ( !cdbus_objectRemoveInterface(objUd->obj, cdbus_interfaceGetName(intfUd->intf)) )
    {
        L2DBUS_TRACE((L2DBUS_TRC_WARN,
            "Failed to removed interface '%s' from service object",
            cdbus_interfaceGetName(intfUd->intf)));
    }
    /* Else interface removed so remove the reference to the Lua wrapper */
    else
    {
        /* We've removed the actual interface owned by the lower-level CDBUS
         * object.
         */
        removed = L2DBUS_TRUE;

        /* Make best effort to remove the strong reference to the interface */

        /* If we can't find the interface to unreference then ... */
        if ( !l2dbus_refListFindItem(&objUd->interfaces, L, intfUd, &iter) )
        {
            L2DBUS_TRACE((L2DBUS_TRC_ERROR,
                        "Failed to drop reference to interface '%s'",
                        cdbus_interfaceGetName(intfUd->intf)));
        }
        /* Else the interface was found so unreference it and erase element */
        else
        {
            l2dbus_refListIterErase(&objUd->interfaces, L, &iter);
        }
    }

    lua_pushboolean(L, removed);
    return 1;
}

/**
 @function introspect
 @within ServiceObject

 Introspects the object and returns the D-Bus XML introspection data.

 This method generates the D-Bus introspection XML data for a service object
 and returns it as a string. Each interface associated with this object
 will be introspected as well.

 @tparam userdata object The userdata representing the ServiceObject.
 @tparam userdata conn The userdata representing the Connection.
 @treturn ?string|nil Returns the D-Bus XML introspection data or **nil**
 if it is unavailable.
 */
static int
l2dbus_serviceObjectIntrospect
    (
    lua_State*  L
    )
{
    l2dbus_ServiceObject* objUd = (l2dbus_ServiceObject*)luaL_checkudata(L, 1,
                                        L2DBUS_SERVICE_OBJECT_MTBL_NAME);
    l2dbus_Connection* connUd = (l2dbus_Connection*)luaL_checkudata(L, 2,
                                        L2DBUS_CONNECTION_MTBL_NAME);
    const char* path;
    cdbus_StringBuffer* buf;

    /* Make sure the module is initialized */
    l2dbus_checkModuleInitialized(L);

    path = luaL_checkstring(L, 3);

    buf = cdbus_objectIntrospect(objUd->obj, connUd->conn, path);
    if ( cdbus_stringBufferIsEmpty(buf) )
    {
        lua_pushnil(L);
    }
    else
    {
        lua_pushstring(L, cdbus_stringBufferRaw(buf));
        cdbus_stringBufferUnref(buf);
    }

    return 1;
}

/*
 * Define the methods of the ServiceObject class
 */
static const luaL_Reg l2dbus_serviceObjectMetaTable[] = {
    {"path", l2dbus_serviceObjectGetPath},
    {"setData", l2dbus_serviceObjectSetData},
    {"data", l2dbus_serviceObjectGetData},
    {"addInterface", l2dbus_serviceObjectAddInterface},
    {"removeInterface", l2dbus_serviceObjectRemoveInterface},
    {"introspect", l2dbus_serviceObjectIntrospect},
    {"__gc", l2dbus_serviceObjectDispose},
    {NULL, NULL},
};

/**
 * @brief Creates the ServiceObject sub-module.
 *
 * This function creates a metatable entry for the ServiceObject userdata
 * and simulates opening the ServiceObject sub-module.
 *
 * @return A table defining the ServiceObject sub-module.
 *
 */
void
l2dbus_openServiceObject
    (
    lua_State*  L
    )
{
    lua_pop(L, l2dbus_createMetatable(L, L2DBUS_SERVICE_OBJECT_TYPE_ID,
        l2dbus_serviceObjectMetaTable));
    lua_newtable(L);
    lua_pushcfunction(L, l2dbus_newServiceObject);
    lua_setfield(L, -2, "new");
}


text:
var tap = require("tap"),
    test = tap.test,
    plan = tap.plan,
    config;

test("load config", function (t) {
   t.plan(20)
   t.doesNotThrow( function() { config = require("../lib/config"); } )
   t.ok(config, "object loaded")
   t.ok(config.ini, "has INI interface")
   t.type(config.ini, "function", "INI interface is the right type")
   t.ok(config.general, "has Generic Config interface")
   t.type(config.general, "function", "Generic Config interface is the right t ype")
   t.ok(config.yaml, "has YAML interface")
   t.type(config.yaml, "function", "YAML interface is the right type")
   t.ok(config.json, "has JSON interface")
   t.type(config.json, "function", "JSON interface is the right type")
   t.ok(config.xml, "has XML interface")
   t.type(config.xml, "function", "XML interface is the right type")
   t.ok(config.perl, "has .pl config interface")
   t.type(config.perl, "function", ".pl interface is the right type")
   t.ok(config.load_files, "has load_files()")
   t.ok(config.load_stems, "has load_stems()")
   t.ok(config.extensions, "has extensions()")
   t.type(config.load_files, "function")
   t.type(config.load_stems, "function")
   t.type(config.extensions, "function")
   t.end()
})


text:
<?php

declare(strict_types=1);

/*
 * This file is part of the RollerworksSearch package.
 *
 * (c) Sebastiaan Stok <s.stok@rollerscapes.net>
 *
 * This source file is subject to the MIT license that is bundled
 * with this source code in the file LICENSE.
 */

namespace Rollerworks\Component\Search\Extension\Doctrine\Dbal\Conversion;

use Doctrine\DBAL\Types\Type as DbType;
use Money\Currencies\ISOCurrencies;
use Money\Formatter\DecimalMoneyFormatter;
use Rollerworks\Component\Search\Doctrine\Dbal\ColumnConversion;
use Rollerworks\Component\Search\Doctrine\Dbal\ConversionHints;
use Rollerworks\Component\Search\Doctrine\Dbal\StrategySupportedConversion;
use Rollerworks\Component\Search\Doctrine\Dbal\ValueConversion;
use Rollerworks\Component\Search\Exception\UnexpectedTypeException;
use Rollerworks\Component\Search\Extension\Core\Model\MoneyValue;

class MoneyValueConversion implements ValueConversion, ColumnConversion, StrategySupportedConversion
{
    private $formatter;
    private $currencies;

    public function __construct()
    {
        $this->currencies = new ISOCurrencies();
        $this->formatter = new DecimalMoneyFormatter($this->currencies);
    }

    /**
     * {@inheritdoc}
     */
    public function convertValue($value, array $options, ConversionHints $hints): string
    {
        if (!$value instanceof MoneyValue) {
            throw new UnexpectedTypeException($value, MoneyValue::class);
        }

        $sqlValue = $hints->connection->quote($this->formatter->format($value->value));
        $castType = $this->getCastType($hints->conversionStrategy, $hints);

        // https://github.com/rollerworks/rollerworks-search-doctrine-dbal/issues/9
        return "CAST({$sqlValue} AS {$castType})";
    }

    /**
     * {@inheritdoc}
     */
    public function convertColumn(string $column, array $options, ConversionHints $hints): string
    {
        if (DbType::DECIMAL === $hints->field->dbType->getName()) {
            return $column;
        }

        $substr = $hints->connection->getDatabasePlatform()->getSubstringExpression($column, 5);
        $castType = $this->getCastType($hints->conversionStrategy, $hints);

        return "CAST($substr AS $castType)";
    }

    /**
     * {@inheritdoc}
     */
    public function getConversionStrategy($value, array $options, ConversionHints $hints): int
    {
        if (!$value instanceof MoneyValue) {
            throw new UnexpectedTypeException($value, MoneyValue::class);
        }

        return $this->currencies->subunitFor($value->value->getCurrency());
    }

    private function getCastType(int $scale, ConversionHints $hints): string
    {
        if (false !== strpos($hints->connection->getDatabasePlatform()->getName(), 'mysql')) {
            return "DECIMAL(10, {$scale})";
        }

        return $hints->connection->getDatabasePlatform()->getDecimalTypeDeclarationSQL(
            ['scale' => $scale]
        );
    }
}


text:
@echo off
echo *** Building Bot.Builder.ChannelConnector
setlocal
setlocal enabledelayedexpansion
setlocal enableextensions
set errorlevel=0
mkdir .\nugets
erase /s .\nugets\Bot.Builder.ChannelConnector*nupkg
msbuild /property:Configuration=release BotBuilderChannelConnector\BotBuilderChannelConnector.csproj
msbuild /property:Configuration=release BotBuilderChannelConnectorOwin\BotBuilderChannelConnectorOwin.csproj
for /f %%v in ('powershell -noprofile "(Get-Command .\BotBuilderChannelConnector\bin\release\Microsoft.Bot.Builder.dll).FileVersionInfo.FileVersion"') do set builder=%%v
rem .\.paket\paket.exe pack output nugets version %builder%
.\.paket\paket.exe pack output nugets version 3.5.5.8
echo *** Finished building Bot.Builder.ChannelConnector


text:
import random

races = [("Dwarf", "+CON;+WIS;-CHA"), ("Elf", "+DEX;+INT;-CON"), ("Gnome", "+CON;+CHA;-STR"), ("Half-Elf", "ANY"), ("Half-Orc", "ANY"), ("Halfling", "+DEX;+CHA;-STR"), ("Human", "ANY")]

class Race():
    def __init__(self, inRace):
        if inRace == "rand":
            self.finalRace, self.raceStats = random.choice(races)
        else:
            self.finalRace, self.raceStats = inRace

    def generate(self):
        return (self.finalRace, self.raceStats)


text:
class MoveBrandToProducts < ActiveRecord::Migration
  def change
    remove_column :variants, :brand_id
  end
end


text:
package logger

import (
	"fmt"
	"os"
	"strings"
	"syscall"
	"time"
)

type ChanLog struct {
	Content   string
	LogTarget string
}

const (
	defaultDateFormatForFileName = "2006_01_02"
	defaultDateLayout            = "2006-01-02"
	defaultFullTimeLayout        = "2006-01-02 15:04:05.999999"
	defaultTimeLayout            = "2006-01-02 15:04:05"
)

type Logger struct {
}

var singleLogger *Logger

func GetLogger() *Logger {
	if singleLogger == nil {
		singleLogger = new(Logger)
	}
	return singleLogger
}

var (
	logChan_Custom chan ChanLog
)

var (
	logRootPath string
)

func init() {
	logChan_Custom = make(chan ChanLog, 10000)
	singleLogger = new(Logger)
}

func Debug(log string, logTarget string) {
	singleLogger.Log(log, logTarget, "debug")
}

func Info(log string, logTarget string) {
	singleLogger.Log(log, logTarget, "info")
}

func Warn(log string, logTarget string) {
	singleLogger.Log(log, logTarget, "warn")
}

func Error(log string, logTarget string) {
	singleLogger.Log(log, logTarget, "error")
}

func Log(log string, logTarget string, logLevel string) {
	singleLogger.Log(log, logTarget, logLevel)
}

func (logger *Logger) Debug(log string, logTarget string) {
	logger.Log(log, logTarget, "debug")
}

func (logger *Logger) Info(log string, logTarget string) {
	logger.Log(log, logTarget, "info")
}

func (logger *Logger) Warn(log string, logTarget string) {
	logger.Log(log, logTarget, "warn")
}

func (logger *Logger) Error(log string, logTarget string) {
	logger.Log(log, logTarget, "error")
}

func (logger *Logger) Log(log string, logTarget string, logLevel string) {
	chanLog := ChanLog{
		LogTarget: logTarget + "_" + logLevel,
		Content:   log,
	}
	logChan_Custom <- chanLog
}

//开启日志处理器
func StartLogHandler(rootPath string) {
	//设置日志根目录
	logRootPath = rootPath
	if !strings.HasSuffix(logRootPath, "/") {
		logRootPath = logRootPath + "/"
	}
	go handleCustom()
}

//处理日志内部函数
func handleCustom() {
	for {
		log := <-logChan_Custom
		writeLog(log, "custom")
	}
}

func writeLog(chanLog ChanLog, level string) {
	filePath := logRootPath + chanLog.LogTarget
	switch level {
	case "custom":
		filePath = filePath + "_" + time.Now().Format(defaultDateFormatForFileName) + ".log"
		break
	}
	log := time.Now().Format(defaultFullTimeLayout) + " " + chanLog.Content
	writeFile(filePath, log)
}

func writeFile(logFile string, log string) {
	var mode os.FileMode
	flag := syscall.O_RDWR | syscall.O_APPEND | syscall.O_CREAT
	mode = 0666
	logstr := log + "\r\n"
	file, err := os.OpenFile(logFile, flag, mode)
	defer file.Close()
	if err != nil {
		fmt.Println(logFile, err)
		return
	}
	file.WriteString(logstr)
}


text:
<?xml version="1.0" encoding="utf-8"?>
<resources>
  <string name="twoFactorAuth">Tweeledige verifikasie</string>
  <string name="twoFactorHelp">Tweeledige verifikasie voeg nog \'n laag sekuriteit tot jou rekening by.</string>
  <string name="twoFactorApp">Kry \'n toep vir tweeledige verifikasie, byvoorbeeld Google Authenticator vir %1$s of %2$s.</string>
  <string name="scanTheCode">Skandeer die QR kode met die toep.</string>
  <string name="enterPassword">Tik jou wagwoord en die verifikasie kode in, wat deur die toep gegenereer word, om die opstelling te voltooi. Jy sal die verifikasie kode elke keer benodig wat jy inteken.</string>
  <string name="ifYouCannotScanEnterX">As u nie die kode kan skandeer nie, voer die geheime %s in u program in.</string>
  <string name="authenticationCode">Verifikasie kode</string>
  <string name="ifYouLoseAccess">Nem kennis: Indien jy toegang tot jou twee ledige verifikasie kodes verloor, kan jy jou wagwoord herstel via e-pos.</string>
  <string name="enableTwoFactor">Skakel twee-ledige verifikasie aan</string>
  <string name="disableTwoFactor">Skakel tweeledige verifikasie af</string>
  <string name="twoFactorEnabled">Twee-ledige verifikasie aangeskakel</string>
  <string name="twoFactorDisable">Jy benodig jou wagwoord en \'n verifikasie kode van jou verifikasie toep om tweeledige verifikasie af te skakel.
As jy jou toegang tot die verifikasie kodes verloor het, kan jy ook jou wagwoord herstel via e-pos.</string>
  <string name="openTwoFactorApp">Maak die twee-faktor verifikasie toep of jou toestel oop om die verifikasie kode te sien en jou identiteit te bevestig.</string>
</resources>


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

 Copyright 2003 - 2016 The eFaps Team

 Licensed under the Apache License, Version 2.0 (the "License");
 you may not use this file except in compliance with the License.
 You may obtain a copy of the License at

      http://www.apache.org/licenses/LICENSE-2.0

 Unless required by applicable law or agreed to in writing, software
 distributed under the License is distributed on an "AS IS" BASIS,
 WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 See the License for the specific language governing permissions and
 limitations under the License.

-->
<ui-table xmlns="http://www.efaps.org/xsd" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://www.efaps.org/xsd http://www.efaps.org/xsd/eFaps_1.0.xsd">
    <uuid>f3c69c81-b623-4c7f-b6e2-a989d5b1617a</uuid>
    <file-application>eFaps-Kernel</file-application>
    <definition>
        <version-expression>(version==latest)</version-expression>
        <name>Admin_IndexSearchResultFieldKeyTable</name>
        <field name="key">
            <property name="Attribute">Key</property>
            <property name="Label">Admin_IndexSearchResultFieldKey/Key.Label</property>
            <property name="HRef">TREE</property>
        </field>
    </definition>
</ui-table>


text:
Home Address<input type="text" name="simpleForm.homeAddress" />

Work Address<input type="text" name="simpleForm.workAddress" />


text:
<!doctype html>

        <title>Spring intro</title>

        <link rel="stylesheet" href="css/bootstrap/bootstrap.min.css"/>
        <link rel="stylesheet" href="css/stylesheet.css"/>

        w


text:
import Progress from "../../@primitives/UI/progress/ProgressStep";
import Forms from "../../@primitives/UI/forms";

import { Personal, Payment, Billing, Confirm } from "./fieldsets";
import Loading from "./Loading";
import Err from "./Err";
import Success from "./Success";
import { monetize } from "../../../util/format";

type ILayout = {
  back: Function,
  campuses: Object[],
  changeSavedAccount: Function,
  countries: Object[],
  clear: Function,
  clearData: Function,
  give: Object,
  goToAccounts: Function,
  goToStepOne: Function,
  next: Function,
  onSubmit: Function,
  save: Function,
  savedPayments: Object[],
  states: Object[],
};

let copiedSchedules;

const Layout = ({
  back,
  campuses,
  changeSavedAccount,
  countries,
  clear,
  clearData,
  give,
  goToAccounts,
  goToStepOne,
  next,
  onSubmit,
  save,
  savedPayments,
  states,
}: ILayout) => {
  const {
    data,
    url,
    errors,
    transactions,
    schedule,
    total,
    savedAccount,
    state,
    transactionType,
    scheduleToRecover,
  } = give;

  let { step } = give;

  if (!campuses.length) {
    return <Loading isPreparation />;
  }

  if (["loading", "error", "success"].indexOf(state) > -1) {
    switch (state) {
      case "loading":
        copiedSchedules = { ...schedule };
        return <Loading isSchedule={copiedSchedules.start} isSavedPayment={transactionType === "savedPayment"} />;
      case "error":
        return <Err msg={errors[Object.keys(errors)[0]]} goToStepOne={goToStepOne} />;
      case "success":
        return (
          <Success
            total={monetize(total.toFixed(2))}
            email={data.personal.email}
            guest={transactionType === "guest"}
            onClick={goToAccounts}
            schedule={copiedSchedules}
          />
        );
      default:
        return null;
    }
  }

  const FORM_STEPS = [Personal, Billing, Payment, Confirm];

  if (transactionType === "savedPayment") {
    step -= 1;
    if (step === 0) step = 1;
    FORM_STEPS.shift();
  }

  const Step = FORM_STEPS[step - 1];

  return (
    <Forms.Form
      id="give"
      theme="hard"
      fieldsetTheme="flush soft-top@handheld scrollable soft-double-bottom"
      method="POST"
      submit={onSubmit}
    >
      <Step
        back={back}
        campuses={campuses}
        changeSavedAccount={changeSavedAccount}
        clear={clear}
        clearData={clearData}
        countries={countries}
        data={data}
        errors={errors}
        goToStepOne={goToStepOne}
        next={next}
        save={save}
        savedAccount={savedAccount}
        savedAccounts={savedPayments}
        schedule={schedule}
        scheduleToRecover={scheduleToRecover}
        states={states}
        total={total}
        transactions={transactions}
        transactionType={transactionType}
        url={url}
      >
        <Progress
          steps={FORM_STEPS.length}
          active={step}
        />
      </Step>
    </Forms.Form>
  );
};

export default Layout;


text:
World = class("World")

function World:initialize( camera, player )
  self.camera = camera
  self.player = player
  self.entities = { player }
  self.addEntities = {}

  self.camera:setCenterOnEntity( self.player, 200 )

  self.player:start()
end

function World:addEntity( entity )
  table.insert( self.addEntities, entity )
end

function World:iterEntities()
  return ipairs(self.entities)
end

function World:update(dt)
  for i, e in self:iterEntities() do
    e:update(dt)

    if e.remove then
      table.remove( self.entities, i )
    end
  end

  for _, e in ipairs(self.addEntities) do
    table.insert( self.entities, e )
  end

  self.addEntities = {}

  self.camera:update(dt)
end

function World:draw( viewport )
  for _, e in self:iterEntities() do
    self.camera:draw( e, viewport )
  end
end

function World:keypressed(key, isRepeat)
  self.player:keypressed(key, isRepeat)
end

function World:keyreleased(key)
  self.player:keyreleased(key)
end