text:
"""The tests for the Entity component helper."""
# pylint: disable=protected-access
import asyncio
from collections import OrderedDict
import logging
import unittest
from unittest.mock import patch, Mock, MagicMock
from datetime import timedelta

import homeassistant.core as ha
import homeassistant.loader as loader
from homeassistant.exceptions import PlatformNotReady
from homeassistant.components import group
from homeassistant.helpers.entity import Entity, generate_entity_id
from homeassistant.helpers.entity_component import (
    EntityComponent, DEFAULT_SCAN_INTERVAL, SLOW_SETUP_WARNING)
from homeassistant.helpers import entity_component
from homeassistant.setup import setup_component

from homeassistant.helpers import discovery
import homeassistant.util.dt as dt_util

from tests.common import (
    get_test_home_assistant, MockPlatform, MockModule, fire_time_changed,
    mock_coro, async_fire_time_changed)

_LOGGER = logging.getLogger(__name__)
DOMAIN = "test_domain"

class EntityTest(Entity):
    """Test for the Entity component."""

    def __init__(self, **values):
        """Initialize an entity."""
        self._values = values

        if 'entity_id' in values:
            self.entity_id = values['entity_id']

    @property
    def name(self):
        """Return the name of the entity."""
        return self._handle('name')

    @property
    def should_poll(self):
        """Return the ste of the polling."""
        return self._handle('should_poll')

    @property
    def unique_id(self):
        """Return the unique ID of the entity."""
        return self._handle('unique_id')

    @property
    def available(self):
        """Return True if entity is available."""
        return self._handle('available')

    def _handle(self, attr):
        """Helper for the attributes."""
        if attr in self._values:
            return self._values[attr]
        return getattr(super(), attr)

class TestHelpersEntityComponent(unittest.TestCase):
    """Test homeassistant.helpers.entity_component module."""

    def setUp(self):  # pylint: disable=invalid-name
        """Initialize a test Home Assistant instance."""
        self.hass = get_test_home_assistant()

    def tearDown(self):  # pylint: disable=invalid-name
        """Clean up the test Home Assistant instance."""
        self.hass.stop()

    def test_setting_up_group(self):
        """Setup the setting of a group."""
        setup_component(self.hass, 'group', {'group': {}})
        component = EntityComponent(_LOGGER, DOMAIN, self.hass,
                                    group_name='everyone')

        # No group after setup
        assert len(self.hass.states.entity_ids()) == 0

        component.add_entities([EntityTest()])

        # group exists
        assert len(self.hass.states.entity_ids()) == 2
        assert self.hass.states.entity_ids('group') == ['group.everyone']

        group = self.hass.states.get('group.everyone')

        assert group.attributes.get('entity_id') == \
            ('test_domain.unnamed_device',)

        # group extended
        component.add_entities([EntityTest(name='goodbye')])

        assert len(self.hass.states.entity_ids()) == 3
        group = self.hass.states.get('group.everyone')

        # Ordered in order of added to the group
        assert group.attributes.get('entity_id') == \
            ('test_domain.goodbye', 'test_domain.unnamed_device')

    def test_polling_only_updates_entities_it_should_poll(self):
        """Test the polling of only updated entities."""
        component = EntityComponent(
            _LOGGER, DOMAIN, self.hass, timedelta(seconds=20))

        no_poll_ent = EntityTest(should_poll=False)
        no_poll_ent.async_update = Mock()
        poll_ent = EntityTest(should_poll=True)
        poll_ent.async_update = Mock()

        component.add_entities([no_poll_ent, poll_ent])

        no_poll_ent.async_update.reset_mock()
        poll_ent.async_update.reset_mock()

        fire_time_changed(self.hass, dt_util.utcnow() + timedelta(seconds=20))
        self.hass.block_till_done()

        assert not no_poll_ent.async_update.called
        assert poll_ent.async_update.called

    def test_polling_updates_entities_with_exception(self):
        """Test the updated entities that not brake with a exception."""
        component = EntityComponent(
            _LOGGER, DOMAIN, self.hass, timedelta(seconds=20))

        update_ok = []
        update_err = []

        def update_mock():
            """Mock normal update."""
            update_ok.append(None)

        def update_mock_err():
            """Mock error update."""
            update_err.append(None)
            raise AssertionError("Fake error update")

        ent1 = EntityTest(should_poll=True)
        ent1.update = update_mock_err
        ent2 = EntityTest(should_poll=True)
        ent2.update = update_mock
        ent3 = EntityTest(should_poll=True)
        ent3.update = update_mock
        ent4 = EntityTest(should_poll=True)
        ent4.update = update_mock

        component.add_entities([ent1, ent2, ent3, ent4])

        update_ok.clear()
        update_err.clear()

        fire_time_changed(self.hass, dt_util.utcnow() + timedelta(seconds=20))
        self.hass.block_till_done()

        assert len(update_ok) == 3
        assert len(update_err) == 1

    def test_update_state_adds_entities(self):
        """Test if updating poll entities cause an entity to be added works."""
        component = EntityComponent(_LOGGER, DOMAIN, self.hass)

        ent1 = EntityTest()
        ent2 = EntityTest(should_poll=True)

        component.add_entities([ent2])
        assert 1 == len(self.hass.states.entity_ids())
        ent2.update = lambda *_: component.add_entities([ent1])

        fire_time_changed(
            self.hass, dt_util.utcnow() + DEFAULT_SCAN_INTERVAL
        )
        self.hass.block_till_done()

        assert 2 == len(self.hass.states.entity_ids())

    def test_update_state_adds_entities_with_update_befor_add_true(self):
        """Test if call update befor add to state machine."""
        component = EntityComponent(_LOGGER, DOMAIN, self.hass)

        ent = EntityTest()
        ent.update = Mock(spec_set=True)

        component.add_entities([ent], True)
        self.hass.block_till_done()

        assert 1 == len(self.hass.states.entity_ids())
        assert ent.update.called

    def test_update_state_adds_entities_with_update_befor_add_false(self):
        """Test if not call update befor add to state machine."""
        component = EntityComponent(_LOGGER, DOMAIN, self.hass)

        ent = EntityTest()
        ent.update = Mock(spec_set=True)

        component.add_entities([ent], False)
        self.hass.block_till_done()

        assert 1 == len(self.hass.states.entity_ids())
        assert not ent.update.called

    def test_adds_entities_with_update_befor_add_true_deadlock_protect(self):
        """Test if call update befor add to state machine.

        It need to run update inside executor and never call
        async_add_entities with True
        """
        call = []
        component = EntityComponent(_LOGGER, DOMAIN, self.hass)

        @asyncio.coroutine
        def async_add_entities_fake(entities, update_befor_add):
            """Fake add_entities_call."""
            call.append(update_befor_add)
        component._platforms['core'].async_add_entities = \
            async_add_entities_fake

        ent = EntityTest()
        ent.update = Mock(spec_set=True)
        component.add_entities([ent], True)

        assert ent.update.called
        assert len(call) == 1
        assert not call[0]

    def test_not_adding_duplicate_entities(self):
        """Test for not adding duplicate entities."""
        component = EntityComponent(_LOGGER, DOMAIN, self.hass)

        assert 0 == len(self.hass.states.entity_ids())

        component.add_entities([None, EntityTest(unique_id='not_very_unique')])

        assert 1 == len(self.hass.states.entity_ids())

        component.add_entities([EntityTest(unique_id='not_very_unique')])

        assert 1 == len(self.hass.states.entity_ids())

    def test_not_assigning_entity_id_if_prescribes_one(self):
        """Test for not assigning an entity ID."""
        component = EntityComponent(_LOGGER, DOMAIN, self.hass)

        assert 'hello.world' not in self.hass.states.entity_ids()

        component.add_entities([EntityTest(entity_id='hello.world')])

        assert 'hello.world' in self.hass.states.entity_ids()

    def test_extract_from_service_returns_all_if_no_entity_id(self):
        """Test the extraction of everything from service."""
        component = EntityComponent(_LOGGER, DOMAIN, self.hass)
        component.add_entities([
            EntityTest(name='test_1'),
            EntityTest(name='test_2'),
        ])

        call = ha.ServiceCall('test', 'service')

        assert ['test_domain.test_1', 'test_domain.test_2'] == \
            sorted(ent.entity_id for ent in
                   component.extract_from_service(call))

    def test_extract_from_service_filter_out_non_existing_entities(self):
        """Test the extraction of non existing entities from service."""
        component = EntityComponent(_LOGGER, DOMAIN, self.hass)
        component.add_entities([
            EntityTest(name='test_1'),
            EntityTest(name='test_2'),
        ])

        call = ha.ServiceCall('test', 'service', {
            'entity_id': ['test_domain.test_2', 'test_domain.non_exist']
        })

        assert ['test_domain.test_2'] == \
               [ent.entity_id for ent in component.extract_from_service(call)]

    def test_extract_from_service_no_group_expand(self):
        """Test not expanding a group."""
        component = EntityComponent(_LOGGER, DOMAIN, self.hass)
        test_group = group.Group.create_group(
            self.hass, 'test_group', ['light.Ceiling', 'light.Kitchen'])
        component.add_entities([test_group])

        call = ha.ServiceCall('test', 'service', {
            'entity_id': ['group.test_group']
        })

        extracted = component.extract_from_service(call, expand_group=False)
        self.assertEqual([test_group], extracted)

    def test_setup_loads_platforms(self):
        """Test the loading of the platforms."""
        component_setup = Mock(return_value=True)
        platform_setup = Mock(return_value=None)
        loader.set_component(
            'test_component',
            MockModule('test_component', setup=component_setup))
        loader.set_component('test_domain.mod2',
                             MockPlatform(platform_setup, ['test_component']))

        component = EntityComponent(_LOGGER, DOMAIN, self.hass)

        assert not component_setup.called
        assert not platform_setup.called

        component.setup({
            DOMAIN: {
                'platform': 'mod2',
            }
        })

        self.hass.block_till_done()
        assert component_setup.called
        assert platform_setup.called

    def test_setup_recovers_when_setup_raises(self):
        """Test the setup if exceptions are happening."""
        platform1_setup = Mock(side_effect=Exception('Broken'))
        platform2_setup = Mock(return_value=None)

        loader.set_component('test_domain.mod1', MockPlatform(platform1_setup))
        loader.set_component('test_domain.mod2', MockPlatform(platform2_setup))

        component = EntityComponent(_LOGGER, DOMAIN, self.hass)

        assert not platform1_setup.called
        assert not platform2_setup.called

        component.setup(OrderedDict([
            (DOMAIN, {'platform': 'mod1'}),
            ("{} 2".format(DOMAIN), {'platform': 'non_exist'}),
            ("{} 3".format(DOMAIN), {'platform': 'mod2'}),
        ]))

        self.hass.block_till_done()
        assert platform1_setup.called
        assert platform2_setup.called

    @patch('homeassistant.helpers.entity_component.EntityComponent'
           '._async_setup_platform', return_value=mock_coro())
    @patch('homeassistant.setup.async_setup_component',
           return_value=mock_coro(True))
    def test_setup_does_discovery(self, mock_setup_component, mock_setup):
        """Test setup for discovery."""
        component = EntityComponent(_LOGGER, DOMAIN, self.hass)

        component.setup({})

        discovery.load_platform(self.hass, DOMAIN, 'platform_test',
                                {'msg': 'discovery_info'})

        self.hass.block_till_done()

        assert mock_setup.called
        assert ('platform_test', {}, {'msg': 'discovery_info'}) == \
            mock_setup.call_args[0]

    @patch('homeassistant.helpers.entity_component.'
           'async_track_time_interval')
    def test_set_scan_interval_via_config(self, mock_track):
        """Test the setting of the scan interval via configuration."""
        def platform_setup(hass, config, add_devices, discovery_info=None):
            """Test the platform setup."""
            add_devices([EntityTest(should_poll=True)])

        loader.set_component('test_domain.platform',
                             MockPlatform(platform_setup))

        component = EntityComponent(_LOGGER, DOMAIN, self.hass)

        component.setup({
            DOMAIN: {
                'platform': 'platform',
                'scan_interval': timedelta(seconds=30),
            }
        })

        self.hass.block_till_done()
        assert mock_track.called
        assert timedelta(seconds=30) == mock_track.call_args[0][2]

    @patch('homeassistant.helpers.entity_component.'
           'async_track_time_interval')
    def test_set_scan_interval_via_platform(self, mock_track):
        """Test the setting of the scan interval via platform."""
        def platform_setup(hass, config, add_devices, discovery_info=None):
            """Test the platform setup."""
            add_devices([EntityTest(should_poll=True)])

        platform = MockPlatform(platform_setup)
        platform.SCAN_INTERVAL = timedelta(seconds=30)

        loader.set_component('test_domain.platform', platform)

        component = EntityComponent(_LOGGER, DOMAIN, self.hass)

        component.setup({
            DOMAIN: {
                'platform': 'platform',
            }
        })

        self.hass.block_till_done()
        assert mock_track.called
        assert timedelta(seconds=30) == mock_track.call_args[0][2]

    def test_set_entity_namespace_via_config(self):
        """Test setting an entity namespace."""
        def platform_setup(hass, config, add_devices, discovery_info=None):
            """Test the platform setup."""
            add_devices([
                EntityTest(name='beer'),
                EntityTest(name=None),
            ])

        platform = MockPlatform(platform_setup)

        loader.set_component('test_domain.platform', platform)

        component = EntityComponent(_LOGGER, DOMAIN, self.hass)

        component.setup({
            DOMAIN: {
                'platform': 'platform',
                'entity_namespace': 'yummy'
            }
        })

        self.hass.block_till_done()

        assert sorted(self.hass.states.entity_ids()) == \
            ['test_domain.yummy_beer', 'test_domain.yummy_unnamed_device']

    def test_adding_entities_with_generator_and_thread_callback(self):
        """Test generator in add_entities that calls thread method.

        We should make sure we resolve the generator to a list before passing
        it into an async context.
        """
        component = EntityComponent(_LOGGER, DOMAIN, self.hass)

        def create_entity(number):
            """Create entity helper."""
            entity = EntityTest()
            entity.entity_id = generate_entity_id(component.entity_id_format,
                                                  'Number', hass=self.hass)
            return entity

        component.add_entities(create_entity(i) for i in range(2))

