<commit_before>package main

import (
    "log"
    "flag"
    "net/http"
    "strings"
    "code.google.com/p/gorest"
    "nowac/kegg"
//    "time"
//    "math/rand"
    "strconv"
   // "github.com/fjukstad/gocache"
    "encoding/json"
    "io/ioutil"
    "bytes"
)

func main () {

    var ip = flag.String("ip", "localhost", "ip to run on")
    var port = flag.String("port", ":8080" ,"port to run on")

    flag.Parse()
    address := *ip+*port

    gorest.RegisterService(new(NOWACService))
    http.Handle("/", gorest.Handle())

    log.Println("Starting server on", address)
    err := http.ListenAndServe(address, nil)
    if err != nil{
        log.Panic("Could not start rest-service:", err)
    }

}

type NOWACService struct {
    gorest.RestService `root:"/"
                        consumes:"application/json"
                        produces:"application/json"`

    newPathwayGraph gorest.EndPoint `method:"GET"
                                    path:"/new/graph/pathway/{Pathways:string}"
                                    output:"string"`

    getInfo gorest.EndPoint `method:"GET"
                            path:"/info/{Items:string}/{InfoType:string}"
                            output:"string"`

    getGeneVis gorest.EndPoint `method:"GET"
                            path:"/vis/{Gene:string}"
                            output:"string"`

    datastore gorest.EndPoint `method:"GET"
                                path:"/datastore/{...:string}"
                                output:"string"`

    datastorePost gorest.EndPoint `method:"POST"
                                    path:"/datastore/{...:string}"
                                    postdata:"string"`

    pathways gorest.EndPoint    `method:"GET"
                                path:"/info/gene/{Gene:string}/pathways"
                                output:"string"`

    commonPathways gorest.EndPoint  `method:"GET"
                                    path:"/info/pathway/{Pathways:string}"
                                    output:"string"`

    pathwayGeneCount gorest.EndPoint    `method:"GET"
                                        path:"/info/gene/{Genes:string}/commonpathways"
                                        output:"string"`

    pathwayIDToName gorest.EndPoint `method:"GET"
                                    path:"/info/pathway/{Id:string}/name"
                                    output:"string"`

    commonGenes gorest.EndPoint `method:"GET"
                                path:"/info/pathway/{Pathways:string}/commongenes"
                                output:"int"`
/*
    geneColor gorest.EndPoint `method:"GET"
                                path:"/in*/
}

type PWMap struct {
    Map map[string] int
}

// Returns the number of common genes shared between multiple pathways
func (serv NOWACService) CommonGenes(Pathways string) int {
    addAccessControlAllowOriginHeader(serv)

    pathwayList := strings.Split(Pathways, " ")

    allGenes := make(map[string]int)

    // Iterate over all genes from different pathways and set their count
    for _, p := range pathwayList {
        pw := kegg.GetPathway(p)
        genes := pw.Genes

        for _, g := range genes {

            count := allGenes[g]
            if count != 0 {
                allGenes[g] = count + 1

            } else {
                allGenes[g] = 1
            }
        }

    }

    // From map of all genes get the ones with count larger than 1
    var commonGenes [] string
    for k, v := range allGenes {
        if v > 1 {
            commonGenes = append(commonGenes, k)
        }
    }

    return len(commonGenes)

}

func (serv NOWACService) PathwayIDToName (Id string) string {
    addAccessControlAllowOriginHeader(serv)
    return kegg.ReadablePathwayName(Id)
}

// Returns a list of pathways and the frequency of given genes. I.e.
// how many of the given genes are represented in different pathways
// Genes is a string that looks like "hsa:123+hsa:321+..."
func (serv NOWACService) PathwayGeneCount (Genes string) string {

	PathwayMap := make(map[string] int, 0)

    geneList := strings.Split(Genes, " ")

    // for every gene get its list of pathways
    for _, g := range geneList {

        geneId := strings.Split(g, ":")[1]
        gene := kegg.GetGene(geneId)
        pws := kegg.Pathways(gene)

        // for each of its pathways, increment the counter for number
        // of genes represented in this pathway.
        for _, p := range pws.Pathways {
            if PathwayMap[p] != 0 {
                PathwayMap[p]++
            } else {
                PathwayMap[p] = 1
            }
        }

    }

    b, err := json.Marshal(PathwayMap)
    if err != nil {
        log.Panic("marshaling went bad: ",err)
    }

    return string(b)
}

func (serv NOWACService) CommonPathways(Pathways string) string {

    return "Not implemented yet"

}

// Will return a list of pathways for a given gene
func (serv NOWACService) Pathways (Gene string) string {

    geneIdString := strings.Split(Gene, " ")[0]
    geneId := strings.Split(geneIdString, ":")[1]
    gene := kegg.GetGene(geneId)
    pws := kegg.Pathways(gene)
    return kegg.PathwaysJSON(pws)

}

// Handles any requests to the Datastore. Will simply make the request to the
// datastore and return the result
func (serv NOWACService) Datastore(args ...string) string {

    addAccessControlAllowOriginHeader(serv)

    requestURL := serv.Context.Request().URL.Path

    // Where the datastore is running, this would be Stallo in later versions
    datastoreBaseURL := "http://localhost:8888/"

    URL := datastoreBaseURL + strings.Trim(requestURL, "/datastore")

    // NOTE: We are not caching results here, this could have been done, but
    // since we're doing work with a test dataset caching is not done.

    //NOTE: http.GET(URL) failed when the number of these calls were really
    //frequent. now trying gocache.
    resp, err := http.Get(URL)
    if err != nil {
        log.Print("request to datastore failed. ",err)
        serv.ResponseBuilder().SetResponseCode(404).Overide(true)
        return ":("
    }

    defer resp.Body.Close()

    // WARNING: int64 -> int conversion. may crash and burn if more than 2^32
    // - 1 bytes were read. Response from Datastore will typically be much
    // shorter than this, so its not an issue.
    respLength := int(resp.ContentLength)

    // Read the response from the body and return it as a string.
    response := make([]byte, respLength)
    _, err = resp.Body.Read(response)
    if err != nil {
        log.Print("reading response from datastore failed. ", err)
        serv.ResponseBuilder().SetResponseCode(404).Overide(true)
        return ":("
    }

    // Set response code to what was returned from Datastore.
    // Will ensure that if a 404 is returned by datastore this is also passed
    // along
    serv.ResponseBuilder().SetResponseCode(resp.StatusCode).Overide(false)

    return string(response)
}

func (serv NOWACService) DatastorePost( PostData string, varArgs ...string) {
    addAccessControlAllowOriginHeader(serv)

    requestURL := serv.Context.Request().URL.Path

    // Where the datastore is running, this would be Stallo in later versions
    datastoreBaseURL := "http://localhost:8888/"

    URL := datastoreBaseURL + strings.Replace(requestURL, "/datastore/","",-1)

    postContent := bytes.NewBufferString(PostData)

    // Perform the actual http post to the datastore
    // note that we set text as datatype. will fail miserably with anything else
    _, err := http.Post(URL, "text", postContent)
    if err != nil {
        log.Print("Post to datastore failed. ", err)
        serv.ResponseBuilder().SetResponseCode(500).Overide(true)
    }

}

func (serv NOWACService) GetGeneVis(Gene string) string {
    addAccessControlAllowOriginHeader(serv)

    log.Print("Returning the VIS code for gene: ", Gene)

    code := GeneExpression(Gene) // Barchar() // ParallelCoordinates(len(Gene))//GeneVisCode(Gene)
    return code
}

func GeneExpression(geneid string) string {

    id, err := strconv.Atoi(geneid)
    if err != nil {
        log.Panic("that was not a gene id: ", geneid, " ", err)
    }
    ds := GetGeneExpression(id)

    // Header, containing all other js
    header := `

    `

    return header+dataset+vis

}

// Returns all information possible for a gene. This includes stuff
// like id,name,definition etc etc.
func (serv NOWACService) GetInfo(Items string, InfoType string) string {

    //TODO: implement different info types such as name/sequence/ etc

    addAccessControlAllowOriginHeader(serv)

    if(strings.Contains(Items, "hsa")){
        // will get the first gene in the list Items. Could be more than one
        // but for starters we'll do with just one.

        geneIdString := strings.Split(Items, " ")[0]
        geneId := strings.Split(geneIdString, ":")[1]

        gene := kegg.GetGene(geneId)

        //gene.Pathways = kegg.ReadablePathwayNames(gene.Pathways)

        return kegg.GeneJSON(gene)
    }

    return Items;

}

func (serv NOWACService) NewPathwayGraph(Pathways string) string {
    addAccessControlAllowOriginHeader(serv)

    pws := parsePathwayInput(Pathways);
    handlerAddress := kegg.PathwayGraphFrom(pws[0])

    return handlerAddress+"/"+pws[0]

}

func addAccessControlAllowOriginHeader (serv NOWACService) {
    // Allowing access control stuff
    rb := serv.ResponseBuilder()
    rb.AddHeader("Access-Control-Allow-Origin","*")
}

func parsePathwayInput(input string) ([] string) {
        // Remove any unwanted characters
	a := strings.Replace(input, "%3A", ":", -1)
	a = strings.Replace(a, "&", "", -1)
	a = strings.Replace(a, "=", "", -1)

	// Split into separate hsa:... strings
	b := strings.Split(a, "pathwaySelect")

	// Clear out first empty item
	b = b[1:len(b)]

    return b

}

func GetGeneExpression(id int) string {

    datastore := "http://localhost:8888"

    query := "/gene/"+strconv.Itoa(id)
    url := datastore+query
    response, err := http.Get(url)

    if err != nil {
        log.Panic("could not download expression ", err)
    }

    defer response.Body.Close()

	exprs, err := ioutil.ReadAll(response.Body)
    if err != nil {
        log.Panic("Could not read expression ", err)
    }

    return string(exprs)

}

<commit_msg>event handlers to show bg info<commit_after>package main

import (
    "log"
    "flag"
    "net/http"
    "strings"
    "code.google.com/p/gorest"
    "nowac/kegg"
//    "time"
//    "math/rand"
    "strconv"
   // "github.com/fjukstad/gocache"
    "encoding/json"
    "io/ioutil"
    "bytes"
)

func main () {

    var ip = flag.String("ip", "localhost", "ip to run on")
    var port = flag.String("port", ":8080" ,"port to run on")

    flag.Parse()
    address := *ip+*port

    gorest.RegisterService(new(NOWACService))
    http.Handle("/", gorest.Handle())

    log.Println("Starting server on", address)
    err := http.ListenAndServe(address, nil)
    if err != nil{
        log.Panic("Could not start rest-service:", err)
    }

}

type NOWACService struct {
    gorest.RestService `root:"/"
                        consumes:"application/json"
                        produces:"application/json"`

    newPathwayGraph gorest.EndPoint `method:"GET"
                                    path:"/new/graph/pathway/{Pathways:string}"
                                    output:"string"`

    getInfo gorest.EndPoint `method:"GET"
                            path:"/info/{Items:string}/{InfoType:string}"
                            output:"string"`

    getGeneVis gorest.EndPoint `method:"GET"
                            path:"/vis/{Gene:string}"
                            output:"string"`

    datastore gorest.EndPoint `method:"GET"
                                path:"/datastore/{...:string}"
                                output:"string"`

    datastorePost gorest.EndPoint `method:"POST"
                                    path:"/datastore/{...:string}"
                                    postdata:"string"`

    pathways gorest.EndPoint    `method:"GET"
                                path:"/info/gene/{Gene:string}/pathways"
                                output:"string"`

    commonPathways gorest.EndPoint  `method:"GET"
                                    path:"/info/pathway/{Pathways:string}"
                                    output:"string"`

    pathwayGeneCount gorest.EndPoint    `method:"GET"
                                        path:"/info/gene/{Genes:string}/commonpathways"
                                        output:"string"`

    pathwayIDToName gorest.EndPoint `method:"GET"
                                    path:"/info/pathway/{Id:string}/name"
                                    output:"string"`

    commonGenes gorest.EndPoint `method:"GET"
                                path:"/info/pathway/{Pathways:string}/commongenes"
                                output:"int"`
/*
    geneColor gorest.EndPoint `method:"GET"
                                path:"/in*/
}

type PWMap struct {
    Map map[string] int
}

// Returns the number of common genes shared between multiple pathways
func (serv NOWACService) CommonGenes(Pathways string) int {
    addAccessControlAllowOriginHeader(serv)

    pathwayList := strings.Split(Pathways, " ")

    allGenes := make(map[string]int)

    // Iterate over all genes from different pathways and set their count
    for _, p := range pathwayList {
        pw := kegg.GetPathway(p)
        genes := pw.Genes

        for _, g := range genes {

            count := allGenes[g]
            if count != 0 {
                allGenes[g] = count + 1

            } else {
                allGenes[g] = 1
            }
        }

    }

    // From map of all genes get the ones with count larger than 1
    var commonGenes [] string
    for k, v := range allGenes {
        if v > 1 {
            commonGenes = append(commonGenes, k)
        }
    }

    return len(commonGenes)

}

