<commit_before>package pitch

import (
	"fmt"
	"github.com/brettbuddin/mt/pkg/interval"
	mt_math "github.com/brettbuddin/mt/pkg/math"
	"math"
)

const (
	concertFrequency = 440.0
	Semitone         = 1
	Tone             = 2
	Ditone           = 3
	Tritone          = 6

	DoubleFlat  = -2
	Flat        = -1
	Natural     = 0
	Sharp       = 1
	DoubleSharp = 2
)

const (
	C int = iota + 1
	D
	E
	F
	G
	A
	B
)

var (
	MiddleOctave        = 4
	UseFancyAccidentals = false

	FlatNames  = NameStrategyFunc(func(i int) int { return namesForFlats[int(mt_math.Mod(float64(i), 12))] })
	SharpNames = NameStrategyFunc(func(i int) int { return namesForSharps[int(mt_math.Mod(float64(i), 12))] })

	accidentalNames      = [5]string{"bb", "b", "", "#", "x"}
	fancyAccidentalNames = [5]string{"♭♭", "♭", "", "♯", "𝄪"}
	pitchNames           = [7]string{"C", "D", "E", "F", "G", "A", "B"}
	namesForFlats        = [12]int{0, 1, 1, 2, 2, 3, 4, 4, 5, 5, 6, 6}
	namesForSharps       = [12]int{0, 0, 1, 1, 2, 3, 3, 4, 4, 5, 5, 6}
	semitone             = math.Pow(2, 1.0/12.0)
	middleA              = NewAbsolute(A, MiddleOctave, Natural)
)

type NameStrategy interface {
	GetMappedIndex(int) int
}

type NameStrategyFunc func(int) int

func (f NameStrategyFunc) GetMappedIndex(i int) int {
	return f(i)
}

func New(diatonic, octaves, accidental int) Pitch {
	return Pitch{interval.New(diatonic, MiddleOctave+octaves, accidental)}
}

func NewAbsolute(diatonic, octaves, accidental int) Pitch {
	return Pitch{interval.New(diatonic, octaves, accidental)}
}

type Pitch struct {
	interval.Interval
}

func (p Pitch) Name(s NameStrategy) string {
	semitones := int(mt_math.Mod(float64(p.Semitones()), 12.0))
	nameIndex := s.GetMappedIndex(semitones)
	delta := semitones - interval.DiatonicToChromatic(nameIndex)

	if delta == 0 {
		return fmt.Sprintf("%s%d", pitchNames[nameIndex], p.Octaves())
	}
	return fmt.Sprintf("%s%s%d", pitchNames[nameIndex], accidentalName(delta+2), p.Octaves())
}

func (p Pitch) AddInterval(i interval.Interval) Pitch {
	return Pitch{p.Interval.AddInterval(i)}
}

func (p Pitch) Freq() float64 {
	return concertFrequency * math.Pow(semitone, float64(p.Semitones()-middleA.Semitones()))
}

func (p Pitch) MIDI() int {
	return p.Semitones() + 12
}

func accidentalName(i int) string {
	if UseFancyAccidentals {
		return fancyAccidentalNames[int(mt_math.Mod(float64(i), float64(len(accidentalNames))))]
	}
	return accidentalNames[int(mt_math.Mod(float64(i), float64(len(accidentalNames))))]
}
<commit_msg>These aren't necessary in this package.<commit_after>package pitch

import (
	"fmt"
	"github.com/brettbuddin/mt/pkg/interval"
	mt_math "github.com/brettbuddin/mt/pkg/math"
	"math"
)

const (
	concertFrequency = 440.0

	DoubleFlat  = -2
	Flat        = -1
	Natural     = 0
	Sharp       = 1
	DoubleSharp = 2
)

const (
	C int = iota + 1
	D
	E
	F
	G
	A
	B
)

var (
	MiddleOctave        = 4
	UseFancyAccidentals = false

	FlatNames  = NameStrategyFunc(func(i int) int { return namesForFlats[int(mt_math.Mod(float64(i), 12))] })
	SharpNames = NameStrategyFunc(func(i int) int { return namesForSharps[int(mt_math.Mod(float64(i), 12))] })

	accidentalNames      = [5]string{"bb", "b", "", "#", "x"}
	fancyAccidentalNames = [5]string{"♭♭", "♭", "", "♯", "𝄪"}
	pitchNames           = [7]string{"C", "D", "E", "F", "G", "A", "B"}
	namesForFlats        = [12]int{0, 1, 1, 2, 2, 3, 4, 4, 5, 5, 6, 6}
	namesForSharps       = [12]int{0, 0, 1, 1, 2, 3, 3, 4, 4, 5, 5, 6}
	semitone             = math.Pow(2, 1.0/12.0)
	middleA              = NewAbsolute(A, MiddleOctave, Natural)
)

type NameStrategy interface {
	GetMappedIndex(int) int
}

type NameStrategyFunc func(int) int

func (f NameStrategyFunc) GetMappedIndex(i int) int {
	return f(i)
}

func New(diatonic, octaves, accidental int) Pitch {
	return Pitch{interval.New(diatonic, MiddleOctave+octaves, accidental)}
}

func NewAbsolute(diatonic, octaves, accidental int) Pitch {
	return Pitch{interval.New(diatonic, octaves, accidental)}
}

type Pitch struct {
	interval.Interval
}

func (p Pitch) Name(s NameStrategy) string {
	semitones := int(mt_math.Mod(float64(p.Semitones()), 12.0))
	nameIndex := s.GetMappedIndex(semitones)
	delta := semitones - interval.DiatonicToChromatic(nameIndex)

	if delta == 0 {
		return fmt.Sprintf("%s%d", pitchNames[nameIndex], p.Octaves())
	}
	return fmt.Sprintf("%s%s%d", pitchNames[nameIndex], accidentalName(delta+2), p.Octaves())
}

func (p Pitch) AddInterval(i interval.Interval) Pitch {
	return Pitch{p.Interval.AddInterval(i)}
}

func (p Pitch) Freq() float64 {
	return concertFrequency * math.Pow(semitone, float64(p.Semitones()-middleA.Semitones()))
}

func (p Pitch) MIDI() int {
	return p.Semitones() + 12
}

func accidentalName(i int) string {
	if UseFancyAccidentals {
		return fancyAccidentalNames[int(mt_math.Mod(float64(i), float64(len(accidentalNames))))]
	}
	return accidentalNames[int(mt_math.Mod(float64(i), float64(len(accidentalNames))))]
}
<|endoftext|>


