<commit_before>package js

import (
	"errors"
	"fmt"
	"strings"
	"testing"

	"github.com/orktes/orlang/ast"
	"github.com/orktes/orlang/types"

	"github.com/orktes/orlang/analyser"
	"github.com/orktes/orlang/parser"
	"github.com/robertkrimen/otto"
)

func TestSimple(t *testing.T) {
	res, err := testCodegen(`
    macro createTuple {
      ($a:expr, $b:expr, $c:expr) : (($a, $b + $c))
    }

    fn getData() : (int32, int32) {
      return createTuple!(1, 1, 1)
    }

    fn sum(a : float64, b : float64) : float64 {
      return a + b
    }

    fn main() {
      var (a, b) = getData()

      var abSum = int32(
        sum(
          float64(a),
          float64(b)
        )
      )

      print("result is: " + int_to_str(int64(abSum - int32(1.5))))
    }
  `)

	if err != nil {
		t.Fatal(err)
	}

	if res != "result is: 2" {
		t.Error("Wrong result received", res)
	}
}

func testCodegen(str string) (string, error) {
	file, err := parser.Parse(strings.NewReader(str))
	if err != nil {
		return "", err
	}

	analyser, err := analyser.New(file)
	if err != nil {
		return "", err
	}

	analyser.AddExternalFunc("int_to_str", &types.SignatureType{
		ArgumentNames: []string{"num"},
		ArgumentTypes: []types.Type{types.Int64Type},
		ReturnType:    types.StringType,
	})

	analyser.AddExternalFunc("print", &types.SignatureType{
		ArgumentNames: []string{"str"},
		ArgumentTypes: []types.Type{types.StringType},
		ReturnType:    types.VoidType,
	})

	analyser.AddExternalFunc("printInt", &types.SignatureType{
		ArgumentNames: []string{"num"},
		ArgumentTypes: []types.Type{types.Int64Type},
		ReturnType:    types.VoidType,
	})

	var analyErr error
	analyser.Error = func(node ast.Node, msg string, fatal bool) {
		if fatal {
			analyErr = errors.New(msg)
		}
	}

	info, err := analyser.Analyse()
	if err != nil {
		return "", err
	}

	if analyErr != nil {
		return "", analyErr
	}

	code := New(info).Generate(file)
	println(string(code)) // debug

	var result string
	vm := otto.New()
	vm.Set("print", func(call otto.FunctionCall) otto.Value {
		result = call.Argument(0).String()
		return otto.Value{}
	})

	vm.Set("int_to_str", func(call otto.FunctionCall) otto.Value {
		result = call.Argument(0).String()
		val, _ := vm.ToValue(result)
		return val
	})

	vm.Set("printInt", func(call otto.FunctionCall) otto.Value {
		resultInt, _ := call.Argument(0).ToInteger()
		result = fmt.Sprintf("%d", resultInt)
		return otto.Value{}
	})
	_, err = vm.Run(string(code))

	return result, err
}
<commit_msg>Macro with repetition<commit_after>package js

import (
	"errors"
	"fmt"
	"strings"
	"testing"

	"github.com/orktes/orlang/ast"
	"github.com/orktes/orlang/types"

	"github.com/orktes/orlang/analyser"
	"github.com/orktes/orlang/parser"
	"github.com/robertkrimen/otto"
)

func TestSimple(t *testing.T) {
	res, err := testCodegen(`
    macro createTuple {
      ($a:expr , $( $x:expr ),*) : (
        (
          $a
          $(
            ,
            $x
          )*
        )
      )
    }

    fn getData() : (int32, int32) {
      return createTuple!(1, 2)
    }

    fn sum(a : float64, b : float64) : float64 {
      return a + b
    }

    fn main() {
      var (a, b) = getData()

      var abSum = int32(
        sum(
          float64(a),
          float64(b)
        )
      )

      print("result is: " + int_to_str(int64(abSum - int32(1.5))))
    }
  `)

	if err != nil {
		t.Fatal(err)
	}

	if res != "result is: 2" {
		t.Error("Wrong result received", res)
	}
}

func testCodegen(str string) (string, error) {
	file, err := parser.Parse(strings.NewReader(str))
	if err != nil {
		return "", err
	}

	analyser, err := analyser.New(file)
	if err != nil {
		return "", err
	}

	analyser.AddExternalFunc("int_to_str", &types.SignatureType{
		ArgumentNames: []string{"num"},
		ArgumentTypes: []types.Type{types.Int64Type},
		ReturnType:    types.StringType,
	})

	analyser.AddExternalFunc("print", &types.SignatureType{
		ArgumentNames: []string{"str"},
		ArgumentTypes: []types.Type{types.StringType},
		ReturnType:    types.VoidType,
	})

	analyser.AddExternalFunc("printInt", &types.SignatureType{
		ArgumentNames: []string{"num"},
		ArgumentTypes: []types.Type{types.Int64Type},
		ReturnType:    types.VoidType,
	})

	var analyErr error
	analyser.Error = func(node ast.Node, msg string, fatal bool) {
		if fatal {
			analyErr = errors.New(msg)
		}
	}

	info, err := analyser.Analyse()
	if err != nil {
		return "", err
	}

	if analyErr != nil {
		return "", analyErr
	}

	code := New(info).Generate(file)
	println(string(code)) // debug

	var result string
	vm := otto.New()
	vm.Set("print", func(call otto.FunctionCall) otto.Value {
		result = call.Argument(0).String()
		return otto.Value{}
	})

	vm.Set("int_to_str", func(call otto.FunctionCall) otto.Value {
		result = call.Argument(0).String()
		val, _ := vm.ToValue(result)
		return val
	})

	vm.Set("printInt", func(call otto.FunctionCall) otto.Value {
		resultInt, _ := call.Argument(0).ToInteger()
		result = fmt.Sprintf("%d", resultInt)
		return otto.Value{}
	})
	_, err = vm.Run(string(code))

	return result, err
}
<|endoftext|>


<commit_before>package simpleserver

import (
	"net"
	"net/http"
	"time"

	"github.com/Sirupsen/logrus"
	"gopkg.in/tylerb/graceful.v1"
)

// A Server defines parameters for running a simple http server.
// Addr is required (unless Serve(l) is used directly). Name is recommended.
type Server struct {
	Name        string
	Logger      *logrus.Logger
	Addr        string
	Handler     http.Handler
	StopTimeout time.Duration
	ln          net.Listener
	srv         *graceful.Server
}

const DefaultStopTimeout = 10 * time.Second

// ServerName just returns the server name. Provided so that structs that stack
// simpleserver will provide this method.
func (s Server) ServerName() string {
	return s.Name
}

// ServerAddr returns the address the server is configured to listen on.
// Provided so that structs that stack simpleserver will provide this method.
func (s Server) ServerAddr() string {
	if s.ln != nil {
		return s.ln.Addr().String()
	}
	return s.Addr
}

// ServeHTTP exists so Server itself satisfies the http.Handler interface. It
// just proxies to Server.Handler.
func (s Server) ServeHTTP(w http.ResponseWriter, req *http.Request) {
	s.Handler.ServeHTTP(w, req)
}

// ListenAndServe listens on the TCP network address srv.Addr and then
// calls Serve to handle requests on incoming connections.
// Accepted connections are configured to enable TCP keep-alives.
// If srv.Addr is blank, ":http" is used.
// ListenAndServe always returns a non-nil error.
func (s *Server) ListenAndServe() error {
	if err := s.newListener(); err != nil {
		return err
	}

	return s.Serve(s.ln)
}

func (s *Server) newListener() error {
	ln, err := net.Listen("tcp", s.Addr)
	if err != nil {
		return err
	}
	s.ln = ln
	return nil
}

// Serve accepts incoming connections on the Listener l. It just proxies to
// http.Server.Serve(l).
// Serve always returns a non-nil error.
func (s *Server) Serve(l net.Listener) error {
	s.ln = l

	if s.Logger != nil {
		s.Logger.WithFields(logrus.Fields{
			"server": s.ServerName(),
			"addr":   s.ServerAddr(),
		}).Info("starting")
	}

	s.srv = &graceful.Server{
		Server:           &http.Server{Handler: s.Handler},
		NoSignalHandling: true,
	}

	return s.srv.Serve(l)
}

func (s Server) stopTimeout() time.Duration {
	if s.StopTimeout > 0 {
		return s.StopTimeout
	}
	return DefaultStopTimeout
}

// Init prepares the Server for Start. If it does not return an error, then
// Start will not return one either.
func (s *Server) Init() error {
	if s.ln == nil {
		if err := s.newListener(); err != nil {
			return err
		}
	}
	return nil
}

// Start the server in a background goroutine. It only returns initialization
// errors. It will not return an error if Init didn't.
func (s *Server) Start() error {
	if err := s.Init(); err != nil {
		return err
	}

	go func() {
		if err := s.Serve(s.ln); err != nil && s.Logger != nil {
			s.Logger.WithError(err).WithFields(logrus.Fields{
				"server": s.ServerName(),
				"addr":   s.ServerAddr(),
			}).Warn("serve error")
		}
	}()

	return nil
}

// Close shuts down the server.
func (s *Server) Close() error {
	if s.srv == nil {
		return nil
	}

	if s.Logger != nil {
		s.Logger.WithFields(logrus.Fields{
			"server": s.ServerName(),
			"addr":   s.ServerAddr(),
		}).Info("stopping")
	}

	ch := s.srv.StopChan()
	s.srv.Stop(s.stopTimeout())
	<-ch

	s.srv = nil
	s.ln = nil

	return nil
}
<commit_msg>more logging updates<commit_after>package simpleserver

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

	"github.com/Sirupsen/logrus"
	"gopkg.in/tylerb/graceful.v1"
)

// A Server defines parameters for running a simple http server.
// Addr is required (unless Serve(l) is used directly). Name is recommended.
type Server struct {
	Name        string
	Logger      *logrus.Logger
	Addr        string
	Handler     http.Handler
	StopTimeout time.Duration
	ln          net.Listener
	srv         *graceful.Server
}

const DefaultStopTimeout = 10 * time.Second

// ServerName just returns the server name. Provided so that structs that stack
// simpleserver will provide this method.
func (s Server) ServerName() string {
	return s.Name
}

// ServerAddr returns the address the server is configured to listen on.
// Provided so that structs that stack simpleserver will provide this method.
func (s Server) ServerAddr() string {
	if s.ln != nil {
		return s.ln.Addr().String()
	}
	return s.Addr
}

// ServeHTTP exists so Server itself satisfies the http.Handler interface. It
// just proxies to Server.Handler.
func (s Server) ServeHTTP(w http.ResponseWriter, req *http.Request) {
	s.Handler.ServeHTTP(w, req)
}

// ListenAndServe listens on the TCP network address srv.Addr and then
// calls Serve to handle requests on incoming connections.
// Accepted connections are configured to enable TCP keep-alives.
// If srv.Addr is blank, ":http" is used.
// ListenAndServe always returns a non-nil error.
func (s *Server) ListenAndServe() error {
	if err := s.newListener(); err != nil {
		return err
	}

	return s.Serve(s.ln)
}

func (s *Server) newListener() error {
	ln, err := net.Listen("tcp", s.Addr)
	if err != nil {
		return err
	}
	s.ln = ln
	return nil
}

// Serve accepts incoming connections on the Listener l. It just proxies to
// http.Server.Serve(l).
// Serve always returns a non-nil error.
func (s *Server) Serve(l net.Listener) error {
	s.ln = l

	var logLogger *log.Logger

	if s.Logger != nil {
		s.Logger.WithFields(logrus.Fields{
			"server": s.ServerName(),
			"addr":   s.ServerAddr(),
		}).Info("starting")

		w := s.Logger.WriterLevel(logrus.DebugLevel)
		logLogger = log.New(w, "", 0)
	}

	s.srv = &graceful.Server{
		Server:           &http.Server{Handler: s.Handler},
		NoSignalHandling: true,
		Logger:           logLogger,
	}

	return s.srv.Serve(l)
}

func (s Server) stopTimeout() time.Duration {
	if s.StopTimeout > 0 {
		return s.StopTimeout
	}
	return DefaultStopTimeout
}

// Init prepares the Server for Start. If it does not return an error, then
// Start will not return one either.
func (s *Server) Init() error {
	if s.ln == nil {
		if err := s.newListener(); err != nil {
			return err
		}
	}
	return nil
}

