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

package eth

import (
	"math/big"
	"math/rand"
	"sync"

	"github.com/ethereum/go-ethereum/core"
	"github.com/ethereum/go-ethereum/core/types"
	"github.com/ethereum/go-ethereum/event"
	"github.com/ethereum/go-ethereum/logger"
	"github.com/ethereum/go-ethereum/logger/glog"
)

const gpoProcessPastBlocks = 100

type blockPriceInfo struct {
	baseGasPrice *big.Int
}

type GasPriceOracle struct {
	eth                           *Ethereum
	chain                         *core.ChainManager
	pool                          *core.TxPool
	events                        event.Subscription
	blocks                        map[uint64]*blockPriceInfo
	firstProcessed, lastProcessed uint64
	lastBaseMutex                 sync.Mutex
	lastBase                      *big.Int
}

func NewGasPriceOracle(eth *Ethereum) (self *GasPriceOracle) {
	self = &GasPriceOracle{}
	self.blocks = make(map[uint64]*blockPriceInfo)
	self.eth = eth
	self.chain = eth.chainManager
	self.pool = eth.txPool
	self.events = eth.EventMux().Subscribe(
		core.ChainEvent{},
		core.ChainSplitEvent{},
		core.TxPreEvent{},
		core.TxPostEvent{},
	)
	self.processPastBlocks()
	go self.listenLoop()
	return
}

func (self *GasPriceOracle) processPastBlocks() {
	last := int64(-1)
	cblock := self.chain.CurrentBlock()
	if cblock != nil {
		last = int64(cblock.NumberU64())
	}
	first := int64(0)
	if last > gpoProcessPastBlocks {
		first = last - gpoProcessPastBlocks
	}
	self.firstProcessed = uint64(first)
	for i := first; i <= last; i++ {
		block := self.chain.GetBlockByNumber(uint64(i))
		if block != nil {
			self.processBlock(block)
		}
	}

}

func (self *GasPriceOracle) listenLoop() {
	for {
		ev, isopen := <-self.events.Chan()
		if !isopen {
			break
		}
		switch ev := ev.(type) {
		case core.ChainEvent:
			self.processBlock(ev.Block)
		case core.ChainSplitEvent:
			self.processBlock(ev.Block)
		case core.TxPreEvent:
		case core.TxPostEvent:
		}
	}
	self.events.Unsubscribe()
}

func (self *GasPriceOracle) processBlock(block *types.Block) {
	i := block.NumberU64()
	if i > self.lastProcessed {
		self.lastProcessed = i
	}

	lastBase := self.eth.GpoMinGasPrice
	bpl := self.blocks[i-1]
	if bpl != nil {
		lastBase = bpl.baseGasPrice
	}
	if lastBase == nil {
		return
	}

	var corr int
	lp := self.lowestPrice(block)
	if lp == nil {
		return
	}

	if lastBase.Cmp(lp) < 0 {
		corr = self.eth.GpobaseStepUp
	} else {
		corr = -self.eth.GpobaseStepDown
	}

	crand := int64(corr * (900 + rand.Intn(201)))
	newBase := new(big.Int).Mul(lastBase, big.NewInt(1000000+crand))
	newBase.Div(newBase, big.NewInt(1000000))

	bpi := self.blocks[i]
	if bpi == nil {
		bpi = &blockPriceInfo{}
		self.blocks[i] = bpi
	}
	bpi.baseGasPrice = newBase
	self.lastBaseMutex.Lock()
	self.lastBase = newBase
	self.lastBaseMutex.Unlock()

	glog.V(logger.Detail).Infof("Processed block #%v, base price is %v\n", block.NumberU64(), newBase.Int64())
}

// returns the lowers possible price with which a tx was or could have been included
func (self *GasPriceOracle) lowestPrice(block *types.Block) *big.Int {
	gasUsed := new(big.Int)

	receipts := self.eth.BlockProcessor().GetBlockReceipts(block.Hash())
	if len(receipts) > 0 {
		if cgu := receipts[len(receipts)-1].CumulativeGasUsed; cgu != nil {
			gasUsed = receipts[len(receipts)-1].CumulativeGasUsed
		}
	}

	if new(big.Int).Mul(gasUsed, big.NewInt(100)).Cmp(new(big.Int).Mul(block.GasLimit(),
		big.NewInt(int64(self.eth.GpoFullBlockRatio)))) < 0 {
		// block is not full, could have posted a tx with MinGasPrice
		return self.eth.GpoMinGasPrice
	}

	txs := block.Transactions()
	if len(txs) == 0 {
		return self.eth.GpoMinGasPrice
	}
	// block is full, find smallest gasPrice
	minPrice := txs[0].GasPrice()
	for i := 1; i < len(txs); i++ {
		price := txs[i].GasPrice()
		if price.Cmp(minPrice) < 0 {
			minPrice = price
		}
	}
	return minPrice
}

func (self *GasPriceOracle) SuggestPrice() *big.Int {
	self.lastBaseMutex.Lock()
	base := self.lastBase
	self.lastBaseMutex.Unlock()

	if base == nil {
		base = self.eth.GpoMinGasPrice
	}
	if base == nil {
		return big.NewInt(10000000000000) // apparently MinGasPrice is not initialized during some tests
	}

	baseCorr := new(big.Int).Mul(base, big.NewInt(int64(self.eth.GpobaseCorrectionFactor)))
	baseCorr.Div(baseCorr, big.NewInt(100))

	if baseCorr.Cmp(self.eth.GpoMinGasPrice) < 0 {
		return self.eth.GpoMinGasPrice
	}

	if baseCorr.Cmp(self.eth.GpoMaxGasPrice) > 0 {
		return self.eth.GpoMaxGasPrice
	}

	return baseCorr
}
<commit_msg>GPO update<commit_after>// Copyright 2015 The go-ethereum Authors
// This file is part of the go-ethereum library.
//
// The go-ethereum library is free software: you can redistribute it and/or modify
// it under the terms of the GNU Lesser General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// The go-ethereum library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public License
// along with the go-ethereum library. If not, see <http://www.gnu.org/licenses/>.

package eth

import (
	"math/big"
	"math/rand"
	"sync"

	"github.com/ethereum/go-ethereum/core"
	"github.com/ethereum/go-ethereum/core/types"
	"github.com/ethereum/go-ethereum/event"
	"github.com/ethereum/go-ethereum/logger"
	"github.com/ethereum/go-ethereum/logger/glog"
)

const gpoProcessPastBlocks = 100

type blockPriceInfo struct {
	baseGasPrice *big.Int
}

type GasPriceOracle struct {
	eth                           *Ethereum
	chain                         *core.ChainManager
	events                        event.Subscription
	blocks                        map[uint64]*blockPriceInfo
	firstProcessed, lastProcessed uint64
	lastBaseMutex                 sync.Mutex
	lastBase, minBase             *big.Int
}

func NewGasPriceOracle(eth *Ethereum) (self *GasPriceOracle) {
	self = &GasPriceOracle{}
	self.blocks = make(map[uint64]*blockPriceInfo)
	self.eth = eth
	self.chain = eth.chainManager
	self.events = eth.EventMux().Subscribe(
		core.ChainEvent{},
		core.ChainSplitEvent{},
	)

	minbase := new(big.Int).Mul(self.eth.GpoMinGasPrice, big.NewInt(100))
	minbase = minbase.Div(minbase, big.NewInt(int64(self.eth.GpobaseCorrectionFactor)))
	self.minBase = minbase

	self.processPastBlocks()
	go self.listenLoop()
	return
}

func (self *GasPriceOracle) processPastBlocks() {
	last := int64(-1)
	cblock := self.chain.CurrentBlock()
	if cblock != nil {
		last = int64(cblock.NumberU64())
	}
	first := int64(0)
	if last > gpoProcessPastBlocks {
		first = last - gpoProcessPastBlocks
	}
	self.firstProcessed = uint64(first)
	for i := first; i <= last; i++ {
		block := self.chain.GetBlockByNumber(uint64(i))
		if block != nil {
			self.processBlock(block)
		}
	}

}

func (self *GasPriceOracle) listenLoop() {
	for {
		ev, isopen := <-self.events.Chan()
		if !isopen {
			break
		}
		switch ev := ev.(type) {
		case core.ChainEvent:
			self.processBlock(ev.Block)
		case core.ChainSplitEvent:
			self.processBlock(ev.Block)
		}
	}
	self.events.Unsubscribe()
}

func (self *GasPriceOracle) processBlock(block *types.Block) {
	i := block.NumberU64()
	if i > self.lastProcessed {
		self.lastProcessed = i
	}

	lastBase := self.eth.GpoMinGasPrice
	bpl := self.blocks[i-1]
	if bpl != nil {
		lastBase = bpl.baseGasPrice
	}
	if lastBase == nil {
		return
	}

	var corr int
	lp := self.lowestPrice(block)
	if lp == nil {
		return
	}

	if lastBase.Cmp(lp) < 0 {
		corr = self.eth.GpobaseStepUp
	} else {
		corr = -self.eth.GpobaseStepDown
	}

	crand := int64(corr * (900 + rand.Intn(201)))
	newBase := new(big.Int).Mul(lastBase, big.NewInt(1000000+crand))
	newBase.Div(newBase, big.NewInt(1000000))

	if newBase.Cmp(self.minBase) < 0 {
		newBase = self.minBase
	}

	bpi := self.blocks[i]
	if bpi == nil {
		bpi = &blockPriceInfo{}
		self.blocks[i] = bpi
	}
	bpi.baseGasPrice = newBase
	self.lastBaseMutex.Lock()
	self.lastBase = newBase
	self.lastBaseMutex.Unlock()

	glog.V(logger.Detail).Infof("Processed block #%v, base price is %v\n", block.NumberU64(), newBase.Int64())
}

// returns the lowers possible price with which a tx was or could have been included
func (self *GasPriceOracle) lowestPrice(block *types.Block) *big.Int {
	gasUsed := big.NewInt(0)

	receipts := self.eth.BlockProcessor().GetBlockReceipts(block.Hash())
	if len(receipts) > 0 {
		if cgu := receipts[len(receipts)-1].CumulativeGasUsed; cgu != nil {
			gasUsed = receipts[len(receipts)-1].CumulativeGasUsed
		}
	}

	if new(big.Int).Mul(gasUsed, big.NewInt(100)).Cmp(new(big.Int).Mul(block.GasLimit(),
		big.NewInt(int64(self.eth.GpoFullBlockRatio)))) < 0 {
		// block is not full, could have posted a tx with MinGasPrice
		return big.NewInt(0)
	}

	txs := block.Transactions()
	if len(txs) == 0 {
		return big.NewInt(0)
	}
	// block is full, find smallest gasPrice
	minPrice := txs[0].GasPrice()
	for i := 1; i < len(txs); i++ {
		price := txs[i].GasPrice()
		if price.Cmp(minPrice) < 0 {
			minPrice = price
		}
	}
	return minPrice
}

func (self *GasPriceOracle) SuggestPrice() *big.Int {
	self.lastBaseMutex.Lock()
	base := self.lastBase
	self.lastBaseMutex.Unlock()

	if base == nil {
		base = self.eth.GpoMinGasPrice
	}
	if base == nil {
		return big.NewInt(10000000000000) // apparently MinGasPrice is not initialized during some tests
	}

	baseCorr := new(big.Int).Mul(base, big.NewInt(int64(self.eth.GpobaseCorrectionFactor)))
	baseCorr.Div(baseCorr, big.NewInt(100))

	if baseCorr.Cmp(self.eth.GpoMinGasPrice) < 0 {
		return self.eth.GpoMinGasPrice
	}

	if baseCorr.Cmp(self.eth.GpoMaxGasPrice) > 0 {
		return self.eth.GpoMaxGasPrice
	}

	return baseCorr
}
<|endoftext|>


<commit_before>package ethpub

import (
	"encoding/hex"
	"encoding/json"
	"github.com/ethereum/eth-go/ethchain"
	"github.com/ethereum/eth-go/ethutil"
	_ "log"
	"strings"
)

// Block interface exposed to QML
type PBlock struct {
	ref          *ethchain.Block
	Number       int    `json:"number"`
	Hash         string `json:"hash"`
	Transactions string `json:"transactions"`
	Time         int64  `json:"time"`
}

// Creates a new QML Block from a chain block
func NewPBlock(block *ethchain.Block) *PBlock {
	if block == nil {
		return nil
	}

	var ptxs []PTx
	for _, tx := range block.Transactions() {
		ptxs = append(ptxs, *NewPTx(tx))
	}

	txJson, err := json.Marshal(ptxs)
	if err != nil {
		return nil
	}

	return &PBlock{ref: block, Number: int(block.Number.Uint64()), Hash: ethutil.Hex(block.Hash()), Transactions: string(txJson), Time: block.Time}
}

func (self *PBlock) ToString() string {
	if self.ref != nil {
		return self.ref.String()
	}

	return ""
}

func (self *PBlock) GetTransaction(hash string) *PTx {
	tx := self.ref.GetTransaction(ethutil.FromHex(hash))
	if tx == nil {
		return nil
	}

	return NewPTx(tx)
}

type PTx struct {
	ref *ethchain.Transaction

	Value    string `json:"value"`
	Gas      string `json:"gas"`
	GasPrice string `json:"gasPrice"`
	Hash     string `json:"hash"`
	Address  string `json:"address"`
	Sender   string `json:"sender"`
	Data     string `json:"data"`
	Contract bool   `json:"isContract"`
}

