<commit_before>// Copyright 2015, David Howden
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.

package main

import (
	"fmt"
	"net/http"
	"path/filepath"
	"strings"

	"golang.org/x/net/context"

	"tchaik.com/index"
	"tchaik.com/index/attr"
	"tchaik.com/index/checklist"
	"tchaik.com/index/favourite"
	"tchaik.com/store"
)

// Library is a type which encompases the components which form a full library.
type Library struct {
	index.Library

	collections map[string]index.Collection
	filters     map[string][]index.FilterItem
	recent      []index.Path
	searcher    index.Searcher
	favourites  favourite.Store
	checklist   checklist.Store
}

type libraryFileSystem struct {
	store.FileSystem
	index.Library
}

// Open implements store.FileSystem and rewrites ID values to their corresponding Location
// values using the index.Library.
func (l *libraryFileSystem) Open(ctx context.Context, path string) (http.File, error) {
	t, ok := l.Library.Track(strings.Trim(path, "/")) // IDs arrive with leading slash
	if !ok {
		return nil, fmt.Errorf("could not find track: %v", path)
	}

	loc := t.GetString("Location")
	if loc == "" {
		return nil, fmt.Errorf("invalid (empty) location for track: %v", path)
	}
	loc = filepath.ToSlash(loc)
	return l.FileSystem.Open(ctx, loc)
}

type group struct {
	Name        string
	Key         index.Key
	TotalTime   interface{} `json:",omitempty"`
	Artist      interface{} `json:",omitempty"`
	AlbumArtist interface{} `json:",omitempty"`
	Composer    interface{} `json:",omitempty"`
	BitRate     interface{} `json:",omitempty"`
	DiscNumber  interface{} `json:",omitempty"`
	ListStyle   interface{} `json:",omitempty"`
	ID          interface{} `json:",omitempty"`
	Year        interface{} `json:",omitempty"`
	Groups      []group     `json:",omitempty"`
	Tracks      []track     `json:",omitempty"`
	Favourite   bool        `json:",omitempty"`
}

type track struct {
	ID          string   `json:",omitempty"`
	Name        string   `json:",omitempty"`
	Album       string   `json:",omitempty"`
	Artist      []string `json:",omitempty"`
	AlbumArtist []string `json:",omitempty"`
	Composer    []string `json:",omitempty"`
	Year        int      `json:",omitempty"`
	DiscNumber  int      `json:",omitempty"`
	TotalTime   int      `json:",omitempty"`
	BitRate     int      `json:",omitempty"`
	Favourite   bool     `json:",omitempty"`
}

// StringSliceEqual is a function used to compare two interface{} types which are assumed
// to be of type []string (or interface{}(nil)).
func StringSliceEqual(x, y interface{}) bool {
	// Annoyingly we have to cater for zero values from map[string]interface{}
	// which don't have the correct type wrapping the nil.
	if x == nil || y == nil {
		return x == nil && y == nil
	}
	xs := x.([]string) // NB: panics here are acceptable: should not be called on a non-'Strings' field.
	ys := y.([]string)
	if len(xs) != len(ys) {
		return false
	}
	for i, xss := range xs {
		if ys[i] != xss {
			return false
		}
	}
	return true
}

func buildCollection(h group, c index.Collection) group {
	getField := func(f string, g index.Group, c index.Collection) interface{} {
		if StringSliceEqual(g.Field(f), c.Field(f)) {
			return nil
		}
		return g.Field(f)
	}

	for _, k := range c.Keys() {
		g := c.Get(k)
		g = index.FirstTrackAttr(attr.Strings("AlbumArtist"), g)
		g = index.CommonGroupAttr([]attr.Interface{attr.Strings("Artist")}, g)
		h.Groups = append(h.Groups, group{
			Name:        g.Name(),
			Key:         k,
			AlbumArtist: getField("AlbumArtist", g, c),
			Artist:      getField("Artist", g, c),
		})
	}
	return h
}

func build(g index.Group, key index.Key) group {
	h := group{
		Name:        g.Name(),
		Key:         key,
		TotalTime:   g.Field("TotalTime"),
		Artist:      g.Field("Artist"),
		AlbumArtist: g.Field("AlbumArtist"),
		Composer:    g.Field("Composer"),
		Year:        g.Field("Year"),
		BitRate:     g.Field("BitRate"),
		DiscNumber:  g.Field("DiscNumber"),
		ListStyle:   g.Field("ListStyle"),
		ID:          g.Field("ID"),
	}

	if c, ok := g.(index.Collection); ok {
		return buildCollection(h, c)
	}

	getString := func(t index.Track, field string) string {
		if g.Field(field) != nil {
			return ""
		}
		return t.GetString(field)
	}

	getStrings := func(t index.Track, field string) []string {
		if g.Field(field) != nil {
			return nil
		}
		return t.GetStrings(field)
	}

	getInt := func(t index.Track, field string) int {
		if g.Field(field) != nil {
			return 0
		}
		return t.GetInt(field)
	}

	for _, t := range g.Tracks() {
		h.Tracks = append(h.Tracks, track{
			ID:        t.GetString("ID"),
			Name:      t.GetString("Name"),
			TotalTime: t.GetInt("TotalTime"),
			// Potentially common fields (don't want to re-transmit everything)
			Artist:      getStrings(t, "Artist"),
			AlbumArtist: getStrings(t, "AlbumArtist"),
			Composer:    getStrings(t, "Composer"),
			Album:       getString(t, "Album"),
			Year:        getInt(t, "Year"),
			DiscNumber:  getInt(t, "DiscNumber"),
			BitRate:     getInt(t, "BitRate"),
		})
	}
	return h
}

// Fetch returns a group from the collection with the given path.
func (l *Library) Fetch(c index.Collection, path []string) (group, error) {
	if len(path) == 0 {
		return build(c, index.Key("Root")), nil
	}

	var g index.Group = c
	k := index.Key(path[0])
	g = c.Get(k)

	if g == nil {
		return group{}, fmt.Errorf("invalid path: near '%v'", path[0])
	}

	index.Sort(g.Tracks(), index.MultiSort(index.SortByInt("DiscNumber"), index.SortByInt("TrackNumber")))
	g = index.Transform(g, index.SplitList("Artist", "AlbumArtist", "Composer"))
	c = index.Collect(g, index.ByPrefix("Name"))
	g = index.SubTransform(c, index.TrimEnumPrefix)
	g = index.SumGroupIntAttr("TotalTime", g)
	commonFields := []attr.Interface{
		attr.String("Album"),
		attr.Strings("Artist"),
		attr.Strings("AlbumArtist"),
		attr.Strings("Composer"),
		attr.Int("Year"),
		attr.Int("BitRate"),
		attr.Int("DiscNumber"),
	}
	g = index.CommonGroupAttr(commonFields, g)
	g = index.RemoveEmptyCollections(g)

	for i, p := range path[1:] {
		var ok bool
		c, ok = g.(index.Collection)
		if !ok {
			return group{}, fmt.Errorf("retrieved Group is not a Collection")
		}

		k = index.Key(p)
		g = c.Get(k)
		if g == nil {
			return group{}, fmt.Errorf("invalid path near '%v'", path[1:][i])
		}

		if _, ok = g.(index.Collection); !ok {
			if i == len(path[1:])-1 {
				break
			}
			return group{}, fmt.Errorf("retrieved Group isn't a Collection: %v", p)
		}
	}
	if g == nil {
		return group{}, fmt.Errorf("could not find group")
	}
	g = index.FirstTrackAttr(attr.String("ID"), g)

	return l.annotateFavourites(path, build(g, k)), nil
}

func (l *Library) annotateFavourites(path []string, g group) group {
	keyPath := make(index.Path, len(path)+1)
	keyPath[0] = "Root"
	for i, p := range path {
		keyPath[i+1] = index.Key(p)
	}

	if len(g.Tracks) > 0 || len(g.Groups) > 0 {
		g.Favourite = l.favourites.Get(keyPath)
	}
	return g
}

// FileSystem wraps the http.FileSystem in a library lookup which will translate /ID
// requests into their corresponding track paths.
func (l *Library) FileSystem(fs store.FileSystem) store.FileSystem {
	return store.Trace(&libraryFileSystem{fs, l.Library}, "libraryFileSystem")
}

// ExpandPaths constructs a collection (group) whose sub-groups are taken from the "Root"
// collection.
func (l *Library) ExpandPaths(paths []index.Path) group {
	return build(index.NewPathsCollection(l.collections["Root"], paths), index.Key("Root"))
}
<commit_msg>Added checklist annotations to outgoing groups.<commit_after>// Copyright 2015, David Howden
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.

package main

import (
	"fmt"
	"net/http"
	"path/filepath"
	"strings"

	"golang.org/x/net/context"

	"tchaik.com/index"
	"tchaik.com/index/attr"
	"tchaik.com/index/checklist"
	"tchaik.com/index/favourite"
	"tchaik.com/store"
)

// Library is a type which encompases the components which form a full library.
type Library struct {
	index.Library

	collections map[string]index.Collection
	filters     map[string][]index.FilterItem
	recent      []index.Path
	searcher    index.Searcher
	favourites  favourite.Store
	checklist   checklist.Store
}

type libraryFileSystem struct {
	store.FileSystem
	index.Library
}

// Open implements store.FileSystem and rewrites ID values to their corresponding Location
// values using the index.Library.
func (l *libraryFileSystem) Open(ctx context.Context, path string) (http.File, error) {
	t, ok := l.Library.Track(strings.Trim(path, "/")) // IDs arrive with leading slash
	if !ok {
		return nil, fmt.Errorf("could not find track: %v", path)
	}

	loc := t.GetString("Location")
	if loc == "" {
		return nil, fmt.Errorf("invalid (empty) location for track: %v", path)
	}
	loc = filepath.ToSlash(loc)
	return l.FileSystem.Open(ctx, loc)
}

type group struct {
	Name        string
	Key         index.Key
	TotalTime   interface{} `json:",omitempty"`
	Artist      interface{} `json:",omitempty"`
	AlbumArtist interface{} `json:",omitempty"`
	Composer    interface{} `json:",omitempty"`
	BitRate     interface{} `json:",omitempty"`
	DiscNumber  interface{} `json:",omitempty"`
	ListStyle   interface{} `json:",omitempty"`
	ID          interface{} `json:",omitempty"`
	Year        interface{} `json:",omitempty"`
	Groups      []group     `json:",omitempty"`
	Tracks      []track     `json:",omitempty"`
	Favourite   bool        `json:",omitempty"`
	Checklist   bool        `json:",omitempty"`
}

type track struct {
	ID          string   `json:",omitempty"`
	Name        string   `json:",omitempty"`
	Album       string   `json:",omitempty"`
	Artist      []string `json:",omitempty"`
	AlbumArtist []string `json:",omitempty"`
	Composer    []string `json:",omitempty"`
	Year        int      `json:",omitempty"`
	DiscNumber  int      `json:",omitempty"`
	TotalTime   int      `json:",omitempty"`
	BitRate     int      `json:",omitempty"`
	Favourite   bool     `json:",omitempty"`
	Checklist   bool     `json:",omitempty"`
}

// StringSliceEqual is a function used to compare two interface{} types which are assumed
// to be of type []string (or interface{}(nil)).
func StringSliceEqual(x, y interface{}) bool {
	// Annoyingly we have to cater for zero values from map[string]interface{}
	// which don't have the correct type wrapping the nil.
	if x == nil || y == nil {
		return x == nil && y == nil
	}
	xs := x.([]string) // NB: panics here are acceptable: should not be called on a non-'Strings' field.
	ys := y.([]string)
	if len(xs) != len(ys) {
		return false
	}
	for i, xss := range xs {
		if ys[i] != xss {
			return false
		}
	}
	return true
}

func buildCollection(h group, c index.Collection) group {
	getField := func(f string, g index.Group, c index.Collection) interface{} {
		if StringSliceEqual(g.Field(f), c.Field(f)) {
			return nil
		}
		return g.Field(f)
	}

	for _, k := range c.Keys() {
		g := c.Get(k)
		g = index.FirstTrackAttr(attr.Strings("AlbumArtist"), g)
		g = index.CommonGroupAttr([]attr.Interface{attr.Strings("Artist")}, g)
		h.Groups = append(h.Groups, group{
			Name:        g.Name(),
			Key:         k,
			AlbumArtist: getField("AlbumArtist", g, c),
			Artist:      getField("Artist", g, c),
		})
	}
	return h
}

