text:
from wtforms.fields import BooleanField, IntegerField
from wtforms.validators import NumberRange

from indico.core import signals
from indico.core.plugins import IndicoPlugin, PluginCategory
from indico.web.forms.base import IndicoForm
from indico.web.forms.fields import MultipleItemsField
from indico.web.forms.widgets import SwitchWidget

from indico_livesync import _
from indico_livesync.blueprint import blueprint
from indico_livesync.cli import cli
from indico_livesync.controllers import extend_plugin_details
from indico_livesync.handler import connect_signals

class SettingsForm(IndicoForm):
    queue_entry_ttl = IntegerField(_('Queue entry TTL'), [NumberRange(min=0)],
                                   description=_("How many days should processed entries be kept in the queue. "
                                                 "The time counts from the creation of the queue entries, so if the "
                                                 "LiveSync task is not running for some time, queue entries may be "
                                                 "deleted during the next run after processing them. Setting it to 0 "
                                                 "disables automatic deletion."))
    excluded_categories = MultipleItemsField(_('Excluded categories'),
                                             fields=[{'id': 'id', 'caption': _("Category ID"), 'required': True}],
                                             description=_("Changes to objects inside these categories or any of their "
                                                           "subcategories are excluded."))
    disable_queue_runs = BooleanField(_('Disable queue runs'), widget=SwitchWidget(),
                                      description=_('Disable all scheduled queue runs.'))
    skip_category_changes = BooleanField(_('Skip category changes'), widget=SwitchWidget(),
                                         description=_('Skip category changes when processing the queue. This can be '
                                                       'useful in large instances when there are significant changes '
                                                       'to large categories in order to avoid processing those '
                                                       'immediately.'))

class LiveSyncPlugin(IndicoPlugin):
    """LiveSync

    Provides the basic LiveSync functionality.
    Only useful if a livesync agent plugin is installed, too.
    """
    configurable = True
    settings_form = SettingsForm
    default_settings = {'excluded_categories': [],
                        'queue_entry_ttl': 0,
                        'disable_queue_runs': False,
                        'skip_category_changes': False}
    category = PluginCategory.synchronization

    def init(self):
        super().init()
        self.backend_classes = {}
        connect_signals(self)
        self.connect(signals.plugin.cli, self._extend_indico_cli)
        self.template_hook('plugin-details', self._extend_plugin_details)

    def get_blueprints(self):
        return blueprint

    def _extend_indico_cli(self, sender, **kwargs):
        return cli

    def register_backend_class(self, name, backend_class):
        if name in self.backend_classes:
            raise RuntimeError(f'Duplicate livesync backend: {name}')
        self.backend_classes[name] = backend_class

    def _extend_plugin_details(self, plugin, **kwargs):
        if plugin == self:
            return extend_plugin_details()


text:
package org.gradle.api.internal.artifacts.dsl;

import org.gradle.api.IllegalDependencyNotation;
import org.gradle.api.InvalidUserDataException;
import org.gradle.api.artifacts.ModuleVersionSelector;
import org.gradle.api.internal.artifacts.DefaultModuleIdentifier;
import org.gradle.internal.exceptions.DiagnosticsVisitor;
import org.gradle.internal.typeconversion.MapKey;
import org.gradle.internal.typeconversion.MapNotationConverter;
import org.gradle.internal.typeconversion.NotationConvertResult;
import org.gradle.internal.typeconversion.NotationConverter;
import org.gradle.internal.typeconversion.NotationParser;
import org.gradle.internal.typeconversion.NotationParserBuilder;
import org.gradle.internal.typeconversion.TypeConversionException;

import java.util.Set;

import static org.gradle.api.internal.artifacts.DefaultModuleVersionSelector.newSelector;

public class ModuleVersionSelectorParsers {

    private static final NotationParserBuilder<Object, ModuleVersionSelector> BUILDER = NotationParserBuilder
            .toType(ModuleVersionSelector.class)
            .fromCharSequence(new StringConverter())
            .converter(new MapConverter());

    public static NotationParser<Object, Set<ModuleVersionSelector>> multiParser() {
        return builder().toFlatteningComposite();
    }

    public static NotationParser<Object, ModuleVersionSelector> parser() {
        return builder().toComposite();
    }

    private static NotationParserBuilder<Object, ModuleVersionSelector> builder() {
        return BUILDER;
    }

    static class MapConverter extends MapNotationConverter<ModuleVersionSelector> {
        @Override
        public void describe(DiagnosticsVisitor visitor) {
            visitor.candidate("Maps").example("[group: 'org.gradle', name:'gradle-core', version: '1.0']");
        }

        protected ModuleVersionSelector parseMap(@MapKey("group") String group, @MapKey("name") String name, @MapKey("version") String version) {
            return newSelector(DefaultModuleIdentifier.newId(group, name), version);
        }
    }

    static class StringConverter implements NotationConverter<String, ModuleVersionSelector> {
        @Override
        public void describe(DiagnosticsVisitor visitor) {
            visitor.candidate("String or CharSequence values").example("'org.gradle:gradle-core:1.0'");
        }

        public void convert(String notation, NotationConvertResult<? super ModuleVersionSelector> result) throws TypeConversionException {
            ParsedModuleStringNotation parsed;
            try {
                parsed = new ParsedModuleStringNotation(notation, null);
            } catch (IllegalDependencyNotation e) {
                throw new InvalidUserDataException(
                        "Invalid format: '" + notation + "'. The correct notation is a 3-part group:name:version notation, "
                                + "e.g: 'org.gradle:gradle-core:1.0'");
            }

            if (parsed.getGroup() == null || parsed.getName() == null || parsed.getVersion() == null) {
                throw new InvalidUserDataException(
                        "Invalid format: '" + notation + "'. Group, name and version cannot be empty. Correct example: "
                                + "'org.gradle:gradle-core:1.0'");
            }
            result.converted(newSelector(DefaultModuleIdentifier.newId(parsed.getGroup(), parsed.getName()), parsed.getVersion()));
        }
    }
}

redpajama_set_name: RedPajamaGithub


text:
using UnityEngine;
using System;
using System.Collections;
using UnityEngine.SceneManagement;

public class GameOverSceneStarter : MonoBehaviour {

	public PriorityQueue priorityQueue;
	public PriorityQueue waitList;

	public BudgetCounter budgetCounter;
	public WelfareCounter welfareCounter;
	public Timer timer;
	public MapController mapController;
	public MapEventProcessor mapEventProcessor;
	public DockUtilizationCounter dockUtilizationCounter;

	public VistaLightsLogger logger;

	// Use this for initialization
	void Start () {

	}

	void Awake() {
		logger = GameObject.Find("BasicLoggerManager").GetComponent<VistaLightsLogger>();
	}

	// Update is called once per frame
	void Update () {
		bool shouldGameEnd = false;
		if (IsEndTimeReached ()) {
			shouldGameEnd = true;
		} else if (IsAllEventProcessed ()) {
			shouldGameEnd = true;
		} else if (IsWelfareZero ()) {
			// shouldGameEnd = true;
		}

		if (shouldGameEnd) {
			LoadGameOverScene ();
		}

	}

	void LoadGameOverScene() {
		timer.Speed = 0;
		budgetCounter.freeze = true;
		welfareCounter.freeze = true;

		logger.EndRun (budgetCounter.money, welfareCounter.Welfare,
			dockUtilizationCounter.CalculateAverageUtilization());

		SceneManager.LoadScene("GameOver", LoadSceneMode.Single);
    }

	private bool IsEndTimeReached() {
		DateTime currentTime = timer.VirtualTime;
		DateTime gameEndTime = mapController.Map.EndTime;
		return currentTime >= gameEndTime;
	}

	private bool IsAllEventProcessed() {
		// FIXME(Yifan): Check if oil is cleaned here
		if (mapEventProcessor.MapEvents.Count == 0 &&
			priorityQueue.GetCount () == 0 &&
			waitList.GetCount () == 0) {
			return true;
		}
		return false;
	}

	private bool IsWelfareZero() {
		return Math.Abs (welfareCounter.Welfare) < 1e-3;
	}
}


text:
<?php

namespace Struzik\EPPClient\Node\Host;

use Struzik\EPPClient\Request\RequestInterface;

class HostAddNode
{
    public static function create(RequestInterface $request, \DOMElement $parentNode): \DOMElement
    {
        $node = $request->getDocument()->createElement('host:add');
        $parentNode->appendChild($node);

        return $node;
    }
}


text:
package io.aeron.cluster;

import io.aeron.Aeron;
import io.aeron.archive.Archive;
import io.aeron.archive.client.AeronArchive;
import io.aeron.cluster.client.ClusterException;
import io.aeron.cluster.codecs.CloseReason;
import io.aeron.cluster.codecs.ConsensusModuleDecoder;
import io.aeron.cluster.codecs.ConsensusModuleEncoder;
import io.aeron.cluster.codecs.MessageHeaderDecoder;
import io.aeron.cluster.codecs.MessageHeaderEncoder;
import io.aeron.cluster.codecs.SessionMessageHeaderDecoder;
import io.aeron.cluster.codecs.SessionMessageHeaderEncoder;
import io.aeron.samples.archive.RecordingReplicator;
import io.aeron.samples.archive.RecordingSignalCapture;
import io.aeron.test.EventLogExtension;
import io.aeron.test.InterruptAfter;
import io.aeron.test.InterruptingTestCallback;
import io.aeron.test.SlowTest;
import io.aeron.test.SystemTestWatcher;
import io.aeron.test.cluster.TestCluster;
import io.aeron.test.cluster.TestNode;
import org.agrona.DirectBuffer;
import org.agrona.ExpandableArrayBuffer;
import org.agrona.IoUtil;
import org.agrona.collections.IntArrayList;
import org.agrona.collections.LongArrayList;
import org.agrona.collections.MutableBoolean;
import org.agrona.collections.MutableInteger;
import org.agrona.collections.MutableLong;
import org.agrona.concurrent.UnsafeBuffer;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.junit.jupiter.api.extension.RegisterExtension;
import org.junit.jupiter.api.io.TempDir;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.CsvSource;

import java.io.File;
import java.io.IOException;
import java.nio.MappedByteBuffer;
import java.util.ArrayList;
import java.util.concurrent.ThreadLocalRandom;
import java.util.concurrent.TimeUnit;

import static io.aeron.CommonContext.IPC_CHANNEL;
import static io.aeron.CommonContext.NULL_SESSION_ID;
import static io.aeron.cluster.ConsensusModuleSnapshotPendingServiceMessagesPatch.replayLocalSnapshotRecording;
import static io.aeron.test.cluster.TestCluster.aCluster;
import static java.nio.ByteOrder.LITTLE_ENDIAN;
import static org.agrona.BitUtil.SIZE_OF_INT;
import static org.junit.jupiter.api.Assertions.*;

@ExtendWith({ EventLogExtension.class, InterruptingTestCallback.class })
class ConsensusModuleSnapshotPendingServiceMessagesPatchTest
{
    private static final int NUM_MESSAGES = 1987;

    @RegisterExtension
    final SystemTestWatcher systemTestWatcher = new SystemTestWatcher();

    @AfterEach
    void tearDown()
    {
        TestNode.MessageTrackingService.delaySessionMessageProcessing(false);
    }

    @Test
    void executeThrowsNullPointerExceptionIfClusterDirIsNull()
    {
        assertThrowsExactly(
            NullPointerException.class,
            () -> new ConsensusModuleSnapshotPendingServiceMessagesPatch().execute(null));
    }

    @Test
    void executeThrowsIllegalArgumentExceptionIfClusterDirDoesNotExist()
    {
        final File clusterDir = new File("non-existing-file-blah-blah");

        final IllegalArgumentException exception = assertThrowsExactly(
            IllegalArgumentException.class,
            () -> new ConsensusModuleSnapshotPendingServiceMessagesPatch().execute(clusterDir));
        assertEquals("invalid cluster directory: " + clusterDir.getAbsolutePath(), exception.getMessage());
    }