@asyncio.coroutine
def test_platform_warn_slow_setup(hass):
    """Warn we log when platform setup takes a long time."""
    platform = MockPlatform()

    loader.set_component('test_domain.platform', platform)

    component = EntityComponent(_LOGGER, DOMAIN, hass)

    with patch.object(hass.loop, 'call_later', MagicMock()) \
            as mock_call:
        yield from component.async_setup({
            DOMAIN: {
                'platform': 'platform',
            }
        })
        assert mock_call.called

        timeout, logger_method = mock_call.mock_calls[0][1][:2]

        assert timeout == SLOW_SETUP_WARNING
        assert logger_method == _LOGGER.warning

        assert mock_call().cancel.called

@asyncio.coroutine
def test_platform_error_slow_setup(hass, caplog):
    """Don't block startup more than SLOW_SETUP_MAX_WAIT."""
    with patch.object(entity_component, 'SLOW_SETUP_MAX_WAIT', 0):
        called = []

        @asyncio.coroutine
        def setup_platform(*args):
            called.append(1)
            yield from asyncio.sleep(1, loop=hass.loop)

        platform = MockPlatform(async_setup_platform=setup_platform)
        component = EntityComponent(_LOGGER, DOMAIN, hass)
        loader.set_component('test_domain.test_platform', platform)
        yield from component.async_setup({
            DOMAIN: {
                'platform': 'test_platform',
            }
        })
        assert len(called) == 1
        assert 'test_domain.test_platform' not in hass.config.components
        assert 'test_platform is taking longer than 0 seconds' in caplog.text

@asyncio.coroutine
def test_extract_from_service_available_device(hass):
    """Test the extraction of entity from service and device is available."""
    component = EntityComponent(_LOGGER, DOMAIN, hass)
    yield from component.async_add_entities([
        EntityTest(name='test_1'),
        EntityTest(name='test_2', available=False),
        EntityTest(name='test_3'),
        EntityTest(name='test_4', available=False),
    ])

    call_1 = ha.ServiceCall('test', 'service')

    assert ['test_domain.test_1', 'test_domain.test_3'] == \
        sorted(ent.entity_id for ent in
               component.async_extract_from_service(call_1))

    call_2 = ha.ServiceCall('test', 'service', data={
        'entity_id': ['test_domain.test_3', 'test_domain.test_4'],
    })

    assert ['test_domain.test_3'] == \
        sorted(ent.entity_id for ent in
               component.async_extract_from_service(call_2))

@asyncio.coroutine
def test_platform_not_ready(hass):
    """Test that we retry when platform not ready."""
    platform1_setup = Mock(side_effect=[PlatformNotReady, PlatformNotReady,
                                        None])
    loader.set_component('test_domain.mod1', MockPlatform(platform1_setup))

    component = EntityComponent(_LOGGER, DOMAIN, hass)

    yield from component.async_setup({
        DOMAIN: {
            'platform': 'mod1'
        }
    })

    assert len(platform1_setup.mock_calls) == 1
    assert 'test_domain.mod1' not in hass.config.components

    utcnow = dt_util.utcnow()

    with patch('homeassistant.util.dt.utcnow', return_value=utcnow):
        # Should not trigger attempt 2
        async_fire_time_changed(hass, utcnow + timedelta(seconds=29))
        yield from hass.async_block_till_done()
        assert len(platform1_setup.mock_calls) == 1

        # Should trigger attempt 2
        async_fire_time_changed(hass, utcnow + timedelta(seconds=30))
        yield from hass.async_block_till_done()
        assert len(platform1_setup.mock_calls) == 2
        assert 'test_domain.mod1' not in hass.config.components

        # This should not trigger attempt 3
        async_fire_time_changed(hass, utcnow + timedelta(seconds=59))
        yield from hass.async_block_till_done()
        assert len(platform1_setup.mock_calls) == 2

        # Trigger attempt 3, which succeeds
        async_fire_time_changed(hass, utcnow + timedelta(seconds=60))
        yield from hass.async_block_till_done()
        assert len(platform1_setup.mock_calls) == 3
        assert 'test_domain.mod1' in hass.config.components


text:
<?php

namespace App\Modules\PushNotificationDevices\Errors;

class PushNotificationDevicesErrors
{

}

redpajama_set_name: RedPajamaGithub


text:
package cli_test

import "fmt"

// PrintUsage can be used to print a listing of available commands.
func ExampleCommandSet_PrintUsage() {
	version := &cli.Command{
		Usage: "version",
		Short: "print the version and exit",
		Run: func([]string) error {
			fmt.Println("1.0.0")
			return nil
		},
	}

	ui := cli.New("example", "")
	ui.Register("version", version)
	ui.PrintUsage("")
}

// PrintUsage can also be used to print the usage text for a command.
func ExampleCommandSet_PrintUsage_command() {
	export := &cli.Command{
		Usage: "export [-v] [-o <outfile>]",
		Short: "export some data",
		Run: func([]string) error {
			fmt.Println("done!")
			return nil
		},
	}
	export.Bool("-v", false, "cause export to be verbose")
	export.String("-o", "", "output to a file")

	ui := cli.New("my_program", "")
	ui.Register("export", export)
	ui.PrintUsage("export")
}


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Server.Maps;
using Server.Network;
using PMU.Sockets;
using Server.Npcs;
using Server.Combat;

namespace Server.AI
{
    public class MapAIProcessingTask
    {
        IMap map;

        public MapAIProcessingTask(IMap map) {
            this.map = map;
        }

        public void ProcessAIThreadPoolCallback(Object state) {
            ProcessAI();
        }

