<commit_before>package main

import (
	"encoding/json"
	"fmt"
	"io"
	"io/ioutil"
	"os"
	"path/filepath"
	"strings"

	specs "github.com/opencontainers/image-spec/specs-go"
	"github.com/opencontainers/image-spec/specs-go/v1"
	"github.com/urfave/cli"
)

var gitCommit = ""

const (
	manifestFileName           = "manifest.json"
	legacyLayerFileName        = "layer.tar"
	legacyRepositoriesFileName = "repositories"
)

var appHelpTemplate = `NAME:
   {{.Name}}{{if .Usage}} - {{.Usage}}{{end}}

USAGE:
   {{if .UsageText}}{{.UsageText}}{{end}} {{if .Version}}{{if not .HideVersion}}

VERSION:
   {{.Version}}{{end}}{{end}}{{if .VisibleFlags}}

OPTIONS:
   {{range $index, $option := .VisibleFlags}}{{if $index}}
   {{end}}{{$option}}{{end}}{{end}}
`

func main() {
	cli.AppHelpTemplate = fmt.Sprintf("%s", appHelpTemplate)
	app := cli.NewApp()
	app.Name = "docker2oci"
	app.Usage = "convert docker image from docker save to oci format image"
	app.UsageText = "docker2oci [OPTIONS] DIRECTORY"
	app.Version = fmt.Sprintf("commit: %s spec version: %s", gitCommit, specs.Version)
	app.Flags = []cli.Flag{
		cli.StringFlag{
			Name:  "i,input",
			Value: "",
			Usage: "Read image from tar archive `FILE`, instead of STDIN",
		},
	}
	app.Action = func(c *cli.Context) error {
		if c.NArg() == 0 {
			return fmt.Errorf("Error: destination 'DIRECTORY' of oci image is requred, see 'docker2oci --help'")
		}
		inputfile := c.String("input")

		var (
			input io.Reader = os.Stdin
		)

		if inputfile != "" {
			infile, err := os.Open(inputfile)
			if err != nil {
				return err
			}
			defer infile.Close()
			input = infile
		}
		dir := c.Args().Get(0)
		if _, err := os.Stat(dir); err == nil {
			return fmt.Errorf("Destination %q exist", dir)
		} else if os.IsNotExist(err) {
			err = os.MkdirAll(dir, 0700)
			if err != nil {
				return err
			}
		} else {
			return err
		}
		return doConvert(input, dir)

	}
	app.Run(os.Args)
}

// TODO: need a refactor to split the big function to several
// small functions
func doConvert(in io.Reader, out string) (retErr error) {
	tmpDir, err := ioutil.TempDir("", "docker2oci-docker-")
	if err != nil {
		return err
	}
	defer os.RemoveAll(tmpDir)

	if err := unpack(tmpDir, in); err != nil {
		return err
	}

	manifestPath := filepath.Join(tmpDir, manifestFileName)
	manifestFile, err := os.Open(manifestPath)
	if err != nil {
		return err
	}
	defer manifestFile.Close()

	var manifests []manifestItem
	if err := json.NewDecoder(manifestFile).Decode(&manifests); err != nil {
		return err
	}

	if err := createLayoutFile(out); err != nil {
		return err
	}

	var index v1.Index
	index.SchemaVersion = 2

	for _, m := range manifests {
		var manifest v1.Manifest

		manifest.SchemaVersion = 2

		configPath := filepath.Join(tmpDir, m.Config)
		config, err := ioutil.ReadFile(configPath)
		if err != nil {
			return err
		}
		img, err := NewFromJSON(config)
		if err != nil {
			return err
		}
		// TODO: use v1.Image to read config from file directly
		// TODO: move this to a function
		ociConfig := v1.Image{
			Created:      &img.Created,
			Author:       img.Author,
			Architecture: img.Architecture,
			OS:           img.OS,
			Config: v1.ImageConfig{
				User:         img.ContainerConfig.User,
				ExposedPorts: img.ContainerConfig.ExposedPorts,
				Env:          img.ContainerConfig.Env,
				Entrypoint:   []string(img.ContainerConfig.Entrypoint),
				Cmd:          []string(img.ContainerConfig.Cmd),
				Volumes:      img.ContainerConfig.Volumes,
				WorkingDir:   img.ContainerConfig.WorkingDir,
				Labels:       img.ContainerConfig.Labels,
				StopSignal:   img.ContainerConfig.StopSignal,
			},
			RootFS: v1.RootFS{
				Type:    img.RootFS.Type,
				DiffIDs: img.RootFS.DiffIDs,
			},
			History: img.History,
		}
		des, err := createConfigFile(out, ociConfig)
		if err != nil {
			return err
		}
		des.MediaType = v1.MediaTypeImageConfig
		manifest.Config = des
		for i, _ := range img.RootFS.DiffIDs {
			layerPath := filepath.Join(tmpDir, m.Layers[i])
			f, err := os.Open(layerPath)
			if err != nil {
				return err
			}
			defer f.Close()
			des, err := createLayerBlob(out, f)
			if err != nil {
				return err
			}
			// TODO: detect the tar format, so we know the mediaType
			des.MediaType = v1.MediaTypeImageLayer
			manifest.Layers = append(manifest.Layers, des)
		}
		des, err = createManifestFile(out, manifest)
		if err != nil {
			return err
		}
		des.MediaType = v1.MediaTypeImageManifest
		des.Platform = &v1.Platform{
			Architecture: ociConfig.Architecture,
			OS:           ociConfig.OS,
		}
		des.Annotations = make(map[string]string)
		// FIXME: a image may have multiple tags
		// TODO: validate the tag
		for _, tag := range m.RepoTags {
			strs := strings.Split(tag, ":")
			if len(strs) != 2 {
				continue
			}
			des.Annotations["org.opencontainers.image.ref.name"] = strs[1]
		}
		index.Manifests = append(index.Manifests, des)
	}
	err = createIndexFile(out, index)
	if err != nil {
		return err
	}

	return nil
}
<commit_msg>fix a typo and do some cleanup<commit_after>package main

import (
	"encoding/json"
	"fmt"
	"io"
	"io/ioutil"
	"os"
	"path/filepath"
	"strings"

	specs "github.com/opencontainers/image-spec/specs-go"
	"github.com/opencontainers/image-spec/specs-go/v1"
	"github.com/urfave/cli"
)

var gitCommit = ""

const (
	manifestFileName           = "manifest.json"
	legacyLayerFileName        = "layer.tar"
	legacyRepositoriesFileName = "repositories"
)

const appHelpTemplate = `NAME:
   {{.Name}}{{if .Usage}} - {{.Usage}}{{end}}

USAGE:
   {{if .UsageText}}{{.UsageText}}{{end}} {{if .Version}}{{if not .HideVersion}}

VERSION:
   {{.Version}}{{end}}{{end}}{{if .VisibleFlags}}

OPTIONS:
   {{range $index, $option := .VisibleFlags}}{{if $index}}
   {{end}}{{$option}}{{end}}{{end}}
`

func main() {
	cli.AppHelpTemplate = fmt.Sprintf("%s", appHelpTemplate)
	app := cli.NewApp()
	app.Name = "docker2oci"
	app.Usage = "convert docker image from docker save to oci format image"
	app.UsageText = "docker2oci [OPTIONS] DIRECTORY"
	app.Version = fmt.Sprintf("commit: %s spec version: %s", gitCommit, specs.Version)
	app.Flags = []cli.Flag{
		cli.StringFlag{
			Name:  "i,input",
			Value: "",
			Usage: "Read image from tar archive `FILE`, instead of STDIN",
		},
	}
	app.Action = func(c *cli.Context) error {
		if c.NArg() == 0 {
			return fmt.Errorf("Error: destination 'DIRECTORY' of oci image is required, see 'docker2oci --help'")
		}
		inputfile := c.String("input")

		var (
			input io.Reader = os.Stdin
		)

		if inputfile != "" {
			infile, err := os.Open(inputfile)
			if err != nil {
				return err
			}
			defer infile.Close()
			input = infile
		}
		dir := c.Args().Get(0)
		if _, err := os.Stat(dir); err == nil {
			return fmt.Errorf("Destination %q exist", dir)
		} else if os.IsNotExist(err) {
			err = os.MkdirAll(dir, 0700)
			if err != nil {
				return err
			}
		} else {
			return err
		}
		return doConvert(input, dir)

	}
	app.Run(os.Args)
}

// TODO: need a refactor to split the big function to several
// small functions
func doConvert(in io.Reader, out string) (retErr error) {
	tmpDir, err := ioutil.TempDir("", "docker2oci-docker-")
	if err != nil {
		return err
	}
	defer os.RemoveAll(tmpDir)

	if err := unpack(tmpDir, in); err != nil {
		return err
	}

	manifestPath := filepath.Join(tmpDir, manifestFileName)
	manifestFile, err := os.Open(manifestPath)
	if err != nil {
		return err
	}
	defer manifestFile.Close()

	var manifests []manifestItem
	if err := json.NewDecoder(manifestFile).Decode(&manifests); err != nil {
		return err
	}

	if err := createLayoutFile(out); err != nil {
		return err
	}

	var index v1.Index
	index.SchemaVersion = 2

	for _, m := range manifests {
		var manifest v1.Manifest

		manifest.SchemaVersion = 2

		configPath := filepath.Join(tmpDir, m.Config)
		config, err := ioutil.ReadFile(configPath)
		if err != nil {
			return err
		}
		img, err := NewFromJSON(config)
		if err != nil {
			return err
		}
		ociConfig := v1.Image{
			Created:      &img.Created,
			Author:       img.Author,
			Architecture: img.Architecture,
			OS:           img.OS,
			Config: v1.ImageConfig{
				User:         img.ContainerConfig.User,
				ExposedPorts: img.ContainerConfig.ExposedPorts,
				Env:          img.ContainerConfig.Env,
				Entrypoint:   []string(img.ContainerConfig.Entrypoint),
				Cmd:          []string(img.ContainerConfig.Cmd),
				Volumes:      img.ContainerConfig.Volumes,
				WorkingDir:   img.ContainerConfig.WorkingDir,
				Labels:       img.ContainerConfig.Labels,
				StopSignal:   img.ContainerConfig.StopSignal,
			},
			RootFS: v1.RootFS{
				Type:    img.RootFS.Type,
				DiffIDs: img.RootFS.DiffIDs,
			},
			History: img.History,
		}
		des, err := createConfigFile(out, ociConfig)
		if err != nil {
			return err
		}
		des.MediaType = v1.MediaTypeImageConfig
		manifest.Config = des
		for i, _ := range img.RootFS.DiffIDs {
			layerPath := filepath.Join(tmpDir, m.Layers[i])
			f, err := os.Open(layerPath)
			if err != nil {
				return err
			}
			defer f.Close()
			des, err := createLayerBlob(out, f)
			if err != nil {
				return err
			}
			// TODO: detect the tar format, so we know the mediaType
			des.MediaType = v1.MediaTypeImageLayer
			manifest.Layers = append(manifest.Layers, des)
		}
		des, err = createManifestFile(out, manifest)
		if err != nil {
			return err
		}
		des.MediaType = v1.MediaTypeImageManifest
		des.Platform = &v1.Platform{
			Architecture: ociConfig.Architecture,
			OS:           ociConfig.OS,
		}
		des.Annotations = make(map[string]string)
		// FIXME: a image may have multiple tags
		// TODO: validate the tag
		for _, tag := range m.RepoTags {
			strs := strings.Split(tag, ":")
			if len(strs) != 2 {
				continue
			}
			des.Annotations["org.opencontainers.image.ref.name"] = strs[1]
		}
		index.Manifests = append(index.Manifests, des)
	}
	err = createIndexFile(out, index)
	if err != nil {
		return err
	}

	return nil
}
<|endoftext|>


<commit_before>package main

import (
	"bufio"
	"crypto/md5"
	"encoding/hex"
	"encoding/json"
	"errors"
	"flag"
	"fmt"
	"html/template"
	"io"
	"math/rand"
	"net/http"
	"os"
	"strings"
	"time"

	"github.com/Sirupsen/logrus"
)

type content map[string]string

var address string
var sourceFile string
var useStdin bool

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

const (
	defaultAddress    = ":2017"
	defaultUseStdin   = false
	defaultSourceFile = ""
)

const humans = `/* TEAM */
Developer: Nick Gerakines
Site: http://ngerakines.me/
Twitter: @ngerakines
Location: Dayton, OH

/* SITE */
Last update: 2017/09/28 (Happy birthday Vanessa!)
Standards: HTML5, CSS3
Software: Visual Studio Code, Golang

/* SOURCE */
Source: https://github.com/ngerakines/wholesome
License: MIT`

const tpl = `
<!doctype html>

    <meta charset="UTF-8">
    <title>Wholesome</title>
    <link rel="author" href="/humans.txt" />

{{ .Line }}

            [permalink]

`

func main() {
	logger := logrus.New()
	logger.Formatter = &logrus.JSONFormatter{}
	logger.Level = logrus.DebugLevel
	logger.Out = os.Stdout

	fs := flag.NewFlagSet("", flag.ExitOnError)
	fs.StringVar(&address, "address", defaultAddress, "The address to bind the server to.")
	fs.BoolVar(&useStdin, "use-stdin", defaultUseStdin, "Read content from STDIN.")
	fs.StringVar(&sourceFile, "source", defaultSourceFile, "Read content from a file.")
	fs.Parse(os.Args[1:])

	var data content
	var err error

	if useStdin {
		data, err = loadStdin()
	}
	if len(sourceFile) > 0 {
		data, err = loadFile(sourceFile)
	}
	if err != nil {
		logger.
			WithFields(logrus.Fields{
				"address":   address,
				"use-stdin": useStdin,
				"source":    sourceFile,
			}).
			WithError(err).
			Fatal("Error loading data.")
	}
	if len(data) == 0 {
		logger.
			WithFields(logrus.Fields{
				"address":   address,
				"use-stdin": useStdin,
				"source":    sourceFile,
			}).
			Fatal("Data is empty")
	}
	keys := make([]string, 0, len(data))
	for k := range data {
		keys = append(keys, k)
	}

	logger.WithField("data", data).Debug("Loaded data.")

	mux := http.NewServeMux()

	mux.HandleFunc("/humans.txt", func(rw http.ResponseWriter, r *http.Request) {
		logger.
			WithFields(logrus.Fields{
				"method": r.Method,
				"uri":    r.URL.Path,
			}).
			Info()
		rw.Header().Set("Content-Type", "text/plain")
		fmt.Fprintln(rw, humans)
	})

	mux.HandleFunc("/", func(rw http.ResponseWriter, r *http.Request) {
		path := r.URL.Path
		entry := logger.WithFields(logrus.Fields{
			"method": r.Method,
			"uri":    path,
		})
		if r.Method != "GET" {
			failRequest(entry, rw, errors.New("unsupported method"), 405)
			return
		}
		contentType := parseContentType(path)

		var hash string
		var line string
		hash = parseHash(path)
		if val, ok := data[hash]; ok {
			line = val
		} else {
			hash = keys[rand.Intn(len(keys))]
			line = data[hash]
		}

		switch contentType {
		case "application/json":
			rw.Header().Set("Content-Type", contentType)
			err = renderJSON(rw, hash, line)
		case "text/plain":
			rw.Header().Set("Content-Type", contentType)
			fmt.Fprintln(rw, line)
		default:
			rw.Header().Set("Content-Type", "text/html")
			err = renderHTML(rw, hash, line)
		}

		if err != nil {
			failRequest(entry, rw, err, 500)
			return
		}

		entry.Info()
	})

	h := &http.Server{
		Addr:    address,
		Handler: mux,
	}

	if err := h.ListenAndServe(); err != nil {
		logger.WithError(err).Warning("HTTP Service stopped.")
	}
}