    @Test
    void executeThrowsIllegalArgumentExceptionIfClusterDirIsNotADirectory(
        final @TempDir File tempDir) throws IOException
    {
        final File clusterDir = new File(tempDir, "file.txt");
        assertTrue(clusterDir.createNewFile());

        final IllegalArgumentException exception = assertThrowsExactly(
            IllegalArgumentException.class,
            () -> new ConsensusModuleSnapshotPendingServiceMessagesPatch().execute(clusterDir));
        assertEquals("invalid cluster directory: " + clusterDir.getAbsolutePath(), exception.getMessage());
    }

    @Test
    void executeThrowsClusterExceptionIfClusterDirDoesNotContainARecordingLog(final @TempDir File tempDir)
    {
        final File clusterDir = new File(tempDir, "cluster-dir");
        assertTrue(clusterDir.mkdir());

        final ClusterException exception = assertThrowsExactly(
            ClusterException.class,
            () -> new ConsensusModuleSnapshotPendingServiceMessagesPatch().execute(clusterDir));
        final Throwable cause = exception.getCause();
        assertInstanceOf(IOException.class, cause);
    }

    @Test
    @SlowTest
    @InterruptAfter(30)
    void executeIsANoOpIfTheSnapshotIsValid()
    {
        final TestCluster cluster = aCluster()
            .withStaticNodes(3)
            .withTimerServiceSupplier(new PriorityHeapTimerServiceSupplier())
            .withServiceSupplier((i) -> new TestNode.TestService[]{
                new TestNode.MessageTrackingService(1, i),
                new TestNode.MessageTrackingService(2, i) })
            .start();
        systemTestWatcher.cluster(cluster);
        final int serviceCount = cluster.node(0).services().length;

        final TestNode leader = cluster.awaitLeader();
        cluster.connectClient();

        TestNode.MessageTrackingService.delaySessionMessageProcessing(true);
        int messageCount = 0;
        final ExpandableArrayBuffer msgBuffer = cluster.msgBuffer();
        for (int i = 0; i < NUM_MESSAGES; i++)
        {
            msgBuffer.putInt(0, ++messageCount, LITTLE_ENDIAN);
            cluster.pollUntilMessageSent(SIZE_OF_INT);
        }
        cluster.takeSnapshot(leader);
        cluster.awaitSnapshotCount(1);
        TestNode.MessageTrackingService.delaySessionMessageProcessing(false);

        cluster.awaitResponseMessageCount(messageCount * serviceCount);
        awaitServiceMessages(cluster, serviceCount, messageCount);
        stopConsensusModulesAndServices(cluster);

        final File leaderClusterDir = leader.consensusModule().context().clusterDir();
        final RecordingLog.Entry leaderSnapshot = ClusterTool.findLatestValidSnapshot(leaderClusterDir);
        assertNotNull(leaderSnapshot);

        final MutableLong mutableNextSessionId = new MutableLong(NULL_SESSION_ID);
        final MutableLong mutableNextServiceSessionId = new MutableLong(NULL_SESSION_ID);
        final MutableLong mutableLogServiceSessionId = new MutableLong(NULL_SESSION_ID);
        final LongArrayList pendingMessageClusterSessionIds = new LongArrayList();
        final ConsensusModuleSnapshotListener stateReader = new NoOpConsensusModuleSnapshotListener()
        {
            public void onLoadConsensusModuleState(
                final long nextSessionId,
                final long nextServiceSessionId,
                final long logServiceSessionId,
                final int pendingMessageCapacity,
                final DirectBuffer buffer,
                final int offset,
                final int length)
            {
                mutableNextSessionId.set(nextSessionId);
                mutableNextServiceSessionId.set(nextServiceSessionId);
                mutableLogServiceSessionId.set(logServiceSessionId);
            }

            public void onLoadPendingMessage(
                final long clusterSessionId, final DirectBuffer buffer, final int offset, final int length)
            {
                pendingMessageClusterSessionIds.add(clusterSessionId);
            }
        };

        readSnapshotRecording(leader, leaderSnapshot.recordingId, stateReader);

        final long beforeNextSessionId = mutableNextSessionId.get();
        final long beforeNextServiceSessionId = mutableNextServiceSessionId.get();
        final long beforeLogServiceSessionId = mutableLogServiceSessionId.get();
        final long[] beforeClusterSessionIds = pendingMessageClusterSessionIds.toLongArray();
        assertNotEquals(NULL_SESSION_ID, beforeNextSessionId);
        assertNotEquals(NULL_SESSION_ID, beforeNextServiceSessionId);
        assertNotEquals(NULL_SESSION_ID, beforeLogServiceSessionId);
        assertNotEquals(beforeNextSessionId, beforeNextServiceSessionId);
        assertNotEquals(beforeNextSessionId, beforeLogServiceSessionId);
        assertNotEquals(beforeNextServiceSessionId, beforeLogServiceSessionId);
        assertNotEquals(0, beforeClusterSessionIds.length);

        final ConsensusModuleSnapshotPendingServiceMessagesPatch snapshotPatch =
            new ConsensusModuleSnapshotPendingServiceMessagesPatch();
        assertFalse(snapshotPatch.execute(leaderClusterDir));

        mutableNextSessionId.set(NULL_SESSION_ID);
        mutableNextServiceSessionId.set(NULL_SESSION_ID);
        mutableLogServiceSessionId.set(NULL_SESSION_ID);
        pendingMessageClusterSessionIds.clear();
        readSnapshotRecording(leader, leaderSnapshot.recordingId, stateReader);
        assertEquals(beforeNextSessionId, mutableNextSessionId.get());
        assertEquals(beforeNextServiceSessionId, mutableNextServiceSessionId.get());
        assertEquals(beforeLogServiceSessionId, mutableLogServiceSessionId.get());
        assertArrayEquals(beforeClusterSessionIds, pendingMessageClusterSessionIds.toLongArray());
    }

    @ParameterizedTest
    @CsvSource({
        "-9193372036854775999, -9223372036854775808, -9223372036854775808, -9200000000000000000, LogServiceSessionId",
        "1000000, 1000, 500000, 1000000, LogServiceSessionId",
        "1000000, $compute, 1000001, 1000999, LogServiceSessionId",
        "5000, 200000, 100000, 150000, NextServiceSessionId",
        "$compute, 200000, 1, 199999, NextServiceSessionId",
        "7777, 9999, 1000000000000000, 1223372036854775, MaxClusterSessionId" })
    @SlowTest
    @InterruptAfter(30)
    @SuppressWarnings("MethodLength")
    void executeShouldPatchTheStateOfTheLeaderSnapshot(
        final String baseLogServiceSessionId,
        final String baseNextServiceSessionId,
        final long clusterSessionIdLowerBound,
        final long clusterSessionIdUpperBound,
        final String mode)
    {
        final TestCluster cluster = aCluster()
            .withStaticNodes(3)
            .withTimerServiceSupplier(new PriorityHeapTimerServiceSupplier())
            .withServiceSupplier((i) -> new TestNode.TestService[]{
                new TestNode.MessageTrackingService(1, i),
                new TestNode.MessageTrackingService(2, i) })
            .start();
        systemTestWatcher.cluster(cluster);
        final int serviceCount = cluster.node(0).services().length;

        final TestNode leader = cluster.awaitLeader();
        cluster.connectClient();

        TestNode.MessageTrackingService.delaySessionMessageProcessing(true);
        int messageCount = 0;
        final ExpandableArrayBuffer msgBuffer = cluster.msgBuffer();
        for (int i = 0; i < NUM_MESSAGES; i++)
        {
            msgBuffer.putInt(0, ++messageCount, LITTLE_ENDIAN);
            cluster.pollUntilMessageSent(SIZE_OF_INT);
        }
        cluster.takeSnapshot(leader);
        cluster.awaitSnapshotCount(1);
        TestNode.MessageTrackingService.delaySessionMessageProcessing(false);

        cluster.awaitResponseMessageCount(messageCount * serviceCount);
        awaitServiceMessages(cluster, serviceCount, messageCount);
        stopConsensusModulesAndServices(cluster);

        final File leaderClusterDir = leader.consensusModule().context().clusterDir();
        final RecordingLog.Entry leaderSnapshot = ClusterTool.findLatestValidSnapshot(leaderClusterDir);
        assertNotNull(leaderSnapshot);

        final MutableLong mutableNextSessionId = new MutableLong();
        final MutableLong mutableNextServiceSessionId = new MutableLong();
        final MutableLong mutableLogServiceSessionId = new MutableLong();
        final MutableInteger consensusModuleStateOffset = new MutableInteger();
        final IntArrayList pendingMessageOffsets = new IntArrayList();
        readSnapshotRecording(leader, leaderSnapshot.recordingId, new NoOpConsensusModuleSnapshotListener()
        {
            public void onLoadConsensusModuleState(
                final long nextSessionId,
                final long nextServiceSessionId,
                final long logServiceSessionId,
                final int pendingMessageCapacity,
                final DirectBuffer buffer,
                final int offset,
                final int length)
            {
                mutableNextSessionId.set(nextSessionId);
                mutableNextServiceSessionId.set(nextServiceSessionId);
                mutableLogServiceSessionId.set(logServiceSessionId);
                consensusModuleStateOffset.set(offset);
                assertEquals(MessageHeaderDecoder.ENCODED_LENGTH + ConsensusModuleDecoder.BLOCK_LENGTH, length);
            }

            public void onLoadPendingMessage(
                final long clusterSessionId, final DirectBuffer buffer, final int offset, final int length)
            {
                pendingMessageOffsets.addInt(offset);
                assertEquals(
                    MessageHeaderDecoder.ENCODED_LENGTH + SessionMessageHeaderDecoder.BLOCK_LENGTH + SIZE_OF_INT,
                    length);
            }
        });
        assertNotEquals(0, consensusModuleStateOffset.get());
        final int numPendingMessages = pendingMessageOffsets.size();
        assertNotEquals(0, numPendingMessages);

        final long expectedNextSessionId = mutableNextSessionId.get();
        assertNotEquals(Long.toString(mutableLogServiceSessionId.get()), baseLogServiceSessionId);
        assertNotEquals(Long.toString(mutableNextServiceSessionId.get()), baseNextServiceSessionId);

        modifySnapshot(
            leader,
            leaderSnapshot,
            consensusModuleStateOffset,
            pendingMessageOffsets,
            baseLogServiceSessionId,
            baseNextServiceSessionId,
            clusterSessionIdLowerBound,
            clusterSessionIdUpperBound);

        final ConsensusModuleSnapshotPendingServiceMessagesPatch snapshotPatch =
            new ConsensusModuleSnapshotPendingServiceMessagesPatch();
        assertTrue(snapshotPatch.execute(leaderClusterDir));

        final MutableBoolean onLoadConsensusModuleState = new MutableBoolean();
        final MutableInteger onLoadPendingMessageCount = new MutableInteger();
        readSnapshotRecording(leader, leaderSnapshot.recordingId, new NoOpConsensusModuleSnapshotListener()
        {
            long nextClusterSessionId;

            public void onLoadConsensusModuleState(
                final long nextSessionId,
                final long nextServiceSessionId,
                final long logServiceSessionId,
                final int pendingMessageCapacity,
                final DirectBuffer buffer,
                final int offset,
                final int length)
            {
                assertEquals(expectedNextSessionId, nextSessionId);

                switch (mode)
                {
                    case "LogServiceSessionId":
                    {
                        assertEquals(Long.parseLong(baseLogServiceSessionId), logServiceSessionId);
                        assertEquals(logServiceSessionId + 1 + numPendingMessages, nextServiceSessionId);
                        break;
                    }
                    case "NextServiceSessionId":
                    {
                        assertEquals(Long.parseLong(baseNextServiceSessionId), nextServiceSessionId);
                        assertEquals(nextServiceSessionId - 1 - numPendingMessages, logServiceSessionId);
                        break;
                    }
                    case "MaxClusterSessionId":
                    {
                        assertEquals(clusterSessionIdUpperBound - numPendingMessages, logServiceSessionId);
                        assertEquals(clusterSessionIdUpperBound + 1, nextServiceSessionId);
                        break;
                    }
                    default:
                    {
                        fail("unknown mode: " + mode);
                    }
                }

                nextClusterSessionId = logServiceSessionId + 1;
                onLoadConsensusModuleState.set(true);
            }

            public void onLoadPendingMessage(
                final long clusterSessionId, final DirectBuffer buffer, final int offset, final int length)
            {
                assertEquals(nextClusterSessionId++, clusterSessionId, "Invalid pending message header!");
                onLoadPendingMessageCount.increment();
            }
        });
        assertTrue(onLoadConsensusModuleState.get());
        assertEquals(numPendingMessages, onLoadPendingMessageCount.get());

        for (int i = 0; i < 3; i++)
        {
            if (i != leader.index())
            {
                replicatePatchedSnapshotToFollower(leader, leaderSnapshot.recordingId, cluster.node(i));
            }
        }

        cluster.stopAllNodes();
        cluster.restartAllNodes(false);
        cluster.connectClient();

        for (int i = 0; i < 10; i++)
        {
            msgBuffer.putInt(0, ++messageCount, LITTLE_ENDIAN);
            cluster.pollUntilMessageSent(SIZE_OF_INT);
        }
        cluster.awaitResponseMessageCount(messageCount * serviceCount);
        awaitServiceMessages(cluster, serviceCount, messageCount);
    }