func build(g index.Group, key index.Key) group {
	h := group{
		Name:        g.Name(),
		Key:         key,
		TotalTime:   g.Field("TotalTime"),
		Artist:      g.Field("Artist"),
		AlbumArtist: g.Field("AlbumArtist"),
		Composer:    g.Field("Composer"),
		Year:        g.Field("Year"),
		BitRate:     g.Field("BitRate"),
		DiscNumber:  g.Field("DiscNumber"),
		ListStyle:   g.Field("ListStyle"),
		ID:          g.Field("ID"),
	}

	if c, ok := g.(index.Collection); ok {
		return buildCollection(h, c)
	}

	getString := func(t index.Track, field string) string {
		if g.Field(field) != nil {
			return ""
		}
		return t.GetString(field)
	}

	getStrings := func(t index.Track, field string) []string {
		if g.Field(field) != nil {
			return nil
		}
		return t.GetStrings(field)
	}

	getInt := func(t index.Track, field string) int {
		if g.Field(field) != nil {
			return 0
		}
		return t.GetInt(field)
	}

	for _, t := range g.Tracks() {
		h.Tracks = append(h.Tracks, track{
			ID:        t.GetString("ID"),
			Name:      t.GetString("Name"),
			TotalTime: t.GetInt("TotalTime"),
			// Potentially common fields (don't want to re-transmit everything)
			Artist:      getStrings(t, "Artist"),
			AlbumArtist: getStrings(t, "AlbumArtist"),
			Composer:    getStrings(t, "Composer"),
			Album:       getString(t, "Album"),
			Year:        getInt(t, "Year"),
			DiscNumber:  getInt(t, "DiscNumber"),
			BitRate:     getInt(t, "BitRate"),
		})
	}
	return h
}

// Fetch returns a group from the collection with the given path.
func (l *Library) Fetch(c index.Collection, path []string) (group, error) {
	if len(path) == 0 {
		return build(c, index.Key("Root")), nil
	}

	var g index.Group = c
	k := index.Key(path[0])
	g = c.Get(k)

	if g == nil {
		return group{}, fmt.Errorf("invalid path: near '%v'", path[0])
	}

	index.Sort(g.Tracks(), index.MultiSort(index.SortByInt("DiscNumber"), index.SortByInt("TrackNumber")))
	g = index.Transform(g, index.SplitList("Artist", "AlbumArtist", "Composer"))
	c = index.Collect(g, index.ByPrefix("Name"))
	g = index.SubTransform(c, index.TrimEnumPrefix)
	g = index.SumGroupIntAttr("TotalTime", g)
	commonFields := []attr.Interface{
		attr.String("Album"),
		attr.Strings("Artist"),
		attr.Strings("AlbumArtist"),
		attr.Strings("Composer"),
		attr.Int("Year"),
		attr.Int("BitRate"),
		attr.Int("DiscNumber"),
	}
	g = index.CommonGroupAttr(commonFields, g)
	g = index.RemoveEmptyCollections(g)

	for i, p := range path[1:] {
		var ok bool
		c, ok = g.(index.Collection)
		if !ok {
			return group{}, fmt.Errorf("retrieved Group is not a Collection")
		}

		k = index.Key(p)
		g = c.Get(k)
		if g == nil {
			return group{}, fmt.Errorf("invalid path near '%v'", path[1:][i])
		}

		if _, ok = g.(index.Collection); !ok {
			if i == len(path[1:])-1 {
				break
			}
			return group{}, fmt.Errorf("retrieved Group isn't a Collection: %v", p)
		}
	}
	if g == nil {
		return group{}, fmt.Errorf("could not find group")
	}
	g = index.FirstTrackAttr(attr.String("ID"), g)

	return l.annotateChecklist(path, l.annotateFavourites(path, build(g, k))), nil
}

func (l *Library) annotateFavourites(path []string, g group) group {
	keyPath := make(index.Path, len(path)+1)
	keyPath[0] = "Root"
	for i, p := range path {
		keyPath[i+1] = index.Key(p)
	}

	if len(g.Tracks) > 0 || len(g.Groups) > 0 {
		g.Favourite = l.favourites.Get(keyPath)
	}
	return g
}

func (l *Library) annotateChecklist(path []string, g group) group {
	keyPath := make(index.Path, len(path)+1)
	keyPath[0] = "Root"
	for i, p := range path {
		keyPath[i+1] = index.Key(p)
	}

	if len(g.Tracks) > 0 || len(g.Groups) > 0 {
		g.Checklist = l.checklist.Get(keyPath)
	}
	return g
}

// FileSystem wraps the http.FileSystem in a library lookup which will translate /ID
// requests into their corresponding track paths.
func (l *Library) FileSystem(fs store.FileSystem) store.FileSystem {
	return store.Trace(&libraryFileSystem{fs, l.Library}, "libraryFileSystem")
}

// ExpandPaths constructs a collection (group) whose sub-groups are taken from the "Root"
// collection.
func (l *Library) ExpandPaths(paths []index.Path) group {
	return build(index.NewPathsCollection(l.collections["Root"], paths), index.Key("Root"))
}
<|endoftext|>


<commit_before>package main

import (
	"bufio"
	"bytes"
	"encoding/json"
	"fmt"
	"io/ioutil"
	"os"
	"os/exec"
	"path/filepath"
	"regexp"
	"sort"
	"strings"
	"text/tabwriter"

	"github.com/pmezard/licenses/assets"
)

type Template struct {
	Title    string
	Nickname string
	Words    map[string]bool
}

func parseTemplate(content string) (*Template, error) {
	t := Template{}
	text := []byte{}
	state := 0
	scanner := bufio.NewScanner(strings.NewReader(content))
	for scanner.Scan() {
		line := strings.TrimSpace(scanner.Text())
		if state == 0 {
			if line == "---" {
				state = 1
			}
		} else if state == 1 {
			if line == "---" {
				state = 2
			} else {
				if strings.HasPrefix(line, "title:") {
					t.Title = strings.TrimSpace(line[len("title:"):])
				} else if strings.HasPrefix(line, "nickname:") {
					t.Nickname = strings.TrimSpace(line[len("nickname:"):])
				}
			}
		} else if state == 2 {
			text = append(text, scanner.Bytes()...)
			text = append(text, []byte("\n")...)
		}
	}
	t.Words = makeWordSet(text)
	return &t, scanner.Err()
}

func loadTemplates() ([]*Template, error) {
	templates := []*Template{}
	for _, a := range assets.Assets {
		templ, err := parseTemplate(a.Content)
		if err != nil {
			return nil, err
		}
		templates = append(templates, templ)
	}
	return templates, nil
}

var (
	reWords     = regexp.MustCompile(`[\w']+`)
	reCopyright = regexp.MustCompile(
		`\s*Copyright (?:©|\(c\)|\xC2\xA9)? ?(?:\d{4}|\[year\]).*?\s*`)
)

func makeWordSet(data []byte) map[string]bool {
	words := map[string]bool{}
	data = bytes.ToLower(data)
	data = reCopyright.ReplaceAll(data, nil)
	matches := reWords.FindAll(data, -1)
	for _, m := range matches {
		words[string(m)] = true
	}
	return words
}

func matchTemplates(license []byte, templates []*Template) (*Template, float64) {
	bestScore := float64(-1)
	var bestTemplate *Template
	words := makeWordSet(license)
	for _, t := range templates {
		common := 0
		for w := range words {
			if _, ok := t.Words[w]; ok {
				common++
			}
		}
		score := 2 * float64(common) / (float64(len(words)) + float64(len(t.Words)))
		if score > bestScore {
			bestScore = score
			bestTemplate = t
		}
	}
	return bestTemplate, bestScore
}

func fixEnv(gopath string) []string {
	if gopath == "" {
		return nil
	}
	kept := []string{
		"GOPATH=" + gopath,
	}
	for _, env := range os.Environ() {
		if !strings.HasPrefix(env, "GOPATH=") {
			kept = append(kept, env)
		}
	}
	return kept
}

type MissingError struct {
	Err string
}

func (err *MissingError) Error() string {
	return err.Err
}

func listDependencies(gopath, pkg string) ([]string, error) {
	templ := "{{range .Deps}}{{.}}|{{end}}"
	cmd := exec.Command("go", "list", "-f", templ, pkg)
	cmd.Env = fixEnv(gopath)
	out, err := cmd.CombinedOutput()
	if err != nil {
		if strings.Contains(string(out), "cannot find package") {
			return nil, &MissingError{Err: string(out)}
		}
		return nil, fmt.Errorf("'go list -f %s %s' failed with:\n%s",
			templ, pkg, string(out))
	}
	deps := []string{}
	for _, s := range strings.Split(string(out), "|") {
		s = strings.TrimSpace(s)
		if s != "" {
			deps = append(deps, s)
		}
	}
	sort.Strings(deps)
	return deps, nil
}

func listStandardPackages(gopath string) ([]string, error) {
	cmd := exec.Command("go", "list", "std")
	cmd.Env = fixEnv(gopath)
	out, err := cmd.CombinedOutput()
	if err != nil {
		return nil, fmt.Errorf("go list std failed with:\n%s", string(out))
	}
	names := []string{}
	for _, s := range strings.Split(string(out), "\n") {
		s = strings.TrimSpace(s)
		if s != "" {
			names = append(names, s)
		}
	}
	return names, nil
}

type PkgInfo struct {
	Name       string
	Dir        string
	Root       string
	ImportPath string
}

func getPackagesInfo(gopath string, pkgs []string) ([]*PkgInfo, error) {
	args := []string{"list", "-json"}
	// TODO: split the list for platforms which do not support massive argument
	// lists.
	args = append(args, pkgs...)
	cmd := exec.Command("go", args...)
	cmd.Env = fixEnv(gopath)
	out, err := cmd.CombinedOutput()
	if err != nil {
		return nil, fmt.Errorf("go %s failed with:\n%s",
			strings.Join(args, " "), string(out))
	}
	infos := make([]*PkgInfo, 0, len(pkgs))
	decoder := json.NewDecoder(bytes.NewBuffer(out))
	for _, pkg := range pkgs {
		info := &PkgInfo{}
		err := decoder.Decode(info)
		if err != nil {
			return nil, fmt.Errorf("could not retrieve package information for %s", pkg)
		}
		if pkg != info.ImportPath {
			return nil, fmt.Errorf("package information mismatch: asked for %s, got %s",
				pkg, info.ImportPath)
		}
		infos = append(infos, info)
	}
	return infos, err
}

var (
	licenseFiles = []string{
		"LICENSE",
		"LICENSE.txt",
		"LICENSE.md",
		"COPYING",
		"COPYRIGHT",
	}
	reLicense = regexp.MustCompile(`(?i)^(?:` +
		`((?:un)?licen[sc]e)|` +
		`((?:un)?licen[sc]e\.(?:md|markdown|txt))|` +
		`(copy(?:ing|right)(?:\.[^.]+)?)|` +
		`(licen[sc]e\.[^.]+)` +
		`)$`)
)

func scoreLicenseName(name string) float64 {
	m := reLicense.FindStringSubmatch(name)
	switch {
	case m == nil:
		break
	case m[1] != "":
		return 1.0
	case m[2] != "":
		return 0.9
	case m[3] != "":
		return 0.8
	case m[4] != "":
		return 0.7
	}
	return 0.
}

func findLicense(info *PkgInfo) (string, error) {
	path := info.ImportPath
	for ; path != "."; path = filepath.Dir(path) {
		fis, err := ioutil.ReadDir(filepath.Join(info.Root, "src", path))
		if err != nil {
			return "", err
		}
		bestScore := float64(0)
		bestName := ""
		for _, fi := range fis {
			if !fi.Mode().IsRegular() {
				continue
			}
			score := scoreLicenseName(fi.Name())
			if score > bestScore {
				bestScore = score
				bestName = fi.Name()
			}
		}
		if bestName != "" {
			return filepath.Join(path, bestName), nil
		}
	}
	return "", nil
}

type License struct {
	Package  string
	Score    float64
	Template *Template
}

func listLicenses(gopath, pkg string) ([]License, error) {
	templates, err := loadTemplates()
	if err != nil {
		return nil, err
	}
	deps, err := listDependencies(gopath, pkg)
	if err != nil {
		if _, ok := err.(*MissingError); ok {
			return nil, err
		}
		return nil, fmt.Errorf("could not list %s dependencies: %s", pkg, err)
	}
	deps = append(deps, pkg)
	std, err := listStandardPackages(gopath)
	if err != nil {
		return nil, fmt.Errorf("could not list standard packages: %s", err)
	}
	stdSet := map[string]bool{}
	for _, n := range std {
		stdSet[n] = true
	}
	infos, err := getPackagesInfo(gopath, deps)
	if err != nil {
		return nil, err
	}
	licenses := []License{}
	for _, info := range infos {
		if stdSet[info.ImportPath] {
			continue
		}
		path, err := findLicense(info)
		if err != nil {
			return nil, err
		}
		license := License{
			Package: info.ImportPath,
		}
		if path != "" {
			data, err := ioutil.ReadFile(filepath.Join(info.Root, "src", path))
			if err != nil {
				return nil, err
			}
			t, score := matchTemplates(data, templates)
			license.Score = score
			license.Template = t
		}
		licenses = append(licenses, license)
	}
	return licenses, nil
}

func printLicenses(args []string) error {
	confidence := 0.9
	licenses, err := listLicenses("", args[0])
	if err != nil {
		return err
	}
	w := tabwriter.NewWriter(os.Stdout, 1, 4, 2, ' ', 0)
	for _, l := range licenses {
		license := "?"
		if l.Template != nil {
			if l.Score >= confidence {
				license = fmt.Sprintf("%s (%2d%%)", l.Template.Title, int(100*l.Score))
			} else {
				license = fmt.Sprintf("? (%s, %2d%%)", l.Template.Title, int(100*l.Score))
			}
		}
		_, err = w.Write([]byte(l.Package + "\t" + license + "\n"))
		if err != nil {
			return err
		}
	}
	return w.Flush()
}

