<commit_before>package main

import (
	"flag"
	"fmt"
	"net/http"

	"github.com/JeanJacquesSerpoul/bridge/distribution"
	"github.com/JeanJacquesSerpoul/bridge/libdds"
	"github.com/gorilla/mux"
)

var version = "undefined"

func handlerVersion(w http.ResponseWriter, r *http.Request) {
	w.WriteHeader(http.StatusOK)
	_, _ = w.Write([]byte(version))
}

func handlerParPbn(w http.ResponseWriter, r *http.Request) {
	pbn, okPbn := r.URL.Query()["pbn"]
	sPbn := checkParams(okPbn, pbn, "")
	vul, okVul := r.URL.Query()["vul"]
	sVul := checkParams(okVul, vul, "NONE")
	s, err := libdds.CallParDDS(sPbn, sVul)
	if err != nil {
		w.WriteHeader(http.StatusBadRequest)
		v := fmt.Sprintf("%v", err)
		_, _ = w.Write([]byte(v))
		return
	}
	w.WriteHeader(http.StatusOK)
	_, _ = w.Write([]byte(s))
}

func checkPostParam(value, defaultValue string) string {
	if value == "" {
		return defaultValue
	}
	return value
}

func checkParams(oK bool, value []string, defaultValue string) string {
	if !oK || len(value[0]) < 1 {
		return defaultValue
	}
	return value[0]
}

func handlerIndex(w http.ResponseWriter, r *http.Request) {
	index, okIndex := r.URL.Query()["value"]
	sIndex := checkParams(okIndex, index, "")
	s := "{\"index\":\"" + sIndex + "\"}"
	board, err := distribution.PbnGenerateFromJSONIndex(s)
	if err != nil {
		w.WriteHeader(http.StatusBadRequest)
		v := fmt.Sprintf("%v", err)
		_, _ = w.Write([]byte(v))
		return
	}
	w.WriteHeader(http.StatusOK)
	_, _ = w.Write([]byte(board))
}

func handlerMaskMultiPbn(w http.ResponseWriter, r *http.Request) {
	if r.Method == "POST" {
		err := r.ParseForm()
		if err != nil {
			_, _ = fmt.Fprintf(w, "ParseForm() err: %v", err)
			return
		}
		sh := new(distribution.Random)
		sDealer := checkPostParam(r.FormValue("dealer"), distribution.Position[0])
		sVulnerable := checkPostParam(r.FormValue("vulnerable"), distribution.Vulnerable[0])
		sMask := checkPostParam(r.FormValue("mask"), distribution.EMPTYDESK)
		sComment := checkPostParam(r.FormValue("comment"), "")
		sCount := checkPostParam(r.FormValue("count"), "1")
		s := "{\"count\":" + sCount + ",\n\"mask\":\"" + sMask + "\",\n\"comment\":\"" + sComment + "\",\n\"dealer\":\"" + sDealer + "\",\n\"Vulnerable\":\"" + sVulnerable + "\"\n}"
		board, err := distribution.PbnDataGenerateFromJSON(sh, s)
		if err != nil {
			w.WriteHeader(http.StatusBadRequest)
			v := fmt.Sprintf("%v", err)
			_, _ = w.Write([]byte(v))
			return
		}
		w.WriteHeader(http.StatusOK)
		_, _ = w.Write([]byte(board))
	}
}

func handlerPointMultiPbn(w http.ResponseWriter, r *http.Request) {
	if r.Method == "POST" {
		err := r.ParseForm()
		if err != nil {
			_, _ = fmt.Fprintf(w, "ParseForm() err: %v", err)
			return
		}
		sh := new(distribution.Random)
		sDealer := checkPostParam(r.FormValue("dealer"), distribution.Position[0])
		sVulnerable := checkPostParam(r.FormValue("vulnerable"), distribution.Vulnerable[0])
		sMask := checkPostParam(r.FormValue("mask"), distribution.EMPTYPOINTS)
		sComment := checkPostParam(r.FormValue("comment"), "")
		sCount := checkPostParam(r.FormValue("count"), "1")
		result := ""
		if sMask == distribution.EMPTYPOINTS {
			sMask = distribution.EMPTYDESK
			s := "{\"count\":" + sCount + ",\n\"mask\":\"" + sMask + "\",\n\"comment\":\"" + sComment + "\",\n\"dealer\":\"" + sDealer + "\",\n\"Vulnerable\":\"" + sVulnerable + "\"\n}"
			result, err = distribution.PbnDataGenerateFromJSON(sh, s)
		} else {
			s := "{\"count\":" + sCount + ",\n\"mask\":\"" + sMask + "\",\n\"comment\":\"" + sComment + "\",\n\"dealer\":\"" + sDealer + "\",\n\"Vulnerable\":\"" + sVulnerable + "\"\n}"
			result, err = distribution.PbnPointDataGenerateFromJSON(sh, s)
		}
		if err != nil {
			w.WriteHeader(http.StatusBadRequest)
			v := fmt.Sprintf("%v", err)
			_, _ = w.Write([]byte(v))
			return
		}
		w.WriteHeader(http.StatusOK)
		_, _ = w.Write([]byte(result))
	}
}

func handlerRandomSuitMultiPbn(w http.ResponseWriter, r *http.Request) {
	if r.Method == "POST" {
		err := r.ParseForm()
		if err != nil {
			_, _ = fmt.Fprintf(w, "ParseForm() err: %v", err)
			return
		}
		sh := new(distribution.Random)
		sDealer := checkPostParam(r.FormValue("dealer"), distribution.Position[0])
		sVulnerable := checkPostParam(r.FormValue("vulnerable"), distribution.Vulnerable[0])
		sMask := checkPostParam(r.FormValue("mask"), distribution.EMPTYSUIT)
		sComment := checkPostParam(r.FormValue("comment"), "")
		sCount := checkPostParam(r.FormValue("count"), "1")
		s := "{\"count\":" + sCount + ",\n\"mask\":\"" + sMask + "\",\n\"comment\":\"" + sComment + "\",\n\"dealer\":\"" + sDealer + "\",\n\"Vulnerable\":\"" + sVulnerable + "\"\n}"
		board, err := distribution.PbnSuitDataGenerateFromJSON(sh, s)
		if err != nil {
			w.WriteHeader(http.StatusBadRequest)
			v := fmt.Sprintf("%v", err)
			_, _ = w.Write([]byte(v))
			return
		}
		w.WriteHeader(http.StatusOK)
		_, _ = w.Write([]byte(board))
	}
}

func handlerMaskPbn(w http.ResponseWriter, r *http.Request) {
	if r.Method == "POST" {
		err := r.ParseForm()
		if err != nil {
			_, _ = fmt.Fprintf(w, "ParseForm() err: %v", err)
			return
		}
		sh := new(distribution.Random)
		sMask := checkPostParam(r.FormValue("mask"), distribution.EMPTYDESK)
		result, err := distribution.PbnAndIndexGenerateFromMask(sh, nil, sMask)
		if err != nil {
			w.WriteHeader(http.StatusBadRequest)
			v := fmt.Sprintf("%v", err)
			_, _ = w.Write([]byte(v))
			return
		}
		w.WriteHeader(http.StatusOK)
		r.Header.Set("Content-Type", "application/json")
		_, _ = w.Write([]byte(result))
	}
}

func handlerPointPbn(w http.ResponseWriter, r *http.Request) {
	if r.Method == "POST" {
		err := r.ParseForm()
		if err != nil {
			_, _ = fmt.Fprintf(w, "ParseForm() err: %v", err)
			return
		}
		sh := new(distribution.Random)
		sMask := checkPostParam(r.FormValue("mask"), distribution.EMPTYPOINTS)
		result := ""
		if sMask == distribution.EMPTYPOINTS {
			result, err = distribution.PbnAndIndexGenerateFromMask(sh, nil, distribution.EMPTYDESK)
		} else {
			result, err = distribution.GetPbnHandsFromPoints(sh, sMask)
		}
		if err != nil {
			w.WriteHeader(http.StatusBadRequest)
			v := fmt.Sprintf("%v", err)
			_, _ = w.Write([]byte(v))
			return
		}
		w.WriteHeader(http.StatusOK)
		r.Header.Set("Content-Type", "application/json")
		_, _ = w.Write([]byte(result))
	}
}

func handlerSuitPbn(w http.ResponseWriter, r *http.Request) {
	if r.Method == "POST" {
		err := r.ParseForm()
		if err != nil {
			_, _ = fmt.Fprintf(w, "ParseForm() err: %v", err)
			return
		}
		sh := new(distribution.Random)
		sMask := checkPostParam(r.FormValue("mask"), distribution.EMPTYSUIT)
		result, err := distribution.PbnAndIndexGenerateFromSuits(sh, sMask)
		if err != nil {
			w.WriteHeader(http.StatusBadRequest)
			v := fmt.Sprintf("%v", err)
			_, _ = w.Write([]byte(v))
			return
		}
		w.WriteHeader(http.StatusOK)
		r.Header.Set("Content-Type", "application/json")
		_, _ = w.Write([]byte(result))
	}
}

func main() {
	portPtr := flag.String("p", "3000", "API port")
	flag.Parse()
	port := *portPtr
	r := mux.NewRouter()
	r.HandleFunc("/api/v1/maskmultipbn", handlerMaskMultiPbn)
	r.HandleFunc("/api/v1/maskpbn", handlerMaskPbn)
	r.HandleFunc("/api/v1/index", handlerIndex)
	r.HandleFunc("/api/v1/version", handlerVersion)
	r.HandleFunc("/api/v1/suitpbn", handlerSuitPbn)
	r.HandleFunc("/api/v1/suitmultipbn", handlerRandomSuitMultiPbn)
	r.HandleFunc("/api/v1/pointpbn", handlerPointPbn)
	r.HandleFunc("/api/v1/pointmultipbn", handlerPointMultiPbn)
	r.HandleFunc("/api/v1/parpbn", handlerParPbn)
	err := http.ListenAndServe(":"+port, r)
	if err != nil {
		_, _ = fmt.Printf("Error err: %v", err)
	}
}
<commit_msg>Cleaning code after using new .golangci.toml<commit_after>package main

import (
	"flag"
	"fmt"
	"log"
	"net/http"

	"github.com/JeanJacquesSerpoul/bridge/distribution"
	"github.com/JeanJacquesSerpoul/bridge/libdds"
	"github.com/gorilla/mux"
)

const POST = "POST"

var version = "undefined"

func handlerVersion(w http.ResponseWriter, r *http.Request) {
	w.WriteHeader(http.StatusOK)
	_, _ = w.Write([]byte(version))
}

func handlerParPbn(w http.ResponseWriter, r *http.Request) {
	pbn, okPbn := r.URL.Query()["pbn"]
	sPbn := checkParams(okPbn, pbn, "")
	vul, okVul := r.URL.Query()["vul"]
	sVul := checkParams(okVul, vul, "NONE")
	s, err := libdds.CallParDDS(sPbn, sVul)

	if err != nil {
		w.WriteHeader(http.StatusBadRequest)

		v := fmt.Sprintf("%v", err)
		_, _ = w.Write([]byte(v))

		return
	}

	w.WriteHeader(http.StatusOK)

	_, _ = w.Write([]byte(s))
}

func checkPostParam(value, defaultValue string) string {
	if value == "" {
		return defaultValue
	}

	return value
}

func checkParams(oK bool, value []string, defaultValue string) string {
	if !oK || len(value[0]) < 1 {
		return defaultValue
	}

	return value[0]
}

func handlerIndex(w http.ResponseWriter, r *http.Request) {
	index, okIndex := r.URL.Query()["value"]
	sIndex := checkParams(okIndex, index, "")
	s := "{\"index\":\"" + sIndex + "\"}"
	board, err := distribution.PbnGenerateFromJSONIndex(s)

	if err != nil {
		w.WriteHeader(http.StatusBadRequest)

		v := fmt.Sprintf("%v", err)
		_, _ = w.Write([]byte(v))

		return
	}

	w.WriteHeader(http.StatusOK)

	_, _ = w.Write([]byte(board))
}

func handlerMaskMultiPbn(w http.ResponseWriter, r *http.Request) {
	if r.Method == POST {
		err := r.ParseForm()
		if err != nil {
			_, _ = fmt.Fprintf(w, "ParseForm() err: %v", err)

			return
		}

		sh := new(distribution.Random)
		sDealer := checkPostParam(r.FormValue("dealer"), distribution.Position[0])
		sVulnerable := checkPostParam(r.FormValue("vulnerable"), distribution.Vulnerable[0])
		sMask := checkPostParam(r.FormValue("mask"), distribution.EMPTYDESK)
		sComment := checkPostParam(r.FormValue("comment"), "")
		sCount := checkPostParam(r.FormValue("count"), "1")
		s := "{\"count\":" + sCount + ",\n\"mask\":\"" + sMask +
			"\",\n\"comment\":\"" + sComment + "\",\n\"dealer\":\"" + sDealer +
			"\",\n\"Vulnerable\":\"" + sVulnerable + "\"\n}"
		board, err := distribution.PbnDataGenerateFromJSON(sh, s)

		if err != nil {
			w.WriteHeader(http.StatusBadRequest)

			v := fmt.Sprintf("%v", err)
			_, _ = w.Write([]byte(v))

			return
		}

		w.WriteHeader(http.StatusOK)

		_, _ = w.Write([]byte(board))
	}
}

func handlerPointMultiPbn(w http.ResponseWriter, r *http.Request) {
	if r.Method == POST {
		err := r.ParseForm()
		if err != nil {
			_, _ = fmt.Fprintf(w, "ParseForm() err: %v", err)

			return
		}

		sh := new(distribution.Random)
		sDealer := checkPostParam(r.FormValue("dealer"), distribution.Position[0])
		sVulnerable := checkPostParam(r.FormValue("vulnerable"), distribution.Vulnerable[0])
		sMask := checkPostParam(r.FormValue("mask"), distribution.EMPTYPOINTS)
		sComment := checkPostParam(r.FormValue("comment"), "")
		sCount := checkPostParam(r.FormValue("count"), "1")

		var result string

		if sMask == distribution.EMPTYPOINTS {
			sMask = distribution.EMPTYDESK
			s := "{\"count\":" + sCount + ",\n\"mask\":\"" + sMask +
				"\",\n\"comment\":\"" + sComment + "\",\n\"dealer\":\"" +
				sDealer + "\",\n\"Vulnerable\":\"" + sVulnerable + "\"\n}"
			result, err = distribution.PbnDataGenerateFromJSON(sh, s)
		} else {
			s := "{\"count\":" + sCount + ",\n\"mask\":\"" + sMask +
				"\",\n\"comment\":\"" + sComment + "\",\n\"dealer\":\"" + sDealer +
				"\",\n\"Vulnerable\":\"" + sVulnerable + "\"\n}"
			result, err = distribution.PbnPointDataGenerateFromJSON(sh, s)
		}

		if err != nil {
			w.WriteHeader(http.StatusBadRequest)

			v := fmt.Sprintf("%v", err)
			_, _ = w.Write([]byte(v))

			return
		}

		w.WriteHeader(http.StatusOK)

		_, _ = w.Write([]byte(result))
	}
}

