<commit_before>// Copyright 2013 beego 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 i18n is for app Internationalization and Localization.
package i18n

import (
	"fmt"
	"reflect"

	"github.com/Unknwon/goconfig"
)

var (
	defautLocale = "en-US"
	message      *goconfig.ConfigFile
)

// SetDefaultLocale sets the default language for localization.
func SetDefaultLocale(locale string) {
	defautLocale = locale
}

// SetMessage sets the message file for localization.
func SetMessage(filePath string) (err error) {
	message, err = goconfig.LoadConfigFile(filePath)
	return err
}

// A Locale describles the information of localization.
type Locale struct {
	CurrentLocale string
}

// Tr translate content to target language.
func Tr(locale, format string, args ...interface{}) string {
	if locale != defautLocale {
		value := message.MustValue(locale, format)
		if value != "" {
			format = value
		}
	}

	if len(args) > 0 {
		params := make([]interface{}, 0, len(args))
		for _, arg := range args {
			if arg != nil {
				val := reflect.ValueOf(arg)
				if val.Kind() == reflect.Slice {
					for i := 0; i < val.Len(); i++ {
						params = append(params, val.Index(i).Interface())
					}
				} else {
					params = append(params, arg)
				}
			}
		}
		return fmt.Sprintf(format, params...)
	}
	return fmt.Sprintf(format)
}

// Tr translate content to target language.
func (l Locale) Tr(format string, args ...interface{}) string {
	return Tr(l.CurrentLocale, format, args...)
}
<commit_msg>support for multi section<commit_after>// Copyright 2013 beego 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 i18n is for app Internationalization and Localization.
package i18n

import (
	"fmt"
	"reflect"

	"github.com/Unknwon/goconfig"
)

var (
	locales localeStore
)

type locale struct {
	lang    string
	message *goconfig.ConfigFile
}

type localeStore []*locale

// Get locale from localeStore use specify lang string
func (d *localeStore) getLocale(lang string) (*locale, bool) {
	for _, l := range locales {
		if l.lang == lang {
			return l, true
		}
	}
	return nil, false
}

// Get target language string
func (d *localeStore) Get(lang, section, format string) (string, bool) {
	if locale, ok := d.getLocale(lang); ok {
		if section == "" {
			section = "common"
		}
		value, err := locale.message.GetValue(section, format)
		if err == nil {
			return value, true
		}
	}
	return "", false
}

// SetMessage sets the message file for localization.
func SetMessage(lang, filePath string) error {
	message, err := goconfig.LoadConfigFile(filePath)
	if err == nil {
		lc := new(locale)
		lc.lang = lang
		lc.message = message
		locales = append(locales, lc)
	}
	return err
}

// A Locale describles the information of localization.
type Locale struct {
	Lang string
}

// Tr translate content to target language.
func (l Locale) Tr(format string, args ...interface{}) string {
	return Tr(l.Lang, format, args...)
}

// Trs translate content to target language with specify section.
func (l Locale) Trs(section, format string, args ...interface{}) string {
	return Trs(l.Lang, section, format, args...)
}

// Tr translate content to target language.
func Tr(lang, format string, args ...interface{}) string {
	return tr(lang, "", format, args...)
}

// Trs translate content to target language with specify section.
func Trs(lang, section, format string, args ...interface{}) string {
	return tr(lang, section, format, args...)
}

func tr(lang, section, format string, args ...interface{}) string {
	value, ok := locales.Get(lang, section, format)
	if ok {
		format = value
	}

	if len(args) > 0 {
		params := make([]interface{}, 0, len(args))
		for _, arg := range args {
			if arg != nil {
				val := reflect.ValueOf(arg)
				if val.Kind() == reflect.Slice {
					for i := 0; i < val.Len(); i++ {
						params = append(params, val.Index(i).Interface())
					}
				} else {
					params = append(params, arg)
				}
			}
		}
		return fmt.Sprintf(format, params...)
	}
	return fmt.Sprintf(format)
}
<|endoftext|>


<commit_before>package app

import (
	"fmt"
	"os"
	"yap/nlp/format/conllu"
	"yap/nlp/format/lattice"
	"yap/nlp/parser/disambig"

	"log"

	"github.com/gonuts/commander"
	"github.com/gonuts/flag"
)

func FuseConfigOut() {
	log.Println("Configuration")
	log.Printf("Use CoNLL-U:\t\t%v", useConllU)
	log.Printf("Limit:\t\t%v", limit)
	log.Println()
	log.Println("Data")
	log.Printf("Test file  (ambig.  lattice):\t%s", input)
	if !VerifyExists(input) {
		return
	}
	if len(inputGold) > 0 {
		log.Printf("Test file  (disambig.  lattice):\t%s", inputGold)
		if !VerifyExists(inputGold) {
			return
		}
	}
	log.Printf("Out (disamb.) file:\t\t\t%s", outMap)
}

func Fuse(cmd *commander.Command, args []string) error {
	REQUIRED_FLAGS := []string{"l", "d", "o"}

	VerifyFlags(cmd, REQUIRED_FLAGS)

	FuseConfigOut()
	SetupEnum([]string{})

	var (
		lAmb  chan lattice.Lattice
		lAmbE error
	)
	if useConllU {
		log.Println("Amb. Lat:\tReading ambiguous conllul lattices from", input)
		lAmb, lAmbE = lattice.StreamULFile(input, limit)
	} else {
		log.Println("Amb. Lat:\tReading ambiguous conllu lattices from", input)
		lAmb, lAmbE = lattice.StreamFile(input, limit)
	}
	if lAmbE != nil {
		log.Println(lAmbE)
		return lAmbE
	}
	log.Println("Streaming to ambiguous lattice conversion")
	predAmbLatStream := lattice.Lattice2SentenceStream(lAmb, EWord, EPOS, EWPOS, EMorphProp, EMHost, EMSuffix)

	log.Println("Streaming disambiguation lattice from", inputGold)
	var lDis chan interface{}
	if useConllU {
		conlluStream, err := conllu.ReadFileAsStream(inputGold, limit)
		if err != nil {
			log.Println(err)
			return err
		}
		lDis = conllu.ConllU2MorphGraphStream(conlluStream, EWord, EPOS, EWPOS, ERel, EMorphProp, EMHost, EMSuffix)
	} else {
		panic("Unsupported")
	}

	log.Println("Fusing streams of gold disambiguation and ambiguous lattices")

	lFused := CombineLatticesStream(lDis, predAmbLatStream)

	log.Println()

	log.Println("Writing to output file", outMap)
	outFile, outFileError := os.Create(outMap)
	if outFileError != nil {
		panic(fmt.Sprintf("Couldn't create output file %s: %s", outMap, outFileError))
	}
	for fusedSent := range lFused {
		mdConfig := fusedSent.(*disambig.MDConfig)
		lat := mdConfig.Lattices
		output := lattice.Sentence2Lattice(lat, nil)
		tokens := make([]string, len(lat))
		for i, tok := range lat {
			tokens[i] = string(tok.Token)
		}
		lattice.UDWrite(outFile, []lattice.Lattice{output}, [][]string{tokens}, nil)
	}

	return nil
}

func FuseCmd() *commander.Command {
	cmd := &commander.Command{
		Run:       Fuse,
		UsageLine: "fuse <file options> [arguments]",
		Short:     "Fuse morphological disambiguations into lattices",
		Long: `
Fuse morphological disambiguations into lattices

	$ ./yap fuse -d <disamb.> -l <amb. lat> -o <out output> [options]

`,
		Flag: *flag.NewFlagSet("md", flag.ExitOnError),
	}
	cmd.Flag.StringVar(&input, "l", "", "Lattices File (.conllul/.lattice)")
	cmd.Flag.StringVar(&inputGold, "d", "", "Morph. Disambigated File (.conll[u])")
	cmd.Flag.StringVar(&outMap, "o", "", "Output Lattice File")
	cmd.Flag.BoolVar(&useConllU, "conllu", true, "use CoNLL-U[L]-format")
	cmd.Flag.IntVar(&limit, "limit", 0, "limit input")
	return cmd
}
<commit_msg>Use a app-specific use-conllu variable for fuse app<commit_after>package app

import (
	"fmt"
	"os"
	"yap/nlp/format/conllu"
	"yap/nlp/format/lattice"
	"yap/nlp/parser/disambig"

	"log"

	"github.com/gonuts/commander"
	"github.com/gonuts/flag"
)

var (
	FUSEuseConLLU bool
)

func FuseConfigOut() {
	log.Println("Configuration")
	log.Printf("Use CoNLL-U:\t\t%v", FUSEuseConLLU)
	log.Printf("Limit:\t\t%v", limit)
	log.Println()
	log.Println("Data")
	log.Printf("Test file  (ambig.  lattice):\t%s", input)
	if !VerifyExists(input) {
		return
	}
	if len(inputGold) > 0 {
		log.Printf("Test file  (disambig.  lattice):\t%s", inputGold)
		if !VerifyExists(inputGold) {
			return
		}
	}
	log.Printf("Out (disamb.) file:\t\t\t%s", outMap)
}

func Fuse(cmd *commander.Command, args []string) error {
	REQUIRED_FLAGS := []string{"l", "d", "o"}

	VerifyFlags(cmd, REQUIRED_FLAGS)

	FuseConfigOut()
	SetupEnum([]string{})

	var (
		lAmb  chan lattice.Lattice
		lAmbE error
	)
	if FUSEuseConLLU {
		log.Println("Amb. Lat:\tReading ambiguous conllul lattices from", input)
		lAmb, lAmbE = lattice.StreamULFile(input, limit)
	} else {
		log.Println("Amb. Lat:\tReading ambiguous conllu lattices from", input)
		lAmb, lAmbE = lattice.StreamFile(input, limit)
	}
	if lAmbE != nil {
		log.Println(lAmbE)
		return lAmbE
	}
	log.Println("Streaming to ambiguous lattice conversion")
	predAmbLatStream := lattice.Lattice2SentenceStream(lAmb, EWord, EPOS, EWPOS, EMorphProp, EMHost, EMSuffix)

	log.Println("Streaming disambiguation lattice from", inputGold)
	var lDis chan interface{}
	if FUSEuseConLLU {
		conlluStream, err := conllu.ReadFileAsStream(inputGold, limit)
		if err != nil {
			log.Println(err)
			return err
		}
		lDis = conllu.ConllU2MorphGraphStream(conlluStream, EWord, EPOS, EWPOS, ERel, EMorphProp, EMHost, EMSuffix)
	} else {
		panic("Unsupported")
	}

	log.Println("Fusing streams of gold disambiguation and ambiguous lattices")

	lFused := CombineLatticesStream(lDis, predAmbLatStream)

	log.Println()

	log.Println("Writing to output file", outMap)
	outFile, outFileError := os.Create(outMap)
	if outFileError != nil {
		panic(fmt.Sprintf("Couldn't create output file %s: %s", outMap, outFileError))
	}
	for fusedSent := range lFused {
		mdConfig := fusedSent.(*disambig.MDConfig)
		lat := mdConfig.Lattices
		output := lattice.Sentence2Lattice(lat, nil)
		tokens := make([]string, len(lat))
		for i, tok := range lat {
			tokens[i] = string(tok.Token)
		}
		lattice.UDWrite(outFile, []lattice.Lattice{output}, [][]string{tokens}, nil)
	}

	return nil
}

func FuseCmd() *commander.Command {
	cmd := &commander.Command{
		Run:       Fuse,
		UsageLine: "fuse <file options> [arguments]",
		Short:     "Fuse morphological disambiguations into lattices",
		Long: `
Fuse morphological disambiguations into lattices

	$ ./yap fuse -d <disamb.> -l <amb. lat> -o <out output> [options]

`,
		Flag: *flag.NewFlagSet("md", flag.ExitOnError),
	}
	cmd.Flag.StringVar(&input, "l", "", "Lattices File (.conllul/.lattice)")
	cmd.Flag.StringVar(&inputGold, "d", "", "Morph. Disambigated File (.conll[u])")
	cmd.Flag.StringVar(&outMap, "o", "", "Output Lattice File")
	cmd.Flag.BoolVar(&FUSEuseConLLU, "conllu", true, "use CoNLL-U[L]-format")
	cmd.Flag.IntVar(&limit, "limit", 0, "limit input")
	return cmd
}
<|endoftext|>


<commit_before>package main

import (
	"log"
	"socialapi/workers/common/runner"
	"socialapi/workers/email/emailsender"

	"github.com/koding/eventexporter"
)

var (
	Name               = "MailSender"
	DefaultQueueLength = 1
)

func main() {
	r := runner.New(Name)
	if err := r.Init(); err != nil {
		log.Fatal(err)
	}

	exporter := eventexporter.NewSegementIOExporter("", DefaultQueueLength)

	constructor := emailsender.New(exporter, r.Log)
	constructor.ForcedRecipient = r.Conf.Email.ForcedRecipient

	r.SetContext(constructor)

	r.Register(emailsender.Mail{}).On(emailsender.SendEmailEventName).Handle(
		(*emailsender.Controller).Process)

	r.Listen()
	r.Wait()
}
<commit_msg>sender: hardcode segment api key for now<commit_after>package main

import (
	"log"
	"socialapi/workers/common/runner"
	"socialapi/workers/email/emailsender"

	"github.com/koding/eventexporter"
)

var (
	Name               = "MailSender"
	DefaultQueueLength = 1

	// TODO: move this to config
	SegmentIOKey = "kb2hfdgf20"
)

func main() {
	r := runner.New(Name)
	if err := r.Init(); err != nil {
		log.Fatal(err)
	}

	exporter := eventexporter.NewSegementIOExporter(SegmentIOKey, DefaultQueueLength)

	constructor := emailsender.New(exporter, r.Log)
	constructor.ForcedRecipient = r.Conf.Email.ForcedRecipient

	r.SetContext(constructor)

	r.Register(emailsender.Mail{}).On(emailsender.SendEmailEventName).Handle(
		(*emailsender.Controller).Process)

	r.Listen()
	r.Wait()
}
<|endoftext|>