func parseHash(path string) string {
	path = strings.TrimPrefix(path, "/")
	path = strings.TrimSuffix(path, ".html")
	path = strings.TrimSuffix(path, ".json")
	path = strings.TrimSuffix(path, ".txt")
	return path
}

func parseContentType(path string) string {
	if strings.HasSuffix(path, ".txt") {
		return "text/plain"
	}
	if strings.HasSuffix(path, ".json") {
		return "application/json"
	}
	return "text/html"
}

func failRequest(entry *logrus.Entry, rw http.ResponseWriter, err error, statusCode int) {
	entry.WithError(err).Error("Failed to handle request.")
	http.Error(rw, err.Error(), statusCode)
}

func renderHTML(w io.Writer, hash, line string) error {
	t, err := template.New("webpage").Parse(tpl)
	if err != nil {
		return err
	}
	return t.Execute(w, struct {
		Hash string
		Line string
	}{
		Hash: hash,
		Line: line,
	})
}

func renderJSON(w io.Writer, hash, line string) error {
	c := struct {
		Line string `json:"line"`
		Hash string `json:"hash"`
	}{Line: line, Hash: hash}
	b, err := json.Marshal(&c)
	if err != nil {
		return err
	}
	_, err = w.Write(b)
	return err
}

func loadFile(path string) (content, error) {
	file, err := os.Open(path)
	if err != nil {
		return nil, err
	}
	defer file.Close()
	scanner := bufio.NewScanner(file)
	return scanContent(scanner)
}

func loadStdin() (content, error) {
	scanner := bufio.NewScanner(os.Stdin)
	return scanContent(scanner)
}

func scanContent(scanner *bufio.Scanner) (content, error) {
	var lines []string
	for scanner.Scan() {
		lines = append(lines, scanner.Text())
	}
	if err := scanner.Err(); err != nil {
		return nil, err
	}
	return parseLines(lines)
}

func parseLines(lines []string) (content, error) {
	content := make(map[string]string)
	for _, line := range lines {
		rawHash := md5.Sum([]byte(line))
		hash := hex.EncodeToString(rawHash[:])
		content[hash] = line
	}
	return content, nil
}
<commit_msg>Formatting address<commit_after>package main

import (
	"bufio"
	"crypto/md5"
	"encoding/hex"
	"encoding/json"
	"errors"
	"flag"
	"fmt"
	"html/template"
	"io"
	"math/rand"
	"net/http"
	"os"
	"strings"
	"time"

	"github.com/Sirupsen/logrus"
)

type content map[string]string

var address string
var sourceFile string
var useStdin bool

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

const (
	defaultAddress    = ":2017"
	defaultUseStdin   = false
	defaultSourceFile = ""
)

const humans = `/* TEAM */
Developer: Nick Gerakines
Site: http://ngerakines.me/
Twitter: @ngerakines
Location: Dayton, OH

/* SITE */
Last update: 2017/09/28 (Happy birthday Vanessa!)
Standards: HTML5, CSS3
Software: Visual Studio Code, Golang

/* SOURCE */
Source: https://github.com/ngerakines/wholesome
License: MIT`

const tpl = `
<!doctype html>

    <meta charset="UTF-8">
    <title>Wholesome</title>
    <link rel="author" href="/humans.txt" />

{{ .Line }}

            [permalink]

`

func main() {
	logger := logrus.New()
	logger.Formatter = &logrus.JSONFormatter{}
	logger.Level = logrus.DebugLevel
	logger.Out = os.Stdout

	fs := flag.NewFlagSet("", flag.ExitOnError)
	fs.StringVar(&address, "address", defaultAddress, "The address to bind the server to.")
	fs.BoolVar(&useStdin, "use-stdin", defaultUseStdin, "Read content from STDIN.")
	fs.StringVar(&sourceFile, "source", defaultSourceFile, "Read content from a file.")
	fs.Parse(os.Args[1:])

	var data content
	var err error

	if useStdin {
		data, err = loadStdin()
	}
	if len(sourceFile) > 0 {
		data, err = loadFile(sourceFile)
	}
	if err != nil {
		logger.
			WithFields(logrus.Fields{
				"address":   address,
				"use-stdin": useStdin,
				"source":    sourceFile,
			}).
			WithError(err).
			Fatal("Error loading data.")
	}
	if len(data) == 0 {
		logger.
			WithFields(logrus.Fields{
				"address":   address,
				"use-stdin": useStdin,
				"source":    sourceFile,
			}).
			Fatal("Data is empty")
	}
	keys := make([]string, 0, len(data))
	for k := range data {
		keys = append(keys, k)
	}

	logger.WithField("data", data).Debug("Loaded data.")

	mux := http.NewServeMux()

	mux.HandleFunc("/humans.txt", func(rw http.ResponseWriter, r *http.Request) {
		logger.
			WithFields(logrus.Fields{
				"method": r.Method,
				"uri":    r.URL.Path,
			}).
			Info()
		rw.Header().Set("Content-Type", "text/plain")
		fmt.Fprintln(rw, humans)
	})

	mux.HandleFunc("/", func(rw http.ResponseWriter, r *http.Request) {
		path := r.URL.Path
		entry := logger.WithFields(logrus.Fields{
			"method": r.Method,
			"uri":    path,
		})
		if r.Method != "GET" {
			failRequest(entry, rw, errors.New("unsupported method"), 405)
			return
		}
		contentType := parseContentType(path)

		var hash string
		var line string
		hash = parseHash(path)
		if val, ok := data[hash]; ok {
			line = val
		} else {
			hash = keys[rand.Intn(len(keys))]
			line = data[hash]
		}

		switch contentType {
		case "application/json":
			rw.Header().Set("Content-Type", contentType)
			err = renderJSON(rw, hash, line)
		case "text/plain":
			rw.Header().Set("Content-Type", contentType)
			fmt.Fprintln(rw, line)
		default:
			rw.Header().Set("Content-Type", "text/html")
			err = renderHTML(rw, hash, line)
		}

		if err != nil {
			failRequest(entry, rw, err, 500)
			return
		}

		entry.Info()
	})

	h := &http.Server{
		Addr:    formatAddress(address),
		Handler: mux,
	}

	if err := h.ListenAndServe(); err != nil {
		logger.WithError(err).Warning("HTTP Service stopped.")
	}
}

func parseHash(path string) string {
	path = strings.TrimPrefix(path, "/")
	path = strings.TrimSuffix(path, ".html")
	path = strings.TrimSuffix(path, ".json")
	path = strings.TrimSuffix(path, ".txt")
	return path
}

func parseContentType(path string) string {
	if strings.HasSuffix(path, ".txt") {
		return "text/plain"
	}
	if strings.HasSuffix(path, ".json") {
		return "application/json"
	}
	return "text/html"
}

func failRequest(entry *logrus.Entry, rw http.ResponseWriter, err error, statusCode int) {
	entry.WithError(err).Error("Failed to handle request.")
	http.Error(rw, err.Error(), statusCode)
}

func renderHTML(w io.Writer, hash, line string) error {
	t, err := template.New("webpage").Parse(tpl)
	if err != nil {
		return err
	}
	return t.Execute(w, struct {
		Hash string
		Line string
	}{
		Hash: hash,
		Line: line,
	})
}

func renderJSON(w io.Writer, hash, line string) error {
	c := struct {
		Line string `json:"line"`
		Hash string `json:"hash"`
	}{Line: line, Hash: hash}
	b, err := json.Marshal(&c)
	if err != nil {
		return err
	}
	_, err = w.Write(b)
	return err
}

func loadFile(path string) (content, error) {
	file, err := os.Open(path)
	if err != nil {
		return nil, err
	}
	defer file.Close()
	scanner := bufio.NewScanner(file)
	return scanContent(scanner)
}

func loadStdin() (content, error) {
	scanner := bufio.NewScanner(os.Stdin)
	return scanContent(scanner)
}

func scanContent(scanner *bufio.Scanner) (content, error) {
	var lines []string
	for scanner.Scan() {
		lines = append(lines, scanner.Text())
	}
	if err := scanner.Err(); err != nil {
		return nil, err
	}
	return parseLines(lines)
}

func parseLines(lines []string) (content, error) {
	content := make(map[string]string)
	for _, line := range lines {
		rawHash := md5.Sum([]byte(line))
		hash := hex.EncodeToString(rawHash[:])
		content[hash] = line
	}
	return content, nil
}

func formatAddress(input string) string {
	if strings.HasPrefix(input, ":") {
		return intput
	}
	return ":" + input
}
<|endoftext|>


<commit_before>package main

import (
	"github.com/nsf/termbox-go"
	// "github.com/gdamore/tcell"
	// "time"
	// "os"
)

type GameMap struct {
	CellAutoMap [][]bool
}

func main() {
	err := termbox.Init()
	if err != nil {
		panic(err)
	}
	defer termbox.Close()

	go launchLife()

	//wait for esc or ctrl+q pressed, and then exit
	loop:
	for {
		switch ev := termbox.PollEvent(); ev.Type {
		case termbox.EventKey:
			if ev.Key == termbox.KeyEsc ||
				ev.Key == termbox.KeyCtrlQ {
				break loop
			}
		case termbox.EventError:
			panic(ev.Err)
		}
	}
}

func launchLife() {
	//gameMap := initGameMap(termbox.Size())
	//fmt.Println(gameMap)
	termbox.SetCell(5, 10, '⏣', termbox.ColorWhite, termbox.ColorBlack)
	termbox.SetCell(1, 2, '⏺', termbox.ColorWhite, termbox.ColorBlack)
	termbox.SetCell(10, 5, '⏹', termbox.ColorWhite, termbox.ColorBlack)
	termbox.Flush()
}

func initGameMap(width, height int) GameMap {
	cellAutoMap := make([][]bool, height)

	for i := 0; i < height; i++ {
		cellAutoMap[i] = make([]bool, width)
	}

	return GameMap{cellAutoMap}
}<commit_msg>Interim changes<commit_after>package main

import (
	"github.com/nsf/termbox-go"
	// "github.com/gdamore/tcell"
	// "time"
	// "os"
	"fmt"
)

const DELAY_MS = 200

type GameMap struct {
	cellMap      [][]bool
	changeEvents []ChangeEvent

}

func (gameMap *GameMap) getSize() (int, int) {
	height := len(gameMap)
	if height == 0 {
		panic("Height must not be 0")
	}

	width := len(gameMap[0])
	if width == 0 {
		panic("Width must not be 0")
	}

	return height, width
}

type ChangeEvent struct {
	x,y int
	newValue bool
}

func main() {
	err := termbox.Init()
	if err != nil {
		panic(err)
	}
	defer termbox.Close()

	go launchLife()

	//wait for esc or ctrl+q pressed, and then exit
	loop:
	for {
		switch ev := termbox.PollEvent(); ev.Type {
		case termbox.EventKey:
			if ev.Key == termbox.KeyEsc ||
				ev.Key == termbox.KeyCtrlQ {
				break loop
			}
		case termbox.EventError:
			panic(ev.Err)
		}
	}
}

func launchLife() {
	gameMap := initGameMap(termbox.Size())
	fmt.Println(gameMap)

	termbox.SetCell(5, 10, '⏣', termbox.ColorWhite, termbox.ColorBlack)
	termbox.SetCell(1, 2, '⏺', termbox.ColorWhite, termbox.ColorBlack)
	termbox.SetCell(10, 5, '⏹', termbox.ColorWhite, termbox.ColorBlack)
	termbox.Flush()
}

func initGameMap(width, height int) *GameMap {
	cellAutoMap := make([][]bool, height)

	for i := 0; i < height; i++ {
		cellAutoMap[i] = make([]bool, width)
	}

	return &GameMap{cellMap: cellAutoMap}
}

func fillMapRandomValues(gameMap *GameMap) {

}<|endoftext|>


<commit_before>package main

import (
	"fmt"
)

func main() {
	fmt.Println("program start today")
	fmt.Println("yidane come here")
	fmt.Println("Frank-Ding:wq")
	fmt.Println("jiangyd conne here")
	fmt.Println("liupeng come here!!!")
	fmt.Println("test merger")
	fmt.Println("develop on mydev branch")
}
<commit_msg>sxfyyzandy add comments<commit_after>package main

import (
	"fmt"
)

func main() {
	fmt.Println("program start today")
	fmt.Println("yidane come here")
	fmt.Println("Frank-Ding:wq")
	fmt.Println("jiangyd conne here")
	fmt.Println("liupeng come here!!!")
	fmt.Println("test merger")
	fmt.Println("develop on mydev branch")

	fmt.Println("sxfyyzandy add comments")
}
<|endoftext|>


<commit_before>// Copyright © 2016 Abcum Ltd
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this info 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.

// +build cgo

package pdflib

// #include <stdio.h>
// #include <stdlib.h>
// #include "pdflib.h"
import "C"

type Instance struct {
	val *C.PDF
}

func New() *Instance {
	return &Instance{val: C.PDF_new()}
}

// AddNamedDest
func (i *Instance) AddNamedDest(name, options string) {}

// AddPathPoint
func (i *Instance) AddPathPoint(path int, x, y float64, kind, options string) {}

// AddTableCell
func (i *Instance) AddTableCell(table, col, row int, text, options string) {}

// AddTextflow
func (i *Instance) AddTextflow(textflow int, text, options string) {}

// AddThumbnail
func (i *Instance) AddThumbnail(image int) {}