func handlerMaskPbn(w http.ResponseWriter, r *http.Request) {
	if r.Method == POST {
		err := r.ParseForm()
		if err != nil {
			_, _ = fmt.Fprintf(w, "ParseForm() err: %v", err)

			return
		}

		sh := new(distribution.Random)
		sMask := checkPostParam(r.FormValue("mask"), distribution.EMPTYDESK)
		result, err := distribution.PbnAndIndexGenerateFromMask(sh, nil, sMask)

		if err != nil {
			w.WriteHeader(http.StatusBadRequest)

			v := fmt.Sprintf("%v", err)
			_, _ = w.Write([]byte(v))

			return
		}

		w.WriteHeader(http.StatusOK)

		r.Header.Set("Content-Type", "application/json")

		_, _ = w.Write([]byte(result))
	}
}

func handlerPointPbn(w http.ResponseWriter, r *http.Request) {
	if r.Method == POST {
		var result string

		err := r.ParseForm()

		if err != nil {
			_, _ = fmt.Fprintf(w, "ParseForm() err: %v", err)

			return
		}

		sh := new(distribution.Random)
		sMask := checkPostParam(r.FormValue("mask"), distribution.EMPTYPOINTS)

		if sMask == distribution.EMPTYPOINTS {
			result, err = distribution.PbnAndIndexGenerateFromMask(sh, nil, distribution.EMPTYDESK)
		} else {
			result, err = distribution.GetPbnHandsFromPoints(sh, sMask)
		}

		if err != nil {
			w.WriteHeader(http.StatusBadRequest)

			v := fmt.Sprintf("%v", err)
			_, _ = w.Write([]byte(v))

			return
		}

		w.WriteHeader(http.StatusOK)

		r.Header.Set("Content-Type", "application/json")

		_, _ = w.Write([]byte(result))
	}
}

func handlerSuitPbn(w http.ResponseWriter, r *http.Request) {
	if r.Method == POST {
		err := r.ParseForm()
		if err != nil {
			_, _ = fmt.Fprintf(w, "ParseForm() err: %v", err)

			return
		}

		sh := new(distribution.Random)
		sMask := checkPostParam(r.FormValue("mask"), distribution.EMPTYSUIT)
		result, err := distribution.PbnAndIndexGenerateFromSuits(sh, sMask)

		if err != nil {
			w.WriteHeader(http.StatusBadRequest)

			v := fmt.Sprintf("%v", err)
			_, _ = w.Write([]byte(v))

			return
		}

		w.WriteHeader(http.StatusOK)

		r.Header.Set("Content-Type", "application/json")

		_, _ = w.Write([]byte(result))
	}
}

func main() {
	portPtr := flag.String("p", "3000", "API port")
	flag.Parse()

	port := *portPtr
	r := mux.NewRouter()

	r.HandleFunc("/api/v1/maskmultipbn", handlerMaskMultiPbn)
	r.HandleFunc("/api/v1/maskpbn", handlerMaskPbn)
	r.HandleFunc("/api/v1/index", handlerIndex)
	r.HandleFunc("/api/v1/version", handlerVersion)
	r.HandleFunc("/api/v1/suitpbn", handlerSuitPbn)
	r.HandleFunc("/api/v1/pointpbn", handlerPointPbn)
	r.HandleFunc("/api/v1/pointmultipbn", handlerPointMultiPbn)
	r.HandleFunc("/api/v1/parpbn", handlerParPbn)
	log.Fatal(http.ListenAndServe(":"+port, r))
}
<|endoftext|>


<commit_before>package kitsu

import (
	"encoding/json"
)

// Auto-generated JSON definition from:
// https://mholt.github.io/json-to-go/

// AnimePage represents one page containing up to 20 anime objects.
type AnimePage struct {
	Data []*Anime `json:"data"`
	Meta struct {
		Count int `json:"count"`
	} `json:"meta"`
	Links struct {
		First string `json:"first"`
		Prev  string `json:"prev"`
		Next  string `json:"next"`
		Last  string `json:"last"`
	} `json:"links"`
}

// GetAnimePage expects the usual query parameter and returns an AnimePage object instead of a raw string.
func GetAnimePage(query string) (*AnimePage, error) {
	body, requestError := Get(query)

	if requestError != nil {
		return nil, requestError[0]
	}

	page := new(AnimePage)
	decodeError := json.Unmarshal(body, page)

	return page, decodeError
}
<commit_msg>Added included field for anime page mappings<commit_after>package kitsu

import (
	"encoding/json"
)

// Auto-generated JSON definition from:
// https://mholt.github.io/json-to-go/

// AnimePage represents one page containing up to 20 anime objects.
type AnimePage struct {
	Data     []*Anime `json:"data"`
	Included []struct {
		ID    string `json:"id"`
		Type  string `json:"type"`
		Links struct {
			Self string `json:"self"`
		} `json:"links"`
		Attributes struct {
			ExternalSite string `json:"externalSite"`
			ExternalID   string `json:"externalId"`
		} `json:"attributes"`
		Relationships struct {
			Media struct {
				Links struct {
					Self    string `json:"self"`
					Related string `json:"related"`
				} `json:"links"`
			} `json:"media"`
		} `json:"relationships"`
	} `json:"included"`
	Meta struct {
		Count int `json:"count"`
	} `json:"meta"`
	Links struct {
		First string `json:"first"`
		Prev  string `json:"prev"`
		Next  string `json:"next"`
		Last  string `json:"last"`
	} `json:"links"`
}

// GetAnimePage expects the usual query parameter and returns an AnimePage object instead of a raw string.
func GetAnimePage(query string) (*AnimePage, error) {
	body, requestError := Get(query)

	if requestError != nil {
		return nil, requestError[0]
	}

	page := new(AnimePage)
	decodeError := json.Unmarshal(body, page)

	return page, decodeError
}
<|endoftext|>


<commit_before>package kit

import (
	"encoding/base64"
	"path/filepath"
	"testing"

	"github.com/stretchr/testify/assert"

	"github.com/Shopify/themekit/kittest"
)

func TestAsset_IsValid(t *testing.T) {
	asset := Asset{Key: "test.txt", Value: "one"}
	assert.Equal(t, true, asset.IsValid())
	asset = Asset{Key: "test.txt", Attachment: "one"}
	assert.Equal(t, true, asset.IsValid())
	asset = Asset{Value: "one"}
	assert.Equal(t, false, asset.IsValid())
	asset = Asset{Key: "test.txt"}
	assert.Equal(t, false, asset.IsValid())
}

func TestAsset_Size(t *testing.T) {
	asset := Asset{Value: "one"}
	assert.Equal(t, 3, asset.Size())
	asset = Asset{Attachment: "other"}
	assert.Equal(t, 5, asset.Size())
}

func TestAsset_Write(t *testing.T) {
	kittest.Setup()
	defer kittest.Cleanup()
	asset := Asset{Key: "output/blah.txt", Value: "this is content"}
	assert.NotNil(t, asset.Write("./does/not/exist"))
	assert.Nil(t, asset.Write(kittest.FixtureProjectPath))
}

func TestAsset_Contents(t *testing.T) {
	asset := Asset{Value: "this is content"}
	data, err := asset.Contents()
	assert.Nil(t, err)
	assert.Equal(t, 15, len(data))

	asset = Asset{Attachment: "this is bad content"}
	data, err = asset.Contents()
	assert.NotNil(t, err)

	asset = Asset{Attachment: base64.StdEncoding.EncodeToString([]byte("this is bad content"))}
	data, err = asset.Contents()
	assert.Nil(t, err)
	assert.Equal(t, 19, len(data))
	assert.Equal(t, []byte("this is bad content"), data)

	asset = Asset{Key: "test.json", Value: "{\"test\":\"one\"}"}
	data, err = asset.Contents()
	assert.Nil(t, err)
	assert.Equal(t, 19, len(data))
	assert.Equal(t, `{
  "test": "one"
}`, string(data))
}

func TestAsset_CheckSum(t *testing.T) {
	asset := Asset{}
	checksum, err := asset.CheckSum()
	assert.NotNil(t, err)

	asset = Asset{Key: "asset/name.txt", Value: "this is content"}
	checksum, err = asset.CheckSum()
	assert.Nil(t, err)
	assert.Equal(t, "b7fcef7fe745f2a95560ff5f550e3b8f", checksum)

	asset = Asset{Key: "asset/name.txt", Attachment: "this is bad content"}
	checksum, err = asset.CheckSum()
	assert.NotNil(t, err)

	asset = Asset{Key: "asset/name.txt", Attachment: base64.StdEncoding.EncodeToString([]byte("this is bad content"))}
	checksum, err = asset.CheckSum()
	assert.Nil(t, err)
	assert.Equal(t, "04c9d416fc81a9dcb5460c560b532634", checksum)
}

func TestFindAllFiles(t *testing.T) {
	kittest.Setup()
	kittest.GenerateProject()
	defer kittest.Cleanup()
	files, err := findAllFiles(kittest.ProjectFiles[0])
	assert.Equal(t, "Path is not a directory", err.Error())
	files, err = findAllFiles(kittest.FixtureProjectPath)
	assert.Nil(t, err)
	assert.Equal(t, len(kittest.ProjectFiles), len(files))
}

func TestLoadAssetsFromDirectory(t *testing.T) {
	kittest.Setup()
	kittest.GenerateProject()
	defer kittest.Cleanup()

	assets, err := loadAssetsFromDirectory(kittest.ProjectFiles[0], "", func(path string) bool { return false })
	assert.Equal(t, "Path is not a directory", err.Error())
	assets, err = loadAssetsFromDirectory(kittest.FixtureProjectPath, "", func(path string) bool {
		return path != filepath.Join("assets","application.js")
	})
	assert.Nil(t, err)
	assert.Equal(t, []Asset{{
		Key:   "assets/application.js",
		Value: "this is js content",
	}}, assets)

	kittest.Setup()
	kittest.GenerateProject()
	defer kittest.Cleanup()
	assets, err = loadAssetsFromDirectory(kittest.FixtureProjectPath, "assets", func(path string) bool { return false })
	assert.Nil(t, err)
	assert.Equal(t, 2, len(assets))
}

func TestLoadAsset(t *testing.T) {
	kittest.Setup()
	kittest.GenerateProject()
	defer kittest.Cleanup()

	asset, err := loadAsset(kittest.FixtureProjectPath, kittest.ProjectFiles[0])
	assert.Equal(t, filepath.ToSlash(kittest.ProjectFiles[0]), asset.Key)
	assert.Equal(t, true, asset.IsValid())
	assert.Equal(t, "this is js content", asset.Value)
	assert.Nil(t, err)

	asset, err = loadAsset(kittest.FixtureProjectPath, "nope.txt")
	assert.NotNil(t, err)

	asset, err = loadAsset(kittest.FixtureProjectPath, "templates")
	assert.NotNil(t, err)
	assert.Equal(t, ErrAssetIsDir, err)

	asset, err = loadAsset(kittest.FixtureProjectPath, "assets/pixel.png")
	assert.Nil(t, err)
	assert.True(t, len(asset.Attachment) > 0)
	assert.True(t, asset.IsValid())
}
<commit_msg>Formatting<commit_after>package kit

import (
	"encoding/base64"
	"path/filepath"
	"testing"

	"github.com/stretchr/testify/assert"

	"github.com/Shopify/themekit/kittest"
)

func TestAsset_IsValid(t *testing.T) {
	asset := Asset{Key: "test.txt", Value: "one"}
	assert.Equal(t, true, asset.IsValid())
	asset = Asset{Key: "test.txt", Attachment: "one"}
	assert.Equal(t, true, asset.IsValid())
	asset = Asset{Value: "one"}
	assert.Equal(t, false, asset.IsValid())
	asset = Asset{Key: "test.txt"}
	assert.Equal(t, false, asset.IsValid())
}

func TestAsset_Size(t *testing.T) {
	asset := Asset{Value: "one"}
	assert.Equal(t, 3, asset.Size())
	asset = Asset{Attachment: "other"}
	assert.Equal(t, 5, asset.Size())
}

func TestAsset_Write(t *testing.T) {
	kittest.Setup()
	defer kittest.Cleanup()
	asset := Asset{Key: "output/blah.txt", Value: "this is content"}
	assert.NotNil(t, asset.Write("./does/not/exist"))
	assert.Nil(t, asset.Write(kittest.FixtureProjectPath))
}

func TestAsset_Contents(t *testing.T) {
	asset := Asset{Value: "this is content"}
	data, err := asset.Contents()
	assert.Nil(t, err)
	assert.Equal(t, 15, len(data))

	asset = Asset{Attachment: "this is bad content"}
	data, err = asset.Contents()
	assert.NotNil(t, err)

	asset = Asset{Attachment: base64.StdEncoding.EncodeToString([]byte("this is bad content"))}
	data, err = asset.Contents()
	assert.Nil(t, err)
	assert.Equal(t, 19, len(data))
	assert.Equal(t, []byte("this is bad content"), data)

	asset = Asset{Key: "test.json", Value: "{\"test\":\"one\"}"}
	data, err = asset.Contents()
	assert.Nil(t, err)
	assert.Equal(t, 19, len(data))
	assert.Equal(t, `{
  "test": "one"
}`, string(data))
}

func TestAsset_CheckSum(t *testing.T) {
	asset := Asset{}
	checksum, err := asset.CheckSum()
	assert.NotNil(t, err)

	asset = Asset{Key: "asset/name.txt", Value: "this is content"}
	checksum, err = asset.CheckSum()
	assert.Nil(t, err)
	assert.Equal(t, "b7fcef7fe745f2a95560ff5f550e3b8f", checksum)

	asset = Asset{Key: "asset/name.txt", Attachment: "this is bad content"}
	checksum, err = asset.CheckSum()
	assert.NotNil(t, err)

	asset = Asset{Key: "asset/name.txt", Attachment: base64.StdEncoding.EncodeToString([]byte("this is bad content"))}
	checksum, err = asset.CheckSum()
	assert.Nil(t, err)
	assert.Equal(t, "04c9d416fc81a9dcb5460c560b532634", checksum)
}