<commit_before>package chroot

import (
	"fmt"
	"github.com/mitchellh/packer/packer"
	"io"
	"log"
	"os"
	"os/exec"
	"path/filepath"
	"syscall"
)

// Communicator is a special communicator that works by executing
// commands locally but within a chroot.
type Communicator struct {
	Chroot        string
	ChrootCommand string
	CopyCommand   string
}

func (c *Communicator) Start(cmd *packer.RemoteCmd) error {

	chrootCommand := fmt.Sprintf("%s %s %s", c.ChrootCommand, c.Chroot, cmd.Command)
	localCmd := exec.Command("/bin/sh", "-c", chrootCommand)
	localCmd.Stdin = cmd.Stdin
	localCmd.Stdout = cmd.Stdout
	localCmd.Stderr = cmd.Stderr
	log.Printf("Executing: %s %#v", localCmd.Path, localCmd.Args)
	if err := localCmd.Start(); err != nil {
		return err
	}

	go func() {
		exitStatus := 0
		if err := localCmd.Wait(); err != nil {
			if exitErr, ok := err.(*exec.ExitError); ok {
				exitStatus = 1

				// There is no process-independent way to get the REAL
				// exit status so we just try to go deeper.
				if status, ok := exitErr.Sys().(syscall.WaitStatus); ok {
					exitStatus = status.ExitStatus()
				}
			}
		}

		log.Printf(
			"Chroot executation ended with '%d': '%s'",
			exitStatus, cmd.Command)
		cmd.SetExited(exitStatus)
	}()

	return nil
}

func (c *Communicator) Upload(dst string, r io.Reader) error {
	dst = filepath.Join(c.Chroot, dst)
	log.Printf("Uploading to chroot dir: %s", dst)
	f, err := os.Create(dst)
	if err != nil {
		return err
	}
	defer f.Close()

	if _, err := io.Copy(f, r); err != nil {
		return err
	}

	return nil
}

func (c *Communicator) UploadDir(dst string, src string, exclude []string) error {
	walkFn := func(fullPath string, info os.FileInfo, err error) error {
		if err != nil {
			return err
		}

		path, err := filepath.Rel(src, fullPath)
		if err != nil {
			return err
		}

		for _, e := range exclude {
			if e == path {
				log.Printf("Skipping excluded file: %s", path)
				return nil
			}
		}

		dstPath := filepath.Join(dst, path)
		dst := filepath.Join(c.Chroot, dst)
		log.Printf("Uploading to chroot dir: %s", dst)
		return copySingle(dst, fullPath, c.CopyCommand)
	}

	log.Printf("Uploading directory '%s' to '%s'", src, dst)
	return filepath.Walk(src, walkFn)
}

func (c *Communicator) Download(src string, w io.Writer) error {
	src = filepath.Join(c.Chroot, src)
	log.Printf("Downloading from chroot dir: %s", src)
	f, err := os.Open(src)
	if err != nil {
		return err
	}
	defer f.Close()

	if _, err := io.Copy(w, f); err != nil {
		return err
	}

	return nil
}
<commit_msg>bugfix.<commit_after>package chroot

import (
	"fmt"
	"github.com/mitchellh/packer/packer"
	"io"
	"log"
	"os"
	"os/exec"
	"path/filepath"
	"syscall"
)

// Communicator is a special communicator that works by executing
// commands locally but within a chroot.
type Communicator struct {
	Chroot        string
	ChrootCommand string
	CopyCommand   string
}

func (c *Communicator) Start(cmd *packer.RemoteCmd) error {

	chrootCommand := fmt.Sprintf("%s %s %s", c.ChrootCommand, c.Chroot, cmd.Command)
	localCmd := exec.Command("/bin/sh", "-c", chrootCommand)
	localCmd.Stdin = cmd.Stdin
	localCmd.Stdout = cmd.Stdout
	localCmd.Stderr = cmd.Stderr
	log.Printf("Executing: %s %#v", localCmd.Path, localCmd.Args)
	if err := localCmd.Start(); err != nil {
		return err
	}

	go func() {
		exitStatus := 0
		if err := localCmd.Wait(); err != nil {
			if exitErr, ok := err.(*exec.ExitError); ok {
				exitStatus = 1

				// There is no process-independent way to get the REAL
				// exit status so we just try to go deeper.
				if status, ok := exitErr.Sys().(syscall.WaitStatus); ok {
					exitStatus = status.ExitStatus()
				}
			}
		}

		log.Printf(
			"Chroot executation ended with '%d': '%s'",
			exitStatus, cmd.Command)
		cmd.SetExited(exitStatus)
	}()

	return nil
}

func (c *Communicator) Upload(dst string, r io.Reader) error {
	dst = filepath.Join(c.Chroot, dst)
	log.Printf("Uploading to chroot dir: %s", dst)
	f, err := os.Create(dst)
	if err != nil {
		return err
	}
	defer f.Close()

	if _, err := io.Copy(f, r); err != nil {
		return err
	}

	return nil
}

func (c *Communicator) UploadDir(dst string, src string, exclude []string) error {
	walkFn := func(fullPath string, info os.FileInfo, err error) error {
		if err != nil {
			return err
		}

		path, err := filepath.Rel(src, fullPath)
		if err != nil {
			return err
		}

		for _, e := range exclude {
			if e == path {
				log.Printf("Skipping excluded file: %s", path)
				return nil
			}
		}

		chrootDest := filepath.Join(c.Chroot, dst, path)
		log.Printf("Uploading to chroot dir: %s", dst)
		return copySingle(chrootDest, fullPath, c.CopyCommand)
	}

	log.Printf("Uploading directory '%s' to '%s'", src, dst)
	return filepath.Walk(src, walkFn)
}

func (c *Communicator) Download(src string, w io.Writer) error {
	src = filepath.Join(c.Chroot, src)
	log.Printf("Downloading from chroot dir: %s", src)
	f, err := os.Open(src)
	if err != nil {
		return err
	}
	defer f.Close()

	if _, err := io.Copy(w, f); err != nil {
		return err
	}

	return nil
}
<|endoftext|>


<commit_before>package virtualbox

import (
	"fmt"
	"github.com/mitchellh/multistep"
	"github.com/mitchellh/packer/packer"
)

// This step attaches the ISO to the virtual machine.
//
// Uses:
//
// Produces:
type stepAttachISO struct {
	diskPath string
}

func (s *stepAttachISO) Run(state multistep.StateBag) multistep.StepAction {
	driver := state.Get("driver").(Driver)
	isoPath := state.Get("iso_path").(string)
	ui := state.Get("ui").(packer.Ui)
	vmName := state.Get("vmName").(string)

	// Attach the disk to the controller
	command := []string{
		"storageattach", vmName,
		"--storagectl", "IDE Controller",
		"--port", "0",
		"--device", "1",
		"--type", "dvddrive",
		"--medium", isoPath,
	}
	if err := driver.VBoxManage(command...); err != nil {
		err := fmt.Errorf("Error attaching ISO: %s", err)
		state.Put("error", err)
		ui.Error(err.Error())
		return multistep.ActionHalt
	}

	// Track the path so that we can unregister it from VirtualBox later
	s.diskPath = isoPath

	return multistep.ActionContinue
}

func (s *stepAttachISO) Cleanup(state multistep.StateBag) {
	if s.diskPath == "" {
		return
	}

	driver := state.Get("driver").(Driver)
	ui := state.Get("ui").(packer.Ui)
	vmName := state.Get("vmName").(string)

	command := []string{
		"storageattach", vmName,
		"--storagectl", "IDE Controller",
		"--port", "0",
		"--device", "1",
		"--medium", "none",
	}

	// Remove the ISO. Note that this will probably fail since
	// stepRemoveDevices does this as well. No big deal.
	driver.VBoxManage(command...)
}
<commit_msg>builder/virtualbox: fix compilation<commit_after>package virtualbox

import (
	"fmt"
	"github.com/mitchellh/multistep"
	"github.com/mitchellh/packer/packer"
)

// This step attaches the ISO to the virtual machine.
//
// Uses:
//
// Produces:
type stepAttachISO struct {
	diskPath string
}

func (s *stepAttachISO) Run(state multistep.StateBag) multistep.StepAction {
	driver := state.Get("driver").(Driver)
	isoPath := state.Get("iso_path").(string)
	ui := state.Get("ui").(packer.Ui)
	vmName := state.Get("vmName").(string)

	// Attach the disk to the controller
	command := []string{
		"storageattach", vmName,
		"--storagectl", "IDE Controller",
		"--port", "0",
		"--device", "1",
		"--type", "dvddrive",
		"--medium", isoPath,
	}
	if err := driver.VBoxManage(command...); err != nil {
		err := fmt.Errorf("Error attaching ISO: %s", err)
		state.Put("error", err)
		ui.Error(err.Error())
		return multistep.ActionHalt
	}

	// Track the path so that we can unregister it from VirtualBox later
	s.diskPath = isoPath

	return multistep.ActionContinue
}

func (s *stepAttachISO) Cleanup(state multistep.StateBag) {
	if s.diskPath == "" {
		return
	}

	driver := state.Get("driver").(Driver)
	vmName := state.Get("vmName").(string)

	command := []string{
		"storageattach", vmName,
		"--storagectl", "IDE Controller",
		"--port", "0",
		"--device", "1",
		"--medium", "none",
	}

	// Remove the ISO. Note that this will probably fail since
	// stepRemoveDevices does this as well. No big deal.
	driver.VBoxManage(command...)
}
<|endoftext|>


<commit_before>package toscalib

type Playbook struct {
	AdjacencyMatrix Matrix
	Index           map[int]Play
	Inputs          map[string]PropertyDefinition
	Outputs         map[string]Output
}

type Play struct {
	NodeTemplate  NodeTemplate
	OperationName string
}

func GeneratePlaybook(s ServiceTemplateDefinition) Playbook {
	var e Playbook
	i := 0
	index := make(map[int]Play, 0)
	for _, node := range s.TopologyTemplate.NodeTemplates {
		for _, intf := range node.Interfaces {
			for op, _ := range intf.Operations {
				index[i] = Play{node, op}
				i += 1
			}
		}
	}
	e.Index = index
	e.Inputs = s.TopologyTemplate.Inputs
	e.Outputs = s.TopologyTemplate.Outputs
	return e
}
<commit_msg>[Enhancement] Add the interface name for comodity<commit_after>package toscalib

type Playbook struct {
	AdjacencyMatrix Matrix
	Index           map[int]Play
	Inputs          map[string]PropertyDefinition
	Outputs         map[string]Output
}

type Play struct {
	NodeTemplate  NodeTemplate
	InterfaceName string
	OperationName string
}

func GeneratePlaybook(s ServiceTemplateDefinition) Playbook {
	var e Playbook
	i := 0
	index := make(map[int]Play, 0)
	for _, node := range s.TopologyTemplate.NodeTemplates {
		for intfn, intf := range node.Interfaces {
			for op, _ := range intf.Operations {
				index[i] = Play{node, intfn, op}
				i += 1
			}
		}
	}
	e.Index = index
	e.Inputs = s.TopologyTemplate.Inputs
	e.Outputs = s.TopologyTemplate.Outputs
	return e
}
<|endoftext|>


<commit_before>// Package main provides ...
package main

import (
	"encoding/hex"
	"flag"
	"fmt"
	"time"

	log "github.com/cihub/seelog"
	"github.com/jonaz/goenocean"
	"github.com/stampzilla/stampzilla-go/nodes/basenode"
	"github.com/stampzilla/stampzilla-go/protocol"
)

var node *protocol.Node
var state *State
var serverSendChannel chan interface{}
var serverRecvChannel chan protocol.Command

func init() {
	var host string
	var port string
	flag.StringVar(&host, "host", "192.168.13.2", "Server host/ip")
	flag.StringVar(&port, "port", "8282", "Server port")

	flag.Parse()

	//Setup Config
	config := &basenode.Config{
		Host: host,
		Port: port}

	basenode.SetConfig(config)

	//Start communication with the server
	serverSendChannel = make(chan interface{})
	serverRecvChannel = make(chan protocol.Command)
	connectionState := basenode.Connect(serverSendChannel, serverRecvChannel)
	go monitorState(connectionState, serverSendChannel)
	go serverRecv(serverRecvChannel)

}

func main() {

	node = protocol.NewNode("enocean")
	// Describe available actions
	node.AddAction("set", "Set", []string{"Devices.Id"})
	node.AddAction("toggle", "Toggle", []string{"Devices.Id"})
	node.AddAction("dim", "Dim", []string{"Devices.Id", "value"})

	// Describe available layouts
	node.AddLayout("1", "switch", "toggle", "Devices", []string{"on"}, "Switches")
	node.AddLayout("2", "slider", "dim", "Devices", []string{"dim"}, "Dimmers")
	node.AddLayout("3", "slider", "dim", "Devices", []string{"dim"}, "Specials")

	state = NewState()
	//state.AddDevice([4]byte{1, 2, 3, 4}, "Testdevice", []string{"asdf"}, "off")
	node.SetState(state)

	setupEepHandlers()

	setupEnoceanCommunication()
}

func monitorState(connectionState chan int, send chan interface{}) {
	for s := range connectionState {
		switch s {
		case basenode.ConnectionStateConnected:
			send <- node
		case basenode.ConnectionStateDisconnected:
		}
	}
}

func serverRecv(recv chan protocol.Command) {

	for d := range recv {
		processCommand(d)
	}

}

func processCommand(cmd protocol.Command) {
	log.Error("INCOMING COMMAND", cmd)
}

func setupEnoceanCommunication() {
	send := make(chan goenocean.Encoder)
	recv := make(chan goenocean.Packet)
	goenocean.Serial(send, recv)

	//go testSend(send)
	//testLearn4bs(send)
	testSenda53808(send)
	reciever(recv)
}

