<commit_before>/*
 * Network packet analysis framework.
 *
 * Copyright (c) 2014, Alessandro Ghedini
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are
 * met:
 *
 *     * Redistributions of source code must retain the above copyright
 *       notice, this list of conditions and the following disclaimer.
 *
 *     * Redistributions in binary form must reproduce the above copyright
 *       notice, this list of conditions and the following disclaimer in the
 *       documentation and/or other materials provided with the distribution.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
 * IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
 * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
 * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR
 * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
 * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
 * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
 * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
 * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
 * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
 * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 */

// Provides encoding and decoding for ICMPv4 packets.
package icmpv4

import "fmt"

import "github.com/ghedo/go.pkt/packet"
import "github.com/ghedo/go.pkt/packet/ipv4"

type Packet struct {
    Type        Type
    Code        Code
    Checksum    uint16        `string:"sum"`
    Id          uint16
    Seq         uint16
    pkt_payload packet.Packet `cmp:"skip" string:"skip"`
}

type Type uint8
type Code uint8

const (
    EchoReply Type = iota
    Reserved1
    Reserved2
    DstUnreachable
    SrcQuench
    RedirectMsg
    Reserved3
    Reserved4
    EchoRequest
    RouterAdv
    RouterSol
    TimeExceeded
    ParamProblem
    Timestamp
    TimestampReply
    InfoRequest
    InfoReply
    AddrMaskRequest
    AddrMaskReply
)

func Make() *Packet {
    return &Packet{
        Type: EchoRequest,
    }
}

func (p *Packet) GetType() packet.Type {
    return packet.ICMPv4
}

func (p *Packet) GetLength() uint16 {
    return 8
}

func (p *Packet) Equals(other packet.Packet) bool {
    return packet.Compare(p, other)
}

func (p *Packet) Answers(other packet.Packet) bool {
    if other == nil || other.GetType() != packet.ICMPv4 {
        return false
    }

    if (other.(*Packet).Type == EchoRequest && p.Type == EchoReply) ||
       (other.(*Packet).Type == Timestamp && p.Type == TimestampReply) ||
       (other.(*Packet).Type == InfoRequest && p.Type == InfoReply) ||
       (other.(*Packet).Type == AddrMaskRequest && p.Type == AddrMaskReply) {
        return (other.(*Packet).Seq == p.Seq) &&
               (other.(*Packet).Id == p.Id)
    }

    return false
}

func (p *Packet) Pack(buf *packet.Buffer) error {
    buf.WriteN(byte(p.Type))
    buf.WriteN(byte(p.Code))
    buf.WriteN(uint16(0x0000))
    buf.WriteN(p.Id)
    buf.WriteN(p.Seq)

    p.Checksum = ipv4.CalculateChecksum(buf.LayerBytes(), 0)
    buf.PutUint16N(2, p.Checksum)

    return nil
}

func (p *Packet) Unpack(buf *packet.Buffer) error {
    buf.ReadN(&p.Type)
    buf.ReadN(&p.Code)
    buf.ReadN(&p.Checksum)
    buf.ReadN(&p.Id)
    buf.ReadN(&p.Seq)

    /* TODO: data */

    return nil
}

func (p *Packet) Payload() packet.Packet {
    return p.pkt_payload
}

func (p *Packet) GuessPayloadType() packet.Type {
    switch p.Type {
    case DstUnreachable, SrcQuench, RedirectMsg, TimeExceeded, ParamProblem:
        return packet.IPv4
    }

    return packet.None
}

func (p *Packet) SetPayload(pl packet.Packet) error {
    switch p.Type {
    case DstUnreachable, SrcQuench, RedirectMsg, TimeExceeded, ParamProblem:
        p.pkt_payload = pl
    }

    return nil
}

func (p *Packet) InitChecksum(csum uint32) {
}

func (p *Packet) String() string {
    return packet.Stringify(p)
}

func (t Type) String() string {
    switch t {
    case EchoReply:         return "echo-reply"
    case DstUnreachable:    return "dst-unreach"
    case SrcQuench:         return "src-quench"
    case RedirectMsg:       return "redirect"
    case EchoRequest:       return "echo-request"
    case RouterAdv:         return "router-adv"
    case RouterSol:         return "router-sol"
    case TimeExceeded:      return "time-exceeded"
    case ParamProblem:      return "param-problem"
    case Timestamp:         return "timestamp-request"
    case TimestampReply:    return "timestamp-reply"
    case InfoRequest:       return "info-request"
    case InfoReply:         return "info-reply"
    case AddrMaskRequest:   return "addr-mask-request"
    case AddrMaskReply:     return "addr-mask-reply"
    default:                return "unknown"
    }
}

func (c Code) String() string {
    if c != 0 {
        return fmt.Sprintf("%x", uint8(c))
    }

    return ""
}
<commit_msg>icmpv4: fix GetLength() when payload is set<commit_after>/*
 * Network packet analysis framework.
 *
 * Copyright (c) 2014, Alessandro Ghedini
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are
 * met:
 *
 *     * Redistributions of source code must retain the above copyright
 *       notice, this list of conditions and the following disclaimer.
 *
 *     * Redistributions in binary form must reproduce the above copyright
 *       notice, this list of conditions and the following disclaimer in the
 *       documentation and/or other materials provided with the distribution.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
 * IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
 * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
 * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR
 * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
 * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
 * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
 * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
 * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
 * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
 * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 */

// Provides encoding and decoding for ICMPv4 packets.
package icmpv4

import "fmt"

import "github.com/ghedo/go.pkt/packet"
import "github.com/ghedo/go.pkt/packet/ipv4"

type Packet struct {
    Type        Type
    Code        Code
    Checksum    uint16        `string:"sum"`
    Id          uint16
    Seq         uint16
    pkt_payload packet.Packet `cmp:"skip" string:"skip"`
}

type Type uint8
type Code uint8

const (
    EchoReply Type = iota
    Reserved1
    Reserved2
    DstUnreachable
    SrcQuench
    RedirectMsg
    Reserved3
    Reserved4
    EchoRequest
    RouterAdv
    RouterSol
    TimeExceeded
    ParamProblem
    Timestamp
    TimestampReply
    InfoRequest
    InfoReply
    AddrMaskRequest
    AddrMaskReply
)

func Make() *Packet {
    return &Packet{
        Type: EchoRequest,
    }
}

func (p *Packet) GetType() packet.Type {
    return packet.ICMPv4
}

func (p *Packet) GetLength() uint16 {
    if p.pkt_payload != nil {
        return p.pkt_payload.GetLength() + 8
    }

    return 8
}

func (p *Packet) Equals(other packet.Packet) bool {
    return packet.Compare(p, other)
}

func (p *Packet) Answers(other packet.Packet) bool {
    if other == nil || other.GetType() != packet.ICMPv4 {
        return false
    }

    if (other.(*Packet).Type == EchoRequest && p.Type == EchoReply) ||
       (other.(*Packet).Type == Timestamp && p.Type == TimestampReply) ||
       (other.(*Packet).Type == InfoRequest && p.Type == InfoReply) ||
       (other.(*Packet).Type == AddrMaskRequest && p.Type == AddrMaskReply) {
        return (other.(*Packet).Seq == p.Seq) &&
               (other.(*Packet).Id == p.Id)
    }

    return false
}

func (p *Packet) Pack(buf *packet.Buffer) error {
    buf.WriteN(byte(p.Type))
    buf.WriteN(byte(p.Code))
    buf.WriteN(uint16(0x0000))
    buf.WriteN(p.Id)
    buf.WriteN(p.Seq)

    p.Checksum = ipv4.CalculateChecksum(buf.LayerBytes(), 0)
    buf.PutUint16N(2, p.Checksum)

    return nil
}

func (p *Packet) Unpack(buf *packet.Buffer) error {
    buf.ReadN(&p.Type)
    buf.ReadN(&p.Code)
    buf.ReadN(&p.Checksum)
    buf.ReadN(&p.Id)
    buf.ReadN(&p.Seq)

    /* TODO: data */

    return nil
}

func (p *Packet) Payload() packet.Packet {
    return p.pkt_payload
}

func (p *Packet) GuessPayloadType() packet.Type {
    switch p.Type {
    case DstUnreachable, SrcQuench, RedirectMsg, TimeExceeded, ParamProblem:
        return packet.IPv4
    }

    return packet.None
}

func (p *Packet) SetPayload(pl packet.Packet) error {
    switch p.Type {
    case DstUnreachable, SrcQuench, RedirectMsg, TimeExceeded, ParamProblem:
        p.pkt_payload = pl
    }

    return nil
}

func (p *Packet) InitChecksum(csum uint32) {
}

func (p *Packet) String() string {
    return packet.Stringify(p)
}

func (t Type) String() string {
    switch t {
    case EchoReply:         return "echo-reply"
    case DstUnreachable:    return "dst-unreach"
    case SrcQuench:         return "src-quench"
    case RedirectMsg:       return "redirect"
    case EchoRequest:       return "echo-request"
    case RouterAdv:         return "router-adv"
    case RouterSol:         return "router-sol"
    case TimeExceeded:      return "time-exceeded"
    case ParamProblem:      return "param-problem"
    case Timestamp:         return "timestamp-request"
    case TimestampReply:    return "timestamp-reply"
    case InfoRequest:       return "info-request"
    case InfoReply:         return "info-reply"
    case AddrMaskRequest:   return "addr-mask-request"
    case AddrMaskReply:     return "addr-mask-reply"
    default:                return "unknown"
    }
}

func (c Code) String() string {
    if c != 0 {
        return fmt.Sprintf("%x", uint8(c))
    }

    return ""
}
<|endoftext|>


<commit_before>package cryptanalysis

import (
	"strings"
)

func BreakSingleByteXor(data []byte) (float64, byte, string) {
	low := 1000.0
	msg := ""
	key := byte(0)

	// Bruteforce the key by XORing each possible key, analyzing the decrypted
	// message, and scoring it. Lowest score wins.
	for i := 0; i < 256; i++ {
		k := byte(i)
		dec := XorArrayByte(data, k)
		str := strings.ToLower(string(dec))
		score := ScoreEnglish(str)

		if score < low {
			low = score
			msg = string(dec)
			key = k
		}
	}

	return low, key, msg
}
<commit_msg>Move conversion to lowercase into Score function.<commit_after>package cryptanalysis

import (
)

func BreakSingleByteXor(data []byte) (float64, byte, string) {
	low := 1000.0
	msg := ""
	key := byte(0)

	// Bruteforce the key by XORing each possible key, analyzing the decrypted
	// message, and scoring it. Lowest score wins.
	for i := 0; i < 256; i++ {
		k := byte(i)
		dec := XorArrayByte(data, k)
		score := ScoreEnglish(string(dec))

		if score < low {
			low = score
			msg = string(dec)
			key = k
		}
	}

	return low, key, msg
}
<|endoftext|>


<commit_before>package main

import (
	"io/ioutil"
	"os"
	"sort"
	"sync"

	"gopkg.in/yaml.v2"
)

// TODO: Refactoring
type iconsYaml struct {
	Icons icons
}

type icons []icon

func newIcons() icons {
	p := iconsYamlPath()
	b, _ := iconsReadYaml(p)      // FIXME: error handling
	y, _ := iconsUnmarshalYaml(b) // FIXME: error handling

	return y.Icons.Sort()
}

func iconsYamlPath() string {
	path := os.Getenv("FAW_ICONS_YAML_PATH") // for test env
	if path == "" {
		path = "icons.yml" // default
	}

	return path
}

func iconsReadYaml(path string) ([]byte, error) {
	return ioutil.ReadFile(path)
}

func iconsUnmarshalYaml(b []byte) (iconsYaml, error) {
	var y iconsYaml
	err := yaml.Unmarshal([]byte(b), &y)
	return y, err
}

func (ics icons) find(terms []string) icons {
	var foundIcons icons
	var wg sync.WaitGroup

	for _, ic := range ics {
		wg.Add(1)
		go func(ic icon) {
			if ic.contains(terms) {
				foundIcons = append(foundIcons, ic)
			}
			wg.Done()
		}(ic)
	}
	wg.Wait()

	return foundIcons
}

// Len for sort
func (ics icons) Len() int {
	return len(ics)
}