        public void ProcessAI() {
            try {
                TickCount tickCount = Core.GetTickCount();

                PacketHitList packetList = null;
                PacketHitList.MethodStart(ref packetList);
                if (map.IsSaving == false) {

                    // Keys/Other timed tile stuff
                    for (int x = 0; x <= map.MaxX; x++) {
                        for (int y = 0; y <= map.MaxY; y++) {
                            if (map.Tile[x, y] != null) {
                                if (tickCount.Elapsed(map.Tile[x, y].DoorTimer, 5000)) {
                                    if ((map.Tile[x, y].Type == Enums.TileType.Key || map.Tile[x, y].Type == Enums.TileType.Door) && map.Tile[x, y].DoorOpen == true) {
                                        map.Tile[x, y].DoorOpen = false;
                                        packetList.AddPacketToMap(map, TcpPacket.CreatePacket("mapkey", x.ToString(), y.ToString(), "0"));
                                    }
                                }
                            }
                        }
                    }

                    Scripting.ScriptManager.InvokeSub("OnMapTick", map);

                    if (map.ProcessingPaused == false) {

                        int livingNpcs = 0;

                        for (int mapNpcSlot = 0; mapNpcSlot < Constants.MAX_MAP_NPCS; mapNpcSlot++) {
                            int npcNum = map.ActiveNpc[mapNpcSlot].Num;
                            MapNpc mapNpc = map.ActiveNpc[mapNpcSlot];

                            if (npcNum > 0) {
                                livingNpcs++;

                                Npc npc = NpcManager.Npcs[npcNum];

                                if (npc.Behavior != Enums.NpcBehavior.FullyScriptedAI || npc.AIScript == "" || npc.AIScript.ToLower() == "none") {
                                    #region Used for attacking on sight
                                    if (npc.Behavior == Enums.NpcBehavior.AttackOnSight || npc.Behavior == Enums.NpcBehavior.Guard) {
                                        foreach (Client i in map.GetClients()) {
                                            if (i.Player.MapID == map.MapID && map.ActiveNpc[mapNpcSlot].Target == null && !i.Player.Dead
                                                && i.Player.Hunted && map.Tile[i.Player.X, i.Player.Y].Type != Enums.TileType.NPCAvoid && i.Player.Hunted) {
                                                if (MovementProcessor.CanCharacterSeeCharacter(map, map.ActiveNpc[mapNpcSlot], i.Player.GetActiveRecruit())) {
                                                    if (npc.Behavior == Enums.NpcBehavior.AttackOnSight/* || i.Player.PK == true*/) {
                                                        //if (!string.IsNullOrEmpty(npc.AttackSay)) {
                                                        //    packetList.AddPacket(i, PacketBuilder.CreateChatMsg("A " + npc.Name + " : " + npc.AttackSay, Text.Grey));
                                                        //}

                                                        map.ActiveNpc[mapNpcSlot].Target = i;
                                                    }
                                                }
                                            }
                                        }
                                    }
                                    #endregion

                                    #region Used for walking/targetting/picking up items
                                    if (npcNum > 0) {
                                        bool hasNpcWalked;

                                        if (map.ActiveNpc[mapNpcSlot].Target != null && map.ActiveNpc[mapNpcSlot].Target.IsPlaying()
                                            && map.ActiveNpc[mapNpcSlot].Target.Player.MapID == map.MapID
                                            && (map.Tile[map.ActiveNpc[mapNpcSlot].Target.Player.X, map.ActiveNpc[mapNpcSlot].Target.Player.Y].Type == Enums.TileType.NPCAvoid
                                            || !map.ActiveNpc[mapNpcSlot].Target.Player.Hunted || map.ActiveNpc[mapNpcSlot].Target.Player.Dead
                                            || !MovementProcessor.CanCharacterSeeCharacter(map, map.ActiveNpc[mapNpcSlot], map.ActiveNpc[mapNpcSlot].Target.Player.GetActiveRecruit()))) {
                                                map.ActiveNpc[mapNpcSlot].Target = null;
                                        }

                                        Client target = map.ActiveNpc[mapNpcSlot].Target;

                                        if (npc.Behavior != Enums.NpcBehavior.Shopkeeper) {
                                            if (target != null) {
                                                if (target.IsPlaying() && target.Player.MapID == map.MapID) {
                                                    hasNpcWalked = false;
                                                    int dir = Math.Rand(0, 5);

                                                    hasNpcWalked = AIProcessor.MoveNpcInDirection((Enums.Direction)dir, map, target, packetList, mapNpcSlot);
                                                    if (!hasNpcWalked) {
                                                        foreach (Enums.Direction direction in Enum.GetValues(typeof(Enums.Direction))) {
                                                            if (direction != (Enums.Direction)dir) {
                                                                if (AIProcessor.MoveNpcInDirection(direction, map, target, packetList, mapNpcSlot)) {
                                                                    break;
                                                                }
                                                            }
                                                        }
                                                    }

                                                    if (hasNpcWalked == false) {
                                                        if (map.ActiveNpc[mapNpcSlot].X - 1 == target.Player.X && map.ActiveNpc[mapNpcSlot].Y == target.Player.Y) {
                                                            if (map.ActiveNpc[mapNpcSlot].Direction != Enums.Direction.Left) {
                                                                MovementProcessor.ChangeNpcDir(packetList, map, mapNpcSlot, Enums.Direction.Left);
                                                            }
                                                            hasNpcWalked = true;
                                                        }
                                                        if (map.ActiveNpc[mapNpcSlot].X + 1 == target.Player.X && map.ActiveNpc[mapNpcSlot].Y == target.Player.Y) {
                                                            if (map.ActiveNpc[mapNpcSlot].Direction != Enums.Direction.Right) {
                                                                MovementProcessor.ChangeNpcDir(packetList, map, mapNpcSlot, Enums.Direction.Right);
                                                            }
                                                            hasNpcWalked = true;
                                                        }
                                                        if (map.ActiveNpc[mapNpcSlot].X == target.Player.X && map.ActiveNpc[mapNpcSlot].Y - 1 == target.Player.Y) {
                                                            if (map.ActiveNpc[mapNpcSlot].Direction != Enums.Direction.Up) {
                                                                MovementProcessor.ChangeNpcDir(packetList, map, mapNpcSlot, Enums.Direction.Up);
                                                            }
                                                            hasNpcWalked = true;
                                                        }
                                                        if (map.ActiveNpc[mapNpcSlot].X == target.Player.X && map.ActiveNpc[mapNpcSlot].Y + 1 == target.Player.Y) {
                                                            if (map.ActiveNpc[mapNpcSlot].Direction != Enums.Direction.Down) {
                                                                MovementProcessor.ChangeNpcDir(packetList, map, mapNpcSlot, Enums.Direction.Down);
                                                            }
                                                            hasNpcWalked = true;
                                                        }
                                                    }

                                                    if (hasNpcWalked == false) {
                                                        int val = Math.Rand(0, 2);
                                                        if (val == 1) {
                                                            val = Math.Rand(0, 4);
                                                            if (MovementProcessor.CanNpcMove(map, mapNpcSlot, (Enums.Direction)val)) {
                                                                MovementProcessor.NpcMove(packetList, map, mapNpcSlot, map.ActiveNpc[mapNpcSlot].Direction, Enums.Speed.Walking);
                                                            }
                                                        }
                                                    }
                                                } else {
                                                    map.ActiveNpc[mapNpcSlot].Target = null;
                                                }
                                            } else {
                                                int shouldWalk = Math.Rand(0, 2);
                                                if (npc.Behavior != Enums.NpcBehavior.Friendly) {
                                                    for (int i = 0; i < Constants.MAX_MAP_ITEMS; i++) {
                                                        if (map.ActiveItem[i].X == map.ActiveNpc[mapNpcSlot].X && map.ActiveItem[i].Y == map.ActiveNpc[mapNpcSlot].Y
                                                            && map.ActiveItem[i].Num > -1 && map.ActiveNpc[mapNpcSlot].HeldItem == null) {
                                                            map.ActiveNpc[mapNpcSlot].MapGetItem();
                                                            shouldWalk = 1;
                                                        }
                                                    }
                                                } else if (npc.Behavior == Enums.NpcBehavior.Friendly) {
                                                    foreach (Client i in map.GetClients()) {
                                                        if (i.Player.X >= map.ActiveNpc[mapNpcSlot].X - 1 && i.Player.X <= map.ActiveNpc[mapNpcSlot].X + 1 &&
                                                            i.Player.Y >= map.ActiveNpc[mapNpcSlot].Y - 1 && i.Player.Y <= map.ActiveNpc[mapNpcSlot].Y + 1) {
                                                                shouldWalk = Math.Rand(0, 10);
                                                                break;
                                                        }
                                                    }
                                                }
                                                if (shouldWalk == 0) {
                                                    shouldWalk = Math.Rand(0, 5);
                                                    if (MovementProcessor.CanNpcMove(map, mapNpcSlot, (Enums.Direction)shouldWalk)) {
                                                        MovementProcessor.NpcMove(packetList, map, mapNpcSlot, map.ActiveNpc[mapNpcSlot].Direction, Enums.Speed.Walking);
                                                    }
                                                }
                                            }
                                        }
                                    }

                                    #endregion

                                    #region Used for attacking players

                                    if (npcNum > 0) {
                                        Client target = map.ActiveNpc[mapNpcSlot].Target;
                                        if (target != null) {
                                            if (target.IsPlaying() && target.Player.MapID == map.MapID) {
                                                // Make sure npcs dont attack more then once a second
                                                if (Core.GetTickCount().Elapsed(map.ActiveNpc[mapNpcSlot].AttackTimer, 1000)) {

                                                    int usableMoveCount = 0;
                                                    for (int i = 0; i < mapNpc.Moves.Length; i++) {
                                                        if (mapNpc.Moves[i].MoveNum > -1 && mapNpc.Moves[i].CurrentPP > 0) {
                                                            usableMoveCount++;
                                                        }
                                                    }
                                                    if (usableMoveCount == 0) {
                                                        if (BattleProcessor.ShouldUseMove(map, mapNpc, -1)) {
                                                            mapNpc.UseMove(-1);
                                                        }
                                                    } else {
                                                        // Try to use a move, up to 50 times
                                                        for (int i = 0; i < 50; i++) {
                                                            int moveSlotToUse = Server.Math.Rand(0, 5) - 1;
                                                            if (moveSlotToUse == -1) {
                                                                // A standard attack
                                                                if (BattleProcessor.ShouldUseMove(map, mapNpc, moveSlotToUse)) {
                                                                    mapNpc.UseMove(moveSlotToUse);
                                                                    break;
                                                                }
                                                            } else {
                                                                if (mapNpc.Moves[moveSlotToUse].MoveNum > -1 && mapNpc.Moves[moveSlotToUse].CurrentPP > 0) {
                                                                    // Use a move
                                                                    if (BattleProcessor.ShouldUseMove(map, mapNpc, moveSlotToUse)) {
                                                                        mapNpc.UseMove(moveSlotToUse);
                                                                        break;
                                                                    }
                                                                }
                                                            }
                                                        }
                                                    }

                                                }
                                            } else {
                                                map.ActiveNpc[mapNpcSlot].Target = null;
                                            }
                                        }
                                    }

                                    #endregion

                                    if (npcNum > 0 && map.ActiveNpc[mapNpcSlot].HPChanged) {
                                        map.ActiveNpc[mapNpcSlot].SendHPToMap(packetList, map, mapNpcSlot);
                                    }
                                } else {
                                    // Scripted AI: Reimplement?
                                    //Globals.AIScriptManager.CallAIProcessSub(NpcManager.Npcs[map.Npc[x].NpcNum].AIScript, tickCount, map.MapNum, x);
                                }
                            }
                        }
                        //try and spawn something
                        if (map.NpcSpawnWait == null) {
                            map.NpcSpawnWait = Core.GetTickCount();
                        }
                        if (Core.GetTickCount().Tick > map.NpcSpawnWait.Tick) {
                            if (livingNpcs < map.MaxNpcs) {
                                map.SpawnNpc(true);
                            }
                            map.NpcSpawnWait = new TickCount(map.NpcSpawnWait.Tick + map.NpcSpawnTime * 1000);
                        }
                    }
                }
                //lock (MapManager.ActiveMapLockObject) {
                bool shouldRemove = false;
                if (map.PlayersOnMap.Count == 0 && tickCount.Elapsed(map.ActivationTime, AIProcessor.MapTTL)) {
                    if (map.IsProcessingComplete()) {
                        shouldRemove = true;

                        for (int i = 1; i < 9; i++) {

                            IMap borderingMap = MapManager.RetrieveActiveBorderingMap(map, (Enums.MapID)i);
                            if (borderingMap != null) {
                                if (borderingMap.PlayersOnMap.Count > 0) {
                                    shouldRemove = false;
                                }
                            }
                        }

                        if (shouldRemove) {
                            MapManager.rwLock.EnterWriteLock();
                            try {
                                if (map.MapType == Enums.MapType.House) {
                                    // Only save the map here when logging out - otherwise, the map is saved when the player is saved
                                    map.Save();
                                }
                                if ((map.MapType == Enums.MapType.RDungeonMap || map.MapType == Enums.MapType.Instanced)) {
                                    using (Database.DatabaseConnection dbConnection = new Database.DatabaseConnection(Database.DatabaseID.Data)) {
                                        if (MapManager.GetTotalPlayersOnMap(dbConnection, map.MapID) == 0) {
                                            DataManager.Maps.MapDataManager.DeleteMap(dbConnection.Database, map.MapID);
                                        } else {
                                            map.Save();
                                        }
                                    }
                                }

                                MapManager.UnsafeRemoveActiveMap(map.MapID);

                            } finally {
                                MapManager.rwLock.ExitWriteLock();
                            }
                        }
                    }
                }
                //}

                PacketHitList.MethodEnded(ref packetList);
            } catch (Exception ex) {
                Server.Exceptions.ErrorLogger.WriteToErrorLog(ex, "MapAIProcessor");
            }
        }
    }
}