// Start the server in a background goroutine. It only returns initialization
// errors. It will not return an error if Init didn't.
func (s *Server) Start() error {
	if err := s.Init(); err != nil {
		return err
	}

	go func() {
		if err := s.Serve(s.ln); err != nil && s.Logger != nil {
			s.Logger.WithError(err).WithFields(logrus.Fields{
				"server": s.ServerName(),
				"addr":   s.ServerAddr(),
			}).Warn("serve error")
		}
	}()

	return nil
}

// Close shuts down the server.
func (s *Server) Close() error {
	if s.srv == nil {
		return nil
	}

	if s.Logger != nil {
		s.Logger.WithFields(logrus.Fields{
			"server": s.ServerName(),
			"addr":   s.ServerAddr(),
		}).Info("stopping")
	}

	ch := s.srv.StopChan()
	s.srv.Stop(s.stopTimeout())
	<-ch

	s.srv = nil
	s.ln = nil

	return nil
}
<|endoftext|>


<commit_before>package main

import (
	"time"
)

// Returns a slice of IncidentFeatures. The slice contains the latest report for all incidents marked as current
func currentIncidentsWithLatestReport() (incidents []IncidentFeature, err error) {
	// Select the latest report for all current incidents
	stmt, err := db.Prepare(`SELECT DISTINCT ON (i.uuid) r.uuid, incident_uuid,
                              guid, title, link, category, pubdate,
                              updated, alert_level, location, council_area, status, fire_type,
                              fire, size, responsible_agency, extra,
                              ST_Y(r.geometry) as lat, ST_X(r.geometry) as lng
                            FROM incidents i
                            JOIN reports r ON i.uuid = r.incident_uuid
                            WHERE i.current = true
                            ORDER BY i.uuid, r.created_at DESC`)
	if err != nil {
		return
	}
	defer stmt.Close()

	rows, err := stmt.Query()
	if err != nil {
		return
	}

	for rows.Next() {
		var lat string
		var lng string
		var ip IncidentProperties
		var fea IncidentFeature

		err = rows.Scan(&ip.ReportUUID, &fea.UUID, &ip.Guid, &ip.Title, &ip.Link, &ip.Category, &ip.Pubdate, &ip.Updated, &ip.AlertLevel, &ip.Location, &ip.CouncilArea, &ip.Status, &ip.FireType, &ip.Fire, &ip.Size, &ip.ResponsibleAgency, &ip.Extra, &lat, &lng)
		if err != nil {
			return
		}

		// Report properties needs to be placed within a IncidentFeature
		// and the IncidentFeature needs to be adjusted based on ip content
		fea.Type = "Feature"
		fea.Properties = ip
		fea.Geometry = pointFromCoordinates(lng, lat)

		incidents = append(incidents, fea)
	}

	return
}

// Takes a slice of report features and returns it wrapped in a GeoJSON FeatureCollection
func incidentFeatureCollectionForIncidentFeatures(fea []IncidentFeature) IncidentFeatureCollection {
	return IncidentFeatureCollection{"FeatureCollection", fea}
}

// IncidentFeatureCollection A GeoJSON FeatureCollection representing a collection of ReportFeatures
type IncidentFeatureCollection struct {
	Type     string            `json:"type"`
	Features []IncidentFeature `json:"features"`
}

// Takes a UUID and returns a IncidentFeature representing that incident
func incidentFeatureForUUID(uuid string) (IncidentFeature, error) {
	fea := IncidentFeature{}

	// Select the latest report for the requested incident
	stmt, err := db.Prepare(`SELECT DISTINCT ON (i.uuid) r.uuid,
                              guid, title, link, category, pubdate,
                              updated, alert_level, location, council_area, status, fire_type,
                              fire, size, responsible_agency, extra,
                              ST_Y(r.geometry) as lat, ST_X(r.geometry) as lng
                            FROM incidents i
                            JOIN reports r ON i.uuid = r.incident_uuid
                            WHERE i.current = true
                            AND i.uuid = $1
                            ORDER BY i.uuid, r.created_at DESC`)
	if err != nil {
		return fea, err
	}
	defer stmt.Close()

	var lat string
	var lng string
	var ip IncidentProperties

	err = stmt.QueryRow(uuid).Scan(&ip.ReportUUID, &ip.Guid, &ip.Title, &ip.Link, &ip.Category, &ip.Pubdate, &ip.Updated, &ip.AlertLevel, &ip.Location, &ip.CouncilArea, &ip.Status, &ip.FireType, &ip.Fire, &ip.Size, &ip.ResponsibleAgency, &ip.Extra, &lat, &lng)
	if err != nil {
		return fea, err
	}

	// Incident properties needs to be placed within a ReportFeature
	// and the IncidentFeature needs to be adjusted based on ip content
	fea.Type = "Feature"
	fea.Properties = ip
	fea.UUID = uuid
	fea.Geometry = pointFromCoordinates(lng, lat)

	return fea, nil
}

// Takes a lat and lng and returns a GeoJSON Point with those coordinates
func pointFromCoordinates(lat string, lng string) (p Point) {
	p = Point{}

	p.Type = "Point"
	p.Coordinates = []string{lat, lng}

	return
}

// IncidentFeature is a GeoJSON feature for an individual report
type IncidentFeature struct {
	Type       string             `json:"type"`
	UUID       string             `json:"id"`
	Geometry   Point              `json:"geometry"`
	Properties IncidentProperties `json:"properties"`
}

// IncidentProperties is a collection of properties for an individual report included in a IncidentFeature GeoJSON response.
type IncidentProperties struct {
	ReportUUID        string    `json:"reportUuid"`
	Guid              string    `json:"guid"`
	Title             string    `json:"title"`
	Link              string    `json:"link"`
	Category          string    `json:"category"`
	Pubdate           time.Time `json:"pubdate"`
	Updated           time.Time `json:"updated"`
	AlertLevel        string    `json:"alertLevel"`
	Location          string    `json:"location"`
	CouncilArea       string    `json:"councilArea"`
	Status            string    `json:"status"`
	FireType          string    `json:"fireType"`
	Fire              bool      `json:"fire"`
	Size              string    `json:"size"`
	ResponsibleAgency string    `json:"responsibleAgency"`
	Extra             string    `json:"extra"`
	//Polygons          []string
}

// Point is a lng, lat coordinate pair used for the GeoJSON geometry type Point.
type Point struct {
	Type        string   `json:"type"`
	Coordinates []string `json:"coordinates"`
}
<commit_msg>Cast to UTC here.<commit_after>package main

import (
	"time"
)

// Returns a slice of IncidentFeatures. The slice contains the latest report for all incidents marked as current
func currentIncidentsWithLatestReport() (incidents []IncidentFeature, err error) {
	// Select the latest report for all current incidents
	stmt, err := db.Prepare(`SELECT DISTINCT ON (i.uuid) r.uuid, incident_uuid,
                              guid, title, link, category, timezone('UTC', pubdate),
                              timezone('UTC', updated), alert_level, location, council_area, status, fire_type,
                              fire, size, responsible_agency, extra,
                              ST_Y(r.geometry) as lat, ST_X(r.geometry) as lng
                            FROM incidents i
                            JOIN reports r ON i.uuid = r.incident_uuid
                            WHERE i.current = true
                            ORDER BY i.uuid, r.created_at DESC`)
	if err != nil {
		return
	}
	defer stmt.Close()

	rows, err := stmt.Query()
	if err != nil {
		return
	}

	for rows.Next() {
		var lat string
		var lng string
		var ip IncidentProperties
		var fea IncidentFeature

		err = rows.Scan(&ip.ReportUUID, &fea.UUID, &ip.Guid, &ip.Title, &ip.Link, &ip.Category, &ip.Pubdate, &ip.Updated, &ip.AlertLevel, &ip.Location, &ip.CouncilArea, &ip.Status, &ip.FireType, &ip.Fire, &ip.Size, &ip.ResponsibleAgency, &ip.Extra, &lat, &lng)
		if err != nil {
			return
		}

		// Report properties needs to be placed within a IncidentFeature
		// and the IncidentFeature needs to be adjusted based on ip content
		fea.Type = "Feature"
		fea.Properties = ip
		fea.Geometry = pointFromCoordinates(lng, lat)

		incidents = append(incidents, fea)
	}

	return
}

// Takes a slice of report features and returns it wrapped in a GeoJSON FeatureCollection
func incidentFeatureCollectionForIncidentFeatures(fea []IncidentFeature) IncidentFeatureCollection {
	return IncidentFeatureCollection{"FeatureCollection", fea}
}

// IncidentFeatureCollection A GeoJSON FeatureCollection representing a collection of ReportFeatures
type IncidentFeatureCollection struct {
	Type     string            `json:"type"`
	Features []IncidentFeature `json:"features"`
}

// Takes a UUID and returns a IncidentFeature representing that incident
func incidentFeatureForUUID(uuid string) (IncidentFeature, error) {
	fea := IncidentFeature{}

	// Select the latest report for the requested incident
	stmt, err := db.Prepare(`SELECT DISTINCT ON (i.uuid) r.uuid,
                              guid, title, link, category, timezone('UTC', pubdate),
                              timezone('UTC', updated), alert_level, location, council_area, status, fire_type,
                              fire, size, responsible_agency, extra,
                              ST_Y(r.geometry) as lat, ST_X(r.geometry) as lng
                            FROM incidents i
                            JOIN reports r ON i.uuid = r.incident_uuid
                            WHERE i.current = true
                            AND i.uuid = $1
                            ORDER BY i.uuid, r.created_at DESC`)
	if err != nil {
		return fea, err
	}
	defer stmt.Close()

	var lat string
	var lng string
	var ip IncidentProperties

	err = stmt.QueryRow(uuid).Scan(&ip.ReportUUID, &ip.Guid, &ip.Title, &ip.Link, &ip.Category, &ip.Pubdate, &ip.Updated, &ip.AlertLevel, &ip.Location, &ip.CouncilArea, &ip.Status, &ip.FireType, &ip.Fire, &ip.Size, &ip.ResponsibleAgency, &ip.Extra, &lat, &lng)
	if err != nil {
		return fea, err
	}

	// Incident properties needs to be placed within a ReportFeature
	// and the IncidentFeature needs to be adjusted based on ip content
	fea.Type = "Feature"
	fea.Properties = ip
	fea.UUID = uuid
	fea.Geometry = pointFromCoordinates(lng, lat)

	return fea, nil
}

// Takes a lat and lng and returns a GeoJSON Point with those coordinates
func pointFromCoordinates(lat string, lng string) (p Point) {
	p = Point{}

	p.Type = "Point"
	p.Coordinates = []string{lat, lng}

	return
}

// IncidentFeature is a GeoJSON feature for an individual report
type IncidentFeature struct {
	Type       string             `json:"type"`
	UUID       string             `json:"id"`
	Geometry   Point              `json:"geometry"`
	Properties IncidentProperties `json:"properties"`
}

// IncidentProperties is a collection of properties for an individual report included in a IncidentFeature GeoJSON response.
type IncidentProperties struct {
	ReportUUID        string    `json:"reportUuid"`
	Guid              string    `json:"guid"`
	Title             string    `json:"title"`
	Link              string    `json:"link"`
	Category          string    `json:"category"`
	Pubdate           time.Time `json:"pubdate"`
	Updated           time.Time `json:"updated"`
	AlertLevel        string    `json:"alertLevel"`
	Location          string    `json:"location"`
	CouncilArea       string    `json:"councilArea"`
	Status            string    `json:"status"`
	FireType          string    `json:"fireType"`
	Fire              bool      `json:"fire"`
	Size              string    `json:"size"`
	ResponsibleAgency string    `json:"responsibleAgency"`
	Extra             string    `json:"extra"`
	//Polygons          []string
}

// Point is a lng, lat coordinate pair used for the GeoJSON geometry type Point.
type Point struct {
	Type        string   `json:"type"`
	Coordinates []string `json:"coordinates"`
}
<|endoftext|>


<commit_before>package guppy

import (
	"fmt"
	"net/http"
)

var (
	apiEntryPoint string       = "https://api.wheresitup.com/v4"
	httpClient    *http.Client = &http.Client{}
)

type WIU struct {
	Client string
	Token  string
}

func (api WIU) setHeaders(req *http.Request, headers map[string]string) {
	req.Header.Add("Content-Type", "application/json")
	req.Header.Add("Auth", fmt.Sprintf("Bearer %s %s", api.Client, api.Token))

	for header, content := range headers {
		req.Header.Add(header, content)
	}
}