func TestFindAllFiles(t *testing.T) {
	kittest.Setup()
	kittest.GenerateProject()
	defer kittest.Cleanup()
	files, err := findAllFiles(kittest.ProjectFiles[0])
	assert.Equal(t, "Path is not a directory", err.Error())
	files, err = findAllFiles(kittest.FixtureProjectPath)
	assert.Nil(t, err)
	assert.Equal(t, len(kittest.ProjectFiles), len(files))
}

func TestLoadAssetsFromDirectory(t *testing.T) {
	kittest.Setup()
	kittest.GenerateProject()
	defer kittest.Cleanup()

	assets, err := loadAssetsFromDirectory(kittest.ProjectFiles[0], "", func(path string) bool { return false })
	assert.Equal(t, "Path is not a directory", err.Error())
	assets, err = loadAssetsFromDirectory(kittest.FixtureProjectPath, "", func(path string) bool {
		return path != filepath.Join("assets", "application.js")
	})
	assert.Nil(t, err)
	assert.Equal(t, []Asset{{
		Key:   "assets/application.js",
		Value: "this is js content",
	}}, assets)

	kittest.Setup()
	kittest.GenerateProject()
	defer kittest.Cleanup()
	assets, err = loadAssetsFromDirectory(kittest.FixtureProjectPath, "assets", func(path string) bool { return false })
	assert.Nil(t, err)
	assert.Equal(t, 2, len(assets))
}

func TestLoadAsset(t *testing.T) {
	kittest.Setup()
	kittest.GenerateProject()
	defer kittest.Cleanup()

	asset, err := loadAsset(kittest.FixtureProjectPath, kittest.ProjectFiles[0])
	assert.Equal(t, filepath.ToSlash(kittest.ProjectFiles[0]), asset.Key)
	assert.Equal(t, true, asset.IsValid())
	assert.Equal(t, "this is js content", asset.Value)
	assert.Nil(t, err)

	asset, err = loadAsset(kittest.FixtureProjectPath, "nope.txt")
	assert.NotNil(t, err)

	asset, err = loadAsset(kittest.FixtureProjectPath, "templates")
	assert.NotNil(t, err)
	assert.Equal(t, ErrAssetIsDir, err)

	asset, err = loadAsset(kittest.FixtureProjectPath, "assets/pixel.png")
	assert.Nil(t, err)
	assert.True(t, len(asset.Attachment) > 0)
	assert.True(t, asset.IsValid())
}
<|endoftext|>


<commit_before>package service

import (
	"encoding/json"
	"errors"
	"fmt"
	"io/ioutil"
	"log"

	"github.com/mchmarny/go-cmd"
)

// CFClient object
type CFClient struct {
	config *ServiceConfig
}

// NewCFClient creates a new isntance of CFClient
func NewCFClient(c *ServiceConfig) *CFClient {
	return &CFClient{
		config: c,
	}
}

func (c *CFClient) initialize() (*cmd.Command, error) {
	log.Println("initializing...")

	// yep, this is a royal hack, should get this from the env somehow
	pushID := genRandomString(8)
	appDir, err := ioutil.TempDir(c.config.CFEnv.TempDir, pushID)
	if err != nil {
		log.Fatalf("err creating a temp dir: %v", err)
		return nil, err
	}

	// api
	cf := cmd.New("cf")

	// TODO: remove the skip API validation part once real cert deployed
	cf.WithArgs("api", c.config.APIEndpoint, "--skip-ssl-validation").
		WithEnv("CF_HOME", appDir).Exec()
	if cf.Err != nil {
		log.Fatalf("err cmd: %v", cf)
		return cf, cf.Err
	}

	// auth
	cf.WithArgs("auth", c.config.APIUser, c.config.APIPassword).Exec()
	if cf.Err != nil {
		log.Fatalf("err cmd: %v", cf)
		return cf, cf.Err
	}

	return cf, nil
}

func (c *CFClient) provision(ctx *CFServiceContext) error {
	log.Printf("provisioning service: %v", ctx)

	// initialize
	cf, err := c.initialize()
	if err != nil {
		log.Fatalf("err initializing command: %v", err)
		return err
	}

	// target
	cf.WithArgs("target", "-o", ctx.OrgName, "-s", ctx.SpaceName).Exec()
	if cf.Err != nil {
		log.Fatalf("err cmd: %v", cf)
		return cf.Err
	}

	// push
	cf.WithArgs("push", ctx.ServiceName, "-p", c.config.AppSource, "--no-start").Exec()
	if cf.Err != nil {
		log.Printf("err cmd: %v", cf)
		c.deprovision(ctx)
		return cf.Err
	}

	// TODO: Add cleanup of dependencies
	for i, dep := range c.config.Dependencies {
		depName := dep.Name + "-" + ctx.ServiceName
		cf.WithArgs("create-service", dep.Name, dep.Plan, depName).Exec()
		if cf.Err != nil {
			log.Printf("err on dependency[%d]: %s - %v", i, depName, cf)
			return cf.Err
		}

		// bind
		cf.WithArgs("bind-service", ctx.ServiceName, depName).Exec()
		if cf.Err != nil {
			log.Printf("err on bind[%d]: %s > %s - %v", i, ctx.ServiceName, depName, cf)
			return cf.Err
		}

		//TODO: check if we need to restage the app after binding
	}

	// start
	cf.WithArgs("start", ctx.ServiceName).Exec()
	if cf.Err != nil {
		log.Printf("err cmd: %v", cf)
		c.deprovision(ctx)
		return cf.Err
	}

	return nil
}

func (c *CFClient) deprovision(ctx *CFServiceContext) error {
	log.Printf("deprovision service: %v", ctx)

	// initialize
	cf, err := c.initialize()
	if err != nil {
		log.Fatalf("err initializing command: %v", err)
		return err
	}

	// target
	cf.WithArgs("target", "-o", ctx.OrgName, "-s", ctx.SpaceName).Exec()
	if cf.Err != nil {
		log.Fatalf("err cmd: %v", cf)
		return cf.Err
	}

	// delete
	cf.WithArgs("delete", ctx.ServiceName, "-f").Exec()
	if cf.Err != nil {
		log.Printf("err cmd: %v", cf)
		return cf.Err
	}

	// TODO: Does the service have to unbined first
	//       or deleting app will take care of it
	for i, dep := range c.config.Dependencies {
		depName := dep.Name + "-" + ctx.ServiceName
		cf.WithArgs("delete-service", dep.Name, "-f").Exec()
		if cf.Err != nil {
			log.Printf("err on dependency delete[%d]: %s - %v", i, depName, cf)
		}
	}

	return nil
}

func (c *CFClient) runQuery(query string) (string, error) {
	log.Printf("running query: %s", query)
	cf, err := c.initialize()
	if err != nil {
		log.Fatalf("err initializing command: %v", err)
		return "", err
	}
	cf.WithArgs("curl", query).Exec()
	return cf.Out, cf.Err
}

func (c *CFClient) getContext(instanceID string) (*CFServiceContext, error) {
	log.Printf("getting service context for: %s", instanceID)

	t := &CFServiceContext{}
	t.InstanceID = instanceID

	srv, err := c.getService(instanceID)
	if err != nil {
		log.Printf("error getting service: %v", err)
		return nil, err
	}
	t.ServiceName = srv.Name
	t.ServiceURI = srv.URI

	space, err := c.getSpace(srv.SpaceGUID)
	if err != nil {
		log.Printf("error getting space: %v", err)
		return nil, err
	}
	t.SpaceName = space.Name

	org, err := c.getOrg(space.OrgGUID)
	if err != nil {
		log.Printf("error getting org: %v", err)
		return nil, err
	}
	t.OrgName = org.Name

	return t, nil

}

func (c *CFClient) getService(instanceID string) (*cfApp, error) {
	log.Printf("getting service info for: %s", instanceID)
	query := fmt.Sprintf("/v2/service_instances/%s", instanceID)
	resp, err := c.runQuery(query)
	if err != nil {
		return nil, errors.New("query error")
	}

	// cf-client.go:150: running query: /v2/service_instances/26576e51...
	// cf-client.go:26: initializing...
	// {
	//    "code": 60004,
	//    "description": "The service instance could not be found: 26576e51-8a47-46e3-bd6e-5908287e9935",
	//    "error_code": "CF-ServiceInstanceNotFound"
	// }
	//
	// TODO: map results to a CFError struct to see if an error was returned.
	// FIXME: looks like service instance object doesn't exist when "cf create-service" called
	// TODO: perhaps a background worker to rename service instances later?

	t := &cfAppResource{}
	log.Println(string(resp))
	err2 := json.Unmarshal([]byte(resp), &t)
	if err2 != nil {
		log.Fatalf("err unmarshaling: %v - %v", err2, resp)
		return nil, errors.New("invalid JSON")
	}
	log.Printf("service output: %v", t)
	t.Entity.GUID = t.Meta.GUID
	return &t.Entity, nil
}

func (c *CFClient) getOrg(orgID string) (*cfApp, error) {
	log.Printf("getting org info for: %s", orgID)
	query := fmt.Sprintf("/v2/organizations/%s", orgID)
	resp, err := c.runQuery(query)
	if err != nil {
		return nil, errors.New("query error")
	}
	log.Println(string(resp))
	t := &cfAppResource{}
	err2 := json.Unmarshal([]byte(resp), &t)
	if err2 != nil {
		log.Fatalf("err unmarshaling: %v - %v", err2, resp)
		return nil, errors.New("invalid JSON")
	}
	log.Printf("org output: %v", t)
	t.Entity.GUID = t.Meta.GUID
	return &t.Entity, nil
}

func (c *CFClient) getSpace(spaceID string) (*cfSpace, error) {
	log.Printf("getting space info for: %s", spaceID)
	query := fmt.Sprintf("/v2/spaces/%s", spaceID)
	resp, err := c.runQuery(query)
	if err != nil {
		return nil, errors.New("query error")
	}
	log.Println(string(resp))
	t := &cfSpaceResource{}
	err2 := json.Unmarshal([]byte(resp), &t)
	if err2 != nil {
		log.Fatalf("err unmarshaling: %v - %v", err2, resp)
		return nil, errors.New("invalid JSON")
	}
	log.Printf("space output: %v", t)
	t.Entity.GUID = t.Meta.GUID
	return &t.Entity, nil
}

func (c *CFClient) getApp(appID string) (*cfApp, error) {
	log.Printf("getting app info for: %s", appID)
	query := fmt.Sprintf("/v2/apps/%s", appID)
	resp, err := c.runQuery(query)
	if err != nil {
		return nil, errors.New("query error")
	}
	log.Println(string(resp))
	t := &cfAppResource{}
	err2 := json.Unmarshal([]byte(resp), &t)
	if err2 != nil {
		log.Fatalf("err unmarshaling: %v - %v", err2, resp)
		return nil, errors.New("invalid JSON")
	}
	log.Printf("app output: %v", t)
	t.Entity.GUID = t.Meta.GUID
	return &t.Entity, nil
}

func (c *CFClient) getBinding(bindingID string) (*CFBindingResponse, error) {
	log.Printf("getting service binding for: %s", bindingID)
	query := fmt.Sprintf("/v2/service_bindings/%s", bindingID)
	resp, err := c.runQuery(query)
	if err != nil {
		return nil, errors.New("query error")
	}
	log.Println(string(resp))
	t := &cfBindingResource{}
	err2 := json.Unmarshal([]byte(resp), &t)
	if err2 != nil {
		log.Fatalf("err unmarshaling: %v - %v", err2, resp)
		return nil, errors.New("invalid JSON")
	}
	log.Printf("service binding output: %v", t)
	t.Entity.GUID = t.Meta.GUID
	return &t.Entity, nil
}

func (c *CFClient) getApps() (*cfAppsResponse, error) {
	log.Println("getting apps...")
	query := "/v2/apps?results-per-page=100"
	resp, err := c.runQuery(query)
	if err != nil {
		return nil, errors.New("query error")
	}
	log.Println(string(resp))
	t := &cfAppsResponse{}
	err2 := json.Unmarshal([]byte(resp), &t)
	if err2 != nil {
		log.Fatalf("err unmarshaling: %v - %v", err2, resp)
		return nil, errors.New("invalid JSON")
	}
	log.Printf("apps output: %v", t)
	return t, nil
}

func (c *CFClient) getServices() (*cfAppsResponse, error) {
	log.Println("getting services...")
	query := "/v2/service_instances?results-per-page=100"
	resp, err := c.runQuery(query)
	if err != nil {
		return nil, errors.New("query error")
	}
	log.Println(string(resp))
	t := &cfAppsResponse{}
	err2 := json.Unmarshal([]byte(resp), &t)
	if err2 != nil {
		log.Fatalf("err unmarshaling: %v - %v", err2, resp)
		return nil, errors.New("invalid JSON")
	}
	log.Printf("services output: %v", t)
	return t, nil
}
<commit_msg>Rename method<commit_after>package service

import (
	"encoding/json"
	"errors"
	"fmt"
	"io/ioutil"
	"log"

	"github.com/mchmarny/go-cmd"
)

// CFClient object
type CFClient struct {
	config *ServiceConfig
}

// NewCFClient creates a new isntance of CFClient
func NewCFClient(c *ServiceConfig) *CFClient {
	return &CFClient{
		config: c,
	}
}

func (c *CFClient) initialize() (*cmd.Command, error) {
	log.Println("initializing...")

	// yep, this is a royal hack, should get this from the env somehow
	pushID := genRandomString(8)
	appDir, err := ioutil.TempDir(c.config.CFEnv.TempDir, pushID)
	if err != nil {
		log.Fatalf("err creating a temp dir: %v", err)
		return nil, err
	}

	// api
	cf := cmd.New("cf")

	// TODO: remove the skip API validation part once real cert deployed
	cf.WithArgs("api", c.config.APIEndpoint, "--skip-ssl-validation").
		WithEnv("CF_HOME", appDir).Exec()
	if cf.Err != nil {
		log.Fatalf("err cmd: %v", cf)
		return cf, cf.Err
	}

	// auth
	cf.WithArgs("auth", c.config.APIUser, c.config.APIPassword).Exec()
	if cf.Err != nil {
		log.Fatalf("err cmd: %v", cf)
		return cf, cf.Err
	}

	return cf, nil
}