<commit_before>/*
Copyright 2017 The OpenEBS Authors

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

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

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

package task

import (
	"fmt"
	"strings"

	"github.com/golang/glog"
	"github.com/openebs/maya/pkg/apis/openebs.io/v1alpha1"
	"github.com/openebs/maya/pkg/template"
	"github.com/openebs/maya/pkg/util"
)

// redactJsonResult will update the provided map by removing the original json
// result doc i.e. bytes and replace it with "--redacted--"
//
// NOTE:
//  This should be done once the task group runner has finished executing all
// its tasks or when executing a task met an error & is now exiting by logging
// the error.
func redactJsonResult(templateValues map[string]interface{}) {
	templateValues[string(v1alpha1.CurrentJsonResultTLP)] = "--redacted--"
}

// PostTaskRunFn is a closure definition that provides option
// to act on an individual task's result
type PostTaskRunFn func(taskResult map[string]interface{})

// TaskGroupRunner helps in running a set of Tasks in sequence
type TaskGroupRunner struct {
	// allTaskIDs will hold the identity of the run tasks managed by this
	// group runner
	allTaskIDs []string
	// allTasks is an array of run tasks
	allTasks []*v1alpha1.RunTask
	// outputTask holds the specs to return this group runner's
	// output in the format (i.e. specs) defined in this output run task
	outputTask *v1alpha1.RunTask
	// rollbacks is an array of task executor that need to be run in
	// sequence in the event of any error
	rollbacks []*taskExecutor
}

func NewTaskGroupRunner() *TaskGroupRunner {
	return &TaskGroupRunner{}
}

func (m *TaskGroupRunner) AddRunTask(runtask *v1alpha1.RunTask) (err error) {
	if runtask == nil {
		err = fmt.Errorf("nil runtask: failed to add run task")
		return
	}

	if len(runtask.Spec.Meta) == 0 {
		err = fmt.Errorf("failed to add run task: nil meta task specs found: task name '%s'", runtask.Name)
		return
	}

	m.allTasks = append(m.allTasks, runtask)
	return
}

// SetOutputTask sets this runner with a run task that will be used
// to return the output after successful execution of this runner.
//
// NOTE:
//  This output format is specified in the provided run task.
func (m *TaskGroupRunner) SetOutputTask(runtask *v1alpha1.RunTask) (err error) {
	if len(runtask.Spec.Meta) == 0 {
		err = fmt.Errorf("failed to set output task: nil meta task specs found: task name '%s'", runtask.Name)
		return
	}

	if len(runtask.Spec.Task) == 0 {
		err = fmt.Errorf("failed to set output task: nil task specs found: task name '%s'", runtask.Name)
		return
	}

	m.outputTask = runtask
	return
}

// isTaskIDUnique verifies if the tasks present in this group runner
// have unique task ids.
func (m *TaskGroupRunner) isTaskIDUnique(identity string) (unique bool) {
	id := strings.ToLower(identity)

	if util.ContainsString(m.allTaskIDs, id) {
		unique = false
		return
	}

	// else add the identity for future verfications
	m.allTaskIDs = append(m.allTaskIDs, id)
	unique = true
	return
}

// planForRollback plans for rollback in case of future errors while executing
// the tasks. This will add to the list of rollback tasks
//
// NOTE:
//  This is just the planning for rollback & not actual rollback.
// In the events of issues this planning will be useful.
func (m *TaskGroupRunner) planForRollback(te *taskExecutor, objectName string) error {
	// There are cases where multiple objects may be created due to a single
	// RunTask. In such cases, object name will have comma separated list of
	// object names.
	objNames := strings.Split(objectName, ",")

	// plan the rollback for all the objects that got created
	for _, name := range objNames {
		// entire rollback plan is encapsulated in the task itself
		rte, err := te.asRollbackInstance(strings.TrimSpace(name))
		if err != nil {
			return err
		}

		if rte == nil {
			// this task does not need a rollback
			continue
		}

		m.rollbacks = append(m.rollbacks, rte)
	}

	return nil
}

// rollback will rollback the previously run operation(s)
func (m *TaskGroupRunner) rollback() {
	count := len(m.rollbacks)
	if count == 0 {
		glog.Warningf("did not rollback: no rollback run tasks were found")
		return
	}

	// execute the rollback tasks in **reverse order**
	for i := count - 1; i >= 0; i-- {
		err := m.rollbacks[i].ExecuteIt()
		if err != nil {
			// warn this rollback error & continue with the next rollbacks
			glog.Warningf("failed to rollback run task: '%s': error '%s'", m.rollbacks[i], err.Error())
		}
	}
}

// runATask will run a task based on the task specs & template values
func (m *TaskGroupRunner) runATask(runtask *v1alpha1.RunTask, values map[string]interface{}) (err error) {
	te, err := newTaskExecutor(runtask, values)
	if err != nil {
		// log with verbose details
		glog.Errorf("failed to initialize runtask executor: name '%s': meta yaml '%s': template values in yaml '%s': template values '%+v'", runtask.Name, runtask.Spec.Meta, template.ToYaml(values), values)
		return
	}

	// check if the task ID is unique in this group
	if !m.isTaskIDUnique(te.getTaskIdentity()) {
		return fmt.Errorf("failed to execute the run task: multiple tasks having same identity is not allowed in a group run: duplicate id '%s'", te.getTaskIdentity())
	}

	errExecute := te.Execute()

	// remove the json doc (i.e. []byte) from template values since it will not
	// be used anymore and if these template values are logged will not clutter
	// the logs
	redactJsonResult(values)

	if errExecute != nil {
		glog.Errorf("failed to execute runtask: name '%s': meta yaml '%s': task yaml '%s': template values in yaml '%s': template values '%+v'", runtask.Name, runtask.Spec.Meta, runtask.Spec.Task, template.ToYaml(values), values)
	}

	// this is planning & not the actual rollback
	errRollback := m.planForRollback(te, util.GetNestedString(values, string(v1alpha1.TaskResultTLP), te.getTaskIdentity(), string(v1alpha1.ObjectNameTRTP)))
	if errRollback != nil {
		glog.Errorf("failed to plan for rollback: '%+v'", errRollback)
	}

	// err will always contain the higher priority error
	// here errExecute > errRollback.
	if errRollback != nil {
		err = errRollback
	}
	if errExecute != nil {
		err = errExecute
	}
	return
}

// runAllTasks will run all tasks in the sequence as defined in the array
func (m *TaskGroupRunner) runAllTasks(values map[string]interface{}) (err error) {
	for _, runtask := range m.allTasks {
		err = m.runATask(runtask, values)
		if err != nil {
			return
		}
	}

	return
}

// runOutput gets the output of this runner once all the tasks were executed
// successfully
func (m *TaskGroupRunner) runOutput(values map[string]interface{}) (output []byte, err error) {
	if len(m.outputTask.Spec.Task) == 0 {
		// nothing needs to be done
		return
	}

	te, err := newTaskExecutor(m.outputTask, values)
	if err != nil {
		return
	}

	output, err = te.Output()
	if err != nil {
		// log with verbose details
		glog.Errorf("failed to execute output task: runtask '%+v': template values in yaml '%s': template values '%+v'", m.outputTask, template.ToYaml(values), values)
	}
	return
}

// Run will run all the defined tasks & will rollback in case of any error
//
// NOTE: values is mutated (i.e. gets modified after each task execution) to
// let the task execution result be made available to the next task before execution
// of this next task
func (m *TaskGroupRunner) Run(values map[string]interface{}) (output []byte, err error) {
	err = m.runAllTasks(values)
	if err != nil {
		glog.Errorf("%+v: failed to execute runtasks", err)
		glog.Warningf("will rollback previously executed runtask(s)")
		m.rollback()
	} else {
		// return this runner's output if there were no errors
		return m.runOutput(values)
	}

	return
}
<commit_msg>Add nil check in cas engine. (#449)<commit_after>/*
Copyright 2017 The OpenEBS Authors

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

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

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

package task

import (
	"fmt"
	"strings"

	"github.com/golang/glog"
	"github.com/openebs/maya/pkg/apis/openebs.io/v1alpha1"
	"github.com/openebs/maya/pkg/template"
	"github.com/openebs/maya/pkg/util"
)

// redactJsonResult will update the provided map by removing the original json
// result doc i.e. bytes and replace it with "--redacted--"
//
// NOTE:
//  This should be done once the task group runner has finished executing all
// its tasks or when executing a task met an error & is now exiting by logging
// the error.
func redactJsonResult(templateValues map[string]interface{}) {
	templateValues[string(v1alpha1.CurrentJsonResultTLP)] = "--redacted--"
}

// PostTaskRunFn is a closure definition that provides option
// to act on an individual task's result
type PostTaskRunFn func(taskResult map[string]interface{})

// TaskGroupRunner helps in running a set of Tasks in sequence
type TaskGroupRunner struct {
	// allTaskIDs will hold the identity of the run tasks managed by this
	// group runner
	allTaskIDs []string
	// allTasks is an array of run tasks
	allTasks []*v1alpha1.RunTask
	// outputTask holds the specs to return this group runner's
	// output in the format (i.e. specs) defined in this output run task
	outputTask *v1alpha1.RunTask
	// rollbacks is an array of task executor that need to be run in
	// sequence in the event of any error
	rollbacks []*taskExecutor
}

func NewTaskGroupRunner() *TaskGroupRunner {
	return &TaskGroupRunner{}
}

func (m *TaskGroupRunner) AddRunTask(runtask *v1alpha1.RunTask) (err error) {
	if runtask == nil {
		err = fmt.Errorf("nil runtask: failed to add run task")
		return
	}

	if len(runtask.Spec.Meta) == 0 {
		err = fmt.Errorf("failed to add run task: nil meta task specs found: task name '%s'", runtask.Name)
		return
	}

	m.allTasks = append(m.allTasks, runtask)
	return
}

// SetOutputTask sets this runner with a run task that will be used
// to return the output after successful execution of this runner.
//
// NOTE:
//  This output format is specified in the provided run task.
func (m *TaskGroupRunner) SetOutputTask(runtask *v1alpha1.RunTask) (err error) {
	if runtask == nil {
		err = fmt.Errorf("failed to set output task: nil run task found")
		return
	}

	if len(runtask.Spec.Meta) == 0 {
		err = fmt.Errorf("failed to set output task: nil meta task specs found: task name '%s'", runtask.Name)
		return
	}

	if len(runtask.Spec.Task) == 0 {
		err = fmt.Errorf("failed to set output task: nil task specs found: task name '%s'", runtask.Name)
		return
	}

	m.outputTask = runtask
	return
}

// isTaskIDUnique verifies if the tasks present in this group runner
// have unique task ids.
func (m *TaskGroupRunner) isTaskIDUnique(identity string) (unique bool) {
	id := strings.ToLower(identity)

	if util.ContainsString(m.allTaskIDs, id) {
		unique = false
		return
	}

	// else add the identity for future verfications
	m.allTaskIDs = append(m.allTaskIDs, id)
	unique = true
	return
}

// planForRollback plans for rollback in case of future errors while executing
// the tasks. This will add to the list of rollback tasks
//
// NOTE:
//  This is just the planning for rollback & not actual rollback.
// In the events of issues this planning will be useful.
func (m *TaskGroupRunner) planForRollback(te *taskExecutor, objectName string) error {
	// There are cases where multiple objects may be created due to a single
	// RunTask. In such cases, object name will have comma separated list of
	// object names.
	objNames := strings.Split(objectName, ",")

	// plan the rollback for all the objects that got created
	for _, name := range objNames {
		// entire rollback plan is encapsulated in the task itself
		rte, err := te.asRollbackInstance(strings.TrimSpace(name))
		if err != nil {
			return err
		}

		if rte == nil {
			// this task does not need a rollback
			continue
		}

		m.rollbacks = append(m.rollbacks, rte)
	}

	return nil
}

// rollback will rollback the previously run operation(s)
func (m *TaskGroupRunner) rollback() {
	count := len(m.rollbacks)
	if count == 0 {
		glog.Warningf("did not rollback: no rollback run tasks were found")
		return
	}

	// execute the rollback tasks in **reverse order**
	for i := count - 1; i >= 0; i-- {
		err := m.rollbacks[i].ExecuteIt()
		if err != nil {
			// warn this rollback error & continue with the next rollbacks
			glog.Warningf("failed to rollback run task: '%s': error '%s'", m.rollbacks[i], err.Error())
		}
	}
}

// runATask will run a task based on the task specs & template values
func (m *TaskGroupRunner) runATask(runtask *v1alpha1.RunTask, values map[string]interface{}) (err error) {
	te, err := newTaskExecutor(runtask, values)
	if err != nil {
		// log with verbose details
		glog.Errorf("failed to initialize runtask executor: name '%s': meta yaml '%s': template values in yaml '%s': template values '%+v'", runtask.Name, runtask.Spec.Meta, template.ToYaml(values), values)
		return
	}

	// check if the task ID is unique in this group
	if !m.isTaskIDUnique(te.getTaskIdentity()) {
		return fmt.Errorf("failed to execute the run task: multiple tasks having same identity is not allowed in a group run: duplicate id '%s'", te.getTaskIdentity())
	}

	errExecute := te.Execute()

	// remove the json doc (i.e. []byte) from template values since it will not
	// be used anymore and if these template values are logged will not clutter
	// the logs
	redactJsonResult(values)

	if errExecute != nil {
		glog.Errorf("failed to execute runtask: name '%s': meta yaml '%s': task yaml '%s': template values in yaml '%s': template values '%+v'", runtask.Name, runtask.Spec.Meta, runtask.Spec.Task, template.ToYaml(values), values)
	}

	// this is planning & not the actual rollback
	errRollback := m.planForRollback(te, util.GetNestedString(values, string(v1alpha1.TaskResultTLP), te.getTaskIdentity(), string(v1alpha1.ObjectNameTRTP)))
	if errRollback != nil {
		glog.Errorf("failed to plan for rollback: '%+v'", errRollback)
	}

	// err will always contain the higher priority error
	// here errExecute > errRollback.
	if errRollback != nil {
		err = errRollback
	}
	if errExecute != nil {
		err = errExecute
	}
	return
}

// runAllTasks will run all tasks in the sequence as defined in the array
func (m *TaskGroupRunner) runAllTasks(values map[string]interface{}) (err error) {
	for _, runtask := range m.allTasks {
		err = m.runATask(runtask, values)
		if err != nil {
			return
		}
	}

	return
}

// runOutput gets the output of this runner once all the tasks were executed
// successfully
func (m *TaskGroupRunner) runOutput(values map[string]interface{}) (output []byte, err error) {

	if m.outputTask == nil || len(m.outputTask.Spec.Task) == 0 {
		// nothing needs to be done
		return
	}

	te, err := newTaskExecutor(m.outputTask, values)
	if err != nil {
		return
	}

	output, err = te.Output()
	if err != nil {
		// log with verbose details
		glog.Errorf("failed to execute output task: runtask '%+v': template values in yaml '%s': template values '%+v'", m.outputTask, template.ToYaml(values), values)
	}
	return
}

// Run will run all the defined tasks & will rollback in case of any error
//
// NOTE: values is mutated (i.e. gets modified after each task execution) to
// let the task execution result be made available to the next task before execution
// of this next task
func (m *TaskGroupRunner) Run(values map[string]interface{}) (output []byte, err error) {
	err = m.runAllTasks(values)
	if err != nil {
		glog.Errorf("%+v: failed to execute runtasks", err)
		glog.Warningf("will rollback previously executed runtask(s)")
		m.rollback()
	} else {
		// return this runner's output if there were no errors
		return m.runOutput(values)
	}

	return
}
<|endoftext|>


<commit_before>package web

import (
	"errors"

	"github.com/graphql-go/graphql"
	"github.com/graphql-go/relay"
	"github.com/wattapp/superchargers/pkg/supercharger"
	"golang.org/x/net/context"
)

var nodeDefinitions *relay.NodeDefinitions

// Each top level type
var locationType *graphql.Object
var emailType *graphql.Object
var phoneType *graphql.Object

// Custom node field types
var enumChargerType = graphql.NewEnum(graphql.EnumConfig{
	Name: "Type",
	Values: graphql.EnumValueConfigMap{
		"SUPERCHARGER": &graphql.EnumValueConfig{
			Value: "SUPERCHARGER",
		},
		"DESTINATION": &graphql.EnumValueConfig{
			Value: "DESTINATION",
		},
	},
})

var typeFields = graphql.FieldConfigArgument{
	"type": &graphql.ArgumentConfig{
		Type: graphql.NewList(enumChargerType),
	},
}
var typeArgs = relay.NewConnectionArgs(typeFields)

func BuildSchema() (graphql.Schema, error) {
	nodeDefinitions = relay.NewNodeDefinitions(relay.NodeDefinitionsConfig{
		IDFetcher: func(id string, info graphql.ResolveInfo, ctx context.Context) (interface{}, error) {
			resolvedID := relay.FromGlobalID(id)

			switch resolvedID.Type {
			case "Location":
				// tripID, _ := strconv.ParseInt(resolvedID.ID, 10, 64)
				// return vehicle.GetTrip(tripID)
				return nil, errors.New("Not implemented")
			default:
				return nil, errors.New("Unknown node type")
			}
		},
		TypeResolve: func(p graphql.ResolveTypeParams) *graphql.Object {
			switch p.Value.(type) {
			default:
				return locationType
			}
		},
	})

	emailType = graphql.NewObject(graphql.ObjectConfig{
		Name: "Email",
		Fields: graphql.Fields{
			"email": &graphql.Field{
				Type: graphql.String,
				Resolve: func(p graphql.ResolveParams) (interface{}, error) {
					e := p.Source.(supercharger.Email)
					return e.Email, nil
				},
			},
			"label": &graphql.Field{
				Type: graphql.String,
				Resolve: func(p graphql.ResolveParams) (interface{}, error) {
					e := p.Source.(supercharger.Email)
					return e.Label, nil
				},
			},
		},
	})

	phoneType = graphql.NewObject(graphql.ObjectConfig{
		Name: "Phone",
		Fields: graphql.Fields{
			"number": &graphql.Field{
				Type: graphql.String,
				Resolve: func(p graphql.ResolveParams) (interface{}, error) {
					e := p.Source.(supercharger.Phone)
					return e.Number, nil
				},
			},
			"label": &graphql.Field{
				Type: graphql.String,
				Resolve: func(p graphql.ResolveParams) (interface{}, error) {
					e := p.Source.(supercharger.Phone)
					return e.Label, nil
				},
			},
		},
	})

	locationType = graphql.NewObject(graphql.ObjectConfig{
		Name:        "Location",
		Description: "A vehicle contains trips and charges",
		Fields: graphql.Fields{
			"id": relay.GlobalIDField("Location", nil),
			"address": &graphql.Field{
				Type: graphql.String,
				Resolve: func(p graphql.ResolveParams) (interface{}, error) {
					v := p.Source.(supercharger.Location)
					return v.Address, nil
				},
			},
			"addressLine1": &graphql.Field{
				Type: graphql.String,
				Resolve: func(p graphql.ResolveParams) (interface{}, error) {
					v := p.Source.(supercharger.Location)
					return v.AddressLine1, nil
				},
			},
			"addressLine2": &graphql.Field{
				Type: graphql.String,
				Resolve: func(p graphql.ResolveParams) (interface{}, error) {
					v := p.Source.(supercharger.Location)
					return v.AddressLine2, nil
				},
			},
			"addressNotes": &graphql.Field{
				Type: graphql.String,
				Resolve: func(p graphql.ResolveParams) (interface{}, error) {
					v := p.Source.(supercharger.Location)
					return v.AddressNotes, nil
				},
			},
			"amentities": &graphql.Field{
				Type: graphql.String,
				Resolve: func(p graphql.ResolveParams) (interface{}, error) {
					v := p.Source.(supercharger.Location)
					return v.Amenities, nil
				},
			},
			"baiduLat": &graphql.Field{
				Type: graphql.Float,
				Resolve: func(p graphql.ResolveParams) (interface{}, error) {
					v := p.Source.(supercharger.Location)
					return v.BaiduLat, nil
				},
			},
			"baiduLng": &graphql.Field{
				Type: graphql.Float,
				Resolve: func(p graphql.ResolveParams) (interface{}, error) {
					v := p.Source.(supercharger.Location)
					return v.BaiduLng, nil
				},
			},
			"chargers": &graphql.Field{
				Type: graphql.String,
				Resolve: func(p graphql.ResolveParams) (interface{}, error) {
					v := p.Source.(supercharger.Location)
					return v.Chargers, nil
				},
			},
			"city": &graphql.Field{
				Type: graphql.String,
				Resolve: func(p graphql.ResolveParams) (interface{}, error) {
					v := p.Source.(supercharger.Location)
					return v.City, nil
				},
			},
			"commonName": &graphql.Field{
				Type: graphql.String,
				Resolve: func(p graphql.ResolveParams) (interface{}, error) {
					v := p.Source.(supercharger.Location)
					return v.CommonName, nil
				},
			},
			"country": &graphql.Field{
				Type: graphql.String,
				Resolve: func(p graphql.ResolveParams) (interface{}, error) {
					v := p.Source.(supercharger.Location)
					return v.Country, nil
				},
			},
			"destinationChargerLogo": &graphql.Field{
				Type: graphql.String,
				Resolve: func(p graphql.ResolveParams) (interface{}, error) {
					v := p.Source.(supercharger.Location)
					return v.DestinationChargerLogo, nil
				},
			},
			"destinationWebsite": &graphql.Field{
				Type: graphql.String,
				Resolve: func(p graphql.ResolveParams) (interface{}, error) {
					v := p.Source.(supercharger.Location)
					return v.DestinationWebsite, nil
				},
			},
			"directionsLink": &graphql.Field{
				Type: graphql.String,
				Resolve: func(p graphql.ResolveParams) (interface{}, error) {
					v := p.Source.(supercharger.Location)
					return v.DirectionsLink, nil
				},
			},
			"emails": &graphql.Field{
				Type: graphql.NewList(emailType),
				Resolve: func(p graphql.ResolveParams) (interface{}, error) {
					v := p.Source.(supercharger.Location)
					return v.Emails, nil
				},
			},
			"geocode": &graphql.Field{
				Type: graphql.String,
				Resolve: func(p graphql.ResolveParams) (interface{}, error) {
					v := p.Source.(supercharger.Location)
					return v.Geocode, nil
				},
			},
			"hours": &graphql.Field{
				Type: graphql.String,
				Resolve: func(p graphql.ResolveParams) (interface{}, error) {
					v := p.Source.(supercharger.Location)
					return v.Hours, nil
				},
			},
			"isGallery": &graphql.Field{
				Type: graphql.Boolean,
				Resolve: func(p graphql.ResolveParams) (interface{}, error) {
					v := p.Source.(supercharger.Location)
					return v.IsGallery, nil
				},
			},
			"kioskPinX": &graphql.Field{
				Type: graphql.Int,
				Resolve: func(p graphql.ResolveParams) (interface{}, error) {
					v := p.Source.(supercharger.Location)
					return v.KioskPinX, nil
				},
			},
			"kioskPinY": &graphql.Field{
				Type: graphql.Int,
				Resolve: func(p graphql.ResolveParams) (interface{}, error) {
					v := p.Source.(supercharger.Location)
					return v.KioskPinY, nil
				},
			},
			"kioskZoomPinX": &graphql.Field{
				Type: graphql.Int,
				Resolve: func(p graphql.ResolveParams) (interface{}, error) {
					v := p.Source.(supercharger.Location)
					return v.KioskZoomPinX, nil
				},
			},
			"kioskZoomPinY": &graphql.Field{
				Type: graphql.Int,
				Resolve: func(p graphql.ResolveParams) (interface{}, error) {
					v := p.Source.(supercharger.Location)
					return v.KioskZoomPinY, nil
				},
			},
			"latitude": &graphql.Field{
				Type: graphql.Float,
				Resolve: func(p graphql.ResolveParams) (interface{}, error) {
					v := p.Source.(supercharger.Location)
					return v.Latitude, nil
				},
			},
			"longitude": &graphql.Field{
				Type: graphql.Float,
				Resolve: func(p graphql.ResolveParams) (interface{}, error) {
					v := p.Source.(supercharger.Location)
					return v.Longitude, nil
				},
			},
			"locationId": &graphql.Field{
				Type: graphql.String,
				Resolve: func(p graphql.ResolveParams) (interface{}, error) {
					v := p.Source.(supercharger.Location)
					return v.LocationID, nil
				},
			},
			"locationType": &graphql.Field{
				Type: graphql.NewList(graphql.String),
				Resolve: func(p graphql.ResolveParams) (interface{}, error) {
					v := p.Source.(supercharger.Location)
					return v.LocationType, nil
				},
			},
			"nid": &graphql.Field{
				Type: graphql.Int,
				Resolve: func(p graphql.ResolveParams) (interface{}, error) {
					v := p.Source.(supercharger.Location)
					return v.Nid, nil
				},
			},
			"openSoon": &graphql.Field{
				Type: graphql.Boolean,
				Resolve: func(p graphql.ResolveParams) (interface{}, error) {
					v := p.Source.(supercharger.Location)
					return v.OpenSoon, nil
				},
			},
			"path": &graphql.Field{
				Type: graphql.String,
				Resolve: func(p graphql.ResolveParams) (interface{}, error) {
					v := p.Source.(supercharger.Location)
					return v.Path, nil
				},
			},
			"postalCode": &graphql.Field{
				Type: graphql.String,
				Resolve: func(p graphql.ResolveParams) (interface{}, error) {
					v := p.Source.(supercharger.Location)
					return v.PostalCode, nil
				},
			},
			"provinceState": &graphql.Field{
				Type: graphql.String,
				Resolve: func(p graphql.ResolveParams) (interface{}, error) {
					v := p.Source.(supercharger.Location)
					return v.ProvinceState, nil
				},
			},
			"region": &graphql.Field{
				Type: graphql.String,
				Resolve: func(p graphql.ResolveParams) (interface{}, error) {
					v := p.Source.(supercharger.Location)
					return v.Region, nil
				},
			},
			"salesPhone": &graphql.Field{
				Type: graphql.NewList(phoneType),
				Resolve: func(p graphql.ResolveParams) (interface{}, error) {
					v := p.Source.(supercharger.Location)
					return v.SalesPhone, nil
				},
			},
			"salesRepresentative": &graphql.Field{
				Type: graphql.String,
				Resolve: func(p graphql.ResolveParams) (interface{}, error) {
					v := p.Source.(supercharger.Location)
					return v.SalesRepresentative, nil
				},
			},
			"subRegion": &graphql.Field{
				Type: graphql.String,
				Resolve: func(p graphql.ResolveParams) (interface{}, error) {
					v := p.Source.(supercharger.Location)
					return v.SubRegion, nil
				},
			},
			"title": &graphql.Field{
				Type: graphql.String,
				Resolve: func(p graphql.ResolveParams) (interface{}, error) {
					v := p.Source.(supercharger.Location)
					return v.Title, nil
				},
			},
		},
		Interfaces: []*graphql.Interface{
			nodeDefinitions.NodeInterface,
		},
	})

	locationsConnectionDefinition := relay.ConnectionDefinitions(relay.ConnectionConfig{
		Name:     "Location",
		NodeType: locationType,
	})

	queryType := graphql.NewObject(graphql.ObjectConfig{
		Name: "Query",
		Fields: graphql.Fields{
			"locations": &graphql.Field{
				Type: locationsConnectionDefinition.ConnectionType,
				Args: typeArgs,
				Resolve: func(p graphql.ResolveParams) (interface{}, error) {
					superchargers, err := supercharger.Superchargers()
					if err != nil {
						return nil, err
					}

					args := relay.NewConnectionArguments(p.Args)

					locations := []interface{}{}
					for _, location := range superchargers {
						locations = append(locations, location)
					}

					return relay.ConnectionFromArray(locations, args), nil
				},
			},
			"node": nodeDefinitions.NodeField,
		},
	})

	return graphql.NewSchema(graphql.SchemaConfig{
		Query: queryType,
	})
}
<commit_msg>Handle pointer values<commit_after>package web

import (
	"errors"
	"strconv"

	"github.com/graphql-go/graphql"
	"github.com/graphql-go/relay"
	"github.com/wattapp/superchargers/pkg/location"
	"github.com/wattapp/superchargers/pkg/supercharger"
	"golang.org/x/net/context"
)

var nodeDefinitions *relay.NodeDefinitions

// Each top level type
var locationType *graphql.Object
var emailType *graphql.Object
var phoneType *graphql.Object

// Custom node field types
var enumChargerType = graphql.NewEnum(graphql.EnumConfig{
	Name: "Type",
	Values: graphql.EnumValueConfigMap{
		"SUPERCHARGER": &graphql.EnumValueConfig{
			Value: "SUPERCHARGER",
		},
		"DESTINATION": &graphql.EnumValueConfig{
			Value: "DESTINATION",
		},
	},
})

var typeFields = graphql.FieldConfigArgument{
	"type": &graphql.ArgumentConfig{
		Type: graphql.NewList(enumChargerType),
	},
}
var typeArgs = relay.NewConnectionArgs(typeFields)

func BuildSchema() (graphql.Schema, error) {
	nodeDefinitions = relay.NewNodeDefinitions(relay.NodeDefinitionsConfig{
		IDFetcher: func(id string, info graphql.ResolveInfo, ctx context.Context) (interface{}, error) {
			resolvedID := relay.FromGlobalID(id)

			switch resolvedID.Type {
			case "Location":
				locationID, _ := strconv.ParseInt(resolvedID.ID, 10, 64)
				return location.GetLocation(locationID)
			default:
				return nil, errors.New("Unknown node type")
			}
		},
		TypeResolve: func(p graphql.ResolveTypeParams) *graphql.Object {
			switch p.Value.(type) {
			case *location.Location:
				return locationType
			default:
				return locationType
			}
		},
	})

	emailType = graphql.NewObject(graphql.ObjectConfig{
		Name: "Email",
		Fields: graphql.Fields{
			"email": &graphql.Field{
				Type: graphql.String,
				Resolve: func(p graphql.ResolveParams) (interface{}, error) {
					e := p.Source.(supercharger.Email)
					return e.Email, nil
				},
			},
			"label": &graphql.Field{
				Type: graphql.String,
				Resolve: func(p graphql.ResolveParams) (interface{}, error) {
					e := p.Source.(supercharger.Email)
					return e.Label, nil
				},
			},
		},
	})

	phoneType = graphql.NewObject(graphql.ObjectConfig{
		Name: "Phone",
		Fields: graphql.Fields{
			"number": &graphql.Field{
				Type: graphql.String,
				Resolve: func(p graphql.ResolveParams) (interface{}, error) {
					e := p.Source.(supercharger.Phone)
					return e.Number, nil
				},
			},
			"label": &graphql.Field{
				Type: graphql.String,
				Resolve: func(p graphql.ResolveParams) (interface{}, error) {
					e := p.Source.(supercharger.Phone)
					return e.Label, nil
				},
			},
		},
	})

	locationType = graphql.NewObject(graphql.ObjectConfig{
		Name:        "Location",
		Description: "A vehicle contains trips and charges",
		Fields: graphql.Fields{
			"id": relay.GlobalIDField("Location", nil),
			"address": &graphql.Field{
				Type: graphql.String,
				Resolve: func(p graphql.ResolveParams) (interface{}, error) {
					l := p.Source.(*location.Location)
					return l.Address, nil
				},
			},
			"addressLine1": &graphql.Field{
				Type: graphql.String,
				Resolve: func(p graphql.ResolveParams) (interface{}, error) {
					l := p.Source.(*location.Location)
					raw := *l.AddressLine1
					if raw == "" {
						return nil, nil
					}
					return raw, nil
				},
			},
			"addressLine2": &graphql.Field{
				Type: graphql.String,
				Resolve: func(p graphql.ResolveParams) (interface{}, error) {
					l := p.Source.(*location.Location)
					raw := *l.AddressLine2
					if raw == "" {
						return nil, nil
					}
					return raw, nil
				},
			},
			"addressNotes": &graphql.Field{
				Type: graphql.String,
				Resolve: func(p graphql.ResolveParams) (interface{}, error) {
					l := p.Source.(*location.Location)
					raw := *l.AddressNotes
					if raw == "" {
						return nil, nil
					}
					return raw, nil
				},
			},
			"amentities": &graphql.Field{
				Type: graphql.String,
				Resolve: func(p graphql.ResolveParams) (interface{}, error) {
					l := p.Source.(*location.Location)
					return l.Amenities, nil
				},
			},
			"baiduLat": &graphql.Field{
				Type: graphql.Float,
				Resolve: func(p graphql.ResolveParams) (interface{}, error) {
					l := p.Source.(*location.Location)
					return l.BaiduLat, nil
				},
			},
			"baiduLng": &graphql.Field{
				Type: graphql.Float,
				Resolve: func(p graphql.ResolveParams) (interface{}, error) {
					l := p.Source.(*location.Location)
					return l.BaiduLng, nil
				},
			},
			"chargers": &graphql.Field{
				Type: graphql.String,
				Resolve: func(p graphql.ResolveParams) (interface{}, error) {
					l := p.Source.(*location.Location)
					raw := *l.Chargers
					if raw == "" {
						return nil, nil
					}
					return raw, nil
				},
			},
			"city": &graphql.Field{
				Type: graphql.String,
				Resolve: func(p graphql.ResolveParams) (interface{}, error) {
					l := p.Source.(*location.Location)
					return l.City, nil
				},
			},
			"commonName": &graphql.Field{
				Type: graphql.String,
				Resolve: func(p graphql.ResolveParams) (interface{}, error) {
					l := p.Source.(*location.Location)
					return l.CommonName, nil
				},
			},
			"country": &graphql.Field{
				Type: graphql.String,
				Resolve: func(p graphql.ResolveParams) (interface{}, error) {
					l := p.Source.(*location.Location)
					return l.Country, nil
				},
			},
			"destinationChargerLogo": &graphql.Field{
				Type: graphql.String,
				Resolve: func(p graphql.ResolveParams) (interface{}, error) {
					l := p.Source.(*location.Location)
					raw := *l.DestinationChargerLogo
					if raw == "" {
						return nil, nil
					}
					return raw, nil
				},
			},
			"destinationWebsite": &graphql.Field{
				Type: graphql.String,
				Resolve: func(p graphql.ResolveParams) (interface{}, error) {
					l := p.Source.(*location.Location)
					raw := *l.DestinationWebsite
					if raw == "" {
						return nil, nil
					}
					return raw, nil
				},
			},
			"directionsLink": &graphql.Field{
				Type: graphql.String,
				Resolve: func(p graphql.ResolveParams) (interface{}, error) {
					l := p.Source.(*location.Location)
					return l.DirectionsLink, nil
				},
			},
			"emails": &graphql.Field{
				Type: graphql.NewList(emailType),
				Resolve: func(p graphql.ResolveParams) (interface{}, error) {
					l := p.Source.(*location.Location)
					return l.Emails, nil
				},
			},
			"geocode": &graphql.Field{
				Type: graphql.String,
				Resolve: func(p graphql.ResolveParams) (interface{}, error) {
					l := p.Source.(*location.Location)
					return l.Geocode, nil
				},
			},
			"hours": &graphql.Field{
				Type: graphql.String,
				Resolve: func(p graphql.ResolveParams) (interface{}, error) {
					l := p.Source.(*location.Location)
					raw := *l.Hours
					if raw == "" {
						return nil, nil
					}
					return raw, nil
				},
			},
			"isGallery": &graphql.Field{
				Type: graphql.Boolean,
				Resolve: func(p graphql.ResolveParams) (interface{}, error) {
					l := p.Source.(*location.Location)
					return l.IsGallery, nil
				},
			},
			"kioskPinX": &graphql.Field{
				Type: graphql.Int,
				Resolve: func(p graphql.ResolveParams) (interface{}, error) {
					l := p.Source.(*location.Location)
					return l.KioskPinX, nil
				},
			},
			"kioskPinY": &graphql.Field{
				Type: graphql.Int,
				Resolve: func(p graphql.ResolveParams) (interface{}, error) {
					l := p.Source.(*location.Location)
					return l.KioskPinY, nil
				},
			},
			"kioskZoomPinX": &graphql.Field{
				Type: graphql.Int,
				Resolve: func(p graphql.ResolveParams) (interface{}, error) {
					l := p.Source.(*location.Location)
					return l.KioskZoomPinX, nil
				},
			},
			"kioskZoomPinY": &graphql.Field{
				Type: graphql.Int,
				Resolve: func(p graphql.ResolveParams) (interface{}, error) {
					l := p.Source.(*location.Location)
					return l.KioskZoomPinY, nil
				},
			},
			"latitude": &graphql.Field{
				Type: graphql.Float,
				Resolve: func(p graphql.ResolveParams) (interface{}, error) {
					l := p.Source.(*location.Location)
					return l.Latitude, nil
				},
			},
			"longitude": &graphql.Field{
				Type: graphql.Float,
				Resolve: func(p graphql.ResolveParams) (interface{}, error) {
					l := p.Source.(*location.Location)
					return l.Longitude, nil
				},
			},
			"locationId": &graphql.Field{
				Type: graphql.String,
				Resolve: func(p graphql.ResolveParams) (interface{}, error) {
					l := p.Source.(*location.Location)
					return l.LocationID, nil
				},
			},
			"locationType": &graphql.Field{
				Type: graphql.NewList(graphql.String),
				Resolve: func(p graphql.ResolveParams) (interface{}, error) {
					l := p.Source.(*location.Location)
					return l.LocationType, nil
				},
			},
			"nid": &graphql.Field{
				Type: graphql.Int,
				Resolve: func(p graphql.ResolveParams) (interface{}, error) {
					l := p.Source.(*location.Location)
					return l.Nid, nil
				},
			},
			"openSoon": &graphql.Field{
				Type: graphql.Boolean,
				Resolve: func(p graphql.ResolveParams) (interface{}, error) {
					l := p.Source.(*location.Location)
					return l.OpenSoon, nil
				},
			},
			"path": &graphql.Field{
				Type: graphql.String,
				Resolve: func(p graphql.ResolveParams) (interface{}, error) {
					l := p.Source.(*location.Location)
					return l.Path, nil
				},
			},
			"postalCode": &graphql.Field{
				Type: graphql.String,
				Resolve: func(p graphql.ResolveParams) (interface{}, error) {
					l := p.Source.(*location.Location)
					raw := *l.PostalCode
					if raw == "" {
						return nil, nil
					}
					return raw, nil
				},
			},
			"provinceState": &graphql.Field{
				Type: graphql.String,
				Resolve: func(p graphql.ResolveParams) (interface{}, error) {
					l := p.Source.(*location.Location)
					raw := *l.ProvinceState
					if raw == "" {
						return nil, nil
					}
					return raw, nil
				},
			},
			"region": &graphql.Field{
				Type: graphql.String,
				Resolve: func(p graphql.ResolveParams) (interface{}, error) {
					l := p.Source.(*location.Location)
					return l.Region, nil
				},
			},
			"salesPhone": &graphql.Field{
				Type: graphql.NewList(phoneType),
				Resolve: func(p graphql.ResolveParams) (interface{}, error) {
					l := p.Source.(*location.Location)
					return l.SalesPhone, nil
				},
			},
			"salesRepresentative": &graphql.Field{
				Type: graphql.String,
				Resolve: func(p graphql.ResolveParams) (interface{}, error) {
					l := p.Source.(*location.Location)
					return l.SalesRepresentative, nil
				},
			},
			"subRegion": &graphql.Field{
				Type: graphql.String,
				Resolve: func(p graphql.ResolveParams) (interface{}, error) {
					l := p.Source.(*location.Location)
					raw := *l.SubRegion
					if raw == "" {
						return nil, nil
					}
					return raw, nil
				},
			},
			"title": &graphql.Field{
				Type: graphql.String,
				Resolve: func(p graphql.ResolveParams) (interface{}, error) {
					l := p.Source.(*location.Location)
					return l.Title, nil
				},
			},
		},
		Interfaces: []*graphql.Interface{
			nodeDefinitions.NodeInterface,
		},
	})

	locationsConnectionDefinition := relay.ConnectionDefinitions(relay.ConnectionConfig{
		Name:     "Location",
		NodeType: locationType,
	})

	queryType := graphql.NewObject(graphql.ObjectConfig{
		Name: "Query",
		Fields: graphql.Fields{
			"locations": &graphql.Field{
				Type: locationsConnectionDefinition.ConnectionType,
				Args: typeArgs,
				Resolve: func(p graphql.ResolveParams) (interface{}, error) {
					locations, err := location.Locations()
					if err != nil {
						return nil, err
					}

					args := relay.NewConnectionArguments(p.Args)

					l := []interface{}{}
					for _, location := range locations {
						l = append(l, location)
					}

					return relay.ConnectionFromArray(l, args), nil
				},
			},
			"node": nodeDefinitions.NodeField,
		},
	})

	return graphql.NewSchema(graphql.SchemaConfig{
		Query: queryType,
	})
}
<|endoftext|>


<commit_before>package aws

import (
	"fmt"
	"testing"

	"github.com/hashicorp/terraform/helper/resource"
	"github.com/hashicorp/terraform/terraform"
)

func TestAccAWSProxyProtocolPolicy_basic(t *testing.T) {
	resource.Test(t, resource.TestCase{
		PreCheck:     func() { testAccPreCheck(t) },
		Providers:    testAccProviders,
		CheckDestroy: testAccCheckProxyProtocolPolicyDestroy,
		Steps: []resource.TestStep{
			resource.TestStep{
				Config: testAccProxyProtocolPolicyConfig,
				Check: resource.ComposeTestCheckFunc(
					resource.TestCheckResourceAttr(
						"aws_proxy_protocol_policy.smtp", "load_balancer", "test-lb"),
					resource.TestCheckResourceAttr(
						"aws_proxy_protocol_policy.smtp", "instance_ports.#", "1"),
					resource.TestCheckResourceAttr(
						"aws_proxy_protocol_policy.smtp", "instance_ports.4196041389", "25"),
				),
			},
			resource.TestStep{
				Config: testAccProxyProtocolPolicyConfigUpdate,
				Check: resource.ComposeTestCheckFunc(
					resource.TestCheckResourceAttr(
						"aws_proxy_protocol_policy.smtp", "load_balancer", "test-lb"),
					resource.TestCheckResourceAttr(
						"aws_proxy_protocol_policy.smtp", "instance_ports.#", "2"),
					resource.TestCheckResourceAttr(
						"aws_proxy_protocol_policy.smtp", "instance_ports.4196041389", "25"),
					resource.TestCheckResourceAttr(
						"aws_proxy_protocol_policy.smtp", "instance_ports.1925441437", "587"),
				),
			},
		},
	})
}

func testAccCheckProxyProtocolPolicyDestroy(s *terraform.State) error {
	if len(s.RootModule().Resources) > 0 {
		return fmt.Errorf("Expected all resources to be gone, but found: %#v", s.RootModule().Resources)
	}

	return nil
}

const testAccProxyProtocolPolicyConfig = `
resource "aws_elb" "lb" {
	name = "test-lb"
	availability_zones = ["us-west-2a"]

	listener {
		instance_port = 25
		instance_protocol = "tcp"
		lb_port = 25
		lb_protocol = "tcp"
	}

	listener {
		instance_port = 587
		instance_protocol = "tcp"
		lb_port = 587
		lb_protocol = "tcp"
	}
}

resource "aws_proxy_protocol_policy" "smtp" {
	load_balancer = "${aws_elb.lb.name}"
	instance_ports = ["25"]
}
`

const testAccProxyProtocolPolicyConfigUpdate = `
resource "aws_elb" "lb" {
	name = "test-lb"
	availability_zones = ["us-west-2a"]

	listener {
		instance_port = 25
		instance_protocol = "tcp"
		lb_port = 25
		lb_protocol = "tcp"
	}

	listener {
		instance_port = 587
		instance_protocol = "tcp"
		lb_port = 587
		lb_protocol = "tcp"
	}
}

resource "aws_proxy_protocol_policy" "smtp" {
	load_balancer = "${aws_elb.lb.name}"
	instance_ports = ["25", "587"]
}
`
<commit_msg>provider/aws: fix CheckDestroy for ProtocolPolicy tests<commit_after>package aws

import (
	"fmt"
	"testing"

	"github.com/aws/aws-sdk-go/aws"
	"github.com/aws/aws-sdk-go/service/elb"
	"github.com/hashicorp/terraform/helper/resource"
	"github.com/hashicorp/terraform/terraform"
)

func TestAccAWSProxyProtocolPolicy_basic(t *testing.T) {
	resource.Test(t, resource.TestCase{
		PreCheck:     func() { testAccPreCheck(t) },
		Providers:    testAccProviders,
		CheckDestroy: testAccCheckProxyProtocolPolicyDestroy,
		Steps: []resource.TestStep{
			resource.TestStep{
				Config: testAccProxyProtocolPolicyConfig,
				Check: resource.ComposeTestCheckFunc(
					resource.TestCheckResourceAttr(
						"aws_proxy_protocol_policy.smtp", "load_balancer", "test-lb"),
					resource.TestCheckResourceAttr(
						"aws_proxy_protocol_policy.smtp", "instance_ports.#", "1"),
					resource.TestCheckResourceAttr(
						"aws_proxy_protocol_policy.smtp", "instance_ports.4196041389", "25"),
				),
			},
			resource.TestStep{
				Config: testAccProxyProtocolPolicyConfigUpdate,
				Check: resource.ComposeTestCheckFunc(
					resource.TestCheckResourceAttr(
						"aws_proxy_protocol_policy.smtp", "load_balancer", "test-lb"),
					resource.TestCheckResourceAttr(
						"aws_proxy_protocol_policy.smtp", "instance_ports.#", "2"),
					resource.TestCheckResourceAttr(
						"aws_proxy_protocol_policy.smtp", "instance_ports.4196041389", "25"),
					resource.TestCheckResourceAttr(
						"aws_proxy_protocol_policy.smtp", "instance_ports.1925441437", "587"),
				),
			},
		},
	})
}

func testAccCheckProxyProtocolPolicyDestroy(s *terraform.State) error {
	conn := testAccProvider.Meta().(*AWSClient).elbconn

	for _, rs := range s.RootModule().Resources {
		if rs.Type != "aws_placement_group" {
			continue
		}

		req := &elb.DescribeLoadBalancersInput{
			LoadBalancerNames: []*string{
				aws.String(rs.Primary.Attributes["load_balancer"])},
		}
		_, err := conn.DescribeLoadBalancers(req)
		if err != nil {
			// Verify the error is what we want
			if isLoadBalancerNotFound(err) {
				continue
			}
			return err
		}

		return fmt.Errorf("still exists")
	}
	return nil
}

const testAccProxyProtocolPolicyConfig = `
resource "aws_elb" "lb" {
	name = "test-lb"
	availability_zones = ["us-west-2a"]

	listener {
		instance_port = 25
		instance_protocol = "tcp"
		lb_port = 25
		lb_protocol = "tcp"
	}

	listener {
		instance_port = 587
		instance_protocol = "tcp"
		lb_port = 587
		lb_protocol = "tcp"
	}
}

resource "aws_proxy_protocol_policy" "smtp" {
	load_balancer = "${aws_elb.lb.name}"
	instance_ports = ["25"]
}
`

const testAccProxyProtocolPolicyConfigUpdate = `
resource "aws_elb" "lb" {
	name = "test-lb"
	availability_zones = ["us-west-2a"]

	listener {
		instance_port = 25
		instance_protocol = "tcp"
		lb_port = 25
		lb_protocol = "tcp"
	}

	listener {
		instance_port = 587
		instance_protocol = "tcp"
		lb_port = 587
		lb_protocol = "tcp"
	}
}

resource "aws_proxy_protocol_policy" "smtp" {
	load_balancer = "${aws_elb.lb.name}"
	instance_ports = ["25", "587"]
}
`
<|endoftext|>


<commit_before>// File stores the contents in the template file so that its part of the package.
package couchdb

import (
	"strings"
	"text/template"
)

var DESIGNTMPL *template.Template = template.Must(template.New("design").Parse(strings.Replace(strings.Replace(`
{
	"_id": "{{.Id}}",
	{{if .RevStatus}}
	"_rev":"{{.Rev}}",
	{{end}}
	"views": {
		{{range .Views}}

		   "{{.Name}}": {
		   {{if .RawStatus}}
			"map": "{{.RawJson}}"
		   {{else}}
			function({{.VariableName}}) { \
\
				function get_value(doc, keys) { \
					var value = {}; \
					for(key in keys) { \
						value[keys[key]] = doc[keys[key]];\
					} \
					return value; \
					}\
				{{if .CondStatus}}
					if({{.Condition}}) { \
						emit({{.EmitStr}}); \
						} \
				{{else}} \
						emit({{.VariableName}}._id, get_value({{.VariableName}},  [{{.EmitStr}}]));\
				{{end}} \
			}"
		   {{end}}
		   },

		{{end}}
		   "{{.LastView.Name}}": {
	            {{if .LastView.RawStatus}}
			"map": "{{.LastView.RawJson}}"
		    {{else}}
			"map": " \
			function({{.LastView.VariableName}}) { \
\
				function get_value(doc, keys) { \
					var value = {}; \
					for(key in keys) { \
						value[keys[key]] = doc[keys[key]];\
					} \
					return value; \
					}\
				{{if .LastView.CondStatus}}
					if({{.LastView.Condition}}) { \
						emit({{.LastView.EmitStr}}); \
						} \
				{{else}} \
						emit({{.LastView.VariableName}}._id, get_value({{.LastView.VariableName}},  [{{.LastView.EmitStr}}]));\
				{{end}} \
			}"
		    {{end}}
		   }
	},
	"language": "javascript"
}
`, "\\\n", "", -1), "\t", "", -1)))
<commit_msg>Updated query template due to mistakes for conditions<commit_after>// File stores the contents in the template file so that its part of the package.
package couchdb

import (
	"strings"
	"text/template"
)

var DESIGNTMPL *template.Template = template.Must(template.New("design").Parse(strings.Replace(strings.Replace(`
{
	"_id": "{{.Id}}",
	{{if .RevStatus}}
	"_rev":"{{.Rev}}",
	{{end}}
	"views": {
		{{range .Views}}

		   "{{.Name}}": {
		   {{if .RawStatus}}
			"map": "{{.RawJson}}"
		   {{else}}
			function({{.VariableName}}) { \
\
				function get_value(doc, keys) { \
					var value = {}; \
					for(key in keys) { \
						value[keys[key]] = doc[keys[key]];\
					} \
					return value; \
					}\
				{{if .CondStatus}}\
					if({{.Condition}}) { \
						emit({{.VariableName}}._id, get_value({{.VariableName}},  [{{.EmitStr}}]));\
						} \
				{{else}} \
						emit({{.VariableName}}._id, get_value({{.VariableName}},  [{{.EmitStr}}]));\
				{{end}} \
			}"
		   {{end}}
		   },

		{{end}}
		   "{{.LastView.Name}}": {
	            {{if .LastView.RawStatus}}
			"map": "{{.LastView.RawJson}}"
		    {{else}}
			"map": " \
			function({{.LastView.VariableName}}) { \
\
				function get_value(doc, keys) { \
					var value = {}; \
					for(key in keys) { \
						value[keys[key]] = doc[keys[key]];\
					} \
					return value; \
					}\
				{{if .LastView.CondStatus}}\
					if({{.LastView.Condition}}) { \
						emit({{.LastView.VariableName}}._id, get_value({{.LastView.VariableName}},  [{{.LastView.EmitStr}}]));\
						} \
				{{else}} \
						emit({{.LastView.VariableName}}._id, get_value({{.LastView.VariableName}},  [{{.LastView.EmitStr}}]));\
				{{end}} \
			}"
		    {{end}}
		   }
	},
	"language": "javascript"
}
`, "\\\n", "", -1), "\t", "", -1)))
<|endoftext|>


<commit_before>package main

import (
	"flag"
	"fmt"
	"log"
	"math/rand"
	"os"
	"path/filepath"
	"sync"
	"sync/atomic"
	"time"

	"github.com/dgraph-io/badger/y"
)

var (
	dir           = flag.String("dir", "datafiles", "File to read from")
	numSerial     = flag.Int64("sreads", 0, "Number of serial random reads")
	numParallel   = flag.Int64("preads", 2000000, "Number of parallel random reads")
	numGoroutines = flag.Int("jobs", 8, "Number of Goroutines")
)

var readSize int64 = 4 << 10

func getIndices(flist []*os.File, maxFileSize int64) (*os.File, int64) {
	fidx := rand.Intn(len(flist))
	iidx := rand.Int63n(maxFileSize - readSize)
	return flist[fidx], iidx
}

func Serial(fList []*os.File, maxFileSize int64) {
	startT := time.Now()
	var i int64 = 0
	b := make([]byte, int(readSize))

	rand.Seed(int64(time.Now().Second()))
	for ; i < *numSerial; i++ {
		fd, offset := getIndices(fList, maxFileSize)
		_, err := fd.ReadAt(b, offset)
		if err != nil {
			log.Fatalf("Error reading file: %v", err)
		}
		if i%10000 == 0 {
			log.Printf("Finished %v reads in serial", i)
		}
	}
	fmt.Println("Serial: Number of random reads per second: ", float64(*numSerial)/time.Since(startT).Seconds())
	fmt.Println("Serial: Time Taken: ", time.Since(startT))
}

func Conc2(fList []*os.File, maxFileSize int64) {
	startT := time.Now()
	var i int64
	var wg sync.WaitGroup

	rand.Seed(int64(time.Now().Second()))
	for k := 0; k < *numGoroutines; k++ {
		wg.Add(1)
		go func() {
			b := make([]byte, int(readSize))
			for atomic.LoadInt64(&i) < *numParallel {
				fd, offset := getIndices(fList, maxFileSize)
				_, err := fd.ReadAt(b, offset)
				if err != nil {
					log.Fatalf("Error reading file: %v", err)
				}
				atomic.AddInt64(&i, 1)
			}
			wg.Done()
		}()
	}
	wg.Wait()
	fmt.Println("Concurrent 2: Number of random reads per second: ", float64(*numParallel)/time.Since(startT).Seconds())
	fmt.Println("Concurrent 2: Time Taken: ", time.Since(startT))
}

type req struct {
	fd     *os.File
	offset int64
}

func Conc3(fList []*os.File, maxFileSize int64) {
	ch := make(chan req, 10000)
	go func() {
		var i int64
		for i = 0; i < *numParallel; i++ {
			var r req
			r.fd, r.offset = getIndices(fList, maxFileSize)
			ch <- r
		}
		close(ch)
	}()

	startT := time.Now()
	var wg sync.WaitGroup
	for k := 0; k < *numGoroutines; k++ {
		wg.Add(1)
		go func() {
			b := make([]byte, int(readSize))
			for req := range ch {
				_, err := req.fd.ReadAt(b, req.offset)
				if err != nil {
					log.Fatalf("Error reading file: %v", err)
				}
			}
			wg.Done()
		}()
	}
	wg.Wait()
	fmt.Println("Concurrent 3: Number of random reads per second: ", float64(*numParallel)/time.Since(startT).Seconds())
	fmt.Println("Concurrent 3: Time Taken: ", time.Since(startT))
}

func main() {
	flag.Parse()

	var flist []*os.File
	var maxFileSize int64
	getFile := func(path string, info os.FileInfo, err error) error {
		if err != nil {
			log.Print(err)
			return nil
		}

		if !info.IsDir() {
			f, err := os.Open(path)
			y.AssertTruef(err == nil, "Error opening file: %v", path)
			flist = append(flist, f)
			log.Println("Opened file:", path, "Size:", info.Size()/(1<<20), "MB")
			maxFileSize = info.Size()
		}
		return nil
	}

	err := filepath.Walk(*dir, getFile)
	if err != nil {
		log.Fatalf("%v", err)
	}
	if len(flist) == 0 {
		log.Fatalf("Must have files already created")
	}

	Serial(flist, maxFileSize)
	Conc2(flist, maxFileSize)
	Conc3(flist, maxFileSize)
}
<commit_msg>Don't use locked rand. Simplify arguments passed<commit_after>package main

import (
	"flag"
	"fmt"
	"log"
	"math/rand"
	"os"
	"path/filepath"
	"runtime/pprof"
	"sync"
	"sync/atomic"
	"time"

	"github.com/dgraph-io/badger/y"
)

var (
	dir           = flag.String("dir", "datafiles", "File to read from")
	numReads      = flag.Int64("num", 2000000, "Number of reads")
	mode          = flag.Int("mode", 1, "0 = serial, 1 = parallel, 2 = parallel via channel")
	numGoroutines = flag.Int("jobs", 8, "Number of Goroutines")
	cpuprofile    = flag.String("cpuprofile", "", "write cpu profile to file")
)

var readSize int64 = 4 << 10

func getIndices(r *rand.Rand, flist []*os.File, maxFileSize int64) (*os.File, int64) {
	fidx := r.Intn(len(flist))
	iidx := r.Int63n(maxFileSize - readSize)
	return flist[fidx], iidx
}

func Serial(fList []*os.File, maxFileSize int64) {
	startT := time.Now()
	var i int64 = 0
	b := make([]byte, int(readSize))

	r := rand.New(rand.NewSource(time.Now().UnixNano()))
	for ; i < *numReads; i++ {
		fd, offset := getIndices(r, fList, maxFileSize)
		_, err := fd.ReadAt(b, offset)
		if err != nil {
			log.Fatalf("Error reading file: %v", err)
		}
		if i%10000 == 0 {
			log.Printf("Finished %v reads in serial", i)
		}
	}
	fmt.Println("Serial: Number of random reads per second: ",
		float64(*numReads)/time.Since(startT).Seconds())
	fmt.Println("Serial: Time Taken: ", time.Since(startT))
}

func Conc2(fList []*os.File, maxFileSize int64) {
	startT := time.Now()
	var i int64
	var wg sync.WaitGroup

	for k := 0; k < *numGoroutines; k++ {
		wg.Add(1)
		go func() {
			b := make([]byte, int(readSize))
			r := rand.New(rand.NewSource(time.Now().UnixNano()))
			for atomic.LoadInt64(&i) < *numReads {
				fd, offset := getIndices(r, fList, maxFileSize)
				_, err := fd.ReadAt(b, offset)
				if err != nil {
					log.Fatalf("Error reading file: %v", err)
				}
				atomic.AddInt64(&i, 1)
			}
			wg.Done()
		}()
	}
	wg.Wait()
	fmt.Println("Concurrent 2: Number of random reads per second: ",
		float64(*numReads)/time.Since(startT).Seconds())
	fmt.Println("Concurrent 2: Time Taken: ", time.Since(startT))
}

type req struct {
	fd     *os.File
	offset int64
}

func Conc3(fList []*os.File, maxFileSize int64) {
	ch := make(chan req, 10000)
	go func() {
		var i int64
		rd := rand.New(rand.NewSource(time.Now().UnixNano()))
		for i = 0; i < *numReads; i++ {
			var r req
			r.fd, r.offset = getIndices(rd, fList, maxFileSize)
			ch <- r
		}
		close(ch)
	}()

	startT := time.Now()
	var wg sync.WaitGroup
	for k := 0; k < *numGoroutines; k++ {
		wg.Add(1)
		go func() {
			b := make([]byte, int(readSize))
			for req := range ch {
				_, err := req.fd.ReadAt(b, req.offset)
				if err != nil {
					log.Fatalf("Error reading file: %v", err)
				}
			}
			wg.Done()
		}()
	}
	wg.Wait()
	fmt.Println("Concurrent 3: Number of random reads per second: ",
		float64(*numReads)/time.Since(startT).Seconds())
	fmt.Println("Concurrent 3: Time Taken: ", time.Since(startT))
}

func main() {
	flag.Parse()

	var flist []*os.File
	var maxFileSize int64
	getFile := func(path string, info os.FileInfo, err error) error {
		if err != nil {
			log.Print(err)
			return nil
		}

		if !info.IsDir() {
			f, err := os.Open(path)
			y.AssertTruef(err == nil, "Error opening file: %v", path)
			flist = append(flist, f)
			log.Println("Opened file:", path, "Size:", info.Size()/(1<<20), "MB")
			maxFileSize = info.Size()
		}
		return nil
	}

	err := filepath.Walk(*dir, getFile)
	if err != nil {
		log.Fatalf("%v", err)
	}
	if len(flist) == 0 {
		log.Fatalf("Must have files already created")
	}

	if *cpuprofile != "" {
		f, err := os.Create(*cpuprofile)
		if err != nil {
			log.Fatal(err)
		}
		pprof.StartCPUProfile(f)
		defer pprof.StopCPUProfile()
	}

	switch *mode {
	case 0:
		Serial(flist, maxFileSize)
	case 1:
		Conc2(flist, maxFileSize)
	case 2:
		Conc3(flist, maxFileSize)
	}
}
<|endoftext|>


<commit_before>package main

import (
	"fmt"
	"os"
	"path/filepath"
	"strconv"
	"strings"

	lua "github.com/anaminus/gopher-lua"
	"github.com/anaminus/rbxmk"
	"github.com/anaminus/rbxmk/formats"
	"github.com/anaminus/rbxmk/library"
	"github.com/anaminus/rbxmk/sources"
	"github.com/anaminus/snek"
)

// shortenPath transforms the given path so that it is relative to the working
// directory. Returns the original path if that fails.
func shortenPath(filename string) string {
	if wd, err := os.Getwd(); err == nil {
		if abs, err := filepath.Abs(filename); err == nil {
			if r, err := filepath.Rel(wd, abs); err == nil {
				filename = r
			}
		}
	}
	return filename
}

// ParseLuaValue parses a string into a Lua value. Numbers, bools, and nil are
// parsed into their respective types, and any other value is interpreted as a
// string.
func ParseLuaValue(s string) lua.LValue {
	switch s {
	case "true":
		return lua.LTrue
	case "false":
		return lua.LFalse
	case "nil":
		return lua.LNil
	}
	if number, err := strconv.ParseFloat(s, 64); err == nil {
		return lua.LNumber(number)
	}
	return lua.LString(s)
}

func init() {
	Program.Register(snek.Def{
		Name:      "run",
		Summary:   "Execute a script.",
		Arguments: `[ FILE ] [ ...VALUE ]`,
		Description: `
Receives a file to be executed as a Lua script. If "-" is given, then the script
will be read from stdin instead.

Remaining arguments are Lua values to be passed to the file. Numbers, bools, and
nil are parsed into their respective types in Lua, and any other value is
interpreted as a string. Within the script, these arguments can be received from
the ... operator.`,
		New: func() snek.Command { return &RunCommand{} },
	})
}

// repeatedString is a string flag that can be specified multiple times.
type repeatedString []string

func (s repeatedString) String() string {
	return strings.Join(s, ",")
}

func (s *repeatedString) Set(v string) error {
	*s = append(*s, v)
	return nil
}

type RunCommand struct {
	IncludedRoots []string
	InsecurePaths bool
	Debug         bool
	Init          func(rbxmk.State)
}

func (c *RunCommand) SetFlags(flags snek.FlagSet) {
	flags.Var((*repeatedString)(&c.IncludedRoots), "include-root", "Mark a path as an accessible root directory. May be specified any number of times.")
	flags.BoolVar(&c.InsecurePaths, "allow-insecure-paths", false, "Disable path restrictions, allowing scripts to access any path in the file system.")
	flags.BoolVar(&c.Debug, "debug", false, "Display stack traces when an error occurs.")
}

// Run is the entrypoint to the command for running scripts. init runs after the
// World envrionment is fully initialized and arguments have been pushed, and
// before the script runs.
func (c *RunCommand) Run(opt snek.Options) error {
	// Parse flags.
	if err := opt.ParseFlags(); err != nil {
		return err
	}
	args := opt.Args()
	if len(args) == 0 {
		opt.Usage()
		return nil
	}
	file := args[0]
	args = args[1:]

	// Initialize world.
	world := rbxmk.NewWorld(lua.NewState(lua.Options{
		SkipOpenLibs:        true,
		IncludeGoStackTrace: c.Debug,
	}))
	if c.InsecurePaths {
		world.FS.SetSecured(false)
	}
	if wd, err := os.Getwd(); err == nil {
		// Working directory is an accessible root.
		world.FS.AddRoot(wd)
	}
	for _, root := range c.IncludedRoots {
		world.FS.AddRoot(root)
	}
	for _, f := range formats.All() {
		world.RegisterFormat(f())
	}
	for _, s := range sources.All() {
		world.RegisterSource(s())
	}
	for _, lib := range library.All() {
		if err := world.Open(lib); err != nil {
			return err
		}
	}

	world.State().SetGlobal("_RBXMK_VERSION", lua.LString(Version))

	// Add script arguments.
	for _, arg := range args {
		world.State().Push(ParseLuaValue(arg))
	}

	if c.Init != nil {
		c.Init(rbxmk.State{World: world, L: world.State()})
	}

	// Run stdin as script.
	if file == "-" {
		if opt.Stdin == nil {
			return fmt.Errorf("no file handle")
		}
		return world.DoFileHandle(opt.Stdin, "", len(args))
	}

	// Run file as script.
	filename := shortenPath(filepath.Clean(file))
	return world.DoFile(filename, len(args))
}
<commit_msg>Indicate flags in arguments to run command.<commit_after>package main

import (
	"fmt"
	"os"
	"path/filepath"
	"strconv"
	"strings"

	lua "github.com/anaminus/gopher-lua"
	"github.com/anaminus/rbxmk"
	"github.com/anaminus/rbxmk/formats"
	"github.com/anaminus/rbxmk/library"
	"github.com/anaminus/rbxmk/sources"
	"github.com/anaminus/snek"
)

// shortenPath transforms the given path so that it is relative to the working
// directory. Returns the original path if that fails.
func shortenPath(filename string) string {
	if wd, err := os.Getwd(); err == nil {
		if abs, err := filepath.Abs(filename); err == nil {
			if r, err := filepath.Rel(wd, abs); err == nil {
				filename = r
			}
		}
	}
	return filename
}

// ParseLuaValue parses a string into a Lua value. Numbers, bools, and nil are
// parsed into their respective types, and any other value is interpreted as a
// string.
func ParseLuaValue(s string) lua.LValue {
	switch s {
	case "true":
		return lua.LTrue
	case "false":
		return lua.LFalse
	case "nil":
		return lua.LNil
	}
	if number, err := strconv.ParseFloat(s, 64); err == nil {
		return lua.LNumber(number)
	}
	return lua.LString(s)
}

func init() {
	Program.Register(snek.Def{
		Name:      "run",
		Summary:   "Execute a script.",
		Arguments: `[ FLAGS ] [ FILE ] [ ...VALUE ]`,
		Description: `
Receives a file to be executed as a Lua script. If "-" is given, then the script
will be read from stdin instead.

Remaining arguments are Lua values to be passed to the file. Numbers, bools, and
nil are parsed into their respective types in Lua, and any other value is
interpreted as a string. Within the script, these arguments can be received from
the ... operator.`,
		New: func() snek.Command { return &RunCommand{} },
	})
}

// repeatedString is a string flag that can be specified multiple times.
type repeatedString []string

func (s repeatedString) String() string {
	return strings.Join(s, ",")
}

func (s *repeatedString) Set(v string) error {
	*s = append(*s, v)
	return nil
}

type RunCommand struct {
	IncludedRoots []string
	InsecurePaths bool
	Debug         bool
	Init          func(rbxmk.State)
}

func (c *RunCommand) SetFlags(flags snek.FlagSet) {
	flags.Var((*repeatedString)(&c.IncludedRoots), "include-root", "Mark a path as an accessible root directory. May be specified any number of times.")
	flags.BoolVar(&c.InsecurePaths, "allow-insecure-paths", false, "Disable path restrictions, allowing scripts to access any path in the file system.")
	flags.BoolVar(&c.Debug, "debug", false, "Display stack traces when an error occurs.")
}

// Run is the entrypoint to the command for running scripts. init runs after the
// World envrionment is fully initialized and arguments have been pushed, and
// before the script runs.
func (c *RunCommand) Run(opt snek.Options) error {
	// Parse flags.
	if err := opt.ParseFlags(); err != nil {
		return err
	}
	args := opt.Args()
	if len(args) == 0 {
		opt.Usage()
		return nil
	}
	file := args[0]
	args = args[1:]

	// Initialize world.
	world := rbxmk.NewWorld(lua.NewState(lua.Options{
		SkipOpenLibs:        true,
		IncludeGoStackTrace: c.Debug,
	}))
	if c.InsecurePaths {
		world.FS.SetSecured(false)
	}
	if wd, err := os.Getwd(); err == nil {
		// Working directory is an accessible root.
		world.FS.AddRoot(wd)
	}
	for _, root := range c.IncludedRoots {
		world.FS.AddRoot(root)
	}
	for _, f := range formats.All() {
		world.RegisterFormat(f())
	}
	for _, s := range sources.All() {
		world.RegisterSource(s())
	}
	for _, lib := range library.All() {
		if err := world.Open(lib); err != nil {
			return err
		}
	}

	world.State().SetGlobal("_RBXMK_VERSION", lua.LString(Version))

	// Add script arguments.
	for _, arg := range args {
		world.State().Push(ParseLuaValue(arg))
	}

	if c.Init != nil {
		c.Init(rbxmk.State{World: world, L: world.State()})
	}

	// Run stdin as script.
	if file == "-" {
		if opt.Stdin == nil {
			return fmt.Errorf("no file handle")
		}
		return world.DoFileHandle(opt.Stdin, "", len(args))
	}

	// Run file as script.
	filename := shortenPath(filepath.Clean(file))
	return world.DoFile(filename, len(args))
}
<|endoftext|>


<commit_before>package redlot

import (
	"strconv"

	"github.com/syndtr/goleveldb/leveldb/util"
)

func encodeHashKey(name, key []byte) (buf []byte) {
	buf = append(buf, typeHASH)
	buf = append(buf, uint32ToBytes(uint32(len(name)))...)
	buf = append(buf, name...)
	buf = append(buf, uint32ToBytes(uint32(len(key)))...)
	buf = append(buf, key...)
	return
}

func decodeHashKey(b []byte) (name, key []byte) {
	nameLen := bytesToUint32(b[1:5])
	name = b[5 : 5+nameLen]
	key = b[9+nameLen:]
	return
}

func encodeHsizeKey(name []byte) (buf []byte) {
	buf = append(buf, typeHSIZE)
	buf = append(buf, uint32ToBytes(uint32(len(name)))...)
	buf = append(buf, name...)
	return
}

func decodeHsizeKey(b []byte) (key []byte) {
	return b[5:]
}

func hashSizeIncr(name []byte, incr int) {
	hsize := encodeHsizeKey(name)

	var size uint32
	if b, err := db.Get(hsize, nil); err == nil {
		size = bytesToUint32(b)
	}

	if incr > 0 {
		size += uint32(incr)
	} else {
		size -= uint32(incr)
	}
	db.Put(hsize, uint32ToBytes(size), nil)
}

// Hset will set a hashmap value by the key.
// Args: name string, key string, value any
func Hset(args [][]byte) (r interface{}, err error) {
	if len(args) < 3 {
		return nil, errNosArgs
	}

	hashSizeIncr(args[0], 1)
	err = db.Put(encodeHashKey(args[0], args[1]), args[2], nil)
	if err != nil {
		hashSizeIncr(args[0], -1)
		return nil, err
	}

	return
}

// Hset will return a hashmap value by the key.
// Args: name string, key string
func Hget(args [][]byte) (r interface{}, err error) {
	if len(args) < 2 {
		return nil, errNosArgs
	}
	var b []byte
	b, err = db.Get(encodeHashKey(args[0], args[1]), nil)
	return string(b), err
}

// Hdel will delete a hashmap value by the key.
// Args: name string, key string
func Hdel(args [][]byte) (r interface{}, err error) {
	if len(args) < 2 {
		return nil, errNosArgs
	}

	return
}

func hincr(key []byte, increment int) (r int64, err error) {
	v, _ := db.Get(key, nil)
	var number int
	if len(v) != 0 {
		var err error
		number, err = strconv.Atoi(string(v))
		if err != nil {
			return -1, errNotInt
		}
	}
	number += increment
	return int64(number), db.Put(key, []byte(strconv.Itoa(number)), nil)
}

// Hincr will incr a hashmap value by the key.
// Args: name string, key string
func Hincr(args [][]byte) (r interface{}, err error) {
	if len(args) < 2 {
		return nil, errNosArgs
	}
	key := encodeHashKey(args[0], args[1])

	return hincr(key, 1)
}

// Hincrby will incr number a hashmap value by the key.
// Args: name string, key string, value int
func Hincrby(args [][]byte) (r interface{}, err error) {
	if len(args) < 3 {
		return nil, errNosArgs
	}
	key := encodeHashKey(args[0], args[1])
	i, e := strconv.Atoi(string(args[2]))
	if e != nil {
		return -1, errNotInt
	}

	return hincr(key, i)
}

// Hexists will check the hashmap key is exists.
// Args: name string, key string
func Hexists(args [][]byte) (r interface{}, err error) {
	if len(args) < 2 {
		return nil, errNosArgs
	}

	return
}

// Hsize will return the hashmap size.
// Args: name string
func Hsize(args [][]byte) (r interface{}, err error) {
	if len(args) < 1 {
		return nil, errNosArgs
	}

	var size int64
	if b, e := db.Get(encodeHsizeKey(args[0]), nil); e != nil {
		size = -1
	} else {
		size = int64(bytesToUint32(b))
	}

	return size, nil
}

// Hlist will list all hashmap in the range.
// Args: start string, end string, limit int
func Hlist(args [][]byte) (r []string, err error) {
	if len(args) < 3 {
		return nil, errNosArgs
	}

	return
}

// Hrlist will reverse list all hashmap in the range.
// Args: start string, end string, limit int
func Hrlist(args [][]byte) (r []string, err error) {
	if len(args) < 3 {
		return nil, errNosArgs
	}

	return
}

// Hkeys will list the hashmap keys in the range.
// Args: name string, start string, end string, limit int
func Hkeys(args [][]byte) (r []string, err error) {
	if len(args) < 4 {
		return nil, errNosArgs
	}

	return
}

// Hgetall will list all keys/value in the hashmap.
// Args: name string
func Hgetall(args [][]byte) (r []string, err error) {
	if len(args) < 1 {
		return nil, errNosArgs
	}

	if _, err = db.Get(encodeHsizeKey(args[0]), nil); err != nil {
		return
	}

	var buf []byte
	buf = append(buf, typeHASH)
	buf = append(buf, uint32ToBytes(uint32(len(args[0])))...)
	buf = append(buf, args[0]...)
	ke := append(buf, []byte{0xff}...)

	iter := db.NewIterator(&util.Range{Start: buf, Limit: ke}, nil)
	for iter.Next() {
		_, key := decodeHashKey(iter.Key())
		r = append(r, string(key))
		r = append(r, string(iter.Value()))
	}
	iter.Release()
	err = iter.Error()
	return
}

// Hscan will list keys/value of the hashmap in the range.
// Args: name string, start string, end string, limit int
func Hscan(args [][]byte) (r []string, err error) {
	if len(args) < 4 {
		return nil, errNosArgs
	}

	return
}

// Hrscan will reverse list keys/value of the hashmap in the range.
// Args: name string, start string, end string, limit int
func Hrscan(args [][]byte) (r []string, err error) {
	if len(args) < 4 {
		return nil, errNosArgs
	}

	return
}

// Hclear will remove all value in the hashmap.
// Args: name string
func Hclear(args [][]byte) (r interface{}, err error) {
	if len(args) < 1 {
		return nil, errNosArgs
	}

	return
}

// MultiHget will return multi hashmap value by keys.
func MultiHget(args [][]byte) (r []string, err error) {
	if len(args) < 2 {
		return nil, errNosArgs
	}

	return
}

// MultiHset will set multi hashmap value by keys.
func MultiHset(args [][]byte) (r interface{}, err error) {
	if len(args) < 3 && len(args)%2 == 0 {
		return nil, errNosArgs
	}

	return
}

// MultiHdel will delete multi hashmap value by keys.
func MultiHdel(args [][]byte) (r interface{}, err error) {
	if len(args) < 2 {
		return nil, errNosArgs
	}

	return
}
<commit_msg>Fix bug: hash size not increment.<commit_after>package redlot

import (
	"strconv"

	"github.com/syndtr/goleveldb/leveldb/util"
)

func encodeHashKey(name, key []byte) (buf []byte) {
	buf = append(buf, typeHASH)
	buf = append(buf, uint32ToBytes(uint32(len(name)))...)
	buf = append(buf, name...)
	buf = append(buf, uint32ToBytes(uint32(len(key)))...)
	buf = append(buf, key...)
	return
}

func decodeHashKey(b []byte) (name, key []byte) {
	nameLen := bytesToUint32(b[1:5])
	name = b[5 : 5+nameLen]
	key = b[9+nameLen:]
	return
}

func encodeHsizeKey(name []byte) (buf []byte) {
	buf = append(buf, typeHSIZE)
	buf = append(buf, uint32ToBytes(uint32(len(name)))...)
	buf = append(buf, name...)
	return
}

func decodeHsizeKey(b []byte) (key []byte) {
	return b[5:]
}

func hashSizeIncr(name []byte, incr int) {
	hsize := encodeHsizeKey(name)

	var size uint32
	if b, err := db.Get(hsize, nil); err == nil {
		size = bytesToUint32(b)
	}

	if incr > 0 {
		size += uint32(incr)
	} else {
		size -= uint32(incr)
	}
	db.Put(hsize, uint32ToBytes(size), nil)
}

// Hset will set a hashmap value by the key.
// Args: name string, key string, value any
func Hset(args [][]byte) (r interface{}, err error) {
	if len(args) < 3 {
		return nil, errNosArgs
	}

	hashSizeIncr(args[0], 1)
	err = db.Put(encodeHashKey(args[0], args[1]), args[2], nil)
	if err != nil {
		hashSizeIncr(args[0], -1)
		return nil, err
	}

	return
}

// Hset will return a hashmap value by the key.
// Args: name string, key string
func Hget(args [][]byte) (r interface{}, err error) {
	if len(args) < 2 {
		return nil, errNosArgs
	}
	var b []byte
	b, err = db.Get(encodeHashKey(args[0], args[1]), nil)
	return string(b), err
}

// Hdel will delete a hashmap value by the key.
// Args: name string, key string
func Hdel(args [][]byte) (r interface{}, err error) {
	if len(args) < 2 {
		return nil, errNosArgs
	}

	return
}

func hincr(name, key []byte, increment int) (r int64, err error) {
	hash := encodeHashKey(name, key)
	v, _ := db.Get(hash, nil)
	var number int
	var exists bool
	if len(v) != 0 {
		number, err = strconv.Atoi(string(v))
		exists = true
		if err != nil {
			return -1, errNotInt
		}
	}
	number += increment
	r = int64(number)
	err = db.Put(hash, []byte(strconv.Itoa(number)), nil)
	if err == nil && !exists {
		hashSizeIncr(name, 1)
	}
	return
}

// Hincr will incr a hashmap value by the key.
// Args: name string, key string
func Hincr(args [][]byte) (r interface{}, err error) {
	if len(args) < 2 {
		return nil, errNosArgs
	}

	return hincr(args[0], args[1], 1)
}

// Hincrby will incr number a hashmap value by the key.
// Args: name string, key string, value int
func Hincrby(args [][]byte) (r interface{}, err error) {
	if len(args) < 3 {
		return nil, errNosArgs
	}
	i, e := strconv.Atoi(string(args[2]))
	if e != nil {
		return -1, errNotInt
	}

	return hincr(args[0], args[1], i)
}

// Hexists will check the hashmap key is exists.
// Args: name string, key string
func Hexists(args [][]byte) (r interface{}, err error) {
	if len(args) < 2 {
		return nil, errNosArgs
	}

	return
}

// Hsize will return the hashmap size.
// Args: name string
func Hsize(args [][]byte) (r interface{}, err error) {
	if len(args) < 1 {
		return nil, errNosArgs
	}

	var size int64
	if b, e := db.Get(encodeHsizeKey(args[0]), nil); e != nil {
		size = -1
	} else {
		size = int64(bytesToUint32(b))
	}

	return size, nil
}

// Hlist will list all hashmap in the range.
// Args: start string, end string, limit int
func Hlist(args [][]byte) (r []string, err error) {
	if len(args) < 3 {
		return nil, errNosArgs
	}

	return
}

// Hrlist will reverse list all hashmap in the range.
// Args: start string, end string, limit int
func Hrlist(args [][]byte) (r []string, err error) {
	if len(args) < 3 {
		return nil, errNosArgs
	}

	return
}

// Hkeys will list the hashmap keys in the range.
// Args: name string, start string, end string, limit int
func Hkeys(args [][]byte) (r []string, err error) {
	if len(args) < 4 {
		return nil, errNosArgs
	}

	return
}

// Hgetall will list all keys/value in the hashmap.
// Args: name string
func Hgetall(args [][]byte) (r []string, err error) {
	if len(args) < 1 {
		return nil, errNosArgs
	}

	if _, err = db.Get(encodeHsizeKey(args[0]), nil); err != nil {
		return
	}

	var buf []byte
	buf = append(buf, typeHASH)
	buf = append(buf, uint32ToBytes(uint32(len(args[0])))...)
	buf = append(buf, args[0]...)
	ke := append(buf, []byte{0xff}...)

	iter := db.NewIterator(&util.Range{Start: buf, Limit: ke}, nil)
	for iter.Next() {
		_, key := decodeHashKey(iter.Key())
		r = append(r, string(key))
		r = append(r, string(iter.Value()))
	}
	iter.Release()
	err = iter.Error()
	return
}

// Hscan will list keys/value of the hashmap in the range.
// Args: name string, start string, end string, limit int
func Hscan(args [][]byte) (r []string, err error) {
	if len(args) < 4 {
		return nil, errNosArgs
	}

	return
}

// Hrscan will reverse list keys/value of the hashmap in the range.
// Args: name string, start string, end string, limit int
func Hrscan(args [][]byte) (r []string, err error) {
	if len(args) < 4 {
		return nil, errNosArgs
	}

	return
}

// Hclear will remove all value in the hashmap.
// Args: name string
func Hclear(args [][]byte) (r interface{}, err error) {
	if len(args) < 1 {
		return nil, errNosArgs
	}

	return
}

// MultiHget will return multi hashmap value by keys.
func MultiHget(args [][]byte) (r []string, err error) {
	if len(args) < 2 {
		return nil, errNosArgs
	}

	return
}

// MultiHset will set multi hashmap value by keys.
func MultiHset(args [][]byte) (r interface{}, err error) {
	if len(args) < 3 && len(args)%2 == 0 {
		return nil, errNosArgs
	}

	return
}

// MultiHdel will delete multi hashmap value by keys.
func MultiHdel(args [][]byte) (r interface{}, err error) {
	if len(args) < 2 {
		return nil, errNosArgs
	}

	return
}
<|endoftext|>