func NewPTx(tx *ethchain.Transaction) *PTx {
	hash := hex.EncodeToString(tx.Hash())
	receiver := hex.EncodeToString(tx.Recipient)
	sender := hex.EncodeToString(tx.Sender())
	data := strings.Join(ethchain.Disassemble(tx.Data), "\n")

	isContract := len(tx.Data) > 0

	return &PTx{ref: tx, Hash: hash, Value: ethutil.CurrencyToString(tx.Value), Address: receiver, Contract: isContract, Gas: tx.Gas.String(), GasPrice: tx.GasPrice.String(), Data: data, Sender: sender}
}

func (self *PTx) ToString() string {
	return self.ref.String()
}

type PKey struct {
	Address    string `json:"address"`
	PrivateKey string `json:"privateKey"`
	PublicKey  string `json:"publicKey"`
}

func NewPKey(key *ethutil.KeyPair) *PKey {
	return &PKey{ethutil.Hex(key.Address()), ethutil.Hex(key.PrivateKey), ethutil.Hex(key.PublicKey)}
}

type PReceipt struct {
	CreatedContract bool   `json:"createdContract"`
	Address         string `json:"address"`
	Hash            string `json:"hash"`
	Sender          string `json:"sender"`
}

func NewPReciept(contractCreation bool, creationAddress, hash, address []byte) *PReceipt {
	return &PReceipt{
		contractCreation,
		ethutil.Hex(creationAddress),
		ethutil.Hex(hash),
		ethutil.Hex(address),
	}
}

type PStateObject struct {
	object *ethchain.StateObject
}

func NewPStateObject(object *ethchain.StateObject) *PStateObject {
	return &PStateObject{object: object}
}

func (c *PStateObject) GetStorage(address string) string {
	// Because somehow, even if you return nil to QML it
	// still has some magical object so we can't rely on
	// undefined or null at the QML side
	if c.object != nil {
		val := c.object.GetMem(ethutil.Big("0x" + address))

		return val.BigInt().String()
	}

	return ""
}

func (c *PStateObject) Value() string {
	if c.object != nil {
		return c.object.Amount.String()
	}

	return ""
}

func (c *PStateObject) Address() string {
	if c.object != nil {
		return ethutil.Hex(c.object.Address())
	}

	return ""
}

func (c *PStateObject) Nonce() int {
	if c.object != nil {
		return int(c.object.Nonce)
	}

	return 0
}

func (c *PStateObject) Root() string {
	if c.object != nil {
		return ethutil.Hex(ethutil.NewValue(c.object.State().Root()).Bytes())
	}

	return "<err>"
}

func (c *PStateObject) IsContract() bool {
	if c.object != nil {
		return len(c.object.Script()) > 0
	}

	return false
}

func (c *PStateObject) Script() string {
	if c.object != nil {
		return strings.Join(ethchain.Disassemble(c.object.Script()), " ")
	}

	return ""
}

type PStorageState struct {
	StateAddress string
	Address      string
	Value        string
}

func NewPStorageState(storageObject *ethchain.StorageState) *PStorageState {
	return &PStorageState{ethutil.Hex(storageObject.StateAddress), ethutil.Hex(storageObject.Address), storageObject.Value.String()}
}
<commit_msg>Add contract addr if it's a contract creation tx<commit_after>package ethpub

import (
	"encoding/hex"
	"encoding/json"
	"github.com/ethereum/eth-go/ethchain"
	"github.com/ethereum/eth-go/ethutil"
	_ "log"
	"strings"
)

// Block interface exposed to QML
type PBlock struct {
	ref          *ethchain.Block
	Number       int    `json:"number"`
	Hash         string `json:"hash"`
	Transactions string `json:"transactions"`
	Time         int64  `json:"time"`
}

// Creates a new QML Block from a chain block
func NewPBlock(block *ethchain.Block) *PBlock {
	if block == nil {
		return nil
	}

	var ptxs []PTx
	for _, tx := range block.Transactions() {
		ptxs = append(ptxs, *NewPTx(tx))
	}

	txJson, err := json.Marshal(ptxs)
	if err != nil {
		return nil
	}

	return &PBlock{ref: block, Number: int(block.Number.Uint64()), Hash: ethutil.Hex(block.Hash()), Transactions: string(txJson), Time: block.Time}
}

func (self *PBlock) ToString() string {
	if self.ref != nil {
		return self.ref.String()
	}

	return ""
}

func (self *PBlock) GetTransaction(hash string) *PTx {
	tx := self.ref.GetTransaction(ethutil.FromHex(hash))
	if tx == nil {
		return nil
	}

	return NewPTx(tx)
}

type PTx struct {
	ref *ethchain.Transaction

	Value    string `json:"value"`
	Gas      string `json:"gas"`
	GasPrice string `json:"gasPrice"`
	Hash     string `json:"hash"`
	Address  string `json:"address"`
	Sender   string `json:"sender"`
	Data     string `json:"data"`
	Contract bool   `json:"isContract"`
}

func NewPTx(tx *ethchain.Transaction) *PTx {
	hash := hex.EncodeToString(tx.Hash())
	receiver := hex.EncodeToString(tx.Recipient)

	if receiver == "" {
		receiver = hex.EncodeToString(tx.CreationAddress())
	}
	sender := hex.EncodeToString(tx.Sender())
	data := strings.Join(ethchain.Disassemble(tx.Data), "\n")

	isContract := len(tx.Data) > 0

	return &PTx{ref: tx, Hash: hash, Value: ethutil.CurrencyToString(tx.Value), Address: receiver, Contract: isContract, Gas: tx.Gas.String(), GasPrice: tx.GasPrice.String(), Data: data, Sender: sender}
}

func (self *PTx) ToString() string {
	return self.ref.String()
}

type PKey struct {
	Address    string `json:"address"`
	PrivateKey string `json:"privateKey"`
	PublicKey  string `json:"publicKey"`
}

func NewPKey(key *ethutil.KeyPair) *PKey {
	return &PKey{ethutil.Hex(key.Address()), ethutil.Hex(key.PrivateKey), ethutil.Hex(key.PublicKey)}
}

type PReceipt struct {
	CreatedContract bool   `json:"createdContract"`
	Address         string `json:"address"`
	Hash            string `json:"hash"`
	Sender          string `json:"sender"`
}

func NewPReciept(contractCreation bool, creationAddress, hash, address []byte) *PReceipt {
	return &PReceipt{
		contractCreation,
		ethutil.Hex(creationAddress),
		ethutil.Hex(hash),
		ethutil.Hex(address),
	}
}

type PStateObject struct {
	object *ethchain.StateObject
}

func NewPStateObject(object *ethchain.StateObject) *PStateObject {
	return &PStateObject{object: object}
}

func (c *PStateObject) GetStorage(address string) string {
	// Because somehow, even if you return nil to QML it
	// still has some magical object so we can't rely on
	// undefined or null at the QML side
	if c.object != nil {
		val := c.object.GetMem(ethutil.Big("0x" + address))

		return val.BigInt().String()
	}

	return ""
}

func (c *PStateObject) Value() string {
	if c.object != nil {
		return c.object.Amount.String()
	}

	return ""
}

func (c *PStateObject) Address() string {
	if c.object != nil {
		return ethutil.Hex(c.object.Address())
	}

	return ""
}

func (c *PStateObject) Nonce() int {
	if c.object != nil {
		return int(c.object.Nonce)
	}

	return 0
}

func (c *PStateObject) Root() string {
	if c.object != nil {
		return ethutil.Hex(ethutil.NewValue(c.object.State().Root()).Bytes())
	}

	return "<err>"
}

func (c *PStateObject) IsContract() bool {
	if c.object != nil {
		return len(c.object.Script()) > 0
	}

	return false
}

func (c *PStateObject) Script() string {
	if c.object != nil {
		return strings.Join(ethchain.Disassemble(c.object.Script()), " ")
	}

	return ""
}

type PStorageState struct {
	StateAddress string
	Address      string
	Value        string
}

func NewPStorageState(storageObject *ethchain.StorageState) *PStorageState {
	return &PStorageState{ethutil.Hex(storageObject.StateAddress), ethutil.Hex(storageObject.Address), storageObject.Value.String()}
}
<|endoftext|>


<commit_before>package main

import (
	"fmt"
	"log"
	"net/http"
	"net/url"
	"os"

	line "github.com/dongri/line-bot-client"
)

var botClient *line.Client

func main() {
	channelID := os.Getenv("LINE_CHANNEL_ID")
	channelSecret := os.Getenv("LINE_CHANNEL_SECRET")
	mid := os.Getenv("LINE_MID")
	proxyURL := getProxyURL() // can set nil if not need

	botClient = line.NewClient(line.EndPoint, channelID, channelSecret, mid, proxyURL)

	http.HandleFunc("/callback", callbackHandler)
	port := os.Getenv("PORT")
	addr := fmt.Sprintf(":%s", port)
	http.ListenAndServe(addr, nil)
}

func callbackHandler(w http.ResponseWriter, r *http.Request) {
	m, err := botClient.ReceiveMessage(r.Body)
	if err != nil {
		log.Print(err)
	}
	for _, result := range m.Result {
		from := result.Content.From

		// Get User Profile
		fromUser, err := botClient.GetUserProfiles(from)
		if err != nil {
			log.Print(err)
		}
		displayName := fromUser.Contacts[0].DisplayName
		// Send Text
		text := result.Content.Text
		sentResult, err := botClient.SendText([]string{from}, text+"\n\nBy "+displayName)
		if err != nil {
			log.Print(err)
		}
		if len(sentResult.Failed) == 0 {
			fmt.Fprintf(w, "Failed")
			return
		}

		// Send Sticker
		metadata := new(line.ContentMetadata)
		metadata.STKID = "2"
		metadata.STKPKGID = "1"
		metadata.STKVER = "100"
		sentResult, err = botClient.SendSticker([]string{from}, *metadata)
		if err != nil {
			log.Print(err)
		}
		if len(sentResult.Failed) == 0 {
			fmt.Fprintf(w, "Failed")
			return
		}

		// Send Image
		originalContentURL := "https://upload.wikimedia.org/wikipedia/commons/5/5e/Line_logo.png"
		previewImageURL := "http://i.imgur.com/Aaso4sY.png"
		sentResult, err = botClient.SendImage([]string{from}, originalContentURL, previewImageURL)
		if err != nil {
			log.Print(err)
		}
		if len(sentResult.Failed) == 0 {
			fmt.Fprintf(w, "Failed")
			return
		}

		// Send Video ....

	}
	fmt.Fprintf(w, "Success")
}

func getProxyURL() *url.URL {
	proxyURL, err := url.Parse(os.Getenv("PROXY_URL"))
	if err != nil {
		log.Fatal(err)
	}
	return proxyURL
}
<commit_msg>Fix log<commit_after>package main

import (
	"fmt"
	"log"
	"net/http"
	"net/url"
	"os"

	line "github.com/dongri/line-bot-client"
)

var botClient *line.Client

func main() {
	channelID := os.Getenv("LINE_CHANNEL_ID")
	channelSecret := os.Getenv("LINE_CHANNEL_SECRET")
	mid := os.Getenv("LINE_MID")
	proxyURL := getProxyURL() // can set nil if not need

	botClient = line.NewClient(line.EndPoint, channelID, channelSecret, mid, proxyURL)

	http.HandleFunc("/callback", callbackHandler)
	port := os.Getenv("PORT")
	addr := fmt.Sprintf(":%s", port)
	http.ListenAndServe(addr, nil)
}

func callbackHandler(w http.ResponseWriter, r *http.Request) {
	m, err := botClient.ReceiveMessage(r.Body)
	if err != nil {
		log.Print(err)
	}
	for _, result := range m.Result {
		from := result.Content.From

		// Get User Profile
		fromUser, err := botClient.GetUserProfiles(from)
		if err != nil {
			log.Print(err)
		}
		displayName := fromUser.Contacts[0].DisplayName
		// Send Text
		text := result.Content.Text
		sentResult, err := botClient.SendText([]string{from}, text+"\n\nBy "+displayName)
		if err != nil {
			log.Print(err)
		}
		if len(sentResult.Failed) == 0 {
			log.Print("Failed")
			return
		}

		// Send Sticker
		metadata := new(line.ContentMetadata)
		metadata.STKID = "2"
		metadata.STKPKGID = "1"
		metadata.STKVER = "100"
		sentResult, err = botClient.SendSticker([]string{from}, *metadata)
		if err != nil {
			log.Print(err)
		}
		if len(sentResult.Failed) == 0 {
			log.Print("Failed")
			return
		}

		// Send Image
		originalContentURL := "https://upload.wikimedia.org/wikipedia/commons/5/5e/Line_logo.png"
		previewImageURL := "http://i.imgur.com/Aaso4sY.png"
		sentResult, err = botClient.SendImage([]string{from}, originalContentURL, previewImageURL)
		if err != nil {
			log.Print(err)
		}
		if len(sentResult.Failed) == 0 {
			log.Print("Failed")
			return
		}

		// Send Video ....

	}
	log.Print("Success")
}

func getProxyURL() *url.URL {
	proxyURL, err := url.Parse(os.Getenv("PROXY_URL"))
	if err != nil {
		log.Fatal(err)
	}
	return proxyURL
}
<|endoftext|>


<commit_before>package main

import (
	"math/rand"
	"time"

	appm "github.com/wgliang/goappmonitor"
)

// Base or system performance data,such as memeory,gc,network and so on.
func baseOrsystem() {
	for _ = range time.Tick(time.Second * time.Duration(10)) {
		// (commonly used) Meter, used to sum and calculate the rate of change. Use scenarios
		// such as the number of home visits statistics, CG etc..
		pv := int64(rand.Int() % 100)
		appm.Meter("appm.meter", pv)
		appm.Meter("appm.meter.2", pv-50)

		// (commonly used) Gauge, used to preserve the value of the instantaneous value of the
		// type of record. Use scenarios such as statistical queue length, statistics CPU usage,
		// and so on.
		queueSize := int64(rand.Int()%100 - 50)
		appm.Gauge("appm.gauge", queueSize)

		cpuUtil := float64(rand.Int()%10000) / float64(100)
		appm.GaugeFloat64("appm.gauge.float64", cpuUtil)
	}
}

