<commit_before>package js

import (
	"testing"

	"github.com/cihangir/gene/generators/common"
	"github.com/cihangir/gene/testdata"
)

func TestJSClient(t *testing.T) {
	common.RunTest(t, &Generator{}, testdata.JSON1, expecteds)
}

var expecteds = []string{`module.exports.account = {
  // New creates a new local Account js client
  Account = function(){}

  // create validators
  Account.validate = function(data){
    return  null
  }

  // create mapper
  Account.map = function(data){
    return null
  }

  Account.Create = function(data, callback) {
    // data should be type of models.Account

    if(err = Account.validate(data)) {
      return callback(err, null)
    }

    // send request to the server
    // we got the response
    var res = {}
    // response should be type of models.Accountx
    res = Account.map(res)
    callback(null, res)
  }

  Account.Delete = function(data, callback) {
    // data should be type of models.Account

    if(err = Account.validate(data)) {
      return callback(err, null)
    }

    // send request to the server
    // we got the response
    var res = {}
    // response should be type of models.Accountx
    res = Account.map(res)
    callback(null, res)
  }

  Account.One = function(data, callback) {
    // data should be type of models.Account

    if(err = Account.validate(data)) {
      return callback(err, null)
    }

    // send request to the server
    // we got the response
    var res = {}
    // response should be type of models.Accountx
    res = Account.map(res)
    callback(null, res)
  }

  Account.Some = function(data, callback) {
    // data should be type of models.Account

    if(err = Account.validate(data)) {
      return callback(err, null)
    }

    // send request to the server
    // we got the response
    var res = {}
    // response should be type of []*models.Accountx
    res = res.map(function(datum) {
      return Account.map(datum);
    });
    callback(null, res)
  }

  Account.Update = function(data, callback) {
    // data should be type of models.Account

    if(err = Account.validate(data)) {
      return callback(err, null)
    }

    // send request to the server
    // we got the response
    var res = {}
    // response should be type of models.Accountx
    res = Account.map(res)
    callback(null, res)
  }

}
`,
	`module.exports.account = {
  // New creates a new local Profile js client
  Profile = function(){}

  // create validators
  Profile.validate = function(data){
    return  null
  }

  // create mapper
  Profile.map = function(data){
    return null
  }

  Profile.Create = function(data, callback) {
    // data should be type of models.Profile

    if(err = Profile.validate(data)) {
      return callback(err, null)
    }

    // send request to the server
    // we got the response
    var res = {}
    // response should be type of models.Profilex
    res = Profile.map(res)
    callback(null, res)
  }

  Profile.Delete = function(data, callback) {
    // data should be type of models.Profile

    if(err = Profile.validate(data)) {
      return callback(err, null)
    }

    // send request to the server
    // we got the response
    var res = {}
    // response should be type of models.Profilex
    res = Profile.map(res)
    callback(null, res)
  }

  Profile.One = function(data, callback) {
    // data should be type of models.Profile

    if(err = Profile.validate(data)) {
      return callback(err, null)
    }

    // send request to the server
    // we got the response
    var res = {}
    // response should be type of models.Profilex
    res = Profile.map(res)
    callback(null, res)
  }

  Profile.Some = function(data, callback) {
    // data should be type of models.Profile

    if(err = Profile.validate(data)) {
      return callback(err, null)
    }

    // send request to the server
    // we got the response
    var res = {}
    // response should be type of []*models.Profilex
    res = res.map(function(datum) {
      return Profile.map(datum);
    });
    callback(null, res)
  }

  Profile.Update = function(data, callback) {
    // data should be type of models.Profile

    if(err = Profile.validate(data)) {
      return callback(err, null)
    }

    // send request to the server
    // we got the response
    var res = {}
    // response should be type of models.Profilex
    res = Profile.map(res)
    callback(null, res)
  }

}
`,
}
<commit_msg>gene/js: skip js client tests<commit_after>package js

import (
	"testing"

	"github.com/cihangir/gene/generators/common"
	"github.com/cihangir/gene/testdata"
)

func TestJSClient(t *testing.T) {
	t.Skip("js client is not complete yet")
	common.RunTest(t, &Generator{}, testdata.JSON1, expecteds)
}

var expecteds = []string{`module.exports.account = {
  // New creates a new local Account js client
  Account = function(){}

  // create validators
  Account.validate = function(data){
    return  null
  }

  // create mapper
  Account.map = function(data){
    return null
  }

  Account.Create = function(data, callback) {
    // data should be type of models.Account

    if(err = Account.validate(data)) {
      return callback(err, null)
    }

    // send request to the server
    // we got the response
    var res = {}
    // response should be type of models.Accountx
    res = Account.map(res)
    callback(null, res)
  }

  Account.Delete = function(data, callback) {
    // data should be type of models.Account

    if(err = Account.validate(data)) {
      return callback(err, null)
    }

    // send request to the server
    // we got the response
    var res = {}
    // response should be type of models.Accountx
    res = Account.map(res)
    callback(null, res)
  }

  Account.One = function(data, callback) {
    // data should be type of models.Account

    if(err = Account.validate(data)) {
      return callback(err, null)
    }

    // send request to the server
    // we got the response
    var res = {}
    // response should be type of models.Accountx
    res = Account.map(res)
    callback(null, res)
  }

  Account.Some = function(data, callback) {
    // data should be type of models.Account

    if(err = Account.validate(data)) {
      return callback(err, null)
    }

    // send request to the server
    // we got the response
    var res = {}
    // response should be type of []*models.Accountx
    res = res.map(function(datum) {
      return Account.map(datum);
    });
    callback(null, res)
  }

  Account.Update = function(data, callback) {
    // data should be type of models.Account

    if(err = Account.validate(data)) {
      return callback(err, null)
    }

    // send request to the server
    // we got the response
    var res = {}
    // response should be type of models.Accountx
    res = Account.map(res)
    callback(null, res)
  }

}
`,
	`module.exports.account = {
  // New creates a new local Profile js client
  Profile = function(){}

  // create validators
  Profile.validate = function(data){
    return  null
  }

  // create mapper
  Profile.map = function(data){
    return null
  }

  Profile.Create = function(data, callback) {
    // data should be type of models.Profile

    if(err = Profile.validate(data)) {
      return callback(err, null)
    }

    // send request to the server
    // we got the response
    var res = {}
    // response should be type of models.Profilex
    res = Profile.map(res)
    callback(null, res)
  }

  Profile.Delete = function(data, callback) {
    // data should be type of models.Profile

    if(err = Profile.validate(data)) {
      return callback(err, null)
    }

    // send request to the server
    // we got the response
    var res = {}
    // response should be type of models.Profilex
    res = Profile.map(res)
    callback(null, res)
  }

  Profile.One = function(data, callback) {
    // data should be type of models.Profile

    if(err = Profile.validate(data)) {
      return callback(err, null)
    }

    // send request to the server
    // we got the response
    var res = {}
    // response should be type of models.Profilex
    res = Profile.map(res)
    callback(null, res)
  }

  Profile.Some = function(data, callback) {
    // data should be type of models.Profile

    if(err = Profile.validate(data)) {
      return callback(err, null)
    }

    // send request to the server
    // we got the response
    var res = {}
    // response should be type of []*models.Profilex
    res = res.map(function(datum) {
      return Profile.map(datum);
    });
    callback(null, res)
  }

  Profile.Update = function(data, callback) {
    // data should be type of models.Profile

    if(err = Profile.validate(data)) {
      return callback(err, null)
    }

    // send request to the server
    // we got the response
    var res = {}
    // response should be type of models.Profilex
    res = Profile.map(res)
    callback(null, res)
  }

}
`,
}
<|endoftext|>


<commit_before>// Package runtime is the micro runtime
package runtime

import (
	"fmt"
	"os"
	"sort"
	"strings"
	"text/tabwriter"

	"github.com/micro/cli/v2"
	"github.com/micro/go-micro/v2"
	"github.com/micro/go-micro/v2/config/cmd"
	"github.com/micro/go-micro/v2/runtime"
	srvRuntime "github.com/micro/go-micro/v2/runtime/service"
)

const (
	// RunUsage message for the run command
	RunUsage = "Required usage: micro run [service] [version] [--source github.com/micro/services]"
	// KillUsage message for the kill command
	KillUsage = "Require usage: micro kill [service] [version]"
	// UpdateUsage message for the update command
	UpdateUsage = "Require usage: micro update [service] [version]"
	// GetUsage message for micro get command
	GetUsage = "Require usage: micro ps [service] [version]"
	// ServicesUsage message for micro services command
	ServicesUsage = "Require usage: micro services"
	// CannotWatch message for the run command
	CannotWatch = "Cannot watch filesystem on this runtime"
)

var (
	// DefaultRetries which should be attempted when starting a service
	DefaultRetries = 3
	// Image to specify if none is specified
	Image = "docker.pkg.github.com/micro/services"
)

func runtimeFromContext(ctx *cli.Context) runtime.Runtime {
	if ctx.Bool("platform") {
		os.Setenv("MICRO_PROXY", "service")
		os.Setenv("MICRO_PROXY_ADDRESS", "proxy.micro.mu:443")
		return srvRuntime.NewRuntime()
	}

	return *cmd.DefaultCmd.Options().Runtime
}

func runService(ctx *cli.Context, srvOpts ...micro.Option) {
	// Init plugins
	for _, p := range Plugins() {
		p.Init(ctx)
	}

	// we need some args to run
	if ctx.Args().Len() == 0 {
		fmt.Println(RunUsage)
		return
	}

	// set and validate the name (arg 1)
	name := ctx.Args().Get(0)
	version := "latest"
	source := ctx.String("source")
	typ := ctx.String("type")
	image := ctx.String("image")
	command := strings.TrimSpace(ctx.String("command"))
	args := strings.TrimSpace(ctx.String("args"))

	// load the runtime
	r := runtimeFromContext(ctx)

	if strings.HasPrefix(name, ".") || strings.HasPrefix(name, "/") {
		fmt.Println(RunUsage)
		return
	}

	// set the version (arg 2, optional)
	if ctx.Args().Len() > 1 {
		version = ctx.Args().Get(1)
	}

	// add environment variable passed in via cli
	var environment []string
	for _, evar := range ctx.StringSlice("env") {
		for _, e := range strings.Split(evar, ",") {
			if len(e) > 0 {
				environment = append(environment, strings.TrimSpace(e))
			}
		}
	}

	var retries = DefaultRetries
	if ctx.IsSet("retries") {
		retries = ctx.Int("retries")
	}

	// set the image from our images if its the platform
	if ctx.Bool("platform") && len(image) == 0 {
		formattedName := strings.ReplaceAll(name, "/", "-")
		image = fmt.Sprintf("%v/%v", Image, formattedName)
	}

	// specify the options
	opts := []runtime.CreateOption{
		runtime.WithOutput(os.Stdout),
		runtime.WithRetries(retries),
		runtime.CreateImage(image),
		runtime.CreateType(typ),
	}

	if len(environment) > 0 {
		opts = append(opts, runtime.WithEnv(environment))
	}

	if len(command) > 0 {
		opts = append(opts, runtime.WithCommand(strings.Split(command, " ")...))
	}

	if len(args) > 0 {
		opts = append(opts, runtime.WithArgs(strings.Split(args, " ")...))
	}

	// run the service
	service := &runtime.Service{
		Name:     name,
		Source:   source,
		Version:  version,
		Metadata: make(map[string]string),
	}

	if err := r.Create(service, opts...); err != nil {
		fmt.Println(err)
		return
	}
}

func killService(ctx *cli.Context, srvOpts ...micro.Option) {
	// we need some args to run
	if ctx.Args().Len() == 0 {
		fmt.Println(RunUsage)
		return
	}

	// set and validate the name (arg 1)
	name := ctx.Args().Get(0)
	if strings.HasPrefix(name, ".") || strings.HasPrefix(name, "/") {
		fmt.Println(RunUsage)
		return
	}

	// set the version (arg 2, optional)
	version := "latest"
	if ctx.Args().Len() > 1 {
		version = ctx.Args().Get(1)
	}

	service := &runtime.Service{
		Name:    name,
		Version: version,
	}

	if err := runtimeFromContext(ctx).Delete(service); err != nil {
		fmt.Println(err)
		return
	}
}

func updateService(ctx *cli.Context, srvOpts ...micro.Option) {
	// we need some args to run
	if ctx.Args().Len() == 0 {
		fmt.Println(RunUsage)
		return
	}

	// set and validate the name (arg 1)
	name := ctx.Args().Get(0)
	if strings.HasPrefix(name, ".") || strings.HasPrefix(name, "/") {
		fmt.Println(RunUsage)
		return
	}

	// set the version (arg 2, optional)
	version := "latest"
	if ctx.Args().Len() > 1 {
		version = ctx.Args().Get(1)
	}

	service := &runtime.Service{
		Name:    name,
		Version: version,
	}

	if err := runtimeFromContext(ctx).Update(service); err != nil {
		fmt.Println(err)
		return
	}
}

