<commit_before>package gobot

import (
	"fmt"
	"time"

	"github.com/bbqgophers/qpid"
	"github.com/felixge/pidctrl"
	gb "github.com/hybridgroup/gobot"
	"github.com/hybridgroup/gobot/api"
	"github.com/hybridgroup/gobot/platforms/raspi"
)

const i2cAddress = 0x4d

var (
	P = 3.0
	I = .05
	B = 0.0
)

type GobotController struct {
	grillProbe *GobotProbe
	gobot      *gb.Gobot
	pi         *raspi.RaspiAdaptor
	api        *api.API
	pid        *pidctrl.PIDController
}

func NewController() *GobotController {
	g := gb.NewGobot()
	r := raspi.NewRaspiAdaptor("qpid")
	robot := gb.NewRobot("qpid",
		[]gb.Connection{r},
		[]gb.Device{},
		nil,
	)
	errs := r.Connect()
	if errs != nil {
		return nil
	}
	g.AddRobot(robot)

	pid := pidctrl.NewPIDController(P, I, B)
	return &GobotController{
		grillProbe: NewProbe(r),
		gobot:      g,
		pi:         r,
		pid:        pid,
	}
}

func (g *GobotController) FoodMonitors() []qpid.Monitor {
	panic("not implemented")
}

func (g *GobotController) GrillMonitor() qpid.Monitor {
	return g.grillProbe
}

func (g *GobotController) Run() error {

	g.api = api.NewAPI(g.gobot)
	g.api.Port = "4000"
	g.api.AddHandler(api.BasicAuth("bbq", "gopher"))
	g.api.Start()
	e := g.pi.I2cStart(i2cAddress)
	if e != nil {
		return e
	}
	go func(){
		errs := g.gobot.Start()
		if errs != nil {
			// hack - maybe change interface?
			panic(errs)
		}
	}()
	return nil
}

func (g *GobotController) Stop() error {
	errs := g.gobot.Stop()
	if errs != nil {
		// hack - maybe change interface?
		return errs[0]
	}

	g.pid.Set(100.0)

	for x := 1; x < 1000; x++ {

		time.Sleep(1 * time.Second)
		temp, err := g.grillProbe.Temperature()
		if err != nil {
			return err
		}
		output := g.pid.Update(float64(temp.C()))
		fmt.Printf("%d - %d C - Output: %f", x, temp, output)
	}

	return nil
}
func (g *GobotController) Status() (qpid.GrillStatus, error) {
	return qpid.GrillStatus{
		Time:         time.Now(),
		GrillSensors: []qpid.Sensor{g.grillProbe},
	}, nil
}
<commit_msg>rudimentary loop for PID<commit_after>package gobot

import (
	"fmt"
	"time"

	"github.com/bbqgophers/qpid"
	"github.com/felixge/pidctrl"
	gb "github.com/hybridgroup/gobot"
	"github.com/hybridgroup/gobot/api"
	"github.com/hybridgroup/gobot/platforms/raspi"
)

const i2cAddress = 0x4d

var (
	Sleep = 10
	P = 3.0
	I = .05
	B = 0.0
)

type GobotController struct {
	grillProbe *GobotProbe
	gobot      *gb.Gobot
	pi         *raspi.RaspiAdaptor
	api        *api.API
	pid        *pidctrl.PIDController
	heating bool
}

func NewController() *GobotController {
	g := gb.NewGobot()
	r := raspi.NewRaspiAdaptor("qpid")
	robot := gb.NewRobot("qpid",
		[]gb.Connection{r},
		[]gb.Device{},
		nil,
	)
	errs := r.Connect()
	if errs != nil {
		return nil
	}
	g.AddRobot(robot)

	pid := pidctrl.NewPIDController(P, I, B)
	return &GobotController{
		grillProbe: NewProbe(r),
		gobot:      g,
		pi:         r,
		pid:        pid,
	}
}

func (g *GobotController) FoodMonitors() []qpid.Monitor {
	panic("not implemented")
}

func (g *GobotController) GrillMonitor() qpid.Monitor {
	return g.grillProbe
}

func (g *GobotController) Run() error {

	g.api = api.NewAPI(g.gobot)
	g.api.Port = "4000"
	g.api.AddHandler(api.BasicAuth("bbq", "gopher"))
	g.api.Start()
	e := g.pi.I2cStart(i2cAddress)
	if e != nil {
		return e
	}
	go func(){
		errs := g.gobot.Start()
		if errs != nil {
			// hack - maybe change interface?
			panic(errs)
		}
	}()

	g.pid.Set(100.0)

	for x := 1; x < 1000; x++ {

		time.Sleep(1* time.Second)
		temp, err := g.grillProbe.Temperature()
		if err != nil {
			return err
		}
		output := g.pid.Update(float64(temp.C()))
		fmt.Printf("%d - %d C - Output: %f\n", x, temp, output)

		for x := 1; x < 10; x ++ {

			if output > float64(x^2) {
				if !g.heating {
					g.heating = true
					fmt.Println("turning on the blower")
				}
				fmt.Println("leaving blower on")
			} else {
				if g.heating {
					g.heating = false
					fmt.Println("turning blower off")
				}
			}
		}
		if output < float64(10) {
			fmt.Println("temperature reached, sleep 10")
			time.Sleep(10*time.Second)
		}
	}
	return nil
}

func (g *GobotController) Stop() error {
	errs := g.gobot.Stop()
	if errs != nil {
		// hack - maybe change interface?
		return errs[0]
	}

	return nil
}
func (g *GobotController) Status() (qpid.GrillStatus, error) {
	return qpid.GrillStatus{
		Time:         time.Now(),
		GrillSensors: []qpid.Sensor{g.grillProbe},
	}, nil
}
<|endoftext|>


<commit_before>package gocricket

import (
	"encoding/xml"
	"fmt"
	"io/ioutil"
	"net/http"
	"strconv"
	"strings"
	"time"
)

const (
	EVENT_NO_CHANGE           = 0
	EVENT_OUT                 = 1
	EVENT_MATCH_STATUS_CHANGE = 2
	EVENT_OVER_CHANGED        = 3
	EVENT_RUN_CHANGE          = 4
	CRICBUZZ_URL              = "http://synd.cricbuzz.com/j2me/1.0/livematches.xml"
)

type Cricket struct {
	lastFetchedResult MatchStat
	teamName          string
	event             chan ResponseEvent
}

func NewCricketWatcher(teamName string, event chan ResponseEvent) (c *Cricket) {
	c = new(Cricket)
	c.teamName = teamName
	c.event = event
	return
}

type Response struct {
	BtTeamName  string
	Overs       string
	MatchStatus string
	Runs        string
	Wickets     string
}

type ResponseEvent struct {
	Response
	EventType int
}

type MatchData struct {
	MatchStats []MatchStat `xml:"match"`
}

type MatchStat struct {
	XMLName     xml.Name     `xml:"match"`
	Type        string       `xml:"type,attr"`
	States      State        `xml:"state"`
	Teams       []Team       `xml:"Tm"`
	BattingTeam *BattingTeam `xml:"mscr>btTm"`
}

type State struct {
	MatchState string `xml:"mchState,attr"`
	Status     string `xml:"status,attr"`
}

type Team struct {
	Name string `xml:"Name,attr"`
}

type InningDetails struct {
	Overs string `xml:"noofovers"`
}

type BattingTeam struct {
	Name  string   `xml:"sName,attr"`
	ID    string   `xml:"id,attr"`
	Inngs []Inning `xml:"Inngs"`
}

type Inning struct {
	Description string `xml:"desc,attr"`
	Run         string `xml:"r,attr"`
	Overs       string `xml:"ovrs,attr"`
	Wickets     string `xml:"wkts,attr"`
}

func (m *MatchData) Print() {
	for _, v := range m.MatchStats {
		fmt.Println("Type is")
		fmt.Printf("%+v\n", v)
	}
}

func (m *MatchStat) convertToResponse(eventType int) ResponseEvent {
	return ResponseEvent{
		Response: Response{
			Overs: m.BattingTeam.Inngs[0].Overs,
			BtTeamName:m.BattingTeam,
			Runs:m.BattingTeam.Inngs[0].Run,
			Wickets:m.BattingTeam.Inngs[0].Wickets,
		},
		EventType: eventType,
	}
}

func (m *MatchStat) TriggerEvent(lastFetchedStat MatchStat, event chan ResponseEvent) {
	var lastBt *BattingTeam
	var newBt *BattingTeam

	if lastFetchedStat.BattingTeam != nil {
		lastBt = lastFetchedStat.BattingTeam
	}

	if m.BattingTeam != nil {
		newBt = m.BattingTeam
	} else {
		fmt.Println("Match Has not yet Started")
		event <- m.convertToResponse(EVENT_NO_CHANGE)
	}

	if newBt.Inngs != nil && len(newBt.Inngs) > 0 {
		in := newBt.Inngs[0]
		run, err := strconv.Atoi(in.Run)
		overs, err := strconv.ParseFloat(in.Overs, 32)
		wkts, err := strconv.Atoi(in.Wickets)
		if err != nil {
			event <- m.convertToResponse(EVENT_NO_CHANGE)
		}
		oldRun, _ := strconv.Atoi(lastBt.Inngs[0].Run)
		oldOvers, _ := strconv.ParseFloat(lastBt.Inngs[0].Overs, 32)
		oldWkts, _ := strconv.Atoi(lastBt.Inngs[0].Wickets)

		if oldRun != run {
			event <- m.convertToResponse(EVENT_RUN_CHANGE)
		}
		if int(oldOvers) != int(overs) {
			event <- m.convertToResponse(EVENT_OVER_CHANGED)
		}
		if oldWkts != wkts {
			event <- m.convertToResponse(EVENT_OUT)
		}
	}
}

func (c *Cricket) Start() {
	var temp MatchData
	var m MatchData
	go func() {
		for {
			resp, _ := http.Get(CRICBUZZ_URL)
			data, _ := ioutil.ReadAll(resp.Body)
			err := xml.Unmarshal(data, &m)
			if err != nil {
				fmt.Print("Error is", err)
			}
			for _, k := range m.MatchStats {
				for _, team := range k.Teams {
					if strings.Compare(team.Name, c.teamName) == 0 {
						if len(temp.MatchStats) > 0 {
							k.TriggerEvent(temp.MatchStats[0], c.event)
						}
					}
				}
			}
			temp = m
			time.Sleep(time.Second * 10)
		}
	}()
}
<commit_msg>observing changes on run,wicket and overs<commit_after>package main

import (
	"encoding/xml"
	"fmt"
	"strconv"
	"io/ioutil"
	"time"
	"strings"
	"net/http"
)

const (
	EVENT_NO_CHANGE           = 0
	EVENT_OUT                 = 1
	EVENT_MATCH_STATUS_CHANGE = 2
	EVENT_OVER_CHANGED        = 3
	EVENT_RUN_CHANGE          = 4
	CRICBUZZ_URL              = "http://synd.cricbuzz.com/j2me/1.0/livematches.xml"
)

type Cricket struct {
	lastFetchedResult MatchStat
	teamName          string
	event             chan ResponseEvent
}

func NewCricketWatcher(teamName string, event chan ResponseEvent) (c *Cricket) {
	c = new(Cricket)
	c.teamName = teamName
	c.event = event
	return
}

type Response struct {
	BtTeamName  string
	Overs       string
	MatchStatus string
	Runs        string
	Wickets     string
}

type ResponseEvent struct {
	Response
	EventType int
}

type MatchData struct {
	MatchStats []MatchStat `xml:"match"`
}

type MatchStat struct {
	XMLName     xml.Name     `xml:"match"`
	Type        string       `xml:"type,attr"`
	States      State        `xml:"state"`
	Teams       []Team       `xml:"Tm"`
	BattingTeam *BattingTeam `xml:"mscr>btTm"`
}

type State struct {
	MatchState string `xml:"mchState,attr"`
	Status     string `xml:"status,attr"`
}

type Team struct {
	Name string `xml:"Name,attr"`
}

type InningDetails struct {
	Overs string `xml:"noofovers"`
}

type BattingTeam struct {
	Name  string   `xml:"sName,attr"`
	ID    string   `xml:"id,attr"`
	Inngs []Inning `xml:"Inngs"`
}

type Inning struct {
	Description string `xml:"desc,attr"`
	Run         string `xml:"r,attr"`
	Overs       string `xml:"ovrs,attr"`
	Wickets     string `xml:"wkts,attr"`
}

func (m *MatchData) Print() {
	for _, v := range m.MatchStats {
		fmt.Printf("%+v\n", v)
	}
}

func (m *MatchStat) convertToResponse(eventType int) ResponseEvent {
	return ResponseEvent{
		Response: Response{
			Overs: m.BattingTeam.Inngs[0].Overs,
			BtTeamName:m.BattingTeam.Name,
			Runs:m.BattingTeam.Inngs[0].Run,
			Wickets:m.BattingTeam.Inngs[0].Wickets,
		},
		EventType: eventType,
	}
}

func (m *MatchStat) TriggerEvent(lastFetchedStat MatchStat, event chan ResponseEvent) {
	var lastBt *BattingTeam
	var newBt *BattingTeam

	if lastFetchedStat.BattingTeam != nil {
		lastBt = lastFetchedStat.BattingTeam
	}

	if m.BattingTeam != nil {
		newBt = m.BattingTeam
	} else {
		fmt.Println("Match Has not yet Started")
		event <- m.convertToResponse(EVENT_NO_CHANGE)
	}
	fmt.Printf("New Batting Score %+v\n", *newBt)
	fmt.Printf("Old Batting Score %+v\n", *lastBt)
	if newBt.Inngs != nil && len(newBt.Inngs) > 0 {
		inningIndex := len(newBt.Inngs) - 1
		in := newBt.Inngs[inningIndex]
		run, err := strconv.Atoi(in.Run)
		overs, err := strconv.ParseFloat(in.Overs, 32)
		wkts, err := strconv.Atoi(in.Wickets)
		if err != nil {
			event <- m.convertToResponse(EVENT_NO_CHANGE)
		}
		oldRun, _ := strconv.Atoi(lastBt.Inngs[inningIndex].Run)
		oldOvers, _ := strconv.ParseFloat(lastBt.Inngs[inningIndex].Overs, 32)
		oldWkts, _ := strconv.Atoi(lastBt.Inngs[inningIndex].Wickets)

		if oldRun != run {
			fmt.Println("Event run change")
			event <- m.convertToResponse(EVENT_RUN_CHANGE)
		}
		if int(oldOvers) != int(overs) {
			fmt.Println("Event over changed")
			event <- m.convertToResponse(EVENT_OVER_CHANGED)
		}
		if oldWkts != wkts {
			fmt.Println("Event out")
			event <- m.convertToResponse(EVENT_OUT)
		}
	}
}