// Custom or business performance data,such as qps,num of function be called, task queue and so on.
func customOrbusiness() {
	for _ = range time.Tick(time.Second) {
		// Histogram, using the exponential decay sampling method, the probability distribution of
		// the statistical object is calculated. Using scenarios such as the probability distribution
		// of the statistics home page to access the delay
		delay := int64(rand.Int31n(100))
		appm.Histogram("appm.histogram", delay)
	}
}

func main() {
	var ch chan int
	go baseOrsystem()
	go customOrbusiness()
	<-ch
}
<commit_msg>fix readme<commit_after>package main

import (
	"math/rand"
	"time"

	appm "github.com/wgliang/goappmonitor"
)

// Base or system performance data,such as memeory,gc,network and so on.
func baseOrsystem() {
	for _ = range time.Tick(time.Second * time.Duration(10)) {
		// (commonly used) Meter, used to sum and calculate the rate of change. Use scenarios
		// such as the number of home visits statistics, CG etc..
		pv := int64(rand.Int31n(100))
		appm.Meter("appm.meter", pv)
		appm.Meter("appm.meter.2", pv-50)

		// (commonly used) Gauge, used to preserve the value of the instantaneous value of the
		// type of record. Use scenarios such as statistical queue length, statistics CPU usage,
		// and so on.
		queueSize := int64(rand.Int31n(100) - 50)
		appm.Gauge("appm.gauge", queueSize)

		cpuUtil := float64(rand.Int31n(10000)) / float64(100)
		appm.GaugeFloat64("appm.gauge.float64", cpuUtil)
	}
}

// Custom or business performance data,such as qps,num of function be called, task queue and so on.
func customOrbusiness() {
	for _ = range time.Tick(time.Second) {
		// Histogram, using the exponential decay sampling method, the probability distribution of
		// the statistical object is calculated. Using scenarios such as the probability distribution
		// of the statistics home page to access the delay
		delay := int64(rand.Int31n(100))
		appm.Histogram("appm.histogram", delay)
	}
}

func main() {
	var ch chan int
	go baseOrsystem()
	go customOrbusiness()
	<-ch
}
<|endoftext|>


<commit_before>package main

import (
	"fmt"
	"github.com/northbright/basicauth"
	"io"
	"net/http"
)

type MyHandler struct{}

var (
	mux = make(map[string]func(http.ResponseWriter, *http.Request))
)

func hello(w http.ResponseWriter, r *http.Request) {
	// Use default argument(default Basic realm string).
	ba := basicauth.New("admin", "admin")
	if ba.IsOK(w, r) {
		io.WriteString(w, "/: you are in.")
	} else {
		io.WriteString(w, "/: 401: unauthorized.")
	}
}

func welcome(w http.ResponseWriter, r *http.Request) {
	// Use customized argument(Basis realm string)
	ba := basicauth.NewWithArgs("john", "123456", basicauth.Arguments{"Yo!"})
	if ba.IsOK(w, r) {
		io.WriteString(w, "/welcome: you're in.")
	} else {
		io.WriteString(w, "/welcome: 401: unauthorized.")
	}
}

func (*MyHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
	url := r.URL.String()
	if h, ok := mux[url]; ok {
		h(w, r)
		return
	}
	io.WriteString(w, "URL can not found: "+r.URL.String())
}

func main() {
	mux["/"] = hello
	mux["/welcome"] = welcome

	server := http.Server{
		Addr:    ":8080",
		Handler: &MyHandler{},
	}

	err := server.ListenAndServe()
	if err != nil {
		fmt.Printf("ListenAndServe: %v", err)
	}

	// Output:
}
<commit_msg>Unexport MyHandler to remove golint warnings.<commit_after>package main

import (
	"fmt"
	"github.com/northbright/basicauth"
	"io"
	"net/http"
)

type myHandler struct{}

var (
	mux = make(map[string]func(http.ResponseWriter, *http.Request))
)

func hello(w http.ResponseWriter, r *http.Request) {
	// Use default argument(default Basic realm string).
	ba := basicauth.New("admin", "admin")
	if ba.IsOK(w, r) {
		io.WriteString(w, "/: you are in.")
	} else {
		io.WriteString(w, "/: 401: unauthorized.")
	}
}

func welcome(w http.ResponseWriter, r *http.Request) {
	// Use customized argument(Basis realm string)
	ba := basicauth.NewWithArgs("john", "123456", basicauth.Arguments{"Yo!"})
	if ba.IsOK(w, r) {
		io.WriteString(w, "/welcome: you're in.")
	} else {
		io.WriteString(w, "/welcome: 401: unauthorized.")
	}
}

func (*myHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
	url := r.URL.String()
	if h, ok := mux[url]; ok {
		h(w, r)
		return
	}
	io.WriteString(w, "URL can not found: "+r.URL.String())
}

func main() {
	mux["/"] = hello
	mux["/welcome"] = welcome

	server := http.Server{
		Addr:    ":8080",
		Handler: &myHandler{},
	}

	err := server.ListenAndServe()
	if err != nil {
		fmt.Printf("ListenAndServe: %v", err)
	}

	// Output:
}
<|endoftext|>


<commit_before>package main

import (
	"fmt"
	"runtime"
	"time"

	"github.com/smartystreets/go-disruptor"
)

const (
	BufferSize = 1024 * 64
	BufferMask = BufferSize - 1
	Iterations = 1000000 * 100
)

var ringBuffer = [BufferSize]int64{}

func main() {
	runtime.GOMAXPROCS(2)

	written, read := disruptor.NewCursor(), disruptor.NewCursor()
	reader := disruptor.NewReader(read, written, written, SampleConsumer{})

	started := time.Now()
	reader.Start()
	// publish(written, read)
	publish(disruptor.NewWriter(written, read, BufferSize))
	reader.Stop()
	finished := time.Now()
	fmt.Println(Iterations, finished.Sub(started))
}

func publish(writer *disruptor.Writer) {
	for sequence := disruptor.InitialSequenceValue; sequence <= Iterations; {
		sequence = writer.Reserve()
		ringBuffer[sequence&BufferMask] = sequence
		writer.Commit(sequence)
	}
}

// func publish(written, read *disruptor.Cursor) {
// 	previous := disruptor.InitialSequenceValue
// 	gate := disruptor.InitialSequenceValue

// 	for previous <= Iterations {
// 		next := previous + 1
// 		wrap := next - BufferSize

// 		for wrap > gate {
// 			gate = read.Sequence
// 		}

// 		ringBuffer[next&BufferMask] = next
// 		written.Sequence = next
// 		previous = next
// 	}
// }

type SampleConsumer struct{}

func (this SampleConsumer) Consume(lower, upper int64) {
	for lower <= upper {
		message := ringBuffer[lower&BufferMask]
		if message != lower {
			fmt.Println("Race condition", message, lower)
			panic("Race condition")
		}
		lower++
	}
}
<commit_msg>3.7ns per operation when not writing to the ring buffer.<commit_after>package main

import (
	"fmt"
	"runtime"
	"time"

	"github.com/smartystreets/go-disruptor"
)

const (
	BufferSize = 1024 * 64
	BufferMask = BufferSize - 1
	Iterations = 1000000 * 100
)

var ringBuffer = [BufferSize]int64{}

func main() {
	runtime.GOMAXPROCS(2)

	written, read := disruptor.NewCursor(), disruptor.NewCursor()
	reader := disruptor.NewReader(read, written, written, SampleConsumer{})

	started := time.Now()
	reader.Start()
	// publish(written, read)
	publish(disruptor.NewWriter(written, read, BufferSize))
	reader.Stop()
	finished := time.Now()
	fmt.Println(Iterations, finished.Sub(started))
}

func publish(writer *disruptor.Writer) {
	for sequence := disruptor.InitialSequenceValue; sequence <= Iterations; {
		sequence = writer.Reserve()
		// ringBuffer[sequence&BufferMask] = sequence
		writer.Commit(sequence)
	}
}

// func publish(written, read *disruptor.Cursor) {
// 	previous := disruptor.InitialSequenceValue
// 	gate := disruptor.InitialSequenceValue

// 	for previous <= Iterations {
// 		next := previous + 1
// 		wrap := next - BufferSize

// 		for wrap > gate {
// 			gate = read.Sequence
// 		}

// 		ringBuffer[next&BufferMask] = next
// 		written.Sequence = next
// 		previous = next
// 	}
// }

type SampleConsumer struct{}

func (this SampleConsumer) Consume(lower, upper int64) {
	for lower <= upper {
		// message := ringBuffer[lower&BufferMask]
		// if message != lower {
		// 	fmt.Println("Race condition", message, lower)
		// 	panic("Race condition")
		// }
		lower++
	}
}
<|endoftext|>


<commit_before>// Copyright (c) 2013-2015 The btcsuite developers
// Use of this source code is governed by an ISC
// license that can be found in the LICENSE file.

package wallet

import (
	"bytes"
	"strings"

	"github.com/btcsuite/btcd/txscript"
	"github.com/btcsuite/btcwallet/chain"
	"github.com/btcsuite/btcwallet/waddrmgr"
	"github.com/btcsuite/btcwallet/walletdb"
	"github.com/btcsuite/btcwallet/wtxmgr"
)

func (w *Wallet) handleChainNotifications() {
	chainClient, err := w.requireChainClient()
	if err != nil {
		log.Errorf("handleChainNotifications called without RPC client")
		w.wg.Done()
		return
	}

	sync := func(w *Wallet) {
		// At the moment there is no recourse if the rescan fails for
		// some reason, however, the wallet will not be marked synced
		// and many methods will error early since the wallet is known
		// to be out of date.
		err := w.syncWithChain()
		if err != nil && !w.ShuttingDown() {
			log.Warnf("Unable to synchronize wallet to chain: %v", err)
		}
	}

	catchUpHashes := func(w *Wallet, client chain.Interface,
		height int32) error {
		// TODO(aakselrod): There's a race conditon here, which
		// happens when a reorg occurs between the
		// rescanProgress notification and the last GetBlockHash
		// call. The solution when using btcd is to make btcd
		// send blockconnected notifications with each block
		// the way Neutrino does, and get rid of the loop. The
		// other alternative is to check the final hash and,
		// if it doesn't match the original hash returned by
		// the notification, to roll back and restart the
		// rescan.
		log.Infof("Catching up block hashes to height %d, this"+
			" might take a while", height)
		err := walletdb.Update(w.db, func(tx walletdb.ReadWriteTx) error {
			ns := tx.ReadWriteBucket(waddrmgrNamespaceKey)

			startBlock := w.Manager.SyncedTo()

			for i := startBlock.Height + 1; i <= height; i++ {
				hash, err := client.GetBlockHash(int64(i))
				if err != nil {
					return err
				}
				header, err := chainClient.GetBlockHeader(hash)
				if err != nil {
					return err
				}

				bs := waddrmgr.BlockStamp{
					Height:    i,
					Hash:      *hash,
					Timestamp: header.Timestamp,
				}
				err = w.Manager.SetSyncedTo(ns, &bs)
				if err != nil {
					return err
				}
			}
			return nil
		})
		if err != nil {
			log.Errorf("Failed to update address manager "+
				"sync state for height %d: %v", height, err)
		}

		log.Info("Done catching up block hashes")
		return err
	}

	for n := range chainClient.Notifications() {
		var notificationName string
		var err error
		switch n := n.(type) {
		case chain.ClientConnected:
			go sync(w)
		case chain.BlockConnected:
			err = walletdb.Update(w.db, func(tx walletdb.ReadWriteTx) error {
				return w.connectBlock(tx, wtxmgr.BlockMeta(n))
			})
			notificationName = "blockconnected"
		case chain.BlockDisconnected:
			err = walletdb.Update(w.db, func(tx walletdb.ReadWriteTx) error {
				return w.disconnectBlock(tx, wtxmgr.BlockMeta(n))
			})
			notificationName = "blockdisconnected"
		case chain.RelevantTx:
			err = walletdb.Update(w.db, func(tx walletdb.ReadWriteTx) error {
				return w.addRelevantTx(tx, n.TxRecord, n.Block)
			})
			notificationName = "recvtx/redeemingtx"
		case chain.FilteredBlockConnected:
			// Atomically update for the whole block.
			if len(n.RelevantTxs) > 0 {
				err = walletdb.Update(w.db, func(
					tx walletdb.ReadWriteTx) error {
					var err error
					for _, rec := range n.RelevantTxs {
						err = w.addRelevantTx(tx, rec,
							n.Block)
						if err != nil {
							return err
						}
					}
					return nil
				})
			}
			notificationName = "filteredblockconnected"

		// The following require some database maintenance, but also
		// need to be reported to the wallet's rescan goroutine.
		case *chain.RescanProgress:
			err = catchUpHashes(w, chainClient, n.Height)
			notificationName = "rescanprogress"
			w.rescanNotifications <- n
		case *chain.RescanFinished:
			err = catchUpHashes(w, chainClient, n.Height)
			notificationName = "rescanprogress"
			w.SetChainSynced(true)
			w.rescanNotifications <- n
		}
		if err != nil {
			// On out-of-sync blockconnected notifications, only
			// send a debug message.
			errStr := "Failed to process consensus server " +
				"notification (name: `%s`, detail: `%v`)"
			if notificationName == "blockconnected" &&
				strings.Contains(err.Error(),
					"couldn't get hash from database") {
				log.Debugf(errStr, notificationName, err)
			} else {
				log.Errorf(errStr, notificationName, err)
			}
		}
	}
	w.wg.Done()
}

