<commit_before>// Copyright 2015 Dorival de Moraes Pedroso. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.

package goga

import (
	"github.com/cpmech/gosl/io"
	"github.com/cpmech/gosl/plt"
	"github.com/cpmech/gosl/utl"
)

// ContourParams holds parameters to plot contours
type ContourParams struct {
	Npts    int       // number of points for contour
	CmapIdx int       // colormap index
	Csimple bool      // simple contour
	AxEqual bool      // axes-equal
	Lwg     float64   // linewidth for g functions
	Lwh     float64   // linewidth for h functions
	Args    string    // extra arguments for plot
	Extra   func()    // extra function
	Xrange  []float64 // to override x-range
	Yrange  []float64 // to override y-range
}

// PlotContour plots contour
func (o *Optimiser) PlotContour(iFlt, jFlt, iOva int, prms ContourParams) {

	// fix parameters
	if prms.Npts < 3 {
		prms.Npts = 41
	}
	if prms.Lwg < 0.1 {
		prms.Lwg = 1.5
	}
	if prms.Lwh < 0.1 {
		prms.Lwh = 1.5
	}

	// limits and meshgrid
	xmin, xmax := o.FltMin[iFlt], o.FltMax[iFlt]
	ymin, ymax := o.FltMin[jFlt], o.FltMax[jFlt]
	if prms.Xrange != nil {
		xmin, xmax = prms.Xrange[0], prms.Xrange[1]
	}
	if prms.Yrange != nil {
		ymin, ymax = prms.Yrange[0], prms.Yrange[1]
	}

	// auxiliary variables
	X, Y := utl.MeshGrid2D(xmin, xmax, ymin, ymax, prms.Npts, prms.Npts)
	Zf := utl.DblsAlloc(prms.Npts, prms.Npts)
	var Zg [][][]float64
	var Zh [][][]float64
	if o.Ng > 0 {
		Zg = utl.Deep3alloc(o.Ng, prms.Npts, prms.Npts)
	}
	if o.Nh > 0 {
		Zh = utl.Deep3alloc(o.Nh, prms.Npts, prms.Npts)
	}

	// compute values
	x := make([]float64, 2)
	grp := 0
	for i := 0; i < prms.Npts; i++ {
		for j := 0; j < prms.Npts; j++ {
			x[0], x[1] = X[i][j], Y[i][j]
			o.MinProb(o.F[grp], o.G[grp], o.H[grp], x, nil, grp)
			Zf[i][j] = o.F[grp][iOva]
			for k, g := range o.G[grp] {
				Zg[k][i][j] = g
			}
			for k, h := range o.H[grp] {
				Zh[k][i][j] = h
			}
		}
	}

	// plot f
	if prms.Csimple {
		plt.ContourSimple(X, Y, Zf, true, 7, "colors=['k'], fsz=7, "+prms.Args)
	} else {
		plt.Contour(X, Y, Zf, io.Sf("fsz=7, cmapidx=%d, "+prms.Args, prms.CmapIdx))
	}

	// plot g
	clr := "yellow"
	if prms.Csimple {
		clr = "blue"
	}
	for _, g := range Zg {
		plt.ContourSimple(X, Y, g, false, 7, io.Sf("zorder=5, levels=[0], colors=['%s'], linewidths=[%g], clip_on=0", clr, prms.Lwg))
	}

	// plot h
	clr = "yellow"
	if prms.Csimple {
		clr = "blue"
	}
	for _, h := range Zh {
		plt.ContourSimple(X, Y, h, false, 7, io.Sf("zorder=5, levels=[0], colors=['%s'], linewidths=[%g], clip_on=0", clr, prms.Lwh))
	}
}

// PlotAddFltFlt adds flt-flt points to existent plot
func (o *Optimiser) PlotAddFltFlt(iFlt, jFlt int, sols []*Solution, fmt plt.Fmt, emptyMarker bool) {
	nsol := len(sols)
	x, y := make([]float64, nsol), make([]float64, nsol)
	for i, sol := range sols {
		x[i], y[i] = sol.Flt[iFlt], sol.Flt[jFlt]
	}
	args := fmt.GetArgs("") + ",clip_on=0,zorder=10"
	if emptyMarker {
		args += io.Sf(",markeredgecolor='%s',markerfacecolor='none'", fmt.C)
	}
	plt.Plot(x, y, args)
}

// PlotAddFltOva adds flt-ova points to existent plot
func (o *Optimiser) PlotAddFltOva(iFlt, iOva int, sols []*Solution, ovaMult float64, fmt plt.Fmt, emptyMarker bool) {
	nsol := len(sols)
	x, y := make([]float64, nsol), make([]float64, nsol)
	for i, sol := range sols {
		x[i], y[i] = sol.Flt[iFlt], sol.Ova[iOva]*ovaMult
	}
	args := fmt.GetArgs("") + ",clip_on=0,zorder=10"
	if emptyMarker {
		args += io.Sf(",markeredgecolor='%s',markerfacecolor='none'", fmt.C)
	}
	plt.Plot(x, y, args)
}

// PlotAddOvaOva adds ova-ova points to existent plot
func (o *Optimiser) PlotAddOvaOva(iOva, jOva int, sols []*Solution, feasibleOnly bool, fmt plt.Fmt, emptyMarker bool) {
	var x, y []float64
	for _, sol := range sols {
		if sol.Feasible() || !feasibleOnly {
			x = append(x, sol.Ova[iOva])
			y = append(y, sol.Ova[jOva])
		}
	}
	args := fmt.GetArgs("") + ",clip_on=0,zorder=10"
	if emptyMarker {
		args += io.Sf(",markeredgecolor='%s',markerfacecolor='none'", fmt.C)
	}
	plt.Plot(x, y, args)
}

// PlotAddParetoFront highlights Pareto front
func (o *Optimiser) PlotAddParetoFront(iOva, jOva int, sols []*Solution, fmt *plt.Fmt, emptyMarker bool) {
	args := fmt.GetArgs("") + ",clip_on=0,zorder=10"
	if emptyMarker {
		args += io.Sf(",markeredgecolor='%s',markerfacecolor='none'", fmt.C)
	}
	x, y, _ := GetParetoFront(iOva, jOva, sols, false)
	plt.Plot(x, y, args)
}

// PlotFltOva plots flt-ova points
func PlotFltOva(fnkey string, opt *Optimiser, sols0 []*Solution, iFlt, iOva, np int, ovaMult float64, fcn func(x float64) float64, extra func(), equalAxes bool) {
	if fcn != nil {
		X := utl.LinSpace(opt.FltMin[0], opt.FltMax[0], np)
		Y := make([]float64, np)
		for i := 0; i < np; i++ {
			Y[i] = fcn(X[i])
		}
		plt.Plot(X, Y, "'b-'")
	}
	if sols0 != nil {
		opt.PlotAddFltOva(iFlt, iOva, sols0, ovaMult, plt.Fmt{L: "initial", M: "o", C: "k", Ls: "none", Ms: 3}, false)
	}
	SortByOva(opt.Solutions, iOva)
	best := opt.Solutions[0]
	opt.PlotAddFltOva(iFlt, iOva, opt.Solutions, ovaMult, plt.Fmt{L: "final", M: "o", C: "r", Ls: "none", Ms: 6}, true)
	plt.PlotOne(best.Flt[iFlt], best.Ova[iOva]*ovaMult, "'g*', markeredgecolor='g', label='best', clip_on=0, zorder=20")
	if extra != nil {
		extra()
	}
	if equalAxes {
		plt.Equal()
	}
	plt.Gll(io.Sf("$x_%d$", iFlt), io.Sf("$f_%d$", iOva), "leg_out=1, leg_ncol=4, leg_hlen=1.5")
	plt.SaveD("/tmp/goga", fnkey+".eps")
}

// PlotFltFlt plots flt-flt contour
func PlotFltFltContour(fnkey string, opt *Optimiser, sols0 []*Solution, iFlt, jFlt, iOva int, cprms ContourParams, extra func(), equalAxes bool) {
	clr1 := "green"
	clr2 := "magenta"
	if cprms.Csimple {
		clr1 = "red"
		clr2 = "green"
	}
	opt.PlotContour(iFlt, jFlt, iOva, cprms)
	if sols0 != nil {
		opt.PlotAddFltFlt(iFlt, jFlt, sols0, plt.Fmt{L: "initial", M: "o", C: "k", Ls: "none", Ms: 3}, false)
	}
	SortByOva(opt.Solutions, iOva)
	best := opt.Solutions[0]
	opt.PlotAddFltFlt(iFlt, jFlt, opt.Solutions, plt.Fmt{L: "final", M: "o", C: clr2, Ls: "none", Ms: 7}, true)
	plt.PlotOne(best.Flt[iFlt], best.Flt[jFlt], io.Sf("'k*', markersize=6, color='%s', markeredgecolor='%s', label='best', clip_on=0, zorder=20", clr1, clr1))
	if extra != nil {
		extra()
	}
	if equalAxes {
		plt.Equal()
	}
	plt.Gll(io.Sf("$x_%d$", iFlt), io.Sf("$x_%d$", jFlt), "leg_out=1, leg_ncol=4, leg_hlen=1.5")
	plt.SaveD("/tmp/goga", fnkey+".eps")
}

// PlotOvaOvaPareto plots ova-ova Pareto values
func PlotOvaOvaPareto(opt *Optimiser, sols0 []*Solution, iOva, jOva int, feasibleOnly, frontOnly, emptyMarker bool, fmt *plt.Fmt) {
	if sols0 != nil {
		opt.PlotAddOvaOva(iOva, jOva, sols0, feasibleOnly, plt.Fmt{L: "initial", M: "+", C: "g", Ls: "none", Ms: 4}, false)
	}
	if !frontOnly {
		opt.PlotAddOvaOva(iOva, jOva, opt.Solutions, feasibleOnly, plt.Fmt{L: "final", M: ".", C: "r", Ls: "none", Ms: 5}, false)
	}
	if fmt == nil {
		fmt = &plt.Fmt{M: "o", C: "k", Ls: "none", Ms: 6}
	}
	opt.PlotAddParetoFront(iOva, jOva, opt.Solutions, fmt, emptyMarker)
	plt.Gll(io.Sf("$f_%d$", iOva), io.Sf("$f_%d$", jOva), "leg_out=1, leg_ncol=4, leg_hlen=1.5")
}
<commit_msg>plotting fronts now takes fmt<commit_after>// Copyright 2015 Dorival de Moraes Pedroso. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.

package goga

import (
	"github.com/cpmech/gosl/io"
	"github.com/cpmech/gosl/plt"
	"github.com/cpmech/gosl/utl"
)

// ContourParams holds parameters to plot contours
type ContourParams struct {
	Npts    int       // number of points for contour
	CmapIdx int       // colormap index
	Csimple bool      // simple contour
	AxEqual bool      // axes-equal
	Lwg     float64   // linewidth for g functions
	Lwh     float64   // linewidth for h functions
	Args    string    // extra arguments for plot
	Extra   func()    // extra function
	Xrange  []float64 // to override x-range
	Yrange  []float64 // to override y-range
}

// PlotContour plots contour
func (o *Optimiser) PlotContour(iFlt, jFlt, iOva int, prms ContourParams) {

	// fix parameters
	if prms.Npts < 3 {
		prms.Npts = 41
	}
	if prms.Lwg < 0.1 {
		prms.Lwg = 1.5
	}
	if prms.Lwh < 0.1 {
		prms.Lwh = 1.5
	}

	// limits and meshgrid
	xmin, xmax := o.FltMin[iFlt], o.FltMax[iFlt]
	ymin, ymax := o.FltMin[jFlt], o.FltMax[jFlt]
	if prms.Xrange != nil {
		xmin, xmax = prms.Xrange[0], prms.Xrange[1]
	}
	if prms.Yrange != nil {
		ymin, ymax = prms.Yrange[0], prms.Yrange[1]
	}

	// auxiliary variables
	X, Y := utl.MeshGrid2D(xmin, xmax, ymin, ymax, prms.Npts, prms.Npts)
	Zf := utl.DblsAlloc(prms.Npts, prms.Npts)
	var Zg [][][]float64
	var Zh [][][]float64
	if o.Ng > 0 {
		Zg = utl.Deep3alloc(o.Ng, prms.Npts, prms.Npts)
	}
	if o.Nh > 0 {
		Zh = utl.Deep3alloc(o.Nh, prms.Npts, prms.Npts)
	}

	// compute values
	x := make([]float64, 2)
	grp := 0
	for i := 0; i < prms.Npts; i++ {
		for j := 0; j < prms.Npts; j++ {
			x[0], x[1] = X[i][j], Y[i][j]
			o.MinProb(o.F[grp], o.G[grp], o.H[grp], x, nil, grp)
			Zf[i][j] = o.F[grp][iOva]
			for k, g := range o.G[grp] {
				Zg[k][i][j] = g
			}
			for k, h := range o.H[grp] {
				Zh[k][i][j] = h
			}
		}
	}

	// plot f
	if prms.Csimple {
		plt.ContourSimple(X, Y, Zf, true, 7, "colors=['k'], fsz=7, "+prms.Args)
	} else {
		plt.Contour(X, Y, Zf, io.Sf("fsz=7, cmapidx=%d, "+prms.Args, prms.CmapIdx))
	}

	// plot g
	clr := "yellow"
	if prms.Csimple {
		clr = "blue"
	}
	for _, g := range Zg {
		plt.ContourSimple(X, Y, g, false, 7, io.Sf("zorder=5, levels=[0], colors=['%s'], linewidths=[%g], clip_on=0", clr, prms.Lwg))
	}

	// plot h
	clr = "yellow"
	if prms.Csimple {
		clr = "blue"
	}
	for _, h := range Zh {
		plt.ContourSimple(X, Y, h, false, 7, io.Sf("zorder=5, levels=[0], colors=['%s'], linewidths=[%g], clip_on=0", clr, prms.Lwh))
	}
}