func (serv NOWACService) PathwayIDToName (Id string) string {
    addAccessControlAllowOriginHeader(serv)
    return kegg.ReadablePathwayName(Id)
}

// Returns a list of pathways and the frequency of given genes. I.e.
// how many of the given genes are represented in different pathways
// Genes is a string that looks like "hsa:123+hsa:321+..."
func (serv NOWACService) PathwayGeneCount (Genes string) string {

	PathwayMap := make(map[string] int, 0)

    geneList := strings.Split(Genes, " ")

    // for every gene get its list of pathways
    for _, g := range geneList {

        geneId := strings.Split(g, ":")[1]
        gene := kegg.GetGene(geneId)
        pws := kegg.Pathways(gene)

        // for each of its pathways, increment the counter for number
        // of genes represented in this pathway.
        for _, p := range pws.Pathways {
            if PathwayMap[p] != 0 {
                PathwayMap[p]++
            } else {
                PathwayMap[p] = 1
            }
        }

    }

    b, err := json.Marshal(PathwayMap)
    if err != nil {
        log.Panic("marshaling went bad: ",err)
    }

    return string(b)
}

func (serv NOWACService) CommonPathways(Pathways string) string {

    return "Not implemented yet"

}

// Will return a list of pathways for a given gene
func (serv NOWACService) Pathways (Gene string) string {

    geneIdString := strings.Split(Gene, " ")[0]
    geneId := strings.Split(geneIdString, ":")[1]
    gene := kegg.GetGene(geneId)
    pws := kegg.Pathways(gene)
    return kegg.PathwaysJSON(pws)

}

// Handles any requests to the Datastore. Will simply make the request to the
// datastore and return the result
func (serv NOWACService) Datastore(args ...string) string {

    addAccessControlAllowOriginHeader(serv)

    requestURL := serv.Context.Request().URL.Path

    // Where the datastore is running, this would be Stallo in later versions
    datastoreBaseURL := "http://localhost:8888/"

    URL := datastoreBaseURL + strings.Trim(requestURL, "/datastore")

    // NOTE: We are not caching results here, this could have been done, but
    // since we're doing work with a test dataset caching is not done.

    //NOTE: http.GET(URL) failed when the number of these calls were really
    //frequent. now trying gocache.
    resp, err := http.Get(URL)
    if err != nil {
        log.Print("request to datastore failed. ",err)
        serv.ResponseBuilder().SetResponseCode(404).Overide(true)
        return ":("
    }

    defer resp.Body.Close()

    // WARNING: int64 -> int conversion. may crash and burn if more than 2^32
    // - 1 bytes were read. Response from Datastore will typically be much
    // shorter than this, so its not an issue.
    respLength := int(resp.ContentLength)

    // Read the response from the body and return it as a string.
    response := make([]byte, respLength)
    _, err = resp.Body.Read(response)
    if err != nil {
        log.Print("reading response from datastore failed. ", err)
        serv.ResponseBuilder().SetResponseCode(404).Overide(true)
        return ":("
    }

    // Set response code to what was returned from Datastore.
    // Will ensure that if a 404 is returned by datastore this is also passed
    // along
    serv.ResponseBuilder().SetResponseCode(resp.StatusCode).Overide(false)

    return string(response)
}

func (serv NOWACService) DatastorePost( PostData string, varArgs ...string) {
    addAccessControlAllowOriginHeader(serv)

    requestURL := serv.Context.Request().URL.Path

    // Where the datastore is running, this would be Stallo in later versions
    datastoreBaseURL := "http://localhost:8888/"

    URL := datastoreBaseURL + strings.Replace(requestURL, "/datastore/","",-1)

    postContent := bytes.NewBufferString(PostData)

    // Perform the actual http post to the datastore
    // note that we set text as datatype. will fail miserably with anything else
    _, err := http.Post(URL, "text", postContent)
    if err != nil {
        log.Print("Post to datastore failed. ", err)
        serv.ResponseBuilder().SetResponseCode(500).Overide(true)
    }

}

func (serv NOWACService) GetGeneVis(Gene string) string {
    addAccessControlAllowOriginHeader(serv)

    log.Print("Returning the VIS code for gene: ", Gene)

    code := GeneExpression(Gene) // Barchar() // ParallelCoordinates(len(Gene))//GeneVisCode(Gene)
    return code
}

func GeneExpression(geneid string) string {

    id, err := strconv.Atoi(geneid)
    if err != nil {
        log.Panic("that was not a gene id: ", geneid, " ", err)
    }
    ds := GetGeneExpression(id)

    // Header, containing all other js
    header := `

    `

    return header+dataset+vis

}

// Returns all information possible for a gene. This includes stuff
// like id,name,definition etc etc.
func (serv NOWACService) GetInfo(Items string, InfoType string) string {

    //TODO: implement different info types such as name/sequence/ etc

    addAccessControlAllowOriginHeader(serv)

    if(strings.Contains(Items, "hsa")){
        // will get the first gene in the list Items. Could be more than one
        // but for starters we'll do with just one.

        geneIdString := strings.Split(Items, " ")[0]
        geneId := strings.Split(geneIdString, ":")[1]

        gene := kegg.GetGene(geneId)

        //gene.Pathways = kegg.ReadablePathwayNames(gene.Pathways)

        return kegg.GeneJSON(gene)
    }

    return Items;

}

func (serv NOWACService) NewPathwayGraph(Pathways string) string {
    addAccessControlAllowOriginHeader(serv)

    pws := parsePathwayInput(Pathways);
    handlerAddress := kegg.PathwayGraphFrom(pws[0])

    return handlerAddress+"/"+pws[0]

}

func addAccessControlAllowOriginHeader (serv NOWACService) {
    // Allowing access control stuff
    rb := serv.ResponseBuilder()
    rb.AddHeader("Access-Control-Allow-Origin","*")
}

func parsePathwayInput(input string) ([] string) {
        // Remove any unwanted characters
	a := strings.Replace(input, "%3A", ":", -1)
	a = strings.Replace(a, "&", "", -1)
	a = strings.Replace(a, "=", "", -1)

	// Split into separate hsa:... strings
	b := strings.Split(a, "pathwaySelect")

	// Clear out first empty item
	b = b[1:len(b)]

    return b

}

func GetGeneExpression(id int) string {

    datastore := "http://localhost:8888"

    query := "/gene/"+strconv.Itoa(id)
    url := datastore+query
    response, err := http.Get(url)

    if err != nil {
        log.Panic("could not download expression ", err)
    }

    defer response.Body.Close()

	exprs, err := ioutil.ReadAll(response.Body)
    if err != nil {
        log.Panic("Could not read expression ", err)
    }

    return string(exprs)

}

<|endoftext|>


<commit_before>package main

import (
	"fmt"
	"github.com/peterbourgon/g2s"
	"log"
	"os"
	"strconv"
	"time"
)

type Backend interface {
	// "Log" check result in the Backend service
	Log(check *Check, statusCode int, duration time.Duration)
	Close()
}

// Backend for Statsd
type StatsdBackend struct {
	statsd g2s.Statter
}

// Instanciate a new StatsdBackend
// Uses:
//   STATSD_HOST env variable
//   STATSD_PORT env variable (defaults to 8125)
//   STATSD_PROTOCOL env variable (defaults to udp)
func NewStatsdBackend() (*StatsdBackend, error) {
	envHost := os.Getenv("STATSD_HOST")
	envPort := os.Getenv("STATSD_PORT")
	envProtocol := os.Getenv("STATSD_PROTOCOL")

	if envHost == "" {
		return nil, fmt.Errorf("STATSD_HOST environment variable must be defined")
	}

	if envPort == "" {
		envPort = "8125"
	}

	if envProtocol == "" {
		envProtocol = "udp"
	}

	statsd, err := g2s.Dial(envProtocol, envHost+":"+envPort)
	if err != nil {
		return nil, err
	}

	return &StatsdBackend{statsd}, nil
}

// Log to statsd the check result as follow:
// `Check.Key`.duration : Request duration
// `Check.Key`.success : Request succeeded (status code is 2xx)
// `Check.Key`.error : Request failed (status code != 200)
func (s *StatsdBackend) Log(check *Check, statusCode int, duration time.Duration) {
	s.statsd.Timing(1.0, check.Key+".duration", duration)
	if 200 <= statusCode && 299 >= statusCode {
		s.statsd.Gauge(1.0, check.Key+".success", strconv.Itoa(statusCode))
	} else {
		s.statsd.Gauge(1.0, check.Key+".error", strconv.Itoa(statusCode))
	}
}

func (s *StatsdBackend) Close() {
	// NO OP
}

// StdoutBackend logs result to Stdout
type StdoutBackend struct {
}

func NewStdoutBackend() *StdoutBackend {

	return &StdoutBackend{}
}

func (s *StdoutBackend) Log(check *Check, statusCode int, duration time.Duration) {
	log.Println(check.Key, statusCode, duration)
}

func (s *StdoutBackend) Close() {
	// NO OP
}
<commit_msg>Changes how StatsBackend log metrics<commit_after>package main

import (
	"fmt"
	"github.com/peterbourgon/g2s"
	"log"
	"os"
	"time"
)

type Backend interface {
	// "Log" check result in the Backend service
	Log(check *Check, statusCode int, duration time.Duration)
	Close()
}

// Backend for Statsd
type StatsdBackend struct {
	statsd g2s.Statter
}

// Instanciate a new StatsdBackend
// Uses:
//   STATSD_HOST env variable
//   STATSD_PORT env variable (defaults to 8125)
//   STATSD_PROTOCOL env variable (defaults to udp)
func NewStatsdBackend() (*StatsdBackend, error) {
	envHost := os.Getenv("STATSD_HOST")
	envPort := os.Getenv("STATSD_PORT")
	envProtocol := os.Getenv("STATSD_PROTOCOL")

	if envHost == "" {
		return nil, fmt.Errorf("STATSD_HOST environment variable must be defined")
	}

	if envPort == "" {
		envPort = "8125"
	}

	if envProtocol == "" {
		envProtocol = "udp"
	}

	statsd, err := g2s.Dial(envProtocol, envHost+":"+envPort)
	if err != nil {
		return nil, err
	}

	return &StatsdBackend{statsd}, nil
}

// Log to statsd the check result as follow:
// `Check.Key`.duration : Request duration
// `Check.Key`.success : Request succeeded (status code is 2xx)
// `Check.Key`.error : Request failed (status code != 200)
func (s *StatsdBackend) Log(check *Check, statusCode int, duration time.Duration) {
	s.statsd.Timing(1.0, check.Key+".duration", duration)
	if 200 <= statusCode && 299 >= statusCode {
		s.statsd.Counter(1.0, check.Key+".success", 1)
	} else {
		s.statsd.Counter(1.0, check.Key+".error", 1)
	}
}

func (s *StatsdBackend) Close() {
	// NO OP
}

// StdoutBackend logs result to Stdout
type StdoutBackend struct {
}

func NewStdoutBackend() *StdoutBackend {

	return &StdoutBackend{}
}

func (s *StdoutBackend) Log(check *Check, statusCode int, duration time.Duration) {
	log.Println(check.Key, statusCode, duration)
}

func (s *StdoutBackend) Close() {
	// NO OP
}
<|endoftext|>


<commit_before>package queue

import (
  "fmt"
  "math"
  "sync"
)
// Circular is a bounded queue implemented as a circular queue.  Even though
// Items, Head, and Tail are exported, in most cases, they should not be
// directly.  Doing so may lead to outcomes less than desirable. Use the
// exported methods to interact with the Circular queue.
type Circular struct {
  sync.Mutex
  Items []interface{}
  Head int
  Tail int
  cap int
}

// NewCircularQ returns an initialized circular queue. Even though creating
// the slice with an initial length is much slower than creating one without
// the initial length, cap only, this is done to simplify the actual queue
// management. Don't need to worry about appending vs adding via index and
// don't need to check to see if an append will cause the slice to grow.
//
// The slice is 1 slot larger than the requested size for empty/full
// detection.
func NewCircularQ(size int) *Circular {
  return &Circular{Items: make([]interface{}, size + 1, size + 1), cap: size}
}