text:
export as namespace SimpleBar;
export = SimpleBar;

declare namespace SimpleBar {
    interface KnownClassNamesOptions {
        contentEl?: string;
        contentWrapper?: string;
        offset?: string;
        mask?: string;
        wrapper?: string;
        placeholder?: string;
        scrollbar?: string;
        track?: string;
        heightAutoObserverWrapperEl?: string;
        heightAutoObserverEl?: string;
        visible?: string;
        horizontal?: string;
        vertical?: string;
        hover?: string;
        dragging?: string;
    }

    type ClassNamesOptions = KnownClassNamesOptions & {
        [className: string]: string;
    };

    interface Options {
        autoHide?: boolean;
        classNames?: ClassNamesOptions;
        forceVisible?: boolean | 'x' | 'y';
        direction?: 'rtl' | 'ltr';
        timeout?: number;
        clickOnTrack?: boolean;
        scrollbarMinSize?: number;
        scrollbarMaxSize?: number;
    }
}

declare class SimpleBar {
    static removeObserver(): void;
    static instances: Pick<WeakMap<HTMLElement, SimpleBar>, 'get' | 'has'>;

    constructor(element: HTMLElement, options?: SimpleBar.Options);

    recalculate(): void;
    getScrollElement(): HTMLElement;
    getContentElement(): HTMLElement;
    unMount(): void;

    el: HTMLElement;
}


text:
<?php

namespace app\models;

use Yii;

/**
 * This is the model class for table "admin_user".
 *
 * @property integer $id
 * @property string $username
 * @property string $password
 */
class AdminUser extends \yii\db\ActiveRecord
{
    /**
     * @inheritdoc
     */
    public static function tableName()
    {
        return 'admin_user';
    }

    /**
     * @inheritdoc
     */
    public function rules()
    {
        return [
            [['username', 'password'], 'required'],
            [['username', 'password'], 'string', 'max' => 255]
        ];
    }

    /**
     * @inheritdoc
     */
    public function attributeLabels()
    {
        return [
            'id' => Yii::t('app', 'ID'),
            'username' => Yii::t('app', 'Username'),
            'password' => Yii::t('app', 'Password'),
        ];
    }
}


text:
var template="";
template += "";
template += "
";
template += "";
template += "    ";
template += "
<\/div>";
template += "";
template += "    ";
template += "
";
template += "";
template += "        ";
template += "
";
template += "
<\/div>";
template += "
<\/div>";
template += "
<\/div>";
template += "        <\/div>";
template += "";
template += "        ";
template += "
";
template += "";
template += "
";
template += "";
template += "                ";
template += "";
template += "
<\/div>";
template += "";
template += "                <button class=\"pswp__button pswp__button--close\" title=\"Close (Esc)\"><\/button>";
template += "";
template += "                <button class=\"pswp__button pswp__button--share\" title=\"Share\"><\/button>";
template += "";
template += "                <button class=\"pswp__button pswp__button--fs\" title=\"Toggle fullscreen\"><\/button>";
template += "";
template += "                <button class=\"pswp__button pswp__button--zoom\" title=\"Zoom in\/out\"><\/button>";
template += "";
template += "                ";
template += "                ";
template += "
";
template += "
";
template += "
";
template += "
<\/div>";
template += "                      <\/div>";
template += "                    <\/div>";
template += "                <\/div>";
template += "            <\/div>";
template += "";
template += "
";
template += "
<\/div> ";
template += "            <\/div>";
template += "";
template += "            <button class=\"pswp__button pswp__button--arrow--left\" title=\"Previous (arrow left)\">";
template += "            <\/button>";
template += "";
template += "            <button class=\"pswp__button pswp__button--arrow--right\" title=\"Next (arrow right)\">";
template += "            <\/button>";
template += "";
template += "
";
template += "
<\/div>";
template += "            <\/div>";
template += "";
template += "        <\/div>";
template += "";
template += "    <\/div>";
template += "";
template += "<\/div>";

export { template };


text:
// Copyright 2010 University of Helsinki
//
//  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.

#if HAVE_CONFIG_H
#  include <config.h>
#endif

#include "ospell.h"