func main() {
	err := printLicenses(os.Args[1:])
	if err != nil {
		fmt.Fprintf(os.Stderr, "error: %s\n", err)
		os.Exit(1)
	}
}
<commit_msg>licenses: improve argument handling, add help<commit_after>package main

import (
	"bufio"
	"bytes"
	"encoding/json"
	"flag"
	"fmt"
	"io/ioutil"
	"os"
	"os/exec"
	"path/filepath"
	"regexp"
	"sort"
	"strings"
	"text/tabwriter"

	"github.com/pmezard/licenses/assets"
)

type Template struct {
	Title    string
	Nickname string
	Words    map[string]bool
}

func parseTemplate(content string) (*Template, error) {
	t := Template{}
	text := []byte{}
	state := 0
	scanner := bufio.NewScanner(strings.NewReader(content))
	for scanner.Scan() {
		line := strings.TrimSpace(scanner.Text())
		if state == 0 {
			if line == "---" {
				state = 1
			}
		} else if state == 1 {
			if line == "---" {
				state = 2
			} else {
				if strings.HasPrefix(line, "title:") {
					t.Title = strings.TrimSpace(line[len("title:"):])
				} else if strings.HasPrefix(line, "nickname:") {
					t.Nickname = strings.TrimSpace(line[len("nickname:"):])
				}
			}
		} else if state == 2 {
			text = append(text, scanner.Bytes()...)
			text = append(text, []byte("\n")...)
		}
	}
	t.Words = makeWordSet(text)
	return &t, scanner.Err()
}

func loadTemplates() ([]*Template, error) {
	templates := []*Template{}
	for _, a := range assets.Assets {
		templ, err := parseTemplate(a.Content)
		if err != nil {
			return nil, err
		}
		templates = append(templates, templ)
	}
	return templates, nil
}

var (
	reWords     = regexp.MustCompile(`[\w']+`)
	reCopyright = regexp.MustCompile(
		`\s*Copyright (?:©|\(c\)|\xC2\xA9)? ?(?:\d{4}|\[year\]).*?\s*`)
)

func makeWordSet(data []byte) map[string]bool {
	words := map[string]bool{}
	data = bytes.ToLower(data)
	data = reCopyright.ReplaceAll(data, nil)
	matches := reWords.FindAll(data, -1)
	for _, m := range matches {
		words[string(m)] = true
	}
	return words
}

func matchTemplates(license []byte, templates []*Template) (*Template, float64) {
	bestScore := float64(-1)
	var bestTemplate *Template
	words := makeWordSet(license)
	for _, t := range templates {
		common := 0
		for w := range words {
			if _, ok := t.Words[w]; ok {
				common++
			}
		}
		score := 2 * float64(common) / (float64(len(words)) + float64(len(t.Words)))
		if score > bestScore {
			bestScore = score
			bestTemplate = t
		}
	}
	return bestTemplate, bestScore
}

func fixEnv(gopath string) []string {
	if gopath == "" {
		return nil
	}
	kept := []string{
		"GOPATH=" + gopath,
	}
	for _, env := range os.Environ() {
		if !strings.HasPrefix(env, "GOPATH=") {
			kept = append(kept, env)
		}
	}
	return kept
}

type MissingError struct {
	Err string
}

func (err *MissingError) Error() string {
	return err.Err
}

func listDependencies(gopath, pkg string) ([]string, error) {
	templ := "{{range .Deps}}{{.}}|{{end}}"
	cmd := exec.Command("go", "list", "-f", templ, pkg)
	cmd.Env = fixEnv(gopath)
	out, err := cmd.CombinedOutput()
	if err != nil {
		if strings.Contains(string(out), "cannot find package") {
			return nil, &MissingError{Err: string(out)}
		}
		return nil, fmt.Errorf("'go list -f %s %s' failed with:\n%s",
			templ, pkg, string(out))
	}
	deps := []string{}
	for _, s := range strings.Split(string(out), "|") {
		s = strings.TrimSpace(s)
		if s != "" {
			deps = append(deps, s)
		}
	}
	sort.Strings(deps)
	return deps, nil
}

func listStandardPackages(gopath string) ([]string, error) {
	cmd := exec.Command("go", "list", "std")
	cmd.Env = fixEnv(gopath)
	out, err := cmd.CombinedOutput()
	if err != nil {
		return nil, fmt.Errorf("go list std failed with:\n%s", string(out))
	}
	names := []string{}
	for _, s := range strings.Split(string(out), "\n") {
		s = strings.TrimSpace(s)
		if s != "" {
			names = append(names, s)
		}
	}
	return names, nil
}

type PkgInfo struct {
	Name       string
	Dir        string
	Root       string
	ImportPath string
}

func getPackagesInfo(gopath string, pkgs []string) ([]*PkgInfo, error) {
	args := []string{"list", "-json"}
	// TODO: split the list for platforms which do not support massive argument
	// lists.
	args = append(args, pkgs...)
	cmd := exec.Command("go", args...)
	cmd.Env = fixEnv(gopath)
	out, err := cmd.CombinedOutput()
	if err != nil {
		return nil, fmt.Errorf("go %s failed with:\n%s",
			strings.Join(args, " "), string(out))
	}
	infos := make([]*PkgInfo, 0, len(pkgs))
	decoder := json.NewDecoder(bytes.NewBuffer(out))
	for _, pkg := range pkgs {
		info := &PkgInfo{}
		err := decoder.Decode(info)
		if err != nil {
			return nil, fmt.Errorf("could not retrieve package information for %s", pkg)
		}
		if pkg != info.ImportPath {
			return nil, fmt.Errorf("package information mismatch: asked for %s, got %s",
				pkg, info.ImportPath)
		}
		infos = append(infos, info)
	}
	return infos, err
}

var (
	licenseFiles = []string{
		"LICENSE",
		"LICENSE.txt",
		"LICENSE.md",
		"COPYING",
		"COPYRIGHT",
	}
	reLicense = regexp.MustCompile(`(?i)^(?:` +
		`((?:un)?licen[sc]e)|` +
		`((?:un)?licen[sc]e\.(?:md|markdown|txt))|` +
		`(copy(?:ing|right)(?:\.[^.]+)?)|` +
		`(licen[sc]e\.[^.]+)` +
		`)$`)
)

func scoreLicenseName(name string) float64 {
	m := reLicense.FindStringSubmatch(name)
	switch {
	case m == nil:
		break
	case m[1] != "":
		return 1.0
	case m[2] != "":
		return 0.9
	case m[3] != "":
		return 0.8
	case m[4] != "":
		return 0.7
	}
	return 0.
}

func findLicense(info *PkgInfo) (string, error) {
	path := info.ImportPath
	for ; path != "."; path = filepath.Dir(path) {
		fis, err := ioutil.ReadDir(filepath.Join(info.Root, "src", path))
		if err != nil {
			return "", err
		}
		bestScore := float64(0)
		bestName := ""
		for _, fi := range fis {
			if !fi.Mode().IsRegular() {
				continue
			}
			score := scoreLicenseName(fi.Name())
			if score > bestScore {
				bestScore = score
				bestName = fi.Name()
			}
		}
		if bestName != "" {
			return filepath.Join(path, bestName), nil
		}
	}
	return "", nil
}

type License struct {
	Package  string
	Score    float64
	Template *Template
}

func listLicenses(gopath, pkg string) ([]License, error) {
	templates, err := loadTemplates()
	if err != nil {
		return nil, err
	}
	deps, err := listDependencies(gopath, pkg)
	if err != nil {
		if _, ok := err.(*MissingError); ok {
			return nil, err
		}
		return nil, fmt.Errorf("could not list %s dependencies: %s", pkg, err)
	}
	deps = append(deps, pkg)
	std, err := listStandardPackages(gopath)
	if err != nil {
		return nil, fmt.Errorf("could not list standard packages: %s", err)
	}
	stdSet := map[string]bool{}
	for _, n := range std {
		stdSet[n] = true
	}
	infos, err := getPackagesInfo(gopath, deps)
	if err != nil {
		return nil, err
	}
	licenses := []License{}
	for _, info := range infos {
		if stdSet[info.ImportPath] {
			continue
		}
		path, err := findLicense(info)
		if err != nil {
			return nil, err
		}
		license := License{
			Package: info.ImportPath,
		}
		if path != "" {
			data, err := ioutil.ReadFile(filepath.Join(info.Root, "src", path))
			if err != nil {
				return nil, err
			}
			t, score := matchTemplates(data, templates)
			license.Score = score
			license.Template = t
		}
		licenses = append(licenses, license)
	}
	return licenses, nil
}

func printLicenses() error {
	flag.Usage = func() {
		fmt.Println(`Usage: licenses IMPORTPATH

licenses lists all dependencies of specified package or command, excluding
standard library packages, and prints their licenses. Licenses are detected by
looking for files named like LICENSE, COPYING, COPYRIGHT and other variants in
the package directory, and its parent directories until one is found. Files
content is matched against a set of well-known licenses and the best match is
displayed along with its score.
`)
		os.Exit(1)
	}
	flag.Parse()
	if flag.NArg() != 1 {
		return fmt.Errorf("expect a single package argument, got %d", flag.NArg())
	}
	pkg := flag.Arg(0)

	confidence := 0.9
	licenses, err := listLicenses("", pkg)
	if err != nil {
		return err
	}
	w := tabwriter.NewWriter(os.Stdout, 1, 4, 2, ' ', 0)
	for _, l := range licenses {
		license := "?"
		if l.Template != nil {
			if l.Score >= confidence {
				license = fmt.Sprintf("%s (%2d%%)", l.Template.Title, int(100*l.Score))
			} else {
				license = fmt.Sprintf("? (%s, %2d%%)", l.Template.Title, int(100*l.Score))
			}
		}
		_, err = w.Write([]byte(l.Package + "\t" + license + "\n"))
		if err != nil {
			return err
		}
	}
	return w.Flush()
}

func main() {
	err := printLicenses()
	if err != nil {
		fmt.Fprintf(os.Stderr, "error: %s\n", err)
		os.Exit(1)
	}
}
<|endoftext|>


<commit_before>package main

import (
  "flag"
  "fmt"
  "math/rand"
  "os"
  "runtime"
  "strconv"
  "strings"
  "sync"
  "time"
)

type Lifegame struct {
  Width int
  Height int
  Field []int
  nextField []int
}

func NewLifegame(w int, h int, n int) *Lifegame {
  res := &Lifegame{w, h, make([]int, w*h), make([]int, w*h)}
  rand.Seed(time.Now().Unix())
  for i:=0; i<n; i++ {
    x := rand.Intn(w)
    y := rand.Intn(h)
    res.Set(x, y, 1)
  }
  return res
}

func (self *Lifegame) Get(x int, y int) int {
  return self.Field[x + y*self.Width]
}

func (self *Lifegame) Set(x int, y int, val int) {
  self.Field[x + y*self.Width] = val
}

func (self *Lifegame) Print() {
  for y:=0; y<self.Height; y++ {
    for x:=0; x<self.Width; x++ {
      var s string
      if self.Get(x,y) == 0 {
        s = "__"
      } else {
        s = "[]"
      }
      fmt.Printf("%s", s)
    }
    fmt.Printf("\n")
  }
}

func (self *Lifegame) CellNext(idx int) int {
  w := self.Width
  delta := [8]int{-w-1, -w, -w+1, -1, 1, w-1, w, w+1}

  numAlive := 0
  for _, d := range delta {
    i := idx + d
    if 0 <= i && i < len(self.Field) && self.Field[i] != 0 {
      numAlive++
    }
  }
  life := self.Field[idx]
  if (life==0 && numAlive==3) || (life==1 && (numAlive==2 || numAlive==3)) {
    return 1
  }
  return 0
}

func (self *Lifegame) Update(numRoutine int) {
  m := len(self.Field)/numRoutine
  var wg sync.WaitGroup
  for i:=0; i<len(self.Field); i+=m {
    wg.Add(1)
    go func(first int, last int) {
      for j:=first; j<last; j++ {
        self.nextField[j] = self.CellNext(j)
      }
      wg.Done()
    }(i, i+m)
  }
  wg.Wait()
  self.Field, self.nextField = self.nextField, self.Field
}

func parseSize(size string) (int, int) {
  sep := strings.Index(size, "x")
  w, errw := strconv.Atoi(size[:sep])
  h, errh := strconv.Atoi(size[sep+1:])
  if errw != nil || errh != nil {
    fmt.Printf("Invalid flag --size='%s'\n", size)
    os.Exit(1)
  }
  return w, h
}

func main() {
  size  := flag.String("size", "10x10", "Size of field. e.g. 10x10")
  steps := flag.Int("steps", 50, "Number of steps")
  procs := flag.Int("procs", 1, "Number of procs to run")
  flag.Parse()

  w, h := parseSize(*size)

  fmt.Printf("Procs: %d\n", *procs)
  fmt.Printf("Field: %dx%d\n", w, h)
  runtime.GOMAXPROCS(*procs)

  lifegame := NewLifegame(w, h, w*h/4)
  lifegame.Print()

  for t:=0; t<*steps; t++ {
    fmt.Println("\n", t)
    lifegame.Update(*procs)
    lifegame.Print()
    time.Sleep(time.Second/10)
  }
}
<commit_msg>use escape sequence<commit_after>package main

