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

package testlapack

import (
	"testing"

	"golang.org/x/exp/rand"
	"gonum.org/v1/gonum/blas/blas64"
)

type Dorg2ler interface {
	Dorg2l(m, n, k int, a []float64, lda int, tau, work []float64)
	Dgeql2er
}

func Dorg2lTest(t *testing.T, impl Dorg2ler) {
	rnd := rand.New(rand.NewSource(1))
	for _, test := range []struct {
		m, n, k, lda int
	}{
		{5, 4, 3, 0},
		{5, 4, 4, 0},
		{3, 3, 2, 0},
		{5, 5, 5, 0},
		{5, 4, 3, 11},
		{5, 4, 4, 11},
		{3, 3, 2, 11},
		{5, 5, 5, 11},
	} {
		m := test.m
		n := test.n
		k := test.k
		lda := test.lda
		if lda == 0 {
			lda = n
		}

		a := make([]float64, m*lda)
		for i := range a {
			a[i] = rnd.NormFloat64()
		}
		tau := nanSlice(max(m, n))
		work := make([]float64, n)
		impl.Dgeql2(m, n, a, lda, tau, work)

		impl.Dorg2l(m, n, k, a, lda, tau[n-k:], work)
		if !hasOrthonormalColumns(blas64.General{m, n, lda, a}) {
			t.Errorf("Case m=%v, n=%v, k=%v: columns of Q not orthonormal", m, n, k)
		}
	}
}
<commit_msg>lapack/testlapack: separate gonum import by blank line<commit_after>// Copyright ©2016 The Gonum Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.

package testlapack

import (
	"testing"

	"golang.org/x/exp/rand"

	"gonum.org/v1/gonum/blas/blas64"
)

type Dorg2ler interface {
	Dorg2l(m, n, k int, a []float64, lda int, tau, work []float64)
	Dgeql2er
}

func Dorg2lTest(t *testing.T, impl Dorg2ler) {
	rnd := rand.New(rand.NewSource(1))
	for _, test := range []struct {
		m, n, k, lda int
	}{
		{5, 4, 3, 0},
		{5, 4, 4, 0},
		{3, 3, 2, 0},
		{5, 5, 5, 0},
		{5, 4, 3, 11},
		{5, 4, 4, 11},
		{3, 3, 2, 11},
		{5, 5, 5, 11},
	} {
		m := test.m
		n := test.n
		k := test.k
		lda := test.lda
		if lda == 0 {
			lda = n
		}

		a := make([]float64, m*lda)
		for i := range a {
			a[i] = rnd.NormFloat64()
		}
		tau := nanSlice(max(m, n))
		work := make([]float64, n)
		impl.Dgeql2(m, n, a, lda, tau, work)

		impl.Dorg2l(m, n, k, a, lda, tau[n-k:], work)
		if !hasOrthonormalColumns(blas64.General{m, n, lda, a}) {
			t.Errorf("Case m=%v, n=%v, k=%v: columns of Q not orthonormal", m, n, k)
		}
	}
}
<|endoftext|>


<commit_before>package task

import (
	"neon/build"
	"neon/util"
)

func init() {
	build.TaskMap["pass"] = build.TaskDescriptor{
		Constructor: Pass,
		Help: `Does nothing.

Arguments:

- none

Examples:

    # do nothing
    - pass:

Notes:

- Useful when an instruction is mandatory but we want to do nothing (in a catch
  instruction for instance). For instance, to run a command and don't stop the
  build even if it fails, we could write:

        - try:
          - "command-that-doesnt-exist"
          catch:
          - pass:

- This implementation is super optimized for speed.`,
	}
}

func Pass(target *build.Target, args util.Object) (build.Task, error) {
	fields := []string{"pass"}
	if err := CheckFields(args, fields, fields); err != nil {
		return nil, err
	}
	return func() error {
		return nil
	}, nil
}
<commit_msg>Fixed pass task documentation<commit_after>package task

import (
	"neon/build"
	"neon/util"
)

func init() {
	build.TaskMap["pass"] = build.TaskDescriptor{
		Constructor: Pass,
		Help: `Does nothing.

Arguments:

- none

Examples:

    # do nothing
    - pass:

Notes:

- This implementation is super optimized for speed.`,
	}
}

func Pass(target *build.Target, args util.Object) (build.Task, error) {
	fields := []string{"pass"}
	if err := CheckFields(args, fields, fields); err != nil {
		return nil, err
	}
	return func() error {
		return nil
	}, nil
}
<|endoftext|>


<commit_before>package amqptee

import (
	"database/sql"
	"io/ioutil"
  "fmt"
	"log"
	"time"

	_ "code.google.com/p/gosqlite/sqlite3"
	_ "github.com/go-sql-driver/mysql"
	_ "github.com/lib/pq"
	"github.com/modcloth-labs/schema_ensurer"
	"github.com/nu7hatch/gouuid"
	"github.com/streadway/amqp"
)

var (
	migrationFormats = map[string][]string{
		"20131108000000_%s": {`
	  CREATE TABLE IF NOT EXISTS %s(
		uuid char(32),

    content_type character varying(256),
    content_encoding character varying(256),
    delivery_mode smallint,
    priority smallint,
    correlation_id character varying(256),
    reply_to character varying(256),
    expiration character varying(256),
    timestamp timestamp with time zone,
    type character varying(256),
    user_id character varying(256),

    exchange character varying(256),
    routing_key character varying(256),

		body text,

		created_at timestamp without time zone NOT NULL
	  );
	  `,
		},
	}
	insertSqlFormat = `
      INSERT INTO %s(
        uuid,
        content_type,
        content_encoding,
        delivery_mode,
        priority,
        correlation_id,
        reply_to,
        expiration,
        timestamp,
        type,
        user_id,
        exchange,
        routing_key,
        body,
        created_at
      ) VALUES(?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
  `
)

type DeliveryStore struct {
	db              *sql.DB
	insertStatement *sql.Stmt
}

func NewDeliveryStore(databaseDriver string, databaseUri string, table string) (deliveryStore *DeliveryStore, err error) {
	me := &DeliveryStore{}

	if me.db, err = sql.Open(databaseDriver, databaseUri); err != nil {
		return nil, err
	}

  if err = me.runMigrations(table); err != nil {
    return nil, err
  }

	if me.insertStatement, err = me.db.Prepare(fmt.Sprintf(insertSqlFormat, table)); err != nil {
		return nil, err
	}

	return me, nil
}

func (me *DeliveryStore) runMigrations(table string) (err error) {
  migrations := map[string][]string{}

  for migrationFormatTag, migrationStatementFormats := range migrationFormats {
    for _, migrationStatementFormat := range migrationStatementFormats {
      migrations[fmt.Sprintf(migrationFormatTag, table)] = append(
        migrations[fmt.Sprintf(migrationFormatTag, table)],
        fmt.Sprintf(migrationStatementFormat, table))
    }
  }

	schemaEnsurer := sensurer.New(me.db, migrations, log.New(ioutil.Discard, "", 0))
	if err = schemaEnsurer.EnsureSchema(); err != nil {
		return err
	}

  return nil
}

func (me *DeliveryStore) Store(delivery *amqp.Delivery) (err error) {
	var (
		u4 *uuid.UUID
	)

	if u4, err = uuid.NewV4(); err != nil {
		return err
	}

	_, err = me.insertStatement.Exec(
		u4.String(),
		delivery.ContentType,
		delivery.ContentEncoding,
		delivery.DeliveryMode,
		delivery.Priority,
		delivery.CorrelationId,
		delivery.ReplyTo,
		delivery.Expiration,
		delivery.Timestamp,
		delivery.Type,
		delivery.UserId,
		delivery.Exchange,
		delivery.RoutingKey,
		delivery.Body,
		time.Now())

	return err
}

func (me *DeliveryStore) Close() {
	me.db.Close()
}
<commit_msg>Adding Postgres specific prepared statement<commit_after>package amqptee

import (
	"database/sql"
	"fmt"
	"io/ioutil"
	"log"
	"time"

	_ "code.google.com/p/gosqlite/sqlite3"
	_ "github.com/go-sql-driver/mysql"
	_ "github.com/lib/pq"
	"github.com/modcloth-labs/schema_ensurer"
	"github.com/nu7hatch/gouuid"
	"github.com/streadway/amqp"
)

var (
	migrationFormats = map[string][]string{
		"20131108000000_%s": {`
	  CREATE TABLE IF NOT EXISTS %s(
		uuid char(32),

    content_type character varying(256),
    content_encoding character varying(256),
    delivery_mode smallint,
    priority smallint,
    correlation_id character varying(256),
    reply_to character varying(256),
    expiration character varying(256),
    timestamp timestamp with time zone,
    type character varying(256),
    user_id character varying(256),

    exchange character varying(256),
    routing_key character varying(256),

		body text,

		created_at timestamp without time zone NOT NULL
	  );
	  `,
		},
	}
	insertSqlNormalFormat = `
      INSERT INTO %s(
        uuid,
        content_type,
        content_encoding,
        delivery_mode,
        priority,
        correlation_id,
        reply_to,
        expiration,
        timestamp,
        type,
        user_id,
        exchange,
        routing_key,
        body,
        created_at
      ) VALUES(?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
  `
	insertSqlPostgresFormat = `
      INSERT INTO %s(
        uuid,
        content_type,
        content_encoding,
        delivery_mode,
        priority,
        correlation_id,
        reply_to,
        expiration,
        timestamp,
        type,
        user_id,
        exchange,
        routing_key,
        body,
        created_at
      ) VALUES($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11, $12, $13, $14, $15)
  `
)

type DeliveryStore struct {
	db              *sql.DB
	insertStatement *sql.Stmt
}

func NewDeliveryStore(databaseDriver string, databaseUri string, table string) (deliveryStore *DeliveryStore, err error) {
	me := &DeliveryStore{}

	if me.db, err = sql.Open(databaseDriver, databaseUri); err != nil {
		return nil, err
	}

	if err = me.runMigrations(table); err != nil {
		return nil, err
	}

	insertSqlFormat := insertSqlNormalFormat
	if databaseDriver == "postgres" {
		insertSqlFormat = insertSqlPostgresFormat
	}

	if me.insertStatement, err = me.db.Prepare(fmt.Sprintf(insertSqlFormat, table)); err != nil {
		return nil, err
	}

	return me, nil
}

func (me *DeliveryStore) runMigrations(table string) (err error) {
	migrations := map[string][]string{}

	for migrationFormatTag, migrationStatementFormats := range migrationFormats {
		for _, migrationStatementFormat := range migrationStatementFormats {
			migrations[fmt.Sprintf(migrationFormatTag, table)] = append(
				migrations[fmt.Sprintf(migrationFormatTag, table)],
				fmt.Sprintf(migrationStatementFormat, table))
		}
	}

	schemaEnsurer := sensurer.New(me.db, migrations, log.New(ioutil.Discard, "", 0))
	if err = schemaEnsurer.EnsureSchema(); err != nil {
		return err
	}

	return nil
}

func (me *DeliveryStore) Store(delivery *amqp.Delivery) (err error) {
	var (
		u4 *uuid.UUID
	)

	if u4, err = uuid.NewV4(); err != nil {
		return err
	}

	_, err = me.insertStatement.Exec(
		u4.String(),
		delivery.ContentType,
		delivery.ContentEncoding,
		delivery.DeliveryMode,
		delivery.Priority,
		delivery.CorrelationId,
		delivery.ReplyTo,
		delivery.Expiration,
		delivery.Timestamp,
		delivery.Type,
		delivery.UserId,
		delivery.Exchange,
		delivery.RoutingKey,
		delivery.Body,
		time.Now())

	return err
}

func (me *DeliveryStore) Close() {
	me.db.Close()
}
<|endoftext|>


<commit_before>package main

import (
	"flag"
	"log"
	"net"
	"time"

	"github.com/myzhan/boomer"
)

//                            +------------+
//                            |            |
//                            |   locust   |
//                            |            |
//                            +------+-----+
//                                   ^
//                                   |  qps & timeout
//                                   |
//	+------------+        +------+-----+        +------------+
//	|            |request |            |request |            |
//	| udpcopy    +------->+ udp proxy  +------->+ backend    |
//	|            |        |            |        |            |
//	+------------+        +------------+        +------------+

// While requests from udpcopy passing through this udp server, it keeps track of qps and timeout.
// Also, it can multi-copy the original request for more stress.

// Known Issues:
// 1. Once locust start the test, it can't be stopped by locust. You should restart locust and this udp server if you
//    want to restart.

// See also:
// udpcopy: https://github.com/wangbin579/udpcopy

type worker struct {
	conn     *net.UDPConn
	requests chan []byte
	recvBuff []byte
}

func newWorker(remoteAddr string) *worker {
	addr, err := net.ResolveUDPAddr("udp", remoteAddr)
	if err != nil {
		log.Fatalln("Failed to create worker", err)
		return nil
	}
	conn, err := net.DialUDP("udp", nil, addr)
	if err != nil {
		log.Fatalln("Failed to create worker", err)
		return nil
	}
	requests := make(chan []byte, 1000)
	recvBuff := make([]byte, *udpBufferSize)
	go func() {
		for {
			req := <-requests
			for n := 0; n < *number; n++ {
				startTime := boomer.Now()
				wn, err := conn.Write(req)
				if err != nil {
					boomer.RecordFailure("udp-write", name, 0.0, err.Error())
					continue
				}

				if *dontRead {
					elapsed := boomer.Now() - startTime
					boomer.RecordSuccess("udp-write", name, elapsed, int64(wn))
				} else {
					conn.SetReadDeadline(time.Now().Add(backendTimeout))
					respLength, err := conn.Read(recvBuff)
					if err != nil {
						boomer.RecordFailure("udp-read", name, 0.0, err.Error())
						continue
					}
					elapsed := boomer.Now() - startTime
					boomer.RecordSuccess("udp-resp", name, elapsed, int64(respLength))
				}
			}
		}
	}()

	return &worker{
		conn:     conn,
		requests: requests,
		recvBuff: recvBuff,
	}

}