// Enqueue will return an error if the queue is full
func (c *Circular) Enqueue(item interface{}) error {
  c.Lock()
  if c.isFull() {
    c.Unlock()
    return fmt.Errorf("queue full: cannot enqueue %v", item)
  }
  c.Items[c.Tail] = item
  c.Tail = int(math.Mod(float64(c.Tail + 1), float64(cap(c.Items))))
  c.Unlock()
  return nil
}

// Dequeue will remove an item from the queue and return it. If the queue is
// empty, a false will be returned.
func (c *Circular) Dequeue() (interface{}, bool) {
  c.Lock()
  if c.isEmpty() {
    c.Unlock()
    return nil, false
  }
  item := c.Items[c.Head]
  c.Head = int(math.Mod(float64(c.Head + 1), float64(cap(c.Items))))
  c.Unlock()
  return item, true
}

// Peek will return the next item in the queue without removing it from the
// queue. If the queue is empty, a false will be returned.
func (c *Circular) Peek() (interface{}, bool) {
  c.Lock()
  defer c.Unlock()
  if c.isEmpty() {
    return nil, false
  }
  return c.Items[c.Head], true
}

// IsEmpty returns whether or not the queue is empty
func (c *Circular) IsEmpty() bool {
  c.Lock()
  defer c.Unlock()
  return c.isEmpty()
}

// isEmpty is an unexported version that expects the caller to handle locking.
// This eliminates double locking on dequeue and peek
func (c *Circular) isEmpty() bool {
  if c.Head == c.Tail {
    return true
  }
  return false
}

// IsFull returns whether or not the queue is full
func (c *Circular) IsFull() bool {
  c.Lock()
  defer  c.Unlock()
  return c.isFull()
}

// isFull is an unexported version that expects the caller to handle locking.
// This eliminates double locking on enqueue
func (c *Circular) isFull() bool {
  if c.Head != int(math.Mod(float64(c.Tail + 1), float64(cap(c.Items)))) {
    return false
  }
  return true
}

// Len returns the current length of the queue (# of items in queue)
func (c *Circular) Len() int {
    c.Lock()
    defer c.Unlock()
    if c.Tail >= c.Head {
      return c.Tail - c.Head
    }
    return c.Tail + len(c.Items) - c.Head
}

// returns the Size of the Queue
func (c *Circular) Size() int {
  return c.cap
}
<commit_msg>make unexported version of peek and have both Peek and Dequeue use it<commit_after>package queue

import (
  "fmt"
  "math"
  "sync"
)
// Circular is a bounded queue implemented as a circular queue.  Even though
// Items, Head, and Tail are exported, in most cases, they should not be
// directly.  Doing so may lead to outcomes less than desirable. Use the
// exported methods to interact with the Circular queue.
type Circular struct {
  sync.Mutex
  Items []interface{}
  Head int
  Tail int
  cap int
}

// NewCircularQ returns an initialized circular queue. Even though creating
// the slice with an initial length is much slower than creating one without
// the initial length, cap only, this is done to simplify the actual queue
// management. Don't need to worry about appending vs adding via index and
// don't need to check to see if an append will cause the slice to grow.
//
// The slice is 1 slot larger than the requested size for empty/full
// detection.
func NewCircularQ(size int) *Circular {
  return &Circular{Items: make([]interface{}, size + 1, size + 1), cap: size}
}

// Enqueue will return an error if the queue is full
func (c *Circular) Enqueue(item interface{}) error {
  c.Lock()
  if c.isFull() {
    c.Unlock()
    return fmt.Errorf("queue full: cannot enqueue %v", item)
  }
  c.Items[c.Tail] = item
  c.Tail = int(math.Mod(float64(c.Tail + 1), float64(cap(c.Items))))
  c.Unlock()
  return nil
}

// Dequeue will remove an item from the queue and return it. If the queue is
// empty, a false will be returned.
func (c *Circular) Dequeue() (interface{}, bool) {
  c.Lock()
  item, ok := c.peek()
  if ok {
    c.Head = int(math.Mod(float64(c.Head + 1), float64(cap(c.Items))))
  }
  c.Unlock()
  return item, ok
}

// Peek will return the next item in the queue without removing it from the
// queue. If the queue is empty, a false will be returned.
func (c *Circular) Peek() (interface{}, bool) {
  c.Lock()
  defer c.Unlock()
  return c.peek()
}

// peek is an unexported version that expects the caller to handle locking.
func (c *Circular) peek() (interface{}, bool) {
  if c.isEmpty() {
    return nil, false
  }
  return c.Items[c.Head], true
}

// IsEmpty returns whether or not the queue is empty
func (c *Circular) IsEmpty() bool {
  c.Lock()
  defer c.Unlock()
  return c.isEmpty()
}

// isEmpty is an unexported version that expects the caller to handle locking.
// This eliminates double locking on dequeue and peek
func (c *Circular) isEmpty() bool {
  if c.Head == c.Tail {
    return true
  }
  return false
}

// IsFull returns whether or not the queue is full
func (c *Circular) IsFull() bool {
  c.Lock()
  defer  c.Unlock()
  return c.isFull()
}

// isFull is an unexported version that expects the caller to handle locking.
// This eliminates double locking on enqueue
func (c *Circular) isFull() bool {
  if c.Head != int(math.Mod(float64(c.Tail + 1), float64(cap(c.Items)))) {
    return false
  }
  return true
}

// Len returns the current length of the queue (# of items in queue)
func (c *Circular) Len() int {
    c.Lock()
    defer c.Unlock()
    if c.Tail >= c.Head {
      return c.Tail - c.Head
    }
    return c.Tail + len(c.Items) - c.Head
}

// returns the Size of the Queue
func (c *Circular) Size() int {
  return c.cap
}
<|endoftext|>


<commit_before>package main

import (
	"flag"
	"io"
	"log"
	"os"
)

var apiToken string

var baseURL = "https://app.rainforestqa.com/api/1"
var out io.Writer = os.Stdout

func parseCommands() []string {
	commands := make([]string, 0, 5)
	for i := len(os.Args) - 1; i > 0; i-- {
		if os.Args[i][0] != '-' {
			commands = append(commands, os.Args[i])
			os.Args = append(os.Args[:i], os.Args[i+1:]...)
		}
	}
	return commands
}
func main() {
	commands := parseCommands()
	command := commands[0]
	flag.StringVar(&apiToken, "token", "no token", "THIS IS THE USAGE")
	flag.Parse()
	switch command {
	case "sites":
		printSites()
	case "folders":
		printFolders()
	case "browsers":
		printBrowsers()
	default:
		log.Fatalf("Unknown command: %s\n", command)
	}
}
<commit_msg>pull API token from environment<commit_after>package main

import (
	"flag"
	"io"
	"log"
	"os"
)

var apiToken string

var baseURL = "https://app.rainforestqa.com/api/1"
var out io.Writer = os.Stdout

func parseCommands() []string {
	commands := make([]string, 0, 5)
	for i := len(os.Args) - 1; i > 0; i-- {
		if os.Args[i][0] != '-' {
			commands = append(commands, os.Args[i])
			os.Args = append(os.Args[:i], os.Args[i+1:]...)
		}
	}
	return commands
}

func main() {
	commands := parseCommands()
	command := commands[0]

	flag.StringVar(&apiToken, "token", "", "API token. You can find your account token at https://app.rainforestqa.com/settings/integrations")
	flag.Parse()

	if len(apiToken) == 0 {
		envToken, present := os.LookupEnv("RAINFOREST_API_TOKEN")

		if present {
			apiToken = envToken
		}
	}

	switch command {
	case "sites":
		printSites()
	case "folders":
		printFolders()
	case "browsers":
		printBrowsers()
	default:
		log.Fatalf("Unknown command: %s\n", command)
	}
}
<|endoftext|>


<commit_before>// Copyright 2015 Factom Foundation
// Use of this source code is governed by the MIT
// license that can be found in the LICENSE file.

package factom

import (
	"encoding/json"
	"fmt"
	"io/ioutil"
	"net/http"
	"strings"

	"github.com/FactomProject/factomd/wsapi"
)

func ECBalance(key string) (int64, error) {
	resp, err := CallV2("entry-credit-balance", false, key, new(wsapi.EntryCreditBalanceResponse))
	if err != nil {
		return 0, err
	}

	if resp.Error != nil {
		return 0, fmt.Errorf(resp.Error.Message)
	}

	return resp.Result.(*wsapi.EntryCreditBalanceResponse).Balance, nil
}

func FctBalance(key string) (int64, error) {
	resp, err := CallV2("factoid-balance", false, key, new(wsapi.FactoidBalanceResponse))
	if err != nil {
		return 0, err
	}

	if resp.Error != nil {
		return 0, fmt.Errorf(resp.Error.Message)
	}

	return resp.Result.(*wsapi.FactoidBalanceResponse).Balance, nil
}

func GenerateFactoidAddress(name string) (string, error) {
	name = strings.TrimSpace(name)

	str := fmt.Sprintf("http://%s/v1/factoid-generate-address/%s", serverFct, name)

	resp, err := http.Get(str)
	if err != nil {
		return "", err
	}

	body, err := ioutil.ReadAll(resp.Body)
	if err != nil {
		return "", err
	}
	resp.Body.Close()

	type x struct {
		Response string
		Success  bool
	}
	b := new(x)
	if err := json.Unmarshal(body, b); err != nil {
		return "", fmt.Errorf("Error attempting to create %s - %v", name, err)
	}

	if !b.Success {
		return "", fmt.Errorf(b.Response)
	}

	return b.Response, nil
}

func GenerateEntryCreditAddress(name string) (string, error) {
	name = strings.TrimSpace(name)

	str := fmt.Sprintf("http://%s/v1/factoid-generate-ec-address/%s", serverFct, name)

	resp, err := http.Get(str)
	if err != nil {
		return "", err
	}

	body, err := ioutil.ReadAll(resp.Body)
	if err != nil {
		return "", err
	}
	resp.Body.Close()

	type x struct {
		Response string
		Success  bool
	}
	b := new(x)
	if err := json.Unmarshal(body, b); err != nil {
		return "", fmt.Errorf("Error attempting to create %s - %v", name, err)
	}

	if !b.Success {
		return "", fmt.Errorf(b.Response)
	}

	return b.Response, nil
}

func GenerateFactoidAddressFromPrivateKey(name string, privateKey string) (string, error) {
	name = strings.TrimSpace(name)

	str := fmt.Sprintf("http://%s/v1/factoid-generate-address-from-private-key/?name=%s&privateKey=%s", serverFct, name, privateKey)

	resp, err := http.Get(str)
	if err != nil {
		return "", err
	}

	body, err := ioutil.ReadAll(resp.Body)
	if err != nil {
		return "", err
	}
	resp.Body.Close()

	type x struct {
		Response string
		Success  bool
	}
	b := new(x)
	if err := json.Unmarshal(body, b); err != nil {
		return "", fmt.Errorf("Error attempting to create %s - %v", name, err)
	}

	if !b.Success {
		return "", fmt.Errorf(b.Response)
	}

	return b.Response, nil
}

func GenerateEntryCreditAddressFromPrivateKey(name string, privateKey string) (string, error) {
	name = strings.TrimSpace(name)

	str := fmt.Sprintf("http://%s/v1/factoid-generate-ec-address-from-private-key/?name=%s&privateKey=%s", serverFct, name, privateKey)

	resp, err := http.Get(str)
	if err != nil {
		return "", err
	}

	body, err := ioutil.ReadAll(resp.Body)
	if err != nil {
		return "", err
	}
	resp.Body.Close()

	type x struct {
		Response string
		Success  bool
	}
	b := new(x)
	if err := json.Unmarshal(body, b); err != nil {
		return "", fmt.Errorf("Error attempting to create %s - %v", name, err)
	}

	if !b.Success {
		return "", fmt.Errorf(b.Response)
	}

	return b.Response, nil
}

func GenerateFactoidAddressFromHumanReadablePrivateKey(name string, privateKey string) (string, error) {
	name = strings.TrimSpace(name)

	str := fmt.Sprintf("http://%s/v1/factoid-generate-address-from-human-readable-private-key/?name=%s&privateKey=%s", serverFct, name, privateKey)

	resp, err := http.Get(str)
	if err != nil {
		return "", err
	}

	body, err := ioutil.ReadAll(resp.Body)
	if err != nil {
		return "", err
	}
	resp.Body.Close()

	type x struct {
		Response string
		Success  bool
	}
	b := new(x)
	if err := json.Unmarshal(body, b); err != nil {
		return "", fmt.Errorf("Error attempting to create %s - %v", name, err)
	}

	if !b.Success {
		return "", fmt.Errorf(b.Response)
	}

	return b.Response, nil
}