func (api WIU) get(endpoint string) (*http.Response, error) {
	req, err := http.NewRequest("GET", fmt.Sprintf("%s/%s", apiEntryPoint, endpoint), nil)
	if err != nil {
		return nil, err
	}

	api.setHeaders(req, nil)

	return httpClient.Do(req)
}
<commit_msg>hey there's a default client!<commit_after>package guppy

import (
	"fmt"
	"net/http"
)

var (
	apiEntryPoint string = "https://api.wheresitup.com/v4"
)

type WIU struct {
	Client string
	Token  string
}

func (api WIU) setHeaders(req *http.Request, headers map[string]string) {
	req.Header.Add("Content-Type", "application/json")
	req.Header.Add("Auth", fmt.Sprintf("Bearer %s %s", api.Client, api.Token))

	for header, content := range headers {
		req.Header.Add(header, content)
	}
}

func (api WIU) get(endpoint string) (*http.Response, error) {
	req, err := http.NewRequest("GET", fmt.Sprintf("%s/%s", apiEntryPoint, endpoint), nil)
	if err != nil {
		return nil, err
	}

	api.setHeaders(req, nil)

	return http.DefaultClient.Do(req)
}
<|endoftext|>


<commit_before>package gramework

// SetName for the server
func (app *App) SetName(name string) {
	app.name = name
}

// ToTLSHandler returns handler that redirects user to HTTP scheme
func (app *App) ToTLSHandler() func(*Context) {
	return func(ctx *Context) {
		ctx.ToTLS()
	}
}

// HTTP returns HTTP-only router
func (app *App) HTTP() *Router {
	return app.defaultRouter.HTTP()
}

// HTTPS returns HTTPS-only router
func (app *App) HTTPS() *Router {
	return app.defaultRouter.HTTPS()
}

// MethodNotAllowed sets MethodNotAllowed handler
func (app *App) MethodNotAllowed(c func(ctx *Context)) *App {
	app.defaultRouter.router.MethodNotAllowed = c
	return app
}

// Redir sends 301 redirect to the given url
//
// it's equivalent to
//
//     ctx.Redirect(url, 301)
func (app *App) Redir(url string) func(*Context) {
	return func(ctx *Context) {
		ctx.Redirect(url, redirectCode)
	}
}