    private static void awaitServiceMessages(final TestCluster cluster, final int serviceCount, final int messageCount)
    {
        for (int i = 0; i < 3; i++)
        {
            final TestNode node = cluster.node(i);
            final TestNode.TestService[] services = node.services();
            for (final TestNode.TestService service : services)
            {
                // 1 client message + 3 service messages x number of services
                cluster.awaitServiceMessageCount(node, service, messageCount + (messageCount * 3 * serviceCount));
                // 2 timers x number of services
                cluster.awaitTimerEventCount(node, service, messageCount * 2 * serviceCount);
            }
        }
    }

    private static void stopConsensusModulesAndServices(final TestCluster cluster)
    {
        for (int i = 0; i < 3; i++)
        {
            final TestNode node = cluster.node(i);
            if (null != node)
            {
                node.isTerminationExpected(true);
                node.stopServiceContainers();
                node.consensusModule().close();
            }
        }
    }

    private static void modifySnapshot(
        final TestNode leader,
        final RecordingLog.Entry leaderSnapshot,
        final MutableInteger consensusModuleStateOffset,
        final IntArrayList pendingMessageOffsets,
        final String baseLogServiceSessionId,
        final String baseNextServiceSessionId,
        final long clusterSessionIdLowerBound,
        final long clusterSessionIdUpperBound)
    {
        final int numberOfPendingMessages = pendingMessageOffsets.size();
        final long logServiceSessionId;
        if ("$compute".equals(baseLogServiceSessionId))
        {
            logServiceSessionId = Long.parseLong(baseNextServiceSessionId) - 1 - numberOfPendingMessages;
        }
        else
        {
            logServiceSessionId = Long.parseLong(baseLogServiceSessionId);
        }

        final long nextServiceSessionId;
        if ("$compute".equals(baseNextServiceSessionId))
        {
            nextServiceSessionId = Long.parseLong(baseLogServiceSessionId) + 1 + numberOfPendingMessages;
        }
        else
        {
            nextServiceSessionId = Long.parseLong(baseNextServiceSessionId);
        }

        final ArrayList<File> segmentFiles = listSegmentFiles(leader, leaderSnapshot.recordingId);
        assertEquals(1, segmentFiles.size());
        final MappedByteBuffer mappedByteBuffer = IoUtil.mapExistingFile(
            segmentFiles.get(0), "snapshot file");
        try
        {
            final UnsafeBuffer snapshotBuffer = new UnsafeBuffer(mappedByteBuffer);
            final MessageHeaderEncoder messageHeaderEncoder = new MessageHeaderEncoder();

            // Set the ConsensusModuleState values
            final ConsensusModuleEncoder consensusModuleEncoder = new ConsensusModuleEncoder();
            consensusModuleEncoder
                .wrapAndApplyHeader(snapshotBuffer, consensusModuleStateOffset.get(), messageHeaderEncoder)
                .logServiceSessionId(logServiceSessionId)
                .nextServiceSessionId(nextServiceSessionId);

            // Now randomize clusterSessionId of every pending service message
            final SessionMessageHeaderEncoder sessionMessageHeaderEncoder = new SessionMessageHeaderEncoder();
            final MutableInteger count = new MutableInteger();
            pendingMessageOffsets.forEachInt((offset) ->
            {
                final long clusterSessionId;
                switch (count.getAndIncrement())
                {
                    case 0:
                        clusterSessionId = clusterSessionIdLowerBound;
                        break;
                    case 1:
                        clusterSessionId = clusterSessionIdUpperBound;
                        break;
                    default:
                        clusterSessionId = ThreadLocalRandom.current()
                            .nextLong(clusterSessionIdLowerBound + 1, clusterSessionIdUpperBound);
                        break;
                }
                sessionMessageHeaderEncoder
                    .wrapAndApplyHeader(snapshotBuffer, offset, messageHeaderEncoder)
                    .clusterSessionId(clusterSessionId);
            });
        }
        finally
        {
            IoUtil.unmap(mappedByteBuffer);
        }
    }

    private static ArrayList<File> listSegmentFiles(final TestNode node, final long recordingId)
    {
        final File[] files = node.archive().context().archiveDir().listFiles();
        assertNotNull(files);
        final String segmentFileNamePrefix = recordingId + "-";
        final ArrayList<File> segmentFiles = new ArrayList<>();
        for (final File file : files)
        {
            if (null != file)
            {
                final String fileName = file.getName();
                if (fileName.startsWith(segmentFileNamePrefix) && fileName.endsWith(".rec"))
                {
                    segmentFiles.add(file);
                }
            }
        }
        return segmentFiles;
    }

    private static void readSnapshotRecording(
        final TestNode node,
        final long recordingId,
        final ConsensusModuleSnapshotListener snapshotListener)
    {
        try (
            Aeron aeron = Aeron.connect(new Aeron.Context()
                .aeronDirectoryName(node.mediaDriver().aeronDirectoryName()));
            AeronArchive archive = AeronArchive.connect(new AeronArchive.Context()
                .controlRequestChannel(IPC_CHANNEL)
                .controlResponseChannel(IPC_CHANNEL)
                .aeron(aeron)))
        {
            replayLocalSnapshotRecording(
                aeron,
                archive,
                recordingId,
                snapshotListener);
        }
    }

    private static void replicatePatchedSnapshotToFollower(
        final TestNode leader, final long snapshotRecordingId, final TestNode follower)
    {
        final File clusterDir = follower.consensusModule().context().clusterDir();
        final RecordingLog.Entry followerSnapshot = ClusterTool.findLatestValidSnapshot(clusterDir);
        assertNotNull(followerSnapshot, "follower without a snapshot node");

        final String aeronDirectoryName = follower.mediaDriver().aeronDirectoryName();
        try (Aeron aeron = Aeron.connect(new Aeron.Context().aeronDirectoryName(aeronDirectoryName));
            AeronArchive aeronArchive = AeronArchive.connect(new AeronArchive.Context()
                .controlRequestChannel(AeronArchive.Configuration.localControlChannel())
                .controlResponseChannel(AeronArchive.Configuration.localControlChannel())
                .aeron(aeron)
                .recordingSignalConsumer(new RecordingSignalCapture())))
        {
            final Archive.Context leaderArchiveContext = leader.archive().context();
            final RecordingReplicator recordingReplicator = new RecordingReplicator(
                aeronArchive,
                snapshotRecordingId,
                followerSnapshot.recordingId,
                leaderArchiveContext.controlChannel(),
                leaderArchiveContext.controlStreamId(),
                null);

            assertEquals(followerSnapshot.recordingId, recordingReplicator.replicate());
        }
    }

    private static class NoOpConsensusModuleSnapshotListener implements ConsensusModuleSnapshotListener
    {
        public void onLoadBeginSnapshot(
            final int appVersion,
            final TimeUnit timeUnit,
            final DirectBuffer buffer,
            final int offset,
            final int length)
        {
        }

        public void onLoadConsensusModuleState(
            final long nextSessionId,
            final long nextServiceSessionId,
            final long logServiceSessionId,
            final int pendingMessageCapacity,
            final DirectBuffer buffer,
            final int offset,
            final int length)
        {
        }

        public void onLoadClusterMembers(
            final int memberId,
            final int highMemberId,
            final String clusterMembers,
            final DirectBuffer buffer,
            final int offset,
            final int length)
        {
        }

        public void onLoadPendingMessage(
            final long clusterSessionId, final DirectBuffer buffer, final int offset, final int length)
        {
        }

        public void onLoadClusterSession(
            final long clusterSessionId,
            final long correlationId,
            final long openedLogPosition,
            final long timeOfLastActivity,
            final CloseReason closeReason,
            final int responseStreamId,
            final String responseChannel,
            final DirectBuffer buffer,
            final int offset,
            final int length)
        {
        }

        public void onLoadTimer(
            final long correlationId,
            final long deadline,
            final DirectBuffer buffer,
            final int offset,
            final int length)
        {
        }

        public void onLoadPendingMessageTracker(
            final long nextServiceSessionId,
            final long logServiceSessionId,
            final int pendingMessageCapacity,
            final int serviceId,
            final DirectBuffer buffer,
            final int offset,
            final int length)
        {
        }

        public void onLoadEndSnapshot(final DirectBuffer buffer, final int offset, final int length)
        {
        }
    }
}


text:
<?php

namespace Mariuzzo\LaravelJsLocalization;

use Illuminate\Filesystem\Filesystem as File;
use Mariuzzo\LaravelJsLocalization\Commands\LangJsCommand;
use Mariuzzo\LaravelJsLocalization\Generators\LangJsGenerator;
use Orchestra\Testbench\TestCase;
use Symfony\Component\Console\Input\ArrayInput;
use Symfony\Component\Console\Output\NullOutput;

/**
 * The LangJsCommandTest class.
 *
 * @author Rubens Mariuzzo <rubens@mariuzzo.com>
 */
class LangJsCommandTest extends TestCase
{
    /**
     * Test the command.
     */
    public function testShouldCommandRun()
    {
        $generator = new LangJsGenerator(new File(), __DIR__.'/fixtures/lang');

        $command = new LangJsCommand($generator);
        $command->setLaravel($this->app);

        $code = $this->runCommand($command, ['target' => __DIR__.'/output/lang.js']);

        $this->assertRunsWithSuccess($code);

        $this->assertFileExists(__DIR__.'/output/lang.js');

        $template = __DIR__.'/../src/Mariuzzo/LaravelJsLocalization/Generators/Templates/langjs_with_messages.js';

        $this->assertFileExists($template);

        $this->assertFileNotEquals($template, __DIR__.'/output/lang.js');
    }

    /**
     * @return void
     */
    public function testShouldTemplateHasHandlebars()
    {
        $template = __DIR__.'/../src/Mariuzzo/LaravelJsLocalization/Generators/Templates/langjs_with_messages.js';

        $this->assertFileExists($template);

        $contents = file_get_contents($template);

        $this->assertNotEmpty($contents);

        $this->assertHasHandlebars('messages', $contents);

        $this->assertHasHandlebars('langjs', $contents);
    }

    /**
     * @return void
     */
    public function testShouldOutputHasNotHandlebars()
    {
        $output = __DIR__.'/output/lang.js';

        $this->assertFileExists($output);

        $contents = file_get_contents($output);

        $this->assertNotEmpty($contents);

        $this->assertHasNotHandlebars('messages', $contents);

        $this->assertHasNotHandlebars('langjs', $contents);
    }