// connectBlock handles a chain server notification by marking a wallet
// that's currently in-sync with the chain server as being synced up to
// the passed block.
func (w *Wallet) connectBlock(dbtx walletdb.ReadWriteTx, b wtxmgr.BlockMeta) error {
	addrmgrNs := dbtx.ReadWriteBucket(waddrmgrNamespaceKey)

	bs := waddrmgr.BlockStamp{
		Height:    b.Height,
		Hash:      b.Hash,
		Timestamp: b.Time,
	}
	err := w.Manager.SetSyncedTo(addrmgrNs, &bs)
	if err != nil {
		return err
	}

	// Notify interested clients of the connected block.
	//
	// TODO: move all notifications outside of the database transaction.
	w.NtfnServer.notifyAttachedBlock(dbtx, &b)
	return nil
}

// disconnectBlock handles a chain server reorganize by rolling back all
// block history from the reorged block for a wallet in-sync with the chain
// server.
func (w *Wallet) disconnectBlock(dbtx walletdb.ReadWriteTx, b wtxmgr.BlockMeta) error {
	addrmgrNs := dbtx.ReadWriteBucket(waddrmgrNamespaceKey)
	txmgrNs := dbtx.ReadWriteBucket(wtxmgrNamespaceKey)

	if !w.ChainSynced() {
		return nil
	}

	// Disconnect the removed block and all blocks after it if we know about
	// the disconnected block. Otherwise, the block is in the future.
	if b.Height <= w.Manager.SyncedTo().Height {
		hash, err := w.Manager.BlockHash(addrmgrNs, b.Height)
		if err != nil {
			return err
		}
		if bytes.Equal(hash[:], b.Hash[:]) {
			bs := waddrmgr.BlockStamp{
				Height: b.Height - 1,
			}
			hash, err = w.Manager.BlockHash(addrmgrNs, bs.Height)
			if err != nil {
				return err
			}
			b.Hash = *hash

			client := w.ChainClient()
			header, err := client.GetBlockHeader(hash)
			if err != nil {
				return err
			}

			bs.Timestamp = header.Timestamp

			err = w.Manager.SetSyncedTo(addrmgrNs, &bs)
			if err != nil {
				return err
			}
			err = w.TxStore.Rollback(txmgrNs, b.Height)
		}
	}

	// Notify interested clients of the disconnected block.
	w.NtfnServer.notifyDetachedBlock(&b.Hash)

	return nil
}

func (w *Wallet) addRelevantTx(dbtx walletdb.ReadWriteTx, rec *wtxmgr.TxRecord, block *wtxmgr.BlockMeta) error {
	addrmgrNs := dbtx.ReadWriteBucket(waddrmgrNamespaceKey)
	txmgrNs := dbtx.ReadWriteBucket(wtxmgrNamespaceKey)

	// At the moment all notified transactions are assumed to actually be
	// relevant.  This assumption will not hold true when SPV support is
	// added, but until then, simply insert the transaction because there
	// should either be one or more relevant inputs or outputs.
	err := w.TxStore.InsertTx(txmgrNs, rec, block)
	if err != nil {
		return err
	}

	// Check every output to determine whether it is controlled by a wallet
	// key.  If so, mark the output as a credit.
	for i, output := range rec.MsgTx.TxOut {
		_, addrs, _, err := txscript.ExtractPkScriptAddrs(output.PkScript,
			w.chainParams)
		if err != nil {
			// Non-standard outputs are skipped.
			continue
		}
		for _, addr := range addrs {
			ma, err := w.Manager.Address(addrmgrNs, addr)
			if err == nil {
				// TODO: Credits should be added with the
				// account they belong to, so wtxmgr is able to
				// track per-account balances.
				err = w.TxStore.AddCredit(txmgrNs, rec, block, uint32(i),
					ma.Internal())
				if err != nil {
					return err
				}
				err = w.Manager.MarkUsed(addrmgrNs, addr)
				if err != nil {
					return err
				}
				log.Debugf("Marked address %v used", addr)
				continue
			}

			// Missing addresses are skipped.  Other errors should
			// be propagated.
			if !waddrmgr.IsError(err, waddrmgr.ErrAddressNotFound) {
				return err
			}
		}
	}

	// Send notification of mined or unmined transaction to any interested
	// clients.
	//
	// TODO: Avoid the extra db hits.
	if block == nil {
		details, err := w.TxStore.UniqueTxDetails(txmgrNs, &rec.Hash, nil)
		if err != nil {
			log.Errorf("Cannot query transaction details for notification: %v", err)
		} else {
			w.NtfnServer.notifyUnminedTransaction(dbtx, details)
		}
	} else {
		details, err := w.TxStore.UniqueTxDetails(txmgrNs, &rec.Hash, &block.Block)
		if err != nil {
			log.Errorf("Cannot query transaction details for notification: %v", err)
		} else {
			w.NtfnServer.notifyMinedTransaction(dbtx, details, block)
		}
	}

	return nil
}
<commit_msg>wallet/chainntfns: ensure safe shutdown during sync<commit_after>// Copyright (c) 2013-2015 The btcsuite developers
// Use of this source code is governed by an ISC
// license that can be found in the LICENSE file.

package wallet

import (
	"bytes"
	"strings"

	"github.com/btcsuite/btcd/txscript"
	"github.com/btcsuite/btcwallet/chain"
	"github.com/btcsuite/btcwallet/waddrmgr"
	"github.com/btcsuite/btcwallet/walletdb"
	"github.com/btcsuite/btcwallet/wtxmgr"
)

func (w *Wallet) handleChainNotifications() {
	chainClient, err := w.requireChainClient()
	if err != nil {
		log.Errorf("handleChainNotifications called without RPC client")
		w.wg.Done()
		return
	}

	sync := func(w *Wallet) {
		// At the moment there is no recourse if the rescan fails for
		// some reason, however, the wallet will not be marked synced
		// and many methods will error early since the wallet is known
		// to be out of date.
		err := w.syncWithChain()
		if err != nil && !w.ShuttingDown() {
			log.Warnf("Unable to synchronize wallet to chain: %v", err)
		}
	}

	catchUpHashes := func(w *Wallet, client chain.Interface,
		height int32) error {
		// TODO(aakselrod): There's a race conditon here, which
		// happens when a reorg occurs between the
		// rescanProgress notification and the last GetBlockHash
		// call. The solution when using btcd is to make btcd
		// send blockconnected notifications with each block
		// the way Neutrino does, and get rid of the loop. The
		// other alternative is to check the final hash and,
		// if it doesn't match the original hash returned by
		// the notification, to roll back and restart the
		// rescan.
		log.Infof("Catching up block hashes to height %d, this"+
			" might take a while", height)
		err := walletdb.Update(w.db, func(tx walletdb.ReadWriteTx) error {
			ns := tx.ReadWriteBucket(waddrmgrNamespaceKey)

			startBlock := w.Manager.SyncedTo()

			for i := startBlock.Height + 1; i <= height; i++ {
				hash, err := client.GetBlockHash(int64(i))
				if err != nil {
					return err
				}
				header, err := chainClient.GetBlockHeader(hash)
				if err != nil {
					return err
				}

				bs := waddrmgr.BlockStamp{
					Height:    i,
					Hash:      *hash,
					Timestamp: header.Timestamp,
				}
				err = w.Manager.SetSyncedTo(ns, &bs)
				if err != nil {
					return err
				}
			}
			return nil
		})
		if err != nil {
			log.Errorf("Failed to update address manager "+
				"sync state for height %d: %v", height, err)
		}

		log.Info("Done catching up block hashes")
		return err
	}

	for n := range chainClient.Notifications() {
		var notificationName string
		var err error
		switch n := n.(type) {
		case chain.ClientConnected:
			go sync(w)
		case chain.BlockConnected:
			err = walletdb.Update(w.db, func(tx walletdb.ReadWriteTx) error {
				return w.connectBlock(tx, wtxmgr.BlockMeta(n))
			})
			notificationName = "blockconnected"
		case chain.BlockDisconnected:
			err = walletdb.Update(w.db, func(tx walletdb.ReadWriteTx) error {
				return w.disconnectBlock(tx, wtxmgr.BlockMeta(n))
			})
			notificationName = "blockdisconnected"
		case chain.RelevantTx:
			err = walletdb.Update(w.db, func(tx walletdb.ReadWriteTx) error {
				return w.addRelevantTx(tx, n.TxRecord, n.Block)
			})
			notificationName = "recvtx/redeemingtx"
		case chain.FilteredBlockConnected:
			// Atomically update for the whole block.
			if len(n.RelevantTxs) > 0 {
				err = walletdb.Update(w.db, func(
					tx walletdb.ReadWriteTx) error {
					var err error
					for _, rec := range n.RelevantTxs {
						err = w.addRelevantTx(tx, rec,
							n.Block)
						if err != nil {
							return err
						}
					}
					return nil
				})
			}
			notificationName = "filteredblockconnected"

		// The following require some database maintenance, but also
		// need to be reported to the wallet's rescan goroutine.
		case *chain.RescanProgress:
			err = catchUpHashes(w, chainClient, n.Height)
			notificationName = "rescanprogress"
			select {
			case w.rescanNotifications <- n:
			case <-w.quitChan():
				return
			}
		case *chain.RescanFinished:
			err = catchUpHashes(w, chainClient, n.Height)
			notificationName = "rescanprogress"
			w.SetChainSynced(true)
			select {
			case w.rescanNotifications <- n:
			case <-w.quitChan():
				return
			}
		}
		if err != nil {
			// On out-of-sync blockconnected notifications, only
			// send a debug message.
			errStr := "Failed to process consensus server " +
				"notification (name: `%s`, detail: `%v`)"
			if notificationName == "blockconnected" &&
				strings.Contains(err.Error(),
					"couldn't get hash from database") {
				log.Debugf(errStr, notificationName, err)
			} else {
				log.Errorf(errStr, notificationName, err)
			}
		}
	}
	w.wg.Done()
}

// connectBlock handles a chain server notification by marking a wallet
// that's currently in-sync with the chain server as being synced up to
// the passed block.
func (w *Wallet) connectBlock(dbtx walletdb.ReadWriteTx, b wtxmgr.BlockMeta) error {
	addrmgrNs := dbtx.ReadWriteBucket(waddrmgrNamespaceKey)

	bs := waddrmgr.BlockStamp{
		Height:    b.Height,
		Hash:      b.Hash,
		Timestamp: b.Time,
	}
	err := w.Manager.SetSyncedTo(addrmgrNs, &bs)
	if err != nil {
		return err
	}

	// Notify interested clients of the connected block.
	//
	// TODO: move all notifications outside of the database transaction.
	w.NtfnServer.notifyAttachedBlock(dbtx, &b)
	return nil
}

// disconnectBlock handles a chain server reorganize by rolling back all
// block history from the reorged block for a wallet in-sync with the chain
// server.
func (w *Wallet) disconnectBlock(dbtx walletdb.ReadWriteTx, b wtxmgr.BlockMeta) error {
	addrmgrNs := dbtx.ReadWriteBucket(waddrmgrNamespaceKey)
	txmgrNs := dbtx.ReadWriteBucket(wtxmgrNamespaceKey)

	if !w.ChainSynced() {
		return nil
	}

	// Disconnect the removed block and all blocks after it if we know about
	// the disconnected block. Otherwise, the block is in the future.
	if b.Height <= w.Manager.SyncedTo().Height {
		hash, err := w.Manager.BlockHash(addrmgrNs, b.Height)
		if err != nil {
			return err
		}
		if bytes.Equal(hash[:], b.Hash[:]) {
			bs := waddrmgr.BlockStamp{
				Height: b.Height - 1,
			}
			hash, err = w.Manager.BlockHash(addrmgrNs, bs.Height)
			if err != nil {
				return err
			}
			b.Hash = *hash

			client := w.ChainClient()
			header, err := client.GetBlockHeader(hash)
			if err != nil {
				return err
			}

			bs.Timestamp = header.Timestamp

			err = w.Manager.SetSyncedTo(addrmgrNs, &bs)
			if err != nil {
				return err
			}
			err = w.TxStore.Rollback(txmgrNs, b.Height)
		}
	}

	// Notify interested clients of the disconnected block.
	w.NtfnServer.notifyDetachedBlock(&b.Hash)

	return nil
}

func (w *Wallet) addRelevantTx(dbtx walletdb.ReadWriteTx, rec *wtxmgr.TxRecord, block *wtxmgr.BlockMeta) error {
	addrmgrNs := dbtx.ReadWriteBucket(waddrmgrNamespaceKey)
	txmgrNs := dbtx.ReadWriteBucket(wtxmgrNamespaceKey)

	// At the moment all notified transactions are assumed to actually be
	// relevant.  This assumption will not hold true when SPV support is
	// added, but until then, simply insert the transaction because there
	// should either be one or more relevant inputs or outputs.
	err := w.TxStore.InsertTx(txmgrNs, rec, block)
	if err != nil {
		return err
	}

	// Check every output to determine whether it is controlled by a wallet
	// key.  If so, mark the output as a credit.
	for i, output := range rec.MsgTx.TxOut {
		_, addrs, _, err := txscript.ExtractPkScriptAddrs(output.PkScript,
			w.chainParams)
		if err != nil {
			// Non-standard outputs are skipped.
			continue
		}
		for _, addr := range addrs {
			ma, err := w.Manager.Address(addrmgrNs, addr)
			if err == nil {
				// TODO: Credits should be added with the
				// account they belong to, so wtxmgr is able to
				// track per-account balances.
				err = w.TxStore.AddCredit(txmgrNs, rec, block, uint32(i),
					ma.Internal())
				if err != nil {
					return err
				}
				err = w.Manager.MarkUsed(addrmgrNs, addr)
				if err != nil {
					return err
				}
				log.Debugf("Marked address %v used", addr)
				continue
			}

			// Missing addresses are skipped.  Other errors should
			// be propagated.
			if !waddrmgr.IsError(err, waddrmgr.ErrAddressNotFound) {
				return err
			}
		}
	}

	// Send notification of mined or unmined transaction to any interested
	// clients.
	//
	// TODO: Avoid the extra db hits.
	if block == nil {
		details, err := w.TxStore.UniqueTxDetails(txmgrNs, &rec.Hash, nil)
		if err != nil {
			log.Errorf("Cannot query transaction details for notification: %v", err)
		} else {
			w.NtfnServer.notifyUnminedTransaction(dbtx, details)
		}
	} else {
		details, err := w.TxStore.UniqueTxDetails(txmgrNs, &rec.Hash, &block.Block)
		if err != nil {
			log.Errorf("Cannot query transaction details for notification: %v", err)
		} else {
			w.NtfnServer.notifyMinedTransaction(dbtx, details, block)
		}
	}

	return nil
}
<|endoftext|>