import (
  "flag"
  "fmt"
  "math/rand"
  "os"
  "runtime"
  "strconv"
  "strings"
  "sync"
  "time"
)

type Lifegame struct {
  Width int
  Height int
  Field []int
  nextField []int
}

func NewLifegame(w int, h int, n int) *Lifegame {
  res := &Lifegame{w, h, make([]int, w*h), make([]int, w*h)}
  rand.Seed(time.Now().Unix())
  for i:=0; i<n; i++ {
    x := rand.Intn(w)
    y := rand.Intn(h)
    res.Set(x, y, 1)
  }
  return res
}

func (self *Lifegame) Get(x int, y int) int {
  return self.Field[x + y*self.Width]
}

func (self *Lifegame) Set(x int, y int, val int) {
  self.Field[x + y*self.Width] = val
}

func (self *Lifegame) Print() {
  for y:=0; y<self.Height; y++ {
    for x:=0; x<self.Width; x++ {
      var s string
      if self.Get(x,y) == 0 {
        s = "__"
      } else {
        s = "[]"
      }
      fmt.Printf("%s", s)
    }
    fmt.Printf("\n")
  }
}

func (self *Lifegame) CellNext(idx int) int {
  w := self.Width
  delta := [8]int{-w-1, -w, -w+1, -1, 1, w-1, w, w+1}

  numAlive := 0
  for _, d := range delta {
    i := idx + d
    if 0 <= i && i < len(self.Field) && self.Field[i] != 0 {
      numAlive++
    }
  }
  life := self.Field[idx]
  if (life==0 && numAlive==3) || (life==1 && (numAlive==2 || numAlive==3)) {
    return 1
  }
  return 0
}

func (self *Lifegame) Update(numRoutine int) {
  m := len(self.Field)/numRoutine
  var wg sync.WaitGroup
  for i:=0; i<len(self.Field); i+=m {
    wg.Add(1)
    go func(first int, last int) {
      for j:=first; j<last; j++ {
        self.nextField[j] = self.CellNext(j)
      }
      wg.Done()
    }(i, i+m)
  }
  wg.Wait()
  self.Field, self.nextField = self.nextField, self.Field
}

func parseSize(size string) (int, int) {
  sep := strings.Index(size, "x")
  w, errw := strconv.Atoi(size[:sep])
  h, errh := strconv.Atoi(size[sep+1:])
  if errw != nil || errh != nil {
    fmt.Printf("Invalid flag --size='%s'\n", size)
    os.Exit(1)
  }
  return w, h
}

func main() {
  size  := flag.String("size", "10x10", "Size of field. e.g. 10x10")
  steps := flag.Int("steps", 1000, "Number of steps")
  procs := flag.Int("procs", 1, "Number of procs to run")
  flag.Parse()

  w, h := parseSize(*size)

  fmt.Printf("Procs: %d\n", *procs)
  fmt.Printf("Field: %dx%d\n", w, h)
  runtime.GOMAXPROCS(*procs)

  lifegame := NewLifegame(w, h, w*h/4)
  lifegame.Print()

  for t:=0; t<*steps; t++ {
    print("\033[2J")
    print("\033[0;0H")
    fmt.Println("\n", t)
    lifegame.Update(*procs)
    lifegame.Print()
    time.Sleep(time.Second/10)
  }
}
<|endoftext|>


<commit_before>//go:generate go run generate.go

// Copyright 2016 govend. All rights reserved.
// Use of this source code is governed by an Apache 2.0
// license that can be found in the LICENSE file.

// Package filters provides filters for Go package import paths.
package filters

import (
	"errors"
	"log"
	"os"
	"path"
	"path/filepath"
	"strings"
)

// Standard filters out standard packages.
func Standard(pkgs []string) []string {

	var list []string
	for _, pkg := range pkgs {

		// skip CGO and any relative import paths
		if pkg == "C" || pkg[0] == '.' {
			continue
		}

		name := path.Base(pkg)
		if stds, ok := stdpkgs[name]; ok {
			for _, stdpkg := range stds {
				if pkg == stdpkg.path {
					goto SKIP
				}
			}
		}
		list = append(list, pkg)

	SKIP:
	}

	return list
}

// Exceptions filters out very special exceptional packages.
func Exceptions(pkgs []string) []string {

	var list []string
	for _, pkg := range pkgs {

		for _, exception := range ExceptionList {
			if Match(pkg, exception) {
				goto SKIP
			}
		}
		list = append(list, pkg)

	SKIP:
	}

	return list
}

// Duplicates filters out any duplicate packages.
func Duplicates(pkgs []string) []string {
	result := []string{}
	seen := map[string]string{}
	for _, val := range pkgs {
		if _, ok := seen[val]; !ok {
			result = append(result, val)
			seen[val] = val
		}
	}
	return result
}

// Local filters out any local packages.
func Local(pkgs []string) []string {

	prefix := projectImportPath()
	l := len(prefix)

	var list []string
	for _, pkg := range pkgs {

		// check the item length is geater than or equal to the prefix length
		// this ensures no out of bounds memory errors will occur
		if len(pkg) >= l {
			if prefix == pkg[:l] {
				continue
			}
		}

		list = append(list, pkg)
	}

	return list
}

// Ellipses trims the ellipses suffix off of package import paths.
func Ellipses(pkgs []string) []string {
	var list []string
	for _, pkg := range pkgs {
		pkg = strings.TrimSuffix(pkg, "/.../")
		pkg = strings.TrimSuffix(pkg, "/...")
		list = append(list, pkg)
	}
	return list
}

// Godeps filters out Godeps package import paths.
func Godeps(pkgs []string) []string {
	var list []string
	for _, pkg := range pkgs {
		if strings.Contains(pkg, "/Godeps/_workspace/src/") {
			split := strings.SplitAfter(pkg, "/Godeps/_workspace/src/")
			if len(split) > 1 {
				pkg = split[1]
			}
		}
		list = append(list, pkg)
	}
	return list
}

// projectImportPath returns the import path of the current working directory.
// It does so by trimming off the $GOPATH/src prefix.
func projectImportPath() string {
	// determine the current working directory and coerce it to an absolute
	cwd, err := os.Getwd()
	if err != nil {
		log.Fatal(err)
	}
	cwd, err = filepath.Abs(cwd)
	if err != nil {
		log.Fatal(err)
	}

	// check the env $GOPATH is valid
	gopath := os.Getenv("GOPATH")
	if len(gopath) == 0 {
		log.Fatal(errors.New("$GOPATH not set"))
	}

	// trim the $GOPATH/src off the current working directory
	gosrc := filepath.Join(gopath, "src") + string(filepath.Separator)
	importpath := strings.TrimPrefix(cwd, gosrc)
	dir, file := filepath.Split(importpath)
	return path.Join(dir, file)
}
<commit_msg>Fix a bug where the prefix of local packages is incorrect<commit_after>//go:generate go run generate.go

// Copyright 2016 govend. All rights reserved.
// Use of this source code is governed by an Apache 2.0
// license that can be found in the LICENSE file.

// Package filters provides filters for Go package import paths.
package filters

import (
	"errors"
	"log"
	"os"
	"path"
	"path/filepath"
	"strings"
)

// Standard filters out standard packages.
func Standard(pkgs []string) []string {

	var list []string
	for _, pkg := range pkgs {

		// skip CGO and any relative import paths
		if pkg == "C" || pkg[0] == '.' {
			continue
		}

		name := path.Base(pkg)
		if stds, ok := stdpkgs[name]; ok {
			for _, stdpkg := range stds {
				if pkg == stdpkg.path {
					goto SKIP
				}
			}
		}
		list = append(list, pkg)

	SKIP:
	}

	return list
}

// Exceptions filters out very special exceptional packages.
func Exceptions(pkgs []string) []string {

	var list []string
	for _, pkg := range pkgs {

		for _, exception := range ExceptionList {
			if Match(pkg, exception) {
				goto SKIP
			}
		}
		list = append(list, pkg)

	SKIP:
	}

	return list
}

// Duplicates filters out any duplicate packages.
func Duplicates(pkgs []string) []string {
	result := []string{}
	seen := map[string]string{}
	for _, val := range pkgs {
		if _, ok := seen[val]; !ok {
			result = append(result, val)
			seen[val] = val
		}
	}
	return result
}

// Local filters out any local packages.
func Local(pkgs []string) []string {
	projectPath := projectImportPath()
	prefix := projectPath + "/"

	var list []string
	for _, pkg := range pkgs {
		if pkg == projectPath || strings.HasPrefix(pkg, prefix) {
			continue
		}

		list = append(list, pkg)
	}

	return list
}

// Ellipses trims the ellipses suffix off of package import paths.
func Ellipses(pkgs []string) []string {
	var list []string
	for _, pkg := range pkgs {
		pkg = strings.TrimSuffix(pkg, "/.../")
		pkg = strings.TrimSuffix(pkg, "/...")
		list = append(list, pkg)
	}
	return list
}

// Godeps filters out Godeps package import paths.
func Godeps(pkgs []string) []string {
	var list []string
	for _, pkg := range pkgs {
		if strings.Contains(pkg, "/Godeps/_workspace/src/") {
			split := strings.SplitAfter(pkg, "/Godeps/_workspace/src/")
			if len(split) > 1 {
				pkg = split[1]
			}
		}
		list = append(list, pkg)
	}
	return list
}

// projectImportPath returns the import path of the current working directory.
// It does so by trimming off the $GOPATH/src prefix.
func projectImportPath() string {
	// determine the current working directory and coerce it to an absolute
	cwd, err := os.Getwd()
	if err != nil {
		log.Fatal(err)
	}
	cwd, err = filepath.Abs(cwd)
	if err != nil {
		log.Fatal(err)
	}

	// check the env $GOPATH is valid
	gopath := os.Getenv("GOPATH")
	if len(gopath) == 0 {
		log.Fatal(errors.New("$GOPATH not set"))
	}

	// trim the $GOPATH/src off the current working directory
	gosrc := filepath.Join(gopath, "src") + string(filepath.Separator)
	importpath := strings.TrimPrefix(cwd, gosrc)
	dir, file := filepath.Split(importpath)
	return path.Join(dir, file)
}
<|endoftext|>


<commit_before>package btcsubprotos

import (
	"bytes"

	"github.com/conformal/btcscript"
	"github.com/conformal/btcwire"
)

func IsBulletin(tx *btcwire.MsgTx) bool {
	// Takes a TX and determines if it is an ahimsa bulletin.
	magic := Ahimsa.Magic
	return matchFirstOut(tx, magic) && len(tx.TxOut) > 1
}

func IsCounterParty(tx *btcwire.MsgTx) bool {
	// Tries to match pushed data to the counterparty format
	magic := CounterParty.Magic

	for _, txout := range tx.TxOut {
		outdata, err := btcscript.PushedData(txout.PkScript)
		if err != nil {
			return false
		}
		for _, push := range outdata {
			if len(push) < 1+len(magic) {
				continue
			}
			// OP_RETURN
			if bytes.Equal(push[:len(magic)], magic) {
				return true
			}
			// Data encoded in public key (First byte is for faking a ECDSA PK).
			if bytes.Equal(push[1:len(magic)+1], magic) {
				return true
			}
		}
	}
	return false
}

func matchFirstOut(tx *btcwire.MsgTx, magic []byte) bool {
	// Tests to see if the first txout in the tx matches the magic bytes.
	firstOutScript := tx.TxOut[0].PkScript

	outdata, err := btcscript.PushedData(firstOutScript)
	if err != nil {
		return false
	}
	if len(outdata[0]) > len(magic) {
		firstpush := outdata[0]
		if bytes.Equal(firstpush[:len(magic)], magic) {
			return true
		}
	}
	return false
}

func IsDocProof(tx *btcwire.MsgTx) bool {
	// Checks to see if tx is a docproof message by looking at its first output.
	magic := DocProof.Magic
	return matchFirstOut(tx, magic)
}
<commit_msg>Error handling<commit_after>package btcsubprotos

import (
	"bytes"

	"github.com/conformal/btcscript"
	"github.com/conformal/btcwire"
)

func IsBulletin(tx *btcwire.MsgTx) bool {
	// Takes a TX and determines if it is an ahimsa bulletin.
	magic := Ahimsa.Magic
	return matchFirstOut(tx, magic) && len(tx.TxOut) > 1
}

func IsCounterParty(tx *btcwire.MsgTx) bool {
	// Tries to match pushed data to the counterparty format
	magic := CounterParty.Magic

	for _, txout := range tx.TxOut {
		outdata, err := btcscript.PushedData(txout.PkScript)
		if err != nil {
			return false
		}
		for _, push := range outdata {
			if len(push) < 1+len(magic) {
				continue
			}
			// OP_RETURN
			if bytes.Equal(push[:len(magic)], magic) {
				return true
			}
			// Data encoded in public key (First byte is for faking a ECDSA PK).
			if bytes.Equal(push[1:len(magic)+1], magic) {
				return true
			}
		}
	}
	return false
}

func matchFirstOut(tx *btcwire.MsgTx, magic []byte) bool {
	// Tests to see if the first txout in the tx matches the magic bytes.
	if len(tx.TxOut) == 0 {
		return false
	}
	firstOutScript := tx.TxOut[0].PkScript

	outdata, err := btcscript.PushedData(firstOutScript)
	if err != nil {
		return false
	}
	if len(outdata) > 0 && len(outdata[0]) > len(magic) {
		firstpush := outdata[0]
		if bytes.Equal(firstpush[:len(magic)], magic) {
			return true
		}
	}
	return false
}