namespace hfst_ospell {

int nByte_utf8(unsigned char c)
{
    /* utility function to determine how many bytes to peel off as
       a utf-8 character for representing as unknown symbol */
    if (c <= 127) {
        return 1;
    } else if ( (c & (128 + 64 + 32 + 16)) == (128 + 64 + 32 + 16) ) {
        return 4;
    } else if ( (c & (128 + 64 + 32 )) == (128 + 64 + 32) ) {
        return 3;
    } else if ( (c & (128 + 64 )) == (128 + 64)) {
        return 2;
    } else {
        return 0;
    }
}

void WeightQueue::push(Weight w)
{
    for (WeightQueue::iterator it = begin(); it != end(); ++it) {
        if (*it > w) {
            insert(it, w);
            return;
        }
    }
    push_back(w);
}

void WeightQueue::pop(void)
{
    pop_back();
}

Weight WeightQueue::get_lowest(void) const
{
    if (size() == 0) {
        return std::numeric_limits<Weight>::max();
    }
    return front();
}

Weight WeightQueue::get_highest(void) const
{
    if (size() == 0) {
        return std::numeric_limits<Weight>::max();
    }
    return back();
}

Transducer::Transducer(FILE* f):
    header(TransducerHeader(f)),
    alphabet(TransducerAlphabet(f, header.symbol_count())),
    keys(alphabet.get_key_table()),
    encoder(keys,header.input_symbol_count()),
    indices(f,header.index_table_size()),
    transitions(f,header.target_table_size())
    {}

Transducer::Transducer(char* raw):
    header(TransducerHeader(&raw)),
    alphabet(TransducerAlphabet(&raw, header.symbol_count())),
    keys(alphabet.get_key_table()),
    encoder(keys,header.input_symbol_count()),
    indices(&raw,header.index_table_size()),
    transitions(&raw,header.target_table_size())
    {}

TreeNode TreeNode::update_lexicon(SymbolNumber symbol,
                                  TransitionTableIndex next_lexicon,
                                  Weight weight)
{
    SymbolVector str(this->string);
    if (symbol != 0) {
        str.push_back(symbol);
    }
    return TreeNode(str,
                    this->input_state,
                    this->mutator_state,
                    next_lexicon,
                    this->flag_state,
                    this->weight + weight);
}

TreeNode TreeNode::update_mutator(TransitionTableIndex next_mutator,
                                  Weight weight)
{
    return TreeNode(this->string,
                    this->input_state,
                    next_mutator,
                    this->lexicon_state,
                    this->flag_state,
                    this->weight + weight);
}

TreeNode TreeNode::update(SymbolNumber symbol,
                          unsigned int next_input,
                          TransitionTableIndex next_mutator,
                          TransitionTableIndex next_lexicon,
                          Weight weight)
{
    SymbolVector str(this->string);
    if (symbol != 0) {
        str.push_back(symbol);
    }
    return TreeNode(str,
                    next_input,
                    next_mutator,
                    next_lexicon,
                    this->flag_state,
                    this->weight + weight);
}

TreeNode TreeNode::update(SymbolNumber symbol,
                          TransitionTableIndex next_mutator,
                          TransitionTableIndex next_lexicon,
                          Weight weight)
{
    SymbolVector str(this->string);
    if (symbol != 0) {
        str.push_back(symbol);
    }
    return TreeNode(str,
                    this->input_state,
                    next_mutator,
                    next_lexicon,
                    this->flag_state,
                    this->weight + weight);
}

bool TreeNode::try_compatible_with(FlagDiacriticOperation op)
{
    switch (op.Operation()) {

    case P: // positive set
        flag_state[op.Feature()] = op.Value();
        return true;

    case N: // negative set (literally, in this implementation)
        flag_state[op.Feature()] = -1*op.Value();
        return true;

    case R: // require
        if (op.Value() == 0) { // "plain" require, return false if unset
            return (flag_state[op.Feature()] != 0);
        }
        return (flag_state[op.Feature()] == op.Value());

    case D: // disallow
        if (op.Value() == 0) { // "plain" disallow, return true if unset
            return (flag_state[op.Feature()] == 0);
        }
        return (flag_state[op.Feature()] != op.Value());

    case C: // clear
        flag_state[op.Feature()] = 0;
        return true;

    case U: // unification
        /* if the feature is unset OR the feature is to this value already OR
           the feature is negatively set to something else than this value */
        if (flag_state[op.Feature()] == 0 ||
            flag_state[op.Feature()] == op.Value() ||
            (flag_state[op.Feature()] < 0 &&
             (flag_state[op.Feature()] * -1 != op.Value()))
            ) {
            flag_state[op.Feature()] = op.Value();
            return true;
        }
        return false;
    }

    return false; // to make the compiler happy
}

Speller::Speller(Transducer* mutator_ptr, Transducer* lexicon_ptr):
        mutator(mutator_ptr),
        lexicon(lexicon_ptr),
        input(),
        queue(TreeNodeQueue()),
        next_node(FlagDiacriticState(get_state_size(), 0)),
        limit(std::numeric_limits<Weight>::max()),
        alphabet_translator(SymbolVector()),
        operations(lexicon->get_operations()),
        limiting(None),
        mode(Correct),
        max_time(-1.0),
        start_clock(0),
        call_counter(0),
        limit_reached(false)
            {
                if (mutator != NULL) {
                    build_alphabet_translator();
                    cache = std::vector<CacheContainer>(
                        mutator->get_key_table()->size(), CacheContainer());
                }
            }

SymbolNumber
Speller::get_state_size()
{
    return static_cast<SymbolNumber>(lexicon->get_state_size());
}

void Speller::lexicon_epsilons(void)
{
    if (!lexicon->has_epsilons_or_flags(next_node.lexicon_state + 1)) {
        return;
    }
    TransitionTableIndex next = lexicon->next(next_node.lexicon_state, 0);
    STransition i_s = lexicon->take_epsilons_and_flags(next);

    while (i_s.symbol != NO_SYMBOL) {
        if (is_under_weight_limit(next_node.weight + i_s.weight)) {
            if (lexicon->transitions.input_symbol(next) == 0) {
                queue.push_back(next_node.update_lexicon((mode == Correct) ? 0 : i_s.symbol,
                                                         i_s.index,
                                                         i_s.weight));
            } else {
                FlagDiacriticState old_flags = next_node.flag_state;
                if (next_node.try_compatible_with( // this is terrible
                        operations->operator[](
                            lexicon->transitions.input_symbol(next)))) {
                    queue.push_back(next_node.update_lexicon(0,
                                                             i_s.index,
                                                             i_s.weight));
                    next_node.flag_state = old_flags;
                }
            }
        }
        ++next;
        i_s = lexicon->take_epsilons_and_flags(next);
    }
}

void Speller::lexicon_consume(void)
{
    unsigned int input_state = next_node.input_state;
    if (input_state >= input.size()) {
        // no more input
        return;
    }
    SymbolNumber this_input;
    if (mutator != NULL && mode != Check) {
        this_input = alphabet_translator[input[input_state]];
    } else {
        // To support zhfst spellers without error models, we allow
        // for the case with plain lexicon symbols
        this_input = input[input_state];
    }
    if(!lexicon->has_transitions(
           next_node.lexicon_state + 1, this_input)) {
        // we have no regular transitions for this
        if (this_input >= lexicon->get_alphabet()->get_orig_symbol_count()) {
            // this input was not originally in the alphabet, so unknown or identity
            // may apply
            if (lexicon->get_unknown() != NO_SYMBOL &&
                lexicon->has_transitions(next_node.lexicon_state + 1,
                                         lexicon->get_unknown())) {
                queue_lexicon_arcs(lexicon->get_unknown(),
                                   next_node.mutator_state,
                                   0.0, 1);
            }
            if (lexicon->get_identity() != NO_SYMBOL &&
                lexicon->has_transitions(next_node.lexicon_state + 1,
                                         lexicon->get_identity())) {
                queue_lexicon_arcs(lexicon->get_identity(),
                                   next_node.mutator_state,
                                   0.0, 1);
            }
        }
        return;
    }
    queue_lexicon_arcs(this_input,
                       next_node.mutator_state, 0.0, 1);
}

void Speller::queue_lexicon_arcs(SymbolNumber input_sym,
                                 unsigned int mutator_state,
                                 Weight mutator_weight,
                                 int input_increment)
{
    TransitionTableIndex next = lexicon->next(next_node.lexicon_state,
                                              input_sym);
    STransition i_s = lexicon->take_non_epsilons(next, input_sym);
    while (i_s.symbol != NO_SYMBOL) {
        if (i_s.symbol == lexicon->get_identity()) {
            i_s.symbol = input[next_node.input_state];
        }
        if (is_under_weight_limit(next_node.weight + i_s.weight + mutator_weight)) {
            queue.push_back(next_node.update(
                                (mode == Correct) ? input_sym : i_s.symbol,
                                next_node.input_state + input_increment,
                                mutator_state,
                                i_s.index,
                                i_s.weight + mutator_weight));
        }
        ++next;
        i_s = lexicon->take_non_epsilons(next, input_sym);
    }
}

void Speller::mutator_epsilons(void)
{
    if (!mutator->has_transitions(next_node.mutator_state + 1, 0)) {
        return;
    }
    TransitionTableIndex next_m = mutator->next(next_node.mutator_state, 0);
    STransition mutator_i_s = mutator->take_epsilons(next_m);

    while (mutator_i_s.symbol != NO_SYMBOL) {
        if (mutator_i_s.symbol == 0) {
            if (is_under_weight_limit(
                    next_node.weight + mutator_i_s.weight)) {
                queue.push_back(next_node.update_mutator(mutator_i_s.index,
                                                         mutator_i_s.weight));
            }
            ++next_m;
            mutator_i_s = mutator->take_epsilons(next_m);
            continue;
        } else if (!lexicon->has_transitions(
                       next_node.lexicon_state + 1,
                       alphabet_translator[mutator_i_s.symbol])) {
            // we have no regular transitions for this
            if (alphabet_translator[mutator_i_s.symbol] >= lexicon->get_alphabet()->get_orig_symbol_count()) {
                // this input was not originally in the alphabet, so unknown or identity
                // may apply
                if (lexicon->get_unknown() != NO_SYMBOL &&
                    lexicon->has_transitions(next_node.lexicon_state + 1,
                                             lexicon->get_unknown())) {
                    queue_lexicon_arcs(lexicon->get_unknown(),
                                       mutator_i_s.index, mutator_i_s.weight);
                }
                if (lexicon->get_identity() != NO_SYMBOL &&
                    lexicon->has_transitions(next_node.lexicon_state + 1,
                                             lexicon->get_identity())) {
                    queue_lexicon_arcs(lexicon->get_identity(),
                                       mutator_i_s.index, mutator_i_s.weight);
                }
            }
            ++next_m;
            mutator_i_s = mutator->take_epsilons(next_m);
            continue;
        }
        queue_lexicon_arcs(alphabet_translator[mutator_i_s.symbol],
                           mutator_i_s.index, mutator_i_s.weight);
        ++next_m;
        mutator_i_s = mutator->take_epsilons(next_m);
    }
}

bool Speller::is_under_weight_limit(Weight w) const
{
    if (limiting == Nbest) {
        return w < limit;
    }
    return w <= limit;
}

void Speller::consume_input()
{
    if (next_node.input_state >= input.size()) {
        return; // not enough input to consume
    }
    SymbolNumber input_sym = input[next_node.input_state];
    if (!mutator->has_transitions(next_node.mutator_state + 1,
                                  input_sym)) {
        // we have no regular transitions for this
        if (input_sym >= mutator->get_alphabet()->get_orig_symbol_count()) {
            // this input was not originally in the alphabet, so unknown or identity
            // may apply
            if (mutator->get_identity() != NO_SYMBOL &&
                mutator->has_transitions(next_node.mutator_state + 1,
                                         mutator->get_identity())) {
                queue_mutator_arcs(mutator->get_identity());
            }
            if (mutator->get_unknown() != NO_SYMBOL &&
                mutator->has_transitions(next_node.mutator_state + 1,
                                         mutator->get_unknown())) {
                queue_mutator_arcs(mutator->get_unknown());
            }
        }
    } else {
        queue_mutator_arcs(input_sym);
    }
}

void Speller::queue_mutator_arcs(SymbolNumber input_sym)
{
    TransitionTableIndex next_m = mutator->next(next_node.mutator_state,
                                                input_sym);
    STransition mutator_i_s = mutator->take_non_epsilons(next_m,
                                                         input_sym);
    while (mutator_i_s.symbol != NO_SYMBOL) {
        if (mutator_i_s.symbol == 0) {
            if (is_under_weight_limit(
                    next_node.weight + mutator_i_s.weight)) {
                queue.push_back(next_node.update(0, next_node.input_state + 1,
                                                 mutator_i_s.index,
                                                 next_node.lexicon_state,
                                                 mutator_i_s.weight));
            }
            ++next_m;
            mutator_i_s = mutator->take_non_epsilons(next_m, input_sym);
            continue;
        } else if (!lexicon->has_transitions(
                    next_node.lexicon_state + 1,
                    alphabet_translator[mutator_i_s.symbol])) {
                // we have no regular transitions for this
                if (alphabet_translator[mutator_i_s.symbol] >= lexicon->get_alphabet()->get_orig_symbol_count()) {
                    // this input was not originally in the alphabet, so unknown or identity
                    // may apply
                    if (lexicon->get_unknown() != NO_SYMBOL &&
                        lexicon->has_transitions(next_node.lexicon_state + 1,
                                                 lexicon->get_unknown())) {
                        queue_lexicon_arcs(lexicon->get_unknown(),
                                           mutator_i_s.index, mutator_i_s.weight, 1);
                    }
                    if (lexicon->get_identity() != NO_SYMBOL &&
                        lexicon->has_transitions(next_node.lexicon_state + 1,
                                                 lexicon->get_identity())) {
                        queue_lexicon_arcs(lexicon->get_identity(),
                                           mutator_i_s.index, mutator_i_s.weight, 1);
                    }
                }
                ++next_m;
                mutator_i_s = mutator->take_non_epsilons(next_m, input_sym);
                continue;
        }
        queue_lexicon_arcs(alphabet_translator[mutator_i_s.symbol],
                           mutator_i_s.index, mutator_i_s.weight, 1);
        ++next_m;
        mutator_i_s = mutator->take_non_epsilons(next_m,
                                                 input_sym);
    }
}

bool Transducer::initialize_input_vector(SymbolVector & input_vector,
                                         Encoder * encoder,
                                         char * line)
{
    input_vector.clear();
    char ** inpointer = &line;
    while (**inpointer != '\0') {
        SymbolNumber k = encoder->find_key(inpointer);
        if (k == NO_SYMBOL) { // no tokenization from alphabet
            // for real handling of other and identity for unseen symbols,
            // use the Speller interface analyse()!
            return false;
        }
        input_vector.push_back(k);
    }
    return true;
}

AnalysisQueue Transducer::lookup(char * line)
{
    std::map<std::string, Weight> outputs;
    AnalysisQueue analyses;
    SymbolVector input;
    TreeNodeQueue queue;
    if (!initialize_input_vector(input, &encoder, line)) {
        return analyses;
    }
    TreeNode start_node(FlagDiacriticState(get_state_size(), 0));
    queue.assign(1, start_node);

    while (queue.size() > 0) {
        TreeNode next_node = queue.back();
        queue.pop_back();

        // Final states
        if (next_node.input_state == input.size() &&
            is_final(next_node.lexicon_state)) {
            Weight weight = next_node.weight +
                final_weight(next_node.lexicon_state);
            std::string output = stringify(get_key_table(),
                                           next_node.string);
            /* if the result is novel or lower weighted than before, insert it */
            if (outputs.count(output) == 0 ||
                outputs[output] > weight) {
                outputs[output] = weight;
            }
        }

        TransitionTableIndex next_index;
        // epsilon loop
        if (has_epsilons_or_flags(next_node.lexicon_state + 1)) {
            next_index = next(next_node.lexicon_state, 0);
            STransition i_s = take_epsilons_and_flags(next_index);
            while (i_s.symbol != NO_SYMBOL) {
                if (transitions.input_symbol(next_index) == 0) {
                    queue.push_back(next_node.update_lexicon(i_s.symbol,
                                                             i_s.index,
                                                             i_s.weight));
                    // Not a true epsilon but a flag diacritic
                } else {
                    FlagDiacriticState old_flags = next_node.flag_state;
                    if (next_node.try_compatible_with(
                            get_operations()->operator[](
                                transitions.input_symbol(next_index)))) {
                        queue.push_back(next_node.update_lexicon(i_s.symbol,
                                                                 i_s.index,
                                                                 i_s.weight));
                        next_node.flag_state = old_flags;
                    }
                }
                ++next_index;
                i_s = take_epsilons_and_flags(next_index);
            }
        }

        // input consumption loop
        unsigned int input_state = next_node.input_state;
        if (input_state < input.size() &&
            has_transitions(
                next_node.lexicon_state + 1, input[input_state])) {

            next_index = next(next_node.lexicon_state,
                              input[input_state]);
            STransition i_s = take_non_epsilons(next_index,
                                                input[input_state]);

            while (i_s.symbol != NO_SYMBOL) {
                queue.push_back(next_node.update(
                                    i_s.symbol,
                                    input_state + 1,
                                    next_node.mutator_state,
                                    i_s.index,
                                    i_s.weight));

                ++next_index;
                i_s = take_non_epsilons(next_index, input[input_state]);
            }
        }

    }

    for (auto& it : outputs) {
        analyses.push(StringWeightPair(it.first, it.second));
    }

    return analyses;
}

bool
Transducer::final_transition(TransitionTableIndex i)
{
    return transitions.final(i);
}

bool
Transducer::final_index(TransitionTableIndex i)
{
    return indices.final(i);
}

KeyTable*
Transducer::get_key_table()
{
    return keys;
}

SymbolNumber
Transducer::find_next_key(char** p)
{
    return encoder.find_key(p);
}

Encoder*
Transducer::get_encoder()
{
    return &encoder;
}

unsigned int
Transducer::get_state_size()
{
    return alphabet.get_state_size();
}

SymbolNumber
Transducer::get_unknown() const
{
    return alphabet.get_unknown();
}

SymbolNumber
Transducer::get_identity() const
{
    return alphabet.get_identity();
}

TransducerAlphabet*
Transducer::get_alphabet()
{
    return &alphabet;
}

OperationMap*
Transducer::get_operations()
{
    return alphabet.get_operation_map();
}

TransitionTableIndex Transducer::next(const TransitionTableIndex i,
                                      const SymbolNumber symbol) const
{
    if (i >= TARGET_TABLE) {
        return i - TARGET_TABLE + 1;
    } else {
        return indices.target(i+1+symbol) - TARGET_TABLE;
    }
}

bool Transducer::has_transitions(const TransitionTableIndex i,
                                 const SymbolNumber symbol) const
{
    if (symbol == NO_SYMBOL) {
        return false;
    }
    if (i >= TARGET_TABLE) {
        return (transitions.input_symbol(i - TARGET_TABLE) == symbol);
    } else {
        return (indices.input_symbol(i+symbol) == symbol);
    }
}

bool Transducer::has_epsilons_or_flags(const TransitionTableIndex i)
{
    if (i >= TARGET_TABLE) {
        return(transitions.input_symbol(i - TARGET_TABLE) == 0||
               is_flag(transitions.input_symbol(i - TARGET_TABLE)));
    } else {
        return (indices.input_symbol(i) == 0);
    }
}

bool Transducer::has_non_epsilons_or_flags(const TransitionTableIndex i)
{
    if (i >= TARGET_TABLE) {
        SymbolNumber this_input = transitions.input_symbol(i - TARGET_TABLE);
        return((this_input != 0 && this_input != NO_SYMBOL) &&
               !is_flag(this_input));
    } else {
        SymbolNumber max_symbol = static_cast<SymbolNumber>(get_key_table()->size());
        for (SymbolNumber sym = 1; sym < max_symbol; ++sym) {
            if (indices.input_symbol(i + sym) == sym) {
                return true;
            }
        }
        return false;
    }
}

STransition Transducer::take_epsilons(const TransitionTableIndex i) const
{
    if (transitions.input_symbol(i) != 0) {
        return STransition(0, NO_SYMBOL);
    }
    return STransition(transitions.target(i),
                       transitions.output_symbol(i),
                       transitions.weight(i));
}

STransition Transducer::take_epsilons_and_flags(const TransitionTableIndex i)
{
    if (transitions.input_symbol(i) != 0 &&
        !is_flag(transitions.input_symbol(i))) {
        return STransition(0, NO_SYMBOL);
    }
    return STransition(transitions.target(i),
                       transitions.output_symbol(i),
                       transitions.weight(i));
}

STransition Transducer::take_non_epsilons(const TransitionTableIndex i,
                                          const SymbolNumber symbol) const
{
    if (transitions.input_symbol(i) != symbol) {
        return STransition(0, NO_SYMBOL);
    }
    return STransition(transitions.target(i),
                       transitions.output_symbol(i),
                       transitions.weight(i));
}

bool Transducer::is_final(const TransitionTableIndex i)
{
    if (i >= TARGET_TABLE) {
        return final_transition(i - TARGET_TABLE);
    } else {
        return final_index(i);
    }
}

Weight Transducer::final_weight(const TransitionTableIndex i) const
{
    if (i >= TARGET_TABLE) {
        return transitions.weight(i - TARGET_TABLE);
    } else {
        return indices.final_weight(i);
    }
}

bool
Transducer::is_flag(const SymbolNumber symbol)
{
    return alphabet.is_flag(symbol);
}

bool
Transducer::is_weighted(void)
{
    return header.probe_flag(Weighted);
}

AnalysisQueue Speller::analyse(char * line, int nbest)
{
    (void)nbest;
    mode = Lookup;
    if (!init_input(line)) {
        return AnalysisQueue();
    }
    std::map<std::string, Weight> outputs;
    AnalysisQueue analyses;
    TreeNode start_node(FlagDiacriticState(get_state_size(), 0));
    queue.assign(1, start_node);
    while (queue.size() > 0) {
        next_node = queue.back();
        queue.pop_back();
        // Final states
        if (next_node.input_state == input.size() &&
            lexicon->is_final(next_node.lexicon_state)) {
            Weight weight = next_node.weight +
                lexicon->final_weight(next_node.lexicon_state);
            std::string output = stringify(lexicon->get_key_table(),
                                           next_node.string);
            /* if the result is novel or lower weighted than before, insert it */
            if (outputs.count(output) == 0 ||
                outputs[output] > weight) {
                outputs[output] = weight;
            }
        }
        lexicon_epsilons();
        lexicon_consume();
    }

    for (auto& it : outputs) {
        analyses.push(StringWeightPair(it.first, it.second));
    }
    return analyses;
}

AnalysisSymbolsQueue Speller::analyseSymbols(char * line, int nbest)
{
    (void)nbest;
    mode = Lookup;
    if (!init_input(line)) {
        return AnalysisSymbolsQueue();
    }
    std::map<std::vector<std::string>, Weight> outputs;
    AnalysisSymbolsQueue analyses;
    TreeNode start_node(FlagDiacriticState(get_state_size(), 0));
    queue.assign(1, start_node);
    while (queue.size() > 0) {
        next_node = queue.back();
        queue.pop_back();
        // Final states
        if (next_node.input_state == input.size() &&
            lexicon->is_final(next_node.lexicon_state)) {
            Weight weight = next_node.weight +
                lexicon->final_weight(next_node.lexicon_state);
            std::vector<std::string> output = symbolify(lexicon->get_key_table(),
                                                        next_node.string);
            /* if the result is novel or lower weighted than before, insert it */
            if (outputs.count(output) == 0 ||
                outputs[output] > weight) {
                outputs[output] = weight;
            }
        }
        lexicon_epsilons();
        lexicon_consume();
    }

    for (auto& it : outputs) {
        analyses.push(SymbolsWeightPair(it.first, it.second));
    }
    return analyses;
}

void Speller::build_cache(SymbolNumber first_sym)
{
    TreeNode start_node(FlagDiacriticState(get_state_size(), 0));
    queue.assign(1, start_node);
    limit = std::numeric_limits<Weight>::max();
    // A placeholding map, only one weight per correction
    StringWeightMap corrections_len_0;
    StringWeightMap corrections_len_1;
    while (queue.size() > 0) {
        next_node = queue.back();
        queue.pop_back();
        lexicon_epsilons();
        mutator_epsilons();
        if (mutator->is_final(next_node.mutator_state) &&
            lexicon->is_final(next_node.lexicon_state)) {
            // complete result of length 0 or 1
            Weight weight = next_node.weight +
                lexicon->final_weight(next_node.lexicon_state) +
                mutator->final_weight(next_node.mutator_state);
            std::string string = stringify(lexicon->get_key_table(), next_node.string);
            /* if the correction is novel or better than before, insert it
             */
            if (next_node.input_state == 0) {
                if (corrections_len_0.count(string) == 0 ||
                    corrections_len_0[string] > weight) {
                    corrections_len_0[string] = weight;
                }
            } else {
                if (corrections_len_1.count(string) == 0 ||
                    corrections_len_1[string] > weight) {
                    corrections_len_1[string] = weight;
                }
            }
        }
        if (next_node.input_state == 1) {
            cache[first_sym].nodes.push_back(next_node);
        } else {
//            std::cerr << "discarded node\n";
        }
        if (first_sym > 0 && next_node.input_state == 0) {
            consume_input();
        }
    }
    cache[first_sym].results_len_0.assign(corrections_len_0.begin(), corrections_len_0.end());
    cache[first_sym].results_len_1.assign(corrections_len_1.begin(), corrections_len_1.end());
    cache[first_sym].empty = false;
}

CorrectionQueue Speller::correct(char * line, int nbest,
                                 Weight maxweight, Weight beam,
                                 float time_cutoff)
{
    mode = Correct;
    // if input initialization fails, return empty correction queue
    if (!init_input(line)) {
        return CorrectionQueue();
    }
    max_time = 0.0;
    if (time_cutoff > 0.0) {
        max_time = time_cutoff;
        start_clock = clock();
        call_counter = 0;
        limit_reached = false;
    }
    set_limiting_behaviour(nbest, maxweight, beam);
    nbest_queue = WeightQueue();
    // The queue for our suggestions
    CorrectionQueue correction_queue;
    // A placeholding map, only one weight per correction
    std::map<std::string, Weight> corrections;
    SymbolNumber first_input = (input.size() == 0) ? 0 : input[0];
    if (cache[first_input].empty) {
        build_cache(first_input); // XXX: cache corrupts limit!
    }
    if (input.size() <= 1) {
        // get the cached results and we're done
        StringWeightVector * results;
        if (input.size() == 0) {
            results = &cache[first_input].results_len_0;
        } else {
            results = &cache[first_input].results_len_1;
        }
        for(auto& it : *results) {
              // First get the correct weight limit
                best_suggestion = std::min(best_suggestion, it.second);
                if (nbest > 0) {
                    nbest_queue.push(it.second);
                    if (nbest_queue.size() > nbest) {
                        nbest_queue.pop();
                    }
                }
            }
        set_limiting_behaviour(nbest, maxweight, beam);
        adjust_weight_limits(nbest, beam);
        for(auto& it : *results) {
              // Then collect the results
            if (it.second <= limit && (nbest == 0 || // we either don't have an nbest condition or
                                        (it.second <= nbest_queue.get_highest() && // we're below the worst nbest weight and
                                         correction_queue.size() < nbest &&
                                         nbest_queue.size() > 0))) { // number of results
                correction_queue.push(StringWeightPair(it.first, it.second));
                if (nbest != 0) {
                    nbest_queue.pop();
                }
            }
        }
        return correction_queue;
    } else {
        // populate the tree node queue
        queue.assign(cache[first_input].nodes.begin(), cache[first_input].nodes.end());
    }
    // TreeNode start_node(FlagDiacriticState(get_state_size(), 0));
    // queue.assign(1, start_node);

    while (queue.size() > 0) {
        // Have we spent too much time?
        if (max_time > 0.0) {
            ++call_counter;
            if (limit_reached ||
                (call_counter % 1000000 == 0 &&
                 (((double)(clock() - start_clock)) / CLOCKS_PER_SEC) > max_time)) {
                limit_reached = true;
                break;
            }
        }
        /*
          For depth-first searching, we save the back node now, remove it
          from the queue and add new nodes to the search at the back.
        */
        next_node = queue.back();
        queue.pop_back();
        set_limiting_behaviour(nbest, maxweight, beam); // XXX: need to reset
        adjust_weight_limits(nbest, beam);
        // if we can't get an acceptable result, never mind
        if (next_node.weight > limit) {
            continue;
        }
        if (next_node.input_state > 1) {
            // Early epsilons were handled during the caching stage
            lexicon_epsilons();
            mutator_epsilons();
        }
        if (next_node.input_state == input.size()) {
            /* if our transducers are in final states
             * we generate the correction
             */
            if (!mutator->is_final(next_node.mutator_state)) {
            }
            if (!lexicon->is_final(next_node.lexicon_state)) {
            }
            if (mutator->is_final(next_node.mutator_state) &&
                lexicon->is_final(next_node.lexicon_state)) {
                Weight weight = next_node.weight +
                    lexicon->final_weight(next_node.lexicon_state) +
                    mutator->final_weight(next_node.mutator_state);
                if (weight > limit) {
                    continue;
                }
                std::string string = stringify(lexicon->get_key_table(), next_node.string);
                /* if the correction is novel or better than before, insert it
                 */
                if (corrections.count(string) == 0 ||
                    corrections[string] > weight) {
                    corrections[string] = weight;
                    best_suggestion = std::min(best_suggestion, weight);
                    if (nbest > 0) {
                        nbest_queue.push(weight);
                        if (nbest_queue.size() > nbest) {
                            nbest_queue.pop();
                        }
                    }
                }
            }
        } else {
            consume_input();
        }
    }
    adjust_weight_limits(nbest, beam);

    for (auto& it : corrections) {
        if (it.second <= limit && // we're not over our weight limit and
            (nbest == 0 || // we either don't have an nbest condition or
             (it.second <= nbest_queue.get_highest() && // we're below the worst nbest weight and
              correction_queue.size() < nbest &&
              nbest_queue.size() > 0))) { // number of results
            correction_queue.push(StringWeightPair(it.first, it.second));
            if (nbest != 0) {
                nbest_queue.pop();
            }
        }
    }
    //cache[first_input].clear();
    return correction_queue;
}

void Speller::set_limiting_behaviour(int nbest, Weight maxweight, Weight beam)
{
    limiting = None;
    limit = std::numeric_limits<Weight>::max();
    best_suggestion = std::numeric_limits<Weight>::max();
    if (maxweight >= 0.0 && nbest > 0 && beam >= 0.0) {
        limiting = MaxWeightNbestBeam;
        limit = maxweight;
    } else if (maxweight >= 0.0 && nbest > 0 && beam < 0.0) {
        limiting = MaxWeightNbest;
        limit = maxweight;
    } else if (maxweight >= 0.0 && beam >= 0.0 && nbest == 0) {
        limiting = MaxWeightBeam;
        limit = maxweight;
    } else if (maxweight < 0.0 && nbest > 0 && beam >= 0.0) {
        limiting = NbestBeam;
    } else if (maxweight >= 0.0 && nbest == 0 && beam < 0.0) {
        limiting = MaxWeight;
        limit = maxweight;
    } else if (maxweight < 0.0 && nbest > 0 && beam < 0.0) {
        limiting = Nbest;
    } else if (maxweight < 0.0 && nbest == 0 && beam >= 0.0) {
        limiting = Beam;
    } else {
        return;
    }
}

void Speller::adjust_weight_limits(int nbest, Weight beam)
{
    if (limiting == MaxWeight) {
        return;
    } else if (limiting == Nbest && nbest_queue.size() >= nbest) {
        limit = nbest_queue.get_highest();
    } else if (limiting == MaxWeightNbest && nbest_queue.size() >= nbest) {
        limit = std::min(limit, nbest_queue.get_lowest());
    } else if (limiting == Beam && best_suggestion < std::numeric_limits<Weight>::max()) {
        limit = best_suggestion + beam;
    } else if (limiting == NbestBeam) {
        if (best_suggestion < std::numeric_limits<Weight>::max()) {
            if (nbest_queue.size() >= nbest) {
                limit = std::min(best_suggestion + beam, nbest_queue.get_lowest());
            } else {
                limit = best_suggestion + beam;
            }
        }
    } else if (limiting == MaxWeightBeam) {
        if (best_suggestion < std::numeric_limits<Weight>::max()) {
            limit = std::min(best_suggestion + beam, limit);
        }
    } else if (limiting == MaxWeightNbestBeam) {
        if (best_suggestion < std::numeric_limits<Weight>::max()) {
            limit = std::min(limit, best_suggestion + beam);
        }
        if (nbest_queue.size() >= nbest) {
            limit = std::min(limit, nbest_queue.get_lowest());
        }
    }
}

bool Speller::check(char * line)
{
    mode = Check;
    if (!init_input(line)) {
        return false;
    }
    TreeNode start_node(FlagDiacriticState(get_state_size(), 0));
    queue.assign(1, start_node);
    limit = std::numeric_limits<Weight>::max();

    while (queue.size() > 0) {
        next_node = queue.back();
        queue.pop_back();
        if (next_node.input_state == input.size() &&
            lexicon->is_final(next_node.lexicon_state)) {
            return true;
        }
        lexicon_epsilons();
        lexicon_consume();
    }
    return false;
}

std::string stringify(KeyTable * key_table,
                      SymbolVector & symbol_vector)
{
    std::string s;
    for (auto& it : symbol_vector) {
        if (it < key_table->size()) {
            s.append(key_table->at(it));
        }
    }
    return s;
}

std::vector<std::string> symbolify(KeyTable * key_table,
                                   SymbolVector & symbol_vector)
{
    std::vector<std::string> s;
    for (auto& it : symbol_vector) {
        if (it < key_table->size()) {
            s.push_back(key_table->at(it));
        }
    }
    return s;
}

void Speller::build_alphabet_translator(void)
{
    TransducerAlphabet * from = mutator->get_alphabet();
    TransducerAlphabet * to = lexicon->get_alphabet();
    KeyTable * from_keys = from->get_key_table();
    StringSymbolMap * to_symbols = to->get_string_to_symbol();
    alphabet_translator.push_back(0); // zeroth element is always epsilon
    for (SymbolNumber i = 1; i < from_keys->size(); ++i) {
        if (to_symbols->count(from_keys->operator[](i)) != 1) {
            // A symbol in the error source isn't present in the
            // lexicon, so we add it.
            std::string sym = from_keys->operator[](i);
            SymbolNumber lexicon_key = static_cast<SymbolNumber>(lexicon->get_key_table()->size());
            lexicon->get_encoder()->read_input_symbol(sym, lexicon_key);
            lexicon->get_alphabet()->add_symbol(sym);
            alphabet_translator.push_back(lexicon_key);
            continue;
        }
        // translator at i points to lexicon's symbol for mutator's string for
        // mutator's symbol number i
        alphabet_translator.push_back(
            to_symbols->operator[](
                from_keys->operator[](i)));
    }
}

bool Speller::init_input(char * line)
{
    // Initialize the symbol vector to the tokenization given by encoder.
    // In the case of tokenization failure, valid utf-8 characters
    // are tokenized as unknown and tokenization is reattempted from
    // such a character onwards. The empty string is tokenized as an
    // empty vector; there is no end marker.
    input.clear();
    SymbolNumber k = NO_SYMBOL;
    char ** inpointer = &line;
    char * oldpointer;

    while (**inpointer != '\0') {
        oldpointer = *inpointer;
        if (mutator != NULL && mode != Check) {
            k = mutator->get_encoder()->find_key(inpointer);
        } else {
            k = lexicon->get_encoder()->find_key(inpointer);
        }
        if (k == NO_SYMBOL) { // no tokenization from alphabet
            int bytes_to_tokenize = nByte_utf8(static_cast<unsigned char>(*oldpointer));
            if (bytes_to_tokenize == 0) {
                return false; // can't parse utf-8 character, admit failure
            } else {
                char new_symbol[5]; // max size plus NUL
                memcpy(new_symbol, oldpointer, bytes_to_tokenize);
                new_symbol[bytes_to_tokenize] = '\0';
                std::string new_symbol_string(new_symbol);
                oldpointer += bytes_to_tokenize;
                *inpointer = oldpointer;
                cache.push_back(CacheContainer());
                if (!lexicon->get_alphabet()->has_string(new_symbol_string)) {
                    lexicon->get_alphabet()->add_symbol(new_symbol_string);
                }
                SymbolNumber k_lexicon = lexicon->get_alphabet()->get_string_to_symbol()
                    ->operator[](new_symbol_string);
                lexicon->get_encoder()->read_input_symbol(new_symbol, k_lexicon);
                if (mutator != NULL) {
                    if (!mutator->get_alphabet()->has_string(new_symbol_string)) {
                        mutator->get_alphabet()->add_symbol(new_symbol_string);
                    }
                    k = mutator->get_alphabet()->get_string_to_symbol()->
                        operator[](new_symbol_string);
                    mutator->get_encoder()->read_input_symbol(new_symbol, k);
                    if (k >= alphabet_translator.size()) {
                        add_symbol_to_alphabet_translator(k_lexicon);
                    }
                }
                input.push_back(k);
                continue;
            }
        } else {
            input.push_back(k);
        }
    }
    return true;
}

void Speller::add_symbol_to_alphabet_translator(SymbolNumber to_sym)
{
    alphabet_translator.push_back(to_sym);
}

} // namespace hfst_ospell