func testLearn4bs(send chan goenocean.Encoder) {
	p := goenocean.NewTelegram4bsLearn()
	p.SetLearnFunc(0x38)
	p.SetLearnType(0x08)

	// OMG THIS WORKS :D:D
	fmt.Printf("Sending: % x\n", p.Encode())
	send <- p
}
func testSenda53808(send chan goenocean.Encoder) {
	p := goenocean.NewEepA53808()
	p.SetDestinationId([4]byte{0x01, 0x86, 0xff, 0x7d})
	p.SetCommand(2)
	//PERMUNDO only supports 0 = off on = 1-255
	p.SetDimValue(1)
	fmt.Printf("Sending: % x\n", p.Encode())
	send <- p

	p.SetDimValue(0)
	time.Sleep(time.Second * 1)
	send <- p

}
func testSendWorking(send chan goenocean.Encoder) {
	p := goenocean.NewTelegramRps()
	p.SetTelegramData([]byte{0x50}) //on
	//p.SetStatus(0x30) //testing shows this does not need to be set! Status defaults to 0

	fmt.Printf("Sending: % x\n", p.Encode())
	send <- p

	//time.Sleep(time.Second * 3)
	//p.SetTelegramData([]byte{0x70}) //off
	//send <- p
}

func reciever(recv chan goenocean.Packet) {
	for p := range recv {
		if p.SenderId() != [4]byte{0, 0, 0, 0} {
			incomingPacket(p)
		}
	}
}

func incomingPacket(p goenocean.Packet) {

	var d *Device
	if d = state.Device(p.SenderId()); d == nil {
		//Add unknown device
		d = state.AddDevice(p.SenderId(), "UNKNOWN", nil, "")

		//TODO save this to json file and read it back on start
		if d.Id() == "0186ff7d" {
			d.AddEep("a51201")
			d.AddEep("d20109")
		}
		serverSendChannel <- node
	}

	if t, ok := p.(goenocean.Telegram); ok {
		for _, deviceEep := range d.EEPs {
			if deviceEep[0:2] != hex.EncodeToString([]byte{t.TelegramType()}) {
				continue
			}

			if h := handlers.getHandler(deviceEep); h != nil {
				h(d, t)
			}
		}
	}

}
<commit_msg>new send flow<commit_after>// Package main provides ...
package main

import (
	"encoding/hex"
	"flag"
	"fmt"
	"time"

	log "github.com/cihub/seelog"
	"github.com/jonaz/goenocean"
	"github.com/stampzilla/stampzilla-go/nodes/basenode"
	"github.com/stampzilla/stampzilla-go/protocol"
)

var node *protocol.Node
var state *State
var serverSendChannel chan interface{}
var serverRecvChannel chan protocol.Command

func init() {
	var host string
	var port string
	flag.StringVar(&host, "host", "192.168.13.2", "Server host/ip")
	flag.StringVar(&port, "port", "8282", "Server port")

	flag.Parse()

	//Setup Config
	config := &basenode.Config{
		Host: host,
		Port: port}

	basenode.SetConfig(config)

	//Start communication with the server
	serverSendChannel = make(chan interface{})
	serverRecvChannel = make(chan protocol.Command)
	connectionState := basenode.Connect(serverSendChannel, serverRecvChannel)
	go monitorState(connectionState, serverSendChannel)
	go serverRecv(serverRecvChannel)

}

func main() {

	node = protocol.NewNode("enocean")
	// Describe available actions
	node.AddAction("set", "Set", []string{"Devices.Id"})
	node.AddAction("toggle", "Toggle", []string{"Devices.Id"})
	node.AddAction("dim", "Dim", []string{"Devices.Id", "value"})

	// Describe available layouts
	node.AddLayout("1", "switch", "toggle", "Devices", []string{"on"}, "Switches")
	node.AddLayout("2", "slider", "dim", "Devices", []string{"dim"}, "Dimmers")
	node.AddLayout("3", "slider", "dim", "Devices", []string{"dim"}, "Specials")

	state = NewState()
	//state.AddDevice([4]byte{1, 2, 3, 4}, "Testdevice", []string{"asdf"}, "off")
	node.SetState(state)

	setupEepHandlers()

	setupEnoceanCommunication()
}

func monitorState(connectionState chan int, send chan interface{}) {
	for s := range connectionState {
		switch s {
		case basenode.ConnectionStateConnected:
			send <- node
		case basenode.ConnectionStateDisconnected:
		}
	}
}

func serverRecv(recv chan protocol.Command) {

	for d := range recv {
		processCommand(d)
	}

}

func processCommand(cmd protocol.Command) {
	log.Error("INCOMING COMMAND", cmd)
}

func setupEnoceanCommunication() {
	send := make(chan goenocean.Request)
	recv := make(chan goenocean.Packet)
	goenocean.Serial(send, recv)

	//go testSend(send)
	//testLearn4bs(send)
	testSenda53808(send)
	reciever(recv)
}

func testLearn4bs(send chan goenocean.Request) {
	p := goenocean.NewTelegram4bsLearn()
	p.SetLearnFunc(0x38)
	p.SetLearnType(0x08)

	// OMG THIS WORKS :D:D
	fmt.Printf("Sending: % x\n", p.Encode())
	send <- goenocean.NewRequest(p)
}
func testSenda53808(send chan goenocean.Request) {
	p := goenocean.NewEepA53808()
	p.SetDestinationId([4]byte{0x01, 0x86, 0xff, 0x7d})
	p.SetCommand(2)
	//PERMUNDO only supports 0 = off on = 1-255
	p.SetDimValue(1)
	fmt.Printf("Sending: % x\n", p.Encode())
	send <- goenocean.NewRequest(p)

	p.SetDimValue(0)
	time.Sleep(time.Second * 1)
	send <- goenocean.NewRequest(p)

}
func testSendWorking(send chan goenocean.Encoder) {
	p := goenocean.NewTelegramRps()
	p.SetTelegramData([]byte{0x50}) //on
	//p.SetStatus(0x30) //testing shows this does not need to be set! Status defaults to 0

	fmt.Printf("Sending: % x\n", p.Encode())
	send <- p

	//time.Sleep(time.Second * 3)
	//p.SetTelegramData([]byte{0x70}) //off
	//send <- p
}

func reciever(recv chan goenocean.Packet) {
	for p := range recv {
		if p.SenderId() != [4]byte{0, 0, 0, 0} {
			incomingPacket(p)
		}
	}
}

func incomingPacket(p goenocean.Packet) {

	var d *Device
	if d = state.Device(p.SenderId()); d == nil {
		//Add unknown device
		d = state.AddDevice(p.SenderId(), "UNKNOWN", nil, "")

		//TODO save this to json file and read it back on start
		if d.Id() == "0186ff7d" {
			d.AddEep("a51201")
			d.AddEep("d20109")
		}
		serverSendChannel <- node
	}

	if t, ok := p.(goenocean.Telegram); ok {
		for _, deviceEep := range d.EEPs {
			if deviceEep[0:2] != hex.EncodeToString([]byte{t.TelegramType()}) {
				continue
			}

			if h := handlers.getHandler(deviceEep); h != nil {
				h(d, t)
			}
		}
	}

}
<|endoftext|>


<commit_before>package main

import (
	"log"
	"net/http"

	"github.com/gorilla/mux"
	x "github.com/javinc/puto"
	"github.com/javinc/puto/index"
	"github.com/javinc/puto/test"
)

// port server
const port = "8000"

func main() {
	m := mux.NewRouter()
	// Routes consist of a path and a handler function.
	m.HandleFunc("/", index.Handler)
	m.HandleFunc("/test", test.Handler)
	m.HandleFunc("/test/{id:[0-9]+}", test.Handler)

	// Migrates Db
	x.MySQL.AutoMigrate(&test.Model)

	// Bind to a port and pass our router in
	log.Println("serving on port", port)
	http.ListenAndServe(":"+port, m)
}
<commit_msg>require id on DELETE and PUT method<commit_after>package main

import (
	"log"
	"net/http"

	"github.com/gorilla/mux"
	x "github.com/javinc/puto"
	"github.com/javinc/puto/index"
	"github.com/javinc/puto/test"
	"github.com/javinc/puto/user"
)

// port server
const port = "8000"

func main() {
	m := mux.NewRouter()

	// Routes consist of a path and a handler function.
	m.HandleFunc("/", index.Handler)
	m.HandleFunc("/test", test.Handler)
	m.HandleFunc("/test/{id:[0-9]+}", test.Handler)
	m.HandleFunc("/user", user.Handler)
	m.HandleFunc("/user/{id:[0-9]+}", user.Handler)

	// Migrates Db
	x.MySQL.AutoMigrate(
		&test.Model,
		&user.Model,
	)

	// Bind to a port and pass our router in
	log.Println("serving on port", port)
	http.ListenAndServe(":"+port, m)
}
<|endoftext|>


<commit_before>package main

import (
	"bytes"
	"code.google.com/p/go.crypto/ssh"
	"encoding/json"
	"errors"
	"flag"
	"fmt"
	"io/ioutil"
	"log"
	"net"
	"net/http"
	"net/url"
	"os"
	"os/signal"
	"path/filepath"
	"syscall"
	"time"
)

var PORT string
var HOST string
var LISTEN string
var RASPIP string

// message to send to stop media
const stopbody = `{"id":1,"jsonrpc":"2.0","method":"Player.Stop","params":{"playerid": %d}}`

// get player id
const getplayer = `{"id":1, "jsonrpc":"2.0","method":"Player.GetActivePlayers"}`

// the message to lauch local media
const body = `{
	"id":1,"jsonrpc":"2.0",
	"method":"Player.Open",
	"params": {
		"item": {
		   "file": "%s"
		 }
	 }
 }`

// response of get players
type itemresp struct {
	Id      int
	Jsonrpc string
	Result  []map[string]interface{}
}

// return active player from XBMC
func getActivePlayer() *itemresp {
	r, _ := http.Post(HOST, "application/json", bytes.NewBufferString(getplayer))
	response, _ := ioutil.ReadAll(r.Body)
	resp := &itemresp{}
	resp.Result = make([]map[string]interface{}, 0)
	json.Unmarshal(response, resp)
	return resp
}

// test if media is playing, if not then quit
func checkPlaying() {

	tick := time.Tick(1 * time.Second)
	for _ = range tick {
		resp := getActivePlayer()
		if len(resp.Result) == 0 {
			os.Exit(0)
		}
	}

}

// when quiting (CTRL+C for example) - tell to XBMC to stop
func onQuit() {
	c := make(chan os.Signal, 1)
	signal.Notify(c, syscall.SIGTERM, syscall.SIGINT)

	select {
	case <-c:
		fmt.Println("Quiting")
		resp := getActivePlayer()
		var playerid int
		for _, result := range resp.Result {
			for key, val := range result {
				if key == "playerid" {
					playerid = int(val.(float64))
				}
			}
		}

		http.Post(HOST, "application/json", bytes.NewBufferString(fmt.Sprintf(stopbody, playerid)))
		os.Exit(0)
	}
}

// begin to locally listen http to serve media
func send(host, file string, port int) {

	u := url.URL{Path: file}
	file = u.String()
	//_body := fmt.Sprintf(body, "http://"+LISTEN+":"+PORT+"/"+file)
	addr := fmt.Sprintf("http://%s:%d/%s", host, port, file)
	_body := fmt.Sprintf(body, addr)

	r, err := http.Post(HOST, "application/json", bytes.NewBufferString(_body))
	if err != nil {
		log.Fatal(err)
	}
	response, _ := ioutil.ReadAll(r.Body)
	log.Println(string(response))
}

func getLocalInterfaceIP() (string, error) {
	ips, _ := net.LookupIP(RASPIP)
	for _, ip := range ips {
		mask := ip.DefaultMask()
		ifaces, err := net.Interfaces()
		if err != nil {
			log.Fatalf("Error while checking you interfaces: %v", err)
		}
		log.Println(ifaces)
		for _, iface := range ifaces {
			if iface.Flags&net.FlagLoopback != 0 {
				continue
			}

			addrs, _ := iface.Addrs()
			for _, addr := range addrs {
				switch v := addr.(type) {
				case *net.IPNet:
					if v.Mask.String() == mask.String() {
						return v.IP.String(), nil
					}
				}

			}
		}
	}
	return "", errors.New("Unable to get local ip")
}

func httpserve(file, dir string, port int) {

	localip, err := getLocalInterfaceIP()
	log.Println(localip)
	if err != nil {
		log.Fatal(err)
	}
	http.Handle("/", http.FileServer(http.Dir(dir)))

	// send xbmc the file query
	go send(localip, file, port)

	// handle CTRL+C to stop
	go onQuit()

	// and wait media end
	go checkPlaying()

	http.ListenAndServe(fmt.Sprintf("0.0.0.0:%d", port), nil)
}

func sshforward(config *ssh.ClientConfig, file, dir string) {

	// Setup sshClientConn (type *ssh.ClientConn)
	sshClientConn, err := ssh.Dial("tcp", RASPIP+":22", config)
	if err != nil {
		log.Fatal(err)
	}

	// Setup sshConn (type net.Conn)
	sshConn, err := sshClientConn.Listen("tcp", "127.0.0.1:0")
	addr := sshConn.Addr()
	port := addr.(*net.TCPAddr).Port
	log.Println("Listening port on raspberry: ", port)

	// send xbmc the file query
	go send("localhost", file, port)
	// handle CTRL+C to stop
	go onQuit()
	// and wait media end
	go checkPlaying()

	// now serve file
	http.Serve(sshConn, http.FileServer(http.Dir(dir)))
}