func IsDocProof(tx *btcwire.MsgTx) bool {
	// Checks to see if tx is a docproof message by looking at its first output.
	magic := DocProof.Magic
	return matchFirstOut(tx, magic)
}
<|endoftext|>


<commit_before>package main

import (
	"flag"
	"fmt"
	"html/template"
	"io"
	"io/ioutil"
	"log"
	"mime"
	"net/http"
	"net/url"
	"os"
	"path"
	"path/filepath"
	"strconv"
	"time"
	tarantula "github.com/swdunlop/tarantula-go"
)

func main() {
	flag.StringVar(&cfg.Bind, `b`, `127.0.0.1:8080`, `HTTP server listen address`)
	flag.StringVar(&cfg.Title, `t`, `Live Fire Exercise`, `title for generated HTML page`)
	flag.StringVar(&cfg.Fwd, `r`, ``, `URL backing any unrecognized paths`)
	flag.Usage = usage
	flag.Parse()

	err := livefireMain()
	if err != nil {
		println("!!", err.Error())
		os.Exit(1)
	}
}

func usage() {
	println(`USAGE: livefire [FLAGS...] FILES...`)
	println(`FLAGS:`)
	flag.PrintDefaults()
	println(helpText)
}

var helpText = `
Livefire serves a number of local files on the command line and constructs
skeleton HTML page around them that will automatically refresh when any of the
files change according to the operating system.  The composition of this file
depends on the extension of the files provided on the command line:

    .css   wrapped with a
{{end}}{{range .JS}}

{{end}}{{range .HTML}}
  {{.}}
{{end}}`))
<commit_msg>support URLs to CSS and JavaScript on CDNs<commit_after>package main

import (
	"flag"
	"fmt"
	"html/template"
	"io"
	"io/ioutil"
	"log"
	"mime"
	"net/http"
	"net/url"
	"os"
	"path"
	"path/filepath"
	"strconv"
	"time"
	tarantula "github.com/swdunlop/tarantula-go"
)

func main() {
	flag.StringVar(&cfg.Bind, `b`, `127.0.0.1:8080`, `HTTP server listen address`)
	flag.StringVar(&cfg.Title, `t`, `Live Fire Exercise`, `title for generated HTML page`)
	flag.StringVar(&cfg.Fwd, `r`, ``, `URL backing any unrecognized paths`)
	flag.Usage = usage
	flag.Parse()
	err := livefireMain(flag.Args()...)
	if err != nil {
		println("!!", err.Error())
		os.Exit(1)
	}
}

func usage() {
	println(`USAGE: livefire [FLAGS...] CONTENTS...`)
	println(`FLAGS:`)
	flag.PrintDefaults()
	println(helpText)
	os.Exit(2)
}

var helpText = `
Livefire serves a number of local files on the command line and generates a
skeleton HTML page around them that will automatically refresh when any of the
files change according to the operating system.  The composition of this file
depends on the extension of the files provided on the command line:

    .css   wrapped with a
{{end}}{{range .Cfg.CDN.JS}}

{{end}}{{range .JS}}

{{end}}{{range .HTML}}
  {{.}}
{{end}}`))
<|endoftext|>


<commit_before>/*
   Copyright 2014 CoreOS, Inc.

   Licensed under the Apache License, Version 2.0 (the "License");
   you may not use this file except in compliance with the License.
   You may obtain a copy of the License at

       http://www.apache.org/licenses/LICENSE-2.0

   Unless required by applicable law or agreed to in writing, software
   distributed under the License is distributed on an "AS IS" BASIS,
   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
   See the License for the specific language governing permissions and
   limitations under the License.
*/

package etcdserver

import (
	"bytes"
	"fmt"
	"log"
	"net/http"
	"time"

	"github.com/coreos/etcd/etcdserver/stats"
	"github.com/coreos/etcd/pkg/types"
	"github.com/coreos/etcd/raft/raftpb"
)

const raftPrefix = "/raft"

// Sender creates the default production sender used to transport raft messages
// in the cluster. The returned sender will update the given ServerStats and
// LeaderStats appropriately.
func Sender(t *http.Transport, cl *Cluster, ss *stats.ServerStats, ls *stats.LeaderStats) func(msgs []raftpb.Message) {
	c := &http.Client{Transport: t}

	return func(msgs []raftpb.Message) {
		for _, m := range msgs {
			// TODO: reuse go routines
			// limit the number of outgoing connections for the same receiver
			go send(c, cl, m, ss, ls)
		}
	}
}

// send uses the given client to send a message to a member in the given
// ClusterStore, retrying up to 3 times for each message. The given
// ServerStats and LeaderStats are updated appropriately
func send(c *http.Client, cl *Cluster, m raftpb.Message, ss *stats.ServerStats, ls *stats.LeaderStats) {
	to := types.ID(m.To)
	cid := cl.ID()
	// TODO (xiangli): reasonable retry logic
	for i := 0; i < 3; i++ {
		memb := cl.Member(to)
		if memb == nil {
			if !cl.IsIDRemoved(to) {
				// TODO: unknown peer id.. what do we do? I
				// don't think his should ever happen, need to
				// look into this further.
				log.Printf("etcdserver: error sending message to unknown receiver %s", to.String())
			}
			return
		}
		u := fmt.Sprintf("%s%s", memb.PickPeerURL(), raftPrefix)

		// TODO: don't block. we should be able to have 1000s
		// of messages out at a time.
		data, err := m.Marshal()
		if err != nil {
			log.Println("sender: dropping message:", err)
			return // drop bad message
		}
		if m.Type == raftpb.MsgApp {
			ss.SendAppendReq(len(data))
		}
		fs := ls.Follower(to.String())

		start := time.Now()
		sent := httpPost(c, u, cid, data)
		end := time.Now()
		if sent {
			fs.Succ(end.Sub(start))
			return
		}
		fs.Fail()
		// TODO: backoff
	}
}

// httpPost POSTs a data payload to a url using the given client. Returns true
// if the POST succeeds, false on any failure.
func httpPost(c *http.Client, url string, cid types.ID, data []byte) bool {
	req, err := http.NewRequest("POST", url, bytes.NewBuffer(data))
	if err != nil {
		// TODO: log the error?
		return false
	}
	req.Header.Set("Content-Type", "application/protobuf")
	req.Header.Set("X-Etcd-Cluster-ID", cid.String())
	resp, err := c.Do(req)
	if err != nil {
		// TODO: log the error?
		return false
	}
	resp.Body.Close()

	switch resp.StatusCode {
	case http.StatusPreconditionFailed:
		// TODO: shutdown the etcdserver gracefully?
		log.Fatalf("etcd: conflicting cluster ID with the target cluster (%s != %s). Exiting.", resp.Header.Get("X-Etcd-Cluster-ID"), cid.String())
		return false
	case http.StatusForbidden:
		// TODO: stop the server
		log.Fatalf("etcd: this member has been permanently removed from the cluster. Exiting.")
		return false
	case http.StatusNoContent:
		return true
	default:
		return false
	}
}
<commit_msg>etcdserver: better logging when member is removed<commit_after>/*
   Copyright 2014 CoreOS, Inc.

   Licensed under the Apache License, Version 2.0 (the "License");
   you may not use this file except in compliance with the License.
   You may obtain a copy of the License at

       http://www.apache.org/licenses/LICENSE-2.0

   Unless required by applicable law or agreed to in writing, software
   distributed under the License is distributed on an "AS IS" BASIS,
   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
   See the License for the specific language governing permissions and
   limitations under the License.
*/

package etcdserver

import (
	"bytes"
	"fmt"
	"log"
	"net/http"
	"time"

	"github.com/coreos/etcd/etcdserver/stats"
	"github.com/coreos/etcd/pkg/types"
	"github.com/coreos/etcd/raft/raftpb"
)

const raftPrefix = "/raft"

// Sender creates the default production sender used to transport raft messages
// in the cluster. The returned sender will update the given ServerStats and
// LeaderStats appropriately.
func Sender(t *http.Transport, cl *Cluster, ss *stats.ServerStats, ls *stats.LeaderStats) func(msgs []raftpb.Message) {
	c := &http.Client{Transport: t}

	return func(msgs []raftpb.Message) {
		for _, m := range msgs {
			// TODO: reuse go routines
			// limit the number of outgoing connections for the same receiver
			go send(c, cl, m, ss, ls)
		}
	}
}

// send uses the given client to send a message to a member in the given
// ClusterStore, retrying up to 3 times for each message. The given
// ServerStats and LeaderStats are updated appropriately
func send(c *http.Client, cl *Cluster, m raftpb.Message, ss *stats.ServerStats, ls *stats.LeaderStats) {
	to := types.ID(m.To)
	cid := cl.ID()
	// TODO (xiangli): reasonable retry logic
	for i := 0; i < 3; i++ {
		memb := cl.Member(to)
		if memb == nil {
			if !cl.IsIDRemoved(to) {
				// TODO: unknown peer id.. what do we do? I
				// don't think his should ever happen, need to
				// look into this further.
				log.Printf("etcdserver: error sending message to unknown receiver %s", to.String())
			}
			return
		}
		u := fmt.Sprintf("%s%s", memb.PickPeerURL(), raftPrefix)

		// TODO: don't block. we should be able to have 1000s
		// of messages out at a time.
		data, err := m.Marshal()
		if err != nil {
			log.Println("sender: dropping message:", err)
			return // drop bad message
		}
		if m.Type == raftpb.MsgApp {
			ss.SendAppendReq(len(data))
		}
		fs := ls.Follower(to.String())

		start := time.Now()
		sent := httpPost(c, u, cid, data)
		end := time.Now()
		if sent {
			fs.Succ(end.Sub(start))
			return
		}
		fs.Fail()
		// TODO: backoff
	}
}

// httpPost POSTs a data payload to a url using the given client. Returns true
// if the POST succeeds, false on any failure.
func httpPost(c *http.Client, url string, cid types.ID, data []byte) bool {
	req, err := http.NewRequest("POST", url, bytes.NewBuffer(data))
	if err != nil {
		// TODO: log the error?
		return false
	}
	req.Header.Set("Content-Type", "application/protobuf")
	req.Header.Set("X-Etcd-Cluster-ID", cid.String())
	resp, err := c.Do(req)
	if err != nil {
		// TODO: log the error?
		return false
	}
	resp.Body.Close()

	switch resp.StatusCode {
	case http.StatusPreconditionFailed:
		// TODO: shutdown the etcdserver gracefully?
		log.Fatalf("etcd: conflicting cluster ID with the target cluster (%s != %s)", resp.Header.Get("X-Etcd-Cluster-ID"), cid.String())
		return false
	case http.StatusForbidden:
		// TODO: stop the server
		log.Println("etcd: this member has been permanently removed from the cluster")
		log.Fatalln("etcd: the data-dir used by this member must be removed so that this host can be re-added with a new member ID")
		return false
	case http.StatusNoContent:
		return true
	default:
		return false
	}
}
<|endoftext|>


<commit_before>package aws

import (
	"fmt"
	"regexp"
	"testing"

	"github.com/hashicorp/terraform-plugin-sdk/helper/acctest"
	"github.com/hashicorp/terraform-plugin-sdk/helper/resource"
)

func TestAccAWSEcsDataSource_ecsTaskDefinition(t *testing.T) {
	rName := fmt.Sprintf("tf-acc-test-%s", acctest.RandString(5))

	resource.ParallelTest(t, resource.TestCase{
		PreCheck:  func() { testAccPreCheck(t) },
		Providers: testAccProviders,
		Steps: []resource.TestStep{
			{
				Config: testAccCheckAwsEcsTaskDefinitionDataSourceConfig(rName),
				Check: resource.ComposeTestCheckFunc(
					resource.TestCheckResourceAttr("data.aws_ecs_task_definition.mongo", "family", rName),
					resource.TestCheckResourceAttr("data.aws_ecs_task_definition.mongo", "network_mode", "bridge"),
					resource.TestMatchResourceAttr("data.aws_ecs_task_definition.mongo", "revision", regexp.MustCompile("^[1-9][0-9]*$")),
					resource.TestCheckResourceAttr("data.aws_ecs_task_definition.mongo", "status", "ACTIVE"),
					resource.TestMatchResourceAttr("data.aws_ecs_task_definition.mongo", "task_role_arn", regexp.MustCompile(fmt.Sprintf("^arn:[^:]+:iam::[^:]+:role/%s$", rName))),
				),
			},
		},
	})
}

