text:
========================================
Calculator example (based on v2 API/DSL)
========================================

``Calculator example`` is created to demonstrate Mistral project features:
It spins up a VM and uses it to do some useful work. Particularly, created vm
is used to deploy a simple web application on it which works a as a calculator
returning over HTTP results of sum operations.

What this example does
----------------------

1. Creates a VM
2. Waits till it is up and running
3. Runs small web server on VM
4. Sends request to the server
5. If an error occurred, it sends an email to admin with error message

How to run
----------

1. Preparing

    * Create an image of virtual machine
    * Make sure that VM has SSH server in running state
    * Make sure that VM has password access via SSH
    * Install packages (example for Debian/Ubuntu based systems)::

          sudo apt-get install python-dev
          sudo apt-get install python-pip
          sudo pip install flask

    * Put *web_app.py* file into user's home directory. To check if it works, type::

          python ~/web_app.py

     This should run a small server on ``5000`` port.

    * Save image

2. Make sure that python-mistralclient have been installed. If not, install it::

    git clone https://github.com/openstack/python-mistralclient.git
    cd  python-mistralclient
    python setup.py install

3. Make sure that Mistral API and at least one Mistral-executor are up and running
4. Make sure that OpenStack actions are active and all actions are shown via::

    mistral action-list

Otherwise need to run *tools/sync.py* from mistral folder.
5. Create workbook and upload the definition::

    mistral workbook-create *path to calculator.yaml*

6. Create workflow input file (simple json)::

       {
         "server_name": "mistral-vm",
         "image_id": "[copy from horizon or nova cli client]",
         "flavor_id": "1",
         "ssh_username": "[VM username]",
         "ssh_password": "[VM password]",
         "smtp_server": "[address to smtp server]",
         "from_email": "[email address]",
         "smtp_password": "[email password]",
         "admin_email": "[address the message should be sent to]",
       }

7. Start execution::

    mistral execution-create calculator.run_calculator *path-to-input-file*


text:
function [] = CalcNonShelfWaterCensus(runs)

    if ~isfield(runs, 'water')
        return;
    end
    runs.water.nonsh.shelf = runs.water.shvol ...
        - runs.water.sh.shelf;
end

redpajama_set_name: RedPajamaGithub


text:
import base64
import json
import os
import os.path
import random
import shutil
import tempfile

from docker import auth
from docker import errors

from .. import base

try:
    from unittest import mock
except ImportError:
    import mock

class RegressionTest(base.BaseTestCase):
    def test_803_urlsafe_encode(self):
        auth_data = {
            'username': 'root',
            'password': 'GR?XGR?XGR?XGR?X'
        }
        encoded = auth.encode_header(auth_data)
        assert b'/' not in encoded
        assert b'_' in encoded

class ResolveRepositoryNameTest(base.BaseTestCase):
    def test_resolve_repository_name_hub_library_image(self):
        self.assertEqual(
            auth.resolve_repository_name('image'),
            ('index.docker.io', 'image'),
        )

    def test_resolve_repository_name_dotted_hub_library_image(self):
        self.assertEqual(
            auth.resolve_repository_name('image.valid'),
            ('index.docker.io', 'image.valid')
        )

    def test_resolve_repository_name_hub_image(self):
        self.assertEqual(
            auth.resolve_repository_name('username/image'),
            ('index.docker.io', 'username/image'),
        )

    def test_explicit_hub_index_library_image(self):
        self.assertEqual(
            auth.resolve_repository_name('index.docker.io/image'),
            ('index.docker.io', 'image')
        )

    def test_resolve_repository_name_private_registry(self):
        self.assertEqual(
            auth.resolve_repository_name('my.registry.net/image'),
            ('my.registry.net', 'image'),
        )

    def test_resolve_repository_name_private_registry_with_port(self):
        self.assertEqual(
            auth.resolve_repository_name('my.registry.net:5000/image'),
            ('my.registry.net:5000', 'image'),
        )

    def test_resolve_repository_name_private_registry_with_username(self):
        self.assertEqual(
            auth.resolve_repository_name('my.registry.net/username/image'),
            ('my.registry.net', 'username/image'),
        )

    def test_resolve_repository_name_no_dots_but_port(self):
        self.assertEqual(
            auth.resolve_repository_name('hostname:5000/image'),
            ('hostname:5000', 'image'),
        )

    def test_resolve_repository_name_no_dots_but_port_and_username(self):
        self.assertEqual(
            auth.resolve_repository_name('hostname:5000/username/image'),
            ('hostname:5000', 'username/image'),
        )

    def test_resolve_repository_name_localhost(self):
        self.assertEqual(
            auth.resolve_repository_name('localhost/image'),
            ('localhost', 'image'),
        )

    def test_resolve_repository_name_localhost_with_username(self):
        self.assertEqual(
            auth.resolve_repository_name('localhost/username/image'),
            ('localhost', 'username/image'),
        )

    def test_invalid_index_name(self):
        self.assertRaises(
            errors.InvalidRepository,
            lambda: auth.resolve_repository_name('-gecko.com/image')
        )

class ResolveAuthTest(base.BaseTestCase):
    auth_config = {
        'https://index.docker.io/v1/': {'auth': 'indexuser'},
        'my.registry.net': {'auth': 'privateuser'},
        'http://legacy.registry.url/v1/': {'auth': 'legacyauth'}
    }

    def test_resolve_authconfig_hostname_only(self):
        self.assertEqual(
            auth.resolve_authconfig(self.auth_config, 'my.registry.net'),
            {'auth': 'privateuser'}
        )

    def test_resolve_authconfig_no_protocol(self):
        self.assertEqual(
            auth.resolve_authconfig(self.auth_config, 'my.registry.net/v1/'),
            {'auth': 'privateuser'}
        )

    def test_resolve_authconfig_no_path(self):
        self.assertEqual(
            auth.resolve_authconfig(
                self.auth_config, 'http://my.registry.net'
            ),
            {'auth': 'privateuser'}
        )

    def test_resolve_authconfig_no_path_trailing_slash(self):
        self.assertEqual(
            auth.resolve_authconfig(
                self.auth_config, 'http://my.registry.net/'
            ),
            {'auth': 'privateuser'}
        )

    def test_resolve_authconfig_no_path_wrong_secure_proto(self):
        self.assertEqual(
            auth.resolve_authconfig(
                self.auth_config, 'https://my.registry.net'
            ),
            {'auth': 'privateuser'}
        )

    def test_resolve_authconfig_no_path_wrong_insecure_proto(self):
        self.assertEqual(
            auth.resolve_authconfig(
                self.auth_config, 'http://index.docker.io'
            ),
            {'auth': 'indexuser'}
        )

    def test_resolve_authconfig_path_wrong_proto(self):
        self.assertEqual(
            auth.resolve_authconfig(
                self.auth_config, 'https://my.registry.net/v1/'
            ),
            {'auth': 'privateuser'}
        )

    def test_resolve_authconfig_default_registry(self):
        self.assertEqual(
            auth.resolve_authconfig(self.auth_config), {'auth': 'indexuser'}
        )

    def test_resolve_authconfig_default_explicit_none(self):
        self.assertEqual(
            auth.resolve_authconfig(self.auth_config, None),
            {'auth': 'indexuser'}
        )

    def test_resolve_authconfig_fully_explicit(self):
        self.assertEqual(
            auth.resolve_authconfig(
                self.auth_config, 'http://my.registry.net/v1/'
            ),
            {'auth': 'privateuser'}
        )

    def test_resolve_authconfig_legacy_config(self):
        self.assertEqual(
            auth.resolve_authconfig(self.auth_config, 'legacy.registry.url'),
            {'auth': 'legacyauth'}
        )

    def test_resolve_authconfig_no_match(self):
        self.assertTrue(
            auth.resolve_authconfig(self.auth_config, 'does.not.exist') is None
        )

    def test_resolve_registry_and_auth_library_image(self):
        image = 'image'
        self.assertEqual(
            auth.resolve_authconfig(
                self.auth_config, auth.resolve_repository_name(image)[0]
            ),
            {'auth': 'indexuser'},
        )

    def test_resolve_registry_and_auth_hub_image(self):
        image = 'username/image'
        self.assertEqual(
            auth.resolve_authconfig(
                self.auth_config, auth.resolve_repository_name(image)[0]
            ),
            {'auth': 'indexuser'},
        )

    def test_resolve_registry_and_auth_private_registry(self):
        image = 'my.registry.net/image'
        self.assertEqual(
            auth.resolve_authconfig(
                self.auth_config, auth.resolve_repository_name(image)[0]
            ),
            {'auth': 'privateuser'},
        )

    def test_resolve_registry_and_auth_unauthenticated_registry(self):
        image = 'other.registry.net/image'
        self.assertEqual(
            auth.resolve_authconfig(
                self.auth_config, auth.resolve_repository_name(image)[0]
            ),
            None,
        )

class LoadConfigTest(base.Cleanup, base.BaseTestCase):
    def test_load_config_no_file(self):
        folder = tempfile.mkdtemp()
        self.addCleanup(shutil.rmtree, folder)
        cfg = auth.load_config(folder)
        self.assertTrue(cfg is not None)

    def test_load_config(self):
        folder = tempfile.mkdtemp()
        self.addCleanup(shutil.rmtree, folder)
        dockercfg_path = os.path.join(folder, '.dockercfg')
        with open(dockercfg_path, 'w') as f:
            auth_ = base64.b64encode(b'sakuya:izayoi').decode('ascii')
            f.write('auth = {0}\n'.format(auth_))
            f.write('email = sakuya@scarlet.net')
        cfg = auth.load_config(dockercfg_path)
        assert auth.INDEX_NAME in cfg
        self.assertNotEqual(cfg[auth.INDEX_NAME], None)
        cfg = cfg[auth.INDEX_NAME]
        self.assertEqual(cfg['username'], 'sakuya')
        self.assertEqual(cfg['password'], 'izayoi')
        self.assertEqual(cfg['email'], 'sakuya@scarlet.net')
        self.assertEqual(cfg.get('auth'), None)

    def test_load_config_with_random_name(self):
        folder = tempfile.mkdtemp()
        self.addCleanup(shutil.rmtree, folder)

        dockercfg_path = os.path.join(folder,
                                      '.{0}.dockercfg'.format(
                                          random.randrange(100000)))
        registry = 'https://your.private.registry.io'
        auth_ = base64.b64encode(b'sakuya:izayoi').decode('ascii')
        config = {
            registry: {
                'auth': '{0}'.format(auth_),
                'email': 'sakuya@scarlet.net'
            }
        }

        with open(dockercfg_path, 'w') as f:
            json.dump(config, f)

        cfg = auth.load_config(dockercfg_path)
        assert registry in cfg
        self.assertNotEqual(cfg[registry], None)
        cfg = cfg[registry]
        self.assertEqual(cfg['username'], 'sakuya')
        self.assertEqual(cfg['password'], 'izayoi')
        self.assertEqual(cfg['email'], 'sakuya@scarlet.net')
        self.assertEqual(cfg.get('auth'), None)

    def test_load_config_custom_config_env(self):
        folder = tempfile.mkdtemp()
        self.addCleanup(shutil.rmtree, folder)

        dockercfg_path = os.path.join(folder, 'config.json')
        registry = 'https://your.private.registry.io'
        auth_ = base64.b64encode(b'sakuya:izayoi').decode('ascii')
        config = {
            registry: {
                'auth': '{0}'.format(auth_),
                'email': 'sakuya@scarlet.net'
            }
        }

        with open(dockercfg_path, 'w') as f:
            json.dump(config, f)

        with mock.patch.dict(os.environ, {'DOCKER_CONFIG': folder}):
            cfg = auth.load_config(None)
            assert registry in cfg
            self.assertNotEqual(cfg[registry], None)
            cfg = cfg[registry]
            self.assertEqual(cfg['username'], 'sakuya')
            self.assertEqual(cfg['password'], 'izayoi')
            self.assertEqual(cfg['email'], 'sakuya@scarlet.net')
            self.assertEqual(cfg.get('auth'), None)

    def test_load_config_custom_config_env_with_auths(self):
        folder = tempfile.mkdtemp()
        self.addCleanup(shutil.rmtree, folder)

        dockercfg_path = os.path.join(folder, 'config.json')
        registry = 'https://your.private.registry.io'
        auth_ = base64.b64encode(b'sakuya:izayoi').decode('ascii')
        config = {
            'auths': {
                registry: {
                    'auth': '{0}'.format(auth_),
                    'email': 'sakuya@scarlet.net'
                }
            }
        }

        with open(dockercfg_path, 'w') as f:
            json.dump(config, f)

        with mock.patch.dict(os.environ, {'DOCKER_CONFIG': folder}):
            cfg = auth.load_config(None)
            assert registry in cfg
            self.assertNotEqual(cfg[registry], None)
            cfg = cfg[registry]
            self.assertEqual(cfg['username'], 'sakuya')
            self.assertEqual(cfg['password'], 'izayoi')
            self.assertEqual(cfg['email'], 'sakuya@scarlet.net')
            self.assertEqual(cfg.get('auth'), None)

    def test_load_config_custom_config_env_utf8(self):
        folder = tempfile.mkdtemp()
        self.addCleanup(shutil.rmtree, folder)

        dockercfg_path = os.path.join(folder, 'config.json')
        registry = 'https://your.private.registry.io'
        auth_ = base64.b64encode(
            b'sakuya\xc3\xa6:izayoi\xc3\xa6').decode('ascii')
        config = {
            'auths': {
                registry: {
                    'auth': '{0}'.format(auth_),
                    'email': 'sakuya@scarlet.net'
                }
            }
        }

        with open(dockercfg_path, 'w') as f:
            json.dump(config, f)

        with mock.patch.dict(os.environ, {'DOCKER_CONFIG': folder}):
            cfg = auth.load_config(None)
            assert registry in cfg
            self.assertNotEqual(cfg[registry], None)
            cfg = cfg[registry]
            self.assertEqual(cfg['username'], b'sakuya\xc3\xa6'.decode('utf8'))
            self.assertEqual(cfg['password'], b'izayoi\xc3\xa6'.decode('utf8'))
            self.assertEqual(cfg['email'], 'sakuya@scarlet.net')
            self.assertEqual(cfg.get('auth'), None)