<commit_before>package youtube_test

import (
	"fmt"
	"io"
	"os"
	"strings"

	"github.com/kkdai/youtube/v2"
)

// ExampleDownload : Example code for how to use this package for download video.
func ExampleClient() {
	videoID := "BaW_jenozKc"
	client := youtube.Client{}

	video, err := client.GetVideo(videoID)
	if err != nil {
		panic(err)
	}

	stream, _, err := client.GetStream(video, &video.Formats[0])
	if err != nil {
		panic(err)
	}

	file, err := os.Create("video.mp4")
	if err != nil {
		panic(err)
	}
	defer file.Close()

	_, err = io.Copy(file, stream)
	if err != nil {
		panic(err)
	}
}

// Example usage for playlists: downloading and checking information.
func ExamplePlaylist() {
	playlistID := "PLQZgI7en5XEgM0L1_ZcKmEzxW1sCOVZwP"
	client := youtube.Client{}

	playlist, err := client.GetPlaylist(playlistID)
	if err != nil {
		panic(err)
	}

	/* ----- Enumerating playlist videos ----- */
	header := fmt.Sprintf("Playlist %s by %s", playlist.Title, playlist.Author)
	println(header)
	println(strings.Repeat("=", len(header)) + "\n")

	for k, v := range playlist.Videos {
		fmt.Printf("(%d) %s - '%s'\n", k+1, v.Author, v.Title)
	}

	/* ----- Downloading the 1st video ----- */
	entry := playlist.Videos[0]
	video, err := client.VideoFromPlaylistEntry(entry)
	if err != nil {
		panic(err)
	}
	// Now it's fully loaded.

	fmt.Printf("Downloading %s by '%s'!\n", video.Title, video.Author)

	stream, _, err := client.GetStream(video, &video.Formats[0])
	if err != nil {
		panic(err)
	}

	file, err := os.Create("video.mp4")

	if err != nil {
		panic(err)
	}

	defer file.Close()
	_, err = io.Copy(file, stream)

	if err != nil {
		panic(err)
	}

	println("Downloaded /video.mp4")
}
<commit_msg>Update example_test<commit_after>package youtube_test

import (
	"fmt"
	"io"
	"os"
	"strings"

	"github.com/kkdai/youtube/v2"
)

// ExampleDownload : Example code for how to use this package for download video.
func ExampleClient() {
	videoID := "BaW_jenozKc"
	client := youtube.Client{}

	video, err := client.GetVideo(videoID)
	if err != nil {
		panic(err)
	}

	formats := video.Formats.WithAudioChannels() // only get videos with audio
	stream, _, err := client.GetStream(video, &formats[0])
	if err != nil {
		panic(err)
	}

	file, err := os.Create("video.mp4")
	if err != nil {
		panic(err)
	}
	defer file.Close()

	_, err = io.Copy(file, stream)
	if err != nil {
		panic(err)
	}
}

// Example usage for playlists: downloading and checking information.
func ExamplePlaylist() {
	playlistID := "PLQZgI7en5XEgM0L1_ZcKmEzxW1sCOVZwP"
	client := youtube.Client{}

	playlist, err := client.GetPlaylist(playlistID)
	if err != nil {
		panic(err)
	}

	/* ----- Enumerating playlist videos ----- */
	header := fmt.Sprintf("Playlist %s by %s", playlist.Title, playlist.Author)
	println(header)
	println(strings.Repeat("=", len(header)) + "\n")

	for k, v := range playlist.Videos {
		fmt.Printf("(%d) %s - '%s'\n", k+1, v.Author, v.Title)
	}

	/* ----- Downloading the 1st video ----- */
	entry := playlist.Videos[0]
	video, err := client.VideoFromPlaylistEntry(entry)
	if err != nil {
		panic(err)
	}
	// Now it's fully loaded.

	fmt.Printf("Downloading %s by '%s'!\n", video.Title, video.Author)

	stream, _, err := client.GetStream(video, &video.Formats[0])
	if err != nil {
		panic(err)
	}

	file, err := os.Create("video.mp4")

	if err != nil {
		panic(err)
	}

	defer file.Close()
	_, err = io.Copy(file, stream)

	if err != nil {
		panic(err)
	}

	println("Downloaded /video.mp4")
}
<|endoftext|>


<commit_before>package plugin_test

import (
	"log"
	"os"
	"strings"

	"net/rpc/jsonrpc"

	"github.com/natefinch/plugin"
)

// This function should be called from the master program that wants to run
// plugins to extend its functionality.
//
// StartWithCodec starts a plugin at path "foo", using the JSON-RPC codec, and
// writing its output to this application's Stderr.  The application can
// then call methods on the rpc client returned using the standard rpc
// pattern.
func ExampleStartWithCodec() {
	foo, err := plugin.StartWithCodec(jsonrpc.NewClient, "/var/lib/foo", os.Stderr)
	if err != nil {
		log.Fatalf("failed to load foo plugin: %s", err)
	}
	var reply string
	foo.Call("Foo.ToUpper", "something", &reply)
}

// This function should be called from the plugin program that wants to provide
// functionality for the master program.
//
// NewServerWithCodec starts an RPC server that reads from stdin and writes to
// stdout. It provides functions attached to the API value passed in.
// Server.Serve() will block forever, so it is common to simply put this at the
// end of the plugin's main function.
func ExampleNewServerWithCodec() {
	p := plugin.NewServerWithCodec(jsonrpc.NewServerCodec)
	if err := p.RegisterName("Foo", API{}); err != nil {
		log.Fatalf("can't register api: %s", err)
	}
	p.Serve()
}

// API is an example type to show how to serve methods over RPC.
type API struct{}

// ToUpper is an example function that gets served over RPC.  See net/rpc for
// details on how to server functionality over RPC.
func (API) ToUpper(input string, output *string) error {
	*output = strings.ToUpper(input)
	return nil
}
<commit_msg>fix test<commit_after>package plugin_test

import (
	"log"
	"os"
	"strings"

	"net/rpc/jsonrpc"

	"github.com/natefinch/plugin"
)

// This function should be called from the master program that wants to run
// plugins to extend its functionality.
//
// StartWithCodec starts a plugin at path "foo", using the JSON-RPC codec, and
// writing its output to this application's Stderr.  The application can
// then call methods on the rpc client returned using the standard rpc
// pattern.
func ExampleStartWithCodec() {
	foo, err := plugin.StartWithCodec(jsonrpc.NewClientCodec, "/var/lib/foo", os.Stderr)
	if err != nil {
		log.Fatalf("failed to load foo plugin: %s", err)
	}
	var reply string
	foo.Call("Foo.ToUpper", "something", &reply)
}

// This function should be called from the plugin program that wants to provide
// functionality for the master program.
//
// NewServerWithCodec starts an RPC server that reads from stdin and writes to
// stdout. It provides functions attached to the API value passed in.
// Server.Serve() will block forever, so it is common to simply put this at the
// end of the plugin's main function.
func ExampleNewServerWithCodec() {
	p := plugin.NewServerWithCodec(jsonrpc.NewServerCodec)
	if err := p.RegisterName("Foo", API{}); err != nil {
		log.Fatalf("can't register api: %s", err)
	}
	p.Serve()
}

// API is an example type to show how to serve methods over RPC.
type API struct{}

// ToUpper is an example function that gets served over RPC.  See net/rpc for
// details on how to server functionality over RPC.
func (API) ToUpper(input string, output *string) error {
	*output = strings.ToUpper(input)
	return nil
}
<|endoftext|>


<commit_before>package structfield_test

import (
	"encoding/json"
	"fmt"
	"github.com/vincent-petithory/structfield"
	"log"
)

func ExampleTransform() {
	// In the context of a REST API:
	// we want to transform the friends field in a friends_url field
	// that contains the URL to the list of friends of the user.
	type User struct {
		Id      string `json:"id"`
		Name    string `json:"name"`
		Age     int    `json:"age"`
		Friends []User `json:"friends"`
	}
	user := User{
		Id:   "4fa654a",
		Name: "Lelouch",
		Age:  22,
		Friends: []User{
			{Id: "65de67a", Name: "Ringo", Age: 25},
			{Id: "942ab70", Name: "Vivi", Age: 28},
		},
	}

	userFriendsToURL := structfield.TransformerFunc(func(field string, value interface{}) (string, interface{}) {
		return field + "_url", fmt.Sprintf("https://some.api.com/users/%s/friends", user.Id)
	})

	m := structfield.Transform(user, map[string]structfield.Transformer{
		"friends": userFriendsToURL,
	})
	_, err := json.Marshal(m)
	if err != nil {
		log.Println(err)
	}
	fmt.Printf("%s", m["friends_url"])
	// Output: https://some.api.com/users/4fa654a/friends
}
<commit_msg>add example with nil argument<commit_after>package structfield_test

import (
	"encoding/json"
	"fmt"
	"github.com/vincent-petithory/structfield"
	"log"
)

func ExampleTransform() {
	// In the context of a REST API:
	// we want to transform the friends field in a friends_url field
	// that contains the URL to the list of friends of the user.
	type User struct {
		Id      string `json:"id"`
		Name    string `json:"name"`
		Age     int    `json:"age"`
		Friends []User `json:"friends"`
	}
	user := User{
		Id:   "4fa654a",
		Name: "Lelouch",
		Age:  22,
		Friends: []User{
			{Id: "65de67a", Name: "Ringo", Age: 25},
			{Id: "942ab70", Name: "Vivi", Age: 28},
		},
	}

	userFriendsToURL := structfield.TransformerFunc(func(field string, value interface{}) (string, interface{}) {
		return field + "_url", fmt.Sprintf("https://some.api.com/users/%s/friends", user.Id)
	})

	m := structfield.Transform(user, map[string]structfield.Transformer{
		"friends": userFriendsToURL,
	})
	_, err := json.Marshal(m)
	if err != nil {
		log.Fatal(err)
	}
	fmt.Printf("%s", m["friends_url"])
	// Output: https://some.api.com/users/4fa654a/friends
}

func ExampleTransform_nil() {
	// nil is a valid value for the transformers argument
	// for retrieving a map[string]interface{} out of a struct.
	type User struct {
		Id      string `json:"id"`
		Name    string `json:"name"`
		Age     int    `json:"age"`
		Friends []User `json:"friends"`
	}
	user := User{
		Id:   "4fa654a",
		Name: "Lelouch",
		Age:  22,
		Friends: []User{
			{Id: "65de67a", Name: "Ringo", Age: 25},
			{Id: "942ab70", Name: "Vivi", Age: 28},
		},
	}

	m := structfield.Transform(user, nil)
	_, err := json.Marshal(m)
	if err != nil {
		log.Fatal(err)
	}
}
<|endoftext|>


<commit_before>package static

import (
	"fmt"
	"net/http"
	"path"
)

func ExampleBuild() {
	handler := http.NewServeMux()
	paths := []string{}

	handler.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
		fmt.Fprintf(w, "Hello %s!", path.Base(r.URL.Path))
	})

	paths = append(paths, "/world")

	Build(DefaultOptions, handler, paths, func(e Event) {
		fmt.Println(e)
	})

	// Output:
	// Action: build, Path: /world, StatusCode: 200, OutputPath: build/world
}

func ExampleBuildSingle() {
	handler := http.NewServeMux()

	handler.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
		fmt.Fprintf(w, "Hello %s!", path.Base(r.URL.Path))
	})

	statusCode, outputPath, err := BuildSingle(DefaultOptions, handler, "/world")
	fmt.Printf("Built: /world, StatusCode: %d, OutputPath: %v, Error: %v", statusCode, outputPath, err)

	// Output:
	// Built: /world, StatusCode: 200, OutputPath: build/world, Error: <nil>
}
<commit_msg>Don't build examples on Windows.<commit_after>// +build !windows

package static

import (
	"fmt"
	"net/http"
	"path"
)

func ExampleBuild() {
	handler := http.NewServeMux()
	paths := []string{}

	handler.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
		fmt.Fprintf(w, "Hello %s!", path.Base(r.URL.Path))
	})

	paths = append(paths, "/world")

	Build(DefaultOptions, handler, paths, func(e Event) {
		fmt.Println(e)
	})

	// Output:
	// Action: build, Path: /world, StatusCode: 200, OutputPath: build/world
}

func ExampleBuildSingle() {
	handler := http.NewServeMux()

	handler.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
		fmt.Fprintf(w, "Hello %s!", path.Base(r.URL.Path))
	})

	statusCode, outputPath, err := BuildSingle(DefaultOptions, handler, "/world")
	fmt.Printf("Built: /world, StatusCode: %d, OutputPath: %v, Error: %v", statusCode, outputPath, err)

	// Output:
	// Built: /world, StatusCode: 200, OutputPath: build/world, Error: <nil>
}
<|endoftext|>