func (c *CFClient) provision(ctx *CFServiceContext) error {
	log.Printf("provisioning service: %v", ctx)

	// initialize
	cf, err := c.initialize()
	if err != nil {
		log.Fatalf("err initializing command: %v", err)
		return err
	}

	// target
	cf.WithArgs("target", "-o", ctx.OrgName, "-s", ctx.SpaceName).Exec()
	if cf.Err != nil {
		log.Fatalf("err cmd: %v", cf)
		return cf.Err
	}

	// push
	cf.WithArgs("push", ctx.ServiceName, "-p", c.config.AppSource, "--no-start").Exec()
	if cf.Err != nil {
		log.Printf("err cmd: %v", cf)
		c.deprovision(ctx)
		return cf.Err
	}

	// TODO: Add cleanup of dependencies
	for i, dep := range c.config.Dependencies {
		depName := dep.Name + "-" + ctx.ServiceName
		cf.WithArgs("create-service", dep.Name, dep.Plan, depName).Exec()
		if cf.Err != nil {
			log.Printf("err on dependency[%d]: %s - %v", i, depName, cf)
			return cf.Err
		}

		// bind
		cf.WithArgs("bind-service", ctx.ServiceName, depName).Exec()
		if cf.Err != nil {
			log.Printf("err on bind[%d]: %s > %s - %v", i, ctx.ServiceName, depName, cf)
			return cf.Err
		}

		//TODO: check if we need to restage the app after binding
	}

	// start
	cf.WithArgs("start", ctx.ServiceName).Exec()
	if cf.Err != nil {
		log.Printf("err cmd: %v", cf)
		c.deprovision(ctx)
		return cf.Err
	}

	return nil
}

func (c *CFClient) deprovision(ctx *CFServiceContext) error {
	log.Printf("deprovision service: %v", ctx)

	// initialize
	cf, err := c.initialize()
	if err != nil {
		log.Fatalf("err initializing command: %v", err)
		return err
	}

	// target
	cf.WithArgs("target", "-o", ctx.OrgName, "-s", ctx.SpaceName).Exec()
	if cf.Err != nil {
		log.Fatalf("err cmd: %v", cf)
		return cf.Err
	}

	// delete
	cf.WithArgs("delete", ctx.ServiceName, "-f").Exec()
	if cf.Err != nil {
		log.Printf("err cmd: %v", cf)
		return cf.Err
	}

	// TODO: Does the service have to unbined first
	//       or deleting app will take care of it
	for i, dep := range c.config.Dependencies {
		depName := dep.Name + "-" + ctx.ServiceName
		cf.WithArgs("delete-service", dep.Name, "-f").Exec()
		if cf.Err != nil {
			log.Printf("err on dependency delete[%d]: %s - %v", i, depName, cf)
		}
	}

	return nil
}

func (c *CFClient) queryAPI(query string) (string, error) {
	log.Printf("running query: %s", query)
	cf, err := c.initialize()
	if err != nil {
		log.Fatalf("err initializing command: %v", err)
		return "", err
	}
	cf.WithArgs("curl", query).Exec()
	return cf.Out, cf.Err
}

func (c *CFClient) getContext(instanceID string) (*CFServiceContext, error) {
	log.Printf("getting service context for: %s", instanceID)

	t := &CFServiceContext{}
	t.InstanceID = instanceID

	srv, err := c.getService(instanceID)
	if err != nil {
		log.Printf("error getting service: %v", err)
		return nil, err
	}
	t.ServiceName = srv.Name
	t.ServiceURI = srv.URI

	space, err := c.getSpace(srv.SpaceGUID)
	if err != nil {
		log.Printf("error getting space: %v", err)
		return nil, err
	}
	t.SpaceName = space.Name

	org, err := c.getOrg(space.OrgGUID)
	if err != nil {
		log.Printf("error getting org: %v", err)
		return nil, err
	}
	t.OrgName = org.Name

	return t, nil

}

func (c *CFClient) getService(instanceID string) (*cfApp, error) {
	log.Printf("getting service info for: %s", instanceID)
	query := fmt.Sprintf("/v2/service_instances/%s", instanceID)
	resp, err := c.queryAPI(query)
	if err != nil {
		return nil, errors.New("query error")
	}

	// cf-client.go:150: running query: /v2/service_instances/26576e51...
	// cf-client.go:26: initializing...
	// {
	//    "code": 60004,
	//    "description": "The service instance could not be found: 26576e51-8a47-46e3-bd6e-5908287e9935",
	//    "error_code": "CF-ServiceInstanceNotFound"
	// }
	//
	// TODO: map results to a CFError struct to see if an error was returned.
	// FIXME: looks like service instance object doesn't exist when "cf create-service" called
	// TODO: perhaps a background worker to rename service instances later?

	t := &cfAppResource{}
	log.Println(string(resp))
	err2 := json.Unmarshal([]byte(resp), &t)
	if err2 != nil {
		log.Fatalf("err unmarshaling: %v - %v", err2, resp)
		return nil, errors.New("invalid JSON")
	}
	log.Printf("service output: %v", t)
	t.Entity.GUID = t.Meta.GUID
	return &t.Entity, nil
}

func (c *CFClient) getOrg(orgID string) (*cfApp, error) {
	log.Printf("getting org info for: %s", orgID)
	query := fmt.Sprintf("/v2/organizations/%s", orgID)
	resp, err := c.queryAPI(query)
	if err != nil {
		return nil, errors.New("query error")
	}
	log.Println(string(resp))
	t := &cfAppResource{}
	err2 := json.Unmarshal([]byte(resp), &t)
	if err2 != nil {
		log.Fatalf("err unmarshaling: %v - %v", err2, resp)
		return nil, errors.New("invalid JSON")
	}
	log.Printf("org output: %v", t)
	t.Entity.GUID = t.Meta.GUID
	return &t.Entity, nil
}

func (c *CFClient) getSpace(spaceID string) (*cfSpace, error) {
	log.Printf("getting space info for: %s", spaceID)
	query := fmt.Sprintf("/v2/spaces/%s", spaceID)
	resp, err := c.queryAPI(query)
	if err != nil {
		return nil, errors.New("query error")
	}
	log.Println(string(resp))
	t := &cfSpaceResource{}
	err2 := json.Unmarshal([]byte(resp), &t)
	if err2 != nil {
		log.Fatalf("err unmarshaling: %v - %v", err2, resp)
		return nil, errors.New("invalid JSON")
	}
	log.Printf("space output: %v", t)
	t.Entity.GUID = t.Meta.GUID
	return &t.Entity, nil
}

func (c *CFClient) getApp(appID string) (*cfApp, error) {
	log.Printf("getting app info for: %s", appID)
	query := fmt.Sprintf("/v2/apps/%s", appID)
	resp, err := c.queryAPI(query)
	if err != nil {
		return nil, errors.New("query error")
	}
	log.Println(string(resp))
	t := &cfAppResource{}
	err2 := json.Unmarshal([]byte(resp), &t)
	if err2 != nil {
		log.Fatalf("err unmarshaling: %v - %v", err2, resp)
		return nil, errors.New("invalid JSON")
	}
	log.Printf("app output: %v", t)
	t.Entity.GUID = t.Meta.GUID
	return &t.Entity, nil
}

func (c *CFClient) getBinding(bindingID string) (*CFBindingResponse, error) {
	log.Printf("getting service binding for: %s", bindingID)
	query := fmt.Sprintf("/v2/service_bindings/%s", bindingID)
	resp, err := c.queryAPI(query)
	if err != nil {
		return nil, errors.New("query error")
	}
	log.Println(string(resp))
	t := &cfBindingResource{}
	err2 := json.Unmarshal([]byte(resp), &t)
	if err2 != nil {
		log.Fatalf("err unmarshaling: %v - %v", err2, resp)
		return nil, errors.New("invalid JSON")
	}
	log.Printf("service binding output: %v", t)
	t.Entity.GUID = t.Meta.GUID
	return &t.Entity, nil
}

func (c *CFClient) getApps() (*cfAppsResponse, error) {
	log.Println("getting apps...")
	query := "/v2/apps?results-per-page=100"
	resp, err := c.queryAPI(query)
	if err != nil {
		return nil, errors.New("query error")
	}
	log.Println(string(resp))
	t := &cfAppsResponse{}
	err2 := json.Unmarshal([]byte(resp), &t)
	if err2 != nil {
		log.Fatalf("err unmarshaling: %v - %v", err2, resp)
		return nil, errors.New("invalid JSON")
	}
	log.Printf("apps output: %v", t)
	return t, nil
}

func (c *CFClient) getServices() (*cfAppsResponse, error) {
	log.Println("getting services...")
	query := "/v2/service_instances?results-per-page=100"
	resp, err := c.queryAPI(query)
	if err != nil {
		return nil, errors.New("query error")
	}
	log.Println(string(resp))
	t := &cfAppsResponse{}
	err2 := json.Unmarshal([]byte(resp), &t)
	if err2 != nil {
		log.Fatalf("err unmarshaling: %v - %v", err2, resp)
		return nil, errors.New("invalid JSON")
	}
	log.Printf("services output: %v", t)
	return t, nil
}
<|endoftext|>


<commit_before>package service

import (
	"github.com/Comcast/webpa-common/logging"
	"github.com/strava/go.serversets"
	"sync/atomic"
)

// Watch is the subset of methods required by this package that *serversets.Watch implements
type Watch interface {
	IsClosed() bool
	Event() <-chan struct{}
	Endpoints() []string
}

var _ Watch = (*serversets.Watch)(nil)

// Subscribe consumes watch events and invokes a subscription function with the endpoints.
// The returned function can be called to cancel the subscription.  This returned cancellation
// function is idempotent.
func Subscribe(logger logging.Logger, watch Watch, subscription func([]string)) func() {
	if logger == nil {
		logger = logging.DefaultLogger()
	}

	logger.Debug("Creating subscription for %v", watch)
	cancel := make(chan struct{})
	go func() {
		defer func() {
			if r := recover(); r != nil {
				logger.Error("Subscription ending due to panic: %s", r)
			}
		}()

		for {
			select {
			case <-cancel:
				logger.Info("Subscription cancel event received")
				return
			case <-watch.Event():
				logger.Debug("Watch event received")
				if watch.IsClosed() {
					logger.Info("Watch closed.  Subscription ending.")
					return
				}

				endpoints := watch.Endpoints()
				logger.Info("Updated endpoints: %v", endpoints)
				subscription(endpoints)
			}
		}
	}()

	return func() {
		defer func() {
			recover()
		}()

		logger.Debug("Subscription cancellation function called")
		close(cancel)
	}
}

// AccessorSubscription represents an Accessor whose state changes as the result
// of events via a subscription.
type AccessorSubscription interface {
	Accessor

	// Cancel removes this subscription from the underlying infrastructure.  No further
	// updates will occur, but this subscription's state will still be usable.
	// This method is idempotent.
	Cancel()
}

// accessorSubscription is the internal implementation of AccessorSubscription
type accessorSubscription struct {
	factory    AccessorFactory
	value      atomic.Value
	cancelFunc func()
}

func (a *accessorSubscription) Cancel() {
	a.cancelFunc()
}

func (a *accessorSubscription) Get(key []byte) (string, error) {
	return a.value.Load().(Accessor).Get(key)
}

func (a *accessorSubscription) update(endpoints []string) {
	a.value.Store(a.factory.New(endpoints))
}

// NewAccessorSubscription subscribes to a watch and updates an atomic Accessor in response
// to updated service endpoints.  The returned object is fully initialized and can be used
// to access endpoints immediately.  In addition, the subscription can be cancelled at any time.
// If the underlying service discovery infrastructure is shutdown, the subscription will no
// longer receive updates but can continue to be used in its stale state.
func NewAccessorSubscription(watch Watch, factory AccessorFactory, o *Options) AccessorSubscription {
	if factory == nil {
		factory = NewAccessorFactory(o)
	}

	subscription := &accessorSubscription{
		factory: factory,
	}

	// use update to initialze the atomic value
	subscription.update(watch.Endpoints())
	subscription.cancelFunc = Subscribe(o.logger(), watch, subscription.update)
	return subscription
}
<commit_msg>Clarifying comments<commit_after>package service

import (
	"github.com/Comcast/webpa-common/logging"
	"github.com/strava/go.serversets"
	"sync/atomic"
)

// Watch is the subset of methods required by this package that *serversets.Watch implements
type Watch interface {
	IsClosed() bool
	Event() <-chan struct{}
	Endpoints() []string
}

var _ Watch = (*serversets.Watch)(nil)

// Subscribe consumes watch events and invokes a subscription function with the endpoints.
// The returned function can be called to cancel the subscription.  This returned cancellation
// function is idempotent.
func Subscribe(logger logging.Logger, watch Watch, subscription func([]string)) func() {
	if logger == nil {
		logger = logging.DefaultLogger()
	}

	logger.Debug("Creating subscription for %#v", watch)
	cancel := make(chan struct{})
	go func() {
		defer func() {
			if r := recover(); r != nil {
				logger.Error("Subscription ending due to panic: %s", r)
			}
		}()

		for {
			select {
			case <-cancel:
				logger.Info("Subscription cancel event received")
				return
			case <-watch.Event():
				logger.Debug("Watch event received")
				if watch.IsClosed() {
					logger.Info("Watch closed.  Subscription ending.")
					return
				}

				endpoints := watch.Endpoints()
				logger.Info("Updated endpoints: %v", endpoints)
				subscription(endpoints)
			}
		}
	}()

	return func() {
		defer func() {
			recover()
		}()

		logger.Debug("Subscription cancellation function called")
		close(cancel)
	}
}

// AccessorSubscription represents an Accessor whose state changes as the result
// of events via a subscription.
type AccessorSubscription interface {
	Accessor

	// Cancel removes this subscription from the underlying infrastructure.  No further
	// updates will occur, but this subscription's state will still be usable.
	// This method is idempotent.
	Cancel()
}

// accessorSubscription is the internal implementation of AccessorSubscription
type accessorSubscription struct {
	factory    AccessorFactory
	value      atomic.Value
	cancelFunc func()
}

func (a *accessorSubscription) Cancel() {
	a.cancelFunc()
}

func (a *accessorSubscription) Get(key []byte) (string, error) {
	return a.value.Load().(Accessor).Get(key)
}

func (a *accessorSubscription) update(endpoints []string) {
	a.value.Store(a.factory.New(endpoints))
}