char*
hfst_strndup(const char* s, size_t n)
  {
    char* rv = static_cast<char*>(malloc(sizeof(char)*n+1));
    if (rv == NULL)
      {
          return rv;
      }
    rv = static_cast<char*>(memcpy(rv, s, n));
    if (rv == NULL)
      {
        return rv;
      }
    rv[n] = '\0';
    return rv;
  }


text:
export class LoginController {

    constructor($rootScope, airyUser) {
        this._airyUser = airyUser;

        this.password = '';

        $rootScope.title = 'Login';
    }

    loginUser() {
        this._airyUser.login(this.password);
    }
}


text:
package main

import (
	"github.com/levenlabs/postmaster/ga"
	_ "github.com/levenlabs/postmaster/rpc"
	_ "github.com/levenlabs/postmaster/webhook"
)

func main() {
	ga.GA.APIMode()
}


text:
#ifdef  NNXX_SOCKET_H
#ifndef NNXX_SOCKET_HPP
#define NNXX_SOCKET_HPP

namespace nnxx {

  template < typename T >
  void socket::setopt(int level, int option, const T &val)
  { setopt(level, option, &val, sizeof(val)); }

  template < typename T >
  void socket::getopt(int level, int option, T &val) const
  {
    size_t len = sizeof(val);
    getopt(level, option, &val, &len);
  }