// Forbidden send 403 Forbidden error
func (app *App) Forbidden(ctx *Context) {
	ctx.Forbidden()
}
<commit_msg>update typo in documentation (#18)<commit_after>package gramework

// SetName for the server
func (app *App) SetName(name string) {
	app.name = name
}

// ToTLSHandler returns handler that redirects user to HTTPS scheme
func (app *App) ToTLSHandler() func(*Context) {
	return func(ctx *Context) {
		ctx.ToTLS()
	}
}

// HTTP returns HTTP-only router
func (app *App) HTTP() *Router {
	return app.defaultRouter.HTTP()
}

// HTTPS returns HTTPS-only router
func (app *App) HTTPS() *Router {
	return app.defaultRouter.HTTPS()
}

// MethodNotAllowed sets MethodNotAllowed handler
func (app *App) MethodNotAllowed(c func(ctx *Context)) *App {
	app.defaultRouter.router.MethodNotAllowed = c
	return app
}

// Redir sends 301 redirect to the given url
//
// it's equivalent to
//
//     ctx.Redirect(url, 301)
func (app *App) Redir(url string) func(*Context) {
	return func(ctx *Context) {
		ctx.Redirect(url, redirectCode)
	}
}

// Forbidden send 403 Forbidden error
func (app *App) Forbidden(ctx *Context) {
	ctx.Forbidden()
}
<|endoftext|>


<commit_before>package model

import (
	"github.com/jinzhu/gorm"
	"github.com/ChaosXu/nerv/lib/db"
	"k8s.io/kubernetes/pkg/registry/core/service/portallocator"
	"github.com/cloudinsight/cloudinsight-agent/common/log"
)

func init() {
	db.Models["App"] = appDesc()
}

func appDesc() *db.ModelDescriptor {
	return &db.ModelDescriptor{
		Type: &App{},
		New: func() interface{} {
			return &App{}
		},
		NewSlice:func() interface{} {
			return &[]App{}
		},
	}
}

// App managed by agent
type App struct {
	gorm.Model
	Name     string    `json:"name" gorm:"not null;unique"`
	Path     string    `json:"path" gorm:"not null;unique"`
	Version  string    `json:"version"`
	Services []Service `json:"services"`
	Log      *Log
}

// Service provide by an app
type Service struct {
	gorm.Model
	Name string    `json:"name" gorm:"not null;unique"` //service name
	Type string    `json:"type" gorm:"not null"`        //service type:e.g. http | https
	Port int32     `json:"port" gorm:"not null"`        //service port
	Uri  string    `json:"uri" gorm:"not null;unique"`  //service uri
}

// Log config the information of app
type Log struct {

}
<commit_msg>fix build error<commit_after>package model

import (
	"github.com/jinzhu/gorm"
	"github.com/ChaosXu/nerv/lib/db"
)

func init() {
	db.Models["App"] = appDesc()
}

func appDesc() *db.ModelDescriptor {
	return &db.ModelDescriptor{
		Type: &App{},
		New: func() interface{} {
			return &App{}
		},
		NewSlice:func() interface{} {
			return &[]App{}
		},
	}
}

// App managed by agent
type App struct {
	gorm.Model
	Name     string    `json:"name" gorm:"not null;unique"`
	Path     string    `json:"path" gorm:"not null;unique"`
	Version  string    `json:"version"`
	Services []Service `json:"services"`
	Log      *Log
}

// Service provide by an app
type Service struct {
	gorm.Model
	Name string    `json:"name" gorm:"not null;unique"` //service name
	Type string    `json:"type" gorm:"not null"`        //service type:e.g. http | https
	Port int32     `json:"port" gorm:"not null"`        //service port
	Uri  string    `json:"uri" gorm:"not null;unique"`  //service uri
}

// Log config the information of app
type Log struct {

}
<|endoftext|>


<commit_before>package main

import (
	"fmt"
	"image"
	"image/color"
	"log"
	"math"
	"os"
	"strconv"

	"github.com/fogleman/pt/pt"
)

func main() {
	log.SetFlags(0)
	args := os.Args[1:]
	if len(args) < 3 || len(args)%2 != 1 {
		log.Fatalln("Usage: combine path1.png weight1 path2.png weight2 ... output.png")
	}
	var images []image.Image
	var weights []int64
	var totalWeight int64
	for i := 0; i < len(args)-1; i += 2 {
		path := args[i]
		weight, err := strconv.ParseInt(args[i+1], 0, 0)
		if err != nil {
			log.Fatalf("Invalid weight: %s\n", args[i+1])
		}
		fmt.Printf("Loading %s...\n", path)
		im, err := pt.LoadImage(path)
		if err != nil {
			log.Fatalf("Error loading %s: %v", path, err)
		}
		images = append(images, im)
		weights = append(weights, weight)
		totalWeight += weight
	}
	for i := 1; i < len(images); i++ {
		s1 := images[0].Bounds().Max
		s2 := images[i].Bounds().Max
		if s1 != s2 {
			log.Fatalf("Images must all have the same dimensions")
		}
	}
	fmt.Println("Combining images...")
	size := images[0].Bounds().Max
	w, h := size.X, size.Y
	result := image.NewRGBA(image.Rect(0, 0, w, h))
	for y := 0; y < h; y++ {
		for x := 0; x < w; x++ {
			fr, fg, fb := 0.0, 0.0, 0.0
			for i, im := range images {
				weight := float64(weights[i])
				r, g, b, _ := im.At(x, y).RGBA()
				fr += weight * float64(r) / 65535
				fg += weight * float64(g) / 65535
				fb += weight * float64(b) / 65535
			}
			fr /= float64(totalWeight)
			fg /= float64(totalWeight)
			fb /= float64(totalWeight)
			r := uint8(math.Min(255, fr*255))
			g := uint8(math.Min(255, fg*255))
			b := uint8(math.Min(255, fb*255))
			result.SetRGBA(x, y, color.RGBA{r, g, b, 255})
		}
	}
	path := args[len(args)-1]
	if err := pt.SavePNG(path, result); err != nil {
		log.Fatalf("Error saving %s: %v", path, err)
	}
}
<commit_msg>16-bit png for combine<commit_after>package main

import (
	"fmt"
	"image"
	"image/color"
	"log"
	"math"
	"os"
	"strconv"

	"github.com/fogleman/pt/pt"
)

func main() {
	log.SetFlags(0)
	args := os.Args[1:]
	if len(args) < 3 || len(args)%2 != 1 {
		log.Fatalln("Usage: combine path1.png weight1 path2.png weight2 ... output.png")
	}
	var images []image.Image
	var weights []int64
	var totalWeight int64
	for i := 0; i < len(args)-1; i += 2 {
		path := args[i]
		weight, err := strconv.ParseInt(args[i+1], 0, 0)
		if err != nil {
			log.Fatalf("Invalid weight: %s\n", args[i+1])
		}
		fmt.Printf("Loading %s...\n", path)
		im, err := pt.LoadImage(path)
		if err != nil {
			log.Fatalf("Error loading %s: %v", path, err)
		}
		images = append(images, im)
		weights = append(weights, weight)
		totalWeight += weight
	}
	for i := 1; i < len(images); i++ {
		s1 := images[0].Bounds().Max
		s2 := images[i].Bounds().Max
		if s1 != s2 {
			log.Fatalf("Images must all have the same dimensions")
		}
	}
	fmt.Println("Combining images...")
	size := images[0].Bounds().Max
	w, h := size.X, size.Y
	result := image.NewNRGBA64(image.Rect(0, 0, w, h))
	for y := 0; y < h; y++ {
		for x := 0; x < w; x++ {
			fr, fg, fb := 0.0, 0.0, 0.0
			for i, im := range images {
				weight := float64(weights[i])
				r, g, b, _ := im.At(x, y).RGBA()
				fr += weight * float64(r) / 65535
				fg += weight * float64(g) / 65535
				fb += weight * float64(b) / 65535
			}
			fr /= float64(totalWeight)
			fg /= float64(totalWeight)
			fb /= float64(totalWeight)
			r := uint16(math.Min(65535, fr*65535))
			g := uint16(math.Min(65535, fg*65535))
			b := uint16(math.Min(65535, fb*65535))
			result.SetNRGBA64(x, y, color.NRGBA64{r, g, b, 65535})
		}
	}
	path := args[len(args)-1]
	if err := pt.SavePNG(path, result); err != nil {
		log.Fatalf("Error saving %s: %v", path, err)
	}
}
<|endoftext|>


<commit_before>/*
Copyright 2018 The Knative Authors

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

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

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

package main

import (
	"context"
	"flag"
	"log"
	"net/http"
	"time"

	// Uncomment the following line to load the gcp plugin (only required to authenticate against GKE clusters).
	_ "k8s.io/client-go/plugin/pkg/client/auth/gcp"

	"github.com/knative/eventing/pkg/logconfig"
	"github.com/knative/eventing/pkg/system"
	"github.com/knative/pkg/configmap"
	"github.com/knative/pkg/logging"
	"github.com/knative/pkg/logging/logkey"
	"github.com/knative/pkg/signals"
	"github.com/prometheus/client_golang/prometheus/promhttp"
	"go.uber.org/zap"
	"k8s.io/client-go/kubernetes"
	controllerruntime "sigs.k8s.io/controller-runtime/pkg/client/config"
)

const (
	metricsScrapeAddr    = ":9090"
	metricsScrapePath    = "/metrics"
)

var (
	experimentalControllers string
	hardcodedLoggingConfig  bool
)

func main() {
	flag.Parse()

	// Read the logging config and setup a logger.
	cm := getLoggingConfigOrDie()

	config, err := logging.NewConfigFromMap(cm, logconfig.Controller)
	if err != nil {
		log.Fatalf("Error parsing logging configuration: %v", err)
	}
	logger, atomicLevel := logging.NewLoggerFromConfig(config, logconfig.Controller)
	defer logger.Sync()
	logger = logger.With(zap.String(logkey.ControllerType, logconfig.Controller))

	logger.Info("Starting the Controller")

	// set up signals so we handle the first shutdown signal gracefully
	stopCh := signals.SetupSignalHandler()

	cfg, err := controllerruntime.GetConfig()
	if err != nil {
		logger.Fatalf("Error building kubeconfig: %v", err)
	}

	kubeClient, err := kubernetes.NewForConfig(cfg)
	if err != nil {
		logger.Fatalf("Error building kubernetes clientset: %v", err)
	}

	// Watch the logging config map and dynamically update logging levels.
	configMapWatcher := configmap.NewInformedWatcher(kubeClient, system.Namespace)
	configMapWatcher.Watch(logconfig.ConfigName, logging.UpdateLevelFromConfigMap(logger, atomicLevel, logconfig.Controller, logconfig.Controller))
	if err = configMapWatcher.Start(stopCh); err != nil {
		logger.Fatalf("failed to start controller config map watcher: %v", err)
	}

	// Start the controller-runtime controllers.
	go func() {
		if err := controllerRuntimeStart(logger, experimentalControllers); err != nil {
			logger.Fatalf("Error running controller-runtime controllers: %v", err)
		}
	}()

	// Start the endpoint that Prometheus scraper talks to
	srv := &http.Server{Addr: metricsScrapeAddr}
	http.Handle(metricsScrapePath, promhttp.Handler())
	go func() {
		logger.Info("Starting metrics listener at %s", metricsScrapeAddr)
		if err := srv.ListenAndServe(); err != nil {
			logger.Infof("Httpserver: ListenAndServe() finished with error: %s", err)
		}
	}()

	<-stopCh

	// Close the http server gracefully
	ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
	defer cancel()
	srv.Shutdown(ctx)
}

func init() {
	flag.StringVar(&experimentalControllers, "experimentalControllers", "", "List of experimental controllers to include in the Knative Controller.")
	flag.BoolVar(&hardcodedLoggingConfig, "hardCodedLoggingConfig", false, "If true, use the hard coded logging config. It is intended to be used only when debugging outside a Kubernetes cluster.")
}

func getLoggingConfigOrDie() map[string]string {
	if hardcodedLoggingConfig {
		return map[string]string{
			"loglevel.controller": "info",
			"zap-logger-config": `
				{
					"level": "info",
					"development": false,
					"outputPaths": ["stdout"],
					"errorOutputPaths": ["stderr"],
					"encoding": "json",
					"encoderConfig": {
					"timeKey": "ts",
					"levelKey": "level",
					"nameKey": "logger",
					"callerKey": "caller",
					"messageKey": "msg",
					"stacktraceKey": "stacktrace",
					"lineEnding": "",
					"levelEncoder": "",
					"timeEncoder": "iso8601",
					"durationEncoder": "",
					"callerEncoder": ""
				}`,
		}
	} else {
		cm, err := configmap.Load("/etc/config-logging")
		if err != nil {
			log.Fatalf("Error loading logging configuration: %v", err)
		}
		return cm
	}
}
<commit_msg>golang format tools (#716)<commit_after>/*
Copyright 2018 The Knative Authors

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

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

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

package main

import (
	"context"
	"flag"
	"log"
	"net/http"
	"time"

	// Uncomment the following line to load the gcp plugin (only required to authenticate against GKE clusters).
	_ "k8s.io/client-go/plugin/pkg/client/auth/gcp"

	"github.com/knative/eventing/pkg/logconfig"
	"github.com/knative/eventing/pkg/system"
	"github.com/knative/pkg/configmap"
	"github.com/knative/pkg/logging"
	"github.com/knative/pkg/logging/logkey"
	"github.com/knative/pkg/signals"
	"github.com/prometheus/client_golang/prometheus/promhttp"
	"go.uber.org/zap"
	"k8s.io/client-go/kubernetes"
	controllerruntime "sigs.k8s.io/controller-runtime/pkg/client/config"
)

const (
	metricsScrapeAddr = ":9090"
	metricsScrapePath = "/metrics"
)

var (
	experimentalControllers string
	hardcodedLoggingConfig  bool
)

func main() {
	flag.Parse()

	// Read the logging config and setup a logger.
	cm := getLoggingConfigOrDie()

	config, err := logging.NewConfigFromMap(cm, logconfig.Controller)
	if err != nil {
		log.Fatalf("Error parsing logging configuration: %v", err)
	}
	logger, atomicLevel := logging.NewLoggerFromConfig(config, logconfig.Controller)
	defer logger.Sync()
	logger = logger.With(zap.String(logkey.ControllerType, logconfig.Controller))

	logger.Info("Starting the Controller")

	// set up signals so we handle the first shutdown signal gracefully
	stopCh := signals.SetupSignalHandler()

	cfg, err := controllerruntime.GetConfig()
	if err != nil {
		logger.Fatalf("Error building kubeconfig: %v", err)
	}

	kubeClient, err := kubernetes.NewForConfig(cfg)
	if err != nil {
		logger.Fatalf("Error building kubernetes clientset: %v", err)
	}

	// Watch the logging config map and dynamically update logging levels.
	configMapWatcher := configmap.NewInformedWatcher(kubeClient, system.Namespace)
	configMapWatcher.Watch(logconfig.ConfigName, logging.UpdateLevelFromConfigMap(logger, atomicLevel, logconfig.Controller, logconfig.Controller))
	if err = configMapWatcher.Start(stopCh); err != nil {
		logger.Fatalf("failed to start controller config map watcher: %v", err)
	}

	// Start the controller-runtime controllers.
	go func() {
		if err := controllerRuntimeStart(logger, experimentalControllers); err != nil {
			logger.Fatalf("Error running controller-runtime controllers: %v", err)
		}
	}()

	// Start the endpoint that Prometheus scraper talks to
	srv := &http.Server{Addr: metricsScrapeAddr}
	http.Handle(metricsScrapePath, promhttp.Handler())
	go func() {
		logger.Info("Starting metrics listener at %s", metricsScrapeAddr)
		if err := srv.ListenAndServe(); err != nil {
			logger.Infof("Httpserver: ListenAndServe() finished with error: %s", err)
		}
	}()

	<-stopCh

	// Close the http server gracefully
	ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
	defer cancel()
	srv.Shutdown(ctx)
}

func init() {
	flag.StringVar(&experimentalControllers, "experimentalControllers", "", "List of experimental controllers to include in the Knative Controller.")
	flag.BoolVar(&hardcodedLoggingConfig, "hardCodedLoggingConfig", false, "If true, use the hard coded logging config. It is intended to be used only when debugging outside a Kubernetes cluster.")
}

func getLoggingConfigOrDie() map[string]string {
	if hardcodedLoggingConfig {
		return map[string]string{
			"loglevel.controller": "info",
			"zap-logger-config": `
				{
					"level": "info",
					"development": false,
					"outputPaths": ["stdout"],
					"errorOutputPaths": ["stderr"],
					"encoding": "json",
					"encoderConfig": {
					"timeKey": "ts",
					"levelKey": "level",
					"nameKey": "logger",
					"callerKey": "caller",
					"messageKey": "msg",
					"stacktraceKey": "stacktrace",
					"lineEnding": "",
					"levelEncoder": "",
					"timeEncoder": "iso8601",
					"durationEncoder": "",
					"callerEncoder": ""
				}`,
		}
	} else {
		cm, err := configmap.Load("/etc/config-logging")
		if err != nil {
			log.Fatalf("Error loading logging configuration: %v", err)
		}
		return cm
	}
}
<|endoftext|>


<commit_before>package main

import (
	"bytes"
	"crypto/rand"
	"crypto/sha256"
	"io/ioutil"
	"log"
	"net"
	"net/http"
	"os"
	"os/signal"
	"time"

	mrand "math/rand"

	"github.com/aaronang/cong-the-ripper/lib"
	"github.com/ogier/pflag"
	"golang.org/x/crypto/pbkdf2"
)

const (
	KeyLen    = 4
	Alphabet  = lib.AlphaNumMixed
	Algorithm = lib.PBKDF2
	Iter      = 1000
)

var url string

func main() {
	ip := pflag.String("ip", "localhost", "Master IP")
	port := pflag.String("port", "8080", "Web server port")
	pflag.Parse()

	url = lib.Protocol + net.JoinHostPort(*ip, *port)

	// go func() {
	// 	for i := 0; i < 30; i++ {
	// 		if _, err := createJob(); err != nil {
	// 			log.Panicln("[createJob] Job wasn't created properly.", err)
	// 		}
	// 		time.Sleep(1 * time.Minute)
	// 	}
	// }()

	f, err := os.Create("/tmp/dat2")
	if err != nil {
		log.Panicln("[main] Creating file failed.", err)
	}
	f.WriteString("[")

	go func() {
		sigchan := make(chan os.Signal, 10)
		signal.Notify(sigchan, os.Interrupt)
		<-sigchan
		f.WriteString("\r]")
		f.Close()
		os.Exit(0)
	}()

	for {
		resp, err := http.Get(url + lib.StatusPath)
		if err != nil {
			log.Panicln("[main] Getting report failed.", err)
		}

		report, err := ioutil.ReadAll(resp.Body)
		if err != nil {
			log.Panicln("[main] Cannot read response.", err)
		}
		f.Write(report)
		f.WriteString("\n,")
		log.Println(report)

		time.Sleep(1 * time.Second)
	}
}

func createJob() (*http.Response, error) {
	body := generateJobJSON()
	return http.Post(url+lib.TasksCreatePath, lib.BodyType, bytes.NewBuffer(body))
}

func generateJobJSON() []byte {
	salt := generateSalt()
	pass := generatePassword()
	dig := generateDigest(pass, salt)

	j := lib.Job{
		Salt:      salt,
		Digest:    dig,
		KeyLen:    KeyLen,
		Iter:      Iter,
		Alphabet:  Alphabet,
		Algorithm: Algorithm,
	}
	body, err := j.ToJSON()
	if err != nil {
		log.Panicln(err)
	}
	return body
}

func generateSalt() []byte {
	b := make([]byte, mrand.Int())
	_, err := rand.Read(b)
	if err != nil {
		log.Panicln("error:", err)
	}
	return b
}

func generateDigest(pass, salt []byte) []byte {
	return pbkdf2.Key(pass, salt, Iter, sha256.Size, sha256.New)
}

func generatePassword() []byte {
	letterBytes := lib.Alphabets[Alphabet]

	b := make([]byte, KeyLen)
	for i := range b {
		b[i] = letterBytes[mrand.Intn(len(letterBytes))]
	}
	return b
}
<commit_msg>Create jobs for experiment<commit_after>package main

import (
	"bytes"
	"crypto/rand"
	"crypto/sha256"
	"io/ioutil"
	"log"
	"net"
	"net/http"
	"os"
	"os/signal"
	"time"

	mrand "math/rand"

	"github.com/aaronang/cong-the-ripper/lib"
	"github.com/ogier/pflag"
	"golang.org/x/crypto/pbkdf2"
)

const (
	KeyLen    = 4
	Alphabet  = lib.AlphaLower
	Algorithm = lib.PBKDF2
	Iter      = 1000
)

var url string

func main() {
	ip := pflag.String("ip", "localhost", "Master IP")
	port := pflag.String("port", "8080", "Web server port")
	pflag.Parse()

	url = lib.Protocol + net.JoinHostPort(*ip, *port)

	go func() {
		for i := 0; i < 2; i++ {
			if _, err := createJob(); err != nil {
				log.Panicln("[createJob] Job wasn't created properly.", err)
			}
			log.Println("[createJob] Job was created successfully.")
			time.Sleep(1 * time.Second)
		}
	}()

	f, err := os.Create("/tmp/dat2")
	if err != nil {
		log.Panicln("[main] Creating file failed.", err)
	}
	f.WriteString("[")

	go func() {
		sigchan := make(chan os.Signal, 10)
		signal.Notify(sigchan, os.Interrupt)
		<-sigchan
		f.WriteString("\r]\n")
		f.Close()
		os.Exit(0)
	}()

	for {
		resp, err := http.Get(url + lib.StatusPath)
		if err != nil {
			log.Panicln("[main] Getting report failed.", err)
		}

		report, err := ioutil.ReadAll(resp.Body)
		if err != nil {
			log.Panicln("[main] Cannot read response.", err)
		}
		f.Write(report)
		f.WriteString("\n,")
		log.Println(string(report))

		time.Sleep(1 * time.Second)
	}
}

func createJob() (*http.Response, error) {
	body := generateJobJSON()
	return http.Post(url+lib.JobsCreatePath, lib.BodyType, bytes.NewBuffer(body))
}

func generateJobJSON() []byte {
	salt := generateSalt()
	pass := generatePassword()
	dig := generateDigest(pass, salt)

	j := lib.Job{
		Salt:      salt,
		Digest:    dig,
		KeyLen:    KeyLen,
		Iter:      Iter,
		Alphabet:  Alphabet,
		Algorithm: Algorithm,
	}
	body, err := j.ToJSON()
	if err != nil {
		log.Panicln(err)
	}
	return body
}

func generateSalt() []byte {
	b := make([]byte, mrand.Intn(6)+1)
	_, err := rand.Read(b)
	if err != nil {
		log.Panicln("error:", err)
	}
	return b
}

func generateDigest(pass, salt []byte) []byte {
	return pbkdf2.Key(pass, salt, Iter, sha256.Size, sha256.New)
}

func generatePassword() []byte {
	letterBytes := lib.Alphabets[Alphabet]

	b := make([]byte, KeyLen)
	for i := range b {
		b[i] = letterBytes[mrand.Intn(len(letterBytes))]
	}
	return b
}
<|endoftext|>


<commit_before>package main

import (
	"github.com/keks/go-ipfs-colog"
	db "github.com/keks/go-ipfs-colog/immutabledb/ipfs-api"
	"gx/ipfs/QmVcLF2CgjQb5BWmYFWsDfxDjbzBfcChfdHRedxeL3dV4K/cli"

	"bufio"
	"bytes"
	"fmt"
	"io"
	"log"
	"os"
	"path"
)

var headFilePath string
var l *colog.CoLog

func fail(reasons ...interface{}) {
	fmt.Print("error: ")
	fmt.Println(reasons...)

	os.Exit(-1)
}

func init() {
	headFilePath = path.Join(os.Getenv("HOME"), ".colog-heads")
}

func updateHeadFile(l *colog.CoLog) error {
	f, err := os.Create(headFilePath)
	if err != nil {
		return err
	}

	defer f.Close()

	for _, h := range l.Heads() {
		_, err = f.WriteString(string(h) + "\n")
		if err != nil {
			return err
		}
	}
	return nil
}

var ipfsdb = db.New()

func prepareLog() (*colog.CoLog, error) {
	l = colog.New("abc", ipfsdb)

	f, err := os.Open(headFilePath)
	if err != nil { // no state to recover; all good
		log.Println("couldn't recover state; open err:", err)
		return l, nil
	}

	defer f.Close()

	bf := bufio.NewReader(f)

	for {
		line, err := bf.ReadString('\n')
		if len(line) == 0 || err != nil {
			break
		}

		line = line[:len(line)-1]

		err = l.FetchFromHead(colog.Hash(line))
		if err != nil {
			continue
		}
	}

	return l, nil
}

var (
	addCmd = cli.Command{
		Name:      "add",
		ShortName: "a",
		Usage:     "add a value to the colog",
		Flags: []cli.Flag{
			cli.BoolFlag{Name: "r"},
			cli.BoolFlag{Name: "s"},
			cli.BoolFlag{Name: "v"},
		},
		Action: func(c *cli.Context) error {
			var data interface{}

			l_old := l

			if c.Bool("r") {
				l = colog.New("abc", ipfsdb)
			}

			if c.Bool("s") {
				data = c.Args()[0]
			} else {
				b := bytes.Buffer{}

				io.Copy(&b, os.Stdin)
				data = b.String()

			}
			e, err := l.Add(data)
			if err != nil {
				return err
			}

			if c.Bool("v") {
				fmt.Println("l:")
				for _, e := range l.Items() {
					fmt.Println(e)
				}
				fmt.Println("l_old:")
				for _, e := range l_old.Items() {
					fmt.Println(e)
				}
			}

			if c.Bool("r") {
				l_old.Join(l)
				l = l_old
			}

			if !c.Bool("v") {
				fmt.Println(e)
			}
			return updateHeadFile(l)
		},
	}

	printCmd = cli.Command{
		Name:      "print",
		ShortName: "p",
		Usage:     "print the log",
		Action: func(c *cli.Context) error {
			for _, e := range l.Items() {
				fmt.Println(e)
			}

			return nil
		},
	}

	headsCmd = cli.Command{
		Name:      "heads",
		ShortName: "hs",
		Usage:     "print the heads",
		Action: func(c *cli.Context) error {
			for _, h := range l.Heads() {
				fmt.Println(h)
			}

			return nil
		},
	}
)

func main() {
	var err error
	l, err = prepareLog()
	if err != nil {
		fail(err)
	}

	app := cli.NewApp()
	app.Name = "ipfs-colog"
	app.Usage = "work with cologs"
	app.Commands = []cli.Command{addCmd, printCmd, headsCmd}
	app.Run(os.Args)
}
<commit_msg>usage for flags<commit_after>package main

import (
	"github.com/keks/go-ipfs-colog"
	db "github.com/keks/go-ipfs-colog/immutabledb/ipfs-api"
	"gx/ipfs/QmVcLF2CgjQb5BWmYFWsDfxDjbzBfcChfdHRedxeL3dV4K/cli"

	"bufio"
	"bytes"
	"fmt"
	"io"
	"log"
	"os"
	"path"
)

var headFilePath string
var l *colog.CoLog

func fail(reasons ...interface{}) {
	fmt.Print("error: ")
	fmt.Println(reasons...)

	os.Exit(-1)
}

func init() {
	headFilePath = path.Join(os.Getenv("HOME"), ".colog-heads")
}

func updateHeadFile(l *colog.CoLog) error {
	f, err := os.Create(headFilePath)
	if err != nil {
		return err
	}

	defer f.Close()

	for _, h := range l.Heads() {
		_, err = f.WriteString(string(h) + "\n")
		if err != nil {
			return err
		}
	}
	return nil
}

var ipfsdb = db.New()

func prepareLog() (*colog.CoLog, error) {
	l = colog.New("abc", ipfsdb)

	f, err := os.Open(headFilePath)
	if err != nil { // no state to recover; all good
		log.Println("couldn't recover state; open err:", err)
		return l, nil
	}

	defer f.Close()

	bf := bufio.NewReader(f)

	for {
		line, err := bf.ReadString('\n')
		if len(line) == 0 || err != nil {
			break
		}

		line = line[:len(line)-1]

		err = l.FetchFromHead(colog.Hash(line))
		if err != nil {
			continue
		}
	}

	return l, nil
}

var (
	addCmd = cli.Command{
		Name:      "add",
		ShortName: "a",
		Usage:     "add a value to the colog",
		Flags: []cli.Flag{
			cli.BoolFlag{
				Name:  "r",
				Usage: "add as new root node",
			},
			cli.BoolFlag{
				Name:  "s",
				Usage: "add string, not stdin",
			},
		},
		Action: func(c *cli.Context) error {
			var data interface{}

			l_old := l

			if c.Bool("r") {
				l = colog.New("abc", ipfsdb)
			}

			if c.Bool("s") {
				data = c.Args()[0]
			} else {
				b := bytes.Buffer{}

				io.Copy(&b, os.Stdin)
				data = b.String()

			}
			e, err := l.Add(data)
			if err != nil {
				return err
			}

			if c.GlobalBool("verbose") {
				fmt.Println("l:")
				for _, e := range l.Items() {
					fmt.Println(e)
				}
				fmt.Println("l_old:")
				for _, e := range l_old.Items() {
					fmt.Println(e)
				}
			}

			if c.Bool("r") {
				l_old.Join(l)
				l = l_old
			}

			if !c.GlobalBool("verbose") {
				fmt.Println(e)
			}
			return updateHeadFile(l)
		},
	}

	printCmd = cli.Command{
		Name:      "print",
		ShortName: "p",
		Usage:     "print the log",
		Action: func(c *cli.Context) error {
			for _, e := range l.Items() {
				fmt.Println(e)
			}

			return nil
		},
	}

	headsCmd = cli.Command{
		Name:      "heads",
		ShortName: "hs",
		Usage:     "print the heads",
		Action: func(c *cli.Context) error {
			for _, h := range l.Heads() {
				fmt.Println(h)
			}

			return nil
		},
	}
)

func main() {
	var err error
	l, err = prepareLog()
	if err != nil {
		fail(err)
	}

	app := cli.NewApp()
	app.Name = "ipfs-colog"
	app.Usage = "work with cologs"
	app.Commands = []cli.Command{addCmd, printCmd, headsCmd}
	app.Flags = []cli.Flag{
		cli.BoolFlag{
			Name:  "verbose",
			Usage: "verbose output",
		},
	}
	app.Run(os.Args)
}
<|endoftext|>


<commit_before>package main

import (
	"bufio"
	"bytes"
	"fmt"
	"os"
	"strconv"
	"strings"

	"github.com/zyedidia/tcell"
)

// TermMessage sends a message to the user in the terminal. This usually occurs before
// micro has been fully initialized -- ie if there is an error in the syntax highlighting
// regular expressions
// The function must be called when the screen is not initialized
// This will write the message, and wait for the user
// to press and key to continue
func TermMessage(msg ...interface{}) {
	screenWasNil := screen == nil
	if !screenWasNil {
		screen.Fini()
	}

	fmt.Println(msg...)
	fmt.Print("\nPress enter to continue")

	reader := bufio.NewReader(os.Stdin)
	reader.ReadString('\n')

	if !screenWasNil {
		InitScreen()
	}
}

// TermError sends an error to the user in the terminal. Like TermMessage except formatted
// as an error
func TermError(filename string, lineNum int, err string) {
	TermMessage(filename + ", " + strconv.Itoa(lineNum) + ": " + err)
}

// Messenger is an object that makes it easy to send messages to the user
// and get input from the user
type Messenger struct {
	// Are we currently prompting the user?
	hasPrompt bool
	// Is there a message to print
	hasMessage bool

	// Message to print
	message string
	// The user's response to a prompt
	response string
	// style to use when drawing the message
	style tcell.Style

	// We have to keep track of the cursor for prompting
	cursorx int

	// This map stores the history for all the different kinds of uses Prompt has
	// It's a map of history type -> history array
	history    map[string][]string
	historyNum int

	// Is the current message a message from the gutter
	gutterMessage bool
}

// Message sends a message to the user
func (m *Messenger) Message(msg ...interface{}) {
	buf := new(bytes.Buffer)
	fmt.Fprint(buf, msg...)
	m.message = buf.String()
	m.style = defStyle

	if _, ok := colorscheme["message"]; ok {
		m.style = colorscheme["message"]
	}
	m.hasMessage = true
}

// Error sends an error message to the user
func (m *Messenger) Error(msg ...interface{}) {
	buf := new(bytes.Buffer)
	fmt.Fprint(buf, msg...)
	m.message = buf.String()
	m.style = defStyle.
		Foreground(tcell.ColorBlack).
		Background(tcell.ColorMaroon)

	if _, ok := colorscheme["error-message"]; ok {
		m.style = colorscheme["error-message"]
	}
	m.hasMessage = true
}

// YesNoPrompt asks the user a yes or no question (waits for y or n) and returns the result
func (m *Messenger) YesNoPrompt(prompt string) (bool, bool) {
	m.Message(prompt)

	_, h := screen.Size()
	for {
		m.Clear()
		m.Display()
		screen.ShowCursor(Count(m.message), h-1)
		screen.Show()
		event := <-events

		switch e := event.(type) {
		case *tcell.EventKey:
			switch e.Key() {
			case tcell.KeyRune:
				if e.Rune() == 'y' {
					return true, false
				} else if e.Rune() == 'n' {
					return false, false
				}
			case tcell.KeyCtrlC, tcell.KeyCtrlQ, tcell.KeyEscape:
				return false, true
			}
		}
	}
}

type Completion int

const (
	NoCompletion Completion = iota
	FileCompletion
	CommandCompletion
	HelpCompletion
	OptionCompletion
)

// Prompt sends the user a message and waits for a response to be typed in
// This function blocks the main loop while waiting for input
func (m *Messenger) Prompt(prompt, historyType string, completionTypes ...Completion) (string, bool) {
	m.hasPrompt = true
	m.Message(prompt)
	if _, ok := m.history[historyType]; !ok {
		m.history[historyType] = []string{""}
	} else {
		m.history[historyType] = append(m.history[historyType], "")
	}
	m.historyNum = len(m.history[historyType]) - 1

	response, canceled := "", true

	RedrawAll()
	for m.hasPrompt {
		var suggestions []string
		m.Clear()

		event := <-events

		switch e := event.(type) {
		case *tcell.EventKey:
			switch e.Key() {
			case tcell.KeyCtrlQ, tcell.KeyCtrlC, tcell.KeyEscape:
				// Cancel
				m.hasPrompt = false
			case tcell.KeyEnter:
				// User is done entering their response
				m.hasPrompt = false
				response, canceled = m.response, false
				m.history[historyType][len(m.history[historyType])-1] = response
			case tcell.KeyTab:
				args := strings.Split(m.response, " ")
				currentArgNum := len(args) - 1
				currentArg := args[currentArgNum]
				var completionType Completion

				if completionTypes[0] == CommandCompletion && currentArgNum > 0 {
					if command, ok := commands[args[0]]; ok {
						completionTypes = append([]Completion{CommandCompletion}, command.completions...)
					}
				}

				if currentArgNum >= len(completionTypes) {
					completionType = completionTypes[len(completionTypes)-1]
				} else {
					completionType = completionTypes[currentArgNum]
				}

				var chosen string
				if completionType == FileCompletion {
					chosen, suggestions = FileComplete(currentArg)
				} else if completionType == CommandCompletion {
					chosen, suggestions = CommandComplete(currentArg)
				} else if completionType == HelpCompletion {
					chosen, suggestions = HelpComplete(currentArg)
				} else if completionType == OptionCompletion {
					chosen, suggestions = OptionComplete(currentArg)
				}

				if chosen != "" {
					if len(args) > 1 {
						chosen = " " + chosen
					}
					m.response = strings.Join(args[:len(args)-1], " ") + chosen
					m.cursorx = Count(m.response)
				}
			}
		}

		m.HandleEvent(event, m.history[historyType])

		messenger.Clear()
		for _, v := range tabs[curTab].views {
			v.Display()
		}
		DisplayTabs()
		messenger.Display()
		if len(suggestions) > 1 {
			m.DisplaySuggestions(suggestions)
		}
		screen.Show()
	}

	m.Reset()
	return response, canceled
}

// HandleEvent handles an event for the prompter
func (m *Messenger) HandleEvent(event tcell.Event, history []string) {
	switch e := event.(type) {
	case *tcell.EventKey:
		switch e.Key() {
		case tcell.KeyUp:
			if m.historyNum > 0 {
				m.historyNum--
				m.response = history[m.historyNum]
				m.cursorx = Count(m.response)
			}
		case tcell.KeyDown:
			if m.historyNum < len(history)-1 {
				m.historyNum++
				m.response = history[m.historyNum]
				m.cursorx = Count(m.response)
			}
		case tcell.KeyLeft:
			if m.cursorx > 0 {
				m.cursorx--
			}
		case tcell.KeyRight:
			if m.cursorx < Count(m.response) {
				m.cursorx++
			}
		case tcell.KeyBackspace2, tcell.KeyBackspace:
			if m.cursorx > 0 {
				m.response = string([]rune(m.response)[:m.cursorx-1]) + string([]rune(m.response)[m.cursorx:])
				m.cursorx--
			}
		case tcell.KeyRune:
			m.response = Insert(m.response, m.cursorx, string(e.Rune()))
			m.cursorx++
		}
		history[m.historyNum] = m.response
	}
}

// Reset resets the messenger's cursor, message and response
func (m *Messenger) Reset() {
	m.cursorx = 0
	m.message = ""
	m.response = ""
}

// Clear clears the line at the bottom of the editor
func (m *Messenger) Clear() {
	w, h := screen.Size()
	for x := 0; x < w; x++ {
		screen.SetContent(x, h-1, ' ', nil, defStyle)
	}
}

func (m *Messenger) DisplaySuggestions(suggestions []string) {
	w, screenH := screen.Size()

	y := screenH - 2

	statusLineStyle := defStyle.Reverse(true)
	if style, ok := colorscheme["statusline"]; ok {
		statusLineStyle = style
	}

	for x := 0; x < w; x++ {
		screen.SetContent(x, y, ' ', nil, statusLineStyle)
	}

	x := 1
	for _, suggestion := range suggestions {
		for _, c := range suggestion {
			screen.SetContent(x, y, c, nil, statusLineStyle)
			x++
		}
		screen.SetContent(x, y, ' ', nil, statusLineStyle)
		x++
	}
}

// Display displays messages or prompts
func (m *Messenger) Display() {
	_, h := screen.Size()
	if m.hasMessage {
		runes := []rune(m.message + m.response)
		for x := 0; x < len(runes); x++ {
			screen.SetContent(x, h-1, runes[x], nil, m.style)
		}
	}
	if m.hasPrompt {
		screen.ShowCursor(Count(m.message)+m.cursorx, h-1)
		screen.Show()
	}
}

// A GutterMessage is a message displayed on the side of the editor
type GutterMessage struct {
	lineNum int
	msg     string
	kind    int
}

// These are the different types of messages
const (
	// GutterInfo represents a simple info message
	GutterInfo = iota
	// GutterWarning represents a compiler warning
	GutterWarning
	// GutterError represents a compiler error
	GutterError
)
<commit_msg>Add pasting in command mode<commit_after>package main

import (
	"bufio"
	"bytes"
	"fmt"
	"os"
	"strconv"
	"strings"

	"github.com/zyedidia/clipboard"
	"github.com/zyedidia/tcell"
)

// TermMessage sends a message to the user in the terminal. This usually occurs before
// micro has been fully initialized -- ie if there is an error in the syntax highlighting
// regular expressions
// The function must be called when the screen is not initialized
// This will write the message, and wait for the user
// to press and key to continue
func TermMessage(msg ...interface{}) {
	screenWasNil := screen == nil
	if !screenWasNil {
		screen.Fini()
	}

	fmt.Println(msg...)
	fmt.Print("\nPress enter to continue")

	reader := bufio.NewReader(os.Stdin)
	reader.ReadString('\n')

	if !screenWasNil {
		InitScreen()
	}
}

// TermError sends an error to the user in the terminal. Like TermMessage except formatted
// as an error
func TermError(filename string, lineNum int, err string) {
	TermMessage(filename + ", " + strconv.Itoa(lineNum) + ": " + err)
}

// Messenger is an object that makes it easy to send messages to the user
// and get input from the user
type Messenger struct {
	// Are we currently prompting the user?
	hasPrompt bool
	// Is there a message to print
	hasMessage bool

	// Message to print
	message string
	// The user's response to a prompt
	response string
	// style to use when drawing the message
	style tcell.Style

	// We have to keep track of the cursor for prompting
	cursorx int

	// This map stores the history for all the different kinds of uses Prompt has
	// It's a map of history type -> history array
	history    map[string][]string
	historyNum int

	// Is the current message a message from the gutter
	gutterMessage bool
}

// Message sends a message to the user
func (m *Messenger) Message(msg ...interface{}) {
	buf := new(bytes.Buffer)
	fmt.Fprint(buf, msg...)
	m.message = buf.String()
	m.style = defStyle

	if _, ok := colorscheme["message"]; ok {
		m.style = colorscheme["message"]
	}
	m.hasMessage = true
}

// Error sends an error message to the user
func (m *Messenger) Error(msg ...interface{}) {
	buf := new(bytes.Buffer)
	fmt.Fprint(buf, msg...)
	m.message = buf.String()
	m.style = defStyle.
		Foreground(tcell.ColorBlack).
		Background(tcell.ColorMaroon)

	if _, ok := colorscheme["error-message"]; ok {
		m.style = colorscheme["error-message"]
	}
	m.hasMessage = true
}

// YesNoPrompt asks the user a yes or no question (waits for y or n) and returns the result
func (m *Messenger) YesNoPrompt(prompt string) (bool, bool) {
	m.Message(prompt)

	_, h := screen.Size()
	for {
		m.Clear()
		m.Display()
		screen.ShowCursor(Count(m.message), h-1)
		screen.Show()
		event := <-events

		switch e := event.(type) {
		case *tcell.EventKey:
			switch e.Key() {
			case tcell.KeyRune:
				if e.Rune() == 'y' {
					return true, false
				} else if e.Rune() == 'n' {
					return false, false
				}
			case tcell.KeyCtrlC, tcell.KeyCtrlQ, tcell.KeyEscape:
				return false, true
			}
		}
	}
}

type Completion int

const (
	NoCompletion Completion = iota
	FileCompletion
	CommandCompletion
	HelpCompletion
	OptionCompletion
)

// Prompt sends the user a message and waits for a response to be typed in
// This function blocks the main loop while waiting for input
func (m *Messenger) Prompt(prompt, historyType string, completionTypes ...Completion) (string, bool) {
	m.hasPrompt = true
	m.Message(prompt)
	if _, ok := m.history[historyType]; !ok {
		m.history[historyType] = []string{""}
	} else {
		m.history[historyType] = append(m.history[historyType], "")
	}
	m.historyNum = len(m.history[historyType]) - 1

	response, canceled := "", true

	RedrawAll()
	for m.hasPrompt {
		var suggestions []string
		m.Clear()

		event := <-events

		switch e := event.(type) {
		case *tcell.EventKey:
			switch e.Key() {
			case tcell.KeyCtrlQ, tcell.KeyCtrlC, tcell.KeyEscape:
				// Cancel
				m.hasPrompt = false
			case tcell.KeyEnter:
				// User is done entering their response
				m.hasPrompt = false
				response, canceled = m.response, false
				m.history[historyType][len(m.history[historyType])-1] = response
			case tcell.KeyTab:
				args := strings.Split(m.response, " ")
				currentArgNum := len(args) - 1
				currentArg := args[currentArgNum]
				var completionType Completion

				if completionTypes[0] == CommandCompletion && currentArgNum > 0 {
					if command, ok := commands[args[0]]; ok {
						completionTypes = append([]Completion{CommandCompletion}, command.completions...)
					}
				}

				if currentArgNum >= len(completionTypes) {
					completionType = completionTypes[len(completionTypes)-1]
				} else {
					completionType = completionTypes[currentArgNum]
				}

				var chosen string
				if completionType == FileCompletion {
					chosen, suggestions = FileComplete(currentArg)
				} else if completionType == CommandCompletion {
					chosen, suggestions = CommandComplete(currentArg)
				} else if completionType == HelpCompletion {
					chosen, suggestions = HelpComplete(currentArg)
				} else if completionType == OptionCompletion {
					chosen, suggestions = OptionComplete(currentArg)
				}

				if chosen != "" {
					if len(args) > 1 {
						chosen = " " + chosen
					}
					m.response = strings.Join(args[:len(args)-1], " ") + chosen
					m.cursorx = Count(m.response)
				}
			}
		}

		m.HandleEvent(event, m.history[historyType])

		messenger.Clear()
		for _, v := range tabs[curTab].views {
			v.Display()
		}
		DisplayTabs()
		messenger.Display()
		if len(suggestions) > 1 {
			m.DisplaySuggestions(suggestions)
		}
		screen.Show()
	}

	m.Reset()
	return response, canceled
}

// HandleEvent handles an event for the prompter
func (m *Messenger) HandleEvent(event tcell.Event, history []string) {
	switch e := event.(type) {
	case *tcell.EventKey:
		switch e.Key() {
		case tcell.KeyUp:
			if m.historyNum > 0 {
				m.historyNum--
				m.response = history[m.historyNum]
				m.cursorx = Count(m.response)
			}
		case tcell.KeyDown:
			if m.historyNum < len(history)-1 {
				m.historyNum++
				m.response = history[m.historyNum]
				m.cursorx = Count(m.response)
			}
		case tcell.KeyLeft:
			if m.cursorx > 0 {
				m.cursorx--
			}
		case tcell.KeyRight:
			if m.cursorx < Count(m.response) {
				m.cursorx++
			}
		case tcell.KeyBackspace2, tcell.KeyBackspace:
			if m.cursorx > 0 {
				m.response = string([]rune(m.response)[:m.cursorx-1]) + string([]rune(m.response)[m.cursorx:])
				m.cursorx--
			}
		case tcell.KeyCtrlV:
			clip, _ := clipboard.ReadAll()
			m.response = Insert(m.response, m.cursorx, clip)
			m.cursorx += Count(clip)
		case tcell.KeyRune:
			m.response = Insert(m.response, m.cursorx, string(e.Rune()))
			m.cursorx++
		}
		history[m.historyNum] = m.response

	case *tcell.EventPaste:
		clip := e.Text()
		m.response = Insert(m.response, m.cursorx, clip)
		m.cursorx += Count(clip)
	}
}

// Reset resets the messenger's cursor, message and response
func (m *Messenger) Reset() {
	m.cursorx = 0
	m.message = ""
	m.response = ""
}

// Clear clears the line at the bottom of the editor
func (m *Messenger) Clear() {
	w, h := screen.Size()
	for x := 0; x < w; x++ {
		screen.SetContent(x, h-1, ' ', nil, defStyle)
	}
}

func (m *Messenger) DisplaySuggestions(suggestions []string) {
	w, screenH := screen.Size()

	y := screenH - 2

	statusLineStyle := defStyle.Reverse(true)
	if style, ok := colorscheme["statusline"]; ok {
		statusLineStyle = style
	}

	for x := 0; x < w; x++ {
		screen.SetContent(x, y, ' ', nil, statusLineStyle)
	}

	x := 1
	for _, suggestion := range suggestions {
		for _, c := range suggestion {
			screen.SetContent(x, y, c, nil, statusLineStyle)
			x++
		}
		screen.SetContent(x, y, ' ', nil, statusLineStyle)
		x++
	}
}

// Display displays messages or prompts
func (m *Messenger) Display() {
	_, h := screen.Size()
	if m.hasMessage {
		runes := []rune(m.message + m.response)
		for x := 0; x < len(runes); x++ {
			screen.SetContent(x, h-1, runes[x], nil, m.style)
		}
	}
	if m.hasPrompt {
		screen.ShowCursor(Count(m.message)+m.cursorx, h-1)
		screen.Show()
	}
}

// A GutterMessage is a message displayed on the side of the editor
type GutterMessage struct {
	lineNum int
	msg     string
	kind    int
}

// These are the different types of messages
const (
	// GutterInfo represents a simple info message
	GutterInfo = iota
	// GutterWarning represents a compiler warning
	GutterWarning
	// GutterError represents a compiler error
	GutterError
)
<|endoftext|>


<commit_before>// Copyright (c) 2015-2022 MinIO, Inc.
//
// This file is part of MinIO Object Storage stack
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License
// along with this program.  If not, see <http://www.gnu.org/licenses/>.

package cmd

import (
	"fmt"
	"sort"
	"strings"
	"sync/atomic"
	"time"

	"github.com/charmbracelet/bubbles/spinner"
	tea "github.com/charmbracelet/bubbletea"
	"github.com/charmbracelet/lipgloss"
	humanize "github.com/dustin/go-humanize"
	"github.com/minio/madmin-go"
	"github.com/olekukonko/tablewriter"
)

// TODO: Add ART (Average Response Time) latency
type topAPIStats struct {
	TotalCalls   uint64
	TotalBytesRX uint64
	TotalBytesTX uint64
}

func (s *topAPIStats) addAPICall(n int) {
	atomic.AddUint64(&s.TotalCalls, uint64(n))
}

func (s *topAPIStats) addAPIBytesRX(n int) {
	atomic.AddUint64(&s.TotalBytesRX, uint64(n))
}

func (s *topAPIStats) addAPIBytesTX(n int) {
	atomic.AddUint64(&s.TotalBytesTX, uint64(n))
}

func (s *topAPIStats) loadAPICall() uint64 {
	return atomic.LoadUint64(&s.TotalCalls)
}

func (s *topAPIStats) loadAPIBytesRX() uint64 {
	return atomic.LoadUint64(&s.TotalBytesRX)
}

func (s *topAPIStats) loadAPIBytesTX() uint64 {
	return atomic.LoadUint64(&s.TotalBytesTX)
}

type traceUI struct {
	spinner     spinner.Model
	quitting    bool
	startTime   time.Time
	result      topAPIResult
	apiStatsMap map[string]*topAPIStats
}

type topAPIResult struct {
	final       bool
	apiCallInfo madmin.ServiceTraceInfo
}

func initTraceUI() *traceUI {
	s := spinner.New()
	s.Spinner = spinner.Points
	s.Style = lipgloss.NewStyle().Foreground(lipgloss.Color("205"))
	return &traceUI{
		spinner:     s,
		startTime:   time.Now(),
		apiStatsMap: make(map[string]*topAPIStats),
	}
}

func (m *traceUI) Init() tea.Cmd {
	return m.spinner.Tick
}

func (m *traceUI) Update(msg tea.Msg) (tea.Model, tea.Cmd) {
	switch msg := msg.(type) {
	case tea.KeyMsg:
		switch msg.String() {
		case "ctrl+c":
			m.quitting = true
			return m, tea.Quit
		default:
			return m, nil
		}
	case topAPIResult:
		m.result = msg
		if msg.final {
			m.quitting = true
			return m, tea.Quit
		}
		return m, nil

	case spinner.TickMsg:
		var cmd tea.Cmd
		m.spinner, cmd = m.spinner.Update(msg)
		return m, cmd
	default:
		return m, nil
	}
}

func (m *traceUI) View() string {
	var s strings.Builder
	s.WriteString("\n")

	// Set table header
	table := tablewriter.NewWriter(&s)
	table.SetAutoWrapText(false)
	table.SetAutoFormatHeaders(true)
	table.SetHeaderAlignment(tablewriter.ALIGN_LEFT)
	table.SetAlignment(tablewriter.ALIGN_LEFT)
	table.SetCenterSeparator("")
	table.SetColumnSeparator("")
	table.SetRowSeparator("")
	table.SetHeaderLine(false)
	table.SetBorder(false)
	table.SetTablePadding("\t") // pad with tabs
	table.SetNoWhiteSpace(true)

	res := m.result.apiCallInfo
	if res.Trace.FuncName != "" && res.Trace.FuncName != "errorResponseHandler" {
		traceSt, ok := m.apiStatsMap[res.Trace.FuncName]
		if !ok {
			traceSt = &topAPIStats{}
		}
		traceSt.addAPICall(1)
		traceSt.addAPIBytesRX(res.Trace.CallStats.InputBytes)
		traceSt.addAPIBytesTX(res.Trace.CallStats.OutputBytes)
		m.apiStatsMap[res.Trace.FuncName] = traceSt
	}

	table.SetHeader([]string{"API", "RX", "TX", "N"})
	data := make([][]string, 0, len(m.apiStatsMap))

	for k, stats := range m.apiStatsMap {
		data = append(data, []string{
			k,
			whiteStyle.Render(humanize.IBytes(stats.loadAPIBytesRX())),
			whiteStyle.Render(humanize.IBytes(stats.loadAPIBytesTX())),
			whiteStyle.Render(fmt.Sprintf("%d", stats.loadAPICall())),
		})
	}
	sort.Slice(data, func(i, j int) bool {
		return data[i][0] < data[j][0]
	})

	table.AppendBulk(data)
	table.Render()

	if !m.quitting {
		s.WriteString(fmt.Sprintf("\nTopAPI: %s", m.spinner.View()))
	} else {
		var totalTX, totalRX, totalCalls uint64
		currentTime := time.Now()
		duration := currentTime.Sub(m.startTime).Seconds()
		if duration == 0 {
			duration = 1 // duration is always 1-sec atleast
		}
		for _, stats := range m.apiStatsMap {
			totalRX += stats.loadAPIBytesRX()
			totalTX += stats.loadAPIBytesTX()
			totalCalls += stats.loadAPICall()
		}
		msg := fmt.Sprintf("\n========\n%d IOP/s, RX %s/s, TX %s/s - in the last %s",
			totalCalls/uint64(duration),
			humanize.IBytes(totalRX/uint64(duration)),
			humanize.IBytes(totalTX/uint64(duration)),
			humanize.RelTime(m.startTime, currentTime, "", ""),
		)
		s.WriteString(msg)
		s.WriteString("\n")
	}
	return s.String()
}
<commit_msg>fix: 'mc admin top api' IOPs, RX/TX remove them (#4115)<commit_after>// Copyright (c) 2015-2022 MinIO, Inc.
//
// This file is part of MinIO Object Storage stack
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License
// along with this program.  If not, see <http://www.gnu.org/licenses/>.

package cmd

import (
	"fmt"
	"sort"
	"strings"
	"sync/atomic"
	"time"

	"github.com/charmbracelet/bubbles/spinner"
	tea "github.com/charmbracelet/bubbletea"
	"github.com/charmbracelet/lipgloss"
	humanize "github.com/dustin/go-humanize"
	"github.com/minio/madmin-go"
	"github.com/olekukonko/tablewriter"
)

// TODO: Add ART (Average Response Time) latency
type topAPIStats struct {
	TotalCalls   uint64
	TotalBytesRX uint64
	TotalBytesTX uint64
}

func (s *topAPIStats) addAPICall(n int) {
	atomic.AddUint64(&s.TotalCalls, uint64(n))
}

func (s *topAPIStats) addAPIBytesRX(n int) {
	atomic.AddUint64(&s.TotalBytesRX, uint64(n))
}

func (s *topAPIStats) addAPIBytesTX(n int) {
	atomic.AddUint64(&s.TotalBytesTX, uint64(n))
}

func (s *topAPIStats) loadAPICall() uint64 {
	return atomic.LoadUint64(&s.TotalCalls)
}

func (s *topAPIStats) loadAPIBytesRX() uint64 {
	return atomic.LoadUint64(&s.TotalBytesRX)
}

func (s *topAPIStats) loadAPIBytesTX() uint64 {
	return atomic.LoadUint64(&s.TotalBytesTX)
}

type traceUI struct {
	spinner     spinner.Model
	quitting    bool
	startTime   time.Time
	result      topAPIResult
	lastResult  topAPIResult
	apiStatsMap map[string]*topAPIStats
}

type topAPIResult struct {
	final       bool
	apiCallInfo madmin.ServiceTraceInfo
}

func initTraceUI() *traceUI {
	s := spinner.New()
	s.Spinner = spinner.Points
	s.Style = lipgloss.NewStyle().Foreground(lipgloss.Color("205"))
	return &traceUI{
		spinner:     s,
		apiStatsMap: make(map[string]*topAPIStats),
	}
}

func (m *traceUI) Init() tea.Cmd {
	return m.spinner.Tick
}

func (m *traceUI) Update(msg tea.Msg) (tea.Model, tea.Cmd) {
	switch msg := msg.(type) {
	case tea.KeyMsg:
		switch msg.String() {
		case "ctrl+c":
			m.quitting = true
			return m, tea.Quit
		default:
			return m, nil
		}
	case topAPIResult:
		m.result = msg
		if m.result.apiCallInfo.Trace.FuncName != "" {
			m.lastResult = m.result
		}
		if msg.final {
			m.quitting = true
			return m, tea.Quit
		}
		return m, nil

	case spinner.TickMsg:
		var cmd tea.Cmd
		m.spinner, cmd = m.spinner.Update(msg)
		return m, cmd
	default:
		return m, nil
	}
}

func (m *traceUI) View() string {
	var s strings.Builder
	s.WriteString("\n")

	// Set table header
	table := tablewriter.NewWriter(&s)
	table.SetAutoWrapText(false)
	table.SetAutoFormatHeaders(true)
	table.SetHeaderAlignment(tablewriter.ALIGN_LEFT)
	table.SetAlignment(tablewriter.ALIGN_LEFT)
	table.SetCenterSeparator("")
	table.SetColumnSeparator("")
	table.SetRowSeparator("")
	table.SetHeaderLine(false)
	table.SetBorder(false)
	table.SetTablePadding("\t") // pad with tabs
	table.SetNoWhiteSpace(true)

	res := m.result.apiCallInfo
	if m.startTime.IsZero() && !res.Trace.Time.IsZero() {
		m.startTime = res.Trace.Time
	}
	if res.Trace.FuncName != "" && res.Trace.FuncName != "errorResponseHandler" {
		traceSt, ok := m.apiStatsMap[res.Trace.FuncName]
		if !ok {
			traceSt = &topAPIStats{}
		}
		traceSt.addAPICall(1)
		traceSt.addAPIBytesRX(res.Trace.CallStats.InputBytes)
		traceSt.addAPIBytesTX(res.Trace.CallStats.OutputBytes)
		m.apiStatsMap[res.Trace.FuncName] = traceSt
	}

	table.SetHeader([]string{"API", "RX", "TX", "N"})
	data := make([][]string, 0, len(m.apiStatsMap))

	for k, stats := range m.apiStatsMap {
		data = append(data, []string{
			k,
			whiteStyle.Render(humanize.IBytes(stats.loadAPIBytesRX())),
			whiteStyle.Render(humanize.IBytes(stats.loadAPIBytesTX())),
			whiteStyle.Render(fmt.Sprintf("%d", stats.loadAPICall())),
		})
	}
	sort.Slice(data, func(i, j int) bool {
		return data[i][0] < data[j][0]
	})

	table.AppendBulk(data)
	table.Render()

	if !m.quitting {
		s.WriteString(fmt.Sprintf("\nTopAPI: %s", m.spinner.View()))
	} else {
		var totalTX, totalRX, totalCalls uint64
		lastReqTime := m.lastResult.apiCallInfo.Trace.Time
		if m.lastResult.apiCallInfo.Trace.Time.IsZero() {
			lastReqTime = time.Now()
		}
		for _, stats := range m.apiStatsMap {
			totalRX += stats.loadAPIBytesRX()
			totalTX += stats.loadAPIBytesTX()
			totalCalls += stats.loadAPICall()
		}
		msg := fmt.Sprintf("\n========\nTotal: %d Calls, %s RX, %s TX - in %.02fs",
			totalCalls,
			humanize.IBytes(totalRX),
			humanize.IBytes(totalTX),
			lastReqTime.Sub(m.startTime).Seconds(),
		)
		s.WriteString(msg)
		s.WriteString("\n")
	}
	return s.String()
}
<|endoftext|>


<commit_before>package main

import (
	"fmt"
	"math/rand"
	"os/exec"
	"time"

	"github.com/andrewcopp/coup"
)

func init() {

}

func main() {

	for i := 0; i < 10; i++ {

		if i != 0 {
			infile := fmt.Sprintf("./cmd/trainer/models/model_%d.cptk", i)
			outfile := fmt.Sprintf("./cmd/trainer/models/model_%d.cptk", i+1)
			if err := exec.Command("python3", "/home/ubuntu/reinforcement/transfer.py", infile, outfile).Run(); err != nil {
				fmt.Println(err)
			}
		} else {
			outfile := fmt.Sprintf("./cmd/trainer/models/model_%d.cptk", i+1)
			if err := exec.Command("python3", "/home/ubuntu/reinforcement/initialize.py", outfile).Run(); err != nil {
				fmt.Println(err)
			}
		}

		wins := 0
		losses := 0
		var chooser coup.Chooser
		chooser = coup.NewAgent(i, 1.0/float64(i))
		one := coup.NewPlayer("Player One", chooser, false)
		for j := 0; j < 1000; j++ {
			rand.Seed(time.Now().UnixNano())
			if i > 0 {
				chooser = coup.NewAgent(rand.Intn(i), 0.0)
			} else {
				chooser = coup.NewRandom()
			}
			two := coup.NewPlayer("Player Two", chooser, false)
			chooser = coup.NewRandom()
			three := coup.NewPlayer("Player Three", chooser, true)
			four := coup.NewPlayer("Player Four", chooser, true)
			five := coup.NewPlayer("Player Five", chooser, true)

			game := coup.NewGame([]*coup.Player{one, two, three, four, five})

			game.Setup()
			winner := game.Play()
			if winner == one {
				one.Chooser.Record(true)
				wins++
			} else {
				one.Chooser.Record(false)
				losses++
			}

			fmt.Printf("Agent %d completed game %d.\n", i, j)
		}
		fmt.Println(float64(wins)/float64((wins+losses))*100.0, "%")
	}

}
<commit_msg>Resetting Player Every Game<commit_after>package main

import (
	"fmt"
	"math/rand"
	"os/exec"
	"time"

	"github.com/andrewcopp/coup"
)

func init() {

}

func main() {

	for i := 0; i < 10; i++ {

		if i != 0 {
			infile := fmt.Sprintf("./cmd/trainer/models/model_%d.cptk", i)
			outfile := fmt.Sprintf("./cmd/trainer/models/model_%d.cptk", i+1)
			if err := exec.Command("python3", "/home/ubuntu/reinforcement/transfer.py", infile, outfile).Run(); err != nil {
				fmt.Println(err)
			}
		} else {
			outfile := fmt.Sprintf("./cmd/trainer/models/model_%d.cptk", i+1)
			if err := exec.Command("python3", "/home/ubuntu/reinforcement/initialize.py", outfile).Run(); err != nil {
				fmt.Println(err)
			}
		}

		wins := 0
		losses := 0
		for j := 0; j < 1000; j++ {
			var chooser coup.Chooser
			chooser = coup.NewAgent(i, 1.0/float64(i))
			one := coup.NewPlayer("Player One", chooser, false)
			rand.Seed(time.Now().UnixNano())
			if i > 0 {
				chooser = coup.NewAgent(rand.Intn(i), 0.0)
			} else {
				chooser = coup.NewRandom()
			}
			two := coup.NewPlayer("Player Two", chooser, false)
			chooser = coup.NewRandom()
			three := coup.NewPlayer("Player Three", chooser, true)
			four := coup.NewPlayer("Player Four", chooser, true)
			five := coup.NewPlayer("Player Five", chooser, true)

			game := coup.NewGame([]*coup.Player{one, two, three, four, five})

			game.Setup()
			winner := game.Play()
			if winner == one {
				one.Chooser.Record(true)
				wins++
			} else {
				one.Chooser.Record(false)
				losses++
			}

			fmt.Printf("Agent %d completed game %d.\n", i, j)
		}
		fmt.Println(float64(wins)/float64((wins+losses))*100.0, "%")
	}

}
<|endoftext|>


<commit_before>package cmd

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

	"github.com/codeclimate/test-reporter/formatters"
	"github.com/codeclimate/test-reporter/version"
	"github.com/gobuffalo/envy"
	"github.com/pkg/errors"
	"github.com/spf13/cobra"
)

type Uploader struct {
	Input       string
	ReporterID  string
	EndpointURL string
}

var uploadOptions = Uploader{}

// uploadCoverageCmd represents the upload command
var uploadCoverageCmd = &cobra.Command{
	Use:   "upload-coverage",
	Short: "Upload pre-formatted coverage payloads to Code Climate servers.",
	RunE: func(cmd *cobra.Command, args []string) error {
		return uploadOptions.Upload()
	},
}

func (u Uploader) Upload() error {
	if u.ReporterID == "" {
		return errors.New("you must supply a CC_TEST_REPORTER_ID ENV variable or pass it via the -r flag")
	}

	var err error
	var in io.Reader
	if u.Input == "-" {
		in = os.Stdin
	} else {
		in, err = os.Open(u.Input)
		if err != nil {
			return errors.WithStack(err)
		}
	}

	// we need to read in the JSON file
	// and set the repo_token to whatever
	// is being set at upload time.
	rep, err := formatters.NewReport()
	if err != nil {
		return errors.WithStack(err)
	}

	err = json.NewDecoder(in).Decode(&rep)
	if err != nil {
		return errors.WithStack(err)
	}
	rep.RepoToken = uploadOptions.ReporterID

	pr, pw := io.Pipe()
	go func() {
		defer pw.Close()
		json.NewEncoder(pw).Encode(rep)
	}()

	c := http.Client{
		Timeout: 30 * time.Second,
	}

	req, err := u.newRequest(pr)
	if err != nil {
		return errors.WithStack(err)
	}

	res, err := c.Do(req)
	if err != nil {
		return errors.WithStack(err)
	}

	io.Copy(os.Stdout, res.Body)

	if res.StatusCode < 200 || res.StatusCode >= 300 {
		return fmt.Errorf("response from %s was %d", u.EndpointURL, res.StatusCode)
	}
	fmt.Printf("Status: %d\n", res.StatusCode)
	return nil
}

func (u Uploader) newRequest(in io.Reader) (*http.Request, error) {
	req, err := http.NewRequest("POST", u.EndpointURL, in)
	if err != nil {
		return nil, errors.WithStack(err)
	}
	req.Header.Set("User-Agent", fmt.Sprintf("TestReporter/%s (Code Climate, Inc.)", version.Version))
	req.Header.Set("Content-Type", "application/json")
	return req, err
}

func init() {
	uploadCoverageCmd.Flags().StringVarP(&uploadOptions.Input, "input", "i", ccDefaultCoveragePath, "input path")
	uploadCoverageCmd.Flags().StringVarP(&uploadOptions.ReporterID, "id", "r", os.Getenv("CC_TEST_REPORTER_ID"), "reporter identifier")
	uploadCoverageCmd.Flags().StringVarP(&uploadOptions.EndpointURL, "endpoint", "e", envy.Get("CC_TEST_REPORTER_COVERAGE_ENDPOINT", "https://codeclimate.com/test_reports"), "endpoint to upload coverage information to")
	RootCmd.AddCommand(uploadCoverageCmd)
}
<commit_msg>added a debug flag. covers both #73 and #71<commit_after>package cmd

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

	"github.com/codeclimate/test-reporter/formatters"
	"github.com/codeclimate/test-reporter/version"
	"github.com/gobuffalo/envy"
	"github.com/pkg/errors"
	"github.com/spf13/cobra"
)

type Uploader struct {
	Input       string
	ReporterID  string
	EndpointURL string
	Debug       bool
}

var uploadOptions = Uploader{}

// uploadCoverageCmd represents the upload command
var uploadCoverageCmd = &cobra.Command{
	Use:   "upload-coverage",
	Short: "Upload pre-formatted coverage payloads to Code Climate servers.",
	RunE: func(cmd *cobra.Command, args []string) error {
		return uploadOptions.Upload()
	},
}

func (u Uploader) Upload() error {
	if u.ReporterID == "" {
		return errors.New("you must supply a CC_TEST_REPORTER_ID ENV variable or pass it via the -r flag")
	}

	var err error
	var in io.Reader
	if u.Input == "-" {
		in = os.Stdin
	} else {
		in, err = os.Open(u.Input)
		if err != nil {
			return errors.WithStack(err)
		}
	}

	// we need to read in the JSON file
	// and set the repo_token to whatever
	// is being set at upload time.
	rep, err := formatters.NewReport()
	if err != nil {
		return errors.WithStack(err)
	}

	err = json.NewDecoder(in).Decode(&rep)
	if err != nil {
		return errors.WithStack(err)
	}
	rep.RepoToken = uploadOptions.ReporterID

	pr, pw := io.Pipe()
	go func() {
		defer pw.Close()
		json.NewEncoder(pw).Encode(rep)
	}()

	c := http.Client{
		Timeout: 30 * time.Second,
	}

	req, err := u.newRequest(pr)
	if err != nil {
		return errors.WithStack(err)
	}

	res, err := c.Do(req)
	if err != nil {
		return errors.WithStack(err)
	}

	if u.Debug {
		io.Copy(os.Stdout, res.Body)
	}

	if res.StatusCode < 200 || res.StatusCode >= 300 {
		return fmt.Errorf("response from %s was %d", u.EndpointURL, res.StatusCode)
	}
	fmt.Printf("Status: %d\n", res.StatusCode)
	return nil
}

func (u Uploader) newRequest(in io.Reader) (*http.Request, error) {
	req, err := http.NewRequest("POST", u.EndpointURL, in)
	if err != nil {
		return nil, errors.WithStack(err)
	}
	req.Header.Set("User-Agent", fmt.Sprintf("TestReporter/%s (Code Climate, Inc.)", version.Version))
	req.Header.Set("Content-Type", "application/json")
	return req, err
}

func init() {
	uploadCoverageCmd.Flags().BoolVarP(&uploadOptions.Debug, "debug", "d", false, "debug")
	uploadCoverageCmd.Flags().StringVarP(&uploadOptions.Input, "input", "i", ccDefaultCoveragePath, "input path")
	uploadCoverageCmd.Flags().StringVarP(&uploadOptions.ReporterID, "id", "r", os.Getenv("CC_TEST_REPORTER_ID"), "reporter identifier")
	uploadCoverageCmd.Flags().StringVarP(&uploadOptions.EndpointURL, "endpoint", "e", envy.Get("CC_TEST_REPORTER_COVERAGE_ENDPOINT", "https://codeclimate.com/test_reports"), "endpoint to upload coverage information to")
	RootCmd.AddCommand(uploadCoverageCmd)
}
<|endoftext|>