    /**
     * Run the command.
     * @param \Illuminate\Console\Command $command
     * @param array $input
     * @return int
     */
    protected function runCommand($command, $input = [])
    {
        return $command->run(new ArrayInput($input), new NullOutput());
    }

    /**
     * Assert the code return is success.
     * @param int  $code
     * @param null $message
     */
    protected function assertRunsWithSuccess($code, $message = null)
    {
        $this->assertEquals(0, $code, $message);
    }

    /**
     * @param string $handle
     * @param string $contents
     */
    protected function assertHasHandlebars($handle, $contents)
    {
        $this->assertEquals(1, preg_match('/\'\{(\s)'.preg_quote($handle).'(\s)\}\'/', $contents));
    }

    /**
     * @param string $handle
     * @param string $contents
     */
    protected function assertHasNotHandlebars($handle, $contents)
    {
        $this->assertEquals(0, preg_match('/\'\{(\s)'.preg_quote($handle).'(\s)\}\'/', $contents));
    }
}


text:
<?php
include_once("bean.config.php");

// namespace beans;

class BeanAclActions extends MySqlRecord
{
    /**
     * A control attribute for the update operation.
     * @note An instance fetched from db is allowed to run the update operation.
     *       A new instance (not fetched from db) is allowed only to run the insert operation but,
     *       after running insertion, the instance is automatically allowed to run update operation.
     * @var bool
     */
    private $allowUpdate = false;

    /**
     * Class attribute for mapping the primary key id of table acl_actions
     *
     * Comment for field id: Not specified

     * @var string $id
     */
    private $id;

    /**
     * A class attribute for evaluating if the table has an autoincrement primary key
     * @var bool $isPkAutoIncrement
     */
    private $isPkAutoIncrement = false;

    /**
     * Class attribute for mapping table field date_entered
     *
     * Comment for field date_entered: Not specified.

     * Field information:
     *  - Data type: datetime
     *  - Null : YES
     *  - DB Index:
     *  - Default:
     *  - Extra:
     * @var string $dateEntered
     */
    private $dateEntered;

    /**
     * Class attribute for mapping table field date_modified
     *
     * Comment for field date_modified: Not specified.

     * Field information:
     *  - Data type: datetime
     *  - Null : YES
     *  - DB Index:
     *  - Default:
     *  - Extra:
     * @var string $dateModified
     */
    private $dateModified;

    /**
     * Class attribute for mapping table field modified_user_id
     *
     * Comment for field modified_user_id: Not specified.

     * Field information:
     *  - Data type: char(36)
     *  - Null : YES
     *  - DB Index:
     *  - Default:
     *  - Extra:
     * @var string $modifiedUserId
     */
    private $modifiedUserId;

    /**
     * Class attribute for mapping table field created_by
     *
     * Comment for field created_by: Not specified.

     * Field information:
     *  - Data type: char(36)
     *  - Null : YES
     *  - DB Index:
     *  - Default:
     *  - Extra:
     * @var string $createdBy
     */
    private $createdBy;

    /**
     * Class attribute for mapping table field name
     *
     * Comment for field name: Not specified.

     * Field information:
     *  - Data type: varchar(150)
     *  - Null : YES
     *  - DB Index:
     *  - Default:
     *  - Extra:
     * @var string $name
     */
    private $name;

    /**
     * Class attribute for mapping table field category
     *
     * Comment for field category: Not specified.

     * Field information:
     *  - Data type: varchar(100)
     *  - Null : YES
     *  - DB Index: MUL
     *  - Default:
     *  - Extra:
     * @var string $category
     */
    private $category;

    /**
     * Class attribute for mapping table field acltype
     *
     * Comment for field acltype: Not specified.

     * Field information:
     *  - Data type: varchar(100)
     *  - Null : YES
     *  - DB Index:
     *  - Default:
     *  - Extra:
     * @var string $acltype
     */
    private $acltype;

    /**
     * Class attribute for mapping table field aclaccess
     *
     * Comment for field aclaccess: Not specified.

     * Field information:
     *  - Data type: int(3)
     *  - Null : YES
     *  - DB Index:
     *  - Default:
     *  - Extra:
     * @var int $aclaccess
     */
    private $aclaccess;

    /**
     * Class attribute for mapping table field deleted
     *
     * Comment for field deleted: Not specified.

     * Field information:
     *  - Data type: tinyint(1)
     *  - Null : YES
     *  - DB Index:
     *  - Default:
     *  - Extra:
     * @var int $deleted
     */
    private $deleted;

    /**
     * Class attribute for storing the SQL DDL of table acl_actions
     * @var string base64 encoded string for DDL
     */
    private $ddl = "Q1JFQVRFIFRBQkxFIGBhY2xfYWN0aW9uc2AgKAogIGBpZGAgY2hhcigzNikgTk9UIE5VTEwsCiAgYGRhdGVfZW50ZXJlZGAgZGF0ZXRpbWUgREVGQVVMVCBOVUxMLAogIGBkYXRlX21vZGlmaWVkYCBkYXRldGltZSBERUZBVUxUIE5VTEwsCiAgYG1vZGlmaWVkX3VzZXJfaWRgIGNoYXIoMzYpIERFRkFVTFQgTlVMTCwKICBgY3JlYXRlZF9ieWAgY2hhcigzNikgREVGQVVMVCBOVUxMLAogIGBuYW1lYCB2YXJjaGFyKDE1MCkgREVGQVVMVCBOVUxMLAogIGBjYXRlZ29yeWAgdmFyY2hhcigxMDApIERFRkFVTFQgTlVMTCwKICBgYWNsdHlwZWAgdmFyY2hhcigxMDApIERFRkFVTFQgTlVMTCwKICBgYWNsYWNjZXNzYCBpbnQoMykgREVGQVVMVCBOVUxMLAogIGBkZWxldGVkYCB0aW55aW50KDEpIERFRkFVTFQgTlVMTCwKICBQUklNQVJZIEtFWSAoYGlkYCksCiAgS0VZIGBpZHhfYWNsYWN0aW9uX2lkX2RlbGAgKGBpZGAsYGRlbGV0ZWRgKSwKICBLRVkgYGlkeF9jYXRlZ29yeV9uYW1lYCAoYGNhdGVnb3J5YCxgbmFtZWApCikgRU5HSU5FPUlubm9EQiBERUZBVUxUIENIQVJTRVQ9dXRmOA==";

    /**
     * setId Sets the class attribute id with a given value
     *
     * The attribute id maps the field id defined as char(36).

     * Comment for field id: Not specified.

     * @param string $id
     * @category Modifier
     */
    public function setId($id)
    {
        $this->id = (string)$id;
    }

    /**
     * setDateEntered Sets the class attribute dateEntered with a given value
     *
     * The attribute dateEntered maps the field date_entered defined as datetime.

     * Comment for field date_entered: Not specified.

     * @param string $dateEntered
     * @category Modifier
     */
    public function setDateEntered($dateEntered)
    {
        $this->dateEntered = (string)$dateEntered;
    }

    /**
     * setDateModified Sets the class attribute dateModified with a given value
     *
     * The attribute dateModified maps the field date_modified defined as datetime.

     * Comment for field date_modified: Not specified.

     * @param string $dateModified
     * @category Modifier
     */
    public function setDateModified($dateModified)
    {
        $this->dateModified = (string)$dateModified;
    }

    /**
     * setModifiedUserId Sets the class attribute modifiedUserId with a given value
     *
     * The attribute modifiedUserId maps the field modified_user_id defined as char(36).

     * Comment for field modified_user_id: Not specified.

     * @param string $modifiedUserId
     * @category Modifier
     */
    public function setModifiedUserId($modifiedUserId)
    {
        $this->modifiedUserId = (string)$modifiedUserId;
    }

    /**
     * setCreatedBy Sets the class attribute createdBy with a given value
     *
     * The attribute createdBy maps the field created_by defined as char(36).

     * Comment for field created_by: Not specified.

     * @param string $createdBy
     * @category Modifier
     */
    public function setCreatedBy($createdBy)
    {
        $this->createdBy = (string)$createdBy;
    }

    /**
     * setName Sets the class attribute name with a given value
     *
     * The attribute name maps the field name defined as varchar(150).

     * Comment for field name: Not specified.

     * @param string $name
     * @category Modifier
     */
    public function setName($name)
    {
        $this->name = (string)$name;
    }

    /**
     * setCategory Sets the class attribute category with a given value
     *
     * The attribute category maps the field category defined as varchar(100).

     * Comment for field category: Not specified.

     * @param string $category
     * @category Modifier
     */
    public function setCategory($category)
    {
        $this->category = (string)$category;
    }

    /**
     * setAcltype Sets the class attribute acltype with a given value
     *
     * The attribute acltype maps the field acltype defined as varchar(100).

     * Comment for field acltype: Not specified.

     * @param string $acltype
     * @category Modifier
     */
    public function setAcltype($acltype)
    {
        $this->acltype = (string)$acltype;
    }

    /**
     * setAclaccess Sets the class attribute aclaccess with a given value
     *
     * The attribute aclaccess maps the field aclaccess defined as int(3).

     * Comment for field aclaccess: Not specified.

     * @param int $aclaccess
     * @category Modifier
     */
    public function setAclaccess($aclaccess)
    {
        $this->aclaccess = (int)$aclaccess;
    }

    /**
     * setDeleted Sets the class attribute deleted with a given value
     *
     * The attribute deleted maps the field deleted defined as tinyint(1).

     * Comment for field deleted: Not specified.

     * @param int $deleted
     * @category Modifier
     */
    public function setDeleted($deleted)
    {
        $this->deleted = (int)$deleted;
    }

    /**
     * getId gets the class attribute id value
     *
     * The attribute id maps the field id defined as char(36).

     * Comment for field id: Not specified.
     * @return string $id
     * @category Accessor of $id
     */
    public function getId()
    {
        return $this->id;
    }

    /**
     * getDateEntered gets the class attribute dateEntered value
     *
     * The attribute dateEntered maps the field date_entered defined as datetime.

     * Comment for field date_entered: Not specified.
     * @return string $dateEntered
     * @category Accessor of $dateEntered
     */
    public function getDateEntered()
    {
        return $this->dateEntered;
    }

    /**
     * getDateModified gets the class attribute dateModified value
     *
     * The attribute dateModified maps the field date_modified defined as datetime.

     * Comment for field date_modified: Not specified.
     * @return string $dateModified
     * @category Accessor of $dateModified
     */
    public function getDateModified()
    {
        return $this->dateModified;
    }

    /**
     * getModifiedUserId gets the class attribute modifiedUserId value
     *
     * The attribute modifiedUserId maps the field modified_user_id defined as char(36).

     * Comment for field modified_user_id: Not specified.
     * @return string $modifiedUserId
     * @category Accessor of $modifiedUserId
     */
    public function getModifiedUserId()
    {
        return $this->modifiedUserId;
    }

    /**
     * getCreatedBy gets the class attribute createdBy value
     *
     * The attribute createdBy maps the field created_by defined as char(36).

     * Comment for field created_by: Not specified.
     * @return string $createdBy
     * @category Accessor of $createdBy
     */
    public function getCreatedBy()
    {
        return $this->createdBy;
    }

    /**
     * getName gets the class attribute name value
     *
     * The attribute name maps the field name defined as varchar(150).

     * Comment for field name: Not specified.
     * @return string $name
     * @category Accessor of $name
     */
    public function getName()
    {
        return $this->name;
    }

    /**
     * getCategory gets the class attribute category value
     *
     * The attribute category maps the field category defined as varchar(100).

     * Comment for field category: Not specified.
     * @return string $category
     * @category Accessor of $category
     */
    public function getCategory()
    {
        return $this->category;
    }

    /**
     * getAcltype gets the class attribute acltype value
     *
     * The attribute acltype maps the field acltype defined as varchar(100).

     * Comment for field acltype: Not specified.
     * @return string $acltype
     * @category Accessor of $acltype
     */
    public function getAcltype()
    {
        return $this->acltype;
    }