<commit_before>// Copyright (c) 2016 Uber Technologies, Inc.
// Copyright (c) 2017 Hiroaki Nakamura
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.

package ltsv_test

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

	"github.com/hnakamur/zap-ltsv"
	"github.com/uber-go/zap"
)

func Example() {
	// Log in LTSV, using a reflection-free LTSV encoder. By default, loggers
	// write all InfoLevel and above logs to standard out.
	logger := zap.New(
		ltsv.NewLTSVEncoder(ltsv.LTSVNoTime()), // drop timestamps in tests
	)

	logger.Warn("Log without structured data...")
	logger.Warn(
		"Or use strongly-typed wrappers to add structured context.",
		zap.String("library", "zap"),
		zap.Duration("latency", time.Nanosecond),
	)

	// Avoid re-serializing the same data repeatedly by creating a child logger
	// with some attached context. That context is added to all the child's
	// log output, but doesn't affect the parent.
	child := logger.With(
		zap.String("user", "jane@test.com"),
		zap.Int("visits", 42),
	)
	child.Error("Oh no!")

	// Output:
	// level:W	msg:Log without structured data...
	// level:W	msg:Or use strongly-typed wrappers to add structured context.	library:zap	latency:1
	// level:E	msg:Oh no!	user:jane@test.com	visits:42
}

func Example_fileOutput() {
	// Create a temporary file to output logs to.
	f, err := ioutil.TempFile("", "log")
	if err != nil {
		panic("failed to create temporary file")
	}
	defer os.Remove(f.Name())

	logger := zap.New(
		ltsv.NewLTSVEncoder(ltsv.LTSVNoTime()), // drop timestamps in tests
		// Write the logging output to the specified file instead of stdout.
		// Any type implementing zap.WriteSyncer or zap.WriteFlusher can be used.
		zap.Output(f),
	)

	logger.Info("This is an info log.", zap.Int("foo", 42))

	// Sync the file so logs are written to disk, and print the file contents.
	// zap will call Sync automatically when logging at FatalLevel or PanicLevel.
	f.Sync()
	contents, err := ioutil.ReadFile(f.Name())
	if err != nil {
		panic("failed to read temporary file")
	}

	fmt.Println(string(contents))
	// Output:
	// level:I	msg:This is an info log.	foo:42
}

func Example_nest() {
	logger := zap.New(
		ltsv.NewLTSVEncoder(ltsv.LTSVNoTime()), // drop timestamps in tests
	)

	// We'd like the logging context to be {"outer":{"inner":42}}
	nest := zap.Nest("outer", zap.Int("inner", 42))
	logger.Info("Logging a nested field.", nest)

	// Output:
	// level:I	msg:Logging a nested field.	outer:{"inner":42}
}

func Example_new() {
	// The default logger outputs to standard out and only writes logs that are
	// Info level or higher.
	logger := zap.New(
		ltsv.NewLTSVEncoder(ltsv.LTSVNoTime()), // drop timestamps in tests
	)

	// The default logger does not print Debug logs.
	logger.Debug("This won't be printed.")
	logger.Info("This is an info log.")

	// Output:
	// level:I	msg:This is an info log.
}

func Example_tee() {
	// Multiple loggers can be combine using Tee.
	output := zap.Output(os.Stdout)
	logger := zap.Tee(
		zap.New(zap.NewTextEncoder(zap.TextNoTime()), output),
		zap.New(zap.NewJSONEncoder(zap.NoTime()), output),
		zap.New(ltsv.NewLTSVEncoder(ltsv.LTSVNoTime()), output),
	)

	logger.Info("this log gets encoded three times, differently", zap.Int("foo", 42))
	// Output:
	// [I] this log gets encoded three times, differently foo=42
	// {"level":"info","msg":"this log gets encoded three times, differently","foo":42}
	// level:I	msg:this log gets encoded three times, differently	foo:42
}

func Example_multiWriteSyncer() {
	// To send output to multiple outputs, use MultiWriteSyncer.
	textLogger := zap.New(
		ltsv.NewLTSVEncoder(ltsv.LTSVNoTime()), // drop timestamps in tests
		zap.Output(zap.MultiWriteSyncer(os.Stdout, os.Stdout)),
	)

	textLogger.Info("One becomes two")
	// Output:
	// level:I	msg:One becomes two
	// level:I	msg:One becomes two
}

func Example_newOptions() {
	// We can pass multiple options to the New method to configure the logging
	// level, output location, or even the initial context.
	logger := zap.New(
		ltsv.NewLTSVEncoder(ltsv.LTSVNoTime()), // drop timestamps in tests
		zap.DebugLevel,
		zap.Fields(zap.Int("count", 1)),
	)

	logger.Debug("This is a debug log.")
	logger.Info("This is an info log.")

	// Output:
	// level:D	msg:This is a debug log.	count:1
	// level:I	msg:This is an info log.	count:1
}

func Example_checkedMessage() {
	logger := zap.New(
		ltsv.NewLTSVEncoder(ltsv.LTSVNoTime()), // drop timestamps in tests
	)

	// By default, the debug logging level is disabled. However, calls to
	// logger.Debug will still allocate a slice to hold any passed fields.
	// Particularly performance-sensitive applications can avoid paying this
	// penalty by using checked messages.
	if cm := logger.Check(zap.DebugLevel, "This is a debug log."); cm.OK() {
		// Debug-level logging is disabled, so we won't get here.
		cm.Write(zap.Int("foo", 42), zap.Stack())
	}

	if cm := logger.Check(zap.InfoLevel, "This is an info log."); cm.OK() {
		// Since info-level logging is enabled, we expect to write out this message.
		cm.Write()
	}

	// Output:
	// level:I	msg:This is an info log.
}

func ExampleNewLTSVEncoder() {
	// An encoder with the default settings.
	ltsv.NewLTSVEncoder()

	// Dropping timestamps is often useful in tests.
	ltsv.NewLTSVEncoder(ltsv.LTSVNoTime())

	// In production, customize the encoder to work with your log aggregation
	// system.
	ltsv.NewLTSVEncoder(
		ltsv.LTSVTimeFormat(time.RFC3339Nano), // log nanoseconds using a format defined for https://golang.org/pkg/time/#Time.Format
		ltsv.LTSVMessageLabel("message"),      // customize the message label
	)
}
<commit_msg>Fix comment in Example (Nest)<commit_after>// Copyright (c) 2016 Uber Technologies, Inc.
// Copyright (c) 2017 Hiroaki Nakamura
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.

package ltsv_test

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

	"github.com/hnakamur/zap-ltsv"
	"github.com/uber-go/zap"
)

func Example() {
	// Log in LTSV, using a reflection-free LTSV encoder. By default, loggers
	// write all InfoLevel and above logs to standard out.
	logger := zap.New(
		ltsv.NewLTSVEncoder(ltsv.LTSVNoTime()), // drop timestamps in tests
	)

	logger.Warn("Log without structured data...")
	logger.Warn(
		"Or use strongly-typed wrappers to add structured context.",
		zap.String("library", "zap"),
		zap.Duration("latency", time.Nanosecond),
	)

	// Avoid re-serializing the same data repeatedly by creating a child logger
	// with some attached context. That context is added to all the child's
	// log output, but doesn't affect the parent.
	child := logger.With(
		zap.String("user", "jane@test.com"),
		zap.Int("visits", 42),
	)
	child.Error("Oh no!")

	// Output:
	// level:W	msg:Log without structured data...
	// level:W	msg:Or use strongly-typed wrappers to add structured context.	library:zap	latency:1
	// level:E	msg:Oh no!	user:jane@test.com	visits:42
}

func Example_fileOutput() {
	// Create a temporary file to output logs to.
	f, err := ioutil.TempFile("", "log")
	if err != nil {
		panic("failed to create temporary file")
	}
	defer os.Remove(f.Name())

	logger := zap.New(
		ltsv.NewLTSVEncoder(ltsv.LTSVNoTime()), // drop timestamps in tests
		// Write the logging output to the specified file instead of stdout.
		// Any type implementing zap.WriteSyncer or zap.WriteFlusher can be used.
		zap.Output(f),
	)

	logger.Info("This is an info log.", zap.Int("foo", 42))

	// Sync the file so logs are written to disk, and print the file contents.
	// zap will call Sync automatically when logging at FatalLevel or PanicLevel.
	f.Sync()
	contents, err := ioutil.ReadFile(f.Name())
	if err != nil {
		panic("failed to read temporary file")
	}

	fmt.Println(string(contents))
	// Output:
	// level:I	msg:This is an info log.	foo:42
}

func Example_nest() {
	logger := zap.New(
		ltsv.NewLTSVEncoder(ltsv.LTSVNoTime()), // drop timestamps in tests
	)

	// We'd like the logging context to be outer:{"inner":42}
	nest := zap.Nest("outer", zap.Int("inner", 42))
	logger.Info("Logging a nested field.", nest)

	// Output:
	// level:I	msg:Logging a nested field.	outer:{"inner":42}
}

func Example_new() {
	// The default logger outputs to standard out and only writes logs that are
	// Info level or higher.
	logger := zap.New(
		ltsv.NewLTSVEncoder(ltsv.LTSVNoTime()), // drop timestamps in tests
	)

	// The default logger does not print Debug logs.
	logger.Debug("This won't be printed.")
	logger.Info("This is an info log.")

	// Output:
	// level:I	msg:This is an info log.
}

func Example_tee() {
	// Multiple loggers can be combine using Tee.
	output := zap.Output(os.Stdout)
	logger := zap.Tee(
		zap.New(zap.NewTextEncoder(zap.TextNoTime()), output),
		zap.New(zap.NewJSONEncoder(zap.NoTime()), output),
		zap.New(ltsv.NewLTSVEncoder(ltsv.LTSVNoTime()), output),
	)

	logger.Info("this log gets encoded three times, differently", zap.Int("foo", 42))
	// Output:
	// [I] this log gets encoded three times, differently foo=42
	// {"level":"info","msg":"this log gets encoded three times, differently","foo":42}
	// level:I	msg:this log gets encoded three times, differently	foo:42
}

func Example_multiWriteSyncer() {
	// To send output to multiple outputs, use MultiWriteSyncer.
	textLogger := zap.New(
		ltsv.NewLTSVEncoder(ltsv.LTSVNoTime()), // drop timestamps in tests
		zap.Output(zap.MultiWriteSyncer(os.Stdout, os.Stdout)),
	)

	textLogger.Info("One becomes two")
	// Output:
	// level:I	msg:One becomes two
	// level:I	msg:One becomes two
}

func Example_newOptions() {
	// We can pass multiple options to the New method to configure the logging
	// level, output location, or even the initial context.
	logger := zap.New(
		ltsv.NewLTSVEncoder(ltsv.LTSVNoTime()), // drop timestamps in tests
		zap.DebugLevel,
		zap.Fields(zap.Int("count", 1)),
	)

	logger.Debug("This is a debug log.")
	logger.Info("This is an info log.")

	// Output:
	// level:D	msg:This is a debug log.	count:1
	// level:I	msg:This is an info log.	count:1
}

func Example_checkedMessage() {
	logger := zap.New(
		ltsv.NewLTSVEncoder(ltsv.LTSVNoTime()), // drop timestamps in tests
	)

	// By default, the debug logging level is disabled. However, calls to
	// logger.Debug will still allocate a slice to hold any passed fields.
	// Particularly performance-sensitive applications can avoid paying this
	// penalty by using checked messages.
	if cm := logger.Check(zap.DebugLevel, "This is a debug log."); cm.OK() {
		// Debug-level logging is disabled, so we won't get here.
		cm.Write(zap.Int("foo", 42), zap.Stack())
	}

	if cm := logger.Check(zap.InfoLevel, "This is an info log."); cm.OK() {
		// Since info-level logging is enabled, we expect to write out this message.
		cm.Write()
	}

	// Output:
	// level:I	msg:This is an info log.
}

func ExampleNewLTSVEncoder() {
	// An encoder with the default settings.
	ltsv.NewLTSVEncoder()

	// Dropping timestamps is often useful in tests.
	ltsv.NewLTSVEncoder(ltsv.LTSVNoTime())

	// In production, customize the encoder to work with your log aggregation
	// system.
	ltsv.NewLTSVEncoder(
		ltsv.LTSVTimeFormat(time.RFC3339Nano), // log nanoseconds using a format defined for https://golang.org/pkg/time/#Time.Format
		ltsv.LTSVMessageLabel("message"),      // customize the message label
	)
}
<|endoftext|>


<commit_before>package main

var middleware []*func(int, int) int
<commit_msg>add framework middleware ideas<commit_after>package main

var middleware []*func(int, int) int

// type (
// 	Handler func (w http.ResponseWriter, r *http.Request) (error)
// )
//
// func Handle(handlers ...Handler) (http.Handler) {
// 	return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
// 		for _, handler := range handlers {
// 			err := handler(w, r)
// 			if err != nil {
// 				w.Write([]byte(err.Error()))
// 				return
// 			}
// 		}
// 	})
// }
<|endoftext|>


<commit_before>package cmd

const Version = "3.27.1"
<commit_msg>version bump<commit_after>package cmd

const Version = "3.28.0"
<|endoftext|>


<commit_before>package cmd

const Version = "v4.5.4"
<commit_msg>version bump<commit_after>package cmd

const Version = "v4.5.5"
<|endoftext|>


<commit_before>package cmd

const Version = "v4.0.6"
<commit_msg>version bump<commit_after>package cmd

const Version = "v4.0.7"
<|endoftext|>


<commit_before>package pslq

import (
	"fmt"
	"fp"
	"math"
	"testing"
)