func main() {

	// flags
	xbmcaddr := flag.String("target", "", "xbmc/kodi ip (raspbmc address, ip or hostname)")
	username := flag.String("login", "", "jsonrpc login (configured in xbmc settings)")
	password := flag.String("password", "", "jsonrpc password (configured in xbmc settings)")
	viassh := flag.Bool("ssh", false, "Use SSH Tunnelling (need ssh user and password)")
	port := flag.Int("port", 8080, "local port (ignored if you use ssh option)")
	sshuser := flag.String("sshuser", "pi", "ssh login")
	sshpassword := flag.String("sshpass", "raspberry", "ssh password")

	flag.Parse()

	if *xbmcaddr == "" {
		fmt.Println("You must provide the xbmc server address")
		os.Exit(1)
	}

	HOST = *xbmcaddr
	RASPIP = *xbmcaddr

	// XBMC can be configured to have username/password
	if *username != "" {
		HOST = *username + ":" + *password + "@" + HOST
	}
	HOST = "http://" + HOST + "/jsonrpc"

	if len(flag.Args()) < 1 {
		fmt.Println("You must provide a file to serve")
		os.Exit(2)
	}

	// find the good path
	toserve := flag.Arg(0)
	dir := "."
	toserve, _ = filepath.Abs(toserve)
	file := filepath.Base(toserve)
	dir = filepath.Dir(toserve)

	if *viassh {
		config := &ssh.ClientConfig{
			User: *sshuser,
			Auth: []ssh.AuthMethod{
				ssh.Password(*sshpassword),
			},
		}

		// serve !
		sshforward(config, file, dir)
	} else {
		httpserve(file, dir, *port)
	}
}
<commit_msg>Now, we serve only the requested file<commit_after>package main

import (
	"bytes"
	"code.google.com/p/go.crypto/ssh"
	"encoding/json"
	"errors"
	"flag"
	"fmt"
	"io/ioutil"
	"log"
	"net"
	"net/http"
	"net/url"
	"os"
	"os/signal"
	"path/filepath"
	"syscall"
	"time"
)

var PORT string
var HOST string
var LISTEN string
var RASPIP string
var SSHPORT int

// message to send to stop media
const stopbody = `{"id":1,"jsonrpc":"2.0","method":"Player.Stop","params":{"playerid": %d}}`

// get player id
const getplayer = `{"id":1, "jsonrpc":"2.0","method":"Player.GetActivePlayers"}`

// the message to lauch local media
const body = `{
	"id":1,"jsonrpc":"2.0",
	"method":"Player.Open",
	"params": {
		"item": {
		   "file": "%s"
		 }
	 }
 }`

// response of get players
type itemresp struct {
	Id      int
	Jsonrpc string
	Result  []map[string]interface{}
}

// return active player from XBMC
func getActivePlayer() *itemresp {
	r, _ := http.Post(HOST, "application/json", bytes.NewBufferString(getplayer))
	response, _ := ioutil.ReadAll(r.Body)
	resp := &itemresp{}
	resp.Result = make([]map[string]interface{}, 0)
	json.Unmarshal(response, resp)
	return resp
}

// test if media is playing, if not then quit
func checkPlaying() {

	tick := time.Tick(3 * time.Second)
	for _ = range tick {
		resp := getActivePlayer()
		if len(resp.Result) == 0 {
			os.Exit(0)
		}
	}

}

// when quiting (CTRL+C for example) - tell to XBMC to stop
func onQuit() {
	c := make(chan os.Signal, 1)
	signal.Notify(c, syscall.SIGTERM, syscall.SIGINT)

	select {
	case <-c:
		fmt.Println("Quiting")
		resp := getActivePlayer()
		var playerid int
		for _, result := range resp.Result {
			for key, val := range result {
				if key == "playerid" {
					playerid = int(val.(float64))
				}
			}
		}

		http.Post(HOST, "application/json", bytes.NewBufferString(fmt.Sprintf(stopbody, playerid)))
		os.Exit(0)
	}
}

// begin to locally listen http to serve media
func send(host, file string, port int) {

	u := url.URL{Path: file}
	file = u.String()
	//_body := fmt.Sprintf(body, "http://"+LISTEN+":"+PORT+"/"+file)
	addr := fmt.Sprintf("http://%s:%d/%s", host, port, file)
	_body := fmt.Sprintf(body, addr)

	r, err := http.Post(HOST, "application/json", bytes.NewBufferString(_body))
	if err != nil {
		log.Fatal(err)
	}
	response, _ := ioutil.ReadAll(r.Body)
	log.Println(string(response))
}

func getLocalInterfaceIP() (string, error) {
	ips, _ := net.LookupIP(RASPIP)
	for _, ip := range ips {
		mask := ip.DefaultMask()
		ifaces, err := net.Interfaces()
		if err != nil {
			log.Fatalf("Error while checking you interfaces: %v", err)
		}
		log.Println(ifaces)
		for _, iface := range ifaces {
			if iface.Flags&net.FlagLoopback != 0 {
				continue
			}

			addrs, _ := iface.Addrs()
			for _, addr := range addrs {
				switch v := addr.(type) {
				case *net.IPNet:
					if v.Mask.String() == mask.String() {
						return v.IP.String(), nil
					}
				}

			}
		}
	}
	return "", errors.New("Unable to get local ip")
}

func httpserve(file, dir string, port int) {

	localip, err := getLocalInterfaceIP()
	log.Println(localip)
	if err != nil {
		log.Fatal(err)
	}

	// handle file http response
	fullpath := filepath.Join(dir, file)
	http.Handle("/", http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		http.ServeFile(w, r, fullpath)
	}))

	// send xbmc the file query
	go send(localip, file, port)

	// handle CTRL+C to stop
	go onQuit()

	// and wait media end
	go checkPlaying()

	http.ListenAndServe(fmt.Sprintf("0.0.0.0:%d", port), nil)
}

func sshforward(config *ssh.ClientConfig, file, dir string) {

	// Setup sshClientConn (type *ssh.ClientConn)
	sshClientConn, err := ssh.Dial("tcp", fmt.Sprintf("%s:%d", RASPIP, SSHPORT), config)
	if err != nil {
		log.Fatal(err)
	}

	// Setup sshConn (type net.Conn)
	sshConn, err := sshClientConn.Listen("tcp", "127.0.0.1:0")
	addr := sshConn.Addr()
	port := addr.(*net.TCPAddr).Port
	log.Println("Listening port on raspberry: ", port)

	// send xbmc the file query
	go send("localhost", file, port)
	// handle CTRL+C to stop
	go onQuit()
	// and wait media end
	go checkPlaying()

	// now serve file
	fullpath := filepath.Join(dir, file)
	http.Serve(sshConn, http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		http.ServeFile(w, r, fullpath)
	}))
}

func main() {

	// flags
	xbmcaddr := flag.String("target", "", "xbmc/kodi ip (raspbmc address, ip or hostname)")
	username := flag.String("login", "", "jsonrpc login (configured in xbmc settings)")
	password := flag.String("password", "", "jsonrpc password (configured in xbmc settings)")
	viassh := flag.Bool("ssh", false, "Use SSH Tunnelling (need ssh user and password)")
	port := flag.Int("port", 8080, "local port (ignored if you use ssh option)")
	sshuser := flag.String("sshuser", "pi", "ssh login")
	sshpassword := flag.String("sshpass", "raspberry", "ssh password")
	sshport := flag.Int("sshport", 22, "target ssh port")

	flag.Parse()

	if *xbmcaddr == "" {
		fmt.Println("You must provide the xbmc server address")
		os.Exit(1)
	}

	HOST = *xbmcaddr
	RASPIP = *xbmcaddr
	SSHPORT = *sshport

	// XBMC can be configured to have username/password
	if *username != "" {
		HOST = *username + ":" + *password + "@" + HOST
	}
	HOST = "http://" + HOST + "/jsonrpc"

	if len(flag.Args()) < 1 {
		fmt.Println("You must provide a file to serve")
		os.Exit(2)
	}

	// find the good path
	toserve := flag.Arg(0)
	dir := "."
	toserve, _ = filepath.Abs(toserve)
	file := filepath.Base(toserve)
	dir = filepath.Dir(toserve)

	if *viassh {
		config := &ssh.ClientConfig{
			User: *sshuser,
			Auth: []ssh.AuthMethod{
				ssh.Password(*sshpassword),
			},
		}

		// serve !
		sshforward(config, file, dir)
	} else {
		httpserve(file, dir, *port)
	}
}
<|endoftext|>


<commit_before>// Copyright 2014 by caixw, All rights reserved.
// Use of this source code is governed by a MIT
// license that can be found in the LICENSE file.

package orm

import (
	"bytes"
	"database/sql"
	"errors"
	"fmt"
	"reflect"

	"github.com/issue9/orm/fetch"
)

// DB与Tx的共有接口，方便以下方法调用。
type engine interface {
	Dialect() Dialect
	Query(replace bool, query string, args ...interface{}) (*sql.Rows, error)
	Exec(replace bool, query string, args ...interface{}) (sql.Result, error)
	Prepare(replace bool, query string) (*sql.Stmt, error)
	Prefix() string
}

// 检测rval中与cols对应的字段都是有效的，且为非零值。
// 若cols的长度为0，返回false。
func checkCols(cols []*Column, rval reflect.Value) bool {
	if len(cols) == 0 {
		return false
	}

	for _, col := range cols {
		field := rval.FieldByName(col.GoName)
		if !field.IsValid() {
			return false
		}

		if reflect.Zero(col.GoType).Interface() == field.Interface() {
			return false
		}
	}
	return true
}

// 根据model中的主键或是唯一索引为sql产生where语句，
// 若两者都不存在，则返回错误信息。rval为struct的reflect.Value
func where(e engine, sql *bytes.Buffer, m *Model, rval reflect.Value) ([]interface{}, error) {
	ret := []interface{}{}

	if checkCols(m.PK, rval) {
		sql.WriteString(" WHERE ")
		for _, col := range m.PK {
			e.Dialect().Quote(sql, col.Name)
			sql.WriteString("=?")
			ret = append(ret, rval.FieldByName(col.GoName).Interface())
		}
		return ret, nil
	}

	// 若不存在pk，也不存在唯一约束
	for _, cols := range m.UniqueIndexes {
		if !checkCols(cols, rval) {
			continue
		}

		sql.WriteString(" WHERE ")
		for _, col := range cols {
			e.Dialect().Quote(sql, col.Name)
			sql.WriteString("=?")
			ret = append(ret, rval.FieldByName(col.GoName).Interface())
			sql.WriteString(" AND ")
		}
		sql.Truncate(sql.Len() - 5) // 去掉最后的" AND "五个字符
		return ret, nil
	} // end range m.UniqueIndexes

	return nil, errors.New("where:无法产生where部分语句")
}

// 根据v的pk或中唯一索引列查找一行数据，并赋值给v
func findOne(e engine, v interface{}) error {
	m, err := newModel(v)
	if err != nil {
		return err
	}

	rval := reflect.ValueOf(v)
	for rval.Kind() == reflect.Ptr {
		rval = rval.Elem()
	}

	if rval.Kind() != reflect.Struct {
		return errors.New("findOne:无效的v.Kind()")
	}

	sql := bytes.NewBufferString("SELECT * FROM ")
	e.Dialect().Quote(sql, e.Prefix()+m.Name)

	vals, err := where(e, sql, m, rval)
	if err != nil {
		return err
	}

	rows, err := e.Query(false, sql.String(), vals...)
	if err != nil {
		return err
	}
	defer rows.Close()

	return fetch.Obj(v, rows)
}

// 插入一个对象到数据库
// 以v中的主键或是唯一索引作为where条件语句。
// 自增字段，即使指定了值，也不会被添加
func insertOne(e engine, v interface{}) error {
	m, err := newModel(v)
	if err != nil {
		return err
	}

	rval := reflect.ValueOf(v)
	for rval.Kind() == reflect.Ptr {
		rval = rval.Elem()
	}

	if rval.Kind() != reflect.Struct {
		return errors.New("insertOne:无效的v.Kind()")
	}

	keys := make([]string, 0, len(m.Cols))
	vals := make([]interface{}, 0, len(m.Cols))
	for name, col := range m.Cols {
		field := rval.FieldByName(col.GoName)
		if !field.IsValid() {
			return fmt.Errorf("insertOne:未找到该名称[%v]的值", col.GoName)
		}

		// 在为零值的情况下，若该列是AI或是有默认值，则过滤掉。无论该零值是否为手动设置的。
		if reflect.Zero(col.GoType).Interface() == field.Interface() &&
			(col.IsAI() || col.HasDefault) {
			continue
		}

		keys = append(keys, name)
		vals = append(vals, field.Interface())
	}

	if len(keys) == 0 {
		return errors.New("insertOne:未指定任何插入的列数据")
	}

	sql := bytes.NewBufferString("INSERT INTO ")
	e.Dialect().Quote(sql, e.Prefix()+m.Name)

	sql.WriteByte('(')
	for _, col := range keys {
		e.Dialect().Quote(sql, col)
		sql.WriteByte(',')
	}
	sql.Truncate(sql.Len() - 1)
	sql.WriteString(")VALUES(")
	for range vals {
		sql.WriteString("?,")
	}
	sql.Truncate(sql.Len() - 1)
	sql.WriteByte(')')

	_, err = e.Exec(false, sql.String(), vals...)
	return err
}

// 更新一个对象
// 以v中的主键或是唯一索引作为where条件语句，其它值为更新值
func updateOne(e engine, v interface{}) error {
	m, err := newModel(v)
	if err != nil {
		return err
	}

	rval := reflect.ValueOf(v)
	for rval.Kind() == reflect.Ptr {
		rval = rval.Elem()
	}

	if rval.Kind() != reflect.Struct {
		return errors.New("updateOne:无效的v.Kind()")
	}

	sql := bytes.NewBufferString("UPDATE ")
	e.Dialect().Quote(sql, e.Prefix()+m.Name)
	sql.WriteString(" SET ")
	vals := make([]interface{}, 0, len(m.Cols))

	for name, col := range m.Cols {
		field := rval.FieldByName(col.GoName)
		if !field.IsValid() {
			return fmt.Errorf("updateOne:未找到该名称[%v]的值", col.GoName)
		}

		// 忽略零值，TODO:还需要对比默认值
		if reflect.Zero(col.GoType).Interface() == field.Interface() {
			continue
		}

		e.Dialect().Quote(sql, name)
		sql.WriteString("=?,")
		vals = append(vals, field.Interface())
	}
	sql.Truncate(sql.Len() - 1)

	whereVals, err := where(e, sql, m, rval)
	if err != nil {
		return err
	}
	vals = append(vals, whereVals...)

	_, err = e.Exec(false, sql.String(), vals...)
	return err
}