// PlotAddFltFlt adds flt-flt points to existent plot
func (o *Optimiser) PlotAddFltFlt(iFlt, jFlt int, sols []*Solution, fmt plt.Fmt, emptyMarker bool) {
	nsol := len(sols)
	x, y := make([]float64, nsol), make([]float64, nsol)
	for i, sol := range sols {
		x[i], y[i] = sol.Flt[iFlt], sol.Flt[jFlt]
	}
	args := fmt.GetArgs("") + ",clip_on=0,zorder=10"
	if emptyMarker {
		args += io.Sf(",markeredgecolor='%s',markerfacecolor='none'", fmt.C)
	}
	plt.Plot(x, y, args)
}

// PlotAddFltOva adds flt-ova points to existent plot
func (o *Optimiser) PlotAddFltOva(iFlt, iOva int, sols []*Solution, ovaMult float64, fmt plt.Fmt, emptyMarker bool) {
	nsol := len(sols)
	x, y := make([]float64, nsol), make([]float64, nsol)
	for i, sol := range sols {
		x[i], y[i] = sol.Flt[iFlt], sol.Ova[iOva]*ovaMult
	}
	args := fmt.GetArgs("") + ",clip_on=0,zorder=10"
	if emptyMarker {
		args += io.Sf(",markeredgecolor='%s',markerfacecolor='none'", fmt.C)
	}
	plt.Plot(x, y, args)
}

// PlotAddOvaOva adds ova-ova points to existent plot
func (o *Optimiser) PlotAddOvaOva(iOva, jOva int, sols []*Solution, feasibleOnly bool, fmt *plt.Fmt) {
	var x, y []float64
	for _, sol := range sols {
		if sol.Feasible() || !feasibleOnly {
			x = append(x, sol.Ova[iOva])
			y = append(y, sol.Ova[jOva])
		}
	}
	args := fmt.GetArgs("") + ",clip_on=0,zorder=10"
	plt.Plot(x, y, args)
}

// PlotAddParetoFront highlights Pareto front
func (o *Optimiser) PlotAddParetoFront(iOva, jOva int, sols []*Solution, fmt *plt.Fmt) {
	args := fmt.GetArgs("") + ",clip_on=0,zorder=10"
	x, y, _ := GetParetoFront(iOva, jOva, sols, false)
	plt.Plot(x, y, args)
}

// PlotFltOva plots flt-ova points
func PlotFltOva(fnkey string, opt *Optimiser, sols0 []*Solution, iFlt, iOva, np int, ovaMult float64, fcn func(x float64) float64, extra func(), equalAxes bool) {
	if fcn != nil {
		X := utl.LinSpace(opt.FltMin[0], opt.FltMax[0], np)
		Y := make([]float64, np)
		for i := 0; i < np; i++ {
			Y[i] = fcn(X[i])
		}
		plt.Plot(X, Y, "'b-'")
	}
	if sols0 != nil {
		opt.PlotAddFltOva(iFlt, iOva, sols0, ovaMult, plt.Fmt{L: "initial", M: "o", C: "k", Ls: "none", Ms: 3}, false)
	}
	SortByOva(opt.Solutions, iOva)
	best := opt.Solutions[0]
	opt.PlotAddFltOva(iFlt, iOva, opt.Solutions, ovaMult, plt.Fmt{L: "final", M: "o", C: "r", Ls: "none", Ms: 6}, true)
	plt.PlotOne(best.Flt[iFlt], best.Ova[iOva]*ovaMult, "'g*', markeredgecolor='g', label='best', clip_on=0, zorder=20")
	if extra != nil {
		extra()
	}
	if equalAxes {
		plt.Equal()
	}
	plt.Gll(io.Sf("$x_%d$", iFlt), io.Sf("$f_%d$", iOva), "leg_out=1, leg_ncol=4, leg_hlen=1.5")
	plt.SaveD("/tmp/goga", fnkey+".eps")
}

// PlotFltFlt plots flt-flt contour
func PlotFltFltContour(fnkey string, opt *Optimiser, sols0 []*Solution, iFlt, jFlt, iOva int, cprms ContourParams, extra func(), equalAxes bool) {
	clr1 := "green"
	clr2 := "magenta"
	if cprms.Csimple {
		clr1 = "red"
		clr2 = "green"
	}
	opt.PlotContour(iFlt, jFlt, iOva, cprms)
	if sols0 != nil {
		opt.PlotAddFltFlt(iFlt, jFlt, sols0, plt.Fmt{L: "initial", M: "o", C: "k", Ls: "none", Ms: 3}, false)
	}
	SortByOva(opt.Solutions, iOva)
	best := opt.Solutions[0]
	opt.PlotAddFltFlt(iFlt, jFlt, opt.Solutions, plt.Fmt{L: "final", M: "o", C: clr2, Ls: "none", Ms: 7}, true)
	plt.PlotOne(best.Flt[iFlt], best.Flt[jFlt], io.Sf("'k*', markersize=6, color='%s', markeredgecolor='%s', label='best', clip_on=0, zorder=20", clr1, clr1))
	if extra != nil {
		extra()
	}
	if equalAxes {
		plt.Equal()
	}
	plt.Gll(io.Sf("$x_%d$", iFlt), io.Sf("$x_%d$", jFlt), "leg_out=1, leg_ncol=4, leg_hlen=1.5")
	plt.SaveD("/tmp/goga", fnkey+".eps")
}

// PlotOvaOvaPareto plots ova-ova Pareto values
//  fmtAll   -- format for all points; use nil if not requested
//  fmtFront -- format for Pareto front; use nil if not requested
func PlotOvaOvaPareto(opt *Optimiser, sols0 []*Solution, iOva, jOva int, feasibleOnly bool, fmtAll, fmtFront *plt.Fmt) {
	if sols0 != nil {
		opt.PlotAddOvaOva(iOva, jOva, sols0, feasibleOnly, &plt.Fmt{L: "initial", M: "+", C: "g", Ls: "none", Ms: 4})
	}
	if fmtAll != nil {
		opt.PlotAddOvaOva(iOva, jOva, opt.Solutions, feasibleOnly, fmtAll)
	}
	if fmtFront != nil {
		opt.PlotAddParetoFront(iOva, jOva, opt.Solutions, fmtFront)
	}
	plt.Gll(io.Sf("$f_%d$", iOva), io.Sf("$f_%d$", jOva), "leg_out=1, leg_ncol=4, leg_hlen=1.5")
}
<|endoftext|>


<commit_before>// +build !windows

package detector

import (
	"fmt"
	"strconv"
	"strings"
	"syscall"
	"unsafe"

	"github.com/solicomo/host-stat-go"
)

func int8ToString(bs []int8) string {
	return strings.TrimRight(string(*(*[]byte)(unsafe.Pointer(&bs))), "\x00")
}

func (Detector) OSVer(params ...string) (result string, err error) {
	var u syscall.Utsname
	if err = syscall.Uname(&u); err != nil {
		return
	}

	sysName := int8ToString(u.Sysname[:])
	nodName := int8ToString(u.Nodename[:])
	release := int8ToString(u.Release[:])
	version := int8ToString(u.Version[:])
	machine := int8ToString(u.Machine[:])
	domName := int8ToString(u.Domainname[:])

	if len(params) == 0 {
		result = sysName + " " + nodName + " " + release + " " + version + " " + machine + " " + domName
	}

	for _, p := range params {
		switch p {
		case "s":
			result += sysName + " "
		case "n":
			result += nodName + " "
		case "r":
			result += release + " "
		case "v":
			result += version + " "
		case "m":
			result += machine + " "
		case "o":
			result += domName + " "
		}
	}
	return
}

func (Detector) Uptime() (result string, err error) {

	if upt, err := host_stat.GetUptimeStat(); err == nil {
		result = fmt.Sprintf("%v", uint64(upt))
	}

	return
}

func (Detector) Load() (result string, err error) {

	if load, err := host_stat.GetLoadStat(); err == nil {
		result = fmt.Sprintf("%v, %v, %v", load.LoadNow, load.LoadPre, load.LoadFar)
	}

	return
}

func (Detector) CPUName() (result string, err error) {

	if ci, err := host_stat.GetCPUInfo(); err == nil {
		result = ci.ModelName
	}

	return
}

func (Detector) CPUCore() (result string, err error) {

	if ci, err := host_stat.GetCPUInfo(); err == nil {
		result = fmt.Sprintf("%v", ci.CoreCount)
	}

	return
}

func (Detector) CPURate() (result string, err error) {

	if cs, err := host_stat.GetCPUStat(); err == nil {
		result = fmt.Sprintf("%v", cs.UserRate)
	}

	return
}

func (Detector) MemSize() (result string, err error) {

	if ms, err := host_stat.GetMemStat(); err == nil {
		result = fmt.Sprintf("%v", ms.MemTotal)
	}

	return
}

func (Detector) MemRate() (result string, err error) {

	if ms, err := host_stat.GetMemStat(); err == nil {
		result = fmt.Sprintf("%v", ms.MemRate)
	}

	return
}

func (Detector) SwapRate() (result string, err error) {

	if ms, err := host_stat.GetMemStat(); err == nil {
		result = fmt.Sprintf("%v", ms.SwapRate)
	}

	return
}

func (Detector) DiskSize() (result string, err error) {

	if ds, err := host_stat.GetDiskStat(); err == nil {

		disk_total := uint64(0)

		for _, v := range disk_stat {
			disk_total += v.Total
		}

		result = fmt.Sprintf("%v", disk_total)
	}

	return
}

func (Detector) DiskRate() (result string, err error) {

	if ds, err := host_stat.GetDiskStat(); err == nil {

		disk_total := uint64(0)
		disk_used := uint64(0)

		for _, v := range disk_stat {
			disk_total += v.Total
			disk_used += v.Used
		}

		result = fmt.Sprintf("%v", Round(float64(disk_used)/float64(disk_total), 2))
	}

	return
}

func (Detector) DiskRead() (result string, err error) {

	if is, err := host_stat.GetIOStat(); err == nil {

		disk_read := uint64(0)

		for _, v := range is {
			disk_read += v.ReadBytes / 1024
		}

		result = fmt.Sprintf("%v", disk_read)
	}

	return
}

func (Detector) DiskWrite() (result string, err error) {
	if is, err := host_stat.GetIOStat(); err == nil {

		disk_write := uint64(0)

		for _, v := range is {
			disk_write += v.WriteBytes / 1024
		}

		result = fmt.Sprintf("%v", disk_write)
	}

	return
}

func (Detector) NetRead() (result string, err error) {

	if ns, err := host_stat.GetNetStat(); err == nil {

		net_read := uint64(0)

		for _, v := range net_stat {
			if v.Device != "lo" {
				net_read += v.RXBytes / 1024
			}
		}

		result = fmt.Sprintf("%v", net_read)
	}

	return
}

func (Detector) NetWrite() (result string, err error) {

	if ns, err := host_stat.GetNetStat(); err == nil {

		net_write := uint64(0)

		for _, v := range net_stat {
			if v.Device != "lo" {
				net_write += v.TXBytes / 1024
			}
		}

		result = fmt.Sprintf("%v", net_write)
	}

	return
}
<commit_msg>fix bug;<commit_after>// +build !windows

package detector

import (
	"fmt"
	"strings"
	"syscall"
	"unsafe"

	"github.com/solicomo/host-stat-go"
)

func int8ToString(bs []int8) string {
	return strings.TrimRight(string(*(*[]byte)(unsafe.Pointer(&bs))), "\x00")
}

func (Detector) OSVer(params ...string) (result string, err error) {
	var u syscall.Utsname
	if err = syscall.Uname(&u); err != nil {
		return
	}

	sysName := int8ToString(u.Sysname[:])
	nodName := int8ToString(u.Nodename[:])
	release := int8ToString(u.Release[:])
	version := int8ToString(u.Version[:])
	machine := int8ToString(u.Machine[:])
	domName := int8ToString(u.Domainname[:])

	if len(params) == 0 {
		result = sysName + " " + nodName + " " + release + " " + version + " " + machine + " " + domName
	}

	for _, p := range params {
		switch p {
		case "s":
			result += sysName + " "
		case "n":
			result += nodName + " "
		case "r":
			result += release + " "
		case "v":
			result += version + " "
		case "m":
			result += machine + " "
		case "o":
			result += domName + " "
		}
	}
	return
}

func (Detector) Uptime() (result string, err error) {

	if upt, err := host_stat.GetUptimeStat(); err == nil {
		result = fmt.Sprintf("%v", uint64(upt.Uptime))
	}

	return
}

func (Detector) Load() (result string, err error) {

	if load, err := host_stat.GetLoadStat(); err == nil {
		result = fmt.Sprintf("%v, %v, %v", load.LoadNow, load.LoadPre, load.LoadFar)
	}

	return
}

func (Detector) CPUName() (result string, err error) {

	if ci, err := host_stat.GetCPUInfo(); err == nil {
		result = ci.ModelName
	}

	return
}

func (Detector) CPUCore() (result string, err error) {

	if ci, err := host_stat.GetCPUInfo(); err == nil {
		result = fmt.Sprintf("%v", ci.CoreCount)
	}

	return
}

func (Detector) CPURate() (result string, err error) {

	if cs, err := host_stat.GetCPUStat(); err == nil {
		result = fmt.Sprintf("%v", cs.UserRate)
	}

	return
}

func (Detector) MemSize() (result string, err error) {

	if ms, err := host_stat.GetMemStat(); err == nil {
		result = fmt.Sprintf("%v", ms.MemTotal)
	}

	return
}