func getService(ctx *cli.Context, srvOpts ...micro.Option) {
	name := ctx.Args().Get(0)
	version := "latest"
	runType := ctx.Bool("runtime")
	typ := ctx.String("type")
	r := runtimeFromContext(ctx)

	if strings.HasPrefix(name, ".") || strings.HasPrefix(name, "/") {
		fmt.Println(GetUsage)
		return
	}

	// set version as second arg
	if ctx.Args().Len() > 1 {
		version = ctx.Args().Get(1)
	}

	// should we list sevices
	var list bool

	// zero args so list all
	if ctx.Args().Len() == 0 {
		list = true
	}

	var err error
	var services []*runtime.Service

	// return a list of services
	switch list {
	case true:
		// return the runtiem services
		if runType {
			services, err = r.Read(runtime.ReadType("runtime"))
		} else {
			// list all running services
			services, err = r.List()
		}
	// return one service
	default:
		// check if service name was passed in
		if len(name) == 0 {
			fmt.Println(GetUsage)
			return
		}

		// get service with name and version
		opts := []runtime.ReadOption{
			runtime.ReadService(name),
			runtime.ReadVersion(version),
		}

		// return the runtime services
		if runType {
			opts = append(opts, runtime.ReadType("runtime"))
		} else {
			opts = append(opts, runtime.ReadType(typ))
		}

		// read the service
		services, err = r.Read(opts...)
	}

	// check the error
	if err != nil {
		fmt.Println(err)
		return
	}

	// make sure we return UNKNOWN when empty string is supplied
	parse := func(m string) string {
		if len(m) == 0 {
			return "n/a"
		}
		return m
	}

	// don't do anything if there's no services
	if len(services) == 0 {
		return
	}

	sort.Slice(services, func(i, j int) bool { return services[i].Name < services[j].Name })

	writer := tabwriter.NewWriter(os.Stdout, 0, 8, 1, '\t', tabwriter.AlignRight)
	fmt.Fprintln(writer, "NAME\tVERSION\tSOURCE\tSTATUS\tBUILD\tMETADATA")
	for _, service := range services {
		status := parse(service.Metadata["status"])
		if status == "error" {
			status = service.Metadata["error"]
		}

		fmt.Fprintf(writer, "%s\t%s\t%s\t%s\t%s\t%s\n",
			service.Name,
			parse(service.Version),
			parse(service.Source),
			status,
			parse(service.Metadata["build"]),
			fmt.Sprintf("owner=%s,group=%s", parse(service.Metadata["owner"]), parse(service.Metadata["group"])))
	}
	writer.Flush()
}
<commit_msg>Set the source if not specified when platform (#648)<commit_after>// Package runtime is the micro runtime
package runtime

import (
	"fmt"
	"os"
	"sort"
	"strings"
	"text/tabwriter"

	"github.com/micro/cli/v2"
	"github.com/micro/go-micro/v2"
	"github.com/micro/go-micro/v2/config/cmd"
	"github.com/micro/go-micro/v2/runtime"
	srvRuntime "github.com/micro/go-micro/v2/runtime/service"
)

const (
	// RunUsage message for the run command
	RunUsage = "Required usage: micro run [service] [version] [--source github.com/micro/services]"
	// KillUsage message for the kill command
	KillUsage = "Require usage: micro kill [service] [version]"
	// UpdateUsage message for the update command
	UpdateUsage = "Require usage: micro update [service] [version]"
	// GetUsage message for micro get command
	GetUsage = "Require usage: micro ps [service] [version]"
	// ServicesUsage message for micro services command
	ServicesUsage = "Require usage: micro services"
	// CannotWatch message for the run command
	CannotWatch = "Cannot watch filesystem on this runtime"
)

var (
	// DefaultRetries which should be attempted when starting a service
	DefaultRetries = 3
	// Image to specify if none is specified
	Image = "docker.pkg.github.com/micro/services"
	// Source where we get services from
	Source = "github.com/micro/services"
)

func runtimeFromContext(ctx *cli.Context) runtime.Runtime {
	if ctx.Bool("platform") {
		os.Setenv("MICRO_PROXY", "service")
		os.Setenv("MICRO_PROXY_ADDRESS", "proxy.micro.mu:443")
		return srvRuntime.NewRuntime()
	}

	return *cmd.DefaultCmd.Options().Runtime
}

func runService(ctx *cli.Context, srvOpts ...micro.Option) {
	// Init plugins
	for _, p := range Plugins() {
		p.Init(ctx)
	}

	// we need some args to run
	if ctx.Args().Len() == 0 {
		fmt.Println(RunUsage)
		return
	}

	// set and validate the name (arg 1)
	name := ctx.Args().Get(0)
	version := "latest"
	source := ctx.String("source")
	typ := ctx.String("type")
	image := ctx.String("image")
	command := strings.TrimSpace(ctx.String("command"))
	args := strings.TrimSpace(ctx.String("args"))

	// load the runtime
	r := runtimeFromContext(ctx)

	if strings.HasPrefix(name, ".") || strings.HasPrefix(name, "/") {
		fmt.Println(RunUsage)
		return
	}

	// set the version (arg 2, optional)
	if ctx.Args().Len() > 1 {
		version = ctx.Args().Get(1)
	}

	// add environment variable passed in via cli
	var environment []string
	for _, evar := range ctx.StringSlice("env") {
		for _, e := range strings.Split(evar, ",") {
			if len(e) > 0 {
				environment = append(environment, strings.TrimSpace(e))
			}
		}
	}

	var retries = DefaultRetries
	if ctx.IsSet("retries") {
		retries = ctx.Int("retries")
	}

	// set the image from our images if its the platform
	if ctx.Bool("platform") && len(image) == 0 {
		formattedName := strings.ReplaceAll(name, "/", "-")
		image = fmt.Sprintf("%v/%v", Image, formattedName)
	}

	// check the source is set
	if ctx.Bool("platform") && len(source) == 0 {
		source = Source
	}

	// specify the options
	opts := []runtime.CreateOption{
		runtime.WithOutput(os.Stdout),
		runtime.WithRetries(retries),
		runtime.CreateImage(image),
		runtime.CreateType(typ),
	}

	if len(environment) > 0 {
		opts = append(opts, runtime.WithEnv(environment))
	}

	if len(command) > 0 {
		opts = append(opts, runtime.WithCommand(strings.Split(command, " ")...))
	}

	if len(args) > 0 {
		opts = append(opts, runtime.WithArgs(strings.Split(args, " ")...))
	}

	// run the service
	service := &runtime.Service{
		Name:     name,
		Source:   source,
		Version:  version,
		Metadata: make(map[string]string),
	}

	if err := r.Create(service, opts...); err != nil {
		fmt.Println(err)
		return
	}
}

func killService(ctx *cli.Context, srvOpts ...micro.Option) {
	// we need some args to run
	if ctx.Args().Len() == 0 {
		fmt.Println(RunUsage)
		return
	}

	// set and validate the name (arg 1)
	name := ctx.Args().Get(0)
	if strings.HasPrefix(name, ".") || strings.HasPrefix(name, "/") {
		fmt.Println(RunUsage)
		return
	}

	// set the version (arg 2, optional)
	version := "latest"
	if ctx.Args().Len() > 1 {
		version = ctx.Args().Get(1)
	}

	service := &runtime.Service{
		Name:    name,
		Version: version,
	}

	if err := runtimeFromContext(ctx).Delete(service); err != nil {
		fmt.Println(err)
		return
	}
}

func updateService(ctx *cli.Context, srvOpts ...micro.Option) {
	// we need some args to run
	if ctx.Args().Len() == 0 {
		fmt.Println(RunUsage)
		return
	}

	// set and validate the name (arg 1)
	name := ctx.Args().Get(0)
	if strings.HasPrefix(name, ".") || strings.HasPrefix(name, "/") {
		fmt.Println(RunUsage)
		return
	}

	// set the version (arg 2, optional)
	version := "latest"
	if ctx.Args().Len() > 1 {
		version = ctx.Args().Get(1)
	}

	service := &runtime.Service{
		Name:    name,
		Version: version,
	}

	if err := runtimeFromContext(ctx).Update(service); err != nil {
		fmt.Println(err)
		return
	}
}

func getService(ctx *cli.Context, srvOpts ...micro.Option) {
	name := ctx.Args().Get(0)
	version := "latest"
	runType := ctx.Bool("runtime")
	typ := ctx.String("type")
	r := runtimeFromContext(ctx)

	if strings.HasPrefix(name, ".") || strings.HasPrefix(name, "/") {
		fmt.Println(GetUsage)
		return
	}

	// set version as second arg
	if ctx.Args().Len() > 1 {
		version = ctx.Args().Get(1)
	}

	// should we list sevices
	var list bool

	// zero args so list all
	if ctx.Args().Len() == 0 {
		list = true
	}

	var err error
	var services []*runtime.Service

	// return a list of services
	switch list {
	case true:
		// return the runtiem services
		if runType {
			services, err = r.Read(runtime.ReadType("runtime"))
		} else {
			// list all running services
			services, err = r.List()
		}
	// return one service
	default:
		// check if service name was passed in
		if len(name) == 0 {
			fmt.Println(GetUsage)
			return
		}

		// get service with name and version
		opts := []runtime.ReadOption{
			runtime.ReadService(name),
			runtime.ReadVersion(version),
		}

		// return the runtime services
		if runType {
			opts = append(opts, runtime.ReadType("runtime"))
		} else {
			opts = append(opts, runtime.ReadType(typ))
		}

		// read the service
		services, err = r.Read(opts...)
	}

	// check the error
	if err != nil {
		fmt.Println(err)
		return
	}

	// make sure we return UNKNOWN when empty string is supplied
	parse := func(m string) string {
		if len(m) == 0 {
			return "n/a"
		}
		return m
	}

	// don't do anything if there's no services
	if len(services) == 0 {
		return
	}

	sort.Slice(services, func(i, j int) bool { return services[i].Name < services[j].Name })

	writer := tabwriter.NewWriter(os.Stdout, 0, 8, 1, '\t', tabwriter.AlignRight)
	fmt.Fprintln(writer, "NAME\tVERSION\tSOURCE\tSTATUS\tBUILD\tMETADATA")
	for _, service := range services {
		status := parse(service.Metadata["status"])
		if status == "error" {
			status = service.Metadata["error"]
		}

		fmt.Fprintf(writer, "%s\t%s\t%s\t%s\t%s\t%s\n",
			service.Name,
			parse(service.Version),
			parse(service.Source),
			status,
			parse(service.Metadata["build"]),
			fmt.Sprintf("owner=%s,group=%s", parse(service.Metadata["owner"]), parse(service.Metadata["group"])))
	}
	writer.Flush()
}
<|endoftext|>


<commit_before>package main

import (
	"fmt"
)

var (
	version = "v0.4.0"
	commit  = "(unknown)"
)

func Version() string {
	return fmt.Sprintf("%s built from git %s", version, commit)
}
<commit_msg>Update version to 0.6.0<commit_after>package main

import (
	"fmt"
)

var (
	version = "v0.6.0"
	commit  = "(unknown)"
)

func Version() string {
	return fmt.Sprintf("%s built from git %s", version, commit)
}
<|endoftext|>


<commit_before>package main

import (
	"flag"
	"fmt"
	"strings"

	"github.com/tbruyelle/hipchat-go/hipchat"
)

const (
	maxMsgLen  = 128
	moreString = " [MORE]"
)

var (
	token  = flag.String("token", "", "The HipChat AuthToken")
	roomId = flag.String("room", "", "The HipChat room id")
)

func main() {
	flag.Parse()
	if *token == "" || *roomId == "" {
		flag.PrintDefaults()
		return
	}
	c := hipchat.NewClient(*token)
	hist, resp, err := c.Room.History(*roomId, &hipchat.HistoryRequest{})
	if err != nil {
		fmt.Printf("Error during room history req %q\n", err)
		fmt.Printf("Server returns %+v\n", resp)
		return
	}
	for _, m := range hist.Items {
		from := ""
		switch m.From.(type) {
		case string:
			from = m.From.(string)
		case map[string]interface{}:
			f := m.From.(map[string]interface{})
			from = f["name"].(string)
		}
		msg := m.Message
		if len(m.Message) > (maxMsgLen - len(moreString)) {
			msg = fmt.Sprintf("%s%s", strings.Replace(m.Message[:maxMsgLen], "\n", " - ", -1), moreString)
		}
		fmt.Printf("%s [%s]: %s\n", from, m.Date, msg)
	}
}
<commit_msg>Fixed build of hiptail example<commit_after>package main

import (
	"flag"
	"fmt"
	"strings"

	"github.com/tbruyelle/hipchat-go/hipchat"
)

const (
	maxMsgLen  = 128
	moreString = " [MORE]"
)

var (
	token  = flag.String("token", "", "The HipChat AuthToken")
	roomId = flag.String("room", "", "The HipChat room id")
)

func main() {
	flag.Parse()
	if *token == "" || *roomId == "" {
		flag.PrintDefaults()
		return
	}
	c := hipchat.NewClient(*token)
	hist, resp, err := c.Room.History(*roomId, &hipchat.HistoryOptions{})
	if err != nil {
		fmt.Printf("Error during room history req %q\n", err)
		fmt.Printf("Server returns %+v\n", resp)
		return
	}
	for _, m := range hist.Items {
		from := ""
		switch m.From.(type) {
		case string:
			from = m.From.(string)
		case map[string]interface{}:
			f := m.From.(map[string]interface{})
			from = f["name"].(string)
		}
		msg := m.Message
		if len(m.Message) > (maxMsgLen - len(moreString)) {
			msg = fmt.Sprintf("%s%s", strings.Replace(m.Message[:maxMsgLen], "\n", " - ", -1), moreString)
		}
		fmt.Printf("%s [%s]: %s\n", from, m.Date, msg)
	}
}
<|endoftext|>


<commit_before>package main

import "fmt"

type version struct {
	Major, Minor, Patch int
	Label               string
	Nick                string
}

var ver = version{
	Major: 1,
	Minor: 0,
	Patch: 0,
	Label: "pre"}

// CommitHash may be set on the build command line:
// go build -ldflags "-X main.CommitHash=`git rev-parse --short HEAD`"
var CommitHash string

const appName string = "dcrdata"

func (v *version) String() string {
	var hashStr string
	if CommitHash != "" {
		hashStr = "+" + CommitHash
	}
	if v.Label != "" {
		return fmt.Sprintf("%d.%d.%d-%s%s",
			v.Major, v.Minor, v.Patch, v.Label, hashStr)
	}
	return fmt.Sprintf("%d.%d.%d%s",
		v.Major, v.Minor, v.Patch, hashStr)
}
<commit_msg>Remove "pre" from version string.<commit_after>package main

import "fmt"

type version struct {
	Major, Minor, Patch int
	Label               string
	Nick                string
}

var ver = version{
	Major: 1,
	Minor: 0,
	Patch: 0,
	Label: ""}

// CommitHash may be set on the build command line:
// go build -ldflags "-X main.CommitHash=`git rev-parse --short HEAD`"
var CommitHash string

const appName string = "dcrdata"

func (v *version) String() string {
	var hashStr string
	if CommitHash != "" {
		hashStr = "+" + CommitHash
	}
	if v.Label != "" {
		return fmt.Sprintf("%d.%d.%d-%s%s",
			v.Major, v.Minor, v.Patch, v.Label, hashStr)
	}
	return fmt.Sprintf("%d.%d.%d%s",
		v.Major, v.Minor, v.Patch, hashStr)
}
<|endoftext|>


<commit_before>// Copyright 2020 Google LLC
//
// 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
//
// 	https://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 safehttp

import (
	"errors"
	"net/http"
	"net/textproto"
)

var disallowedHeaders = map[string]bool{"Set-Cookie": true}

const (
	disallowedErrorMessage = "disallowed header"
	immutableErrorMessage  = "immutable header"
)

// Header represents the key-value pairs in an HTTP header.
// The keys will be in canonical form, as returned by
// textproto.CanonicalMIMEHeaderKey.
type Header struct {
	wrapped   http.Header
	immutable map[string]bool
}

func newHeader(h http.Header) Header {
	return Header{wrapped: h, immutable: map[string]bool{}}
}

// MarkImmutable marks the header with the given name as immutable.
// This header is now read-only. The name is first canonicalized
// using textproto.CanonicalMIMEHeaderKey.
func (h Header) MarkImmutable(name string) {
	name = textproto.CanonicalMIMEHeaderKey(name)
	h.immutable[name] = true
}

// Set sets the header with the given name to the given value.
// The name is first canonicalized using textproto.CanonicalMIMEHeaderKey.
// If this headers is not immutable, this function removes all other
// values currently associated with this header before setting the new
// value. Returns an error when applied on immutable headers.
func (h Header) Set(name, value string) error {
	name = textproto.CanonicalMIMEHeaderKey(name)
	if disallowedHeaders[name] {
		return errors.New(disallowedErrorMessage)
	}
	if h.immutable[name] {
		return errors.New(immutableErrorMessage)
	}
	h.wrapped.Set(name, value)
	return nil
}

// Add adds a new header with the given name and the given value to
// the collection of headers. The name is first canonicalized using
// textproto.CanonicalMIMEHeaderKey. Returns an error when applied
// on immutable headers.
func (h Header) Add(name, value string) error {
	name = textproto.CanonicalMIMEHeaderKey(name)
	if disallowedHeaders[name] {
		return errors.New(disallowedErrorMessage)
	}
	if h.immutable[name] {
		return errors.New(immutableErrorMessage)
	}
	h.wrapped.Add(name, value)
	return nil
}

// Del deletes all headers with the given name. The name is first
// canonicalized using textproto.CanonicalMIMEHeaderKey. Returns an
// error when applied on immutable headers.
func (h Header) Del(name string) error {
	name = textproto.CanonicalMIMEHeaderKey(name)
	if disallowedHeaders[name] {
		return errors.New(disallowedErrorMessage)
	}
	if h.immutable[name] {
		return errors.New(immutableErrorMessage)
	}
	h.wrapped.Del(name)
	return nil
}

// Get returns the value of the first header with the given name.
// The name is first canonicalized using textproto.CanonicalMIMEHeaderKey.
// If no header exists with the given name then "" is returned.
func (h Header) Get(name string) string {
	return h.wrapped.Get(name)
}

// Values returns all the values of all the headers with the given name.
// The name is first canonicalized using textproto.CanonicalMIMEHeaderKey.
// If no header exists with the given name then nil is returned.
func (h Header) Values(name string) []string {
	return h.wrapped.Values(name)
}

// SetCookie adds the cookie provided as a Set-Cookie header in the header
// collection. If the cookie is nil or cookie.Name is invalid, an empty
// string is returned.
// TODO: Replace http.Cookie with safehttp.Cookie.
func (h Header) SetCookie(cookie *http.Cookie) {
	if v := cookie.String(); v != "" {
		h.wrapped.Add("Set-Cookie", v)
	}
}

// TODO: Add Write, WriteSubset and Clone when needed.
<commit_msg>Fixed incorrect comment<commit_after>// Copyright 2020 Google LLC
//
// 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
//
// 	https://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 safehttp

import (
	"errors"
	"net/http"
	"net/textproto"
)

var disallowedHeaders = map[string]bool{"Set-Cookie": true}

const (
	disallowedErrorMessage = "disallowed header"
	immutableErrorMessage  = "immutable header"
)

// Header represents the key-value pairs in an HTTP header.
// The keys will be in canonical form, as returned by
// textproto.CanonicalMIMEHeaderKey.
type Header struct {
	wrapped   http.Header
	immutable map[string]bool
}

func newHeader(h http.Header) Header {
	return Header{wrapped: h, immutable: map[string]bool{}}
}

// MarkImmutable marks the header with the given name as immutable.
// This header is now read-only. The name is first canonicalized
// using textproto.CanonicalMIMEHeaderKey.
func (h Header) MarkImmutable(name string) {
	name = textproto.CanonicalMIMEHeaderKey(name)
	h.immutable[name] = true
}

// Set sets the header with the given name to the given value.
// The name is first canonicalized using textproto.CanonicalMIMEHeaderKey.
// If this headers is not immutable, this function removes all other
// values currently associated with this header before setting the new
// value. Returns an error when applied on immutable headers.
func (h Header) Set(name, value string) error {
	name = textproto.CanonicalMIMEHeaderKey(name)
	if disallowedHeaders[name] {
		return errors.New(disallowedErrorMessage)
	}
	if h.immutable[name] {
		return errors.New(immutableErrorMessage)
	}
	h.wrapped.Set(name, value)
	return nil
}

// Add adds a new header with the given name and the given value to
// the collection of headers. The name is first canonicalized using
// textproto.CanonicalMIMEHeaderKey. Returns an error when applied
// on immutable headers.
func (h Header) Add(name, value string) error {
	name = textproto.CanonicalMIMEHeaderKey(name)
	if disallowedHeaders[name] {
		return errors.New(disallowedErrorMessage)
	}
	if h.immutable[name] {
		return errors.New(immutableErrorMessage)
	}
	h.wrapped.Add(name, value)
	return nil
}

// Del deletes all headers with the given name. The name is first
// canonicalized using textproto.CanonicalMIMEHeaderKey. Returns an
// error when applied on immutable headers.
func (h Header) Del(name string) error {
	name = textproto.CanonicalMIMEHeaderKey(name)
	if disallowedHeaders[name] {
		return errors.New(disallowedErrorMessage)
	}
	if h.immutable[name] {
		return errors.New(immutableErrorMessage)
	}
	h.wrapped.Del(name)
	return nil
}

// Get returns the value of the first header with the given name.
// The name is first canonicalized using textproto.CanonicalMIMEHeaderKey.
// If no header exists with the given name then "" is returned.
func (h Header) Get(name string) string {
	return h.wrapped.Get(name)
}

// Values returns all the values of all the headers with the given name.
// The name is first canonicalized using textproto.CanonicalMIMEHeaderKey.
// If no header exists with the given name then nil is returned.
func (h Header) Values(name string) []string {
	return h.wrapped.Values(name)
}

// SetCookie adds the cookie provided as a Set-Cookie header in the header
// collection. If the cookie is nil or cookie.Name is invalid, no header is
// added.
// TODO: Replace http.Cookie with safehttp.Cookie.
func (h Header) SetCookie(cookie *http.Cookie) {
	if v := cookie.String(); v != "" {
		h.wrapped.Add("Set-Cookie", v)
	}
}

// TODO: Add Write, WriteSubset and Clone when needed.
<|endoftext|>


<commit_before>package lifx

const Version = "0.4.0"
<commit_msg>1.0.0<commit_after>package lifx

const Version = "1.0.0"
<|endoftext|>


<commit_before>// Copyright 2017 phcurtis fn Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.

package fn

import (
	"io/ioutil"
	"log"
	"os"
	"testing"
)

func Test_unexportFuncs(t *testing.T) {
	tests := []struct {
		name  string
		nform nameform
		want  string
	}{
		{"lvlll-fullfn", nfull, "github.com/phcurtis/fn.Test_unexportFuncs.func1"},
		{"lvlll-basefn", nbase, "fn.Test_unexportFuncs.func1"},
	}

	for _, test := range tests {
		t.Run(test.name, func(t *testing.T) {
			got := lvlll(0, test.nform)
			if got != test.want {
				t.Errorf("\n got:%s \nwant:%s", got, test.want)
			}
		})
	}
}

func Test_forcepanichelplt(t *testing.T) {
	if !testing.Verbose() {
		LogSetOutput(ioutil.Discard) // to hide trace output
	} else {
		LogSetOutput(os.Stderr) // so will see trace output and LogTrace stuff
	}
	if !testing.Verbose() {
		log.SetOutput(ioutil.Discard) // toss log.Panic output
	}

	defer SetPkgCfgDef(true)       // restore defaults at end of this func
	defer log.SetOutput(os.Stderr) // restore log output

	f := func() func() {
		begTime, begFn, reffile, reflnum := helpltbeg(0, LbegTraceLab, "")
		return func() {
			helpltend(0, LendTraceLab, begTime, begFn, "hack"+reffile, reflnum, "")
		}
	}

	defer func() {
		var p interface{}
		p = recover()
		if testing.Verbose() {
			log.Printf("panicErr:%v\n", p)
		}
		if p == nil {
			t.Errorf("should have paniced ... due to hacking reffile ")
		}
		if testing.Verbose() {
			log.Println("Recovered from panic")
		}
	}()

	f()() // make panic happen
}
<commit_msg>log. to logt. and strMinWidth test<commit_after>// Copyright 2017 phcurtis fn Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.

package fn

import (
	"io/ioutil"
	"os"
	"testing"
)

func Test_unexportFuncs(t *testing.T) {
	tests := []struct {
		name  string
		nform nameform
		want  string
	}{
		{"lvlll-fullfn", nfull, "github.com/phcurtis/fn.Test_unexportFuncs.func1"},
		{"lvlll-basefn", nbase, "fn.Test_unexportFuncs.func1"},
	}

	for _, test := range tests {
		t.Run(test.name, func(t *testing.T) {
			got := lvlll(0, test.nform)
			if got != test.want {
				t.Errorf("\n got:%s \nwant:%s", got, test.want)
			}
		})
	}

	t.Run("strMinWidth", func(t *testing.T) {
		got := strMinWidth("12345", 10)
		want := "12345     "
		if got != want {
			t.Errorf("\n got:%s \nwant:%s", got, want)
		}
	})
}

func Test_forcepanichelplt(t *testing.T) {
	if !testing.Verbose() {
		LogSetOutput(ioutil.Discard) // to hide trace output
	} else {
		LogSetOutput(os.Stderr) // so will see trace output and LogTrace stuff
	}

	defer SetPkgCfgDef(true) // restore defaults at end of this func

	f := func() func() {
		begTime, begFn, reffile, reflnum := helpltbeg(0, LbegTraceLab, "")
		return func() {
			helpltend(0, LendTraceLab, begTime, begFn, "hack"+reffile, reflnum, "")
		}
	}

	defer func() {
		var p interface{}
		p = recover()
		if testing.Verbose() {
			t.Logf("panicErr:%v\n", p)
		}
		if p == nil {
			t.Errorf("should have paniced ... due to hacking reffile ")
		}
		if testing.Verbose() {
			t.Logf("%s\n", "Recovered from panic")
		}
	}()

	f()() // make panic happen
}
<|endoftext|>


<commit_before>package main

// The git commit that was compiled. This will be filled in by the compiler.
var GitCommit string
var GitDescribe string

// The main version number that is being run at the moment.
const Version = "0.5.6"

// A pre-release marker for the version. If this is "" (empty string)
// then it means that it is a final release. Otherwise, this is a pre-release
// such as "dev" (in development), "beta", "rc1", etc.
const VersionPrerelease = "dev"
<commit_msg>bump version<commit_after>package main

// The git commit that was compiled. This will be filled in by the compiler.
var GitCommit string
var GitDescribe string

// The main version number that is being run at the moment.
const Version = "0.5.6"

// A pre-release marker for the version. If this is "" (empty string)
// then it means that it is a final release. Otherwise, this is a pre-release
// such as "dev" (in development), "beta", "rc1", etc.
const VersionPrerelease = "rc1"
<|endoftext|>


<commit_before>package main

var Version string = "0.0.1"
<commit_msg>bump up<commit_after>package main

var Version string = "0.1.0"
<|endoftext|>


<commit_before>// Copyright (c) 2017-2022 Snowflake Computing Inc. All rights reserved.

package gosnowflake

// SnowflakeGoDriverVersion is the version of Go Snowflake Driver.
const SnowflakeGoDriverVersion = "1.6.5"
<commit_msg>SNOW-530866: Bumped up GoLang connector PATCH version from 1.6.5 to 1.6.6 (#529)<commit_after>// Copyright (c) 2017-2022 Snowflake Computing Inc. All rights reserved.

package gosnowflake

// SnowflakeGoDriverVersion is the version of Go Snowflake Driver.
const SnowflakeGoDriverVersion = "1.6.6"
<|endoftext|>


<commit_before>package sdk

const VERSION = "8.1.6"
<commit_msg>Incremented version.<commit_after>package sdk

const VERSION = "8.2.1"
<|endoftext|>


<commit_before>package main

import (
	"bytes"
	"errors"
	"fmt"
	"io/ioutil"
	"log"
	"math/rand"
	"net/http"
	"os"
	"path/filepath"
	"time"

	"github.com/stripe/sequins/blocks"
)

const versionHeader = "X-Sequins-Version"

var errNoAvailablePeers = errors.New("no available peers")
var errProxiedIncorrectly = errors.New("this server doesn't have the requested partition")

// TODO: need a way to clean up zookeeper cruft

// TODO: verify that the set of files stays consistent; once at startup, once
// when we finish indexing, and then maybe periodically after that.

// A version represents a single version of a particular sequins db: in
// other words, a collection of files. In the distributed case, it understands
// partitions and can route requests.
type version struct {
	sequins *sequins

	path          string
	db            string
	name          string
	created       time.Time
	blockStore    *blocks.BlockStore
	partitions    *partitions
	numPartitions int
}

func newVersion(sequins *sequins, path, db, name string, numPartitions int) *version {
	vs := &version{
		sequins:       sequins,
		path:          path,
		db:            db,
		name:          name,
		created:       time.Now(),
		numPartitions: numPartitions,
	}

	var local map[int]bool
	if sequins.peers != nil {
		vs.partitions = watchPartitions(sequins.zkWatcher, sequins.peers,
			db, name, numPartitions, sequins.config.ZK.Replication)

		local = vs.partitions.pickLocalPartitions()
	}

	// Try loading anything we have locally. If it doesn't work out, that's ok.
	_, err := os.Stat(filepath.Join(path, ".manifest"))
	if err == nil {
		log.Println("Loading version from manifest at", path)

		blockStore, err := blocks.NewFromManifest(path, local)
		if err != nil {
			log.Println("Error loading", vs.db, "version", vs.name, "from manifest:", err)
		}

		vs.blockStore = blockStore
		if vs.partitions != nil {
			vs.partitions.updateLocalPartitions(local)
		}
	}

	return vs
}

func (vs *version) ready() bool {
	if vs.numPartitions == 0 {
		return true
	} else if vs.sequins.peers == nil {
		return vs.blockStore != nil
	}

	return vs.partitions.ready()
}

func (vs *version) advertiseAndWait() bool {
	if vs.sequins.peers == nil || vs.numPartitions == 0 {
		return true
	}

	return vs.partitions.advertiseAndWait()
}

// serveKey is the entrypoint for incoming HTTP requests.
func (vs *version) serveKey(w http.ResponseWriter, r *http.Request, key string) {
	res, err := vs.get(key, r)

	if err == errNoAvailablePeers {
		// All of our peers failed us. 502.
		log.Printf("All peers failed to respond for /%s/%s (version %s)", vs.db, key, vs.name)
		w.WriteHeader(http.StatusBadGateway)
	} else if err != nil {
		// Some other error. 500.
		log.Printf("Error fetching value for /%s/%s: %s\n", vs.db, key, err)
		w.WriteHeader(http.StatusInternalServerError)
	} else if res == nil {
		// Either the key doesn't exist locally, or we got back the
		// proxied response, and it didn't exist on the peer. 404.
		w.Header().Add(versionHeader, vs.name)
		w.WriteHeader(http.StatusNotFound)
	} else {
		// Explicitly unset Content-Type, so ServeContent doesn't try to do any
		// sniffing.
		w.Header()["Content-Type"] = nil
		w.Header().Add(versionHeader, vs.name)
		http.ServeContent(w, r, key, vs.created, bytes.NewReader(res))
	}
}

// get looks up a value locally, or, failing that, asks a peer that has it.
// If the request was proxied, it is not proxied further.
func (vs *version) get(key string, r *http.Request) ([]byte, error) {
	if vs.numPartitions == 0 {
		return nil, nil
	}

	partition, alternatePartition := blocks.KeyPartition(key, vs.numPartitions)
	if vs.hasPartition(partition) || vs.hasPartition(alternatePartition) {
		return vs.blockStore.Get(key)
	} else if r.URL.Query().Get("proxy") == "" {
		res, err := vs.proxyRequest(partition, r)
		if res == nil && err == nil && alternatePartition != partition {
			log.Println("Trying alternate partition for pathological key", key)
			res, err = vs.proxyRequest(alternatePartition, r)
		}

		return res, err
	} else {
		return nil, errProxiedIncorrectly
	}

}

// hasPartition returns true if we have the partition available locally.
func (vs *version) hasPartition(partition int) bool {
	return vs.partitions == nil || vs.partitions.local[partition]
}

// proxyRequest proxies the request, trying each peer that should have the key
// in turn.
func (vs *version) proxyRequest(partition int, r *http.Request) ([]byte, error) {
	peers := vs.partitions.getPeers(partition)

	// Shuffle the peers, so we try them in a random order.
	// TODO: don't blacklist nodes, but we can weight them lower
	shuffled := make([]string, len(peers))
	perm := rand.Perm(len(peers))
	for i, v := range perm {
		shuffled[v] = peers[i]
	}

	for _, peer := range shuffled {
		res, err := vs.proxyAttempt(peer, r)
		if err != nil {
			log.Printf("Error proxying request to peer %s: %s", r.URL.String(), err)
			continue
		}

		return res, nil
	}

	return nil, errNoAvailablePeers
}

func (vs *version) proxyAttempt(peer string, r *http.Request) ([]byte, error) {
	r.URL.RawQuery = fmt.Sprintf("proxy=%s", vs.name)
	r.URL.Scheme = "http"
	r.URL.Host = peer
	proxyRequest, err := http.NewRequest("GET", r.URL.String(), nil)
	if err != nil {
		return nil, err
	}

	resp, err := vs.sequins.proxyClient.Do(proxyRequest)
	if err != nil {
		return nil, err
	}

	defer resp.Body.Close()
	if resp.StatusCode == 404 {
		return nil, nil
	} else if resp.StatusCode != 200 {
		return nil, fmt.Errorf("got %d", resp.StatusCode)
	}

	return ioutil.ReadAll(resp.Body)
}

func (vs *version) close() {
	if vs.partitions != nil {
		vs.partitions.close()
	}

	if vs.blockStore != nil {
		vs.blockStore.Close()
	}
}

func (vs *version) delete() error {
	if vs.blockStore != nil {
		return vs.blockStore.Delete()
	}

	return nil
}
<commit_msg>Make sure we always proxy keys if we don't have any data locally<commit_after>package main

import (
	"bytes"
	"errors"
	"fmt"
	"io/ioutil"
	"log"
	"math/rand"
	"net/http"
	"os"
	"path/filepath"
	"time"

	"github.com/stripe/sequins/blocks"
)

const versionHeader = "X-Sequins-Version"

var errNoAvailablePeers = errors.New("no available peers")
var errProxiedIncorrectly = errors.New("this server doesn't have the requested partition")

// TODO: need a way to clean up zookeeper cruft

// TODO: verify that the set of files stays consistent; once at startup, once
// when we finish indexing, and then maybe periodically after that.

// A version represents a single version of a particular sequins db: in
// other words, a collection of files. In the distributed case, it understands
// partitions and can route requests.
type version struct {
	sequins *sequins

	path          string
	db            string
	name          string
	created       time.Time
	blockStore    *blocks.BlockStore
	partitions    *partitions
	numPartitions int
}

func newVersion(sequins *sequins, path, db, name string, numPartitions int) *version {
	vs := &version{
		sequins:       sequins,
		path:          path,
		db:            db,
		name:          name,
		created:       time.Now(),
		numPartitions: numPartitions,
	}

	var local map[int]bool
	if sequins.peers != nil {
		vs.partitions = watchPartitions(sequins.zkWatcher, sequins.peers,
			db, name, numPartitions, sequins.config.ZK.Replication)

		local = vs.partitions.pickLocalPartitions()
	}

	// Try loading anything we have locally. If it doesn't work out, that's ok.
	_, err := os.Stat(filepath.Join(path, ".manifest"))
	if err == nil {
		log.Println("Loading version from manifest at", path)

		blockStore, err := blocks.NewFromManifest(path, local)
		if err != nil {
			log.Println("Error loading", vs.db, "version", vs.name, "from manifest:", err)
		}

		vs.blockStore = blockStore
		if vs.partitions != nil {
			vs.partitions.updateLocalPartitions(local)
		}
	}

	return vs
}

func (vs *version) ready() bool {
	if vs.numPartitions == 0 {
		return true
	} else if vs.sequins.peers == nil {
		return vs.blockStore != nil
	}

	return vs.partitions.ready()
}

func (vs *version) advertiseAndWait() bool {
	if vs.sequins.peers == nil || vs.numPartitions == 0 {
		return true
	}

	return vs.partitions.advertiseAndWait()
}

// serveKey is the entrypoint for incoming HTTP requests.
func (vs *version) serveKey(w http.ResponseWriter, r *http.Request, key string) {
	res, err := vs.get(key, r)

	if err == errNoAvailablePeers {
		// All of our peers failed us. 502.
		log.Printf("All peers failed to respond for /%s/%s (version %s)", vs.db, key, vs.name)
		w.WriteHeader(http.StatusBadGateway)
	} else if err != nil {
		// Some other error. 500.
		log.Printf("Error fetching value for /%s/%s: %s\n", vs.db, key, err)
		w.WriteHeader(http.StatusInternalServerError)
	} else if res == nil {
		// Either the key doesn't exist locally, or we got back the
		// proxied response, and it didn't exist on the peer. 404.
		w.Header().Add(versionHeader, vs.name)
		w.WriteHeader(http.StatusNotFound)
	} else {
		// Explicitly unset Content-Type, so ServeContent doesn't try to do any
		// sniffing.
		w.Header()["Content-Type"] = nil
		w.Header().Add(versionHeader, vs.name)
		http.ServeContent(w, r, key, vs.created, bytes.NewReader(res))
	}
}

// get looks up a value locally, or, failing that, asks a peer that has it.
// If the request was proxied, it is not proxied further.
func (vs *version) get(key string, r *http.Request) ([]byte, error) {
	if vs.numPartitions == 0 {
		return nil, nil
	}

	partition, alternatePartition := blocks.KeyPartition(key, vs.numPartitions)
	if vs.hasPartition(partition) || vs.hasPartition(alternatePartition) {
		return vs.blockStore.Get(key)
	} else if r.URL.Query().Get("proxy") == "" {
		res, err := vs.proxyRequest(partition, r)
		if res == nil && err == nil && alternatePartition != partition {
			log.Println("Trying alternate partition for pathological key", key)
			res, err = vs.proxyRequest(alternatePartition, r)
		}

		return res, err
	} else {
		return nil, errProxiedIncorrectly
	}

}

// hasPartition returns true if we have the partition available locally.
func (vs *version) hasPartition(partition int) bool {
	return vs.blockStore != nil && (vs.partitions == nil || vs.partitions.local[partition])
}

// proxyRequest proxies the request, trying each peer that should have the key
// in turn.
func (vs *version) proxyRequest(partition int, r *http.Request) ([]byte, error) {
	peers := vs.partitions.getPeers(partition)

	// Shuffle the peers, so we try them in a random order.
	// TODO: don't blacklist nodes, but we can weight them lower
	shuffled := make([]string, len(peers))
	perm := rand.Perm(len(peers))
	for i, v := range perm {
		shuffled[v] = peers[i]
	}

	for _, peer := range shuffled {
		res, err := vs.proxyAttempt(peer, r)
		if err != nil {
			log.Printf("Error proxying request to peer %s: %s", r.URL.String(), err)
			continue
		}

		return res, nil
	}

	return nil, errNoAvailablePeers
}

func (vs *version) proxyAttempt(peer string, r *http.Request) ([]byte, error) {
	r.URL.RawQuery = fmt.Sprintf("proxy=%s", vs.name)
	r.URL.Scheme = "http"
	r.URL.Host = peer
	proxyRequest, err := http.NewRequest("GET", r.URL.String(), nil)
	if err != nil {
		return nil, err
	}

	resp, err := vs.sequins.proxyClient.Do(proxyRequest)
	if err != nil {
		return nil, err
	}

	defer resp.Body.Close()
	if resp.StatusCode == 404 {
		return nil, nil
	} else if resp.StatusCode != 200 {
		return nil, fmt.Errorf("got %d", resp.StatusCode)
	}

	return ioutil.ReadAll(resp.Body)
}

func (vs *version) close() {
	if vs.partitions != nil {
		vs.partitions.close()
	}

	if vs.blockStore != nil {
		vs.blockStore.Close()
	}
}

func (vs *version) delete() error {
	if vs.blockStore != nil {
		return vs.blockStore.Delete()
	}

	return nil
}
<|endoftext|>


<commit_before>package main

const Version = "0.1.0"
<commit_msg>bump to 0.1.0+git<commit_after>package main

const Version = "0.1.0+git"
<|endoftext|>


<commit_before>/*
Copyright 2019 The Kubernetes 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 designate

import (
	"fmt"

	"github.com/gophercloud/gophercloud/openstack/dns/v2/recordsets"

	"k8s.io/kops/dnsprovider/pkg/dnsprovider"
)

var _ dnsprovider.ResourceRecordChangeset = &ResourceRecordChangeset{}

type ResourceRecordChangeset struct {
	zone   *Zone
	rrsets *ResourceRecordSets

	additions []dnsprovider.ResourceRecordSet
	removals  []dnsprovider.ResourceRecordSet
	upserts   []dnsprovider.ResourceRecordSet
}

func (c *ResourceRecordChangeset) Add(rrset dnsprovider.ResourceRecordSet) dnsprovider.ResourceRecordChangeset {
	c.additions = append(c.additions, rrset)
	return c
}

func (c *ResourceRecordChangeset) Remove(rrset dnsprovider.ResourceRecordSet) dnsprovider.ResourceRecordChangeset {
	c.removals = append(c.removals, rrset)
	return c
}

func (c *ResourceRecordChangeset) Upsert(rrset dnsprovider.ResourceRecordSet) dnsprovider.ResourceRecordChangeset {
	c.upserts = append(c.upserts, rrset)
	return c
}

func (c *ResourceRecordChangeset) Apply() error {
	zoneID := c.zone.impl.ID

	for _, removal := range c.removals {
		rrID, err := c.nameToID(removal.Name())
		if err != nil {
			return err
		}
		err = recordsets.Delete(c.zone.zones.iface.sc, zoneID, rrID).ExtractErr()
		if err != nil {
			return err
		}
	}

	for _, addition := range c.additions {
		opts := recordsets.CreateOpts{
			Name:    addition.Name(),
			TTL:     int(addition.Ttl()),
			Type:    string(addition.Type()),
			Records: addition.Rrdatas(),
		}
		_, err := recordsets.Create(c.zone.zones.iface.sc, zoneID, opts).Extract()
		if err != nil {
			return err
		}
	}

	for _, upsert := range c.upserts {
		rrID, err := c.nameToID(upsert.Name())
		if err != nil {
			return err
		}
		uopts := recordsets.UpdateOpts{
			TTL:     int(upsert.Ttl()),
			Records: upsert.Rrdatas(),
		}
		_, err = recordsets.Update(c.zone.zones.iface.sc, zoneID, rrID, uopts).Extract()
		if err != nil {
			copts := recordsets.CreateOpts{
				Name:    upsert.Name(),
				TTL:     int(upsert.Ttl()),
				Type:    string(upsert.Type()),
				Records: upsert.Rrdatas(),
			}
			_, err := recordsets.Create(c.zone.zones.iface.sc, zoneID, copts).Extract()
			if err != nil {
				return err
			}
		}
	}

	return nil
}

func (c *ResourceRecordChangeset) IsEmpty() bool {
	return len(c.removals) == 0 && len(c.additions) == 0 && len(c.upserts) == 0
}

// ResourceRecordSets returns the parent ResourceRecordSets
func (c *ResourceRecordChangeset) ResourceRecordSets() dnsprovider.ResourceRecordSets {
	return c.rrsets
}

func (c *ResourceRecordChangeset) nameToID(name string) (string, error) {
	opts := recordsets.ListOpts{
		Name: name,
	}
	allPages, err := recordsets.ListByZone(c.zone.zones.iface.sc, c.zone.impl.ID, opts).AllPages()
	if err != nil {
		return "", err
	}
	rrs, err := recordsets.ExtractRecordSets(allPages)
	if err != nil {
		return "", err
	}
	switch len(rrs) {
	case 0:
		return "", fmt.Errorf("couldn't find recordset with name: %s, expected 1", name)
	case 1:
		return rrs[0].ID, nil
	default:
		return "", fmt.Errorf("found multiple recordsets with name: %s, expected 1", name)
	}
}
<commit_msg>fix errors<commit_after>/*
Copyright 2019 The Kubernetes 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 designate

import (
	"fmt"

	"github.com/gophercloud/gophercloud/openstack/dns/v2/recordsets"

	"k8s.io/kops/dnsprovider/pkg/dnsprovider"
)

var _ dnsprovider.ResourceRecordChangeset = &ResourceRecordChangeset{}

type ResourceRecordChangeset struct {
	zone   *Zone
	rrsets *ResourceRecordSets

	additions []dnsprovider.ResourceRecordSet
	removals  []dnsprovider.ResourceRecordSet
	upserts   []dnsprovider.ResourceRecordSet
}

func (c *ResourceRecordChangeset) Add(rrset dnsprovider.ResourceRecordSet) dnsprovider.ResourceRecordChangeset {
	c.additions = append(c.additions, rrset)
	return c
}

func (c *ResourceRecordChangeset) Remove(rrset dnsprovider.ResourceRecordSet) dnsprovider.ResourceRecordChangeset {
	c.removals = append(c.removals, rrset)
	return c
}

func (c *ResourceRecordChangeset) Upsert(rrset dnsprovider.ResourceRecordSet) dnsprovider.ResourceRecordChangeset {
	c.upserts = append(c.upserts, rrset)
	return c
}

func (c *ResourceRecordChangeset) Apply() error {
	zoneID := c.zone.impl.ID

	for _, removal := range c.removals {
		rrID, err := c.nameToID(removal.Name())
		if err != nil {
			return err
		}
		err = recordsets.Delete(c.zone.zones.iface.sc, zoneID, rrID).ExtractErr()
		if err != nil {
			return err
		}
	}

	for _, addition := range c.additions {
		opts := recordsets.CreateOpts{
			Name:    addition.Name(),
			TTL:     int(addition.Ttl()),
			Type:    string(addition.Type()),
			Records: addition.Rrdatas(),
		}
		_, err := recordsets.Create(c.zone.zones.iface.sc, zoneID, opts).Extract()
		if err != nil {
			return err
		}
	}

	for _, upsert := range c.upserts {
		rrID, err := c.nameToID(upsert.Name())
		if err != nil {
			return err
		}
		ttl := int(upsert.Ttl())
		uopts := recordsets.UpdateOpts{
			TTL:     &ttl,
			Records: upsert.Rrdatas(),
		}
		_, err = recordsets.Update(c.zone.zones.iface.sc, zoneID, rrID, uopts).Extract()
		if err != nil {
			copts := recordsets.CreateOpts{
				Name:    upsert.Name(),
				TTL:     int(upsert.Ttl()),
				Type:    string(upsert.Type()),
				Records: upsert.Rrdatas(),
			}
			_, err := recordsets.Create(c.zone.zones.iface.sc, zoneID, copts).Extract()
			if err != nil {
				return err
			}
		}
	}

	return nil
}

func (c *ResourceRecordChangeset) IsEmpty() bool {
	return len(c.removals) == 0 && len(c.additions) == 0 && len(c.upserts) == 0
}

// ResourceRecordSets returns the parent ResourceRecordSets
func (c *ResourceRecordChangeset) ResourceRecordSets() dnsprovider.ResourceRecordSets {
	return c.rrsets
}

func (c *ResourceRecordChangeset) nameToID(name string) (string, error) {
	opts := recordsets.ListOpts{
		Name: name,
	}
	allPages, err := recordsets.ListByZone(c.zone.zones.iface.sc, c.zone.impl.ID, opts).AllPages()
	if err != nil {
		return "", err
	}
	rrs, err := recordsets.ExtractRecordSets(allPages)
	if err != nil {
		return "", err
	}
	switch len(rrs) {
	case 0:
		return "", fmt.Errorf("couldn't find recordset with name: %s, expected 1", name)
	case 1:
		return rrs[0].ID, nil
	default:
		return "", fmt.Errorf("found multiple recordsets with name: %s, expected 1", name)
	}
}
<|endoftext|>


<commit_before>// +build !gromacs

/*
 * general_test.go
 *
 * Copyright 2012 Raul Mera <rmera{at}chemDOThelsinkiDOTfi>
 *
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU Lesser General Public License as
 * published by the Free Software Foundation; either version 2.1 of the
 * License, or (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General
 * Public License along with this program.  If not, see
 * <http://www.gnu.org/licenses/>.
 *
 *
 */

/*This provides some tests for the library, in the form of little functions
 * that have practical applications*/

package chem

import "github.com/skelterjohn/go.matrix"
import "fmt"
import "testing"
import "os"

//TestChangeAxis reads the PDB 2c9v.pdb from the test directory, collects
//The CA and CB of residue D124 of the chain A, and uses Clifford algebra to rotate the
//whole molecule such as the vector defined by these 2 atoms is
//aligned with the Z axis. The new molecule is written
//as 2c9v_aligned.pdb to the test folder.
func BenchmarkChangeAxis(Te *testing.B) {
	mol, err := PdbRead("test/2c9v.pdb", true)
	if err != nil {
		Te.Error(err)
	}
	//The selection thing
	orient_atoms := [2]int{0, 0}
	for index := 0; index < mol.Len(); index++ {
		atom := mol.Atom(index)
		if atom.Chain == 'A' && atom.Molid == 124 {
			if atom.Name == "CA" {
				orient_atoms[0] = index
			} else if atom.Name == "CB" {
				orient_atoms[1] = index
			}
		}
	}
	//Get the axis of rotation
	//ov1:=mol.Coord(orient_atoms[0], 0)
	ov2 := mol.Coord(orient_atoms[1], 0)
	//now we center the thing in the beta carbon of D124
	err = SubRow(mol.Coords[0], ov2)
	//Now the rotation
	ov1 := mol.Coord(orient_atoms[0], 0) //make sure we have the correct versions
	ov2 = mol.Coord(orient_atoms[1], 0)  //same
	orient := ov2.Copy()
	orient.SubtractDense(ov1)
	//	PdbWrite(mol,"test/2c9v-124centered.pdb")
	Z := matrix.MakeDenseMatrix([]float64{0, 0, 1}, 1, 3)
	axis, _ := Cross3D(orient, Z)
	angle := AngleInVectors(orient, Z)
	mol.Coords[0] = Rotate(mol.Coords[0], axis, angle)
	if err != nil {
		Te.Error(err)
	}
	PdbWrite(mol, "test/2c9v-aligned.pdb")
	fmt.Println("bench1")
}

//TestOldChangeAxis reads the PDB 2c9v.pdb from the test directory, collects
//The CA and CB of residue D124 of the chain A, and rotates the
//whole molecule such as the vector defined by these 2 atoms is
//aligned with the Z axis. The new molecule is written
//as 2c9v_aligned.pdb to the test folder.
func BenchmarkOldChangeAxis(Te *testing.B) {
	mol, err := PdbRead("test/2c9v.pdb", true)
	if err != nil {
		Te.Error(err)
	}
	orient_atoms := [2]int{0, 0}
	for index := 0; index < mol.Len(); index++ {
		atom := mol.Atom(index)
		if atom.Chain == 'A' && atom.Molid == 124 {
			if atom.Name == "CA" {
				orient_atoms[0] = index
			} else if atom.Name == "CB" {
				orient_atoms[1] = index
			}
		}
	}
	ov1 := mol.Coord(orient_atoms[0], 0)
	ov2 := mol.Coord(orient_atoms[1], 0)
	//now we center the thing in the beta carbon of D124
	err = SubRow(mol.Coords[0], ov2)
	//Now the rotation
	ov1 = mol.Coord(orient_atoms[0], 0) //make sure we have the correct versions
	ov2 = mol.Coord(orient_atoms[1], 0) //same
	orient := ov2.Copy()
	orient.SubtractDense(ov1)
	rotation := GetSwitchZ(orient)
	//	fmt.Println("rotation: ",rotation)
	mol.Coords[0] = matrix.ParallelProduct(mol.Coords[0], rotation)
	//	fmt.Println(orient_atoms[1], mol.Atom(orient_atoms[1]),mol.Atom(orient_atoms[0]))
	if err != nil {
		Te.Error(err)
	}
	PdbWrite(mol, "test/2c9v-old-aligned.pdb")
	fmt.Println("bench2")
}

//TestMultiXyz tests that multi-XYZ files are opened and read correctly.
func TestMultiXyz(Te *testing.T) {
	mol, err := XyzRead("test/sample.xyz")
	if err != nil {
		Te.Error(err)
	}
	fmt.Println("Read: ", len(mol.Coords), " snapshots")
	fmt.Println("Atom 42 Coords (should change)")
	fmt.Println("First snapshot: ", mol.Coords[0].GetRowVector(41), "Second snapshot: ", mol.Coords[1].GetRowVector(41))
	fmt.Println("Atom 3 Coords (shouldnt change)")
	fmt.Println("First snapshot: ", mol.Coords[0].GetRowVector(2), "Second snapshot: ", mol.Coords[1].GetRowVector(2))

}

//TestGeo opens the sample.xyz file in the test directory, and pull a number of hardcoded atoms
//In the direction of a hardcoded vectos. It builds 12 files with the pulled atoms  displaced by
//different ammounts along the pulling vector
func TestGeo(Te *testing.T) {
	pulled_atoms := [7]int{43, 41, 42, 40, 85, 86, 87}
	pulling_vector := [2]int{40, 88}
	mol, err := XyzRead("test/sample.xyz")
	if err != nil {
		Te.Error(err)
	}
	pulled_res := SomeRows(mol.Coords[0], pulled_atoms[:])
	at1 := mol.Coord(pulling_vector[0], 0)
	vector := mol.Coord(pulling_vector[1], 0)
	vector = vector.Copy()
	err = vector.SubtractDense(at1)
	if err != nil {
		Te.Error(err)
	}
	vector = Unitarize(vector)
	var scale_factors = [12]float64{-1.0, -2.0, 1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0, 9.0, 10.0}
	for _, scaling := range scale_factors {
		vec := vector.Copy()
		pulled := pulled_res.Copy()
		vec.Scale(scaling)
		err = AddRow(pulled, vec)
		if err != nil {
			Te.Error(err)
		}
		mol.SetCoords(pulled, pulled_atoms[:], 0)
		err = mol.Corrupted()
		if err != nil {
			Te.Error(err)
		}
		XyzWrite(mol, mol.Coords[0], fmt.Sprintf("test/sample_%03.1f.xyz", scaling))
	}
}

//TestRama tests the Ramachandran plot functionality.
//it generates a Ramachandran plot for the chain A of the PDB 2c9v.
func TestRama(Te *testing.T) {
	mol, err := PdbRead("test/2c9v.pdb", true)
	if err != nil {
		Te.Error(err)
	}
	ramalist, err := RamaList(mol, "A", []int{0, -1}) ////
	if err != nil {
		Te.Error(err)
	}
	rama, err := RamaCalc(mol.Coords[0], ramalist)
	if err != nil {
		Te.Error(err)
	}
	fmt.Println("Rama", rama, len(rama), len(ramalist), mol.Len())
	err = RamaPlot(rama, "test/Rama")
	if err != nil {
		Te.Error(err)
	}
	//PdbWrite(mol,"test/Used4Rama.pdb")
	//for the 3 residue  I should get -131.99, 152.49.
}

//TestQM tests the QM functionality. It prepares input for ORCA and MOPAC
//In the case of MOPAC it reads a previously prepared output and gets the energy.
func TestQM(Te *testing.T) {
	mol, err := XyzRead("test/sample.xyz")
	if err != nil {
		Te.Error(err)
	}
	if err := mol.Corrupted(); err != nil {
		Te.Error(err)
	}
	mol.Del(mol.Len() - 1)
	mol.SetCharge(1)
	mol.SetUnpaired(0)
	calc := new(QMCalc)
	calc.SCFTightness = 3 //very demanding
	calc.Optimize = true
	calc.Method = "BLYP"
	calc.Dielectric = 4
	calc.Basis = "def2-TZVPP"
	calc.HighBasis = "def2-QZVPP"
	calc.HBAtoms = []int{3, 10, 12}
	calc.HBElements = []string{"Cu", "Zn"}
	calc.RI=true
	calc.Disperssion = "D2"
	calc.CConstraints = []int{0, 10, 20}
	orca := MakeOrcaRunner()
	atoms, _ := mol.Next(true)
	original_dir, _ := os.Getwd() //will check in a few lines
	if err = os.Chdir("./test"); err != nil {
		Te.Error(err)
	}
	_ = orca.BuildInput(mol, atoms, calc)
	path, _ := os.Getwd()
	fmt.Println(path)
	//Now a MOPAC optimization with the same configuration.
	mopac := MakeMopacRunner()
	mopac.BuildInput(mol, atoms, calc)
	mopaccommand := os.Getenv("MOPAC_LICENSE") + "/MOPAC2009.exe"
	mopac.SetCommand(mopaccommand)
	fmt.Println("command", mopaccommand)
	//	if err:=mopac.Run(true); err!=nil{
	//		Te.Error(err.Error())
	//	}
	energy, err := mopac.GetEnergy()
	if err != nil {
		if err.Error() == "Probable problem in calculation" {
			fmt.Println(err.Error())
		} else {
			Te.Error(err)
		}
	}
	geometry, err := mopac.GetGeometry(mol)
	if err != nil {
		if err.Error() == "Probable problem in calculation" {
			fmt.Println(err.Error())
		} else {
			Te.Error(err)
		}
	}
	mol.Coords[0] = geometry
	fmt.Println(energy)
	if err := XyzWrite(mol, mol.Coords[0], "mopac.xyz"); err != nil {
		Te.Error(err)
	}
	//Took away this because it takes too long to run :-)
	/*	if err=orca.Run(true); err!=nil{
		Te.Error(err)
		}
	*/
	if err = os.Chdir(original_dir); err != nil {
		Te.Error(err)
	}
}

func TestMatrix(Te *testing.T) {
	a := []float64{1, 1, 4, 2, 2, 5, 3, 3, 6}
	A := matrix.MakeDenseMatrix(a, 3, 3)
	fmt.Println("before:\n", A)
	A, err := DMDelRow(A, 1)
	if err != nil {
		Te.Error(err)
	}
	fmt.Println("after:\n", A)
}

//This function tests the SelCone function.
//it selects a 2-way cone from 3 residues on the interface of SOD1 (PDB: 2c9v)
//and makes a new PDB with them.
func TestSelectCone(Te *testing.T) {
	mol, err := PdbRead("test/2c9v.pdb", true)
	if err != nil {
		Te.Error(err)
	}
	res := []int{116, 146, 147}
	allowed_chains := []string{"A", "F"}
	sele := AtomsFromMolecules(mol, res, allowed_chains)
	fmt.Println(sele)
	selection := SomeRows(mol.Coords[0], sele)
	test, _ := mol.SomeAtoms(sele) //Debug info.
	fmt.Println(test[2], test[3])
	cone := SelCone(mol.Coords[0], selection, 0.75, 20, 1, 0, 0) //0.524 approx pi/6 approx 30deg.
	top, _ := mol.SomeAtoms(cone)
	ref, _ := MakeTopology(top, 0, 1)
	coordst := SomeRows(mol.Coords[0], cone)
	coords := make([]*matrix.DenseMatrix, 1, 1)
	coords[0] = coordst
	newmol, _ := MakeMolecule(ref, coords, mol.Bfactors)
	PdbWrite(newmol, "test/mylittlecone.pdb")

}

func TestReorder(Te *testing.T){
	mol, err := PdbRead("test/2c9v.pdb",false)
	if err != nil {
		Te.Error(err)
	}
	for key,val:=range(mol.Atoms){
		if val.Molid==6{
			mol.Atoms[key].Id=9999
			mol.Atoms[key].Molid=444
		}
	}
	mol.ResetIds()
	PdbWrite(mol,"test/ordertest.pdb")

}

<commit_msg>dcd reading partially working<commit_after>// +build !gromacs

/*
 * general_test.go
 *
 * Copyright 2012 Raul Mera <rmera{at}chemDOThelsinkiDOTfi>
 *
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU Lesser General Public License as
 * published by the Free Software Foundation; either version 2.1 of the
 * License, or (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General
 * Public License along with this program.  If not, see
 * <http://www.gnu.org/licenses/>.
 *
 *
 */

/*This provides some tests for the library, in the form of little functions
 * that have practical applications*/

package chem

import "github.com/skelterjohn/go.matrix"
import "fmt"
import "testing"
import "os"

//TestChangeAxis reads the PDB 2c9v.pdb from the test directory, collects
//The CA and CB of residue D124 of the chain A, and uses Clifford algebra to rotate the
//whole molecule such as the vector defined by these 2 atoms is
//aligned with the Z axis. The new molecule is written
//as 2c9v_aligned.pdb to the test folder.
func BenchmarkChangeAxis(Te *testing.B) {
	mol, err := PdbRead("test/2c9v.pdb", true)
	if err != nil {
		Te.Error(err)
	}
	//The selection thing
	orient_atoms := [2]int{0, 0}
	for index := 0; index < mol.Len(); index++ {
		atom := mol.Atom(index)
		if atom.Chain == 'A' && atom.Molid == 124 {
			if atom.Name == "CA" {
				orient_atoms[0] = index
			} else if atom.Name == "CB" {
				orient_atoms[1] = index
			}
		}
	}
	//Get the axis of rotation
	//ov1:=mol.Coord(orient_atoms[0], 0)
	ov2 := mol.Coord(orient_atoms[1], 0)
	//now we center the thing in the beta carbon of D124
	err = SubRow(mol.Coords[0], ov2)
	//Now the rotation
	ov1 := mol.Coord(orient_atoms[0], 0) //make sure we have the correct versions
	ov2 = mol.Coord(orient_atoms[1], 0)  //same
	orient := ov2.Copy()
	orient.SubtractDense(ov1)
	//	PdbWrite(mol,"test/2c9v-124centered.pdb")
	Z := matrix.MakeDenseMatrix([]float64{0, 0, 1}, 1, 3)
	axis, _ := Cross3D(orient, Z)
	angle := AngleInVectors(orient, Z)
	mol.Coords[0] = Rotate(mol.Coords[0], axis, angle)
	if err != nil {
		Te.Error(err)
	}
	PdbWrite(mol, "test/2c9v-aligned.pdb")
	fmt.Println("bench1")
}

//TestOldChangeAxis reads the PDB 2c9v.pdb from the test directory, collects
//The CA and CB of residue D124 of the chain A, and rotates the
//whole molecule such as the vector defined by these 2 atoms is
//aligned with the Z axis. The new molecule is written
//as 2c9v_aligned.pdb to the test folder.
func BenchmarkOldChangeAxis(Te *testing.B) {
	mol, err := PdbRead("test/2c9v.pdb", true)
	if err != nil {
		Te.Error(err)
	}
	orient_atoms := [2]int{0, 0}
	for index := 0; index < mol.Len(); index++ {
		atom := mol.Atom(index)
		if atom.Chain == 'A' && atom.Molid == 124 {
			if atom.Name == "CA" {
				orient_atoms[0] = index
			} else if atom.Name == "CB" {
				orient_atoms[1] = index
			}
		}
	}
	ov1 := mol.Coord(orient_atoms[0], 0)
	ov2 := mol.Coord(orient_atoms[1], 0)
	//now we center the thing in the beta carbon of D124
	err = SubRow(mol.Coords[0], ov2)
	//Now the rotation
	ov1 = mol.Coord(orient_atoms[0], 0) //make sure we have the correct versions
	ov2 = mol.Coord(orient_atoms[1], 0) //same
	orient := ov2.Copy()
	orient.SubtractDense(ov1)
	rotation := GetSwitchZ(orient)
	//	fmt.Println("rotation: ",rotation)
	mol.Coords[0] = matrix.ParallelProduct(mol.Coords[0], rotation)
	//	fmt.Println(orient_atoms[1], mol.Atom(orient_atoms[1]),mol.Atom(orient_atoms[0]))
	if err != nil {
		Te.Error(err)
	}
	PdbWrite(mol, "test/2c9v-old-aligned.pdb")
	fmt.Println("bench2")
}

//TestMultiXyz tests that multi-XYZ files are opened and read correctly.
func TestMultiXyz(Te *testing.T) {
	mol, err := XyzRead("test/sample.xyz")
	if err != nil {
		Te.Error(err)
	}
	fmt.Println("Read: ", len(mol.Coords), " snapshots")
	fmt.Println("Atom 42 Coords (should change)")
	fmt.Println("First snapshot: ", mol.Coords[0].GetRowVector(41), "Second snapshot: ", mol.Coords[1].GetRowVector(41))
	fmt.Println("Atom 3 Coords (shouldnt change)")
	fmt.Println("First snapshot: ", mol.Coords[0].GetRowVector(2), "Second snapshot: ", mol.Coords[1].GetRowVector(2))

}

//TestGeo opens the sample.xyz file in the test directory, and pull a number of hardcoded atoms
//In the direction of a hardcoded vectos. It builds 12 files with the pulled atoms  displaced by
//different ammounts along the pulling vector
func TestGeo(Te *testing.T) {
	pulled_atoms := [7]int{43, 41, 42, 40, 85, 86, 87}
	pulling_vector := [2]int{40, 88}
	mol, err := XyzRead("test/sample.xyz")
	if err != nil {
		Te.Error(err)
	}
	pulled_res := SomeRows(mol.Coords[0], pulled_atoms[:])
	at1 := mol.Coord(pulling_vector[0], 0)
	vector := mol.Coord(pulling_vector[1], 0)
	vector = vector.Copy()
	err = vector.SubtractDense(at1)
	if err != nil {
		Te.Error(err)
	}
	vector = Unitarize(vector)
	var scale_factors = [12]float64{-1.0, -2.0, 1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0, 9.0, 10.0}
	for _, scaling := range scale_factors {
		vec := vector.Copy()
		pulled := pulled_res.Copy()
		vec.Scale(scaling)
		err = AddRow(pulled, vec)
		if err != nil {
			Te.Error(err)
		}
		mol.SetCoords(pulled, pulled_atoms[:], 0)
		err = mol.Corrupted()
		if err != nil {
			Te.Error(err)
		}
		XyzWrite(mol, mol.Coords[0], fmt.Sprintf("test/sample_%03.1f.xyz", scaling))
	}
}

//TestRama tests the Ramachandran plot functionality.
//it generates a Ramachandran plot for the chain A of the PDB 2c9v.
func TestRama(Te *testing.T) {
	mol, err := PdbRead("test/2c9v.pdb", true)
	if err != nil {
		Te.Error(err)
	}
	ramalist, err := RamaList(mol, "A", []int{0, -1}) ////
	if err != nil {
		Te.Error(err)
	}
	rama, err := RamaCalc(mol.Coords[0], ramalist)
	if err != nil {
		Te.Error(err)
	}
	fmt.Println("Rama", rama, len(rama), len(ramalist), mol.Len())
	err = RamaPlot(rama, "test/Rama")
	if err != nil {
		Te.Error(err)
	}
	//PdbWrite(mol,"test/Used4Rama.pdb")
	//for the 3 residue  I should get -131.99, 152.49.
}

//TestQM tests the QM functionality. It prepares input for ORCA and MOPAC
//In the case of MOPAC it reads a previously prepared output and gets the energy.
func TestQM(Te *testing.T) {
	mol, err := XyzRead("test/sample.xyz")
	if err != nil {
		Te.Error(err)
	}
	if err := mol.Corrupted(); err != nil {
		Te.Error(err)
	}
	mol.Del(mol.Len() - 1)
	mol.SetCharge(1)
	mol.SetUnpaired(0)
	calc := new(QMCalc)
	calc.SCFTightness = 3 //very demanding
	calc.Optimize = true
	calc.Method = "BLYP"
	calc.Dielectric = 4
	calc.Basis = "def2-TZVPP"
	calc.HighBasis = "def2-QZVPP"
	calc.HBAtoms = []int{3, 10, 12}
	calc.HBElements = []string{"Cu", "Zn"}
	calc.RI=true
	calc.Disperssion = "D2"
	calc.CConstraints = []int{0, 10, 20}
	orca := MakeOrcaRunner()
	atoms, _ := mol.Next(true)
	original_dir, _ := os.Getwd() //will check in a few lines
	if err = os.Chdir("./test"); err != nil {
		Te.Error(err)
	}
	_ = orca.BuildInput(mol, atoms, calc)
	path, _ := os.Getwd()
	fmt.Println(path)
	//Now a MOPAC optimization with the same configuration.
	mopac := MakeMopacRunner()
	mopac.BuildInput(mol, atoms, calc)
	mopaccommand := os.Getenv("MOPAC_LICENSE") + "/MOPAC2009.exe"
	mopac.SetCommand(mopaccommand)
	fmt.Println("command", mopaccommand)
	//	if err:=mopac.Run(true); err!=nil{
	//		Te.Error(err.Error())
	//	}
	energy, err := mopac.GetEnergy()
	if err != nil {
		if err.Error() == "Probable problem in calculation" {
			fmt.Println(err.Error())
		} else {
			Te.Error(err)
		}
	}
	geometry, err := mopac.GetGeometry(mol)
	if err != nil {
		if err.Error() == "Probable problem in calculation" {
			fmt.Println(err.Error())
		} else {
			Te.Error(err)
		}
	}
	mol.Coords[0] = geometry
	fmt.Println(energy)
	if err := XyzWrite(mol, mol.Coords[0], "mopac.xyz"); err != nil {
		Te.Error(err)
	}
	//Took away this because it takes too long to run :-)
	/*	if err=orca.Run(true); err!=nil{
		Te.Error(err)
		}
	*/
	if err = os.Chdir(original_dir); err != nil {
		Te.Error(err)
	}
}

func TestMatrix(Te *testing.T) {
	a := []float64{1, 1, 4, 2, 2, 5, 3, 3, 6}
	A := matrix.MakeDenseMatrix(a, 3, 3)
	fmt.Println("before:\n", A)
	A, err := DMDelRow(A, 1)
	if err != nil {
		Te.Error(err)
	}
	fmt.Println("after:\n", A)
}

//This function tests the SelCone function.
//it selects a 2-way cone from 3 residues on the interface of SOD1 (PDB: 2c9v)
//and makes a new PDB with them.
func TestSelectCone(Te *testing.T) {
	mol, err := PdbRead("test/2c9v.pdb", true)
	if err != nil {
		Te.Error(err)
	}
	res := []int{116, 146, 147}
	allowed_chains := []string{"A", "F"}
	sele := AtomsFromMolecules(mol, res, allowed_chains)
	fmt.Println(sele)
	selection := SomeRows(mol.Coords[0], sele)
	test, _ := mol.SomeAtoms(sele) //Debug info.
	fmt.Println(test[2], test[3])
	cone := SelCone(mol.Coords[0], selection, 0.75, 20, 1, 0, 0) //0.524 approx pi/6 approx 30deg.
	top, _ := mol.SomeAtoms(cone)
	ref, _ := MakeTopology(top, 0, 1)
	coordst := SomeRows(mol.Coords[0], cone)
	coords := make([]*matrix.DenseMatrix, 1, 1)
	coords[0] = coordst
	newmol, _ := MakeMolecule(ref, coords, mol.Bfactors)
	PdbWrite(newmol, "test/mylittlecone.pdb")

}

func TestReorder(Te *testing.T){
	mol, err := PdbRead("test/2c9v.pdb",false)
	if err != nil {
		Te.Error(err)
	}
	for key,val:=range(mol.Atoms){
		if val.Molid==6{
			mol.Atoms[key].Id=9999
			mol.Atoms[key].Molid=444
		}
	}
	mol.ResetIds()
	PdbWrite(mol,"test/ordertest.pdb")

}

func TestDCD(Te *testing.T){
	try:=new(DcdObj)
	if err:=try.InitRead("test/OUT-min.dcd");err!=nil{
		Te.Error(err)
		}
	fmt.Println("header!")
	i:=1
	for {
		var viej bool
		if i==1{
			viej=true
			_=viej
			}
		if _,err:=try.Next(viej);err!=nil{
			Te.Error(err)
			break
		}
		fmt.Println("YEY!", i)
		i++
	}
}
<|endoftext|>


<commit_before>package geo

import "github.com/nfleet/via/postgeodb"

var (
	config, _ = LoadConfig("../development.json")
	geoDB     = postgeodb.GeoPostgresDB{config}
	test_geo  = NewGeo(true, geoDB, 3600)
)
<commit_msg>Add tests for the configuration loading.<commit_after>package geo

import (
	"testing"

	"github.com/nfleet/via/postgeodb"
)

var (
	config, _ = LoadConfig("../development.json")
	geoDB     = postgeodb.GeoPostgresDB{config}
	test_geo  = NewGeo(true, geoDB, 3600)
)

func TestGeo(t *testing.T) {
	_, err := LoadConfig("../development.json")
	if err != nil {
		t.Fatal(err)
	}
}
<|endoftext|>


<commit_before>// Take well-formed input in graphie format and send it to statsd
//
// LICENSE:
//   Copyright 2015 Yieldbot. <devops@yieldbot.com>
//   Released under the MIT License; see LICENSE
//   for details.

package main

import (
	"flag"
	dracky "github.com/yieldbot/sensu-yieldbot-library/src"
  "github.com/quipo/statsd"
)

func main() {

  // set commandline flags
	HostPtr := flag.String("host", "localhost" "the statsd host")
	PortPtr := flag.String("port", "8125", "the statsd port")
  ProtocolPtr := flag.String("protocol", "udp", "the protocol to connect with")

	flag.Parse()
	statsdHost := *HostPtr
	statsdPort := *PortPtr
  statsdProtocol := *ProtocolPtr

   statsdclient := statsd.NewStatsdClient(statsdHost + ":" + statsdPort)
   statsdclient.CreateSocket()
   defer stats.Close()

   sensuEvent := new(dracky.SensuEvent)
   sensuEvent = sensuEvent.AcquireSensuEvent()

   metricData := sensuEvent.Check.Output

   for i, m := range metricData {
     statsdclient.SesdEvent(m)
   }
 }
<commit_msg>clean client functions<commit_after>// Take well-formed input in graphie format and send it to statsd
//
// LICENSE:
//   Copyright 2015 Yieldbot. <devops@yieldbot.com>
//   Released under the MIT License; see LICENSE
//   for details.

package main

import (
	"flag"
	"github.com/quipo/statsd"
	dracky "github.com/yieldbot/sensu-yieldbot-library/src"
)

func main() {

	// set commandline flags
	HostPtr := flag.String("host", "localhost", "the statsd host")
	PortPtr := flag.String("port", "8125", "the statsd port")
	ProtocolPtr := flag.String("protocol", "udp", "the protocol to connect with")

	flag.Parse()
	statsdHost := *HostPtr
	statsdPort := *PortPtr
	statsdProtocol := *ProtocolPtr

	statsdClient := statsd.NewStatsdClient(statsdHost+":"+statsdPort, "")
	statsdClient.CreateSocket()
	defer statsdClient.Close()

	sensuEvent := new(dracky.SensuEvent)
	sensuEvent = sensuEvent.AcquireSensuEvent()

	metricData := sensuEvent.Check.Output

	for i, m := range metricData {
		// I need to break up the metric into the string and the value
		statsdClient.FAbsolute(m, 0)
	}
}
<|endoftext|>


<commit_before>package config

import (
	"atlantis/router/backend"
	"atlantis/router/logger"
	"atlantis/router/routing"
	"net/http"
	"sync"
)

type Config struct {
	sync.RWMutex
	MatcherFactory *routing.MatcherFactory
	Pools          map[string]*backend.Pool
	Rules          map[string]*routing.Rule
	Tries          map[string]*routing.Trie
}

func NewConfig(matcherFactory *routing.MatcherFactory) *Config {
	return &Config{
		MatcherFactory: matcherFactory,
		Pools:          make(map[string]*backend.Pool, 20),
		Rules:          make(map[string]*routing.Rule, 1000),
		Tries:          make(map[string]*routing.Trie, 100),
	}
}

func (c *Config) Route(r *http.Request) *backend.Pool {
	c.RLock()
	defer c.RUnlock()

	var pool *backend.Pool

	next := c.Tries["root"]
	for next != nil {
		pool, next = next.Walk(r)
		if pool != nil {
			return pool
		}
	}
	return nil
}

func (c *Config) AddPool(pool Pool) {
	c.Lock()
	defer c.Unlock()

	if _, ok := c.Pools[pool.Name]; ok {
		logger.Errorf("pool exists in config", pool.Name)
		return
	}

	c.Pools[pool.Name] = c.ConstructPool(pool)

	// update references to this pool
	for _, rule := range c.Rules {
		if rule.Pool == pool.Name {
			rule.PoolPtr = c.Pools[pool.Name]
		}
	}

}

func (c *Config) UpdatePool(pool Pool) {
	c.Lock()
	defer c.Unlock()

	if _, ok := c.Pools[pool.Name]; !ok {
		logger.Errorf("no pool %s to update", pool.Name)
		return
	}

	c.Pools[pool.Name].Reconfigure(c.ConstructPoolConfig(pool))
}

func (c *Config) DelPool(name string) {
	c.Lock()
	defer c.Unlock()

	if _, ok := c.Pools[name]; !ok {
		logger.Errorf("no pool %s to delete", name)
		return
	}

	// nil references to this pool
	for _, rule := range c.Rules {
		if rule.Pool == name {
			rule.PoolPtr = nil
		}
	}

	c.Pools[name].Shutdown()
	delete(c.Pools, name)
}

func (c *Config) AddRule(rule Rule) {
	c.Lock()
	defer c.Unlock()

	if _, ok := c.Rules[rule.Name]; ok {
		logger.Errorf("rule %s exists in config", rule.Name)
		return
	}

	c.Rules[rule.Name] = c.ConstructRule(rule)

	// update references to this rule
	for _, trie := range c.Tries {
		trie.UpdateRule(c.Rules[rule.Name])
	}
}

func (c *Config) UpdateRule(rule Rule) {
	c.Lock()
	defer c.Unlock()

	if _, ok := c.Rules[rule.Name]; ok {
		delete(c.Rules, rule.Name)
	}

	c.Rules[rule.Name] = c.ConstructRule(rule)

	// update references to this rule
	for _, trie := range c.Tries {
		trie.UpdateRule(c.Rules[rule.Name])
	}
}

func (c *Config) DelRule(name string) {
	c.Lock()
	defer c.Unlock()

	if _, ok := c.Rules[name]; !ok {
		logger.Errorf("no rule %s to delete", name)
		return
	}

	// nil references to this rule
	dummy := routing.DummyRule(name)
	for _, trie := range c.Tries {
		trie.UpdateRule(dummy)
	}

	delete(c.Rules, name)
}

func (c *Config) AddTrie(trie Trie) {
	c.Lock()
	defer c.Unlock()

	if _, ok := c.Tries[trie.Name]; ok {
		logger.Errorf("trie %s exists in config", trie.Name)
		return
	}

	c.Tries[trie.Name] = c.ConstructTrie(trie)

	// update references to this trie
	for _, rule := range c.Rules {
		if rule.Next == trie.Name {
			rule.NextPtr = c.Tries[trie.Name]
		}
	}
}

func (c *Config) UpdateTrie(trie Trie) {
	c.Lock()
	defer c.Unlock()

	if _, ok := c.Tries[trie.Name]; ok {
		delete(c.Tries, trie.Name)
	}

	c.Tries[trie.Name] = c.ConstructTrie(trie)

	// update references to this trie
	for _, rule := range c.Rules {
		if rule.Next == trie.Name {
			rule.NextPtr = c.Tries[trie.Name]
		}
	}
}

func (c *Config) DelTrie(name string) {
	c.Lock()
	defer c.Unlock()

	if _, ok := c.Tries[name]; !ok {
		logger.Errorf("no trie %s to delete", name)
		return
	}

	// nil references to this trie
	dummy := routing.DummyTrie(name)
	for _, rule := range c.Rules {
		if rule.Next == name {
			rule.NextPtr = dummy
		}
	}

	delete(c.Tries, name)
}
<commit_msg>Enable multirouters.<commit_after>package config

import (
	"atlantis/router/backend"
	"atlantis/router/logger"
	"atlantis/router/routing"
	"net/http"
	"sync"
)

type Config struct {
	sync.RWMutex
	MatcherFactory *routing.MatcherFactory
	Pools          map[string]*backend.Pool
	Rules          map[string]*routing.Rule
	Tries          map[string]*routing.Trie
}

func NewConfig(matcherFactory *routing.MatcherFactory) *Config {
	return &Config{
		MatcherFactory: matcherFactory,
		Pools:          make(map[string]*backend.Pool, 20),
		Rules:          make(map[string]*routing.Rule, 1000),
		Tries:          make(map[string]*routing.Trie, 100),
	}
}

func (c *Config) RouteFrom(trie string, r *http.Request) *backend.Pool {
	c.RLock()
	defer c.RUnlock()

	var pool *backend.Pool

	next := c.Tries[trie]
	for next != nil {
		pool, next = next.Walk(r)
		if pool != nil {
			return pool
		}
	}
	return nil
}

func (c *Config) Route(r *http.Request) *backend.Pool {
	return c.RouteFrom("root", r)
}

func (c *Config) AddPool(pool Pool) {
	c.Lock()
	defer c.Unlock()

	if _, ok := c.Pools[pool.Name]; ok {
		logger.Errorf("pool exists in config", pool.Name)
		return
	}

	c.Pools[pool.Name] = c.ConstructPool(pool)

	// update references to this pool
	for _, rule := range c.Rules {
		if rule.Pool == pool.Name {
			rule.PoolPtr = c.Pools[pool.Name]
		}
	}

}

func (c *Config) UpdatePool(pool Pool) {
	c.Lock()
	defer c.Unlock()

	if _, ok := c.Pools[pool.Name]; !ok {
		logger.Errorf("no pool %s to update", pool.Name)
		return
	}

	c.Pools[pool.Name].Reconfigure(c.ConstructPoolConfig(pool))
}

func (c *Config) DelPool(name string) {
	c.Lock()
	defer c.Unlock()

	if _, ok := c.Pools[name]; !ok {
		logger.Errorf("no pool %s to delete", name)
		return
	}

	// nil references to this pool
	for _, rule := range c.Rules {
		if rule.Pool == name {
			rule.PoolPtr = nil
		}
	}

	c.Pools[name].Shutdown()
	delete(c.Pools, name)
}

func (c *Config) AddRule(rule Rule) {
	c.Lock()
	defer c.Unlock()

	if _, ok := c.Rules[rule.Name]; ok {
		logger.Errorf("rule %s exists in config", rule.Name)
		return
	}

	c.Rules[rule.Name] = c.ConstructRule(rule)

	// update references to this rule
	for _, trie := range c.Tries {
		trie.UpdateRule(c.Rules[rule.Name])
	}
}

func (c *Config) UpdateRule(rule Rule) {
	c.Lock()
	defer c.Unlock()

	if _, ok := c.Rules[rule.Name]; ok {
		delete(c.Rules, rule.Name)
	}

	c.Rules[rule.Name] = c.ConstructRule(rule)

	// update references to this rule
	for _, trie := range c.Tries {
		trie.UpdateRule(c.Rules[rule.Name])
	}
}

func (c *Config) DelRule(name string) {
	c.Lock()
	defer c.Unlock()

	if _, ok := c.Rules[name]; !ok {
		logger.Errorf("no rule %s to delete", name)
		return
	}

	// nil references to this rule
	dummy := routing.DummyRule(name)
	for _, trie := range c.Tries {
		trie.UpdateRule(dummy)
	}

	delete(c.Rules, name)
}

func (c *Config) AddTrie(trie Trie) {
	c.Lock()
	defer c.Unlock()

	if _, ok := c.Tries[trie.Name]; ok {
		logger.Errorf("trie %s exists in config", trie.Name)
		return
	}

	c.Tries[trie.Name] = c.ConstructTrie(trie)

	// update references to this trie
	for _, rule := range c.Rules {
		if rule.Next == trie.Name {
			rule.NextPtr = c.Tries[trie.Name]
		}
	}
}

func (c *Config) UpdateTrie(trie Trie) {
	c.Lock()
	defer c.Unlock()

	if _, ok := c.Tries[trie.Name]; ok {
		delete(c.Tries, trie.Name)
	}

	c.Tries[trie.Name] = c.ConstructTrie(trie)

	// update references to this trie
	for _, rule := range c.Rules {
		if rule.Next == trie.Name {
			rule.NextPtr = c.Tries[trie.Name]
		}
	}
}

func (c *Config) DelTrie(name string) {
	c.Lock()
	defer c.Unlock()

	if _, ok := c.Tries[name]; !ok {
		logger.Errorf("no trie %s to delete", name)
		return
	}

	// nil references to this trie
	dummy := routing.DummyTrie(name)
	for _, rule := range c.Rules {
		if rule.Next == name {
			rule.NextPtr = dummy
		}
	}

	delete(c.Tries, name)
}
<|endoftext|>


<commit_before>package alignment

//package main

import . "./interface"
import "fmt"
import "math"

type Rgotoh struct {
	x     string
	y     string
	h     [][][]int
	vague bool
	Constants
}

func NewRGotoh(y string, x string, settings Constants) *Rgotoh {
	xlen := len(x) + 1
	h := make([][][]int, 3)
	for i := 0; i < 3; i++ {
		h[i] = make([][]int, xlen)
		for y := 0; y < xlen; y++ {
			h[i][y] = make([]int, 2)
		}
	}
	Rgotoh := &Rgotoh{x: x, y: y, h: h}
	Rgotoh.Constants = settings
	return Rgotoh
}

func (l Rgotoh) Strlen() (int, int) {
	return len(l.x), len(l.y)
}

func (l Rgotoh) Substitution(x int, y int) int {
	return l.Constants.Substitution(l.x[x-1], l.y[y-1])
}

func (l Rgotoh) Score() int {
	e, _ := l.ScoreArgs(len(l.x))
	return e
}

func (l *Rgotoh) Length() {
	l.RegionAlign(0, len(l.x), 0, len(l.y), true)
}

func (l *Rgotoh) RegionAlign(i1 int, i2 int, j1 int, j2 int, order bool) (result int, class int) {
	var m = i2 - i1
	var n = j2 - j1
	l.h[0][0][0] = 0
	l.h[1][0][0] = math.MinInt64
	l.h[2][0][0] = math.MinInt64
	for i := 1; i <= m; i++ {
		l.h[0][i][0] = math.MinInt32
		l.h[1][i][0] = l.Cost(i)
		l.h[2][i][0] = math.MinInt32
	}

	for j := 1; j <= n; j++ {
		l.h[0][0][1] = math.MinInt32
		l.h[1][0][1] = math.MinInt32
		l.h[2][0][1] = l.Cost(j)
		for i := 1; i <= m; i++ {
			var nexth int
			//Update H^1 (l.h[0])
			nexth, _ = Max(l.h[0][i-1][0], l.h[1][i-1][0], l.h[2][i-1][0])
			//fmt.Println(i, j)
			if order {
				l.h[0][i][1] = nexth + l.Substitution(i+i1, j+j1)
			} else {
				l.h[0][i][1] = nexth + l.Substitution(i2-i+1, j2-j+1)
			}
			//Update H^2 (l.h[1])
			e, d := l.Geted()
			nexth, _ = Max(l.h[0][i-1][1]-d, l.h[1][i-1][1]-e, l.h[2][i-1][1]-d)
			l.h[1][i][1] = nexth
			//Update H^3 (l.h[2])
			nexth, _ = Max(l.h[0][i][0]-d, math.MinInt64, l.h[2][i][0]-e)
			l.h[2][i][1] = nexth
		}
		for i := 0; i <= m; i++ {
			l.h[0][i][0] = l.h[0][i][1]
			l.h[1][i][0] = l.h[1][i][1]
			l.h[2][i][0] = l.h[2][i][1]
		}
	}
	return l.ScoreArgs(m)
}

func (l Rgotoh) ScoreArgs(x int) (e int, k int) {
	e, k = Max(l.h[0][x][0], l.h[1][x][0], l.h[2][x][0])
	return
}

func (l Rgotoh) Print(i int, j int) (string, string, string) {
	//fmt.Println(l.LinearSpaceAlign(120, 120, 120, 120))
	//fmt.Println(l.RegionAlign(0, 7, 0, 0, true))
	if len(l.x) > 200 {
		l.vague = true
	}
	return l.LinearSpace(0, 0, i-1, j-1, l.Score())
	//return l.LinearBinaryAlign(0, i-1, 0, j-1, l.Score())
	//return l.linearSpaceAlign(0, len(l.x), 0, len(l.y))
}

func (l Rgotoh) LinearSpace(i0 int, j0 int, i int, j int, score int) (p string, q string, r string) {
	if (i < i0 && j == j0) || (j < j0 && i == i0) {
		return
	} else if i < i0 {
		for jt := j0; jt <= j; jt++ {
			p += "-"
			q += " "
			r += fmt.Sprintf("%c", l.y[jt])
		}
		return
	} else if j < j0 {
		for it := i0; it <= i; it++ {
			p += fmt.Sprintf("%c", l.x[it])
			q += " "
			r += "-"
		}
		return
	}
	maxj := j + 1 //To use determine whethere i have a suitable solution.
	min := 0
	if l.vague && j-70 >= 0 {
		min = j - 70
	}
	for jh := j; jh >= min; jh-- {
		tmp1, err1 := l.RegionAlign(0, i, 0, jh, true)
		tmp2, err2 := l.RegionAlign(i, len(l.x), jh, len(l.y), false)
		tmp := tmp1 + tmp2
		_, d := l.Geted()
		if err1 == err2 && err2 >= 1 {
			tmp += d
		}
		//fmt.Println(tmp1, tmp2, err1, err2, tmp, jh)
		if tmp == score {
			maxj = jh
			break
		}
	}
	//fmt.Println(i, j, maxj, "result")
	p, q, r = l.LinearSpace(i0, j0, i-1, maxj-1, score)
	if maxj == j+1 {
		//When no suitable solution is not found for i.
		p += fmt.Sprintf("%c", l.x[i])
		q += " "
		r += "-"
	} else if maxj < j {
		//When no suitable solution is not found for j.
		p += fmt.Sprintf("%c", l.x[i])
		q += "|"
		r += fmt.Sprintf("%c", l.y[maxj])
		for maxj++; maxj <= j; maxj++ {
			p += "-"
			q += " "
			r += fmt.Sprintf("%c", l.y[maxj])
		}
	} else {
		//fmt.Println(i)
		p += fmt.Sprintf("%c", l.x[i])
		q += "|"
		r += fmt.Sprintf("%c", l.y[j])
	}
	return
}

func (l Rgotoh) LinearBinaryAlign(i1 int, i2 int, j1 int, j2 int, score int) (p string, q string, r string) {
	if i2-i1 <= 100 || j2-j1 <= 100 {
		//fmt.Println(i1, j1, i2, j2, "delegate")
		return l.LinearSpace(i1, j1, i2, j2, score)
	}
	ih := ((i1 + i2) / 2)
	if ih >= len(l.x) || ih < i1 {
		panic(i1 + i2)
	}
	maxscore, maxj := -1000, j1+1
	for jh := j2; jh >= j1; jh-- {
		tmp1, err1 := l.RegionAlign(i1, ih, j1, jh, true)
		tmp2, err2 := l.RegionAlign(ih, i2, jh, j2, false)
		//fmt.Println(tmp1, tmp2)
		tmp := tmp1 + tmp2
		_, d := l.Geted()
		if err1 >= 1 && err2 >= 1 {
			tmp += d
		}
		//fmt.Println(i1, i2, j1, j2, ih, jh, tmp)
		if tmp > maxscore {
			maxscore = tmp
			maxj = jh
		}
	}
	fmt.Println(i1, ih, i2, j1, maxj, j2)
	p, q, r = l.LinearBinaryAlign(i1, ih-1, j1, maxj-1, score)
	//p += fmt.Sprintf("%c", l.x[ih])
	//q += "|"
	//r += fmt.Sprintf("%c", l.y[maxj])
	p2, q2, r2 := l.LinearBinaryAlign(ih, i2, maxj, j2, score)
	p += p2
	q += q2
	r += r2
	return
}
<commit_msg>Fix the calc of score<commit_after>package alignment

//package main

import . "./interface"
import "fmt"
import "math"

type Rgotoh struct {
	x     string
	y     string
	h     [][][]int
	vague bool
	Constants
}

func NewRGotoh(y string, x string, settings Constants) *Rgotoh {
	xlen := len(x) + 1
	h := make([][][]int, 3)
	for i := 0; i < 3; i++ {
		h[i] = make([][]int, xlen)
		for y := 0; y < xlen; y++ {
			h[i][y] = make([]int, 2)
		}
	}
	Rgotoh := &Rgotoh{x: x, y: y, h: h}
	Rgotoh.Constants = settings
	return Rgotoh
}

func (l Rgotoh) Strlen() (int, int) {
	return len(l.x), len(l.y)
}

func (l Rgotoh) Substitution(x int, y int) int {
	return l.Constants.Substitution(l.x[x-1], l.y[y-1])
}

func (l Rgotoh) Score() int {
	e, _ := l.ScoreArgs(len(l.x))
	return e
}

func (l *Rgotoh) Length() {
	l.RegionAlign(0, len(l.x), 0, len(l.y), true)
}

func (l *Rgotoh) RegionAlign(i1 int, i2 int, j1 int, j2 int, order bool) (int, int, int) {
	var m = i2 - i1
	var n = j2 - j1
	l.h[0][0][0] = 0
	l.h[1][0][0] = math.MinInt64
	l.h[2][0][0] = math.MinInt64
	for i := 1; i <= m; i++ {
		l.h[0][i][0] = math.MinInt32
		l.h[1][i][0] = l.Cost(i)
		l.h[2][i][0] = math.MinInt32
	}

	for j := 1; j <= n; j++ {
		l.h[0][0][1] = math.MinInt32
		l.h[1][0][1] = math.MinInt32
		l.h[2][0][1] = l.Cost(j)
		for i := 1; i <= m; i++ {
			var nexth int
			//Update H^1 (l.h[0])
			nexth, _ = Max(l.h[0][i-1][0], l.h[1][i-1][0], l.h[2][i-1][0])
			//fmt.Println(i, j)
			if order {
				l.h[0][i][1] = nexth + l.Substitution(i+i1, j+j1)
			} else {
				l.h[0][i][1] = nexth + l.Substitution(i2-i+1, j2-j+1)
			}
			//Update H^2 (l.h[1])
			e, d := l.Geted()
			nexth, _ = Max(l.h[0][i-1][1]-d, l.h[1][i-1][1]-e, l.h[2][i-1][1]-d)
			l.h[1][i][1] = nexth
			//Update H^3 (l.h[2])
			nexth, _ = Max(l.h[0][i][0]-d, math.MinInt64, l.h[2][i][0]-e)
			l.h[2][i][1] = nexth
		}
		for i := 0; i <= m; i++ {
			l.h[0][i][0] = l.h[0][i][1]
			l.h[1][i][0] = l.h[1][i][1]
			l.h[2][i][0] = l.h[2][i][1]
		}
	}
	return l.h[0][m][0], l.h[1][m][0], l.h[2][m][0] //l.ScoreArgs(m)
}

func (l Rgotoh) ScoreArgs(x int) (e int, k int) {
	e, k = Max(l.h[0][x][0], l.h[1][x][0], l.h[2][x][0])
	return
}

func (l Rgotoh) Print(i int, j int) (string, string, string) {
	//fmt.Println(l.LinearSpaceAlign(120, 120, 120, 120))
	//fmt.Println(l.RegionAlign(0, 7, 0, 0, true))
	if len(l.x) > 200 {
		l.vague = true
	}
	return l.LinearSpace(0, 0, i-1, j-1, l.Score())
	//return l.LinearBinaryAlign(0, i-1, 0, j-1, l.Score())
	//return l.linearSpaceAlign(0, len(l.x), 0, len(l.y))
}

func (l Rgotoh) pointMaxScore(i1 int, j1 int, i2 int, j2 int, ih int, jh int) int {
	tmp11, tmp12, tmp13 := l.RegionAlign(i1, ih, j1, jh, true)
	tmp21, tmp22, tmp23 := l.RegionAlign(ih, i2, jh, j2, false)
	_, d := l.Geted()
	array := make([]int, 8)
	array[0] = tmp11 + tmp21
	array[1] = tmp11 + tmp22
	array[2] = tmp11 + tmp23
	array[3] = tmp12 + tmp21
	array[4] = tmp12 + tmp22 + d
	array[5] = tmp12 + tmp23
	array[6] = tmp13 + tmp21
	array[7] = tmp13 + tmp23 + d

	tmp := math.MinInt64
	for _, v := range array {
		if tmp < v {
			tmp = v
		}
	}
	return tmp
}

func (l Rgotoh) LinearSpace(i0 int, j0 int, i int, j int, score int) (p string, q string, r string) {
	if (i < i0 && j == j0) || (j < j0 && i == i0) {
		return
	} else if i < i0 {
		for jt := j0; jt <= j; jt++ {
			p += "-"
			q += " "
			r += fmt.Sprintf("%c", l.y[jt])
		}
		return
	} else if j < j0 {
		for it := i0; it <= i; it++ {
			p += fmt.Sprintf("%c", l.x[it])
			q += " "
			r += "-"
		}
		return
	}
	maxj := j + 1 //To use determine whethere i have a suitable solution.
	min := 0
	if l.vague && j-70 >= 0 {
		min = j - 70
	}
	for jh := j; jh >= min; jh-- {
		tmp := l.pointMaxScore(0, 0, len(l.x), len(l.y), i, jh)
		//fmt.Println(tmp1, tmp2, err1, err2, tmp, jh)
		if tmp == score {
			maxj = jh
			break
		}
	}
	//fmt.Println(i, j, maxj, "result")
	p, q, r = l.LinearSpace(i0, j0, i-1, maxj-1, score)
	if maxj == j+1 {
		//When no suitable solution is not found for i.
		p += fmt.Sprintf("%c", l.x[i])
		q += " "
		r += "-"
	} else if maxj < j {
		//When no suitable solution is not found for j.
		p += fmt.Sprintf("%c", l.x[i])
		q += "|"
		r += fmt.Sprintf("%c", l.y[maxj])
		for maxj++; maxj <= j; maxj++ {
			p += "-"
			q += " "
			r += fmt.Sprintf("%c", l.y[maxj])
		}
	} else {
		//fmt.Println(i)
		p += fmt.Sprintf("%c", l.x[i])
		q += "|"
		r += fmt.Sprintf("%c", l.y[j])
	}
	return
}

func (l Rgotoh) LinearBinaryAlign(i1 int, i2 int, j1 int, j2 int, score int) (p string, q string, r string) {
	if i2-i1 <= 100 || j2-j1 <= 100 {
		return l.LinearSpace(i1, j1, i2, j2, score)
	}
	ih := ((i1 + i2) / 2)

	maxscore, maxj := -1000, j1+1
	for jh := j2; jh >= j1; jh-- {
		tmp := l.pointMaxScore(i1, j1, i2, j2, ih, jh)

		//fmt.Println(i1, i2, j1, j2, ih, jh, tmp)
		if tmp > maxscore {
			maxscore = tmp
			maxj = jh
		}
	}
	fmt.Println(i1, ih, i2, j1, maxj, j2)
	p, q, r = l.LinearBinaryAlign(i1, ih-1, j1, maxj-1, score)
	//p += fmt.Sprintf("%c", l.x[ih])
	//q += "|"
	//r += fmt.Sprintf("%c", l.y[maxj])
	p2, q2, r2 := l.LinearBinaryAlign(ih, i2, maxj, j2, score)
	p += p2
	q += q2
	r += r2
	return
}
<|endoftext|>