text:
This directory contains Dart sample code related to the Kiosk API.

## Usage:

- Install the Dart protoc plugin:
  - `pub global activate protoc_plugin`.
  - add `.pub-cache/bin` in your home dir to your PATH if you haven't already.

- Run `COMPILE-PROTOS.sh` to download additional sources and compile needed support code.
- Run `pub get` to download Dart dependencies.
- Run `dart bin/server.dart` to run the sample server.
- Run `dart bin/client.dart` to run the sample client.


text:
// ------------------------------------------------------------------------------
// Copyright (c) 2015 Microsoft Corporation
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
// ------------------------------------------------------------------------------

package com.onedrive.sdk.generated;

import com.onedrive.sdk.concurrency.*;
import com.onedrive.sdk.core.*;
import com.onedrive.sdk.extensions.*;
import com.onedrive.sdk.http.*;
import com.onedrive.sdk.generated.*;
import com.onedrive.sdk.options.*;
import com.onedrive.sdk.serializer.*;

import java.util.*;

// **NOTE** This file was generated by a tool and any changes will be overwritten.

/**
 * The class for the Base Create Link Request.
 */
public class BaseCreateLinkRequest extends BaseRequest implements IBaseCreateLinkRequest {
    protected final CreateLinkBody mBody;

    /**
     * The request for this CreateLink
     *
     * @param requestUrl The request url
     * @param client The service client
     * @param options The options for this request
     */
    public BaseCreateLinkRequest(final String requestUrl, final IOneDriveClient client, final List<Option> options, final String type) {
        super(requestUrl, client, options, Permission.class);
        mBody = new CreateLinkBody();
        mBody.type = type;
    }

    /**
     * @deprecated  As of release 1.1.3, replaced by {@link #post(ICallback)}
     */
    @Deprecated public void create(final ICallback<Permission> callback) {
        this.post(callback);
    }

    /**
     * @deprecated  As of release 1.1.3, replaced by {@link #post()}
     */
    @Deprecated public Permission create() throws ClientException {
        return this.post();
    }

    public void post(final ICallback<Permission> callback) {
        send(HttpMethod.POST, callback, mBody);
    }

    public Permission post() throws ClientException {
        return send(HttpMethod.POST, mBody);
    }

    public ICreateLinkRequest select(final String value) {
        getQueryOptions().add(new QueryOption("select", value));
        return (CreateLinkRequest)this;
    }

    public ICreateLinkRequest top(final int value) {
        getQueryOptions().add(new QueryOption("top", value+""));
        return (CreateLinkRequest)this;
    }

    public ICreateLinkRequest expand(final String value) {
        getQueryOptions().add(new QueryOption("expand", value));
        return (CreateLinkRequest)this;
    }
}

redpajama_set_name: RedPajamaGithub


text:
ACCEPTED

#### According to
The Catalogue of Life, 3rd January 2011

#### Published in
Annals Inst. Agron. Moscow 9: 47 (1903)

#### Original name
Peronospora cubensis Berk. & M.A. Curtis, 1868

### Remarks
null


text:
(function ($, SmallGrid) {
    "use strict";

    $.extend(true, SmallGrid, {
        "Grid": {
            "Create": CreateModel,
            "Model": GridModel
        }
    });

    function GridModel($container, context, settings) {
        var self = this,
            plugins = {},
            version = "0.6.2 beta",
            id = SmallGrid.Utils.createGuid();

        /*
         * Init & Destroy
         */
        function init() {
            registerPlugins(settings.plugins);

            var contextKeys = ["windowManager", "view", "viewModel"];
            for (var i = 0; i < contextKeys.length; i++) {
                context[contextKeys[i]].init();
            }

            self.onInitialize.notify({});
            return self;
        }

        function destroy() {
            unregisterPlugins();

            var contextKeys = ["windowManager", "view", "viewModel", "rowsModel", "columnsModel"];
            for (var i = 0; i < contextKeys.length; i++) {
                context[contextKeys[i]].destroy();
                delete context[contextKeys[i]];
            }

            self.onDestroy.notify({});
        }
        /*
         * WindowManager
         */
        function getWindowManager() {
            return context.windowManager;
        }

        /*
         * View
         */
        function getView() {
            return context.view;
        }

        /*
         * View model
         */
        function getViewModel() {
            return context.viewModel;
        }

        function getRowsModel() {
            return context.rowsModel;
        }

        function getColumnsModel() {
            return context.columnsModel;
        }

        /*
         * Settings
         */
        function getSettings() {
            return settings;
        }

        /*
         * Plugins
         */
        function getPlugin(name) {
            if (plugins[name]) {
                return plugins[name];
            }
        }

        function getPlugins() {
            return plugins;
        }

        function isRegisteredPlugin(name) {
            return plugins[name] !== undefined;
        }

        function registerPlugin(name, pluginSettings) {
            if (isRegisteredPlugin(name)) {
                unregisterPlugin(name);
            }

            var plugin = SmallGrid.Plugins.Create(
                name,
                context,
                settings,
                pluginSettings
            );

            if (!plugin) {
                throw new Error("Plugin is not defined.");
            }

            plugins[name] = plugin;
        }

        function registerPlugins(plugins) {
            var keys = Object.keys(plugins);
            for (var i = 0; i < keys.length; i++) {
                registerPlugin(keys[i], plugins[keys[i]]);
            }
        }

        function unregisterPlugin(name) {
            if (plugins[name]) {
                plugins[name].destroy();
                delete plugins[name];
            }
        }

        function unregisterPlugins() {
            var keys = Object.keys(plugins);
            for (var i = 0; i < keys.length; i++) {
                unregisterPlugin(keys[i]);
            }
        }

        /*
         * Other
         */
        function getVersion() {
            return version;
        }

        function getId() {
            return id;
        }

        $.extend(this, {
            "init": init,
            "destroy": destroy,

            "getId": getId,
            "getPlugin": getPlugin,
            "getPlugins": getPlugins,
            "getSettings": getSettings,
            "getVersion": getVersion,
            "getView": getView,
            "getViewModel": getViewModel,
            "getRowsModel": getRowsModel,
            "getColumnsModel": getColumnsModel,
            "getWindowManager": getWindowManager,
            "isRegisteredPlugin": isRegisteredPlugin,
            "registerPlugin": registerPlugin,
            "registerPlugins": registerPlugins,
            "unregisterPlugin": unregisterPlugin,
            "unregisterPlugins": unregisterPlugins,

            "onInitialize": SmallGrid.Callback.Create(),
            "onDestroy": SmallGrid.Callback.Create()
        });
    }

    function CreateModel($container, rows, columns, options, autoInit) {
        var settings = SmallGrid.Settings.Create(options || {});
        var rowsModel = SmallGrid.Row.Create(rows || [], settings);
        var columnsModel = SmallGrid.Column.Create(columns || [], settings);
        var viewModel = SmallGrid.View.Model.Create(rowsModel, columnsModel, settings, false);
        var view = SmallGrid.View.Create($container, viewModel, settings, false);
        var windowManager = SmallGrid.View.Window.Create(view, settings, false);

        var grid = new GridModel(
            $container,
            {
                "columnsModel": columnsModel,
                "rowsModel": rowsModel,
                "view": view,
                "viewModel": viewModel,
                "windowManager": windowManager
            },
            settings
        );

        if (autoInit !== false) grid.init();

        return grid;

    }

})(jQuery, window.SmallGrid = window.SmallGrid || {});


text:
export const Slotted = {
    template: (
        `

            <slot name="fullName">
                <slot name="firstName">d:firstName</slot>
                <slot name="lastName">d:lastName</slot>
            </slot>

`)
};

export const ScopedSlotted = {
    template: (
        `

            <slot name="fullName" data="a:fullName">
                <slot name="firstName" data="a:firstName">d:firstName</slot>
                <slot name="lastName" data="a:lastName">d:lastName</slot>
            </slot>

`)
};


text:
layout: "v2_fluid/docs_base"
version: "nightly"
versionHref: "/docs/v2/nightly"
path: ""
category: api
id: "{{ClickBlock | slugify}}"
title: "ClickBlock"
header_sub_title: "Let in module "
doc: "ClickBlock"
docType: "let"
---

    View Source

    Improve this doc

  ClickBlock

ClickBlock let

exported from ionic/ionic

defined in ionic/util/click-block.ts (line 38)


text:
set -e
SCRIPT_DIR="$( cd -P "$( dirname "${BASH_SOURCE[0]}" )" && pwd )"
PROJECT_DIR="$SCRIPT_DIR/../"
pushd $PROJECT_DIR

gem build go_cart.gemspec
for f in *.gem; do gem install --local $f; done
rm -rf *.gem

popd


text:
package com.bsb.sample.sonar.rule.implement;

import com.bsb.common.integration.checkstyle.tester.CheckStyleTester;
import com.bsb.sample.test.sonar.model.implement.ClassWithTooManyImplement;
import com.bsb.sonar.sample.rule.implement.ImplementClausesCounterCheck;
import com.puppycrawl.tools.checkstyle.api.SeverityLevel;
import org.junit.BeforeClass;
import org.junit.Test;

import java.util.Locale;

import static com.bsb.common.integration.checkstyle.tester.ViolationMatcher.*;

/**
 * @author Sebastien Gerard
 */
public class ImplementClausesCounterCheckFrenchTest extends AbstractCheckTest {

    private static CheckStyleTester analysis;

    @BeforeClass
    public static void setup() {
        analysis = getTester().withLocale(Locale.FRENCH).build().assertNoException();
    }

    @Test
    public void locale() {
        analysis.get(ClassWithTooManyImplement.class)
            .assertOnlyThose(
                violation(ImplementClausesCounterCheck.class).on(23, 40)
                    .withLevel(SeverityLevel.WARNING)
                    .withMessage("Trop d'implements (plus de 2).")
            );
    }

}