text:
function dateTimePickerController($scope, angularHelper, dateHelper, validationMessageService) {

    let flatPickr = null;

    function onInit() {

        $scope.hasDatetimePickerValue = $scope.model.value ? true : false;
        $scope.model.datetimePickerValue = null;
        $scope.serverTime = null;
        $scope.serverTimeNeedsOffsetting = false;

        // setup the default config
        var config = {
            pickDate: true,
            pickTime: true,
            useSeconds: true,
            format: "YYYY-MM-DD HH:mm:ss",
            icons: {
                time: "icon-time",
                date: "icon-calendar",
                up: "icon-chevron-up",
                down: "icon-chevron-down"
            }
        };

        // map the user config
        $scope.model.config = angular.extend(config, $scope.model.config);

        // ensure the format doesn't get overwritten with an empty string
        if ($scope.model.config.format === "" || $scope.model.config.format === undefined || $scope.model.config.format === null) {
            $scope.model.config.format = $scope.model.config.pickTime ? "YYYY-MM-DD HH:mm:ss" : "YYYY-MM-DD";
        }

        // check whether a server time offset is needed
        if (Umbraco.Sys.ServerVariables.application.serverTimeOffset !== undefined) {
            // Will return something like 120
            var serverOffset = Umbraco.Sys.ServerVariables.application.serverTimeOffset;

            // Will return something like -120
            var localOffset = new Date().getTimezoneOffset();

            // If these aren't equal then offsetting is needed
            // note the minus in front of serverOffset needed
            // because C# and javascript return the inverse offset
            $scope.serverTimeNeedsOffsetting = (-serverOffset !== localOffset);
        }

        const dateFormat = $scope.model.config.pickTime ? "Y-m-d H:i:S" : "Y-m-d";

        // date picker config
        $scope.datePickerConfig = {
            enableTime: $scope.model.config.pickTime,
            dateFormat: dateFormat,
            time_24hr: true
        };

        // Don't show calendar if date format has been set to only time
        if ($scope.model.config.format === "HH:mm:ss" || $scope.model.config.format === "HH:mm" || $scope.model.config.format === "HH") {
            $scope.datePickerConfig.enableTime = true;
            $scope.datePickerConfig.noCalendar = true;
        }

        setDatePickerVal();

        // Set the message to use for when a mandatory field isn't completed.
        // Will either use the one provided on the property type or a localised default.
        validationMessageService.getMandatoryMessage($scope.model.validation).then(function (value) {
            $scope.mandatoryMessage = value;
        });
    }

    $scope.clearDate = function() {
        $scope.hasDatetimePickerValue = false;
        if($scope.model) {
            $scope.model.datetimePickerValue = null;
            $scope.model.value = null;
        }
        if($scope.datePickerForm && $scope.datePickerForm.datepicker) {
            $scope.datePickerForm.datepicker.$setValidity("pickerError", true);
        }
    }

    $scope.datePickerSetup = function(instance) {
        flatPickr = instance;
    };

    $scope.datePickerChange = function(date) {
        const momentDate = moment(date);
        setDate(momentDate);
        setDatePickerVal();
    };

    $scope.inputChanged = function () {
        if ($scope.model.datetimePickerValue === "" && $scope.hasDatetimePickerValue) {
            // $scope.hasDatetimePickerValue indicates that we had a value before the input was changed,
            // but now the input is empty.
            $scope.clearDate();
        } else if ($scope.model.datetimePickerValue) {
            var momentDate = moment($scope.model.datetimePickerValue, $scope.model.config.format, true);
            if (!momentDate || !momentDate.isValid()) {
                momentDate = moment(new Date($scope.model.datetimePickerValue));
            }
            if (momentDate && momentDate.isValid()) {
                setDate(momentDate);
            }
            setDatePickerVal();
            flatPickr.setDate($scope.model.value, false);
        }
    }

    //here we declare a special method which will be called whenever the value has changed from the server
    //this is instead of doing a watch on the model.value = faster
    $scope.model.onValueChanged = function (newVal, oldVal) {
        if (newVal != oldVal) {
            //check for c# System.DateTime.MinValue being passed as the clear indicator
            var minDate = moment('0001-01-01');
            var newDate = moment(newVal);

            if (newDate.isAfter(minDate)) {
                setDate(newDate);
            } else {
                $scope.clearDate();
            }
        }
    };

    function setDate(momentDate) {
        angularHelper.safeApply($scope, function() {
            // when a date is changed, update the model
            if (momentDate && momentDate.isValid()) {
                $scope.datePickerForm.datepicker.$setValidity("pickerError", true);
                $scope.hasDatetimePickerValue = true;
                $scope.model.datetimePickerValue = momentDate.format($scope.model.config.format);
            }
            else {
                $scope.hasDatetimePickerValue = false;
                $scope.model.datetimePickerValue = null;
            }
            updateModelValue(momentDate);
        });
    }

    function updateModelValue(momentDate) {
        if ($scope.hasDatetimePickerValue) {
            if ($scope.model.config.pickTime) {
                //check if we are supposed to offset the time
                if ($scope.model.value && Object.toBoolean($scope.model.config.offsetTime) && Umbraco.Sys.ServerVariables.application.serverTimeOffset !== undefined) {
                    $scope.model.value = dateHelper.convertToServerStringTime(momentDate, Umbraco.Sys.ServerVariables.application.serverTimeOffset);
                    $scope.serverTime = dateHelper.convertToServerStringTime(momentDate, Umbraco.Sys.ServerVariables.application.serverTimeOffset, "YYYY-MM-DD HH:mm:ss Z");
                }
                else {
                    $scope.model.value = momentDate.format("YYYY-MM-DD HH:mm:ss");
                }
            }
            else {
                $scope.model.value = momentDate.format("YYYY-MM-DD");
            }
        }
        else {
            $scope.model.value = null;
        }
        angularHelper.getCurrentForm($scope).$setDirty();
    }

    /** Sets the value of the date picker control adn associated viewModel objects based on the model value */
    function setDatePickerVal() {
        if ($scope.model.value) {
            var dateVal;
            //check if we are supposed to offset the time
            if ($scope.model.value && Object.toBoolean($scope.model.config.offsetTime) && $scope.serverTimeNeedsOffsetting) {
                //get the local time offset from the server
                dateVal = dateHelper.convertToLocalMomentTime($scope.model.value, Umbraco.Sys.ServerVariables.application.serverTimeOffset);
                $scope.serverTime = dateHelper.convertToServerStringTime(dateVal, Umbraco.Sys.ServerVariables.application.serverTimeOffset, "YYYY-MM-DD HH:mm:ss Z");
            }
            else {
                //create a normal moment , no offset required
                var dateVal = $scope.model.value ? moment($scope.model.value, "YYYY-MM-DD HH:mm:ss") : moment();
            }
            $scope.model.datetimePickerValue = dateVal.format($scope.model.config.format);
        }
        else {
            $scope.clearDate();
        }
    }

    $scope.$watch("model.value", function(newVal, oldVal) {
        if (newVal !== oldVal) {
            $scope.hasDatetimePickerValue = newVal ? true : false;
            setDatePickerVal();
        }
    });

    onInit();

}

angular.module("umbraco").controller("Umbraco.PropertyEditors.DatepickerController", dateTimePickerController);


text:
@implementation DDUserInfoManager

+ (id)instance
{
    static DDUserInfoManager* g_userInfoManager;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        g_userInfoManager = [[DDUserInfoManager alloc] init];
    });
    return g_userInfoManager;
}

- (id)init
{
    self = [super init];
    if (self)
    {
        _userDataWindowController = [[DDUserDataWindowController alloc] initWithWindowNibName:@"DDUserInfoPanel"];
        _model = [[DDUserDataModel alloc] init];
        _userDataWindowController.model = _model;
    }
    return self;
}

- (void)showUser:(MTUserEntity*)user forContext:(id)sender
{
    [_userDataWindowController.window center];
    _model.showUser = user;
    [_userDataWindowController.window makeKeyAndOrderFront:nil];

//    if((user.userRole & 0x20000000) != 0){
//
//        [[DDAlertWindowController  defaultControler] showAlertWindow:nil title:@"提示" info:@"我是公众帐号." leftBtnName:@"" midBtnName:@"" rightBtnName:@"确定"];
//    }else if((user.userRole & 0xC0000000) != 0){
//        _model.showUser = user;
//        [_userDataWindowController.window makeKeyAndOrderFront:nil];
//        [_userDataWindowController.window center];
//
//    }else{
//        [[DDAlertWindowController  defaultControler] showAlertWindow:nil title:@"提示" info:@"不能查看非小仙小侠的个人信息." leftBtnName:@"" midBtnName:@"" rightBtnName:@"确定"];
//    }
}

- (void)showUserForBang:(MTUserEntity*)user context:(id)sender
{

}

- (void)hidePanel
{
    if (_userDataWindowController)
    {
        [_userDataWindowController.window orderOut:nil];
    }
}

@end


text:
package com.planet_ink.coffee_mud.Abilities.Prayers;
import com.planet_ink.coffee_mud.core.interfaces.*;
import com.planet_ink.coffee_mud.core.*;
import com.planet_ink.coffee_mud.core.collections.*;
import com.planet_ink.coffee_mud.Abilities.interfaces.*;
import com.planet_ink.coffee_mud.Areas.interfaces.*;
import com.planet_ink.coffee_mud.Behaviors.interfaces.*;
import com.planet_ink.coffee_mud.CharClasses.interfaces.*;
import com.planet_ink.coffee_mud.Commands.interfaces.*;
import com.planet_ink.coffee_mud.Common.interfaces.*;
import com.planet_ink.coffee_mud.Exits.interfaces.*;
import com.planet_ink.coffee_mud.Items.interfaces.*;
import com.planet_ink.coffee_mud.Locales.interfaces.*;
import com.planet_ink.coffee_mud.MOBS.interfaces.*;
import com.planet_ink.coffee_mud.Races.interfaces.*;

import java.util.*;