// 获取v对象的表名，v可以是一个结构体，也可以是一个字符串。
func getTableName(e engine, v interface{}) (string, error) {
	switch tbl := v.(type) {
	case string:
		return tbl, nil
	case []rune:
		return string(tbl), nil
	case []byte:
		return string(tbl), nil
	}

	m, err := newModel(v)
	if err != nil {
		return "", err
	}
	return m.Name, nil
}

func dropOne(e engine, v interface{}) error {
	tbl, err := getTableName(e, v)
	if err != nil {
		return err
	}

	sql := bytes.NewBufferString("DROP TABLE IF EXISTS ")
	e.Dialect().Quote(sql, e.Prefix()+tbl)
	_, err = e.Exec(false, sql.String())
	return err
}

func truncateOne(e engine, v interface{}) error {
	tbl, err := getTableName(e, v)
	if err != nil {
		return err
	}

	sql := e.Dialect().TruncateTableSQL(e.Prefix() + tbl)
	_, err = e.Exec(false, sql)
	return err
}

// 创建一个或多个数据表
func createMult(e engine, objs ...interface{}) error {
	sql := new(bytes.Buffer)
	d := e.Dialect()

	for i, v := range objs {
		m, err := newModel(v)
		if err != nil {
			return err
		}

		rval := reflect.ValueOf(v)
		for rval.Kind() == reflect.Ptr {
			rval = rval.Elem()
		}

		if rval.Kind() != reflect.Struct {
			return fmt.Errorf("createMult:objs[%v]类型必须为结构体或是结构体指针", i)
		}

		sql.Reset()
		sql.WriteString("CREATE TABLE IF NOT EXISTS ")
		d.Quote(sql, e.Prefix()+m.Name)
		sql.WriteByte('(')
		d.AIColSQL(sql, m)
		d.NoAIColSQL(sql, m)
		d.ConstraintsSQL(sql, m)
		sql.Truncate(sql.Len() - 1)
		sql.WriteByte(')')

		if _, err = e.Exec(false, sql.String()); err != nil {
			return err
		}
	}

	return nil
}

// 插入一个或多个数据
// v可以是对象或是对象数组
func insertMult(e engine, objs ...interface{}) error {
	for _, obj := range objs {
		if err := insertOne(e, obj); err != nil {
			return err
		}
	}
	return nil
}

// 查找多个数据
func findMult(e engine, objs ...interface{}) error {
	for _, obj := range objs {
		if err := findOne(e, obj); err != nil {
			return err
		}
	}
	return nil
}

// 更新一个或多个类型。
// 更新依据为每个对象的主键或是唯一索引列。
// 若不存在此两个类型的字段，则返回错误信息。
func updateMult(e engine, objs ...interface{}) error {
	for _, obj := range objs {
		if err := updateOne(e, obj); err != nil {
			return err
		}
	}
	return nil
}

// 删除objs每个元素表示的数据。
// 以objs中每个元素的主键或是唯一索引作为where条件语句。
func deleteMult(e engine, objs ...interface{}) error {
	sql := new(bytes.Buffer)
	for i, v := range objs {
		m, err := newModel(v)
		if err != nil {
			return err
		}

		rval := reflect.ValueOf(v)
		for rval.Kind() == reflect.Ptr {
			rval = rval.Elem()
		}

		if rval.Kind() != reflect.Struct {
			return fmt.Errorf("deleteMult:objs[%v]类型必须为结构体或是结构体指针", i)
		}

		sql.Reset()
		sql.WriteString("DELETE FROM ")
		e.Dialect().Quote(sql, e.Prefix()+m.Name)

		vals, err := where(e, sql, m, rval)
		if err != nil {
			return err
		}

		if _, err = e.Exec(false, sql.String(), vals...); err != nil {
			return err
		}
	}
	return nil
}

func dropMult(e engine, objs ...interface{}) error {
	for _, obj := range objs {
		if err := dropOne(e, obj); err != nil {
			return err
		}
	}
	return nil
}

func truncateMult(e engine, objs ...interface{}) error {
	for _, obj := range objs {
		if err := truncateOne(e, obj); err != nil {
			return err
		}
	}
	return nil
}
<commit_msg>将dropOne与dropMult合并，将truncateOne与truncateMult合并<commit_after>// Copyright 2014 by caixw, All rights reserved.
// Use of this source code is governed by a MIT
// license that can be found in the LICENSE file.

package orm

import (
	"bytes"
	"database/sql"
	"errors"
	"fmt"
	"reflect"

	"github.com/issue9/orm/fetch"
)

// DB与Tx的共有接口，方便以下方法调用。
type engine interface {
	Dialect() Dialect
	Query(replace bool, query string, args ...interface{}) (*sql.Rows, error)
	Exec(replace bool, query string, args ...interface{}) (sql.Result, error)
	Prepare(replace bool, query string) (*sql.Stmt, error)
	Prefix() string
}

// 检测rval中与cols对应的字段都是有效的，且为非零值。
// 若cols的长度为0，返回false。
func checkCols(cols []*Column, rval reflect.Value) bool {
	if len(cols) == 0 {
		return false
	}

	for _, col := range cols {
		field := rval.FieldByName(col.GoName)
		if !field.IsValid() {
			return false
		}

		if reflect.Zero(col.GoType).Interface() == field.Interface() {
			return false
		}
	}
	return true
}

// 根据model中的主键或是唯一索引为sql产生where语句，
// 若两者都不存在，则返回错误信息。rval为struct的reflect.Value
func where(e engine, sql *bytes.Buffer, m *Model, rval reflect.Value) ([]interface{}, error) {
	ret := []interface{}{}

	if checkCols(m.PK, rval) {
		sql.WriteString(" WHERE ")
		for _, col := range m.PK {
			e.Dialect().Quote(sql, col.Name)
			sql.WriteString("=?")
			ret = append(ret, rval.FieldByName(col.GoName).Interface())
		}
		return ret, nil
	}

	// 若不存在pk，也不存在唯一约束
	for _, cols := range m.UniqueIndexes {
		if !checkCols(cols, rval) {
			continue
		}

		sql.WriteString(" WHERE ")
		for _, col := range cols {
			e.Dialect().Quote(sql, col.Name)
			sql.WriteString("=?")
			ret = append(ret, rval.FieldByName(col.GoName).Interface())
			sql.WriteString(" AND ")
		}
		sql.Truncate(sql.Len() - 5) // 去掉最后的" AND "五个字符
		return ret, nil
	} // end range m.UniqueIndexes

	return nil, errors.New("where:无法产生where部分语句")
}

// 根据v的pk或中唯一索引列查找一行数据，并赋值给v
func findOne(e engine, v interface{}) error {
	m, err := newModel(v)
	if err != nil {
		return err
	}

	rval := reflect.ValueOf(v)
	for rval.Kind() == reflect.Ptr {
		rval = rval.Elem()
	}

	if rval.Kind() != reflect.Struct {
		return errors.New("findOne:无效的v.Kind()")
	}

	sql := bytes.NewBufferString("SELECT * FROM ")
	e.Dialect().Quote(sql, e.Prefix()+m.Name)

	vals, err := where(e, sql, m, rval)
	if err != nil {
		return err
	}

	rows, err := e.Query(false, sql.String(), vals...)
	if err != nil {
		return err
	}
	defer rows.Close()

	return fetch.Obj(v, rows)
}

// 插入一个对象到数据库
// 以v中的主键或是唯一索引作为where条件语句。
// 自增字段，即使指定了值，也不会被添加
func insertOne(e engine, v interface{}) error {
	m, err := newModel(v)
	if err != nil {
		return err
	}

	rval := reflect.ValueOf(v)
	for rval.Kind() == reflect.Ptr {
		rval = rval.Elem()
	}

	if rval.Kind() != reflect.Struct {
		return errors.New("insertOne:无效的v.Kind()")
	}

	keys := make([]string, 0, len(m.Cols))
	vals := make([]interface{}, 0, len(m.Cols))
	for name, col := range m.Cols {
		field := rval.FieldByName(col.GoName)
		if !field.IsValid() {
			return fmt.Errorf("insertOne:未找到该名称[%v]的值", col.GoName)
		}

		// 在为零值的情况下，若该列是AI或是有默认值，则过滤掉。无论该零值是否为手动设置的。
		if reflect.Zero(col.GoType).Interface() == field.Interface() &&
			(col.IsAI() || col.HasDefault) {
			continue
		}

		keys = append(keys, name)
		vals = append(vals, field.Interface())
	}

	if len(keys) == 0 {
		return errors.New("insertOne:未指定任何插入的列数据")
	}

	sql := bytes.NewBufferString("INSERT INTO ")
	e.Dialect().Quote(sql, e.Prefix()+m.Name)

	sql.WriteByte('(')
	for _, col := range keys {
		e.Dialect().Quote(sql, col)
		sql.WriteByte(',')
	}
	sql.Truncate(sql.Len() - 1)
	sql.WriteString(")VALUES(")
	for range vals {
		sql.WriteString("?,")
	}
	sql.Truncate(sql.Len() - 1)
	sql.WriteByte(')')

	_, err = e.Exec(false, sql.String(), vals...)
	return err
}

// 更新一个对象
// 以v中的主键或是唯一索引作为where条件语句，其它值为更新值
func updateOne(e engine, v interface{}) error {
	m, err := newModel(v)
	if err != nil {
		return err
	}

	rval := reflect.ValueOf(v)
	for rval.Kind() == reflect.Ptr {
		rval = rval.Elem()
	}

	if rval.Kind() != reflect.Struct {
		return errors.New("updateOne:无效的v.Kind()")
	}

	sql := bytes.NewBufferString("UPDATE ")
	e.Dialect().Quote(sql, e.Prefix()+m.Name)
	sql.WriteString(" SET ")
	vals := make([]interface{}, 0, len(m.Cols))

	for name, col := range m.Cols {
		field := rval.FieldByName(col.GoName)
		if !field.IsValid() {
			return fmt.Errorf("updateOne:未找到该名称[%v]的值", col.GoName)
		}

		// 忽略零值，TODO:还需要对比默认值
		if reflect.Zero(col.GoType).Interface() == field.Interface() {
			continue
		}

		e.Dialect().Quote(sql, name)
		sql.WriteString("=?,")
		vals = append(vals, field.Interface())
	}
	sql.Truncate(sql.Len() - 1)

	whereVals, err := where(e, sql, m, rval)
	if err != nil {
		return err
	}
	vals = append(vals, whereVals...)

	_, err = e.Exec(false, sql.String(), vals...)
	return err
}

// 获取v对象的表名，v可以是一个结构体，也可以是一个字符串。
func getTableName(e engine, v interface{}) (string, error) {
	switch tbl := v.(type) {
	case string:
		return tbl, nil
	case []rune:
		return string(tbl), nil
	case []byte:
		return string(tbl), nil
	}

	m, err := newModel(v)
	if err != nil {
		return "", err
	}
	return m.Name, nil
}

// 创建一个或多个数据表
func createMult(e engine, objs ...interface{}) error {
	sql := new(bytes.Buffer)
	d := e.Dialect()

	for i, v := range objs {
		m, err := newModel(v)
		if err != nil {
			return err
		}

		rval := reflect.ValueOf(v)
		for rval.Kind() == reflect.Ptr {
			rval = rval.Elem()
		}

		if rval.Kind() != reflect.Struct {
			return fmt.Errorf("createMult:objs[%v]类型必须为结构体或是结构体指针", i)
		}

		sql.Reset()
		sql.WriteString("CREATE TABLE IF NOT EXISTS ")
		d.Quote(sql, e.Prefix()+m.Name)
		sql.WriteByte('(')
		d.AIColSQL(sql, m)
		d.NoAIColSQL(sql, m)
		d.ConstraintsSQL(sql, m)
		sql.Truncate(sql.Len() - 1)
		sql.WriteByte(')')

		if _, err = e.Exec(false, sql.String()); err != nil {
			return err
		}
	}

	return nil
}

// 插入一个或多个数据
// v可以是对象或是对象数组
func insertMult(e engine, objs ...interface{}) error {
	for _, obj := range objs {
		if err := insertOne(e, obj); err != nil {
			return err
		}
	}
	return nil
}

// 查找多个数据
func findMult(e engine, objs ...interface{}) error {
	for _, obj := range objs {
		if err := findOne(e, obj); err != nil {
			return err
		}
	}
	return nil
}

// 更新一个或多个类型。
// 更新依据为每个对象的主键或是唯一索引列。
// 若不存在此两个类型的字段，则返回错误信息。
func updateMult(e engine, objs ...interface{}) error {
	for _, obj := range objs {
		if err := updateOne(e, obj); err != nil {
			return err
		}
	}
	return nil
}

// 删除objs每个元素表示的数据。
// 以objs中每个元素的主键或是唯一索引作为where条件语句。
func deleteMult(e engine, objs ...interface{}) error {
	sql := new(bytes.Buffer)
	for i, v := range objs {
		m, err := newModel(v)
		if err != nil {
			return err
		}

		rval := reflect.ValueOf(v)
		for rval.Kind() == reflect.Ptr {
			rval = rval.Elem()
		}

		if rval.Kind() != reflect.Struct {
			return fmt.Errorf("deleteMult:objs[%v]类型必须为结构体或是结构体指针", i)
		}

		sql.Reset()
		sql.WriteString("DELETE FROM ")
		e.Dialect().Quote(sql, e.Prefix()+m.Name)

		vals, err := where(e, sql, m, rval)
		if err != nil {
			return err
		}

		if _, err = e.Exec(false, sql.String(), vals...); err != nil {
			return err
		}
	}
	return nil
}