func testAccCheckAwsEcsTaskDefinitionDataSourceConfig(rName string) string {
	return fmt.Sprintf(`
resource "aws_iam_role" "mongo_role" {
  name = "%[1]s"

  assume_role_policy = <<POLICY
{
  "Version": "2012-10-17",
  "Statement": [
    {
      "Action": "sts:AssumeRole",
      "Principal": {
        "Service": "ec2.amazonaws.com"
      },
      "Effect": "Allow",
      "Sid": ""
    }
  ]
}
POLICY
}

resource "aws_ecs_task_definition" "mongo" {
  family        = "%[1]s"
  task_role_arn = "${aws_iam_role.mongo_role.arn}"
  network_mode  = "bridge"

  container_definitions = <<DEFINITION
[
  {
    "cpu": 128,
    "environment": [{
      "name": "SECRET",
      "value": "KEY"
    }],
    "essential": true,
    "image": "mongo:latest",
    "memory": 128,
    "memoryReservation": 64,
    "name": "mongodb"
  }
]
DEFINITION
}

data "aws_ecs_task_definition" "mongo" {
  task_definition = "${aws_ecs_task_definition.mongo.family}"
}
`, rName)
}
<commit_msg>Updates ECS acceptance tests to use ARN testing check functions<commit_after>package aws

import (
	"fmt"
	"regexp"
	"testing"

	"github.com/hashicorp/terraform-plugin-sdk/helper/acctest"
	"github.com/hashicorp/terraform-plugin-sdk/helper/resource"
)

func TestAccAWSEcsDataSource_ecsTaskDefinition(t *testing.T) {
	resourceName := "data.aws_ecs_task_definition.mongo"
	rName := fmt.Sprintf("tf-acc-test-%s", acctest.RandString(5))

	resource.ParallelTest(t, resource.TestCase{
		PreCheck:  func() { testAccPreCheck(t) },
		Providers: testAccProviders,
		Steps: []resource.TestStep{
			{
				Config: testAccCheckAwsEcsTaskDefinitionDataSourceConfig(rName),
				Check: resource.ComposeTestCheckFunc(
					resource.TestCheckResourceAttr(resourceName, "family", rName),
					resource.TestCheckResourceAttr(resourceName, "network_mode", "bridge"),
					resource.TestMatchResourceAttr(resourceName, "revision", regexp.MustCompile("^[1-9][0-9]*$")),
					resource.TestCheckResourceAttr(resourceName, "status", "ACTIVE"),
					resource.TestCheckResourceAttrPair(resourceName, "task_role_arn", "aws_iam_role.mongo_role", "arn"),
				),
			},
		},
	})
}

func testAccCheckAwsEcsTaskDefinitionDataSourceConfig(rName string) string {
	return fmt.Sprintf(`
resource "aws_iam_role" "mongo_role" {
  name = "%[1]s"

  assume_role_policy = <<POLICY
{
  "Version": "2012-10-17",
  "Statement": [
    {
      "Action": "sts:AssumeRole",
      "Principal": {
        "Service": "ec2.amazonaws.com"
      },
      "Effect": "Allow",
      "Sid": ""
    }
  ]
}
POLICY
}

resource "aws_ecs_task_definition" "mongo" {
  family        = "%[1]s"
  task_role_arn = "${aws_iam_role.mongo_role.arn}"
  network_mode  = "bridge"

  container_definitions = <<DEFINITION
[
  {
    "cpu": 128,
    "environment": [{
      "name": "SECRET",
      "value": "KEY"
    }],
    "essential": true,
    "image": "mongo:latest",
    "memory": 128,
    "memoryReservation": 64,
    "name": "mongodb"
  }
]
DEFINITION
}

data "aws_ecs_task_definition" "mongo" {
  task_definition = "${aws_ecs_task_definition.mongo.family}"
}
`, rName)
}
<|endoftext|>


<commit_before>// How to use : first call SetupLocation(InputLat,InputLon float64) to set base latitude and longitude.
// To genreate the location you can call RandomLatLong() to generate using seconds degree.
// And RandomLatLongMinute to genereate new location using minute degree.
package location

import "math/rand"

var lat, lon float64

type LocationDegree struct {
	Degree  int
	Minutes int
	Seconds int
}

// setup base location for generating the new randon lat, lon value.
func SetupLocation(InputLat, InputLon float64) {
	lat = InputLat
	lon = InputLon
}

// Convert the latitude or longitudet into Degre Seconds mninute
func ToDegree(location float64) LocationDegree {
	// get degree
	degree := int(location)
	location = location - float64(degree)

	// get minute
	multiply := location * 60.0
	minutes := int(multiply)
	location = multiply - float64(minutes)

	// get seconds
	multiply = location * 60
	seconds := int(multiply)

	// check if the decimal is 9 or 8 we are gointo round up
	location = multiply - float64(seconds)
	if location > 0.5 {
		seconds += 1
	}

	return LocationDegree{
		Degree:  degree,
		Minutes: minutes,
		Seconds: seconds,
	}

}

// convert given location Value into Decimal.
func ToDecimal(locationDegree LocationDegree) float64 {
	result := float64(locationDegree.Seconds) / 60.0

	result += float64(locationDegree.Minutes)

	result = result / 60.0

	result += float64(locationDegree.Degree)

	return result
}

// add seconds to lat or lon so we can get new location.
// we created array location so we can randomly select lat and lon to add new seconds degree.
// getting seconds value using pseu-do random from given seconds.
// returning latitude and longitude in order.
func RandomLatLong(seconds int) (float64, float64) {
	location := []float64{lat, lon}
	randomIndex := rand.Intn(len(location))

	randomSeconds := getRandomNumber(seconds)

	// convert the lat or lon depends on random selection to degree
	degreeLocation := ToDegree(location[randomIndex])
	degreeLocation.Seconds += randomSeconds

	// convert the degree to decimal degree and replace it to the current index
	location[randomIndex] = ToDecimal(degreeLocation)

	// return lat and lon in orner
	return location[0], location[1]
}

// add minute to lat or lon so we can get new location.
// we created array location so we can randomly select lat and lon to add new seconds degree.
// getting minute value using pseu-do random from given minute.
// returning latitude and longitude in order.
func RandomLatLongMinute(minute int) (float64, float64) {

	location := []float64{lat, lon}
	randomIndex := rand.Intn(len(location))

	randomMinute := getRandomNumber(minute)

	// convert the lat or lon depends on random selection to degree
	degreeLocation := ToDegree(location[randomIndex])
	degreeLocation.Minutes += randomMinute

	// convert the degree to decimal degree and replace it to the current index
	location[randomIndex] = ToDecimal(degreeLocation)

	// return lat and lon in orner
	return location[0], location[1]
}

// Get Random number from the maximal number given
// minimal number is 1 to max number
func getRandomNumber(max int) int {
	return rand.Intn(max-1) + 1
}
<commit_msg>refactor ToDegree and ToDecimal<commit_after>// How to use : first call SetupLocation(InputLat,InputLon float64) to set base latitude and longitude.
// To genreate the location you can call RandomLatLong() to generate using seconds degree.
// And RandomLatLongMinute to genereate new location using minute degree.
package location

import "math/rand"

var lat, lon float64

type LocationDegree struct {
	Degree  int
	Minutes int
	Seconds int
}

// setup base location for generating the new randon lat, lon value.
func SetupLocation(InputLat, InputLon float64) {
	lat = InputLat
	lon = InputLon
}

// Convert the latitude or longitudet into Degre Seconds mninute
func ToDegree(location float64) LocationDegree {
	// get the location in seconds, rounded up if needed
	seconds := int(location*60.0*60.0 + 0.5)
	minutes := seconds / 60
	degrees := seconds / (60 * 60)

	return LocationDegree{
		Degree:  degrees,
		Minutes: minutes % 60,
		Seconds: seconds % 60,
	}

}

// convert given location Value into Decimal.
func ToDecimal(locationDegree LocationDegree) float64 {
	totalSeconds := locationDegree.Degree * 60 * 60
	totalSeconds += locationDegree.Minutes * 60
	totalSeconds += locationDegree.Seconds
	return float64(totalSeconds) / (60.0 * 60.0)
}

// add seconds to lat or lon so we can get new location.
// we created array location so we can randomly select lat and lon to add new seconds degree.
// getting seconds value using pseu-do random from given seconds.
// returning latitude and longitude in order.
func RandomLatLong(seconds int) (float64, float64) {
	location := []float64{lat, lon}
	randomIndex := rand.Intn(len(location))

	randomSeconds := getRandomNumber(seconds)

	// convert the lat or lon depends on random selection to degree
	degreeLocation := ToDegree(location[randomIndex])
	degreeLocation.Seconds += randomSeconds

	// convert the degree to decimal degree and replace it to the current index
	location[randomIndex] = ToDecimal(degreeLocation)

	// return lat and lon in orner
	return location[0], location[1]
}

// add minute to lat or lon so we can get new location.
// we created array location so we can randomly select lat and lon to add new seconds degree.
// getting minute value using pseu-do random from given minute.
// returning latitude and longitude in order.
func RandomLatLongMinute(minute int) (float64, float64) {

	location := []float64{lat, lon}
	randomIndex := rand.Intn(len(location))

	randomMinute := getRandomNumber(minute)

	// convert the lat or lon depends on random selection to degree
	degreeLocation := ToDegree(location[randomIndex])
	degreeLocation.Minutes += randomMinute

	// convert the degree to decimal degree and replace it to the current index
	location[randomIndex] = ToDecimal(degreeLocation)

	// return lat and lon in orner
	return location[0], location[1]
}

// Get Random number from the maximal number given
// minimal number is 1 to max number
func getRandomNumber(max int) int {
	return rand.Intn(max-1) + 1
}
<|endoftext|>


<commit_before>package main

import (
	"flag"
	"fmt"
	"os"
	"os/exec"
	"path/filepath"
	"strings"
	"time"
)

func execCommand(command string) string {
	output, err := exec.Command("bash", "-c", command).Output()
	if err != nil {
		fmt.Println("Command '", command, "' returned error:", err)
	}

	return string(output)
}

func execCommandAndReport(command string, reportChannel chan int) {
	execCommand(command)
	reportChannel <- 1
}

func isConnectedToVPN() bool {
	_, err := os.Stat("/proc/sys/net/ipv4/conf/tun0")
	if err != nil {
		return true
	}

	return false
}

func listenForAudioSource(inputChannel chan int, audioSources []string) {
	for {
		output := execCommand("pacmd list-sink-inputs")
		for _, audioSource := range audioSources {
			if strings.Contains(output, audioSource) {
				inputChannel <- 1
			}
		}

		// This check doesn't need to happen very often.
		time.Sleep(time.Second * 15)
	}
}

func listenForEvents(inputChannel chan int, path string, size int) {
	file, err := os.Open(path)
	if err != nil {
		fmt.Println(err)
		os.Exit(1)
	}

	for {
		bytes := make([]byte, size)
		_, err := file.Read(bytes)
		if err != nil {
			fmt.Println("Error attempting to read N bytes from", path, ":", err)
			continue
		}

		inputChannel <- 1
	}
}

func spawnForDevices(inputChannel chan int) {
	// Add all devices under /dev/input/by-id because these seem to only list
	// the input devices I'm looking for. Maybe this should look for "mouse" or
	// "keyboard" as well? Maybe make this a cli flag?
	// The only error if for a bad format.
	paths, _ := filepath.Glob("/dev/input/by-id/*")
	fmt.Println("Listening to the following input devices:")
	for _, path := range paths {
		fmt.Println("-", path)
		go listenForEvents(inputChannel, path, 24)
	}
}

func spawnForAudioSources(inputChannel chan int) {
	audioSources := []string{
		`application.name = "Chromium"`,
	}
	fmt.Println("Listening for the following audio sources:")
	for _, audioSource := range audioSources {
		fmt.Println("-", audioSource)
	}
	go listenForAudioSource(inputChannel, audioSources)
}

func main() {
	lockCommandPtr := flag.String("locker", "pgrep -f i3lock && i3lock", "Command to execute your screen lock.")
	lockTimePtr := flag.Uint("time", 5, "Minutes of idle time before locking.")
	notifierCommandPtr := flag.String("notifier", "notify-send -u critical -t 10000 -- 'Locking screen soon.'", "Command to execute your screen lock.")
	notifyTimePtr := flag.Uint("notify", 30, "Seconds before locking when a notification is sent.")
	suspendCommandPtr := flag.String("suspender", "systemctl suspend", "Command for suspending computer.")
	suspendTimePtr := flag.Uint("suspend", 15, "Minutes of idle time before suspending.")
	disableSuspendWhileOnVPNPtr := flag.Bool("disable-suspend-while-on-vpn", true, "Don't engage suspend if we're conected to a VPN.")
	flag.Parse()

	inputChannel := make(chan int)
	spawnForDevices(inputChannel)
	spawnForAudioSources(inputChannel)

	// Main loop
	lockTime := time.Duration(*lockTimePtr) * time.Minute
	notifyTime := time.Duration(lockTime - (time.Duration(*notifyTimePtr) * time.Second))
	lockTimer := time.NewTimer(lockTime)
	notifyTimer := time.NewTimer(notifyTime)
	suspendTime := time.Duration(*suspendTimePtr) * time.Minute
	suspendTimer := time.NewTimer(suspendTime)
	currentlyLocked := false
	lockFinishedChannel := make(chan int)

	fmt.Println("Timer settings:")
	fmt.Println("- Notify after", notifyTime)
	fmt.Println("- Lock after", lockTime)
	fmt.Println("- Suspend after", suspendTime)

	fmt.Println("Starting wait/lock/notify/suspend loop...")
	for {
		select {
		case <- inputChannel:
			// Await any device or sound input.
			if !currentlyLocked {
				lockTimer.Reset(lockTime)
				notifyTimer.Reset(notifyTime)
			}
			suspendTimer.Reset(suspendTime)
		case <- lockFinishedChannel:
			// Reset lock state when lock exec completes.
			fmt.Println("Locker finished!")
			currentlyLocked = false
			lockTimer.Reset(lockTime)
			notifyTimer.Reset(notifyTime)
			suspendTimer.Reset(suspendTime)
		case <- notifyTimer.C:
			// Notfication timer has fired.
			fmt.Println("Notifying about locking soon!")
			go execCommand(*notifierCommandPtr)
		case <- lockTimer.C:
			// Lock timer has fired.
			fmt.Println("Locking computer!")
			currentlyLocked = true
			go execCommandAndReport(*lockCommandPtr, lockFinishedChannel)
		case <- suspendTimer.C:
			// Suspend timer has fired.

			// If we're connected to a VPN then don't suspend.
			if *disableSuspendWhileOnVPNPtr && isConnectedToVPN() {
				fmt.Println("Skipping suspend because VPN is connected")
				continue
			}

			fmt.Println("Suspending computer!")
			execCommand(*suspendCommandPtr)
			suspendTimer.Reset(suspendTime)
		}
	}
}
<commit_msg>Add ability to disable suspend mode<commit_after>package main