func createWorkers() {
	workersPool = make([]*worker, *workersCount)
	for n := 0; n < *workersCount; n++ {
		workersPool[n] = newWorker(*backendAddr)
	}
}

func proxy() {

	// Pooling workers
	createWorkers()

	listener, err := net.ListenUDP("udp", &net.UDPAddr{
		IP:   net.ParseIP(*proxyHost),
		Port: *proxyPort,
	})
	if err != nil {
		log.Fatal("error binding on port:", *proxyPort, err)
	}

	workerIndex := uint64(0)

	for {
		data := make([]byte, *udpBufferSize)
		n, _, err := listener.ReadFromUDP(data)
		if err != nil {
			log.Println("error during read, current request is dropped.", err)
			continue
		}
		if *udpBufferSize <= n {
			log.Printf("request size is larger than %d，please enlarge udp-buffer-size. current request is dropped.\n", *udpBufferSize)
			continue
		}
		if !testStarted {
			// test is not started, drop current request.
			continue
		}

		// Round-robin selection
		workerIndex = workerIndex + 1
		selectedWorker := workersPool[workerIndex%(uint64(*workersCount))]
		selectedWorker.requests <- data[:n]
	}
}

func deadend() {
	testStarted = true
	for {
		time.Sleep(time.Second * 100)
	}
}

func main() {

	task := &boomer.Task{
		Name:   "udproxy",
		Weight: 10,
		Fn:     deadend,
	}

	go proxy()

	boomer.Run(task)
}

const name = "udproxy"

var testStarted = false
var workersPool []*worker

// command line arguments
var backendAddr *string
var backendTimeout time.Duration
var proxyHost *string
var proxyPort *int
var udpBufferSize *int
var number *int
var workersCount *int
var dontRead *bool

func init() {

	backendAddr = flag.String("backend-addr", "127.0.0.1:44444", "backend address")
	timeout := flag.Int("backend-timeout", 1000, "backend timeout(ms)")
	proxyHost = flag.String("proxy-host", "0.0.0.0", "proxy bind-host")
	proxyPort = flag.Int("proxy-port", 23333, "proxy bind-port")
	workersCount = flag.Int("workers", 20, "UDP workers")
	udpBufferSize = flag.Int("udp-buffer-size", 4096, "udp recv buffer size")
	number = flag.Int("number", 1, "the number of replication for multi-copying")
	dontRead = flag.Bool("dontread", false, "do not wait for backend's response")
	flag.Parse()

	backendTimeout = time.Duration(*timeout) * time.Millisecond
}
<commit_msg>subscribe to boomer's internal events to start and stop test<commit_after>package main

import (
	"flag"
	"log"
	"net"
	"time"

	"github.com/myzhan/boomer"
)

//                            +------------+
//                            |            |
//                            |   locust   |
//                            |            |
//                            +------+-----+
//                                   ^
//                                   |  qps & timeout
//                                   |
//	+------------+        +------+-----+        +------------+
//	|            |request |            |request |            |
//	| udpcopy    +------->+ udp proxy  +------->+ backend    |
//	|            |        |            |        |            |
//	+------------+        +------------+        +------------+

// While requests from udpcopy passing through this udp server, it keeps track of qps and timeout.
// Also, it can multi-copy the original request for more stress.

// See also:
// udpcopy: https://github.com/wangbin579/udpcopy

const name = "udpproxy"

var testStarted = false
var workersPool []*worker

// command line arguments
var backendAddr *string
var backendTimeout time.Duration
var proxyHost *string
var proxyPort *int
var udpBufferSize *int
var number *int
var workersCount *int
var dontRead *bool

type worker struct {
	conn     *net.UDPConn
	requests chan []byte
	recvBuff []byte
}

func newWorker(remoteAddr string) *worker {
	addr, err := net.ResolveUDPAddr("udp", remoteAddr)
	if err != nil {
		log.Fatalln("Failed to create worker", err)
		return nil
	}
	conn, err := net.DialUDP("udp", nil, addr)
	if err != nil {
		log.Fatalln("Failed to create worker", err)
		return nil
	}
	requests := make(chan []byte, 1000)
	recvBuff := make([]byte, *udpBufferSize)
	go func() {
		for req := range requests {
			for n := 0; n < *number; n++ {
				startTime := boomer.Now()
				wn, err := conn.Write(req)
				if err != nil {
					boomer.RecordFailure(name, "udp-write", 0.0, err.Error())
					continue
				}

				if *dontRead {
					elapsed := boomer.Now() - startTime
					boomer.RecordSuccess(name, "udp-write", elapsed, int64(wn))
				} else {
					conn.SetReadDeadline(time.Now().Add(backendTimeout))
					respLength, err := conn.Read(recvBuff)
					if err != nil {
						boomer.RecordFailure(name, "udp-read", 0.0, err.Error())
						continue
					}
					elapsed := boomer.Now() - startTime
					boomer.RecordSuccess(name, "udp-resp", elapsed, int64(respLength))
				}
			}
		}
	}()

	return &worker{
		conn:     conn,
		requests: requests,
		recvBuff: recvBuff,
	}
}

func createWorkers() {
	workersPool = make([]*worker, *workersCount)
	for n := 0; n < *workersCount; n++ {
		workersPool[n] = newWorker(*backendAddr)
	}
}

func proxy() {
	// Pooling workers
	createWorkers()

	listener, err := net.ListenUDP("udp", &net.UDPAddr{
		IP:   net.ParseIP(*proxyHost),
		Port: *proxyPort,
	})
	if err != nil {
		log.Fatal("error binding on port:", *proxyPort, err)
	}

	workerIndex := uint64(0)

	for {
		data := make([]byte, *udpBufferSize)
		n, _, err := listener.ReadFromUDP(data)
		if err != nil {
			log.Println("error during read, current request is dropped.", err)
			continue
		}
		if *udpBufferSize <= n {
			log.Printf("request size is larger than %d，please enlarge udp-buffer-size. current request is dropped.\n", *udpBufferSize)
			continue
		}
		if !testStarted {
			// test is not started, drop current request.
			continue
		}

		// Round-robin selection
		workerIndex = workerIndex + 1
		selectedWorker := workersPool[workerIndex%(uint64(*workersCount))]
		selectedWorker.requests <- data[:n]
	}
}

func startTest(workers, hatchRate int) {
	testStarted = true
}

func stopTest() {
	testStarted = false
}

func deadend() {
	for {
		time.Sleep(time.Second * 100)
	}
}

func main() {
	boomer.Events.Subscribe("boomer:hatch", startTest)
	boomer.Events.Subscribe("boomer:stop", stopTest)

	task := &boomer.Task{
		Name:   "udproxy",
		Weight: 10,
		Fn:     deadend,
	}

	go proxy()

	boomer.Run(task)
}

func init() {
	backendAddr = flag.String("backend-addr", "127.0.0.1:44444", "backend address")
	timeout := flag.Int("backend-timeout", 1000, "backend timeout(ms)")
	proxyHost = flag.String("proxy-host", "0.0.0.0", "proxy bind-host")
	proxyPort = flag.Int("proxy-port", 23333, "proxy bind-port")
	workersCount = flag.Int("workers", 20, "UDP workers")
	udpBufferSize = flag.Int("udp-buffer-size", 4096, "udp recv buffer size")
	number = flag.Int("number", 1, "the number of replication for multi-copying")
	dontRead = flag.Bool("dontread", false, "do not wait for backend's response")
	flag.Parse()

	backendTimeout = time.Duration(*timeout) * time.Millisecond
}
<|endoftext|>


<commit_before>// Copyright 2012 Gary Burd
//
// 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 redis

import (
	"crypto/sha1"
	"encoding/hex"
	"io"
	"strings"
)

// Script encapsulates the source, hash and key count for a Lua script. See
// http://redis.io/commands/eval for information on scripts in Redis.
type Script struct {
	keyCount int
	src      string
	hash     string
}

// NewScript returns a new script object. If keyCount is greater than or equal
// to zero, then the count is automatically inserted in the EVAL command
// argument list. If keyCount is less than zero, then the application supplies
// the count as the first value in the keysAndArgs argument to the Do, Send and
// SendHash methods.
func NewScript(keyCount int, src string) *Script {
	h := sha1.New()
	io.WriteString(h, src)
	return &Script{keyCount, src, hex.EncodeToString(h.Sum(nil))}
}

func (s *Script) args(spec string, keysAndArgs []interface{}) []interface{} {
	var args []interface{}
	if s.keyCount < 0 {
		args = make([]interface{}, 1+len(keysAndArgs))
		args[0] = spec
		copy(args[1:], keysAndArgs)
	} else {
		args = make([]interface{}, 2+len(keysAndArgs))
		args[0] = spec
		args[1] = s.keyCount
		copy(args[2:], keysAndArgs)
	}
	return args
}

// Do evaluates the script. Under the covers, Do optimistically evaluates the
// script using the EVALSHA command. If the command fails because the script is
// not loaded, then Do evaluates the script using the EVAL command (thus
// causing the script to load).
func (s *Script) Do(c Conn, keysAndArgs ...interface{}) (interface{}, error) {
	v, err := c.Do("EVALSHA", s.args(s.hash, keysAndArgs)...)
	if e, ok := err.(Error); ok && strings.HasPrefix(string(e), "NOSCRIPT ") {
		v, err = c.Do("EVAL", s.args(s.src, keysAndArgs)...)
	}
	return v, err
}

// SendHash evaluates the script without waiting for the reply. The script is
// evaluated with the EVALSHA command. The application must ensure that the
// script is loaded by a previous call to Send, Do or Load methods.
func (s *Script) SendHash(c Conn, keysAndArgs ...interface{}) error {
	return c.Send("EVALSHA", s.args(s.hash, keysAndArgs)...)
}

// Send evaluates the script without waiting for the reply.
func (s *Script) Send(c Conn, keysAndArgs ...interface{}) error {
	return c.Send("EVAL", s.args(s.src, keysAndArgs)...)
}

// Load loads the script without evaluating it.
func (s *Script) Load(c Conn) error {
	_, err := c.Do("SCRIPT", "LOAD", s.src)
	return err
}
<commit_msg>Add Script.Hash()<commit_after>// Copyright 2012 Gary Burd
//
// 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 redis

import (
	"crypto/sha1"
	"encoding/hex"
	"io"
	"strings"
)

// Script encapsulates the source, hash and key count for a Lua script. See
// http://redis.io/commands/eval for information on scripts in Redis.
type Script struct {
	keyCount int
	src      string
	hash     string
}

// NewScript returns a new script object. If keyCount is greater than or equal
// to zero, then the count is automatically inserted in the EVAL command
// argument list. If keyCount is less than zero, then the application supplies
// the count as the first value in the keysAndArgs argument to the Do, Send and
// SendHash methods.
func NewScript(keyCount int, src string) *Script {
	h := sha1.New()
	io.WriteString(h, src)
	return &Script{keyCount, src, hex.EncodeToString(h.Sum(nil))}
}

func (s *Script) args(spec string, keysAndArgs []interface{}) []interface{} {
	var args []interface{}
	if s.keyCount < 0 {
		args = make([]interface{}, 1+len(keysAndArgs))
		args[0] = spec
		copy(args[1:], keysAndArgs)
	} else {
		args = make([]interface{}, 2+len(keysAndArgs))
		args[0] = spec
		args[1] = s.keyCount
		copy(args[2:], keysAndArgs)
	}
	return args
}

// Hash returns the script hash.
func (s *Script) Hash() string {
	return s.hash
}

// Do evaluates the script. Under the covers, Do optimistically evaluates the
// script using the EVALSHA command. If the command fails because the script is
// not loaded, then Do evaluates the script using the EVAL command (thus
// causing the script to load).
func (s *Script) Do(c Conn, keysAndArgs ...interface{}) (interface{}, error) {
	v, err := c.Do("EVALSHA", s.args(s.hash, keysAndArgs)...)
	if e, ok := err.(Error); ok && strings.HasPrefix(string(e), "NOSCRIPT ") {
		v, err = c.Do("EVAL", s.args(s.src, keysAndArgs)...)
	}
	return v, err
}

// SendHash evaluates the script without waiting for the reply. The script is
// evaluated with the EVALSHA command. The application must ensure that the
// script is loaded by a previous call to Send, Do or Load methods.
func (s *Script) SendHash(c Conn, keysAndArgs ...interface{}) error {
	return c.Send("EVALSHA", s.args(s.hash, keysAndArgs)...)
}

// Send evaluates the script without waiting for the reply.
func (s *Script) Send(c Conn, keysAndArgs ...interface{}) error {
	return c.Send("EVAL", s.args(s.src, keysAndArgs)...)
}

// Load loads the script without evaluating it.
func (s *Script) Load(c Conn) error {
	_, err := c.Do("SCRIPT", "LOAD", s.src)
	return err
}
<|endoftext|>