  template < typename T >
  T socket::getopt(int level, int option) const
  {
    T optval;
    getopt(level, option, optval);
    return optval;
  }

}

#endif // NNXX_SOCKET_HPP
#endif // NNXX_SOCKET_H

#if defined(NNXX_SOCKET_H) && defined(NNXX_MESSAGE_H)
#ifndef NNXX_SOCKET_MESSAGE
#define NNXX_SOCKET_MESSAGE

#include <iterator>

namespace nnxx {

  template < typename T >
  T socket::recv(int flags, message_control &ctl)
  {
    using std::begin;
    using std::end;
    const auto msg = this->recv(flags, ctl);
    return T{ begin(msg), end(msg) };
  }

  template < typename T >
  T socket::recv(int flags)
  {
    using std::begin;
    using std::end;
    const auto msg = this->recv(flags);
    return T{ begin(msg), end(msg) };
  }

  template < typename T >
  int socket::send(const T &obj, int flags, message_control &&ctl)
  { return send(make_message(obj), flags, ctl); }

  template < typename T >
  int socket::send(const T &obj, int flags)
  { return send(make_message(obj), flags); }

}

#endif // NNXX_SOCKET_MESSAGE
#endif // NNXX_SOCKET_H && NNXX_MESSAGE_H


text:
<?xml version="1.0" encoding="UTF-8"?>
<project name="master" default="none">

	<import file="build-template.xml"/>

	<!--
		Use this file to provide your workspace-specific tasks. Several examples follow.

		Note: make sure that all defined targets depends on the template.init target.

		1. To execute tasks before/after compilation:

		<target name="compile" depends="template.init">
			<echo message="This task executed before compilation..."/>
			<antcall target="template.compile"/>
			<echo message="This task executed AFTER compilation."/>
		</target>

		2. Insert a build target:

		<target name="build" dependencies="template.init,template.build, findbugs"/>
		<target name="findbugs">
			...
		</target>
	-->