// Align
func (i *Instance) Align(x, y float64) {}

// Arc
func (i *Instance) Arc(x, y, r, alpha, beta float64) {}

// Arcn
func (i *Instance) Arcn(x, y, r, alpha, beta float64) {}

// BeginDocument
func (i *Instance) BeginDocument(filename, options string) {}

// BeginDocumentCallback
func (i *Instance) BeginDocumentCallback() {} // FIXME

// BeginFont
func (i *Instance) BeginFont(fontname string, a, b, c, d, e, f float64, options string) {}

// BeginGlyph
func (i *Instance) BeginGlyph(glyphname string, wx, llx, lly, urx, ury float64) {}

// BeginPageExt adds a new page to the document, and specify various options.
func (i *Instance) BeginPageExt(w, h float64, options string) {}

// BeginTemplate
func (i *Instance) BeginTemplate(w, h float64) {}

// Circle
func (i *Instance) Circle(x, y, r float64) {}

// CircularArc
func (i *Instance) CircularArc(x1, y1, x2, y2 float64) {}

// Clip
func (i *Instance) Clip() {}

// CloseFont closes an open font handle which has not yet been used in the document.
func (i *Instance) CloseFont(font int) {}

// CloseImage closes an image
func (i *Instance) CloseImage(image int) {}

// ClosePdiDocument
func (i *Instance) ClosePdiDocument(doc int) {}

// ClosePdiPage
func (i *Instance) ClosePdiPage(page int) {}

// ClosePath
func (i *Instance) ClosePath() {}

// ClosePathFillStroke
func (i *Instance) ClosePathFillStroke() {}

// Concat
func (i *Instance) Concat(a, b, c, d, e, f float64) {}

// ContinueText
func (i *Instance) ContinueText(text string) {}

// Create3dView
func (i *Instance) Create3dView(username, options string) {}

// CreateAction
func (i *Instance) CreateAction(kind, options string) {}

// CreateAnnotation
func (i *Instance) CreateAnnotation(llx, llr, urx, ury float64, kind, options string) {}

// CreateBookmark
func (i *Instance) CreateBookmark(text, options string) {}

// CreateField
func (i *Instance) CreateField(llx, lly, urx, ury float64, name, kind, options string) {}

// CreateFieldgroup
func (i *Instance) CreateFieldgroup(name, options string) {}

// CreateGstate
func (i *Instance) CreateGstate(options string) {}

// CreatePvf
func (i *Instance) CreatePvf(filename string, data []byte, options string) {}

// CreateTextflow
func (i *Instance) CreateTextflow(text, options string) {}

// CurveTo
func (i *Instance) CurveTo(x1, y1, x2, y2, x3, y3 float64) {}

// DefineLayer
func (i *Instance) DefineLayer(name, options string) {}

// Delete
func (i *Instance) Delete() {}

// DeletePath
func (i *Instance) DeletePath(path int) {}

// DeletePvf
func (i *Instance) DeletePvf(filename string) {}

// DeleteTable
func (i *Instance) DeleteTable(table int, options string) {}

// DeleteTextflow
func (i *Instance) DeleteTextflow(textflow int) {}

// DrawPath
func (i *Instance) DrawPath(path int, x, y float64, options string) {}

// Ellipse
func (i *Instance) Ellipse(x, y, rx, ry float64) {}

// EndDocument
func (i *Instance) EndDocument(options string) {}

// EndFont
func (i *Instance) EndFont() {}

// EndGlyph
func (i *Instance) EndGlyph() {}

// EndItem
func (i *Instance) EndItem(id int) {}

// EndLayer
func (i *Instance) EndLayer() {}

// EndMc
func (i *Instance) EndMc() {}

// EndPageExt
func (i *Instance) EndPageExt() {}

// EndPattern
func (i *Instance) EndPattern() {}

// EndTemplateExt
func (i *Instance) EndTemplateExt(w, h float64) {}

// EndPath
func (i *Instance) EndPath() {}

// Fill
func (i *Instance) Fill() {}

// FillImageblock
func (i *Instance) FillImageblock(page int, blockname string, image int, options string) {}

// FillPdfblock
func (i *Instance) FillPdfblock(page int, blockname string, document int, options string) {}

// FillTextblock
func (i *Instance) FillTextblock(page int, blockname, text, options string) {}

// FitImage
func (i *Instance) FitImage(image int, x, y float64, options string) {}

// FitPdiPage
func (i *Instance) FitPdiPage(page int, x, y float64, options string) {}

// FitTable
func (i *Instance) FitTable(table int, llx, lly, urx, ury float64, options string) {}

// FitTextflow
func (i *Instance) FitTextflow(textflow int, llx, lly, urx, ury, options string) {}

// FitTextline
func (i *Instance) FitTextline(text string, x, y, float64, options string) {}

// GetBuffer
func (i *Instance) GetBuffer() {}

// GetParameter
func (i *Instance) GetParameter(key string, modifier float64) {}

// GetValue
func (i *Instance) GetValue(key string, modifier float64) {}

// InfoFont
func (i *Instance) InfoFont(font int, keyword, options string) {}

// InfoImage
func (i *Instance) InfoImage(image int, keyword, options string) {}

// InfoMatchbox
func (i *Instance) InfoMatchbox(boxname string, num int, keyword string) {}

// InfoPath
func (i *Instance) InfoPath(path int, keyword, options string) {}

// InfoPdiPage
func (i *Instance) InfoPdiPage(page int, keyword, options string) {}

// InfoTable
func (i *Instance) InfoTable(table int, keyword string) {}

// InfoTextflow
func (i *Instance) InfoTextflow(textflow int, keyword string) {}

// InfoTextline
func (i *Instance) InfoTextline(text, keyword, options string) {}

// InitGraphics
func (i *Instance) InitGraphics() {}

// LineTo
func (i *Instance) LineTo(x, y float64) {}

// Load3dData
func (i *Instance) Load3dData(filename, options string) {}

// LoadFont
func (i *Instance) LoadFont(fontname, encoding, options string) {}

// LoadIccProfile
func (i *Instance) LoadIccProfile(profilename, options string) {}

// LoadImage
func (i *Instance) LoadImage(imagetype, filename, options string) {}

// MakeSpotColor
func (i *Instance) MakeSpotColor(spotname string) {}

// McPoint
func (i *Instance) McPoint(tag, options string) {}

// MoveTo
func (i *Instance) MoveTo(x, y float64) {}

// OpenPdiDocument
func (i *Instance) OpenPdiDocument(filename, options string) {}

// OpenPdiCallback
func (i *Instance) OpenPdiCallback() {} // FIXME

// OpenPdiPage
func (i *Instance) OpenPdiPage(doc, page int, options string) {}

// PcosGetNumber
func (i *Instance) PcosGetNumber(doc int, path string) {}

// PcosGetString
func (i *Instance) PcosGetString(doc int, path string) {}

// PcosGetStream
func (i *Instance) PcosGetStream(doc int, options, path string) {}

// ProcessPdi
func (i *Instance) ProcessPdi(doc, page int, options string) {}

// RCurveTo
func (i *Instance) RCurveTo(x1, y1, x2, y2, x3, y3 float64) {}

// Rect
func (i *Instance) Rect(x, y, w, h float64) {}

// Restore
func (i *Instance) Restore() {}

// ResumePage
func (i *Instance) ResumePage(options string) {}

// Rotate
func (i *Instance) Rotate(phi float64) {}

// Save
func (i *Instance) Save() {}

// Scale
func (i *Instance) Scale(sx, sy float64) {}

// SetGstate
func (i *Instance) SetGstate(gstate int) {}

// SetInfo
func (i *Instance) SetInfo(key, value string) {}

// SetLayerDependency
func (i *Instance) SetLayerDependency(kind, options string) {}

// SetOption
func (i *Instance) SetOption(options string) {}

// SetParameter
func (i *Instance) SetParameter(key, value string) {}

// SetTextPos
func (i *Instance) SetTextPos(x, y float64) {}

// SetValue
func (i *Instance) SetValue(x, y float64) {}

// SetColor
func (i *Instance) SetColor(fstype, colorspace string, c1, c2, c3, c4 float64) {}

// SetDash
func (i *Instance) SetDash(b, w float64) {}

// SetDashPattern
func (i *Instance) SetDashPattern(options string) {}

// SetFlat
func (i *Instance) SetFlat(flatness float64) {}

// SetFont
func (i *Instance) SetFont(font int, fontsize float64) {}

// SetGray
func (i *Instance) SetGray(gray float64) {}

// SetGrayFill
func (i *Instance) SetGrayFill(gray float64) {}

// SetGrayStroke
func (i *Instance) SetGrayStroke(gray float64) {}

// SetLinecap
func (i *Instance) SetLinecap(linecap int) {}

// SetLinejoin
func (i *Instance) SetLinejoin(linejoin int) {}

// SetLinewidth
func (i *Instance) SetLinewidth(width float64) {}

// SetMatrix
func (i *Instance) SetMatrix(a, b, c, d, e, f float64) {}

// SetMatrix
func (i *Instance) SetMiterLimit(miter float64) {}

// Shading
func (i *Instance) Shading(shtype string, x0, y0, x1, y1, c1, c2, c3, c4 float64, options string) {}

// ShadingPattern
func (i *Instance) ShadingPattern(shading int, options string) {}

// Shfill
func (i *Instance) Shfill(shading int) {}

// Show
func (i *Instance) Show(text string) {}

// ShowXY
func (i *Instance) ShowXY(text string, x, y float64) {}

// Skew
func (i *Instance) Skew(alpha, beta float64) {}

// StringWidth
func (i *Instance) StringWidth(text string, font int, fontsize float64) {}

// Stroke
func (i *Instance) Stroke() {}

// SuspendPage
func (i *Instance) SuspendPage(options string) {}

// Translate
func (i *Instance) Translate(tx, ty float64) {}
<commit_msg>Update godoc comments<commit_after>// Copyright © 2016 Abcum Ltd
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this info 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.

// +build cgo

package pdflib

// #include <stdio.h>
// #include <stdlib.h>
// #include "pdflib.h"
import "C"

type Instance struct {
	val *C.PDF
}

// Instance represents a PDFlib instance.
func New() *Instance {
	return &Instance{val: C.PDF_new()}
}

// AddNamedDest ...
func (i *Instance) AddNamedDest(name, options string) {}

// AddPathPoint ...
func (i *Instance) AddPathPoint(path int, x, y float64, kind, options string) {}

// AddTableCell ...
func (i *Instance) AddTableCell(table, col, row int, text, options string) {}

// AddTextflow ...
func (i *Instance) AddTextflow(textflow int, text, options string) {}

// AddThumbnail ...
func (i *Instance) AddThumbnail(image int) {}

// Align ...
func (i *Instance) Align(x, y float64) {}

// Arc ...
func (i *Instance) Arc(x, y, r, alpha, beta float64) {}

// Arcn ...
func (i *Instance) Arcn(x, y, r, alpha, beta float64) {}

// BeginDocument ...
func (i *Instance) BeginDocument(filename, options string) {}

// BeginDocumentCallback ...
func (i *Instance) BeginDocumentCallback() {} // FIXME

// BeginFont ...
func (i *Instance) BeginFont(fontname string, a, b, c, d, e, f float64, options string) {}

// BeginGlyph ...
func (i *Instance) BeginGlyph(glyphname string, wx, llx, lly, urx, ury float64) {}

// BeginPageExt adds a new page to the document, and specify various options. ...
func (i *Instance) BeginPageExt(w, h float64, options string) {}

// BeginTemplate ...
func (i *Instance) BeginTemplate(w, h float64) {}

// Circle ...
func (i *Instance) Circle(x, y, r float64) {}

// CircularArc ...
func (i *Instance) CircularArc(x1, y1, x2, y2 float64) {}

// Clip ...
func (i *Instance) Clip() {}

// CloseFont closes an open font handle which has not yet been used in the document. ...
func (i *Instance) CloseFont(font int) {}

// CloseImage closes an image ...
func (i *Instance) CloseImage(image int) {}

// ClosePdiDocument ...
func (i *Instance) ClosePdiDocument(doc int) {}

// ClosePdiPage ...
func (i *Instance) ClosePdiPage(page int) {}

// ClosePath ...
func (i *Instance) ClosePath() {}

// ClosePathFillStroke ...
func (i *Instance) ClosePathFillStroke() {}

// Concat ...
func (i *Instance) Concat(a, b, c, d, e, f float64) {}

// ContinueText ...
func (i *Instance) ContinueText(text string) {}

// Create3dView ...
func (i *Instance) Create3dView(username, options string) {}

// CreateAction ...
func (i *Instance) CreateAction(kind, options string) {}

// CreateAnnotation ...
func (i *Instance) CreateAnnotation(llx, llr, urx, ury float64, kind, options string) {}

// CreateBookmark ...
func (i *Instance) CreateBookmark(text, options string) {}

// CreateField ...
func (i *Instance) CreateField(llx, lly, urx, ury float64, name, kind, options string) {}

// CreateFieldgroup ...
func (i *Instance) CreateFieldgroup(name, options string) {}

// CreateGstate ...
func (i *Instance) CreateGstate(options string) {}

// CreatePvf ...
func (i *Instance) CreatePvf(filename string, data []byte, options string) {}

// CreateTextflow ...
func (i *Instance) CreateTextflow(text, options string) {}

// CurveTo ...
func (i *Instance) CurveTo(x1, y1, x2, y2, x3, y3 float64) {}

// DefineLayer ...
func (i *Instance) DefineLayer(name, options string) {}

// Delete ...
func (i *Instance) Delete() {}

// DeletePath ...
func (i *Instance) DeletePath(path int) {}

// DeletePvf ...
func (i *Instance) DeletePvf(filename string) {}

// DeleteTable ...
func (i *Instance) DeleteTable(table int, options string) {}

// DeleteTextflow ...
func (i *Instance) DeleteTextflow(textflow int) {}

// DrawPath ...
func (i *Instance) DrawPath(path int, x, y float64, options string) {}

// Ellipse ...
func (i *Instance) Ellipse(x, y, rx, ry float64) {}

// EndDocument ...
func (i *Instance) EndDocument(options string) {}

// EndFont ...
func (i *Instance) EndFont() {}

// EndGlyph ...
func (i *Instance) EndGlyph() {}

// EndItem ...
func (i *Instance) EndItem(id int) {}

// EndLayer ...
func (i *Instance) EndLayer() {}

// EndMc ...
func (i *Instance) EndMc() {}

// EndPageExt ...
func (i *Instance) EndPageExt() {}