// NewAccessorSubscription subscribes to a watch and updates an atomic Accessor in response
// to updated service endpoints.  The returned object is fully initialized and can be used
// to access endpoints immediately.  In addition, the subscription can be cancelled at any time.
// If the underlying service discovery infrastructure is shutdown, the subscription will no
// longer receive updates but can continue to be used in its stale state.
func NewAccessorSubscription(watch Watch, factory AccessorFactory, o *Options) AccessorSubscription {
	if factory == nil {
		factory = NewAccessorFactory(o)
	}

	subscription := &accessorSubscription{
		factory: factory,
	}

	// use update to initialze the atomic value
	subscription.update(watch.Endpoints())
	subscription.cancelFunc = Subscribe(o.logger(), watch, subscription.update)
	return subscription
}
<|endoftext|>


<commit_before>// Package sessions contains middleware for easy session management in Martini.
//
//  package main
//
//  import (
//    "github.com/codegangsta/martini"
//    "github.com/codegangsta/martini-contrib/sessions"
//  )
//
//  func main() {
// 	  m := martini.Classic()
//
// 	  store := sessions.NewCookieStore([]byte("secret123"))
// 	  m.Use(sessions.Sessions("my_session", store))
//
// 	  m.Get("/", func(session sessions.Session) string {
// 		  session.Set("hello", "world")
// 	  })
//  }
package sessions

import (
	"github.com/codegangsta/martini"
	"github.com/gorilla/context"
	"github.com/gorilla/sessions"
	"log"
	"net/http"
)

const (
	errorFormat = "[sessions] ERROR! %s\n"
)

// Store is an interface for custom session stores.
type Store interface {
	sessions.Store
}

// NewCookieStore returns a new CookieStore.
//
// Keys are defined in pairs to allow key rotation, but the common case is to set a single
// authentication key and optionally an encryption key.
//
// The first key in a pair is used for authentication and the second for encryption. The
// encryption key can be set to nil or omitted in the last pair, but the authentication key
// is required in all pairs.
//
// It is recommended to use an authentication key with 32 or 64 bytes. The encryption key,
// if set, must be either 16, 24, or 32 bytes to select AES-128, AES-192, or AES-256 modes.
func NewCookieStore(keyPairs ...[]byte) Store {
	return sessions.NewCookieStore(keyPairs...)
}

// Session stores the values and optional configuration for a session.
type Session interface {
	// Get returns the session value associated to the given key.
	Get(key interface{}) interface{}
	// Set sets the session value associated to the given key.
	Set(key interface{}, val interface{})
	// AddFlash adds a flash message to the session.
	// A single variadic argument is accepted, and it is optional: it defines the flash key.
	// If not defined "_flash" is used by default.
	AddFlash(value interface{}, vars ...string)
	// Flashes returns a slice of flash messages from the session.
	// A single variadic argument is accepted, and it is optional: it defines the flash key.
	// If not defined "_flash" is used by default.
	Flashes(vars ...string) []interface{}
}

// Sessions is a Middleware that maps a session.Session service into the Martini handler chain.
// Sessions can use a number of storage solutions with the given store.
func Sessions(name string, store Store) martini.Handler {
	return func(res http.ResponseWriter, r *http.Request, c martini.Context, l *log.Logger) {
		s, err := store.Get(r, name)
		// clear the context right away, we don't need to use
		// gorilla context and we don't want memory leaks
		context.Clear(r)

		check(err, l)

		// Map to the Session interface
		c.MapTo(&session{s}, (*Session)(nil))

		c.Next()

		// save session after other handlers are run
		check(s.Save(r, res), l)
	}
}

type session struct {
	*sessions.Session
}

func (s *session) Get(key interface{}) interface{} {
	return s.Session.Values[key]
}

func (s *session) Set(key interface{}, val interface{}) {
	s.Session.Values[key] = val
}

func check(err error, l *log.Logger) {
	if err != nil {
		l.Printf(errorFormat, err)
	}
}
<commit_msg>Now using before hookto save sessions<commit_after>// Package sessions contains middleware for easy session management in Martini.
//
//  package main
//
//  import (
//    "github.com/codegangsta/martini"
//    "github.com/codegangsta/martini-contrib/sessions"
//  )
//
//  func main() {
// 	  m := martini.Classic()
//
// 	  store := sessions.NewCookieStore([]byte("secret123"))
// 	  m.Use(sessions.Sessions("my_session", store))
//
// 	  m.Get("/", func(session sessions.Session) string {
// 		  session.Set("hello", "world")
// 	  })
//  }
package sessions

import (
	"github.com/codegangsta/martini"
	"github.com/gorilla/context"
	"github.com/gorilla/sessions"
	"log"
	"net/http"
)

const (
	errorFormat = "[sessions] ERROR! %s\n"
)

// Store is an interface for custom session stores.
type Store interface {
	sessions.Store
}

// NewCookieStore returns a new CookieStore.
//
// Keys are defined in pairs to allow key rotation, but the common case is to set a single
// authentication key and optionally an encryption key.
//
// The first key in a pair is used for authentication and the second for encryption. The
// encryption key can be set to nil or omitted in the last pair, but the authentication key
// is required in all pairs.
//
// It is recommended to use an authentication key with 32 or 64 bytes. The encryption key,
// if set, must be either 16, 24, or 32 bytes to select AES-128, AES-192, or AES-256 modes.
func NewCookieStore(keyPairs ...[]byte) Store {
	return sessions.NewCookieStore(keyPairs...)
}

// Session stores the values and optional configuration for a session.
type Session interface {
	// Get returns the session value associated to the given key.
	Get(key interface{}) interface{}
	// Set sets the session value associated to the given key.
	Set(key interface{}, val interface{})
	// AddFlash adds a flash message to the session.
	// A single variadic argument is accepted, and it is optional: it defines the flash key.
	// If not defined "_flash" is used by default.
	AddFlash(value interface{}, vars ...string)
	// Flashes returns a slice of flash messages from the session.
	// A single variadic argument is accepted, and it is optional: it defines the flash key.
	// If not defined "_flash" is used by default.
	Flashes(vars ...string) []interface{}
}

// Sessions is a Middleware that maps a session.Session service into the Martini handler chain.
// Sessions can use a number of storage solutions with the given store.
func Sessions(name string, store Store) martini.Handler {
	return func(res http.ResponseWriter, r *http.Request, c martini.Context, l *log.Logger) {
		s, err := store.Get(r, name)
		// clear the context, we don't need to use
		// gorilla context and we don't want memory leaks
		defer context.Clear(r)

		check(err, l)

		// Map to the Session interface
		c.MapTo(&session{s}, (*Session)(nil))

		// Use before hook to save out the session
		rw := res.(martini.ResponseWriter)
		rw.Before(func(martini.ResponseWriter) {
			check(s.Save(r, res), l)
		})
	}
}

type session struct {
	*sessions.Session
}

func (s *session) Get(key interface{}) interface{} {
	return s.Session.Values[key]
}

func (s *session) Set(key interface{}, val interface{}) {
	s.Session.Values[key] = val
}

func check(err error, l *log.Logger) {
	if err != nil {
		l.Printf(errorFormat, err)
	}
}
<|endoftext|>


<commit_before>package sessions

import (
	"github.com/yang-f/beauty/db"
	"github.com/yang-f/beauty/models"
	"github.com/yang-f/beauty/utils/token"
	"net/http"
)

func CurrentUser(r *http.Request) models.User {
	cookie, err := r.Cookie("token")
	if err != nil || cookie.Value == "" {
		return models.User{}
	}
	user_id, err := token.Valid(cookie.Value)
	if err != nil {
		return models.User{}
	}

	rows, res, err := db.Query("select * from user where user_id= '%d'", user_id)

	if err != nil {
		return models.User{}
	}

	if len(rows) == 0 {
		return models.User{}
	}
	row := rows[0]
	user := models.User{
		User_id:   row.Int(res.Map("user_id")),
		User_name: row.Str(res.Map("user_name")),
		User_type: row.Str(res.Map("user_type")),
		Add_time:  row.Str(res.Map("add_time"))}

	return user
}
<commit_msg>error handler<commit_after>package sessions

import (
	"github.com/yang-f/beauty/db"
	"github.com/yang-f/beauty/models"
	"github.com/yang-f/beauty/utils/token"
	"net/http"
	"strings"
)

func CurrentUser(r *http.Request) models.User {
	cookie, err := r.Cookie("token")
	if err != nil || cookie.Value == "" {
		return models.User{}
	}
	key, err := token.Valid(cookie.Value)
	if err != nil {
		return models.User{}
	}
	if !strings.Contains(key, "|") {
		return models.User{}
	}
	keys := strings.Split(key, "|")
	rows, res, err := db.QueryNonLogging("select * from user where user_id = '%v' and user_pass = '%v'", keys[0], keys[1])

	if err != nil {
		return models.User{}
	}

	if len(rows) == 0 {
		return models.User{}
	}
	row := rows[0]
	user := models.User{
		User_id:   row.Int(res.Map("user_id")),
		User_name: row.Str(res.Map("user_name")),
		User_type: row.Str(res.Map("user_type")),
		Add_time:  row.Str(res.Map("add_time"))}

	return user
}
<|endoftext|>