func (c *Cricket) Start() {
	var temp MatchData
	go func() {
		for {
			var m MatchData
			resp, _ := http.Get(CRICBUZZ_URL)
			data, _ := ioutil.ReadAll(resp.Body)
			err := xml.Unmarshal(data, &m)
			if err != nil {
				fmt.Print("Error is", err)
			}
			matchStat := c.TeamMatchStat(m)
			if matchStat.BattingTeam != nil && len(temp.MatchStats) > 0{
				matchStat.TriggerEvent(c.TeamMatchStat(temp),c.event)
			}
			temp = m
			time.Sleep(time.Second * 10)
		}
	}()
}

func (c *Cricket ) TeamMatchStat(m MatchData) (s MatchStat) {
	for _, k := range m.MatchStats {
		for _, team := range k.Teams {
			if strings.Compare(team.Name, c.teamName) == 0 {
				s = k
				return
			}
		}
	}
	return
}
<|endoftext|>


<commit_before>// Gorending is cli tool that crawls github trending in real time.
package main

import (
	"fmt"
	"log"
	"os"
	"strings"
	"time"

	"github.com/PuerkitoBio/goquery"
	"github.com/urfave/cli"
)

// CrawlTrending function requests to Github website and prints parsed trendings.
func CrawlTrending(lang string, count int) error {
	doc, err := goquery.NewDocument("https://github.com/trending/" + lang)
	if err != nil {
		log.Fatal(err)
		return err
	}

	repoList := doc.Find(".d-inline-block > h3 > a").Slice(0, count)

	repoList.Each(func(i int, s *goquery.Selection) {
		repoName := strings.Trim(s.Text(), " \n")
		fmt.Printf("%d - %s\n", i+1, repoName)
	})
	return nil
}