// Less for sort
func (ics icons) Less(i, j int) bool {
	return ics[i].ID < ics[j].ID
}

// Swap for sort
func (ics icons) Swap(i, j int) {
	ics[i], ics[j] = ics[j], ics[i]
}

func (ics icons) Sort() icons {
	sort.Sort(ics)
	return ics
}
<commit_msg>Revert "Add goroutine to icons#find()"<commit_after>package main

import (
	"io/ioutil"
	"os"
	"sort"

	"gopkg.in/yaml.v2"
)

// TODO: Refactoring
type iconsYaml struct {
	Icons icons
}

type icons []icon

func newIcons() icons {
	p := iconsYamlPath()
	b, _ := iconsReadYaml(p)      // FIXME: error handling
	y, _ := iconsUnmarshalYaml(b) // FIXME: error handling

	return y.Icons.Sort()
}

func iconsYamlPath() string {
	path := os.Getenv("FAW_ICONS_YAML_PATH") // for test env
	if path == "" {
		path = "icons.yml" // default
	}

	return path
}

func iconsReadYaml(path string) ([]byte, error) {
	return ioutil.ReadFile(path)
}

func iconsUnmarshalYaml(b []byte) (iconsYaml, error) {
	var y iconsYaml
	err := yaml.Unmarshal([]byte(b), &y)
	return y, err
}

func (ics icons) find(terms []string) icons {
	var foundIcons icons

	for _, ic := range ics {
		if ic.contains(terms) {
			foundIcons = append(foundIcons, ic)
		}
	}

	return foundIcons
}

// Len for sort
func (ics icons) Len() int {
	return len(ics)
}

// Less for sort
func (ics icons) Less(i, j int) bool {
	return ics[i].ID < ics[j].ID
}

// Swap for sort
func (ics icons) Swap(i, j int) {
	ics[i], ics[j] = ics[j], ics[i]
}

func (ics icons) Sort() icons {
	sort.Sort(ics)
	return ics
}
<|endoftext|>


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

package convert

import (
	"io"
	"math"

	"github.com/hajimehoshi/ebiten/audio"
	"github.com/hajimehoshi/ebiten/internal/web"
)

func sinc(x float64) float64 {
	if x == 0 {
		return 1
	}
	return math.Sin(x) / x
}

type Resampling struct {
	source       audio.ReadSeekCloser
	size         int64
	from         int
	to           int
	pos          int64
	srcBlock     int64
	srcBufL      map[int64][]float64
	srcBufR      map[int64][]float64
	lruSrcBlocks []int64
}

const resamplingBufferSize = 4096

func NewResampling(source audio.ReadSeekCloser, size int64, from, to int) *Resampling {
	r := &Resampling{
		source:   source,
		size:     size,
		from:     from,
		to:       to,
		srcBlock: -1,
		srcBufL:  map[int64][]float64{},
		srcBufR:  map[int64][]float64{},
	}
	return r
}

func (r *Resampling) Size() int64 {
	s := int64(float64(r.size) * float64(r.to) / float64(r.from))
	return s / 4 * 4
}

func (r *Resampling) src(i int) (float64, float64, error) {
	// Use int here since int64 is very slow on browsers.
	// TODO: Resampling is too heavy on browsers. How about using OfflineAudioContext?
	if i < 0 {
		return 0, 0, nil
	}
	if r.size/4 <= int64(i) {
		return 0, 0, nil
	}
	nextPos := int64(i) / resamplingBufferSize
	if _, ok := r.srcBufL[nextPos]; !ok {
		if r.srcBlock+1 != nextPos {
			if _, err := r.source.Seek(nextPos*resamplingBufferSize*4, io.SeekStart); err != nil {
				return 0, 0, err
			}
		}
		buf := make([]uint8, resamplingBufferSize*4)
		c := 0
		for c < len(buf) {
			n, err := r.source.Read(buf[c:])
			c += n
			if err != nil {
				if err == io.EOF {
					break
				}
				return 0, 0, err
			}
		}
		buf = buf[:c]
		sl := make([]float64, resamplingBufferSize)
		sr := make([]float64, resamplingBufferSize)
		for i := 0; i < len(buf)/4; i++ {
			sl[i] = float64(int16(buf[4*i])|(int16(buf[4*i+1])<<8)) / (1<<15 - 1)
			sr[i] = float64(int16(buf[4*i+2])|(int16(buf[4*i+3])<<8)) / (1<<15 - 1)
		}
		r.srcBlock = nextPos
		r.srcBufL[r.srcBlock] = sl
		r.srcBufR[r.srcBlock] = sr
		// To keep srcBufL/R not too big, let's remove the least used buffers.
		if len(r.lruSrcBlocks) >= 4 {
			p := r.lruSrcBlocks[0]
			delete(r.srcBufL, p)
			delete(r.srcBufR, p)
			r.lruSrcBlocks = r.lruSrcBlocks[1:]
		}
		r.lruSrcBlocks = append(r.lruSrcBlocks, r.srcBlock)
	} else {
		r.srcBlock = nextPos
		idx := -1
		for i, p := range r.lruSrcBlocks {
			if p == r.srcBlock {
				idx = i
				break
			}
		}
		if idx == -1 {
			panic("not reach")
		}
		r.lruSrcBlocks = append(r.lruSrcBlocks[:idx], r.lruSrcBlocks[idx+1:]...)
		r.lruSrcBlocks = append(r.lruSrcBlocks, r.srcBlock)
	}
	ii := i % resamplingBufferSize
	return r.srcBufL[r.srcBlock][ii], r.srcBufR[r.srcBlock][ii], nil
}

func (r *Resampling) at(t int64) (float64, float64, error) {
	windowSize := 8.0
	if web.IsBrowser() {
		windowSize = 4.0
	}
	tInSrc := float64(t) * float64(r.from) / float64(r.to)
	startN := tInSrc - windowSize
	if startN < 0 {
		startN = 0
	}
	if float64(r.size/4) <= startN {
		startN = float64(r.size/4) - 1
	}
	endN := tInSrc + windowSize + 1
	if float64(r.size/4) <= endN {
		endN = float64(r.size/4) - 1
	}
	lv := 0.0
	rv := 0.0
	for n := startN; n < endN; n++ {
		srcL, srcR, err := r.src(int(n))
		if err != nil {
			return 0, 0, err
		}
		w := 0.5 + 0.5*math.Cos(2*math.Pi*(tInSrc-n)/(windowSize*2+1))
		s := sinc(math.Pi*(tInSrc-n)) * w
		lv += srcL * s
		rv += srcR * s
	}
	if lv < -1 {
		lv = -1
	}
	if lv > 1 {
		lv = 1
	}
	if rv < -1 {
		rv = -1
	}
	if rv > 1 {
		rv = 1
	}
	return lv, rv, nil
}

func (r *Resampling) Read(b []uint8) (int, error) {
	if r.pos == r.Size() {
		return 0, io.EOF
	}
	n := len(b) / 4 * 4
	if r.Size()-r.pos <= int64(n) {
		n = int(r.Size() - r.pos)
	}
	for i := 0; i < n/4; i++ {
		l, r, err := r.at(r.pos/4 + int64(i))
		if err != nil {
			return 0, err
		}
		l16 := int16(l * (1<<15 - 1))
		r16 := int16(r * (1<<15 - 1))
		b[4*i] = uint8(l16)
		b[4*i+1] = uint8(l16 >> 8)
		b[4*i+2] = uint8(r16)
		b[4*i+3] = uint8(r16 >> 8)
	}
	r.pos += int64(n)
	return n, nil
}

func (r *Resampling) Seek(offset int64, whence int) (int64, error) {
	switch whence {
	case io.SeekStart:
		r.pos = offset
	case io.SeekCurrent:
		r.pos += offset
	case io.SeekEnd:
		r.pos += r.Size() + offset
	}
	if r.pos < 0 {
		r.pos = 0
	}
	if r.Size() <= r.pos {
		r.pos = r.Size()
	}
	return r.pos, nil
}

func (r *Resampling) Close() error {
	return r.source.Close()
}
<commit_msg>audio/internal/convert: Change the window smaller for performance<commit_after>// Copyright 2017 The Ebiten Authors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

package convert

import (
	"io"
	"math"

	"github.com/hajimehoshi/ebiten/audio"
	"github.com/hajimehoshi/ebiten/internal/web"
)

func sinc(x float64) float64 {
	if x == 0 {
		return 1
	}
	return math.Sin(x) / x
}

type Resampling struct {
	source       audio.ReadSeekCloser
	size         int64
	from         int
	to           int
	pos          int64
	srcBlock     int64
	srcBufL      map[int64][]float64
	srcBufR      map[int64][]float64
	lruSrcBlocks []int64
}

const resamplingBufferSize = 4096

func NewResampling(source audio.ReadSeekCloser, size int64, from, to int) *Resampling {
	r := &Resampling{
		source:   source,
		size:     size,
		from:     from,
		to:       to,
		srcBlock: -1,
		srcBufL:  map[int64][]float64{},
		srcBufR:  map[int64][]float64{},
	}
	return r
}

func (r *Resampling) Size() int64 {
	s := int64(float64(r.size) * float64(r.to) / float64(r.from))
	return s / 4 * 4
}

func (r *Resampling) src(i int) (float64, float64, error) {
	// Use int here since int64 is very slow on browsers.
	// TODO: Resampling is too heavy on browsers. How about using OfflineAudioContext?
	if i < 0 {
		return 0, 0, nil
	}
	if r.size/4 <= int64(i) {
		return 0, 0, nil
	}
	nextPos := int64(i) / resamplingBufferSize
	if _, ok := r.srcBufL[nextPos]; !ok {
		if r.srcBlock+1 != nextPos {
			if _, err := r.source.Seek(nextPos*resamplingBufferSize*4, io.SeekStart); err != nil {
				return 0, 0, err
			}
		}
		buf := make([]uint8, resamplingBufferSize*4)
		c := 0
		for c < len(buf) {
			n, err := r.source.Read(buf[c:])
			c += n
			if err != nil {
				if err == io.EOF {
					break
				}
				return 0, 0, err
			}
		}
		buf = buf[:c]
		sl := make([]float64, resamplingBufferSize)
		sr := make([]float64, resamplingBufferSize)
		for i := 0; i < len(buf)/4; i++ {
			sl[i] = float64(int16(buf[4*i])|(int16(buf[4*i+1])<<8)) / (1<<15 - 1)
			sr[i] = float64(int16(buf[4*i+2])|(int16(buf[4*i+3])<<8)) / (1<<15 - 1)
		}
		r.srcBlock = nextPos
		r.srcBufL[r.srcBlock] = sl
		r.srcBufR[r.srcBlock] = sr
		// To keep srcBufL/R not too big, let's remove the least used buffers.
		if len(r.lruSrcBlocks) >= 4 {
			p := r.lruSrcBlocks[0]
			delete(r.srcBufL, p)
			delete(r.srcBufR, p)
			r.lruSrcBlocks = r.lruSrcBlocks[1:]
		}
		r.lruSrcBlocks = append(r.lruSrcBlocks, r.srcBlock)
	} else {
		r.srcBlock = nextPos
		idx := -1
		for i, p := range r.lruSrcBlocks {
			if p == r.srcBlock {
				idx = i
				break
			}
		}
		if idx == -1 {
			panic("not reach")
		}
		r.lruSrcBlocks = append(r.lruSrcBlocks[:idx], r.lruSrcBlocks[idx+1:]...)
		r.lruSrcBlocks = append(r.lruSrcBlocks, r.srcBlock)
	}
	ii := i % resamplingBufferSize
	return r.srcBufL[r.srcBlock][ii], r.srcBufR[r.srcBlock][ii], nil
}