// EndPattern ...
func (i *Instance) EndPattern() {}

// EndTemplateExt ...
func (i *Instance) EndTemplateExt(w, h float64) {}

// EndPath ...
func (i *Instance) EndPath() {}

// Fill ...
func (i *Instance) Fill() {}

// FillImageblock ...
func (i *Instance) FillImageblock(page int, blockname string, image int, options string) {}

// FillPdfblock ...
func (i *Instance) FillPdfblock(page int, blockname string, document int, options string) {}

// FillTextblock ...
func (i *Instance) FillTextblock(page int, blockname, text, options string) {}

// FitImage ...
func (i *Instance) FitImage(image int, x, y float64, options string) {}

// FitPdiPage ...
func (i *Instance) FitPdiPage(page int, x, y float64, options string) {}

// FitTable ...
func (i *Instance) FitTable(table int, llx, lly, urx, ury float64, options string) {}

// FitTextflow ...
func (i *Instance) FitTextflow(textflow int, llx, lly, urx, ury, options string) {}

// FitTextline ...
func (i *Instance) FitTextline(text string, x, y, float64, options string) {}

// GetBuffer ...
func (i *Instance) GetBuffer() {}

// GetParameter ...
func (i *Instance) GetParameter(key string, modifier float64) {}

// GetValue ...
func (i *Instance) GetValue(key string, modifier float64) {}

// InfoFont ...
func (i *Instance) InfoFont(font int, keyword, options string) {}

// InfoImage ...
func (i *Instance) InfoImage(image int, keyword, options string) {}

// InfoMatchbox ...
func (i *Instance) InfoMatchbox(boxname string, num int, keyword string) {}

// InfoPath ...
func (i *Instance) InfoPath(path int, keyword, options string) {}

// InfoPdiPage ...
func (i *Instance) InfoPdiPage(page int, keyword, options string) {}

// InfoTable ...
func (i *Instance) InfoTable(table int, keyword string) {}

// InfoTextflow ...
func (i *Instance) InfoTextflow(textflow int, keyword string) {}

// InfoTextline ...
func (i *Instance) InfoTextline(text, keyword, options string) {}

// InitGraphics ...
func (i *Instance) InitGraphics() {}

// LineTo ...
func (i *Instance) LineTo(x, y float64) {}

// Load3dData ...
func (i *Instance) Load3dData(filename, options string) {}

// LoadFont ...
func (i *Instance) LoadFont(fontname, encoding, options string) {}

// LoadIccProfile ...
func (i *Instance) LoadIccProfile(profilename, options string) {}

// LoadImage ...
func (i *Instance) LoadImage(imagetype, filename, options string) {}

// MakeSpotColor ...
func (i *Instance) MakeSpotColor(spotname string) {}

// McPoint ...
func (i *Instance) McPoint(tag, options string) {}

// MoveTo ...
func (i *Instance) MoveTo(x, y float64) {}

// OpenPdiDocument ...
func (i *Instance) OpenPdiDocument(filename, options string) {}

// OpenPdiCallback ...
func (i *Instance) OpenPdiCallback() {} // FIXME

// OpenPdiPage ...
func (i *Instance) OpenPdiPage(doc, page int, options string) {}

// PcosGetNumber ...
func (i *Instance) PcosGetNumber(doc int, path string) {}

// PcosGetString ...
func (i *Instance) PcosGetString(doc int, path string) {}

// PcosGetStream ...
func (i *Instance) PcosGetStream(doc int, options, path string) {}

// ProcessPdi ...
func (i *Instance) ProcessPdi(doc, page int, options string) {}

// RCurveTo ...
func (i *Instance) RCurveTo(x1, y1, x2, y2, x3, y3 float64) {}

// Rect ...
func (i *Instance) Rect(x, y, w, h float64) {}

// Restore ...
func (i *Instance) Restore() {}

// ResumePage ...
func (i *Instance) ResumePage(options string) {}

// Rotate ...
func (i *Instance) Rotate(phi float64) {}

// Save ...
func (i *Instance) Save() {}

// Scale ...
func (i *Instance) Scale(sx, sy float64) {}

// SetGstate ...
func (i *Instance) SetGstate(gstate int) {}

// SetInfo ...
func (i *Instance) SetInfo(key, value string) {}

// SetLayerDependency ...
func (i *Instance) SetLayerDependency(kind, options string) {}

// SetOption ...
func (i *Instance) SetOption(options string) {}

// SetParameter ...
func (i *Instance) SetParameter(key, value string) {}

// SetTextPos ...
func (i *Instance) SetTextPos(x, y float64) {}

// SetValue ...
func (i *Instance) SetValue(x, y float64) {}

// SetColor ...
func (i *Instance) SetColor(fstype, colorspace string, c1, c2, c3, c4 float64) {}

// SetDash ...
func (i *Instance) SetDash(b, w float64) {}

// SetDashPattern ...
func (i *Instance) SetDashPattern(options string) {}

// SetFlat ...
func (i *Instance) SetFlat(flatness float64) {}

// SetFont ...
func (i *Instance) SetFont(font int, fontsize float64) {}

// SetGray ...
func (i *Instance) SetGray(gray float64) {}

// SetGrayFill ...
func (i *Instance) SetGrayFill(gray float64) {}

// SetGrayStroke ...
func (i *Instance) SetGrayStroke(gray float64) {}

// SetLinecap ...
func (i *Instance) SetLinecap(linecap int) {}

// SetLinejoin ...
func (i *Instance) SetLinejoin(linejoin int) {}

// SetLinewidth ...
func (i *Instance) SetLinewidth(width float64) {}

// SetMatrix ...
func (i *Instance) SetMatrix(a, b, c, d, e, f float64) {}

// SetMatrix ...
func (i *Instance) SetMiterLimit(miter float64) {}

// Shading ...
func (i *Instance) Shading(shtype string, x0, y0, x1, y1, c1, c2, c3, c4 float64, options string) {}

// ShadingPattern ...
func (i *Instance) ShadingPattern(shading int, options string) {}

// Shfill ...
func (i *Instance) Shfill(shading int) {}

// Show ...
func (i *Instance) Show(text string) {}

// ShowXY ...
func (i *Instance) ShowXY(text string, x, y float64) {}

// Skew ...
func (i *Instance) Skew(alpha, beta float64) {}

// StringWidth ...
func (i *Instance) StringWidth(text string, font int, fontsize float64) {}

// Stroke ...
func (i *Instance) Stroke() {}

// SuspendPage ...
func (i *Instance) SuspendPage(options string) {}

// Translate ...
func (i *Instance) Translate(tx, ty float64) {}
<|endoftext|>


<commit_before>package main

import (
	"crypto/tls"
	"errors"
	"fmt"
	"io/ioutil"
	"net/http"
	"strings"
	"time"
)

var clientHttps *http.Client
var clientHttp *http.Client

func init() {
	initConf()

	tr := &http.Transport{
		TLSClientConfig: &tls.Config{InsecureSkipVerify: true},
	}
	clientHttps = &http.Client{Transport: tr}
	clientHttp = &http.Client{}
}

// handler entrance
func handler(w http.ResponseWriter, r *http.Request) {
	w.Header().Set("Content-Type", "application/json")

	for i := 0; i < len(appConf.Uris); i++ {
		if r.URL.Path == appConf.Uris[i].Uri {
			handleRequest(w, r, appConf.Uris[i].Delay, appConf.Uris[i])
			return
		}
	}
}

func handleRequest(w http.ResponseWriter, r *http.Request, delay int, uri Uri) {
	time.Sleep(time.Duration(delay) * time.Millisecond)

	// from outer
	if uri.Source != "" {
		handleSource(w, r, uri)
		return
	}

	// from json
	for _, entry := range uri.Headers {
		for key, value := range entry {
			w.Header().Set(key, value)
		}
	}

	fmt.Fprintf(w, uri.Body)
}

func handleSource(w http.ResponseWriter, r *http.Request, uri Uri) {
	srcArry := strings.SplitN(uri.Source, " ", 2)
	if strings.HasPrefix(srcArry[1], "http://") {
		handleHttp(w, r, clientHttp, srcArry)
		return
	}

	if strings.HasPrefix(srcArry[1], "https://") {
		handleHttp(w, r, clientHttps, srcArry)
		return
	}

	// handle local file
	fmt.Fprintf(w, loadCert(uri.Body))
	return
}

// handle http and https
func handleHttp(w http.ResponseWriter, r *http.Request, client *http.Client, srcArry []string) {
	var resp *http.Response
	var err error
	if srcArry[0] == "GET" {
		fmt.Println("GET:[", srcArry[1], "]")
		resp, err = client.Get(srcArry[1])
	} else if srcArry[0] == "POST" {
		fmt.Println("POST:[", srcArry[1], "]")
		resp, err = client.Post(srcArry[1], "application/json", r.Body)
	} else {
		err = errors.New("Method not supported yet:" + srcArry[0])
	}

	if err != nil {
		fmt.Fprintf(w, err.Error())
		return
	}
	defer resp.Body.Close()

	body, err := ioutil.ReadAll(resp.Body)
	if err != nil {
		fmt.Fprintf(w, err.Error())
		return
	}
	for key, entry := range resp.Header {
		w.Header().Set(key, strings.Join(entry, ","))
	}
	fmt.Fprintf(w, string(body))
}

func main() {
	for i := 0; i < len(appConf.Uris); i++ {
		http.HandleFunc(appConf.Uris[i].Uri, handler)
	}
	//http.HandleFunc("/", handler)
	//http.ListenAndServeTLS(":20175", "cert/server.cert", "cert/server.key", nil)
	http.ListenAndServe(":20175", nil)
}

func loadCert(filename string) string {
	data, err := ioutil.ReadFile(filename)
	if err != nil {
		fmt.Println("ERROR:", err)
	}
	return string(data)
}
<commit_msg>support proxy mode<commit_after>package main

import (
	"crypto/tls"
	"errors"
	"fmt"
	"io/ioutil"
	"net/http"
	"os"
	"strings"
	"time"
)

var clientHttps *http.Client
var clientHttp *http.Client

func init() {
	initConf()

	tr := &http.Transport{
		TLSClientConfig: &tls.Config{InsecureSkipVerify: true},
	}
	clientHttps = &http.Client{Transport: tr}
	clientHttp = &http.Client{}
}

// handler entrance
func handler(w http.ResponseWriter, r *http.Request) {
	w.Header().Set("Content-Type", "application/json")

	for i := 0; i < len(appConf.Uris); i++ {
		if r.URL.Path == appConf.Uris[i].Uri {
			handleRequest(w, r, appConf.Uris[i].Delay, appConf.Uris[i])
			return
		}
	}
}

func handleRequest(w http.ResponseWriter, r *http.Request, delay int, uri Uri) {
	time.Sleep(time.Duration(delay) * time.Millisecond)

	// from outer
	if uri.Source != "" {
		handleSource(w, r, uri)
		return
	}

	// from json
	for _, entry := range uri.Headers {
		for key, value := range entry {
			w.Header().Set(key, value)
		}
	}

	fmt.Fprintf(w, uri.Body)
}

func handleSource(w http.ResponseWriter, r *http.Request, uri Uri) {
	srcArry := strings.SplitN(uri.Source, " ", 2)
	if strings.HasPrefix(srcArry[1], "http://") {
		handleHttp(w, r, clientHttp, srcArry)
		return
	}

	if strings.HasPrefix(srcArry[1], "https://") {
		handleHttp(w, r, clientHttps, srcArry)
		return
	}

	// handle local file
	fmt.Fprintf(w, loadCert(uri.Body))
	return
}

// handle http and https
func handleHttp(w http.ResponseWriter, r *http.Request, client *http.Client, srcArry []string) {
	var resp *http.Response
	var err error
	if srcArry[0] == "GET" {
		fmt.Println("GET:[", srcArry[1], "]")
		resp, err = client.Get(srcArry[1])
	} else if srcArry[0] == "POST" {
		fmt.Println("POST:[", srcArry[1], "]")
		resp, err = client.Post(srcArry[1], "application/json", r.Body)
	} else {
		err = errors.New("Method not supported yet:" + srcArry[0])
	}

	if err != nil {
		fmt.Fprintf(w, err.Error())
		return
	}
	defer resp.Body.Close()

	body, err := ioutil.ReadAll(resp.Body)
	if err != nil {
		fmt.Fprintf(w, err.Error())
		return
	}
	for key, entry := range resp.Header {
		w.Header().Set(key, strings.Join(entry, ","))
	}
	fmt.Fprintf(w, string(body))
}

func main() {
	for i := 0; i < len(appConf.Uris); i++ {
		http.HandleFunc(appConf.Uris[i].Uri, handler)
	}
	//http.HandleFunc("/", handler)
	if exist("config/server.cert") && exist("config/server.key") {
		http.ListenAndServeTLS(":20175", "cert/server.cert", "cert/server.key", nil)
	} else {
		http.ListenAndServe(":20175", nil)
	}
}

func loadCert(filename string) string {
	data, err := ioutil.ReadFile(filename)
	if err != nil {
		fmt.Println("ERROR:", err)
	}
	return string(data)
}

func exist(filename string) bool {
	_, err := os.Stat(filename)
	return err == nil || os.IsExist(err)
}
<|endoftext|>


<commit_before>package main

// about using johnniedoe/contrib/gzip:
// johnniedoe's fork fixes a critical issue for which .String resulted in
// an ERR_DECODING_FAILED. This is an actual pull request on the contrib
// repo, but apparently, gin is dead.

import (
	"encoding/gob"
	"fmt"

	"git.zxq.co/ripple/rippleapi/app"
	"git.zxq.co/ripple/schiavolib"
	"git.zxq.co/x/rs"
	"github.com/fatih/structs"
	"github.com/getsentry/raven-go"
	"github.com/gin-gonic/contrib/sessions"
	"github.com/gin-gonic/gin"
	_ "github.com/go-sql-driver/mysql"
	"github.com/jmoiron/sqlx"
	"github.com/johnniedoe/contrib/gzip"
	"github.com/thehowl/conf"
	"github.com/thehowl/qsql"
	"gopkg.in/mailgun/mailgun-go.v1"
)

// version is the version of hanayo
const version = "v1.0.3"