func GenerateEntryCreditAddressFromHumanReadablePrivateKey(name string, privateKey string) (string, error) {
	name = strings.TrimSpace(name)

	str := fmt.Sprintf("http://%s/v1/factoid-generate-ec-address-from-human-readable-private-key/?name=%s&privateKey=%s", serverFct, name, privateKey)

	resp, err := http.Get(str)
	if err != nil {
		return "", err
	}

	body, err := ioutil.ReadAll(resp.Body)
	if err != nil {
		return "", err
	}
	resp.Body.Close()

	type x struct {
		Response string
		Success  bool
	}
	b := new(x)
	if err := json.Unmarshal(body, b); err != nil {
		return "", fmt.Errorf("Error attempting to create %s - %v", name, err)
	}

	if !b.Success {
		return "", fmt.Errorf(b.Response)
	}

	return b.Response, nil
}

func GenerateFactoidAddressFromMnemonic(name string, mnemonic string) (string, error) {
	name = strings.TrimSpace(name)

	mnemonic = strings.Replace(mnemonic, " ", "%20", -1)

	str := fmt.Sprintf("http://%s/v1/factoid-generate-address-from-token-sale/?name=%s&mnemonic=%s", serverFct, name, mnemonic)

	resp, err := http.Get(str)
	if err != nil {
		return "", err
	}

	body, err := ioutil.ReadAll(resp.Body)
	if err != nil {
		return "", err
	}
	resp.Body.Close()

	type x struct {
		Response string
		Success  bool
	}
	b := new(x)
	if err := json.Unmarshal(body, b); err != nil {
		return "", fmt.Errorf("Error attempting to create %s - %v", name, err)
	}

	if !b.Success {
		return "", fmt.Errorf(b.Response)
	}

	return b.Response, nil
}
<commit_msg>Fix on balance<commit_after>// Copyright 2015 Factom Foundation
// Use of this source code is governed by the MIT
// license that can be found in the LICENSE file.

package factom

import (
	"encoding/json"
	"fmt"
	"io/ioutil"
	"net/http"
	"strings"

	"github.com/FactomProject/factomd/wsapi"
)

func ECBalance(key string) (int64, error) {
	resp, err := CallV2("entry-credit-balance", false, key, new(wsapi.EntryCreditBalanceResponse))
	if err != nil {
		return 0, err
	}

	if resp.Error != nil {
		return 0, fmt.Errorf(resp.Error.Message)
	}

	return resp.Result.(*wsapi.EntryCreditBalanceResponse).Balance, nil
}

func FctBalance(key string) (int64, error) {
	resp, err := CallV2("factoid-balance", false, key, new(wsapi.FactoidBalanceResponse))
	if err != nil {
		return 0, err
	}

	if resp.Error != nil {
		return 0, fmt.Errorf(resp.Error.Message)
	}

	return resp.Result.(*wsapi.FactoidBalanceResponse).Balance, nil
}

func GenerateFactoidAddress(name string) (string, error) {
	name = strings.TrimSpace(name)

	str := fmt.Sprintf("http://%s/v1/factoid-generate-address/%s", serverFct, name)

	resp, err := http.Get(str)
	if err != nil {
		return "", err
	}

	body, err := ioutil.ReadAll(resp.Body)
	if err != nil {
		return "", err
	}
	resp.Body.Close()

	type x struct {
		Response string
		Success  bool
	}

	fmt.Println(body)

	b := new(x)
	if err := json.Unmarshal(body, b); err != nil {
		return "", fmt.Errorf("Error attempting to create %s - %v", name, err)
	}

	if !b.Success {
		return "", fmt.Errorf(b.Response)
	}

	return b.Response, nil
}

func GenerateEntryCreditAddress(name string) (string, error) {
	name = strings.TrimSpace(name)

	str := fmt.Sprintf("http://%s/v1/factoid-generate-ec-address/%s", serverFct, name)

	resp, err := http.Get(str)
	if err != nil {
		return "", err
	}

	body, err := ioutil.ReadAll(resp.Body)
	if err != nil {
		return "", err
	}
	resp.Body.Close()

	type x struct {
		Response string
		Success  bool
	}

	fmt.Println(string(body))

	b := new(x)
	if err := json.Unmarshal(body, b); err != nil {
		return "", fmt.Errorf("Error attempting to create %s - %v", name, err)
	}

	if !b.Success {
		return "", fmt.Errorf(b.Response)
	}

	return b.Response, nil
}

func GenerateFactoidAddressFromPrivateKey(name string, privateKey string) (string, error) {
	name = strings.TrimSpace(name)

	str := fmt.Sprintf("http://%s/v1/factoid-generate-address-from-private-key/?name=%s&privateKey=%s", serverFct, name, privateKey)

	resp, err := http.Get(str)
	if err != nil {
		return "", err
	}

	body, err := ioutil.ReadAll(resp.Body)
	if err != nil {
		return "", err
	}
	resp.Body.Close()

	type x struct {
		Response string
		Success  bool
	}
	b := new(x)
	if err := json.Unmarshal(body, b); err != nil {
		return "", fmt.Errorf("Error attempting to create %s - %v", name, err)
	}

	if !b.Success {
		return "", fmt.Errorf(b.Response)
	}

	return b.Response, nil
}

func GenerateEntryCreditAddressFromPrivateKey(name string, privateKey string) (string, error) {
	name = strings.TrimSpace(name)

	str := fmt.Sprintf("http://%s/v1/factoid-generate-ec-address-from-private-key/?name=%s&privateKey=%s", serverFct, name, privateKey)

	resp, err := http.Get(str)
	if err != nil {
		return "", err
	}

	body, err := ioutil.ReadAll(resp.Body)
	if err != nil {
		return "", err
	}
	resp.Body.Close()

	type x struct {
		Response string
		Success  bool
	}
	b := new(x)
	if err := json.Unmarshal(body, b); err != nil {
		return "", fmt.Errorf("Error attempting to create %s - %v", name, err)
	}

	if !b.Success {
		return "", fmt.Errorf(b.Response)
	}

	return b.Response, nil
}

func GenerateFactoidAddressFromHumanReadablePrivateKey(name string, privateKey string) (string, error) {
	name = strings.TrimSpace(name)

	str := fmt.Sprintf("http://%s/v1/factoid-generate-address-from-human-readable-private-key/?name=%s&privateKey=%s", serverFct, name, privateKey)

	resp, err := http.Get(str)
	if err != nil {
		return "", err
	}

	body, err := ioutil.ReadAll(resp.Body)
	if err != nil {
		return "", err
	}
	resp.Body.Close()

	type x struct {
		Response string
		Success  bool
	}
	b := new(x)
	if err := json.Unmarshal(body, b); err != nil {
		return "", fmt.Errorf("Error attempting to create %s - %v", name, err)
	}

	if !b.Success {
		return "", fmt.Errorf(b.Response)
	}

	return b.Response, nil
}

func GenerateEntryCreditAddressFromHumanReadablePrivateKey(name string, privateKey string) (string, error) {
	name = strings.TrimSpace(name)

	str := fmt.Sprintf("http://%s/v1/factoid-generate-ec-address-from-human-readable-private-key/?name=%s&privateKey=%s", serverFct, name, privateKey)

	resp, err := http.Get(str)
	if err != nil {
		return "", err
	}

	body, err := ioutil.ReadAll(resp.Body)
	if err != nil {
		return "", err
	}
	resp.Body.Close()

	type x struct {
		Response string
		Success  bool
	}
	b := new(x)
	if err := json.Unmarshal(body, b); err != nil {
		return "", fmt.Errorf("Error attempting to create %s - %v", name, err)
	}

	if !b.Success {
		return "", fmt.Errorf(b.Response)
	}

	return b.Response, nil
}

func GenerateFactoidAddressFromMnemonic(name string, mnemonic string) (string, error) {
	name = strings.TrimSpace(name)

	mnemonic = strings.Replace(mnemonic, " ", "%20", -1)

	str := fmt.Sprintf("http://%s/v1/factoid-generate-address-from-token-sale/?name=%s&mnemonic=%s", serverFct, name, mnemonic)

	resp, err := http.Get(str)
	if err != nil {
		return "", err
	}

	body, err := ioutil.ReadAll(resp.Body)
	if err != nil {
		return "", err
	}
	resp.Body.Close()

	type x struct {
		Response string
		Success  bool
	}
	b := new(x)
	if err := json.Unmarshal(body, b); err != nil {
		return "", fmt.Errorf("Error attempting to create %s - %v", name, err)
	}

	if !b.Success {
		return "", fmt.Errorf(b.Response)
	}

	return b.Response, nil
}
<|endoftext|>


<commit_before>/*
 *    Copyright (C) 2014 Christian Muehlhaeuser
 *                  2014 Michael Wendland
 *
 *    This program is free software: you can redistribute it and/or modify
 *    it under the terms of the GNU Affero General Public License as published
 *    by the Free Software Foundation, either version 3 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 Affero General Public License for more details.
 *
 *    You should have received a copy of the GNU Affero General Public License
 *    along with this program.  If not, see <http://www.gnu.org/licenses/>.
 *
 *    Authors:
 *      Christian Muehlhaeuser <muesli@gmail.com>
 *      Michael Wendland <michiwend@michiwend.com>
 *      Johannes Fürmann <johannes@weltraumpflege.org>
 */

package main

import (
	"encoding/json"
	"io/ioutil"
	"log"
	"os"
	"os/signal"
	"syscall"

	"github.com/muesli/beehive/app"
	_ "github.com/muesli/beehive/filters"
	_ "github.com/muesli/beehive/filters/contains"
	_ "github.com/muesli/beehive/filters/equals"
	_ "github.com/muesli/beehive/filters/endswith"
	_ "github.com/muesli/beehive/filters/startswith"

	"github.com/muesli/beehive/modules"
	_ "github.com/muesli/beehive/modules/anelpowerctrlbee"
	_ "github.com/muesli/beehive/modules/ircbee"
	_ "github.com/muesli/beehive/modules/jabberbee"
	_ "github.com/muesli/beehive/modules/jenkinsbee"
	_ "github.com/muesli/beehive/modules/nagiosbee"
	_ "github.com/muesli/beehive/modules/notificationbee"
	_ "github.com/muesli/beehive/modules/rssbee"
	_ "github.com/muesli/beehive/modules/webbee"
	_ "github.com/muesli/beehive/modules/timebee"
	_ "github.com/muesli/beehive/modules/serialbee"
	_ "github.com/muesli/beehive/modules/spaceapibee"
	_ "github.com/muesli/beehive/modules/htmlextractbee"
	//_ "github.com/muesli/beehive/modules/efabee"
	_ "github.com/muesli/beehive/modules/twitterbee"
	_ "github.com/muesli/beehive/modules/cronbee"
)

var (
	configFile string
)

type Config struct {
	Bees   []modules.Bee
	Chains []modules.Chain
}

// Loads chains from config
func loadConfig() Config {
	config := Config{}

	j, err := ioutil.ReadFile(configFile)
	if err == nil {
		err = json.Unmarshal(j, &config)
	}

	if err != nil {
		log.Fatal(err)
	}

	return config
}

// Saves chains to config
func saveConfig(c Config) {
	j, err := json.MarshalIndent(c, "", "  ")
	if err == nil {
		err = ioutil.WriteFile(configFile, j, 0644)
	}

	if err != nil {
		log.Fatal(err)
	}
}

func main() {
	app.AddFlags([]app.CliFlag{
		app.CliFlag{&configFile, "config", "./beehive.conf", "Config-file to use"},
	})

	// Parse command-line args for all registered modules
	app.Run()

	log.Println()
	log.Println("Beehive is buzzing...")

	config := loadConfig()

	// Initialize modules
	modules.StartModules(config.Bees)
	// Load chains from config
	modules.SetChains(config.Chains)

	// Wait for signals
	ch := make(chan os.Signal, 1)
	signal.Notify(ch, syscall.SIGHUP, syscall.SIGTERM, syscall.SIGINT, syscall.SIGKILL)

	for s := range ch {
		log.Println("Got signal:", s)

		switch s {
		case syscall.SIGHUP:
			modules.RestartModules(config.Bees)

		case syscall.SIGTERM:
			fallthrough
		case syscall.SIGKILL:
			fallthrough
		case syscall.SIGINT:
			return
		}
	}

	// Save chains to config
	/*config.Chains = modules.Chains()
	saveConfig(config)*/
}
<commit_msg>* Actually reload config on -HUP.<commit_after>/*
 *    Copyright (C) 2014 Christian Muehlhaeuser
 *                  2014 Michael Wendland
 *
 *    This program is free software: you can redistribute it and/or modify
 *    it under the terms of the GNU Affero General Public License as published
 *    by the Free Software Foundation, either version 3 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 Affero General Public License for more details.
 *
 *    You should have received a copy of the GNU Affero General Public License
 *    along with this program.  If not, see <http://www.gnu.org/licenses/>.
 *
 *    Authors:
 *      Christian Muehlhaeuser <muesli@gmail.com>
 *      Michael Wendland <michiwend@michiwend.com>
 *      Johannes Fürmann <johannes@weltraumpflege.org>
 */