import (
	"flag"
	"fmt"
	"os"
	"os/exec"
	"path/filepath"
	"strings"
	"time"
)

func execCommand(command string) string {
	output, err := exec.Command("bash", "-c", command).Output()
	if err != nil {
		fmt.Println("Command '", command, "' returned error:", err)
	}

	return string(output)
}

func execCommandAndReport(command string, reportChannel chan int) {
	execCommand(command)
	reportChannel <- 1
}

func isConnectedToVPN() bool {
	_, err := os.Stat("/proc/sys/net/ipv4/conf/tun0")
	if err != nil {
		return true
	}

	return false
}

func listenForAudioSource(inputChannel chan int, audioSources []string) {
	for {
		output := execCommand("pacmd list-sink-inputs")
		for _, audioSource := range audioSources {
			if strings.Contains(output, audioSource) {
				inputChannel <- 1
			}
		}

		// This check doesn't need to happen very often.
		time.Sleep(time.Second * 15)
	}
}

func listenForEvents(inputChannel chan int, path string, size int) {
	file, err := os.Open(path)
	if err != nil {
		fmt.Println(err)
		os.Exit(1)
	}

	for {
		bytes := make([]byte, size)
		_, err := file.Read(bytes)
		if err != nil {
			fmt.Println("Error attempting to read N bytes from", path, ":", err)
			continue
		}

		inputChannel <- 1
	}
}

func spawnForDevices(inputChannel chan int) {
	// Add all devices under /dev/input/by-id because these seem to only list
	// the input devices I'm looking for. Maybe this should look for "mouse" or
	// "keyboard" as well? Maybe make this a cli flag?
	// The only error if for a bad format.
	paths, _ := filepath.Glob("/dev/input/by-id/*")
	fmt.Println("Listening to the following input devices:")
	for _, path := range paths {
		fmt.Println("-", path)
		go listenForEvents(inputChannel, path, 24)
	}
}

func spawnForAudioSources(inputChannel chan int) {
	audioSources := []string{
		`application.name = "Chromium"`,
	}
	fmt.Println("Listening for the following audio sources:")
	for _, audioSource := range audioSources {
		fmt.Println("-", audioSource)
	}
	go listenForAudioSource(inputChannel, audioSources)
}

func main() {
	lockCommandPtr := flag.String("locker", "pgrep -f i3lock && i3lock", "Command to execute your screen lock.")
	lockTimePtr := flag.Uint("time", 5, "Minutes of idle time before locking.")
	notifierCommandPtr := flag.String("notifier", "notify-send -u critical -t 10000 -- 'Locking screen soon.'", "Command to execute your screen lock.")
	notifyTimePtr := flag.Uint("notify", 30, "Seconds before locking when a notification is sent.")
	suspendCommandPtr := flag.String("suspender", "systemctl suspend", "Command for suspending computer.")
	suspendTimePtr := flag.Uint("suspend", 15, "Minutes of idle time before suspending.")
	suspendDisabledPtr := flag.Bool("suspend-disabled", false, "Don't over suspend.")
	suspendDisabledWhileOnVPNPtr := flag.Bool("suspend-disabled-while-on-vpn", true, "Don't engage suspend if we're conected to a VPN.")
	flag.Parse()

	inputChannel := make(chan int)
	spawnForDevices(inputChannel)
	spawnForAudioSources(inputChannel)

	// Main loop
	lockTime := time.Duration(*lockTimePtr) * time.Minute
	notifyTime := time.Duration(lockTime - (time.Duration(*notifyTimePtr) * time.Second))
	lockTimer := time.NewTimer(lockTime)
	notifyTimer := time.NewTimer(notifyTime)
	suspendTime := time.Duration(*suspendTimePtr) * time.Minute
	suspendTimer := time.NewTimer(suspendTime)
	currentlyLocked := false
	lockFinishedChannel := make(chan int)

	fmt.Println("Timer settings:")
	fmt.Println("- Notify after", notifyTime)
	fmt.Println("- Lock after", lockTime)
	if *suspendDisabledPtr {
		fmt.Println("- Suspend disabled: true")
	} else {
		fmt.Println("- Suspend after", suspendTime)
		fmt.Println("- Suspend disabled while connected to VPN:", *suspendDisabledWhileOnVPNPtr)
	}

	fmt.Println("Starting wait/lock/notify/suspend loop...")
	for {
		select {
		case <- inputChannel:
			// Await any device or sound input.
			if !currentlyLocked {
				lockTimer.Reset(lockTime)
				notifyTimer.Reset(notifyTime)
			}
			suspendTimer.Reset(suspendTime)
		case <- lockFinishedChannel:
			// Reset lock state when lock exec completes.
			fmt.Println("Locker finished!")
			currentlyLocked = false
			lockTimer.Reset(lockTime)
			notifyTimer.Reset(notifyTime)
			suspendTimer.Reset(suspendTime)
		case <- notifyTimer.C:
			// Notfication timer has fired.
			fmt.Println("Notifying about locking soon!")
			go execCommand(*notifierCommandPtr)
		case <- lockTimer.C:
			// Lock timer has fired.
			fmt.Println("Locking computer!")
			currentlyLocked = true
			go execCommandAndReport(*lockCommandPtr, lockFinishedChannel)
		case <- suspendTimer.C:
			// Suspend timer has fired.
			if *suspendDisabledPtr {
				continue
			}

			// If we're connected to a VPN then don't suspend.
			if *suspendDisabledWhileOnVPNPtr && isConnectedToVPN() {
				fmt.Println("Skipping suspend because VPN is connected")
				continue
			}

			fmt.Println("Suspending computer!")
			execCommand(*suspendCommandPtr)
			suspendTimer.Reset(suspendTime)
		}
	}
}
<|endoftext|>


<commit_before>// Package log2 supplies a global debug and error log function, and a log
// function adaptor.
package log2

import (
	"fmt"
	"log"
)

var (
	// DebugF is used to output the debug logging by other packages,
	// which supplies a common way. The logging is outputted to os.Stderr
	// by default.
	DebugF func(format string, args ...interface{})

	// ErrorF is used to output the error logging by other packages,
	// which supplies a common way. The logging is outputted to os.Stderr
	// by default.
	ErrorF func(format string, args ...interface{})
)

func init() {
	DebugF = func(format string, args ...interface{}) {
		format = fmt.Sprintf("[DEBUG] %s\n", format)
		log.Printf(format, args...)
	}

	ErrorF = func(format string, args ...interface{}) {
		format = fmt.Sprintf("[ERROR] %s\n", format)
		log.Printf(format, args...)
	}
}

// LoggerFunc converts a function to a suitable logger interface.
type LoggerFunc func(format string, args ...interface{})

// Printf implements the logger interface including the method Printf.
func (l LoggerFunc) Printf(format string, args ...interface{}) {
	l(format, args...)
}

// Debug implements the logger interface including the method Debug.
func (l LoggerFunc) Debug(format string, args ...interface{}) {
	l(format, args...)
}

// Debugf implements the logger interface including the method Debugf.
func (l LoggerFunc) Debugf(format string, args ...interface{}) {
	l(format, args...)
}

// Info implements the logger interface including the method Info.
func (l LoggerFunc) Info(format string, args ...interface{}) {
	l(format, args...)
}

// Infof implements the logger interface including the method Infof.
func (l LoggerFunc) Infof(format string, args ...interface{}) {
	l(format, args...)
}

// Warningf implements the logger interface including the method Warningf.
func (l LoggerFunc) Warningf(format string, args ...interface{}) {
	l(format, args...)
}

// Warning implements the logger interface including the method Warning.
func (l LoggerFunc) Warning(format string, args ...interface{}) {
	l(format, args...)
}

// Error implements the logger interface including the method Error.
func (l LoggerFunc) Error(format string, args ...interface{}) {
	l(format, args...)
}

// Errorf implements the logger interface including the method Errorf.
func (l LoggerFunc) Errorf(format string, args ...interface{}) {
	l(format, args...)
}

// Warnf implements the logger interface including the method Warnf.
func (l LoggerFunc) Warnf(format string, args ...interface{}) {
	l(format, args...)
}

// Warn implements the logger interface including the method Warn.
func (l LoggerFunc) Warn(format string, args ...interface{}) {
	l(format, args...)
}
<commit_msg>Add Logger interface<commit_after>// Package log2 supplies a global debug and error log function, and a log
// function adaptor.
package log2

import (
	"fmt"
	"log"
)

var (
	// DebugF is used to output the debug logging by other packages,
	// which supplies a common way. The logging is outputted to os.Stderr
	// by default.
	DebugF func(format string, args ...interface{})

	// ErrorF is used to output the error logging by other packages,
	// which supplies a common way. The logging is outputted to os.Stderr
	// by default.
	ErrorF func(format string, args ...interface{})
)

// Logger is a logger interface based on the level.
//
// For the level, Critical > Error > Warning > Info > Debug.
type Logger interface {
	// Debug records the log as the debug level.
	Debug(format string, args ...interface{})

	// Info records the log as the info level.
	Info(format string, args ...interface{})

	// Warning records the log as the warning level.
	Warning(format string, args ...interface{})

	// Error records the log as the error level.
	Error(format string, args ...interface{})

	// Critical records the log as the critical level.
	Critical(format string, args ...interface{})
}

func init() {
	DebugF = func(format string, args ...interface{}) {
		format = fmt.Sprintf("[DEBUG] %s\n", format)
		log.Printf(format, args...)
	}

	ErrorF = func(format string, args ...interface{}) {
		format = fmt.Sprintf("[ERROR] %s\n", format)
		log.Printf(format, args...)
	}
}

// LoggerFunc converts a function to a suitable logger interface.
type LoggerFunc func(format string, args ...interface{})

// Printf implements the logger interface including the method Printf.
func (l LoggerFunc) Printf(format string, args ...interface{}) {
	l(format, args...)
}

// Debug implements the logger interface including the method Debug.
func (l LoggerFunc) Debug(format string, args ...interface{}) {
	l(format, args...)
}

// Debugf implements the logger interface including the method Debugf.
func (l LoggerFunc) Debugf(format string, args ...interface{}) {
	l(format, args...)
}

// Info implements the logger interface including the method Info.
func (l LoggerFunc) Info(format string, args ...interface{}) {
	l(format, args...)
}

// Infof implements the logger interface including the method Infof.
func (l LoggerFunc) Infof(format string, args ...interface{}) {
	l(format, args...)
}

// Warningf implements the logger interface including the method Warningf.
func (l LoggerFunc) Warningf(format string, args ...interface{}) {
	l(format, args...)
}

// Warning implements the logger interface including the method Warning.
func (l LoggerFunc) Warning(format string, args ...interface{}) {
	l(format, args...)
}

// Error implements the logger interface including the method Error.
func (l LoggerFunc) Error(format string, args ...interface{}) {
	l(format, args...)
}

// Errorf implements the logger interface including the method Errorf.
func (l LoggerFunc) Errorf(format string, args ...interface{}) {
	l(format, args...)
}

// Warnf implements the logger interface including the method Warnf.
func (l LoggerFunc) Warnf(format string, args ...interface{}) {
	l(format, args...)
}

// Warn implements the logger interface including the method Warn.
func (l LoggerFunc) Warn(format string, args ...interface{}) {
	l(format, args...)
}
<|endoftext|>


<commit_before>package logalert

import (
	"fmt"
	"io"
	"log"
	"sync"
	"time"
)

// Logger is the logalert logger
type Logger struct {
	*sync.Mutex
	infoLogger    *log.Logger
	errLogger     *log.Logger
	alertSenders  []AlertSender
	gracePeriod   time.Duration
	lastAlertSent time.Time
}

// NewLogalert init a new logalert
func NewLogger(infoWriter, errWritter io.Writer, alertSenders []AlertSender, gracePeriodSeconds int) *Logger {
	logger := Logger{
		&sync.Mutex{},
		log.New(infoWriter, "INFO: ", log.Ldate|log.Ltime),
		log.New(errWritter, "ERROR: ", log.Ldate|log.Ltime|log.Lshortfile),
		alertSenders,
		time.Duration(gracePeriodSeconds) * time.Second,
		time.Unix(0, 0),
	}
	return &logger
}