// 删除objs中指定的表名。
// objs可以是字符串表名，或是一个表示model的实例。
// 系统会默认给表名加上表名前缀。
func dropMult(e engine, objs ...interface{}) error {
	sql := new(bytes.Buffer)
	for _, v := range objs {
		tbl, err := getTableName(e, v)
		if err != nil {
			return err
		}

		sql.Reset()
		sql := bytes.NewBufferString("DROP TABLE IF EXISTS ")
		e.Dialect().Quote(sql, e.Prefix()+tbl)
		if _, err = e.Exec(false, sql.String()); err != nil {
			return err
		}
	}

	return nil
}

// 清空表，并重置AI计数。
// objs可以是字符串表名，或是一个表示model的实例。
// 系统会默认给表名加上表名前缀。
func truncateMult(e engine, objs ...interface{}) error {
	for _, v := range objs {
		tbl, err := getTableName(e, v)
		if err != nil {
			return err
		}

		sql := e.Dialect().TruncateTableSQL(e.Prefix() + tbl)
		if _, err = e.Exec(false, sql); err != nil {
			return err
		}
	}

	return nil
}
<|endoftext|>


<commit_before>package generator

import (
	log "github.com/Sirupsen/logrus"
	terrain "github.com/lawrencecraft/terrainmodel"
	"math"
	"math/rand"
	"time"
)

type DiamondSquareGenerator struct {
	Roughness float32
	X         int
	Y         int
}

func NewDiamondSquareGenerator(roughness float32, x int, y int) *DiamondSquareGenerator {
	return &DiamondSquareGenerator{X: x, Y: y, Roughness: roughness}
}

func incrementAverage(x uint16, y uint16, t *terrain.Terrain, currentCount int, currentSum int) (int, int) {
	v, e := t.GetHeight(x, y)
	if e == nil {
		return currentCount + 1, currentSum + int(v)
	}
	return currentCount, currentSum
}

func normalizeOffset(avg uint16, offset int) uint16 {
	norm := int(avg) + offset
	if norm < 0 {
		return 0
	}
	return uint16(norm)
}

func setSquare(t *terrain.Terrain, x uint16, y uint16, offset int, scale uint16) {
	c, s := incrementAverage(x+scale, y+scale, t, 0, 0)
	c, s = incrementAverage(x-scale, y-scale, t, c, s)
	c, s = incrementAverage(x+scale, y-scale, t, c, s)
	c, s = incrementAverage(x-scale, y+scale, t, c, s)

	avg := uint16(s / c)

	n := normalizeOffset(avg, offset)
	t.SetHeight(x, y, n)
}

func setDiamond(t *terrain.Terrain, x uint16, y uint16, offset int, scale uint16) {
	c, s := incrementAverage(x, y+scale, t, 0, 0)
	c, s = incrementAverage(x, y-scale, t, c, s)
	c, s = incrementAverage(x+scale, y, t, c, s)
	c, s = incrementAverage(x-scale, y, t, c, s)

	avg := uint16(s / c)
	n := normalizeOffset(avg, offset)

	t.SetHeight(x, y, n)
}

func generateTerrain(t *terrain.Terrain, roughness float32, x0y0 uint16, xmaxy0 uint16, x0ymax uint16, xmaxymax uint16) {
	maxDimension := t.X - 1 // At this point, we are 100% sure the terrain will be square
	offsetMultiplier := int(math.MaxUint16)
	t.SetHeight(0, 0, x0y0)
	t.SetHeight(maxDimension, 0, xmaxy0)
	t.SetHeight(0, maxDimension, x0ymax)
	t.SetHeight(maxDimension, maxDimension, xmaxymax)

	rand.Seed(time.Now().UnixNano())

	iteration := 1

	sideLength := maxDimension
	for sideLength > 1 {

		halfSize := uint16(sideLength / 2)
		log.Debug("Size ", sideLength, " halfsize:", halfSize)

		// Square
		for x := halfSize; x < t.X; x += sideLength {
			for y := halfSize; y < t.Y; y += sideLength {
				offset := int(rand.Float32()*float32(offsetMultiplier)*2.0) - offsetMultiplier
				log.Debug("Setting square: ", x, ",", y, "with offset", offset)
				setSquare(t, x, y, offset, halfSize)
			}
		}

		// Diamond
		for y := uint16(0); y < t.Y; y += halfSize {
			for x := (y + halfSize) % sideLength; x < t.X; x += sideLength {
				offset := int(rand.Float32()*float32(offsetMultiplier)*2.0) - offsetMultiplier
				log.Debug("Setting diamond: ", x, ",", y, " with offset ", offset)
				setDiamond(t, x, y, offset, halfSize)
			}
		}

		iteration += 1
		offsetMultiplier /= 2
		sideLength = halfSize
	}
}

func getScale(x int, y int) int {
	maxDimension := x
	if y > x {
		maxDimension = y
	}
	return int(math.Ceil(math.Log2(float64(maxDimension - 1))))
}

func (d *DiamondSquareGenerator) Generate() (*terrain.Terrain, error) {
	scale := getScale(d.X, d.Y)
	squareDimension := uint16(math.Exp2(float64(scale)))
	operatingTerrain := terrain.New(squareDimension, squareDimension, math.MaxUint16)
	generateTerrain(operatingTerrain, d.Roughness, uint16(math.MaxUint16*rand.Float32()), uint16(math.MaxUint16*rand.Float32()), uint16(math.MaxUint16*rand.Float32()), uint16(math.MaxUint16*rand.Float32()))
	// Special case: if the generated terrain is the same as what is requested, return it
	if d.X == int(squareDimension) && d.Y == int(squareDimension) {
		return operatingTerrain, nil
	}
	// Copy to a new terrain of the requested size
	returningTerrain := terrain.New(uint16(d.X), uint16(d.Y), operatingTerrain.MaxHeight)
	err := operatingTerrain.CopyTo(returningTerrain, 0, 0)
	if err != nil {
		return nil, err
	}
	return returningTerrain, nil
}
<commit_msg>Adding roughness and fixing initial square calculation<commit_after>package generator

import (
	log "github.com/Sirupsen/logrus"
	terrain "github.com/lawrencecraft/terrainmodel"
	"math"
	"math/rand"
	"time"
)

type DiamondSquareGenerator struct {
	Roughness float32
	X         int
	Y         int
}

func NewDiamondSquareGenerator(roughness float32, x int, y int) *DiamondSquareGenerator {
	return &DiamondSquareGenerator{X: x, Y: y, Roughness: roughness}
}

func incrementAverage(x uint16, y uint16, t *terrain.Terrain, currentCount int, currentSum int) (int, int) {
	v, e := t.GetHeight(x, y)
	if e == nil {
		return currentCount + 1, currentSum + int(v)
	}
	return currentCount, currentSum
}

func normalizeOffset(avg uint16, offset int) uint16 {
	norm := int(avg) + offset
	if norm < 0 {
		return 0
	}
	return uint16(norm)
}

func setSquare(t *terrain.Terrain, x uint16, y uint16, offset int, scale uint16) {
	c, s := incrementAverage(x+scale, y+scale, t, 0, 0)
	c, s = incrementAverage(x-scale, y-scale, t, c, s)
	c, s = incrementAverage(x+scale, y-scale, t, c, s)
	c, s = incrementAverage(x-scale, y+scale, t, c, s)

	avg := uint16(s / c)

	n := normalizeOffset(avg, offset)
	t.SetHeight(x, y, n)
}

func setDiamond(t *terrain.Terrain, x uint16, y uint16, offset int, scale uint16) {
	c, s := incrementAverage(x, y+scale, t, 0, 0)
	c, s = incrementAverage(x, y-scale, t, c, s)
	c, s = incrementAverage(x+scale, y, t, c, s)
	c, s = incrementAverage(x-scale, y, t, c, s)

	avg := uint16(s / c)
	n := normalizeOffset(avg, offset)

	t.SetHeight(x, y, n)
}

func generateTerrain(t *terrain.Terrain, roughness float32, x0y0 uint16, xmaxy0 uint16, x0ymax uint16, xmaxymax uint16) {
	maxDimension := t.X - 1 // At this point, we are 100% sure the terrain will be square
	offsetMultiplier := int(math.MaxUint16)
	t.SetHeight(0, 0, x0y0)
	t.SetHeight(maxDimension, 0, xmaxy0)
	t.SetHeight(0, maxDimension, x0ymax)
	t.SetHeight(maxDimension, maxDimension, xmaxymax)

	rand.Seed(time.Now().UnixNano())

	iteration := 1

	sideLength := maxDimension
	for sideLength > 1 {

		halfSize := uint16(sideLength / 2)
		log.Debug("Size ", sideLength, " halfsize:", halfSize)

		// Square
		for x := halfSize; x < t.X; x += sideLength {
			for y := halfSize; y < t.Y; y += sideLength {
				offset := int(float32(int(rand.Float32()*float32(offsetMultiplier)*2.0)-offsetMultiplier) * roughness)
				log.Debug("Setting square: ", x, ",", y, "with offset", offset)
				setSquare(t, x, y, offset, halfSize)
			}
		}

		// Diamond
		for y := uint16(0); y < t.Y; y += halfSize {
			for x := (y + halfSize) % sideLength; x < t.X; x += sideLength {
				offset := int(rand.Float32()*float32(offsetMultiplier)*2.0) - offsetMultiplier
				log.Debug("Setting diamond: ", x, ",", y, " with offset ", offset)
				setDiamond(t, x, y, offset, halfSize)
			}
		}

		iteration += 1
		offsetMultiplier /= 2
		sideLength = halfSize
	}
}

func getScale(x int, y int) int {
	maxDimension := x
	if y > x {
		maxDimension = y
	}
	return int(math.Ceil(math.Log2(float64(maxDimension - 1))))
}

func (d *DiamondSquareGenerator) Generate() (*terrain.Terrain, error) {
	scale := getScale(d.X, d.Y)
	squareDimension := uint16(math.Exp2(float64(scale))) + 1 // Must be 2^n + 1 -- use the minimum size we calculated previously
	log.Debug("Generating square of dimension ", squareDimension)
	operatingTerrain := terrain.New(squareDimension, squareDimension, math.MaxUint16)
	generateTerrain(operatingTerrain, d.Roughness, uint16(math.MaxUint16*rand.Float32()), uint16(math.MaxUint16*rand.Float32()), uint16(math.MaxUint16*rand.Float32()), uint16(math.MaxUint16*rand.Float32()))
	// Special case: if the generated terrain is the same as what is requested, return it
	if d.X == int(squareDimension) && d.Y == int(squareDimension) {
		log.Debug("Shortcutting copy - no need as requested terrain is square")
		return operatingTerrain, nil
	}
	// Copy to a new terrain of the requested size
	returningTerrain := terrain.New(uint16(d.X), uint16(d.Y), operatingTerrain.MaxHeight)
	err := operatingTerrain.CopyTo(returningTerrain, 0, 0)
	if err != nil {
		log.Debug("diamondsquare.go - encountered error on terrain copy: ", err)
		return nil, err
	}
	return returningTerrain, nil
}
<|endoftext|>


<commit_before>package pgtype

import (
	"database/sql/driver"
	"encoding/binary"
	"math"
	"strconv"

	"github.com/jackc/pgx/pgio"
	"github.com/pkg/errors"
)

type Int8 struct {
	Int    int64
	Status Status
}

func (dst *Int8) Set(src interface{}) error {
	if src == nil {
		*dst = Int8{Status: Null}
		return nil
	}

	switch value := src.(type) {
	case int8:
		*dst = Int8{Int: int64(value), Status: Present}
	case uint8:
		*dst = Int8{Int: int64(value), Status: Present}
	case int16:
		*dst = Int8{Int: int64(value), Status: Present}
	case uint16:
		*dst = Int8{Int: int64(value), Status: Present}
	case int32:
		*dst = Int8{Int: int64(value), Status: Present}
	case uint32:
		*dst = Int8{Int: int64(value), Status: Present}
	case int64:
		*dst = Int8{Int: int64(value), Status: Present}
	case uint64:
		if value > math.MaxInt64 {
			return errors.Errorf("%d is greater than maximum value for Int8", value)
		}
		*dst = Int8{Int: int64(value), Status: Present}
	case int:
		if int64(value) < math.MinInt64 {
			return errors.Errorf("%d is greater than maximum value for Int8", value)
		}
		if int64(value) > math.MaxInt64 {
			return errors.Errorf("%d is greater than maximum value for Int8", value)
		}
		*dst = Int8{Int: int64(value), Status: Present}
	case uint:
		if uint64(value) > math.MaxInt64 {
			return errors.Errorf("%d is greater than maximum value for Int8", value)
		}
		*dst = Int8{Int: int64(value), Status: Present}
	case string:
		num, err := strconv.ParseInt(value, 10, 64)
		if err != nil {
			return err
		}
		*dst = Int8{Int: num, Status: Present}
	default:
		if originalSrc, ok := underlyingNumberType(src); ok {
			return dst.Set(originalSrc)
		}
		return errors.Errorf("cannot convert %v to Int8", value)
	}

	return nil
}

func (dst *Int8) Get() interface{} {
	switch dst.Status {
	case Present:
		return dst.Int
	case Null:
		return nil
	default:
		return dst.Status
	}
}

func (src *Int8) AssignTo(dst interface{}) error {
	return int64AssignTo(int64(src.Int), src.Status, dst)
}

func (dst *Int8) DecodeText(ci *ConnInfo, src []byte) error {
	if src == nil {
		*dst = Int8{Status: Null}
		return nil
	}

	n, err := strconv.ParseInt(string(src), 10, 64)
	if err != nil {
		return err
	}

	*dst = Int8{Int: n, Status: Present}
	return nil
}