    /**
     * getAclaccess gets the class attribute aclaccess value
     *
     * The attribute aclaccess maps the field aclaccess defined as int(3).

     * Comment for field aclaccess: Not specified.
     * @return int $aclaccess
     * @category Accessor of $aclaccess
     */
    public function getAclaccess()
    {
        return $this->aclaccess;
    }

    /**
     * getDeleted gets the class attribute deleted value
     *
     * The attribute deleted maps the field deleted defined as tinyint(1).

     * Comment for field deleted: Not specified.
     * @return int $deleted
     * @category Accessor of $deleted
     */
    public function getDeleted()
    {
        return $this->deleted;
    }

    /**
     * Gets DDL SQL code of the table acl_actions
     * @return string
     * @category Accessor
     */
    public function getDdl()
    {
        return base64_decode($this->ddl);
    }

    /**
    * Gets the name of the managed table
    * @return string
    * @category Accessor
    */
    public function getTableName()
    {
        return "acl_actions";
    }

    /**
     * The BeanAclActions constructor
     *
     * It creates and initializes an object in two way:
     *  - with null (not fetched) data if none $id is given.
     *  - with a fetched data row from the table acl_actions having id=$id
     * @param string $id. If omitted an empty (not fetched) instance is created.
     * @return BeanAclActions Object
     */
    public function __construct($id = null)
    {
        parent::__construct();
        if (!empty($id)) {
            $this->select($id);
        }
    }

    /**
     * The implicit destructor
     */
    public function __destruct()
    {
        $this->close();
    }

    /**
     * Explicit destructor. It calls the implicit destructor automatically.
     */
    public function close()
    {
        unset($this);
    }

    /**
     * Fetchs a table row of acl_actions into the object.
     *
     * Fetched table fields values are assigned to class attributes and they can be managed by using
     * the accessors/modifiers methods of the class.
     * @param string $id the primary key id value of table acl_actions which identifies the row to select.
     * @return int affected selected row
     * @category DML
     */
    public function select($id)
    {
        $sql =  "SELECT * FROM acl_actions WHERE id={$this->parseValue($id,'string')}";
        $this->resetLastSqlError();
        $result =  $this->query($sql);
        $this->resultSet=$result;
        $this->lastSql = $sql;
        if ($result){
            $rowObject = $result->fetch_object();
            @$this->id = $this->replaceAposBackSlash($rowObject->id);
            @$this->dateEntered = empty($rowObject->date_entered) ? null : date(FETCHED_DATETIME_FORMAT,strtotime($rowObject->date_entered));
            @$this->dateModified = empty($rowObject->date_modified) ? null : date(FETCHED_DATETIME_FORMAT,strtotime($rowObject->date_modified));
            @$this->modifiedUserId = $this->replaceAposBackSlash($rowObject->modified_user_id);
            @$this->createdBy = $this->replaceAposBackSlash($rowObject->created_by);
            @$this->name = $this->replaceAposBackSlash($rowObject->name);
            @$this->category = $this->replaceAposBackSlash($rowObject->category);
            @$this->acltype = $this->replaceAposBackSlash($rowObject->acltype);
            @$this->aclaccess = (integer)$rowObject->aclaccess;
            @$this->deleted = (integer)$rowObject->deleted;
            $this->allowUpdate = true;
        } else {
            $this->lastSqlError = $this->sqlstate . " - ". $this->error;
        }
        return $this->affected_rows;
    }

    /**
     * Deletes a specific row from the table acl_actions
     * @param string $id the primary key id value of table acl_actions which identifies the row to delete.
     * @return int affected deleted row
     * @category DML
     */
    public function delete($id)
    {
        $sql = "DELETE FROM acl_actions WHERE id={$this->parseValue($id,'string')}";
        $this->resetLastSqlError();
        $result = $this->query($sql);
        $this->lastSql = $sql;
        if (!$result) {
            $this->lastSqlError = $this->sqlstate . " - ". $this->error;
        }
        return $this->affected_rows;
    }

    /**
     * Insert the current object into a new table row of acl_actions
     *
     * All class attributes values defined for mapping all table fields are automatically used during inserting
     * @return mixed MySQL insert result
     * @category DML
     */
    public function insert()
    {
        if ($this->isPkAutoIncrement) {
            $this->id = "";
        }
        // $constants = get_defined_constants();
        $sql = <<< SQL
            INSERT INTO acl_actions
            (id,date_entered,date_modified,modified_user_id,created_by,name,category,acltype,aclaccess,deleted)
            VALUES({$this->parseValue($this->id,'notNumber')},
			{$this->parseValue($this->dateEntered,'datetime')},
			{$this->parseValue($this->dateModified,'datetime')},
			{$this->parseValue($this->modifiedUserId,'notNumber')},
			{$this->parseValue($this->createdBy,'notNumber')},
			{$this->parseValue($this->name,'notNumber')},
			{$this->parseValue($this->category,'notNumber')},
			{$this->parseValue($this->acltype,'notNumber')},
			{$this->parseValue($this->aclaccess)},
			{$this->parseValue($this->deleted)})
SQL;
        $this->resetLastSqlError();
        $result = $this->query($sql);
        $this->lastSql = $sql;
        if (!$result) {
            $this->lastSqlError = $this->sqlstate . " - ". $this->error;
        } else {
            $this->allowUpdate = true;
            if ($this->isPkAutoIncrement) {
                $this->id = $this->insert_id;
            }
        }
        return $result;
    }

    /**
     * Updates a specific row from the table acl_actions with the values of the current object.
     *
     * All class attribute values defined for mapping all table fields are automatically used during updating of selected row.

     * Null values are used for all attributes not previously setted.
     * @param string $id the primary key id value of table acl_actions which identifies the row to update.
     * @return mixed MySQL update result
     * @category DML
     */
    public function update($id)
    {
        // $constants = get_defined_constants();
        if ($this->allowUpdate) {
            $sql = <<< SQL
            UPDATE
                acl_actions
            SET
				date_entered={$this->parseValue($this->dateEntered,'datetime')},
				date_modified={$this->parseValue($this->dateModified,'datetime')},
				modified_user_id={$this->parseValue($this->modifiedUserId,'notNumber')},
				created_by={$this->parseValue($this->createdBy,'notNumber')},
				name={$this->parseValue($this->name,'notNumber')},
				category={$this->parseValue($this->category,'notNumber')},
				acltype={$this->parseValue($this->acltype,'notNumber')},
				aclaccess={$this->parseValue($this->aclaccess)},
				deleted={$this->parseValue($this->deleted)}
            WHERE
                id={$this->parseValue($id,'string')}
SQL;
            $this->resetLastSqlError();
            $result = $this->query($sql);
            if (!$result) {
                $this->lastSqlError = $this->sqlstate . " - ". $this->error;
            } else {
                $this->select($id);
                $this->lastSql = $sql;
                return $result;
            }
        } else {
            return false;
        }
    }

    /**
     * Facility for updating a row of acl_actions previously loaded.
     *
     * All class attribute values defined for mapping all table fields are automatically used during updating.
     * @category DML Helper
     * @return mixed MySQLi update result
     */
    public function updateCurrent()
    {
        if ($this->id != "") {
            return $this->update($this->id);
        } else {
            return false;
        }
    }

}
?>


text:
package org.apache.hadoop.hbase.rest.model;

import java.io.IOException;
import java.io.Serializable;

import javax.servlet.ServletContext;
import javax.xml.bind.annotation.XmlAttribute;
import javax.xml.bind.annotation.XmlRootElement;

import org.apache.hadoop.hbase.rest.ProtobufMessageHandler;
import org.apache.hadoop.hbase.rest.RESTServlet;
import org.apache.hadoop.hbase.rest.protobuf.generated.VersionMessage.Version;

import com.sun.jersey.spi.container.servlet.ServletContainer;

/**
 * A representation of the collection of versions of the REST gateway software
 * components.
 *

 *
restVersion: REST gateway revision

 *
jvmVersion: the JVM vendor and version information

 *
osVersion: the OS type, version, and hardware architecture

 *
serverVersion: the name and version of the servlet container

 *
jerseyVersion: the version of the embedded Jersey framework

 *

 */
@XmlRootElement(name="Version")
public class VersionModel implements Serializable, ProtobufMessageHandler {

	private static final long serialVersionUID = 1L;

	private String restVersion;
  private String jvmVersion;
  private String osVersion;
  private String serverVersion;
  private String jerseyVersion;

  /**
   * Default constructor. Do not use.
   */
  public VersionModel() {}

  /**
   * Constructor
   * @param context the servlet context
   */
	public VersionModel(ServletContext context) {
	  restVersion = RESTServlet.VERSION_STRING;
	  jvmVersion = System.getProperty("java.vm.vendor") + ' ' +
      System.getProperty("java.version") + '-' +
      System.getProperty("java.vm.version");
	  osVersion = System.getProperty("os.name") + ' ' +
      System.getProperty("os.version") + ' ' +
      System.getProperty("os.arch");
	  serverVersion = context.getServerInfo();
	  jerseyVersion = ServletContainer.class.getPackage()
      .getImplementationVersion();
	}

	/**
	 * @return the REST gateway version
	 */
	@XmlAttribute(name="REST")
	public String getRESTVersion() {
    return restVersion;
  }

	/**
	 * @return the JVM vendor and version
	 */
  @XmlAttribute(name="JVM")
  public String getJVMVersion() {
    return jvmVersion;
  }

  /**
   * @return the OS name, version, and hardware architecture
   */
  @XmlAttribute(name="OS")
  public String getOSVersion() {
    return osVersion;
  }

  /**
   * @return the servlet container version
   */
  @XmlAttribute(name="Server")
  public String getServerVersion() {
    return serverVersion;
  }

  /**
   * @return the version of the embedded Jersey framework
   */
  @XmlAttribute(name="Jersey")
  public String getJerseyVersion() {
    return jerseyVersion;
  }

  /**
   * @param version the REST gateway version string
   */
  public void setRESTVersion(String version) {
    this.restVersion = version;
  }

  /**
   * @param version the OS version string
   */
  public void setOSVersion(String version) {
    this.osVersion = version;
  }

  /**
   * @param version the JVM version string
   */
  public void setJVMVersion(String version) {
    this.jvmVersion = version;
  }

  /**
   * @param version the servlet container version string
   */
  public void setServerVersion(String version) {
    this.serverVersion = version;
  }

  /**
   * @param version the Jersey framework version string
   */
  public void setJerseyVersion(String version) {
    this.jerseyVersion = version;
  }

  /* (non-Javadoc)
	 * @see java.lang.Object#toString()
	 */
	@Override
	public String toString() {
	  StringBuilder sb = new StringBuilder();
	  sb.append("rest ");
	  sb.append(restVersion);
	  sb.append(" [JVM: ");
	  sb.append(jvmVersion);
	  sb.append("] [OS: ");
	  sb.append(osVersion);
	  sb.append("] [Server: ");
	  sb.append(serverVersion);
	  sb.append("] [Jersey: ");
    sb.append(jerseyVersion);
	  sb.append("]\n");
	  return sb.toString();
	}

	@Override
  public byte[] createProtobufOutput() {
	  Version.Builder builder = Version.newBuilder();
	  builder.setRestVersion(restVersion);
	  builder.setJvmVersion(jvmVersion);
	  builder.setOsVersion(osVersion);
	  builder.setServerVersion(serverVersion);
	  builder.setJerseyVersion(jerseyVersion);
	  return builder.build().toByteArray();
  }

  @Override
  public ProtobufMessageHandler getObjectFromMessage(byte[] message)
      throws IOException {
    Version.Builder builder = Version.newBuilder();
    builder.mergeFrom(message);
    if (builder.hasRestVersion()) {
      restVersion = builder.getRestVersion();
    }
    if (builder.hasJvmVersion()) {
      jvmVersion = builder.getJvmVersion();
    }
    if (builder.hasOsVersion()) {
      osVersion = builder.getOsVersion();
    }
    if (builder.hasServerVersion()) {
      serverVersion = builder.getServerVersion();
    }
    if (builder.hasJerseyVersion()) {
      jerseyVersion = builder.getJerseyVersion();
    }
    return this;
  }
}