func compareResult(t *testing.T, actual []int64, expected ...int64) {
	if len(actual) < len(expected) {
		t.Fatalf("lengths wrong of answers got %d expecting %d", len(actual), len(expected))
	}
	for i := range actual {
		var e int64
		if i >= len(expected) {
			e = 0
		} else {
			e = expected[i]

		}
		if actual[i] != e {
			t.Errorf("actual[%d]=%d != expected[%d]=%d", i, &actual[i], i, e)
		}
	}
}

// assert pslq([3*pi+4*e/7, pi, e, log(2)]) == [7, -21, -4, 0]
// assert pslq([4.9999999999999991, 1]) == [1, -5]
// assert pslq([2,1]) == [1, -2]

func TestPslqSimple(t *testing.T) {
	env := fp.NewEnvironment(63)
	//one := float64(1<<60)

	in := make([]fp.FixedPoint, 2)
	in[0].SetInt64(env, 1)
	in[1].SetInt64(env, -2)

	out, err := Pslq(env, in, 0, 0, true)
	if err != nil {
		t.Error("Got error", err)
	}
	fmt.Printf("out = %v\n", out)
	compareResult(t, out, 2, 1)
}

func TestPslq2(t *testing.T) {
	env := fp.NewEnvironment(63)

	inFloat := []float64{
		3*math.Pi + 4*math.E/7,
		math.Pi,
		math.E,
		math.Log(2),
	}
	in := make([]fp.FixedPoint, len(inFloat))
	for i := range inFloat {
		in[i].SetFloat64(env, inFloat[i])
	}
	out, err := Pslq(env, in, 0, 0, true)
	if err != nil {
		t.Error("Got error", err)
	}
	fmt.Printf("out = %v\n", out)
	compareResult(t, out, 7, -21, -4, 0)
}

func TestPslq3(t *testing.T) {
	env := fp.NewEnvironment(63)

	inFloat := []float64{
		3*math.Pi + 4*math.E/7,
		math.Pi,
		math.E,
		math.Log(2),
		0.28917320090206799499,
		0.57591529756863646394,
		0.55698607277729539344,
		0.54073048514703925260,
		0.99835889431176827458,
		0.11551877481656358526,
	}
	in := make([]fp.FixedPoint, len(inFloat))
	for i := range inFloat {
		in[i].SetFloat64(env, inFloat[i])
	}
	out, err := Pslq(env, in, 0, 1000, true)
	if err != nil {
		t.Error("Got error", err)
	}
	fmt.Printf("out = %v\n", out)
	compareResult(t, out, 7, -21, -4, 0, 0, 0, 0, 0, 0, 0)
}

// Evaluates a BBP term
//
// sum(k=0->inf)(1/base**k * (1/a*k + b))
func bbp(env *fp.Environment, base, a, b int64, result *fp.FixedPoint) {
	var term, power, aFp, bFp, _1 fp.FixedPoint
	power.SetInt64(env, 1)
	result.SetInt64(env, 0)
	aFp.SetInt64(env, a)
	bFp.SetInt64(env, b)
	_1.SetInt64(env, 1)
	for k := int64(0); ; k++ {
		term.MulInt64(&aFp, k)
		term.Add(&term, &bFp)
		term.Div(&_1, &term)
		term.Mul(&term, &power)
		if term.Sign() == 0 {
			break
		}
		result.Add(result, &term)
		power.DivInt64(&power, base)
	}
}

func TestPslq4(t *testing.T) {
	env := fp.NewEnvironment(64)

	in := make([]fp.FixedPoint, 8)
	for i := range in {
		if i == 0 {
			in[i].SetFloat64(env, math.Pi)
		} else {
			bbp(env, 16, 8, int64(i), &in[i])
		}
		fmt.Printf("in[%d] = %d\n", i, &in[i])
	}
	out, err := Pslq(env, in, 0, 1000, true)
	if err != nil {
		t.Error("Got error", err)
	}
	fmt.Printf("out = %v\n", out)
	compareResult(t, out, 1, -4, 0, 0, 2, 1, 1, 0)
}

// Returns acot(x) in result
func acot(env *fp.Environment, x int64, result *fp.FixedPoint) {
	var term, power fp.FixedPoint
	power.SetInt64(env, 1)
	power.DivInt64(&power, x) // 1/x
	x2 := x * x
	result.SetInt64(env, 0)
	positive := true
	for k := int64(1); ; k += 2 {
		kp := k
		if !positive {
			kp = -k
		}
		positive = !positive
		term.DivInt64(&power, kp)
		if term.Sign() == 0 {
			break
		}
		result.Add(result, &term)
		power.DivInt64(&power, x2)
	}
}

// Returns pi using Machin's formula
func pi(env *fp.Environment, result *fp.FixedPoint) {
	var tmp fp.FixedPoint
	acot(env, 5, &tmp)
	tmp.Lsh(&tmp, 2)
	acot(env, 239, result)
	result.Sub(&tmp, result)
	result.Lsh(result, 2)
}

func TestPslq5(t *testing.T) {
	env := fp.NewEnvironment(64)

	in := make([]fp.FixedPoint, 8)
	in[0].SetFloat64(env, math.Pi)
	acot(env, 2, &in[1])
	acot(env, 4, &in[2])
	acot(env, 6, &in[3])
	acot(env, 7, &in[4])
	acot(env, 8, &in[5])
	acot(env, 9, &in[6])
	acot(env, 10, &in[7])
	out, err := Pslq(env, in, 0, 1000, true)
	if err != nil {
		t.Error("Got error", err)
	}
	fmt.Printf("out = %v\n", out)
	compareResult(t, out, 1, -8, 0, 0, 4, 0, 0, 0)
}

func TestPslq6(t *testing.T) {
	env := fp.NewEnvironment(64)

	in := make([]fp.FixedPoint, 3)
	in[0].SetFloat64(env, math.Pi/4)
	acot(env, 5, &in[1])
	acot(env, 239, &in[2])
	out, err := Pslq(env, in, 0, 1000, true)
	if err != nil {
		t.Error("Got error", err)
	}
	fmt.Printf("out = %v\n", out)
	compareResult(t, out, 1, -4, 1)
}

func TestPslq7(t *testing.T) {
	env := fp.NewEnvironment(64)

	in := make([]fp.FixedPoint, 5)
	in[0].SetFloat64(env, math.Pi/4)
	acot(env, 49, &in[1])
	acot(env, 57, &in[2])
	acot(env, 239, &in[3])
	acot(env, 110443, &in[4])
	out, err := Pslq(env, in, 0, 1000, true)
	if err != nil {
		t.Error("Got error", err)
	}
	fmt.Printf("out = %v\n", out)
	compareResult(t, out, 1, -12, -32, 5, -12)
}

func TestPslq8(t *testing.T) {
	env := fp.NewEnvironment(256)

	in := make([]fp.FixedPoint, 16)
	for i := range in {
		if i == 0 {
			pi(env, &in[i])
		} else {
			bbp(env, 16, 8, int64(i), &in[i])
		}
		fmt.Printf("in[%d] = %d\n", i, &in[i])
	}
	out, err := Pslq(env, in, 0, 10000, true)
	if err != nil {
		t.Error("Got error", err)
	}
	fmt.Printf("out = %v\n", out)
	compareResult(t, out, 1, -4, 0, 0, 2, 1, 1)
}
<commit_msg>Add more tests and stop them being noisy<commit_after>package pslq

import (
	"fmt"
	"fp"
	"math"
	"testing"
)

const verbose = false

func compareResult(t *testing.T, actual []int64, expected ...int64) {
	if len(actual) < len(expected) {
		t.Fatalf("lengths wrong of answers got %d expecting %d", len(actual), len(expected))
	}
	for i := range actual {
		var e int64
		if i >= len(expected) {
			e = 0
		} else {
			e = expected[i]

		}
		if actual[i] != e {
			t.Errorf("actual[%d]=%d != expected[%d]=%d", i, &actual[i], i, e)
		}
	}
}

// assert pslq([3*pi+4*e/7, pi, e, log(2)]) == [7, -21, -4, 0]
// assert pslq([4.9999999999999991, 1]) == [1, -5]
// assert pslq([2,1]) == [1, -2]

func TestPslqSimple(t *testing.T) {
	env := fp.NewEnvironment(63)
	//one := float64(1<<60)

	in := make([]fp.FixedPoint, 2)
	in[0].SetInt64(env, 1)
	in[1].SetInt64(env, -2)

	out, err := Pslq(env, in, 0, 0, verbose)
	if err != nil {
		t.Error("Got error", err)
	}
	if verbose {
		fmt.Printf("out = %v\n", out)
	}
	compareResult(t, out, 2, 1)
}

func TestPslq2(t *testing.T) {
	env := fp.NewEnvironment(63)

	inFloat := []float64{
		3*math.Pi + 4*math.E/7,
		math.Pi,
		math.E,
		math.Log(2),
	}
	in := make([]fp.FixedPoint, len(inFloat))
	for i := range inFloat {
		in[i].SetFloat64(env, inFloat[i])
	}
	out, err := Pslq(env, in, 0, 0, verbose)
	if err != nil {
		t.Error("Got error", err)
	}
	if verbose {
		fmt.Printf("out = %v\n", out)
	}
	compareResult(t, out, 7, -21, -4, 0)
}

func TestPslq3(t *testing.T) {
	env := fp.NewEnvironment(63)

	inFloat := []float64{
		3*math.Pi + 4*math.E/7,
		math.Pi,
		math.E,
		math.Log(2),
		0.28917320090206799499,
		0.57591529756863646394,
		0.55698607277729539344,
		0.54073048514703925260,
		0.99835889431176827458,
		0.11551877481656358526,
	}
	in := make([]fp.FixedPoint, len(inFloat))
	for i := range inFloat {
		in[i].SetFloat64(env, inFloat[i])
	}
	out, err := Pslq(env, in, 0, 1000, verbose)
	if err != nil {
		t.Error("Got error", err)
	}
	if verbose {
		fmt.Printf("out = %v\n", out)
	}
	compareResult(t, out, 7, -21, -4, 0, 0, 0, 0, 0, 0, 0)
}

// Evaluates a BBP term
//
// sum(k=0->inf)(1/base**k * (1/a*k + b))
func bbp(env *fp.Environment, base, a, b int64, result *fp.FixedPoint) {
	var term, power, aFp, bFp, _1 fp.FixedPoint
	power.SetInt64(env, 1)
	result.SetInt64(env, 0)
	aFp.SetInt64(env, a)
	bFp.SetInt64(env, b)
	_1.SetInt64(env, 1)
	for k := int64(0); ; k++ {
		term.MulInt64(&aFp, k)
		term.Add(&term, &bFp)
		term.Div(&_1, &term)
		term.Mul(&term, &power)
		if term.Sign() == 0 {
			break
		}
		result.Add(result, &term)
		power.DivInt64(&power, base)
	}
}

func TestPslq4(t *testing.T) {
	env := fp.NewEnvironment(64)

	in := make([]fp.FixedPoint, 8)
	for i := range in {
		if i == 0 {
			in[i].SetFloat64(env, math.Pi)
		} else {
			bbp(env, 16, 8, int64(i), &in[i])
		}
		if verbose {
			fmt.Printf("in[%d] = %d\n", i, &in[i])
		}
	}
	out, err := Pslq(env, in, 0, 1000, verbose)
	if err != nil {
		t.Error("Got error", err)
	}
	if verbose {
		fmt.Printf("out = %v\n", out)
	}
	compareResult(t, out, 1, -4, 0, 0, 2, 1, 1, 0)
}

func TestPslq4a(t *testing.T) {
	env := fp.NewEnvironment(512)

	in := make([]fp.FixedPoint, 5)
	for i := range in {
		if i == 0 {
			pi(env, &in[i])
		} else {
			bbp(env, 10, 5, int64(i), &in[i])
		}
		if verbose {
			fmt.Printf("in[%d] = %d\n", i, &in[i])
		}
	}
	out, err := Pslq(env, in, 1E18, 1000, verbose)
	if err == nil || err.Error() != "could not find an integer relation" {
		t.Errorf("Wrong error %v", err)
	}
	if verbose {
		fmt.Printf("out = %v\n", out)
	}
	if out != nil {
		t.Errorf("Expecting nil out, got %v", out)
	}
}

// out = [44 120 -359 -665 431 -138 248 -166 146 -22 -5 20 339 -563 -606 -89 391 201 351 -31 -5 588 235 -663 183 646 -130 -73 11 167 -31 -788 666 -645 580 -15 -145 -523 -519 532 -169 686 43 80 -387 -234 560 486 285 -318]

func TOOLONGTestPslq4b(t *testing.T) {
	env := fp.NewEnvironment(1024 * 2)

	in := make([]fp.FixedPoint, 50)
	for i := range in {
		if i == 0 {
			pi(env, &in[i])
		} else {
			bbp(env, 100, 50, int64(i), &in[i])
		}
		if verbose {
			fmt.Printf("in[%d] = %d\n", i, &in[i])
		}
	}
	out, err := Pslq(env, in, 1E18, 1E6, verbose)
	if err == nil || err.Error() != "could not find an integer relation" {
		t.Errorf("Wrong error %v", err)
	}
	if verbose {
		fmt.Printf("out = %v\n", out)
	}
	if out != nil {
		t.Errorf("Expecting nil out, got %v", out)
	}
}

// Returns acot(x) in result
func acot(env *fp.Environment, x int64, result *fp.FixedPoint) {
	var term, power fp.FixedPoint
	power.SetInt64(env, 1)
	power.DivInt64(&power, x) // 1/x
	x2 := x * x
	result.SetInt64(env, 0)
	positive := true
	for k := int64(1); ; k += 2 {
		kp := k
		if !positive {
			kp = -k
		}
		positive = !positive
		term.DivInt64(&power, kp)
		if term.Sign() == 0 {
			break
		}
		result.Add(result, &term)
		power.DivInt64(&power, x2)
	}
}