<commit_before>/*
   Copyright 2019 Artem Sidorenko <artem@posteo.de>

   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 source provides the data source functionality
package source

import (
	_ "github.com/artem-sidorenko/chagen/source/connectors/github" //enable github
)
<commit_msg>Enable GitLab connector<commit_after>/*
   Copyright 2019 Artem Sidorenko <artem@posteo.de>

   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 source provides the data source functionality
package source

import (
	_ "github.com/artem-sidorenko/chagen/source/connectors/github" //enable github
	_ "github.com/artem-sidorenko/chagen/source/connectors/gitlab" //enable gitlab
)
<|endoftext|>


<commit_before>/*
Copyright 2019 The Vitess 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 cluster

import (
	"encoding/json"
	"fmt"
	"io/ioutil"
	"net/http"
	"os"
	"os/exec"
	"path"
	"reflect"
	"strconv"
	"strings"
	"syscall"
	"time"

	"vitess.io/vitess/go/vt/log"
)

// VtgateProcess is a generic handle for a running vtgate .
// It can be spawned manually
type VtgateProcess struct {
	Name                  string
	Binary                string
	CommonArg             VtctlProcess
	LogDir                string
	FileToLogQueries      string
	Port                  int
	GrpcPort              int
	MySQLServerPort       int
	MySQLServerSocketPath string
	Cell                  string
	CellsToWatch          string
	TabletTypesToWait     string
	GatewayImplementation string
	ServiceMap            string
	PidFile               string
	MySQLAuthServerImpl   string
	Directory             string
	VerifyURL             string
	//Extra Args to be set before starting the vtgate process
	ExtraArgs []string

	proc *exec.Cmd
	exit chan error
}

// Setup starts Vtgate process with required arguements
func (vtgate *VtgateProcess) Setup() (err error) {

	vtgate.proc = exec.Command(
		vtgate.Binary,
		"-topo_implementation", vtgate.CommonArg.TopoImplementation,
		"-topo_global_server_address", vtgate.CommonArg.TopoGlobalAddress,
		"-topo_global_root", vtgate.CommonArg.TopoGlobalRoot,
		"-log_dir", vtgate.LogDir,
		"-log_queries_to_file", vtgate.FileToLogQueries,
		"-port", fmt.Sprintf("%d", vtgate.Port),
		"-grpc_port", fmt.Sprintf("%d", vtgate.GrpcPort),
		"-mysql_server_port", fmt.Sprintf("%d", vtgate.MySQLServerPort),
		"-mysql_server_socket_path", vtgate.MySQLServerSocketPath,
		"-cell", vtgate.Cell,
		"-cells_to_watch", vtgate.CellsToWatch,
		"-tablet_types_to_wait", vtgate.TabletTypesToWait,
		"-gateway_implementation", vtgate.GatewayImplementation,
		"-service_map", vtgate.ServiceMap,
		"-mysql_auth_server_impl", vtgate.MySQLAuthServerImpl,
		"-pid_file", vtgate.PidFile,
	)
	if *isCoverage {
		vtgate.proc.Args = append(vtgate.proc.Args, "-test.coverprofile="+getCoveragePath("vtgate.out"))
	}

	vtgate.proc.Args = append(vtgate.proc.Args, vtgate.ExtraArgs...)

	errFile, _ := os.Create(path.Join(vtgate.LogDir, "vtgate-stderr.txt"))
	vtgate.proc.Stderr = errFile

	vtgate.proc.Env = append(vtgate.proc.Env, os.Environ()...)

	log.Infof("Running vtgate with command: %v", strings.Join(vtgate.proc.Args, " "))

	err = vtgate.proc.Start()
	if err != nil {
		return
	}
	vtgate.exit = make(chan error)
	go func() {
		if vtgate.proc != nil {
			vtgate.exit <- vtgate.proc.Wait()
		}
	}()

	timeout := time.Now().Add(60 * time.Second)
	for time.Now().Before(timeout) {
		if vtgate.WaitForStatus() {
			return nil
		}
		select {
		case err := <-vtgate.exit:
			return fmt.Errorf("process '%s' exited prematurely (err: %s)", vtgate.Name, err)
		default:
			time.Sleep(300 * time.Millisecond)
		}
	}

	return fmt.Errorf("process '%s' timed out after 60s (err: %s)", vtgate.Name, <-vtgate.exit)
}

// WaitForStatus function checks if vtgate process is up and running
func (vtgate *VtgateProcess) WaitForStatus() bool {
	resp, err := http.Get(vtgate.VerifyURL)
	if err != nil {
		return false
	}
	if resp.StatusCode == 200 {
		return true
	}
	return false
}

// GetStatusForTabletOfShard function gets status for a specific tablet of a shard in keyspace
// endPointsCount : number of endpoints
func (vtgate *VtgateProcess) GetStatusForTabletOfShard(name string, endPointsCount int) bool {
	resp, err := http.Get(vtgate.VerifyURL)
	if err != nil {
		return false
	}
	if resp.StatusCode == 200 {
		resultMap := make(map[string]interface{})
		respByte, _ := ioutil.ReadAll(resp.Body)
		err := json.Unmarshal(respByte, &resultMap)
		if err != nil {
			panic(err)
		}
		object := reflect.ValueOf(resultMap["HealthcheckConnections"])
		masterConnectionExist := false
		if object.Kind() == reflect.Map {
			for _, key := range object.MapKeys() {
				if key.String() == name {
					value := fmt.Sprintf("%v", object.MapIndex(key))
					countStr := strconv.Itoa(endPointsCount)
					return value == countStr
				}
			}
		}
		return masterConnectionExist
	}
	return false
}

// WaitForStatusOfTabletInShard function waits till status of a tablet in shard is 1
// endPointsCount: how many endpoints to wait for
func (vtgate *VtgateProcess) WaitForStatusOfTabletInShard(name string, endPointsCount int) error {
	timeout := time.Now().Add(10 * time.Second)
	for time.Now().Before(timeout) {
		if vtgate.GetStatusForTabletOfShard(name, endPointsCount) {
			return nil
		}
		select {
		case err := <-vtgate.exit:
			return fmt.Errorf("process '%s' exited prematurely (err: %s)", vtgate.Name, err)
		default:
			time.Sleep(300 * time.Millisecond)
		}
	}
	return fmt.Errorf("wait for %s failed", name)
}

// TearDown shuts down the running vtgate service
func (vtgate *VtgateProcess) TearDown() error {
	if vtgate.proc == nil || vtgate.exit == nil {
		return nil
	}
	// Attempt graceful shutdown with SIGTERM first
	vtgate.proc.Process.Signal(syscall.SIGTERM)

	select {
	case err := <-vtgate.exit:
		vtgate.proc = nil
		return err

	case <-time.After(10 * time.Second):
		vtgate.proc.Process.Kill()
		vtgate.proc = nil
		return <-vtgate.exit
	}
}

// VtgateProcessInstance returns a Vtgate handle for vtgate process
// configured with the given Config.
// The process must be manually started by calling setup()
func VtgateProcessInstance(port int, grpcPort int, mySQLServerPort int, cell string, cellsToWatch string, hostname string, tabletTypesToWait string, topoPort int, tmpDirectory string, extraArgs []string) *VtgateProcess {
	vtctl := VtctlProcessInstance(topoPort, hostname)
	vtgate := &VtgateProcess{
		Name:                  "vtgate",
		Binary:                "vtgate",
		FileToLogQueries:      path.Join(tmpDirectory, "/vtgate_querylog.txt"),
		Directory:             os.Getenv("VTDATAROOT"),
		ServiceMap:            "grpc-tabletmanager,grpc-throttler,grpc-queryservice,grpc-updatestream,grpc-vtctl,grpc-vtworker,grpc-vtgateservice",
		LogDir:                tmpDirectory,
		Port:                  port,
		GrpcPort:              grpcPort,
		MySQLServerPort:       mySQLServerPort,
		MySQLServerSocketPath: path.Join(tmpDirectory, "mysql.sock"),
		Cell:                  cell,
		CellsToWatch:          cellsToWatch,
		TabletTypesToWait:     tabletTypesToWait,
		GatewayImplementation: "discoverygateway",
		CommonArg:             *vtctl,
		PidFile:               path.Join(tmpDirectory, "/vtgate.pid"),
		MySQLAuthServerImpl:   "none",
		ExtraArgs:             extraArgs,
	}

	vtgate.VerifyURL = fmt.Sprintf("http://%s:%d/debug/vars", hostname, port)

	return vtgate
}

// GetVars returns map of vars
func (vtgate *VtgateProcess) GetVars() (map[string]interface{}, error) {
	resultMap := make(map[string]interface{})
	resp, err := http.Get(vtgate.VerifyURL)
	if err != nil {
		return nil, fmt.Errorf("error getting response from %s", vtgate.VerifyURL)
	}
	if resp.StatusCode == 200 {
		respByte, _ := ioutil.ReadAll(resp.Body)
		err := json.Unmarshal(respByte, &resultMap)
		if err != nil {
			return nil, fmt.Errorf("not able to parse response body")
		}
		return resultMap, nil
	}
	return nil, fmt.Errorf("unsuccessful response")
}
<commit_msg>use the new gateway for end to end tests<commit_after>/*
Copyright 2019 The Vitess 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 cluster

import (
	"encoding/json"
	"fmt"
	"io/ioutil"
	"net/http"
	"os"
	"os/exec"
	"path"
	"reflect"
	"strconv"
	"strings"
	"syscall"
	"time"

	"vitess.io/vitess/go/vt/log"
)

// VtgateProcess is a generic handle for a running vtgate .
// It can be spawned manually
type VtgateProcess struct {
	Name                  string
	Binary                string
	CommonArg             VtctlProcess
	LogDir                string
	FileToLogQueries      string
	Port                  int
	GrpcPort              int
	MySQLServerPort       int
	MySQLServerSocketPath string
	Cell                  string
	CellsToWatch          string
	TabletTypesToWait     string
	GatewayImplementation string
	ServiceMap            string
	PidFile               string
	MySQLAuthServerImpl   string
	Directory             string
	VerifyURL             string
	//Extra Args to be set before starting the vtgate process
	ExtraArgs []string

	proc *exec.Cmd
	exit chan error
}

// Setup starts Vtgate process with required arguements
func (vtgate *VtgateProcess) Setup() (err error) {

	vtgate.proc = exec.Command(
		vtgate.Binary,
		"-topo_implementation", vtgate.CommonArg.TopoImplementation,
		"-topo_global_server_address", vtgate.CommonArg.TopoGlobalAddress,
		"-topo_global_root", vtgate.CommonArg.TopoGlobalRoot,
		"-log_dir", vtgate.LogDir,
		"-log_queries_to_file", vtgate.FileToLogQueries,
		"-port", fmt.Sprintf("%d", vtgate.Port),
		"-grpc_port", fmt.Sprintf("%d", vtgate.GrpcPort),
		"-mysql_server_port", fmt.Sprintf("%d", vtgate.MySQLServerPort),
		"-mysql_server_socket_path", vtgate.MySQLServerSocketPath,
		"-cell", vtgate.Cell,
		"-cells_to_watch", vtgate.CellsToWatch,
		"-tablet_types_to_wait", vtgate.TabletTypesToWait,
		"-gateway_implementation", vtgate.GatewayImplementation,
		"-service_map", vtgate.ServiceMap,
		"-mysql_auth_server_impl", vtgate.MySQLAuthServerImpl,
		"-pid_file", vtgate.PidFile,
	)
	if *isCoverage {
		vtgate.proc.Args = append(vtgate.proc.Args, "-test.coverprofile="+getCoveragePath("vtgate.out"))
	}

	vtgate.proc.Args = append(vtgate.proc.Args, vtgate.ExtraArgs...)

	errFile, _ := os.Create(path.Join(vtgate.LogDir, "vtgate-stderr.txt"))
	vtgate.proc.Stderr = errFile

	vtgate.proc.Env = append(vtgate.proc.Env, os.Environ()...)

	log.Infof("Running vtgate with command: %v", strings.Join(vtgate.proc.Args, " "))

	err = vtgate.proc.Start()
	if err != nil {
		return
	}
	vtgate.exit = make(chan error)
	go func() {
		if vtgate.proc != nil {
			vtgate.exit <- vtgate.proc.Wait()
		}
	}()

	timeout := time.Now().Add(60 * time.Second)
	for time.Now().Before(timeout) {
		if vtgate.WaitForStatus() {
			return nil
		}
		select {
		case err := <-vtgate.exit:
			return fmt.Errorf("process '%s' exited prematurely (err: %s)", vtgate.Name, err)
		default:
			time.Sleep(300 * time.Millisecond)
		}
	}

	return fmt.Errorf("process '%s' timed out after 60s (err: %s)", vtgate.Name, <-vtgate.exit)
}

// WaitForStatus function checks if vtgate process is up and running
func (vtgate *VtgateProcess) WaitForStatus() bool {
	resp, err := http.Get(vtgate.VerifyURL)
	if err != nil {
		return false
	}
	if resp.StatusCode == 200 {
		return true
	}
	return false
}

// GetStatusForTabletOfShard function gets status for a specific tablet of a shard in keyspace
// endPointsCount : number of endpoints
func (vtgate *VtgateProcess) GetStatusForTabletOfShard(name string, endPointsCount int) bool {
	resp, err := http.Get(vtgate.VerifyURL)
	if err != nil {
		return false
	}
	if resp.StatusCode == 200 {
		resultMap := make(map[string]interface{})
		respByte, _ := ioutil.ReadAll(resp.Body)
		err := json.Unmarshal(respByte, &resultMap)
		if err != nil {
			panic(err)
		}
		object := reflect.ValueOf(resultMap["HealthcheckConnections"])
		masterConnectionExist := false
		if object.Kind() == reflect.Map {
			for _, key := range object.MapKeys() {
				if key.String() == name {
					value := fmt.Sprintf("%v", object.MapIndex(key))
					countStr := strconv.Itoa(endPointsCount)
					return value == countStr
				}
			}
		}
		return masterConnectionExist
	}
	return false
}

// WaitForStatusOfTabletInShard function waits till status of a tablet in shard is 1
// endPointsCount: how many endpoints to wait for
func (vtgate *VtgateProcess) WaitForStatusOfTabletInShard(name string, endPointsCount int) error {
	timeout := time.Now().Add(10 * time.Second)
	for time.Now().Before(timeout) {
		if vtgate.GetStatusForTabletOfShard(name, endPointsCount) {
			return nil
		}
		select {
		case err := <-vtgate.exit:
			return fmt.Errorf("process '%s' exited prematurely (err: %s)", vtgate.Name, err)
		default:
			time.Sleep(300 * time.Millisecond)
		}
	}
	return fmt.Errorf("wait for %s failed", name)
}

// TearDown shuts down the running vtgate service
func (vtgate *VtgateProcess) TearDown() error {
	if vtgate.proc == nil || vtgate.exit == nil {
		return nil
	}
	// Attempt graceful shutdown with SIGTERM first
	vtgate.proc.Process.Signal(syscall.SIGTERM)

	select {
	case err := <-vtgate.exit:
		vtgate.proc = nil
		return err

	case <-time.After(10 * time.Second):
		vtgate.proc.Process.Kill()
		vtgate.proc = nil
		return <-vtgate.exit
	}
}

// VtgateProcessInstance returns a Vtgate handle for vtgate process
// configured with the given Config.
// The process must be manually started by calling setup()
func VtgateProcessInstance(port int, grpcPort int, mySQLServerPort int, cell string, cellsToWatch string, hostname string, tabletTypesToWait string, topoPort int, tmpDirectory string, extraArgs []string) *VtgateProcess {
	vtctl := VtctlProcessInstance(topoPort, hostname)
	vtgate := &VtgateProcess{
		Name:                  "vtgate",
		Binary:                "vtgate",
		FileToLogQueries:      path.Join(tmpDirectory, "/vtgate_querylog.txt"),
		Directory:             os.Getenv("VTDATAROOT"),
		ServiceMap:            "grpc-tabletmanager,grpc-throttler,grpc-queryservice,grpc-updatestream,grpc-vtctl,grpc-vtworker,grpc-vtgateservice",
		LogDir:                tmpDirectory,
		Port:                  port,
		GrpcPort:              grpcPort,
		MySQLServerPort:       mySQLServerPort,
		MySQLServerSocketPath: path.Join(tmpDirectory, "mysql.sock"),
		Cell:                  cell,
		CellsToWatch:          cellsToWatch,
		TabletTypesToWait:     tabletTypesToWait,
		GatewayImplementation: "tabletgateway",
		CommonArg:             *vtctl,
		PidFile:               path.Join(tmpDirectory, "/vtgate.pid"),
		MySQLAuthServerImpl:   "none",
		ExtraArgs:             extraArgs,
	}

	vtgate.VerifyURL = fmt.Sprintf("http://%s:%d/debug/vars", hostname, port)

	return vtgate
}

// GetVars returns map of vars
func (vtgate *VtgateProcess) GetVars() (map[string]interface{}, error) {
	resultMap := make(map[string]interface{})
	resp, err := http.Get(vtgate.VerifyURL)
	if err != nil {
		return nil, fmt.Errorf("error getting response from %s", vtgate.VerifyURL)
	}
	if resp.StatusCode == 200 {
		respByte, _ := ioutil.ReadAll(resp.Body)
		err := json.Unmarshal(respByte, &resultMap)
		if err != nil {
			return nil, fmt.Errorf("not able to parse response body")
		}
		return resultMap, nil
	}
	return nil, fmt.Errorf("unsuccessful response")
}
<|endoftext|>


<commit_before>package speccy

import (
	"fmt"

	"github.com/jbert/zog"
	"github.com/veandco/go-sdl2/sdl"
)

const (
	screenWidth  = 256
	screenHeight = 192
	screenScale  = 4

	screenMemStart = 0x4000
	colourMemStart = 0x5800
)

type Screen struct {
	window   *sdl.Window
	renderer *sdl.Renderer
	mem      *zog.Memory

	flashCount int
}

func NewScreen(mem *zog.Memory) (*Screen, error) {
	winTitle := "Speccy"
	window, err := sdl.CreateWindow(winTitle, sdl.WINDOWPOS_UNDEFINED, sdl.WINDOWPOS_UNDEFINED,
		screenWidth*screenScale, screenHeight*screenScale, sdl.WINDOW_SHOWN)
	if err != nil {
		return nil, fmt.Errorf("Failed to create window: %s\n", err)
	}

	renderer, err := sdl.CreateRenderer(window, -1, sdl.RENDERER_ACCELERATED)
	if err != nil {
		return nil, fmt.Errorf("Failed to create renderer: %s\n", err)
	}
	renderer.Clear()

	return &Screen{
		window:   window,
		renderer: renderer,
		mem:      mem,
	}, nil
}

func (s *Screen) Draw() {

	// Clear screen
	rect := sdl.Rect{0, 0, int32(screenWidth * screenScale), int32(screenHeight * screenScale)}
	s.renderer.SetDrawColor(255, 255, 255, 255)
	s.renderer.FillRect(&rect)

	// Draw each scanline
	for y := 0; y < screenHeight; y++ {
		s.drawScanline(y)
	}
	s.renderer.Present()
	s.flashCount = (s.flashCount + 1) % 64
}

func (s *Screen) drawScanline(y int) {
	lineMemLen := screenWidth / 8

	sector := (y & 0xc0) >> 6
	sectorRow := (y & 0x38) >> 3
	charRow := (y & 0x07)
	addr := screenMemStart + (sector*64+charRow*8+sectorRow)*lineMemLen

	colourRow := (sector << 3) + sectorRow
	colourAddr := colourMemStart + (256/8)*colourRow

	lineMem, err := s.mem.PeekBuf(uint16(addr), lineMemLen)
	if err != nil {
		panic(fmt.Errorf("Can't read screen memory at [%04X] len (%04X)", addr, lineMemLen))
	}
	colourMem, err := s.mem.PeekBuf(uint16(colourAddr), lineMemLen)
	if err != nil {
		panic(fmt.Errorf("Can't read screen memory at [%04X] len (%04X)", addr, lineMemLen))
	}

	for i, b := range lineMem {
		colourByte := colourMem[i]
		ink := colourByte & 0x07
		paper := (colourByte & 0x38) >> 3
		bright := (colourByte & 0x40) >> 6
		flash := (colourByte & 0x80) >> 7

		for bit := 0; bit < 8; bit++ {
			x := i*8 + bit
			if b&0x80 != 0 {
				s.SetDrawColour(true, ink, paper, bright, flash)
				//				s.renderer.SetDrawColor(0, 0, 0, 255)
			} else {
				s.SetDrawColour(false, ink, paper, bright, flash)
				//				s.renderer.SetDrawColor(255, 255, 255, 255)
			}
			//			fmt.Printf("x %d y %d i %d bit %d\n", x, y, i, b)
			rect := sdl.Rect{int32(x * screenScale), int32(y * screenScale), screenScale, screenScale}
			s.renderer.FillRect(&rect)
			//			s.renderer.DrawPoint(x, y)
			b <<= 1
		}
	}
}

// Bright versions, non-bright are reduced from ff to d7
var Colours = []sdl.Color{
	{0, 0, 0, 0},
	{0, 0, 1, 0},
	{1, 0, 0, 0},
	{1, 0, 1, 0},
	{0, 1, 0, 0},
	{0, 1, 1, 0},
	{1, 1, 0, 0},
	{1, 1, 1, 0},
}

func (s *Screen) SetDrawColour(wantInk bool, ink, paper, bright, flash byte) {
	invert := flash != 0 && s.flashCount < 32 // 0-31 inverted, 32-63 not inverted

	index := paper
	if (wantInk && !invert) || (invert && !wantInk) {
		index = ink
	}
	c := Colours[index]
	factor := byte(0xd7)
	if bright != 0 {
		factor = 0xff
	}
	s.renderer.SetDrawColor(c.R*factor, c.G*factor, c.B*factor, 255)
}

func (s *Screen) Close() {
	s.renderer.Destroy()
	s.window.Destroy()
}
<commit_msg>no need to clear sdl screen, we redraw<commit_after>package speccy

import (
	"fmt"

	"github.com/jbert/zog"
	"github.com/veandco/go-sdl2/sdl"
)

const (
	screenWidth  = 256
	screenHeight = 192
	screenScale  = 4

	screenMemStart = 0x4000
	colourMemStart = 0x5800
)

type Screen struct {
	window   *sdl.Window
	renderer *sdl.Renderer
	mem      *zog.Memory

	flashCount int
}

func NewScreen(mem *zog.Memory) (*Screen, error) {
	winTitle := "Speccy"
	window, err := sdl.CreateWindow(winTitle, sdl.WINDOWPOS_UNDEFINED, sdl.WINDOWPOS_UNDEFINED,
		screenWidth*screenScale, screenHeight*screenScale, sdl.WINDOW_SHOWN)
	if err != nil {
		return nil, fmt.Errorf("Failed to create window: %s\n", err)
	}

	renderer, err := sdl.CreateRenderer(window, -1, sdl.RENDERER_ACCELERATED)
	if err != nil {
		return nil, fmt.Errorf("Failed to create renderer: %s\n", err)
	}
	renderer.Clear()

	return &Screen{
		window:   window,
		renderer: renderer,
		mem:      mem,
	}, nil
}

func (s *Screen) Draw() {

	// Clear screen
	//rect := sdl.Rect{0, 0, int32(screenWidth * screenScale), int32(screenHeight * screenScale)}
	//	s.renderer.SetDrawColor(255, 255, 255, 255)
	//	s.renderer.FillRect(&rect)

	// Draw each scanline
	for y := 0; y < screenHeight; y++ {
		s.drawScanline(y)
	}
	s.renderer.Present()
	s.flashCount = (s.flashCount + 1) % 64
}

func (s *Screen) drawScanline(y int) {
	lineMemLen := screenWidth / 8

	sector := (y & 0xc0) >> 6
	sectorRow := (y & 0x38) >> 3
	charRow := (y & 0x07)
	addr := screenMemStart + (sector*64+charRow*8+sectorRow)*lineMemLen

	colourRow := (sector << 3) + sectorRow
	colourAddr := colourMemStart + (256/8)*colourRow

	lineMem, err := s.mem.PeekBuf(uint16(addr), lineMemLen)
	if err != nil {
		panic(fmt.Errorf("Can't read screen memory at [%04X] len (%04X)", addr, lineMemLen))
	}
	colourMem, err := s.mem.PeekBuf(uint16(colourAddr), lineMemLen)
	if err != nil {
		panic(fmt.Errorf("Can't read screen memory at [%04X] len (%04X)", addr, lineMemLen))
	}

	for i, b := range lineMem {
		colourByte := colourMem[i]
		ink := colourByte & 0x07
		paper := (colourByte & 0x38) >> 3
		bright := (colourByte & 0x40) >> 6
		flash := (colourByte & 0x80) >> 7

		for bit := 0; bit < 8; bit++ {
			x := i*8 + bit
			if b&0x80 != 0 {
				s.SetDrawColour(true, ink, paper, bright, flash)
				//				s.renderer.SetDrawColor(0, 0, 0, 255)
			} else {
				s.SetDrawColour(false, ink, paper, bright, flash)
				//				s.renderer.SetDrawColor(255, 255, 255, 255)
			}
			//			fmt.Printf("x %d y %d i %d bit %d\n", x, y, i, b)
			rect := sdl.Rect{int32(x * screenScale), int32(y * screenScale), screenScale, screenScale}
			s.renderer.FillRect(&rect)
			//			s.renderer.DrawPoint(x, y)
			b <<= 1
		}
	}
}

// Bright versions, non-bright are reduced from ff to d7
var Colours = []sdl.Color{
	{0, 0, 0, 0},
	{0, 0, 1, 0},
	{1, 0, 0, 0},
	{1, 0, 1, 0},
	{0, 1, 0, 0},
	{0, 1, 1, 0},
	{1, 1, 0, 0},
	{1, 1, 1, 0},
}

func (s *Screen) SetDrawColour(wantInk bool, ink, paper, bright, flash byte) {
	invert := flash != 0 && s.flashCount < 32 // 0-31 inverted, 32-63 not inverted

	index := paper
	if (wantInk && !invert) || (invert && !wantInk) {
		index = ink
	}
	c := Colours[index]
	factor := byte(0xd7)
	if bright != 0 {
		factor = 0xff
	}
	s.renderer.SetDrawColor(c.R*factor, c.G*factor, c.B*factor, 255)
}

func (s *Screen) Close() {
	s.renderer.Destroy()
	s.window.Destroy()
}
<|endoftext|>


<commit_before>package google

import (
	"fmt"
	"log"

	"github.com/hashicorp/terraform/helper/schema"
	"google.golang.org/api/compute/v1"
)

func resourceComputeForwardingRule() *schema.Resource {
	return &schema.Resource{
		Create: resourceComputeForwardingRuleCreate,
		Read:   resourceComputeForwardingRuleRead,
		Delete: resourceComputeForwardingRuleDelete,
		Update: resourceComputeForwardingRuleUpdate,
		Importer: &schema.ResourceImporter{
			State: schema.ImportStatePassthrough,
		},

		Schema: map[string]*schema.Schema{
			"name": &schema.Schema{
				Type:     schema.TypeString,
				Required: true,
				ForceNew: true,
			},

			"target": &schema.Schema{
				Type:     schema.TypeString,
				Optional: true,
				ForceNew: false,
			},

			"backend_service": &schema.Schema{
				Type:     schema.TypeString,
				Optional: true,
				ForceNew: true,
			},

			"description": &schema.Schema{
				Type:     schema.TypeString,
				Optional: true,
				ForceNew: true,
			},

			"ip_address": &schema.Schema{
				Type:     schema.TypeString,
				Optional: true,
				ForceNew: true,
				Computed: true,
			},

			"ip_protocol": &schema.Schema{
				Type:     schema.TypeString,
				Optional: true,
				ForceNew: true,
				Computed: true,
			},

			"load_balancing_scheme": &schema.Schema{
				Type:     schema.TypeString,
				Optional: true,
				ForceNew: true,
				Default:  "EXTERNAL",
			},

			"network": &schema.Schema{
				Type:             schema.TypeString,
				Optional:         true,
				ForceNew:         true,
				Computed:         true,
				DiffSuppressFunc: compareSelfLinkOrResourceName,
			},

			"port_range": &schema.Schema{
				Type:             schema.TypeString,
				Optional:         true,
				ForceNew:         true,
				DiffSuppressFunc: portRangeDiffSuppress,
			},

			"ports": &schema.Schema{
				Type:     schema.TypeSet,
				Elem:     &schema.Schema{Type: schema.TypeString},
				Optional: true,
				ForceNew: true,
				Set:      schema.HashString,
				MaxItems: 5,
			},

			"project": &schema.Schema{
				Type:     schema.TypeString,
				Optional: true,
				ForceNew: true,
				Computed: true,
			},

			"region": &schema.Schema{
				Type:     schema.TypeString,
				Optional: true,
				ForceNew: true,
				Computed: true,
			},

			"self_link": &schema.Schema{
				Type:     schema.TypeString,
				Computed: true,
			},

			"subnetwork": &schema.Schema{
				Type:     schema.TypeString,
				Optional: true,
				ForceNew: true,
				Computed: true,
			},
		},
	}
}

func resourceComputeForwardingRuleCreate(d *schema.ResourceData, meta interface{}) error {
	config := meta.(*Config)

	network, err := ParseNetworkFieldValue(d.Get("network").(string), d, config)
	if err != nil {
		return err
	}

	region, err := getRegion(d, config)
	if err != nil {
		return err
	}

	project, err := getProject(d, config)
	if err != nil {
		return err
	}

	ps := d.Get("ports").(*schema.Set).List()
	ports := make([]string, 0, len(ps))
	for _, v := range ps {
		ports = append(ports, v.(string))
	}

	frule := &compute.ForwardingRule{
		BackendService:      d.Get("backend_service").(string),
		IPAddress:           d.Get("ip_address").(string),
		IPProtocol:          d.Get("ip_protocol").(string),
		Description:         d.Get("description").(string),
		LoadBalancingScheme: d.Get("load_balancing_scheme").(string),
		Name:                d.Get("name").(string),
		Network:             network.RelativeLink(),
		PortRange:           d.Get("port_range").(string),
		Ports:               ports,
		Subnetwork:          d.Get("subnetwork").(string),
		Target:              d.Get("target").(string),
	}

	log.Printf("[DEBUG] ForwardingRule insert request: %#v", frule)
	op, err := config.clientCompute.ForwardingRules.Insert(
		project, region, frule).Do()
	if err != nil {
		return fmt.Errorf("Error creating ForwardingRule: %s", err)
	}

	// It probably maybe worked, so store the ID now
	d.SetId(frule.Name)

	err = computeOperationWait(config.clientCompute, op, project, "Creating Fowarding Rule")
	if err != nil {
		return err
	}

	return resourceComputeForwardingRuleRead(d, meta)
}

func resourceComputeForwardingRuleUpdate(d *schema.ResourceData, meta interface{}) error {
	config := meta.(*Config)

	region, err := getRegion(d, config)
	if err != nil {
		return err
	}

	project, err := getProject(d, config)
	if err != nil {
		return err
	}

	d.Partial(true)

	if d.HasChange("target") {
		target_name := d.Get("target").(string)
		target_ref := &compute.TargetReference{Target: target_name}
		op, err := config.clientCompute.ForwardingRules.SetTarget(
			project, region, d.Id(), target_ref).Do()
		if err != nil {
			return fmt.Errorf("Error updating target: %s", err)
		}

		err = computeOperationWait(config.clientCompute, op, project, "Updating Forwarding Rule")
		if err != nil {
			return err
		}

		d.SetPartial("target")
	}

	d.Partial(false)

	return resourceComputeForwardingRuleRead(d, meta)
}

func resourceComputeForwardingRuleRead(d *schema.ResourceData, meta interface{}) error {
	config := meta.(*Config)

	region, err := getRegion(d, config)
	if err != nil {
		return err
	}

	project, err := getProject(d, config)
	if err != nil {
		return err
	}

	frule, err := config.clientCompute.ForwardingRules.Get(
		project, region, d.Id()).Do()
	if err != nil {
		return handleNotFoundError(err, d, fmt.Sprintf("Forwarding Rule %q", d.Get("name").(string)))
	}

	d.Set("name", frule.Name)
	d.Set("target", frule.Target)
	d.Set("backend_service", frule.BackendService)
	d.Set("description", frule.Description)
	d.Set("load_balancing_scheme", frule.LoadBalancingScheme)
	d.Set("network", frule.Network)
	d.Set("port_range", frule.PortRange)
	d.Set("ports", frule.Ports)
	d.Set("project", project)
	d.Set("region", region)
	d.Set("subnetwork", frule.Subnetwork)
	d.Set("ip_address", frule.IPAddress)
	d.Set("ip_protocol", frule.IPProtocol)
	d.Set("self_link", frule.SelfLink)
	return nil
}

func resourceComputeForwardingRuleDelete(d *schema.ResourceData, meta interface{}) error {
	config := meta.(*Config)

	region, err := getRegion(d, config)
	if err != nil {
		return err
	}

	project, err := getProject(d, config)
	if err != nil {
		return err
	}

	// Delete the ForwardingRule
	log.Printf("[DEBUG] ForwardingRule delete request")
	op, err := config.clientCompute.ForwardingRules.Delete(
		project, region, d.Id()).Do()
	if err != nil {
		return fmt.Errorf("Error deleting ForwardingRule: %s", err)
	}

	err = computeOperationWait(config.clientCompute, op, project, "Deleting Forwarding Rule")
	if err != nil {
		return err
	}

	d.SetId("")
	return nil
}
<commit_msg>add diffsuppress to allow lowercase ip protocols (#1118)<commit_after>package google

import (
	"fmt"
	"log"
	"strings"

	"github.com/hashicorp/terraform/helper/schema"
	"google.golang.org/api/compute/v1"
)

func resourceComputeForwardingRule() *schema.Resource {
	return &schema.Resource{
		Create: resourceComputeForwardingRuleCreate,
		Read:   resourceComputeForwardingRuleRead,
		Delete: resourceComputeForwardingRuleDelete,
		Update: resourceComputeForwardingRuleUpdate,
		Importer: &schema.ResourceImporter{
			State: schema.ImportStatePassthrough,
		},

		Schema: map[string]*schema.Schema{
			"name": &schema.Schema{
				Type:     schema.TypeString,
				Required: true,
				ForceNew: true,
			},

			"target": &schema.Schema{
				Type:     schema.TypeString,
				Optional: true,
				ForceNew: false,
			},

			"backend_service": &schema.Schema{
				Type:     schema.TypeString,
				Optional: true,
				ForceNew: true,
			},

			"description": &schema.Schema{
				Type:     schema.TypeString,
				Optional: true,
				ForceNew: true,
			},

			"ip_address": &schema.Schema{
				Type:     schema.TypeString,
				Optional: true,
				ForceNew: true,
				Computed: true,
			},

			"ip_protocol": &schema.Schema{
				Type:     schema.TypeString,
				Optional: true,
				ForceNew: true,
				Computed: true,
				DiffSuppressFunc: func(k, old, new string, d *schema.ResourceData) bool {
					return strings.ToUpper(old) == strings.ToUpper(new)
				},
			},

			"load_balancing_scheme": &schema.Schema{
				Type:     schema.TypeString,
				Optional: true,
				ForceNew: true,
				Default:  "EXTERNAL",
			},

			"network": &schema.Schema{
				Type:             schema.TypeString,
				Optional:         true,
				ForceNew:         true,
				Computed:         true,
				DiffSuppressFunc: compareSelfLinkOrResourceName,
			},

			"port_range": &schema.Schema{
				Type:             schema.TypeString,
				Optional:         true,
				ForceNew:         true,
				DiffSuppressFunc: portRangeDiffSuppress,
			},

			"ports": &schema.Schema{
				Type:     schema.TypeSet,
				Elem:     &schema.Schema{Type: schema.TypeString},
				Optional: true,
				ForceNew: true,
				Set:      schema.HashString,
				MaxItems: 5,
			},

			"project": &schema.Schema{
				Type:     schema.TypeString,
				Optional: true,
				ForceNew: true,
				Computed: true,
			},

			"region": &schema.Schema{
				Type:     schema.TypeString,
				Optional: true,
				ForceNew: true,
				Computed: true,
			},

			"self_link": &schema.Schema{
				Type:     schema.TypeString,
				Computed: true,
			},

			"subnetwork": &schema.Schema{
				Type:     schema.TypeString,
				Optional: true,
				ForceNew: true,
				Computed: true,
			},
		},
	}
}

func resourceComputeForwardingRuleCreate(d *schema.ResourceData, meta interface{}) error {
	config := meta.(*Config)

	network, err := ParseNetworkFieldValue(d.Get("network").(string), d, config)
	if err != nil {
		return err
	}

	region, err := getRegion(d, config)
	if err != nil {
		return err
	}

	project, err := getProject(d, config)
	if err != nil {
		return err
	}

	ps := d.Get("ports").(*schema.Set).List()
	ports := make([]string, 0, len(ps))
	for _, v := range ps {
		ports = append(ports, v.(string))
	}

	frule := &compute.ForwardingRule{
		BackendService:      d.Get("backend_service").(string),
		IPAddress:           d.Get("ip_address").(string),
		IPProtocol:          d.Get("ip_protocol").(string),
		Description:         d.Get("description").(string),
		LoadBalancingScheme: d.Get("load_balancing_scheme").(string),
		Name:                d.Get("name").(string),
		Network:             network.RelativeLink(),
		PortRange:           d.Get("port_range").(string),
		Ports:               ports,
		Subnetwork:          d.Get("subnetwork").(string),
		Target:              d.Get("target").(string),
	}

	log.Printf("[DEBUG] ForwardingRule insert request: %#v", frule)
	op, err := config.clientCompute.ForwardingRules.Insert(
		project, region, frule).Do()
	if err != nil {
		return fmt.Errorf("Error creating ForwardingRule: %s", err)
	}

	// It probably maybe worked, so store the ID now
	d.SetId(frule.Name)

	err = computeOperationWait(config.clientCompute, op, project, "Creating Fowarding Rule")
	if err != nil {
		return err
	}

	return resourceComputeForwardingRuleRead(d, meta)
}

func resourceComputeForwardingRuleUpdate(d *schema.ResourceData, meta interface{}) error {
	config := meta.(*Config)

	region, err := getRegion(d, config)
	if err != nil {
		return err
	}

	project, err := getProject(d, config)
	if err != nil {
		return err
	}

	d.Partial(true)

	if d.HasChange("target") {
		target_name := d.Get("target").(string)
		target_ref := &compute.TargetReference{Target: target_name}
		op, err := config.clientCompute.ForwardingRules.SetTarget(
			project, region, d.Id(), target_ref).Do()
		if err != nil {
			return fmt.Errorf("Error updating target: %s", err)
		}

		err = computeOperationWait(config.clientCompute, op, project, "Updating Forwarding Rule")
		if err != nil {
			return err
		}

		d.SetPartial("target")
	}

	d.Partial(false)

	return resourceComputeForwardingRuleRead(d, meta)
}

func resourceComputeForwardingRuleRead(d *schema.ResourceData, meta interface{}) error {
	config := meta.(*Config)

	region, err := getRegion(d, config)
	if err != nil {
		return err
	}

	project, err := getProject(d, config)
	if err != nil {
		return err
	}

	frule, err := config.clientCompute.ForwardingRules.Get(
		project, region, d.Id()).Do()
	if err != nil {
		return handleNotFoundError(err, d, fmt.Sprintf("Forwarding Rule %q", d.Get("name").(string)))
	}

	d.Set("name", frule.Name)
	d.Set("target", frule.Target)
	d.Set("backend_service", frule.BackendService)
	d.Set("description", frule.Description)
	d.Set("load_balancing_scheme", frule.LoadBalancingScheme)
	d.Set("network", frule.Network)
	d.Set("port_range", frule.PortRange)
	d.Set("ports", frule.Ports)
	d.Set("project", project)
	d.Set("region", region)
	d.Set("subnetwork", frule.Subnetwork)
	d.Set("ip_address", frule.IPAddress)
	d.Set("ip_protocol", frule.IPProtocol)
	d.Set("self_link", frule.SelfLink)
	return nil
}

func resourceComputeForwardingRuleDelete(d *schema.ResourceData, meta interface{}) error {
	config := meta.(*Config)

	region, err := getRegion(d, config)
	if err != nil {
		return err
	}

	project, err := getProject(d, config)
	if err != nil {
		return err
	}

	// Delete the ForwardingRule
	log.Printf("[DEBUG] ForwardingRule delete request")
	op, err := config.clientCompute.ForwardingRules.Delete(
		project, region, d.Id()).Do()
	if err != nil {
		return fmt.Errorf("Error deleting ForwardingRule: %s", err)
	}

	err = computeOperationWait(config.clientCompute, op, project, "Deleting Forwarding Rule")
	if err != nil {
		return err
	}

	d.SetId("")
	return nil
}
<|endoftext|>


<commit_before>package main

import (
  "flag"
  "fmt"
  "os"
  "strings"
  "path/filepath"
  "sprinter/nixcmd"
  "sprinter/wincmd"
)

var nixcmdFlag = flag.String("nixcmd", "", "  NIXcommand")
var wincmdFlag = flag.String("wincmd", "", "  WINDOWScommand")
var fileFlag = flag.String("file", "", " File")
var keyFlag = flag.String("key", "", " Key")
var userFlag = flag.String("user", "root", " User")
var portFlag = flag.Int("port", 22, " Port")
var hostFlag = flag.String("host", "", " Host")
var httpsFlag = flag.Bool("https", false, " HTTPS")
var insecureFlag = flag.Bool("insecure", false, " Insecure")
var cacertFlag = flag.String("cacert", "", "CACert")

func init() {
  Hostsfile, err := filepath.Abs(filepath.Dir(os.Args[0]) + "/Hostsfile")
  if err != nil {
    fmt.Println(err)
  }
  flag.StringVar(nixcmdFlag, "nc", "", "  NIXcommand")
  flag.StringVar(wincmdFlag, "wc", "", "  WINDOWScommand")
  flag.StringVar(fileFlag, "f", Hostsfile, "  File")
  flag.StringVar(keyFlag, "k", "", "  Key")
  flag.StringVar(userFlag, "u", "root", "  User")
  flag.IntVar(portFlag, "p", 22, "  Port")
  flag.StringVar(hostFlag, "h", "", " Host")
  flag.BoolVar(httpsFlag, "ssl", false, "HTTPS")
  flag.BoolVar(insecureFlag, "insec", false, "Insecure")
  flag.StringVar(cacertFlag, "ca", "", "CACert")
}

var usage = `Usage: sprinter [options] <args>

Sprinter executes SSH commands on systems by reading a file line by line

-nc, -nixcmd             Run NIX command or commands: 'df-h','uname -a'
-wc, -wincmd             Run Windows command or commands: 'ipconfig /all', 'set'
-f, -file, optional      Hosts file location, default is ./Hostsfile
-h, -host, optional      Run commands on one host
-k, -key                 PEM key file location: ~/.ssh/key.pem
-u, -user, optional      Username and/or password to run as: Administrator:secret
                         default is root
-p, -port, optional      Port to SSH/WinRM as: 5985, default is 22
-https, optional         Use HTTPS for WinRM, default is false
-insecure, optional      Use SSL validation, default is false
-cacert, optional        Use CA Certificate, default is None

Documentation:  https://github.com/marshyski/sprinter/blob/master/README.md

`

func main() {

  flag.Usage = func() {
    fmt.Println(usage)
  }

  flag.Parse()

  if *nixcmdFlag == "" && *wincmdFlag == "" {
    fmt.Println(usage)
    os.Exit(1)
  }

  if *fileFlag == "" && *hostFlag == "" {
    fmt.Println(usage)
    os.Exit(1)
  }

  username := strings.Split(*userFlag, ":")[0]
  password := ``
  if strings.Contains(*userFlag, ":") {
    password += strings.Split(*userFlag, ":")[0]
  }

  if *nixcmdFlag != "" {
    nixcmd.Nix(*nixcmdFlag, *portFlag, username, *fileFlag, *keyFlag, password, *hostFlag)
  }

  if *wincmdFlag != "" {
    wincmd.Win(*wincmdFlag, *portFlag, username, *fileFlag, *httpsFlag, *insecureFlag, password, *cacertFlag, *hostFlag)
  }
}
<commit_msg>Changed usaged title<commit_after>package main

import (
  "flag"
  "fmt"
  "os"
  "strings"
  "path/filepath"
  "sprinter/nixcmd"
  "sprinter/wincmd"
)

var nixcmdFlag = flag.String("nixcmd", "", "  NIXcommand")
var wincmdFlag = flag.String("wincmd", "", "  WINDOWScommand")
var fileFlag = flag.String("file", "", " File")
var keyFlag = flag.String("key", "", " Key")
var userFlag = flag.String("user", "root", " User")
var portFlag = flag.Int("port", 22, " Port")
var hostFlag = flag.String("host", "", " Host")
var httpsFlag = flag.Bool("https", false, " HTTPS")
var insecureFlag = flag.Bool("insecure", false, " Insecure")
var cacertFlag = flag.String("cacert", "", "CACert")

func init() {
  Hostsfile, err := filepath.Abs(filepath.Dir(os.Args[0]) + "/Hostsfile")
  if err != nil {
    fmt.Println(err)
  }
  flag.StringVar(nixcmdFlag, "nc", "", "  NIXcommand")
  flag.StringVar(wincmdFlag, "wc", "", "  WINDOWScommand")
  flag.StringVar(fileFlag, "f", Hostsfile, "  File")
  flag.StringVar(keyFlag, "k", "", "  Key")
  flag.StringVar(userFlag, "u", "root", "  User")
  flag.IntVar(portFlag, "p", 22, "  Port")
  flag.StringVar(hostFlag, "h", "", " Host")
  flag.BoolVar(httpsFlag, "ssl", false, "HTTPS")
  flag.BoolVar(insecureFlag, "insec", false, "Insecure")
  flag.StringVar(cacertFlag, "ca", "", "CACert")
}

var usage = `Usage: sprinter [options] <args>

Sprinter remote executes SSH / WinRM commands

-nc, -nixcmd             Run NIX command or commands: 'df-h','uname -a'
-wc, -wincmd             Run Windows command or commands: 'ipconfig /all', 'set'
-f, -file, optional      Hosts file location, default is ./Hostsfile
-h, -host, optional      Run commands on one host
-k, -key                 PEM key file location: ~/.ssh/key.pem
-u, -user, optional      Username and/or password to run as: Administrator:secret
                         default is root
-p, -port, optional      Port to SSH/WinRM as: 5985, default is 22
-https, optional         Use HTTPS for WinRM, default is false
-insecure, optional      Use SSL validation, default is false
-cacert, optional        Use CA Certificate, default is None

Documentation:  https://github.com/marshyski/sprinter/blob/master/README.md

`

func main() {

  flag.Usage = func() {
    fmt.Println(usage)
  }

  flag.Parse()

  if *nixcmdFlag == "" && *wincmdFlag == "" {
    fmt.Println(usage)
    os.Exit(1)
  }

  if *fileFlag == "" && *hostFlag == "" {
    fmt.Println(usage)
    os.Exit(1)
  }

  username := strings.Split(*userFlag, ":")[0]
  password := ``
  if strings.Contains(*userFlag, ":") {
    password += strings.Split(*userFlag, ":")[0]
  }

  if *nixcmdFlag != "" {
    nixcmd.Nix(*nixcmdFlag, *portFlag, username, *fileFlag, *keyFlag, password, *hostFlag)
  }

  if *wincmdFlag != "" {
    wincmd.Win(*wincmdFlag, *portFlag, username, *fileFlag, *httpsFlag, *insecureFlag, password, *cacertFlag, *hostFlag)
  }
}
<|endoftext|>


<commit_before>//
// Copyright (c) 2015-2017 Snowplow Analytics Ltd. All rights reserved.
//
// This program is licensed to you under the Apache License Version 2.0,
// and you may not use this file except in compliance with the Apache License Version 2.0.
// You may obtain a copy of the Apache License Version 2.0 at http://www.apache.org/licenses/LICENSE-2.0.
//
// Unless required by applicable law or agreed to in writing,
// software distributed under the Apache License Version 2.0 is distributed on an
// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the Apache License Version 2.0 for the specific language governing permissions and limitations there under.
//
package main

import (
	"bytes"
	"os"
	"text/template"
	"time"
)

var (
	templFuncs = template.FuncMap{
		"nowWithFormat": func(format string) string {
			return time.Now().Format(format)
		},
		"systemEnv": func(env string) string {
			return os.Getenv(env)
		},
		"awsChainCredentials":   awsChainCredentials,
		"awsEC2RoleCredentials": awsEC2RoleCredentials,
		"awsEnvCredentials":     awsEnvCredentials,
		"awsProfileCredentials": awsProfileCredentials,
	}
)

// Generalized interface to a database client
type Db interface {
	RunQuery(ReadyQuery, bool) QueryStatus
	GetTarget() Target
}

// Reads the script and fills in the template
func prepareQuery(queryPath string, sp SQLProvider, template bool, variables map[string]interface{}) (string, error) {

	var script string
	var err error

	script, err = sp.GetSQL(queryPath)

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

	if template {
		script, err = fillTemplate(script, variables) // Yech, mutate
		if err != nil {
			return "", err
		}
	}
	return script, nil
}

// Fills in a script which is a template
func fillTemplate(script string, variables map[string]interface{}) (string, error) {

	t, err := template.New("playbook").Funcs(templFuncs).Parse(script)
	if err != nil {
		return "", err
	}

	var filled bytes.Buffer
	if err := t.Execute(&filled, variables); err != nil {
		return "", err
	}
	return filled.String(), nil
}
<commit_msg>Add a random number templating function (close #109)<commit_after>//
// Copyright (c) 2015-2017 Snowplow Analytics Ltd. All rights reserved.
//
// This program is licensed to you under the Apache License Version 2.0,
// and you may not use this file except in compliance with the Apache License Version 2.0.
// You may obtain a copy of the Apache License Version 2.0 at http://www.apache.org/licenses/LICENSE-2.0.
//
// Unless required by applicable law or agreed to in writing,
// software distributed under the Apache License Version 2.0 is distributed on an
// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the Apache License Version 2.0 for the specific language governing permissions and limitations there under.
//
package main

import (
	"bytes"
	"math/rand"
	"os"
	"strconv"
	"text/template"
	"time"
)

var (
	templFuncs = template.FuncMap{
		"nowWithFormat": func(format string) string {
			return time.Now().Format(format)
		},
		"systemEnv": func(env string) string {
			return os.Getenv(env)
		},
		"randomInt": func() (string, error) {
			r := rand.NewSource(time.Now().UnixNano())
			return strconv.FormatInt(r.Int63(), 10), nil
		},
		"awsChainCredentials":   awsChainCredentials,
		"awsEC2RoleCredentials": awsEC2RoleCredentials,
		"awsEnvCredentials":     awsEnvCredentials,
		"awsProfileCredentials": awsProfileCredentials,
	}
)

// Generalized interface to a database client
type Db interface {
	RunQuery(ReadyQuery, bool) QueryStatus
	GetTarget() Target
}

// Reads the script and fills in the template
func prepareQuery(queryPath string, sp SQLProvider, template bool, variables map[string]interface{}) (string, error) {

	var script string
	var err error

	script, err = sp.GetSQL(queryPath)

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

	if template {
		script, err = fillTemplate(script, variables) // Yech, mutate
		if err != nil {
			return "", err
		}
	}
	return script, nil
}

// Fills in a script which is a template
func fillTemplate(script string, variables map[string]interface{}) (string, error) {

	t, err := template.New("playbook").Funcs(templFuncs).Parse(script)
	if err != nil {
		return "", err
	}

	var filled bytes.Buffer
	if err := t.Execute(&filled, variables); err != nil {
		return "", err
	}
	return filled.String(), nil
}
<|endoftext|>


<commit_before>package sqlhooks

import (
	"database/sql"
	"flag"
	"fmt"
	"sort"
	"testing"
	"time"
)

var (
	driverFlag = flag.String("driver", "test", "SQL Driver")
	dsnFlag    = flag.String("dsn", "db", "DSN")
)

type ops struct {
	wipe        string
	create      string
	insert      string
	selectwhere string
	selectall   string
}

var queries = make(map[string]ops)

func openDBWithHooks(t *testing.T, hooks *Hooks) *sql.DB {
	q := queries[*driverFlag]

	// First, we connect directly using `test` driver
	if db, err := sql.Open(*driverFlag, *dsnFlag); err != nil {
		t.Fatalf("sql.Open: %v", err)
		return nil
	} else {
		if _, err := db.Exec(q.wipe); err != nil {
			t.Fatalf("WIPE: %v", err)
			return nil
		}

		if _, err := db.Exec(q.create); err != nil {
			t.Fatalf("CREATE: %v", err)
			return nil
		}
	}

	// Now, return a db handler using hooked driver
	driver := NewDriver(*driverFlag, hooks)
	driverName := fmt.Sprintf("sqlhooks-%d", time.Now().UnixNano())
	Register(driverName, driver)

	db, err := sql.Open(driverName, *dsnFlag)
	if err != nil {
		t.Fatalf("sql.Open: %v", err)
		return nil
	}

	return db
}

func TestHooks(t *testing.T) {
	q := queries[*driverFlag]
	tests := []struct {
		op    string
		query string
		args  []interface{}
	}{
		{"exec", q.insert, []interface{}{"foo", "bar"}},
		{"query", q.selectwhere, []interface{}{"foo", "bar"}},
		{"query", q.selectall, []interface{}{}},
		{"stmt.query", q.selectall, nil},
		{"stmt.exec", q.insert, []interface{}{"x", "y"}},
		{"tx.query", q.selectall, nil},
		{"tx.exec", q.insert, []interface{}{"x", "y"}},
	}

	for _, test := range tests {
		done := false
		assert := func(query string, args ...interface{}) func(error) {
			// Query Assertions
			if query != test.query {
				t.Errorf("query = `%s`, expected `%s`", query, test.query)
			}

			if test.args == nil {
				test.args = []interface{}{}
			}

			// Arguments assertions
			if len(args) != len(test.args) {
				t.Errorf("Expected args: %d, got %d", len(test.args), len(args))
			}
			for i, _ := range test.args {
				if args[i] != test.args[i] {
					t.Errorf("%s: arg[%d] == %#v, got %#v", test.op, i, test.args[i], args[i])
				}
			}

			return func(error) {
				done = true
			}
		}
		db := openDBWithHooks(t, &Hooks{Query: assert, Exec: assert})

		switch test.op {
		case "query":
			if _, err := db.Query(test.query, test.args...); err != nil {
				t.Errorf("query: %v", err)
			}
		case "exec":
			if _, err := db.Exec(test.query, test.args...); err != nil {
				t.Errorf("exec: %v", err)
			}
		case "stmt.query":
			if stmt, err := db.Prepare(test.query); err != nil {
				t.Errorf("prepare: %v", err)
			} else {
				if _, err := stmt.Query(test.args...); err != nil {
					t.Errorf("prepared query: %v", err)
				}
			}
		case "stmt.exec":
			if stmt, err := db.Prepare(test.query); err != nil {
				t.Errorf("prepare: %v", err)
			} else {
				if _, err := stmt.Exec(test.args...); err != nil {
					t.Errorf("prepared exec: %v", err)
				}
			}
		case "tx.query":
			tx, err := db.Begin()
			if err != nil {
				t.Errorf("[%s] begin: %v", test.op, err)
			}
			if _, err := tx.Query(test.query, test.args...); err != nil {
				t.Errorf("[%s] query: %v", test.op, err)
			}
			if err := tx.Commit(); err != nil {
				t.Errorf("[%s] commit: %v", test.op, err)
			}
		case "tx.exec":
			tx, err := db.Begin()
			if err != nil {
				t.Errorf("[%s] begin: %v", test.op, err)
			}
			if _, err := tx.Exec(test.query, test.args...); err != nil {
				t.Errorf("[%s] exec: %v", test.op, err)
			}
			if err := tx.Commit(); err != nil {
				t.Errorf("[%s] commit: %v", test.op, err)
			}
		}

		if done == false {
			t.Errorf("Expected %s cancelation to be completed", test.op)
		}

	}
}

func TestEmptyHooks(t *testing.T) {
	q := queries[*driverFlag]
	db := openDBWithHooks(t, &Hooks{})

	if _, err := db.Exec(q.insert, "foo", "bar"); err != nil {
		t.Fatalf("Exec: %v\n", err)
	}

	if _, err := db.Query(q.selectall); err != nil {
		t.Fatalf("Query: %v\n", err)
	}
}

func TestCreateInsertAndSelect(t *testing.T) {
	q := queries[*driverFlag]
	db := openDBWithHooks(t, &Hooks{})

	db.Exec(q.insert, "a", "1")
	db.Exec(q.insert, "b", "2")
	db.Exec(q.insert, "c", "3")

	rows, _ := db.Query(q.selectall)
	var fs []string
	for rows.Next() {
		var f1 string
		var f2 string
		rows.Scan(&f1, &f2)
		fs = append(fs, f1)
	}
	sort.Strings(fs)
	if len(fs) != 3 {
		t.Fatalf("Expected 3 rows, got: %d", len(fs))
	}

	for i, e := range []string{"a", "b", "c"}[:len(fs)] {
		f := fs[i]
		if f != e {
			t.Errorf("f1 = `%s`, expected: `%s`", f, e)
		}
	}
}

func TestTXs(t *testing.T) {
	for _, op := range []string{"commit", "rollback"} {
		ids := struct {
			begin string
			end   string
		}{}

		db := openDBWithHooks(t, &Hooks{
			Begin: func(id string) {
				ids.begin = id
			},
			Commit: func(id string) {
				ids.end = id
			},
			Rollback: func(id string) {
				ids.end = id
			},
		})

		tx, err := db.Begin()
		if err != nil {
			t.Errorf("begin: %v", err)
			continue
		}

		switch op {
		case "commit":
			if err := tx.Commit(); err != nil {
				t.Errorf("commit: %v", err)
			}
		case "rollback":
			if err := tx.Rollback(); err != nil {
				t.Errorf("rollback: %v", err)
			}
		}

		if ids.begin == "" {
			t.Errorf("Expected id to be != ''")
		}

		if ids.begin != ids.end {
			t.Errorf("Expected equals ids, got '%s = %s'", ids.begin, ids.end)
		}
	}
}

func TestErrorHandling(t *testing.T) {
	// As test driver does not implement .Query and .Exec (driver.ErrSkip)
	// we can't test this feature with it
	if *driverFlag == "test" {
		t.SkipNow()
	}

	q := queries[*driverFlag]
	tests := []struct {
		op      string
		query   string
		args    []interface{}
		isValid bool
	}{
		{"exec", q.insert, []interface{}{"a", "b"}, true},
		{"exec", "invalid.exec", nil, false},
		{"query", q.selectall, nil, true},
		{"query", "invalid.query", nil, false},
	}

	for _, test := range tests {
		assert := func(err error) {
			if !test.isValid && err == nil {
				t.Errorf("[%s] expected error, got nil", test.query)
			}
			if test.isValid && err != nil {
				t.Errorf("[%s] unexpected error, got %v", test.query, err)
			}
		}

		fn := func(q string, a ...interface{}) func(error) {
			return assert
		}

		db := openDBWithHooks(t, &Hooks{Query: fn, Exec: fn})
		var err error
		switch test.op {
		case "exec":
			_, err = db.Exec(test.query, test.args...)
		case "query":
			_, err = db.Query(test.query, test.args...)
		}

		assert(err)
	}
}
<commit_msg>Make mysql pass the tests<commit_after>package sqlhooks

import (
	"database/sql"
	"flag"
	"fmt"
	"sort"
	"testing"
	"time"
)

var (
	driverFlag = flag.String("driver", "test", "SQL Driver")
	dsnFlag    = flag.String("dsn", "db", "DSN")
)

type ops struct {
	wipe        string
	create      string
	insert      string
	selectwhere string
	selectall   string
}

var queries = make(map[string]ops)

func openDBWithHooks(t *testing.T, hooks *Hooks, dsnArgs ...string) *sql.DB {
	q := queries[*driverFlag]

	dsn := *dsnFlag
	for _, arg := range dsnArgs {
		dsn = dsn + arg
	}

	// First, we connect directly using `test` driver
	if db, err := sql.Open(*driverFlag, dsn); err != nil {
		t.Fatalf("sql.Open: %v", err)
		return nil
	} else {
		if _, err := db.Exec(q.wipe); err != nil {
			t.Fatalf("WIPE: %v", err)
			return nil
		}

		if _, err := db.Exec(q.create); err != nil {
			t.Fatalf("CREATE: %v", err)
			return nil
		}
		if err := db.Close(); err != nil {
			t.Fatalf("db.Close: %v", err)
		}
	}

	// Now, return a db handler using hooked driver
	driver := NewDriver(*driverFlag, hooks)
	driverName := fmt.Sprintf("sqlhooks-%d", time.Now().UnixNano())
	Register(driverName, driver)

	db, err := sql.Open(driverName, dsn)
	if err != nil {
		t.Fatalf("sql.Open: %v", err)
		return nil
	}

	return db
}

func TestHooks(t *testing.T) {
	q := queries[*driverFlag]
	tests := []struct {
		op    string
		query string
		args  []interface{}
	}{
		{"exec", q.insert, []interface{}{"foo", "bar"}},
		{"query", q.selectwhere, []interface{}{"foo", "bar"}},
		{"query", q.selectall, []interface{}{}},
		{"stmt.query", q.selectall, nil},
		{"stmt.exec", q.insert, []interface{}{"x", "y"}},
		{"tx.query", q.selectall, nil},
		{"tx.exec", q.insert, []interface{}{"x", "y"}},
	}

	for _, test := range tests {
		done := false
		assert := func(query string, args ...interface{}) func(error) {
			// Query Assertions
			if query != test.query {
				t.Errorf("query = `%s`, expected `%s`", query, test.query)
			}

			if test.args == nil {
				test.args = []interface{}{}
			}

			// Arguments assertions
			if len(args) != len(test.args) {
				t.Errorf("Expected args: %d, got %d", len(test.args), len(args))
			}
			for i, _ := range test.args {
				if args[i] != test.args[i] {
					t.Errorf("%s: arg[%d] == %#v, got %#v", test.op, i, test.args[i], args[i])
				}
			}

			return func(error) {
				done = true
			}
		}
		db := openDBWithHooks(t, &Hooks{Query: assert, Exec: assert})

		switch test.op {
		case "query":
			if _, err := db.Query(test.query, test.args...); err != nil {
				t.Errorf("query: %v", err)
			}
		case "exec":
			if _, err := db.Exec(test.query, test.args...); err != nil {
				t.Errorf("exec: %v", err)
			}
		case "stmt.query":
			if stmt, err := db.Prepare(test.query); err != nil {
				t.Errorf("prepare: %v", err)
			} else {
				if _, err := stmt.Query(test.args...); err != nil {
					t.Errorf("prepared query: %v", err)
				}
			}
		case "stmt.exec":
			if stmt, err := db.Prepare(test.query); err != nil {
				t.Errorf("prepare: %v", err)
			} else {
				if _, err := stmt.Exec(test.args...); err != nil {
					t.Errorf("prepared exec: %v", err)
				}
			}
		case "tx.query":
			tx, err := db.Begin()
			if err != nil {
				t.Errorf("[%s] begin: %v", test.op, err)
			}
			if rows, err := tx.Query(test.query, test.args...); err != nil {
				t.Errorf("[%s] query: %v", test.op, err)
			} else {
				rows.Close()
			}
			if err := tx.Commit(); err != nil {
				t.Errorf("[%s] commit: %v", test.op, err)
			}
		case "tx.exec":
			tx, err := db.Begin()
			if err != nil {
				t.Errorf("[%s] begin: %v", test.op, err)
			}
			if _, err := tx.Exec(test.query, test.args...); err != nil {
				t.Errorf("[%s] exec: %v", test.op, err)
			}
			if err := tx.Commit(); err != nil {
				t.Errorf("[%s] commit: %v", test.op, err)
			}
		}

		if done == false {
			t.Errorf("Expected %s cancelation to be completed", test.op)
		}

		db.Close()
	}
}

func TestEmptyHooks(t *testing.T) {
	q := queries[*driverFlag]
	db := openDBWithHooks(t, &Hooks{})

	if _, err := db.Exec(q.insert, "foo", "bar"); err != nil {
		t.Fatalf("Exec: %v\n", err)
	}

	if _, err := db.Query(q.selectall); err != nil {
		t.Fatalf("Query: %v\n", err)
	}
}

func TestCreateInsertAndSelect(t *testing.T) {
	q := queries[*driverFlag]
	db := openDBWithHooks(t, &Hooks{})

	db.Exec(q.insert, "a", "1")
	db.Exec(q.insert, "b", "2")
	db.Exec(q.insert, "c", "3")

	rows, _ := db.Query(q.selectall)
	var fs []string
	for rows.Next() {
		var f1 string
		var f2 string
		rows.Scan(&f1, &f2)
		fs = append(fs, f1)
	}
	sort.Strings(fs)
	if len(fs) != 3 {
		t.Fatalf("Expected 3 rows, got: %d", len(fs))
	}

	for i, e := range []string{"a", "b", "c"}[:len(fs)] {
		f := fs[i]
		if f != e {
			t.Errorf("f1 = `%s`, expected: `%s`", f, e)
		}
	}
}

func TestTXs(t *testing.T) {
	for _, op := range []string{"commit", "rollback"} {
		ids := struct {
			begin string
			end   string
		}{}

		db := openDBWithHooks(t, &Hooks{
			Begin: func(id string) {
				ids.begin = id
			},
			Commit: func(id string) {
				ids.end = id
			},
			Rollback: func(id string) {
				ids.end = id
			},
		})

		tx, err := db.Begin()
		if err != nil {
			t.Errorf("begin: %v", err)
			continue
		}

		switch op {
		case "commit":
			if err := tx.Commit(); err != nil {
				t.Errorf("commit: %v", err)
			}
		case "rollback":
			if err := tx.Rollback(); err != nil {
				t.Errorf("rollback: %v", err)
			}
		}

		if ids.begin == "" {
			t.Errorf("Expected id to be != ''")
		}

		if ids.begin != ids.end {
			t.Errorf("Expected equals ids, got '%s = %s'", ids.begin, ids.end)
		}
	}
}

func TestErrorHandling(t *testing.T) {
	var dsn string

	switch *driverFlag {
	case "test":
		// As test driver does not implement .Query and .Exec (driver.ErrSkip)
		// we can't test this feature with it
		t.SkipNow()
	case "mysql":
		dsn = "?interpolateParams=true"
	}

	q := queries[*driverFlag]
	tests := []struct {
		op      string
		query   string
		args    []interface{}
		isValid bool
	}{
		{"exec", q.insert, []interface{}{"a", "b"}, true},
		{"exec", "invalid.exec", nil, false},
		{"query", q.selectall, nil, true},
		{"query", "invalid.query", nil, false},
	}

	for _, test := range tests {
		assert := func(err error) {
			if !test.isValid && err == nil {
				t.Errorf("[%s] expected error, got nil", test.query)
			}
			if test.isValid && err != nil {
				t.Errorf("[%s] unexpected error, got %v", test.query, err)
			}
		}

		fn := func(q string, a ...interface{}) func(error) {
			return assert
		}

		db := openDBWithHooks(t, &Hooks{Query: fn, Exec: fn}, dsn)
		var err error
		switch test.op {
		case "exec":
			_, err = db.Exec(test.query, test.args...)
		case "query":
			_, err = db.Query(test.query, test.args...)
		}

		assert(err)
	}
}
<|endoftext|>


<commit_before>// main.go
package main

import (
	"flag"
	"fmt"
	"log"
	"os/exec"
	"regexp"
	"strconv"
	"strings"
	"time"
)

const (
	SLEEP_TIME          = 3 * time.Second
	KEYBOARD_BUFER_SIZE = 10000
)

// Return map from key numbers to key names like "F1", "Tab", "d"
func GetKeymap() map[uint8]string {
	return GetKeymapFromOutput(GetKeymapOutput())
}

// Return output of utility that prints system keymap
func GetKeymapOutput() []byte {
	cmd := exec.Command("xmodmap", "-pke")
	out, err := cmd.Output()
	if err != nil {
		log.Fatal(err)
	}
	return out
}

// Return map with keymap from text
func GetKeymapFromOutput(buf []byte) map[uint8]string {
	const KEY_NUM_STRING_RE = "\\d+[ ]*=[ ]*\\S+"
	re := regexp.MustCompile(KEY_NUM_STRING_RE)
	resByte := re.FindAll(buf, -1)
	keyMap := make(map[uint8]string)
	for _, line := range resByte {
		lineSpitted := strings.Split(string(line), " ")
		if key, err := strconv.Atoi(lineSpitted[0]); err == nil {
			keyMap[uint8(key)] = lineSpitted[2]
		}
	}
	return keyMap
}

// Extract pressed keys from bufer buf
// It returns slice with key numbers in the same order
func GetKeyNumsFromOutput(buf []byte) []uint8 {
	const KEY_NUM_STRING_RE = "press[ ]+(\\d+)"
	re := regexp.MustCompile(KEY_NUM_STRING_RE)
	resByte := re.FindAll(buf, -1)
	keyNums := make([]uint8, len(resByte))
	re = regexp.MustCompile("\\d+")
	for i, line := range resByte {
		numByte := re.Find(line)
		if num, err := strconv.Atoi(string(numByte)); err == nil {
			keyNums[i] = uint8(num)
		} else {
			log.Fatal(err)
		}
	}
	return keyNums
}

type StatForTime struct {
	time int
	keys map[string]int
}

func main() {

	keyboardId := flag.Int("id", -1, "Your keyboard id")
	outputPath := flag.String("o", "", "Path to export file")
	flag.Parse()
	log.Println("keyboardId =", *keyboardId, "outputPath =", *outputPath)
	switch {
	case *keyboardId == -1 && *outputPath == "":
		flag.PrintDefaults()
		return
	case *keyboardId != -1:
		cmd := exec.Command("xinput", "test", strconv.Itoa(*keyboardId))

		stdout, err := cmd.StdoutPipe()
		if err != nil {
			log.Fatal(err)
		}
		if err := cmd.Start(); err != nil {
			log.Fatal(err)
		}

		buf := make([]byte, KEYBOARD_BUFER_SIZE)
		for {
			n, err := stdout.Read(buf)
			if err != nil {
				log.Fatal(err)
			}
			// processing buf here
			fmt.Println(n)
			time.Sleep(SLEEP_TIME)
		}
	case *outputPath != "":
		//exporting here
	}
}
<commit_msg>Added struct StatForTime<commit_after>// main.go
package main

import (
	"database/sql"
	"flag"
	"fmt"
	"log"
	"os/exec"
	"regexp"
	"strconv"
	"strings"
	"time"

	_ "github.com/mattn/go-sqlite3"
)

const (
	SLEEP_TIME          = 3 * time.Second
	KEYBOARD_BUFER_SIZE = 10000
	DATABASE_NAME       = "./gokeystat.db"
	CAPTURE_TIME        = 5 * time.Second // time between capturing keyboard to db
)

type StatForTime struct {
	time int
	keys map[string]int
}

// Return map from key numbers to key names like "F1", "Tab", "d"
func GetKeymap() map[uint8]string {
	return GetKeymapFromOutput(GetKeymapOutput())
}

// Return output of utility that prints system keymap
func GetKeymapOutput() []byte {
	cmd := exec.Command("xmodmap", "-pke")
	out, err := cmd.Output()
	if err != nil {
		log.Fatal(err)
	}
	return out
}

// Return map with keymap from text
func GetKeymapFromOutput(buf []byte) map[uint8]string {
	const KEY_NUM_STRING_RE = "\\d+[ ]*=[ ]*\\S+"
	re := regexp.MustCompile(KEY_NUM_STRING_RE)
	resByte := re.FindAll(buf, -1)
	keyMap := make(map[uint8]string)
	for _, line := range resByte {
		lineSpitted := strings.Split(string(line), " ")
		if key, err := strconv.Atoi(lineSpitted[0]); err == nil {
			keyMap[uint8(key)] = lineSpitted[2]
		}
	}
	return keyMap
}

// Extract pressed keys from bufer buf
// It returns slice with key numbers in the same order
func GetKeyNumsFromOutput(buf []byte) []uint8 {
	const KEY_NUM_STRING_RE = "press[ ]+(\\d+)"
	re := regexp.MustCompile(KEY_NUM_STRING_RE)
	resByte := re.FindAll(buf, -1)
	keyNums := make([]uint8, len(resByte))
	re = regexp.MustCompile("\\d+")
	for i, line := range resByte {
		numByte := re.Find(line)
		if num, err := strconv.Atoi(string(numByte)); err == nil {
			keyNums[i] = uint8(num)
		} else {
			log.Fatal(err)
		}
	}
	return keyNums
}

func InitDb(db *sql.DB, keyMap map[uint8]string) {
	keyNums := make([]int, 0, len(keyMap))
	for keyNum := range keyMap {
		keyNums = append(keyNums, int(keyNum))
	}

	sqlInit := `CREATE TABLE IF NOT EXISTS keylog (
        time INTEGER primary key`

	for keyNum := range keyNums {
		sqlInit += ",\n" + "KEY" + strconv.Itoa(keyNum) + " INTEGER"
	}
	sqlInit += "\n);"
	_, err := db.Exec(sqlInit)
	if err != nil {
		log.Fatalf("%q: %s\n", err, sqlInit)
	}

	// Inserting keymap to table
	sqlInit = `CREATE TABLE IF NOT EXISTS keymap (
        num INTEGER primary key,
		value STRING
	);`

	_, err = db.Exec(sqlInit)
	if err != nil {
		log.Fatalf("%q: %s\n", err, sqlInit)
	}

	tx, err := db.Begin()
	if err != nil {
		log.Fatal(err)
	}
	stmt, err := tx.Prepare("insert into keymap(num, value) values(?, ?)")
	if err != nil {
		log.Fatal(err)
	}
	defer stmt.Close()

	for keyNum, keyName := range keyMap {
		_, err = stmt.Exec(keyNum, keyName)
		if err != nil {
			log.Fatal(err)
		}
	}
	tx.Commit()
}

func main() {

	keyboardId := flag.Int("id", -1, "Your keyboard id")
	outputPath := flag.String("o", "", "Path to export file")
	flag.Parse()
	log.Println("keyboardId =", *keyboardId, "outputPath =", *outputPath)
	switch {
	case *keyboardId == -1 && *outputPath == "":
		flag.PrintDefaults()
		return
	case *keyboardId != -1:
		// Opening database
		db, err := sql.Open("sqlite3", DATABASE_NAME)
		if err != nil {
			log.Fatal(err)
		}
		defer db.Close()
		keyMap := GetKeymap()

		InitDb(db, keyMap)
		cmd := exec.Command("xinput", "test", strconv.Itoa(*keyboardId))

		stdout, err := cmd.StdoutPipe()
		if err != nil {
			log.Fatal(err)
		}
		if err := cmd.Start(); err != nil {
			log.Fatal(err)
		}

		buf := make([]byte, KEYBOARD_BUFER_SIZE)
		for {
			n, err := stdout.Read(buf)
			if err != nil {
				log.Fatal(err)
			}
			// processing buf here
			fmt.Println(n)
			time.Sleep(SLEEP_TIME)
		}
	case *outputPath != "":
		//exporting here
	}
}
<|endoftext|>


<commit_before>package main

import (
	"encoding/json"
	"flag"
	"fmt"
	"net/http"
	"time"
)

type interceptingWriter struct {
	code int
	http.ResponseWriter
}

func (iw *interceptingWriter) WriteHeader(code int) {
	iw.code = code
	iw.ResponseWriter.WriteHeader(code)
}

// Log is the structure for logging
type Log struct {
	Time     time.Time `json:"time"`
	IP       string    `json:"ip"`
	Method   string    `json:"method"`
	Status   int       `json:"status"`
	Duration string    `json:"duration"`
	Path     string    `json:"path"`
	Referrer string    `json:"referrer"`
}

// Logger is a logging middleware. Path, request time and Method are recorded
func Logger(inner http.Handler) http.Handler {
	return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		start := time.Now()
		iw := interceptingWriter{200, w}

		inner.ServeHTTP(&iw, r)

		d := fmt.Sprintf("%s", time.Since(start))
		l := Log{
			Time:     time.Now(),
			IP:       r.Header.Get("X-Forwarded-For"),
			Method:   r.Method,
			Status:   iw.code,
			Duration: d,
			Path:     r.RequestURI,
			Referrer: r.Referer(),
		}

		b, _ := json.Marshal(l)
		fmt.Println(string(b))
	})
}

// Cache is a caching middleware
func Cache(inner http.Handler) http.Handler {
	return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		w.Header().Add("Cache-Control", "public")
		w.Header().Add("Cache-Control", "maxage=86400") // One day
		inner.ServeHTTP(w, r)
	})
}

func main() {
	var (
		dir = flag.String("path", "public", "Path to static site")
	)

	fs := http.FileServer(http.Dir(*dir))
	fs = Logger(fs)
	http.Handle("/", fs)
	http.ListenAndServe(":3000", nil)
}
<commit_msg>actually use the caching middleware<commit_after>package main

import (
	"encoding/json"
	"flag"
	"fmt"
	"net/http"
	"strings"
	"time"
)

type interceptingWriter struct {
	code int
	http.ResponseWriter
}

func (iw *interceptingWriter) WriteHeader(code int) {
	iw.code = code
	iw.ResponseWriter.WriteHeader(code)
}

// Log is the structure for logging
type Log struct {
	Time     time.Time `json:"time"`
	IP       string    `json:"ip"`
	Method   string    `json:"method"`
	Status   int       `json:"status"`
	Duration string    `json:"duration"`
	Path     string    `json:"path"`
	Referrer string    `json:"referrer"`
}

// Logger is a logging middleware. Path, request time and Method are recorded
func Logger(inner http.Handler) http.Handler {
	return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		start := time.Now()
		iw := interceptingWriter{200, w}

		inner.ServeHTTP(&iw, r)

		d := fmt.Sprintf("%s", time.Since(start))
		l := Log{
			Time:     time.Now(),
			IP:       r.Header.Get("X-Forwarded-For"),
			Method:   r.Method,
			Status:   iw.code,
			Duration: d,
			Path:     r.RequestURI,
			Referrer: r.Referer(),
		}

		b, _ := json.Marshal(l)
		fmt.Println(string(b))
	})
}

// Cache is a caching middleware
func Cache(inner http.Handler) http.Handler {
	return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		w.Header().Add("Cache-Control", "public")
		if strings.Compare(w.Header().Get("Content-Type"), "text/html") != 0 {
			w.Header().Add("Cache-Control", "maxage=604800") // 1 Week
		} else {
			w.Header().Add("Cache-Control", "maxage=86400") // 1 Day
		}
		inner.ServeHTTP(w, r)
	})
}

func main() {
	var (
		dir = flag.String("path", "public", "Path to static site")
	)

	fs := http.FileServer(http.Dir(*dir))
	fs = Logger(fs)
	fs = Cache(fs)
	http.Handle("/", fs)
	http.ListenAndServe(":3000", nil)
}
<|endoftext|>