func (dst *Int8) DecodeBinary(ci *ConnInfo, src []byte) error {
	if src == nil {
		*dst = Int8{Status: Null}
		return nil
	}

	if len(src) != 8 {
		return errors.Errorf("invalid length for int8: %v", len(src))
	}

	n := int64(binary.BigEndian.Uint64(src))

	*dst = Int8{Int: n, Status: Present}
	return nil
}

func (src *Int8) EncodeText(ci *ConnInfo, buf []byte) ([]byte, error) {
	switch src.Status {
	case Null:
		return nil, nil
	case Undefined:
		return nil, errUndefined
	}

	return append(buf, strconv.FormatInt(src.Int, 10)...), nil
}

func (src *Int8) EncodeBinary(ci *ConnInfo, buf []byte) ([]byte, error) {
	switch src.Status {
	case Null:
		return nil, nil
	case Undefined:
		return nil, errUndefined
	}

	return pgio.AppendInt64(buf, src.Int), nil
}

// Scan implements the database/sql Scanner interface.
func (dst *Int8) Scan(src interface{}) error {
	if src == nil {
		*dst = Int8{Status: Null}
		return nil
	}

	switch src := src.(type) {
	case int64:
		*dst = Int8{Int: src, Status: Present}
		return nil
	case string:
		return dst.DecodeText(nil, []byte(src))
	case []byte:
		srcCopy := make([]byte, len(src))
		copy(srcCopy, src)
		return dst.DecodeText(nil, srcCopy)
	}

	return errors.Errorf("cannot scan %T", src)
}

// Value implements the database/sql/driver Valuer interface.
func (src *Int8) Value() (driver.Value, error) {
	switch src.Status {
	case Present:
		return int64(src.Int), nil
	case Null:
		return nil, nil
	default:
		return nil, errUndefined
	}
}

func (src *Int8) MarshalJSON() ([]byte, error) {
	switch src.Status {
	case Present:
		return []byte(strconv.FormatInt(src.Int, 10)), nil
	case Null:
		return []byte("null"), nil
	case Undefined:
		return nil, errUndefined
	}

	return nil, errBadStatus
}
<commit_msg>UnmarshalJSON for Int8 missing<commit_after>package pgtype

import (
	"database/sql/driver"
	"encoding/binary"
	"math"
	"strconv"

	"github.com/jackc/pgx/pgio"
	"github.com/pkg/errors"
)

type Int8 struct {
	Int    int64
	Status Status
}

func (dst *Int8) Set(src interface{}) error {
	if src == nil {
		*dst = Int8{Status: Null}
		return nil
	}

	switch value := src.(type) {
	case int8:
		*dst = Int8{Int: int64(value), Status: Present}
	case uint8:
		*dst = Int8{Int: int64(value), Status: Present}
	case int16:
		*dst = Int8{Int: int64(value), Status: Present}
	case uint16:
		*dst = Int8{Int: int64(value), Status: Present}
	case int32:
		*dst = Int8{Int: int64(value), Status: Present}
	case uint32:
		*dst = Int8{Int: int64(value), Status: Present}
	case int64:
		*dst = Int8{Int: int64(value), Status: Present}
	case uint64:
		if value > math.MaxInt64 {
			return errors.Errorf("%d is greater than maximum value for Int8", value)
		}
		*dst = Int8{Int: int64(value), Status: Present}
	case int:
		if int64(value) < math.MinInt64 {
			return errors.Errorf("%d is greater than maximum value for Int8", value)
		}
		if int64(value) > math.MaxInt64 {
			return errors.Errorf("%d is greater than maximum value for Int8", value)
		}
		*dst = Int8{Int: int64(value), Status: Present}
	case uint:
		if uint64(value) > math.MaxInt64 {
			return errors.Errorf("%d is greater than maximum value for Int8", value)
		}
		*dst = Int8{Int: int64(value), Status: Present}
	case string:
		num, err := strconv.ParseInt(value, 10, 64)
		if err != nil {
			return err
		}
		*dst = Int8{Int: num, Status: Present}
	default:
		if originalSrc, ok := underlyingNumberType(src); ok {
			return dst.Set(originalSrc)
		}
		return errors.Errorf("cannot convert %v to Int8", value)
	}

	return nil
}

func (dst *Int8) Get() interface{} {
	switch dst.Status {
	case Present:
		return dst.Int
	case Null:
		return nil
	default:
		return dst.Status
	}
}

func (src *Int8) AssignTo(dst interface{}) error {
	return int64AssignTo(int64(src.Int), src.Status, dst)
}

func (dst *Int8) DecodeText(ci *ConnInfo, src []byte) error {
	if src == nil {
		*dst = Int8{Status: Null}
		return nil
	}

	n, err := strconv.ParseInt(string(src), 10, 64)
	if err != nil {
		return err
	}

	*dst = Int8{Int: n, Status: Present}
	return nil
}

func (dst *Int8) DecodeBinary(ci *ConnInfo, src []byte) error {
	if src == nil {
		*dst = Int8{Status: Null}
		return nil
	}

	if len(src) != 8 {
		return errors.Errorf("invalid length for int8: %v", len(src))
	}

	n := int64(binary.BigEndian.Uint64(src))

	*dst = Int8{Int: n, Status: Present}
	return nil
}

func (src *Int8) EncodeText(ci *ConnInfo, buf []byte) ([]byte, error) {
	switch src.Status {
	case Null:
		return nil, nil
	case Undefined:
		return nil, errUndefined
	}

	return append(buf, strconv.FormatInt(src.Int, 10)...), nil
}

func (src *Int8) EncodeBinary(ci *ConnInfo, buf []byte) ([]byte, error) {
	switch src.Status {
	case Null:
		return nil, nil
	case Undefined:
		return nil, errUndefined
	}

	return pgio.AppendInt64(buf, src.Int), nil
}

// Scan implements the database/sql Scanner interface.
func (dst *Int8) Scan(src interface{}) error {
	if src == nil {
		*dst = Int8{Status: Null}
		return nil
	}

	switch src := src.(type) {
	case int64:
		*dst = Int8{Int: src, Status: Present}
		return nil
	case string:
		return dst.DecodeText(nil, []byte(src))
	case []byte:
		srcCopy := make([]byte, len(src))
		copy(srcCopy, src)
		return dst.DecodeText(nil, srcCopy)
	}

	return errors.Errorf("cannot scan %T", src)
}

// Value implements the database/sql/driver Valuer interface.
func (src *Int8) Value() (driver.Value, error) {
	switch src.Status {
	case Present:
		return int64(src.Int), nil
	case Null:
		return nil, nil
	default:
		return nil, errUndefined
	}
}

func (src *Int8) MarshalJSON() ([]byte, error) {
	switch src.Status {
	case Present:
		return []byte(strconv.FormatInt(src.Int, 10)), nil
	case Null:
		return []byte("null"), nil
	case Undefined:
		return nil, errUndefined
	}

	return nil, errBadStatus
}

func (dst *Int8) UnmarshalJSON(b []byte) error {
	var n int64
	err := json.Unmarshal(b, &n)
	if err != nil {
		return err
	}

	*dst = Int8{Int: n, Status: Present}

	return nil
}
<|endoftext|>


<commit_before>// Copyright 2015 Canonical Ltd.
// Licensed under the AGPLv3, see LICENCE file for details.

package lxd

import (
	"fmt"

	"github.com/juju/errors"
	"github.com/juju/loggo"
	"github.com/juju/names"

	"github.com/juju/juju/cloudconfig/containerinit"
	"github.com/juju/juju/cloudconfig/instancecfg"
	"github.com/juju/juju/container"
	"github.com/juju/juju/instance"
	"github.com/juju/juju/tools/lxdclient"
)

var (
        logger = loggo.GetLogger("juju.container.lxd")
)

const (
	DefaultLxdBridge = "lxcbr0"
)

// XXX: should we allow managing containers on other hosts? this is
// functionality LXD gives us and from discussion juju would use eventually for
// the local provider, so the APIs probably need to be changed to pass extra
// args around. I'm punting for now.
type containerManager struct {
	name string
	// A cached client.
	client *lxdclient.Client
}

// containerManager implements container.Manager.
var _ container.Manager = (*containerManager)(nil)

func ConnectLocal(namespace string) (*lxdclient.Client, error) {
	cfg := lxdclient.Config{
		Namespace: namespace,
		Remote: lxdclient.Local,
	}

	cfg, err := cfg.WithDefaults()
	if err != nil {
		return nil, errors.Trace(err)
	}

	client, err := lxdclient.Connect(cfg)
	if err != nil {
		return nil, errors.Trace(err)
	}

	return client, nil
}

func NewContainerManager(conf container.ManagerConfig) (container.Manager, error) {
	name := conf.PopValue(container.ConfigName)
	if name == "" {
		return nil, errors.Errorf("name is required")
	}

	conf.WarnAboutUnused()
	return &containerManager{name: name}, nil
}

func (manager *containerManager) CreateContainer(
	instanceConfig *instancecfg.InstanceConfig,
	series string,
	networkConfig *container.NetworkConfig,
	storageConfig *container.StorageConfig,
) (inst instance.Instance, _ *instance.HardwareCharacteristics, err error) {
	if manager.client == nil {
		manager.client, err = ConnectLocal(manager.name)
		if err != nil {
			return
		}
	}

	err = manager.client.EnsureImageExists(series)
	if err != nil {
		return
	}

	name := names.NewMachineTag(instanceConfig.MachineId).String()
	if manager.name != "" {
		name = fmt.Sprintf("%s-%s", manager.name, name)
	}

	userData, err := containerinit.CloudInitUserData(instanceConfig, networkConfig)
	if err != nil {
		return
	}

	metadata := map[string]string{
		lxdclient.UserdataKey: string(userData),
		// An extra piece of info to let people figure out where this
		// thing came from.
		"user.juju-environment": manager.name,

		// Make sure these come back up on host reboot.
		"boot.autostart": "true",
	}

	spec := lxdclient.InstanceSpec{
		Name: name,
		Image: manager.client.ImageNameForSeries(series),
		Metadata: metadata,
		Profiles: []string{
			"default",
		},
	}

	logger.Infof("starting instance %q (image %q)...", spec.Name, spec.Image)
	_, err = manager.client.AddInstance(spec)
	if err != nil {
		return
	}

	inst = &lxdInstance{name, manager.client}
	return
}

func (manager *containerManager) DestroyContainer(id instance.Id) error {
	if manager.client == nil {
		var err error
		manager.client, err = ConnectLocal(manager.name)
		if err != nil {
			return err
		}
	}

	return errors.Trace(manager.client.RemoveInstances("", string(id)))
}

func (manager *containerManager) ListContainers() (result []instance.Instance, err error) {
	result = []instance.Instance{}
	if manager.client == nil {
		manager.client, err = ConnectLocal(manager.name)
		if err != nil {
			return
		}
	}

	lxdInstances, err := manager.client.Instances("")
	if err != nil {
		return
	}

	for _, i := range lxdInstances {
		result = append(result, &lxdInstance{i.Name, manager.client})
	}

	return
}

func (manager *containerManager) IsInitialized() bool {
	if manager.client != nil {
		return true
	}

	// NewClient does a roundtrip to the server to make sure it understands
	// the versions, so all we need to do is connect above and we're done.
	var err error
	manager.client, err = ConnectLocal(manager.name)
	return err == nil
}
<commit_msg>lxd container type: remember to use the namespace<commit_after>// Copyright 2015 Canonical Ltd.
// Licensed under the AGPLv3, see LICENCE file for details.

package lxd

import (
	"fmt"

	"github.com/juju/errors"
	"github.com/juju/loggo"
	"github.com/juju/names"

	"github.com/juju/juju/cloudconfig/containerinit"
	"github.com/juju/juju/cloudconfig/instancecfg"
	"github.com/juju/juju/container"
	"github.com/juju/juju/instance"
	"github.com/juju/juju/tools/lxdclient"
)

var (
        logger = loggo.GetLogger("juju.container.lxd")
)

const (
	DefaultLxdBridge = "lxcbr0"
)

// XXX: should we allow managing containers on other hosts? this is
// functionality LXD gives us and from discussion juju would use eventually for
// the local provider, so the APIs probably need to be changed to pass extra
// args around. I'm punting for now.
type containerManager struct {
	name string
	// A cached client.
	client *lxdclient.Client
}

// containerManager implements container.Manager.
var _ container.Manager = (*containerManager)(nil)

func ConnectLocal(namespace string) (*lxdclient.Client, error) {
	cfg := lxdclient.Config{
		Namespace: namespace,
		Remote: lxdclient.Local,
	}

	cfg, err := cfg.WithDefaults()
	if err != nil {
		return nil, errors.Trace(err)
	}

	client, err := lxdclient.Connect(cfg)
	if err != nil {
		return nil, errors.Trace(err)
	}

	return client, nil
}

func NewContainerManager(conf container.ManagerConfig) (container.Manager, error) {
	name := conf.PopValue(container.ConfigName)
	if name == "" {
		return nil, errors.Errorf("name is required")
	}

	conf.WarnAboutUnused()
	return &containerManager{name: name}, nil
}