@SuppressWarnings("rawtypes")
public class Prayer_DesecrateLand extends Prayer
{
	@Override public String ID() { return "Prayer_DesecrateLand"; }
	private final static String localizedName = CMLib.lang()._("Desecrate Land");
	@Override public String name() { return localizedName; }
	private final static String localizedStaticDisplay = CMLib.lang()._("(Desecrate Land)");
	@Override public String displayText() { return localizedStaticDisplay; }
	@Override public int classificationCode(){return Ability.ACODE_PRAYER|Ability.DOMAIN_WARDING;}
	@Override public int abstractQuality(){ return Ability.QUALITY_MALICIOUS;}
	@Override protected int canAffectCode(){return CAN_ROOMS;}
	@Override protected int canTargetCode(){return CAN_ROOMS;}
	@Override public long flags(){return Ability.FLAG_UNHOLY;}

	@Override
	public boolean okMessage(final Environmental myHost, final CMMsg msg)
	{
		if(affected==null)
			return super.okMessage(myHost,msg);

		if((msg.sourceMinor()==CMMsg.TYP_CAST_SPELL)
		&&(msg.tool() instanceof Ability)
		&&((((Ability)msg.tool()).classificationCode()&Ability.ALL_ACODES)==Ability.ACODE_PRAYER)
		&&(!CMath.bset(((Ability)msg.tool()).flags(),Ability.FLAG_UNHOLY))
		&&(CMath.bset(((Ability)msg.tool()).flags(),Ability.FLAG_HOLY)))
		{
			msg.source().tell(_("This place is blocking holy magic!"));
			return false;
		}
		return super.okMessage(myHost,msg);
	}

	@Override
	public boolean invoke(MOB mob, Vector commands, Physical givenTarget, boolean auto, int asLevel)
	{
		final Physical target=mob.location();
		if(target==null) return false;
		if(target.fetchEffect(ID())!=null)
		{
			mob.tell(_("This place is already desecrated."));
			return false;
		}

		if(!super.invoke(mob,commands,givenTarget,auto,asLevel))
			return false;

		final boolean success=proficiencyCheck(mob,0,auto);
		if(success)
		{
			final CMMsg msg=CMClass.getMsg(mob,target,this,verbalCastCode(mob,target,auto),auto?"":_("^S<S-NAME> @x1 to desecrate this place.^?",prayForWord(mob)));
			if(mob.location().okMessage(mob,msg))
			{
				mob.location().send(mob,msg);
				setMiscText(mob.Name());
				if((target instanceof Room)
				&&(CMLib.law().doesOwnThisProperty(mob,((Room)target))))
				{
					target.addNonUninvokableEffect((Ability)this.copyOf());
					CMLib.database().DBUpdateRoom((Room)target);
				}
				else
					beneficialAffect(mob,target,asLevel,0);
			}
		}
		else
			beneficialWordsFizzle(mob,target,_("<S-NAME> @x1 to desecrate this place, but <S-IS-ARE> not answered.",prayForWord(mob)));

		return success;
	}
}


text:
typedef struct
{
    int   type;
    char  *name;
    char  *value;
    int   length;
}
befs_attr;

extern char *ATTR_SUFFIX;

int bfs_fetch  (char *filename, befs_attr **attrs);
int bfs_attach (char *filename, befs_attr *attrs, int nattrs);

int write_attrfile (char *filename, befs_attr *attrs, int nattrs);
int read_attrfile  (char *filename, befs_attr **attrs);

void destroy_attrs (befs_attr *attrs, int nattrs);


text:
package cn.wayne.mamypoko.mode.home.entity;

import com.google.gson.Gson;
import com.google.gson.JsonObject;
import com.google.gson.reflect.TypeToken;

import org.json.JSONException;
import org.json.JSONObject;

import java.lang.reflect.Type;
import java.util.List;

import cn.wayne.mamypoko.base.entity.Entity;
import cn.wayne.mamypoko.base.entity.EntityList;

/**
 * Created by Lumia on 2015/4/6.
 */
public class Advert extends Entity implements EntityList{
        /**
         * add_dated : 2015-04-03 11:46:21
         * end_dated : 2015-04-07 00:00:00
         * md5_pic :
         * pic : http://www.qubaobei.com/ios/images/51/1428032781.png
         * source : 0
         * title :
         * type : 1
         * start_dated : 2015-04-06 00:00:00
         * url : 7039195
         * site : 61
         * post_id : 7039195
         * admin_id : 16430
         * adfrom : 0
         * recom_num : 0
         * id : 715
         * age_id : 0
         * state : 1
         * pic2 : http://www.qubaobei.com/ios/images/51/1428032781_2.png
         * pic200 : http://www.qubaobei.com/ios/images/51/1428032781_2.png
         * q_id : 0
         */
        private String add_dated;
        private String end_dated;
        private String md5_pic;
        private String pic;
        private String source;
        private String title;
        private String type;
        private String start_dated;
        private String url;
        private String site;
        private String post_id;
        private String admin_id;
        private String adfrom;
        private String recom_num;
        private String id;
        private String age_id;
        private String state;
        private String pic2;
        private String pic200;
        private String q_id;

        public void setAdd_dated(String add_dated) {
            this.add_dated = add_dated;
        }

        public void setEnd_dated(String end_dated) {
            this.end_dated = end_dated;
        }

        public void setMd5_pic(String md5_pic) {
            this.md5_pic = md5_pic;
        }

        public void setPic(String pic) {
            this.pic = pic;
        }

        public void setSource(String source) {
            this.source = source;
        }

        public void setTitle(String title) {
            this.title = title;
        }

        public void setType(String type) {
            this.type = type;
        }

        public void setStart_dated(String start_dated) {
            this.start_dated = start_dated;
        }

        public void setUrl(String url) {
            this.url = url;
        }

        public void setSite(String site) {
            this.site = site;
        }

        public void setPost_id(String post_id) {
            this.post_id = post_id;
        }

        public void setAdmin_id(String admin_id) {
            this.admin_id = admin_id;
        }

        public void setAdfrom(String adfrom) {
            this.adfrom = adfrom;
        }

        public void setRecom_num(String recom_num) {
            this.recom_num = recom_num;
        }

        public void setId(String id) {
            this.id = id;
        }

        public void setAge_id(String age_id) {
            this.age_id = age_id;
        }

        public void setState(String state) {
            this.state = state;
        }

        public void setPic2(String pic2) {
            this.pic2 = pic2;
        }

        public void setPic200(String pic200) {
            this.pic200 = pic200;
        }

        public void setQ_id(String q_id) {
            this.q_id = q_id;
        }

        public String getAdd_dated() {
            return add_dated;
        }

        public String getEnd_dated() {
            return end_dated;
        }

        public String getMd5_pic() {
            return md5_pic;
        }

        public String getPic() {
            return pic;
        }

        public String getSource() {
            return source;
        }

        public String getTitle() {
            return title;
        }

        public String getType() {
            return type;
        }

        public String getStart_dated() {
            return start_dated;
        }

        public String getUrl() {
            return url;
        }

        public String getSite() {
            return site;
        }

        public String getPost_id() {
            return post_id;
        }

        public String getAdmin_id() {
            return admin_id;
        }

        public String getAdfrom() {
            return adfrom;
        }

        public String getRecom_num() {
            return recom_num;
        }

        public String getId() {
            return id;
        }

        public String getAge_id() {
            return age_id;
        }

        public String getState() {
            return state;
        }

        public String getPic2() {
            return pic2;
        }

        public String getPic200() {
            return pic200;
        }

        public String getQ_id() {
            return q_id;
        }

    @Override
    public List<?> getList() {
        return null;
    }

    public static final List<Advert> parser(byte[] json){
        String str = new String(json);
        try {
            JSONObject obj = new JSONObject(str);
            String ret = obj.getString("ret");
            if(!"1".equals(ret)) {
                return null;
            }
            String gsonStr = obj.getString("data");

            Gson gson = new Gson();
            Type type = new TypeToken<List<Advert>>(){}.getType();
            return gson.fromJson(gsonStr,type);
        } catch (JSONException e) {
            e.printStackTrace();
            return null;
        }
    }

}