func (r *Resampling) at(t int64) (float64, float64, error) {
	windowSize := 4.0
	tInSrc := float64(t) * float64(r.from) / float64(r.to)
	startN := tInSrc - windowSize
	if startN < 0 {
		startN = 0
	}
	if float64(r.size/4) <= startN {
		startN = float64(r.size/4) - 1
	}
	endN := tInSrc + windowSize + 1
	if float64(r.size/4) <= endN {
		endN = float64(r.size/4) - 1
	}
	lv := 0.0
	rv := 0.0
	for n := startN; n < endN; n++ {
		srcL, srcR, err := r.src(int(n))
		if err != nil {
			return 0, 0, err
		}
		w := 0.5 + 0.5*math.Cos(2*math.Pi*(tInSrc-n)/(windowSize*2+1))
		s := sinc(math.Pi*(tInSrc-n)) * w
		lv += srcL * s
		rv += srcR * s
	}
	if lv < -1 {
		lv = -1
	}
	if lv > 1 {
		lv = 1
	}
	if rv < -1 {
		rv = -1
	}
	if rv > 1 {
		rv = 1
	}
	return lv, rv, nil
}

func (r *Resampling) Read(b []uint8) (int, error) {
	if r.pos == r.Size() {
		return 0, io.EOF
	}
	n := len(b) / 4 * 4
	if r.Size()-r.pos <= int64(n) {
		n = int(r.Size() - r.pos)
	}
	for i := 0; i < n/4; i++ {
		l, r, err := r.at(r.pos/4 + int64(i))
		if err != nil {
			return 0, err
		}
		l16 := int16(l * (1<<15 - 1))
		r16 := int16(r * (1<<15 - 1))
		b[4*i] = uint8(l16)
		b[4*i+1] = uint8(l16 >> 8)
		b[4*i+2] = uint8(r16)
		b[4*i+3] = uint8(r16 >> 8)
	}
	r.pos += int64(n)
	return n, nil
}

func (r *Resampling) Seek(offset int64, whence int) (int64, error) {
	switch whence {
	case io.SeekStart:
		r.pos = offset
	case io.SeekCurrent:
		r.pos += offset
	case io.SeekEnd:
		r.pos += r.Size() + offset
	}
	if r.pos < 0 {
		r.pos = 0
	}
	if r.Size() <= r.pos {
		r.pos = r.Size()
	}
	return r.pos, nil
}

func (r *Resampling) Close() error {
	return r.source.Close()
}
<|endoftext|>


<commit_before>// Copyright 2013 Michael Yang. All rights reserved.
// Use of this source code is governed by a MIT-style
// license that can be found in the LICENSE file.
package id3

import (
	"fmt"
	"io"
)

const (
	HeaderSize = 10
)

type Tag struct {
	Header
	Frames map[string][]Framer
}

func NewTag(reader io.Reader) *Tag {
	t := &Tag{NewHeader(reader), make(map[string][]Framer)}
	if t.Header == nil {
		return nil
	}

	var frame Framer
	for size := t.Header.Size(); size > 0; {
		switch t.Header.Version() {
		case "2.3":
			frame = NewV3Frame(reader)
		default:
			frame = NewV3Frame(reader)
		}

		if frame == nil {
			break
		}

		id := frame.Id()
		t.Frames[id] = append(t.Frames[id], frame)

		size -= frame.Size()
	}

	return t
}

func (t Tag) Bytes() []byte {
	data := make([]byte, t.Size())

	index := 0
	for _, v := range t.Frames {
		for _, f := range v {
			size := FrameHeaderSize + f.Size()

			switch t.Header.Version() {
			case "2.3":
				copy(data[index:index+size], V3Bytes(f))
			default:
				copy(data[index:index+size], V3Bytes(f))
			}

			index += size
		}
	}

	return append(t.Header.Bytes(), data...)
}

type Header interface {
	Version() string
	Size() int
	Bytes() []byte
}

func NewHeader(reader io.Reader) Header {
	data := make([]byte, HeaderSize)
	n, err := io.ReadFull(reader, data)
	if n < HeaderSize || err != nil || string(data[:3]) != "ID3" {
		return nil
	}

	size, err := synchint(data[6:])
	if err != nil {
		return nil
	}

	return Head{
		version:  data[3],
		revision: data[4],
		flags:    data[5],
		size:     size,
	}
}

type Head struct {
	version, revision byte
	flags             byte
	size              int32
}

func (h Head) Version() string {
	return fmt.Sprintf("%d.%d", h.version, h.revision)
}

func (h Head) Size() int {
	return int(h.size)
}

func (h Head) Bytes() []byte {
	data := make([]byte, HeaderSize)

	copy(data[:3], []byte("ID3"))
	copy(data[6:], synchbytes(h.size))
	data[3] = h.version
	data[4] = h.revision
	data[5] = h.flags

	return data
}
<commit_msg>Fix version format<commit_after>// Copyright 2013 Michael Yang. All rights reserved.
// Use of this source code is governed by a MIT-style
// license that can be found in the LICENSE file.
package id3

import (
	"fmt"
	"io"
)

const (
	HeaderSize = 10
)

type Tag struct {
	Header
	Frames map[string][]Framer
}

func NewTag(reader io.Reader) *Tag {
	t := &Tag{NewHeader(reader), make(map[string][]Framer)}
	if t.Header == nil {
		return nil
	}

	var frame Framer
	for size := t.Header.Size(); size > 0; {
		switch t.Header.Version() {
		case "2.3.0":
			frame = NewV3Frame(reader)
		default:
			frame = NewV3Frame(reader)
		}

		if frame == nil {
			break
		}

		id := frame.Id()
		t.Frames[id] = append(t.Frames[id], frame)

		size -= frame.Size()
	}

	return t
}

func (t Tag) Bytes() []byte {
	data := make([]byte, t.Size())

	index := 0
	for _, v := range t.Frames {
		for _, f := range v {
			size := FrameHeaderSize + f.Size()

			switch t.Header.Version() {
			case "2.3":
				copy(data[index:index+size], V3Bytes(f))
			default:
				copy(data[index:index+size], V3Bytes(f))
			}

			index += size
		}
	}

	return append(t.Header.Bytes(), data...)
}

type Header interface {
	Version() string
	Size() int
	Bytes() []byte
}

func NewHeader(reader io.Reader) Header {
	data := make([]byte, HeaderSize)
	n, err := io.ReadFull(reader, data)
	if n < HeaderSize || err != nil || string(data[:3]) != "ID3" {
		return nil
	}

	size, err := synchint(data[6:])
	if err != nil {
		return nil
	}

	return Head{
		version:  data[3],
		revision: data[4],
		flags:    data[5],
		size:     size,
	}
}

type Head struct {
	version, revision byte
	flags             byte
	size              int32
}

func (h Head) Version() string {
	return fmt.Sprintf("2.%d.%d", h.version, h.revision)
}

func (h Head) Size() int {
	return int(h.size)
}

func (h Head) Bytes() []byte {
	data := make([]byte, HeaderSize)

	copy(data[:3], []byte("ID3"))
	copy(data[6:], synchbytes(h.size))
	data[3] = h.version
	data[4] = h.revision
	data[5] = h.flags

	return data
}
<|endoftext|>


<commit_before>package main

import "encoding/json"
import "flag"
import "fmt"
import "io/ioutil"
import "math/rand"
import "time"
import "os"
import "runtime"
import "runtime/pprof"

func main() {
	numRenderJobs := flag.Int(
		"j", runtime.NumCPU(), "how many render jobs to spawn")

	profilePath := flag.String(
		"p", "", "if non-empty, path to write the cpu profile to")

	flag.Parse()

	if len(*profilePath) > 0 {
		f, err := os.Create(*profilePath)
		if err != nil {
			panic(err)
		}
		defer func() {
			if err := f.Close(); err != nil {
				panic(err)
			}
		}()

		pprof.StartCPUProfile(f)
		defer pprof.StopCPUProfile()
	}

	runtime.GOMAXPROCS(*numRenderJobs)

	seed := time.Now().UTC().UnixNano()
	rng := rand.New(rand.NewSource(seed))

	if flag.NArg() < 1 {
		fmt.Fprintf(
			os.Stderr, "%s [options] [scene.json...]\n",
			os.Args[0])
		flag.PrintDefaults()
		os.Exit(-1)
	}

	for i := 0; i < flag.NArg(); i++ {
		inputPath := flag.Arg(i)
		fmt.Printf(
			"Processing %s (%d/%d)...\n",
			inputPath, i+1, flag.NArg())
		configBytes, err := ioutil.ReadFile(inputPath)
		if err != nil {
			panic(err)
		}
		var config map[string]interface{}
		err = json.Unmarshal(configBytes, &config)
		if err != nil {
			panic(err)
		}
		sceneConfig := config["scene"].(map[string]interface{})
		scene := MakeScene(sceneConfig)
		rendererConfig := config["renderer"].(map[string]interface{})
		renderer := MakeRenderer(rendererConfig)
		renderer.Render(*numRenderJobs, rng, &scene)
	}
}
<commit_msg>Make ilium look at the extension of the input file to figure out what to do<commit_after>package main

import "encoding/json"
import "flag"
import "fmt"
import "io/ioutil"
import "math/rand"
import "time"
import "os"
import "path/filepath"
import "runtime"
import "runtime/pprof"

func processSceneFile(rng *rand.Rand, scenePath string, numRenderJobs int) {
	configBytes, err := ioutil.ReadFile(scenePath)
	if err != nil {
		panic(err)
	}
	var config map[string]interface{}
	err = json.Unmarshal(configBytes, &config)
	if err != nil {
		panic(err)
	}
	sceneConfig := config["scene"].(map[string]interface{})
	scene := MakeScene(sceneConfig)
	rendererConfig := config["renderer"].(map[string]interface{})
	renderer := MakeRenderer(rendererConfig)
	renderer.Render(numRenderJobs, rng, &scene)
}

func main() {
	numRenderJobs := flag.Int(
		"j", runtime.NumCPU(), "how many render jobs to spawn")

	profilePath := flag.String(
		"p", "", "if non-empty, path to write the cpu profile to")

	flag.Parse()

	if len(*profilePath) > 0 {
		f, err := os.Create(*profilePath)
		if err != nil {
			panic(err)
		}
		defer func() {
			if err := f.Close(); err != nil {
				panic(err)
			}
		}()

		pprof.StartCPUProfile(f)
		defer pprof.StopCPUProfile()
	}

	runtime.GOMAXPROCS(*numRenderJobs)

	seed := time.Now().UTC().UnixNano()
	rng := rand.New(rand.NewSource(seed))

	if flag.NArg() < 1 {
		fmt.Fprintf(
			os.Stderr, "%s [options] [scene.json...]\n",
			os.Args[0])
		flag.PrintDefaults()
		os.Exit(-1)
	}

	for i := 0; i < flag.NArg(); i++ {
		inputPath := flag.Arg(i)
		fmt.Printf(
			"Processing %s (%d/%d)...\n",
			inputPath, i+1, flag.NArg())
		extension := filepath.Ext(inputPath)
		switch extension {
		case ".json":
			processSceneFile(rng, inputPath, *numRenderJobs)
		default:
			panic("Unknown extension: " + extension)
		}
	}
}
<|endoftext|>


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

package docker

import (
	"bytes"
	"encoding/base64"
	"encoding/json"
	"errors"
	"fmt"
	"io"
	"io/ioutil"
	"net/http"
	"net/url"
	"os"
	"time"
)

// APIImages represent an image returned in the ListImages call.
type APIImages struct {
	ID          string   `json:"Id"`
	RepoTags    []string `json:",omitempty"`
	Created     int64
	Size        int64
	VirtualSize int64
	ParentId    string `json:",omitempty"`
	Repository  string `json:",omitempty"`
	Tag         string `json:",omitempty"`
}

type Image struct {
	ID              string    `json:"id"`
	Parent          string    `json:"parent,omitempty"`
	Comment         string    `json:"comment,omitempty"`
	Created         time.Time `json:"created"`
	Container       string    `json:"container,omitempty"`
	ContainerConfig Config    `json:"containerconfig,omitempty"`
	DockerVersion   string    `json:"dockerversion,omitempty"`
	Author          string    `json:"author,omitempty"`
	Config          *Config   `json:"config,omitempty"`
	Architecture    string    `json:"architecture,omitempty"`
	Size            int64
}

type ImagePre012 struct {
	ID              string    `json:"id"`
	Parent          string    `json:"parent,omitempty"`
	Comment         string    `json:"comment,omitempty"`
	Created         time.Time `json:"created"`
	Container       string    `json:"container,omitempty"`
	ContainerConfig Config    `json:"container_config,omitempty"`
	DockerVersion   string    `json:"docker_version,omitempty"`
	Author          string    `json:"author,omitempty"`
	Config          *Config   `json:"config,omitempty"`
	Architecture    string    `json:"architecture,omitempty"`
	Size            int64
}