<commit_before>/*
Copyright 2015 The ContainerOps Authors All rights reserved.

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 setting

import (
	"encoding/json"
	"fmt"
	"io/ioutil"
	"net/http"
	"os"
	"time"
)

type NotificationsCtx struct {
	Name      string         `json:"name,omitempty"`
	Endpoints []EndpointDesc `json:"endpoints,omitempty"`
}

type EndpointDesc struct {
	Name      string        `json:"name"`
	URL       string        `json:"url"`
	Headers   http.Header   `json:"headers"`
	Timeout   time.Duration `json:"timeout"`
	Threshold int           `json:"threshold"`
	Backoff   time.Duration `json:"backoff"`
	EventDB   string        `json:"eventdb"`
	Disabled  bool          `json:"disabled"`
}

type AuthorDesc map[string]interface{}

type AuthorsCtx map[string]AuthorDesc

type Desc struct {
	Notifications NotificationsCtx `json:"notifications,omitempty"`
	Authors       AuthorsCtx       `json:"auth,omitempty"`
}

var JSONConfCtx Desc

func GetConfFromJSON(path string) error {
	fp, err := os.Open(path)
	if err != nil {
		return fmt.Errorf("err: %v", err.Error())
	}

	buf, err := ioutil.ReadAll(fp)
	if err != nil {
		return fmt.Errorf("err: %v", err.Error())
	}

	if err := json.Unmarshal(buf, &JSONConfCtx); err != nil {
		return fmt.Errorf("err: %v", err.Error())
	}

	return nil
}

func (auth AuthorsCtx) Name() (name string) {
	name = ""
	for key, _ := range auth {
		name = key
		break
	}
	return
}
<commit_msg>Delete the parsejson file.<commit_after><|endoftext|>


<commit_before>package circle

func Circles(grid [][]int) int {
	rows := len(grid)
	var ret int
	visited := make([]bool, rows)
	for i := 0; i < rows; i++ {
		if !visited[i] {
			dfs(grid, &visited, i, rows)
			ret++
		}
	}
	return ret
}

func dfs(grid [][]int, visited *[]bool, i, n int) {
	for j := 0; j < n; j++ {
		// unvisited person j in the current friend circle
		if !(*visited)[j] && grid[i][j] == 1 {
			(*visited)[j] = true
			dfs(grid, visited, j, n)
		}
	}
}

func Circles2(grid [][]int) int {
	n := len(grid)
	ret := n
	ids := make([]int, n)
	// quick-find,
	for i := range ids {
		ids[i] = i // each person i is his/her own circle
	}
	union := func(p, q int) {
		// union person p and q
		// change all id in ids equal to ids[p] to ids[q]
		pid := ids[p]
		for i := range ids {
			if ids[i] == pid {
				ids[i] = ids[q]
			}
		}
	}
	for i := 0; i < n; i++ {
		for j := i + 1; j < n; j++ {
			if grid[i][j] == 1 {
				if ids[i] != ids[j] {
					ret--
					union(i, j)
				}
			}
		}
	}
	return ret
}

func Circles3(grid [][]int) int {
	n := len(grid)
	ret := n
	// quick-union
	ids := make([]int, n) // ids[i] represents the parent of i
	for i := range ids {
		ids[i] = i
	}
	root := func(i int) int {
		for i != ids[i] {
			i = ids[i]
		}
		return i
	}
	union := func(p, q int) {
		i, j := root(p), root(q)
		ids[i] = j
	}
	for i := 0; i < n; i++ {
		for j := 1; j < n; j++ {
			if grid[i][j] == 1 {
				if root(i) != root(j) {
					ret--
					union(i, j)
				}
			}
		}
	}
	return ret
}

func Circles4(grid [][]int) int {
	n := len(grid)
	ret := n
	// quick-union with weighted
	ids := make([]int, n) // ids[i] represents the parent of i
	sz := make([]int, n)  // sz[i] reprents the number of elements of root i
	for i := range ids {
		ids[i] = i
		sz[i] = 1
	}
	root := func(i int) int {
		for i != ids[i] {
			i = ids[i]
		}
		return i
	}
	union := func(p, q int) {
		i, j := root(p), root(q)
		// merge smaller tree into larger tree
		if sz[i] < sz[j] {
			ids[i] = j
			sz[j] += sz[i]
		} else {
			ids[j] = i
			sz[i] += sz[j]
		}
	}
	for i := 0; i < n; i++ {
		for j := 1; j < n; j++ {
			if grid[i][j] == 1 {
				if root(i) != root(j) {
					ret--
					union(i, j)
				}
			}
		}
	}
	return ret
}

func Circles5(grid [][]int) int {
	n := len(grid)
	ret := n
	// weighted quick-union with path compression
	ids := make([]int, n) // ids[i] represents the parent of i
	sz := make([]int, n)
	for i := range ids {
		ids[i] = i
		sz[i] = 1
	}
	root := func(i int) int {
		for i != ids[i] {
			ids[i] = ids[ids[i]] // make every other node in path point to its grandparent
			i = ids[i]
		}
		return i
	}
	union := func(p, q int) {
		i, j := root(p), root(q)
		if sz[i] < sz[j] {
			ids[i] = j
			sz[j] += sz[i]
		} else {
			ids[j] = i
			sz[i] += sz[j]
		}
	}
	for i := 0; i < n; i++ {
		for j := 1; j < n; j++ {
			if grid[i][j] == 1 {
				if root(i) != root(j) {
					ret--
					union(i, j)
				}
			}
		}
	}
	return ret
}
<commit_msg>optimized version of weighted quick-union with path compression<commit_after>package circle

func Circles(grid [][]int) int {
	rows := len(grid)
	var ret int
	visited := make([]bool, rows)
	for i := 0; i < rows; i++ {
		if !visited[i] {
			dfs(grid, &visited, i, rows)
			ret++
		}
	}
	return ret
}

func dfs(grid [][]int, visited *[]bool, i, n int) {
	for j := 0; j < n; j++ {
		// unvisited person j in the current friend circle
		if !(*visited)[j] && grid[i][j] == 1 {
			(*visited)[j] = true
			dfs(grid, visited, j, n)
		}
	}
}

func Circles2(grid [][]int) int {
	n := len(grid)
	ret := n
	ids := make([]int, n)
	// quick-find,
	for i := range ids {
		ids[i] = i // each person i is his/her own circle
	}
	union := func(p, q int) {
		// union person p and q
		// change all id in ids equal to ids[p] to ids[q]
		pid := ids[p]
		for i := range ids {
			if ids[i] == pid {
				ids[i] = ids[q]
			}
		}
	}
	for i := 0; i < n; i++ {
		for j := i + 1; j < n; j++ {
			if grid[i][j] == 1 {
				if ids[i] != ids[j] {
					ret--
					union(i, j)
				}
			}
		}
	}
	return ret
}

func Circles3(grid [][]int) int {
	n := len(grid)
	ret := n
	// quick-union
	ids := make([]int, n) // ids[i] represents the parent of i
	for i := range ids {
		ids[i] = i
	}
	root := func(i int) int {
		for i != ids[i] {
			i = ids[i]
		}
		return i
	}
	union := func(p, q int) {
		i, j := root(p), root(q)
		ids[i] = j
	}
	for i := 0; i < n; i++ {
		for j := 1; j < n; j++ {
			if grid[i][j] == 1 {
				if root(i) != root(j) {
					ret--
					union(i, j)
				}
			}
		}
	}
	return ret
}

func Circles4(grid [][]int) int {
	n := len(grid)
	ret := n
	// quick-union with weighted
	ids := make([]int, n) // ids[i] represents the parent of i
	sz := make([]int, n)  // sz[i] reprents the number of elements of root i
	for i := range ids {
		ids[i] = i
		sz[i] = 1
	}
	root := func(i int) int {
		for i != ids[i] {
			i = ids[i]
		}
		return i
	}
	union := func(p, q int) {
		i, j := root(p), root(q)
		// merge smaller tree into larger tree
		if i == j {
			// no need to merge
			return
		}
		if sz[i] < sz[j] {
			ids[i] = j
			sz[j] += sz[i]
		} else {
			ids[j] = i
			sz[i] += sz[j]
		}
	}
	for i := 0; i < n; i++ {
		for j := 1; j < n; j++ {
			if grid[i][j] == 1 {
				if root(i) != root(j) {
					ret--
					union(i, j)
				}
			}
		}
	}
	return ret
}

func Circles5(grid [][]int) int {
	n := len(grid)
	ret := n
	// weighted quick-union with path compression
	ids := make([]int, n) // ids[i] represents the parent of i
	sz := make([]int, n)
	for i := range ids {
		ids[i] = i
		sz[i] = 1
	}
	root := func(i int) int {
		for i != ids[i] {
			ids[i] = ids[ids[i]] // make every other node in path point to its grandparent
			i = ids[i]
		}
		return i
	}
	union := func(p, q int) {
		i, j := root(p), root(q)
		if sz[i] < sz[j] {
			ids[i] = j
			sz[j] += sz[i]
		} else {
			ids[j] = i
			sz[i] += sz[j]
		}
	}
	for i := 0; i < n; i++ {
		for j := 1; j < n; j++ {
			if grid[i][j] == 1 {
				if root(i) != root(j) {
					ret--
					union(i, j)
				}
			}
		}
	}
	return ret
}
<|endoftext|>


<commit_before>package main

import (
	"bufio"
	"errors"
	"io/ioutil"
	"net"
	"os"
	"os/exec"
	"path"
	"strconv"
	"strings"

	"gopkg.in/op/go-logging.v1"
	"gopkg.in/yaml.v2"
)

type Error interface {
	Error() string
}

type WormholeConfig struct {
	Port    int               `yaml:"port,omitempty"`
	Mapping map[string]string `yaml:"mapping"`
	Editors map[string]string `yaml:"editors"`
}

func (this *WormholeConfig) GetPort() int {
	if 0 == this.Port {
		return 5115
	}

	return this.Port
}

var log = logging.MustGetLogger("wormhole")
var format = logging.MustStringFormatter(
	"%{color}%{time:15:04:05.000} %{shortfunc} %{level:.5s} %{id:03x}%{color:reset} >> %{message}",
)
var config WormholeConfig

func main() {

	// Setup logging
	logbackend := logging.NewLogBackend(os.Stdout, "", 0)
	logbackendformatter := logging.NewBackendFormatter(logbackend, format)
	logging.SetBackend(logbackendformatter)

	// Read config
	log.Info("Parsing wormhole configuration ...")
	source, err := ioutil.ReadFile(path.Join(os.Getenv("HOME"), ".wormhole.yml"))
	if err != nil {
		log.Fatal(err)
	}

	err = yaml.Unmarshal(source, &config)
	if err != nil {
		log.Fatal(err)
	}
	log.Debug("Configuration: %v", config)

	// Start main
	log.Info("Wormhole server starting ...")

	l, err := net.Listen("tcp4", ":"+strconv.Itoa(config.GetPort()))
	if err != nil {
		log.Fatal(err)
	}

	log.Info("Listening at " + l.Addr().String())

	defer l.Close()
	for {
		// Wait for connection
		conn, err := l.Accept()
		if err != nil {
			log.Fatal(err)
		}

		log.Debug("Received connection from %s", conn.RemoteAddr().String())

		// Handle connection
		go handleConnection(conn)
	}
}

func handleConnection(c net.Conn) {
	defer c.Close()

	line, err := bufio.NewReader(c).ReadString('\n')
	if err != nil {
		log.Fatal(err)
	}

	writer := bufio.NewWriter(c)

	log.Debug("[%s] %s", c.RemoteAddr().String(), line)
	resp, err := handleLine(c, line)

	if err != nil {
		writer.WriteString("[ERR] ")
		writer.WriteString(err.Error())
	} else {
		writer.WriteString("[OK]")
		writer.WriteString(resp)
	}

	writer.Flush()
}

func handleLine(c net.Conn, line string) (resp string, err Error) {
	parts := strings.Split(strings.TrimSpace(line), " ")

	log.Debug("Extracted parts %s", parts)
	if len(parts) < 2 {
		log.Debug("Too little parts, quit.")
		return "", errors.New("Too few words, expected at least 2.")
	}

	switch parts[0] {
	case "INVOKE":
		return handleInvocation(parts[1:])
	}

	return "", errors.New("Unknown command, expected one of [EDIT, SHELL, EXPLORE, START]")
}

func handleInvocation(parts []string) (resp string, err Error) {
	log.Info("Invoking ", parts)

	go executeCommand("/bin/sleep", "10")
	return "OK", nil
}

func executeCommand(executable string, args ...string) (err Error) {
	cmd := exec.Command(executable, args...)

	out, err := cmd.CombinedOutput()
	if err != nil {
		log.Error(err.Error())
		return err
	}

	// cmd.StdoutPipe().close()
	// cmd.StderrPipe().close()
	// cmd.StdinPipe().close()

	if err := cmd.Start(); err != nil {
		log.Error(err.Error())
		return err
	}

	log.Info("Started '%s' w/ PID %d", executable, cmd.Process.Pid)

	cmd.Wait()

	log.Info("PID %d has quit.", cmd.Process.Pid)

	return nil
}
<commit_msg>Resolve mapping, rework logging<commit_after>package main

import (
	"bufio"
	"errors"
	"io/ioutil"
	"net"
	"os"
	"os/exec"
	"path"
	"strconv"
	"strings"

	"gopkg.in/op/go-logging.v1"
	"gopkg.in/yaml.v2"
)

type Error interface {
	Error() string
}

type WormholeConfig struct {
	Port    int               `yaml:"port,omitempty"`
	Mapping map[string]string `yaml:"mapping"`
	Editors map[string]string `yaml:"editors"`
}

func (this *WormholeConfig) GetPort() int {
	if 0 == this.Port {
		return 5115
	}

	return this.Port
}

func (this *WormholeConfig) GetMapping(key string) (executable string, err Error) {
	executable, ok := this.Mapping[key]

	if !ok {
		return "", errors.New("No mapping for " + key)
	}

	return executable, nil
}

func (this *WormholeConfig) AvailableMappings() string {
	var keys []string

	for key, _ := range this.Mapping {
		keys = append(keys, key)
	}

	return strings.Join(keys, ", ")
}

var log = logging.MustGetLogger("wormhole")
var format = logging.MustStringFormatter(
	"%{color}%{time:15:04:05.000} %{shortfunc} %{level:.5s} %{id:03x}%{color:reset} >> %{message}",
)
var config WormholeConfig

func main() {

	// Setup logging
	logbackend := logging.NewLogBackend(os.Stdout, "", 0)
	logbackendformatter := logging.NewBackendFormatter(logbackend, format)
	logging.SetBackend(logbackendformatter)

	// Read config
	log.Info("Parsing wormhole configuration ...")
	source, err := ioutil.ReadFile(path.Join(os.Getenv("HOME"), ".wormhole.yml"))
	if err != nil {
		log.Fatal(err)
	}

	err = yaml.Unmarshal(source, &config)
	if err != nil {
		log.Fatal(err)
	}
	log.Debug("Configuration: %v", config)

	// Start main
	log.Info("Wormhole server starting ...")

	l, err := net.Listen("tcp4", ":"+strconv.Itoa(config.GetPort()))
	if err != nil {
		log.Fatal(err)
	}

	log.Info("Listening at " + l.Addr().String())

	defer l.Close()
	for {
		// Wait for connection
		conn, err := l.Accept()
		if err != nil {
			log.Fatal(err)
		}

		log.Debug("Received connection from %s", conn.RemoteAddr().String())

		// Handle connection
		go handleConnection(conn)
	}
}

func handleConnection(c net.Conn) {
	defer c.Close()

	line, err := bufio.NewReader(c).ReadString('\n')
	if err != nil {
		log.Fatal(err)
	}

	writer := bufio.NewWriter(c)

	log.Debug("[%s] %s", c.RemoteAddr().String(), line)
	resp, err := handleLine(c, line)

	if err != nil {
		writer.WriteString("[ERR] ")
		writer.WriteString(err.Error())
	} else {
		writer.WriteString("[OK] ")
		writer.WriteString(resp)
	}

	writer.WriteString("\n")
	writer.Flush()
}

func handleLine(c net.Conn, line string) (resp string, err Error) {
	parts := strings.Split(strings.TrimSpace(line), " ")

	log.Debug("Extracted parts %s", parts)
	if len(parts) < 2 {
		log.Warning("Too little parts, quit.")
		return "", errors.New("Too few words, expected at least 2.")
	}

	switch strings.ToLower(parts[0]) {
	case "invoke":
		return handleInvocation(parts[1], parts[2:])
	}

	return "", errors.New("Unknown command, expected one of " + config.AvailableMappings())
}

func handleInvocation(mapping string, args []string) (resp string, err Error) {
	executable, err := config.GetMapping(mapping)
	if err != nil {
		return "", err
	}

	log.Info("Invoking '%v' (mapped by %v) with args: %v", executable, mapping, args)
	go executeCommand("/bin/sleep", "10")
	return "OK", nil
}

func executeCommand(executable string, args ...string) (err Error) {
	cmd := exec.Command(executable, args...)

	// out, err := cmd.CombinedOutput()
	// if err != nil {
	// 	log.Error(err.Error())
	// 	return err
	// }

	// cmd.StdoutPipe().close()
	// cmd.StderrPipe().close()
	// cmd.StdinPipe().close()

	if err := cmd.Start(); err != nil {
		log.Error(err.Error())
		return err
	}

	log.Info("Started '%s' w/ PID %d", executable, cmd.Process.Pid)

	cmd.Wait()

	log.Info("PID %d has quit.", cmd.Process.Pid)

	return nil
}
<|endoftext|>


<commit_before>package qbit

import (
	"errors"
	"sync/atomic"
	"time"
)

type BasicQueueManager struct {
	queue     Queue
	started   int64
	batchSize int
}

func NewQueueManager(channelSize int, batchSize int, pollWaitDuration time.Duration, listener ReceiveQueueListener) QueueManager {
	channel := make(chan []interface{}, channelSize)
	queue := &BasicQueue{
		channel:          channel,
		batchSize:        batchSize,
		pollWaitDuration: pollWaitDuration,
	}

	queueManager := &BasicQueueManager{
		queue:     queue,
		batchSize: batchSize,
	}

	if listener == nil {
		listener = NewQueueListener(&QueueListener{})
	}
	queueManager.startListener(listener)
	return queueManager
}

func NewSimpleQueueManager(listener ReceiveQueueListener) QueueManager {
	return NewQueueManager(1, 10000, time.Millisecond*10, listener)
}

func (bqm *BasicQueueManager) startListener(listener ReceiveQueueListener) error {
	var err error

	if bqm.Started() {
		err = errors.New("Queue already started")
	} else if atomic.CompareAndSwapInt64(&bqm.started, 0, 1) {
		go manageQueue(bqm.batchSize, bqm, bqm.queue.ReceiveQueue(), listener)
	}
	return err
}

func (bqm *BasicQueueManager) Started() bool {
	started := atomic.LoadInt64(&bqm.started)
	return started == 1
}

func (bqm *BasicQueueManager) Stopped() bool {
	started := atomic.LoadInt64(&bqm.started)
	return started == 0
}

func (bqm *BasicQueueManager) Queue() Queue {
	return bqm.queue
}

func (bqm *BasicQueueManager) SendQueueWithAutoFlush(flushDuration time.Duration) SendQueue {

	sendQueue := NewLockingSendQueue(bqm.queue.SendQueue())

	go func() {
		for {
			timer := time.NewTimer(flushDuration)
			select {
			case <-timer.C:
				sendQueue.FlushSends()
				timer.Reset(flushDuration)
			}

			if bqm.Stopped() {
				break
			}
		}
	}()

	return sendQueue
}

func (bqm *BasicQueueManager) Stop() error {
	var err error
	if !bqm.Started() {
		err = errors.New("Cant' stop Queue, it was not started")
	} else if atomic.CompareAndSwapInt64(&bqm.started, 1, 0) {
		err = nil
	}
	return err
}

func manageQueue(batchSize int, queueManager QueueManager, inputQueue ReceiveQueue,
	listener ReceiveQueueListener) {
	listener.Init()
	var items []interface{}
	count := 0

	items = inputQueue.ReadBatch()

OuterLoop:
	for {

		if items != nil {
			listener.StartBatch()
			for i := 0; i < len(items); i++ {
				count++
				listener.Receive(items[i])
			}
			listener.EndBatch()
			if batchSize == len(items) {
				recycleBuffer(batchSize, items)
			}
			items = inputQueue.ReadBatch()
			continue OuterLoop
		} else {
			items = inputQueue.ReadBatchWait()
			if items == nil {
				listener.Empty()
				if queueManager.Stopped() {
					listener.Shutdown()
					break OuterLoop
				}

			}
		}
	}
}

//func manageQueue(limit int, queueManager QueueManager, inputQueue ReceiveQueue, listener ReceiveQueueListener) {
//	listener.Init()
//	var item interface{}
//	count := 0
//	item = inputQueue.Poll() //Initialize things.
//
//OuterLoop:
//	for {
//		if item != nil {
//			listener.StartBatch()
//		}
//
//		for {
//			if item == nil {
//				break
//			}
//			listener.Receive(item)
//			/* If the receive count has hit the max then we need to call limit. */
//			if count >= limit {
//				listener.EndBatch()
//				count = 0
//				if queueManager.Stopped() {
//					listener.Shutdown()
//					break OuterLoop
//				}
//			}
//			/* Grab the next item from the queue. */
//			item = inputQueue.Poll()
//			count++
//		}
//
//		count = 0
//		listener.Empty()
//
//		// Get the next item, but wait this time since the queue was empty.
//		// This pauses the queue handling so we don't eat up all of the CPU.
//		item = inputQueue.PollWait()
//		if queueManager.Stopped() {
//			listener.Shutdown()
//			break OuterLoop
//		}
//
//		if item == nil {
//			/* Idle means we yielded and then waited a full wait time, so idle might be a good time to do clean up
//			or timed tasks.
//			*/
//			listener.Idle()
//		}
//	}
//}
<commit_msg>Fixed idle vs empty logic<commit_after>package qbit