var (
	config struct {
		ListenTo string `description:"ip:port from which to take requests."`
		Unix     bool   `description:"Whether ListenTo is an unix socket."`

		DSN string `description:"MySQL server DSN"`

		CookieSecret string

		RedisEnable         bool
		RedisMaxConnections int
		RedisNetwork        string
		RedisAddress        string
		RedisPassword       string

		AvatarURL     string
		BaseURL       string
		DiscordServer string

		API       string
		BanchoAPI string
		APISecret string

		IP_API string

		Offline          bool   `description:"If this is true, files will be served from the local server instead of the CDN."`
		MainRippleFolder string `description:"Folder where all the non-go projects are contained, such as old-frontend, lets, ci-system."`
		AvatarsFolder    string `description:"location folder of avatars"`

		MailgunDomain        string
		MailgunPrivateAPIKey string
		MailgunPublicAPIKey  string
		MailgunFrom          string

		RecaptchaSite    string
		RecaptchaPrivate string

		DiscordOAuthID     string
		DiscordOAuthSecret string
		DonorBotURL        string
		DonorBotSecret     string

		SentryDSN string
	}
	configMap map[string]interface{}
	db        *sqlx.DB
	qb        *qsql.DB
	mg        mailgun.Mailgun
)

func main() {
	fmt.Println("hanayo " + version)

	err := conf.Load(&config, "hanayo.conf")
	switch err {
	case nil:
		// carry on
	case conf.ErrNoFile:
		conf.Export(config, "hanayo.conf")
		fmt.Println("The configuration file was not found. We created one for you.")
		return
	default:
		panic(err)
	}

	var configDefaults = map[*string]string{
		&config.ListenTo:         ":45221",
		&config.CookieSecret:     rs.String(46),
		&config.AvatarURL:        "https://a.ripple.moe",
		&config.BaseURL:          "https://ripple.moe",
		&config.BanchoAPI:        "https://c.ripple.moe",
		&config.API:              "http://localhost:40001/api/v1/",
		&config.APISecret:        "Potato",
		&config.IP_API:           "https://ip.zxq.co",
		&config.DiscordServer:    "#",
		&config.MainRippleFolder: "/home/ripple/ripple",
		&config.MailgunFrom:      `"Ripple" <noreply@ripple.moe>`,
	}
	for key, value := range configDefaults {
		if *key == "" {
			*key = value
		}
	}

	configMap = structs.Map(config)

	// initialise db
	db, err = sqlx.Open("mysql", config.DSN)
	if err != nil {
		panic(err)
	}
	qb = qsql.New(db.DB)
	if err != nil {
		panic(err)
	}

	// initialise mailgun
	mg = mailgun.NewMailgun(
		config.MailgunDomain,
		config.MailgunPrivateAPIKey,
		config.MailgunPublicAPIKey,
	)

	if gin.Mode() == gin.DebugMode {
		fmt.Println("Development environment detected. Starting fsnotify on template folder...")
		err := reloader()
		if err != nil {
			fmt.Println(err)
		}
	}

	schiavo.Prefix = "hanayo"
	schiavo.Bunker.Send(fmt.Sprintf("STARTUATO, mode: %s", gin.Mode()))

	// even if it's not release, we say that it's release
	// so that gin doesn't spam
	gin.SetMode(gin.ReleaseMode)

	gobRegisters := []interface{}{
		[]message{},
		errorMessage{},
		infoMessage{},
		neutralMessage{},
		warningMessage{},
		successMessage{},
	}
	for _, el := range gobRegisters {
		gob.Register(el)
	}

	fmt.Println("Importing templates...")
	loadTemplates("")

	fmt.Println("Setting up rate limiter...")
	setUpLimiter()

	fmt.Println("Exporting configuration...")

	conf.Export(config, "hanayo.conf")

	httpLoop()
}

func httpLoop() {
	for {
		e := generateEngine()
		fmt.Println("Starting webserver...")
		if !startuato(e) {
			break
		}
	}
}

func generateEngine() *gin.Engine {
	fmt.Println("Starting session system...")
	var store sessions.Store
	if config.RedisMaxConnections != 0 {
		var err error
		store, err = sessions.NewRedisStore(
			config.RedisMaxConnections,
			config.RedisNetwork,
			config.RedisAddress,
			config.RedisPassword,
			[]byte(config.CookieSecret),
		)
		if err != nil {
			fmt.Println(err)
			store = sessions.NewCookieStore([]byte(config.CookieSecret))
		}
	} else {
		store = sessions.NewCookieStore([]byte(config.CookieSecret))
	}

	r := gin.Default()

	// sentry
	if config.SentryDSN != "" {
		ravenClient, err := raven.New(config.SentryDSN)
		if err != nil {
			fmt.Println(err)
		} else {
			r.Use(app.Recovery(ravenClient, false))
		}
	}

	r.Use(
		gzip.Gzip(gzip.DefaultCompression),
		checkRedirect,
		sessions.Sessions("session", store),
		sessionInitializer(),
		rateLimiter(false),
		twoFALock,
	)

	r.Static("/static", "static")
	r.StaticFile("/favicon.ico", "static/favicon.ico")

	r.POST("/login", loginSubmit)
	r.GET("/logout", logout)

	r.GET("/register", register)
	r.POST("/register", registerSubmit)
	r.GET("/register/verify", verifyAccount)
	r.GET("/register/welcome", welcome)

	r.GET("/u/:user", userProfile)

	r.POST("/pwreset", passwordReset)
	r.GET("/pwreset/continue", passwordResetContinue)
	r.POST("/pwreset/continue", passwordResetContinueSubmit)

	r.GET("/2fa_gateway", tfaGateway)
	r.GET("/2fa_gateway/clear", clear2fa)
	r.GET("/2fa_gateway/verify", verify2fa)

	r.GET("/irc/generate", ircGenToken)

	r.GET("/settings/password", changePassword)
	r.POST("/settings/password", changePasswordSubmit)
	r.POST("/settings/userpage/parse", parseBBCode)
	r.POST("/settings/avatar", avatarSubmit)
	r.POST("/settings/2fa/disable", disable2fa)
	r.GET("/settings/discord/finish", discordFinish)

	r.GET("/donate/rates", getRates)

	loadSimplePages(r)

	r.NoRoute(notFound)

	return r
}

const alwaysRespondText = `Ooops! Looks like something went really wrong while trying to process your request.
Perhaps report this to a Ripple developer?
Retrying doing again what you were trying to do might work, too.`
<commit_msg>⬆ v1.0.4 ⬆<commit_after>package main

// about using johnniedoe/contrib/gzip:
// johnniedoe's fork fixes a critical issue for which .String resulted in
// an ERR_DECODING_FAILED. This is an actual pull request on the contrib
// repo, but apparently, gin is dead.

import (
	"encoding/gob"
	"fmt"

	"git.zxq.co/ripple/rippleapi/app"
	"git.zxq.co/ripple/schiavolib"
	"git.zxq.co/x/rs"
	"github.com/fatih/structs"
	"github.com/getsentry/raven-go"
	"github.com/gin-gonic/contrib/sessions"
	"github.com/gin-gonic/gin"
	_ "github.com/go-sql-driver/mysql"
	"github.com/jmoiron/sqlx"
	"github.com/johnniedoe/contrib/gzip"
	"github.com/thehowl/conf"
	"github.com/thehowl/qsql"
	"gopkg.in/mailgun/mailgun-go.v1"
)

// version is the version of hanayo
const version = "v1.0.4"

var (
	config struct {
		ListenTo string `description:"ip:port from which to take requests."`
		Unix     bool   `description:"Whether ListenTo is an unix socket."`

		DSN string `description:"MySQL server DSN"`

		CookieSecret string

		RedisEnable         bool
		RedisMaxConnections int
		RedisNetwork        string
		RedisAddress        string
		RedisPassword       string

		AvatarURL     string
		BaseURL       string
		DiscordServer string

		API       string
		BanchoAPI string
		APISecret string

		IP_API string

		Offline          bool   `description:"If this is true, files will be served from the local server instead of the CDN."`
		MainRippleFolder string `description:"Folder where all the non-go projects are contained, such as old-frontend, lets, ci-system."`
		AvatarsFolder    string `description:"location folder of avatars"`

		MailgunDomain        string
		MailgunPrivateAPIKey string
		MailgunPublicAPIKey  string
		MailgunFrom          string

		RecaptchaSite    string
		RecaptchaPrivate string

		DiscordOAuthID     string
		DiscordOAuthSecret string
		DonorBotURL        string
		DonorBotSecret     string

		SentryDSN string
	}
	configMap map[string]interface{}
	db        *sqlx.DB
	qb        *qsql.DB
	mg        mailgun.Mailgun
)

func main() {
	fmt.Println("hanayo " + version)

	err := conf.Load(&config, "hanayo.conf")
	switch err {
	case nil:
		// carry on
	case conf.ErrNoFile:
		conf.Export(config, "hanayo.conf")
		fmt.Println("The configuration file was not found. We created one for you.")
		return
	default:
		panic(err)
	}

	var configDefaults = map[*string]string{
		&config.ListenTo:         ":45221",
		&config.CookieSecret:     rs.String(46),
		&config.AvatarURL:        "https://a.ripple.moe",
		&config.BaseURL:          "https://ripple.moe",
		&config.BanchoAPI:        "https://c.ripple.moe",
		&config.API:              "http://localhost:40001/api/v1/",
		&config.APISecret:        "Potato",
		&config.IP_API:           "https://ip.zxq.co",
		&config.DiscordServer:    "#",
		&config.MainRippleFolder: "/home/ripple/ripple",
		&config.MailgunFrom:      `"Ripple" <noreply@ripple.moe>`,
	}
	for key, value := range configDefaults {
		if *key == "" {
			*key = value
		}
	}

	configMap = structs.Map(config)

	// initialise db
	db, err = sqlx.Open("mysql", config.DSN)
	if err != nil {
		panic(err)
	}
	qb = qsql.New(db.DB)
	if err != nil {
		panic(err)
	}

	// initialise mailgun
	mg = mailgun.NewMailgun(
		config.MailgunDomain,
		config.MailgunPrivateAPIKey,
		config.MailgunPublicAPIKey,
	)

	if gin.Mode() == gin.DebugMode {
		fmt.Println("Development environment detected. Starting fsnotify on template folder...")
		err := reloader()
		if err != nil {
			fmt.Println(err)
		}
	}

	schiavo.Prefix = "hanayo"
	schiavo.Bunker.Send(fmt.Sprintf("STARTUATO, mode: %s", gin.Mode()))

	// even if it's not release, we say that it's release
	// so that gin doesn't spam
	gin.SetMode(gin.ReleaseMode)

	gobRegisters := []interface{}{
		[]message{},
		errorMessage{},
		infoMessage{},
		neutralMessage{},
		warningMessage{},
		successMessage{},
	}
	for _, el := range gobRegisters {
		gob.Register(el)
	}

	fmt.Println("Importing templates...")
	loadTemplates("")

	fmt.Println("Setting up rate limiter...")
	setUpLimiter()

	fmt.Println("Exporting configuration...")

	conf.Export(config, "hanayo.conf")

	httpLoop()
}

func httpLoop() {
	for {
		e := generateEngine()
		fmt.Println("Starting webserver...")
		if !startuato(e) {
			break
		}
	}
}

func generateEngine() *gin.Engine {
	fmt.Println("Starting session system...")
	var store sessions.Store
	if config.RedisMaxConnections != 0 {
		var err error
		store, err = sessions.NewRedisStore(
			config.RedisMaxConnections,
			config.RedisNetwork,
			config.RedisAddress,
			config.RedisPassword,
			[]byte(config.CookieSecret),
		)
		if err != nil {
			fmt.Println(err)
			store = sessions.NewCookieStore([]byte(config.CookieSecret))
		}
	} else {
		store = sessions.NewCookieStore([]byte(config.CookieSecret))
	}

	r := gin.Default()

	// sentry
	if config.SentryDSN != "" {
		ravenClient, err := raven.New(config.SentryDSN)
		if err != nil {
			fmt.Println(err)
		} else {
			r.Use(app.Recovery(ravenClient, false))
		}
	}

	r.Use(
		gzip.Gzip(gzip.DefaultCompression),
		checkRedirect,
		sessions.Sessions("session", store),
		sessionInitializer(),
		rateLimiter(false),
		twoFALock,
	)

	r.Static("/static", "static")
	r.StaticFile("/favicon.ico", "static/favicon.ico")

	r.POST("/login", loginSubmit)
	r.GET("/logout", logout)

	r.GET("/register", register)
	r.POST("/register", registerSubmit)
	r.GET("/register/verify", verifyAccount)
	r.GET("/register/welcome", welcome)

	r.GET("/u/:user", userProfile)

	r.POST("/pwreset", passwordReset)
	r.GET("/pwreset/continue", passwordResetContinue)
	r.POST("/pwreset/continue", passwordResetContinueSubmit)

	r.GET("/2fa_gateway", tfaGateway)
	r.GET("/2fa_gateway/clear", clear2fa)
	r.GET("/2fa_gateway/verify", verify2fa)

	r.GET("/irc/generate", ircGenToken)

	r.GET("/settings/password", changePassword)
	r.POST("/settings/password", changePasswordSubmit)
	r.POST("/settings/userpage/parse", parseBBCode)
	r.POST("/settings/avatar", avatarSubmit)
	r.POST("/settings/2fa/disable", disable2fa)
	r.GET("/settings/discord/finish", discordFinish)

	r.GET("/donate/rates", getRates)

	loadSimplePages(r)

	r.NoRoute(notFound)

	return r
}

const alwaysRespondText = `Ooops! Looks like something went really wrong while trying to process your request.
Perhaps report this to a Ripple developer?
Retrying doing again what you were trying to do might work, too.`
<|endoftext|>


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

package gf256

import "testing"

var f = NewField(0x11d)	// x^8 + x^4 + x^3 + x^2 + 1

func TestBasic(t *testing.T) {
	if f.Exp(0) != 1 || f.Exp(1) != 2 || f.Exp(255) != 1 {
		panic("bad Exp")
	}
}
<commit_msg>gf256: test encoding, linearity, Gauss-Jordan<commit_after>// Copyright 2010 The Go Authors.  All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.

package gf256

import (
	"bytes"
	"fmt"
	"testing"
)

var f = NewField(0x11d)	// x^8 + x^4 + x^3 + x^2 + 1

func TestBasic(t *testing.T) {
	if f.Exp(0) != 1 || f.Exp(1) != 2 || f.Exp(255) != 1 {
		panic("bad Exp")
	}
}

func TestEncode(t *testing.T) {
	data := []byte{0x10, 0x20, 0x0c, 0x56, 0x61, 0x80, 0xec, 0x11, 0xec, 0x11, 0xec, 0x11, 0xec, 0x11, 0xec, 0x11}
	check := []byte{0xa5, 0x24, 0xd4, 0xc1, 0xed, 0x36, 0xc7, 0x87, 0x2c, 0x55}
	out := f.ECBytes(data, len(check))
	if !bytes.Equal(out, check) {
		t.Errorf("have %x want %x", out, check)
	}
}