text:
package ec2

import (
	"context"
	"fmt"
	awsmiddleware "github.com/aws/aws-sdk-go-v2/aws/middleware"
	"github.com/aws/aws-sdk-go-v2/aws/signer/v4"
	"github.com/aws/aws-sdk-go-v2/service/ec2/types"
	"github.com/aws/smithy-go/middleware"
	smithyhttp "github.com/aws/smithy-go/transport/http"
)

// Creates a Traffic Mirror filter. A Traffic Mirror filter is a set of rules that
// defines the traffic to mirror. By default, no traffic is mirrored. To mirror
// traffic, use CreateTrafficMirrorFilterRule
// (https://docs.aws.amazon.com/AWSEC2/latest/APIReference/API_CreateTrafficMirrorFilterRule.htm)
// to add Traffic Mirror rules to the filter. The rules you add define what traffic
// gets mirrored. You can also use ModifyTrafficMirrorFilterNetworkServices
// (https://docs.aws.amazon.com/AWSEC2/latest/APIReference/API_ModifyTrafficMirrorFilterNetworkServices.html)
// to mirror supported network services.
func (c *Client) CreateTrafficMirrorFilter(ctx context.Context, params *CreateTrafficMirrorFilterInput, optFns ...func(*Options)) (*CreateTrafficMirrorFilterOutput, error) {
	if params == nil {
		params = &CreateTrafficMirrorFilterInput{}
	}

	result, metadata, err := c.invokeOperation(ctx, "CreateTrafficMirrorFilter", params, optFns, c.addOperationCreateTrafficMirrorFilterMiddlewares)
	if err != nil {
		return nil, err
	}

	out := result.(*CreateTrafficMirrorFilterOutput)
	out.ResultMetadata = metadata
	return out, nil
}

type CreateTrafficMirrorFilterInput struct {

	// Unique, case-sensitive identifier that you provide to ensure the idempotency of
	// the request. For more information, see How to ensure idempotency
	// (https://docs.aws.amazon.com/AWSEC2/latest/APIReference/Run_Instance_Idempotency.html).
	ClientToken *string

	// The description of the Traffic Mirror filter.
	Description *string

	// Checks whether you have the required permissions for the action, without
	// actually making the request, and provides an error response. If you have the
	// required permissions, the error response is DryRunOperation. Otherwise, it is
	// UnauthorizedOperation.
	DryRun *bool

	// The tags to assign to a Traffic Mirror filter.
	TagSpecifications []types.TagSpecification

	noSmithyDocumentSerde
}

type CreateTrafficMirrorFilterOutput struct {

	// Unique, case-sensitive identifier that you provide to ensure the idempotency of
	// the request. For more information, see How to ensure idempotency
	// (https://docs.aws.amazon.com/AWSEC2/latest/APIReference/Run_Instance_Idempotency.html).
	ClientToken *string

	// Information about the Traffic Mirror filter.
	TrafficMirrorFilter *types.TrafficMirrorFilter

	// Metadata pertaining to the operation's result.
	ResultMetadata middleware.Metadata

	noSmithyDocumentSerde
}

func (c *Client) addOperationCreateTrafficMirrorFilterMiddlewares(stack *middleware.Stack, options Options) (err error) {
	err = stack.Serialize.Add(&awsEc2query_serializeOpCreateTrafficMirrorFilter{}, middleware.After)
	if err != nil {
		return err
	}
	err = stack.Deserialize.Add(&awsEc2query_deserializeOpCreateTrafficMirrorFilter{}, middleware.After)
	if err != nil {
		return err
	}
	if err = addSetLoggerMiddleware(stack, options); err != nil {
		return err
	}
	if err = awsmiddleware.AddClientRequestIDMiddleware(stack); err != nil {
		return err
	}
	if err = smithyhttp.AddComputeContentLengthMiddleware(stack); err != nil {
		return err
	}
	if err = addResolveEndpointMiddleware(stack, options); err != nil {
		return err
	}
	if err = v4.AddComputePayloadSHA256Middleware(stack); err != nil {
		return err
	}
	if err = addRetryMiddlewares(stack, options); err != nil {
		return err
	}
	if err = addHTTPSignerV4Middleware(stack, options); err != nil {
		return err
	}
	if err = awsmiddleware.AddRawResponseToMetadata(stack); err != nil {
		return err
	}
	if err = awsmiddleware.AddRecordResponseTiming(stack); err != nil {
		return err
	}
	if err = addClientUserAgent(stack); err != nil {
		return err
	}
	if err = smithyhttp.AddErrorCloseResponseBodyMiddleware(stack); err != nil {
		return err
	}
	if err = smithyhttp.AddCloseResponseBodyMiddleware(stack); err != nil {
		return err
	}
	if err = addIdempotencyToken_opCreateTrafficMirrorFilterMiddleware(stack, options); err != nil {
		return err
	}
	if err = stack.Initialize.Add(newServiceMetadataMiddleware_opCreateTrafficMirrorFilter(options.Region), middleware.Before); err != nil {
		return err
	}
	if err = addRequestIDRetrieverMiddleware(stack); err != nil {
		return err
	}
	if err = addResponseErrorMiddleware(stack); err != nil {
		return err
	}
	if err = addRequestResponseLogging(stack, options); err != nil {
		return err
	}
	return nil
}

type idempotencyToken_initializeOpCreateTrafficMirrorFilter struct {
	tokenProvider IdempotencyTokenProvider
}

func (*idempotencyToken_initializeOpCreateTrafficMirrorFilter) ID() string {
	return "OperationIdempotencyTokenAutoFill"
}

func (m *idempotencyToken_initializeOpCreateTrafficMirrorFilter) HandleInitialize(ctx context.Context, in middleware.InitializeInput, next middleware.InitializeHandler) (
	out middleware.InitializeOutput, metadata middleware.Metadata, err error,
) {
	if m.tokenProvider == nil {
		return next.HandleInitialize(ctx, in)
	}

	input, ok := in.Parameters.(*CreateTrafficMirrorFilterInput)
	if !ok {
		return out, metadata, fmt.Errorf("expected middleware input to be of type *CreateTrafficMirrorFilterInput ")
	}

	if input.ClientToken == nil {
		t, err := m.tokenProvider.GetIdempotencyToken()
		if err != nil {
			return out, metadata, err
		}
		input.ClientToken = &t
	}
	return next.HandleInitialize(ctx, in)
}
func addIdempotencyToken_opCreateTrafficMirrorFilterMiddleware(stack *middleware.Stack, cfg Options) error {
	return stack.Initialize.Add(&idempotencyToken_initializeOpCreateTrafficMirrorFilter{tokenProvider: cfg.IdempotencyTokenProvider}, middleware.Before)
}

func newServiceMetadataMiddleware_opCreateTrafficMirrorFilter(region string) *awsmiddleware.RegisterServiceMetadata {
	return &awsmiddleware.RegisterServiceMetadata{
		Region:        region,
		ServiceID:     ServiceID,
		SigningName:   "ec2",
		OperationName: "CreateTrafficMirrorFilter",
	}
}


text:
package edu.cmu.sv.ws.ssnoc.data.util;

import java.sql.Connection;
import java.sql.SQLException;

/**
 * This interface will define the methods that any ConnectionPool implementation
 * should implement.
 *
 */
public interface IConnectionPool {
	Connection getConnection() throws SQLException;
	public void switchConnectionToTest();
	public void switchConnectionToLive();
	public boolean isTest();
}


text:
/**
 * External dependencies
 */
import { __, _n, sprintf } from '@wordpress/i18n';
import { addQueryArgs } from '@wordpress/url';
import apiFetch from '@wordpress/api-fetch';
import { Component, Fragment } from '@wordpress/element';
import { find } from 'lodash';
import PropTypes from 'prop-types';
import { SearchListControl, SearchListItem } from '@woocommerce/components';
import { SelectControl } from '@wordpress/components';
import { ENDPOINTS } from '@woocommerce/block-settings';

/**
 * Internal dependencies
 */
import './style.scss';

class ProductCategoryControl extends Component {
	constructor() {
		super( ...arguments );
		this.state = {
			list: [],
			loading: true,
		};
		this.renderItem = this.renderItem.bind( this );
	}

	componentDidMount() {
		apiFetch( {
			path: addQueryArgs( `${ ENDPOINTS.products }/categories`, { per_page: -1 } ),
		} )
			.then( ( list ) => {
				this.setState( { list, loading: false } );
			} )
			.catch( () => {
				this.setState( { list: [], loading: false } );
			} );
	}

	renderItem( args ) {
		const { item, search, depth = 0 } = args;
		const classes = [
			'woocommerce-product-categories__item',
		];
		if ( search.length ) {
			classes.push( 'is-searching' );
		}
		if ( depth === 0 && item.parent !== 0 ) {
			classes.push( 'is-skip-level' );
		}

		const accessibleName = ! item.breadcrumbs.length ?
			item.name :
			`${ item.breadcrumbs.join( ', ' ) }, ${ item.name }`;

		return (
			<SearchListItem
				className={ classes.join( ' ' ) }
				{ ...args }
				showCount
				aria-label={ sprintf(
					_n(
						'%s, has %d product',
						'%s, has %d products',
						item.count,
						'woo-gutenberg-products-block'
					),
					accessibleName,
					item.count
				) }
			/>
		);
	}

	render() {
		const { list, loading } = this.state;
		const { onChange, onOperatorChange, operator, selected, isSingle } = this.props;

		const messages = {
			clear: __( 'Clear all product categories', 'woo-gutenberg-products-block' ),
			list: __( 'Product Categories', 'woo-gutenberg-products-block' ),
			noItems: __(
				"Your store doesn't have any product categories.",
				'woo-gutenberg-products-block'
			),
			search: __(
				'Search for product categories',
				'woo-gutenberg-products-block'
			),
			selected: ( n ) =>
				sprintf(
					_n(
						'%d category selected',
						'%d categories selected',
						n,
						'woo-gutenberg-products-block'
					),
					n
				),
			updated: __(
				'Category search results updated.',
				'woo-gutenberg-products-block'
			),
		};

		return (
			<Fragment>
				<SearchListControl
					className="woocommerce-product-categories"
					list={ list }
					isLoading={ loading }
					selected={ selected.map( ( id ) => find( list, { id } ) ).filter( Boolean ) }
					onChange={ onChange }
					renderItem={ this.renderItem }
					messages={ messages }
					isHierarchical
					isSingle={ isSingle }
				/>
				{ ( !! onOperatorChange ) && (
					<div className={ selected.length < 2 ? 'screen-reader-text' : '' }>
						<SelectControl
							className="woocommerce-product-categories__operator"
							label={ __( 'Display products matching', 'woo-gutenberg-products-block' ) }
							help={ __( 'Pick at least two categories to use this setting.', 'woo-gutenberg-products-block' ) }
							value={ operator }
							onChange={ onOperatorChange }
							options={ [
								{
									label: __( 'Any selected categories', 'woo-gutenberg-products-block' ),
									value: 'any',
								},
								{
									label: __( 'All selected categories', 'woo-gutenberg-products-block' ),
									value: 'all',
								},
							] }
						/>
					</div>
				) }
			</Fragment>
		);
	}
}

ProductCategoryControl.propTypes = {
	/**
	 * Callback to update the selected product categories.
	 */
	onChange: PropTypes.func.isRequired,
	/**
	 * Callback to update the category operator. If not passed in, setting is not used.
	 */
	onOperatorChange: PropTypes.func,
	/**
	 * Setting for whether products should match all or any selected categories.
	 */
	operator: PropTypes.oneOf( [ 'all', 'any' ] ),
	/**
	 * The list of currently selected category IDs.
	 */
	selected: PropTypes.array.isRequired,
	/**
	 * Allow only a single selection. Defaults to false.
	 */
	isSingle: PropTypes.bool,
};