text:
1. Install NodeJS via [Node Version Manager (NVM)](https://github.com/creationix/nvm) if you are on Linux/OSX. If you're on Windows, just install [NodeJS](http://nodejs.org/).

2. Clone this repository.

3. Run the following in command line:

```
npm install -g webpack
npm install
```

## To start the application:

```
npm run prod
```

Go to [`http://localhost:3000/`](http://localhost:3000) (Or [127.0.0.1](http://127.0.0.1:3000) if `localhost` is not configured).

## To develop:

```
npm start
```


text:
export {
  default as renderWithCoilProvider,
  createSnapshotsRenderer,
} from "./render-with-coil-provider";
export { default as getMeta } from "./get-meta";


text:
package com.perforce.p4java.impl.mapbased.rpc.sys;

import java.io.IOException;
import java.io.InputStream;
import java.io.PushbackInputStream;

/**
 * InputStream wrapper that detects and skips the Unicode BOM (Byte Order Mark)
 * in Unicode encoded text files.
 *
 * <pre>
 * EF BB BF    = UTF-8 BOM
 * FF FE       = UTF-16, little-endian BOM
 * FE FF       = UTF-16, big-endian BOM
 * FF FE 00 00 = UTF-32, little-endian BOM
 * 00 00 FE FF = UTF-32, big-endian BOM
 * </pre>
 */
public class RpcUnicodeInputStream extends InputStream {

	private final PushbackInputStream in;
	private final BOM bom;
	private boolean skipped = false;

	/**
	 * Types of Unicode BOMs.
	 */
	public static final class BOM {

		final byte bytes[];
		private final String description;

		private BOM(final byte bom[], final String description) {
			this.bytes = bom;
			this.description = description;
		}

		/**
		 * Default to no BOM.
		 */
		public static final BOM NONE = new BOM(new byte[] {}, "NONE");

		/**
		 * UTF-8 BOM (EF BB BF).
		 */
		public static final BOM UTF_8 = new BOM(new byte[] {
				(byte) 0xEF,
				(byte) 0xBB,
				(byte) 0xBF }, "UTF-8");

		/**
		 * UTF-16, little-endian (FF FE).
		 */
		public static final BOM UTF_16_LE = new BOM(new byte[] {
				(byte) 0xFF,
				(byte) 0xFE }, "UTF-16 little-endian");

		/**
		 * UTF-16, big-endian (FE FF).
		 */
		public static final BOM UTF_16_BE = new BOM(new byte[] {
				(byte) 0xFE,
				(byte) 0xFF }, "UTF-16 big-endian");

		/**
		 * UTF-32, little-endian (FF FE 00 00).
		 */
		public static final BOM UTF_32_LE = new BOM(new byte[] {
				(byte) 0xFF,
				(byte) 0xFE,
				(byte) 0x00,
				(byte) 0x00 }, "UTF-32 little-endian");

		/**
		 * UTF-32, big-endian (00 00 FE FF).
		 */
		public static final BOM UTF_32_BE = new BOM(new byte[] {
				(byte) 0x00,
				(byte) 0x00,
				(byte) 0xFE,
				(byte) 0xFF }, "UTF-32 big-endian");

		/**
		 * Returns the string representation of this BOM.
		 */
		public final String toString() {
			return description;
		}

		/**
		 * Returns the bytes of this BOM.
		 */
		public final byte[] getBytes() {
			final int length = bytes.length;
			final byte[] result = new byte[length];
			System.arraycopy(bytes, 0, result, 0, length);
			return result;
		}
	}

	/**
	 * Constructs a new RpcUnicodeInputStream that wraps the InputStream.
	 */
	public RpcUnicodeInputStream(final InputStream inputStream) throws NullPointerException, IOException {
		if (inputStream == null) {
			throw new NullPointerException("Null inputstream passed to the RpcUnicodeInputStream constructor.");
		}

		in = new PushbackInputStream(inputStream, 4);

		final byte bom[] = new byte[4];
		final int read = in.read(bom);

		switch (read) {

		case 4:
			if ((bom[0] == (byte) 0xFF)
					&& (bom[1] == (byte) 0xFE)
					&& (bom[2] == (byte) 0x00)
					&& (bom[3] == (byte) 0x00)) {
				this.bom = BOM.UTF_32_LE;
				break;
			} else if ((bom[0] == (byte) 0x00)
					&& (bom[1] == (byte) 0x00)
					&& (bom[2] == (byte) 0xFE)
					&& (bom[3] == (byte) 0xFF)) {
				this.bom = BOM.UTF_32_BE;
				break;
			}

		case 3:
			if ((bom[0] == (byte) 0xEF)
					&& (bom[1] == (byte) 0xBB)
					&& (bom[2] == (byte) 0xBF)) {
				this.bom = BOM.UTF_8;
				break;
			}

		case 2:
			if ((bom[0] == (byte) 0xFF)
					&& (bom[1] == (byte) 0xFE)) {
				this.bom = BOM.UTF_16_LE;
				break;
			} else if ((bom[0] == (byte) 0xFE)
					&& (bom[1] == (byte) 0xFF)) {
				this.bom = BOM.UTF_16_BE;
				break;
			}

		default:
			this.bom = BOM.NONE;
			break;
		}

		if (read > 0)
			in.unread(bom, 0, read);
	}

	/**
	 * Returns the BOM found in the InputStream.
	 */
	public final BOM getBOM() {
		return bom;
	}

	/**
	 * Skips the BOM found in the InputStream.
	 */
	public final synchronized RpcUnicodeInputStream skipBOM() throws IOException {
		if (!skipped) {
			in.skip(bom.bytes.length);
			skipped = true;
		}
		return this;
	}

	/**
	 * {@inheritDoc}
	 */
	public int read() throws IOException {
		return in.read();
	}

	/**
	 * {@inheritDoc}
	 */
	public int read(final byte b[]) throws IOException, NullPointerException {
		return in.read(b, 0, b.length);
	}

	/**
	 * {@inheritDoc}
	 */
	public int read(final byte b[], final int off, final int len)
			throws IOException, NullPointerException {
		return in.read(b, off, len);
	}

	/**
	 * {@inheritDoc}
	 */
	public long skip(final long n) throws IOException {
		return in.skip(n);
	}

	/**
	 * {@inheritDoc}
	 */
	public int available() throws IOException {
		return in.available();
	}

	/**
	 * {@inheritDoc}
	 */
	public void close() throws IOException {
		in.close();
	}

	/**
	 * {@inheritDoc}
	 */
	public synchronized void mark(final int readlimit) {
		in.mark(readlimit);
	}

	/**
	 * {@inheritDoc}
	 */
	public synchronized void reset() throws IOException {
		in.reset();
	}

	/**
	 * {@inheritDoc}
	 */
	public boolean markSupported() {
		return in.markSupported();
	}
}


text:
#pragma once
#include <aws/backup/Backup_EXPORTS.h>
#include <aws/backup/BackupRequest.h>
#include <aws/core/utils/memory/stl/AWSString.h>
#include <aws/core/utils/memory/stl/AWSVector.h>
#include <aws/backup/model/FrameworkControl.h>
#include <utility>
#include <aws/core/utils/UUID.h>

namespace Aws
{
namespace Backup
{
namespace Model
{

  /**
   */
  class AWS_BACKUP_API UpdateFrameworkRequest : public BackupRequest
  {
  public:
    UpdateFrameworkRequest();

    // Service request name is the Operation name which will send this request out,
    // each operation should has unique request name, so that we can get operation's name from this request.
    // Note: this is not true for response, multiple operations may have the same response name,
    // so we can not get operation's name from response.
    inline virtual const char* GetServiceRequestName() const override { return "UpdateFramework"; }

    Aws::String SerializePayload() const override;

    /**
     *
The unique name of a framework. This name is between 1 and 256 characters,
     * starting with a letter, and consisting of letters (a-z, A-Z), numbers (0-9), and
     * underscores (_).

     */
    inline const Aws::String& GetFrameworkName() const{ return m_frameworkName; }

    /**
     *
The unique name of a framework. This name is between 1 and 256 characters,
     * starting with a letter, and consisting of letters (a-z, A-Z), numbers (0-9), and
     * underscores (_).

     */
    inline bool FrameworkNameHasBeenSet() const { return m_frameworkNameHasBeenSet; }

    /**
     *
The unique name of a framework. This name is between 1 and 256 characters,
     * starting with a letter, and consisting of letters (a-z, A-Z), numbers (0-9), and
     * underscores (_).

     */
    inline void SetFrameworkName(const Aws::String& value) { m_frameworkNameHasBeenSet = true; m_frameworkName = value; }

    /**
     *
The unique name of a framework. This name is between 1 and 256 characters,
     * starting with a letter, and consisting of letters (a-z, A-Z), numbers (0-9), and
     * underscores (_).

     */
    inline void SetFrameworkName(Aws::String&& value) { m_frameworkNameHasBeenSet = true; m_frameworkName = std::move(value); }

    /**
     *
The unique name of a framework. This name is between 1 and 256 characters,
     * starting with a letter, and consisting of letters (a-z, A-Z), numbers (0-9), and
     * underscores (_).

     */
    inline void SetFrameworkName(const char* value) { m_frameworkNameHasBeenSet = true; m_frameworkName.assign(value); }

    /**
     *
The unique name of a framework. This name is between 1 and 256 characters,
     * starting with a letter, and consisting of letters (a-z, A-Z), numbers (0-9), and
     * underscores (_).

     */
    inline UpdateFrameworkRequest& WithFrameworkName(const Aws::String& value) { SetFrameworkName(value); return *this;}

    /**
     *
The unique name of a framework. This name is between 1 and 256 characters,
     * starting with a letter, and consisting of letters (a-z, A-Z), numbers (0-9), and
     * underscores (_).

     */
    inline UpdateFrameworkRequest& WithFrameworkName(Aws::String&& value) { SetFrameworkName(std::move(value)); return *this;}

    /**
     *
The unique name of a framework. This name is between 1 and 256 characters,
     * starting with a letter, and consisting of letters (a-z, A-Z), numbers (0-9), and
     * underscores (_).

     */
    inline UpdateFrameworkRequest& WithFrameworkName(const char* value) { SetFrameworkName(value); return *this;}

    /**
     *
An optional description of the framework with a maximum 1,024 characters.

     */
    inline const Aws::String& GetFrameworkDescription() const{ return m_frameworkDescription; }

    /**
     *
An optional description of the framework with a maximum 1,024 characters.

     */
    inline bool FrameworkDescriptionHasBeenSet() const { return m_frameworkDescriptionHasBeenSet; }

    /**
     *
An optional description of the framework with a maximum 1,024 characters.

     */
    inline void SetFrameworkDescription(const Aws::String& value) { m_frameworkDescriptionHasBeenSet = true; m_frameworkDescription = value; }

    /**
     *
An optional description of the framework with a maximum 1,024 characters.

     */
    inline void SetFrameworkDescription(Aws::String&& value) { m_frameworkDescriptionHasBeenSet = true; m_frameworkDescription = std::move(value); }

    /**
     *
An optional description of the framework with a maximum 1,024 characters.

     */
    inline void SetFrameworkDescription(const char* value) { m_frameworkDescriptionHasBeenSet = true; m_frameworkDescription.assign(value); }

    /**
     *
An optional description of the framework with a maximum 1,024 characters.

     */
    inline UpdateFrameworkRequest& WithFrameworkDescription(const Aws::String& value) { SetFrameworkDescription(value); return *this;}

    /**
     *
An optional description of the framework with a maximum 1,024 characters.

     */
    inline UpdateFrameworkRequest& WithFrameworkDescription(Aws::String&& value) { SetFrameworkDescription(std::move(value)); return *this;}

    /**
     *
An optional description of the framework with a maximum 1,024 characters.

     */
    inline UpdateFrameworkRequest& WithFrameworkDescription(const char* value) { SetFrameworkDescription(value); return *this;}

    /**
     *
A list of the controls that make up the framework. Each control in the list
     * has a name, input parameters, and scope.

     */
    inline const Aws::Vector<FrameworkControl>& GetFrameworkControls() const{ return m_frameworkControls; }

    /**
     *
A list of the controls that make up the framework. Each control in the list
     * has a name, input parameters, and scope.

     */
    inline bool FrameworkControlsHasBeenSet() const { return m_frameworkControlsHasBeenSet; }

    /**
     *
A list of the controls that make up the framework. Each control in the list
     * has a name, input parameters, and scope.

     */
    inline void SetFrameworkControls(const Aws::Vector<FrameworkControl>& value) { m_frameworkControlsHasBeenSet = true; m_frameworkControls = value; }

    /**
     *
A list of the controls that make up the framework. Each control in the list
     * has a name, input parameters, and scope.

     */
    inline void SetFrameworkControls(Aws::Vector<FrameworkControl>&& value) { m_frameworkControlsHasBeenSet = true; m_frameworkControls = std::move(value); }

    /**
     *
A list of the controls that make up the framework. Each control in the list
     * has a name, input parameters, and scope.

     */
    inline UpdateFrameworkRequest& WithFrameworkControls(const Aws::Vector<FrameworkControl>& value) { SetFrameworkControls(value); return *this;}

    /**
     *
A list of the controls that make up the framework. Each control in the list
     * has a name, input parameters, and scope.

     */
    inline UpdateFrameworkRequest& WithFrameworkControls(Aws::Vector<FrameworkControl>&& value) { SetFrameworkControls(std::move(value)); return *this;}

    /**
     *
A list of the controls that make up the framework. Each control in the list
     * has a name, input parameters, and scope.

     */
    inline UpdateFrameworkRequest& AddFrameworkControls(const FrameworkControl& value) { m_frameworkControlsHasBeenSet = true; m_frameworkControls.push_back(value); return *this; }

    /**
     *
A list of the controls that make up the framework. Each control in the list
     * has a name, input parameters, and scope.

     */
    inline UpdateFrameworkRequest& AddFrameworkControls(FrameworkControl&& value) { m_frameworkControlsHasBeenSet = true; m_frameworkControls.push_back(std::move(value)); return *this; }

    /**
     *
A customer-chosen string that you can use to distinguish between otherwise
     * identical calls to UpdateFrameworkInput. Retrying a successful
     * request with the same idempotency token results in a success message with no
     * action taken.

     */
    inline const Aws::String& GetIdempotencyToken() const{ return m_idempotencyToken; }

    /**
     *
A customer-chosen string that you can use to distinguish between otherwise
     * identical calls to UpdateFrameworkInput. Retrying a successful
     * request with the same idempotency token results in a success message with no
     * action taken.

     */
    inline bool IdempotencyTokenHasBeenSet() const { return m_idempotencyTokenHasBeenSet; }

    /**
     *
A customer-chosen string that you can use to distinguish between otherwise
     * identical calls to UpdateFrameworkInput. Retrying a successful
     * request with the same idempotency token results in a success message with no
     * action taken.

     */
    inline void SetIdempotencyToken(const Aws::String& value) { m_idempotencyTokenHasBeenSet = true; m_idempotencyToken = value; }

    /**
     *
A customer-chosen string that you can use to distinguish between otherwise
     * identical calls to UpdateFrameworkInput. Retrying a successful
     * request with the same idempotency token results in a success message with no
     * action taken.

     */
    inline void SetIdempotencyToken(Aws::String&& value) { m_idempotencyTokenHasBeenSet = true; m_idempotencyToken = std::move(value); }

    /**
     *
A customer-chosen string that you can use to distinguish between otherwise
     * identical calls to UpdateFrameworkInput. Retrying a successful
     * request with the same idempotency token results in a success message with no
     * action taken.

     */
    inline void SetIdempotencyToken(const char* value) { m_idempotencyTokenHasBeenSet = true; m_idempotencyToken.assign(value); }

    /**
     *
A customer-chosen string that you can use to distinguish between otherwise
     * identical calls to UpdateFrameworkInput. Retrying a successful
     * request with the same idempotency token results in a success message with no
     * action taken.

     */
    inline UpdateFrameworkRequest& WithIdempotencyToken(const Aws::String& value) { SetIdempotencyToken(value); return *this;}

    /**
     *
A customer-chosen string that you can use to distinguish between otherwise
     * identical calls to UpdateFrameworkInput. Retrying a successful
     * request with the same idempotency token results in a success message with no
     * action taken.

     */
    inline UpdateFrameworkRequest& WithIdempotencyToken(Aws::String&& value) { SetIdempotencyToken(std::move(value)); return *this;}

    /**
     *
A customer-chosen string that you can use to distinguish between otherwise
     * identical calls to UpdateFrameworkInput. Retrying a successful
     * request with the same idempotency token results in a success message with no
     * action taken.

     */
    inline UpdateFrameworkRequest& WithIdempotencyToken(const char* value) { SetIdempotencyToken(value); return *this;}

  private:

    Aws::String m_frameworkName;
    bool m_frameworkNameHasBeenSet;

    Aws::String m_frameworkDescription;
    bool m_frameworkDescriptionHasBeenSet;

    Aws::Vector<FrameworkControl> m_frameworkControls;
    bool m_frameworkControlsHasBeenSet;

    Aws::String m_idempotencyToken;
    bool m_idempotencyTokenHasBeenSet;
  };

} // namespace Model
} // namespace Backup
} // namespace Aws


text:
require 'message_store'
require 'settings'

require 'messaging/log'

require 'messaging/stream_name'

require 'messaging/message'
require 'messaging/message/metadata'
require 'messaging/message/copy'
require 'messaging/message/follow'
require 'messaging/message/sequence_accessor'

require 'messaging/message/transform'
require 'messaging/message/import'
require 'messaging/message/export'

require 'messaging/category'

require 'messaging/write'
require 'messaging/write/substitute'

require 'messaging/message_registry'
require 'messaging/handle'
require 'messaging/handle/defaults'


text:
function Blocksep()
  return "\n\n"
end

-- This function is called once for the whole document. Parameters:
-- body, title, date are strings; authors is an array of strings;
-- variables is a table.  One could use some kind of templating
-- system here; this just gives you a simple standalone HTML file.
function Doc(body, title, authors, date, variables)
  return body .. '\n'
end

-- The functions that follow render corresponding pandoc elements.
-- s is always a string, attr is always a table of attributes, and
-- items is always an array of strings (the items in a list).
-- Comments indicate the types of other variables.

function Str(s)
  return s
end

function Space()
  return " "
end

function LineBreak()
  return "\n"
end

function Emph(s)
  return "[I]" .. s .. "[/I]"
end

function Strong(s)
  return "[B]" .. s .. "[/B]"
end

function Strikeout(s)
  return '[STRIKE]' .. s .. '[/STRIKE]'
end

function Link(s, src, tit)
  if s then
    return '[URL=' .. src .. ']' .. s .. '[/URL]'
  else
    return '[URL]' .. src .. '[/URL]'
  end
end

function Image(s, src, tit)
  return "[IMG]" .. src .. "[/IMG]"
end

function Code(s, attr)
  return '[FONT="Courier New"]' .. s .. "[/FONT]"
end

function Plain(s)
  return s
end

function Para(s)
  return s
end

-- lev is an integer, the header level.
function Header(level, s, attr)
  if level == 1 then
 	 return "[B][SIZE=+2]" .. s .. "[/SIZE][/B]"
  elseif level == 2 then
 	 return "[B][SIZE=+1]" .. s .. "[/SIZE][/B]"
  elseif level == 3 then
 	 return "[B][U]" .. s .. "[/U][/B]"
  else
 	 return "[B]" .. s .. "[/B]"
  end
end

function BlockQuote(s)
  return "[QUOTE]\n" .. s .. "\n[/QUOTE]"
end

function HorizontalRule()
  return "[HR][/HR]"
end

function CodeBlock(s, attr)
    return "[CODE]\n" .. s .. "\n[/CODE]"
end

function BulletList(items)
  local buffer = {}
  for _, item in ipairs(items) do
    table.insert(buffer, "[*]" .. item)
  end
  return "[LIST]\n" .. table.concat(buffer, "\n") .. "\n[/LIST]"
end

function OrderedList(items)
  local buffer = {}
  for _, item in ipairs(items) do
    table.insert(buffer, "[*]" .. item)
  end
  return "[LIST=1]\n" .. table.concat(buffer, "\n") .. "\n[/LIST]"
end

-- Convert pandoc alignment to something HTML can use.
-- align is AlignLeft, AlignRight, AlignCenter, or AlignDefault.
function html_align(align)
  if align == 'AlignLeft' then
    return 'left'
  elseif align == 'AlignRight' then
    return 'right'
  elseif align == 'AlignCenter' then
    return 'center'
  else
    return 'left'
  end
end

-- The following code will produce runtime warnings when you haven't defined
-- all of the functions you need for the custom writer, so it's useful
-- to include when you're working on a writer.
local meta = {}
meta.__index =
  function(_, key)
    io.stderr:write(string.format("WARNING: Undefined function '%s'\n",key))
    return function() return "" end
  end
setmetatable(_G, meta)


text:
namespace rj = arrow::rapidjson;

namespace arrow {

using internal::ParseValue;

namespace ipc {
namespace internal {
namespace json {

using ::arrow::internal::checked_cast;
using ::arrow::internal::checked_pointer_cast;

namespace {

constexpr auto kParseFlags = rj::kParseFullPrecisionFlag | rj::kParseNanAndInfFlag;

Status JSONTypeError(const char* expected_type, rj::Type json_type) {
  return Status::Invalid("Expected ", expected_type, " or null, got JSON type ",
                         json_type);
}

class Converter {
 public:
  virtual ~Converter() = default;

  virtual Status Init() { return Status::OK(); }

  virtual Status AppendValue(const rj::Value& json_obj) = 0;

  Status AppendNull() { return this->builder()->AppendNull(); }

  virtual Status AppendValues(const rj::Value& json_array) = 0;

  virtual std::shared_ptr<ArrayBuilder> builder() = 0;

  virtual Status Finish(std::shared_ptr<Array>* out) {
    auto builder = this->builder();
    if (builder->length() == 0) {
      // Make sure the builder was initialized
      RETURN_NOT_OK(builder->Resize(1));
    }
    return builder->Finish(out);
  }

 protected:
  std::shared_ptr<DataType> type_;
};

Status GetConverter(const std::shared_ptr<DataType>&, std::shared_ptr<Converter>* out);

// CRTP
template <class Derived>
class ConcreteConverter : public Converter {
 public:
  Status AppendValues(const rj::Value& json_array) override {
    auto self = static_cast<Derived*>(this);
    if (!json_array.IsArray()) {
      return JSONTypeError("array", json_array.GetType());
    }
    auto size = json_array.Size();
    for (uint32_t i = 0; i < size; ++i) {
      RETURN_NOT_OK(self->AppendValue(json_array[i]));
    }
    return Status::OK();
  }

  const std::shared_ptr<DataType>& value_type() {
    if (type_->id() != Type::DICTIONARY) {
      return type_;
    }
    return checked_cast<const DictionaryType&>(*type_).value_type();
  }

  template <typename BuilderType>
  Status MakeConcreteBuilder(std::shared_ptr<BuilderType>* out) {
    std::unique_ptr<ArrayBuilder> builder;
    RETURN_NOT_OK(MakeBuilder(default_memory_pool(), this->type_, &builder));
    *out = checked_pointer_cast<BuilderType>(std::move(builder));
    DCHECK(*out);
    return Status::OK();
  }
};

// ------------------------------------------------------------------------
// Converter for null arrays

class NullConverter final : public ConcreteConverter<NullConverter> {
 public:
  explicit NullConverter(const std::shared_ptr<DataType>& type) {
    type_ = type;
    builder_ = std::make_shared<NullBuilder>();
  }

  Status AppendValue(const rj::Value& json_obj) override {
    if (json_obj.IsNull()) {
      return AppendNull();
    }
    return JSONTypeError("null", json_obj.GetType());
  }

  std::shared_ptr<ArrayBuilder> builder() override { return builder_; }

 private:
  std::shared_ptr<NullBuilder> builder_;
};

// ------------------------------------------------------------------------
// Converter for boolean arrays

class BooleanConverter final : public ConcreteConverter<BooleanConverter> {
 public:
  explicit BooleanConverter(const std::shared_ptr<DataType>& type) {
    type_ = type;
    builder_ = std::make_shared<BooleanBuilder>();
  }

  Status AppendValue(const rj::Value& json_obj) override {
    if (json_obj.IsNull()) {
      return AppendNull();
    }
    if (json_obj.IsBool()) {
      return builder_->Append(json_obj.GetBool());
    }
    if (json_obj.IsInt()) {
      return builder_->Append(json_obj.GetInt() != 0);
    }
    return JSONTypeError("boolean", json_obj.GetType());
  }

  std::shared_ptr<ArrayBuilder> builder() override { return builder_; }

 private:
  std::shared_ptr<BooleanBuilder> builder_;
};

// ------------------------------------------------------------------------
// Helpers for numeric converters

// Convert single signed integer value (also {Date,Time}{32,64} and Timestamp)
template <typename T>
enable_if_physical_signed_integer<T, Status> ConvertNumber(const rj::Value& json_obj,
                                                           const DataType& type,
                                                           typename T::c_type* out) {
  if (json_obj.IsInt64()) {
    int64_t v64 = json_obj.GetInt64();
    *out = static_cast<typename T::c_type>(v64);
    if (*out == v64) {
      return Status::OK();
    } else {
      return Status::Invalid("Value ", v64, " out of bounds for ", type);
    }
  } else {
    *out = static_cast<typename T::c_type>(0);
    return JSONTypeError("signed int", json_obj.GetType());
  }
}

// Convert single unsigned integer value
template <typename T>
enable_if_physical_unsigned_integer<T, Status> ConvertNumber(const rj::Value& json_obj,
                                                             const DataType& type,
                                                             typename T::c_type* out) {
  if (json_obj.IsUint64()) {
    uint64_t v64 = json_obj.GetUint64();
    *out = static_cast<typename T::c_type>(v64);
    if (*out == v64) {
      return Status::OK();
    } else {
      return Status::Invalid("Value ", v64, " out of bounds for ", type);
    }
  } else {
    *out = static_cast<typename T::c_type>(0);
    return JSONTypeError("unsigned int", json_obj.GetType());
  }
}

// Convert single floating point value
template <typename T>
enable_if_physical_floating_point<T, Status> ConvertNumber(const rj::Value& json_obj,
                                                           const DataType& type,
                                                           typename T::c_type* out) {
  if (json_obj.IsNumber()) {
    *out = static_cast<typename T::c_type>(json_obj.GetDouble());
    return Status::OK();
  } else {
    *out = static_cast<typename T::c_type>(0);
    return JSONTypeError("number", json_obj.GetType());
  }
}

// ------------------------------------------------------------------------
// Converter for int arrays

template <typename Type, typename BuilderType = typename TypeTraits<Type>::BuilderType>
class IntegerConverter final
    : public ConcreteConverter<IntegerConverter<Type, BuilderType>> {
  using c_type = typename Type::c_type;

  static constexpr auto is_signed = std::is_signed<c_type>::value;

 public:
  explicit IntegerConverter(const std::shared_ptr<DataType>& type) { this->type_ = type; }

  Status Init() override { return this->MakeConcreteBuilder(&builder_); }

  Status AppendValue(const rj::Value& json_obj) override {
    if (json_obj.IsNull()) {
      return this->AppendNull();
    }
    c_type value;
    RETURN_NOT_OK(ConvertNumber<Type>(json_obj, *this->type_, &value));
    return builder_->Append(value);
  }

  std::shared_ptr<ArrayBuilder> builder() override { return builder_; }

 private:
  std::shared_ptr<BuilderType> builder_;
};

// ------------------------------------------------------------------------
// Converter for float arrays

template <typename Type, typename BuilderType = typename TypeTraits<Type>::BuilderType>
class FloatConverter final : public ConcreteConverter<FloatConverter<Type, BuilderType>> {
  using c_type = typename Type::c_type;

 public:
  explicit FloatConverter(const std::shared_ptr<DataType>& type) { this->type_ = type; }

  Status Init() override { return this->MakeConcreteBuilder(&builder_); }

  Status AppendValue(const rj::Value& json_obj) override {
    if (json_obj.IsNull()) {
      return this->AppendNull();
    }
    c_type value;
    RETURN_NOT_OK(ConvertNumber<Type>(json_obj, *this->type_, &value));
    return builder_->Append(value);
  }

  std::shared_ptr<ArrayBuilder> builder() override { return builder_; }

 private:
  std::shared_ptr<BuilderType> builder_;
};

// ------------------------------------------------------------------------
// Converter for decimal arrays

template <typename DecimalSubtype, typename DecimalValue, typename BuilderType>
class DecimalConverter final
    : public ConcreteConverter<
          DecimalConverter<DecimalSubtype, DecimalValue, BuilderType>> {
 public:
  explicit DecimalConverter(const std::shared_ptr<DataType>& type) {
    this->type_ = type;
    decimal_type_ = &checked_cast<const DecimalSubtype&>(*this->value_type());
  }

  Status Init() override { return this->MakeConcreteBuilder(&builder_); }

  Status AppendValue(const rj::Value& json_obj) override {
    if (json_obj.IsNull()) {
      return this->AppendNull();
    }
    if (json_obj.IsString()) {
      int32_t precision, scale;
      DecimalValue d;
      auto view = util::string_view(json_obj.GetString(), json_obj.GetStringLength());
      RETURN_NOT_OK(DecimalValue::FromString(view, &d, &precision, &scale));
      if (scale != decimal_type_->scale()) {
        return Status::Invalid("Invalid scale for decimal: expected ",
                               decimal_type_->scale(), ", got ", scale);
      }
      return builder_->Append(d);
    }
    return JSONTypeError("decimal string", json_obj.GetType());
  }

  std::shared_ptr<ArrayBuilder> builder() override { return builder_; }

 private:
  std::shared_ptr<BuilderType> builder_;
  const DecimalSubtype* decimal_type_;
};

template <typename BuilderType = typename TypeTraits<Decimal128Type>::BuilderType>
using Decimal128Converter = DecimalConverter<Decimal128Type, Decimal128, BuilderType>;
template <typename BuilderType = typename TypeTraits<Decimal256Type>::BuilderType>
using Decimal256Converter = DecimalConverter<Decimal256Type, Decimal256, BuilderType>;

// ------------------------------------------------------------------------
// Converter for timestamp arrays

class TimestampConverter final : public ConcreteConverter<TimestampConverter> {
 public:
  explicit TimestampConverter(const std::shared_ptr<DataType>& type)
      : timestamp_type_{checked_cast<const TimestampType*>(type.get())} {
    this->type_ = type;
    builder_ = std::make_shared<TimestampBuilder>(type, default_memory_pool());
  }

  Status AppendValue(const rj::Value& json_obj) override {
    if (json_obj.IsNull()) {
      return this->AppendNull();
    }
    int64_t value;
    if (json_obj.IsNumber()) {
      RETURN_NOT_OK(ConvertNumber<Int64Type>(json_obj, *this->type_, &value));
    } else if (json_obj.IsString()) {
      util::string_view view(json_obj.GetString(), json_obj.GetStringLength());
      if (!ParseValue(*timestamp_type_, view.data(), view.size(), &value)) {
        return Status::Invalid("couldn't parse timestamp from ", view);
      }
    } else {
      return JSONTypeError("timestamp", json_obj.GetType());
    }
    return builder_->Append(value);
  }

  std::shared_ptr<ArrayBuilder> builder() override { return builder_; }

 private:
  const TimestampType* timestamp_type_;
  std::shared_ptr<TimestampBuilder> builder_;
};

// ------------------------------------------------------------------------
// Converter for day-time interval arrays

class DayTimeIntervalConverter final
    : public ConcreteConverter<DayTimeIntervalConverter> {
 public:
  explicit DayTimeIntervalConverter(const std::shared_ptr<DataType>& type) {
    this->type_ = type;
    builder_ = std::make_shared<DayTimeIntervalBuilder>(default_memory_pool());
  }

  Status AppendValue(const rj::Value& json_obj) override {
    if (json_obj.IsNull()) {
      return this->AppendNull();
    }
    DayTimeIntervalType::DayMilliseconds value;
    if (!json_obj.IsArray()) {
      return JSONTypeError("array", json_obj.GetType());
    }
    if (json_obj.Size() != 2) {
      return Status::Invalid(
          "day time interval pair must have exactly two elements, had ", json_obj.Size());
    }
    RETURN_NOT_OK(ConvertNumber<Int32Type>(json_obj[0], *this->type_, &value.days));
    RETURN_NOT_OK(
        ConvertNumber<Int32Type>(json_obj[1], *this->type_, &value.milliseconds));
    return builder_->Append(value);
  }

  std::shared_ptr<ArrayBuilder> builder() override { return builder_; }

 private:
  std::shared_ptr<DayTimeIntervalBuilder> builder_;
};

class MonthDayNanoIntervalConverter final
    : public ConcreteConverter<MonthDayNanoIntervalConverter> {
 public:
  explicit MonthDayNanoIntervalConverter(const std::shared_ptr<DataType>& type) {
    this->type_ = type;
    builder_ = std::make_shared<MonthDayNanoIntervalBuilder>(default_memory_pool());
  }

  Status AppendValue(const rj::Value& json_obj) override {
    if (json_obj.IsNull()) {
      return this->AppendNull();
    }
    MonthDayNanoIntervalType::MonthDayNanos value;
    if (!json_obj.IsArray()) {
      return JSONTypeError("array", json_obj.GetType());
    }
    if (json_obj.Size() != 3) {
      return Status::Invalid(
          "month_day_nano_interval  must have exactly 3 elements, had ", json_obj.Size());
    }
    RETURN_NOT_OK(ConvertNumber<Int32Type>(json_obj[0], *this->type_, &value.months));
    RETURN_NOT_OK(ConvertNumber<Int32Type>(json_obj[1], *this->type_, &value.days));
    RETURN_NOT_OK(
        ConvertNumber<Int64Type>(json_obj[2], *this->type_, &value.nanoseconds));

    return builder_->Append(value);
  }

  std::shared_ptr<ArrayBuilder> builder() override { return builder_; }

 private:
  std::shared_ptr<MonthDayNanoIntervalBuilder> builder_;
};

// ------------------------------------------------------------------------
// Converter for binary and string arrays

template <typename Type, typename BuilderType = typename TypeTraits<Type>::BuilderType>
class StringConverter final
    : public ConcreteConverter<StringConverter<Type, BuilderType>> {
 public:
  explicit StringConverter(const std::shared_ptr<DataType>& type) { this->type_ = type; }

  Status Init() override { return this->MakeConcreteBuilder(&builder_); }

  Status AppendValue(const rj::Value& json_obj) override {
    if (json_obj.IsNull()) {
      return this->AppendNull();
    }
    if (json_obj.IsString()) {
      auto view = util::string_view(json_obj.GetString(), json_obj.GetStringLength());
      return builder_->Append(view);
    } else {
      return JSONTypeError("string", json_obj.GetType());
    }
  }

  std::shared_ptr<ArrayBuilder> builder() override { return builder_; }

 private:
  std::shared_ptr<BuilderType> builder_;
};

// ------------------------------------------------------------------------
// Converter for fixed-size binary arrays

template <typename BuilderType = typename TypeTraits<FixedSizeBinaryType>::BuilderType>
class FixedSizeBinaryConverter final
    : public ConcreteConverter<FixedSizeBinaryConverter<BuilderType>> {
 public:
  explicit FixedSizeBinaryConverter(const std::shared_ptr<DataType>& type) {
    this->type_ = type;
  }

  Status Init() override { return this->MakeConcreteBuilder(&builder_); }

  Status AppendValue(const rj::Value& json_obj) override {
    if (json_obj.IsNull()) {
      return this->AppendNull();
    }
    if (json_obj.IsString()) {
      auto view = util::string_view(json_obj.GetString(), json_obj.GetStringLength());
      if (view.length() != static_cast<size_t>(builder_->byte_width())) {
        std::stringstream ss;
        ss << "Invalid string length " << view.length() << " in JSON input for "
           << this->type_->ToString();
        return Status::Invalid(ss.str());
      }
      return builder_->Append(view);
    } else {
      return JSONTypeError("string", json_obj.GetType());
    }
  }

  std::shared_ptr<ArrayBuilder> builder() override { return builder_; }

 private:
  std::shared_ptr<BuilderType> builder_;
};

// ------------------------------------------------------------------------
// Converter for list arrays

template <typename TYPE>
class ListConverter final : public ConcreteConverter<ListConverter<TYPE>> {
 public:
  using BuilderType = typename TypeTraits<TYPE>::BuilderType;

  explicit ListConverter(const std::shared_ptr<DataType>& type) { this->type_ = type; }

  Status Init() override {
    const auto& list_type = checked_cast<const TYPE&>(*this->type_);
    RETURN_NOT_OK(GetConverter(list_type.value_type(), &child_converter_));
    auto child_builder = child_converter_->builder();
    builder_ =
        std::make_shared<BuilderType>(default_memory_pool(), child_builder, this->type_);
    return Status::OK();
  }

  Status AppendValue(const rj::Value& json_obj) override {
    if (json_obj.IsNull()) {
      return this->AppendNull();
    }
    RETURN_NOT_OK(builder_->Append());
    // Extend the child converter with this JSON array
    return child_converter_->AppendValues(json_obj);
  }

  std::shared_ptr<ArrayBuilder> builder() override { return builder_; }

 private:
  std::shared_ptr<BuilderType> builder_;
  std::shared_ptr<Converter> child_converter_;
};

// ------------------------------------------------------------------------
// Converter for map arrays

class MapConverter final : public ConcreteConverter<MapConverter> {
 public:
  explicit MapConverter(const std::shared_ptr<DataType>& type) { type_ = type; }

  Status Init() override {
    const auto& map_type = checked_cast<const MapType&>(*type_);
    RETURN_NOT_OK(GetConverter(map_type.key_type(), &key_converter_));
    RETURN_NOT_OK(GetConverter(map_type.item_type(), &item_converter_));
    auto key_builder = key_converter_->builder();
    auto item_builder = item_converter_->builder();
    builder_ = std::make_shared<MapBuilder>(default_memory_pool(), key_builder,
                                            item_builder, type_);
    return Status::OK();
  }

  Status AppendValue(const rj::Value& json_obj) override {
    if (json_obj.IsNull()) {
      return this->AppendNull();
    }
    RETURN_NOT_OK(builder_->Append());
    if (!json_obj.IsArray()) {
      return JSONTypeError("array", json_obj.GetType());
    }
    auto size = json_obj.Size();
    for (uint32_t i = 0; i < size; ++i) {
      const auto& json_pair = json_obj[i];
      if (!json_pair.IsArray()) {
        return JSONTypeError("array", json_pair.GetType());
      }
      if (json_pair.Size() != 2) {
        return Status::Invalid("key item pair must have exactly two elements, had ",
                               json_pair.Size());
      }
      if (json_pair[0].IsNull()) {
        return Status::Invalid("null key is invalid");
      }
      RETURN_NOT_OK(key_converter_->AppendValue(json_pair[0]));
      RETURN_NOT_OK(item_converter_->AppendValue(json_pair[1]));
    }
    return Status::OK();
  }

  std::shared_ptr<ArrayBuilder> builder() override { return builder_; }

 private:
  std::shared_ptr<MapBuilder> builder_;
  std::shared_ptr<Converter> key_converter_, item_converter_;
};

// ------------------------------------------------------------------------
// Converter for fixed size list arrays

class FixedSizeListConverter final : public ConcreteConverter<FixedSizeListConverter> {
 public:
  explicit FixedSizeListConverter(const std::shared_ptr<DataType>& type) { type_ = type; }

  Status Init() override {
    const auto& list_type = checked_cast<const FixedSizeListType&>(*type_);
    list_size_ = list_type.list_size();
    RETURN_NOT_OK(GetConverter(list_type.value_type(), &child_converter_));
    auto child_builder = child_converter_->builder();
    builder_ = std::make_shared<FixedSizeListBuilder>(default_memory_pool(),
                                                      child_builder, type_);
    return Status::OK();
  }

  Status AppendValue(const rj::Value& json_obj) override {
    if (json_obj.IsNull()) {
      return this->AppendNull();
    }
    RETURN_NOT_OK(builder_->Append());
    // Extend the child converter with this JSON array
    RETURN_NOT_OK(child_converter_->AppendValues(json_obj));
    if (json_obj.GetArray().Size() != static_cast<rj::SizeType>(list_size_)) {
      return Status::Invalid("incorrect list size ", json_obj.GetArray().Size());
    }
    return Status::OK();
  }

  std::shared_ptr<ArrayBuilder> builder() override { return builder_; }

 private:
  int32_t list_size_;
  std::shared_ptr<FixedSizeListBuilder> builder_;
  std::shared_ptr<Converter> child_converter_;
};

// ------------------------------------------------------------------------
// Converter for struct arrays

class StructConverter final : public ConcreteConverter<StructConverter> {
 public:
  explicit StructConverter(const std::shared_ptr<DataType>& type) { type_ = type; }

  Status Init() override {
    std::vector<std::shared_ptr<ArrayBuilder>> child_builders;
    for (const auto& field : type_->fields()) {
      std::shared_ptr<Converter> child_converter;
      RETURN_NOT_OK(GetConverter(field->type(), &child_converter));
      child_converters_.push_back(child_converter);
      child_builders.push_back(child_converter->builder());
    }
    builder_ = std::make_shared<StructBuilder>(type_, default_memory_pool(),
                                               std::move(child_builders));
    return Status::OK();
  }

  // Append a JSON value that is either an array of N elements in order
  // or an object mapping struct names to values (omitted struct members
  // are mapped to null).
  Status AppendValue(const rj::Value& json_obj) override {
    if (json_obj.IsNull()) {
      return this->AppendNull();
    }
    if (json_obj.IsArray()) {
      auto size = json_obj.Size();
      auto expected_size = static_cast<uint32_t>(type_->num_fields());
      if (size != expected_size) {
        return Status::Invalid("Expected array of size ", expected_size,
                               ", got array of size ", size);
      }
      for (uint32_t i = 0; i < size; ++i) {
        RETURN_NOT_OK(child_converters_[i]->AppendValue(json_obj[i]));
      }
      return builder_->Append();
    }
    if (json_obj.IsObject()) {
      auto remaining = json_obj.MemberCount();
      auto num_children = type_->num_fields();
      for (int32_t i = 0; i < num_children; ++i) {
        const auto& field = type_->field(i);
        auto it = json_obj.FindMember(field->name());
        if (it != json_obj.MemberEnd()) {
          --remaining;
          RETURN_NOT_OK(child_converters_[i]->AppendValue(it->value));
        } else {
          RETURN_NOT_OK(child_converters_[i]->AppendNull());
        }
      }
      if (remaining > 0) {
        rj::StringBuffer sb;
        rj::Writer<rj::StringBuffer> writer(sb);
        json_obj.Accept(writer);
        return Status::Invalid("Unexpected members in JSON object for type ",
                               type_->ToString(), " Object: ", sb.GetString());
      }
      return builder_->Append();
    }
    return JSONTypeError("array or object", json_obj.GetType());
  }

  std::shared_ptr<ArrayBuilder> builder() override { return builder_; }

 private:
  std::shared_ptr<StructBuilder> builder_;
  std::vector<std::shared_ptr<Converter>> child_converters_;
};

// ------------------------------------------------------------------------
// Converter for union arrays

class UnionConverter final : public ConcreteConverter<UnionConverter> {
 public:
  explicit UnionConverter(const std::shared_ptr<DataType>& type) { type_ = type; }

  Status Init() override {
    auto union_type = checked_cast<const UnionType*>(type_.get());
    mode_ = union_type->mode();
    type_id_to_child_num_.clear();
    type_id_to_child_num_.resize(union_type->max_type_code() + 1, -1);
    int child_i = 0;
    for (auto type_id : union_type->type_codes()) {
      type_id_to_child_num_[type_id] = child_i++;
    }
    std::vector<std::shared_ptr<ArrayBuilder>> child_builders;
    for (const auto& field : type_->fields()) {
      std::shared_ptr<Converter> child_converter;
      RETURN_NOT_OK(GetConverter(field->type(), &child_converter));
      child_converters_.push_back(child_converter);
      child_builders.push_back(child_converter->builder());
    }
    if (mode_ == UnionMode::DENSE) {
      builder_ = std::make_shared<DenseUnionBuilder>(default_memory_pool(),
                                                     std::move(child_builders), type_);
    } else {
      builder_ = std::make_shared<SparseUnionBuilder>(default_memory_pool(),
                                                      std::move(child_builders), type_);
    }
    return Status::OK();
  }

  // Append a JSON value that must be a 2-long array, containing the type_id
  // and value of the UnionArray's slot.
  Status AppendValue(const rj::Value& json_obj) override {
    if (json_obj.IsNull()) {
      return this->AppendNull();
    }
    if (!json_obj.IsArray()) {
      return JSONTypeError("array", json_obj.GetType());
    }
    if (json_obj.Size() != 2) {
      return Status::Invalid("Expected [type_id, value] pair, got array of size ",
                             json_obj.Size());
    }
    const auto& id_obj = json_obj[0];
    if (!id_obj.IsInt()) {
      return JSONTypeError("int", id_obj.GetType());
    }

    auto id = static_cast<int8_t>(id_obj.GetInt());
    auto child_num = type_id_to_child_num_[id];
    if (child_num == -1) {
      return Status::Invalid("type_id ", id, " not found in ", *type_);
    }

    auto child_converter = child_converters_[child_num];
    if (mode_ == UnionMode::SPARSE) {
      RETURN_NOT_OK(checked_cast<SparseUnionBuilder&>(*builder_).Append(id));
      for (auto&& other_converter : child_converters_) {
        if (other_converter != child_converter) {
          RETURN_NOT_OK(other_converter->AppendNull());
        }
      }
    } else {
      RETURN_NOT_OK(checked_cast<DenseUnionBuilder&>(*builder_).Append(id));
    }
    return child_converter->AppendValue(json_obj[1]);
  }

  std::shared_ptr<ArrayBuilder> builder() override { return builder_; }

 private:
  UnionMode::type mode_;
  std::shared_ptr<ArrayBuilder> builder_;
  std::vector<std::shared_ptr<Converter>> child_converters_;
  std::vector<int8_t> type_id_to_child_num_;
};

// ------------------------------------------------------------------------
// General conversion functions

Status ConversionNotImplemented(const std::shared_ptr<DataType>& type) {
  return Status::NotImplemented("JSON conversion to ", type->ToString(),
                                " not implemented");
}

Status GetDictConverter(const std::shared_ptr<DataType>& type,
                        std::shared_ptr<Converter>* out) {
  std::shared_ptr<Converter> res;

  const auto value_type = checked_cast<const DictionaryType&>(*type).value_type();

#define SIMPLE_CONVERTER_CASE(ID, CLASS, TYPE)                    \
  case ID:                                                        \
    res = std::make_shared<CLASS<DictionaryBuilder<TYPE>>>(type); \
    break;

#define PARAM_CONVERTER_CASE(ID, CLASS, TYPE)                           \
  case ID:                                                              \
    res = std::make_shared<CLASS<TYPE, DictionaryBuilder<TYPE>>>(type); \
    break;

  switch (value_type->id()) {
    PARAM_CONVERTER_CASE(Type::INT8, IntegerConverter, Int8Type)
    PARAM_CONVERTER_CASE(Type::INT16, IntegerConverter, Int16Type)
    PARAM_CONVERTER_CASE(Type::INT32, IntegerConverter, Int32Type)
    PARAM_CONVERTER_CASE(Type::INT64, IntegerConverter, Int64Type)
    PARAM_CONVERTER_CASE(Type::UINT8, IntegerConverter, UInt8Type)
    PARAM_CONVERTER_CASE(Type::UINT16, IntegerConverter, UInt16Type)
    PARAM_CONVERTER_CASE(Type::UINT32, IntegerConverter, UInt32Type)
    PARAM_CONVERTER_CASE(Type::UINT64, IntegerConverter, UInt64Type)
    PARAM_CONVERTER_CASE(Type::FLOAT, FloatConverter, FloatType)
    PARAM_CONVERTER_CASE(Type::DOUBLE, FloatConverter, DoubleType)
    PARAM_CONVERTER_CASE(Type::STRING, StringConverter, StringType)
    PARAM_CONVERTER_CASE(Type::BINARY, StringConverter, BinaryType)
    PARAM_CONVERTER_CASE(Type::LARGE_STRING, StringConverter, LargeStringType)
    PARAM_CONVERTER_CASE(Type::LARGE_BINARY, StringConverter, LargeBinaryType)
    SIMPLE_CONVERTER_CASE(Type::FIXED_SIZE_BINARY, FixedSizeBinaryConverter,
                          FixedSizeBinaryType)
    SIMPLE_CONVERTER_CASE(Type::DECIMAL128, Decimal128Converter, Decimal128Type)
    SIMPLE_CONVERTER_CASE(Type::DECIMAL256, Decimal256Converter, Decimal256Type)
    default:
      return ConversionNotImplemented(type);
  }

#undef SIMPLE_CONVERTER_CASE
#undef PARAM_CONVERTER_CASE

  RETURN_NOT_OK(res->Init());
  *out = res;
  return Status::OK();
}

Status GetConverter(const std::shared_ptr<DataType>& type,
                    std::shared_ptr<Converter>* out) {
  if (type->id() == Type::DICTIONARY) {
    return GetDictConverter(type, out);
  }

  std::shared_ptr<Converter> res;

#define SIMPLE_CONVERTER_CASE(ID, CLASS) \
  case ID:                               \
    res = std::make_shared<CLASS>(type); \
    break;

  switch (type->id()) {
    SIMPLE_CONVERTER_CASE(Type::INT8, IntegerConverter<Int8Type>)
    SIMPLE_CONVERTER_CASE(Type::INT16, IntegerConverter<Int16Type>)
    SIMPLE_CONVERTER_CASE(Type::INT32, IntegerConverter<Int32Type>)
    SIMPLE_CONVERTER_CASE(Type::INT64, IntegerConverter<Int64Type>)
    SIMPLE_CONVERTER_CASE(Type::UINT8, IntegerConverter<UInt8Type>)
    SIMPLE_CONVERTER_CASE(Type::UINT16, IntegerConverter<UInt16Type>)
    SIMPLE_CONVERTER_CASE(Type::UINT32, IntegerConverter<UInt32Type>)
    SIMPLE_CONVERTER_CASE(Type::UINT64, IntegerConverter<UInt64Type>)
    SIMPLE_CONVERTER_CASE(Type::TIMESTAMP, TimestampConverter)
    SIMPLE_CONVERTER_CASE(Type::DATE32, IntegerConverter<Date32Type>)
    SIMPLE_CONVERTER_CASE(Type::DATE64, IntegerConverter<Date64Type>)
    SIMPLE_CONVERTER_CASE(Type::TIME32, IntegerConverter<Time32Type>)
    SIMPLE_CONVERTER_CASE(Type::TIME64, IntegerConverter<Time64Type>)
    SIMPLE_CONVERTER_CASE(Type::DURATION, IntegerConverter<DurationType>)
    SIMPLE_CONVERTER_CASE(Type::NA, NullConverter)
    SIMPLE_CONVERTER_CASE(Type::BOOL, BooleanConverter)
    SIMPLE_CONVERTER_CASE(Type::HALF_FLOAT, IntegerConverter<HalfFloatType>)
    SIMPLE_CONVERTER_CASE(Type::FLOAT, FloatConverter<FloatType>)
    SIMPLE_CONVERTER_CASE(Type::DOUBLE, FloatConverter<DoubleType>)
    SIMPLE_CONVERTER_CASE(Type::LIST, ListConverter<ListType>)
    SIMPLE_CONVERTER_CASE(Type::LARGE_LIST, ListConverter<LargeListType>)
    SIMPLE_CONVERTER_CASE(Type::MAP, MapConverter)
    SIMPLE_CONVERTER_CASE(Type::FIXED_SIZE_LIST, FixedSizeListConverter)
    SIMPLE_CONVERTER_CASE(Type::STRUCT, StructConverter)
    SIMPLE_CONVERTER_CASE(Type::STRING, StringConverter<StringType>)
    SIMPLE_CONVERTER_CASE(Type::BINARY, StringConverter<BinaryType>)
    SIMPLE_CONVERTER_CASE(Type::LARGE_STRING, StringConverter<LargeStringType>)
    SIMPLE_CONVERTER_CASE(Type::LARGE_BINARY, StringConverter<LargeBinaryType>)
    SIMPLE_CONVERTER_CASE(Type::FIXED_SIZE_BINARY, FixedSizeBinaryConverter<>)
    SIMPLE_CONVERTER_CASE(Type::DECIMAL128, Decimal128Converter<>)
    SIMPLE_CONVERTER_CASE(Type::DECIMAL256, Decimal256Converter<>)
    SIMPLE_CONVERTER_CASE(Type::SPARSE_UNION, UnionConverter)
    SIMPLE_CONVERTER_CASE(Type::DENSE_UNION, UnionConverter)
    SIMPLE_CONVERTER_CASE(Type::INTERVAL_MONTHS, IntegerConverter<MonthIntervalType>)
    SIMPLE_CONVERTER_CASE(Type::INTERVAL_DAY_TIME, DayTimeIntervalConverter)
    SIMPLE_CONVERTER_CASE(Type::INTERVAL_MONTH_DAY_NANO, MonthDayNanoIntervalConverter)
    default:
      return ConversionNotImplemented(type);
  }

#undef SIMPLE_CONVERTER_CASE

  RETURN_NOT_OK(res->Init());
  *out = res;
  return Status::OK();
}

}  // namespace

Result<std::shared_ptr<Array>> ArrayFromJSON(const std::shared_ptr<DataType>& type,
                                             util::string_view json_string) {
  std::shared_ptr<Converter> converter;
  RETURN_NOT_OK(GetConverter(type, &converter));

  rj::Document json_doc;
  json_doc.Parse<kParseFlags>(json_string.data(), json_string.length());
  if (json_doc.HasParseError()) {
    return Status::Invalid("JSON parse error at offset ", json_doc.GetErrorOffset(), ": ",
                           GetParseError_En(json_doc.GetParseError()));
  }

  // The JSON document should be an array, append it
  RETURN_NOT_OK(converter->AppendValues(json_doc));
  std::shared_ptr<Array> out;
  RETURN_NOT_OK(converter->Finish(&out));
  return out;
}

Result<std::shared_ptr<Array>> ArrayFromJSON(const std::shared_ptr<DataType>& type,
                                             const std::string& json_string) {
  return ArrayFromJSON(type, util::string_view(json_string));
}

Result<std::shared_ptr<Array>> ArrayFromJSON(const std::shared_ptr<DataType>& type,
                                             const char* json_string) {
  return ArrayFromJSON(type, util::string_view(json_string));
}

Status ChunkedArrayFromJSON(const std::shared_ptr<DataType>& type,
                            const std::vector<std::string>& json_strings,
                            std::shared_ptr<ChunkedArray>* out) {
  ArrayVector out_chunks;
  out_chunks.reserve(json_strings.size());
  for (const std::string& chunk_json : json_strings) {
    out_chunks.emplace_back();
    ARROW_ASSIGN_OR_RAISE(out_chunks.back(), ArrayFromJSON(type, chunk_json));
  }
  *out = std::make_shared<ChunkedArray>(std::move(out_chunks), type);
  return Status::OK();
}

Status DictArrayFromJSON(const std::shared_ptr<DataType>& type,
                         util::string_view indices_json,
                         util::string_view dictionary_json, std::shared_ptr<Array>* out) {
  if (type->id() != Type::DICTIONARY) {
    return Status::TypeError("DictArrayFromJSON requires dictionary type, got ", *type);
  }

  const auto& dictionary_type = checked_cast<const DictionaryType&>(*type);

  ARROW_ASSIGN_OR_RAISE(auto indices,
                        ArrayFromJSON(dictionary_type.index_type(), indices_json));
  ARROW_ASSIGN_OR_RAISE(auto dictionary,
                        ArrayFromJSON(dictionary_type.value_type(), dictionary_json));

  return DictionaryArray::FromArrays(type, std::move(indices), std::move(dictionary))
      .Value(out);
}

Status ScalarFromJSON(const std::shared_ptr<DataType>& type,
                      util::string_view json_string, std::shared_ptr<Scalar>* out) {
  std::shared_ptr<Converter> converter;
  RETURN_NOT_OK(GetConverter(type, &converter));

  rj::Document json_doc;
  json_doc.Parse<kParseFlags>(json_string.data(), json_string.length());
  if (json_doc.HasParseError()) {
    return Status::Invalid("JSON parse error at offset ", json_doc.GetErrorOffset(), ": ",
                           GetParseError_En(json_doc.GetParseError()));
  }

  std::shared_ptr<Array> array;
  RETURN_NOT_OK(converter->AppendValue(json_doc));
  RETURN_NOT_OK(converter->Finish(&array));
  DCHECK_EQ(array->length(), 1);
  return array->GetScalar(0).Value(out);
}

Status DictScalarFromJSON(const std::shared_ptr<DataType>& type,
                          util::string_view index_json, util::string_view dictionary_json,
                          std::shared_ptr<Scalar>* out) {
  if (type->id() != Type::DICTIONARY) {
    return Status::TypeError("DictScalarFromJSON requires dictionary type, got ", *type);
  }

  const auto& dictionary_type = checked_cast<const DictionaryType&>(*type);

  std::shared_ptr<Scalar> index;
  std::shared_ptr<Array> dictionary;
  RETURN_NOT_OK(ScalarFromJSON(dictionary_type.index_type(), index_json, &index));
  ARROW_ASSIGN_OR_RAISE(dictionary,
                        ArrayFromJSON(dictionary_type.value_type(), dictionary_json));

  *out = DictionaryScalar::Make(std::move(index), std::move(dictionary));
  return Status::OK();
}

}  // namespace json
}  // namespace internal
}  // namespace ipc
}  // namespace arrow


text:
title: Zach Gage
summary: Game developer, artist
date: 2018-01-23
categories:
- artist
- developer
- game
- mac
---

### Who are you, and what do you do?

My name is [Zach Gage](http://www.stfj.net/ "Zach's website."), I make videogames and art.

### What hardware do you use?

I actually just did a total overhaul on my extremely-aged digital setup a few months ago so it's all probably a little boring --- I use a [13" 2017 MacBook Pro][macbook-pro], a [5K LG UltraFine display][ultrafine-5k]. I prop my MacBook up on an old [IndieBox](https://store.theindiebox.com/ "An indie game subscription service.") box. I keep cool with a [Vornado Zippi fan][zippi] which was harvested from a friend's company when they moved offices. It sounds exactly like a physical hard-drive reading and writing a ton of data when it's on. I also have an old Vew-Do balance board for keeping me focused on long calls.

I work at a standing desk that is built out of a desk my dad made a long time ago with some MultiTable legs on it. I use a [Drobo 5N2][5n2] for backup.

I use a [Magic Mouse 2][magic-mouse-2] and a [Apple extended keyboard][keyboard] (wired).

### And what software?

I develop my games with [Unity][], [Visual Studio][visual-studio], [Dash][], and obviously [Xcode][].

For the art and web stuff I use [Adobe Creative Cloud][creative-cloud] (mostly [Photoshop][] and [Illustrator][]. Sometimes [Dreamweaver][] and [InDesign][]) and [Glyphs][] (in most of my games I use fonts as my sprite-sheets so I can use [Text Mesh Pro][text-mesh-pro] to handle their scaling).

For day to day FTP stuff I use [Transmit][] and sometimes [Coda][].

For font management (super important!) I use [FontExplorer X][fontexplorer-x].

For building sound effects I use [Logic Pro X][logic-pro].

For trailers, [Final Cut Pro X][final-cut-pro-x].

[Direct Mail][direct-mail] is a lifesaver for sending out big press blasts.

I spend a lot of time on [Slack][] to keep my sanity while working alone in my apartment. Also [Tweetbot][] helps there.

I keep all my to-do lists in [TextEdit][].

[Backblaze][] has saved my bacon once or twice.

[ColorSnapper 2][colorsnapper] is so handy for matching colors when moving between Unity and the Adobe products.

And [Fantastical 2][fantastical] keeps my schedule organized!

### What would be your dream setup?

I wish my NAS could run [Plex][] adequately, I had an external thunderbolt GPU for my laptop, and someone would come over with a magic box that would compile my Xcode builds faster.

[5n2]: https://www.drobo.com/storage-products/5n2/ "A five-bay NAS."
[backblaze]: https://www.backblaze.com/cloud-backup.html "Online backup."
[coda]: https://panic.com/coda/ "A single-window HTML/web tool for the Mac."
[colorsnapper]: https://colorsnapper.com/ "A colour picker for the Mac."
[creative-cloud]: https://www.adobe.com/creativecloud.html "A subscription service for Adobe's creative suite."
[dash]: https://kapeli.com/dash "A snippet and documentation browser for Mac developers."
[direct-mail]: https://directmailmac.com/ "An email marketing app for the Mac."
[dreamweaver]: https://www.adobe.com/products/dreamweaver.html "A WYSIWYG editor."
[fantastical]: https://flexibits.com/fantastical "A calendaring app for the Mac."
[final-cut-pro-x]: https://en.wikipedia.org/wiki/Final_Cut_Pro_X "A nonlinear video editor."
[fontexplorer-x]: https://www.fontexplorerx.com/ "Font management software."
[glyphs]: https://www.glyphsapp.com/ "A font editor for the Mac."
[illustrator]: https://www.adobe.com/products/illustrator.html "A vector graphics editor."
[indesign]: https://www.adobe.com/products/indesign.html "A desktop/web publishing application."
[keyboard]: https://www.apple.com/keyboard/ "The keyboard."
[logic-pro]: https://www.apple.com/logic-pro/ "A professional audio application for the Mac."
[macbook-pro]: https://www.apple.com/macbook-pro/ "A laptop."
[magic-mouse-2]: https://en.wikipedia.org/wiki/Magic_Mouse_2 "A multi-touch mouse."
[photoshop]: https://www.adobe.com/products/photoshop.html "A bitmap image editor."
[plex]: https://plex.tv/ "Media center software."
[slack]: https://slack.com/ "A collaboration service."
[text-mesh-pro]: http://digitalnativestudios.com/ "A text rendering plugin for Unity."
[textedit]: https://support.apple.com/en-us/HT2523 "A text editor included with Mac OS X."
[transmit]: https://panic.com/transmit/ "An FTP/SFTP client for the Mac."
[tweetbot]: https://tapbots.com/tweetbot/mac/ "A Twitter client for the Mac."
[ultrafine-5k]: https://www.apple.com/shop/product/HKN62LL/A/lg-ultrafine-5k-display "A 27 inch monitor."
[unity]: https://unity3d.com/unity/ "A cross-platform game development tool."
[visual-studio]: http://www.visualstudio.com "A Windows development environment."
[xcode]: https://en.wikipedia.org/wiki/Xcode "An IDE for Mac developers."
[zippi]: https://www.amazon.com/Vornado-Zippi-Personal-Fan-Black/dp/B000E19MQ8/ "A personal fan."


text:
$(document).ready(function() {

	$('#id_permcat').change(function() {
		$('.loading').toggleClass('invisible');
		var permName = $('#id_permcat').val();
		loadConnectionRole(permName);
	});

});

function loadConnectionRole(name) {

	if(! name)
		name = 'default';

	$('.defperms-edit input').each(function() {
		if(! $(this).is(':disabled'))
			$(this).removeAttr('checked');
	});

	$.get('permcat/' + name, function(data) {
		$(data.perms).each(function() {
			if(this.value)
				$('#id_perms_' + this.name).attr('checked','checked');
		});
		$('.loading').toggleClass('invisible');
	});
}