func TestLinear(t *testing.T) {
	d1 := []byte{0x00, 0x00}
	c1 := []byte{0x00, 0x00}
	if out := f.ECBytes(d1, len(c1)); !bytes.Equal(out, c1) {
		t.Errorf("ECBytes(%x, %d) = %x, want 0", d1, len(c1), out)
	}
	d2 := []byte{0x00, 0x01}
	c2 := f.ECBytes(d2, 2)
	d3 := []byte{0x00, 0x02}
	c3 := f.ECBytes(d3, 2)
	cx := make([]byte, 2)
	for i := range cx {
		cx[i] = c2[i] ^ c3[i]
	}
	d4 := []byte{0x00, 0x03}
	c4 := f.ECBytes(d4, 2)
	if !bytes.Equal(cx, c4) {
		t.Errorf("ECBytes(%x, 2) = %x\nECBytes(%x, 2) = %x\nxor = %x\nECBytes(%x, 2) = %x",
			d2, c2, d3, c3, cx, d4, c4)
	}
}

func TestGaussJordan(t *testing.T) {

	m := make([][]byte, 16)
	for i := range m {
		m[i] = make([]byte, 4)
		m[i][i/8] = 1<<uint(i%8)
		copy(m[i][2:], f.ECBytes(m[i][:2], 2))
	}
	fmt.Printf("---\n")
	for _, row := range m {
		fmt.Printf("%x\n", row)
	}
	b := []uint{0,1,2,3,12,13,14,15,20,21,22,23,24,25,26,27}
	for i := 0; i < 16; i++ {
		bi := b[i]
		if m[i][bi/8] & (1<<(7-bi%8)) == 0 {
			for j := i+1;; j++ {
				if j >= len(m) {
					t.Errorf("lost track for %d", bi)
					break
				}
				if m[j][bi/8] & (1<<(7-bi%8)) != 0 {
					m[i], m[j] = m[j], m[i]
					break
				}
			}
		}
		for j := i+1; j < len(m); j++ {
			if m[j][bi/8] & (1<<(7-bi%8)) != 0 {
				for k := range m[j] {
					m[j][k] ^= m[i][k]
				}
			}
		}
	}
	fmt.Printf("---\n")
	for _, row := range m {
		fmt.Printf("%x\n", row)
	}
	for i := 15; i >= 0; i-- {
		bi := b[i]
		for j := i-1; j >= 0; j-- {
			if m[j][bi/8] & (1<<(7-bi%8)) != 0 {
				for k := range m[j] {
					m[j][k] ^= m[i][k]
				}
			}
		}
	}
	fmt.Printf("---\n")
	for _, row := range m {
		fmt.Printf("%x", row)
		if out := f.ECBytes(row[:2], 2); !bytes.Equal(out, row[2:]) {
			fmt.Printf(" - want %x", out)
		}
		fmt.Printf("\n")
	}
}
<|endoftext|>


<commit_before>package main

import (
	"archive/zip"
	"encoding/json"
	"fmt"
	"io/ioutil"
	"net/http"
	"path/filepath"
	"time"

	"github.com/beevik/etree"
	"github.com/gorilla/mux"
	"github.com/rs/cors"
	"github.com/urfave/negroni"
	graceful "gopkg.in/tylerb/graceful.v1"
)

// Metadata metadata struct
type Metadata struct {
	Title      string    `json:"title"`
	Author     string    `json:"author"`
	Identifier string    `json:"identifier"`
	Language   string    `json:"language"`
	Modified   time.Time `json:"modified"`
}

// Link link struct
type Link struct {
	Rel      string `json:"rel,omitempty"`
	Href     string `json:"href"`
	TypeLink string `json:"type"`
	Height   int    `json:"height,omitempty"`
	Width    int    `json:"width,omitempty"`
}

// Manifest manifest struct
type Manifest struct {
	Metadata  Metadata `json:"metadata"`
	Links     []Link   `json:"links"`
	Spine     []Link   `json:"spine,omitempty"`
	Resources []Link   `json:"resources"`
}

func main() {

	n := negroni.Classic()
	c := cors.New(cors.Options{
		AllowedOrigins: []string{"*"},
	})
	n.Use(c)
	n.UseHandler(loanHandler(false))

	graceful.Run(":8096", time.Duration(10)*time.Second, n)

}

func loanHandler(test bool) http.Handler {
	serv := mux.NewRouter()

	serv.HandleFunc("/manifest/{filename}/manifest.json", getManifest)
	serv.HandleFunc("/assets/{filename}/{asset:.*}", getAsset)

	return serv

}

func getManifest(w http.ResponseWriter, req *http.Request) {
	var opfFileName string
	var manifestStruct Manifest
	var metaStruct Metadata

	metaStruct.Modified = time.Now()

	vars := mux.Vars(req)
	filename := vars["filename"]

	self := Link{
		Rel:      "self",
		Href:     "http://" + req.Host + "/manifest/" + filename + "/manifest.json",
		TypeLink: "application/epub+zip",
	}
	manifestStruct.Links = make([]Link, 1)
	manifestStruct.Resources = make([]Link, 0)
	manifestStruct.Resources = make([]Link, 0)
	manifestStruct.Links[0] = self

	zipReader, err := zip.OpenReader(filename)
	if err != nil {
		fmt.Println(err)
	}

	for _, f := range zipReader.File {
		if f.Name == "META-INF/container.xml" {
			rc, errOpen := f.Open()
			if errOpen != nil {
				fmt.Println("error openging " + f.Name)
			}
			doc := etree.NewDocument()
			_, err = doc.ReadFrom(rc)
			if err == nil {
				root := doc.SelectElement("container")
				rootFiles := root.SelectElements("rootfiles")
				for _, rootFileTag := range rootFiles {
					rootFile := rootFileTag.SelectElement("rootfile")
					if rootFile != nil {
						opfFileName = rootFile.SelectAttrValue("full-path", "")
					}
				}
			} else {
				fmt.Println(err)
			}
			rc.Close()
		}
	}

	if opfFileName != "" {
		for _, f := range zipReader.File {
			if f.Name == opfFileName {
				rc, errOpen := f.Open()
				if errOpen != nil {
					fmt.Println("error openging " + f.Name)
				}
				doc := etree.NewDocument()
				_, err = doc.ReadFrom(rc)
				if err == nil {
					root := doc.SelectElement("package")
					meta := root.SelectElement("metadata")

					titleTag := meta.SelectElement("title")
					metaStruct.Title = titleTag.Text()

					langTag := meta.SelectElement("language")
					metaStruct.Language = langTag.Text()

					identifierTag := meta.SelectElement("identifier")
					metaStruct.Identifier = identifierTag.Text()

					creatorTag := meta.SelectElement("creator")
					metaStruct.Author = creatorTag.Text()

					bookManifest := root.SelectElement("manifest")
					itemsManifest := bookManifest.SelectElements("item")
					for _, item := range itemsManifest {
						linkItem := Link{}
						linkItem.TypeLink = item.SelectAttrValue("media-type", "")
						linkItem.Href = "https://proto.myopds.com/assets/" + filename + "/" + item.SelectAttrValue("href", "")
						if linkItem.TypeLink == "application/xhtml+xml" {
							manifestStruct.Spine = append(manifestStruct.Spine, linkItem)
						} else {
							manifestStruct.Resources = append(manifestStruct.Resources, linkItem)
						}
					}

					manifestStruct.Metadata = metaStruct
					j, _ := json.Marshal(manifestStruct)
					fmt.Println(string(j))
					w.Write(j)
					return
				}
			}
		}
	}

}

func getAsset(w http.ResponseWriter, req *http.Request) {
	vars := mux.Vars(req)
	filename := vars["filename"]
	assetname := vars["asset"]

	zipReader, err := zip.OpenReader(filename)
	if err != nil {
		fmt.Println(err)
	}

	for _, f := range zipReader.File {
		fmt.Println(f.Name)
		if f.Name == "OPS/"+assetname {
			rc, errOpen := f.Open()
			if errOpen != nil {
				fmt.Println("error openging " + f.Name)
			}
			buff, _ := ioutil.ReadAll(rc)
			defer rc.Close()
			extension := filepath.Ext(f.Name)
			if extension == ".css" {
				w.Header().Set("Content-Type", "text/css")
			}
			if extension == ".xml" {
				w.Header().Set("Content-Type", "application/xhtml+xml")
			}
			if extension == ".js" {
				w.Header().Set("Content-Type", "text/javascript")
			}
			w.Write(buff)
			return
		}
	}

}
<commit_msg>use dynamic path for resources<commit_after>package main

import (
	"archive/zip"
	"encoding/json"
	"fmt"
	"io/ioutil"
	"net/http"
	"path/filepath"
	"strings"
	"time"

	"github.com/beevik/etree"
	"github.com/gorilla/mux"
	"github.com/rs/cors"
	"github.com/urfave/negroni"
	graceful "gopkg.in/tylerb/graceful.v1"
)

// Metadata metadata struct
type Metadata struct {
	Title      string    `json:"title"`
	Author     string    `json:"author"`
	Identifier string    `json:"identifier"`
	Language   string    `json:"language"`
	Modified   time.Time `json:"modified"`
}

// Link link struct
type Link struct {
	Rel      string `json:"rel,omitempty"`
	Href     string `json:"href"`
	TypeLink string `json:"type"`
	Height   int    `json:"height,omitempty"`
	Width    int    `json:"width,omitempty"`
}

// Manifest manifest struct
type Manifest struct {
	Metadata  Metadata `json:"metadata"`
	Links     []Link   `json:"links"`
	Spine     []Link   `json:"spine,omitempty"`
	Resources []Link   `json:"resources"`
}

func main() {

	n := negroni.Classic()
	c := cors.New(cors.Options{
		AllowedOrigins: []string{"*"},
	})
	n.Use(c)
	n.UseHandler(loanHandler(false))

	graceful.Run(":8096", time.Duration(10)*time.Second, n)

}

func loanHandler(test bool) http.Handler {
	serv := mux.NewRouter()

	serv.HandleFunc("/manifest/{filename}/manifest.json", getManifest)
	serv.HandleFunc("/assets/{filename}/{asset:.*}", getAsset)

	return serv

}

func getManifest(w http.ResponseWriter, req *http.Request) {
	var opfFileName string
	var manifestStruct Manifest
	var metaStruct Metadata

	metaStruct.Modified = time.Now()

	vars := mux.Vars(req)
	filename := vars["filename"]

	self := Link{
		Rel:      "self",
		Href:     "http://" + req.Host + "/manifest/" + filename + "/manifest.json",
		TypeLink: "application/epub+zip",
	}
	manifestStruct.Links = make([]Link, 1)
	manifestStruct.Resources = make([]Link, 0)
	manifestStruct.Resources = make([]Link, 0)
	manifestStruct.Links[0] = self

	zipReader, err := zip.OpenReader(filename)
	if err != nil {
		fmt.Println(err)
		return
	}

	for _, f := range zipReader.File {
		if f.Name == "META-INF/container.xml" {
			rc, errOpen := f.Open()
			if errOpen != nil {
				fmt.Println("error openging " + f.Name)
			}
			doc := etree.NewDocument()
			_, err = doc.ReadFrom(rc)
			if err == nil {
				root := doc.SelectElement("container")
				rootFiles := root.SelectElements("rootfiles")
				for _, rootFileTag := range rootFiles {
					rootFile := rootFileTag.SelectElement("rootfile")
					if rootFile != nil {
						opfFileName = rootFile.SelectAttrValue("full-path", "")
					}
				}
			} else {
				fmt.Println(err)
			}
			rc.Close()
		}
	}

	if opfFileName != "" {
		for _, f := range zipReader.File {
			if f.Name == opfFileName {
				rc, errOpen := f.Open()
				if errOpen != nil {
					fmt.Println("error openging " + f.Name)
				}
				doc := etree.NewDocument()
				_, err = doc.ReadFrom(rc)
				if err == nil {
					root := doc.SelectElement("package")
					meta := root.SelectElement("metadata")

					titleTag := meta.SelectElement("title")
					metaStruct.Title = titleTag.Text()

					langTag := meta.SelectElement("language")
					metaStruct.Language = langTag.Text()

					identifierTag := meta.SelectElement("identifier")
					metaStruct.Identifier = identifierTag.Text()

					creatorTag := meta.SelectElement("creator")
					metaStruct.Author = creatorTag.Text()

					bookManifest := root.SelectElement("manifest")
					itemsManifest := bookManifest.SelectElements("item")
					for _, item := range itemsManifest {
						linkItem := Link{}
						linkItem.TypeLink = item.SelectAttrValue("media-type", "")
						linkItem.Href = "https://proto.myopds.com/assets/" + filename + "/" + item.SelectAttrValue("href", "")
						if linkItem.TypeLink == "application/xhtml+xml" {
							manifestStruct.Spine = append(manifestStruct.Spine, linkItem)
						} else {
							manifestStruct.Resources = append(manifestStruct.Resources, linkItem)
						}
					}

					manifestStruct.Metadata = metaStruct
					j, _ := json.Marshal(manifestStruct)
					fmt.Println(string(j))
					w.Write(j)
					return
				}
			}
		}
	}

}

func getAsset(w http.ResponseWriter, req *http.Request) {
	var opfFileName string

	vars := mux.Vars(req)
	filename := vars["filename"]
	assetname := vars["asset"]

	zipReader, err := zip.OpenReader(filename)
	if err != nil {
		fmt.Println(err)
	}

	for _, f := range zipReader.File {
		if f.Name == "META-INF/container.xml" {
			rc, errOpen := f.Open()
			if errOpen != nil {
				fmt.Println("error openging " + f.Name)
			}
			doc := etree.NewDocument()
			_, err = doc.ReadFrom(rc)
			if err == nil {
				root := doc.SelectElement("container")
				rootFiles := root.SelectElements("rootfiles")
				for _, rootFileTag := range rootFiles {
					rootFile := rootFileTag.SelectElement("rootfile")
					if rootFile != nil {
						opfFileName = rootFile.SelectAttrValue("full-path", "")
					}
				}
			} else {
				fmt.Println(err)
			}
			rc.Close()
		}
	}

	resourcePath := strings.Split(opfFileName, "/")[0]

	for _, f := range zipReader.File {
		fmt.Println(f.Name)
		if f.Name == resourcePath+"/"+assetname {
			rc, errOpen := f.Open()
			if errOpen != nil {
				fmt.Println("error openging " + f.Name)
			}
			buff, _ := ioutil.ReadAll(rc)
			defer rc.Close()
			extension := filepath.Ext(f.Name)
			if extension == ".css" {
				w.Header().Set("Content-Type", "text/css")
			}
			if extension == ".xml" {
				w.Header().Set("Content-Type", "application/xhtml+xml")
			}
			if extension == ".js" {
				w.Header().Set("Content-Type", "text/javascript")
			}
			w.Write(buff)
			return
		}
	}

}
<|endoftext|>