func main() {
	app := cli.NewApp()
	app.Name = "gorending"
	app.Usage = "Show Github trending in Terminal!"
	app.Version = "1.0.0"
	app.Compiled = time.Now()
	app.Copyright = "(c) 2017 Myungseo Kang"
	app.Authors = []cli.Author{
		cli.Author{
			Name:  "Myungseo Kang",
			Email: "l3opold7@gmail.com",
		},
	}

	app.Flags = []cli.Flag{
		// lang flag is language that you want to see
		cli.StringFlag{
			Name:  "lang, L",
			Value: "",
			Usage: "language that you want to see (default: all language)",
		},
		// count flag is count that you want to see
		cli.IntFlag{
			Name:  "count, C",
			Value: 10,
			Usage: "count that you want to see",
		},
	}

	app.Action = func(c *cli.Context) error {
		lang := c.String("lang")
		count := c.Int("count")

		err := CrawlTrending(lang, count)
		if err != nil {
			return err
		}

		return nil
	}

	app.Run(os.Args)
}
<commit_msg>Show full repo url (#12)<commit_after>// Gorending is cli tool that crawls github trendings in Terminal at real time.
package main

import (
	"fmt"
	"log"
	"os"
	"strings"
	"time"

	"github.com/PuerkitoBio/goquery"
	"github.com/urfave/cli"
)

// GithubURL is Github url
var GithubURL = "https://github.com"

// TrendingURL is Github trending url
var TrendingURL = GithubURL + "/trending/"

// CrawlTrending function requests to Github website and prints parsed trendings.
func CrawlTrending(lang string, count int) error {
	doc, err := goquery.NewDocument(TrendingURL + lang)
	if err != nil {
		log.Fatal(err)
		return err
	}

	repoList := doc.Find(".d-inline-block > h3 > a").Slice(0, count)

	repoList.Each(func(i int, s *goquery.Selection) {
		repoURL, ok := s.Attr("href")
		repoName := strings.Trim(s.Text(), " \n")
		if ok {
			fmt.Printf("%d - %s (%s)\n", i+1, repoName, GithubURL+repoURL)
		}
	})
	return nil
}

func main() {
	app := cli.NewApp()
	app.Name = "gorending"
	app.Usage = "Show Github trending in Terminal!"
	app.Version = "1.0.1"
	app.Compiled = time.Now()
	app.Copyright = "(c) 2017 Myungseo Kang"
	app.Authors = []cli.Author{
		cli.Author{
			Name:  "Myungseo Kang",
			Email: "l3opold7@gmail.com",
		},
	}

	app.Flags = []cli.Flag{
		// lang flag is language that you want to see
		cli.StringFlag{
			Name:  "lang, L",
			Value: "",
			Usage: "language that you want to see (default: all language)",
		},
		// count flag is count that you want to see
		cli.IntFlag{
			Name:  "count, C",
			Value: 10,
			Usage: "count that you want to see",
		},
	}

	app.Action = func(c *cli.Context) error {
		lang := c.String("lang")
		count := c.Int("count")

		err := CrawlTrending(lang, count)
		if err != nil {
			return err
		}

		return nil
	}

	app.Run(os.Args)
}
<|endoftext|>


<commit_before>package gosseract

import (
  "os"
  "os/exec"
  "io/ioutil"
  "bytes"
  "strings"
)
/* TODO#1: Error or nil っていう返し方無いか
type Error struct {
  Message string
}
TODO#1が解決されるまでコメントアウト */

type AnywayArgs struct {
  SourcePath  string
  Destination string
}
var (
  TMPDIR = "/tmp"
  OUTEXT = ".txt"
  COMMAND = "tesseract"
  VERSION = "0.0.1"
)

func Greeting() string {
  return "Hello,Gosseract!"
}

/**
 * とにかくパラメータ喰わせて一発でOCRしたい場合の
 * コマンドラッパー
 */
func Anyway(args AnywayArgs) string {
  // 最終的な返り値
  out := ""

  // 引数で行き先を指定されない場合は
  // (とりあえず) `/tmp/anyway,txt`に置く
  // tesseractが標準出力に対応してるハズ
  // tesseractのバージョンを見るようなメソッドを用意しないとアカンなこれ
  if args.Destination == "" {
    args.Destination = TMPDIR + "/anyway"
  }

  // tesseractコマンドを実行
  command := exec.Command(COMMAND, args.SourcePath, args.Destination)
  e := command.Run()
  if e != nil {
    panic(e)
  }

  // 出力を読む
  // tesseractの出力はコマンドラインの第二引数に.txtを付けたものに置かれる
  fn := args.Destination + OUTEXT
  f, _ := os.OpenFile(fn, 1, 1)
  buf, _ := ioutil.ReadFile(f.Name())
  out = string(buf)

  return out
}

/**
 * privateなメソッドってどうやって定義するんだ？
 */
func getTesseractVersion() string {
  command := exec.Command(COMMAND, "--version")
  var stderr bytes.Buffer
  command.Stderr = &stderr //謎に標準エラーで来るw
  e := command.Run()
  if e != nil {
    panic(e)
  }
  // なんかクズい
  tesseractInfo := strings.Split(stderr.String(), " ")[1]
  return strings.TrimRight(tesseractInfo, "\n")
}
/**
 * 利用可能な言語の一覧を取得する
 */
func getAvailableLanguages() []string {
  command := exec.Command(COMMAND, "--list-langs")
  var stderr bytes.Buffer
  command.Stderr = &stderr //謎に標準エラーで来るw
  e := command.Run()
  if e != nil {
    panic(e)
  }
  langs := strings.Split(stderr.String(), "\n")
  langs = langs[1:len(langs) - 1]
  return langs
}
<commit_msg>Add general private method<commit_after>package gosseract

import (
  "os"
  "os/exec"
  "io/ioutil"
  "bytes"
  "strings"
)
/* TODO#1: Error or nil っていう返し方無いか
type Error struct {
  Message string
}
TODO#1が解決されるまでコメントアウト */

type AnywayArgs struct {
  SourcePath  string
  Destination string
}
var (
  TMPDIR = "/tmp"
  OUTEXT = ".txt"
  COMMAND = "tesseract"
  VERSION = "0.0.1"
)

func Greeting() string {
  return "Hello,Gosseract!"
}

/**
 * とにかくパラメータ喰わせて一発でOCRしたい場合の
 * コマンドラッパー
 */
func Anyway(args AnywayArgs) string {
  // 最終的な返り値
  out := ""

  // 引数で行き先を指定されない場合は
  // (とりあえず) `/tmp/anyway,txt`に置く
  // tesseractが標準出力に対応してるハズ
  // tesseractのバージョンを見るようなメソッドを用意しないとアカンなこれ
  if args.Destination == "" {
    args.Destination = TMPDIR + "/anyway"
  }

  // tesseractコマンドを実行
  command := exec.Command(COMMAND, args.SourcePath, args.Destination)
  e := command.Run()
  if e != nil {
    panic(e)
  }

  // 出力を読む
  // tesseractの出力はコマンドラインの第二引数に.txtを付けたものに置かれる
  fn := args.Destination + OUTEXT
  f, _ := os.OpenFile(fn, 1, 1)
  buf, _ := ioutil.ReadFile(f.Name())
  out = string(buf)

  return out
}

/**
 * privateなメソッドってどうやって定義するんだ？
 */
func getTesseractVersion() string {
  command := exec.Command(COMMAND, "--version")
  var stderr bytes.Buffer
  command.Stderr = &stderr //謎に標準エラーで来るw
  e := command.Run()
  if e != nil {
    panic(e)
  }
  // なんかクズい
  tesseractInfo := strings.Split(stderr.String(), " ")[1]
  return strings.TrimRight(tesseractInfo, "\n")
}
/**
 * 利用可能な言語の一覧を取得する
 */
func getAvailableLanguages() []string {
  command := exec.Command(COMMAND, "--list-langs")
  var stderr bytes.Buffer
  command.Stderr = &stderr //謎に標準エラーで来るw
  e := command.Run()
  if e != nil {
    panic(e)
  }
  langs := strings.Split(stderr.String(), "\n")
  langs = langs[1:len(langs) - 1]
  return langs
}

/**
 * 汎用: コマンドを実行する
 */
func _exec(command string, args []string) string {
  cmd := _generateCommand(command, args)
  var stdout, stderr bytes.Buffer
  cmd.Stdout = &stdout
  cmd.Stderr = &stderr
  _ = cmd.Run()
  if stdout.String() != "" {
    return stdout.String()
  }
  return stderr.String()
}
/**
 * TODO#3: こんなラッパーメソッド作らんとアカンのクソじゃね？
 */
func _generateCommand(_command string, args []string) *exec.Cmd {
  if len(args) == 0 {
    return exec.Command(_command)
  }
  if len(args) == 1 {
    return exec.Command(_command, args[0])
  }
  if len(args) == 2 {
    return exec.Command(_command, args[0], args[1])
  }
  if len(args) == 3 {
    return exec.Command(_command, args[0], args[1], args[2])
  }
  if len(args) == 4 {
    return exec.Command(_command, args[0], args[1], args[2], args[3])
  }
  if len(args) == 5 {
    return exec.Command(_command, args[0], args[1], args[2], args[3], args[4])
  }
  return exec.Command(_command)
}
<|endoftext|>


<commit_before>package main

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

func createTempfile(content string) (*os.File, error) {
	tmp := os.TempDir()
	f, err := ioutil.TempFile(tmp, "migemogrep")
	if err != nil {
		return nil, err
	}
	_, err = f.Write([]byte(content))
	if err != nil {
		return nil, err
	}
	_, err = f.Seek(0, os.SEEK_SET)
	if err != nil {
		return nil, err
	}
	return f, nil
}

func TestEmpty(t *testing.T) {
	f, err := createTempfile(`
`)
	if err != nil {
		t.Fatal(err)
	}
	defer f.Close()

	opt := &grepOpt{
		optNumber:   true,
		optFilename: false,
	}

	buf := new(bytes.Buffer)
	out = buf
	defer func() {
		out = os.Stdout
	}()

	err = grep(f, regexp.MustCompile("^foo"), opt)
	if err != nil {
		t.Fatal(err)
	}

	if buf.Len() > 0 {
		t.Fatal("Should be empty")
	}
}

func TestHit(t *testing.T) {
	f, err := createTempfile(`
foobar
barbaz
`)
	if err != nil {
		t.Fatal(err)
	}
	defer f.Close()

	opt := &grepOpt{
		optNumber:   false,
		optFilename: false,
	}

	buf := new(bytes.Buffer)
	out = buf
	defer func() {
		out = os.Stdout
	}()

	err = grep(f, regexp.MustCompile("^foo"), opt)
	if err != nil {
		t.Fatal(err)
	}

	s := buf.String()
	if s != "foobar\n" {
		t.Fatalf("Should be %v but %v", `foobar`, s)
	}
}

func TestNumber(t *testing.T) {
	f, err := createTempfile(`
barbaz
foobar
`)
	if err != nil {
		t.Fatal(err)
	}
	defer f.Close()

	opt := &grepOpt{
		optNumber:   true,
		optFilename: false,
	}

	buf := new(bytes.Buffer)
	out = buf
	defer func() {
		out = os.Stdout
	}()

	err = grep(f, regexp.MustCompile("^foo"), opt)
	if err != nil {
		t.Fatal(err)
	}

	s := buf.String()
	if s != "2:foobar\n" {
		t.Fatalf("Should be %v but %v", `2:foobar`, s)
	}
}
<commit_msg>Fix test<commit_after>package main

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

func createTempfile(content string) (*os.File, error) {
	tmp := os.TempDir()
	f, err := ioutil.TempFile(tmp, "migemogrep")
	if err != nil {
		return nil, err
	}
	_, err = f.Write([]byte(content))
	if err != nil {
		return nil, err
	}
	_, err = f.Seek(0, os.SEEK_SET)
	if err != nil {
		return nil, err
	}
	return f, nil
}

func TestEmpty(t *testing.T) {
	f, err := createTempfile(`
`)
	if err != nil {
		t.Fatal(err)
	}
	defer f.Close()

	opt := &grepOpt{
		optNumber:   true,
		optFilename: false,
	}

	buf := new(bytes.Buffer)
	out = buf
	defer func() {
		out = os.Stdout
	}()

	err = grep(f, regexp.MustCompile("^foo"), opt)
	if err != nil {
		t.Fatal(err)
	}

	if buf.Len() > 0 {
		t.Fatal("Should be empty")
	}
}

func TestHit(t *testing.T) {
	f, err := createTempfile(`
foobar
barbaz
`)
	if err != nil {
		t.Fatal(err)
	}
	defer f.Close()

	opt := &grepOpt{
		optNumber:   false,
		optFilename: false,
	}

	buf := new(bytes.Buffer)
	out = buf
	defer func() {
		out = os.Stdout
	}()

	err = grep(f, regexp.MustCompile("^foo"), opt)
	if err != nil {
		t.Fatal(err)
	}

	s := buf.String()
	if s != "foobar\n" {
		t.Fatalf("Should be %v but %v", `foobar`, s)
	}
}

func TestNumber(t *testing.T) {
	f, err := createTempfile(`
barbaz
foobar
`)
	if err != nil {
		t.Fatal(err)
	}
	defer f.Close()

	opt := &grepOpt{
		optNumber:   true,
		optFilename: false,
	}

	buf := new(bytes.Buffer)
	out = buf
	defer func() {
		out = os.Stdout
	}()

	err = grep(f, regexp.MustCompile("^foo"), opt)
	if err != nil {
		t.Fatal(err)
	}

	s := buf.String()
	expect := "3:foobar\n"
	if s != expect {
		t.Fatalf("Should be %v but %v", expect, s)
	}
}
<|endoftext|>


<commit_before>package main

import "fmt"
import "flag"

var width = flag.Int("width", 10, "Horizontal width of the grid.")
var height = flag.Int("height", 10, "Vertical height of the grid.")

func main() {
	flag.Parse()

	point := Point{}
	point.x = *width
	point.y = *height
	fmt.Printf("Here is the point %v.\n", point)

	grid := Grid{}
	grid.Points = make([]Point, 100)

	v := 1
	h := 1
	for v <= *width {
		for h <= *height {
			tempPoint := Point{}
			tempPoint.x = h
			tempPoint.y = v
			h += 1
			fmt.Printf("Here is the point %v.\n", tempPoint)
		}
		v += 1
		h = 1
	}

}
<commit_msg>appending points to a Grid instance<commit_after>package main

import "fmt"
import "flag"

var width = flag.Int("width", 10, "Horizontal width of the grid.")
var height = flag.Int("height", 10, "Vertical height of the grid.")

func main() {
	flag.Parse()

	point := Point{}
	point.x = *width
	point.y = *height
	fmt.Printf("Here is the point %v.\n", point)

	grid := Grid{}
	// grid.Points = make([]Point, 100)

	v := 1
	h := 1
	for v <= *width {
		for h <= *height {
			tempPoint := Point{}
			tempPoint.x = h
			tempPoint.y = v
			h += 1
			grid.Points = append(grid.Points,tempPoint)
			fmt.Printf("Here is the point %v.\n", tempPoint)
		}
		v += 1
		h = 1
	}
	fmt.Printf("Num of Points %v.\n",len(grid.Points))

}
<|endoftext|>


<commit_before>package trace

import (
	"context"
	"math/rand"
	"net"
	"reflect"
	"time"

	"github.com/Sirupsen/logrus"
	"github.com/golang/protobuf/proto"
	"github.com/stripe/veneur/ssf"
)

func init() {
	rand.Seed(time.Now().Unix())
}

const traceKey = "trace"

// this should be set exactly once, at startup
var Service = ""

const localVeneurAddress = "127.0.0.1:8128"

type Trace struct {
	// the ID for the root span
	// which is also the ID for the trace itself
	TraceId int64

	// For the root span, this will be equal
	// to the TraceId
	SpanId int64

	// For the root span, this will be <= 0
	ParentId int64

	// The Resource should be the same for all spans in the same trace
	Resource string

	Start time.Time

	// If non-zero, the trace will be treated
	// as an error
	Status ssf.SSFSample_Status

	Tags []*ssf.SSFTag
}

// Record sends a trace to the (local) veneur instance,
// which will pass it on to the tracing agent running on the
// global veneur instance.
func (t *Trace) Record(name string, tags []*ssf.SSFTag) error {
	duration := time.Now().Sub(t.Start).Nanoseconds()

	t.Tags = append(t.Tags, tags...)

	sample := &ssf.SSFSample{
		Metric:    ssf.SSFSample_TRACE,
		Timestamp: t.Start.UnixNano(),
		Status:    t.Status,
		Name:      *proto.String(name),
		Trace: &ssf.SSFTrace{
			TraceId:  t.TraceId,
			Id:       t.SpanId,
			ParentId: t.ParentId,
		},
		Value:      duration,
		SampleRate: *proto.Float32(.10),
		Tags:       t.Tags,
		Resource:   t.Resource,
		Service:    Service,
	}

	err := sendSample(sample)
	if err != nil {
		logrus.WithError(err).Error("Error submitting sample")
	}
	return err
}

func (t *Trace) Error(err error) {
	t.Status = ssf.SSFSample_CRITICAL
	tags := []*ssf.SSFTag{
		{
			Name:  "error.msg",
			Value: err.Error(),
		},
		{
			Name:  "error.type",
			Value: reflect.TypeOf(err).Name(),
		},
		{
			Name:  "error.stack",
			Value: "",
		},
	}

	t.Tags = append(t.Tags, tags...)
}

// Attach attaches the current trace to the context
// and returns a copy of the context with that trace
// stored under the key "trace".
func (t *Trace) Attach(c context.Context) context.Context {
	return context.WithValue(c, traceKey, t)
}

// SpanFromContext is used to create a child span
// when the parent trace is in the context
func SpanFromContext(c context.Context) *Trace {
	parent, ok := c.Value(traceKey).(*Trace)
	if !ok {
		logrus.WithField("type", reflect.TypeOf(c.Value(traceKey))).Error("expected *Trace from context")
	}

	spanId := proto.Int64(rand.Int63())
	span := &Trace{
		TraceId:  parent.TraceId,
		SpanId:   *spanId,
		ParentId: parent.SpanId,
		Resource: parent.Resource,
		Start:    time.Now(),
	}

	return span
}

// StartTrace is called by to create the root-level span
// for a trace
func StartTrace(resource string) *Trace {
	traceId := proto.Int64(rand.Int63())

	t := &Trace{
		TraceId:  *traceId,
		SpanId:   *traceId,
		ParentId: 0,
		Resource: resource,
	}

	t.Start = time.Now()
	return t
}

// sendSample marshals the sample using protobuf and sends it
// over UDP to the local veneur instance
func sendSample(sample *ssf.SSFSample) error {
	server_addr, err := net.ResolveUDPAddr("udp", localVeneurAddress)
	if err != nil {
		return err
	}

	conn, err := net.DialUDP("udp", nil, server_addr)
	if err != nil {
		return err
	}

	defer conn.Close()

	data, err := proto.Marshal(sample)
	if err != nil {
		return err
	}

	_, err = conn.Write(data)
	if err != nil {
		return err
	}

	return nil
}
<commit_msg>Ensure that error.type is nonempty<commit_after>package trace

import (
	"context"
	"math/rand"
	"net"
	"reflect"
	"time"

	"github.com/Sirupsen/logrus"
	"github.com/golang/protobuf/proto"
	"github.com/stripe/veneur/ssf"
)

func init() {
	rand.Seed(time.Now().Unix())
}

const traceKey = "trace"

// this should be set exactly once, at startup
var Service = ""

const localVeneurAddress = "127.0.0.1:8128"

type Trace struct {
	// the ID for the root span
	// which is also the ID for the trace itself
	TraceId int64

	// For the root span, this will be equal
	// to the TraceId
	SpanId int64

	// For the root span, this will be <= 0
	ParentId int64

	// The Resource should be the same for all spans in the same trace
	Resource string

	Start time.Time

	// If non-zero, the trace will be treated
	// as an error
	Status ssf.SSFSample_Status

	Tags []*ssf.SSFTag
}

// Record sends a trace to the (local) veneur instance,
// which will pass it on to the tracing agent running on the
// global veneur instance.
func (t *Trace) Record(name string, tags []*ssf.SSFTag) error {
	duration := time.Now().Sub(t.Start).Nanoseconds()

	t.Tags = append(t.Tags, tags...)

	sample := &ssf.SSFSample{
		Metric:    ssf.SSFSample_TRACE,
		Timestamp: t.Start.UnixNano(),
		Status:    t.Status,
		Name:      *proto.String(name),
		Trace: &ssf.SSFTrace{
			TraceId:  t.TraceId,
			Id:       t.SpanId,
			ParentId: t.ParentId,
		},
		Value:      duration,
		SampleRate: *proto.Float32(.10),
		Tags:       t.Tags,
		Resource:   t.Resource,
		Service:    Service,
	}

	err := sendSample(sample)
	if err != nil {
		logrus.WithError(err).Error("Error submitting sample")
	}
	return err
}

func (t *Trace) Error(err error) {
	t.Status = ssf.SSFSample_CRITICAL

	errorType := reflect.TypeOf(err).Name()
	if errorType == "" {
		errorType = "error"
	}

	tags := []*ssf.SSFTag{
		{
			Name:  "error.msg",
			Value: err.Error(),
		},
		{
			Name:  "error.type",
			Value: errorType,
		},
		{
			Name:  "error.stack",
			Value: err.Error(),
		},
	}

	t.Tags = append(t.Tags, tags...)
}

// Attach attaches the current trace to the context
// and returns a copy of the context with that trace
// stored under the key "trace".
func (t *Trace) Attach(c context.Context) context.Context {
	return context.WithValue(c, traceKey, t)
}

// SpanFromContext is used to create a child span
// when the parent trace is in the context
func SpanFromContext(c context.Context) *Trace {
	parent, ok := c.Value(traceKey).(*Trace)
	if !ok {
		logrus.WithField("type", reflect.TypeOf(c.Value(traceKey))).Error("expected *Trace from context")
	}

	spanId := proto.Int64(rand.Int63())
	span := &Trace{
		TraceId:  parent.TraceId,
		SpanId:   *spanId,
		ParentId: parent.SpanId,
		Resource: parent.Resource,
		Start:    time.Now(),
	}

	return span
}

// StartTrace is called by to create the root-level span
// for a trace
func StartTrace(resource string) *Trace {
	traceId := proto.Int64(rand.Int63())

	t := &Trace{
		TraceId:  *traceId,
		SpanId:   *traceId,
		ParentId: 0,
		Resource: resource,
	}

	t.Start = time.Now()
	return t
}

// sendSample marshals the sample using protobuf and sends it
// over UDP to the local veneur instance
func sendSample(sample *ssf.SSFSample) error {
	server_addr, err := net.ResolveUDPAddr("udp", localVeneurAddress)
	if err != nil {
		return err
	}

	conn, err := net.DialUDP("udp", nil, server_addr)
	if err != nil {
		return err
	}

	defer conn.Close()

	data, err := proto.Marshal(sample)
	if err != nil {
		return err
	}

	_, err = conn.Write(data)
	if err != nil {
		return err
	}

	return nil
}
<|endoftext|>


<commit_before>package tvapi

import (
	"fmt"
	"net"
	"strings"
	"time"
)

// Pull out the characters up to the first \r
func parseResult(resultstring []byte) string {
	parsed := strings.Split(string(resultstring), "\r")
	return parsed[0]
}

// Send transmits Sharp Aquos API commands to the Television over the network
func Send(sharpCommand string, sharpParameter string, ip string, port string) string {
	cmdString := fmt.Sprintf("%4s%-4s\r", sharpCommand, sharpParameter)

	connectString := fmt.Sprintf("%s:%s", ip, port)
	conn, err := net.DialTimeout("tcp", connectString, time.Duration(10*time.Millisecond))

	if err != nil {
		fmt.Println("Error connecting to TV.")
		return ("Error connecting to TV")
	}

	fmt.Fprintf(conn, cmdString)
	if err != nil {
		fmt.Println("An error occured.")
		fmt.Println(err.Error())
	}

	apiResult := make([]byte, 32)
	bytesRead, err := conn.Read(apiResult)
	if err != nil {
		fmt.Println(err.Error())
		fmt.Printf("Only red in %d bytes:", bytesRead)

	} else {
		resultString := parseResult(apiResult)
		conn.Close()
		return resultString
	}

	return "no result"
}
<commit_msg>Fixed typo in error message.<commit_after>package tvapi

import (
	"fmt"
	"net"
	"strings"
	"time"
)

// Pull out the characters up to the first \r
func parseResult(resultstring []byte) string {
	parsed := strings.Split(string(resultstring), "\r")
	return parsed[0]
}

// Send transmits Sharp Aquos API commands to the Television over the network
func Send(sharpCommand string, sharpParameter string, ip string, port string) string {
	cmdString := fmt.Sprintf("%4s%-4s\r", sharpCommand, sharpParameter)

	connectString := fmt.Sprintf("%s:%s", ip, port)
	conn, err := net.DialTimeout("tcp", connectString, time.Duration(10*time.Millisecond))

	if err != nil {
		fmt.Println("Error connecting to TV.")
		return ("Error connecting to TV")
	}

	fmt.Fprintf(conn, cmdString)
	if err != nil {
		fmt.Println("An error occured.")
		fmt.Println(err.Error())
	}

	apiResult := make([]byte, 32)
	bytesRead, err := conn.Read(apiResult)
	if err != nil {
		fmt.Println(err.Error())
		fmt.Printf("Only read in %d bytes:", bytesRead)

	} else {
		resultString := parseResult(apiResult)
		conn.Close()
		return resultString
	}

	return "no result"
}
<|endoftext|>


<commit_before>package types

import (
	"os"
	"time"

	"github.com/docker/engine-api/types/container"
	"github.com/docker/engine-api/types/network"
	"github.com/docker/engine-api/types/registry"
	"github.com/docker/go-connections/nat"
)

// ContainerCreateResponse contains the information returned to a client on the
// creation of a new container.
type ContainerCreateResponse struct {
	// ID is the ID of the created container.
	ID string `json:"Id"`

	// Warnings are any warnings encountered during the creation of the container.
	Warnings []string `json:"Warnings"`
}

// ContainerExecCreateResponse contains response of Remote API:
// POST "/containers/{name:.*}/exec"
type ContainerExecCreateResponse struct {
	// ID is the exec ID.
	ID string `json:"Id"`
}

// ContainerUpdateResponse contains response of Remote API:
// POST /containers/{name:.*}/update
type ContainerUpdateResponse struct {
	// Warnings are any warnings encountered during the updating of the container.
	Warnings []string `json:"Warnings"`
}

// AuthResponse contains response of Remote API:
// POST "/auth"
type AuthResponse struct {
	// Status is the authentication status
	Status string `json:"Status"`
}

// ContainerWaitResponse contains response of Remote API:
// POST "/containers/"+containerID+"/wait"
type ContainerWaitResponse struct {
	// StatusCode is the status code of the wait job
	StatusCode int `json:"StatusCode"`
}

// ContainerCommitResponse contains response of Remote API:
// POST "/commit?container="+containerID
type ContainerCommitResponse struct {
	ID string `json:"Id"`
}

// ContainerChange contains response of Remote API:
// GET "/containers/{name:.*}/changes"
type ContainerChange struct {
	Kind int
	Path string
}

// ImageHistory contains response of Remote API:
// GET "/images/{name:.*}/history"
type ImageHistory struct {
	ID        string `json:"Id"`
	Created   int64
	CreatedBy string
	Tags      []string
	Size      int64
	Comment   string
}

// ImageDelete contains response of Remote API:
// DELETE "/images/{name:.*}"
type ImageDelete struct {
	Untagged string `json:",omitempty"`
	Deleted  string `json:",omitempty"`
}

// Image contains response of Remote API:
// GET "/images/json"
type Image struct {
	ID          string `json:"Id"`
	ParentID    string `json:"ParentId"`
	RepoTags    []string
	RepoDigests []string
	Created     int64
	Size        int64
	VirtualSize int64
	Labels      map[string]string
}

// GraphDriverData returns Image's graph driver config info
// when calling inspect command
type GraphDriverData struct {
	Name string
	Data map[string]string
}

// ImageInspect contains response of Remote API:
// GET "/images/{name:.*}/json"
type ImageInspect struct {
	ID              string `json:"Id"`
	RepoTags        []string
	RepoDigests     []string
	Parent          string
	Comment         string
	Created         string
	Container       string
	ContainerConfig *container.Config
	DockerVersion   string
	Author          string
	Config          *container.Config
	Architecture    string
	Os              string
	Size            int64
	VirtualSize     int64
	GraphDriver     GraphDriverData
}

// Port stores open ports info of container
// e.g. {"PrivatePort": 8080, "PublicPort": 80, "Type": "tcp"}
type Port struct {
	IP          string `json:",omitempty"`
	PrivatePort int
	PublicPort  int `json:",omitempty"`
	Type        string
}

// Container contains response of Remote API:
// GET  "/containers/json"
type Container struct {
	ID         string `json:"Id"`
	Names      []string
	Image      string
	ImageID    string
	Command    string
	Created    int64
	Ports      []Port
	SizeRw     int64 `json:",omitempty"`
	SizeRootFs int64 `json:",omitempty"`
	Labels     map[string]string
	State      string
	Status     string
	HostConfig struct {
		NetworkMode string `json:",omitempty"`
	}
	NetworkSettings *SummaryNetworkSettings
}

// CopyConfig contains request body of Remote API:
// POST "/containers/"+containerID+"/copy"
type CopyConfig struct {
	Resource string
}

// ContainerPathStat is used to encode the header from
// GET "/containers/{name:.*}/archive"
// "Name" is the file or directory name.
type ContainerPathStat struct {
	Name       string      `json:"name"`
	Size       int64       `json:"size"`
	Mode       os.FileMode `json:"mode"`
	Mtime      time.Time   `json:"mtime"`
	LinkTarget string      `json:"linkTarget"`
}

// ContainerProcessList contains response of Remote API:
// GET "/containers/{name:.*}/top"
type ContainerProcessList struct {
	Processes [][]string
	Titles    []string
}

// Version contains response of Remote API:
// GET "/version"
type Version struct {
	Version       string
	APIVersion    string `json:"ApiVersion"`
	GitCommit     string
	GoVersion     string
	Os            string
	Arch          string
	KernelVersion string `json:",omitempty"`
	Experimental  bool   `json:",omitempty"`
	BuildTime     string `json:",omitempty"`
}

// Info contains response of Remote API:
// GET "/info"
type Info struct {
	ID                 string
	Containers         int
	ContainersRunning  int
	ContainersPaused   int
	ContainersStopped  int
	Images             int
	Driver             string
	DriverStatus       [][2]string
	SystemStatus       [][2]string
	Plugins            PluginsInfo
	MemoryLimit        bool
	SwapLimit          bool
	CPUCfsPeriod       bool `json:"CpuCfsPeriod"`
	CPUCfsQuota        bool `json:"CpuCfsQuota"`
	CPUShares          bool
	CPUSet             bool
	IPv4Forwarding     bool
	BridgeNfIptables   bool
	BridgeNfIP6tables  bool `json:"BridgeNfIp6tables"`
	Debug              bool
	NFd                int
	OomKillDisable     bool
	NGoroutines        int
	SystemTime         string
	ExecutionDriver    string
	LoggingDriver      string
	NEventsListener    int
	KernelVersion      string
	OperatingSystem    string
	OSType             string
	Architecture       string
	IndexServerAddress string
	RegistryConfig     *registry.ServiceConfig
	NCPU               int
	MemTotal           int64
	DockerRootDir      string
	HTTPProxy          string `json:"HttpProxy"`
	HTTPSProxy         string `json:"HttpsProxy"`
	NoProxy            string
	Name               string
	Labels             []string
	ExperimentalBuild  bool
	ServerVersion      string
	ClusterStore       string
	ClusterAdvertise   string
}

// PluginsInfo is a temp struct holding Plugins name
// registered with docker daemon. It is used by Info struct
type PluginsInfo struct {
	// List of Volume plugins registered
	Volume []string
	// List of Network plugins registered
	Network []string
	// List of Authorization plugins registered
	Authorization []string
}

// ExecStartCheck is a temp struct used by execStart
// Config fields is part of ExecConfig in runconfig package
type ExecStartCheck struct {
	// ExecStart will first check if it's detached
	Detach bool
	// Check if there's a tty
	Tty bool
}

// ContainerState stores container's running state
// it's part of ContainerJSONBase and will return by "inspect" command
type ContainerState struct {
	Status     string
	Running    bool
	Paused     bool
	Restarting bool
	OOMKilled  bool
	Dead       bool
	Pid        int
	ExitCode   int
	Error      string
	StartedAt  string
	FinishedAt string
}

// ContainerJSONBase contains response of Remote API:
// GET "/containers/{name:.*}/json"
type ContainerJSONBase struct {
	ID              string `json:"Id"`
	Created         string
	Path            string
	Args            []string
	State           *ContainerState
	Image           string
	ResolvConfPath  string
	HostnamePath    string
	HostsPath       string
	LogPath         string
	Name            string
	RestartCount    int
	Driver          string
	MountLabel      string
	ProcessLabel    string
	AppArmorProfile string
	ExecIDs         []string
	HostConfig      *container.HostConfig
	GraphDriver     GraphDriverData
	SizeRw          *int64 `json:",omitempty"`
	SizeRootFs      *int64 `json:",omitempty"`
}

// ContainerJSON is newly used struct along with MountPoint
type ContainerJSON struct {
	*ContainerJSONBase
	Mounts          []MountPoint
	Config          *container.Config
	NetworkSettings *NetworkSettings
}

// NetworkSettings exposes the network settings in the api
type NetworkSettings struct {
	NetworkSettingsBase
	DefaultNetworkSettings
	Networks map[string]*network.EndpointSettings
}

// SummaryNetworkSettings provides a summary of container's networks
// in /containers/json
type SummaryNetworkSettings struct {
	Networks map[string]*network.EndpointSettings
}

// NetworkSettingsBase holds basic information about networks
type NetworkSettingsBase struct {
	Bridge                 string
	SandboxID              string
	HairpinMode            bool
	LinkLocalIPv6Address   string
	LinkLocalIPv6PrefixLen int
	Ports                  nat.PortMap
	SandboxKey             string
	SecondaryIPAddresses   []network.Address
	SecondaryIPv6Addresses []network.Address
}

// DefaultNetworkSettings holds network information
// during the 2 release deprecation period.
// It will be removed in Docker 1.11.
type DefaultNetworkSettings struct {
	EndpointID          string
	Gateway             string
	GlobalIPv6Address   string
	GlobalIPv6PrefixLen int
	IPAddress           string
	IPPrefixLen         int
	IPv6Gateway         string
	MacAddress          string
}

// MountPoint represents a mount point configuration inside the container.
type MountPoint struct {
	Name        string `json:",omitempty"`
	Source      string
	Destination string
	Driver      string `json:",omitempty"`
	Mode        string
	RW          bool
	Propagation string
}

// Volume represents the configuration of a volume for the remote API
type Volume struct {
	Name       string // Name is the name of the volume
	Driver     string // Driver is the Driver name used to create the volume
	Mountpoint string // Mountpoint is the location on disk of the volume
}

// VolumesListResponse contains the response for the remote API:
// GET "/volumes"
type VolumesListResponse struct {
	Volumes  []*Volume // Volumes is the list of volumes being returned
	Warnings []string  // Warnings is a list of warnings that occurred when getting the list from the volume drivers
}

// VolumeCreateRequest contains the response for the remote API:
// POST "/volumes/create"
type VolumeCreateRequest struct {
	Name       string            // Name is the requested name of the volume
	Driver     string            // Driver is the name of the driver that should be used to create the volume
	DriverOpts map[string]string // DriverOpts holds the driver specific options to use for when creating the volume.
}

// NetworkResource is the body of the "get network" http response message
type NetworkResource struct {
	Name       string
	ID         string `json:"Id"`
	Scope      string
	Driver     string
	EnableIPv6 bool
	IPAM       network.IPAM
	Internal   bool
	Containers map[string]EndpointResource
	Options    map[string]string
}

// EndpointResource contains network resources allocated and used for a container in a network
type EndpointResource struct {
	Name        string
	EndpointID  string
	MacAddress  string
	IPv4Address string
	IPv6Address string
}

// NetworkCreate is the expected body of the "create network" http request message
type NetworkCreate struct {
	Name           string
	CheckDuplicate bool
	Driver         string
	EnableIPv6     bool
	IPAM           network.IPAM
	Internal       bool
	Options        map[string]string
}

// NetworkCreateResponse is the response message sent by the server for network create call
type NetworkCreateResponse struct {
	ID      string `json:"Id"`
	Warning string
}

// NetworkConnect represents the data to be used to connect a container to the network
type NetworkConnect struct {
	Container      string
	EndpointConfig *network.EndpointSettings `json:",omitempty"`
}

// NetworkDisconnect represents the data to be used to disconnect a container from the network
type NetworkDisconnect struct {
	Container string
	Force     bool
}
<commit_msg>Add cgroupDriver to Info<commit_after>package types

import (
	"os"
	"time"

	"github.com/docker/engine-api/types/container"
	"github.com/docker/engine-api/types/network"
	"github.com/docker/engine-api/types/registry"
	"github.com/docker/go-connections/nat"
)

// ContainerCreateResponse contains the information returned to a client on the
// creation of a new container.
type ContainerCreateResponse struct {
	// ID is the ID of the created container.
	ID string `json:"Id"`

	// Warnings are any warnings encountered during the creation of the container.
	Warnings []string `json:"Warnings"`
}

// ContainerExecCreateResponse contains response of Remote API:
// POST "/containers/{name:.*}/exec"
type ContainerExecCreateResponse struct {
	// ID is the exec ID.
	ID string `json:"Id"`
}

// ContainerUpdateResponse contains response of Remote API:
// POST /containers/{name:.*}/update
type ContainerUpdateResponse struct {
	// Warnings are any warnings encountered during the updating of the container.
	Warnings []string `json:"Warnings"`
}

// AuthResponse contains response of Remote API:
// POST "/auth"
type AuthResponse struct {
	// Status is the authentication status
	Status string `json:"Status"`
}

// ContainerWaitResponse contains response of Remote API:
// POST "/containers/"+containerID+"/wait"
type ContainerWaitResponse struct {
	// StatusCode is the status code of the wait job
	StatusCode int `json:"StatusCode"`
}

// ContainerCommitResponse contains response of Remote API:
// POST "/commit?container="+containerID
type ContainerCommitResponse struct {
	ID string `json:"Id"`
}

// ContainerChange contains response of Remote API:
// GET "/containers/{name:.*}/changes"
type ContainerChange struct {
	Kind int
	Path string
}

// ImageHistory contains response of Remote API:
// GET "/images/{name:.*}/history"
type ImageHistory struct {
	ID        string `json:"Id"`
	Created   int64
	CreatedBy string
	Tags      []string
	Size      int64
	Comment   string
}

// ImageDelete contains response of Remote API:
// DELETE "/images/{name:.*}"
type ImageDelete struct {
	Untagged string `json:",omitempty"`
	Deleted  string `json:",omitempty"`
}

// Image contains response of Remote API:
// GET "/images/json"
type Image struct {
	ID          string `json:"Id"`
	ParentID    string `json:"ParentId"`
	RepoTags    []string
	RepoDigests []string
	Created     int64
	Size        int64
	VirtualSize int64
	Labels      map[string]string
}

// GraphDriverData returns Image's graph driver config info
// when calling inspect command
type GraphDriverData struct {
	Name string
	Data map[string]string
}

// ImageInspect contains response of Remote API:
// GET "/images/{name:.*}/json"
type ImageInspect struct {
	ID              string `json:"Id"`
	RepoTags        []string
	RepoDigests     []string
	Parent          string
	Comment         string
	Created         string
	Container       string
	ContainerConfig *container.Config
	DockerVersion   string
	Author          string
	Config          *container.Config
	Architecture    string
	Os              string
	Size            int64
	VirtualSize     int64
	GraphDriver     GraphDriverData
}

// Port stores open ports info of container
// e.g. {"PrivatePort": 8080, "PublicPort": 80, "Type": "tcp"}
type Port struct {
	IP          string `json:",omitempty"`
	PrivatePort int
	PublicPort  int `json:",omitempty"`
	Type        string
}

// Container contains response of Remote API:
// GET  "/containers/json"
type Container struct {
	ID         string `json:"Id"`
	Names      []string
	Image      string
	ImageID    string
	Command    string
	Created    int64
	Ports      []Port
	SizeRw     int64 `json:",omitempty"`
	SizeRootFs int64 `json:",omitempty"`
	Labels     map[string]string
	State      string
	Status     string
	HostConfig struct {
		NetworkMode string `json:",omitempty"`
	}
	NetworkSettings *SummaryNetworkSettings
}

// CopyConfig contains request body of Remote API:
// POST "/containers/"+containerID+"/copy"
type CopyConfig struct {
	Resource string
}

// ContainerPathStat is used to encode the header from
// GET "/containers/{name:.*}/archive"
// "Name" is the file or directory name.
type ContainerPathStat struct {
	Name       string      `json:"name"`
	Size       int64       `json:"size"`
	Mode       os.FileMode `json:"mode"`
	Mtime      time.Time   `json:"mtime"`
	LinkTarget string      `json:"linkTarget"`
}

// ContainerProcessList contains response of Remote API:
// GET "/containers/{name:.*}/top"
type ContainerProcessList struct {
	Processes [][]string
	Titles    []string
}

// Version contains response of Remote API:
// GET "/version"
type Version struct {
	Version       string
	APIVersion    string `json:"ApiVersion"`
	GitCommit     string
	GoVersion     string
	Os            string
	Arch          string
	KernelVersion string `json:",omitempty"`
	Experimental  bool   `json:",omitempty"`
	BuildTime     string `json:",omitempty"`
}

// Info contains response of Remote API:
// GET "/info"
type Info struct {
	ID                 string
	Containers         int
	ContainersRunning  int
	ContainersPaused   int
	ContainersStopped  int
	Images             int
	Driver             string
	DriverStatus       [][2]string
	SystemStatus       [][2]string
	Plugins            PluginsInfo
	MemoryLimit        bool
	SwapLimit          bool
	CPUCfsPeriod       bool `json:"CpuCfsPeriod"`
	CPUCfsQuota        bool `json:"CpuCfsQuota"`
	CPUShares          bool
	CPUSet             bool
	IPv4Forwarding     bool
	BridgeNfIptables   bool
	BridgeNfIP6tables  bool `json:"BridgeNfIp6tables"`
	Debug              bool
	NFd                int
	OomKillDisable     bool
	NGoroutines        int
	SystemTime         string
	ExecutionDriver    string
	LoggingDriver      string
	CgroupDriver       string
	NEventsListener    int
	KernelVersion      string
	OperatingSystem    string
	OSType             string
	Architecture       string
	IndexServerAddress string
	RegistryConfig     *registry.ServiceConfig
	NCPU               int
	MemTotal           int64
	DockerRootDir      string
	HTTPProxy          string `json:"HttpProxy"`
	HTTPSProxy         string `json:"HttpsProxy"`
	NoProxy            string
	Name               string
	Labels             []string
	ExperimentalBuild  bool
	ServerVersion      string
	ClusterStore       string
	ClusterAdvertise   string
}

// PluginsInfo is a temp struct holding Plugins name
// registered with docker daemon. It is used by Info struct
type PluginsInfo struct {
	// List of Volume plugins registered
	Volume []string
	// List of Network plugins registered
	Network []string
	// List of Authorization plugins registered
	Authorization []string
}

// ExecStartCheck is a temp struct used by execStart
// Config fields is part of ExecConfig in runconfig package
type ExecStartCheck struct {
	// ExecStart will first check if it's detached
	Detach bool
	// Check if there's a tty
	Tty bool
}

// ContainerState stores container's running state
// it's part of ContainerJSONBase and will return by "inspect" command
type ContainerState struct {
	Status     string
	Running    bool
	Paused     bool
	Restarting bool
	OOMKilled  bool
	Dead       bool
	Pid        int
	ExitCode   int
	Error      string
	StartedAt  string
	FinishedAt string
}

// ContainerJSONBase contains response of Remote API:
// GET "/containers/{name:.*}/json"
type ContainerJSONBase struct {
	ID              string `json:"Id"`
	Created         string
	Path            string
	Args            []string
	State           *ContainerState
	Image           string
	ResolvConfPath  string
	HostnamePath    string
	HostsPath       string
	LogPath         string
	Name            string
	RestartCount    int
	Driver          string
	MountLabel      string
	ProcessLabel    string
	AppArmorProfile string
	ExecIDs         []string
	HostConfig      *container.HostConfig
	GraphDriver     GraphDriverData
	SizeRw          *int64 `json:",omitempty"`
	SizeRootFs      *int64 `json:",omitempty"`
}

// ContainerJSON is newly used struct along with MountPoint
type ContainerJSON struct {
	*ContainerJSONBase
	Mounts          []MountPoint
	Config          *container.Config
	NetworkSettings *NetworkSettings
}

// NetworkSettings exposes the network settings in the api
type NetworkSettings struct {
	NetworkSettingsBase
	DefaultNetworkSettings
	Networks map[string]*network.EndpointSettings
}

// SummaryNetworkSettings provides a summary of container's networks
// in /containers/json
type SummaryNetworkSettings struct {
	Networks map[string]*network.EndpointSettings
}

// NetworkSettingsBase holds basic information about networks
type NetworkSettingsBase struct {
	Bridge                 string
	SandboxID              string
	HairpinMode            bool
	LinkLocalIPv6Address   string
	LinkLocalIPv6PrefixLen int
	Ports                  nat.PortMap
	SandboxKey             string
	SecondaryIPAddresses   []network.Address
	SecondaryIPv6Addresses []network.Address
}

// DefaultNetworkSettings holds network information
// during the 2 release deprecation period.
// It will be removed in Docker 1.11.
type DefaultNetworkSettings struct {
	EndpointID          string
	Gateway             string
	GlobalIPv6Address   string
	GlobalIPv6PrefixLen int
	IPAddress           string
	IPPrefixLen         int
	IPv6Gateway         string
	MacAddress          string
}

// MountPoint represents a mount point configuration inside the container.
type MountPoint struct {
	Name        string `json:",omitempty"`
	Source      string
	Destination string
	Driver      string `json:",omitempty"`
	Mode        string
	RW          bool
	Propagation string
}

// Volume represents the configuration of a volume for the remote API
type Volume struct {
	Name       string // Name is the name of the volume
	Driver     string // Driver is the Driver name used to create the volume
	Mountpoint string // Mountpoint is the location on disk of the volume
}

// VolumesListResponse contains the response for the remote API:
// GET "/volumes"
type VolumesListResponse struct {
	Volumes  []*Volume // Volumes is the list of volumes being returned
	Warnings []string  // Warnings is a list of warnings that occurred when getting the list from the volume drivers
}

// VolumeCreateRequest contains the response for the remote API:
// POST "/volumes/create"
type VolumeCreateRequest struct {
	Name       string            // Name is the requested name of the volume
	Driver     string            // Driver is the name of the driver that should be used to create the volume
	DriverOpts map[string]string // DriverOpts holds the driver specific options to use for when creating the volume.
}

// NetworkResource is the body of the "get network" http response message
type NetworkResource struct {
	Name       string
	ID         string `json:"Id"`
	Scope      string
	Driver     string
	EnableIPv6 bool
	IPAM       network.IPAM
	Internal   bool
	Containers map[string]EndpointResource
	Options    map[string]string
}

// EndpointResource contains network resources allocated and used for a container in a network
type EndpointResource struct {
	Name        string
	EndpointID  string
	MacAddress  string
	IPv4Address string
	IPv6Address string
}

// NetworkCreate is the expected body of the "create network" http request message
type NetworkCreate struct {
	Name           string
	CheckDuplicate bool
	Driver         string
	EnableIPv6     bool
	IPAM           network.IPAM
	Internal       bool
	Options        map[string]string
}

// NetworkCreateResponse is the response message sent by the server for network create call
type NetworkCreateResponse struct {
	ID      string `json:"Id"`
	Warning string
}

// NetworkConnect represents the data to be used to connect a container to the network
type NetworkConnect struct {
	Container      string
	EndpointConfig *network.EndpointSettings `json:",omitempty"`
}

// NetworkDisconnect represents the data to be used to disconnect a container from the network
type NetworkDisconnect struct {
	Container string
	Force     bool
}
<|endoftext|>


<commit_before>package cast

import (
	"math"

	"testing"
)

func TestUint32FromUint8(t *testing.T) {

	tests := []struct{
		Value uint8
	}{
		{
			Value: 0,
		},
		{
			Value: 1,
		},
		{
			Value: math.MaxUint8,
		},
	}

	{
		const numRand = 20
		for i:=0; i<numRand; i++ {
			test := struct{
				Value uint8
			}{
				Value: uint8(randomness.Int63n(math.MaxUint8)),
			}
			tests = append(tests, test)
		}
	}

	for testNumber, test := range tests {

		x, err := Uint32(test.Value)
		if nil != err {
			t.Errorf("For test #%d, did not expect an error, but actually got one: (%T) %v", testNumber, err, err)
			continue
		}

		y := uint8(x)

		if expected, actual := test.Value, y; expected != actual {
			t.Errorf("For test #%d, expected %v, but actually got %v.", testNumber, expected, actual)
			continue
		}
	}
}

func TestUint32FromUint16(t *testing.T) {

	tests := []struct{
		Value uint16
	}{
		{
			Value: 0,
		},
		{
			Value: 1,
		},
		{
			Value: math.MaxUint16,
		},
	}

	{
		const numRand = 20
		for i:=0; i<numRand; i++ {
			test := struct{
				Value uint16
			}{
				Value: uint16(randomness.Int63n(math.MaxUint16)),
			}
			tests = append(tests, test)
		}
	}

	for testNumber, test := range tests {

		x, err := Uint32(test.Value)
		if nil != err {
			t.Errorf("For test #%d, did not expect an error, but actually got one: (%T) %v", testNumber, err, err)
			continue
		}

		y := uint16(x)

		if expected, actual := test.Value, y; expected != actual {
			t.Errorf("For test #%d, expected %v, but actually got %v.", testNumber, expected, actual)
			continue
		}
	}
}

func TestUint32FromUint32(t *testing.T) {

	tests := []struct{
		Value uint32
	}{
		{
			Value: 0,
		},
		{
			Value: 1,
		},
		{
			Value: math.MaxUint32,
		},
	}

	{
		const numRand = 20
		for i:=0; i<numRand; i++ {
			test := struct{
				Value uint32
			}{
				Value: uint32(randomness.Int63n(math.MaxUint32)),
			}
			tests = append(tests, test)
		}
	}

	for testNumber, test := range tests {

		x, err := Uint32(test.Value)
		if nil != err {
			t.Errorf("For test #%d, did not expect an error, but actually got one: (%T) %v", testNumber, err, err)
			continue
		}

		y := uint32(x)

		if expected, actual := test.Value, y; expected != actual {
			t.Errorf("For test #%d, expected %v, but actually got %v.", testNumber, expected, actual)
			continue
		}
	}
}
<commit_msg>cosmetic change. moved some tests in file.<commit_after>package cast

import (
	"math"

	"testing"
)

func TestUint32FromUint32(t *testing.T) {

	tests := []struct{
		Value uint32
	}{
		{
			Value: 0,
		},
		{
			Value: 1,
		},
		{
			Value: math.MaxUint32,
		},
	}

	{
		const numRand = 20
		for i:=0; i<numRand; i++ {
			test := struct{
				Value uint32
			}{
				Value: uint32(randomness.Int63n(math.MaxUint32)),
			}
			tests = append(tests, test)
		}
	}

	for testNumber, test := range tests {

		x, err := Uint32(test.Value)
		if nil != err {
			t.Errorf("For test #%d, did not expect an error, but actually got one: (%T) %v", testNumber, err, err)
			continue
		}

		y := uint32(x)

		if expected, actual := test.Value, y; expected != actual {
			t.Errorf("For test #%d, expected %v, but actually got %v.", testNumber, expected, actual)
			continue
		}
	}
}

func TestUint32FromUint16(t *testing.T) {

	tests := []struct{
		Value uint16
	}{
		{
			Value: 0,
		},
		{
			Value: 1,
		},
		{
			Value: math.MaxUint16,
		},
	}

	{
		const numRand = 20
		for i:=0; i<numRand; i++ {
			test := struct{
				Value uint16
			}{
				Value: uint16(randomness.Int63n(math.MaxUint16)),
			}
			tests = append(tests, test)
		}
	}

	for testNumber, test := range tests {

		x, err := Uint32(test.Value)
		if nil != err {
			t.Errorf("For test #%d, did not expect an error, but actually got one: (%T) %v", testNumber, err, err)
			continue
		}

		y := uint16(x)

		if expected, actual := test.Value, y; expected != actual {
			t.Errorf("For test #%d, expected %v, but actually got %v.", testNumber, expected, actual)
			continue
		}
	}
}

func TestUint32FromUint8(t *testing.T) {

	tests := []struct{
		Value uint8
	}{
		{
			Value: 0,
		},
		{
			Value: 1,
		},
		{
			Value: math.MaxUint8,
		},
	}

	{
		const numRand = 20
		for i:=0; i<numRand; i++ {
			test := struct{
				Value uint8
			}{
				Value: uint8(randomness.Int63n(math.MaxUint8)),
			}
			tests = append(tests, test)
		}
	}

	for testNumber, test := range tests {

		x, err := Uint32(test.Value)
		if nil != err {
			t.Errorf("For test #%d, did not expect an error, but actually got one: (%T) %v", testNumber, err, err)
			continue
		}

		y := uint8(x)

		if expected, actual := test.Value, y; expected != actual {
			t.Errorf("For test #%d, expected %v, but actually got %v.", testNumber, expected, actual)
			continue
		}
	}
}
<|endoftext|>


<commit_before>package phpobject

import (
	"errors"
	"fmt"
	"io"
	"strings"
)

func unserializaNil(r io.Reader) (ret PValue, err error) {
	var s string
	fmt.Fscanf(r, "%1s", &s)
	if s == ";" {
		return PNil, nil
	}
	return PNil, errors.New("Unserialize Nil fail")
}

func unserializeBool(r io.Reader) (ret PBool, err error) {
	var i int
	if n, nerr := fmt.Fscanf(r, ":%1d;", &i); nerr == nil && n == 1 {
		return PBool(i != 0), nil
	}
	return PFalse, errors.New("Unserialize Bool fail")
}

func unserializeLong(r io.Reader) (ret PLong, err error) {
	var i int
	if n, nerr := fmt.Fscanf(r, ":%d;", &i); nerr == nil && n == 1 {
		return PLong(i), nil
	}
	return 0, errors.New("Unserialize Long fail")
}

func unserializeDouble(r io.Reader) (ret PDouble, err error) {
	var d float64
	if n, nerr := fmt.Fscanf(r, ":%f;", &d); nerr == nil && n == 1 {
		return PDouble(d), nil
	}
	return 0, errors.New("Unserialize Double fail")
}

func unserializeString(r io.Reader) (ret PString, err error) {
	var l int
	if ln, lerr := fmt.Fscanf(r, ":%d:\"", &l); lerr == nil && ln == 1 {
		buf := make([]byte, l+2)
		if _, berr := io.ReadFull(r, buf); berr == nil && buf[l-1] == '"' && buf[l] == ';' {
			return PString(buf[:l-1]), nil
		}
	}
	return "", errors.New("Unserialize String fail")
}

func unserializeKey(r io.Reader, isstr bool) (ret string, err error) {
	if isstr {
		var l int
		if ln, lerr := fmt.Fscanf(r, ":%d:\"", &l); lerr == nil && ln == 1 {
			buf := make([]byte, l+2)
			if _, berr := io.ReadFull(r, buf); berr == nil && buf[l-1] == '"' && buf[l] == ';' {
				return string(buf[:l-1]), nil
			}
		}
	} else {
		var s string
		if ln, lerr := fmt.Fscanf(r, ":%[^;];", &s); lerr == nil && ln == 1 {
			return s, nil
		}
	}
	return "", errors.New("Unserialize Key fail")
}

func unserializeArray(r io.Reader) (ret *PArray, err error) {
	var l int
	if ln, lerr := fmt.Fscanf(r, ":%d:{", &l); lerr == nil && ln == 1 {
		array := NewArray()
		for i := 0; i < l; i++ {
			var s string
			fmt.Fscanf(r, "%1s", &s)
			key, kerr := unserializeKey(r, s == "s")
			if kerr != nil {
				return nil, kerr
			}
			val, verr := Unserialize(r)
			if verr != nil {
				return nil, verr
			}
			array.Set(key, val)
		}
		var s string
		fmt.Fscanf(r, "%1s", &s)
		if s == "}" {
			return array, nil
		}
	}
	return nil, errors.New("Unserialize Array fail")
}

func unserializeVarname(r io.Reader) (clsname, varname string, err error) {
	var s string
	fmt.Fscanf(r, "%1s", &s)
	if cname, cerr := unserializeString(r); cerr == nil {
		slist := strings.Split(string(cname), "\x00")
		if len(slist) == 2 {
			return slist[0], slist[1], nil
		} else if len(slist) == 1 {
			return "", slist[0], nil
		} else {
			return "", "", errors.New("Unserialize Varname fail")
		}
	} else {
		return "", "", errors.New("Unserialize Varname fail")
	}
}

func unserializeObject(r io.Reader) (ret *PObject, err error) {
	var cl int
	if ln, lerr := fmt.Fscanf(r, ":%d:\"", &cl); lerr == nil && ln == 1 {
		cnbuf := make([]byte, cl+1)
		var cname string
		if _, cerr := io.ReadFull(r, cnbuf); cerr == nil && cnbuf[cl] == '"' {
			cname = string(cnbuf[:cl])
		} else {
			return nil, errors.New("Unserialize Object Name fail")
		}
		var n int
		if nn, nerr := fmt.Fscanf(r, ":%d:{", &n); nerr == nil && nn == 1 {
		} else {
			return nil, errors.New("Unserialize Object len(Member) fail")
		}
		object := NewObject(cname)
		for i := 0; i < n; i++ {
			clsname, varname, verr := unserializeVarname(r)
			if verr != nil {
				return nil, verr
			}
			val, pverr := unserializeValue(r)
			if pverr != nil {
				return nil, errors.New("Unserialize Object len(Member) fail")
			}
			if object.Set(clsname, varname, val) != nil {
				return nil, errors.New("Unserialize Object set fail")
			}
		}
		var s string
		fmt.Fscanf(r, "%1s", &s)
		if s == "}" {
			return object, nil
		}
	}
	return nil, errors.New("Unserialize Object fail")
}

func unserializeValue(r io.Reader) (ret PValue, err error) {
	var s string
	fmt.Fscanf(r, "%1s", &s)
	switch s {
	case "N":
		return unserializaNil(r)
	case "b":
		return unserializeBool(r)
	case "i":
		return unserializeLong(r)
	case "d":
		return unserializeDouble(r)
	case "s":
		return unserializeString(r)
	case "a":
		return unserializeArray(r)
	case "O":
		return unserializeObject(r)
	default:
		return nil, errors.New("Unknow value type")
	}
}

func Unserialize(r io.Reader) (ret PValue, err error) {
	return unserializeValue(r)
}
<commit_msg>fix unserialize<commit_after>package phpobject

import (
	"errors"
	"fmt"
	"io"
	"strconv"
	"strings"
)

func unserializaNil(r io.Reader) (ret PValue, err error) {
	var s string
	fmt.Fscanf(r, "%1s", &s)
	if s == ";" {
		return PNil, nil
	}
	return PNil, errors.New("Unserialize Nil fail")
}

func unserializeBool(r io.Reader) (ret PBool, err error) {
	var i int
	if n, nerr := fmt.Fscanf(r, ":%1d;", &i); nerr == nil && n == 1 {
		return PBool(i != 0), nil
	}
	return PFalse, errors.New("Unserialize Bool fail")
}

func unserializeLong(r io.Reader) (ret PLong, err error) {
	var i int
	if n, nerr := fmt.Fscanf(r, ":%d;", &i); nerr == nil && n == 1 {
		return PLong(i), nil
	}
	return 0, errors.New("Unserialize Long fail")
}

func unserializeDouble(r io.Reader) (ret PDouble, err error) {
	var d float64
	if n, nerr := fmt.Fscanf(r, ":%f;", &d); nerr == nil && n == 1 {
		return PDouble(d), nil
	}
	return 0, errors.New("Unserialize Double fail")
}

func unserializeString(r io.Reader) (ret PString, err error) {
	var l int
	if ln, lerr := fmt.Fscanf(r, ":%d:\"", &l); lerr == nil && ln == 1 {
		buf := make([]byte, l+2)
		if _, berr := io.ReadFull(r, buf); berr == nil && buf[l] == '"' && buf[l+1] == ';' {
			return PString(buf[:l]), nil
		}
	}
	return "", errors.New("Unserialize String fail")
}

func unserializeKey(r io.Reader, isstr bool) (ret string, err error) {
	if isstr {
		if s, serr := unserializeString(r); serr == nil {
			return string(s), nil
		}
	} else {
		if l, lerr := unserializeLong(r); lerr == nil {
			return strconv.Itoa(int(l)), lerr
		}
	}
	return "", errors.New("Unserialize Key fail")
}

func unserializeArray(r io.Reader) (ret *PArray, err error) {
	var l int
	if ln, lerr := fmt.Fscanf(r, ":%d:{", &l); lerr == nil && ln == 1 {
		array := NewArray()
		for i := 0; i < l; i++ {
			var s string
			fmt.Fscanf(r, "%1s", &s)
			key, kerr := unserializeKey(r, s == "s")
			if kerr != nil {
				return nil, kerr
			}
			val, verr := unserializeValue(r)
			if verr != nil {
				return nil, verr
			}
			array.Set(key, val)
		}
		var s string
		fmt.Fscanf(r, "%1s", &s)
		if s == "}" {
			return array, nil
		}
	}
	return nil, errors.New("Unserialize Array fail")
}

func unserializeVarname(r io.Reader) (clsname, varname string, err error) {
	var s string
	fmt.Fscanf(r, "%1s", &s)
	if cname, cerr := unserializeString(r); cerr == nil {
		slist := strings.Split(string(cname), "\x00")
		if len(slist) == 2 {
			return slist[0], slist[1], nil
		} else if len(slist) == 1 {
			return "", slist[0], nil
		} else {
			return "", "", errors.New("Unserialize Varname fail")
		}
	} else {
		return "", "", errors.New("Unserialize Varname fail")
	}
}

func unserializeObject(r io.Reader) (ret *PObject, err error) {
	var cl int
	if ln, lerr := fmt.Fscanf(r, ":%d:\"", &cl); lerr == nil && ln == 1 {
		cnbuf := make([]byte, cl+1)
		var cname string
		if _, cerr := io.ReadFull(r, cnbuf); cerr == nil && cnbuf[cl] == '"' {
			cname = string(cnbuf[:cl])
		} else {
			return nil, errors.New("Unserialize Object Name fail")
		}
		var n int
		if nn, nerr := fmt.Fscanf(r, ":%d:{", &n); nerr == nil && nn == 1 {
		} else {
			return nil, errors.New("Unserialize Object len(Member) fail")
		}
		object := NewObject(cname)
		for i := 0; i < n; i++ {
			clsname, varname, verr := unserializeVarname(r)
			if verr != nil {
				return nil, verr
			}
			val, pverr := unserializeValue(r)
			if pverr != nil {
				return nil, errors.New("Unserialize Object len(Member) fail")
			}
			if object.Set(clsname, varname, val) != nil {
				return nil, errors.New("Unserialize Object set fail")
			}
		}
		var s string
		fmt.Fscanf(r, "%1s", &s)
		if s == "}" {
			return object, nil
		}
	}
	return nil, errors.New("Unserialize Object fail")
}

func unserializeValue(r io.Reader) (ret PValue, err error) {
	var s string
	fmt.Fscanf(r, "%1s", &s)
	switch s {
	case "N":
		return unserializaNil(r)
	case "b":
		return unserializeBool(r)
	case "i":
		return unserializeLong(r)
	case "d":
		return unserializeDouble(r)
	case "s":
		return unserializeString(r)
	case "a":
		return unserializeArray(r)
	case "O":
		return unserializeObject(r)
	default:
		return nil, errors.New("Unknow value type")
	}
}

func Unserialize(r io.Reader) (ret PValue, err error) {
	return unserializeValue(r)
}
<|endoftext|>


<commit_before>package main

import (
	"bytes"
	"encoding/json"
	"github.com/gorilla/mux"
	. "gopkg.in/check.v1"
	"net/http"
	"net/http/httptest"
	"net/url"
	"os"
	"vip/test"
)

var (
	_ = Suite(&UploadSuite{})
)

type UploadSuite struct{}

func (s *UploadSuite) SetUpSuite(c *C) {
	setUpSuite(c)
}

func (s *UploadSuite) SetUpTest(c *C) {
	setUpTest(c)

	storage = test.NewStore()
}

func (s *UploadSuite) TestUpload(c *C) {
	authToken = "lalalatokenlalala"
	os.Setenv("DOMAIN_DATA", "")

	recorder := httptest.NewRecorder()

	// Mock up a router so that mux.Vars are passed
	// correctly
	m := mux.NewRouter()
	m.Handle("/upload/{bucket_id}", verifyAuth(handleUpload))
	f, err := os.Open("./test/awesome.jpeg")
	c.Assert(err, IsNil)

	req, err := http.NewRequest("POST", "http://localhost:8080/upload/samplebucket", f)
	c.Assert(err, IsNil)
	fstat, err := os.Stat("./test/awesome.jpeg")
	c.Assert(err, IsNil)
	req.ContentLength = fstat.Size()
	req.Header.Set("Content-Type", "image/jpeg")
	req.Header.Set("X-Vip-Token", authToken)

	m.ServeHTTP(recorder, req)

	var u UploadResponse
	err = json.NewDecoder(recorder.Body).Decode(&u)
	c.Assert(err, IsNil)
	c.Assert(len(u.Url), Not(Equals), 0)

	uri, err := url.Parse(u.Url)
	c.Assert(err, IsNil)

	c.Assert(uri.Scheme, Equals, "http")
	c.Assert(uri.Host, Equals, "localhost:8080")
	c.Assert(uri.Path[1:13], Equals, "samplebucket")
	c.Assert(uri.Path[len(uri.Path)-9:len(uri.Path)], Equals, "-1024x768")
	c.Assert(recorder.HeaderMap["Content-Type"][0], Equals, "application/json")
}

func (s *UploadSuite) TestEmptyUpload(c *C) {
	authToken = "lalalatokenlalala"
	os.Setenv("ALLOWED_ORIGIN", "")

	recorder := httptest.NewRecorder()

	// Mock up a router so that mux.Vars are passed
	// correctly
	m := mux.NewRouter()
	m.Handle("/upload/{bucket_id}", verifyAuth(handleUpload))
	f := &bytes.Reader{}
	req, err := http.NewRequest("POST", "http://localhost:8080/upload/samplebucket", f)
	c.Assert(err, IsNil)

	req.Header.Set("Content-Type", "image/jpeg")
	req.Header.Set("X-Vip-Token", authToken)

	m.ServeHTTP(recorder, req)
	c.Assert(recorder.Code, Equals, http.StatusBadRequest)

	var u ErrorResponse
	err = json.NewDecoder(recorder.Body).Decode(&u)
	c.Assert(err, IsNil)
	c.Assert(u.Msg, Equals, "File must have size greater than 0")
}

func (s *UploadSuite) TestUnauthorizedUpload(c *C) {
	authToken = "lalalatokenlalala"
	os.Setenv("ALLOWED_ORIGIN", "")

	recorder := httptest.NewRecorder()

	// Mock up a router so that mux.Vars are passed
	// correctly
	m := mux.NewRouter()
	m.Handle("/upload/{bucket_id}", verifyAuth(handleUpload))

	f, err := os.Open("./test/awesome.jpeg")
	c.Assert(err, IsNil)

	req, err := http.NewRequest("POST", "http://localhost:8080/upload/samplebucket", f)

	c.Assert(err, IsNil)

	req.Header.Set("Content-Type", "image/jpeg")

	m.ServeHTTP(recorder, req)

	c.Assert(recorder.Code, Equals, http.StatusUnauthorized)
}

func (s *UploadSuite) TestSetOriginData(c *C) {
	authToken = "heyheyheyimatoken"
	os.Setenv("ALLOWED_ORIGIN", "WHATEVER, MAN")

	recorder := httptest.NewRecorder()

	m := mux.NewRouter()
	m.Handle("/upload/{bucket_id}", verifyAuth(handleUpload))

	f, err := os.Open("./test/awesome.jpeg")
	c.Assert(err, IsNil)

	req, err := http.NewRequest("POST", "http://localhost:8080/upload/samplebucket", f)
	c.Assert(err, IsNil)
	fstat, err := os.Stat("./test/awesome.jpeg")
	c.Assert(err, IsNil)
	req.ContentLength = fstat.Size()
	req.Header.Set("Origin", "WHATEVER, MAN")
	c.Assert(err, IsNil)
	req.Header.Set("Content-Type", "image/jpeg")

	m.ServeHTTP(recorder, req)
	c.Assert(recorder.Code, Equals, http.StatusCreated)
}
<commit_msg>Try new image instead of awesome.jpeg<commit_after>package main

import (
	"bytes"
	"encoding/json"
	"github.com/gorilla/mux"
	. "gopkg.in/check.v1"
	"net/http"
	"net/http/httptest"
	"net/url"
	"os"
	"vip/test"
)

var (
	_ = Suite(&UploadSuite{})
)

type UploadSuite struct{}

func (s *UploadSuite) SetUpSuite(c *C) {
	setUpSuite(c)
}

func (s *UploadSuite) SetUpTest(c *C) {
	setUpTest(c)

	storage = test.NewStore()
}

func (s *UploadSuite) TestUpload(c *C) {
	authToken = "lalalatokenlalala"
	os.Setenv("DOMAIN_DATA", "")

	recorder := httptest.NewRecorder()

	// Mock up a router so that mux.Vars are passed
	// correctly
	m := mux.NewRouter()
	m.Handle("/upload/{bucket_id}", verifyAuth(handleUpload))
	f, err := os.Open("./test/exif_test_img.jpg")
	c.Assert(err, IsNil)

	req, err := http.NewRequest("POST", "http://localhost:8080/upload/samplebucket", f)
	c.Assert(err, IsNil)
	fstat, err := os.Stat("./test/exif_test_img.jpg")
	c.Assert(err, IsNil)
	req.ContentLength = fstat.Size()
	req.Header.Set("Content-Type", "image/jpeg")
	req.Header.Set("X-Vip-Token", authToken)

	m.ServeHTTP(recorder, req)

	var u UploadResponse
	err = json.NewDecoder(recorder.Body).Decode(&u)
	c.Assert(err, IsNil)
	c.Assert(len(u.Url), Not(Equals), 0)

	uri, err := url.Parse(u.Url)
	c.Assert(err, IsNil)

	c.Assert(uri.Scheme, Equals, "http")
	c.Assert(uri.Host, Equals, "localhost:8080")
	c.Assert(uri.Path[1:13], Equals, "samplebucket")
	c.Assert(uri.Path[len(uri.Path)-9:len(uri.Path)], Equals, "-1024x768")
	c.Assert(recorder.HeaderMap["Content-Type"][0], Equals, "application/json")
}

func (s *UploadSuite) TestEmptyUpload(c *C) {
	authToken = "lalalatokenlalala"
	os.Setenv("ALLOWED_ORIGIN", "")

	recorder := httptest.NewRecorder()

	// Mock up a router so that mux.Vars are passed
	// correctly
	m := mux.NewRouter()
	m.Handle("/upload/{bucket_id}", verifyAuth(handleUpload))
	f := &bytes.Reader{}
	req, err := http.NewRequest("POST", "http://localhost:8080/upload/samplebucket", f)
	c.Assert(err, IsNil)

	req.Header.Set("Content-Type", "image/jpeg")
	req.Header.Set("X-Vip-Token", authToken)

	m.ServeHTTP(recorder, req)
	c.Assert(recorder.Code, Equals, http.StatusBadRequest)

	var u ErrorResponse
	err = json.NewDecoder(recorder.Body).Decode(&u)
	c.Assert(err, IsNil)
	c.Assert(u.Msg, Equals, "File must have size greater than 0")
}

func (s *UploadSuite) TestUnauthorizedUpload(c *C) {
	authToken = "lalalatokenlalala"
	os.Setenv("ALLOWED_ORIGIN", "")

	recorder := httptest.NewRecorder()

	// Mock up a router so that mux.Vars are passed
	// correctly
	m := mux.NewRouter()
	m.Handle("/upload/{bucket_id}", verifyAuth(handleUpload))

	f, err := os.Open("./test/exif_test_img.jpg")
	c.Assert(err, IsNil)

	req, err := http.NewRequest("POST", "http://localhost:8080/upload/samplebucket", f)

	c.Assert(err, IsNil)

	req.Header.Set("Content-Type", "image/jpeg")

	m.ServeHTTP(recorder, req)

	c.Assert(recorder.Code, Equals, http.StatusUnauthorized)
}

func (s *UploadSuite) TestSetOriginData(c *C) {
	authToken = "heyheyheyimatoken"
	os.Setenv("ALLOWED_ORIGIN", "WHATEVER, MAN")

	recorder := httptest.NewRecorder()

	m := mux.NewRouter()
	m.Handle("/upload/{bucket_id}", verifyAuth(handleUpload))

	f, err := os.Open("./test/exif_test_img.jpg")
	c.Assert(err, IsNil)

	req, err := http.NewRequest("POST", "http://localhost:8080/upload/samplebucket", f)
	c.Assert(err, IsNil)
	fstat, err := os.Stat("./test/exif_test_img.jpg")
	c.Assert(err, IsNil)
	req.ContentLength = fstat.Size()
	req.Header.Set("Origin", "WHATEVER, MAN")
	c.Assert(err, IsNil)
	req.Header.Set("Content-Type", "image/jpeg")

	m.ServeHTTP(recorder, req)
	c.Assert(recorder.Code, Equals, http.StatusCreated)
}
<|endoftext|>


<commit_before>package utils

import (
	"crypto/rand"
	"crypto/rsa"
	"crypto/tls"
	"crypto/x509"
	"crypto/x509/pkix"
	"encoding/pem"
	"io/ioutil"
	"math/big"
	"net"
	"os"
	"time"
)

func getTLSConfig(caCert, cert, key []byte, allowInsecure bool) (*tls.Config, error) {
	// TLS config
	var tlsConfig tls.Config
	tlsConfig.InsecureSkipVerify = allowInsecure
	certPool := x509.NewCertPool()

	certPool.AppendCertsFromPEM(caCert)
	tlsConfig.RootCAs = certPool
	keypair, err := tls.X509KeyPair(cert, key)
	if err != nil {
		return &tlsConfig, err
	}
	tlsConfig.Certificates = []tls.Certificate{keypair}
	if allowInsecure {
		tlsConfig.InsecureSkipVerify = true
	}

	return &tlsConfig, nil
}

func newCertificate(org string) (*x509.Certificate, error) {
	now := time.Now()
	// need to set notBefore slightly in the past to account for time
	// skew in the VMs otherwise the certs sometimes are not yet valid
	notBefore := time.Date(now.Year(), now.Month(), now.Day(), now.Hour(), now.Minute()-5, 0, 0, time.Local)
	notAfter := notBefore.Add(time.Hour * 24 * 1080)

	serialNumberLimit := new(big.Int).Lsh(big.NewInt(1), 128)
	serialNumber, err := rand.Int(rand.Reader, serialNumberLimit)
	if err != nil {
		return nil, err
	}

	return &x509.Certificate{
		SerialNumber: serialNumber,
		Subject: pkix.Name{
			Organization: []string{org},
		},
		NotBefore: notBefore,
		NotAfter:  notAfter,

		KeyUsage:              x509.KeyUsageKeyEncipherment | x509.KeyUsageDigitalSignature | x509.KeyUsageKeyAgreement,
		BasicConstraintsValid: true,
	}, nil

}

// GenerateCACertificate generates a new certificate authority from the specified org
// and bit size and stores the resulting certificate and key file
// in the arguments.
func GenerateCACertificate(certFile, keyFile, org string, bits int) error {
	template, err := newCertificate(org)
	if err != nil {
		return err
	}

	template.IsCA = true
	template.KeyUsage |= x509.KeyUsageCertSign
	template.KeyUsage |= x509.KeyUsageKeyEncipherment
	template.KeyUsage |= x509.KeyUsageKeyAgreement

	priv, err := rsa.GenerateKey(rand.Reader, bits)
	if err != nil {
		return err
	}

	derBytes, err := x509.CreateCertificate(rand.Reader, template, template, &priv.PublicKey, priv)
	if err != nil {
		return err
	}

	certOut, err := os.Create(certFile)
	if err != nil {
		return err
	}

	pem.Encode(certOut, &pem.Block{Type: "CERTIFICATE", Bytes: derBytes})
	certOut.Close()

	keyOut, err := os.OpenFile(keyFile, os.O_WRONLY|os.O_CREATE|os.O_TRUNC, 0600)
	if err != nil {
		return err

	}

	pem.Encode(keyOut, &pem.Block{Type: "RSA PRIVATE KEY", Bytes: x509.MarshalPKCS1PrivateKey(priv)})
	keyOut.Close()

	return nil
}

// GenerateCert generates a new certificate signed using the provided
// certificate authority files and stores the result in the certificate
// file and key provided.  The provided host names are set to the
// appropriate certificate fields.
func GenerateCert(hosts []string, certFile, keyFile, caFile, caKeyFile, org string, bits int) error {
	template, err := newCertificate(org)
	if err != nil {
		return err
	}
	// client
	if len(hosts) == 1 && hosts[0] == "" {
		template.ExtKeyUsage = []x509.ExtKeyUsage{x509.ExtKeyUsageClientAuth}
		template.KeyUsage = x509.KeyUsageDigitalSignature
	} else { // server
		template.ExtKeyUsage = []x509.ExtKeyUsage{x509.ExtKeyUsageClientAuth, x509.ExtKeyUsageServerAuth}
		for _, h := range hosts {
			if ip := net.ParseIP(h); ip != nil {
				template.IPAddresses = append(template.IPAddresses, ip)
			} else {
				template.DNSNames = append(template.DNSNames, h)
			}
		}
	}

	tlsCert, err := tls.LoadX509KeyPair(caFile, caKeyFile)
	if err != nil {
		return err
	}

	priv, err := rsa.GenerateKey(rand.Reader, bits)
	if err != nil {
		return err
	}

	x509Cert, err := x509.ParseCertificate(tlsCert.Certificate[0])
	if err != nil {
		return err
	}

	derBytes, err := x509.CreateCertificate(rand.Reader, template, x509Cert, &priv.PublicKey, tlsCert.PrivateKey)
	if err != nil {
		return err
	}

	certOut, err := os.Create(certFile)
	if err != nil {
		return err
	}

	pem.Encode(certOut, &pem.Block{Type: "CERTIFICATE", Bytes: derBytes})
	certOut.Close()

	keyOut, err := os.OpenFile(keyFile, os.O_WRONLY|os.O_CREATE|os.O_TRUNC, 0600)
	if err != nil {
		return err
	}

	pem.Encode(keyOut, &pem.Block{Type: "RSA PRIVATE KEY", Bytes: x509.MarshalPKCS1PrivateKey(priv)})
	keyOut.Close()

	return nil
}

func ValidateCertificate(addr, caCertPath, serverCertPath, serverKeyPath string) (bool, error) {
	caCert, err := ioutil.ReadFile(caCertPath)
	if err != nil {
		return false, err
	}

	serverCert, err := ioutil.ReadFile(serverCertPath)
	if err != nil {
		return false, err
	}

	serverKey, err := ioutil.ReadFile(serverKeyPath)
	if err != nil {
		return false, err
	}

	tlsConfig, err := getTLSConfig(caCert, serverCert, serverKey, false)
	if err != nil {
		return false, err
	}

	dialer := &net.Dialer{
		Timeout: time.Second * 2,
	}

	_, err = tls.DialWithDialer(dialer, "tcp", addr, tlsConfig)
	if err != nil {
		return false, nil
	}

	return true, nil
}
<commit_msg>Remove redundent assignment to InsecureSkipVerify<commit_after>package utils

import (
	"crypto/rand"
	"crypto/rsa"
	"crypto/tls"
	"crypto/x509"
	"crypto/x509/pkix"
	"encoding/pem"
	"io/ioutil"
	"math/big"
	"net"
	"os"
	"time"
)

func getTLSConfig(caCert, cert, key []byte, allowInsecure bool) (*tls.Config, error) {
	// TLS config
	var tlsConfig tls.Config
	tlsConfig.InsecureSkipVerify = allowInsecure
	certPool := x509.NewCertPool()

	certPool.AppendCertsFromPEM(caCert)
	tlsConfig.RootCAs = certPool
	keypair, err := tls.X509KeyPair(cert, key)
	if err != nil {
		return &tlsConfig, err
	}
	tlsConfig.Certificates = []tls.Certificate{keypair}

	return &tlsConfig, nil
}

func newCertificate(org string) (*x509.Certificate, error) {
	now := time.Now()
	// need to set notBefore slightly in the past to account for time
	// skew in the VMs otherwise the certs sometimes are not yet valid
	notBefore := time.Date(now.Year(), now.Month(), now.Day(), now.Hour(), now.Minute()-5, 0, 0, time.Local)
	notAfter := notBefore.Add(time.Hour * 24 * 1080)

	serialNumberLimit := new(big.Int).Lsh(big.NewInt(1), 128)
	serialNumber, err := rand.Int(rand.Reader, serialNumberLimit)
	if err != nil {
		return nil, err
	}

	return &x509.Certificate{
		SerialNumber: serialNumber,
		Subject: pkix.Name{
			Organization: []string{org},
		},
		NotBefore: notBefore,
		NotAfter:  notAfter,

		KeyUsage:              x509.KeyUsageKeyEncipherment | x509.KeyUsageDigitalSignature | x509.KeyUsageKeyAgreement,
		BasicConstraintsValid: true,
	}, nil

}

// GenerateCACertificate generates a new certificate authority from the specified org
// and bit size and stores the resulting certificate and key file
// in the arguments.
func GenerateCACertificate(certFile, keyFile, org string, bits int) error {
	template, err := newCertificate(org)
	if err != nil {
		return err
	}

	template.IsCA = true
	template.KeyUsage |= x509.KeyUsageCertSign
	template.KeyUsage |= x509.KeyUsageKeyEncipherment
	template.KeyUsage |= x509.KeyUsageKeyAgreement

	priv, err := rsa.GenerateKey(rand.Reader, bits)
	if err != nil {
		return err
	}

	derBytes, err := x509.CreateCertificate(rand.Reader, template, template, &priv.PublicKey, priv)
	if err != nil {
		return err
	}

	certOut, err := os.Create(certFile)
	if err != nil {
		return err
	}

	pem.Encode(certOut, &pem.Block{Type: "CERTIFICATE", Bytes: derBytes})
	certOut.Close()

	keyOut, err := os.OpenFile(keyFile, os.O_WRONLY|os.O_CREATE|os.O_TRUNC, 0600)
	if err != nil {
		return err

	}

	pem.Encode(keyOut, &pem.Block{Type: "RSA PRIVATE KEY", Bytes: x509.MarshalPKCS1PrivateKey(priv)})
	keyOut.Close()

	return nil
}

// GenerateCert generates a new certificate signed using the provided
// certificate authority files and stores the result in the certificate
// file and key provided.  The provided host names are set to the
// appropriate certificate fields.
func GenerateCert(hosts []string, certFile, keyFile, caFile, caKeyFile, org string, bits int) error {
	template, err := newCertificate(org)
	if err != nil {
		return err
	}
	// client
	if len(hosts) == 1 && hosts[0] == "" {
		template.ExtKeyUsage = []x509.ExtKeyUsage{x509.ExtKeyUsageClientAuth}
		template.KeyUsage = x509.KeyUsageDigitalSignature
	} else { // server
		template.ExtKeyUsage = []x509.ExtKeyUsage{x509.ExtKeyUsageClientAuth, x509.ExtKeyUsageServerAuth}
		for _, h := range hosts {
			if ip := net.ParseIP(h); ip != nil {
				template.IPAddresses = append(template.IPAddresses, ip)
			} else {
				template.DNSNames = append(template.DNSNames, h)
			}
		}
	}

	tlsCert, err := tls.LoadX509KeyPair(caFile, caKeyFile)
	if err != nil {
		return err
	}

	priv, err := rsa.GenerateKey(rand.Reader, bits)
	if err != nil {
		return err
	}

	x509Cert, err := x509.ParseCertificate(tlsCert.Certificate[0])
	if err != nil {
		return err
	}

	derBytes, err := x509.CreateCertificate(rand.Reader, template, x509Cert, &priv.PublicKey, tlsCert.PrivateKey)
	if err != nil {
		return err
	}

	certOut, err := os.Create(certFile)
	if err != nil {
		return err
	}

	pem.Encode(certOut, &pem.Block{Type: "CERTIFICATE", Bytes: derBytes})
	certOut.Close()

	keyOut, err := os.OpenFile(keyFile, os.O_WRONLY|os.O_CREATE|os.O_TRUNC, 0600)
	if err != nil {
		return err
	}

	pem.Encode(keyOut, &pem.Block{Type: "RSA PRIVATE KEY", Bytes: x509.MarshalPKCS1PrivateKey(priv)})
	keyOut.Close()

	return nil
}

func ValidateCertificate(addr, caCertPath, serverCertPath, serverKeyPath string) (bool, error) {
	caCert, err := ioutil.ReadFile(caCertPath)
	if err != nil {
		return false, err
	}

	serverCert, err := ioutil.ReadFile(serverCertPath)
	if err != nil {
		return false, err
	}

	serverKey, err := ioutil.ReadFile(serverKeyPath)
	if err != nil {
		return false, err
	}

	tlsConfig, err := getTLSConfig(caCert, serverCert, serverKey, false)
	if err != nil {
		return false, err
	}

	dialer := &net.Dialer{
		Timeout: time.Second * 2,
	}

	_, err = tls.DialWithDialer(dialer, "tcp", addr, tlsConfig)
	if err != nil {
		return false, nil
	}

	return true, nil
}
<|endoftext|>


<commit_before>package utils

import (
	"io/ioutil"
	"fmt"
	"encoding/json"
	"log"
	"github.com/vladpereskokov/Technopark_HighLoad-nginx/configs"
)

func FromFile(filename string) (*configs.Config, error) {
	file, err := ioutil.ReadFile(filename)

	if err != nil {
		return &configs.Config{}, fmt.Errorf("can not open file: %v", err)
	}

	return fromReader(file)
}

func fromReader(r []byte) (*configs.Config, error) {
	config := new(configs.Config)
	err := json.Unmarshal(r, &config)

	if err != nil {
		return config, fmt.Errorf("can not parse config: %v", err)
	}

	return config, nil
}
<commit_msg>del unused imports<commit_after>package utils

import (
	"encoding/json"
	"fmt"
	"github.com/vladpereskokov/Technopark_HighLoad-nginx/configs"
	"io/ioutil"
)

func FromFile(filename string) (*configs.Config, error) {
	file, err := ioutil.ReadFile(filename)

	if err != nil {
		return &configs.Config{}, fmt.Errorf("can not open file: %v", err)
	}

	return fromReader(file)
}

func fromReader(r []byte) (*configs.Config, error) {
	config := new(configs.Config)
	err := json.Unmarshal(r, &config)

	if err != nil {
		return config, fmt.Errorf("can not parse config: %v", err)
	}

	return config, nil
}
<|endoftext|>


<commit_before>// Package utils - 套件所需的公用工具
//
package utils

import (
	"regexp"
	"strconv"
	"time"
)

// ExchangeMap is simple to check tse or otc.
var ExchangeMap = map[string]bool{"tse": true, "otc": true}

// TaipeiTimeZone is for time.Data() setting.
var TaipeiTimeZone = time.FixedZone("Asia/Taipei", 8*3600)

// TWSE base url.
const (
	TWSEURL     string = "http://mis.tse.com.tw"
	TWSEHOST    string = "http://www.twse.com.tw"
	OTCHOST     string = "http://www.tpex.org.tw"
	OTCCSV      string = "/ch/stock/aftertrading/daily_trading_info/st43_download.php?d=%d/%02d&stkno=%s&r=%d" // year, mon, stock, rand
	TWSECSV     string = "/ch/trading/exchange/STOCK_DAY/STOCK_DAY_print.php?genpage=genpage/Report%d%02d/%d%02d_F3_1_8_%s.php&type=csv&r=%d"
	TWSELISTCSV string = "/ch/trading/exchange/MI_INDEX/MI_INDEX.php" // year, mon, day, type
	TWSEREAL    string = "/stock/api/getStockInfo.jsp?ex_ch=%s_%s.tw_%s&json=1&delay=0&_=%d"
)

// RandInt return random int.
func RandInt() int {
	return time.Now().Nanosecond()
}

//func RandInt() int64 {
//	result, _ := rand.Int(rand.Reader, big.NewInt(102400))
//	return result.Int64()
//}

//func RandInt() int64 {
//	r := rand.New(rand.NewSource(time.Now().UnixNano()))
//	return r.Int63n(100000)
//}

var dateReg = regexp.MustCompile(`([\d]{2,})/([\d]{1,2})/([\d]{1,2})`)

// ParseDate is to parse "104/01/13" format.
func ParseDate(strDate string) time.Time {
	p := dateReg.FindStringSubmatch(strDate)
	year, _ := strconv.Atoi(p[1])
	mon, _ := strconv.Atoi(p[2])
	day, _ := strconv.Atoi(p[3])
	return time.Date(year+1911, time.Month(mon), day, 0, 0, 0, 0, TaipeiTimeZone)
}

// SumFloat64 計算總和（float64）
func SumFloat64(data []float64) float64 {
	var result float64
	for _, v := range data {
		result += v
	}
	return result
}

// AvgFlast64 計算平均（float64）
func AvgFlast64(data []float64) float64 {
	return float64(int(SumFloat64(data)*100)/len(data)) / 100
}

// SumUint64 計算總和（uint64）
func SumUint64(data []uint64) uint64 {
	var result uint64
	for _, v := range data {
		result += v
	}
	return result
}

// AvgUint64 計算平均（uint64）
func AvgUint64(data []uint64) uint64 {
	return SumUint64(data) / uint64(len(data))
}

// ThanPastUint64 計算最後一個數值是否為過去幾天最大或最小（uint64）
func ThanPastUint64(data []uint64, days int, max bool) bool {
	var dataFloat64 = make([]float64, days+1)
	for i, v := range data[len(data)-1-days:] {
		dataFloat64[i] = float64(v)
	}
	return thanPast(dataFloat64, max)
}

// ThanPastFloat64 計算最後一個數值是否為過去幾天最大或最小（float64）
func ThanPastFloat64(data []float64, days int, max bool) bool {
	return thanPast(data[len(data)-1-days:], max)
}

func thanPast(data []float64, max bool) bool {
	//var dataFloat64 []float64
	//dataFloat64 = make([]float64, days+1)
	//for i, v := range data[len(data)-1-days : len(data)-1] {
	//	switch v.(type) {
	//	case int64:
	//		dataFloat64[i] = float64(v.(int64))
	//	case float64:
	//		dataFloat64[i] = v.(float64)
	//	}
	//}

	var base = data[len(data)-1]
	var condition func(b float64) bool

	if max {
		condition = func(b float64) bool { return base > b }
	} else {
		condition = func(b float64) bool { return base < b }
	}

	for _, v := range data[:len(data)-1] {
		if condition(v) {
			continue
		} else {
			return false
		}
	}
	return true
}

func thanSumPast(data []float64, max bool) bool {
	var result = data[len(data)-1] > SumFloat64(data[:len(data)-2])
	if max {
		return result
	}
	return !result
}
<commit_msg>Add `ThanSumPastFloat64`.<commit_after>// Package utils - 套件所需的公用工具
//
package utils

import (
	"regexp"
	"strconv"
	"time"
)

// ExchangeMap is simple to check tse or otc.
var ExchangeMap = map[string]bool{"tse": true, "otc": true}

// TaipeiTimeZone is for time.Data() setting.
var TaipeiTimeZone = time.FixedZone("Asia/Taipei", 8*3600)

// TWSE base url.
const (
	TWSEURL     string = "http://mis.tse.com.tw"
	TWSEHOST    string = "http://www.twse.com.tw"
	OTCHOST     string = "http://www.tpex.org.tw"
	OTCCSV      string = "/ch/stock/aftertrading/daily_trading_info/st43_download.php?d=%d/%02d&stkno=%s&r=%d" // year, mon, stock, rand
	TWSECSV     string = "/ch/trading/exchange/STOCK_DAY/STOCK_DAY_print.php?genpage=genpage/Report%d%02d/%d%02d_F3_1_8_%s.php&type=csv&r=%d"
	TWSELISTCSV string = "/ch/trading/exchange/MI_INDEX/MI_INDEX.php" // year, mon, day, type
	TWSEREAL    string = "/stock/api/getStockInfo.jsp?ex_ch=%s_%s.tw_%s&json=1&delay=0&_=%d"
)

// RandInt return random int.
func RandInt() int {
	return time.Now().Nanosecond()
}

//func RandInt() int64 {
//	result, _ := rand.Int(rand.Reader, big.NewInt(102400))
//	return result.Int64()
//}

//func RandInt() int64 {
//	r := rand.New(rand.NewSource(time.Now().UnixNano()))
//	return r.Int63n(100000)
//}

var dateReg = regexp.MustCompile(`([\d]{2,})/([\d]{1,2})/([\d]{1,2})`)

// ParseDate is to parse "104/01/13" format.
func ParseDate(strDate string) time.Time {
	p := dateReg.FindStringSubmatch(strDate)
	year, _ := strconv.Atoi(p[1])
	mon, _ := strconv.Atoi(p[2])
	day, _ := strconv.Atoi(p[3])
	return time.Date(year+1911, time.Month(mon), day, 0, 0, 0, 0, TaipeiTimeZone)
}

// SumFloat64 計算總和（float64）
func SumFloat64(data []float64) float64 {
	var result float64
	for _, v := range data {
		result += v
	}
	return result
}

// AvgFlast64 計算平均（float64）
func AvgFlast64(data []float64) float64 {
	return float64(int(SumFloat64(data)*100)/len(data)) / 100
}

// SumUint64 計算總和（uint64）
func SumUint64(data []uint64) uint64 {
	var result uint64
	for _, v := range data {
		result += v
	}
	return result
}

// AvgUint64 計算平均（uint64）
func AvgUint64(data []uint64) uint64 {
	return SumUint64(data) / uint64(len(data))
}

// ThanPastUint64 計算最後一個數值是否為過去幾天最大或最小（uint64）
func ThanPastUint64(data []uint64, days int, max bool) bool {
	var dataFloat64 = make([]float64, days+1)
	for i, v := range data[len(data)-1-days:] {
		dataFloat64[i] = float64(v)
	}
	return thanPast(dataFloat64, max)
}

// ThanPastFloat64 計算最後一個數值是否為過去幾天最大或最小（float64）
func ThanPastFloat64(data []float64, days int, max bool) bool {
	return thanPast(data[len(data)-1-days:], max)
}

func thanPast(data []float64, max bool) bool {
	//var dataFloat64 []float64
	//dataFloat64 = make([]float64, days+1)
	//for i, v := range data[len(data)-1-days : len(data)-1] {
	//	switch v.(type) {
	//	case int64:
	//		dataFloat64[i] = float64(v.(int64))
	//	case float64:
	//		dataFloat64[i] = v.(float64)
	//	}
	//}

	var base = data[len(data)-1]
	var condition func(b float64) bool

	if max {
		condition = func(b float64) bool { return base > b }
	} else {
		condition = func(b float64) bool { return base < b }
	}

	for _, v := range data[:len(data)-1] {
		if condition(v) {
			continue
		} else {
			return false
		}
	}
	return true
}

// ThanSumPastFloat64 計算最後一個數值是否為過去幾天的總和大或小（float64）
func ThanSumPastFloat64(data []float64, days int, max bool) bool {
	return thanSumPast(data[len(data)-1-days:], max)
}

func thanSumPast(data []float64, max bool) bool {
	var result = data[len(data)-1] > SumFloat64(data[:len(data)-1])
	if max {
		return result
	}
	return !result
}
<|endoftext|>