func (manager *containerManager) CreateContainer(
	instanceConfig *instancecfg.InstanceConfig,
	series string,
	networkConfig *container.NetworkConfig,
	storageConfig *container.StorageConfig,
) (inst instance.Instance, _ *instance.HardwareCharacteristics, err error) {
	if manager.client == nil {
		manager.client, err = ConnectLocal(manager.name)
		if err != nil {
			return
		}
	}

	err = manager.client.EnsureImageExists(series)
	if err != nil {
		return
	}

	name := names.NewMachineTag(instanceConfig.MachineId).String()
	if manager.name != "" {
		name = fmt.Sprintf("%s-%s", manager.name, name)
	}

	userData, err := containerinit.CloudInitUserData(instanceConfig, networkConfig)
	if err != nil {
		return
	}

	metadata := map[string]string{
		lxdclient.UserdataKey: string(userData),
		// An extra piece of info to let people figure out where this
		// thing came from.
		"user.juju-environment": manager.name,

		// Make sure these come back up on host reboot.
		"boot.autostart": "true",
	}

	spec := lxdclient.InstanceSpec{
		Name: name,
		Image: manager.client.ImageNameForSeries(series),
		Metadata: metadata,
		Profiles: []string{
			"default",
		},
	}

	logger.Infof("starting instance %q (image %q)...", spec.Name, spec.Image)
	_, err = manager.client.AddInstance(spec)
	if err != nil {
		return
	}

	inst = &lxdInstance{name, manager.client}
	return
}

func (manager *containerManager) DestroyContainer(id instance.Id) error {
	if manager.client == nil {
		var err error
		manager.client, err = ConnectLocal(manager.name)
		if err != nil {
			return err
		}
	}

	return errors.Trace(manager.client.RemoveInstances(manager.name, string(id)))
}

func (manager *containerManager) ListContainers() (result []instance.Instance, err error) {
	result = []instance.Instance{}
	if manager.client == nil {
		manager.client, err = ConnectLocal(manager.name)
		if err != nil {
			return
		}
	}

	lxdInstances, err := manager.client.Instances(manager.name)
	if err != nil {
		return
	}

	for _, i := range lxdInstances {
		result = append(result, &lxdInstance{i.Name, manager.client})
	}

	return
}

func (manager *containerManager) IsInitialized() bool {
	if manager.client != nil {
		return true
	}

	// NewClient does a roundtrip to the server to make sure it understands
	// the versions, so all we need to do is connect above and we're done.
	var err error
	manager.client, err = ConnectLocal(manager.name)
	return err == nil
}
<|endoftext|>


<commit_before>package user

import (
	"github.com/gin-gonic/gin"
	"github.com/stretchr/testify/assert"
	"gopkg.in/DATA-DOG/go-sqlmock.v1"
	"testing"

	"github.com/eirka/eirka-libs/db"
	e "github.com/eirka/eirka-libs/errors"
)

func TestProtect(t *testing.T) {

	var err error

	Secret = "secret"

	mock, err := db.NewTestDb()
	assert.NoError(t, err, "An error was not expected")

	rows := sqlmock.NewRows([]string{"role"}).AddRow(1)

	mock.ExpectQuery(`SELECT COALESCE`).WillReturnRows(rows)

	gin.SetMode(gin.ReleaseMode)

	router := gin.New()

	router.Use(validate.ValidateParams())
	router.Use(user.Auth(true))
	router.Use(user.Protect())

	router.GET("/important", func(c *gin.Context) {
		c.String(200, "OK")
		return
	})

	first := performRequest(router, "GET", "/important")

	assert.Equal(t, first.Code, 401, "HTTP request code should match")

	user := DefaultUser()
	user.SetId(2)
	user.SetAuthenticated()

	user.hash, err = HashPassword("testpassword")
	if assert.NoError(t, err, "An error was not expected") {
		assert.NotNil(t, user.hash, "password should be returned")
	}

	assert.True(t, user.ComparePassword("testpassword"), "Password should validate")

	token, err := user.CreateToken()
	if assert.NoError(t, err, "An error was not expected") {
		assert.NotEmpty(t, badtoken, "token should be returned")
	}

	second := performJwtHeaderRequest(router, "GET", "/important", token)

}
<commit_msg>add protect middleware test<commit_after>package user

import (
	"github.com/gin-gonic/gin"
	"github.com/stretchr/testify/assert"
	"gopkg.in/DATA-DOG/go-sqlmock.v1"
	"testing"

	"github.com/eirka/eirka-libs/db"
	"github.com/eirka/eirka-libs/validate"
)

func TestProtect(t *testing.T) {

	var err error

	Secret = "secret"

	mock, err := db.NewTestDb()
	assert.NoError(t, err, "An error was not expected")

	rows := sqlmock.NewRows([]string{"role"}).AddRow(1)

	mock.ExpectQuery(`SELECT COALESCE`).WillReturnRows(rows)

	gin.SetMode(gin.ReleaseMode)

	router := gin.New()

	router.Use(validate.ValidateParams())
	router.Use(Auth(true))
	router.Use(Protect())

	router.GET("/important", func(c *gin.Context) {
		c.String(200, "OK")
		return
	})

	first := performRequest(router, "GET", "/important")

	assert.Equal(t, first.Code, 401, "HTTP request code should match")

	user := DefaultUser()
	user.SetId(2)
	user.SetAuthenticated()

	user.hash, err = HashPassword("testpassword")
	if assert.NoError(t, err, "An error was not expected") {
		assert.NotNil(t, user.hash, "password should be returned")
	}

	assert.True(t, user.ComparePassword("testpassword"), "Password should validate")

	token, err := user.CreateToken()
	if assert.NoError(t, err, "An error was not expected") {
		assert.NotEmpty(t, token, "token should be returned")
	}

	second := performJwtHeaderRequest(router, "GET", "/important", token)

}
<|endoftext|>


<commit_before>package file

import (
	"github.com/achun/testing-want"
	"os"
	"testing"
	"time"
)

func TestFile(t *testing.T) {
	Testfile(t, `_test/`)
	Testfile(t, `_test`)
	Testfile(t, `./_test`)
	Testfile(t, `./_test/`)

	Testfile(t, `_test/log`)
	Testfile(t, `_test/log`)
	Testfile(t, `./_test/log`)
	Testfile(t, `./_test/log`)
	Testfile(t, `_test/access-log`)
}
func Testfile(t *testing.T, path string) {
	f, err := New(path)
	want.Nil(t, err)
	defer func() {
		want.Nil(t, f.Close())
		println(f.Name)
		want.Nil(t, os.Remove(f.Name))
	}()

	want.Nil(t, want.Err(
		f.Write([]byte("string line\n")),
	))
	f.fd.Sync()
	now := time.Now()
	println(f.Name)
	name := f.Name
	f.Rotate(now, now)
	want.Nil(t, os.Remove(name))
}
<commit_msg>change  method of want<commit_after>package file

import (
	"github.com/achun/testing-want"
	"os"
	"testing"
	"time"
)

func TestFile(t *testing.T) {
	Testfile(t, `_test/`)
	Testfile(t, `_test`)
	Testfile(t, `./_test`)
	Testfile(t, `./_test/`)

	Testfile(t, `_test/log`)
	Testfile(t, `_test/log`)
	Testfile(t, `./_test/log`)
	Testfile(t, `./_test/log`)
	Testfile(t, `_test/access-log`)
}
func Testfile(t *testing.T, path string) {
	wt := want.T(t)
	f, err := New(path)

	wt.Nil(err)
	defer func() {
		wt.Nil(f.Close())
		wt.Nil(os.Remove(f.Name))
	}()

	wt.Nil(want.LastError(
		f.Write([]byte("string line\n")),
	))
	f.fd.Sync()
	now := time.Now()
	name := f.Name
	f.Rotate(now, now)
	wt.True(f.Name != name, "rotate failed: ", name)
	wt.Nil(os.Remove(name))
}
<|endoftext|>


<commit_before>package flatmap

import (
	"fmt"
	"regexp"
	"sort"
	"strconv"
	"strings"
)

// Expand takes a map and a key (prefix) and expands that value into
// a more complex structure. This is the reverse of the Flatten operation.
func Expand(m map[string]string, key string) interface{} {
	// If the key is exactly a key in the map, just return it
	if v, ok := m[key]; ok {
		if v == "true" {
			return true
		} else if v == "false" {
			return false
		}

		return v
	}

	// Check if the key is an array, and if so, expand the array
	if _, ok := m[key+".#"]; ok {
		return expandArray(m, key)
	}

	// Check if this is a prefix in the map
	prefix := key + "."
	for k, _ := range m {
		if strings.HasPrefix(k, prefix) {
			return expandMap(m, prefix)
		}
	}

	return nil
}

func expandArray(m map[string]string, prefix string) []interface{} {
	num, err := strconv.ParseInt(m[prefix+".#"], 0, 0)
	if err != nil {
		panic(err)
	}

	keySet := make(map[int]struct{})
	listElementKey := regexp.MustCompile("^" + prefix + "\\.([0-9]+)(?:\\..*)?$")
	for key := range m {
		if matches := listElementKey.FindStringSubmatch(key); matches != nil {
			k, err := strconv.ParseInt(matches[1], 0, 0)
			if err != nil {
				panic(err)
			}
			keySet[int(k)] = struct{}{}
		}
	}

	keysList := make([]int, 0, num)
	for key := range keySet {
		keysList = append(keysList, key)
	}
	sort.Ints(keysList)

	result := make([]interface{}, num)
	for i, key := range keysList {
		result[i] = Expand(m, fmt.Sprintf("%s.%d", prefix, key))
	}

	return result
}

func expandMap(m map[string]string, prefix string) map[string]interface{} {
	result := make(map[string]interface{})
	for k, _ := range m {
		if !strings.HasPrefix(k, prefix) {
			continue
		}

		key := k[len(prefix):]
		idx := strings.Index(key, ".")
		if idx != -1 {
			key = key[:idx]
		}
		if _, ok := result[key]; ok {
			continue
		}

		// skip the map count value
		if key == "%" {
			continue
		}
		result[key] = Expand(m, k[:len(prefix)+len(key)])
	}

	return result
}
<commit_msg>Minor fixups to expandArray<commit_after>package flatmap

import (
	"fmt"
	"sort"
	"strconv"
	"strings"
)

// Expand takes a map and a key (prefix) and expands that value into
// a more complex structure. This is the reverse of the Flatten operation.
func Expand(m map[string]string, key string) interface{} {
	// If the key is exactly a key in the map, just return it
	if v, ok := m[key]; ok {
		if v == "true" {
			return true
		} else if v == "false" {
			return false
		}

		return v
	}

	// Check if the key is an array, and if so, expand the array
	if _, ok := m[key+".#"]; ok {
		return expandArray(m, key)
	}

	// Check if this is a prefix in the map
	prefix := key + "."
	for k, _ := range m {
		if strings.HasPrefix(k, prefix) {
			return expandMap(m, prefix)
		}
	}

	return nil
}

func expandArray(m map[string]string, prefix string) []interface{} {
	num, err := strconv.ParseInt(m[prefix+".#"], 0, 0)
	if err != nil {
		panic(err)
	}

	keySet := map[int]bool{}
	for k := range m {
		if !strings.HasPrefix(k, prefix+".") {
			continue
		}

		key := k[len(prefix)+1:]
		idx := strings.Index(key, ".")
		if idx != -1 {
			key = key[:idx]
		}

		// skip the count value
		if key == "#" {
			continue
		}

		k, err := strconv.Atoi(key)
		if err != nil {
			panic(err)
		}
		keySet[int(k)] = true
	}

	keysList := make([]int, 0, num)
	for key := range keySet {
		keysList = append(keysList, key)
	}
	sort.Ints(keysList)

	result := make([]interface{}, num)
	for i, key := range keysList {
		result[i] = Expand(m, fmt.Sprintf("%s.%d", prefix, key))
	}

	return result
}

func expandMap(m map[string]string, prefix string) map[string]interface{} {
	result := make(map[string]interface{})
	for k, _ := range m {
		if !strings.HasPrefix(k, prefix) {
			continue
		}

		key := k[len(prefix):]
		idx := strings.Index(key, ".")
		if idx != -1 {
			key = key[:idx]
		}
		if _, ok := result[key]; ok {
			continue
		}

		// skip the map count value
		if key == "%" {
			continue
		}
		result[key] = Expand(m, k[:len(prefix)+len(key)])
	}

	return result
}
<|endoftext|>


<commit_before>// Copyright 2019 The Gitea Authors. All rights reserved.
// Use of this source code is governed by a MIT-style
// license that can be found in the LICENSE file.

package migrations

import (
	"code.gitea.io/gitea/modules/setting"

	"xorm.io/xorm"
)

func prependRefsHeadsToIssueRefs(x *xorm.Engine) error {
	var query string

	switch {
	case setting.Database.UseMSSQL:
		query = "UPDATE `issue` SET `ref` = 'refs/heads/' + `ref` WHERE `ref` IS NOT NULL AND `ref` <> '' AND `ref` NOT LIKE 'refs/%'"
	default:
		query = "UPDATE `issue` SET `ref` = 'refs/heads/' || `ref` WHERE `ref` IS NOT NULL AND `ref` <> '' AND `ref` NOT LIKE 'refs/%'"
	}

	_, err := x.Exec(query)
	return err
}
<commit_msg>Fix issue ref migration (#11419)<commit_after>// Copyright 2019 The Gitea Authors. All rights reserved.
// Use of this source code is governed by a MIT-style
// license that can be found in the LICENSE file.

package migrations

import (
	"code.gitea.io/gitea/modules/setting"

	"xorm.io/xorm"
)

func prependRefsHeadsToIssueRefs(x *xorm.Engine) error {
	var query string

	switch {
	case setting.Database.UseMSSQL:
		query = "UPDATE `issue` SET `ref` = 'refs/heads/' + `ref` WHERE `ref` IS NOT NULL AND `ref` <> '' AND `ref` NOT LIKE 'refs/%'"
	case setting.Database.UseMySQL:
		query = "UPDATE `issue` SET `ref` = CONCAT('refs/heads/', `ref`) WHERE `ref` IS NOT NULL AND `ref` <> '' AND `ref` NOT LIKE 'refs/%';"
	default:
		query = "UPDATE `issue` SET `ref` = 'refs/heads/' || `ref` WHERE `ref` IS NOT NULL AND `ref` <> '' AND `ref` NOT LIKE 'refs/%'"
	}

	_, err := x.Exec(query)
	return err
}
<|endoftext|>