// Returns pi using Machin's formula
func pi(env *fp.Environment, result *fp.FixedPoint) {
	var tmp fp.FixedPoint
	acot(env, 5, &tmp)
	tmp.Lsh(&tmp, 2)
	acot(env, 239, result)
	result.Sub(&tmp, result)
	result.Lsh(result, 2)
}

func TestPslq5(t *testing.T) {
	env := fp.NewEnvironment(64)

	in := make([]fp.FixedPoint, 8)
	in[0].SetFloat64(env, math.Pi)
	acot(env, 2, &in[1])
	acot(env, 4, &in[2])
	acot(env, 6, &in[3])
	acot(env, 7, &in[4])
	acot(env, 8, &in[5])
	acot(env, 9, &in[6])
	acot(env, 10, &in[7])
	out, err := Pslq(env, in, 0, 1000, verbose)
	if err != nil {
		t.Error("Got error", err)
	}
	if verbose {
		fmt.Printf("out = %v\n", out)
	}
	compareResult(t, out, 1, -8, 0, 0, 4, 0, 0, 0)
}

func TestPslq6(t *testing.T) {
	env := fp.NewEnvironment(64)

	in := make([]fp.FixedPoint, 3)
	in[0].SetFloat64(env, math.Pi/4)
	acot(env, 5, &in[1])
	acot(env, 239, &in[2])
	out, err := Pslq(env, in, 0, 1000, verbose)
	if err != nil {
		t.Error("Got error", err)
	}
	if verbose {
		fmt.Printf("out = %v\n", out)
	}
	compareResult(t, out, 1, -4, 1)
}

func TestPslq7(t *testing.T) {
	env := fp.NewEnvironment(64)

	in := make([]fp.FixedPoint, 5)
	in[0].SetFloat64(env, math.Pi/4)
	acot(env, 49, &in[1])
	acot(env, 57, &in[2])
	acot(env, 239, &in[3])
	acot(env, 110443, &in[4])
	out, err := Pslq(env, in, 0, 1000, verbose)
	if err != nil {
		t.Error("Got error", err)
	}
	if verbose {
		fmt.Printf("out = %v\n", out)
	}
	compareResult(t, out, 1, -12, -32, 5, -12)
}

func TestPslq8(t *testing.T) {
	env := fp.NewEnvironment(256)

	in := make([]fp.FixedPoint, 16)
	for i := range in {
		if i == 0 {
			pi(env, &in[i])
		} else {
			bbp(env, 16, 8, int64(i), &in[i])
		}
		if verbose {
			fmt.Printf("in[%d] = %d\n", i, &in[i])
		}
	}
	out, err := Pslq(env, in, 0, 10000, verbose)
	if err != nil {
		t.Error("Got error", err)
	}
	if verbose {
		fmt.Printf("out = %v\n", out)
	}
	compareResult(t, out, 1, -4, 0, 0, 2, 1, 1)
}
<|endoftext|>


<commit_before>package main

import (
	"fmt"
	"github.com/phrase/phraseapp-api-client/Godeps/_workspace/src/gopkg.in/yaml.v2"
	"github.com/phrase/phraseapp-go/phraseapp"
	"os"
	"path"
	"path/filepath"
	"strings"
)

func ConfigPushPull() (*PushPullConfig, error) {
	content, err := ConfigContent()
	if err != nil {
		return nil, err
	}

	return parsePushPullArgs(content)
}

type Path struct {
	UserPath        string
	Separator       string
	AbsPath         string
	Components      []string
	Mode            string
	LocaleSpecified bool
	FormatSpecified bool
}

func (p *Path) RealPath() string {
	return path.Join(p.Separator, p.UserPath, p.Separator)
}

func (p *Path) SubPath(toReplace, replacement string) string {
	return path.Join(p.Separator, strings.Replace(p.UserPath, toReplace, replacement, 0), p.Separator)
}

func PathComponents(userPath string) *Path {
	p := &Path{UserPath: userPath, Separator: string(os.PathSeparator)}

	if strings.HasSuffix(p.UserPath, path.Join("**", "*")) {
		p.Mode = "**/*"
	} else if strings.HasSuffix(p.UserPath, "*") {
		p.Mode = "*"
	} else {
		p.Mode = ""
	}

	p.UserPath = strings.TrimSpace(trimSuffix(p.UserPath, p.Mode))

	split := strings.Split(p.UserPath, p.Separator)
	for _, part := range split {
		if part != p.Separator {
			if !p.LocaleSpecified {
				p.LocaleSpecified = strings.Contains(part, "<locale_name>")
			}
			if !p.FormatSpecified {
				p.FormatSpecified = strings.Contains(part, "<format_name>")
			}
			p.Components = append(p.Components, part)
		}
	}

	return p
}

func PullStrategy(p *Path, params *Params) ([]string, error) {
	files := []string{}
	if p.LocaleSpecified {
		locales, err := phraseapp.LocalesList(params.ProjectId, 1, 25)
		if err != nil {
			return nil, err
		}
		for _, locale := range locales {
			absPath, err := NewLocaleFile(p, locale.Name)
			if err != nil {
				return nil, err
			}
			files = append(files, absPath)
		}
	} else {
		absPath, err := filepath.Abs(p.UserPath)
		if err != nil {
			return nil, err
		}
		switch {
		case p.Mode == "":
			return []string{absPath}, nil

		case p.Mode == "*":
			return singleDirectoryStrategy(absPath, "")

		}
	}

	return files, nil
}

// File handling
func recursiveStrategy(root, fileFormat string) ([]string, error) {
	fileList := []string{}
	err := filepath.Walk(root, func(path string, f os.FileInfo, err error) error {
		if isLocaleFile(f.Name(), fileFormat) {
			fileList = append(fileList, path)
		}
		return nil
	})

	if err != nil {
		return nil, err
	}

	return fileList, nil
}

func singleDirectoryStrategy(root, fileFormat string) ([]string, error) {
	files, err := filepath.Glob(root)
	if err != nil {
		return nil, err
	}
	localeFiles := []string{}
	for _, f := range files {
		if fileFormat != "" {
			if isLocaleFile(f, fileFormat) {
				localeFiles = append(localeFiles, f)
			}
		} else {
			localeFiles = append(localeFiles, f)
		}
	}
	return localeFiles, nil
}

func NewLocaleFile(p *Path, localeName string) (string, error) {
	newPath := p.SubPath("<locale_name>", localeName)

	absPath, err := filepath.Abs(newPath)
	if err != nil {
		return "", err
	}

	err = fileExists(absPath)
	if err != nil {
		absDir := filepath.Dir(absPath)
		os.MkdirAll(absDir, 0644)

		f, err := os.Create(absPath)
		if err != nil {
			return "", err
		}
		defer f.Close()
	}

	return absPath, nil
}

func isLocaleFile(file, extension string) bool {
	fileExtension := fmt.Sprintf(".%s", extension)
	return strings.HasSuffix(file, fileExtension)
}

func trimSuffix(s, suffix string) string {
	if strings.HasSuffix(s, suffix) {
		s = s[:len(s)-len(suffix)]
	}
	return s
}

func fileExists(absPath string) error {
	if _, err := os.Stat(absPath); os.IsNotExist(err) {
		return fmt.Errorf("no such file or directory:", absPath)
	}
	return nil
}

// Parsing
type Params struct {
	File        string
	AccessToken string `yaml:"access_token"`
	ProjectId   string `yaml:"project_id"`
	Format      string
	FormatName  string `yaml:"format_name"`
	LocaleId    string `yaml:"locale_id"`
	Emoji       bool   `yaml:"emoji"`
}

type PushPullConfig struct {
	Phraseapp struct {
		AccessToken string `yaml:"access_token"`
		ProjectId   string `yaml:"project_id"`
		Push        struct {
			Sources []*Params
		}
		Pull struct {
			Targets []*Params
		}
	}
}

func parsePushPullArgs(yml string) (*PushPullConfig, error) {
	var pushPullConfig *PushPullConfig

	err := yaml.Unmarshal([]byte(yml), &pushPullConfig)
	if err != nil {
		return nil, err
	}

	return pushPullConfig, nil
}
<commit_msg>added note because of current Params structure<commit_after>package main

import (
	"fmt"
	"os"
	"path"
	"path/filepath"
	"strings"

	"github.com/phrase/phraseapp-api-client/Godeps/_workspace/src/gopkg.in/yaml.v2"
	"github.com/phrase/phraseapp-go/phraseapp"
)

func ConfigPushPull() (*PushPullConfig, error) {
	content, err := ConfigContent()
	if err != nil {
		return nil, err
	}

	return parsePushPullArgs(content)
}

type Path struct {
	UserPath        string
	Separator       string
	AbsPath         string
	Components      []string
	Mode            string
	LocaleSpecified bool
	FormatSpecified bool
}

func (p *Path) RealPath() string {
	return path.Join(p.Separator, p.UserPath, p.Separator)
}

func (p *Path) SubPath(toReplace, replacement string) string {
	return path.Join(p.Separator, strings.Replace(p.UserPath, toReplace, replacement, 0), p.Separator)
}

func PathComponents(userPath string) *Path {
	p := &Path{UserPath: userPath, Separator: string(os.PathSeparator)}

	if strings.HasSuffix(p.UserPath, path.Join("**", "*")) {
		p.Mode = "**/*"
	} else if strings.HasSuffix(p.UserPath, "*") {
		p.Mode = "*"
	} else {
		p.Mode = ""
	}

	p.UserPath = strings.TrimSpace(trimSuffix(p.UserPath, p.Mode))

	split := strings.Split(p.UserPath, p.Separator)
	for _, part := range split {
		if part != p.Separator {
			if !p.LocaleSpecified {
				p.LocaleSpecified = strings.Contains(part, "<locale_name>")
			}
			if !p.FormatSpecified {
				p.FormatSpecified = strings.Contains(part, "<format_name>")
			}
			p.Components = append(p.Components, part)
		}
	}

	return p
}

func PullStrategy(p *Path, params *Params) ([]string, error) {
	files := []string{}
	if p.LocaleSpecified {
		locales, err := phraseapp.LocalesList(params.ProjectId, 1, 25)
		if err != nil {
			return nil, err
		}
		for _, locale := range locales {
			absPath, err := NewLocaleFile(p, locale.Name)
			if err != nil {
				return nil, err
			}
			files = append(files, absPath)
		}
	} else {
		absPath, err := filepath.Abs(p.UserPath)
		if err != nil {
			return nil, err
		}
		switch {
		case p.Mode == "":
			return []string{absPath}, nil

		case p.Mode == "*":
			return singleDirectoryStrategy(absPath, "")

		}
	}

	return files, nil
}

// File handling
func recursiveStrategy(root, fileFormat string) ([]string, error) {
	fileList := []string{}
	err := filepath.Walk(root, func(path string, f os.FileInfo, err error) error {
		if isLocaleFile(f.Name(), fileFormat) {
			fileList = append(fileList, path)
		}
		return nil
	})

	if err != nil {
		return nil, err
	}

	return fileList, nil
}

func singleDirectoryStrategy(root, fileFormat string) ([]string, error) {
	files, err := filepath.Glob(root)
	if err != nil {
		return nil, err
	}
	localeFiles := []string{}
	for _, f := range files {
		if fileFormat != "" {
			if isLocaleFile(f, fileFormat) {
				localeFiles = append(localeFiles, f)
			}
		} else {
			localeFiles = append(localeFiles, f)
		}
	}
	return localeFiles, nil
}

func NewLocaleFile(p *Path, localeName string) (string, error) {
	newPath := p.SubPath("<locale_name>", localeName)

	absPath, err := filepath.Abs(newPath)
	if err != nil {
		return "", err
	}

	err = fileExists(absPath)
	if err != nil {
		absDir := filepath.Dir(absPath)
		os.MkdirAll(absDir, 0644)

		f, err := os.Create(absPath)
		if err != nil {
			return "", err
		}
		defer f.Close()
	}

	return absPath, nil
}

func isLocaleFile(file, extension string) bool {
	fileExtension := fmt.Sprintf(".%s", extension)
	return strings.HasSuffix(file, fileExtension)
}

func trimSuffix(s, suffix string) string {
	if strings.HasSuffix(s, suffix) {
		s = s[:len(s)-len(suffix)]
	}
	return s
}

func fileExists(absPath string) error {
	if _, err := os.Stat(absPath); os.IsNotExist(err) {
		return fmt.Errorf("no such file or directory:", absPath)
	}
	return nil
}

// @TODO: This is not exactly the specified format. Params only contains params to upload/download. AccessToken, File, ProjectId in top-level struct.
// @TODO: Because of this the naming is bad, see wizard.go for almost desired syntax.
// Parsing
type Params struct {
	File        string
	AccessToken string `yaml:"access_token"`
	ProjectId   string `yaml:"project_id"`
	Format      string
	FormatName  string `yaml:"format_name"`
	LocaleId    string `yaml:"locale_id"`
	Emoji       bool   `yaml:"emoji"`
}

type PushPullConfig struct {
	Phraseapp struct {
		AccessToken string `yaml:"access_token"`
		ProjectId   string `yaml:"project_id"`
		Push        struct {
			Sources []*Params
		}
		Pull struct {
			Targets []*Params
		}
	}
}

func parsePushPullArgs(yml string) (*PushPullConfig, error) {
	var pushPullConfig *PushPullConfig

	err := yaml.Unmarshal([]byte(yml), &pushPullConfig)
	if err != nil {
		return nil, err
	}

	return pushPullConfig, nil
}
<|endoftext|>