func (Detector) MemRate() (result string, err error) {

	if ms, err := host_stat.GetMemStat(); err == nil {
		result = fmt.Sprintf("%v", ms.MemRate)
	}

	return
}

func (Detector) SwapRate() (result string, err error) {

	if ms, err := host_stat.GetMemStat(); err == nil {
		result = fmt.Sprintf("%v", ms.SwapRate)
	}

	return
}

func (Detector) DiskSize() (result string, err error) {

	if ds, err := host_stat.GetDiskStat(); err == nil {

		disk_total := uint64(0)

		for _, v := range ds {
			disk_total += v.Total
		}

		result = fmt.Sprintf("%v", disk_total)
	}

	return
}

func (Detector) DiskRate() (result string, err error) {

	if ds, err := host_stat.GetDiskStat(); err == nil {

		disk_total := uint64(0)
		disk_used := uint64(0)

		for _, v := range ds {
			disk_total += v.Total
			disk_used += v.Used
		}

		result = fmt.Sprintf("%v", Round(float64(disk_used)/float64(disk_total), 2))
	}

	return
}

func (Detector) DiskRead() (result string, err error) {

	if is, err := host_stat.GetIOStat(); err == nil {

		disk_read := uint64(0)

		for _, v := range is {
			disk_read += v.ReadBytes / 1024
		}

		result = fmt.Sprintf("%v", disk_read)
	}

	return
}

func (Detector) DiskWrite() (result string, err error) {
	if is, err := host_stat.GetIOStat(); err == nil {

		disk_write := uint64(0)

		for _, v := range is {
			disk_write += v.WriteBytes / 1024
		}

		result = fmt.Sprintf("%v", disk_write)
	}

	return
}

func (Detector) NetRead() (result string, err error) {

	if ns, err := host_stat.GetNetStat(); err == nil {

		net_read := uint64(0)

		for _, v := range ns {
			if v.Device != "lo" {
				net_read += v.RXBytes / 1024
			}
		}

		result = fmt.Sprintf("%v", net_read)
	}

	return
}

func (Detector) NetWrite() (result string, err error) {

	if ns, err := host_stat.GetNetStat(); err == nil {

		net_write := uint64(0)

		for _, v := range ns {
			if v.Device != "lo" {
				net_write += v.TXBytes / 1024
			}
		}

		result = fmt.Sprintf("%v", net_write)
	}

	return
}
<|endoftext|>


<commit_before>package app

//ShortHelp is a short description of dry
const ShortHelp = `
dry

Connects to a Docker daemon if environment variable DOCKER_HOST is present
then shows the list of containers and allows some interaction with them.

`

const help = `
<white>dry</>

Connects to a Docker daemon if environment variable DOCKER_HOST is present
then shows the list of containers and allows some interaction with them.

Command    Description
	<white>F1</>       Cycles through containers sort modes (by Id | by Image | by Status | by Name)
	<white>F2</>       Toggles showing all containers (default shows just running)
	<white>F5</>       Refresh container list
	<white>k</>        Kills the selected container
	<white>l</>        Displays the logs of the selected container
	<white>r</>        Restarts selected container (noop if it is already running)
	<white>s</>        Displays a live stream of the selected container resource usage statistics
	<white>t</>        Stops selected container (noop if it is not running)
	<white>Enter</>    Returns low-level information on the selected container
	<white>q</>        Quits <white>dry</>.
	<white>esc</>      In the main view, quits <white>dry</>. In any other view, goes back to the main view

## Moving around in logs/inspect
	<white>g</>    		 Moves the cursor to the beggining
	<white>G</>   		 Moves the cursor until the end
	<white>pg up</>		 Moves the cursor "screen size" lines up
	<white>pg down</>	 Moves the cursor "screen size" lines down

<r> Press any key to continue </r>
`

const keyMappings = "[H]:<darkgrey>Help</> [Q]:<darkgrey>Quit</> <blue>|</> " +
	"[F1]:<darkgrey>Sort</> [F2]:<darkgrey>Toggle Show Containers</> [F5]:<darkgrey>Refresh</> <blue>|</> " +
	"[E]:<darkgrey>Remove</> [K]:<darkgrey>Kill</> [L]:<darkgrey>Logs</> [R]:<darkgrey>Restart</> " +
	"[S]:<darkgrey>Stats</> [T]:<darkgrey>Stop</> <blue>|</>" +
	"[Enter]:<darkgrey>Inspect</>"
<commit_msg>Update help<commit_after>package app

//ShortHelp is a short description of dry
const ShortHelp = `
dry

Connects to a Docker daemon if environment variable DOCKER_HOST is present
then shows the list of containers and allows some interaction with them.

`

const help = `
<white>dry</>

Connects to a Docker daemon, then shows the list of containers and allows some interaction with them.

Visit <blue>http://moncho.github.io/dry/</> for more information.

Command    Description
	<white>F1</>       Cycles through containers sort modes (by Id | by Image | by Status | by Name)
	<white>F2</>       Toggles showing all containers (default shows just running)
	<white>F5</>       Refresh container list
	<white>F10</>      Inspects Docker
	<white>e</>        Removes the selected container
	<white>Crtl+e</>   Removes all stopped containers
	<white>k</>        Kills the selected container
	<white>l</>        Displays the logs of the selected container
	<white>r</>        Restarts selected container (noop if it is already running)
	<white>s</>        Displays a live stream of the selected container resource usage statistics
	<white>t</>        Stops selected container (noop if it is not running)
	<white>Enter</>    Returns low-level information on the selected container
	<white>q</>        Quits <white>dry</>.
	<white>esc</>      In the main view, quits <white>dry</>. In any other view, goes back to the main view

## Moving around in logs/inspect
	<white>g</>        Moves the cursor to the beggining
	<white>G</>        Moves the cursor until the end
	<white>n</>        After a search, it moves forwards until the next search hit
	<white>N</>        After a search, it moves backwards until the next search hit
	<white>s</>        Searchs in the text being shown
	<white>pg up</>    Moves the cursor "screen size" lines up
	<white>pg down</>  Moves the cursor "screen size" lines down

<r> Press ESC to exit help. </r>
`

const keyMappings = "[H]:<darkgrey>Help</> [Q]:<darkgrey>Quit</> <blue>|</> " +
	"[F1]:<darkgrey>Sort</> [F2]:<darkgrey>Toggle Show Containers</> [F5]:<darkgrey>Refresh</> [F10]:<darkgrey>Docker Info</> <blue>|</> " +
	"[E]:<darkgrey>Remove</> [K]:<darkgrey>Kill</> [L]:<darkgrey>Logs</> [R]:<darkgrey>Restart</> " +
	"[S]:<darkgrey>Stats</> [T]:<darkgrey>Stop</> <blue>|</>" +
	"[Enter]:<darkgrey>Inspect</>"
<|endoftext|>


<commit_before>package state

import (
	"encoding/hex"
	"sort"

	"github.com/bytom/bytom/config"
	"github.com/bytom/bytom/consensus"
	"github.com/bytom/bytom/errors"
	"github.com/bytom/bytom/protocol/bc"
	"github.com/bytom/bytom/protocol/bc/types"
)

// CheckpointStatus represent current status of checkpoint
type CheckpointStatus uint8

const (
	// Growing means that the checkpoint has not ended the current epoch
	Growing CheckpointStatus = iota

	// Unjustified means thant the checkpoint has ended the current epoch, but not been justified
	Unjustified

	// Justified if checkpoint is the root, or there exists a super link c′ → c where c′ is justified
	Justified

	// Finalized if checkpoint c is justified and there is a sup link c→c′ where c′is a direct child of c
	Finalized
)

var errIncreaseCheckpoint = errors.New("invalid block for increase checkpoint")

// Checkpoint represent the block/hash under consideration for finality for a given epoch.
// This block is the last block of the previous epoch. Rather than dealing with every block,
// Casper only considers checkpoints for finalization. When a checkpoint is explicitly finalized,
// all ancestor blocks of the checkpoint are implicitly finalized.
type Checkpoint struct {
	Height     uint64
	Hash       bc.Hash
	ParentHash bc.Hash
	Timestamp  uint64
	Status     CheckpointStatus

	Rewards map[string]uint64 // controlProgram -> num of reward
	Votes   map[string]uint64 // pubKey -> num of vote

	// only save in the memory, not be persisted
	Parent   *Checkpoint      `json:"-"`
	SupLinks []*types.SupLink `json:"-"`
}

// NewCheckpoint create a new checkpoint instance
func NewCheckpoint(parent *Checkpoint) *Checkpoint {
	checkpoint := &Checkpoint{
		ParentHash: parent.Hash,
		Parent:     parent,
		Status:     Growing,
		Rewards:    make(map[string]uint64),
		Votes:      make(map[string]uint64),
	}

	for pubKey, num := range parent.Votes {
		if num != 0 {
			checkpoint.Votes[pubKey] = num
		}
	}
	return checkpoint
}

// AddVerification add a valid verification to checkpoint's supLink
func (c *Checkpoint) AddVerification(sourceHash bc.Hash, sourceHeight uint64, validatorOrder int, signature []byte) *types.SupLink {
	for _, supLink := range c.SupLinks {
		if supLink.SourceHash == sourceHash {
			supLink.Signatures[validatorOrder] = signature
			return supLink
		}
	}

	supLink := &types.SupLink{
		SourceHeight: sourceHeight,
		SourceHash:   sourceHash,
	}
	supLink.Signatures[validatorOrder] = signature
	c.SupLinks = append(c.SupLinks, supLink)
	return supLink
}

// ContainsVerification return whether the specified validator has add verification to current checkpoint
// sourceHash not as filter if is nil,
func (c *Checkpoint) ContainsVerification(validatorOrder int, sourceHash *bc.Hash) bool {
	for _, supLink := range c.SupLinks {
		if (sourceHash == nil || supLink.SourceHash == *sourceHash) && len(supLink.Signatures[validatorOrder]) != 0 {
			return true
		}
	}
	return false
}

// Increase will increase the height of checkpoint
func (c *Checkpoint) Increase(block *types.Block) error {
	empty := bc.Hash{}
	prevHash := c.Hash
	if c.Hash == empty {
		prevHash = c.ParentHash
	}

	if block.PreviousBlockHash != prevHash {
		return errIncreaseCheckpoint
	}

	if block.Height%consensus.ActiveNetParams.BlocksOfEpoch == 0 {
		c.Status = Unjustified
	}

	c.Hash = block.Hash()
	c.Height = block.Height
	c.Timestamp = block.Timestamp
	c.applyVotes(block)
	c.applyValidatorReward(block)
	c.applyFederationReward()
	return nil
}

// Validator represent the participants of the PoS network
// Responsible for block generation and verification
type Validator struct {
	PubKey  string
	Order   int
	VoteNum uint64
}

// EffectiveValidators return next epoch of effective validators, if the status of checkpoint is growing, return empty
func (c *Checkpoint) EffectiveValidators() map[string]*Validator {
	validators := c.AllValidators()
	if len(validators) == 0 {
		return federationValidators()
	}

	result := make(map[string]*Validator)
	for i := 0; i < len(validators) && i < consensus.MaxNumOfValidators; i++ {
		validator := validators[i]
		validator.Order = i
		result[validator.PubKey] = validator
	}
	return result
}

// AllValidators return all validators has vote num
func (c *Checkpoint) AllValidators() []*Validator {
	if c.Status == Growing {
		return nil
	}

	var validators []*Validator
	for pubKey, voteNum := range c.Votes {
		if voteNum >= consensus.ActiveNetParams.MinValidatorVoteNum {
			validators = append(validators, &Validator{
				PubKey:  pubKey,
				VoteNum: c.Votes[pubKey],
			})
		}
	}

	sort.Slice(validators, func(i, j int) bool {
		numI, numJ := validators[i].VoteNum, validators[j].VoteNum
		if numI != numJ {
			return numI > numJ
		}
		return validators[i].PubKey > validators[j].PubKey
	})
	return validators
}

func (c *Checkpoint) applyVotes(block *types.Block) {
	for _, tx := range block.Transactions {
		for _, input := range tx.Inputs {
			if vetoInput, ok := input.TypedInput.(*types.VetoInput); ok {
				pubKey := hex.EncodeToString(vetoInput.Vote)
				if c.Votes[pubKey] > vetoInput.Amount {
					c.Votes[pubKey] -= vetoInput.Amount
				} else {
					delete(c.Votes, pubKey)
				}
			}
		}

		for _, output := range tx.Outputs {
			if voteOutput, ok := output.TypedOutput.(*types.VoteOutput); ok {
				c.Votes[hex.EncodeToString(voteOutput.Vote)] += output.Amount
			}
		}
	}
}