ProductCategoryControl.defaultProps = {
	operator: 'any',
	isSingle: false,
};

export default ProductCategoryControl;


text:
<?xml version="1.0" encoding="utf-8"?>
<resources>
    <string-array name="recording_frequency_display">
        <item>1 minute</item>
        <item>2 minute</item>
        <item>3 minute</item>
        <item>5 minute</item>
        <item>10 minute</item>
        </string-array>
    <string-array name="recording_frequency_value">
        <item>60</item>
        <item>120</item>
        <item>180</item>
        <item>300</item>
        <item>600</item>
    </string-array>
</resources>


text:
@class NSString;

@interface GetUserRankDetailResponse_Button : WXPBGeneratedMessage
{
}

+ (void)initialize;

// Remaining properties
@property(retain, nonatomic) NSString *icon; // @dynamic icon;
@property(retain, nonatomic) NSString *title; // @dynamic title;
@property(retain, nonatomic) NSString *url; // @dynamic url;

@end


text:
SublimeDAL is a lightwieght C# based ORM. It's inspired by Dapper. I'm building this as an exercise to learn.

##Support
   ```
   Supports all .NET ADO providers.
   ```

### Initializing the context
   ```
   DbContext context = new DbContext(new ConnectionProvider(new ConnectionStringProvider()));
   string connectionStringKey = @"northwind";
   ```

### Simple select query
   ```
   string query = @"SELECT TOP 10 * FROM customers";
   List<Customer> customers = context.Query<Customer>(connectionStringKey, query, null);
   ```

### Parametrized SQL query
   ```
   string parameterizedQuery = @"SELECT * FROM Customers WHERE CustomerID = @customerId";
   string paramName = "customerId";
   string customerId = @"ALFKI";
   Tuple<string, object> t = new Tuple<string, object>(paramName, customerId);
   customers = context.Query<Customer>(connectionStringKey, parameterizedQuery, new List<Tuple<string, object>>() { t });
   ```

### Executing a procedure
   ```
   Tuple<string, object, DbType, ParameterDirection> procedureParam = new Tuple<string, object, DbType, ParameterDirection>("OrderID", 10248, DbType.Int32, ParameterDirection.Input);
   List<CustomerOrderDetail> details = context.Procedure<CustomerOrderDetail>(connectionStringKey, "dbo.CustOrdersDetail", new List<Tuple<string, object, DbType, ParameterDirection>>() { procedureParam });
   ```

### Insert data
   ```
   string insertQuery = @"insert into region (RegionID, RegionDescription)values (@regionId, @description)";
   var valueTupleList = new List<Tuple<string, object>>();
   Tuple<string, object> t1 = new Tuple<string, object>("regionId", 5);
   Tuple<string, object> t2 = new Tuple<string, object>("description", "MidWestern");

   int result = context.ExecuteQuery(connectionStringKey, insertQuery, new List<Tuple<string, object>>() { t1, t2 });
   ```

### Update data
   ```
   string updateQuery = @"UPDATE region SET RegionDescription = @description WHERE RegionID = @regionId";
   t2 = new Tuple<string, object>("description", "Mid-Western");
   result = context.ExecuteQuery(connectionStringKey, updateQuery, new List<Tuple<string, object>>() { t1, t2 });
   ```

### Delete data
   ```
   string deleteQuery = @"DELETE FROM region WHERE RegionID = @regionId";
   result = context.ExecuteQuery(connectionStringKey, deleteQuery, new List<Tuple<string, object>>() { t1 });
   ```

##Current known limitations
   ```
   * Cannot perform multiple inserts.
   ```
###License [MIT-License](License.md)


text:
use std::str::{FromStr, ParseBoolError};
use std::num::ParseIntError;
use std::fmt::{self, Display, Formatter};
use std::string;

#[derive(Debug)]
pub struct ParseValueError(());

#[derive(Debug)]
pub struct ParseNameError(());

impl From<ParseNameError> for ParseValueError {
    fn from(_: ParseNameError) -> Self { ParseValueError(()) }
}
impl From<ParseIntError> for ParseValueError {
    fn from(_: ParseIntError) -> Self { ParseValueError(()) }
}
impl From<ParseBoolError> for ParseValueError {
    fn from(_: ParseBoolError) -> Self { ParseValueError(()) }
}
// Required since String implements FromStr with Error = ()
impl From<string::ParseError> for ParseValueError {
    fn from(_: string::ParseError) -> Self { ParseValueError(()) }
}

macro_rules! declare_type {
    ($name:ident, Check) =>  { pub type $name = bool; };
    ($name:ident, Spin)  =>  { pub type $name = i64; };
    ($name:ident, Combo) =>  { pub type $name = u32; };
    ($name:ident, Button) => { pub type $name = (); };
    ($name:ident, String) => { pub type $name = String; };
}

macro_rules! to_owned {
    ($value:expr, String) => { $value.to_string() };
    ($value:expr, $kind:ident) => { $value };
}

macro_rules! info_impl {
    ($name:ident : Check() = $default:expr) => { Info::Check(Name::$name, $default) };
    ($name:ident : Spin($min:expr, $max:expr) = $default:expr) => { Info::Spin(Name::$name, $default, $min, $max) };
    ($name:ident : Combo($($val:expr),+) = $default:expr) => { Info::Combo(Name::$name, $default, &[$($val,)+]) };
    ($name:ident : Button() = $default:expr) => { Info::Button(Name::$name, $default) };
    ($name:ident : String() = $default:expr) => { Info::String(Name::$name, $default) };
}

macro_rules! parse_value {
    ($name:expr, Combo, $value_string:expr) => {{
        let temp = $name as usize; // work around an ICE
        let combo_list: &[&'static str] = match INFO[temp] {
            Info::Combo(_, _, x) => &x,
            _ => unreachable!(),
        };
        combo_list.iter().position(|x| *x == $value_string)
            .map_or(Err(ParseValueError(())), |x| Ok(x as u32))
    }};
    ($name:expr, Button, $value_string:expr) => { Ok::<(), ParseValueError>(()) };
    ($name:expr, Spin, $value_string:expr) => {{
        let val: i64 = try!($value_string.parse());
        let temp = $name as usize; // work around an ICE
        let (min_val, max_val): (i64, i64) = match INFO[temp] {
            Info::Spin(_, _, x, y) => (x, y),
            _ => unreachable!(),
        };
        if val >= min_val && val <= max_val {
            Ok(val)
        } else {
            Err(ParseValueError(()))
        }
    }};
    ($name:expr, $kind:ident, $value_string:expr) => {
        $value_string.parse()
    };
}

macro_rules! options_impl {
    (($num_opt:expr) options
     $(
         $name:ident ($field_name:ident, $str:expr) : $kind:ident ($($info:tt),*) = $default:expr,
      )+) => {

        mod type_of {
            $(declare_type!($name, $kind);)+
        }

        #[derive(PartialEq, Eq, Clone, Debug)]
        pub enum Value {
            $($name(type_of::$name),)+
        }

        #[derive(PartialEq, Eq, Copy, Clone, Debug)]
        pub enum Name {
            $($name,)+
        }

        pub const INFO: [Info; $num_opt] = [$(
            info_impl!($name: $kind($($info),*) = $default),
        )+];

        #[derive(Clone, Debug)]
        pub struct Data {
            $(
                pub $field_name: type_of::$name,
             )+
        }
        impl Data {
            pub fn new() -> Data {
                Data {
                    $(
                        $field_name: to_owned!($default, $kind),
                     )+
                }
            }
            pub fn set_value(&mut self, val: Value) {
                match val {
                    $(
                        Value::$name(x) => self.$field_name = x,
                     )+
                }
            }
        }

        impl FromStr for Value {
            type Err = ParseValueError;
            fn from_str(s: &str) -> Result<Self, ParseValueError> {
                // consume everything up to and including "name"
                let mut words = s.split(' ').skip_while(|&s| s != "name");
                words.next();

                let mut name_vec = Vec::<&str>::new();
                let mut value_vec = Vec::<&str>::new();

                let mut found_value = false;
                for curr_word in words {
                    if found_value {
                        value_vec.push(curr_word);
                    } else {
                        if curr_word == "value" {
                            found_value = true;
                        } else {
                            name_vec.push(curr_word);
                        }
                    }
                }

                let name_string  =  name_vec.join(" ").trim().to_string();
                let value_string = value_vec.join(" ").trim().to_string();

                let name: Name = try!(name_string.parse());
                Ok(match name {
                    $(
                        Name::$name => Value::$name(try!(
                                parse_value!(Name::$name, $kind, value_string))),
                    )+
                })
            }
        }

        impl FromStr for Name {
            type Err = ParseNameError;
            fn from_str(s: &str) -> Result<Self, ParseNameError> {
                match s {
                    $(
                        $str => Ok(Name::$name),
                     )+
                    _ => Err(ParseNameError(())),
                }
            }
        }

        impl Display for Name {
            fn fmt(&self, f: &mut Formatter) -> fmt::Result {
                match *self {
                    $(
                        Name::$name => write!(f, $str),
                     )+
                }
            }
        }
    }
}

options_impl!{
    (5) options
    Hash(hash_size, "hash"): Spin (1, 1024) = 1,
    TestCheck(test_check, "testcheck"): Check () = false,
    TestCombo(test_combo, "testcombo"): Combo ("foo", "bar", "baz") = 0,
    TestButton(test_button, "testbutton"): Button () = (),
    TestString(test_string, "teststring"): String () = "something",
}

#[derive(PartialEq, Eq, Copy, Clone, Debug)]
pub enum Type {
    Check,
    Spin,
    Combo,
    Button,
    String,
}

// The second fields of each variant are the default values
#[derive(PartialEq, Eq, Clone, Debug)]
pub enum Info {
    Check(Name, bool),
    Spin(Name, i64, i64, i64),
    Combo(Name, u32, &'static[&'static str]),
    Button(Name, ()),
    String(Name, &'static str),
}

impl Display for Info {
    fn fmt(&self, f: &mut Formatter) -> fmt::Result {
        match *self {
            Info::Check(name, default) =>
                write!(f, "name {} type check default {}", name, default),
            Info::Spin(name, default, min, max) =>
                write!(f, "name {} type spin default {} min {} max {}", name, default, min, max),
            Info::Combo(name, default, choices) => {
                try!(write!(f, "name {} type combo default {}", name, choices[default as usize]));
                for s in choices {
                    try!(write!(f, " var {}", s));
                }
                Ok(())
            },
            Info::Button(name, _) =>
                write!(f, "name {} type button", name),
            Info::String(name, default) =>
                write!(f, "name {} type string default {}", name, default),
        }
    }
}


text:
/* http://keith-wood.name/themes.html
   Applying CSS themes for jQuery v1.2.0.
   Written by Keith Wood (kbwood{at}iinet.com.au) September 2008.
   Dual licensed under the GPL (http://dev.jquery.com/browser/trunk/jquery/GPL-LICENSE.txt) and
   MIT (http://dev.jquery.com/browser/trunk/jquery/MIT-LICENSE.txt) licenses.
   Please attribute the author if you use it. */

/* Apply various themes to your site.
   Attach the functionality with options like:
   $('link').themes({themes: ['cupertino', 'smoothness']});
*/