// SetAlertSenders set alert senders
func (l *Logger) SetAlertSenders(as []AlertSender) {
	l.Lock()
	defer l.Unlock()
	l.alertSenders = as
}

// SendAlert send alerts via alertSenders
func (l *Logger) SendAlert(v ...interface{}) {
	l.Lock()
	defer l.Unlock()
	if time.Since(l.lastAlertSent) > l.gracePeriod {
		for _, sender := range l.alertSenders {
			sender.Send(fmt.Sprint(v...))
		}
		l.lastAlertSent = time.Now()
	}
}

// Info log at INFO level
func (l *Logger) Info(v ...interface{}) {
	l.infoLogger.Println(v...)
	return
}

// InfoAlert log at info level and send alert
func (l *Logger) InfoAlert(v ...interface{}) {
	l.Info(v...)
	l.SendAlert(v...)
	return
}

// Error write error log
func (l *Logger) Error(v ...interface{}) {
	l.errLogger.Println(v...)
	return
}

// ErrorAlert write error log and send alert
func (l *Logger) ErrorAlert(v ...interface{}) {
	l.Error(v...)
	l.SendAlert(v...)
	return
}
<commit_msg>add formatter<commit_after>package logalert

import (
	"fmt"
	"io"
	"log"
	"sync"
	"time"
)

// Logger is the logalert logger
type Logger struct {
	*sync.Mutex
	infoLogger    *log.Logger
	errLogger     *log.Logger
	alertSenders  []AlertSender
	gracePeriod   time.Duration
	lastAlertSent time.Time
}

// NewLogger init a new logalert
func NewLogger(infoWriter, errWritter io.Writer, alertSenders []AlertSender, gracePeriodSeconds int) *Logger {
	logger := Logger{
		&sync.Mutex{},
		log.New(infoWriter, "INFO: ", log.Ldate|log.Ltime),
		log.New(errWritter, "ERROR: ", log.Ldate|log.Ltime),
		alertSenders,
		time.Duration(gracePeriodSeconds) * time.Second,
		time.Unix(0, 0),
	}
	return &logger
}

// SetAlertSenders set alert senders
func (l *Logger) SetAlertSenders(as []AlertSender) {
	l.Lock()
	defer l.Unlock()
	l.alertSenders = as
}

// SendAlert send alerts via alertSenders
func (l *Logger) SendAlert(v ...interface{}) {
	l.Lock()
	defer l.Unlock()
	if time.Since(l.lastAlertSent) > l.gracePeriod {
		for _, sender := range l.alertSenders {
			sender.Send(fmt.Sprint(formatMsg(v...)))
		}
		l.lastAlertSent = time.Now()
	}
}

// Info log at INFO level
func (l *Logger) Info(v ...interface{}) {
	l.infoLogger.Println(formatMsg(v...))
	return
}

// InfoAlert log at info level and send alert
func (l *Logger) InfoAlert(v ...interface{}) {
	l.Info(v...)
	l.SendAlert(v...)
	return
}

// Error write error log
func (l *Logger) Error(v ...interface{}) {
	l.errLogger.Println(formatMsg(v...))
	return
}

// ErrorAlert write error log and send alert
func (l *Logger) ErrorAlert(v ...interface{}) {
	l.Error(v...)
	l.SendAlert(v...)
	return
}

// formatErrorMsg format error output
func formatMsg(v ...interface{}) string {
	m := ""
	for _, part := range v {
		m = m + fmt.Sprintf("%v", part)
	}
	return m
}
<|endoftext|>


<commit_before>//
// miner.go
// Staring template for PointCoint miner.
//
// cs4501: Cryptocurrency Cafe
// University of Virginia, Spring 2015
// Project 2
//

package main

import (
	"fmt"
	"log"
	"math/rand"
	"time"
	"github.com/PointCoin/btcjson"
	"math/big"
	"github.com/PointCoin/btcutil"
	"github.com/PointCoin/btcwire"
	"github.com/PointCoin/btcrpcclient"

	// "github.com/PointCoin/pointcoind/blockchain"
)

const (
	// This should match your settings in pointcoind.conf
	rpcuser = "ankitgupta"
	rpcpass = "password"
	// This file should exist if pointcoind was setup correctly
	cert    = "/home/ubuntu/.pointcoind/rpc.cert"
)

func GetClient() *btcrpcclient.Client {
	return setupRpcClient(cert, rpcuser, rpcpass)
}
func GetTemplate(client *btcrpcclient.Client) *btcjson.GetBlockTemplateResult {

	// Get a new block template from pointcoind.
	log.Printf("Requesting a block template\n")
	template, err := client.GetBlockTemplate(&btcjson.TemplateRequest{})
	if err != nil {
		log.Fatal(err)
	}
	return template
}

func SetUpBlock(template *btcjson.GetBlockTemplateResult) (*btcwire.MsgBlock, big.Int) {
	// The hash of the previous block
	prevHash := template.PreviousHash

	// The difficulty target
	difficulty := formatDiff(template.Bits)

	// The height of the next block (number of blocks between genesis block and next block)
	height := template.Height

	// The transactions from the network
	txs := formatTransactions(template.Transactions)

	// These are configurable parameters to the coinbase transaction
	msg := "ag7bf" // replace with your UVa Computing ID (e.g., "dee2b")

	// This is my address generated with wallet of passphrase "mywallet",
	// old miner address: PcvNdeZ6UsC8R34NQqi9YyxKfSXQcjoWHy
	a := "Prxy397nCyskwHwmiv3TaFG6ZgZ88Cbnju"

	coinbaseTx := CreateCoinbaseTx(height, a, msg)

	txs = prepend(coinbaseTx.MsgTx(), txs)
	merkleRoot := createMerkleRoot(txs)

	// Finish the miner!
	// print("Looking for valid block....")
	source := rand.NewSource(time.Now().UnixNano())
	myRand := rand.New(source)
	var nonce uint32 = myRand.Uint32();

	block := CreateBlock(prevHash, merkleRoot, difficulty, nonce, txs)

	return block, difficulty

}

func mainn() {
	print := fmt.Println
	// Setup the client using application constants, fail horribly if there's a problem
	client := setupRpcClient(cert, rpcuser, rpcpass)

	for { // Loop forever (you may want to do something smarter!)
		// Get a new block template from pointcoind.
		log.Printf("Requesting a block template\n")
		template, err := client.GetBlockTemplate(&btcjson.TemplateRequest{})
		if err != nil {
			log.Fatal(err)
		}

		// The template returned by GetBlockTemplate provides these fields that
		// you will need to use to create a new block:

		// The hash of the previous block
		prevHash := template.PreviousHash

		// The difficulty target
		difficulty := formatDiff(template.Bits)

		// The height of the next block (number of blocks between genesis block and next block)
		height := template.Height

		// The transactions from the network
		txs := formatTransactions(template.Transactions)

		// These are configurable parameters to the coinbase transaction
		msg := "ag7bf" // replace with your UVa Computing ID (e.g., "dee2b")

		// This is my address generated with wallet of passphrase "mywallet",
		a := "PcvNdeZ6UsC8R34NQqi9YyxKfSXQcjoWHy" // replace with the address you want mining fees to go to (or leave it like this and Nick gets them)

		coinbaseTx := CreateCoinbaseTx(height, a, msg)

		txs = prepend(coinbaseTx.MsgTx(), txs)
		merkleRoot := createMerkleRoot(txs)

		// Finish the miner!
		print("Looking for valid block....")
		source := rand.NewSource(time.Now().UnixNano())
		myRand := rand.New(source)
		var nonce uint32 = myRand.Uint32();

		block := CreateBlock(prevHash, merkleRoot, difficulty, nonce, txs)

		// Naive approach, try 20 million times before checking for new template
		// Loop, checking hashes against difficulty until valid hash is found
		for i := 0; i < 20000000; i++ {
			blockSha, _ := block.Header.BlockSha()
			// print("Trying with nonce: ", block.Header.Nonce)

			if lessThanDiff(blockSha, difficulty) {
				// submit block
				print("valid hash found")
				err := client.SubmitBlock(btcutil.NewBlock(block), nil)
				print(err)
				break
			} else {
				if block.Header.Nonce == 4294967294 {
					block.Header.Nonce = 0
				} else {
					block.Header.Nonce += 1
				}
			}
		}

	}
}
<commit_msg>took out print statement<commit_after>//
// miner.go
// Staring template for PointCoint miner.
//
// cs4501: Cryptocurrency Cafe
// University of Virginia, Spring 2015
// Project 2
//

package main

import (
	"fmt"
	"log"
	"math/rand"
	"time"
	"github.com/PointCoin/btcjson"
	"math/big"
	"github.com/PointCoin/btcutil"
	"github.com/PointCoin/btcwire"
	"github.com/PointCoin/btcrpcclient"

	// "github.com/PointCoin/pointcoind/blockchain"
)

const (
	// This should match your settings in pointcoind.conf
	rpcuser = "ankitgupta"
	rpcpass = "password"
	// This file should exist if pointcoind was setup correctly
	cert    = "/home/ubuntu/.pointcoind/rpc.cert"
)

func GetClient() *btcrpcclient.Client {
	return setupRpcClient(cert, rpcuser, rpcpass)
}
func GetTemplate(client *btcrpcclient.Client) *btcjson.GetBlockTemplateResult {

	// Get a new block template from pointcoind.
	// log.Printf("Requesting a block template\n")
	template, err := client.GetBlockTemplate(&btcjson.TemplateRequest{})
	if err != nil {
		log.Fatal(err)
	}
	return template
}

func SetUpBlock(template *btcjson.GetBlockTemplateResult) (*btcwire.MsgBlock, big.Int) {
	// The hash of the previous block
	prevHash := template.PreviousHash

	// The difficulty target
	difficulty := formatDiff(template.Bits)

	// The height of the next block (number of blocks between genesis block and next block)
	height := template.Height

	// The transactions from the network
	txs := formatTransactions(template.Transactions)

	// These are configurable parameters to the coinbase transaction
	msg := "ag7bf" // replace with your UVa Computing ID (e.g., "dee2b")

	// This is my address generated with wallet of passphrase "mywallet",
	// old miner address: PcvNdeZ6UsC8R34NQqi9YyxKfSXQcjoWHy
	a := "Prxy397nCyskwHwmiv3TaFG6ZgZ88Cbnju"

	coinbaseTx := CreateCoinbaseTx(height, a, msg)

	txs = prepend(coinbaseTx.MsgTx(), txs)
	merkleRoot := createMerkleRoot(txs)

	// Finish the miner!
	// print("Looking for valid block....")
	source := rand.NewSource(time.Now().UnixNano())
	myRand := rand.New(source)
	var nonce uint32 = myRand.Uint32();

	block := CreateBlock(prevHash, merkleRoot, difficulty, nonce, txs)

	return block, difficulty

}

func mainn() {
	print := fmt.Println
	// Setup the client using application constants, fail horribly if there's a problem
	client := setupRpcClient(cert, rpcuser, rpcpass)

	for { // Loop forever (you may want to do something smarter!)
		// Get a new block template from pointcoind.
		log.Printf("Requesting a block template\n")
		template, err := client.GetBlockTemplate(&btcjson.TemplateRequest{})
		if err != nil {
			log.Fatal(err)
		}

		// The template returned by GetBlockTemplate provides these fields that
		// you will need to use to create a new block:

		// The hash of the previous block
		prevHash := template.PreviousHash

		// The difficulty target
		difficulty := formatDiff(template.Bits)

		// The height of the next block (number of blocks between genesis block and next block)
		height := template.Height

		// The transactions from the network
		txs := formatTransactions(template.Transactions)

		// These are configurable parameters to the coinbase transaction
		msg := "ag7bf" // replace with your UVa Computing ID (e.g., "dee2b")

		// This is my address generated with wallet of passphrase "mywallet",
		a := "PcvNdeZ6UsC8R34NQqi9YyxKfSXQcjoWHy" // replace with the address you want mining fees to go to (or leave it like this and Nick gets them)

		coinbaseTx := CreateCoinbaseTx(height, a, msg)

		txs = prepend(coinbaseTx.MsgTx(), txs)
		merkleRoot := createMerkleRoot(txs)

		// Finish the miner!
		print("Looking for valid block....")
		source := rand.NewSource(time.Now().UnixNano())
		myRand := rand.New(source)
		var nonce uint32 = myRand.Uint32();

		block := CreateBlock(prevHash, merkleRoot, difficulty, nonce, txs)

		// Naive approach, try 20 million times before checking for new template
		// Loop, checking hashes against difficulty until valid hash is found
		for i := 0; i < 20000000; i++ {
			blockSha, _ := block.Header.BlockSha()
			// print("Trying with nonce: ", block.Header.Nonce)

			if lessThanDiff(blockSha, difficulty) {
				// submit block
				print("valid hash found")
				err := client.SubmitBlock(btcutil.NewBlock(block), nil)
				print(err)
				break
			} else {
				if block.Header.Nonce == 4294967294 {
					block.Header.Nonce = 0
				} else {
					block.Header.Nonce += 1
				}
			}
		}

	}
}
<|endoftext|>