package main

import (
	"encoding/json"
	"io/ioutil"
	"log"
	"os"
	"os/signal"
	"syscall"

	"github.com/muesli/beehive/app"
	_ "github.com/muesli/beehive/filters"
	_ "github.com/muesli/beehive/filters/contains"
	_ "github.com/muesli/beehive/filters/equals"
	_ "github.com/muesli/beehive/filters/endswith"
	_ "github.com/muesli/beehive/filters/startswith"

	"github.com/muesli/beehive/modules"
	_ "github.com/muesli/beehive/modules/anelpowerctrlbee"
	_ "github.com/muesli/beehive/modules/ircbee"
	_ "github.com/muesli/beehive/modules/jabberbee"
	_ "github.com/muesli/beehive/modules/jenkinsbee"
	_ "github.com/muesli/beehive/modules/nagiosbee"
	_ "github.com/muesli/beehive/modules/notificationbee"
	_ "github.com/muesli/beehive/modules/rssbee"
	_ "github.com/muesli/beehive/modules/webbee"
	_ "github.com/muesli/beehive/modules/timebee"
	_ "github.com/muesli/beehive/modules/serialbee"
	_ "github.com/muesli/beehive/modules/spaceapibee"
	_ "github.com/muesli/beehive/modules/htmlextractbee"
	//_ "github.com/muesli/beehive/modules/efabee"
	_ "github.com/muesli/beehive/modules/twitterbee"
	_ "github.com/muesli/beehive/modules/cronbee"
)

var (
	configFile string
)

type Config struct {
	Bees   []modules.Bee
	Chains []modules.Chain
}

// Loads chains from config
func loadConfig() Config {
	config := Config{}

	j, err := ioutil.ReadFile(configFile)
	if err == nil {
		err = json.Unmarshal(j, &config)
	}

	if err != nil {
		log.Fatal(err)
	}

	return config
}

// Saves chains to config
func saveConfig(c Config) {
	j, err := json.MarshalIndent(c, "", "  ")
	if err == nil {
		err = ioutil.WriteFile(configFile, j, 0644)
	}

	if err != nil {
		log.Fatal(err)
	}
}

func main() {
	app.AddFlags([]app.CliFlag{
		app.CliFlag{&configFile, "config", "./beehive.conf", "Config-file to use"},
	})

	// Parse command-line args for all registered modules
	app.Run()

	log.Println()
	log.Println("Beehive is buzzing...")

	config := loadConfig()

	// Initialize modules
	modules.StartModules(config.Bees)
	// Load chains from config
	modules.SetChains(config.Chains)

	// Wait for signals
	ch := make(chan os.Signal, 1)
	signal.Notify(ch, syscall.SIGHUP, syscall.SIGTERM, syscall.SIGINT, syscall.SIGKILL)

	for s := range ch {
		log.Println("Got signal:", s)

		switch s {
		case syscall.SIGHUP:
			config = loadConfig()
			modules.RestartModules(config.Bees)
			modules.SetChains(config.Chains)

		case syscall.SIGTERM:
			fallthrough
		case syscall.SIGKILL:
			fallthrough
		case syscall.SIGINT:
			return
		}
	}

	// Save chains to config
	/*config.Chains = modules.Chains()
	saveConfig(config)*/
}
<|endoftext|>


<commit_before>package main

import (
	"log"

	"github.com/muesli/beehive/app"

	"github.com/muesli/beehive/modules"
	//_ "github.com/muesli/beehive/modules/hellobee"
	_ "github.com/muesli/beehive/modules/ircbee"
	_ "github.com/muesli/beehive/modules/webbee"
)

func main() {
	// Parse command-line args for all registered modules
	app.Run()

	log.Println("Beehive is buzzing...")

	// Initialize modules
	modules.StartModules()

	// Keep app alive
	ch := make(chan bool)
	<-ch
}
<commit_msg>* Activate HelloBee by default. For funsies.<commit_after>package main

import (
	"log"

	"github.com/muesli/beehive/app"

	"github.com/muesli/beehive/modules"
	_ "github.com/muesli/beehive/modules/hellobee"
	_ "github.com/muesli/beehive/modules/ircbee"
	_ "github.com/muesli/beehive/modules/webbee"
)

func main() {
	// Parse command-line args for all registered modules
	app.Run()

	log.Println("Beehive is buzzing...")

	// Initialize modules
	modules.StartModules()

	// Keep app alive
	ch := make(chan bool)
	<-ch
}
<|endoftext|>


<commit_before>package main

import (
	"bufio"
	"bytes"
	"errors"
	"fmt"
	"io"
	"log"
	"regexp"
	"strconv"
)

const (
	Unicoded     byte   = 100
	Unicodee     byte   = 101
	Unicodei     byte   = 105
	Unicodel     byte   = 108
	Unicode0     byte   = 48
	Unicode1     byte   = 49
	Unicode2     byte   = 50
	Unicode3     byte   = 51
	Unicode4     byte   = 52
	Unicode5     byte   = 53
	Unicode6     byte   = 54
	Unicode7     byte   = 55
	Unicode8     byte   = 56
	Unicode9     byte   = 57
	BeIntPattern string = "^(0|-[1-9]\\d*|[1-9]\\d*)$"
)

func BeDecode(b []byte) (dict *BeDict, err error) {
	defer func() {
		if ex := recover(); ex != nil {
			err = fmt.Errorf("%v", ex)
		}
	}()
	r := bufio.NewReader(bytes.NewReader(b))
	entity := decodeEntity(r)
	if entity == nil || entity.Type != BeDictType {
		err = errors.New("Root element was not a dictionary.")
	}
	dict = entity.Dictionary
	return dict, err
}

func decodeEntity(reader *bufio.Reader) *BeNode {
	var bencodeEntity BeNode
	if b, err := reader.Peek(1); err != nil {
		if err == io.EOF {
			return nil
		} else {
			panic(err)
		}
	} else {
		switch b[0] {
		case Unicodei:
			bencodeEntity = BeNode{Integer: decodeInteger(reader), Type: BeIntegerType}
		case Unicode0, Unicode1, Unicode2, Unicode3, Unicode4, Unicode5, Unicode6, Unicode7, Unicode8, Unicode9:
			bencodeEntity = BeNode{String: decodeString(reader), Type: BeStringType}
		case Unicodel:
			bencodeEntity = BeNode{List: decodeList(reader), Type: BeListType}
		case Unicoded:
			bencodeEntity = BeNode{Dictionary: decodeDictionary(reader), Type: BeDictType}
		case Unicodee:
			reader.ReadByte()
		default:
			return nil
		}
	}
	return &bencodeEntity
}

func decodeInteger(reader *bufio.Reader) *BeInteger {
	var str string
	if b, err := reader.ReadBytes('e'); err != nil {
		panic(err)
	} else {
		str = fmt.Sprintf("%s", string(b[1:len(b)-1]))
		if b, err := regexp.MatchString(BeIntPattern, str); err != nil || b == false {
			panic(fmt.Sprintf("Could not parse integer: %s", str))
		}
	}
	log.Printf("INFO: Decoded integer. Returning %v", BeInteger{str})
	return &BeInteger{str}
}

func decodeString(reader *bufio.Reader) *BeString {
	var length int
	// get the length of the BeString
	if b, err := reader.ReadBytes(':'); err != nil {
		panic(err)
	} else {
		str := fmt.Sprintf("%s", string(b[:len(b)-1]))
		length, err = strconv.Atoi(str)
		if err != nil {
			panic(err)
		}
	}
	// get the value of the BeString
	var buf bytes.Buffer
	for i := 0; i < length; i++ {
		if b, err := reader.ReadByte(); err != nil {
			if err == io.EOF {
				break
			} else {
				panic(err)
			}
		} else {
			buf.WriteByte(b)
		}
	}
	log.Printf("INFO: Decoded string. Returning %v in %v", buf.String(), BeString{length, buf.Bytes()})
	return &BeString{length, buf.Bytes()}
}

func decodeList(reader *bufio.Reader) *BeList {
	var list BeList
	reader.ReadByte()
	for {
		value := decodeEntity(reader)
		if value == nil {
			break
		}
		list = append(list, *value)
	}
	log.Printf("INFO: Decoded list. Returning %v", list)
	return &list
}

func decodeDictionary(reader *bufio.Reader) *BeDict {
	var dict BeDict = make(BeDict)
	reader.ReadByte()
	for {
		// get dictionary key
		key := decodeEntity(reader)
		if key == nil || key.String == nil {
			break
		} else if key.Type != BeStringType {
			panic("Dictionary key was not a string.")
		} else {
			// get associated value
			v := decodeEntity(reader)
			if v.IsNil() {
				panic(fmt.Sprintf("Dictionary key '%s' does not have an associated value.", key.String.Val))
			}
			dict[string(key.String.Val)] = *v
		}
	}
	log.Printf("INFO: Decoded dictionary. Returning %v", dict)
	return &dict
}
<commit_msg>Bug fix for list decode<commit_after>package main

import (
	"bufio"
	"bytes"
	"errors"
	"fmt"
	"io"
	"log"
	"regexp"
	"strconv"
)

const (
	Unicoded     byte   = 100
	Unicodee     byte   = 101
	Unicodei     byte   = 105
	Unicodel     byte   = 108
	Unicode0     byte   = 48
	Unicode1     byte   = 49
	Unicode2     byte   = 50
	Unicode3     byte   = 51
	Unicode4     byte   = 52
	Unicode5     byte   = 53
	Unicode6     byte   = 54
	Unicode7     byte   = 55
	Unicode8     byte   = 56
	Unicode9     byte   = 57
	BeIntPattern string = "^(0|-[1-9]\\d*|[1-9]\\d*)$"
)

func BeDecode(b []byte) (dict *BeDict, err error) {
	defer func() {
		if ex := recover(); ex != nil {
			err = fmt.Errorf("%v", ex)
		}
	}()
	r := bufio.NewReader(bytes.NewReader(b))
	entity := decodeEntity(r)
	if entity == nil || entity.Type != BeDictType {
		err = errors.New("Root element was not a dictionary.")
	}
	dict = entity.Dictionary
	return dict, err
}

func decodeEntity(reader *bufio.Reader) *BeNode {
	var bencodeEntity BeNode
	if b, err := reader.Peek(1); err != nil {
		if err == io.EOF {
			return nil
		} else {
			panic(err)
		}
	} else {
		switch b[0] {
		case Unicodei:
			bencodeEntity = BeNode{Integer: decodeInteger(reader), Type: BeIntegerType}
		case Unicode0, Unicode1, Unicode2, Unicode3, Unicode4, Unicode5, Unicode6, Unicode7, Unicode8, Unicode9:
			bencodeEntity = BeNode{String: decodeString(reader), Type: BeStringType}
		case Unicodel:
			bencodeEntity = BeNode{List: decodeList(reader), Type: BeListType}
		case Unicoded:
			bencodeEntity = BeNode{Dictionary: decodeDictionary(reader), Type: BeDictType}
		case Unicodee:
			reader.ReadByte()
		default:
			return nil
		}
	}
	return &bencodeEntity
}

func decodeInteger(reader *bufio.Reader) *BeInteger {
	var str string
	if b, err := reader.ReadBytes('e'); err != nil {
		panic(err)
	} else {
		str = fmt.Sprintf("%s", string(b[1:len(b)-1]))
		if b, err := regexp.MatchString(BeIntPattern, str); err != nil || b == false {
			panic(fmt.Sprintf("Could not parse integer: %s", str))
		}
	}
	log.Printf("INFO: Decoded integer. Returning %v", BeInteger{str})
	return &BeInteger{str}
}

func decodeString(reader *bufio.Reader) *BeString {
	var length int
	// get the length of the BeString
	if b, err := reader.ReadBytes(':'); err != nil {
		panic(err)
	} else {
		str := fmt.Sprintf("%s", string(b[:len(b)-1]))
		length, err = strconv.Atoi(str)
		if err != nil {
			panic(err)
		}
	}
	// get the value of the BeString
	var buf bytes.Buffer
	for i := 0; i < length; i++ {
		if b, err := reader.ReadByte(); err != nil {
			if err == io.EOF {
				break
			} else {
				panic(err)
			}
		} else {
			buf.WriteByte(b)
		}
	}
	log.Printf("INFO: Decoded string. Returning %v in %v", buf.String(), BeString{length, buf.Bytes()})
	return &BeString{length, buf.Bytes()}
}