text:
<template name="sideNav">

			{{> accountBox }}

		{{> toolbar}}
		{{#if currentUser}}

				{{_ "More_unreads"}}

					{{> roomList unread=true label="Unread_Rooms" }}

					{{#each roomType}}
						{{#if canShowRoomType}}
							{{> roomList identifier=identifier label=label isCombined=isCombined header=header }}
						{{/if}}
					{{/each}}

					{{#if canViewHistory}}

							{{_ "History"}}

					{{/if}}

				{{_ "More_unreads"}}

					{{> Template.dynamic template=flexTemplate data=flexData }}

		{{else}}

					{{> roomList anonymous=true label="Channels" }}

		{{/if}}

			{{{footer}}}

</template>


text:
module Azure::Automation::Mgmt::V2015_10_31
  module Models
    #
    # The dsc nodeconfiguration property associated with the entity.
    #
    class DscNodeConfigurationAssociationProperty

      include MsRestAzure

      # @return [String] Gets or sets the name of the dsc nodeconfiguration.
      attr_accessor :name

      #
      # Mapper for DscNodeConfigurationAssociationProperty class as Ruby Hash.
      # This will be used for serialization/deserialization.
      #
      def self.mapper()
        {
          client_side_validation: true,
          required: false,
          serialized_name: 'DscNodeConfigurationAssociationProperty',
          type: {
            name: 'Composite',
            class_name: 'DscNodeConfigurationAssociationProperty',
            model_properties: {
              name: {
                client_side_validation: true,
                required: false,
                serialized_name: 'name',
                type: {
                  name: 'String'
                }
              }
            }
          }
        }
      end
    end
  end
end


text:
#pragma warning(disable : 4244)

class CEnvelope {
public:
	CEnvelope();
	virtual ~CEnvelope();

  float attack;
  float sustain;
  float release;
  float amplitude;
  float shape;
  float GetEnv(int time);
};

#pragma pack(1)

typedef struct {
  float frequency;	char frequency_env;
  float volume;			char volume_env;
	float pw;					char pw_env;
  char waveform;
} OSCILLATOR;

class CSample {
public:
	CSample(char * raw);
	virtual ~CSample();

  CEnvelope  * env; int numenv;
  OSCILLATOR * osc; int numosc;

  char filter;
  char rezo;
  float cutoff;    char cutoff_env;
  float resonance; char resonance_env;
  float resoamp;   char resoamp_env;

	float clip_level;
	float gain;

	int length;

#if 0
  int filter;
  int rezo;
  float cutoff;    int cutoff_env;
  float resonance; int resonance_env;
  float resoamp;   int resoamp_env;

	float clip_level;
	float gain;
#endif

	char sequence[16]; CEnvelope * seqenv;

	void zVCF( float *out, float *in, int num,
                    float &h0, float &h1, float rate, float bandwidth, int type );

	void GetFullSample(float * buff, int len);
	void GetFullSampleToXM(char * buff, int len);
};

#pragma pack()


text:
// Go support for Protocol Buffers - Google's data interchange format
//
// Copyright 2010 The Go Authors.  All rights reserved.
// https://github.com/golang/protobuf
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
//     * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
//     * Redistributions in binary form must reproduce the above
// copyright notice, this list of conditions and the following disclaimer
// in the documentation and/or other materials provided with the
// distribution.
//     * Neither the name of Google Inc. nor the names of its
// contributors may be used to endorse or promote products derived from
// this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

/*
	The code generator for the plugin for the Google protocol buffer compiler.
	It generates Go code from the protocol buffer description files read by the
	main routine.
*/
package generator

import (
	"bufio"
	"bytes"
	"fmt"
	"go/parser"
	"go/printer"
	"go/token"
	"log"
	"os"
	"path"
	"strconv"
	"strings"
	"unicode"
	"unicode/utf8"

	"github.com/golang/protobuf/proto"
	"github.com/golang/protobuf/protoc-gen-go/descriptor"
	plugin "github.com/golang/protobuf/protoc-gen-go/plugin"
	"github.com/johanbrandhorst/protobuf/proto"
)

// A Plugin provides functionality to add to the output during Go code generation,
// such as to produce RPC stubs.
type Plugin interface {
	// Name identifies the plugin.
	Name() string
	// Init is called once after data structures are built but before
	// code generation begins.
	Init(g *Generator)
	// Generate produces the code generated by the plugin for this file,
	// except for the imports, by calling the generator's methods P, In, and Out.
	Generate(file *FileDescriptor)
	// GenerateImports produces the import declarations for this file.
	// It is called after Generate.
	GenerateImports(file *FileDescriptor)
}

var plugins []Plugin

// RegisterPlugin installs a (second-order) plugin to be run when the Go output is generated.
// It is typically called during initialization.
func RegisterPlugin(p Plugin) {
	plugins = append(plugins, p)
}

// generatedCodeVersion indicates a version of the generated code.
// It is incremented whenever an incompatibility between the generated code and
// the jspb package is introduced; the generated code references
// a constant, jspb.JspbPackageIsVersionN (where N is generatedCodeVersion).
const generatedCodeVersion = 2

// Each type we import as a protocol buffer (other than FileDescriptorProto) needs
// a pointer to the FileDescriptorProto that represents it.  These types achieve that
// wrapping by placing each Proto inside a struct with the pointer to its File. The
// structs have the same names as their contents, with "Proto" removed.
// FileDescriptor is used to store the things that it points to.

// The file and package name method are common to messages and enums.
type common struct {
	file *descriptor.FileDescriptorProto // File this object comes from.
}

// PackageName is name in the package clause in the generated file.
func (c *common) PackageName() string { return uniquePackageOf(c.file) }

func (c *common) File() *descriptor.FileDescriptorProto { return c.file }

func fileIsProto3(file *descriptor.FileDescriptorProto) bool {
	return file.GetSyntax() == "proto3"
}

func (c *common) proto3() bool { return fileIsProto3(c.file) }

// Descriptor represents a protocol buffer message.
type Descriptor struct {
	common
	*descriptor.DescriptorProto
	parent   *Descriptor       // The containing message, if any.
	nested   []*Descriptor     // Inner messages, if any.
	enums    []*EnumDescriptor // Inner enums, if any.
	typename []string          // Cached typename vector.
	index    int               // The index into the container, whether the file or another message.
	path     string            // The SourceCodeInfo path as comma-separated integers.
	group    bool
}

// TypeName returns the elements of the dotted type name.
// The package name is not part of this name.
func (d *Descriptor) TypeName() []string {
	if d.typename != nil {
		return d.typename
	}
	n := 0
	for parent := d; parent != nil; parent = parent.parent {
		n++
	}
	s := make([]string, n, n)
	for parent := d; parent != nil; parent = parent.parent {
		n--
		s[n] = parent.GetName()
	}
	d.typename = s
	return s
}

// EnumDescriptor describes an enum. If it's at top level, its parent will be nil.
// Otherwise it will be the descriptor of the message in which it is defined.
type EnumDescriptor struct {
	common
	*descriptor.EnumDescriptorProto
	parent   *Descriptor // The containing message, if any.
	typename []string    // Cached typename vector.
	index    int         // The index into the container, whether the file or a message.
	path     string      // The SourceCodeInfo path as comma-separated integers.
}

// TypeName returns the elements of the dotted type name.
// The package name is not part of this name.
func (e *EnumDescriptor) TypeName() (s []string) {
	if e.typename != nil {
		return e.typename
	}
	name := e.GetName()
	if e.parent == nil {
		s = make([]string, 1)
	} else {
		pname := e.parent.TypeName()
		s = make([]string, len(pname)+1)
		copy(s, pname)
	}
	s[len(s)-1] = name
	e.typename = s
	return s
}

// Everything but the last element of the full type name, CamelCased.
// The values of type Foo.Bar are call Foo_value1... not Foo_Bar_value1... .
func (e *EnumDescriptor) prefix() string {
	if e.parent == nil {
		// If the enum is not part of a message, the prefix is just the type name.
		return CamelCase(*e.Name) + "_"
	}
	typeName := e.TypeName()
	return CamelCaseSlice(typeName[0:len(typeName)-1]) + "_"
}

// The integer value of the named constant in this enumerated type.
func (e *EnumDescriptor) integerValueAsString(name string) string {
	for _, c := range e.Value {
		if c.GetName() == name {
			return fmt.Sprint(c.GetNumber())
		}
	}
	log.Fatal("cannot find value for enum constant")
	return ""
}

// ImportedDescriptor describes a type that has been publicly imported from another file.
type ImportedDescriptor struct {
	common
	o Object
}

func (id *ImportedDescriptor) TypeName() []string { return id.o.TypeName() }

// FileDescriptor describes an protocol buffer descriptor file (.proto).
// It includes slices of all the messages and enums defined within it.
// Those slices are constructed by WrapTypes.
type FileDescriptor struct {
	*descriptor.FileDescriptorProto
	desc []*Descriptor         // All the messages defined in this file.
	enum []*EnumDescriptor     // All the enums defined in this file.
	imp  []*ImportedDescriptor // All types defined in files publicly imported by this file.

	// Comments, stored as a map of path (comma-separated integers) to the comment.
	comments map[string]*descriptor.SourceCodeInfo_Location

	index int // The index of this file in the list of files to generate code for

	proto3 bool // whether to generate proto3 code for this file
}

// PackageName is the package name we'll use in the generated code to refer to this file.
func (d *FileDescriptor) PackageName() string { return uniquePackageOf(d.FileDescriptorProto) }

// VarName is the variable name we'll use in the generated code to refer
// to the compressed bytes of this descriptor. It is not exported, so
// it is only valid inside the generated package.
func (d *FileDescriptor) VarName() string { return fmt.Sprintf("fileDescriptor%d", d.index) }

// goPackageOption interprets the file's go_package option.
// If there is no go_package, it returns ("", "", false).
// If there's a simple name, it returns ("", pkg, true).
// If the option implies an import path, it returns (impPath, pkg, true).
func (d *FileDescriptor) goPackageOption() (impPath, pkg string, ok bool) {
	pkg = gopherjs.GetGopherJSPackage(d.FileDescriptorProto)
	if pkg == "" {
		return
	}
	ok = true
	// The presence of a slash implies there's an import path.
	slash := strings.LastIndex(pkg, "/")
	if slash < 0 {
		return
	}
	impPath, pkg = pkg, pkg[slash+1:]
	// A semicolon-delimited suffix overrides the package name.
	sc := strings.IndexByte(impPath, ';')
	if sc < 0 {
		return
	}
	impPath, pkg = impPath[:sc], impPath[sc+1:]
	return
}

// goPackageName returns the Go package name to use in the
// generated Go file. The result explicit reports whether the name
// came from an option gopherjs_package statement.  If explicit is false,
// the name was derived from the protocol buffer's package statement
// or the input file name.
func (d *FileDescriptor) goPackageName() (name string, explicit bool) {
	// Does the file have a "go_package" option?
	if _, pkg, ok := d.goPackageOption(); ok {
		return pkg, true
	}

	// Does the file have a package clause?
	if pkg := d.GetPackage(); pkg != "" {
		return pkg, false
	}
	// Use the file base name.
	return baseName(d.GetName()), false
}

// goFileName returns the output name for the generated Go file.
func (d *FileDescriptor) goFileName() string {
	name := *d.Name
	if ext := path.Ext(name); ext == ".proto" || ext == ".protodevel" {
		name = name[:len(name)-len(ext)]
	}
	name += ".pb.gopherjs.go"

	// Does the file have a "go_package" option?
	// If it does, it may override the filename.
	if impPath, _, ok := d.goPackageOption(); ok && impPath != "" {
		// Replace the existing dirname with the declared import path.
		_, name = path.Split(name)
		name = path.Join(impPath, name)
		return name
	}

	return name
}

// Object is an interface abstracting the abilities shared by enums, messages, extensions and imported objects.
type Object interface {
	PackageName() string // The name we use in our output (a_b_c), possibly renamed for uniqueness.
	TypeName() []string
	File() *descriptor.FileDescriptorProto
}

// Each package name we generate must be unique. The package we're generating
// gets its own name but every other package must have a unique name that does
// not conflict in the code we generate.  These names are chosen globally (although
// they don't have to be, it simplifies things to do them globally).
func uniquePackageOf(fd *descriptor.FileDescriptorProto) string {
	s, ok := uniquePackageName[fd]
	if !ok {
		log.Fatal("internal error: no package name defined for " + fd.GetName())
	}
	return s
}

// Generator is the type whose methods generate the output, stored in the associated response structure.
type Generator struct {
	*bytes.Buffer

	Request  *plugin.CodeGeneratorRequest  // The input.
	Response *plugin.CodeGeneratorResponse // The output.

	Param             map[string]string // Command-line parameters.
	PackageImportPath string            // Go import path of the package we're generating code for
	ImportPrefix      string            // String to prefix to imported package file names.
	ImportMap         map[string]string // Mapping from .proto file name to import path

	Pkg map[string]string // The names under which we import support packages

	packageName      string                     // What we're calling ourselves.
	allFiles         []*FileDescriptor          // All files in the tree
	allFilesByName   map[string]*FileDescriptor // All files by filename.
	genFiles         []*FileDescriptor          // Those files we will generate output for.
	file             *FileDescriptor            // The file we are compiling now.
	usedPackages     map[string]bool            // Names of packages used in current file.
	typeNameToObject map[string]Object          // Key is a fully-qualified name in input syntax.
	init             []string                   // Lines to emit in the init function.
	indent           string
	writeOutput      bool
}

// New creates a new generator and allocates the request and response protobufs.
func New() *Generator {
	g := new(Generator)
	g.Buffer = new(bytes.Buffer)
	g.Request = new(plugin.CodeGeneratorRequest)
	g.Response = new(plugin.CodeGeneratorResponse)
	return g
}

// Error reports a problem, including an error, and exits the program.
func (g *Generator) Error(err error, msgs ...string) {
	s := strings.Join(msgs, " ") + ":" + err.Error()
	log.Print("protoc-gen-gopherjs: error:", s)
	os.Exit(1)
}

// Fail reports a problem and exits the program.
func (g *Generator) Fail(msgs ...string) {
	s := strings.Join(msgs, " ")
	log.Print("protoc-gen-gopherjs: error:", s)
	os.Exit(1)
}

// CommandLineParameters breaks the comma-separated list of key=value pairs
// in the parameter (a member of the request protobuf) into a key/value map.
// It then sets file name mappings defined by those entries.
func (g *Generator) CommandLineParameters(parameter string) {
	g.Param = make(map[string]string)
	for _, p := range strings.Split(parameter, ",") {
		if i := strings.Index(p, "="); i < 0 {
			g.Param[p] = ""
		} else {
			g.Param[p[0:i]] = p[i+1:]
		}
	}

	g.ImportMap = make(map[string]string)
	pluginList := "none" // Default list of plugin names to enable (empty means all).
	for k, v := range g.Param {
		switch k {
		case "import_prefix":
			g.ImportPrefix = v
		case "import_path":
			g.PackageImportPath = v
		case "plugins":
			pluginList = v
		default:
			if len(k) > 0 && k[0] == 'M' {
				g.ImportMap[k[1:]] = v
			}
		}
	}
	if pluginList != "" {
		// Amend the set of plugins.
		enabled := make(map[string]bool)
		for _, name := range strings.Split(pluginList, "+") {
			enabled[name] = true
		}
		var nplugins []Plugin
		for _, p := range plugins {
			if enabled[p.Name()] {
				nplugins = append(nplugins, p)
			}
		}
		plugins = nplugins
	}
}

// DefaultPackageName returns the package name printed for the object.
// If its file is in a different package, it returns the package name we're using for this file, plus ".".
// Otherwise it returns the empty string.
func (g *Generator) DefaultPackageName(obj Object) string {
	pkg := obj.PackageName()
	if pkg == g.packageName {
		return ""
	}
	return pkg + "."
}

// For each input file, the unique package name to use, underscored.
var uniquePackageName = make(map[*descriptor.FileDescriptorProto]string)

// Package names already registered.  Key is the name from the .proto file;
// value is the name that appears in the generated code.
var pkgNamesInUse = make(map[string]bool)

// Create and remember a guaranteed unique package name for this file descriptor.
// Pkg is the candidate name.  If f is nil, it's a builtin package like "proto" and
// has no file descriptor.
func RegisterUniquePackageName(pkg string, f *FileDescriptor) string {
	// Convert dots to underscores before finding a unique alias.
	pkg = strings.Map(badToUnderscore, pkg)

	for i, orig := 1, pkg; pkgNamesInUse[pkg]; i++ {
		// It's a duplicate; must rename.
		pkg = orig + strconv.Itoa(i)
	}
	// Install it.
	pkgNamesInUse[pkg] = true
	if f != nil {
		uniquePackageName[f.FileDescriptorProto] = pkg
	}
	return pkg
}

var isGoKeyword = map[string]bool{
	"break":       true,
	"case":        true,
	"chan":        true,
	"const":       true,
	"continue":    true,
	"default":     true,
	"else":        true,
	"defer":       true,
	"fallthrough": true,
	"for":         true,
	"func":        true,
	"go":          true,
	"goto":        true,
	"if":          true,
	"import":      true,
	"interface":   true,
	"map":         true,
	"package":     true,
	"range":       true,
	"return":      true,
	"select":      true,
	"struct":      true,
	"switch":      true,
	"type":        true,
	"var":         true,
}

func sanitiseIdentifier(i string) string {
	// Identifier must not be keyword: insert _.
	if isGoKeyword[i] {
		i = "_" + i
	}
	// Identifier must not begin with digit: insert _.
	if r, _ := utf8.DecodeRuneInString(i); unicode.IsDigit(r) {
		i = "_" + i
	}

	return i
}

// defaultGoPackage returns the package name to use,
// derived from the import path of the package we're building code for.
func (g *Generator) defaultGoPackage() string {
	p := g.PackageImportPath
	if i := strings.LastIndex(p, "/"); i >= 0 {
		p = p[i+1:]
	}
	if p == "" {
		return ""
	}

	return sanitiseIdentifier(strings.Map(badToUnderscore, p))
}

// SetPackageNames sets the package name for this run.
// The package name must agree across all files being generated.
// It also defines unique package names for all imported files.
func (g *Generator) SetPackageNames() {
	// Register the name for this package.  It will be the first name
	// registered so is guaranteed to be unmodified.
	pkg, explicit := g.genFiles[0].goPackageName()

	// Check all files for an explicit go_package option.
	for _, f := range g.genFiles {
		thisPkg, thisExplicit := f.goPackageName()
		if thisExplicit {
			if !explicit {
				// Let this file's go_package option serve for all input files.
				pkg, explicit = thisPkg, true
			} else if thisPkg != pkg {
				g.Fail("inconsistent package names:", thisPkg, pkg)
			}
		}
	}

	// If we don't have an explicit go_package option but we have an
	// import path, use that.
	if !explicit {
		p := g.defaultGoPackage()
		if p != "" {
			pkg, explicit = p, true
		}
	}

	// If there was no go_package and no import path to use,
	// double-check that all the inputs have the same implicit
	// Go package name.
	if !explicit {
		for _, f := range g.genFiles {
			thisPkg, _ := f.goPackageName()
			if thisPkg != pkg {
				g.Fail("inconsistent package names:", thisPkg, pkg)
			}
		}
	}

	g.packageName = RegisterUniquePackageName(pkg, g.genFiles[0])

	// Register the support package names. They might collide with the
	// name of a package we import.
	g.Pkg = map[string]string{
		"jspb": RegisterUniquePackageName("jspb", nil),
	}

AllFiles:
	for _, f := range g.allFiles {
		for _, genf := range g.genFiles {
			if f == genf {
				// In this package already.
				uniquePackageName[f.FileDescriptorProto] = g.packageName
				continue AllFiles
			}
		}
		// The file is a dependency, so we want to ignore its go_package option
		// because that is only relevant for its specific generated output.
		pkg := f.GetPackage()
		if pkg == "" {
			pkg = baseName(*f.Name)
		}
		RegisterUniquePackageName(pkg, f)
	}
}

// WrapTypes walks the incoming data, wrapping DescriptorProtos, EnumDescriptorProtos
// and FileDescriptorProtos into file-referenced objects within the Generator.
// It also creates the list of files to generate and so should be called before GenerateAllFiles.
func (g *Generator) WrapTypes() {
	g.allFiles = make([]*FileDescriptor, 0, len(g.Request.ProtoFile))
	g.allFilesByName = make(map[string]*FileDescriptor, len(g.allFiles))
	for _, f := range g.Request.ProtoFile {
		// We must wrap the descriptors before we wrap the enums
		descs := wrapDescriptors(f)
		g.buildNestedDescriptors(descs)
		enums := wrapEnumDescriptors(f, descs)
		g.buildNestedEnums(descs, enums)
		fd := &FileDescriptor{
			FileDescriptorProto: f,
			desc:                descs,
			enum:                enums,
			proto3:              fileIsProto3(f),
		}
		extractComments(fd)
		g.allFiles = append(g.allFiles, fd)
		g.allFilesByName[f.GetName()] = fd
	}
	for _, fd := range g.allFiles {
		fd.imp = wrapImported(fd.FileDescriptorProto, g)
	}

	g.genFiles = make([]*FileDescriptor, 0, len(g.Request.FileToGenerate))
	for _, fileName := range g.Request.FileToGenerate {
		fd := g.allFilesByName[fileName]
		if fd == nil {
			g.Fail("could not find file named", fileName)
		}
		fd.index = len(g.genFiles)
		g.genFiles = append(g.genFiles, fd)
	}
}

// Scan the descriptors in this file.  For each one, build the slice of nested descriptors
func (g *Generator) buildNestedDescriptors(descs []*Descriptor) {
	for _, desc := range descs {
		if len(desc.NestedType) != 0 {
			for _, nest := range descs {
				if nest.parent == desc {
					desc.nested = append(desc.nested, nest)
				}
			}
			if len(desc.nested) != len(desc.NestedType) {
				g.Fail("internal error: nesting failure for", desc.GetName())
			}
		}
	}
}

func (g *Generator) buildNestedEnums(descs []*Descriptor, enums []*EnumDescriptor) {
	for _, desc := range descs {
		if len(desc.EnumType) != 0 {
			for _, enum := range enums {
				if enum.parent == desc {
					desc.enums = append(desc.enums, enum)
				}
			}
			if len(desc.enums) != len(desc.EnumType) {
				g.Fail("internal error: enum nesting failure for", desc.GetName())
			}
		}
	}
}

// Construct the Descriptor
func newDescriptor(desc *descriptor.DescriptorProto, parent *Descriptor, file *descriptor.FileDescriptorProto, index int) *Descriptor {
	d := &Descriptor{
		common:          common{file},
		DescriptorProto: desc,
		parent:          parent,
		index:           index,
	}
	if parent == nil {
		d.path = fmt.Sprintf("%d,%d", messagePath, index)
	} else {
		d.path = fmt.Sprintf("%s,%d,%d", parent.path, messageMessagePath, index)
	}

	// The only way to distinguish a group from a message is whether
	// the containing message has a TYPE_GROUP field that matches.
	if parent != nil {
		parts := d.TypeName()
		if file.Package != nil {
			parts = append([]string{file.GetPackage()}, parts...)
		}
		exp := "." + strings.Join(parts, ".")
		for _, field := range parent.Field {
			if field.GetType() == descriptor.FieldDescriptorProto_TYPE_GROUP && field.GetTypeName() == exp {
				d.group = true
				break
			}
		}
	}

	return d
}

// Return a slice of all the Descriptors defined within this file
func wrapDescriptors(file *descriptor.FileDescriptorProto) []*Descriptor {
	sl := make([]*Descriptor, 0, len(file.MessageType)+10)
	for i, desc := range file.MessageType {
		sl = wrapThisDescriptor(sl, desc, nil, file, i)
	}
	return sl
}

// Wrap this Descriptor, recursively
func wrapThisDescriptor(sl []*Descriptor, desc *descriptor.DescriptorProto, parent *Descriptor, file *descriptor.FileDescriptorProto, index int) []*Descriptor {
	sl = append(sl, newDescriptor(desc, parent, file, index))
	me := sl[len(sl)-1]
	for i, nested := range desc.NestedType {
		sl = wrapThisDescriptor(sl, nested, me, file, i)
	}
	return sl
}

// Construct the EnumDescriptor
func newEnumDescriptor(desc *descriptor.EnumDescriptorProto, parent *Descriptor, file *descriptor.FileDescriptorProto, index int) *EnumDescriptor {
	ed := &EnumDescriptor{
		common:              common{file},
		EnumDescriptorProto: desc,
		parent:              parent,
		index:               index,
	}
	if parent == nil {
		ed.path = fmt.Sprintf("%d,%d", enumPath, index)
	} else {
		ed.path = fmt.Sprintf("%s,%d,%d", parent.path, messageEnumPath, index)
	}
	return ed
}

// Return a slice of all the EnumDescriptors defined within this file
func wrapEnumDescriptors(file *descriptor.FileDescriptorProto, descs []*Descriptor) []*EnumDescriptor {
	sl := make([]*EnumDescriptor, 0, len(file.EnumType)+10)
	// Top-level enums.
	for i, enum := range file.EnumType {
		sl = append(sl, newEnumDescriptor(enum, nil, file, i))
	}
	// Enums within messages. Enums within embedded messages appear in the outer-most message.
	for _, nested := range descs {
		for i, enum := range nested.EnumType {
			sl = append(sl, newEnumDescriptor(enum, nested, file, i))
		}
	}
	return sl
}

// Return a slice of all the types that are publicly imported into this file.
func wrapImported(file *descriptor.FileDescriptorProto, g *Generator) (sl []*ImportedDescriptor) {
	for _, index := range file.PublicDependency {
		df := g.fileByName(file.Dependency[index])
		for _, d := range df.desc {
			if d.GetOptions().GetMapEntry() {
				continue
			}
			sl = append(sl, &ImportedDescriptor{common{file}, d})
		}
		for _, e := range df.enum {
			sl = append(sl, &ImportedDescriptor{common{file}, e})
		}
	}
	return
}

func extractComments(file *FileDescriptor) {
	file.comments = make(map[string]*descriptor.SourceCodeInfo_Location)
	for _, loc := range file.GetSourceCodeInfo().GetLocation() {
		if loc.LeadingComments == nil {
			continue
		}
		var p []string
		for _, n := range loc.Path {
			p = append(p, strconv.Itoa(int(n)))
		}
		file.comments[strings.Join(p, ",")] = loc
	}
}

// BuildTypeNameMap builds the map from fully qualified type names to objects.
// The key names for the map come from the input data, which puts a period at the beginning.
// It should be called after SetPackageNames and before GenerateAllFiles.
func (g *Generator) BuildTypeNameMap() {
	g.typeNameToObject = make(map[string]Object)
	for _, f := range g.allFiles {
		// The names in this loop are defined by the proto world, not us, so the
		// package name may be empty.  If so, the dotted package name of X will
		// be ".X"; otherwise it will be ".pkg.X".
		dottedPkg := "." + f.GetPackage()
		if dottedPkg != "." {
			dottedPkg += "."
		}
		for _, enum := range f.enum {
			name := dottedPkg + dottedSlice(enum.TypeName())
			g.typeNameToObject[name] = enum
		}
		for _, desc := range f.desc {
			name := dottedPkg + dottedSlice(desc.TypeName())
			g.typeNameToObject[name] = desc
		}
	}
}

// ObjectNamed, given a fully-qualified input type name as it appears in the input data,
// returns the descriptor for the message or enum with that name.
func (g *Generator) ObjectNamed(typeName string) Object {
	o, ok := g.typeNameToObject[typeName]
	if !ok {
		g.Fail("can't find object with type", typeName)
	}

	// If the file of this object isn't a direct dependency of the current file,
	// or in the current file, then this object has been publicly imported into
	// a dependency of the current file.
	// We should return the ImportedDescriptor object for it instead.
	direct := *o.File().Name == *g.file.Name
	if !direct {
		for _, dep := range g.file.Dependency {
			if *g.fileByName(dep).Name == *o.File().Name {
				direct = true
				break
			}
		}
	}
	if !direct {
		found := false
	Loop:
		for _, dep := range g.file.Dependency {
			df := g.fileByName(*g.fileByName(dep).Name)
			for _, td := range df.imp {
				if td.o == o {
					// Found it!
					o = td
					found = true
					break Loop
				}
			}
		}
		if !found {
			log.Printf("protoc-gen-gopherjs: WARNING: failed finding publicly imported dependency for %v, used in %v", typeName, *g.file.Name)
		}
	}

	return o
}

// P prints the arguments to the generated output.  It handles strings and int32s, plus
// handling indirections because they may be *string, etc.
func (g *Generator) P(str ...interface{}) {
	if !g.writeOutput {
		return
	}
	g.WriteString(g.indent)
	for _, v := range str {
		switch s := v.(type) {
		case string:
			g.WriteString(s)
		case *string:
			g.WriteString(*s)
		case bool:
			fmt.Fprintf(g, "%t", s)
		case *bool:
			fmt.Fprintf(g, "%t", *s)
		case int:
			fmt.Fprintf(g, "%d", s)
		case *int32:
			fmt.Fprintf(g, "%d", *s)
		case *int64:
			fmt.Fprintf(g, "%d", *s)
		case float64:
			fmt.Fprintf(g, "%g", s)
		case *float64:
			fmt.Fprintf(g, "%g", *s)
		default:
			g.Fail(fmt.Sprintf("unknown type in printer: %T", v))
		}
	}
	g.WriteByte('\n')
}

// addInitf stores the given statement to be printed inside the file's init function.
// The statement is given as a format specifier and arguments.
func (g *Generator) addInitf(stmt string, a ...interface{}) {
	g.init = append(g.init, fmt.Sprintf(stmt, a...))
}

// In Indents the output one tab stop.
func (g *Generator) In() { g.indent += "\t" }

// Out unindents the output one tab stop.
func (g *Generator) Out() {
	if len(g.indent) > 0 {
		g.indent = g.indent[1:]
	}
}

// GenerateAllFiles generates the output for all the files we're outputting.
func (g *Generator) GenerateAllFiles() {
	// Initialize the plugins
	for _, p := range plugins {
		p.Init(g)
	}
	// Generate the output. The generator runs for every file, even the files
	// that we don't generate output for, so that we can collate the full list
	// of exported symbols to support public imports.
	genFileMap := make(map[*FileDescriptor]bool, len(g.genFiles))
	for _, file := range g.genFiles {
		genFileMap[file] = true
	}
	for _, file := range g.allFiles {
		g.Reset()
		g.writeOutput = genFileMap[file]
		g.generate(file)
		if !g.writeOutput {
			continue
		}
		g.Response.File = append(g.Response.File, &plugin.CodeGeneratorResponse_File{
			Name:    proto.String(file.goFileName()),
			Content: proto.String(g.String()),
		})
	}
}

// Run all the plugins associated with the file.
func (g *Generator) runPlugins(file *FileDescriptor) {
	for _, p := range plugins {
		p.Generate(file)
	}
}

// FileOf return the FileDescriptor for this FileDescriptorProto.
func (g *Generator) FileOf(fd *descriptor.FileDescriptorProto) *FileDescriptor {
	for _, file := range g.allFiles {
		if file.FileDescriptorProto == fd {
			return file
		}
	}
	g.Fail("could not find file in table:", fd.GetName())
	return nil
}

// Fill the response protocol buffer with the generated output for all the files we're
// supposed to generate.
func (g *Generator) generate(file *FileDescriptor) {
	g.file = g.FileOf(file.FileDescriptorProto)
	g.usedPackages = make(map[string]bool)

	for _, td := range g.file.imp {
		g.generateImported(td)
	}
	for _, enum := range g.file.enum {
		g.generateEnum(enum)
	}
	for _, desc := range g.file.desc {
		// Don't generate virtual messages for maps.
		if desc.GetOptions().GetMapEntry() {
			continue
		}
		g.generateMessage(desc)
	}

	g.generateInitFunction()

	// Run the plugins before the imports so we know which imports are necessary.
	g.runPlugins(file)

	// Generate header and imports last, though they appear first in the output.
	rem := g.Buffer
	g.Buffer = new(bytes.Buffer)
	g.generateHeader()
	g.generateImports()
	g.generateVersionAssertion()

	if !g.writeOutput {
		return
	}
	g.Write(rem.Bytes())

	// Reformat generated code.
	fset := token.NewFileSet()
	raw := g.Bytes()
	ast, err := parser.ParseFile(fset, "", g, parser.ParseComments)
	if err != nil {
		// Print out the bad code with line numbers.
		// This should never happen in practice, but it can while changing generated code,
		// so consider this a debugging aid.
		var src bytes.Buffer
		s := bufio.NewScanner(bytes.NewReader(raw))
		for line := 1; s.Scan(); line++ {
			fmt.Fprintf(&src, "%5d\t%s\n", line, s.Bytes())
		}
		g.Fail("bad Go source code was generated:", err.Error(), "\n"+src.String())
	}
	g.Reset()
	err = (&printer.Config{Mode: printer.TabIndent | printer.UseSpaces, Tabwidth: 8}).Fprint(g, fset, ast)
	if err != nil {
		g.Fail("generated Go source code could not be reformatted:", err.Error())
	}
}

// Generate the header, including package definition
func (g *Generator) generateHeader() {
	g.P("// Code generated by protoc-gen-gopherjs. DO NOT EDIT.")
	g.P("// source: ", g.file.Name)
	g.P()

	name := g.file.PackageName()

	if g.file.index == 0 {
		// Generate package docs for the first file in the package.
		g.P("/*")
		g.In()
		g.P("Package ", name, " is a generated protocol buffer package.")
		g.P()
		if loc, ok := g.file.comments[strconv.Itoa(packagePath)]; ok {
			// not using g.PrintComments because this is a /* */ comment block.
			text := strings.TrimSuffix(loc.GetLeadingComments(), "\n")
			for _, line := range strings.Split(text, "\n") {
				line = strings.TrimPrefix(line, " ")
				// ensure we don't escape from the block comment
				line = strings.Replace(line, "*/", "* /", -1)
				g.P(line)
			}
			g.P()
		}
		var topMsgs []string
		g.P("It is generated from these files:")
		g.In()
		for _, f := range g.genFiles {
			g.P(f.Name)
			for _, msg := range f.desc {
				if msg.parent != nil {
					continue
				}
				topMsgs = append(topMsgs, CamelCaseSlice(msg.TypeName()))
			}
		}
		g.Out()
		g.P()
		g.P("It has these top-level messages:")
		g.In()
		for _, msg := range topMsgs {
			g.P(msg)
		}
		g.Out()
		g.Out()
		g.P("*/")
	}

	g.P("package ", name)
	g.P()
}

// PrintComments prints any comments from the source .proto file.
// The path is a comma-separated list of integers.
// It returns an indication of whether any comments were printed.
// See descriptor.proto for its format.
func (g *Generator) PrintComments(path string) bool {
	if !g.writeOutput {
		return false
	}
	if loc, ok := g.file.comments[path]; ok {
		text := strings.TrimSuffix(loc.GetLeadingComments(), "\n")
		for _, line := range strings.Split(text, "\n") {
			g.P("// ", strings.TrimPrefix(line, " "))
		}
		return true
	}
	return false
}

func (g *Generator) fileByName(filename string) *FileDescriptor {
	return g.allFilesByName[filename]
}

// weak returns whether the ith import of the current file is a weak import.
func (g *Generator) weak(i int32) bool {
	for _, j := range g.file.WeakDependency {
		if j == i {
			return true
		}
	}
	return false
}

// Generate the imports
func (g *Generator) generateImports() {
	g.P("import ", g.Pkg["jspb"], " ", strconv.Quote(g.ImportPrefix+"github.com/johanbrandhorst/protobuf/jspb"))
	for i, s := range g.file.Dependency {
		fd := g.fileByName(s)
		// Do not import our own package.
		if fd.PackageName() == g.packageName {
			continue
		}
		filename := fd.goFileName()
		// By default, import path is the dirname of the Go filename.
		importPath := path.Dir(filename)
		fmt.Fprintln(os.Stderr, importPath)
		// Skip blacklisted package from being added as import dependency
		if importPath == "github.com/johanbrandhorst/protobuf/proto" {
			// We don't want to add this package because it's only used
			// for the gopherjs_package directive, and it has no use in generated
			// packages.
			continue
		}
		if substitution, ok := g.ImportMap[s]; ok {
			importPath = substitution
		}
		importPath = g.ImportPrefix + importPath
		// Skip weak imports.
		if g.weak(int32(i)) {
			g.P("// skipping weak import ", fd.PackageName(), " ", strconv.Quote(importPath))
			continue
		}
		// We need to import all the dependencies, even if we don't reference them,
		// because other code and tools depend on having the full transitive closure
		// of protocol buffer types in the binary.
		pname := fd.PackageName()
		if _, ok := g.usedPackages[pname]; !ok {
			pname = "_"
		}
		g.P("import ", pname, " ", strconv.Quote(importPath))
	}
	g.P()

	// TODO: may need to worry about uniqueness across plugins
	for _, p := range plugins {
		p.GenerateImports(g.file)
		g.P()
	}
	g.P()
}

func (g *Generator) generateImported(id *ImportedDescriptor) {
	// Don't generate public import symbols for files that we are generating
	// code for, since those symbols will already be in this package.
	// We can't simply avoid creating the ImportedDescriptor objects,
	// because g.genFiles isn't populated at that stage.
	tn := id.TypeName()
	sn := tn[len(tn)-1]
	df := g.FileOf(id.o.File())
	filename := *df.Name
	for _, fd := range g.genFiles {
		if *fd.Name == filename {
			g.P("// Ignoring public import of ", sn, " from ", filename)
			g.P()
			return
		}
	}
	g.P("// ", sn, " from public import ", filename)
	g.usedPackages[df.PackageName()] = true

	g.P()
}

func (g *Generator) generateVersionAssertion() {
	// Assert version compatibility.
	g.P("// This is a compile-time assertion to ensure that this generated file")
	g.P("// is compatible with the jspb package it is being compiled against.")
	g.P("const _ = ", g.Pkg["jspb"], ".JspbPackageIsVersion", generatedCodeVersion)
	g.P()
}

// Generate the enum definitions for this EnumDescriptor.
func (g *Generator) generateEnum(enum *EnumDescriptor) {
	// The full type name
	typeName := enum.TypeName()
	// The full type name, CamelCased.
	ccTypeName := CamelCaseSlice(typeName)
	ccPrefix := enum.prefix()

	g.PrintComments(enum.path)
	g.P("type ", ccTypeName, " int")
	g.P("const (")
	g.In()
	for i, e := range enum.Value {
		g.PrintComments(fmt.Sprintf("%s,%d,%d", enum.path, enumValuePath, i))

		name := ccPrefix + *e.Name
		g.P(name, " ", ccTypeName, " = ", e.Number)
	}
	g.Out()
	g.P(")")
	g.P("var ", ccTypeName, "_name = map[int]string{")
	g.In()
	generated := make(map[int32]bool) // avoid duplicate values
	for _, e := range enum.Value {
		duplicate := ""
		if _, present := generated[*e.Number]; present {
			duplicate = "// Duplicate value: "
		}
		g.P(duplicate, e.Number, ": ", strconv.Quote(*e.Name), ",")
		generated[*e.Number] = true
	}
	g.Out()
	g.P("}")
	g.P("var ", ccTypeName, "_value = map[string]int{")
	g.In()
	for _, e := range enum.Value {
		g.P(strconv.Quote(*e.Name), ": ", e.Number, ",")
	}
	g.Out()
	g.P("}")

	g.P("func (x ", ccTypeName, ") String() string {")
	g.In()
	g.P("return ", ccTypeName, "_name[int(x)]")
	g.Out()
	g.P("}")

	g.P()
}

func needsStar(typ descriptor.FieldDescriptorProto_Type) bool {
	switch typ {
	case descriptor.FieldDescriptorProto_TYPE_GROUP:
		return false
	case descriptor.FieldDescriptorProto_TYPE_MESSAGE:
		return false
	case descriptor.FieldDescriptorProto_TYPE_BYTES:
		return false
	}
	return true
}

// TypeName is the printed name appropriate for an item. If the object is in the current file,
// TypeName drops the package name and underscores the rest.
// Otherwise the object is from another package; and the result is the underscored
// package name followed by the item name.
// The result always has an initial capital.
func (g *Generator) TypeName(obj Object) string {
	return g.DefaultPackageName(obj) + CamelCaseSlice(obj.TypeName())
}

// TypeNameWithPackage is like TypeName, but always includes the package
// name even if the object is in our own package.
func (g *Generator) TypeNameWithPackage(obj Object) string {
	return obj.PackageName() + CamelCaseSlice(obj.TypeName())
}

// GoType returns a string representing the type name, and the wire type
func (g *Generator) GoType(message *Descriptor, field *descriptor.FieldDescriptorProto) (typ string) {
	// TODO: Options.
	switch field.GetType() {
	case descriptor.FieldDescriptorProto_TYPE_DOUBLE:
		typ = "float64"
	case descriptor.FieldDescriptorProto_TYPE_FLOAT:
		typ = "float32"
	case descriptor.FieldDescriptorProto_TYPE_INT64:
		typ = "int64"
	case descriptor.FieldDescriptorProto_TYPE_UINT64:
		typ = "uint64"
	case descriptor.FieldDescriptorProto_TYPE_INT32:
		typ = "int32"
	case descriptor.FieldDescriptorProto_TYPE_UINT32:
		typ = "uint32"
	case descriptor.FieldDescriptorProto_TYPE_FIXED64:
		typ = "uint64"
	case descriptor.FieldDescriptorProto_TYPE_FIXED32:
		typ = "uint32"
	case descriptor.FieldDescriptorProto_TYPE_BOOL:
		typ = "bool"
	case descriptor.FieldDescriptorProto_TYPE_STRING:
		typ = "string"
	case descriptor.FieldDescriptorProto_TYPE_GROUP:
		desc := g.ObjectNamed(field.GetTypeName())
		typ = "*" + g.TypeName(desc)
	case descriptor.FieldDescriptorProto_TYPE_MESSAGE:
		desc := g.ObjectNamed(field.GetTypeName())
		typ = "*" + g.TypeName(desc)
	case descriptor.FieldDescriptorProto_TYPE_BYTES:
		typ = "[]byte"
	case descriptor.FieldDescriptorProto_TYPE_ENUM:
		desc := g.ObjectNamed(field.GetTypeName())
		typ = g.TypeName(desc)
	case descriptor.FieldDescriptorProto_TYPE_SFIXED32:
		typ = "int32"
	case descriptor.FieldDescriptorProto_TYPE_SFIXED64:
		typ = "int64"
	case descriptor.FieldDescriptorProto_TYPE_SINT32:
		typ = "int32"
	case descriptor.FieldDescriptorProto_TYPE_SINT64:
		typ = "int64"
	default:
		g.Fail("unknown type for", field.GetName())
	}
	if isRepeated(field) {
		typ = "[]" + typ
	} else if message != nil && message.proto3() {
		return
	} else if field.OneofIndex != nil && message != nil {
		return
	} else if needsStar(field.GetType()) {
		typ = "*" + typ
	}
	return
}

// JSPBTypeFunc gets the jspb function type suffix
func (g *Generator) JSPBTypeFunc(field *descriptor.FieldDescriptorProto) string {
	switch field.GetType() {
	case descriptor.FieldDescriptorProto_TYPE_INT32:
		return "Int32"
	case descriptor.FieldDescriptorProto_TYPE_SFIXED32:
		return "Sfixed32"
	case descriptor.FieldDescriptorProto_TYPE_SINT32:
		return "Sint32"
	case descriptor.FieldDescriptorProto_TYPE_UINT32:
		return "Uint32"
	case descriptor.FieldDescriptorProto_TYPE_FIXED32:
		return "Fixed32"
	case descriptor.FieldDescriptorProto_TYPE_INT64:
		return "Int64"
	case descriptor.FieldDescriptorProto_TYPE_SFIXED64:
		return "Sfixed64"
	case descriptor.FieldDescriptorProto_TYPE_SINT64:
		return "Sint64"
	case descriptor.FieldDescriptorProto_TYPE_UINT64:
		return "Uint64"
	case descriptor.FieldDescriptorProto_TYPE_FIXED64:
		return "Fixed64"
	case descriptor.FieldDescriptorProto_TYPE_FLOAT:
		return "Float32"
	case descriptor.FieldDescriptorProto_TYPE_DOUBLE:
		return "Float64"
	case descriptor.FieldDescriptorProto_TYPE_BOOL:
		return "Bool"
	case descriptor.FieldDescriptorProto_TYPE_STRING:
		return "String"
	case descriptor.FieldDescriptorProto_TYPE_BYTES:
		return "Bytes"
	default:
		panic(fmt.Sprint("unknown type for", field.GetName(), field.GetTypeName()))
	}
}

func (g *Generator) RecordTypeUse(t string) {
	if obj, ok := g.typeNameToObject[t]; ok {
		// Call ObjectNamed to get the true object to record the use.
		obj = g.ObjectNamed(t)
		g.usedPackages[obj.PackageName()] = true
	}
}

// Method names that may be generated.  Fields with these names get an
// underscore appended. Any change to this set is a potential incompatible
// API change because it changes generated field names.
var methodNames = [...]string{
	"Marshal",
	"MarshalToWriter",
	"Unmarshal",
	"UnmarshalFromReader",
}

// Generate the type and default constant definitions for this Descriptor.
func (g *Generator) generateMessage(message *Descriptor) {
	// The full type name
	typeName := message.TypeName()
	// The full type name, CamelCased.
	messageType := CamelCaseSlice(typeName)

	usedNames := make(map[string]bool)
	for _, n := range methodNames {
		usedNames[n] = true
	}

	// Maps populated during first message field iteration
	// CamelCased field name
	fieldNames := make(map[*descriptor.FieldDescriptorProto]string)
	// Getter name
	fieldGetterNames := make(map[*descriptor.FieldDescriptorProto]string)
	// Field Go type
	fieldTypes := make(map[*descriptor.FieldDescriptorProto]string)
	// Field Number as a string
	fieldNumbers := make(map[*descriptor.FieldDescriptorProto]string)
	// Field map fields, if field is a map
	fieldMapFields := make(map[*descriptor.FieldDescriptorProto]struct {
		Key, Value *descriptor.FieldDescriptorProto
	})
	// Field map types, if field if a map
	fieldMapTypes := make(map[*descriptor.FieldDescriptorProto]struct {
		Key, Value string
	})

	oneofFieldName := make(map[int32]string)                           // indexed by oneof_index field of FieldDescriptorProto
	oneofDisc := make(map[int32]string)                                // name of discriminator method
	oneofTypeName := make(map[*descriptor.FieldDescriptorProto]string) // without star
	oneofInsertPoints := make(map[int32]int)                           // oneof_index => offset of g.Buffer

	// allocNames finds a conflict-free variation of the given strings,
	// consistently mutating their suffixes.
	// It returns the same number of strings.
	allocNames := func(ns ...string) []string {
	Loop:
		for {
			for _, n := range ns {
				if usedNames[n] {
					for i := range ns {
						ns[i] += "_"
					}
					continue Loop
				}
			}
			for _, n := range ns {
				usedNames[n] = true
			}
			return ns
		}
	}

	g.PrintComments(message.path)
	g.P("type ", messageType, " struct {")
	g.In()

	// Write out fields of the message
	for i, field := range message.Field {
		// Allocate the getter and the field at the same time so name
		// collisions create field/method consistent names.
		// TODO: This allocation occurs based on the order of the fields
		// in the proto file, meaning that a change in the field
		// ordering can change generated Method/Field names.
		ns := allocNames(CamelCase(field.GetName()), "Get"+CamelCase(field.GetName()))
		fieldNames[field], fieldGetterNames[field] = ns[0], ns[1]
		fieldTypes[field] = g.GoType(message, field)
		fieldNumbers[field] = strconv.Itoa(int(field.GetNumber()))

		// Print comment for field if it isn't a oneof field
		if field.OneofIndex == nil {
			g.PrintComments(fmt.Sprintf("%s,%d,%d", message.path, messageFieldPath, i))
		}

		// Populate field oneof metadata maps
		if field.OneofIndex != nil && oneofFieldName[field.GetOneofIndex()] == "" {
			// This is the first field of a oneof we haven't seen before.
			// Generate the union field.
			odp := message.OneofDecl[int(field.GetOneofIndex())]
			oneofFieldName[field.GetOneofIndex()] = allocNames(CamelCase(odp.GetName()))[0]

			com := g.PrintComments(fmt.Sprintf("%s,%d,%d", message.path, messageOneofPath, field.GetOneofIndex()))
			if com {
				g.P("//")
			}
			g.P("// Types that are valid to be assigned to ", oneofFieldName[field.GetOneofIndex()], ":")
			// Generate the rest of this comment later,
			// when we've computed any disambiguation.
			oneofInsertPoints[field.GetOneofIndex()] = g.Buffer.Len()

			oneofDisc[field.GetOneofIndex()] = "is" + messageType + "_" + oneofFieldName[field.GetOneofIndex()]
			g.P(oneofFieldName[field.GetOneofIndex()], " ", oneofDisc[field.GetOneofIndex()])
		}

		// Populate field metadata maps
		if d := g.getMapDescriptor(field); d != nil {
			// Figure out the Go types and tags for the key and value types.
			fieldMapFields[field] = struct {
				Key, Value *descriptor.FieldDescriptorProto
			}{
				Key:   d.Field[0],
				Value: d.Field[1],
			}

			valType := g.GoType(d, fieldMapFields[field].Value)

			// Message and enum types are the only two possibly foreign types used in maps,
			// so record their use.
			switch fieldMapFields[field].Value.GetType() {
			case descriptor.FieldDescriptorProto_TYPE_MESSAGE:
				g.RecordTypeUse(fieldMapFields[field].Value.GetTypeName())
			case descriptor.FieldDescriptorProto_TYPE_ENUM:
				g.RecordTypeUse(fieldMapFields[field].Value.GetTypeName())
				fallthrough
			default:
				valType = strings.TrimPrefix(valType, "*")
			}

			fieldMapTypes[field] = struct {
				Key, Value string
			}{
				// We don't use stars, except for message-typed values.
				// They are not permitted as map keys.
				Key:   strings.TrimPrefix(g.GoType(d, fieldMapFields[field].Key), "*"),
				Value: valType,
			}

			argType := fmt.Sprintf("map[%s]%s", fieldMapTypes[field].Key, fieldMapTypes[field].Value)
			fieldTypes[field] = argType
		}

		// Change oneof typenames if they collide with enums= or message types
		if field.OneofIndex != nil {
			tname := messageType + "_" + fieldNames[field]
			// It is possible for this to collide with a message or enum
			// nested in this message. Check for collisions.
			for {
				ok := true
				for _, desc := range message.nested {
					if CamelCaseSlice(desc.TypeName()) == tname {
						ok = false
						break
					}
				}
				for _, enum := range message.enums {
					if CamelCaseSlice(enum.TypeName()) == tname {
						ok = false
						break
					}
				}
				if !ok {
					tname += "_"
					continue
				}
				break
			}

			oneofTypeName[field] = tname
			continue
		}

		g.P(fieldNames[field], " ", fieldTypes[field])
	}

	g.Out()
	g.P("}")
	g.P()

	// Update g.Buffer to list valid oneof types in comment.
	// We do this down here, after we've disambiguated the oneof type names.
	// We go in reverse order of insertion point to avoid invalidating offsets.
	for oi := int32(len(message.OneofDecl)); oi >= 0; oi-- {
		ip := oneofInsertPoints[oi]
		all := g.Buffer.Bytes()
		rem := all[ip:]
		g.Buffer = bytes.NewBuffer(all[:ip:ip]) // set cap so we don't scribble on rem
		for _, field := range message.Field {
			if field.OneofIndex == nil || field.GetOneofIndex() != oi {
				continue
			}
			g.P("//\t*", oneofTypeName[field])
		}
		g.Buffer.Write(rem)
	}

	// Oneof per-field types, discriminants and getters.
	//
	// Generate unexported named types for the discriminant interfaces.
	for oi := range message.OneofDecl {
		g.P("// ", oneofDisc[int32(oi)], " is used to distinguish types assignable to ", oneofFieldName[int32(oi)])
		g.P("type ", oneofDisc[int32(oi)], " interface { ", oneofDisc[int32(oi)], "() }")
	}
	g.P()

	// Generate Oneof field structs
	for i, field := range message.Field {
		if field.OneofIndex == nil {
			continue
		}
		g.P("// ", oneofTypeName[field], " is assignable to ", oneofFieldName[field.GetOneofIndex()])
		g.P("type ", oneofTypeName[field], " struct {")
		g.In()
		g.PrintComments(fmt.Sprintf("%s,%d,%d", message.path, messageFieldPath, i))
		g.P(fieldNames[field], " ", fieldTypes[field])
		g.Out()
		g.P("}")
		g.RecordTypeUse(field.GetTypeName())
	}
	g.P()

	// Ensure all Oneof fields satisfy discriminant interface
	for _, field := range message.Field {
		if field.OneofIndex == nil {
			continue
		}
		g.P("func (*", oneofTypeName[field], ") ", oneofDisc[field.GetOneofIndex()], "() {}")
	}
	g.P()

	// Generate Oneof Getter
	for oi := range message.OneofDecl {
		getter := allocNames("Get" + oneofFieldName[int32(oi)])[0]
		g.generateGetter(getter, oneofFieldName[int32(oi)], messageType, oneofDisc[int32(oi)])
	}

	// Field getters
	for _, field := range message.Field {
		// Generate Getter
		if field.OneofIndex != nil {
			g.P("// ", fieldGetterNames[field], " gets the ", fieldNames[field], " of the ", messageType, ".")
			g.P("func (m *", messageType, ") ", fieldGetterNames[field], "() (x ", fieldTypes[field], ") {")
			g.P("if v, ok := m.Get", oneofFieldName[field.GetOneofIndex()], "().(*", oneofTypeName[field], "); ok {")
			g.In()
			g.P("return v.", fieldNames[field])
			g.Out()
			g.P("}")
			g.P("return x")
			g.Out()
			g.P("}")
			g.P()
		} else {
			g.generateGetter(fieldGetterNames[field], fieldNames[field], messageType, fieldTypes[field])
		}
	}

	// Add MarshalToWriter
	g.P("// MarshalToWriter marshals ", messageType, " to the provided writer.")
	g.P("func (m *" + messageType + ") MarshalToWriter(writer jspb.Writer) {")
	g.In()
	g.P("if m == nil {")
	g.In()
	g.P("return")
	g.Out()
	g.P("}")
	g.P()
	// Write Oneof fields first
	for oi := range message.OneofDecl {
		g.P("switch t := m.", oneofFieldName[int32(oi)], ".(type) {")
		for _, field := range message.Field {
			if field.OneofIndex == nil || field.GetOneofIndex() != int32(oi) {
				continue
			}
			g.P("case *", oneofTypeName[field], ":")
			g.generateFieldWriter(field, fieldNames[field], fieldNumbers[field], "t")
		}
		g.P("}")
		g.P()
	}
	for _, field := range message.Field {
		if field.OneofIndex != nil {
			// Oneofs have already been dealt with
			continue
		}
		if fieldMapFields[field].Key != nil {
			// Special case for maps
			g.P("if len(m.", fieldNames[field], ") > 0 {")
			g.In()
			g.P("for key, value := range m.", fieldNames[field], " {")
			g.In()
			g.P("writer.WriteMessage(", fieldNumbers[field], ", func() {")
			g.In()
			g.P("writer.Write", g.JSPBTypeFunc(fieldMapFields[field].Key), "(1, key)")

			// Because Messages and Enums can be map values we need special handling
			switch fieldMapFields[field].Value.GetType() {
			case descriptor.FieldDescriptorProto_TYPE_MESSAGE:
				g.P("writer.WriteMessage(2, func () {")
				g.In()
				g.P("value.MarshalToWriter(writer)")
				g.Out()
				g.P("})")
			case descriptor.FieldDescriptorProto_TYPE_ENUM:
				g.P("writer.WriteEnum(2, int(value))")
			default:
				g.P("writer.Write", g.JSPBTypeFunc(fieldMapFields[field].Value), "(2, value)")
			}

			g.Out()
			g.P("})")
			g.Out()
			g.P("}")
			g.Out()
			g.P("}")
		} else if isRepeated(field) {
			// Special handling for slices
			switch field.GetType() {
			case descriptor.FieldDescriptorProto_TYPE_MESSAGE:
				g.RecordTypeUse(field.GetTypeName())
				g.P("for _, msg := range m.", fieldNames[field], " {")
				g.In()
				g.P("writer.WriteMessage(", fieldNumbers[field], ", func () {")
				g.In()
				g.P("msg.MarshalToWriter(writer)")
				g.Out()
				g.P("})")
				g.Out()
				g.P("}")
			case descriptor.FieldDescriptorProto_TYPE_ENUM:
				g.RecordTypeUse(field.GetTypeName())
				g.P("if len(m.", fieldNames[field], ") > 0 {")
				g.In()
				g.P("var ints []int")
				g.P("for _, enum := range m.", fieldNames[field], " {")
				g.In()
				g.P("ints = append(ints, int(enum))")
				g.Out()
				g.P("}")
				g.P("writer.WriteEnumSlice(", fieldNumbers[field], ", ints)")
				g.Out()
				g.P("}")
			case descriptor.FieldDescriptorProto_TYPE_STRING,
				descriptor.FieldDescriptorProto_TYPE_BYTES:
				g.P("for _, val := range m.", fieldNames[field], " {")
				g.In()
				g.P("writer.Write", g.JSPBTypeFunc(field), "(", fieldNumbers[field], ", val)")
				g.Out()
				g.P("}")
			default:
				g.P("if len(m.", fieldNames[field], ") > 0 {")
				g.In()
				g.P("writer.Write", g.JSPBTypeFunc(field), "Slice(", fieldNumbers[field], ", m.", fieldNames[field], ")")
				g.Out()
				g.P("}")
			}
		} else {
			g.generateFieldWriter(field, fieldNames[field], fieldNumbers[field], "m")
		}
		g.P()
	}
	g.Out()
	g.P("return")
	g.P("}")
	g.P()

	// Add Marshal
	g.P("// Marshal marshals ", messageType, " to a slice of bytes.")
	g.P("func (m *" + messageType + ") Marshal() []byte {")
	g.In()
	g.P("writer := jspb.NewWriter()")
	g.P("m.MarshalToWriter(writer)")
	g.P("return writer.GetResult()")
	g.Out()
	g.P("}")
	g.P()

	// Add UnmarshalFromReader
	g.P("// UnmarshalFromReader unmarshals a ", messageType, " from the provided reader.")
	g.P("func (m *"+messageType+") UnmarshalFromReader(reader jspb.Reader) *", messageType, " {")
	g.In()
	g.P("for reader.Next() {")
	g.In()
	g.P("if m == nil {")
	g.In()
	g.P("m = &", messageType, "{}")
	g.Out()
	g.P("}")
	g.P()
	g.P("switch reader.GetFieldNumber() {")
	// Fields
	for _, field := range message.Field {
		g.P("case ", fieldNumbers[field], ":")
		g.In()
		if fieldMapFields[field].Key != nil {
			// Special case for maps
			g.P("if m.", fieldNames[field], " == nil {")
			g.In()
			g.P("m.", fieldNames[field], " = ", fieldTypes[field], "{}")
			g.Out()
			g.P("}")
			g.P("reader.ReadMessage(func() {")
			g.In()
			g.P("var key ", fieldMapTypes[field].Key)
			g.P("var value ", fieldMapTypes[field].Value)
			g.P("for reader.Next() {")
			g.In()
			g.P("switch reader.GetFieldNumber() {")
			g.P("case 1:")
			g.In()
			g.P("key = reader.Read", g.JSPBTypeFunc(fieldMapFields[field].Key), "()")
			g.Out()
			g.P("case 2:")
			g.In()

			// Because Messages and Enums can be map values we need special handling
			switch fieldMapFields[field].Value.GetType() {
			case descriptor.FieldDescriptorProto_TYPE_MESSAGE:
				g.P("reader.ReadMessage(func() {")
				g.In()
				// Get underlying type by stripping pointer token
				newTypeName := strings.TrimPrefix(g.GoType(message, fieldMapFields[field].Value), "*")
				g.P("value = new(", newTypeName, ").UnmarshalFromReader(reader)")
				g.Out()
				g.P("})")
			case descriptor.FieldDescriptorProto_TYPE_ENUM:
				g.P("value = ", g.GoType(message, fieldMapFields[field].Value), "(reader.ReadEnum())")
			default:
				g.P("value = reader.Read", g.JSPBTypeFunc(fieldMapFields[field].Value), "()")
			}

			g.Out()
			g.P("}")
			g.P("m.", fieldNames[field], "[key] = value")
			g.Out()
			g.P("}")
			g.Out()
			g.P("})")
		} else if isRepeated(field) {
			// Special handling for slices
			switch field.GetType() {
			case descriptor.FieldDescriptorProto_TYPE_MESSAGE:
				g.RecordTypeUse(field.GetTypeName())
				g.P("reader.ReadMessage(func() {")
				g.In()
				// Get underlying type by stripping slice and pointer tokens
				newTypeName := strings.TrimPrefix(fieldTypes[field], "[]*")
				g.P("m.", fieldNames[field], " = append(m.", fieldNames[field], ", new(", newTypeName, ").UnmarshalFromReader(reader))")
				g.Out()
				g.P("})")
			case descriptor.FieldDescriptorProto_TYPE_ENUM:
				g.RecordTypeUse(field.GetTypeName())
				g.P("values := reader.ReadEnumSlice()")
				g.P("for _, enum := range values {")
				g.In()
				// Get underlying type by stripping slice token
				newTypeName := strings.TrimPrefix(fieldTypes[field], "[]")
				g.P("m.", fieldNames[field], " = append(m.", fieldNames[field], ", ", newTypeName, "(enum))")
				g.Out()
				g.P("}")
			case descriptor.FieldDescriptorProto_TYPE_STRING,
				descriptor.FieldDescriptorProto_TYPE_BYTES:
				g.P("m.", fieldNames[field], " = append(m.", fieldNames[field], ", reader.Read", g.JSPBTypeFunc(field), "())")
			default:
				g.P("m.", fieldNames[field], " = reader.Read", g.JSPBTypeFunc(field), "Slice()")
			}
		} else if field.OneofIndex != nil {
			// Special handling for oneof fields
			switch field.GetType() {
			case descriptor.FieldDescriptorProto_TYPE_MESSAGE:
				g.RecordTypeUse(field.GetTypeName())
				g.P("reader.ReadMessage(func() {")
				g.In()
				g.P("m.", oneofFieldName[field.GetOneofIndex()], " = &", oneofTypeName[field], "{")
				g.In()
				// Get underlying type by stripping pointer token
				newTypeName := strings.TrimPrefix(fieldTypes[field], "*")
				g.P(fieldNames[field], ": new(", newTypeName, ").UnmarshalFromReader(reader),")
				g.Out()
				g.P("}")
				g.Out()
				g.P("})")
			case descriptor.FieldDescriptorProto_TYPE_ENUM:
				g.RecordTypeUse(field.GetTypeName())
				g.P("m.", oneofFieldName[field.GetOneofIndex()], " = &", oneofTypeName[field], "{")
				g.In()
				g.P(fieldNames[field], ": ", fieldTypes[field], "(reader.ReadEnum()),")
				g.Out()
				g.P("}")
			default:
				g.P("m.", oneofFieldName[field.GetOneofIndex()], " = &", oneofTypeName[field], "{")
				g.In()
				g.P(fieldNames[field], ": reader.Read", g.JSPBTypeFunc(field), "(),")
				g.Out()
				g.P("}")
			}
		} else {
			switch field.GetType() {
			case descriptor.FieldDescriptorProto_TYPE_MESSAGE:
				g.RecordTypeUse(field.GetTypeName())
				g.P("reader.ReadMessage(func() {")
				g.In()
				g.P("m.", fieldNames[field], " = m.", fieldNames[field], ".UnmarshalFromReader(reader)")
				g.Out()
				g.P("})")
			case descriptor.FieldDescriptorProto_TYPE_ENUM:
				g.RecordTypeUse(field.GetTypeName())
				g.P("m.", fieldNames[field], " = ", fieldTypes[field], "(reader.ReadEnum())")
			default:
				g.P("m.", fieldNames[field], " = reader.Read", g.JSPBTypeFunc(field), "()")
			}
		}
		g.Out()
	}
	g.P("default:")
	g.In()
	g.P("reader.SkipField()")
	g.Out()
	g.P("}")
	g.Out()
	g.P("}")
	g.P()
	g.P("return m")
	g.Out()
	g.P("}")
	g.P()

	// Add Unmarshal
	g.P("// Unmarshal unmarshals a ", messageType, " from a slice of bytes.")
	g.P("func (m *"+messageType+") Unmarshal(rawBytes []byte) (*", messageType, ", error) {")
	g.In()
	g.P("reader := jspb.NewReader(rawBytes)")
	g.P()
	g.P("m = m.UnmarshalFromReader(reader)")
	g.P()
	g.P("if err := reader.Err(); err != nil {")
	g.In()
	g.P("return nil, err")
	g.Out()
	g.P("}")
	g.P()
	g.P("return m, nil")
	g.Out()
	g.P("}")
	g.P()
}

func (g *Generator) generateGetter(getterName, fieldName, messageName, returnType string) {
	g.P("// ", getterName, " gets the ", fieldName, " of the ", messageName, ".")
	g.P("func (m *", messageName, ") ", getterName, "() (x ", returnType, ") {")
	g.In()
	g.P("if m == nil {")
	g.In()
	g.P("return x")
	g.Out()
	g.P("}")
	g.P("return m." + fieldName)
	g.P("}")
	g.P()
}

func (g *Generator) generateFieldWriter(field *descriptor.FieldDescriptorProto, fieldName, fieldNumbers, messageVariable string) {
	g.In()
	switch field.GetType() {
	case descriptor.FieldDescriptorProto_TYPE_MESSAGE:
		g.RecordTypeUse(field.GetTypeName())
		g.P("if ", messageVariable, ".", fieldName, " != nil {")
		g.In()
		g.P("writer.WriteMessage(", fieldNumbers, ", func () {")
		g.In()
		g.P(messageVariable, ".", fieldName, ".MarshalToWriter(writer)")
		g.Out()
		g.P("})")
		g.Out()
		g.P("}")
	case descriptor.FieldDescriptorProto_TYPE_ENUM:
		g.RecordTypeUse(field.GetTypeName())
		g.P("if int(", messageVariable, ".", fieldName, ") != 0 {")
		g.In()
		g.P("writer.WriteEnum(", fieldNumbers, ", int(", messageVariable, ".", fieldName, "))")
		g.Out()
		g.P("}")
	case descriptor.FieldDescriptorProto_TYPE_BOOL:
		g.P("if ", messageVariable, ".", fieldName, " {")
		g.In()
		g.P("writer.WriteBool(", fieldNumbers, ", ", messageVariable, ".", fieldName, ")")
		g.Out()
		g.P("}")
	case descriptor.FieldDescriptorProto_TYPE_STRING,
		descriptor.FieldDescriptorProto_TYPE_BYTES:
		g.P("if len(", messageVariable, ".", fieldName, ") > 0 {")
		g.In()
		g.P("writer.Write", g.JSPBTypeFunc(field), "(", fieldNumbers, ", ", messageVariable, ".", fieldName, ")")
		g.Out()
		g.P("}")
	default:
		g.P("if ", messageVariable, ".", fieldName, " != 0 {")
		g.In()
		g.P("writer.Write", g.JSPBTypeFunc(field), "(", fieldNumbers, ", ", messageVariable, ".", fieldName, ")")
		g.Out()
		g.P("}")
	}
	g.Out()
}

func (g *Generator) getMapDescriptor(field *descriptor.FieldDescriptorProto) *Descriptor {
	if field.GetType() == descriptor.FieldDescriptorProto_TYPE_MESSAGE {
		desc := g.ObjectNamed(field.GetTypeName())
		if d, ok := desc.(*Descriptor); ok && d.GetOptions().GetMapEntry() {
			return d
		}
	}

	return nil
}

func (g *Generator) generateInitFunction() {
	if len(g.init) == 0 {
		return
	}
	g.P("func init() {")
	g.In()
	for _, l := range g.init {
		g.P(l)
	}
	g.Out()
	g.P("}")
	g.init = nil
}

// And now lots of helper functions.

// Is c an ASCII lower-case letter?
func isASCIILower(c byte) bool {
	return 'a' <= c && c <= 'z'
}

// Is c an ASCII digit?
func isASCIIDigit(c byte) bool {
	return '0' <= c && c <= '9'
}

// CamelCase returns the CamelCased name.
// If there is an interior underscore followed by a lower case letter,
// drop the underscore and convert the letter to upper case.
// There is a remote possibility of this rewrite causing a name collision,
// but it's so remote we're prepared to pretend it's nonexistent - since the
// C++ generator lowercases names, it's extremely unlikely to have two fields
// with different capitalizations.
// In short, _my_field_name_2 becomes XMyFieldName_2.
func CamelCase(s string) string {
	if s == "" {
		return ""
	}
	t := make([]byte, 0, 32)
	i := 0
	if s[0] == '_' {
		// Need a capital letter; drop the '_'.
		t = append(t, 'X')
		i++
	}
	// Invariant: if the next letter is lower case, it must be converted
	// to upper case.
	// That is, we process a word at a time, where words are marked by _ or
	// upper case letter. Digits are treated as words.
	for ; i < len(s); i++ {
		c := s[i]
		if c == '_' && i+1 < len(s) && isASCIILower(s[i+1]) {
			continue // Skip the underscore in s.
		}
		if isASCIIDigit(c) {
			t = append(t, c)
			continue
		}
		// Assume we have a letter now - if not, it's a bogus identifier.
		// The next word is a sequence of characters that must start upper case.
		if isASCIILower(c) {
			c ^= ' ' // Make it a capital letter.
		}
		t = append(t, c) // Guaranteed not lower case.
		// Accept lower case sequence that follows.
		for i+1 < len(s) && isASCIILower(s[i+1]) {
			i++
			t = append(t, s[i])
		}
	}
	return string(t)
}

// CamelCaseSlice is like CamelCase, but the argument is a slice of strings to
// be joined with "_".
func CamelCaseSlice(elem []string) string { return CamelCase(strings.Join(elem, "_")) }

// dottedSlice turns a sliced name into a dotted name.
func dottedSlice(elem []string) string { return strings.Join(elem, ".") }

// Is this field repeated?
func isRepeated(field *descriptor.FieldDescriptorProto) bool {
	return field.Label != nil && field.GetLabel() == descriptor.FieldDescriptorProto_LABEL_REPEATED
}

// Is this field a scalar numeric type?
func isScalar(field *descriptor.FieldDescriptorProto) bool {
	if field.Type == nil {
		return false
	}
	switch field.GetType() {
	case descriptor.FieldDescriptorProto_TYPE_DOUBLE,
		descriptor.FieldDescriptorProto_TYPE_FLOAT,
		descriptor.FieldDescriptorProto_TYPE_INT64,
		descriptor.FieldDescriptorProto_TYPE_UINT64,
		descriptor.FieldDescriptorProto_TYPE_INT32,
		descriptor.FieldDescriptorProto_TYPE_FIXED64,
		descriptor.FieldDescriptorProto_TYPE_FIXED32,
		descriptor.FieldDescriptorProto_TYPE_BOOL,
		descriptor.FieldDescriptorProto_TYPE_UINT32,
		descriptor.FieldDescriptorProto_TYPE_ENUM,
		descriptor.FieldDescriptorProto_TYPE_SFIXED32,
		descriptor.FieldDescriptorProto_TYPE_SFIXED64,
		descriptor.FieldDescriptorProto_TYPE_SINT32,
		descriptor.FieldDescriptorProto_TYPE_SINT64:
		return true
	default:
		return false
	}
}

// badToUnderscore is the mapping function used to generate Go names from package names,
// which can be dotted in the input .proto file.  It replaces non-identifier characters such as
// dot or dash with underscore.
func badToUnderscore(r rune) rune {
	if unicode.IsLetter(r) || unicode.IsDigit(r) || r == '_' {
		return r
	}
	return '_'
}

// baseName returns the last path element of the name, with the last dotted suffix removed.
func baseName(name string) string {
	// First, find the last element
	if i := strings.LastIndex(name, "/"); i >= 0 {
		name = name[i+1:]
	}
	// Now drop the suffix
	if i := strings.LastIndex(name, "."); i >= 0 {
		name = name[0:i]
	}
	return name
}

// The SourceCodeInfo message describes the location of elements of a parsed
// .proto file by way of a "path", which is a sequence of integers that
// describe the route from a FileDescriptorProto to the relevant submessage.
// The path alternates between a field number of a repeated field, and an index
// into that repeated field. The constants below define the field numbers that
// are used.
//
// See descriptor.proto for more information about this.
const (
	// tag numbers in FileDescriptorProto
	packagePath = 2 // package
	messagePath = 4 // message_type
	enumPath    = 5 // enum_type
	// tag numbers in DescriptorProto
	messageFieldPath   = 2 // field
	messageMessagePath = 3 // nested_type
	messageEnumPath    = 4 // enum_type
	messageOneofPath   = 8 // oneof_decl
	// tag numbers in EnumDescriptorProto
	enumValuePath = 2 // value
)


text:
<?php

namespace PHPExiftool\Driver\Tag\Sony;

use JMS\Serializer\Annotation\ExclusionPolicy;
use PHPExiftool\Driver\AbstractTag;

/**
 * @ExclusionPolicy("all")
 */
class DistortionCorrection extends AbstractTag
{

    protected $Id = 'mixed';

    protected $Name = 'DistortionCorrection';

    protected $FullName = 'mixed';

    protected $GroupName = 'Sony';

    protected $g0 = 'MakerNotes';

    protected $g1 = 'Sony';

    protected $g2 = 'Image';

    protected $Type = 'int8u';

    protected $Writable = true;

    protected $Description = 'Distortion Correction';

    protected $flag_Permanent = true;

    protected $Values = array(
        0 => array(
            'Id' => 0,
            'Label' => 'None',
        ),
        1 => array(
            'Id' => 1,
            'Label' => 'Applied',
        ),
    );

}


text:
**ACT.SpecialSpellTimer**
=====================
[![Downloads](https://img.shields.io/github/downloads/anoyetta/ACT.SpecialSpellTimer/total.svg)](https://github.com/anoyetta/ACT.SpecialSpellTimer/releases)

# 移行しました
ACT.SpecialSpellTimer, ACT.TTSYukkuri, ACT.UltraScouter は配布を統合し下記のプロジェクトに移行しました。
**ACT.Hojoring**
**https://github.com/anoyetta/ACT.Hojoring**
こちらから最新版を取得してください。


text:
#include <grpc/support/port_platform.h>

#include "src/core/ext/xds/xds_client_stats.h"

#include <string.h>

#include <grpc/support/atm.h>
#include <grpc/support/string_util.h>

#include "src/core/ext/xds/xds_client.h"

namespace grpc_core {

namespace {

uint64_t GetAndResetCounter(std::atomic<uint64_t>* from) {
  return from->exchange(0, std::memory_order_relaxed);
}

}  // namespace

//
// XdsClusterDropStats
//

XdsClusterDropStats::XdsClusterDropStats(
    RefCountedPtr<XdsClient> xds_client,
    const XdsBootstrap::XdsServer& lrs_server, absl::string_view cluster_name,
    absl::string_view eds_service_name)
    : RefCounted(GRPC_TRACE_FLAG_ENABLED(grpc_xds_client_refcount_trace)
                     ? "XdsClusterDropStats"
                     : nullptr),
      xds_client_(std::move(xds_client)),
      lrs_server_(lrs_server),
      cluster_name_(cluster_name),
      eds_service_name_(eds_service_name) {
  if (GRPC_TRACE_FLAG_ENABLED(grpc_xds_client_trace)) {
    gpr_log(GPR_INFO, "[xds_client %p] created drop stats %p for {%s, %s, %s}",
            xds_client_.get(), this, lrs_server_.server_uri.c_str(),
            std::string(cluster_name_).c_str(),
            std::string(eds_service_name_).c_str());
  }
}

XdsClusterDropStats::~XdsClusterDropStats() {
  if (GRPC_TRACE_FLAG_ENABLED(grpc_xds_client_trace)) {
    gpr_log(GPR_INFO,
            "[xds_client %p] destroying drop stats %p for {%s, %s, %s}",
            xds_client_.get(), this, lrs_server_.server_uri.c_str(),
            std::string(cluster_name_).c_str(),
            std::string(eds_service_name_).c_str());
  }
  xds_client_->RemoveClusterDropStats(lrs_server_, cluster_name_,
                                      eds_service_name_, this);
  xds_client_.reset(DEBUG_LOCATION, "DropStats");
}

XdsClusterDropStats::Snapshot XdsClusterDropStats::GetSnapshotAndReset() {
  Snapshot snapshot;
  snapshot.uncategorized_drops = GetAndResetCounter(&uncategorized_drops_);
  MutexLock lock(&mu_);
  snapshot.categorized_drops = std::move(categorized_drops_);
  return snapshot;
}

void XdsClusterDropStats::AddUncategorizedDrops() {
  uncategorized_drops_.fetch_add(1);
}

void XdsClusterDropStats::AddCallDropped(const std::string& category) {
  MutexLock lock(&mu_);
  ++categorized_drops_[category];
}

//
// XdsClusterLocalityStats
//

XdsClusterLocalityStats::XdsClusterLocalityStats(
    RefCountedPtr<XdsClient> xds_client,
    const XdsBootstrap::XdsServer& lrs_server, absl::string_view cluster_name,
    absl::string_view eds_service_name, RefCountedPtr<XdsLocalityName> name)
    : RefCounted(GRPC_TRACE_FLAG_ENABLED(grpc_xds_client_refcount_trace)
                     ? "XdsClusterLocalityStats"
                     : nullptr),
      xds_client_(std::move(xds_client)),
      lrs_server_(lrs_server),
      cluster_name_(cluster_name),
      eds_service_name_(eds_service_name),
      name_(std::move(name)) {
  if (GRPC_TRACE_FLAG_ENABLED(grpc_xds_client_trace)) {
    gpr_log(GPR_INFO,
            "[xds_client %p] created locality stats %p for {%s, %s, %s, %s}",
            xds_client_.get(), this, lrs_server_.server_uri.c_str(),
            std::string(cluster_name_).c_str(),
            std::string(eds_service_name_).c_str(),
            name_->AsHumanReadableString().c_str());
  }
}

XdsClusterLocalityStats::~XdsClusterLocalityStats() {
  if (GRPC_TRACE_FLAG_ENABLED(grpc_xds_client_trace)) {
    gpr_log(GPR_INFO,
            "[xds_client %p] destroying locality stats %p for {%s, %s, %s, %s}",
            xds_client_.get(), this, lrs_server_.server_uri.c_str(),
            std::string(cluster_name_).c_str(),
            std::string(eds_service_name_).c_str(),
            name_->AsHumanReadableString().c_str());
  }
  xds_client_->RemoveClusterLocalityStats(lrs_server_, cluster_name_,
                                          eds_service_name_, name_, this);
  xds_client_.reset(DEBUG_LOCATION, "LocalityStats");
}

XdsClusterLocalityStats::Snapshot
XdsClusterLocalityStats::GetSnapshotAndReset() {
  Snapshot snapshot = {
      GetAndResetCounter(&total_successful_requests_),
      // Don't reset total_requests_in_progress because it's
      // not related to a single reporting interval.
      total_requests_in_progress_.load(std::memory_order_relaxed),
      GetAndResetCounter(&total_error_requests_),
      GetAndResetCounter(&total_issued_requests_),
      {}};
  MutexLock lock(&backend_metrics_mu_);
  snapshot.backend_metrics = std::move(backend_metrics_);
  return snapshot;
}

void XdsClusterLocalityStats::AddCallStarted() {
  total_issued_requests_.fetch_add(1, std::memory_order_relaxed);
  total_requests_in_progress_.fetch_add(1, std::memory_order_relaxed);
}

void XdsClusterLocalityStats::AddCallFinished(bool fail) {
  std::atomic<uint64_t>& to_increment =
      fail ? total_error_requests_ : total_successful_requests_;
  to_increment.fetch_add(1, std::memory_order_relaxed);
  total_requests_in_progress_.fetch_add(-1, std::memory_order_acq_rel);
}

}  // namespace grpc_core


text:
import random
import numpy as np
import marshal

def generate_room(dim=(13, 13), p_change_directions=0.35, num_steps=25, num_boxes=3, tries=4, second_player=False):
    """
    Generates a Sokoban room, represented by an integer matrix. The elements are encoded as follows:
    wall = 0
    empty space = 1
    box target = 2
    box not on target = 3
    box on target = 4
    player = 5

    :param dim:
    :param p_change_directions:
    :param num_steps:
    :return: Numpy 2d Array
    """
    room_state = np.zeros(shape=dim)
    room_structure = np.zeros(shape=dim)

    # Some times rooms with a score == 0 are the only possibility.
    # In these case, we try another model.
    for t in range(tries):
        room = room_topology_generation(dim, p_change_directions, num_steps)
        room = place_boxes_and_player(room, num_boxes=num_boxes, second_player=second_player)

        # Room fixed represents all not movable parts of the room
        room_structure = np.copy(room)
        room_structure[room_structure == 5] = 1

        # Room structure represents the current state of the room including movable parts
        room_state = room.copy()
        room_state[room_state == 2] = 4

        room_state, score, box_mapping = reverse_playing(room_state, room_structure)
        room_state[room_state == 3] = 4

        if score > 0:
            break

    if score == 0:
        raise RuntimeWarning('Generated Model with score == 0')

    return room_structure, room_state, box_mapping

def room_topology_generation(dim=(10, 10), p_change_directions=0.35, num_steps=15):
    """
    Generate a room topology, which consits of empty floors and walls.

    :param dim:
    :param p_change_directions:
    :param num_steps:
    :return:
    """
    dim_x, dim_y = dim

    # The ones in the mask represent all fields which will be set to floors
    # during the random walk. The centered one will be placed over the current
    # position of the walk.
    masks = [
        [
            [0, 0, 0],
            [1, 1, 1],
            [0, 0, 0]
        ],
        [
            [0, 1, 0],
            [0, 1, 0],
            [0, 1, 0]
        ],
        [
            [0, 0, 0],
            [1, 1, 0],
            [0, 1, 0]
        ],
        [
            [0, 0, 0],
            [1, 1, 0],
            [1, 1, 0]
        ],
        [
            [0, 0, 0],
            [0, 1, 1],
            [0, 1, 0]
        ]
    ]

    # Possible directions during the walk
    directions = [(1, 0), (0, 1), (-1, 0), (0, -1)]
    direction = random.sample(directions, 1)[0]

    # Starting position of random walk
    position = np.array([
        random.randint(1, dim_x - 1),
        random.randint(1, dim_y - 1)]
    )

    level = np.zeros(dim, dtype=int)

    for s in range(num_steps):

        # Change direction randomly
        if random.random() < p_change_directions:
            direction = random.sample(directions, 1)[0]

        # Update position
        position = position + direction
        position[0] = max(min(position[0], dim_x - 2), 1)
        position[1] = max(min(position[1], dim_y - 2), 1)

        # Apply mask
        mask = random.sample(masks, 1)[0]
        mask_start = position - 1
        level[mask_start[0]:mask_start[0] + 3, mask_start[1]:mask_start[1] + 3] += mask

    level[level > 0] = 1
    level[:, [0, dim_y - 1]] = 0
    level[[0, dim_x - 1], :] = 0

    return level

def place_boxes_and_player(room, num_boxes, second_player):
    """
    Places the player and the boxes into the floors in a room.

    :param room:
    :param num_boxes:
    :return:
    """
    # Get all available positions
    possible_positions = np.where(room == 1)
    num_possible_positions = possible_positions[0].shape[0]
    num_players = 2 if second_player else 1

    if num_possible_positions <= num_boxes + num_players:
        raise RuntimeError('Not enough free spots (#{}) to place {} player and {} boxes.'.format(
            num_possible_positions,
            num_players,
            num_boxes)
        )

    # Place player(s)
    ind = np.random.randint(num_possible_positions)
    player_position = possible_positions[0][ind], possible_positions[1][ind]
    room[player_position] = 5

    if second_player:
        ind = np.random.randint(num_possible_positions)
        player_position = possible_positions[0][ind], possible_positions[1][ind]
        room[player_position] = 5

    # Place boxes
    for n in range(num_boxes):
        possible_positions = np.where(room == 1)
        num_possible_positions = possible_positions[0].shape[0]

        ind = np.random.randint(num_possible_positions)
        box_position = possible_positions[0][ind], possible_positions[1][ind]
        room[box_position] = 2

    return room

# Global variables used for reverse playing.
explored_states = set()
num_boxes = 0
best_room_score = -1
best_room = None
best_box_mapping = None

def reverse_playing(room_state, room_structure, search_depth=100):
    """
    This function plays Sokoban reverse in a way, such that the player can
    move and pull boxes.
    It ensures a solvable level with all boxes not being placed on a box target.
    :param room_state:
    :param room_structure:
    :param search_depth:
    :return: 2d array
    """
    global explored_states, num_boxes, best_room_score, best_room, best_box_mapping

    # Box_Mapping is used to calculate the box displacement for every box
    box_mapping = {}
    box_locations = np.where(room_structure == 2)
    num_boxes = len(box_locations[0])
    for l in range(num_boxes):
        box = (box_locations[0][l], box_locations[1][l])
        box_mapping[box] = box

    # explored_states globally stores the best room state and score found during search
    explored_states = set()
    best_room_score = -1
    best_box_mapping = box_mapping
    depth_first_search(room_state, room_structure, box_mapping, box_swaps=0, last_pull=(-1, -1), ttl=300)

    return best_room, best_room_score, best_box_mapping

def depth_first_search(room_state, room_structure, box_mapping, box_swaps=0, last_pull=(-1, -1), ttl=300):
    """
    Searches through all possible states of the room.
    This is a recursive function, which stops if the tll is reduced to 0 or
    over 1.000.000 states have been explored.
    :param room_state:
    :param room_structure:
    :param box_mapping:
    :param box_swaps:
    :param last_pull:
    :param ttl:
    :return:
    """
    global explored_states, num_boxes, best_room_score, best_room, best_box_mapping

    ttl -= 1
    if ttl <= 0 or len(explored_states) >= 300000:
        return

    state_tohash = marshal.dumps(room_state)

    # Only search this state, if it not yet has been explored
    if not (state_tohash in explored_states):

        # Add current state and its score to explored states
        room_score = box_swaps * box_displacement_score(box_mapping)
        if np.where(room_state == 2)[0].shape[0] != num_boxes:
            room_score = 0

        if room_score > best_room_score:
            best_room = room_state
            best_room_score = room_score
            best_box_mapping = box_mapping

        explored_states.add(state_tohash)

        for action in ACTION_LOOKUP.keys():
            # The state and box mapping  need to be copied to ensure
            # every action start from a similar state.
            room_state_next = room_state.copy()
            box_mapping_next = box_mapping.copy()

            room_state_next, box_mapping_next, last_pull_next = \
                reverse_move(room_state_next, room_structure, box_mapping_next, last_pull, action)

            box_swaps_next = box_swaps
            if last_pull_next != last_pull:
                box_swaps_next += 1

            depth_first_search(room_state_next, room_structure,
                               box_mapping_next, box_swaps_next,
                               last_pull, ttl)

def reverse_move(room_state, room_structure, box_mapping, last_pull, action):
    """
    Perform reverse action. Where all actions in the range [0, 3] correspond to
    push actions and the ones greater 3 are simmple move actions.
    :param room_state:
    :param room_structure:
    :param box_mapping:
    :param last_pull:
    :param action:
    :return:
    """
    player_position = np.where(room_state == 5)
    player_position = np.array([player_position[0][0], player_position[1][0]])

    change = CHANGE_COORDINATES[action % 4]
    next_position = player_position + change

    # Check if next position is an empty floor or an empty box target
    if room_state[next_position[0], next_position[1]] in [1, 2]:

        # Move player, independent of pull or move action.
        room_state[player_position[0], player_position[1]] = room_structure[player_position[0], player_position[1]]
        room_state[next_position[0], next_position[1]] = 5

        # In addition try to pull a box if the action is a pull action
        if action < 4:
            possible_box_location = change[0] * -1, change[1] * -1
            possible_box_location += player_position

            if room_state[possible_box_location[0], possible_box_location[1]] in [3, 4]:
                # Perform pull of the adjacent box
                room_state[player_position[0], player_position[1]] = 3
                room_state[possible_box_location[0], possible_box_location[1]] = room_structure[
                    possible_box_location[0], possible_box_location[1]]

                # Update the box mapping
                for k in box_mapping.keys():
                    if box_mapping[k] == (possible_box_location[0], possible_box_location[1]):
                        box_mapping[k] = (player_position[0], player_position[1])
                        last_pull = k

    return room_state, box_mapping, last_pull

def box_displacement_score(box_mapping):
    """
    Calculates the sum of all Manhattan distances, between the boxes
    and their origin box targets.
    :param box_mapping:
    :return:
    """
    score = 0

    for box_target in box_mapping.keys():
        box_location = np.array(box_mapping[box_target])
        box_target = np.array(box_target)
        dist = np.sum(np.abs(box_location - box_target))
        score += dist

    return score

TYPE_LOOKUP = {
    0: 'wall',
    1: 'empty space',
    2: 'box target',
    3: 'box on target',
    4: 'box not on target',
    5: 'player'
}

ACTION_LOOKUP = {
    0: 'push up',
    1: 'push down',
    2: 'push left',
    3: 'push right',
    4: 'move up',
    5: 'move down',
    6: 'move left',
    7: 'move right',
}

# Moves are mapped to coordinate changes as follows
# 0: Move up
# 1: Move down
# 2: Move left
# 3: Move right
CHANGE_COORDINATES = {
    0: (-1, 0),
    1: (1, 0),
    2: (0, -1),
    3: (0, 1)
}