import (
	"errors"
	"sync/atomic"
	"time"
)

type BasicQueueManager struct {
	queue     Queue
	started   int64
	batchSize int
}

func NewQueueManager(channelSize int, batchSize int, pollWaitDuration time.Duration, listener ReceiveQueueListener) QueueManager {
	channel := make(chan []interface{}, channelSize)
	queue := &BasicQueue{
		channel:          channel,
		batchSize:        batchSize,
		pollWaitDuration: pollWaitDuration,
	}

	queueManager := &BasicQueueManager{
		queue:     queue,
		batchSize: batchSize,
	}

	if listener == nil {
		listener = NewQueueListener(&QueueListener{})
	}
	queueManager.startListener(listener)
	return queueManager
}

func NewSimpleQueueManager(listener ReceiveQueueListener) QueueManager {
	return NewQueueManager(1, 10000, time.Millisecond*10, listener)
}

func (bqm *BasicQueueManager) startListener(listener ReceiveQueueListener) error {
	var err error

	if bqm.Started() {
		err = errors.New("Queue already started")
	} else if atomic.CompareAndSwapInt64(&bqm.started, 0, 1) {
		go manageQueue(bqm.batchSize, bqm, bqm.queue.ReceiveQueue(), listener)
	}
	return err
}

func (bqm *BasicQueueManager) Started() bool {
	started := atomic.LoadInt64(&bqm.started)
	return started == 1
}

func (bqm *BasicQueueManager) Stopped() bool {
	started := atomic.LoadInt64(&bqm.started)
	return started == 0
}

func (bqm *BasicQueueManager) Queue() Queue {
	return bqm.queue
}

func (bqm *BasicQueueManager) SendQueueWithAutoFlush(flushDuration time.Duration) SendQueue {

	sendQueue := NewLockingSendQueue(bqm.queue.SendQueue())

	go func() {
		for {
			timer := time.NewTimer(flushDuration)
			select {
			case <-timer.C:
				sendQueue.FlushSends()
				timer.Reset(flushDuration)
			}

			if bqm.Stopped() {
				break
			}
		}
	}()

	return sendQueue
}

func (bqm *BasicQueueManager) Stop() error {
	var err error
	if !bqm.Started() {
		err = errors.New("Cant' stop Queue, it was not started")
	} else if atomic.CompareAndSwapInt64(&bqm.started, 1, 0) {
		err = nil
	}
	return err
}

func manageQueue(batchSize int, queueManager QueueManager, inputQueue ReceiveQueue,
	listener ReceiveQueueListener) {
	listener.Init()
	var items []interface{}
	count := 0

	items = inputQueue.ReadBatch()

OuterLoop:
	for {

		if items != nil {
			listener.StartBatch()
			for i := 0; i < len(items); i++ {
				count++
				listener.Receive(items[i])
			}
			listener.EndBatch()
			if batchSize == len(items) {
				recycleBuffer(batchSize, items)
			}
			items = inputQueue.ReadBatch()
			continue OuterLoop
		} else {
			listener.Empty()
			items = inputQueue.ReadBatchWait()
			if items == nil {
				listener.Idle()
				if queueManager.Stopped() {
					listener.Shutdown()
					break OuterLoop
				}
			}
		}
	}
}

//func manageQueue(limit int, queueManager QueueManager, inputQueue ReceiveQueue, listener ReceiveQueueListener) {
//	listener.Init()
//	var item interface{}
//	count := 0
//	item = inputQueue.Poll() //Initialize things.
//
//OuterLoop:
//	for {
//		if item != nil {
//			listener.StartBatch()
//		}
//
//		for {
//			if item == nil {
//				break
//			}
//			listener.Receive(item)
//			/* If the receive count has hit the max then we need to call limit. */
//			if count >= limit {
//				listener.EndBatch()
//				count = 0
//				if queueManager.Stopped() {
//					listener.Shutdown()
//					break OuterLoop
//				}
//			}
//			/* Grab the next item from the queue. */
//			item = inputQueue.Poll()
//			count++
//		}
//
//		count = 0
//		listener.Empty()
//
//		// Get the next item, but wait this time since the queue was empty.
//		// This pauses the queue handling so we don't eat up all of the CPU.
//		item = inputQueue.PollWait()
//		if queueManager.Stopped() {
//			listener.Shutdown()
//			break OuterLoop
//		}
//
//		if item == nil {
//			/* Idle means we yielded and then waited a full wait time, so idle might be a good time to do clean up
//			or timed tasks.
//			*/
//			listener.Idle()
//		}
//	}
//}
<|endoftext|>


<commit_before>package slog

import "bosun.org/_third_party/code.google.com/p/winsvc/debug"

type eventLog struct {
	l  debug.Log
	id uint32
}

// Sets the logger to a Windows Event Log. Designed for use with the
// code.google.com/p/winsvc/eventlog and code.google.com/p/winsvc/debug
// packages.
func SetEventLog(l debug.Log, eid uint32) {
	Set(&eventLog{l, eid})
}

func (e *eventLog) Fatal(v string) {
	e.Error(v)
}

func (e *eventLog) Info(v string) {
	e.l.Info(e.id, v)
}

func (e *eventLog) Warning(v string) {
	e.l.Warning(e.id, v)
}
func (e *eventLog) Error(v string) {
	e.l.Error(e.id, v)
}
<commit_msg>slog: Include severity when writing to event log in Windows<commit_after>package slog

import (
	"fmt"

	"bosun.org/_third_party/code.google.com/p/winsvc/debug"
)

type eventLog struct {
	l  debug.Log
	id uint32
}

// Sets the logger to a Windows Event Log. Designed for use with the
// code.google.com/p/winsvc/eventlog and code.google.com/p/winsvc/debug
// packages.
func SetEventLog(l debug.Log, eid uint32) {
	Set(&eventLog{l, eid})
}

func (e *eventLog) Fatal(v string) {
	e.l.Error(e.id, fmt.Sprintf("fatal: %s", v))
}

func (e *eventLog) Info(v string) {
	e.l.Info(e.id, fmt.Sprintf("info: %s", v))
}

func (e *eventLog) Warning(v string) {
	e.l.Warning(e.id, fmt.Sprintf("warning: %s", v))
}
func (e *eventLog) Error(v string) {
	e.l.Error(e.id, fmt.Sprintf("error: %s", v))
}
<|endoftext|>


<commit_before>package image

import (
	"image"
	"image/color"

	"honnef.co/go/cups/raster"
)

// FIXME respect bounding boxes

func rect(p *raster.Page) image.Rectangle {
	// TODO respect bounding box
	return image.Rect(0, 0, int(p.Header.CUPSWidth), int(p.Header.CUPSHeight))
}

// Image returns an image.Image of the page.
//
// Depending on the color space and bit depth used, image.Image
// implementations from this package or from the Go standard library
// image package may be used. The mapping is as follows:
//
//   - 1-bit, ColorSpaceBlack -> *Monochrome
//   - 8-bit, ColorSpaceBlack -> *image.Gray
//   - 8-bit, ColorSpaceCMYK -> *image.CMYK
//   - Other combinations are not currently supported and will return
//     ErrUnsupported. They might be added in the future.
//
// No calls to ReadLine or ReadAll must be made before or after
// calling Image. That is, Image consumes the entire stream of the
// current page.
//
// Note that decoding an entire page at once may use considerable
// amounts of memory. For efficient, line-wise processing, a
// combination of ReadLine and ParseColors should be used instead.
func Image(p *raster.Page) (image.Image, error) {
	b := make([]byte, p.TotalSize())
	err := p.ReadAll(b)
	if err != nil {
		return nil, err
	}

	// FIXME support color orders other than chunked
	if p.Header.CUPSColorOrder != raster.ChunkyPixels {
		return nil, raster.ErrUnsupported
	}
	switch p.Header.CUPSColorSpace {
	case raster.ColorSpaceBlack:
		switch p.Header.CUPSBitsPerColor {
		case 1:
			return &Monochrome{
				Pix:    b,
				Stride: int(p.Header.CUPSBytesPerLine),
				Rect:   rect(p),
			}, nil
		case 8:
			for i, v := range b {
				b[i] = 255 - v
			}
			return &image.Gray{
				Pix:    b,
				Stride: int(p.Header.CUPSBytesPerLine),
				Rect:   rect(p),
			}, nil
		default:
			return nil, raster.ErrUnsupported
		}
	case raster.ColorSpaceCMYK:
		if p.Header.CUPSBitsPerColor != 8 {
			return nil, raster.ErrUnsupported
		}
		// TODO does cups have a byte order for colors in a pixel and
		// do we need to swap bytes?
		return &image.CMYK{
			Pix:    b,
			Stride: int(p.Header.CUPSBytesPerLine),
			Rect:   rect(p),
		}, nil
	default:
		return nil, raster.ErrUnsupported
	}
}

var _ image.Image = (*Monochrome)(nil)

type Monochrome struct {
	Pix    []uint8
	Stride int
	Rect   image.Rectangle
}

func (img *Monochrome) ColorModel() color.Model {
	return color.GrayModel
}

func (img *Monochrome) Bounds() image.Rectangle {
	return img.Rect
}

func (img *Monochrome) At(x, y int) color.Color {
	idx := img.PixOffset(x, y)
	if img.Pix[idx]<<uint(x%8)&128 == 0 {
		return color.Gray{Y: 255}
	}
	return color.Gray{Y: 0}
}

// PixOffset returns the index of the first element of Pix that
// corresponds to the pixel at (x, y).
func (img *Monochrome) PixOffset(x, y int) int {
	// TODO respect non-zero starting point of bounding box
	return y*img.Stride + (x / 8)
}
<commit_msg>raster/image: document Monochrome type<commit_after>package image

import (
	"image"
	"image/color"

	"honnef.co/go/cups/raster"
)

// FIXME respect bounding boxes

func rect(p *raster.Page) image.Rectangle {
	// TODO respect bounding box
	return image.Rect(0, 0, int(p.Header.CUPSWidth), int(p.Header.CUPSHeight))
}

// Image returns an image.Image of the page.
//
// Depending on the color space and bit depth used, image.Image
// implementations from this package or from the Go standard library
// image package may be used. The mapping is as follows:
//
//   - 1-bit, ColorSpaceBlack -> *Monochrome
//   - 8-bit, ColorSpaceBlack -> *image.Gray
//   - 8-bit, ColorSpaceCMYK -> *image.CMYK
//   - Other combinations are not currently supported and will return
//     ErrUnsupported. They might be added in the future.
//
// No calls to ReadLine or ReadAll must be made before or after
// calling Image. That is, Image consumes the entire stream of the
// current page.
//
// Note that decoding an entire page at once may use considerable
// amounts of memory. For efficient, line-wise processing, a
// combination of ReadLine and ParseColors should be used instead.
func Image(p *raster.Page) (image.Image, error) {
	b := make([]byte, p.TotalSize())
	err := p.ReadAll(b)
	if err != nil {
		return nil, err
	}

	// FIXME support color orders other than chunked
	if p.Header.CUPSColorOrder != raster.ChunkyPixels {
		return nil, raster.ErrUnsupported
	}
	switch p.Header.CUPSColorSpace {
	case raster.ColorSpaceBlack:
		switch p.Header.CUPSBitsPerColor {
		case 1:
			return &Monochrome{
				Pix:    b,
				Stride: int(p.Header.CUPSBytesPerLine),
				Rect:   rect(p),
			}, nil
		case 8:
			for i, v := range b {
				b[i] = 255 - v
			}
			return &image.Gray{
				Pix:    b,
				Stride: int(p.Header.CUPSBytesPerLine),
				Rect:   rect(p),
			}, nil
		default:
			return nil, raster.ErrUnsupported
		}
	case raster.ColorSpaceCMYK:
		if p.Header.CUPSBitsPerColor != 8 {
			return nil, raster.ErrUnsupported
		}
		// TODO does cups have a byte order for colors in a pixel and
		// do we need to swap bytes?
		return &image.CMYK{
			Pix:    b,
			Stride: int(p.Header.CUPSBytesPerLine),
			Rect:   rect(p),
		}, nil
	default:
		return nil, raster.ErrUnsupported
	}
}

var _ image.Image = (*Monochrome)(nil)

// Monochrome is an in-memory monochromatic image, with 8 pixels
// packed into one byte. Its At method returns color.Gray values.
type Monochrome struct {
	Pix    []uint8
	Stride int
	Rect   image.Rectangle
}