func decodeList(reader *bufio.Reader) *BeList {
	var list BeList
	reader.ReadByte()
	for {
		value := decodeEntity(reader)
		if value == nil || value.IsNil() {
			break
		}
		list = append(list, *value)
	}
	log.Printf("INFO: Decoded list. Returning %v", list)
	return &list
}

func decodeDictionary(reader *bufio.Reader) *BeDict {
	var dict BeDict = make(BeDict)
	reader.ReadByte()
	for {
		// get dictionary key
		key := decodeEntity(reader)
		if key == nil || key.String == nil {
			break
		} else if key.Type != BeStringType {
			panic("Dictionary key was not a string.")
		} else {
			// get associated value
			v := decodeEntity(reader)
			if v.IsNil() {
				panic(fmt.Sprintf("Dictionary key '%s' does not have an associated value.", key.String.Val))
			}
			dict[string(key.String.Val)] = *v
		}
	}
	log.Printf("INFO: Decoded dictionary. Returning %v", dict)
	return &dict
}
<|endoftext|>


<commit_before>// Copyright 2015 Richard Hawkins
//
// 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 sprite provides functions for managing sprites.

package sprite

import (
	"bytes"
	"fmt"
	"image"
	"image/draw"
	"runtime"

	"github.com/go-gl/gl/v4.1-core/gl"
	"github.com/go-gl/mathgl/mgl32"
	"github.com/hurricanerix/FlappyDisk/gen"
)

func init() {
	// GLFW event handling must run on the main OS thread
	runtime.LockOSThread()
}

// New returns Sprite
func New(assetName string) (*Sprite, error) {
	data, err := gen.Asset(assetName)
	if err != nil {
		return nil, err
	}

	tex, err := newTexture(data)
	if err != nil {
		return nil, err
	}

	s := Sprite{
		AssetName: assetName,
		Pos:       mgl32.Vec3{0.0, 0.0, 0.0},
		Scale:     1.0,
		Rot:       0.0,
		Texture:   tex,
		data:      data,
		model:     mgl32.Ident4(),
	}

	return &s, nil
}

// Sprite represents position, rotation and scale for a given asset.
type Sprite struct {
	AssetName    string
	Pos          mgl32.Vec3
	Scale        float64
	Rot          float64
	Texture      uint32
	data         []byte
	vao          uint32
	model        mgl32.Mat4
	modelUniform int32
}

func (s *Sprite) Bind(program uint32) error {
	gl.GenVertexArrays(1, &s.vao)
	gl.BindVertexArray(s.vao)

	var vbo uint32
	gl.GenBuffers(1, &vbo)
	gl.BindBuffer(gl.ARRAY_BUFFER, vbo)
	gl.BufferData(gl.ARRAY_BUFFER, len(vertices)*4, gl.Ptr(vertices), gl.STATIC_DRAW)

	vertAttrib := uint32(gl.GetAttribLocation(program, gl.Str("vert\x00")))
	gl.EnableVertexAttribArray(vertAttrib)
	gl.VertexAttribPointer(vertAttrib, 3, gl.FLOAT, false, 5*4, gl.PtrOffset(0))

	texCoordAttrib := uint32(gl.GetAttribLocation(program, gl.Str("vertTexCoord\x00")))
	gl.EnableVertexAttribArray(texCoordAttrib)
	gl.VertexAttribPointer(texCoordAttrib, 2, gl.FLOAT, false, 5*4, gl.PtrOffset(3*4))

	textureUniform := gl.GetUniformLocation(program, gl.Str("tex\x00"))
	gl.Uniform1i(textureUniform, 0)

	s.modelUniform = gl.GetUniformLocation(program, gl.Str("model\x00"))
	gl.UniformMatrix4fv(s.modelUniform, 1, false, &s.model[0])
	return nil
}

func (s *Sprite) Draw() {
	s.model = (mgl32.Scale3D(float32(s.Scale), float32(s.Scale), 0.0)).Mul4(
		mgl32.Translate3D(s.Pos[0], s.Pos[1], s.Pos[2])).Mul4(
		mgl32.HomogRotate3DZ(float32(s.Rot)))

	gl.UniformMatrix4fv(s.modelUniform, 1, false, &s.model[0])

	gl.BindVertexArray(s.vao)

	gl.ActiveTexture(gl.TEXTURE0)
	gl.BindTexture(gl.TEXTURE_2D, s.Texture)

	gl.DrawArrays(gl.TRIANGLES, 0, 6*2*3)
}

func newTexture(b []byte) (uint32, error) {
	img, _, err := image.Decode(bytes.NewReader(b))
	if err != nil {
		return 0, err
	}

	rgba := image.NewRGBA(img.Bounds())
	if rgba.Stride != rgba.Rect.Size().X*4 {
		return 0, fmt.Errorf("unsupported stride")
	}
	draw.Draw(rgba, rgba.Bounds(), img, image.Point{0, 0}, draw.Src)

	var texture uint32
	gl.GenTextures(1, &texture)
	gl.ActiveTexture(gl.TEXTURE0)
	gl.BindTexture(gl.TEXTURE_2D, texture)
	gl.TexParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.LINEAR)
	gl.TexParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST)
	gl.TexParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE)
	gl.TexParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE)
	gl.TexImage2D(
		gl.TEXTURE_2D,
		0,
		gl.RGBA,
		int32(rgba.Rect.Size().X),
		int32(rgba.Rect.Size().Y),
		0,
		gl.RGBA,
		gl.UNSIGNED_BYTE,
		gl.Ptr(rgba.Pix))

	return texture, nil
}

var vertices = []float32{
	0.5, 0.5, -0.5, 1.0, 0.0,
	-0.5, 0.5, -0.5, 0.0, 0.0,
	0.5, -0.5, -0.5, 1.0, 1.0,
	-0.5, 0.5, -0.5, 0.0, 0.0,
	-0.5, -0.5, -0.5, 0.0, 1.0,
	0.5, -0.5, -0.5, 1.0, 1.0,
}
<commit_msg>Fix transparency<commit_after>// Copyright 2015 Richard Hawkins
//
// 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 sprite provides functions for managing sprites.

package sprite

import (
	"bytes"
	"fmt"
	"image"
	"image/draw"
	"runtime"

	"github.com/go-gl/gl/v4.1-core/gl"
	"github.com/go-gl/mathgl/mgl32"
	"github.com/hurricanerix/FlappyDisk/gen"
)

func init() {
	// GLFW event handling must run on the main OS thread
	runtime.LockOSThread()
}

// New returns Sprite
func New(assetName string) (*Sprite, error) {
	data, err := gen.Asset(assetName)
	if err != nil {
		return nil, err
	}

	tex, err := newTexture(data)
	if err != nil {
		return nil, err
	}

	s := Sprite{
		AssetName: assetName,
		Pos:       mgl32.Vec3{0.0, 0.0, 0.0},
		Scale:     1.0,
		Rot:       0.0,
		Texture:   tex,
		data:      data,
		model:     mgl32.Ident4(),
	}

	return &s, nil
}

// Sprite represents position, rotation and scale for a given asset.
type Sprite struct {
	AssetName    string
	Pos          mgl32.Vec3
	Scale        float64
	Rot          float64
	Texture      uint32
	data         []byte
	vao          uint32
	model        mgl32.Mat4
	modelUniform int32
}

func (s *Sprite) Bind(program uint32) error {
	gl.GenVertexArrays(1, &s.vao)
	gl.BindVertexArray(s.vao)

	var vbo uint32
	gl.GenBuffers(1, &vbo)
	gl.BindBuffer(gl.ARRAY_BUFFER, vbo)
	gl.BufferData(gl.ARRAY_BUFFER, len(vertices)*4, gl.Ptr(vertices), gl.STATIC_DRAW)

	vertAttrib := uint32(gl.GetAttribLocation(program, gl.Str("vert\x00")))
	gl.EnableVertexAttribArray(vertAttrib)
	gl.VertexAttribPointer(vertAttrib, 3, gl.FLOAT, false, 5*4, gl.PtrOffset(0))

	texCoordAttrib := uint32(gl.GetAttribLocation(program, gl.Str("vertTexCoord\x00")))
	gl.EnableVertexAttribArray(texCoordAttrib)
	gl.VertexAttribPointer(texCoordAttrib, 2, gl.FLOAT, false, 5*4, gl.PtrOffset(3*4))

	textureUniform := gl.GetUniformLocation(program, gl.Str("tex\x00"))
	gl.Uniform1i(textureUniform, 0)

	s.modelUniform = gl.GetUniformLocation(program, gl.Str("model\x00"))
	gl.UniformMatrix4fv(s.modelUniform, 1, false, &s.model[0])
	return nil
}

func (s *Sprite) Draw() {
	s.model = (mgl32.Scale3D(float32(s.Scale), float32(s.Scale), 0.0)).Mul4(
		mgl32.Translate3D(s.Pos[0], s.Pos[1], s.Pos[2])).Mul4(
		mgl32.HomogRotate3DZ(float32(s.Rot)))

	gl.UniformMatrix4fv(s.modelUniform, 1, false, &s.model[0])

	gl.BindVertexArray(s.vao)

	gl.ActiveTexture(gl.TEXTURE0)
	gl.BindTexture(gl.TEXTURE_2D, s.Texture)

	gl.DrawArrays(gl.TRIANGLES, 0, 6*2*3)
}

func newTexture(b []byte) (uint32, error) {
	img, _, err := image.Decode(bytes.NewReader(b))
	if err != nil {
		return 0, err
	}

	rgba := image.NewRGBA(img.Bounds())
	if rgba.Stride != rgba.Rect.Size().X*4 {
		return 0, fmt.Errorf("unsupported stride")
	}
	draw.Draw(rgba, rgba.Bounds(), img, image.Point{0, 0}, draw.Src)

	var texture uint32
	gl.Enable(gl.BLEND)
	gl.BlendFunc(gl.SRC_ALPHA, gl.ONE_MINUS_SRC_ALPHA)

	gl.GenTextures(1, &texture)
	gl.ActiveTexture(gl.TEXTURE0)
	gl.BindTexture(gl.TEXTURE_2D, texture)
	gl.TexParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.LINEAR)
	gl.TexParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST)
	gl.TexParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE)
	gl.TexParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE)
	gl.TexImage2D(
		gl.TEXTURE_2D,
		0,
		gl.RGBA,
		int32(rgba.Rect.Size().X),
		int32(rgba.Rect.Size().Y),
		0,
		gl.RGBA,
		gl.UNSIGNED_BYTE,
		gl.Ptr(rgba.Pix))

	return texture, nil
}

var vertices = []float32{
	0.5, 0.5, -0.5, 1.0, 0.0,
	-0.5, 0.5, -0.5, 0.0, 0.0,
	0.5, -0.5, -0.5, 1.0, 1.0,
	-0.5, 0.5, -0.5, 0.0, 0.0,
	-0.5, -0.5, -0.5, 0.0, 1.0,
	0.5, -0.5, -0.5, 1.0, 1.0,
}
<|endoftext|>


<commit_before>// Package binding transforms a raw request into a struct
// ready to be used your application. It can also perform
// validation on the data and handle errors.
package binding

import (
	"encoding/json"
	"io"
	"mime/multipart"
	"net/http"
	"reflect"
	"strconv"
	"strings"

	"github.com/go-martini/martini"
)

/*
	For the land of Middle-ware Earth:
		One func to rule them all,
		One func to find them,
		One func to bring them all,
		And in this package BIND them.
*/

// Bind wraps up the functionality of the Form and Json middleware
// according to the Content-Type and verb of the request.
// A Content-Type is required for POST and PUT requests.
// Bind invokes the ErrorHandler middleware to bail out if errors
// occurred. If you want to perform your own error handling, use
// Form or Json middleware directly. An interface pointer can
// be added as a second argument in order to map the struct to
// a specific interface.
func Bind(obj interface{}, ifacePtr ...interface{}) martini.Handler {
	return func(context martini.Context, req *http.Request) {
		contentType := req.Header.Get("Content-Type")

		if req.Method == "POST" || req.Method == "PUT" || contentType != "" {
			if strings.Contains(contentType, "form-urlencoded") {
				context.Invoke(Form(obj, ifacePtr...))
			} else if strings.Contains(contentType, "multipart/form-data") {
				context.Invoke(MultipartForm(obj, ifacePtr...))
			} else if strings.Contains(contentType, "json") {
				context.Invoke(Json(obj, ifacePtr...))
			} else {
				var errors Errors
				if contentType == "" {
					errors.Add([]string{}, ContentTypeError, "Empty Content-Type")
				} else {
					errors.Add([]string{}, ContentTypeError, "Unsupported Content-Type")
				}
				context.Map(errors)
			}
		}

		context.Invoke(ErrorHandler)
	}
}