var (
	// ErrNoSuchImage is the error returned when the image does not exist.
	ErrNoSuchImage = errors.New("no such image")

	// ErrMissingRepo is the error returned when the remote repository is
	// missing.
	ErrMissingRepo = errors.New("missing remote repository e.g. 'github.com/user/repo'")

	// ErrMissingOutputStream is the error returned when no output stream
	// is provided to some calls, like BuildImage.
	ErrMissingOutputStream = errors.New("missing output stream")
)

// ListImages returns the list of available images in the server.
//
// See http://goo.gl/dkMrwP for more details.
func (c *Client) ListImages(all bool) ([]APIImages, error) {
	path := "/images/json?all="
	if all {
		path += "1"
	} else {
		path += "0"
	}
	body, _, err := c.do("GET", path, nil)
	if err != nil {
		return nil, err
	}
	var images []APIImages
	err = json.Unmarshal(body, &images)
	if err != nil {
		return nil, err
	}
	return images, nil
}

// RemoveImage removes an image by its name or ID.
//
// See http://goo.gl/7hjHHy for more details.
func (c *Client) RemoveImage(name string) error {
	_, status, err := c.do("DELETE", "/images/"+name, nil)
	if status == http.StatusNotFound {
		return ErrNoSuchImage
	}
	return err
}

// InspectImage returns an image by its name or ID.
//
// See http://goo.gl/pHEbma for more details.
func (c *Client) InspectImage(name string) (*Image, error) {
	body, status, err := c.do("GET", "/images/"+name+"/json", nil)
	if status == http.StatusNotFound {
		return nil, ErrNoSuchImage
	}
	if err != nil {
		return nil, err
	}

	var image Image

	// if the caller elected to skip checking the server's version, assume it's the latest
	if c.SkipServerVersionCheck || c.expectedApiVersion.GreaterThanOrEqualTo(apiVersion_1_12) {
		err = json.Unmarshal(body, &image)
		if err != nil {
			return nil, err
		}
	} else {
		var imagePre012 ImagePre012
		err = json.Unmarshal(body, &imagePre012)
		if err != nil {
			return nil, err
		}

		image.ID = imagePre012.ID
		image.Parent = imagePre012.Parent
		image.Comment = imagePre012.Comment
		image.Created = imagePre012.Created
		image.Container = imagePre012.Container
		image.ContainerConfig = imagePre012.ContainerConfig
		image.DockerVersion = imagePre012.DockerVersion
		image.Author = imagePre012.Author
		image.Config = imagePre012.Config
		image.Architecture = imagePre012.Architecture
		image.Size = imagePre012.Size
	}

	return &image, nil
}

// PushImageOptions represents options to use in the PushImage method.
//
// See http://goo.gl/GBmyhc for more details.
type PushImageOptions struct {
	// Name of the image
	Name string

	// Registry server to push the image
	Registry string

	OutputStream io.Writer `qs:"-"`
}

// AuthConfiguration represents authentication options to use in the PushImage
// method. It represents the authencation in the Docker index server.
type AuthConfiguration struct {
	Username string `json:"username,omitempty"`
	Password string `json:"password,omitempty"`
	Email    string `json:"email,omitempty"`
}

// PushImage pushes an image to a remote registry, logging progress to w.
//
// An empty instance of AuthConfiguration may be used for unauthenticated
// pushes.
//
// See http://goo.gl/GBmyhc for more details.
func (c *Client) PushImage(opts PushImageOptions, auth AuthConfiguration) error {
	if opts.Name == "" {
		return ErrNoSuchImage
	}
	name := opts.Name
	opts.Name = ""
	path := "/images/" + name + "/push?" + queryString(&opts)
	var headers = make(map[string]string)
	var buf bytes.Buffer
	json.NewEncoder(&buf).Encode(auth)

	headers["X-Registry-Auth"] = base64.URLEncoding.EncodeToString(buf.Bytes())

	return c.stream("POST", path, true, headers, nil, opts.OutputStream, nil)
}

// PullImageOptions present the set of options available for pulling an image
// from a registry.
//
// See http://goo.gl/PhBKnS for more details.
type PullImageOptions struct {
	Repository   string `qs:"fromImage"`
	Registry     string
	Tag          string
	OutputStream io.Writer `qs:"-"`
}

// PullImage pulls an image from a remote registry, logging progress to w.
//
// See http://goo.gl/PhBKnS for more details.
func (c *Client) PullImage(opts PullImageOptions, auth AuthConfiguration) error {
	if opts.Repository == "" {
		return ErrNoSuchImage
	}

	var headers = make(map[string]string)
	var buf bytes.Buffer
	json.NewEncoder(&buf).Encode(auth)
	headers["X-Registry-Auth"] = base64.URLEncoding.EncodeToString(buf.Bytes())

	return c.createImage(queryString(&opts), headers, nil, opts.OutputStream)
}

func (c *Client) createImage(qs string, headers map[string]string, in io.Reader, w io.Writer) error {
	path := "/images/create?" + qs
	return c.stream("POST", path, true, headers, in, w, nil)
}

// ImportImageOptions present the set of informations available for importing
// an image from a source file or the stdin.
//
// See http://goo.gl/PhBKnS for more details.
type ImportImageOptions struct {
	Repository string `qs:"repo"`
	Source     string `qs:"fromSrc"`
	Tag        string `qs:"tag"`

	InputStream  io.Reader `qs:"-"`
	OutputStream io.Writer `qs:"-"`
}

// ImportImage imports an image from a url, a file or stdin
//
// See http://goo.gl/PhBKnS for more details.
func (c *Client) ImportImage(opts ImportImageOptions) error {
	if opts.Repository == "" {
		return ErrNoSuchImage
	}
	if opts.Source != "-" {
		opts.InputStream = nil
	}
	if opts.Source != "-" && !isURL(opts.Source) {
		f, err := os.Open(opts.Source)
		if err != nil {
			return err
		}
		b, err := ioutil.ReadAll(f)
		opts.InputStream = bytes.NewBuffer(b)
		opts.Source = "-"
	}
	return c.createImage(queryString(&opts), nil, opts.InputStream, opts.OutputStream)
}

// BuildImageOptions present the set of informations available for building
// an image from a tarfile with a Dockerfile in it,the details about Dockerfile
// see http://docs.docker.io/en/latest/reference/builder/
type BuildImageOptions struct {
	Name           string    `qs:"t"`
	NoCache        bool      `qs:"nocache"`
	SuppressOutput bool      `qs:"q"`
	RmTmpContainer bool      `qs:"rm"`
	InputStream    io.Reader `qs:"-"`
	OutputStream   io.Writer `qs:"-"`
	Remote         string    `qs:"remote"`
}

// BuildImage builds an image from a tarball's url or a Dockerfile in the input
// stream.
func (c *Client) BuildImage(opts BuildImageOptions) error {
	if opts.OutputStream == nil {
		return ErrMissingOutputStream
	}
	var headers map[string]string
	if opts.Remote != "" && opts.Name == "" {
		opts.Name = opts.Remote
	}
	if opts.InputStream != nil {
		headers = map[string]string{"Content-Type": "application/tar"}
	} else if opts.Remote == "" {
		return ErrMissingRepo
	}
	return c.stream("POST", fmt.Sprintf("/build?%s",
		queryString(&opts)), true, headers, opts.InputStream, opts.OutputStream, nil)
}

// TagImageOptions present the set of options to tag an image
type TagImageOptions struct {
	Repo  string `qs:"repo"`
	Tag   string `qs:"tag"`
	Force bool   `qs:"force"`
}

// TagImage adds a tag to the image 'name'
func (c *Client) TagImage(name string, opts TagImageOptions) error {
	if name == "" {
		return ErrNoSuchImage
	}
	_, status, err := c.do("POST", fmt.Sprintf("/images/"+name+"/tag?%s",
		queryString(&opts)), nil)
	if status == http.StatusNotFound {
		return ErrNoSuchImage
	}

	return err
}

func isURL(u string) bool {
	p, err := url.Parse(u)
	if err != nil {
		return false
	}
	return p.Scheme == "http" || p.Scheme == "https"
}
<commit_msg>Allow pushing of single image tags<commit_after>// Copyright 2014 go-dockerclient authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.

package docker

import (
	"bytes"
	"encoding/base64"
	"encoding/json"
	"errors"
	"fmt"
	"io"
	"io/ioutil"
	"net/http"
	"net/url"
	"os"
	"time"
)

// APIImages represent an image returned in the ListImages call.
type APIImages struct {
	ID          string   `json:"Id"`
	RepoTags    []string `json:",omitempty"`
	Created     int64
	Size        int64
	VirtualSize int64
	ParentId    string `json:",omitempty"`
	Repository  string `json:",omitempty"`
	Tag         string `json:",omitempty"`
}

type Image struct {
	ID              string    `json:"id"`
	Parent          string    `json:"parent,omitempty"`
	Comment         string    `json:"comment,omitempty"`
	Created         time.Time `json:"created"`
	Container       string    `json:"container,omitempty"`
	ContainerConfig Config    `json:"containerconfig,omitempty"`
	DockerVersion   string    `json:"dockerversion,omitempty"`
	Author          string    `json:"author,omitempty"`
	Config          *Config   `json:"config,omitempty"`
	Architecture    string    `json:"architecture,omitempty"`
	Size            int64
}

type ImagePre012 struct {
	ID              string    `json:"id"`
	Parent          string    `json:"parent,omitempty"`
	Comment         string    `json:"comment,omitempty"`
	Created         time.Time `json:"created"`
	Container       string    `json:"container,omitempty"`
	ContainerConfig Config    `json:"container_config,omitempty"`
	DockerVersion   string    `json:"docker_version,omitempty"`
	Author          string    `json:"author,omitempty"`
	Config          *Config   `json:"config,omitempty"`
	Architecture    string    `json:"architecture,omitempty"`
	Size            int64
}

var (
	// ErrNoSuchImage is the error returned when the image does not exist.
	ErrNoSuchImage = errors.New("no such image")

	// ErrMissingRepo is the error returned when the remote repository is
	// missing.
	ErrMissingRepo = errors.New("missing remote repository e.g. 'github.com/user/repo'")

	// ErrMissingOutputStream is the error returned when no output stream
	// is provided to some calls, like BuildImage.
	ErrMissingOutputStream = errors.New("missing output stream")
)

// ListImages returns the list of available images in the server.
//
// See http://goo.gl/dkMrwP for more details.
func (c *Client) ListImages(all bool) ([]APIImages, error) {
	path := "/images/json?all="
	if all {
		path += "1"
	} else {
		path += "0"
	}
	body, _, err := c.do("GET", path, nil)
	if err != nil {
		return nil, err
	}
	var images []APIImages
	err = json.Unmarshal(body, &images)
	if err != nil {
		return nil, err
	}
	return images, nil
}

// RemoveImage removes an image by its name or ID.
//
// See http://goo.gl/7hjHHy for more details.
func (c *Client) RemoveImage(name string) error {
	_, status, err := c.do("DELETE", "/images/"+name, nil)
	if status == http.StatusNotFound {
		return ErrNoSuchImage
	}
	return err
}

// InspectImage returns an image by its name or ID.
//
// See http://goo.gl/pHEbma for more details.
func (c *Client) InspectImage(name string) (*Image, error) {
	body, status, err := c.do("GET", "/images/"+name+"/json", nil)
	if status == http.StatusNotFound {
		return nil, ErrNoSuchImage
	}
	if err != nil {
		return nil, err
	}

	var image Image

	// if the caller elected to skip checking the server's version, assume it's the latest
	if c.SkipServerVersionCheck || c.expectedApiVersion.GreaterThanOrEqualTo(apiVersion_1_12) {
		err = json.Unmarshal(body, &image)
		if err != nil {
			return nil, err
		}
	} else {
		var imagePre012 ImagePre012
		err = json.Unmarshal(body, &imagePre012)
		if err != nil {
			return nil, err
		}

		image.ID = imagePre012.ID
		image.Parent = imagePre012.Parent
		image.Comment = imagePre012.Comment
		image.Created = imagePre012.Created
		image.Container = imagePre012.Container
		image.ContainerConfig = imagePre012.ContainerConfig
		image.DockerVersion = imagePre012.DockerVersion
		image.Author = imagePre012.Author
		image.Config = imagePre012.Config
		image.Architecture = imagePre012.Architecture
		image.Size = imagePre012.Size
	}

	return &image, nil
}