<commit_before>package pqueue

import "github.com/satori/go.uuid"

type Replica struct {
	ServerId  string
	ReplicaTs uint64
}

type PQMessage struct {
	Id           string
	Payload      string
	Priority     int64
	CreatedTs    int64
	PopCount     int64
	ReplicatedTo []Replica
}

func NewPQMessageWithId(id string, payload string, priority int64) *PQMessage {

	pqm := PQMessage{
		Id:           id,
		Payload:      payload,
		Priority:     priority,
		CreatedTs:    Uts(),
		PopCount:     0,
		ReplicatedTo: []Replica{},
	}
	return &pqm
}

func NewPQMessage(payload string, priority int64) *PQMessage {
	id := uuid.NewV4().String()
	return NewPQMessageWithId(id, payload, priority)
}

func (pqm *PQMessage) AddReplica(serverId string, replicaTs uint64) {
	r := Replica{ServerId: serverId, ReplicaTs: replicaTs}
	pqm.ReplicatedTo = append(pqm.ReplicatedTo, r)
}

func (pqm *PQMessage) GetId() string {
	return pqm.Id
}

func (pqm *PQMessage) GetPayload() string {
	return pqm.Payload
}

func (pqm *PQMessage) GetStatus() map[string]interface{} {
	res := make(map[string]interface{})
	res["CreatedTs"] = pqm.CreatedTs
	res["Priority"] = pqm.Priority
	res["PopCount"] = pqm.PopCount
	return res
}

func (pqm *PQMessage) GetSize() int {
	return len(pqm.Payload)
}
<commit_msg>Removed UUID generator for message ids. Added message map processing to create a new message.<commit_after>package pqueue

import (
	"firempq/defs"
	"firempq/qerrors"
	"firempq/util"
	"strconv"
)

const (
	MAX_MESSAGE_ID_LENGTH = 64
)

type Replica struct {
	ServerId  string
	ReplicaTs uint64
}

type PQMessage struct {
	Id           string
	Payload      string
	Priority     int64
	CreatedTs    int64
	PopCount     int64
	ReplicatedTo []Replica
}

func NewPQMessageWithId(id string, payload string, priority int64) *PQMessage {

	pqm := PQMessage{
		Id:           id,
		Payload:      payload,
		Priority:     priority,
		CreatedTs:    Uts(),
		PopCount:     0,
		ReplicatedTo: []Replica{},
	}
	return &pqm
}

func MessageFromMap(params map[string]string) (*PQMessage, error) {
	// Get and check message id.
	var msgId string
	var ok bool
	var strValue string
	var priority int64
	var err error
	var payload string

	msgId, ok = params[defs.PARAM_MSG_ID]
	if !ok {
		msgId = util.GenRandMsgId()
	} else if len(msgId) > MAX_MESSAGE_ID_LENGTH {
		return nil, qerrors.ERR_MSG_ID_TOO_LARGE
	}

	strValue, ok = params[defs.PARAM_MSG_PRIORITY]
	if !ok {
		return nil, qerrors.ERR_MSG_NO_PRIORITY
	}
	priority, err = strconv.ParseInt(strValue, 10, 0)
	if err != nil {
		return nil, qerrors.ERR_MSG_WRONG_PRIORITY
	}

	payload, ok = params[defs.PARAM_MSG_PAYLOAD]
	if !ok {
		payload = ""
	}

	return NewPQMessageWithId(msgId, payload, priority), nil
}

func NewPQMessage(payload string, priority int64) *PQMessage {
	id := util.GenRandMsgId()
	return NewPQMessageWithId(id, payload, priority)
}

func (pqm *PQMessage) AddReplica(serverId string, replicaTs uint64) {
	r := Replica{ServerId: serverId, ReplicaTs: replicaTs}
	pqm.ReplicatedTo = append(pqm.ReplicatedTo, r)
}

func (pqm *PQMessage) GetId() string {
	return pqm.Id
}

func (pqm *PQMessage) GetPayload() string {
	return pqm.Payload
}

func (pqm *PQMessage) GetStatus() map[string]interface{} {
	res := make(map[string]interface{})
	res["CreatedTs"] = pqm.CreatedTs
	res["Priority"] = pqm.Priority
	res["PopCount"] = pqm.PopCount
	return res
}

func (pqm *PQMessage) GetSize() int {
	return len(pqm.Payload)
}
<|endoftext|>


<commit_before>package main

import (
	"crypto/sha1"
	"database/sql"
	"encoding/base64"
	"encoding/json"
	"encoding/xml"
	"fmt"
	"html"
	"html/template"
	"io"
	"io/ioutil"
	"log"
	"net/http"

	"github.com/dchest/uniuri"
	"github.com/ewhal/pygments"
	_ "github.com/go-sql-driver/mysql"
	"github.com/gorilla/mux"
)

const (
	ADDRESS  = "http://localhost:9900"
	LENGTH   = 6
	PORT     = ":9900"
	USERNAME = ""
	PASS     = ""
	NAME     = ""
	DATABASE = USERNAME + ":" + PASS + "@/" + NAME + "?charset=utf8"
)

type Response struct {
	ID     string `json:"id"`
	HASH   string `json:"hash"`
	URL    string `json:"url"`
	SIZE   int    `json:"size"`
	DELKEY string `json:"delkey"`
}

type Page struct {
	Title string
	Body  []byte
	Raw   string
	Home  string
}

func check(err error) {
	if err != nil {
		fmt.Println(err)
	}
}

func generateName() string {
	s := uniuri.NewLen(LENGTH)
	db, err := sql.Open("mysql", DATABASE)
	check(err)

	query, err := db.Query("select id from pastebin")
	for query.Next() {
		var id string
		err := query.Scan(&id)
		if err != nil {

		}
		if id == s {
			generateName()
		}
	}
	db.Close()

	return s

}
func hash(paste string) string {
	hasher := sha1.New()

	hasher.Write([]byte(paste))
	sha := base64.URLEncoding.EncodeToString(hasher.Sum(nil))
	return sha
}

func save(raw string, lang string) []string {
	db, err := sql.Open("mysql", DATABASE)
	check(err)

	sha := hash(raw)
	query, err := db.Query("select id, hash, data, delkey from pastebin")
	for query.Next() {
		var id, hash, paste, delkey string
		err := query.Scan(&id, &hash, &paste, &delkey)
		check(err)
		if hash == sha {
			url := ADDRESS + "/p/" + id
			return []string{id, hash, url, paste, delkey}
		}
	}
	id := generateName()
	var url string
	if lang == "" {
		url = ADDRESS + "/p/" + id
	} else {
		url = ADDRESS + "/p/" + id + "/" + lang
	}
	delKey := uniuri.NewLen(40)
	paste := html.EscapeString(raw)

	stmt, err := db.Prepare("INSERT INTO pastebin(id, hash, data, delkey) values(?,?,?,?)")
	check(err)
	_, err = stmt.Exec(id, sha, paste, delKey)
	check(err)
	db.Close()
	return []string{id, sha, url, paste, delKey}
}