// Form is middleware to deserialize form-urlencoded data from the request.
// It gets data from the form-urlencoded body, if present, or from the
// query string. It uses the http.Request.ParseForm() method
// to perform deserialization, then reflection is used to map each field
// into the struct with the proper type. Structs with primitive slice types
// (bool, float, int, string) can support deserialization of repeated form
// keys, for example: key=val1&key=val2&key=val3
// An interface pointer can be added as a second argument in order
// to map the struct to a specific interface.
func Form(formStruct interface{}, ifacePtr ...interface{}) martini.Handler {
	return func(context martini.Context, req *http.Request) {
		var errors Errors

		ensureNotPointer(formStruct)
		formStruct := reflect.New(reflect.TypeOf(formStruct))
		parseErr := req.ParseForm()

		// Format validation of the request body or the URL would add considerable overhead,
		// and ParseForm does not complain when URL encoding is off.
		// Because an empty request body or url can also mean absence of all needed values,
		// it is not in all cases a bad request, so let's return 422.
		if parseErr != nil {
			errors.Add([]string{}, DeserializationError, parseErr.Error())
		}
		mapForm(formStruct, req.Form, nil, errors)
		validateAndMap(formStruct, context, errors, ifacePtr...)
	}
}

// MultipartForm works much like Form, except it can parse multipart forms
// and handle file uploads. Like the other deserialization middleware handlers,
// you can pass in an interface to make the interface available for injection
// into other handlers later.
func MultipartForm(formStruct interface{}, ifacePtr ...interface{}) martini.Handler {
	return func(context martini.Context, req *http.Request) {
		var errors Errors

		ensureNotPointer(formStruct)
		formStruct := reflect.New(reflect.TypeOf(formStruct))

		// Workaround for multipart forms returning nil instead of an error
		// when content is not multipart
		// https://code.google.com/p/go/issues/detail?id=6334
		multipartReader, err := req.MultipartReader()
		if err != nil {
			errors.Add([]string{}, DeserializationError, err.Error())
		} else {
			form, parseErr := multipartReader.ReadForm(MaxMemory)
			if parseErr != nil {
				errors.Add([]string{}, DeserializationError, parseErr.Error())
			}
			req.MultipartForm = form
		}

		mapForm(formStruct, req.MultipartForm.Value, req.MultipartForm.File, errors)
		validateAndMap(formStruct, context, errors, ifacePtr...)
	}
}

// Json is middleware to deserialize a JSON payload from the request
// into the struct that is passed in. The resulting struct is then
// validated, but no error handling is actually performed here.
// An interface pointer can be added as a second argument in order
// to map the struct to a specific interface.
func Json(jsonStruct interface{}, ifacePtr ...interface{}) martini.Handler {
	return func(context martini.Context, req *http.Request) {
		var errors Errors

		ensureNotPointer(jsonStruct)

		jsonStruct := reflect.New(reflect.TypeOf(jsonStruct))

		if req.Body != nil {
			defer req.Body.Close()
			err := json.NewDecoder(req.Body).Decode(jsonStruct.Interface())
			if err != nil && err != io.EOF {
				errors.Add([]string{}, DeserializationError, err.Error())
			}
		}

		validateAndMap(jsonStruct, context, errors, ifacePtr...)
	}
}

// Validate is middleware to enforce required fields. If the struct
// passed in implements Validator, then the user-defined Validate method
// is executed, and its errors are mapped to the context. This middleware
// performs no error handling: it merely detects errors and maps them.
func Validate(obj interface{}) martini.Handler {
	return func(context martini.Context, req *http.Request) {
		var errors Errors
		errors = validateStruct(errors, obj)
		if validator, ok := obj.(Validator); ok {
			errors = validator.Validate(errors, req)
		}
		context.Map(errors)
	}
}

// Performs required field checking on a struct
func validateStruct(errors Errors, obj interface{}) Errors {
	typ := reflect.TypeOf(obj)
	val := reflect.ValueOf(obj)

	if typ.Kind() == reflect.Ptr {
		typ = typ.Elem()
		val = val.Elem()
	}

	for i := 0; i < typ.NumField(); i++ {
		field := typ.Field(i)

		// Skip ignored and unexported fields in the struct
		if field.Tag.Get("form") == "-" || !val.Field(i).CanInterface() {
			continue
		}

		fieldValue := val.Field(i).Interface()
		zero := reflect.Zero(field.Type).Interface()

		// Validate nested and embedded structs (if pointer, only do so if not nil)
		if field.Type.Kind() == reflect.Struct ||
			(field.Type.Kind() == reflect.Ptr && !reflect.DeepEqual(zero, fieldValue) &&
				field.Type.Elem().Kind() == reflect.Struct) {
			errors = validateStruct(errors, fieldValue)
		}

		if strings.Index(field.Tag.Get("binding"), "required") > -1 {
			if reflect.DeepEqual(zero, fieldValue) {
				name := field.Name
				if j := field.Tag.Get("json"); j != "" {
					name = j
				} else if f := field.Tag.Get("form"); f != "" {
					name = f
				}
				errors.Add([]string{name}, RequiredError, "Required")
			}
		}
	}
	return errors
}

// Takes values from the form data and puts them into a struct
func mapForm(formStruct reflect.Value, form map[string][]string,
	formfile map[string][]*multipart.FileHeader, errors Errors) {

	if formStruct.Kind() == reflect.Ptr {
		formStruct = formStruct.Elem()
	}
	typ := formStruct.Type()

	for i := 0; i < typ.NumField(); i++ {
		typeField := typ.Field(i)
		structField := formStruct.Field(i)

		if typeField.Type.Kind() == reflect.Struct {
			mapForm(structField, form, formfile, errors)
		} else if inputFieldName := typeField.Tag.Get("form"); inputFieldName != "" {
			if !structField.CanSet() {
				continue
			}

			inputValue, exists := form[inputFieldName]
			if exists {
				numElems := len(inputValue)
				if structField.Kind() == reflect.Slice && numElems > 0 {
					sliceOf := structField.Type().Elem().Kind()
					slice := reflect.MakeSlice(structField.Type(), numElems, numElems)
					for i := 0; i < numElems; i++ {
						setWithProperType(sliceOf, inputValue[i], slice.Index(i), inputFieldName, errors)
					}
					formStruct.Field(i).Set(slice)
				} else {
					setWithProperType(typeField.Type.Kind(), inputValue[0], structField, inputFieldName, errors)
				}
				continue
			}

			inputFile, exists := formfile[inputFieldName]
			if !exists {
				continue
			}
			fhType := reflect.TypeOf((*multipart.FileHeader)(nil))
			numElems := len(inputFile)
			if structField.Kind() == reflect.Slice && numElems > 0 && structField.Type().Elem() == fhType {
				slice := reflect.MakeSlice(structField.Type(), numElems, numElems)
				for i := 0; i < numElems; i++ {
					slice.Index(i).Set(reflect.ValueOf(inputFile[i]))
				}
				structField.Set(slice)
			} else if structField.Type() == fhType {
				structField.Set(reflect.ValueOf(inputFile[0]))
			}
		}
	}
}

// ErrorHandler simply counts the number of errors in the
// context and, if more than 0, writes a response with an
// error code and a JSON payload describing the errors.
// The response will have a JSON content-type.
// Middleware remaining on the stack will not even see the request
// if, by this point, there are any errors.
// This is a "default" handler, of sorts, and you are
// welcome to use your own instead. The Bind middleware
// invokes this automatically for convenience.
func ErrorHandler(errs Errors, resp http.ResponseWriter) {
	if len(errs) > 0 {
		resp.Header().Set("Content-Type", jsonContentType)
		if errs.Has(DeserializationError) {
			resp.WriteHeader(http.StatusBadRequest)
		} else if errs.Has(ContentTypeError) {
			resp.WriteHeader(http.StatusUnsupportedMediaType)
		} else {
			resp.WriteHeader(StatusUnprocessableEntity)
		}
		errOutput, _ := json.Marshal(errs)
		resp.Write(errOutput)
		return
	}
}

// This sets the value in a struct of an indeterminate type to the
// matching value from the request (via Form middleware) in the
// same type, so that not all deserialized values have to be strings.
// Supported types are string, int, float, and bool.
func setWithProperType(valueKind reflect.Kind, val string, structField reflect.Value, nameInTag string, errors Errors) {
	switch valueKind {
	case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
		if val == "" {
			val = "0"
		}
		intVal, err := strconv.ParseInt(val, 10, 64)
		if err != nil {
			errors.Add([]string{nameInTag}, TypeError, "Value could not be parsed as integer")
		} else {
			structField.SetInt(intVal)
		}
	case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64:
		if val == "" {
			val = "0"
		}
		uintVal, err := strconv.ParseUint(val, 10, 64)
		if err != nil {
			errors.Add([]string{nameInTag}, TypeError, "Value could not be parsed as unsigned integer")
		} else {
			structField.SetUint(uintVal)
		}
	case reflect.Bool:
		if val == "" {
			val = "false"
		}
		boolVal, err := strconv.ParseBool(val)
		if err != nil {
			errors.Add([]string{nameInTag}, TypeError, "Value could not be parsed as boolean")
		} else {
			structField.SetBool(boolVal)
		}
	case reflect.Float32:
		if val == "" {
			val = "0.0"
		}
		floatVal, err := strconv.ParseFloat(val, 32)
		if err != nil {
			errors.Add([]string{nameInTag}, TypeError, "Value could not be parsed as 32-bit float")
		} else {
			structField.SetFloat(floatVal)
		}
	case reflect.Float64:
		if val == "" {
			val = "0.0"
		}
		floatVal, err := strconv.ParseFloat(val, 64)
		if err != nil {
			errors.Add([]string{nameInTag}, TypeError, "Value could not be parsed as 64-bit float")
		} else {
			structField.SetFloat(floatVal)
		}
	case reflect.String:
		structField.SetString(val)
	}
}

// Don't pass in pointers to bind to. Can lead to bugs. See:
// https://github.com/codegangsta/martini-contrib/pull/34#issuecomment-29683659
func ensureNotPointer(obj interface{}) {
	if reflect.TypeOf(obj).Kind() == reflect.Ptr {
		panic("Pointers are not accepted as binding models")
	}
}

// Performs validation and combines errors from validation
// with errors from deserialization, then maps both the
// resulting struct and the errors to the context.
func validateAndMap(obj reflect.Value, context martini.Context, errors Errors, ifacePtr ...interface{}) {
	context.Invoke(Validate(obj.Interface()))
	errors = append(errors, getErrors(context)...)
	context.Map(errors)
	context.Map(obj.Elem().Interface())
	if len(ifacePtr) > 0 {
		context.MapTo(obj.Elem().Interface(), ifacePtr[0])
	}
}

// getErrors simply gets the errors from the context (it's kind of a chore)
func getErrors(context martini.Context) Errors {
	return context.Get(reflect.TypeOf(Errors{})).Interface().(Errors)
}

type (
	// Implement the Validator interface to handle some rudimentary
	// request validation logic so your application doesn't have to.
	Validator interface {
		// Validate validates that the request is OK. It is recommended
		// that validation be limited to checking values for syntax and
		// semantics, enough to know that you can make sense of the request
		// in your application. For example, you might verify that a credit
		// card number matches a valid pattern, but you probably wouldn't
		// perform an actual credit card authorization here.
		Validate(Errors, *http.Request) Errors
	}
)

var (
	// Maximum amount of memory to use when parsing a multipart form.
	// Set this to whatever value you prefer; default is 10 MB.
	MaxMemory = int64(1024 * 1024 * 10)
)

const (
	jsonContentType           = "application/json; charset=utf-8"
	StatusUnprocessableEntity = 422
)
<commit_msg>Fixed URL-binding<commit_after>// Package binding transforms a raw request into a struct
// ready to be used your application. It can also perform
// validation on the data and handle errors.
package binding

import (
	"encoding/json"
	"io"
	"mime/multipart"
	"net/http"
	"reflect"
	"strconv"
	"strings"

	"github.com/go-martini/martini"
)

/*
	For the land of Middle-ware Earth:
		One func to rule them all,
		One func to find them,
		One func to bring them all,
		And in this package BIND them.
*/