</project>


text:
typedef NS_ENUM(NSUInteger, LDKDrawerMode)
{
    LDKDrawerModeOneThird,
    LDKDrawerModeTwoThirds,
    LDKDrawerModeThreeThirds
};

typedef NS_ENUM(NSUInteger, LDKAccordionSectionType)
{
    LDKAccordionSectionTypeCollapsableView,
    LDKAccordionSectionTypeFixedView,
    LDKAccordionSectionTypeNavigation
};

#endif


text:
namespace Songhay.StudioFloor.Shared.Models
{
    /// <summary>
    /// Defines selected App Members
    /// </summary>
    public interface IApp
    {
        /// <summary>
        /// Gets or sets a value indicating whether App should close on Dispatcher exception.
        /// </summary>
        /// <value>
        /// <c>true</c> if App should close on Dispatcher exception; otherwise, <c>false</c>.
        /// </value>
        bool ShouldCloseOnDispatcherException { get; set; }
    }
}


text:
commandArray = {}
subject = 'Domoticz - Alarm activation'
body = ''
siren = 'Sirène'
alarmSwitchFrontDoor = 'Alarme porte entrée'

if (globalvariables['Security'] ~= 'Disarmed') then
    body = 'Alarm was correctly armed'
else
    body = 'Alarm was correctly disarmed'
    -- Ensure to deactivate the Siren and related devices
    commandArray[siren] = 'Off'
    commandArray[alarmSwitchFrontDoor] = 'Off'
end

commandArray['SendNotification'] = subject .. '#' .. body .. '#0#spacealarm'

return commandArray


text:
namespace Vurdalakov
{
    using System;
    using System.Runtime.InteropServices;

    public static class MarshalEx
    {
        public static Byte[] AllocateBytesForStruct<T>() where T : struct
        {
            return new byte[Marshal.SizeOf(typeof(T))];
        }

        public static Byte[] StructToBytes<T>(T structure) where T : struct
        {
            var bytes = AllocateBytesForStruct<T>();

            var handle = GCHandle.Alloc(bytes, GCHandleType.Pinned);

            try
            {
                var pinned = handle.AddrOfPinnedObject();
                Marshal.StructureToPtr(structure, pinned, false);

                return bytes;
            }
            finally
            {
                handle.Free();
            }
        }

        public static T BytesToStruct<T>(Byte[] bytes) where T : struct
        {
            var handle = GCHandle.Alloc(bytes, GCHandleType.Pinned);

            try
            {
                var pinned = handle.AddrOfPinnedObject();
                return (T)Marshal.PtrToStructure(pinned, typeof(T));
            }
            finally
            {
                handle.Free();
            }
        }

        public static T BytesToStruct<T>(Byte[] bytes, Int32 startIndex, Int32 length) where T : struct
        {
            var partial = new Byte[length];
            Array.Copy(bytes, startIndex, partial, 0, length);

            return BytesToStruct<T>(partial);
        }
    }
}


text:
package com.amazonaws.services.simpleworkflow.flow.worker;

import java.util.concurrent.TimeUnit;

public interface TaskPoller {

    boolean pollAndProcessSingleTask() throws Exception;

    void shutdown();

    void shutdownNow();

    boolean awaitTermination(long left, TimeUnit milliseconds) throws InterruptedException;

}


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading.Tasks;

namespace Cognito.StripeClient
{
	internal sealed class Response
	{
		public string Content { get; set; }

		public HttpStatusCode StatusCode { get; set; }

		public string StatusMessage { get; set; }

		public bool IsSuccessStatusCode { get { return StatusCode == HttpStatusCode.OK; } }
	}
}


text:
describe('emp', function() {
  it('exists', function() {
    emp.should.exist;
  });
});


text:
package com.simonellistonball.nifi.OpenCV;

import java.util.List;

import org.apache.nifi.util.MockFlowFile;
import org.apache.nifi.util.TestRunner;
import org.apache.nifi.util.TestRunners;
import org.junit.Before;
import org.junit.Test;

import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.*;

public class GetCameraFrameProcessorTest {

	private TestRunner testRunner;

	@Before
	public void init() {
		testRunner = TestRunners.newTestRunner(GetCameraFrame.class);
	}

	@Test
	public void testProcessor() {
		testRunner.run();
		testRunner.assertAllFlowFilesTransferred(GetCameraFrame.REL_SUCCESS);
		List<MockFlowFile> flowFilesForRelationship = testRunner.getFlowFilesForRelationship(GetCameraFrame.REL_SUCCESS);
		for (MockFlowFile flowFile: flowFilesForRelationship) {
			Long length = flowFile.getSize();
			assertThat(length, greaterThan(100*1024L));
		}
	}

}


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace ThermostatLib
{
    public class HttpdHandlers:List<HttpdHandler>
    {
    }
}


text:
{% extends "admin/base_site.html" %}
{% block content_title %}

Elastic Search - Admin View

{% endblock %}

{% block extrastyle %}
  {{ block.super }}

{% endblock %}

{% block content %}

    Page last rendered: {{ now }} {{ settings.TIME_ZONE }}
    {% if outstanding_records %}
      (Auto-refreshing every 30 seconds)

    {% endif %}

  {% if error_messages %}

Errors

      {% for msg in error_messages %}

          {{ msg }}

      {% endfor %}

  {% endif %}

  {% if outstanding_records %}

{{ outstanding_records|length }} Outstanding indexing tasks

        Refresh page

            batchid :: name
            status
            creation time
            start time
            end time
            delta
            message

          {% for record in outstanding_records %}

              {{ record.batch_id }} :: {{ record.name }}
              {{ record.get_status_display }}
              {{ record.creation_time }}
              {{ record.start_time }}
              {{ record.end_time }}

                {% if record.start_time and record.end_time %}
                  ({{ record.delta }})
                {% endif %}

              {{ record.message }}

          {% endfor %}

  {% endif %}

Settings and details

      Settings at the time this page was loaded:

ES_URLS	{{ settings.ES_URLS }}

ES_INDEX_PREFIX	{{ settings.ES_INDEX_PREFIX }}

ES_INDEXES	{{ settings.ES_INDEXES }}

Elasticsearch version	{{ es_deets.version.number }}

Index Status

      All indexes available:

        index name
        total documents in index

        {% for index_name, index_count in indexes %}

            {{ index_name }}	{{ index_count }}

              {% if index_name == index %}
                IN USE
              {% endif %}

        {% endfor %}

Index ({{ index }})

    {% if mapping_type_stats == None %}

        Index does not exist.

    {% else %}

          mapping type
          count

          {% for stats_name, stats_count in mapping_type_stats.items %}

{{ stats_name }}	{{ stats_count }}

          {% endfor %}

    {% endif %}

Reindex

    {% if outstanding_records %}

        WARNING! There are outstanding index tasks! Don't launch another
        indexing pass unless you really know you want to.

    {% endif %}

Reindex into existing index

      This reindexes into the existing index. Don't do this if you've
      made mapping changes since this will not recreate the index with
      the new mappings.

    <form method="POST">
      {% csrf_token %}
      <input type="submit" name="reindex"
             value="index into {{ index }}"
             {% if outstanding_records %}disabled{% endif %}>
    </form>

Delete existing index, recreate it and index everything

      This DELETES the existing index, recreates it
      with the mappings, and indexes into the new index.

    <form method="POST">
      {% csrf_token %}
      <input class="DANGER" type="submit" name="recreate_reindex"
             value="DELETE index and index into {{ index }}"
             {% if outstanding_records %}disabled{% endif %}>
    </form>

Mark outstanding records as failed

      This marks outstanding records as fail. This allows you to run a
      new reindexing pass.

    <form method="POST">
      {% csrf_token %}
      <input type="hidden" name="reset" value="1">
      <input type="submit" name="reset"
             value="Mark records as failed">
    </form>

Reindexing history

          batchid :: name
          status
          creation time
          start time
          end time
          delta
          message

        {% for record in recent_records %}

            {{ record.batch_id }} :: {{ record.name }}
            {{ record.get_status_display }}
            {{ record.creation_time }}
            {{ record.start_time }}
            {{ record.end_time }}

              {% if record.start_time and record.end_time %}
                ({{ record.delta }})
              {% endif %}

            {{ record.message }}

        {% endfor %}

{% endblock %}