// PushImageOptions represents options to use in the PushImage method.
//
// See http://goo.gl/GBmyhc for more details.
type PushImageOptions struct {
	// Name of the image
	Name string

	// Tag of the image
	Tag string

	// Registry server to push the image
	Registry string

	OutputStream io.Writer `qs:"-"`
}

// AuthConfiguration represents authentication options to use in the PushImage
// method. It represents the authencation in the Docker index server.
type AuthConfiguration struct {
	Username string `json:"username,omitempty"`
	Password string `json:"password,omitempty"`
	Email    string `json:"email,omitempty"`
}

// PushImage pushes an image to a remote registry, logging progress to w.
//
// An empty instance of AuthConfiguration may be used for unauthenticated
// pushes.
//
// See http://goo.gl/GBmyhc for more details.
func (c *Client) PushImage(opts PushImageOptions, auth AuthConfiguration) error {
	if opts.Name == "" {
		return ErrNoSuchImage
	}
	name := opts.Name
	opts.Name = ""
	path := "/images/" + name + "/push?" + queryString(&opts)
	var headers = make(map[string]string)
	var buf bytes.Buffer
	json.NewEncoder(&buf).Encode(auth)

	headers["X-Registry-Auth"] = base64.URLEncoding.EncodeToString(buf.Bytes())

	return c.stream("POST", path, true, headers, nil, opts.OutputStream, nil)
}

// PullImageOptions present the set of options available for pulling an image
// from a registry.
//
// See http://goo.gl/PhBKnS for more details.
type PullImageOptions struct {
	Repository   string `qs:"fromImage"`
	Registry     string
	Tag          string
	OutputStream io.Writer `qs:"-"`
}

// PullImage pulls an image from a remote registry, logging progress to w.
//
// See http://goo.gl/PhBKnS for more details.
func (c *Client) PullImage(opts PullImageOptions, auth AuthConfiguration) error {
	if opts.Repository == "" {
		return ErrNoSuchImage
	}

	var headers = make(map[string]string)
	var buf bytes.Buffer
	json.NewEncoder(&buf).Encode(auth)
	headers["X-Registry-Auth"] = base64.URLEncoding.EncodeToString(buf.Bytes())

	return c.createImage(queryString(&opts), headers, nil, opts.OutputStream)
}

func (c *Client) createImage(qs string, headers map[string]string, in io.Reader, w io.Writer) error {
	path := "/images/create?" + qs
	return c.stream("POST", path, true, headers, in, w, nil)
}

// ImportImageOptions present the set of informations available for importing
// an image from a source file or the stdin.
//
// See http://goo.gl/PhBKnS for more details.
type ImportImageOptions struct {
	Repository string `qs:"repo"`
	Source     string `qs:"fromSrc"`
	Tag        string `qs:"tag"`

	InputStream  io.Reader `qs:"-"`
	OutputStream io.Writer `qs:"-"`
}

// ImportImage imports an image from a url, a file or stdin
//
// See http://goo.gl/PhBKnS for more details.
func (c *Client) ImportImage(opts ImportImageOptions) error {
	if opts.Repository == "" {
		return ErrNoSuchImage
	}
	if opts.Source != "-" {
		opts.InputStream = nil
	}
	if opts.Source != "-" && !isURL(opts.Source) {
		f, err := os.Open(opts.Source)
		if err != nil {
			return err
		}
		b, err := ioutil.ReadAll(f)
		opts.InputStream = bytes.NewBuffer(b)
		opts.Source = "-"
	}
	return c.createImage(queryString(&opts), nil, opts.InputStream, opts.OutputStream)
}

// BuildImageOptions present the set of informations available for building
// an image from a tarfile with a Dockerfile in it,the details about Dockerfile
// see http://docs.docker.io/en/latest/reference/builder/
type BuildImageOptions struct {
	Name           string    `qs:"t"`
	NoCache        bool      `qs:"nocache"`
	SuppressOutput bool      `qs:"q"`
	RmTmpContainer bool      `qs:"rm"`
	InputStream    io.Reader `qs:"-"`
	OutputStream   io.Writer `qs:"-"`
	Remote         string    `qs:"remote"`
}

// BuildImage builds an image from a tarball's url or a Dockerfile in the input
// stream.
func (c *Client) BuildImage(opts BuildImageOptions) error {
	if opts.OutputStream == nil {
		return ErrMissingOutputStream
	}
	var headers map[string]string
	if opts.Remote != "" && opts.Name == "" {
		opts.Name = opts.Remote
	}
	if opts.InputStream != nil {
		headers = map[string]string{"Content-Type": "application/tar"}
	} else if opts.Remote == "" {
		return ErrMissingRepo
	}
	return c.stream("POST", fmt.Sprintf("/build?%s",
		queryString(&opts)), true, headers, opts.InputStream, opts.OutputStream, nil)
}

// TagImageOptions present the set of options to tag an image
type TagImageOptions struct {
	Repo  string `qs:"repo"`
	Tag   string `qs:"tag"`
	Force bool   `qs:"force"`
}

// TagImage adds a tag to the image 'name'
func (c *Client) TagImage(name string, opts TagImageOptions) error {
	if name == "" {
		return ErrNoSuchImage
	}
	_, status, err := c.do("POST", fmt.Sprintf("/images/"+name+"/tag?%s",
		queryString(&opts)), nil)
	if status == http.StatusNotFound {
		return ErrNoSuchImage
	}

	return err
}

func isURL(u string) bool {
	p, err := url.Parse(u)
	if err != nil {
		return false
	}
	return p.Scheme == "http" || p.Scheme == "https"
}
<|endoftext|>


<commit_before>// Copyright 2014 Hajime Hoshi
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

package ebiten

import (
	"errors"
	"fmt"
	"github.com/hajimehoshi/ebiten/internal/graphics"
	"github.com/hajimehoshi/ebiten/internal/graphics/opengl"
	"image"
	"image/color"
)

// Image represents an image.
// The pixel format is alpha-premultiplied.
// Image implements image.Image.
type Image struct {
	framebuffer *graphics.Framebuffer
	texture     *graphics.Texture
	pixels      []uint8
	width       int
	height      int
}

// Size returns the size of the image.
func (i *Image) Size() (width, height int) {
	if i.width == 0 {
		i.width, i.height = i.framebuffer.Size()
	}
	return i.width, i.height
}

// Clear resets the pixels of the image into 0.
func (i *Image) Clear() (err error) {
	return i.Fill(color.Transparent)
}

// Fill fills the image with a solid color.
func (i *Image) Fill(clr color.Color) (err error) {
	i.pixels = nil
	useGLContext(func(c *opengl.Context) {
		err = i.framebuffer.Fill(c, clr)
	})
	return
}

// DrawImage draws the given image on the receiver image.
//
// This method accepts the options.
// The parts of the given image at the parts of the destination.
// After determining parts to draw, this applies the geometry matrix and the color matrix.
//
// Here are the default values:
//     ImageParts: (0, 0) - (source width, source height) to (0, 0) - (source width, source height)
//                 (i.e. the whole source image)
//     GeoM:       Identity matrix
//     ColorM:     Identity matrix (that changes no colors)
//
// Be careful that this method is potentially slow.
// It would be better if you could call this method fewer times.
func (i *Image) DrawImage(image *Image, options *DrawImageOptions) (err error) {
	if i == image {
		return errors.New("Image.DrawImage: image should be different from the receiver")
	}
	i.pixels = nil
	if options == nil {
		options = &DrawImageOptions{}
	}
	parts := options.ImageParts
	if parts == nil {
		// Check options.Parts for backward-compatibility.
		dparts := options.Parts
		if dparts != nil {
			parts = imageParts(dparts)
		} else {
			w, h := image.Size()
			parts = &wholeImage{w, h}
		}
	}
	w, h := image.Size()
	quads := &textureQuads{parts: parts, width: w, height: h}
	useGLContext(func(c *opengl.Context) {
		err = i.framebuffer.DrawTexture(c, image.texture, quads, &options.GeoM, &options.ColorM)
	})
	return
}

// DrawLine draws a line.
func (i *Image) DrawLine(x0, y0, x1, y1 int, clr color.Color) error {
	return i.DrawLines(&line{x0, y0, x1, y1, clr})
}

// DrawLines draws lines.
func (i *Image) DrawLines(lines Lines) (err error) {
	i.pixels = nil
	useGLContext(func(c *opengl.Context) {
		err = i.framebuffer.DrawLines(c, lines)
	})
	return
}

// Bounds returns the bounds of the image.
func (i *Image) Bounds() image.Rectangle {
	w, h := i.Size()
	return image.Rect(0, 0, w, h)
}

// ColorModel returns the color model of the image.
func (i *Image) ColorModel() color.Model {
	return color.RGBAModel
}

// At returns the color of the image at (x, y).
//
// This method loads pixels from VRAM to system memory if necessary.
func (i *Image) At(x, y int) color.Color {
	if i.pixels == nil {
		useGLContext(func(c *opengl.Context) {
			var err error
			i.pixels, err = i.framebuffer.Pixels(c)
			if err != nil {
				panic(err)
			}
		})
	}
	w, _ := i.Size()
	w = graphics.NextPowerOf2Int(w)
	idx := 4*x + 4*y*w
	r, g, b, a := i.pixels[idx], i.pixels[idx+1], i.pixels[idx+2], i.pixels[idx+3]
	return color.RGBA{r, g, b, a}
}

func (i *Image) dispose() {
	useGLContext(func(c *opengl.Context) {
		if i.framebuffer != nil {
			i.framebuffer.Dispose(c)
		}
		if i.texture != nil {
			i.texture.Dispose(c)
		}
	})
	i.pixels = nil
}

// ReplacePixels replaces the pixels of the image with p.
//
// The given p must represent RGBA pre-multiplied alpha values. len(p) must equal to 4 * (image width) * (image height).
//
// This function may be slow (as for implementation, this calls glTexSubImage2D).
func (i *Image) ReplacePixels(p []uint8) error {
	// Don't set i.pixels here because i.pixels is used not every time.

	i.pixels = nil
	w, h := i.Size()
	l := 4 * w * h
	if len(p) != l {
		return errors.New(fmt.Sprintf("p's length must be %d", l))
	}
	var err error
	useGLContext(func(c *opengl.Context) {
		err = i.texture.ReplacePixels(c, p)
	})
	return err
}

// A DrawImageOptions represents options to render an image on an image.
type DrawImageOptions struct {
	ImageParts ImageParts
	GeoM       GeoM
	ColorM     ColorM

	// Deprecated (as of 1.1.0-alpha): Use ImageParts instead.
	Parts []ImagePart
}

// NewImage returns an empty image.
//
// NewImage generates a new texture and a new framebuffer.
// Be careful that image objects will never be released
// even though nothing refers the image object and GC works.
// It is because there is no way to define finalizers for Go objects if you use GopherJS.
func NewImage(width, height int, filter Filter) (*Image, error) {
	var img *Image
	var err error
	useGLContext(func(c *opengl.Context) {
		var texture *graphics.Texture
		var framebuffer *graphics.Framebuffer
		texture, err = graphics.NewTexture(c, width, height, glFilter(c, filter))
		if err != nil {
			return
		}
		framebuffer, err = graphics.NewFramebufferFromTexture(c, texture)
		if err != nil {
			return
		}
		img = &Image{framebuffer: framebuffer, texture: texture}
	})
	if err != nil {
		return nil, err
	}
	if err := img.Clear(); err != nil {
		return nil, err
	}
	return img, nil
}