(function($) { // Hide scope, no $ conflict

var COOKIE_NAME = 'themeID';

/* Theme sharing manager. */
function Themes() {
	this.currentTheme = '';
	this._uuid = new Date().getTime();
	this._linkID = 'th' + this._uuid;
	this._defaults = {
		themeBase: '',  // The base URL for all the theme files
		defaultTheme: '', // The ID of the default theme, first one if blank
		cookieExpiry: 0,  // The expiry time for the theme cookie, date or number of days
		cookiePath: '/',  // The path that the cookie applies to
		cookieDomain: '',  // The domain that the cookie applies to
		onSelect: null  // Callback on theme selection, theme ID and URL are passed as parameters
	};
	this._settings = {
		themes: [],  // List of theme IDs to use, empty for all
		icons: 'img/themes.gif', // Horizontal amalgamation of all theme icons
		iconSize: [23, 20],  // The width and height of the individual icons
		previews: 'img/themes-preview.gif', // Horizontal amalgamation of all theme previews
		previewSize: [90, 80],  // The width and height of the individual previews
		showPreview: true,  // True to display a popup preview, false to not show it
		compact: true  // True if a compact presentation should be used, false for full
	};
	this._themes = {  // The definitions of the available themes
		'blacktie': {display: 'Black Tie', icon: 0, preview: 0,
			url: 'black-tie/ui.all.css'},
		'blitzer': {display: 'Blitzer', icon: 1, preview: 1,
			url: 'blitzer/ui.all.css'},
		'cupertino': {display: 'Cupertino', icon: 2, preview: 2,
			url: 'cupertino/ui.all.css'},
		'darkhive': {display: 'Dark Hive', icon: 17, preview: 17,
			url: 'dark-hive/ui.all.css'},
		'dotluv': {display: 'Dot Luv', icon: 3, preview: 3,
			url: 'dot-luv/ui.all.css'},
		'eggplant': {display: 'Eggplant', icon: 18, preview: 18,
			url: 'eggplant/ui.all.css'},
		'excitebike': {display: 'Excite Bike', icon: 4, preview: 4,
			url: 'excite-bike/ui.all.css'},
		'flick': {display: 'Flick', icon: 19, preview: 19,
			url: 'flick/ui.all.css'},
		'hotsneaks': {display: 'Hot Sneaks', icon: 5, preview: 5,
			url: 'hot-sneaks/ui.all.css'},
		'humanity': {display: 'Humanity', icon: 6, preview: 6,
			url: 'humanity/ui.all.css'},
		'lefrog': {display: 'Le Frog', icon: 20, preview: 20,
			url: 'le-frog/ui.all.css'},
		'mintchoc': {display: 'Mint Choc', icon: 7, preview: 7,
			url: 'mint-choc/ui.all.css'},
		'overcast': {display: 'Overcast', icon: 21, preview: 21,
			url: 'overcast/ui.all.css'},
		'peppergrinder': {display: 'Pepper Grinder', icon: 22, preview: 22,
			url: 'pepper-grinder/ui.all.css'},
		'redmond': {display: 'Redmond', icon: 8, preview: 8,
			url: 'redmond/ui.all.css'},
		'smoothness': {display: 'Smoothness', icon: 9, preview: 9,
			url: 'smoothness/ui.all.css'},
		'southstreet': {display: 'South Street', icon: 10, preview: 10,
			url: 'south-street/ui.all.css'},
		'start': {display: 'Start', icon: 11, preview: 11,
			url: 'start/ui.all.css'},
		'sunny': {display: 'Sunny', icon: 23, preview: 23,
			url: 'sunny/ui.all.css'},
		'swankypurse': {display: 'Swanky Purse', icon: 12, preview: 12,
			url: 'swanky-purse/ui.all.css'},
		'trontastic': {display: 'Trontastic', icon: 13, preview: 13,
			url: 'trontastic/ui.all.css'},
		'uidarkness': {display: 'UI Darkess', icon: 14, preview: 14,
			url: 'ui-darkness/ui.all.css'},
		'uilightness': {display: 'UI Lightness', icon: 15, preview: 15,
			url: 'ui-lightness/ui.all.css'},
		'vader': {display: 'Vader', icon: 16, preview: 16,
			url: 'vader/ui.all.css'}
	};
}

$.extend(Themes.prototype, {
	/* Class name added to elements to indicate already configured with themeing. */
	markerClassName: 'hasThemes',

	/* Override the default settings for all theme instances.
	   @param  settings  (object) the new settings to use as defaults
	   @return  (Theme object) this object */
	setDefaults: function(settings) {
		extendRemove(this._defaults, settings || {});
		return this;
	},

	/* Initialise the theme for the page.
	   @param  settings  (object, optional) default settings to be used
	   @return  (Theme object) this object */
	init: function(settings) {
		if (settings) {
			this.setDefaults(settings);
		}
		var search = new RegExp(COOKIE_NAME + '=([^;]*)');
		var matches = search.exec(document.cookie);
		var themeId = (matches ? matches[1] : '') || this._defaults.defaultTheme;
		var firstId = '';
		var found = false;
		for (var id in this._themes) {
			firstId = firstId || id;
			found = (themeId == id);
			if (found) {
				break;
			}
		}
		themeId = (found ? themeId : firstId);
		this._setTheme(themeId, this._themes[themeId].display,
			this._defaults.themeBase + this._themes[themeId].url, true);
		return this;
	},

	/* Add a new theme to the list.
	   @param  id       (string) the ID of the new theme
	   @param  display  (string) the display name for this theme
	   @param  icon     (url) the location of an icon for this theme (25x22), or
	                    (number) the index of the icon within the combined image
	   @param  preview  (url) the location of a preview for this theme (105x92), or
	                    (number) the index of the preview within the combined image
	   @param  url      (url) the URL for the theme definition (CSS)
	   @return  (Theme object) this object */
	addTheme: function(id, display, icon, preview, url) {
		this._themes[id] = {display: display, icon: icon, preview: preview, url: url};
		return this;
	},

	/* Return the list of defined themes.
	   @return  (object[]) indexed by theme id (string), each object contains
	            display (string) the display name,
	            icon    (string) the location of the icon,, or
	                    (number) the icon's index in the combined image
	            url     (string) the URL for the theme's CSS definition */
	getThemes: function() {
		return this._themes;
	},

	/* Attach the themeing widget to a div.
	   @param  target    (element) the element to attach to
	   @param  settings  (object) the settings for this element */
	_attachThemes: function(target, settings) {
		target = $(target);
		if (target.hasClass(this.markerClassName)) {
			return;
		}
		target.addClass(this.markerClassName);
		this._updateTheme(target, settings);
	},

	/* Reconfigure the settings for a theme link.
	   @param  target    (element) the element to change settings for
	   @param  settings  (object) the changed settings for this element */
	_changeThemes: function(target, settings) {
		target = $(target);
		if (!target.hasClass(this.markerClassName)) {
			return;
		}
		this._updateTheme(target, settings);
	},

	/* Construct the requested themeing links.
	   @param  target    (element) the element to attach to
	   @param  settings  (object) the settings for this element */
	_updateTheme: function(target, settings) {
		settings = extendRemove($.extend({}, this._settings, this._defaults), settings);
		var themes = settings.themes;
		if (themes.length == 0) {
			$.each(this._themes, function(id) {
				themes[themes.length] = id;
			});
		}
		var escape = function(value) {
			return value.replace(/'/, '\\\'');
		};
		var previewId = 'th' + ++this._uuid;
		var html = '
';
		var allThemes = this._themes;
		$.each(themes, function(index, id) {
			var theme = allThemes[id];
			if (!theme) {
				return;
			}
			html += '
';
			if (theme.icon != null) {
				html += '<span title="' + theme.display + '"';
				if (typeof theme.icon == 'number') {
					html += ' style="background: transparent url(' + settings.icons +
						') no-repeat -' + (theme.icon * settings.iconSize[0]) + 'px 0px;' +
						($.browser.mozilla && $.browser.version < '1.9' ?
						' padding-left: ' + settings.iconSize[0] + 'px;' +
						' padding-bottom: ' + (settings.iconSize[1] - 16) + 'px;' : '') + '">';
				}
				else {
					html += '>';
				}
				html +=	'' + (settings.compact ? '' : ' ');
			}
			html +=	(settings.compact ? '' : theme.display) + '
';
		});
		html += '

';
		target.html(html);
	},

	/* Remove the themeing widget from a link. */
	_destroyThemes: function(target) {
		target = $(target);
		if (!target.hasClass(this.markerClassName)) {
			return;
		}
		target.removeClass(this.markerClassName).empty();
	},

	/* Load a new theme.
	   @param  id       (string) the ID of the new theme
	   @param  display  (string) the display name of the new theme
	   @param  url      (string) the location of the CSS
	   @param  loading  (boolean) true if initially loading */
	_setTheme: function(id, display, url, loading) {
		if ($('#' + $.themes._linkID).length == 0) {
			$('head').append('<link rel="stylesheet" type="text/css" id="' + $.themes._linkID + '"/>');
		}
		$('#' + $.themes._linkID).attr('href', url);
		$.themes.currentTheme = id;
		$('.' + $.themes.markerClassName + ' li').removeClass('themes_current');
		$('.themes__' + id).addClass('themes_current');
		// Custom callback
		var onSelect = $.themes._defaults.onSelect;
		if (onSelect) {
			onSelect.apply(window, [id, display, url]);
		}
		if (!loading) {
			// Calculate cookie expiry
			var addDays = function(days) {
				var date = new Date();
				date.setDate(date.getDate() + days);
				return date;
			};
			var expiryDate = ($.themes._defaults.cookieExpiry ?
				(typeof $.themes._defaults.cookieExpiry == 'number' ?
				addDays($.themes._defaults.cookieExpiry) : $.themes._defaults.cookieExpiry) : null);
			// Save theme setting as cookie
			document.cookie = COOKIE_NAME + '=' + id +
				(expiryDate ? '; expires=' + expiryDate.toUTCString() : '') +
				($.themes._defaults.cookiePath ? '; path=' + $.themes._defaults.cookiePath : '') +
				($.themes._defaults.cookieDomain ? '; domain=' + $.themes._defaults.cookieDomain : '');
		}
		return false;
	},

	/* Show the preview for the current theme.
	   @param  link     (element) the element containing the theme link
	   @param  id       (string) the ID of the preview division
	   @param  display  (string) the display text for this theme
	   @param  preview  (string) the URL of the preview image or
	                    (number) index into the combined previews
	   @param  width    (number) the width of the preview images */
	_showPreview: function(link, id, display, preview, width) {
		if (preview == null) {
			return;
		}
		var html = '';
		if (typeof preview == 'number') {
			$(id + ' div').show().
				css('background-position', '-' + (preview * width) + 'px 0px');
		}
		else {
			$(id + ' div').hide();
			html += '
';
		}
		html += '' + display + '';
		var parent = $(link).parent();
		var absParent = null;
		$(link).parents().each(function() {
			if ($(this).css('position') == 'absolute') {
				absParent = $(this);
			}
			return !absParent;
		});
		var offset = parent.offset();
		var absOffset = (absParent ? absParent.offset() : {left: 0, top: 0});
		var left = offset.left - absOffset.left + parseInt(parent.css('padding-left'), 10);
		var top = offset.top - absOffset.top + parent.height() +
			parseInt(parent.css('padding-top'), 10) + 1;
		$(id).children(':not(:first)').remove().end().
			append(html).css({left: left, top: top}).show();
	},

	/* Hide the theme preview.
	   @param  id  (string) the ID of the preview division */
	_hidePreview: function(id) {
		$(id).hide();
	}
});

/* jQuery extend now ignores nulls! */
function extendRemove(target, props) {
	$.extend(target, props);
	for (var name in props) {
		if (props[name] == null) {
			target[name] = null;
		}
	}
	return target;
}

/* Attach the themeing functionality to a jQuery selection.
   @param  command  (string) the command to run (optional, default 'attach')
   @param  options  (object) the new settings to use for these themeing instances
   @return  (jQuery object) for chaining further calls */
$.fn.themes = function(options) {
	var otherArgs = Array.prototype.slice.call(arguments, 1);
	return this.each(function() {
		if (typeof options == 'string') {
			$.themes['_' + options + 'Themes'].
				apply($.themes, [this].concat(otherArgs));
		}
		else {
			$.themes._attachThemes(this, options || {});
		}
	});
};

/* Initialise the themeing functionality. */
$.themes = new Themes(); // singleton instance

})(jQuery);