func (img *Monochrome) ColorModel() color.Model {
	return color.GrayModel
}

func (img *Monochrome) Bounds() image.Rectangle {
	return img.Rect
}

func (img *Monochrome) At(x, y int) color.Color {
	idx := img.PixOffset(x, y)
	if img.Pix[idx]<<uint(x%8)&128 == 0 {
		return color.Gray{Y: 255}
	}
	return color.Gray{Y: 0}
}

// PixOffset returns the index of the first element of Pix that
// corresponds to the pixel at (x, y).
func (img *Monochrome) PixOffset(x, y int) int {
	// TODO respect non-zero starting point of bounding box
	return y*img.Stride + (x / 8)
}
<|endoftext|>


<commit_before>package dev

import (
	"github.com/watermint/toolbox/infra/control/app_control"
	"github.com/watermint/toolbox/infra/quality"
	"github.com/watermint/toolbox/infra/recpie/app_kitchen"
	"github.com/watermint/toolbox/infra/recpie/app_vo"
)

type Quality struct {
}

func (z *Quality) Test(c app_control.Control) error {
	return z.Exec(app_kitchen.NewKitchen(c, &app_vo.EmptyValueObject{}))
}

func (z *Quality) Hidden() {
}

func (z *Quality) Requirement() app_vo.ValueObject {
	return &app_vo.EmptyValueObject{}
}

func (z *Quality) Exec(k app_kitchen.Kitchen) error {
	quality.Suite(k.Control())
	return nil
}
<commit_msg>fix: quality test should not be executed except binary form<commit_after>package dev

import (
	"github.com/watermint/toolbox/infra/control/app_control"
	"github.com/watermint/toolbox/infra/quality"
	"github.com/watermint/toolbox/infra/recpie/app_kitchen"
	"github.com/watermint/toolbox/infra/recpie/app_vo"
)

type Quality struct {
}

func (z *Quality) Test(c app_control.Control) error {
	return nil
}

func (z *Quality) Hidden() {
}

func (z *Quality) Requirement() app_vo.ValueObject {
	return &app_vo.EmptyValueObject{}
}

func (z *Quality) Exec(k app_kitchen.Kitchen) error {
	quality.Suite(k.Control())
	return nil
}
<|endoftext|>


<commit_before>package main

import (
	//"fmt"
	"github.com/simulatedsimian/yx5300"
)

func main() {
	conn, err := yx5300.MakeSerialConnection("/dev/ttyUSB0", false)
	if err != nil {
		panic(err)
	}

	conn.WriteCommand(CMD_SEL_DEV, 0, DEV_TF)

	conn.WriteCommand(CMD_SEL_DEV, 0, DEV_TF)
	time.Sleep(500 * time.Millisecond)

	conn.WriteCommand(CMD_QUERY_FLDR_COUNT, 0, 0)
	time.Sleep(500 * time.Millisecond)

	conn.WriteCommand(CMD_QUERY_TOT_TRACKS, 0, 0)
	time.Sleep(500 * time.Millisecond)

	for n := 1; n < 10; n++ {
		conn.WriteCommand(CMD_QUERY_FLDR_TRACKS, 0, byte(n))
		time.Sleep(500 * time.Millisecond)
	}

	conn.WriteCommand(CMD_PLAY_FOLDER_FILE, 5, 2)

	for {
		time.Sleep(5 * time.Second)
		//conn.WriteCommand(CMD_QUERY_STATUS, 0, 0)
	}
}
<commit_msg>testing commands<commit_after>package main

import (
	"github.com/simulatedsimian/yx5300"
	"time"
)

func main() {
	conn, err := yx5300.MakeSerialConnection("/dev/ttyUSB0", false)
	if err != nil {
		panic(err)
	}

	conn.WriteCommand(yx5300.CMD_SEL_DEV, 0, yx5300.DEV_TF)

	conn.WriteCommand(yx5300.CMD_SEL_DEV, 0, yx5300.DEV_TF)
	time.Sleep(500 * time.Millisecond)

	conn.WriteCommand(yx5300.CMD_QUERY_FLDR_COUNT, 0, 0)
	time.Sleep(500 * time.Millisecond)

	conn.WriteCommand(yx5300.CMD_QUERY_TOT_TRACKS, 0, 0)
	time.Sleep(500 * time.Millisecond)

	for n := 1; n < 10; n++ {
		conn.WriteCommand(yx5300.CMD_QUERY_FLDR_TRACKS, 0, byte(n))
		time.Sleep(500 * time.Millisecond)
	}

	conn.WriteCommand(yx5300.CMD_PLAY_FOLDER_FILE, 4, 1)
	conn.WriteCommand(yx5300.CMD_PLAY_FOLDER_FILE, 4, 2)
	conn.WriteCommand(yx5300.CMD_PLAY_FOLDER_FILE, 4, 3)

	for {
		time.Sleep(5 * time.Second)
		//conn.WriteCommand(CMD_QUERY_STATUS, 0, 0)
	}
}
<|endoftext|>


<commit_before>package resource

import (
	"errors"
	"github.com/qor/qor"

	"reflect"
)

var (
	ErrProcessorRecordNotFound = errors.New("record not found")
	ErrProcessorSkipLeft       = errors.New("skip left")
)

type Processor struct {
	Result    interface{}
	Resource  *Resource
	Context   *qor.Context
	MetaDatas MetaDatas
	SkipLeft  bool
}

func (processor *Processor) checkSkipLeft(errs ...error) bool {
	if processor.SkipLeft {
		return true
	}

	for _, err := range errs {
		if err == ErrProcessorSkipLeft {
			processor.SkipLeft = true
			break
		}
	}
	return processor.SkipLeft
}

func (processor *Processor) Initialize() error {
	err := ErrProcessorRecordNotFound
	if finder := processor.Resource.Finder; finder != nil {
		err = finder(processor.Result, processor.MetaDatas, processor.Context)
	}
	processor.checkSkipLeft(err)
	return err
}

func (processor *Processor) Validate() (errors []error) {
	if processor.checkSkipLeft() {
		return
	}

	for _, fc := range processor.Resource.validators {
		erres := fc(processor.Result, processor.MetaDatas, processor.Context)
		if processor.checkSkipLeft(erres...) {
			break
		}
		errors = append(errors, erres...)
	}
	return
}

func (processor *Processor) Decode() (errors []error) {
	if processor.checkSkipLeft() {
		return
	}

	for _, metaData := range processor.MetaDatas {
		if metaor := metaData.Meta; metaor != nil {
			meta := metaor.GetMeta()
			if len(metaData.MetaDatas) > 0 {
				if resource := meta.GetMeta().Resource; resource != nil {
					field := reflect.Indirect(reflect.ValueOf(processor.Result)).FieldByName(meta.Name)
					if field.Kind() == reflect.Struct {
						association := field.Addr().Interface()
						errors = append(errors, resource.Decode(association, metaData.MetaDatas, processor.Context).Start()...)
					} else if field.Kind() == reflect.Slice {
						value := reflect.New(field.Type().Elem())
						errors = append(errors, resource.Decode(value.Interface(), metaData.MetaDatas, processor.Context).Start()...)
						if !reflect.DeepEqual(reflect.Zero(field.Type().Elem()).Interface(), value.Elem().Interface()) {
							field.Set(reflect.Append(field, value.Elem()))
						}
					}
				}
			} else {
				metaData.Meta.Set(processor.Result, processor.MetaDatas, processor.Context)
			}
		}
	}
	return
}

func (processor *Processor) Commit() (errors []error) {
	errors = processor.Decode()
	if processor.checkSkipLeft(errors...) {
		return
	}

	resource := processor.Resource
	for _, fc := range resource.processors {
		erres := fc(processor.Result, processor.MetaDatas, processor.Context)
		if processor.checkSkipLeft(erres...) {
			break
		}
		errors = append(errors, erres...)
	}
	return
}

func (processor *Processor) Start() (errors []error) {
	processor.Initialize()
	if errors = append(errors, processor.Validate()...); len(errors) == 0 {
		errors = append(errors, processor.Commit()...)
	}
	return
}
<commit_msg>resource: un-expose Processor.Decode<commit_after>package resource

import (
	"errors"

	"github.com/qor/qor"

	"reflect"
)

var (
	ErrProcessorRecordNotFound = errors.New("record not found")
	ErrProcessorSkipLeft       = errors.New("skip left")
)

type Processor struct {
	Result    interface{}
	Resource  *Resource
	Context   *qor.Context
	MetaDatas MetaDatas
	SkipLeft  bool
}

func (processor *Processor) checkSkipLeft(errs ...error) bool {
	if processor.SkipLeft {
		return true
	}

	for _, err := range errs {
		if err == ErrProcessorSkipLeft {
			processor.SkipLeft = true
			break
		}
	}
	return processor.SkipLeft
}

func (processor *Processor) Initialize() error {
	err := ErrProcessorRecordNotFound
	if finder := processor.Resource.Finder; finder != nil {
		err = finder(processor.Result, processor.MetaDatas, processor.Context)
	}
	processor.checkSkipLeft(err)
	return err
}

func (processor *Processor) Validate() (errors []error) {
	if processor.checkSkipLeft() {
		return
	}

	for _, fc := range processor.Resource.validators {
		erres := fc(processor.Result, processor.MetaDatas, processor.Context)
		if processor.checkSkipLeft(erres...) {
			break
		}
		errors = append(errors, erres...)
	}
	return
}

func (processor *Processor) decode() (errors []error) {
	if processor.checkSkipLeft() {
		return
	}

	for _, metaData := range processor.MetaDatas {
		if metaor := metaData.Meta; metaor != nil {
			meta := metaor.GetMeta()
			if len(metaData.MetaDatas) > 0 {
				if resource := meta.GetMeta().Resource; resource != nil {
					field := reflect.Indirect(reflect.ValueOf(processor.Result)).FieldByName(meta.Name)
					if field.Kind() == reflect.Struct {
						association := field.Addr().Interface()
						errors = append(errors, resource.Decode(association, metaData.MetaDatas, processor.Context).Start()...)
					} else if field.Kind() == reflect.Slice {
						value := reflect.New(field.Type().Elem())
						errors = append(errors, resource.Decode(value.Interface(), metaData.MetaDatas, processor.Context).Start()...)
						if !reflect.DeepEqual(reflect.Zero(field.Type().Elem()).Interface(), value.Elem().Interface()) {
							field.Set(reflect.Append(field, value.Elem()))
						}
					}
				}
			} else {
				metaData.Meta.Set(processor.Result, processor.MetaDatas, processor.Context)
			}
		}
	}
	return
}

func (processor *Processor) Commit() (errors []error) {
	errors = processor.decode()
	if processor.checkSkipLeft(errors...) {
		return
	}

	resource := processor.Resource
	for _, fc := range resource.processors {
		erres := fc(processor.Result, processor.MetaDatas, processor.Context)
		if processor.checkSkipLeft(erres...) {
			break
		}
		errors = append(errors, erres...)
	}
	return
}

func (processor *Processor) Start() (errors []error) {
	processor.Initialize()
	if errors = append(errors, processor.Validate()...); len(errors) == 0 {
		errors = append(errors, processor.Commit()...)
	}
	return
}
<|endoftext|>


<commit_before>package http_handlers

import (
	"encoding/json"
	"fmt"
	"net/http"
	_ "net/url"

	_ "gopkg.in/mgo.v2/bson"
	"web_apps/news_aggregator/modules/database"
)

type TestStruct struct {
	Status int
}

type FeedMoreParams struct {
	ContentType string
	Skip        int
}

func indexNews() {

}

func GetIndexNews(w http.ResponseWriter, r *http.Request) {
	aggregated_news, err := database.NewsMainIndexNews()
	//aggregated_news, err := database.HackerNewsIndexNews()
	//aggregated_gn, err := database.GoogleNewsIndexNews()

	if err != nil {
		http.Error(w, err.Error(), http.StatusInternalServerError)
		return
	}

	respondToJson(w, aggregated_news)
}

func LatestNews(w http.ResponseWriter, r *http.Request) {
	//aggregated_news, err := database.HackerNewsLatestNews()
	aggregated_news, err := database.NewsMainIndexNews()
	if err != nil {
		http.Error(w, err.Error(), http.StatusInternalServerError)
		return
	}

	respondToJson(w, aggregated_news)
}

func FeedMore(w http.ResponseWriter, r *http.Request) {
	var feedMore FeedMoreParams
	if err := json.NewDecoder(r.Body).Decode(&feedMore); err != nil {
		fmt.Println(err)
		http.Error(w, err.Error(), http.StatusInternalServerError)
	}

	aggregated_news, err := database.HackerNewsFeedMore(feedMore.ContentType, feedMore.Skip)
	_ = err

	respondToJson(w, aggregated_news)

}

// func TopScoreNews(w http.ResponseWriter, r *http.Request) {

// }
<commit_msg>added fetch time profiler<commit_after>package http_handlers

import (
	"encoding/json"
	"fmt"
	"net/http"
	"time"
	_ "net/url"

	_ "gopkg.in/mgo.v2/bson"
	"web_apps/news_aggregator/modules/database"
)

type TestStruct struct {
	Status int
}

type FeedMoreParams struct {
	ContentType string
	Skip        int
}

func indexNews() {

}

func GetIndexNews(w http.ResponseWriter, r *http.Request) {
	aggregated_news, err := database.NewsMainIndexNews()
	if err != nil {
		http.Error(w, err.Error(), http.StatusInternalServerError)
		return
	}

	respondToJson(w, aggregated_news)
}

func LatestNews(w http.ResponseWriter, r *http.Request) {
	start := time.Now()
	aggregated_news, err := database.NewsMainIndexNews()
	fmt.Println("FETCH index took: ", time.Since(start))
	if err != nil {
		http.Error(w, err.Error(), http.StatusInternalServerError)
		return
	}

	respondToJson(w, aggregated_news)
}

func FeedMore(w http.ResponseWriter, r *http.Request) {
	var feedMore FeedMoreParams
	if err := json.NewDecoder(r.Body).Decode(&feedMore); err != nil {
		fmt.Println(err)
		http.Error(w, err.Error(), http.StatusInternalServerError)
	}

	aggregated_news, err := database.HackerNewsFeedMore(feedMore.ContentType, feedMore.Skip)
	_ = err

	respondToJson(w, aggregated_news)

}

// func TopScoreNews(w http.ResponseWriter, r *http.Request) {

// }
<|endoftext|>