func federationValidators() map[string]*Validator {
	validators := map[string]*Validator{}
	for i, xPub := range config.CommonConfig.Federation.Xpubs {
		validators[xPub.String()] = &Validator{PubKey: xPub.String(), Order: i}
	}
	return validators
}
<commit_msg>try remove mid status (#2016)<commit_after>package state

import (
	"encoding/hex"
	"sort"

	"github.com/bytom/bytom/config"
	"github.com/bytom/bytom/consensus"
	"github.com/bytom/bytom/errors"
	"github.com/bytom/bytom/protocol/bc"
	"github.com/bytom/bytom/protocol/bc/types"
)

// CheckpointStatus represent current status of checkpoint
type CheckpointStatus uint8

const (
	// Growing means that the checkpoint has not ended the current epoch
	Growing CheckpointStatus = iota

	// Unjustified means thant the checkpoint has ended the current epoch, but not been justified
	Unjustified

	// Justified if checkpoint is the root, or there exists a super link c′ → c where c′ is justified
	Justified

	// Finalized if checkpoint c is justified and there is a sup link c→c′ where c′is a direct child of c
	Finalized
)

var errIncreaseCheckpoint = errors.New("invalid block for increase checkpoint")

// Checkpoint represent the block/hash under consideration for finality for a given epoch.
// This block is the last block of the previous epoch. Rather than dealing with every block,
// Casper only considers checkpoints for finalization. When a checkpoint is explicitly finalized,
// all ancestor blocks of the checkpoint are implicitly finalized.
type Checkpoint struct {
	Height     uint64
	Hash       bc.Hash
	ParentHash bc.Hash
	Timestamp  uint64
	Status     CheckpointStatus

	Rewards map[string]uint64 // controlProgram -> num of reward
	Votes   map[string]uint64 // pubKey -> num of vote

	// only save in the memory, not be persisted
	Parent   *Checkpoint      `json:"-"`
	SupLinks []*types.SupLink `json:"-"`
}

// NewCheckpoint create a new checkpoint instance
func NewCheckpoint(parent *Checkpoint) *Checkpoint {
	checkpoint := &Checkpoint{
		Height:     parent.Height,
		Hash:       parent.Hash,
		Timestamp:  parent.Timestamp,
		ParentHash: parent.Hash,
		Parent:     parent,
		Status:     Growing,
		Rewards:    make(map[string]uint64),
		Votes:      make(map[string]uint64),
	}

	for pubKey, num := range parent.Votes {
		if num != 0 {
			checkpoint.Votes[pubKey] = num
		}
	}
	return checkpoint
}

// AddVerification add a valid verification to checkpoint's supLink
func (c *Checkpoint) AddVerification(sourceHash bc.Hash, sourceHeight uint64, validatorOrder int, signature []byte) *types.SupLink {
	for _, supLink := range c.SupLinks {
		if supLink.SourceHash == sourceHash {
			supLink.Signatures[validatorOrder] = signature
			return supLink
		}
	}

	supLink := &types.SupLink{
		SourceHeight: sourceHeight,
		SourceHash:   sourceHash,
	}
	supLink.Signatures[validatorOrder] = signature
	c.SupLinks = append(c.SupLinks, supLink)
	return supLink
}

// ContainsVerification return whether the specified validator has add verification to current checkpoint
// sourceHash not as filter if is nil,
func (c *Checkpoint) ContainsVerification(validatorOrder int, sourceHash *bc.Hash) bool {
	for _, supLink := range c.SupLinks {
		if (sourceHash == nil || supLink.SourceHash == *sourceHash) && len(supLink.Signatures[validatorOrder]) != 0 {
			return true
		}
	}
	return false
}

// Increase will increase the height of checkpoint
func (c *Checkpoint) Increase(block *types.Block) error {
	if block.PreviousBlockHash != c.Hash {
		return errIncreaseCheckpoint
	}

	if block.Height%consensus.ActiveNetParams.BlocksOfEpoch == 0 {
		c.Status = Unjustified
	}

	c.Hash = block.Hash()
	c.Height = block.Height
	c.Timestamp = block.Timestamp
	c.applyVotes(block)
	c.applyValidatorReward(block)
	c.applyFederationReward()
	return nil
}

// Validator represent the participants of the PoS network
// Responsible for block generation and verification
type Validator struct {
	PubKey  string
	Order   int
	VoteNum uint64
}

// EffectiveValidators return next epoch of effective validators, if the status of checkpoint is growing, return empty
func (c *Checkpoint) EffectiveValidators() map[string]*Validator {
	validators := c.AllValidators()
	if len(validators) == 0 {
		return federationValidators()
	}

	result := make(map[string]*Validator)
	for i := 0; i < len(validators) && i < consensus.MaxNumOfValidators; i++ {
		validator := validators[i]
		validator.Order = i
		result[validator.PubKey] = validator
	}
	return result
}

// AllValidators return all validators has vote num
func (c *Checkpoint) AllValidators() []*Validator {
	if c.Status == Growing {
		return nil
	}

	var validators []*Validator
	for pubKey, voteNum := range c.Votes {
		if voteNum >= consensus.ActiveNetParams.MinValidatorVoteNum {
			validators = append(validators, &Validator{
				PubKey:  pubKey,
				VoteNum: c.Votes[pubKey],
			})
		}
	}

	sort.Slice(validators, func(i, j int) bool {
		numI, numJ := validators[i].VoteNum, validators[j].VoteNum
		if numI != numJ {
			return numI > numJ
		}
		return validators[i].PubKey > validators[j].PubKey
	})
	return validators
}

func (c *Checkpoint) applyVotes(block *types.Block) {
	for _, tx := range block.Transactions {
		for _, input := range tx.Inputs {
			if vetoInput, ok := input.TypedInput.(*types.VetoInput); ok {
				pubKey := hex.EncodeToString(vetoInput.Vote)
				if c.Votes[pubKey] > vetoInput.Amount {
					c.Votes[pubKey] -= vetoInput.Amount
				} else {
					delete(c.Votes, pubKey)
				}
			}
		}

		for _, output := range tx.Outputs {
			if voteOutput, ok := output.TypedOutput.(*types.VoteOutput); ok {
				c.Votes[hex.EncodeToString(voteOutput.Vote)] += output.Amount
			}
		}
	}
}

func federationValidators() map[string]*Validator {
	validators := map[string]*Validator{}
	for i, xPub := range config.CommonConfig.Federation.Xpubs {
		validators[xPub.String()] = &Validator{PubKey: xPub.String(), Order: i}
	}
	return validators
}
<|endoftext|>


<commit_before>package main

import (
	"bytes"
	"encoding/json"
	"fmt"
	"html/template"
	"io/ioutil"
	"log"
	"math"
	"net/http"
	"os"
	"strconv"
	"strings"
)

// Define the types

type configuration struct {
	Name           string `json: "name"`
	Url            string `json: "url"`
	CallbackSecret string `json: "callbacksecret"`
	BasePrice      int    `json: "baseprice"`
	MinimumPrice   int    `json: "minprice"`
	ApiKey         string `json: "coinbasekey"`
}

type transactionResult struct {
	Success bool `json:"success"`
	Button  struct {
		Code string `json:"code"`
	} `json:"button"`
}

type callbackResult struct {
	Order struct {
		Filename string `json:"custom"`
	} `json:"order"`
}

// Create the configuration
var config = configuration{}

// Do stuff

// Get an appropriate name for the file.
func newFileName(fname string) string {
	result := strings.Replace(strings.Replace(fname, "/", "-", -1), " ", "-", -1)
	if _, err := os.Stat("f/" + result); os.IsNotExist(err) {
		if _, err := os.Stat("tmp/" + result); os.IsNotExist(err) {
			// Don't do anything.
		} else {
			result = newFileName("p" + result)
		}
	} else {
		result = newFileName("p" + result)
	}
	return result
}

// Create a coinbase button.
func createButton(n string, p int) string {
	coinbaserequest := "{ \"button\": {" +
		"\"name\": \"One-Time Hosting Purchase\"," +
		"\"type\": \"buy_now\"," +
		"\"price_string\": \"" + strconv.FormatFloat(float64(p)/float64(100000000), 'f', 8, 64) + "\"," +
		"\"price_currency_iso\": \"BTC\"," +
		"\"custom\": \"" + n + "\"," +
		"\"callback_url\": \"whatever\"," +
		"\"description\": \"Indefinite storage of the provided file. Your file will be available at: http://btcdl.bearbin.net/f/" + n + " when the transaction processes.\"," +
		"\"type\": \"buy_now\"," +
		"\"style\": \"custom_large\"" +
		"} }"
	fmt.Println(coinbaserequest)
	request_body := bytes.NewBuffer([]byte(coinbaserequest))

	client := &http.Client{}
	req, err := http.NewRequest("POST", "https://coinbase.com/api/v1/buttons?api_key="+config.ApiKey, request_body)
	if err != nil {
		fmt.Println(err)
	}

	req.Header.Add("content-type", "application/json")
	resp, err := client.Do(req)
	if err != nil {
		fmt.Println(err)
	}

	response_body, err := ioutil.ReadAll(resp.Body)
	if err != nil {
		fmt.Println(err)
	}
	defer resp.Body.Close()
	res := transactionResult{}
	fmt.Println(string(response_body))
	err = json.Unmarshal(response_body, &res)
	return res.Button.Code

}

// hello world, the web server
func upload(w http.ResponseWriter, req *http.Request) {

	// Get the form file.
	file, header, err := req.FormFile("file")
	if err != nil {
		fmt.Println(err)
		return
	}

	// Get the name for the file.
	fileName := newFileName(header.Filename)
	log.Print("Uploaded new file: ", fileName)

	data, err := ioutil.ReadAll(file)
	if err != nil {
		log.Print(err)
		return
	}
	err = ioutil.WriteFile("tmp/"+fileName, data, 0777)
	if err != nil {
		log.Print(err)
		return
	}

	// Get file size.
	supfil, _ := os.Stat("tmp/" + fileName)
	fileSize := math.Floor(float64(supfil.Size()) / 1024)
	price := int(math.Floor(float64(config.BasePrice) * (fileSize/1024)))
	if price < config.MinimumPrice {
		price = config.MinimumPrice
	}
	// Redirect the user.
	http.Redirect(w, req, "https://coinbase.com/checkouts/"+createButton(fileName, price), 302)

}

func coinbaseCallback(w http.ResponseWriter, req *http.Request) {
	fmt.Println("LELELELE")
	body, _ := ioutil.ReadAll(req.Body)
	res := callbackResult{}
	fmt.Println(body)
	json.Unmarshal([]byte(body), &res)
	fmt.Println(res.Order.Filename)
	os.Rename("tmp/"+res.Order.Filename, "f/"+res.Order.Filename)
}

func MainPage(w http.ResponseWriter, req *http.Request) {
	t, _ := template.ParseFiles("index.html")
	t.Execute(w, "")
}

func main() {
	// Inititalize the config.
	configFile, err := os.Open("config.json")
	if err != nil {
		log.Fatal("Failed to open config: ", err)
	}
	decoder := json.NewDecoder(configFile)

	err = decoder.Decode(&config)
	if err != nil {
		log.Fatal("Failed to open config: ", err)
	}

	// Main page
	http.HandleFunc("/", MainPage)
	// Upload page
	http.HandleFunc("/upload", upload)
	// Coinbase callback
	http.HandleFunc("/wheatver", coinbaseCallback)
	// Static files
	http.Handle("/f/", http.FileServer(http.Dir("")))

	// Try and serve port 80.
	err = http.ListenAndServe(":80", nil)
	if err != nil {
		// Failed for some reason, try port 8080
		log.Print("Failed to bind to port 80, trying 8080.")
		err := http.ListenAndServe(":8080", nil)
		if err != nil {
			// Failed.
			log.Fatal("ListenAndServe: ", err)
		}
	}
}
<commit_msg>Added a comment.<commit_after>package main
// Package main runs the petulant-lana server.

import (
	"bytes"
	"encoding/json"
	"fmt"
	"html/template"
	"io/ioutil"
	"log"
	"math"
	"net/http"
	"os"
	"strconv"
	"strings"
)

// Define the types

type configuration struct {
	Name           string `json: "name"`
	Url            string `json: "url"`
	CallbackSecret string `json: "callbacksecret"`
	BasePrice      int    `json: "baseprice"`
	MinimumPrice   int    `json: "minprice"`
	ApiKey         string `json: "coinbasekey"`
}

type transactionResult struct {
	Success bool `json:"success"`
	Button  struct {
		Code string `json:"code"`
	} `json:"button"`
}

type callbackResult struct {
	Order struct {
		Filename string `json:"custom"`
	} `json:"order"`
}

// Create the configuration
var config = configuration{}

// Do stuff

// Get an appropriate name for the file.
func newFileName(fname string) string {
	result := strings.Replace(strings.Replace(fname, "/", "-", -1), " ", "-", -1)
	if _, err := os.Stat("f/" + result); os.IsNotExist(err) {
		if _, err := os.Stat("tmp/" + result); os.IsNotExist(err) {
			// Don't do anything.
		} else {
			result = newFileName("p" + result)
		}
	} else {
		result = newFileName("p" + result)
	}
	return result
}

// Create a coinbase button.
func createButton(n string, p int) string {
	coinbaserequest := "{ \"button\": {" +
		"\"name\": \"One-Time Hosting Purchase\"," +
		"\"type\": \"buy_now\"," +
		"\"price_string\": \"" + strconv.FormatFloat(float64(p)/float64(100000000), 'f', 8, 64) + "\"," +
		"\"price_currency_iso\": \"BTC\"," +
		"\"custom\": \"" + n + "\"," +
		"\"callback_url\": \"whatever\"," +
		"\"description\": \"Indefinite storage of the provided file. Your file will be available at: http://btcdl.bearbin.net/f/" + n + " when the transaction processes.\"," +
		"\"type\": \"buy_now\"," +
		"\"style\": \"custom_large\"" +
		"} }"
	fmt.Println(coinbaserequest)
	request_body := bytes.NewBuffer([]byte(coinbaserequest))

	client := &http.Client{}
	req, err := http.NewRequest("POST", "https://coinbase.com/api/v1/buttons?api_key="+config.ApiKey, request_body)
	if err != nil {
		fmt.Println(err)
	}

	req.Header.Add("content-type", "application/json")
	resp, err := client.Do(req)
	if err != nil {
		fmt.Println(err)
	}

	response_body, err := ioutil.ReadAll(resp.Body)
	if err != nil {
		fmt.Println(err)
	}
	defer resp.Body.Close()
	res := transactionResult{}
	fmt.Println(string(response_body))
	err = json.Unmarshal(response_body, &res)
	return res.Button.Code

}

// hello world, the web server
func upload(w http.ResponseWriter, req *http.Request) {

	// Get the form file.
	file, header, err := req.FormFile("file")
	if err != nil {
		fmt.Println(err)
		return
	}

	// Get the name for the file.
	fileName := newFileName(header.Filename)
	log.Print("Uploaded new file: ", fileName)

	data, err := ioutil.ReadAll(file)
	if err != nil {
		log.Print(err)
		return
	}
	err = ioutil.WriteFile("tmp/"+fileName, data, 0777)
	if err != nil {
		log.Print(err)
		return
	}

	// Get file size.
	supfil, _ := os.Stat("tmp/" + fileName)
	fileSize := math.Floor(float64(supfil.Size()) / 1024)
	price := int(math.Floor(float64(config.BasePrice) * (fileSize/1024)))
	if price < config.MinimumPrice {
		price = config.MinimumPrice
	}
	// Redirect the user.
	http.Redirect(w, req, "https://coinbase.com/checkouts/"+createButton(fileName, price), 302)

}

func coinbaseCallback(w http.ResponseWriter, req *http.Request) {
	fmt.Println("LELELELE")
	body, _ := ioutil.ReadAll(req.Body)
	res := callbackResult{}
	fmt.Println(body)
	json.Unmarshal([]byte(body), &res)
	fmt.Println(res.Order.Filename)
	os.Rename("tmp/"+res.Order.Filename, "f/"+res.Order.Filename)
}

func MainPage(w http.ResponseWriter, req *http.Request) {
	t, _ := template.ParseFiles("index.html")
	t.Execute(w, "")
}

func main() {
	// Inititalize the config.
	configFile, err := os.Open("config.json")
	if err != nil {
		log.Fatal("Failed to open config: ", err)
	}
	decoder := json.NewDecoder(configFile)

	err = decoder.Decode(&config)
	if err != nil {
		log.Fatal("Failed to open config: ", err)
	}

	// Main page
	http.HandleFunc("/", MainPage)
	// Upload page
	http.HandleFunc("/upload", upload)
	// Coinbase callback
	http.HandleFunc("/wheatver", coinbaseCallback)
	// Static files
	http.Handle("/f/", http.FileServer(http.Dir("")))

	// Try and serve port 80.
	err = http.ListenAndServe(":80", nil)
	if err != nil {
		// Failed for some reason, try port 8080
		log.Print("Failed to bind to port 80, trying 8080.")
		err := http.ListenAndServe(":8080", nil)
		if err != nil {
			// Failed.
			log.Fatal("ListenAndServe: ", err)
		}
	}
}
<|endoftext|>


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

// pgsqldriver is a PostgreSQL driver for the experimental Go SQL database package.
package pgsqldriver

/*
#include <stdlib.h>
#include <libpq-fe.h>

static char**makeCharArray(int size) {
	return calloc(sizeof(char*), size);
}

static void setArrayString(char **a, char *s, int n) {
	a[n] = s;
}

static void freeCharArray(char **a, int size) {
	int i;
	for (i = 0; i < size; i++)
		free(a[i]);
	free(a);
}
*/
// #cgo CFLAGS: -I/usr/local/pgsql/include
// #cgo LDFLAGS: -L/usr/local/pgsql/lib -lpq
import "C"

import (
	"database/sql"
	"database/sql/driver"
	"encoding/hex"
	"errors"
	"fmt"
	"io"
	"runtime"
	"strconv"
	"strings"
	"time"
	"unsafe"
)

func connError(db *C.PGconn) error {
	return errors.New("conn error:" + C.GoString(C.PQerrorMessage(db)))
}

func resultError(res *C.PGresult) error {
	serr := C.GoString(C.PQresultErrorMessage(res))
	if serr == "" {
		return nil
	}
	return errors.New("result error: " + serr)
}

const timeFormat = "2006-01-02 15:04:05.000000-07"

type Date struct {
	time.Time
}

var _ sql.ScannerInto = (*Date)(nil)

func (d *Date) ScanInto(value interface{}) error {
	switch s := value.(type) {
	case string:
		t, err := time.Parse("2006-01-02", s)
		if err != nil {
			return err
		}
		d.Time = t
	default:
		return errors.New("invalid type")
	}
	return nil
}

type postgresDriver struct{}

// Open creates a new database connection using the given connection string.
// Each parameter setting is in the form 'keyword=value'.
// See http://www.postgresql.org/docs/9.0/static/libpq-connect.html#LIBPQ-PQCONNECTDBPARAMS
// for a list of recognized parameters.
func (d *postgresDriver) Open(name string) (conn driver.Conn, err error) {
	cparams := C.CString(name)
	defer C.free(unsafe.Pointer(cparams))
	db := C.PQconnectdb(cparams)
	if C.PQstatus(db) != C.CONNECTION_OK {
		err = connError(db)
		C.PQfinish(db)
		return nil, err
	}
	conn = &driverConn{db, 0}
	runtime.SetFinalizer(conn, (*driverConn).Close)
	return
}

type driverConn struct {
	db      *C.PGconn
	stmtNum int
}

// Check that driverConn implements driver.Execer interface.
var _ driver.Execer = (*driverConn)(nil)

func (c *driverConn) exec(stmt string, args []interface{}) (cres *C.PGresult) {
	stmtstr := C.CString(stmt)
	defer C.free(unsafe.Pointer(stmtstr))
	if len(args) == 0 {
		cres = C.PQexec(c.db, stmtstr)
	} else {
		cargs := buildCArgs(args)
		defer C.freeCharArray(cargs, C.int(len(args)))
		cres = C.PQexecParams(c.db, stmtstr, C.int(len(args)), nil, cargs, nil, nil, 0)
	}
	return cres
}

func (c *driverConn) Exec(query string, args []interface{}) (res driver.Result, err error) {
	cres := c.exec(query, args)
	if err = resultError(cres); err != nil {
		C.PQclear(cres)
		return
	}
	defer C.PQclear(cres)
	ns := C.GoString(C.PQcmdTuples(cres))
	if ns == "" {
		return driver.DDLSuccess, nil
	}
	rowsAffected, err := strconv.ParseInt(ns, 10, 64)
	if err != nil {
		return
	}
	return driver.RowsAffected(rowsAffected), nil
}

func (c *driverConn) Prepare(query string) (driver.Stmt, error) {
	// Generate unique statement name.
	stmtname := strconv.Itoa(c.stmtNum)
	cstmtname := C.CString(stmtname)
	c.stmtNum++
	defer C.free(unsafe.Pointer(cstmtname))
	stmtstr := C.CString(query)
	defer C.free(unsafe.Pointer(stmtstr))
	res := C.PQprepare(c.db, cstmtname, stmtstr, 0, nil)
	err := resultError(res)
	if err != nil {
		C.PQclear(res)
		return nil, err
	}
	stmtinfo := C.PQdescribePrepared(c.db, cstmtname)
	err = resultError(stmtinfo)
	if err != nil {
		C.PQclear(stmtinfo)
		return nil, err
	}
	defer C.PQclear(stmtinfo)
	nparams := int(C.PQnparams(stmtinfo))
	statement := &driverStmt{stmtname, c.db, res, nparams}
	runtime.SetFinalizer(statement, (*driverStmt).Close)
	return statement, nil
}

func (c *driverConn) Close() error {
	if c != nil && c.db != nil {
		C.PQfinish(c.db)
		c.db = nil
		runtime.SetFinalizer(c, nil)
	}
	return nil
}

func (c *driverConn) Begin() (driver.Tx, error) {
	if _, err := c.Exec("BEGIN", nil); err != nil {
		return nil, err
	}
	// driverConn implements driver.Tx interface.
	return c, nil
}

func (c *driverConn) Commit() (err error) {
	_, err = c.Exec("COMMIT", nil)
	return
}

func (c *driverConn) Rollback() (err error) {
	_, err = c.Exec("ROLLBACK", nil)
	return
}

type driverStmt struct {
	name    string
	db      *C.PGconn
	res     *C.PGresult
	nparams int
}

func (s *driverStmt) NumInput() int {
	return s.nparams
}

func (s *driverStmt) exec(params []interface{}) *C.PGresult {
	stmtName := C.CString(s.name)
	defer C.free(unsafe.Pointer(stmtName))
	cparams := buildCArgs(params)
	defer C.freeCharArray(cparams, C.int(len(params)))
	return C.PQexecPrepared(s.db, stmtName, C.int(len(params)), cparams, nil, nil, 0)
}

func (s *driverStmt) Exec(args []interface{}) (res driver.Result, err error) {
	cres := s.exec(args)
	if err = resultError(cres); err != nil {
		C.PQclear(cres)
		return
	}
	defer C.PQclear(cres)
	rowsAffected, err := strconv.ParseInt(C.GoString(C.PQcmdTuples(cres)), 10, 64)
	if err != nil {
		return
	}
	return driver.RowsAffected(rowsAffected), nil
}

func (s *driverStmt) Query(args []interface{}) (driver.Rows, error) {
	cres := s.exec(args)
	if err := resultError(cres); err != nil {
		C.PQclear(cres)
		return nil, err
	}
	return newResult(cres), nil
}

func (s *driverStmt) Close() error {
	if s != nil && s.res != nil {
		C.PQclear(s.res)
		runtime.SetFinalizer(s, nil)
	}
	return nil
}

type driverRows struct {
	res     *C.PGresult
	nrows   int
	currRow int
	ncols   int
	cols    []string
}

func newResult(res *C.PGresult) *driverRows {
	ncols := int(C.PQnfields(res))
	nrows := int(C.PQntuples(res))
	result := &driverRows{res: res, nrows: nrows, currRow: -1, ncols: ncols, cols: nil}
	runtime.SetFinalizer(result, (*driverRows).Close)
	return result
}

func (r *driverRows) Columns() []string {
	if r.cols == nil {
		r.cols = make([]string, r.ncols)
		for i := 0; i < r.ncols; i++ {
			r.cols[i] = C.GoString(C.PQfname(r.res, C.int(i)))
		}
	}
	return r.cols
}

func argErr(i int, argType string, err string) error {
	return errors.New(fmt.Sprintf("arg %d as %s: %s", i, argType, err))
}

func (r *driverRows) Next(dest []interface{}) error {
	r.currRow++
	if r.currRow >= r.nrows {
		return io.EOF
	}

	for i := 0; i < len(dest); i++ {
		if int(C.PQgetisnull(r.res, C.int(r.currRow), C.int(i))) == 1 {
			dest[i] = nil
			continue
		}
		val := C.GoString(C.PQgetvalue(r.res, C.int(r.currRow), C.int(i)))
		switch vtype := uint(C.PQftype(r.res, C.int(i))); vtype {
		case BOOLOID:
			if val == "t" {
				dest[i] = "true"
			} else {
				dest[i] = "false"
			}
		case BYTEAOID:
			if !strings.HasPrefix(val, "\\x") {
				return argErr(i, "[]byte", "invalid byte string format")
			}
			buf, err := hex.DecodeString(val[2:])
			if err != nil {
				return argErr(i, "[]byte", err.Error())
			}
			dest[i] = buf
		case CHAROID, BPCHAROID, VARCHAROID, TEXTOID,
			INT2OID, INT4OID, INT8OID, OIDOID, XIDOID,
			FLOAT8OID, FLOAT4OID,
			DATEOID, TIMEOID, TIMESTAMPOID, TIMESTAMPTZOID, INTERVALOID, TIMETZOID,
			NUMERICOID:
			dest[i] = val
		default:
			return errors.New(fmt.Sprintf("unsupported type oid: %d", vtype))
		}
	}
	return nil
}

func (r *driverRows) Close() error {
	if r.res != nil {
		C.PQclear(r.res)
		r.res = nil
		runtime.SetFinalizer(r, nil)
	}
	return nil
}

func buildCArgs(params []interface{}) **C.char {
	sparams := make([]string, len(params))
	for i, v := range params {
		var str string
		switch v := v.(type) {
		case []byte:
			str = "\\x" + hex.EncodeToString(v)
		case bool:
			if v {
				str = "t"
			} else {
				str = "f"
			}
		case time.Time:
			str = v.Format(timeFormat)
		default:
			str = fmt.Sprint(v)
		}

		sparams[i] = str
	}
	cparams := C.makeCharArray(C.int(len(sparams)))
	for i, s := range sparams {
		C.setArrayString(cparams, C.CString(s), C.int(i))
	}
	return cparams
}

func init() {
	sql.Register("postgres", &postgresDriver{})
}
<commit_msg>Doc update<commit_after>// Copyright 2011 John E. Barham. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.

// Package pgsqldriver is a PostgreSQL driver for the Go SQL database package.
package pgsqldriver

/*
#include <stdlib.h>
#include <libpq-fe.h>

static char**makeCharArray(int size) {
	return calloc(sizeof(char*), size);
}

static void setArrayString(char **a, char *s, int n) {
	a[n] = s;
}

static void freeCharArray(char **a, int size) {
	int i;
	for (i = 0; i < size; i++)
		free(a[i]);
	free(a);
}
*/
// #cgo CFLAGS: -I/usr/local/pgsql/include
// #cgo LDFLAGS: -L/usr/local/pgsql/lib -lpq
import "C"

import (
	"database/sql"
	"database/sql/driver"
	"encoding/hex"
	"errors"
	"fmt"
	"io"
	"runtime"
	"strconv"
	"strings"
	"time"
	"unsafe"
)

func connError(db *C.PGconn) error {
	return errors.New("conn error:" + C.GoString(C.PQerrorMessage(db)))
}

func resultError(res *C.PGresult) error {
	serr := C.GoString(C.PQresultErrorMessage(res))
	if serr == "" {
		return nil
	}
	return errors.New("result error: " + serr)
}

const timeFormat = "2006-01-02 15:04:05.000000-07"

type Date struct {
	time.Time
}

var _ sql.ScannerInto = (*Date)(nil)

func (d *Date) ScanInto(value interface{}) error {
	switch s := value.(type) {
	case string:
		t, err := time.Parse("2006-01-02", s)
		if err != nil {
			return err
		}
		d.Time = t
	default:
		return errors.New("invalid type")
	}
	return nil
}

type postgresDriver struct{}

// Open creates a new database connection using the given connection string.
// Each parameter setting is in the form 'keyword=value'.
// See http://www.postgresql.org/docs/9.0/static/libpq-connect.html#LIBPQ-PQCONNECTDBPARAMS
// for a list of recognized parameters.
func (d *postgresDriver) Open(name string) (conn driver.Conn, err error) {
	cparams := C.CString(name)
	defer C.free(unsafe.Pointer(cparams))
	db := C.PQconnectdb(cparams)
	if C.PQstatus(db) != C.CONNECTION_OK {
		err = connError(db)
		C.PQfinish(db)
		return nil, err
	}
	conn = &driverConn{db, 0}
	runtime.SetFinalizer(conn, (*driverConn).Close)
	return
}

type driverConn struct {
	db      *C.PGconn
	stmtNum int
}

// Check that driverConn implements driver.Execer interface.
var _ driver.Execer = (*driverConn)(nil)

func (c *driverConn) exec(stmt string, args []interface{}) (cres *C.PGresult) {
	stmtstr := C.CString(stmt)
	defer C.free(unsafe.Pointer(stmtstr))
	if len(args) == 0 {
		cres = C.PQexec(c.db, stmtstr)
	} else {
		cargs := buildCArgs(args)
		defer C.freeCharArray(cargs, C.int(len(args)))
		cres = C.PQexecParams(c.db, stmtstr, C.int(len(args)), nil, cargs, nil, nil, 0)
	}
	return cres
}

func (c *driverConn) Exec(query string, args []interface{}) (res driver.Result, err error) {
	cres := c.exec(query, args)
	if err = resultError(cres); err != nil {
		C.PQclear(cres)
		return
	}
	defer C.PQclear(cres)
	ns := C.GoString(C.PQcmdTuples(cres))
	if ns == "" {
		return driver.DDLSuccess, nil
	}
	rowsAffected, err := strconv.ParseInt(ns, 10, 64)
	if err != nil {
		return
	}
	return driver.RowsAffected(rowsAffected), nil
}

func (c *driverConn) Prepare(query string) (driver.Stmt, error) {
	// Generate unique statement name.
	stmtname := strconv.Itoa(c.stmtNum)
	cstmtname := C.CString(stmtname)
	c.stmtNum++
	defer C.free(unsafe.Pointer(cstmtname))
	stmtstr := C.CString(query)
	defer C.free(unsafe.Pointer(stmtstr))
	res := C.PQprepare(c.db, cstmtname, stmtstr, 0, nil)
	err := resultError(res)
	if err != nil {
		C.PQclear(res)
		return nil, err
	}
	stmtinfo := C.PQdescribePrepared(c.db, cstmtname)
	err = resultError(stmtinfo)
	if err != nil {
		C.PQclear(stmtinfo)
		return nil, err
	}
	defer C.PQclear(stmtinfo)
	nparams := int(C.PQnparams(stmtinfo))
	statement := &driverStmt{stmtname, c.db, res, nparams}
	runtime.SetFinalizer(statement, (*driverStmt).Close)
	return statement, nil
}

func (c *driverConn) Close() error {
	if c != nil && c.db != nil {
		C.PQfinish(c.db)
		c.db = nil
		runtime.SetFinalizer(c, nil)
	}
	return nil
}

func (c *driverConn) Begin() (driver.Tx, error) {
	if _, err := c.Exec("BEGIN", nil); err != nil {
		return nil, err
	}
	// driverConn implements driver.Tx interface.
	return c, nil
}

func (c *driverConn) Commit() (err error) {
	_, err = c.Exec("COMMIT", nil)
	return
}

func (c *driverConn) Rollback() (err error) {
	_, err = c.Exec("ROLLBACK", nil)
	return
}

type driverStmt struct {
	name    string
	db      *C.PGconn
	res     *C.PGresult
	nparams int
}

func (s *driverStmt) NumInput() int {
	return s.nparams
}

func (s *driverStmt) exec(params []interface{}) *C.PGresult {
	stmtName := C.CString(s.name)
	defer C.free(unsafe.Pointer(stmtName))
	cparams := buildCArgs(params)
	defer C.freeCharArray(cparams, C.int(len(params)))
	return C.PQexecPrepared(s.db, stmtName, C.int(len(params)), cparams, nil, nil, 0)
}

func (s *driverStmt) Exec(args []interface{}) (res driver.Result, err error) {
	cres := s.exec(args)
	if err = resultError(cres); err != nil {
		C.PQclear(cres)
		return
	}
	defer C.PQclear(cres)
	rowsAffected, err := strconv.ParseInt(C.GoString(C.PQcmdTuples(cres)), 10, 64)
	if err != nil {
		return
	}
	return driver.RowsAffected(rowsAffected), nil
}

func (s *driverStmt) Query(args []interface{}) (driver.Rows, error) {
	cres := s.exec(args)
	if err := resultError(cres); err != nil {
		C.PQclear(cres)
		return nil, err
	}
	return newResult(cres), nil
}

func (s *driverStmt) Close() error {
	if s != nil && s.res != nil {
		C.PQclear(s.res)
		runtime.SetFinalizer(s, nil)
	}
	return nil
}

type driverRows struct {
	res     *C.PGresult
	nrows   int
	currRow int
	ncols   int
	cols    []string
}

func newResult(res *C.PGresult) *driverRows {
	ncols := int(C.PQnfields(res))
	nrows := int(C.PQntuples(res))
	result := &driverRows{res: res, nrows: nrows, currRow: -1, ncols: ncols, cols: nil}
	runtime.SetFinalizer(result, (*driverRows).Close)
	return result
}

func (r *driverRows) Columns() []string {
	if r.cols == nil {
		r.cols = make([]string, r.ncols)
		for i := 0; i < r.ncols; i++ {
			r.cols[i] = C.GoString(C.PQfname(r.res, C.int(i)))
		}
	}
	return r.cols
}

func argErr(i int, argType string, err string) error {
	return errors.New(fmt.Sprintf("arg %d as %s: %s", i, argType, err))
}

func (r *driverRows) Next(dest []interface{}) error {
	r.currRow++
	if r.currRow >= r.nrows {
		return io.EOF
	}

	for i := 0; i < len(dest); i++ {
		if int(C.PQgetisnull(r.res, C.int(r.currRow), C.int(i))) == 1 {
			dest[i] = nil
			continue
		}
		val := C.GoString(C.PQgetvalue(r.res, C.int(r.currRow), C.int(i)))
		switch vtype := uint(C.PQftype(r.res, C.int(i))); vtype {
		case BOOLOID:
			if val == "t" {
				dest[i] = "true"
			} else {
				dest[i] = "false"
			}
		case BYTEAOID:
			if !strings.HasPrefix(val, "\\x") {
				return argErr(i, "[]byte", "invalid byte string format")
			}
			buf, err := hex.DecodeString(val[2:])
			if err != nil {
				return argErr(i, "[]byte", err.Error())
			}
			dest[i] = buf
		case CHAROID, BPCHAROID, VARCHAROID, TEXTOID,
			INT2OID, INT4OID, INT8OID, OIDOID, XIDOID,
			FLOAT8OID, FLOAT4OID,
			DATEOID, TIMEOID, TIMESTAMPOID, TIMESTAMPTZOID, INTERVALOID, TIMETZOID,
			NUMERICOID:
			dest[i] = val
		default:
			return errors.New(fmt.Sprintf("unsupported type oid: %d", vtype))
		}
	}
	return nil
}

func (r *driverRows) Close() error {
	if r.res != nil {
		C.PQclear(r.res)
		r.res = nil
		runtime.SetFinalizer(r, nil)
	}
	return nil
}

func buildCArgs(params []interface{}) **C.char {
	sparams := make([]string, len(params))
	for i, v := range params {
		var str string
		switch v := v.(type) {
		case []byte:
			str = "\\x" + hex.EncodeToString(v)
		case bool:
			if v {
				str = "t"
			} else {
				str = "f"
			}
		case time.Time:
			str = v.Format(timeFormat)
		default:
			str = fmt.Sprint(v)
		}

		sparams[i] = str
	}
	cparams := C.makeCharArray(C.int(len(sparams)))
	for i, s := range sparams {
		C.setArrayString(cparams, C.CString(s), C.int(i))
	}
	return cparams
}

func init() {
	sql.Register("postgres", &postgresDriver{})
}
<|endoftext|>


<commit_before>package main

import (
	"context"

	"os/exec"
	"strings"
	"time"

	log "github.com/Sirupsen/logrus"
)

func execId(timeout int) string {
	ctx, cancel := context.WithTimeout(context.Background(), time.Duration(timeout)*time.Second)
	defer cancel()

	output, err := exec.CommandContext(ctx, "id", "-u", "-n").Output()
	if err != nil {
		log.Fatalf("id -u -n failed %s", err.Error())
	}
	return strings.Replace(string(output), "\n", "", -1)
}

func execPgStop(timeout int) {
	ctx, cancel := context.WithTimeout(context.Background(), time.Duration(timeout)*time.Second)
	defer cancel()

	if err := exec.CommandContext(ctx, "service", "postgresql", "stop").Run(); err != nil {
		log.Fatalf("service postgres stop failed %s", err.Error())
	}
}

func execRepmgrPromote(timeout int) {
	ctx, cancel := context.WithTimeout(context.Background(), time.Duration(timeout)*time.Second)
	defer cancel()

	if err := exec.CommandContext(ctx, "repmgr", "standby", "promote").Run(); err != nil {
		log.Warningf("repmgr standby promote failed %s", err.Error())
	} else {
		return
	}

	if err := exec.CommandContext(ctx, "repmgr", "standby", "promote").Run(); err != nil {
		log.Warningf("repmgr standby promote failed %s", err.Error())
		log.Info("trying repmgr standby switchover")
		execRepmgrSwitchover(timeout)
	}
}

func execRepmgrSwitchover(timeout int) {
	ctx, cancel := context.WithTimeout(context.Background(), time.Duration(timeout)*time.Second)
	defer cancel()

	if err := exec.CommandContext(ctx, "repmgr", "standby", "switchover").Run(); err != nil {
		log.Fatalf("repmgr standby switchover failed %s", err.Error())
	}
}

func execRepmgrVersion(timeout int) {
	ctx, cancel := context.WithTimeout(context.Background(), time.Duration(timeout)*time.Second)
	defer cancel()

	output, err := exec.CommandContext(ctx, "repmgr", "-V").Output()
	if err != nil {
		log.Fatalf("repmgr -V failed %s", err.Error())
	}
	log.Info(strings.Replace(string(output), "\n", "", -1))
}
<commit_msg>don't block on switchover<commit_after>package main

import (
	"context"

	"os/exec"
	"strings"
	"time"

	log "github.com/Sirupsen/logrus"
)

func execId(timeout int) string {
	ctx, cancel := context.WithTimeout(context.Background(), time.Duration(timeout)*time.Second)
	defer cancel()

	output, err := exec.CommandContext(ctx, "id", "-u", "-n").Output()
	if err != nil {
		log.Fatalf("id -u -n failed %s", err.Error())
	}
	return strings.Replace(string(output), "\n", "", -1)
}

func execPgStop(timeout int) {
	ctx, cancel := context.WithTimeout(context.Background(), time.Duration(timeout)*time.Second)
	defer cancel()

	if err := exec.CommandContext(ctx, "service", "postgresql", "stop").Run(); err != nil {
		log.Fatalf("service postgres stop failed %s", err.Error())
	}
}

func execRepmgrPromote(timeout int) {
	ctx, cancel := context.WithTimeout(context.Background(), time.Duration(timeout)*time.Second)
	defer cancel()

	if err := exec.CommandContext(ctx, "repmgr", "standby", "promote").Run(); err != nil {
		log.Warningf("repmgr standby promote failed %s", err.Error())
	} else {
		return
	}

	if err := exec.CommandContext(ctx, "repmgr", "standby", "promote").Run(); err != nil {
		log.Warningf("repmgr standby promote failed %s", err.Error())
		log.Info("trying repmgr standby switchover")
		go execRepmgrSwitchover()
	}
}

func execRepmgrSwitchover() {

	if err := exec.Command("repmgr", "standby", "switchover").Run(); err != nil {
		log.Warningf("repmgr standby switchover failed %s", err.Error())
	}
}

func execRepmgrVersion(timeout int) {
	ctx, cancel := context.WithTimeout(context.Background(), time.Duration(timeout)*time.Second)
	defer cancel()

	output, err := exec.CommandContext(ctx, "repmgr", "-V").Output()
	if err != nil {
		log.Fatalf("repmgr -V failed %s", err.Error())
	}
	log.Info(strings.Replace(string(output), "\n", "", -1))
}
<|endoftext|>


<commit_before>package main

import (
	"fmt"
	"io/ioutil"
	"os"
	"strings"

	"qlang.io/qlang.v2/qlang"
	"qlang.io/qlang/terminal"

	qspec "qlang.io/qlang.spec.v1"
	qipt "qlang.io/qlang.v2/interpreter"
	qall "qlang.io/qlang/qlang.all"
)

var (
	historyFile = os.Getenv("HOME") + "/.qlang.history"
)

func main() {
	qall.InitSafe(false)
	qlang.Import("", qipt.Exports)
	qlang.SetDumpCode(os.Getenv("QLANG_DUMPCODE"))

	libs := os.Getenv("QLANG_PATH")
	if libs == "" {
		libs = os.Getenv("HOME") + "/qlang"
	}

	lang, err := qlang.New(qlang.InsertSemis)
	if err != nil {
		fmt.Fprintln(os.Stderr, err)
		os.Exit(1)
	}
	lang.SetLibs(libs)

	// exec source
	if len(os.Args) > 1 {
		fname := os.Args[1]
		b, err := ioutil.ReadFile(fname)
		if err != nil {
			fmt.Fprintln(os.Stderr, err)
			os.Exit(2)
		}
		err = lang.SafeExec(b, fname)
		if err != nil {
			fmt.Fprintln(os.Stderr, err)
			os.Exit(3)
		}
		return
	}

	// interpreter
	qall.Copyright()

	var ret interface{}
	qlang.SetOnPop(func(v interface{}) {
		ret = v
	})

	term := terminal.New()
	term.LoadHistroy(historyFile) // load/save histroy
	defer term.SaveHistroy(historyFile)

	fnReadMore := func(expr string, line string) (string, bool) { // read more line check
		if strings.HasSuffix(line, "\\") {
			return expr + line[:len(line)-1], true
		}
		return expr + line + "\n", false
	}

	for {
		expr, err := term.Scan(">>> ", fnReadMore)
		if err != nil {
			if err == terminal.ErrPromptAborted {
				break
			}
			fmt.Fprintln(os.Stderr, err)
			continue
		}
		expr = strings.TrimSpace(expr)
		if expr == "" {
			continue
		}
		ret = qspec.Undefined
		err = lang.SafeEval(expr)
		if err != nil {
			fmt.Println(strings.TrimSpace(err.Error()))
			continue
		}
		if ret != qspec.Undefined {
			fmt.Println(ret)
		}
	}
}

// -----------------------------------------------------------------------------
<commit_msg>qexport ^C abort input, ^D empty input for exit<commit_after>package main

import (
	"fmt"
	"io"
	"io/ioutil"
	"os"
	"strings"

	"qlang.io/qlang.v2/qlang"
	"qlang.io/qlang/terminal"

	qspec "qlang.io/qlang.spec.v1"
	qipt "qlang.io/qlang.v2/interpreter"
	qall "qlang.io/qlang/qlang.all"
)

var (
	historyFile = os.Getenv("HOME") + "/.qlang.history"
)

func main() {
	qall.InitSafe(false)
	qlang.Import("", qipt.Exports)
	qlang.SetDumpCode(os.Getenv("QLANG_DUMPCODE"))

	libs := os.Getenv("QLANG_PATH")
	if libs == "" {
		libs = os.Getenv("HOME") + "/qlang"
	}

	lang, err := qlang.New(qlang.InsertSemis)
	if err != nil {
		fmt.Fprintln(os.Stderr, err)
		os.Exit(1)
	}
	lang.SetLibs(libs)

	// exec source
	if len(os.Args) > 1 {
		fname := os.Args[1]
		b, err := ioutil.ReadFile(fname)
		if err != nil {
			fmt.Fprintln(os.Stderr, err)
			os.Exit(2)
		}
		err = lang.SafeExec(b, fname)
		if err != nil {
			fmt.Fprintln(os.Stderr, err)
			os.Exit(3)
		}
		return
	}

	// interpreter
	qall.Copyright()

	var ret interface{}
	qlang.SetOnPop(func(v interface{}) {
		ret = v
	})

	term := terminal.New()
	term.LoadHistroy(historyFile) // load/save histroy
	defer term.SaveHistroy(historyFile)

	fnReadMore := func(expr string, line string) (string, bool) { // read more line check
		if strings.HasSuffix(line, "\\") {
			return expr + line[:len(line)-1], true
		}
		return expr + line + "\n", false
	}

	for {
		expr, err := term.Scan(">>> ", fnReadMore)
		if err != nil {
			if err == terminal.ErrPromptAborted {
				fmt.Println("Aborted")
				continue
			} else if err == io.EOF {
				break
			}
			fmt.Fprintln(os.Stderr, err)
			continue
		}
		expr = strings.TrimSpace(expr)
		if expr == "" {
			continue
		}
		ret = qspec.Undefined
		err = lang.SafeEval(expr)
		if err != nil {
			fmt.Println(strings.TrimSpace(err.Error()))
			continue
		}
		if ret != qspec.Undefined {
			fmt.Println(ret)
		}
	}
}

// -----------------------------------------------------------------------------
<|endoftext|>


<commit_before>package arduino

import (
	"github.com/FraBle/WikidataQuiz/config"
	"github.com/distributed/sers"
	"log"
)

func SetColor(color string) (err error) {
	s, err := sers.Open(config.CONFIG.ComPort)
	if err != nil {
		log.Printf("Error connecting to Arduino: %v", err)
		return
	}
	_, err = s.Write([]byte(color))
	if err != nil {
		log.Printf("Error setting LED to green: %v", err)
	}
	s.Close()
	return
}
<commit_msg>better error messages for arduino connection<commit_after>package arduino

import (
	// standard library
	"fmt"
	"log"

	// external packages
	"github.com/distributed/sers"

	// internal packages
	"github.com/FraBle/WikidataQuiz/config"
)

func SetColor(color string) (err error) {
	s, err := sers.Open(config.CONFIG.ComPort)
	if err != nil {
		log.Printf("Error connecting to Arduino: %v", err)
		err = fmt.Errorf("Error connecting to Arduino: %v", err)
		return
	}
	_, err = s.Write([]byte(color))
	if err != nil {
		log.Printf("Error setting LED color: %v", err)
		err = fmt.Errorf("Error setting LED color: %v", err)
	}
	s.Close()
	return
}
<|endoftext|>


<commit_before>// Copyright 2012-present Oliver Eilhard. All rights reserved.
// Use of this source code is governed by a MIT-license.
// See http://olivere.mit-license.org/license.txt for details.

package elastic

import (
	"encoding/json"
	"testing"
)

func TestSearchSourceMatchAllQuery(t *testing.T) {
	matchAllQ := NewMatchAllQuery()
	builder := NewSearchSource().Query(matchAllQ)
	src, err := builder.Source()
	if err != nil {
		t.Fatal(err)
	}
	data, err := json.Marshal(src)
	if err != nil {
		t.Fatalf("marshaling to JSON failed: %v", err)
	}
	got := string(data)
	expected := `{"query":{"match_all":{}}}`
	if got != expected {
		t.Errorf("expected\n%s\n,got:\n%s", expected, got)
	}
}

func TestSearchSourceNoStoredFields(t *testing.T) {
	matchAllQ := NewMatchAllQuery()
	builder := NewSearchSource().Query(matchAllQ).NoStoredFields()
	src, err := builder.Source()
	if err != nil {
		t.Fatal(err)
	}
	data, err := json.Marshal(src)
	if err != nil {
		t.Fatalf("marshaling to JSON failed: %v", err)
	}
	got := string(data)
	expected := `{"query":{"match_all":{}}}`
	if got != expected {
		t.Errorf("expected\n%s\n,got:\n%s", expected, got)
	}
}

func TestSearchSourceStoredFields(t *testing.T) {
	matchAllQ := NewMatchAllQuery()
	builder := NewSearchSource().Query(matchAllQ).StoredFields("message", "tags")
	src, err := builder.Source()
	if err != nil {
		t.Fatal(err)
	}
	data, err := json.Marshal(src)
	if err != nil {
		t.Fatalf("marshaling to JSON failed: %v", err)
	}
	got := string(data)
	expected := `{"query":{"match_all":{}},"stored_fields":["message","tags"]}`
	if got != expected {
		t.Errorf("expected\n%s\n,got:\n%s", expected, got)
	}
}

func TestSearchSourceFetchSourceDisabled(t *testing.T) {
	matchAllQ := NewMatchAllQuery()
	builder := NewSearchSource().Query(matchAllQ).FetchSource(false)
	src, err := builder.Source()
	if err != nil {
		t.Fatal(err)
	}
	data, err := json.Marshal(src)
	if err != nil {
		t.Fatalf("marshaling to JSON failed: %v", err)
	}
	got := string(data)
	expected := `{"_source":false,"query":{"match_all":{}}}`
	if got != expected {
		t.Errorf("expected\n%s\n,got:\n%s", expected, got)
	}
}

func TestSearchSourceFetchSourceByWildcards(t *testing.T) {
	matchAllQ := NewMatchAllQuery()
	fsc := NewFetchSourceContext(true).Include("obj1.*", "obj2.*").Exclude("*.description")
	builder := NewSearchSource().Query(matchAllQ).FetchSourceContext(fsc)
	src, err := builder.Source()
	if err != nil {
		t.Fatal(err)
	}
	data, err := json.Marshal(src)
	if err != nil {
		t.Fatalf("marshaling to JSON failed: %v", err)
	}
	got := string(data)
	expected := `{"_source":{"excludes":["*.description"],"includes":["obj1.*","obj2.*"]},"query":{"match_all":{}}}`
	if got != expected {
		t.Errorf("expected\n%s\n,got:\n%s", expected, got)
	}
}

func TestSearchSourceDocvalueFields(t *testing.T) {
	matchAllQ := NewMatchAllQuery()
	builder := NewSearchSource().Query(matchAllQ).DocvalueFields("test1", "test2")
	src, err := builder.Source()
	if err != nil {
		t.Fatal(err)
	}
	data, err := json.Marshal(src)
	if err != nil {
		t.Fatalf("marshaling to JSON failed: %v", err)
	}
	got := string(data)
	expected := `{"docvalue_fields":["test1","test2"],"query":{"match_all":{}}}`
	if got != expected {
		t.Errorf("expected\n%s\n,got:\n%s", expected, got)
	}
}

func TestSearchSourceScriptFields(t *testing.T) {
	matchAllQ := NewMatchAllQuery()
	sf1 := NewScriptField("test1", NewScript("doc['my_field_name'].value * 2"))
	sf2 := NewScriptField("test2", NewScript("doc['my_field_name'].value * factor").Param("factor", 3.1415927))
	builder := NewSearchSource().Query(matchAllQ).ScriptFields(sf1, sf2)
	src, err := builder.Source()
	if err != nil {
		t.Fatal(err)
	}
	data, err := json.Marshal(src)
	if err != nil {
		t.Fatalf("marshaling to JSON failed: %v", err)
	}
	got := string(data)
	expected := `{"query":{"match_all":{}},"script_fields":{"test1":{"script":"doc['my_field_name'].value * 2"},"test2":{"script":{"inline":"doc['my_field_name'].value * factor","params":{"factor":3.1415927}}}}}`
	if got != expected {
		t.Errorf("expected\n%s\n,got:\n%s", expected, got)
	}
}

func TestSearchSourcePostFilter(t *testing.T) {
	matchAllQ := NewMatchAllQuery()
	pf := NewTermQuery("tag", "important")
	builder := NewSearchSource().Query(matchAllQ).PostFilter(pf)
	src, err := builder.Source()
	if err != nil {
		t.Fatal(err)
	}
	data, err := json.Marshal(src)
	if err != nil {
		t.Fatalf("marshaling to JSON failed: %v", err)
	}
	got := string(data)
	expected := `{"post_filter":{"term":{"tag":"important"}},"query":{"match_all":{}}}`
	if got != expected {
		t.Errorf("expected\n%s\n,got:\n%s", expected, got)
	}
}

func TestSearchSourceHighlight(t *testing.T) {
	matchAllQ := NewMatchAllQuery()
	hl := NewHighlight().Field("content")
	builder := NewSearchSource().Query(matchAllQ).Highlight(hl)
	src, err := builder.Source()
	if err != nil {
		t.Fatal(err)
	}
	data, err := json.Marshal(src)
	if err != nil {
		t.Fatalf("marshaling to JSON failed: %v", err)
	}
	got := string(data)
	expected := `{"highlight":{"fields":{"content":{}}},"query":{"match_all":{}}}`
	if got != expected {
		t.Errorf("expected\n%s\n,got:\n%s", expected, got)
	}
}

func TestSearchSourceRescoring(t *testing.T) {
	matchAllQ := NewMatchAllQuery()
	rescorerQuery := NewMatchQuery("field1", "the quick brown fox").Type("phrase").Slop(2)
	rescorer := NewQueryRescorer(rescorerQuery)
	rescorer = rescorer.QueryWeight(0.7)
	rescorer = rescorer.RescoreQueryWeight(1.2)
	rescore := NewRescore().WindowSize(50).Rescorer(rescorer)
	builder := NewSearchSource().Query(matchAllQ).Rescorer(rescore)
	src, err := builder.Source()
	if err != nil {
		t.Fatal(err)
	}
	data, err := json.Marshal(src)
	if err != nil {
		t.Fatalf("marshaling to JSON failed: %v", err)
	}
	got := string(data)
	expected := `{"query":{"match_all":{}},"rescore":{"query":{"query_weight":0.7,"rescore_query":{"match":{"field1":{"query":"the quick brown fox","slop":2,"type":"phrase"}}},"rescore_query_weight":1.2},"window_size":50}}`
	if got != expected {
		t.Errorf("expected\n%s\n,got:\n%s", expected, got)
	}
}

func TestSearchSourceIndexBoost(t *testing.T) {
	matchAllQ := NewMatchAllQuery()
	builder := NewSearchSource().Query(matchAllQ).IndexBoost("index1", 1.4).IndexBoost("index2", 1.3)
	src, err := builder.Source()
	if err != nil {
		t.Fatal(err)
	}
	data, err := json.Marshal(src)
	if err != nil {
		t.Fatalf("marshaling to JSON failed: %v", err)
	}
	got := string(data)
	expected := `{"indices_boost":{"index1":1.4,"index2":1.3},"query":{"match_all":{}}}`
	if got != expected {
		t.Errorf("expected\n%s\n,got:\n%s", expected, got)
	}
}

func TestSearchSourceMixDifferentSorters(t *testing.T) {
	matchAllQ := NewMatchAllQuery()
	builder := NewSearchSource().Query(matchAllQ).
		Sort("a", false).
		SortWithInfo(SortInfo{Field: "b", Ascending: true}).
		SortBy(NewScriptSort(NewScript("doc['field_name'].value * factor").Param("factor", 1.1), "number"))
	src, err := builder.Source()
	if err != nil {
		t.Fatal(err)
	}
	data, err := json.Marshal(src)
	if err != nil {
		t.Fatalf("marshaling to JSON failed: %v", err)
	}
	got := string(data)
	expected := `{"query":{"match_all":{}},"sort":[{"a":{"order":"desc"}},{"b":{"order":"asc"}},{"_script":{"order":"asc","script":{"inline":"doc['field_name'].value * factor","params":{"factor":1.1}},"type":"number"}}]}`
	if got != expected {
		t.Errorf("expected\n%s\n,got:\n%s", expected, got)
	}
}

func TestSearchSourceInnerHits(t *testing.T) {
	matchAllQ := NewMatchAllQuery()
	builder := NewSearchSource().Query(matchAllQ).
		InnerHit("comments", NewInnerHit().Type("comment").Query(NewMatchQuery("user", "olivere"))).
		InnerHit("views", NewInnerHit().Path("view"))
	src, err := builder.Source()
	if err != nil {
		t.Fatal(err)
	}
	data, err := json.Marshal(src)
	if err != nil {
		t.Fatalf("marshaling to JSON failed: %v", err)
	}
	got := string(data)
	expected := `{"inner_hits":{"comments":{"type":{"comment":{"query":{"match":{"user":{"query":"olivere"}}}}}},"views":{"path":{"view":{}}}},"query":{"match_all":{}}}`
	if got != expected {
		t.Errorf("expected\n%s\n,got:\n%s", expected, got)
	}
}

func TestSearchSourceSearchAfter(t *testing.T) {
	matchAllQ := NewMatchAllQuery()
	builder := NewSearchSource().Query(matchAllQ).SearchAfter(1463538857, "tweet#654323")
	src, err := builder.Source()
	if err != nil {
		t.Fatal(err)
	}
	data, err := json.Marshal(src)
	if err != nil {
		t.Fatalf("marshaling to JSON failed: %v", err)
	}
	got := string(data)
	expected := `{"query":{"match_all":{}},"search_after":[1463538857,"tweet#654323"]}`
	if got != expected {
		t.Errorf("expected\n%s\n,got:\n%s", expected, got)
	}
}
<commit_msg> unit test for search source<commit_after>// Copyright 2012-present Oliver Eilhard. All rights reserved.
// Use of this source code is governed by a MIT-license.
// See http://olivere.mit-license.org/license.txt for details.

package elastic

import (
	"encoding/json"
	"testing"
)

func TestSearchSourceMatchAllQuery(t *testing.T) {
	matchAllQ := NewMatchAllQuery()
	builder := NewSearchSource().Query(matchAllQ)
	src, err := builder.Source()
	if err != nil {
		t.Fatal(err)
	}
	data, err := json.Marshal(src)
	if err != nil {
		t.Fatalf("marshaling to JSON failed: %v", err)
	}
	got := string(data)
	expected := `{"query":{"match_all":{}}}`
	if got != expected {
		t.Errorf("expected\n%s\n,got:\n%s", expected, got)
	}
}

func TestSearchSourceNoStoredFields(t *testing.T) {
	matchAllQ := NewMatchAllQuery()
	builder := NewSearchSource().Query(matchAllQ).NoStoredFields()
	src, err := builder.Source()
	if err != nil {
		t.Fatal(err)
	}
	data, err := json.Marshal(src)
	if err != nil {
		t.Fatalf("marshaling to JSON failed: %v", err)
	}
	got := string(data)
	expected := `{"query":{"match_all":{}}}`
	if got != expected {
		t.Errorf("expected\n%s\n,got:\n%s", expected, got)
	}
}

func TestSearchSourceStoredFields(t *testing.T) {
	matchAllQ := NewMatchAllQuery()
	builder := NewSearchSource().Query(matchAllQ).StoredFields("message", "tags")
	src, err := builder.Source()
	if err != nil {
		t.Fatal(err)
	}
	data, err := json.Marshal(src)
	if err != nil {
		t.Fatalf("marshaling to JSON failed: %v", err)
	}
	got := string(data)
	expected := `{"query":{"match_all":{}},"stored_fields":["message","tags"]}`
	if got != expected {
		t.Errorf("expected\n%s\n,got:\n%s", expected, got)
	}
}

func TestSearchSourceFetchSourceDisabled(t *testing.T) {
	matchAllQ := NewMatchAllQuery()
	builder := NewSearchSource().Query(matchAllQ).FetchSource(false)
	src, err := builder.Source()
	if err != nil {
		t.Fatal(err)
	}
	data, err := json.Marshal(src)
	if err != nil {
		t.Fatalf("marshaling to JSON failed: %v", err)
	}
	got := string(data)
	expected := `{"_source":false,"query":{"match_all":{}}}`
	if got != expected {
		t.Errorf("expected\n%s\n,got:\n%s", expected, got)
	}
}

func TestSearchSourceFetchSourceByWildcards(t *testing.T) {
	matchAllQ := NewMatchAllQuery()
	fsc := NewFetchSourceContext(true).Include("obj1.*", "obj2.*").Exclude("*.description")
	builder := NewSearchSource().Query(matchAllQ).FetchSourceContext(fsc)
	src, err := builder.Source()
	if err != nil {
		t.Fatal(err)
	}
	data, err := json.Marshal(src)
	if err != nil {
		t.Fatalf("marshaling to JSON failed: %v", err)
	}
	got := string(data)
	expected := `{"_source":{"excludes":["*.description"],"includes":["obj1.*","obj2.*"]},"query":{"match_all":{}}}`
	if got != expected {
		t.Errorf("expected\n%s\n,got:\n%s", expected, got)
	}
}

func TestSearchSourceDocvalueFields(t *testing.T) {
	matchAllQ := NewMatchAllQuery()
	builder := NewSearchSource().Query(matchAllQ).DocvalueFields("test1", "test2")
	src, err := builder.Source()
	if err != nil {
		t.Fatal(err)
	}
	data, err := json.Marshal(src)
	if err != nil {
		t.Fatalf("marshaling to JSON failed: %v", err)
	}
	got := string(data)
	expected := `{"docvalue_fields":["test1","test2"],"query":{"match_all":{}}}`
	if got != expected {
		t.Errorf("expected\n%s\n,got:\n%s", expected, got)
	}
}

func TestSearchSourceScriptFields(t *testing.T) {
	matchAllQ := NewMatchAllQuery()
	sf1 := NewScriptField("test1", NewScript("doc['my_field_name'].value * 2"))
	sf2 := NewScriptField("test2", NewScript("doc['my_field_name'].value * factor").Param("factor", 3.1415927))
	builder := NewSearchSource().Query(matchAllQ).ScriptFields(sf1, sf2)
	src, err := builder.Source()
	if err != nil {
		t.Fatal(err)
	}
	data, err := json.Marshal(src)
	if err != nil {
		t.Fatalf("marshaling to JSON failed: %v", err)
	}
	got := string(data)
	expected := `{"query":{"match_all":{}},"script_fields":{"test1":{"script":"doc['my_field_name'].value * 2"},"test2":{"script":{"inline":"doc['my_field_name'].value * factor","params":{"factor":3.1415927}}}}}`
	if got != expected {
		t.Errorf("expected\n%s\n,got:\n%s", expected, got)
	}
}

func TestSearchSourcePostFilter(t *testing.T) {
	matchAllQ := NewMatchAllQuery()
	pf := NewTermQuery("tag", "important")
	builder := NewSearchSource().Query(matchAllQ).PostFilter(pf)
	src, err := builder.Source()
	if err != nil {
		t.Fatal(err)
	}
	data, err := json.Marshal(src)
	if err != nil {
		t.Fatalf("marshaling to JSON failed: %v", err)
	}
	got := string(data)
	expected := `{"post_filter":{"term":{"tag":"important"}},"query":{"match_all":{}}}`
	if got != expected {
		t.Errorf("expected\n%s\n,got:\n%s", expected, got)
	}
}

func TestSearchSourceHighlight(t *testing.T) {
	matchAllQ := NewMatchAllQuery()
	hl := NewHighlight().Field("content")
	builder := NewSearchSource().Query(matchAllQ).Highlight(hl)
	src, err := builder.Source()
	if err != nil {
		t.Fatal(err)
	}
	data, err := json.Marshal(src)
	if err != nil {
		t.Fatalf("marshaling to JSON failed: %v", err)
	}
	got := string(data)
	expected := `{"highlight":{"fields":{"content":{}}},"query":{"match_all":{}}}`
	if got != expected {
		t.Errorf("expected\n%s\n,got:\n%s", expected, got)
	}
}

func TestSearchSourceRescoring(t *testing.T) {
	matchAllQ := NewMatchAllQuery()
	rescorerQuery := NewMatchQuery("field1", "the quick brown fox").Type("phrase").Slop(2)
	rescorer := NewQueryRescorer(rescorerQuery)
	rescorer = rescorer.QueryWeight(0.7)
	rescorer = rescorer.RescoreQueryWeight(1.2)
	rescore := NewRescore().WindowSize(50).Rescorer(rescorer)
	builder := NewSearchSource().Query(matchAllQ).Rescorer(rescore)
	src, err := builder.Source()
	if err != nil {
		t.Fatal(err)
	}
	data, err := json.Marshal(src)
	if err != nil {
		t.Fatalf("marshaling to JSON failed: %v", err)
	}
	got := string(data)
	expected := `{"query":{"match_all":{}},"rescore":{"query":{"query_weight":0.7,"rescore_query":{"match":{"field1":{"query":"the quick brown fox","slop":2,"type":"phrase"}}},"rescore_query_weight":1.2},"window_size":50}}`
	if got != expected {
		t.Errorf("expected\n%s\n,got:\n%s", expected, got)
	}
}

func TestSearchSourceIndexBoost(t *testing.T) {
	matchAllQ := NewMatchAllQuery()
	builder := NewSearchSource().Query(matchAllQ).IndexBoost("index1", 1.4).IndexBoost("index2", 1.3)
	src, err := builder.Source()
	if err != nil {
		t.Fatal(err)
	}
	data, err := json.Marshal(src)
	if err != nil {
		t.Fatalf("marshaling to JSON failed: %v", err)
	}
	got := string(data)
	expected := `{"indices_boost":{"index1":1.4,"index2":1.3},"query":{"match_all":{}}}`
	if got != expected {
		t.Errorf("expected\n%s\n,got:\n%s", expected, got)
	}
}

func TestSearchSourceMixDifferentSorters(t *testing.T) {
	matchAllQ := NewMatchAllQuery()
	builder := NewSearchSource().Query(matchAllQ).
		Sort("a", false).
		SortWithInfo(SortInfo{Field: "b", Ascending: true}).
		SortBy(NewScriptSort(NewScript("doc['field_name'].value * factor").Param("factor", 1.1), "number"))
	src, err := builder.Source()
	if err != nil {
		t.Fatal(err)
	}
	data, err := json.Marshal(src)
	if err != nil {
		t.Fatalf("marshaling to JSON failed: %v", err)
	}
	got := string(data)
	expected := `{"query":{"match_all":{}},"sort":[{"a":{"order":"desc"}},{"b":{"order":"asc"}},{"_script":{"order":"asc","script":{"inline":"doc['field_name'].value * factor","params":{"factor":1.1}},"type":"number"}}]}`
	if got != expected {
		t.Errorf("expected\n%s\n,got:\n%s", expected, got)
	}
}

func TestSearchSourceInnerHits(t *testing.T) {
	matchAllQ := NewMatchAllQuery()
	builder := NewSearchSource().Query(matchAllQ).
		InnerHit("comments", NewInnerHit().Type("comment").Query(NewMatchQuery("user", "olivere"))).
		InnerHit("views", NewInnerHit().Path("view"))
	src, err := builder.Source()
	if err != nil {
		t.Fatal(err)
	}
	data, err := json.Marshal(src)
	if err != nil {
		t.Fatalf("marshaling to JSON failed: %v", err)
	}
	got := string(data)
	expected := `{"inner_hits":{"comments":{"type":{"comment":{"query":{"match":{"user":{"query":"olivere"}}}}}},"views":{"path":{"view":{}}}},"query":{"match_all":{}}}`
	if got != expected {
		t.Errorf("expected\n%s\n,got:\n%s", expected, got)
	}
}

func TestSearchSourceSearchAfter(t *testing.T) {
	matchAllQ := NewMatchAllQuery()
	builder := NewSearchSource().Query(matchAllQ).SearchAfter(1463538857, "tweet#654323")
	src, err := builder.Source()
	if err != nil {
		t.Fatal(err)
	}
	data, err := json.Marshal(src)
	if err != nil {
		t.Fatalf("marshaling to JSON failed: %v", err)
	}
	got := string(data)
	expected := `{"query":{"match_all":{}},"search_after":[1463538857,"tweet#654323"]}`
	if got != expected {
		t.Errorf("expected\n%s\n,got:\n%s", expected, got)
	}
}

func TestSearchSourceProfiledQuery(t *testing.T) {
	matchAllQ := NewMatchAllQuery()
	builder := NewSearchSource().Query(matchAllQ).Profile(true)
	src, err := builder.Source()
	if err != nil {
		t.Fatal(err)
	}
	data, err := json.Marshal(src)
	if err != nil {
		t.Fatalf("marshaling to JSON failed: %v", err)
	}
	got := string(data)
	expected := `{"profile":true,"query":{"match_all":{}}}`
	if got != expected {
		t.Errorf("expected\n%s\n,got:\n%s", expected, got)
	}
}
<|endoftext|>