// NewImageFromImage creates a new image with the given image (img).
//
// NewImageFromImage generates a new texture and a new framebuffer.
// Be careful that image objects will never be released
// even though nothing refers the image object and GC works.
// It is because there is no way to define finalizers for Go objects if you use GopherJS.
func NewImageFromImage(img image.Image, filter Filter) (*Image, error) {
	var eimg *Image
	var err error
	useGLContext(func(c *opengl.Context) {
		var texture *graphics.Texture
		var framebuffer *graphics.Framebuffer
		texture, err = graphics.NewTextureFromImage(c, img, glFilter(c, filter))
		if err != nil {
			return
		}
		framebuffer, err = graphics.NewFramebufferFromTexture(c, texture)
		if err != nil {
			return
		}
		eimg = &Image{framebuffer: framebuffer, texture: texture}
	})
	if err != nil {
		return nil, err
	}
	return eimg, nil
}
<commit_msg>image: Remove image.DrawLine (#142)<commit_after>// Copyright 2014 Hajime Hoshi
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

package ebiten

import (
	"errors"
	"fmt"
	"github.com/hajimehoshi/ebiten/internal/graphics"
	"github.com/hajimehoshi/ebiten/internal/graphics/opengl"
	"image"
	"image/color"
)

// Image represents an image.
// The pixel format is alpha-premultiplied.
// Image implements image.Image.
type Image struct {
	framebuffer *graphics.Framebuffer
	texture     *graphics.Texture
	pixels      []uint8
	width       int
	height      int
}

// Size returns the size of the image.
func (i *Image) Size() (width, height int) {
	if i.width == 0 {
		i.width, i.height = i.framebuffer.Size()
	}
	return i.width, i.height
}

// Clear resets the pixels of the image into 0.
func (i *Image) Clear() (err error) {
	return i.Fill(color.Transparent)
}

// Fill fills the image with a solid color.
func (i *Image) Fill(clr color.Color) (err error) {
	i.pixels = nil
	useGLContext(func(c *opengl.Context) {
		err = i.framebuffer.Fill(c, clr)
	})
	return
}

// DrawImage draws the given image on the receiver image.
//
// This method accepts the options.
// The parts of the given image at the parts of the destination.
// After determining parts to draw, this applies the geometry matrix and the color matrix.
//
// Here are the default values:
//     ImageParts: (0, 0) - (source width, source height) to (0, 0) - (source width, source height)
//                 (i.e. the whole source image)
//     GeoM:       Identity matrix
//     ColorM:     Identity matrix (that changes no colors)
//
// Be careful that this method is potentially slow.
// It would be better if you could call this method fewer times.
func (i *Image) DrawImage(image *Image, options *DrawImageOptions) (err error) {
	if i == image {
		return errors.New("Image.DrawImage: image should be different from the receiver")
	}
	i.pixels = nil
	if options == nil {
		options = &DrawImageOptions{}
	}
	parts := options.ImageParts
	if parts == nil {
		// Check options.Parts for backward-compatibility.
		dparts := options.Parts
		if dparts != nil {
			parts = imageParts(dparts)
		} else {
			w, h := image.Size()
			parts = &wholeImage{w, h}
		}
	}
	w, h := image.Size()
	quads := &textureQuads{parts: parts, width: w, height: h}
	useGLContext(func(c *opengl.Context) {
		err = i.framebuffer.DrawTexture(c, image.texture, quads, &options.GeoM, &options.ColorM)
	})
	return
}

// DrawLines draws lines.
func (i *Image) DrawLines(lines Lines) (err error) {
	i.pixels = nil
	useGLContext(func(c *opengl.Context) {
		err = i.framebuffer.DrawLines(c, lines)
	})
	return
}

// Bounds returns the bounds of the image.
func (i *Image) Bounds() image.Rectangle {
	w, h := i.Size()
	return image.Rect(0, 0, w, h)
}

// ColorModel returns the color model of the image.
func (i *Image) ColorModel() color.Model {
	return color.RGBAModel
}

// At returns the color of the image at (x, y).
//
// This method loads pixels from VRAM to system memory if necessary.
func (i *Image) At(x, y int) color.Color {
	if i.pixels == nil {
		useGLContext(func(c *opengl.Context) {
			var err error
			i.pixels, err = i.framebuffer.Pixels(c)
			if err != nil {
				panic(err)
			}
		})
	}
	w, _ := i.Size()
	w = graphics.NextPowerOf2Int(w)
	idx := 4*x + 4*y*w
	r, g, b, a := i.pixels[idx], i.pixels[idx+1], i.pixels[idx+2], i.pixels[idx+3]
	return color.RGBA{r, g, b, a}
}

func (i *Image) dispose() {
	useGLContext(func(c *opengl.Context) {
		if i.framebuffer != nil {
			i.framebuffer.Dispose(c)
		}
		if i.texture != nil {
			i.texture.Dispose(c)
		}
	})
	i.pixels = nil
}

// ReplacePixels replaces the pixels of the image with p.
//
// The given p must represent RGBA pre-multiplied alpha values. len(p) must equal to 4 * (image width) * (image height).
//
// This function may be slow (as for implementation, this calls glTexSubImage2D).
func (i *Image) ReplacePixels(p []uint8) error {
	// Don't set i.pixels here because i.pixels is used not every time.

	i.pixels = nil
	w, h := i.Size()
	l := 4 * w * h
	if len(p) != l {
		return errors.New(fmt.Sprintf("p's length must be %d", l))
	}
	var err error
	useGLContext(func(c *opengl.Context) {
		err = i.texture.ReplacePixels(c, p)
	})
	return err
}

// A DrawImageOptions represents options to render an image on an image.
type DrawImageOptions struct {
	ImageParts ImageParts
	GeoM       GeoM
	ColorM     ColorM

	// Deprecated (as of 1.1.0-alpha): Use ImageParts instead.
	Parts []ImagePart
}

// NewImage returns an empty image.
//
// NewImage generates a new texture and a new framebuffer.
// Be careful that image objects will never be released
// even though nothing refers the image object and GC works.
// It is because there is no way to define finalizers for Go objects if you use GopherJS.
func NewImage(width, height int, filter Filter) (*Image, error) {
	var img *Image
	var err error
	useGLContext(func(c *opengl.Context) {
		var texture *graphics.Texture
		var framebuffer *graphics.Framebuffer
		texture, err = graphics.NewTexture(c, width, height, glFilter(c, filter))
		if err != nil {
			return
		}
		framebuffer, err = graphics.NewFramebufferFromTexture(c, texture)
		if err != nil {
			return
		}
		img = &Image{framebuffer: framebuffer, texture: texture}
	})
	if err != nil {
		return nil, err
	}
	if err := img.Clear(); err != nil {
		return nil, err
	}
	return img, nil
}

// NewImageFromImage creates a new image with the given image (img).
//
// NewImageFromImage generates a new texture and a new framebuffer.
// Be careful that image objects will never be released
// even though nothing refers the image object and GC works.
// It is because there is no way to define finalizers for Go objects if you use GopherJS.
func NewImageFromImage(img image.Image, filter Filter) (*Image, error) {
	var eimg *Image
	var err error
	useGLContext(func(c *opengl.Context) {
		var texture *graphics.Texture
		var framebuffer *graphics.Framebuffer
		texture, err = graphics.NewTextureFromImage(c, img, glFilter(c, filter))
		if err != nil {
			return
		}
		framebuffer, err = graphics.NewFramebufferFromTexture(c, texture)
		if err != nil {
			return
		}
		eimg = &Image{framebuffer: framebuffer, texture: texture}
	})
	if err != nil {
		return nil, err
	}
	return eimg, nil
}
<|endoftext|>


<commit_before>/*
Copyright 2015 The Kubernetes Authors.

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

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

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

package e2e

import (
	"flag"
	"fmt"
	"os"
	"testing"

	"k8s.io/kubernetes/test/e2e"
	"k8s.io/kubernetes/test/e2e/framework"
	"k8s.io/kubernetes/test/e2e/framework/testfiles"
	"k8s.io/kubernetes/test/e2e/framework/viperconfig"
	"k8s.io/kubernetes/test/e2e/generated"

	// test sources
	_ "k8s.io/kubernetes/test/e2e/apimachinery"
	_ "k8s.io/kubernetes/test/e2e/apps"
	_ "k8s.io/kubernetes/test/e2e/auth"
	_ "k8s.io/kubernetes/test/e2e/autoscaling"
	_ "k8s.io/kubernetes/test/e2e/common"
	_ "k8s.io/kubernetes/test/e2e/instrumentation"
	_ "k8s.io/kubernetes/test/e2e/kubectl"
	_ "k8s.io/kubernetes/test/e2e/lifecycle"
	_ "k8s.io/kubernetes/test/e2e/lifecycle/bootstrap"
	_ "k8s.io/kubernetes/test/e2e/network"
	_ "k8s.io/kubernetes/test/e2e/node"
	_ "k8s.io/kubernetes/test/e2e/scalability"
	_ "k8s.io/kubernetes/test/e2e/scheduling"
	_ "k8s.io/kubernetes/test/e2e/servicecatalog"
	_ "k8s.io/kubernetes/test/e2e/storage"
	_ "k8s.io/kubernetes/test/e2e/ui"
)

var viperConfig = flag.String("viper-config", "", "The name of a viper config file (https://github.com/spf13/viper#what-is-viper). All e2e command line parameters can also be configured in such a file. May contain a path and may or may not contain the file suffix. The default is to look for an optional file with `e2e` as base name. If a file is specified explicitly, it must be present.")

func TestE2E(t *testing.T) {
	// Register framework flags, then handle flags and Viper config.
	framework.HandleFlags()
	if err := viperconfig.ViperizeFlags(*viperConfig, ""); err != nil {
		fmt.Fprintln(os.Stderr, err)
		os.Exit(1)
	}
	framework.AfterReadingAllFlags(&framework.TestContext)

	// TODO: Deprecating repo-root over time... instead just use gobindata_util.go , see #23987.
	// Right now it is still needed, for example by
	// test/e2e/framework/ingress/ingress_utils.go
	// for providing the optional secret.yaml file and by
	// test/e2e/framework/util.go for cluster/log-dump.
	if framework.TestContext.RepoRoot != "" {
		testfiles.AddFileSource(testfiles.RootFileSource{Root: framework.TestContext.RepoRoot})
	}

	// Enable bindata file lookup as fallback.
	testfiles.AddFileSource(testfiles.BindataFileSource{
		Asset:      generated.Asset,
		AssetNames: generated.AssetNames,
	})

	e2e.RunE2ETests(t)
}

func getenv(envar, def string) string {
	v := os.Getenv(envar)
	if v == "" {
		return def
	}
	return v
}

// E2EHostedZone returns the hosted zone defined for e2e test.
func E2EHostedZone() string {
	return getenv("HOSTED_ZONE", "example.org")
}

// E2EClusterAlias returns the alias of the cluster used for e2e tests.
func E2EClusterAlias() string {
	result, ok := os.LookupEnv("CLUSTER_ALIAS")
	if !ok {
		panic("CLUSTER_ALIAS not defined")
	}
	return result
}

// E2ES3AWSIAMBucket returns the s3 bucket name used for AWS IAM e2e tests.
func E2ES3AWSIAMBucket() string {
	return getenv("S3_AWS_IAM_BUCKET", "")
}

// E2EAWSIAMRole returns the AWS IAM role used for AWS IAM e2e tests.
func E2EAWSIAMRole() string {
	return getenv("AWS_IAM_ROLE", "")
}
<commit_msg>Add TestMain<commit_after>/*
Copyright 2015 The Kubernetes Authors.

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

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

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

package e2e

import (
	"flag"
	"fmt"
	"os"
	"testing"

	"k8s.io/kubernetes/test/e2e"
	"k8s.io/kubernetes/test/e2e/framework"
	"k8s.io/kubernetes/test/e2e/framework/testfiles"
	"k8s.io/kubernetes/test/e2e/framework/viperconfig"
	"k8s.io/kubernetes/test/e2e/generated"

	// test sources
	_ "k8s.io/kubernetes/test/e2e/apimachinery"
	_ "k8s.io/kubernetes/test/e2e/apps"
	_ "k8s.io/kubernetes/test/e2e/auth"
	_ "k8s.io/kubernetes/test/e2e/autoscaling"
	_ "k8s.io/kubernetes/test/e2e/common"
	_ "k8s.io/kubernetes/test/e2e/instrumentation"
	_ "k8s.io/kubernetes/test/e2e/kubectl"
	_ "k8s.io/kubernetes/test/e2e/lifecycle"
	_ "k8s.io/kubernetes/test/e2e/lifecycle/bootstrap"
	_ "k8s.io/kubernetes/test/e2e/network"
	_ "k8s.io/kubernetes/test/e2e/node"
	_ "k8s.io/kubernetes/test/e2e/scalability"
	_ "k8s.io/kubernetes/test/e2e/scheduling"
	_ "k8s.io/kubernetes/test/e2e/servicecatalog"
	_ "k8s.io/kubernetes/test/e2e/storage"
	_ "k8s.io/kubernetes/test/e2e/ui"
)

var viperConfig = flag.String("viper-config", "", "The name of a viper config file (https://github.com/spf13/viper#what-is-viper). All e2e command line parameters can also be configured in such a file. May contain a path and may or may not contain the file suffix. The default is to look for an optional file with `e2e` as base name. If a file is specified explicitly, it must be present.")

func TestMain(m *testing.M) {
	// Register framework flags, then handle flags and Viper config.
	framework.HandleFlags()
	if err := viperconfig.ViperizeFlags(*viperConfig, ""); err != nil {
		fmt.Fprintln(os.Stderr, err)
		os.Exit(1)
	}
	framework.AfterReadingAllFlags(&framework.TestContext)

	// TODO: Deprecating repo-root over time... instead just use gobindata_util.go , see #23987.
	// Right now it is still needed, for example by
	// test/e2e/framework/ingress/ingress_utils.go
	// for providing the optional secret.yaml file and by
	// test/e2e/framework/util.go for cluster/log-dump.
	if framework.TestContext.RepoRoot != "" {
		testfiles.AddFileSource(testfiles.RootFileSource{Root: framework.TestContext.RepoRoot})
	}

	// Enable bindata file lookup as fallback.
	testfiles.AddFileSource(testfiles.BindataFileSource{
		Asset:      generated.Asset,
		AssetNames: generated.AssetNames,
	})
	os.Exit(m.Run())
}

func TestE2E(t *testing.T) {
	e2e.RunE2ETests(t)
}

func getenv(envar, def string) string {
	v := os.Getenv(envar)
	if v == "" {
		return def
	}
	return v
}

// E2EHostedZone returns the hosted zone defined for e2e test.
func E2EHostedZone() string {
	return getenv("HOSTED_ZONE", "example.org")
}

// E2EClusterAlias returns the alias of the cluster used for e2e tests.
func E2EClusterAlias() string {
	result, ok := os.LookupEnv("CLUSTER_ALIAS")
	if !ok {
		panic("CLUSTER_ALIAS not defined")
	}
	return result
}

// E2ES3AWSIAMBucket returns the s3 bucket name used for AWS IAM e2e tests.
func E2ES3AWSIAMBucket() string {
	return getenv("S3_AWS_IAM_BUCKET", "")
}

// E2EAWSIAMRole returns the AWS IAM role used for AWS IAM e2e tests.
func E2EAWSIAMRole() string {
	return getenv("AWS_IAM_ROLE", "")
}
<|endoftext|>


<commit_before>// Copyright 2014 The Serviced Authors.
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

package zookeeper

import (
	"encoding/json"
	"path"
	"sync"

	zklib "github.com/control-center/go-zookeeper/zk"
	"github.com/control-center/serviced/coordinator/client"
)

// Connection is a Zookeeper based implementation of client.Connection.
type Connection struct {
	sync.RWMutex
	conn     *zklib.Conn
	basePath string
	onClose  func(int)
	id       int
}

// Assert that Connection implements client.Connection.
var _ client.Connection = &Connection{}

// IsClosed returns connection closed error if true, otherwise returns nil.
func (c *Connection) isClosed() error {
	if c.conn == nil {
		return client.ErrConnectionClosed
	}
	return nil
}

// Close closes the client connection to zookeeper. Calling close twice will
// result in a no-op.
func (c *Connection) Close() {
	c.Lock()
	defer c.Unlock()
	if c.conn != nil {
		c.conn.Close()
		c.conn = nil
		if c.onClose != nil {
			c.onClose(c.id)
			c.onClose = nil
		}
	}
}

// SetID sets the connection ID
func (c *Connection) SetID(i int) {
	c.Lock()
	defer c.Unlock()
	c.id = i
}

// ID gets the connection ID
func (c *Connection) ID() int {
	c.RLock()
	defer c.RUnlock()
	return c.id
}

// SetOnClose performs cleanup when a connection is closed
func (c *Connection) SetOnClose(onClose func(int)) {
	c.Lock()
	defer c.Unlock()
	if err := c.isClosed(); err == nil {
		c.onClose = onClose
	}
}

// NewTransaction creates a new transaction object
func (c *Connection) NewTransaction() client.Transaction {
	return &Transaction{
		conn: c,
		ops:  []multiReq{},
	}
}

// NewLock creates a new lock object
func (c *Connection) NewLock(p string) (client.Lock, error) {
	c.RLock()
	defer c.RUnlock()
	if err := c.isClosed(); err != nil {
		return nil, err
	}
	lock := &Lock{
		lock: zklib.NewLock(c.conn, path.Join(c.basePath, p), zklib.WorldACL(zklib.PermAll)),
	}
	return lock, nil
}

// NewLeader returns a managed leader object at the given path bound to the
// current connection.
func (c *Connection) NewLeader(p string) (client.Leader, error) {
	c.RLock()
	defer c.RUnlock()
	if err := c.isClosed(); err != nil {
		return nil, err
	}
	return NewLeader(c.conn, path.Join(path.Join(c.basePath, p))), nil
}

// Create adds a node at the specified path
func (c *Connection) Create(path string, node client.Node) error {
	c.RLock()
	defer c.RUnlock()
	if err := c.isClosed(); err != nil {
		return err
	}
	if err := c.ensurePath(path); err != nil {
		return err
	}
	return c.create(path, node)
}

func (c *Connection) create(p string, node client.Node) error {
	bytes, err := json.Marshal(node)
	if err != nil {
		return client.ErrSerialization
	}
	pth := path.Join(c.basePath, p)
	if _, err := c.conn.Create(pth, bytes, 0, zklib.WorldACL(zklib.PermAll)); err != nil {
		return xlateError(err)
	}
	node.SetVersion(&zklib.Stat{})
	return nil
}

// CreateDir adds a dir at the specified path
func (c *Connection) CreateDir(path string) error {
	c.RLock()
	defer c.RUnlock()
	if err := c.isClosed(); err != nil {
		return err
	}
	if err := c.ensurePath(path); err != nil {
		return err
	}
	return c.createDir(path)
}

func (c *Connection) createDir(p string) error {
	pth := path.Join(c.basePath, p)
	_, err := c.conn.Create(pth, []byte{}, 0, zklib.WorldACL(zklib.PermAll))
	return err
}

func (c *Connection) ensurePath(p string) error {
	dp := path.Dir(p)
	if ok, err := c.exists(dp); err != nil {
		return err
	} else if !ok {
		if p == "" || p == "/" {
			return nil
		} else if err := c.ensurePath(dp); err != nil {
			return err
		} else if err := c.createDir(dp); err != client.ErrNodeExists {
			return err
		}
	}
	return nil
}

// CreateEphemeral creates a node whose existance depends on the persistence of
// the connection.
func (c *Connection) CreateEphemeral(path string, node client.Node) (string, error) {
	c.RLock()
	defer c.RUnlock()
	if err := c.isClosed(); err != nil {
		return "", err
	}
	if err := c.ensurePath(path); err != nil {
		return "", err
	}
	return c.createEphemeral(path, node)
}

func (c *Connection) createEphemeral(p string, node client.Node) (string, error) {
	bytes, err := json.Marshal(node)
	if err != nil {
		return "", client.ErrSerialization
	}
	pth := path.Join(c.basePath, p)
	epth, err := c.conn.CreateProtectedEphemeralSequential(pth, bytes, zklib.WorldACL(zklib.PermAll))
	return epth, xlateError(err)
}

// Set assigns a value to an existing node at a given path
func (c *Connection) Set(path string, node client.Node) error {
	c.RLock()
	defer c.RUnlock()
	if err := c.isClosed(); err != nil {
		return err
	}
	return c.set(path, node)
}

func (c *Connection) set(p string, node client.Node) error {
	bytes, err := json.Marshal(node)
	if err != nil {
		return client.ErrSerialization
	}
	stat := &zklib.Stat{}
	if version := node.Version(); version != nil {
		var ok bool
		if stat, ok = version.(*zklib.Stat); !ok {
			return client.ErrInvalidVersionObj
		}
	}
	pth := path.Join(c.basePath, p)
	if _, err := c.conn.Set(pth, bytes, stat.Version); err != nil {
		return xlateError(err)
	}
	return nil
}

// Delete recursively removes a path and its children
func (c *Connection) Delete(path string) error {
	c.RLock()
	defer c.RUnlock()
	if err := c.isClosed(); err != nil {
		return err
	}
	return c.delete(path)
}

func (c *Connection) delete(p string) error {
	children, err := c.children(p)
	if err != nil {
		return err
	}
	for _, child := range children {
		if err := c.delete(path.Join(p, child)); err != nil {
			return err
		}
	}
	pth := path.Join(c.basePath, p)
	_, stat, err := c.conn.Get(pth)
	if err != nil {
		return xlateError(err)
	}
	return xlateError(c.conn.Delete(pth, stat.Version))
}

// Exists returns true if the path exists
func (c *Connection) Exists(path string) (bool, error) {
	c.RLock()
	defer c.RUnlock()
	if err := c.isClosed(); err != nil {
		return false, err
	}
	return c.exists(path)
}

func (c *Connection) exists(p string) (bool, error) {
	exists, _, err := c.conn.Exists(path.Join(c.basePath, p))
	if err == zklib.ErrNoNode {
		return false, nil
	}
	return exists, xlateError(err)
}

// Get returns the node at the given path.
func (c *Connection) Get(path string, node client.Node) error {
	c.RLock()
	defer c.RUnlock()
	if err := c.isClosed(); err != nil {
		return err
	}
	return c.get(path, node)
}

func (c *Connection) get(p string, node client.Node) error {
	p = path.Join(c.basePath, p)
	bytes, stat, err := c.conn.Get(p)
	if err != nil {
		return xlateError(err)
	}
	if len(bytes) == 0 {
		return client.ErrEmptyNode
	}
	if err := json.Unmarshal(bytes, node); err != nil {
		return client.ErrSerialization
	}
	node.SetVersion(stat)
	return nil
}

// GetW returns the node at the given path as well as a channel to watch for
// events on that node.
func (c *Connection) GetW(path string, node client.Node, cancel <-chan struct{}) (<-chan client.Event, error) {
	c.RLock()
	defer c.RUnlock()
	if err := c.isClosed(); err != nil {
		return nil, err
	}
	return c.getW(path, node, cancel)
}

func (c *Connection) getW(p string, node client.Node, cancel <-chan struct{}) (<-chan client.Event, error) {
	p = path.Join(c.basePath, p)
	bytes, stat, ch, err := c.conn.GetW(p)
	if err != nil {
		return nil, xlateError(err)
	}
	if len(bytes) == 0 {
		return nil, client.ErrEmptyNode
	} else if err := json.Unmarshal(bytes, node); err != nil {
		return nil, client.ErrSerialization
	}
	node.SetVersion(stat)
	return c.toClientEvent(ch, cancel), nil
}

func (c *Connection) toClientEvent(ch <-chan zklib.Event, cancel <-chan struct{}) <-chan client.Event {
	evCh := make(chan client.Event, 1)
	go func() {
		select {
		case zkev := <-ch:
			ev := client.Event{Type: client.EventType(zkev.Type)}
			select {
			case evCh <- ev:
			case <-cancel:
			}
		case <-cancel:
			c.cancelEvent(ch)
		}
	}()
	return evCh
}

func (c *Connection) cancelEvent(ch <-chan zklib.Event) {
	c.RLock()
	defer c.RUnlock()
	if err := c.isClosed(); err != nil {
		return
	}
	c.conn.CancelEvent(ch)
}

// Children returns the children of the node at the given path.
func (c *Connection) Children(path string) ([]string, error) {
	c.RLock()
	defer c.RUnlock()
	if err := c.isClosed(); err != nil {
		return []string{}, err
	}
	return c.children(path)
}

func (c *Connection) children(p string) ([]string, error) {
	pth := path.Join(c.basePath, p)
	children, _, err := c.conn.Children(pth)
	if err != nil {
		return []string{}, xlateError(err)
	}
	return children, nil
}

// ChildrenW returns the children of the node at the given path as well as a
// channel to watch for events on that node.
func (c *Connection) ChildrenW(path string, cancel <-chan struct{}) ([]string, <-chan client.Event, error) {
	c.RLock()
	defer c.RUnlock()
	if err := c.isClosed(); err != nil {
		return []string{}, nil, err
	}
	return c.childrenW(path, cancel)
}

func (c *Connection) childrenW(p string, cancel <-chan struct{}) ([]string, <-chan client.Event, error) {
	p = path.Join(c.basePath, p)
	children, _, ch, err := c.conn.ChildrenW(p)
	if err != nil {
		return []string{}, nil, xlateError(err)
	}
	return children, c.toClientEvent(ch, cancel), nil
}
<commit_msg>translate the createDir error<commit_after>// Copyright 2014 The Serviced Authors.
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

package zookeeper

import (
	"encoding/json"
	"path"
	"sync"

	zklib "github.com/control-center/go-zookeeper/zk"
	"github.com/control-center/serviced/coordinator/client"
)

// Connection is a Zookeeper based implementation of client.Connection.
type Connection struct {
	sync.RWMutex
	conn     *zklib.Conn
	basePath string
	onClose  func(int)
	id       int
}

// Assert that Connection implements client.Connection.
var _ client.Connection = &Connection{}

// IsClosed returns connection closed error if true, otherwise returns nil.
func (c *Connection) isClosed() error {
	if c.conn == nil {
		return client.ErrConnectionClosed
	}
	return nil
}

// Close closes the client connection to zookeeper. Calling close twice will
// result in a no-op.
func (c *Connection) Close() {
	c.Lock()
	defer c.Unlock()
	if c.conn != nil {
		c.conn.Close()
		c.conn = nil
		if c.onClose != nil {
			c.onClose(c.id)
			c.onClose = nil
		}
	}
}

// SetID sets the connection ID
func (c *Connection) SetID(i int) {
	c.Lock()
	defer c.Unlock()
	c.id = i
}

// ID gets the connection ID
func (c *Connection) ID() int {
	c.RLock()
	defer c.RUnlock()
	return c.id
}

// SetOnClose performs cleanup when a connection is closed
func (c *Connection) SetOnClose(onClose func(int)) {
	c.Lock()
	defer c.Unlock()
	if err := c.isClosed(); err == nil {
		c.onClose = onClose
	}
}

// NewTransaction creates a new transaction object
func (c *Connection) NewTransaction() client.Transaction {
	return &Transaction{
		conn: c,
		ops:  []multiReq{},
	}
}

// NewLock creates a new lock object
func (c *Connection) NewLock(p string) (client.Lock, error) {
	c.RLock()
	defer c.RUnlock()
	if err := c.isClosed(); err != nil {
		return nil, err
	}
	lock := &Lock{
		lock: zklib.NewLock(c.conn, path.Join(c.basePath, p), zklib.WorldACL(zklib.PermAll)),
	}
	return lock, nil
}

// NewLeader returns a managed leader object at the given path bound to the
// current connection.
func (c *Connection) NewLeader(p string) (client.Leader, error) {
	c.RLock()
	defer c.RUnlock()
	if err := c.isClosed(); err != nil {
		return nil, err
	}
	return NewLeader(c.conn, path.Join(path.Join(c.basePath, p))), nil
}

// Create adds a node at the specified path
func (c *Connection) Create(path string, node client.Node) error {
	c.RLock()
	defer c.RUnlock()
	if err := c.isClosed(); err != nil {
		return err
	}
	if err := c.ensurePath(path); err != nil {
		return err
	}
	return c.create(path, node)
}

func (c *Connection) create(p string, node client.Node) error {
	bytes, err := json.Marshal(node)
	if err != nil {
		return client.ErrSerialization
	}
	pth := path.Join(c.basePath, p)
	if _, err := c.conn.Create(pth, bytes, 0, zklib.WorldACL(zklib.PermAll)); err != nil {
		return xlateError(err)
	}
	node.SetVersion(&zklib.Stat{})
	return nil
}

// CreateDir adds a dir at the specified path
func (c *Connection) CreateDir(path string) error {
	c.RLock()
	defer c.RUnlock()
	if err := c.isClosed(); err != nil {
		return err
	}
	if err := c.ensurePath(path); err != nil {
		return err
	}
	return c.createDir(path)
}

func (c *Connection) createDir(p string) error {
	pth := path.Join(c.basePath, p)
	_, err := c.conn.Create(pth, []byte{}, 0, zklib.WorldACL(zklib.PermAll))
	return xlateError(err)
}

func (c *Connection) ensurePath(p string) error {
	dp := path.Dir(p)
	if p == "" || p == "/" {
		return nil
	} else if err := c.ensurePath(dp); err != nil {
		return err
	} else if err := c.createDir(dp); err != client.ErrNodeExists {
		return err
	}
	return nil
}

// CreateEphemeral creates a node whose existance depends on the persistence of
// the connection.
func (c *Connection) CreateEphemeral(path string, node client.Node) (string, error) {
	c.RLock()
	defer c.RUnlock()
	if err := c.isClosed(); err != nil {
		return "", err
	}
	if err := c.ensurePath(path); err != nil {
		return "", err
	}
	return c.createEphemeral(path, node)
}

func (c *Connection) createEphemeral(p string, node client.Node) (string, error) {
	bytes, err := json.Marshal(node)
	if err != nil {
		return "", client.ErrSerialization
	}
	pth := path.Join(c.basePath, p)
	epth, err := c.conn.CreateProtectedEphemeralSequential(pth, bytes, zklib.WorldACL(zklib.PermAll))
	return epth, xlateError(err)
}

// Set assigns a value to an existing node at a given path
func (c *Connection) Set(path string, node client.Node) error {
	c.RLock()
	defer c.RUnlock()
	if err := c.isClosed(); err != nil {
		return err
	}
	return c.set(path, node)
}

func (c *Connection) set(p string, node client.Node) error {
	bytes, err := json.Marshal(node)
	if err != nil {
		return client.ErrSerialization
	}
	stat := &zklib.Stat{}
	if version := node.Version(); version != nil {
		var ok bool
		if stat, ok = version.(*zklib.Stat); !ok {
			return client.ErrInvalidVersionObj
		}
	}
	pth := path.Join(c.basePath, p)
	if _, err := c.conn.Set(pth, bytes, stat.Version); err != nil {
		return xlateError(err)
	}
	return nil
}

// Delete recursively removes a path and its children
func (c *Connection) Delete(path string) error {
	c.RLock()
	defer c.RUnlock()
	if err := c.isClosed(); err != nil {
		return err
	}
	return c.delete(path)
}

func (c *Connection) delete(p string) error {
	children, err := c.children(p)
	if err != nil {
		return err
	}
	for _, child := range children {
		if err := c.delete(path.Join(p, child)); err != nil {
			return err
		}
	}
	pth := path.Join(c.basePath, p)
	_, stat, err := c.conn.Get(pth)
	if err != nil {
		return xlateError(err)
	}
	return xlateError(c.conn.Delete(pth, stat.Version))
}

// Exists returns true if the path exists
func (c *Connection) Exists(path string) (bool, error) {
	c.RLock()
	defer c.RUnlock()
	if err := c.isClosed(); err != nil {
		return false, err
	}
	return c.exists(path)
}

func (c *Connection) exists(p string) (bool, error) {
	exists, _, err := c.conn.Exists(path.Join(c.basePath, p))
	if err == zklib.ErrNoNode {
		return false, nil
	}
	return exists, xlateError(err)
}

// Get returns the node at the given path.
func (c *Connection) Get(path string, node client.Node) error {
	c.RLock()
	defer c.RUnlock()
	if err := c.isClosed(); err != nil {
		return err
	}
	return c.get(path, node)
}

func (c *Connection) get(p string, node client.Node) error {
	p = path.Join(c.basePath, p)
	bytes, stat, err := c.conn.Get(p)
	if err != nil {
		return xlateError(err)
	}
	if len(bytes) == 0 {
		return client.ErrEmptyNode
	}
	if err := json.Unmarshal(bytes, node); err != nil {
		return client.ErrSerialization
	}
	node.SetVersion(stat)
	return nil
}

// GetW returns the node at the given path as well as a channel to watch for
// events on that node.
func (c *Connection) GetW(path string, node client.Node, cancel <-chan struct{}) (<-chan client.Event, error) {
	c.RLock()
	defer c.RUnlock()
	if err := c.isClosed(); err != nil {
		return nil, err
	}
	return c.getW(path, node, cancel)
}

func (c *Connection) getW(p string, node client.Node, cancel <-chan struct{}) (<-chan client.Event, error) {
	p = path.Join(c.basePath, p)
	bytes, stat, ch, err := c.conn.GetW(p)
	if err != nil {
		return nil, xlateError(err)
	}
	if len(bytes) == 0 {
		return nil, client.ErrEmptyNode
	} else if err := json.Unmarshal(bytes, node); err != nil {
		return nil, client.ErrSerialization
	}
	node.SetVersion(stat)
	return c.toClientEvent(ch, cancel), nil
}

func (c *Connection) toClientEvent(ch <-chan zklib.Event, cancel <-chan struct{}) <-chan client.Event {
	evCh := make(chan client.Event, 1)
	go func() {
		select {
		case zkev := <-ch:
			ev := client.Event{Type: client.EventType(zkev.Type)}
			select {
			case evCh <- ev:
			case <-cancel:
			}
		case <-cancel:
			c.cancelEvent(ch)
		}
	}()
	return evCh
}

func (c *Connection) cancelEvent(ch <-chan zklib.Event) {
	c.RLock()
	defer c.RUnlock()
	if err := c.isClosed(); err != nil {
		return
	}
	c.conn.CancelEvent(ch)
}

// Children returns the children of the node at the given path.
func (c *Connection) Children(path string) ([]string, error) {
	c.RLock()
	defer c.RUnlock()
	if err := c.isClosed(); err != nil {
		return []string{}, err
	}
	return c.children(path)
}

func (c *Connection) children(p string) ([]string, error) {
	pth := path.Join(c.basePath, p)
	children, _, err := c.conn.Children(pth)
	if err != nil {
		return []string{}, xlateError(err)
	}
	return children, nil
}

// ChildrenW returns the children of the node at the given path as well as a
// channel to watch for events on that node.
func (c *Connection) ChildrenW(path string, cancel <-chan struct{}) ([]string, <-chan client.Event, error) {
	c.RLock()
	defer c.RUnlock()
	if err := c.isClosed(); err != nil {
		return []string{}, nil, err
	}
	return c.childrenW(path, cancel)
}

func (c *Connection) childrenW(p string, cancel <-chan struct{}) ([]string, <-chan client.Event, error) {
	p = path.Join(c.basePath, p)
	children, _, ch, err := c.conn.ChildrenW(p)
	if err != nil {
		return []string{}, nil, xlateError(err)
	}
	return children, c.toClientEvent(ch, cancel), nil
}
<|endoftext|>


<commit_before>package rtda

/*
JVM
  Thread
    pc
    Stack
      Frame
        LocalVars
        OperandStack
*/
type Thread struct {
    // todo
    pc      uint32
    stack   *Stack
}

func newThread(maxStackSize int) (*Thread) {
    stack := newStack(maxStackSize)
    return &Thread{0, stack}
}
<commit_msg>comment<commit_after>package rtda

/*
JVM
  Thread
    pc
    Stack
      Frame
        LocalVars
        OperandStack
*/
type Thread struct {
    pc      uint32
    stack   *Stack
    // todo
}

func newThread(maxStackSize int) (*Thread) {
    stack := newStack(maxStackSize)
    return &Thread{0, stack}
}
<|endoftext|>