func delHandler(w http.ResponseWriter, r *http.Request) {
	vars := mux.Vars(r)
	paste := vars["pasteId"]
	delkey := vars["delKey"]

	db, err := sql.Open("mysql", DATABASE)
	check(err)

	stmt, err := db.Prepare("delete from pastebin where delkey=?")
	check(err)

	res, err := stmt.Exec(html.EscapeString(delkey))
	check(err)

	_, err = res.RowsAffected()
	if err == sql.ErrNoRows {
		io.WriteString(w, "Error invalid paste")
	} else {
		io.WriteString(w, paste+" deleted")
	}
	db.Close()

}
func saveHandler(w http.ResponseWriter, r *http.Request) {
	vars := mux.Vars(r)
	output := vars["output"]
	switch r.Method {
	case "POST":
		paste := r.FormValue("p")
		lang := r.FormValue("lang")
		if paste == "" {
			http.Error(w, "Empty paste", 500)
			return
		}
		values := save(paste, lang)
		b := &Response{
			ID:     values[0],
			HASH:   values[1],
			URL:    values[2],
			SIZE:   len(values[3]),
			DELKEY: values[4],
		}

		switch output {
		case "json":

			w.Header().Set("Content-Type", "application/json")
			err := json.NewEncoder(w).Encode(b)

			if err != nil {
				http.Error(w, err.Error(), http.StatusInternalServerError)
				return
			}
		case "xml":
			x, err := xml.MarshalIndent(b, "", "  ")
			if err != nil {
				http.Error(w, err.Error(), http.StatusInternalServerError)
				return
			}

			w.Header().Set("Content-Type", "application/xml")
			w.Write(x)

		case "html":
			w.Header().Set("Content-Type", "text/html")
			io.WriteString(w, "
URL: "+b.URL+"
")
			io.WriteString(w, "
Delete Key: "+b.DELKEY+"
")

		case "redirect":
			http.Redirect(w, r, b.URL, 301)

		default:
			w.Header().Set("Content-Type", "plain/text")
			io.WriteString(w, b.URL+"\n")
			io.WriteString(w, "delete key: "+b.DELKEY+"\n")
		}
	}

}

func highlight(s string, lang string) (string, error) {

	highlight, err := pygments.Highlight(html.UnescapeString(s), html.EscapeString(lang), "html", "style=autumn,linenos=True, lineanchors=True,anchorlinenos=True,noclasses=True,", "utf-8")
	if err != nil {
		return "", err
	}
	return highlight, nil

}

func getPaste(paste string, lang string) string {
	param1 := html.EscapeString(paste)
	db, err := sql.Open("mysql", DATABASE)
	var s string
	err = db.QueryRow("select data from pastebin where id=?", param1).Scan(&s)
	db.Close()
	check(err)

	if err == sql.ErrNoRows {
		return "Error invalid paste"
	} else {
		if lang == "" {
			return html.UnescapeString(s)
		} else {
			high, err := highlight(s, lang)
			check(err)
			return high

		}
	}

}

func pasteHandler(w http.ResponseWriter, r *http.Request) {
	vars := mux.Vars(r)
	paste := vars["pasteId"]
	lang := vars["lang"]
	s := getPaste(paste, lang)
	link := ADDRESS + "/raw/" + paste
	if lang == "" {
		p := &Page{
			Title: paste,
			Body:  []byte(s),
			Raw:   link,
			Home:  ADDRESS,
		}
		t, err := template.ParseFiles("assets/paste.html")
		if err != nil {
			http.Error(w, err.Error(), http.StatusInternalServerError)
		}
		t.Execute(w, p)

	} else {
		dat, err := ioutil.ReadFile("assets/syntax.html")
		check(err)
		w.Write(string(dat), paste, paste, s, ADDRESS, link)

	}
}

func rawHandler(w http.ResponseWriter, r *http.Request) {
	vars := mux.Vars(r)
	paste := vars["pasteId"]
	s := getPaste(paste, "")
	io.WriteString(w, s)

}

func main() {
	router := mux.NewRouter()
	router.HandleFunc("/p/{pasteId}", pasteHandler)
	router.HandleFunc("/raw/{pasteId}", rawHandler)
	router.HandleFunc("/p/{pasteId}/{lang}", pasteHandler)
	router.HandleFunc("/{clone}/{pasteId}", cloneHandler)
	router.HandleFunc("/{download}/{pasteId}", downloadHandler)
	router.HandleFunc("/save", saveHandler)
	router.HandleFunc("/save/{output}", saveHandler)
	router.HandleFunc("/del/{pasteId}/{delKey}", delHandler)
	router.PathPrefix("/").Handler(http.StripPrefix("/", http.FileServer(http.Dir("assets/"))))
	err := http.ListenAndServe(PORT, router)
	if err != nil {
		log.Fatal(err)
	}

}
<commit_msg>Add missing handler functions<commit_after>package main

import (
	"crypto/sha1"
	"database/sql"
	"encoding/base64"
	"encoding/json"
	"encoding/xml"
	"fmt"
	"html"
	"html/template"
	"io"
	"io/ioutil"
	"log"
	"net/http"

	"github.com/dchest/uniuri"
	"github.com/ewhal/pygments"
	_ "github.com/go-sql-driver/mysql"
	"github.com/gorilla/mux"
)

const (
	ADDRESS  = "http://localhost:9900"
	LENGTH   = 6
	PORT     = ":9900"
	USERNAME = ""
	PASS     = ""
	NAME     = ""
	DATABASE = USERNAME + ":" + PASS + "@/" + NAME + "?charset=utf8"
)

type Response struct {
	ID     string `json:"id"`
	HASH   string `json:"hash"`
	URL    string `json:"url"`
	SIZE   int    `json:"size"`
	DELKEY string `json:"delkey"`
}

type Page struct {
	Title string
	Body  []byte
	Raw   string
	Home  string
}

func check(err error) {
	if err != nil {
		fmt.Println(err)
	}
}

func generateName() string {
	s := uniuri.NewLen(LENGTH)
	db, err := sql.Open("mysql", DATABASE)
	check(err)

	query, err := db.Query("select id from pastebin")
	for query.Next() {
		var id string
		err := query.Scan(&id)
		if err != nil {

		}
		if id == s {
			generateName()
		}
	}
	db.Close()

	return s

}
func hash(paste string) string {
	hasher := sha1.New()

	hasher.Write([]byte(paste))
	sha := base64.URLEncoding.EncodeToString(hasher.Sum(nil))
	return sha
}

func save(raw string, lang string) []string {
	db, err := sql.Open("mysql", DATABASE)
	check(err)

	sha := hash(raw)
	query, err := db.Query("select id, hash, data, delkey from pastebin")
	for query.Next() {
		var id, hash, paste, delkey string
		err := query.Scan(&id, &hash, &paste, &delkey)
		check(err)
		if hash == sha {
			url := ADDRESS + "/p/" + id
			return []string{id, hash, url, paste, delkey}
		}
	}
	id := generateName()
	var url string
	if lang == "" {
		url = ADDRESS + "/p/" + id
	} else {
		url = ADDRESS + "/p/" + id + "/" + lang
	}
	delKey := uniuri.NewLen(40)
	paste := html.EscapeString(raw)

	stmt, err := db.Prepare("INSERT INTO pastebin(id, hash, data, delkey) values(?,?,?,?)")
	check(err)
	_, err = stmt.Exec(id, sha, paste, delKey)
	check(err)
	db.Close()
	return []string{id, sha, url, paste, delKey}
}

func delHandler(w http.ResponseWriter, r *http.Request) {
	vars := mux.Vars(r)
	paste := vars["pasteId"]
	delkey := vars["delKey"]

	db, err := sql.Open("mysql", DATABASE)
	check(err)

	stmt, err := db.Prepare("delete from pastebin where delkey=?")
	check(err)

	res, err := stmt.Exec(html.EscapeString(delkey))
	check(err)

	_, err = res.RowsAffected()
	if err == sql.ErrNoRows {
		io.WriteString(w, "Error invalid paste")
	} else {
		io.WriteString(w, paste+" deleted")
	}
	db.Close()

}
func saveHandler(w http.ResponseWriter, r *http.Request) {
	vars := mux.Vars(r)
	output := vars["output"]
	switch r.Method {
	case "POST":
		paste := r.FormValue("p")
		lang := r.FormValue("lang")
		if paste == "" {
			http.Error(w, "Empty paste", 500)
			return
		}
		values := save(paste, lang)
		b := &Response{
			ID:     values[0],
			HASH:   values[1],
			URL:    values[2],
			SIZE:   len(values[3]),
			DELKEY: values[4],
		}

		switch output {
		case "json":

			w.Header().Set("Content-Type", "application/json")
			err := json.NewEncoder(w).Encode(b)

			if err != nil {
				http.Error(w, err.Error(), http.StatusInternalServerError)
				return
			}
		case "xml":
			x, err := xml.MarshalIndent(b, "", "  ")
			if err != nil {
				http.Error(w, err.Error(), http.StatusInternalServerError)
				return
			}

			w.Header().Set("Content-Type", "application/xml")
			w.Write(x)

		case "html":
			w.Header().Set("Content-Type", "text/html")
			io.WriteString(w, "
URL: "+b.URL+"
")
			io.WriteString(w, "
Delete Key: "+b.DELKEY+"
")

		case "redirect":
			http.Redirect(w, r, b.URL, 301)

		default:
			w.Header().Set("Content-Type", "plain/text")
			io.WriteString(w, b.URL+"\n")
			io.WriteString(w, "delete key: "+b.DELKEY+"\n")
		}
	}

}

func highlight(s string, lang string) (string, error) {

	highlight, err := pygments.Highlight(html.UnescapeString(s), html.EscapeString(lang), "html", "style=autumn,linenos=True, lineanchors=True,anchorlinenos=True,noclasses=True,", "utf-8")
	if err != nil {
		return "", err
	}
	return highlight, nil

}

func getPaste(paste string, lang string) string {
	param1 := html.EscapeString(paste)
	db, err := sql.Open("mysql", DATABASE)
	var s string
	err = db.QueryRow("select data from pastebin where id=?", param1).Scan(&s)
	db.Close()
	check(err)

	if err == sql.ErrNoRows {
		return "Error invalid paste"
	} else {
		if lang == "" {
			return html.UnescapeString(s)
		} else {
			high, err := highlight(s, lang)
			check(err)
			return high

		}
	}

}

func pasteHandler(w http.ResponseWriter, r *http.Request) {
	vars := mux.Vars(r)
	paste := vars["pasteId"]
	lang := vars["lang"]
	s := getPaste(paste, lang)
	link := ADDRESS + "/raw/" + paste
	if lang == "" {
		p := &Page{
			Title: paste,
			Body:  []byte(s),
			Raw:   link,
			Home:  ADDRESS,
		}
		t, err := template.ParseFiles("assets/paste.html")
		if err != nil {
			http.Error(w, err.Error(), http.StatusInternalServerError)
		}
		t.Execute(w, p)

	} else {
		dat, err := ioutil.ReadFile("assets/syntax.html")
		check(err)
		w.Write(string(dat), paste, paste, s, ADDRESS, link)

	}
}

func cloneHandler(w http.ResponseWriter, r *http.Request) {
}
func downloadHandler(w http.ResponseWriter, r *http.Request) {
}
func rawHandler(w http.ResponseWriter, r *http.Request) {
	vars := mux.Vars(r)
	paste := vars["pasteId"]
	s := getPaste(paste, "")
	io.WriteString(w, s)

}

func main() {
	router := mux.NewRouter()
	router.HandleFunc("/p/{pasteId}", pasteHandler)
	router.HandleFunc("/raw/{pasteId}", rawHandler)
	router.HandleFunc("/p/{pasteId}/{lang}", pasteHandler)
	router.HandleFunc("/{clone}/{pasteId}", cloneHandler)
	router.HandleFunc("/{download}/{pasteId}", downloadHandler)
	router.HandleFunc("/save", saveHandler)
	router.HandleFunc("/save/{output}", saveHandler)
	router.HandleFunc("/del/{pasteId}/{delKey}", delHandler)
	router.PathPrefix("/").Handler(http.StripPrefix("/", http.FileServer(http.Dir("assets/"))))
	err := http.ListenAndServe(PORT, router)
	if err != nil {
		log.Fatal(err)
	}

}
<|endoftext|>


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

package main

import (
	"flag"
	"fmt"
	"os"
	"os/signal"
	"runtime"
	"runtime/pprof"
	"syscall"
	"time"

	"github.com/tsuru/bs/bslog"
	"github.com/tsuru/bs/config"
	"github.com/tsuru/bs/log"
	"github.com/tsuru/bs/metric"
	_ "github.com/tsuru/bs/metric/logstash"
	"github.com/tsuru/bs/status"
)

const (
	version = "v1.9"
)

var printVersion bool

type StopWaiter interface {
	Stop()
	Wait()
}

func init() {
	flag.BoolVar(&printVersion, "version", false, "Print version and exit")
}

func startSignalHandler(callback func(os.Signal), signals ...os.Signal) {
	sigChan := make(chan os.Signal, 4)
	go func() {
		if signal, ok := <-sigChan; ok {
			callback(signal)
		}
	}()
	signal.Notify(sigChan, signals...)
}

func onSignalDebugGoroutines(signal os.Signal) {
	var buf []byte
	var written int
	currLen := 1024
	for written == len(buf) {
		buf = make([]byte, currLen)
		written = runtime.Stack(buf, true)
		currLen *= 2
	}
	fmt.Print(string(buf[:written]))
	startSignalHandler(onSignalDebugGoroutines, syscall.SIGUSR1)
}

func onSignalDebugProfile(signal os.Signal) {
	cpufile, err := os.OpenFile("./cpuprofile.out", os.O_WRONLY|os.O_CREATE|os.O_TRUNC, 0660)
	if err != nil {
		bslog.Warnf("Error trying to open profile file: %s", err)
		return
	}
	memfile, err := os.OpenFile("./memprofile.out", os.O_WRONLY|os.O_CREATE|os.O_TRUNC, 0660)
	if err != nil {
		bslog.Warnf("Error trying to open profile file: %s", err)
		return
	}
	lockfile, err := os.OpenFile("./lockprofile.out", os.O_WRONLY|os.O_CREATE|os.O_TRUNC, 0660)
	if err != nil {
		bslog.Warnf("Error trying to open profile file: %s", err)
		return
	}
	bslog.Warnf("Starting profile...")
	defer bslog.Warnf("Profile done, files written: %s, %s, %s", cpufile.Name(), memfile.Name(), lockfile.Name())
	runtime.GC()
	pprof.WriteHeapProfile(memfile)
	memfile.Close()
	runtime.SetBlockProfileRate(1)
	time.Sleep(30 * time.Second)
	pprof.Lookup("block").WriteTo(lockfile, 0)
	runtime.SetBlockProfileRate(0)
	lockfile.Close()
	pprof.StartCPUProfile(cpufile)
	time.Sleep(30 * time.Second)
	pprof.StopCPUProfile()
	cpufile.Close()
	startSignalHandler(onSignalDebugProfile, syscall.SIGUSR2)
}

func main() {
	startSignalHandler(onSignalDebugGoroutines, syscall.SIGUSR1)
	startSignalHandler(onSignalDebugProfile, syscall.SIGUSR2)
	flag.Parse()
	if printVersion {
		fmt.Printf("bs version %s\n", version)
		return
	}
	lf := log.LogForwarder{
		BindAddress:     config.Config.SyslogListenAddress,
		DockerEndpoint:  config.Config.DockerEndpoint,
		EnabledBackends: config.Config.LogBackends,
	}
	err := lf.Start()
	if err != nil {
		bslog.Fatalf("Unable to initialize log forwarder: %s\n", err)
	}
	mRunner := metric.NewRunner(config.Config.DockerEndpoint, config.Config.MetricsInterval,
		config.Config.MetricsBackend)
	err = mRunner.Start()
	if err != nil {
		bslog.Warnf("Unable to initialize metrics runner: %s\n", err)
	}
	reporter, err := status.NewReporter(&status.ReporterConfig{
		TsuruEndpoint:  config.Config.TsuruEndpoint,
		TsuruToken:     config.Config.TsuruToken,
		DockerEndpoint: config.Config.DockerEndpoint,
		Interval:       config.Config.StatusInterval,
	})
	if err != nil {
		bslog.Warnf("Unable to initialize status reporter: %s\n", err)
	}
	monitorEl := []StopWaiter{&lf, mRunner}
	if reporter != nil {
		monitorEl = append(monitorEl, reporter)
	}
	var signaled bool
	startSignalHandler(func(signal os.Signal) {
		signaled = true
		for _, m := range monitorEl {
			go m.Stop()
		}
	}, os.Interrupt, syscall.SIGTERM, syscall.SIGQUIT)
	for _, m := range monitorEl {
		m.Wait()
	}
	if !signaled {
		bslog.Fatalf("Exiting bs because no service could be initialized.")
	}
}
<commit_msg>main: reorde printVersion<commit_after>// Copyright 2016 bs authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.

package main

import (
	"flag"
	"fmt"
	"os"
	"os/signal"
	"runtime"
	"runtime/pprof"
	"syscall"
	"time"

	"github.com/tsuru/bs/bslog"
	"github.com/tsuru/bs/config"
	"github.com/tsuru/bs/log"
	"github.com/tsuru/bs/metric"
	_ "github.com/tsuru/bs/metric/logstash"
	"github.com/tsuru/bs/status"
)

const (
	version = "v1.9"
)

var printVersion bool

type StopWaiter interface {
	Stop()
	Wait()
}

func init() {
	flag.BoolVar(&printVersion, "version", false, "Print version and exit")
}

func startSignalHandler(callback func(os.Signal), signals ...os.Signal) {
	sigChan := make(chan os.Signal, 4)
	go func() {
		if signal, ok := <-sigChan; ok {
			callback(signal)
		}
	}()
	signal.Notify(sigChan, signals...)
}

func onSignalDebugGoroutines(signal os.Signal) {
	var buf []byte
	var written int
	currLen := 1024
	for written == len(buf) {
		buf = make([]byte, currLen)
		written = runtime.Stack(buf, true)
		currLen *= 2
	}
	fmt.Print(string(buf[:written]))
	startSignalHandler(onSignalDebugGoroutines, syscall.SIGUSR1)
}

func onSignalDebugProfile(signal os.Signal) {
	cpufile, err := os.OpenFile("./cpuprofile.out", os.O_WRONLY|os.O_CREATE|os.O_TRUNC, 0660)
	if err != nil {
		bslog.Warnf("Error trying to open profile file: %s", err)
		return
	}
	memfile, err := os.OpenFile("./memprofile.out", os.O_WRONLY|os.O_CREATE|os.O_TRUNC, 0660)
	if err != nil {
		bslog.Warnf("Error trying to open profile file: %s", err)
		return
	}
	lockfile, err := os.OpenFile("./lockprofile.out", os.O_WRONLY|os.O_CREATE|os.O_TRUNC, 0660)
	if err != nil {
		bslog.Warnf("Error trying to open profile file: %s", err)
		return
	}
	bslog.Warnf("Starting profile...")
	defer bslog.Warnf("Profile done, files written: %s, %s, %s", cpufile.Name(), memfile.Name(), lockfile.Name())
	runtime.GC()
	pprof.WriteHeapProfile(memfile)
	memfile.Close()
	runtime.SetBlockProfileRate(1)
	time.Sleep(30 * time.Second)
	pprof.Lookup("block").WriteTo(lockfile, 0)
	runtime.SetBlockProfileRate(0)
	lockfile.Close()
	pprof.StartCPUProfile(cpufile)
	time.Sleep(30 * time.Second)
	pprof.StopCPUProfile()
	cpufile.Close()
	startSignalHandler(onSignalDebugProfile, syscall.SIGUSR2)
}

func main() {
	flag.Parse()
	if printVersion {
		fmt.Printf("bs version %s\n", version)
		return
	}
	startSignalHandler(onSignalDebugGoroutines, syscall.SIGUSR1)
	startSignalHandler(onSignalDebugProfile, syscall.SIGUSR2)
	lf := log.LogForwarder{
		BindAddress:     config.Config.SyslogListenAddress,
		DockerEndpoint:  config.Config.DockerEndpoint,
		EnabledBackends: config.Config.LogBackends,
	}
	err := lf.Start()
	if err != nil {
		bslog.Fatalf("Unable to initialize log forwarder: %s\n", err)
	}
	mRunner := metric.NewRunner(config.Config.DockerEndpoint, config.Config.MetricsInterval,
		config.Config.MetricsBackend)
	err = mRunner.Start()
	if err != nil {
		bslog.Warnf("Unable to initialize metrics runner: %s\n", err)
	}
	reporter, err := status.NewReporter(&status.ReporterConfig{
		TsuruEndpoint:  config.Config.TsuruEndpoint,
		TsuruToken:     config.Config.TsuruToken,
		DockerEndpoint: config.Config.DockerEndpoint,
		Interval:       config.Config.StatusInterval,
	})
	if err != nil {
		bslog.Warnf("Unable to initialize status reporter: %s\n", err)
	}
	monitorEl := []StopWaiter{&lf, mRunner}
	if reporter != nil {
		monitorEl = append(monitorEl, reporter)
	}
	var signaled bool
	startSignalHandler(func(signal os.Signal) {
		signaled = true
		for _, m := range monitorEl {
			go m.Stop()
		}
	}, os.Interrupt, syscall.SIGTERM, syscall.SIGQUIT)
	for _, m := range monitorEl {
		m.Wait()
	}
	if !signaled {
		bslog.Fatalf("Exiting bs because no service could be initialized.")
	}
}
<|endoftext|>