// Bind wraps up the functionality of the Form and Json middleware
// according to the Content-Type and verb of the request.
// A Content-Type is required for POST and PUT requests.
// Bind invokes the ErrorHandler middleware to bail out if errors
// occurred. If you want to perform your own error handling, use
// Form or Json middleware directly. An interface pointer can
// be added as a second argument in order to map the struct to
// a specific interface.
func Bind(obj interface{}, ifacePtr ...interface{}) martini.Handler {
	return func(context martini.Context, req *http.Request) {
		contentType := req.Header.Get("Content-Type")

		if req.Method == "POST" || req.Method == "PUT" || contentType != "" {
			if strings.Contains(contentType, "form-urlencoded") {
				context.Invoke(Form(obj, ifacePtr...))
			} else if strings.Contains(contentType, "multipart/form-data") {
				context.Invoke(MultipartForm(obj, ifacePtr...))
			} else if strings.Contains(contentType, "json") {
				context.Invoke(Json(obj, ifacePtr...))
			} else {
				var errors Errors
				if contentType == "" {
					errors.Add([]string{}, ContentTypeError, "Empty Content-Type")
				} else {
					errors.Add([]string{}, ContentTypeError, "Unsupported Content-Type")
				}
				context.Map(errors)
			}
		} else {
			context.Invoke(Form(obj, ifacePtr...))
		}

		context.Invoke(ErrorHandler)
	}
}

// Form is middleware to deserialize form-urlencoded data from the request.
// It gets data from the form-urlencoded body, if present, or from the
// query string. It uses the http.Request.ParseForm() method
// to perform deserialization, then reflection is used to map each field
// into the struct with the proper type. Structs with primitive slice types
// (bool, float, int, string) can support deserialization of repeated form
// keys, for example: key=val1&key=val2&key=val3
// An interface pointer can be added as a second argument in order
// to map the struct to a specific interface.
func Form(formStruct interface{}, ifacePtr ...interface{}) martini.Handler {
	return func(context martini.Context, req *http.Request) {
		var errors Errors

		ensureNotPointer(formStruct)
		formStruct := reflect.New(reflect.TypeOf(formStruct))
		parseErr := req.ParseForm()

		// Format validation of the request body or the URL would add considerable overhead,
		// and ParseForm does not complain when URL encoding is off.
		// Because an empty request body or url can also mean absence of all needed values,
		// it is not in all cases a bad request, so let's return 422.
		if parseErr != nil {
			errors.Add([]string{}, DeserializationError, parseErr.Error())
		}
		mapForm(formStruct, req.Form, nil, errors)
		validateAndMap(formStruct, context, errors, ifacePtr...)
	}
}

// MultipartForm works much like Form, except it can parse multipart forms
// and handle file uploads. Like the other deserialization middleware handlers,
// you can pass in an interface to make the interface available for injection
// into other handlers later.
func MultipartForm(formStruct interface{}, ifacePtr ...interface{}) martini.Handler {
	return func(context martini.Context, req *http.Request) {
		var errors Errors

		ensureNotPointer(formStruct)
		formStruct := reflect.New(reflect.TypeOf(formStruct))

		// Workaround for multipart forms returning nil instead of an error
		// when content is not multipart
		// https://code.google.com/p/go/issues/detail?id=6334
		multipartReader, err := req.MultipartReader()
		if err != nil {
			errors.Add([]string{}, DeserializationError, err.Error())
		} else {
			form, parseErr := multipartReader.ReadForm(MaxMemory)
			if parseErr != nil {
				errors.Add([]string{}, DeserializationError, parseErr.Error())
			}
			req.MultipartForm = form
		}

		mapForm(formStruct, req.MultipartForm.Value, req.MultipartForm.File, errors)
		validateAndMap(formStruct, context, errors, ifacePtr...)
	}
}

// Json is middleware to deserialize a JSON payload from the request
// into the struct that is passed in. The resulting struct is then
// validated, but no error handling is actually performed here.
// An interface pointer can be added as a second argument in order
// to map the struct to a specific interface.
func Json(jsonStruct interface{}, ifacePtr ...interface{}) martini.Handler {
	return func(context martini.Context, req *http.Request) {
		var errors Errors

		ensureNotPointer(jsonStruct)

		jsonStruct := reflect.New(reflect.TypeOf(jsonStruct))

		if req.Body != nil {
			defer req.Body.Close()
			err := json.NewDecoder(req.Body).Decode(jsonStruct.Interface())
			if err != nil && err != io.EOF {
				errors.Add([]string{}, DeserializationError, err.Error())
			}
		}

		validateAndMap(jsonStruct, context, errors, ifacePtr...)
	}
}

// Validate is middleware to enforce required fields. If the struct
// passed in implements Validator, then the user-defined Validate method
// is executed, and its errors are mapped to the context. This middleware
// performs no error handling: it merely detects errors and maps them.
func Validate(obj interface{}) martini.Handler {
	return func(context martini.Context, req *http.Request) {
		var errors Errors
		errors = validateStruct(errors, obj)
		if validator, ok := obj.(Validator); ok {
			errors = validator.Validate(errors, req)
		}
		context.Map(errors)
	}
}

// Performs required field checking on a struct
func validateStruct(errors Errors, obj interface{}) Errors {
	typ := reflect.TypeOf(obj)
	val := reflect.ValueOf(obj)

	if typ.Kind() == reflect.Ptr {
		typ = typ.Elem()
		val = val.Elem()
	}

	for i := 0; i < typ.NumField(); i++ {
		field := typ.Field(i)

		// Skip ignored and unexported fields in the struct
		if field.Tag.Get("form") == "-" || !val.Field(i).CanInterface() {
			continue
		}

		fieldValue := val.Field(i).Interface()
		zero := reflect.Zero(field.Type).Interface()

		// Validate nested and embedded structs (if pointer, only do so if not nil)
		if field.Type.Kind() == reflect.Struct ||
			(field.Type.Kind() == reflect.Ptr && !reflect.DeepEqual(zero, fieldValue) &&
				field.Type.Elem().Kind() == reflect.Struct) {
			errors = validateStruct(errors, fieldValue)
		}

		if strings.Index(field.Tag.Get("binding"), "required") > -1 {
			if reflect.DeepEqual(zero, fieldValue) {
				name := field.Name
				if j := field.Tag.Get("json"); j != "" {
					name = j
				} else if f := field.Tag.Get("form"); f != "" {
					name = f
				}
				errors.Add([]string{name}, RequiredError, "Required")
			}
		}
	}
	return errors
}

// Takes values from the form data and puts them into a struct
func mapForm(formStruct reflect.Value, form map[string][]string,
	formfile map[string][]*multipart.FileHeader, errors Errors) {

	if formStruct.Kind() == reflect.Ptr {
		formStruct = formStruct.Elem()
	}
	typ := formStruct.Type()

	for i := 0; i < typ.NumField(); i++ {
		typeField := typ.Field(i)
		structField := formStruct.Field(i)

		if typeField.Type.Kind() == reflect.Struct {
			mapForm(structField, form, formfile, errors)
		} else if inputFieldName := typeField.Tag.Get("form"); inputFieldName != "" {
			if !structField.CanSet() {
				continue
			}

			inputValue, exists := form[inputFieldName]
			if exists {
				numElems := len(inputValue)
				if structField.Kind() == reflect.Slice && numElems > 0 {
					sliceOf := structField.Type().Elem().Kind()
					slice := reflect.MakeSlice(structField.Type(), numElems, numElems)
					for i := 0; i < numElems; i++ {
						setWithProperType(sliceOf, inputValue[i], slice.Index(i), inputFieldName, errors)
					}
					formStruct.Field(i).Set(slice)
				} else {
					setWithProperType(typeField.Type.Kind(), inputValue[0], structField, inputFieldName, errors)
				}
				continue
			}

			inputFile, exists := formfile[inputFieldName]
			if !exists {
				continue
			}
			fhType := reflect.TypeOf((*multipart.FileHeader)(nil))
			numElems := len(inputFile)
			if structField.Kind() == reflect.Slice && numElems > 0 && structField.Type().Elem() == fhType {
				slice := reflect.MakeSlice(structField.Type(), numElems, numElems)
				for i := 0; i < numElems; i++ {
					slice.Index(i).Set(reflect.ValueOf(inputFile[i]))
				}
				structField.Set(slice)
			} else if structField.Type() == fhType {
				structField.Set(reflect.ValueOf(inputFile[0]))
			}
		}
	}
}

// ErrorHandler simply counts the number of errors in the
// context and, if more than 0, writes a response with an
// error code and a JSON payload describing the errors.
// The response will have a JSON content-type.
// Middleware remaining on the stack will not even see the request
// if, by this point, there are any errors.
// This is a "default" handler, of sorts, and you are
// welcome to use your own instead. The Bind middleware
// invokes this automatically for convenience.
func ErrorHandler(errs Errors, resp http.ResponseWriter) {
	if len(errs) > 0 {
		resp.Header().Set("Content-Type", jsonContentType)
		if errs.Has(DeserializationError) {
			resp.WriteHeader(http.StatusBadRequest)
		} else if errs.Has(ContentTypeError) {
			resp.WriteHeader(http.StatusUnsupportedMediaType)
		} else {
			resp.WriteHeader(StatusUnprocessableEntity)
		}
		errOutput, _ := json.Marshal(errs)
		resp.Write(errOutput)
		return
	}
}

// This sets the value in a struct of an indeterminate type to the
// matching value from the request (via Form middleware) in the
// same type, so that not all deserialized values have to be strings.
// Supported types are string, int, float, and bool.
func setWithProperType(valueKind reflect.Kind, val string, structField reflect.Value, nameInTag string, errors Errors) {
	switch valueKind {
	case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
		if val == "" {
			val = "0"
		}
		intVal, err := strconv.ParseInt(val, 10, 64)
		if err != nil {
			errors.Add([]string{nameInTag}, TypeError, "Value could not be parsed as integer")
		} else {
			structField.SetInt(intVal)
		}
	case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64:
		if val == "" {
			val = "0"
		}
		uintVal, err := strconv.ParseUint(val, 10, 64)
		if err != nil {
			errors.Add([]string{nameInTag}, TypeError, "Value could not be parsed as unsigned integer")
		} else {
			structField.SetUint(uintVal)
		}
	case reflect.Bool:
		if val == "" {
			val = "false"
		}
		boolVal, err := strconv.ParseBool(val)
		if err != nil {
			errors.Add([]string{nameInTag}, TypeError, "Value could not be parsed as boolean")
		} else {
			structField.SetBool(boolVal)
		}
	case reflect.Float32:
		if val == "" {
			val = "0.0"
		}
		floatVal, err := strconv.ParseFloat(val, 32)
		if err != nil {
			errors.Add([]string{nameInTag}, TypeError, "Value could not be parsed as 32-bit float")
		} else {
			structField.SetFloat(floatVal)
		}
	case reflect.Float64:
		if val == "" {
			val = "0.0"
		}
		floatVal, err := strconv.ParseFloat(val, 64)
		if err != nil {
			errors.Add([]string{nameInTag}, TypeError, "Value could not be parsed as 64-bit float")
		} else {
			structField.SetFloat(floatVal)
		}
	case reflect.String:
		structField.SetString(val)
	}
}

// Don't pass in pointers to bind to. Can lead to bugs. See:
// https://github.com/codegangsta/martini-contrib/pull/34#issuecomment-29683659
func ensureNotPointer(obj interface{}) {
	if reflect.TypeOf(obj).Kind() == reflect.Ptr {
		panic("Pointers are not accepted as binding models")
	}
}

// Performs validation and combines errors from validation
// with errors from deserialization, then maps both the
// resulting struct and the errors to the context.
func validateAndMap(obj reflect.Value, context martini.Context, errors Errors, ifacePtr ...interface{}) {
	context.Invoke(Validate(obj.Interface()))
	errors = append(errors, getErrors(context)...)
	context.Map(errors)
	context.Map(obj.Elem().Interface())
	if len(ifacePtr) > 0 {
		context.MapTo(obj.Elem().Interface(), ifacePtr[0])
	}
}

// getErrors simply gets the errors from the context (it's kind of a chore)
func getErrors(context martini.Context) Errors {
	return context.Get(reflect.TypeOf(Errors{})).Interface().(Errors)
}

type (
	// Implement the Validator interface to handle some rudimentary
	// request validation logic so your application doesn't have to.
	Validator interface {
		// Validate validates that the request is OK. It is recommended
		// that validation be limited to checking values for syntax and
		// semantics, enough to know that you can make sense of the request
		// in your application. For example, you might verify that a credit
		// card number matches a valid pattern, but you probably wouldn't
		// perform an actual credit card authorization here.
		Validate(Errors, *http.Request) Errors
	}
)

var (
	// Maximum amount of memory to use when parsing a multipart form.
	// Set this to whatever value you prefer; default is 10 MB.
	MaxMemory = int64(1024 * 1024 * 10)
)

const (
	jsonContentType           = "application/json; charset=utf-8"
	StatusUnprocessableEntity = 422
)
<|endoftext|>