id
int32
0
167k
repo
stringlengths
5
54
path
stringlengths
4
155
func_name
stringlengths
1
118
original_string
stringlengths
52
85.5k
language
stringclasses
1 value
code
stringlengths
52
85.5k
code_tokens
sequence
docstring
stringlengths
6
2.61k
docstring_tokens
sequence
sha
stringlengths
40
40
url
stringlengths
85
252
2,700
ipfs/go-ipld-cbor
encoding/marshaller.go
Encode
func (m *Marshaller) Encode(obj interface{}, w io.Writer) error { m.writer.w = w err := m.marshal.Marshal(obj) m.writer.w = nil return err }
go
func (m *Marshaller) Encode(obj interface{}, w io.Writer) error { m.writer.w = w err := m.marshal.Marshal(obj) m.writer.w = nil return err }
[ "func", "(", "m", "*", "Marshaller", ")", "Encode", "(", "obj", "interface", "{", "}", ",", "w", "io", ".", "Writer", ")", "error", "{", "m", ".", "writer", ".", "w", "=", "w", "\n", "err", ":=", "m", ".", "marshal", ".", "Marshal", "(", "obj", ")", "\n", "m", ".", "writer", ".", "w", "=", "nil", "\n", "return", "err", "\n", "}" ]
// Encode encodes the given object to the given writer.
[ "Encode", "encodes", "the", "given", "object", "to", "the", "given", "writer", "." ]
59d81622555073ee8fdb6eed13c728a1fedeb724
https://github.com/ipfs/go-ipld-cbor/blob/59d81622555073ee8fdb6eed13c728a1fedeb724/encoding/marshaller.go#L34-L39
2,701
ipfs/go-ipld-cbor
encoding/marshaller.go
Marshal
func (m *Marshaller) Marshal(obj interface{}) ([]byte, error) { var buf bytes.Buffer if err := m.Encode(obj, &buf); err != nil { return nil, err } return buf.Bytes(), nil }
go
func (m *Marshaller) Marshal(obj interface{}) ([]byte, error) { var buf bytes.Buffer if err := m.Encode(obj, &buf); err != nil { return nil, err } return buf.Bytes(), nil }
[ "func", "(", "m", "*", "Marshaller", ")", "Marshal", "(", "obj", "interface", "{", "}", ")", "(", "[", "]", "byte", ",", "error", ")", "{", "var", "buf", "bytes", ".", "Buffer", "\n", "if", "err", ":=", "m", ".", "Encode", "(", "obj", ",", "&", "buf", ")", ";", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "return", "buf", ".", "Bytes", "(", ")", ",", "nil", "\n", "}" ]
// Marshal marshels the given object to a byte slice.
[ "Marshal", "marshels", "the", "given", "object", "to", "a", "byte", "slice", "." ]
59d81622555073ee8fdb6eed13c728a1fedeb724
https://github.com/ipfs/go-ipld-cbor/blob/59d81622555073ee8fdb6eed13c728a1fedeb724/encoding/marshaller.go#L42-L48
2,702
ipfs/go-ipld-cbor
encoding/marshaller.go
NewPooledMarshaller
func NewPooledMarshaller(atl atlas.Atlas) PooledMarshaller { return PooledMarshaller{ pool: sync.Pool{ New: func() interface{} { return NewMarshallerAtlased(atl) }, }, } }
go
func NewPooledMarshaller(atl atlas.Atlas) PooledMarshaller { return PooledMarshaller{ pool: sync.Pool{ New: func() interface{} { return NewMarshallerAtlased(atl) }, }, } }
[ "func", "NewPooledMarshaller", "(", "atl", "atlas", ".", "Atlas", ")", "PooledMarshaller", "{", "return", "PooledMarshaller", "{", "pool", ":", "sync", ".", "Pool", "{", "New", ":", "func", "(", ")", "interface", "{", "}", "{", "return", "NewMarshallerAtlased", "(", "atl", ")", "\n", "}", ",", "}", ",", "}", "\n", "}" ]
// NewPooledMarshaller returns a PooledMarshaller with the given atlas. Do not // copy after use.
[ "NewPooledMarshaller", "returns", "a", "PooledMarshaller", "with", "the", "given", "atlas", ".", "Do", "not", "copy", "after", "use", "." ]
59d81622555073ee8fdb6eed13c728a1fedeb724
https://github.com/ipfs/go-ipld-cbor/blob/59d81622555073ee8fdb6eed13c728a1fedeb724/encoding/marshaller.go#L57-L65
2,703
ipfs/go-ipld-cbor
encoding/marshaller.go
Marshal
func (p *PooledMarshaller) Marshal(obj interface{}) ([]byte, error) { m := p.pool.Get().(*Marshaller) bts, err := m.Marshal(obj) p.pool.Put(m) return bts, err }
go
func (p *PooledMarshaller) Marshal(obj interface{}) ([]byte, error) { m := p.pool.Get().(*Marshaller) bts, err := m.Marshal(obj) p.pool.Put(m) return bts, err }
[ "func", "(", "p", "*", "PooledMarshaller", ")", "Marshal", "(", "obj", "interface", "{", "}", ")", "(", "[", "]", "byte", ",", "error", ")", "{", "m", ":=", "p", ".", "pool", ".", "Get", "(", ")", ".", "(", "*", "Marshaller", ")", "\n", "bts", ",", "err", ":=", "m", ".", "Marshal", "(", "obj", ")", "\n", "p", ".", "pool", ".", "Put", "(", "m", ")", "\n", "return", "bts", ",", "err", "\n", "}" ]
// Marshal marshals the passed object using the pool of marshallers.
[ "Marshal", "marshals", "the", "passed", "object", "using", "the", "pool", "of", "marshallers", "." ]
59d81622555073ee8fdb6eed13c728a1fedeb724
https://github.com/ipfs/go-ipld-cbor/blob/59d81622555073ee8fdb6eed13c728a1fedeb724/encoding/marshaller.go#L68-L73
2,704
ipfs/go-ipld-cbor
encoding/marshaller.go
Encode
func (p *PooledMarshaller) Encode(obj interface{}, w io.Writer) error { m := p.pool.Get().(*Marshaller) err := m.Encode(obj, w) p.pool.Put(m) return err }
go
func (p *PooledMarshaller) Encode(obj interface{}, w io.Writer) error { m := p.pool.Get().(*Marshaller) err := m.Encode(obj, w) p.pool.Put(m) return err }
[ "func", "(", "p", "*", "PooledMarshaller", ")", "Encode", "(", "obj", "interface", "{", "}", ",", "w", "io", ".", "Writer", ")", "error", "{", "m", ":=", "p", ".", "pool", ".", "Get", "(", ")", ".", "(", "*", "Marshaller", ")", "\n", "err", ":=", "m", ".", "Encode", "(", "obj", ",", "w", ")", "\n", "p", ".", "pool", ".", "Put", "(", "m", ")", "\n", "return", "err", "\n", "}" ]
// Encode encodes the passed object to the given writer using the pool of // marshallers.
[ "Encode", "encodes", "the", "passed", "object", "to", "the", "given", "writer", "using", "the", "pool", "of", "marshallers", "." ]
59d81622555073ee8fdb6eed13c728a1fedeb724
https://github.com/ipfs/go-ipld-cbor/blob/59d81622555073ee8fdb6eed13c728a1fedeb724/encoding/marshaller.go#L77-L82
2,705
ipfs/go-ipld-cbor
encoding/unmarshaller.go
NewUnmarshallerAtlased
func NewUnmarshallerAtlased(atl atlas.Atlas) *Unmarshaller { m := new(Unmarshaller) m.unmarshal = cbor.NewUnmarshallerAtlased(cbor.DecodeOptions{CoerceUndefToNull: true}, &m.reader, atl) return m }
go
func NewUnmarshallerAtlased(atl atlas.Atlas) *Unmarshaller { m := new(Unmarshaller) m.unmarshal = cbor.NewUnmarshallerAtlased(cbor.DecodeOptions{CoerceUndefToNull: true}, &m.reader, atl) return m }
[ "func", "NewUnmarshallerAtlased", "(", "atl", "atlas", ".", "Atlas", ")", "*", "Unmarshaller", "{", "m", ":=", "new", "(", "Unmarshaller", ")", "\n", "m", ".", "unmarshal", "=", "cbor", ".", "NewUnmarshallerAtlased", "(", "cbor", ".", "DecodeOptions", "{", "CoerceUndefToNull", ":", "true", "}", ",", "&", "m", ".", "reader", ",", "atl", ")", "\n", "return", "m", "\n", "}" ]
// NewUnmarshallerAtlased creates a new reusable unmarshaller.
[ "NewUnmarshallerAtlased", "creates", "a", "new", "reusable", "unmarshaller", "." ]
59d81622555073ee8fdb6eed13c728a1fedeb724
https://github.com/ipfs/go-ipld-cbor/blob/59d81622555073ee8fdb6eed13c728a1fedeb724/encoding/unmarshaller.go#L27-L31
2,706
ipfs/go-ipld-cbor
encoding/unmarshaller.go
Decode
func (m *Unmarshaller) Decode(r io.Reader, obj interface{}) error { m.reader.r = r err := m.unmarshal.Unmarshal(obj) m.reader.r = nil return err }
go
func (m *Unmarshaller) Decode(r io.Reader, obj interface{}) error { m.reader.r = r err := m.unmarshal.Unmarshal(obj) m.reader.r = nil return err }
[ "func", "(", "m", "*", "Unmarshaller", ")", "Decode", "(", "r", "io", ".", "Reader", ",", "obj", "interface", "{", "}", ")", "error", "{", "m", ".", "reader", ".", "r", "=", "r", "\n", "err", ":=", "m", ".", "unmarshal", ".", "Unmarshal", "(", "obj", ")", "\n", "m", ".", "reader", ".", "r", "=", "nil", "\n", "return", "err", "\n", "}" ]
// Decode reads a CBOR object from the given reader and decodes it into the // given object.
[ "Decode", "reads", "a", "CBOR", "object", "from", "the", "given", "reader", "and", "decodes", "it", "into", "the", "given", "object", "." ]
59d81622555073ee8fdb6eed13c728a1fedeb724
https://github.com/ipfs/go-ipld-cbor/blob/59d81622555073ee8fdb6eed13c728a1fedeb724/encoding/unmarshaller.go#L35-L40
2,707
ipfs/go-ipld-cbor
encoding/unmarshaller.go
Unmarshal
func (m *Unmarshaller) Unmarshal(b []byte, obj interface{}) error { return m.Decode(bytes.NewReader(b), obj) }
go
func (m *Unmarshaller) Unmarshal(b []byte, obj interface{}) error { return m.Decode(bytes.NewReader(b), obj) }
[ "func", "(", "m", "*", "Unmarshaller", ")", "Unmarshal", "(", "b", "[", "]", "byte", ",", "obj", "interface", "{", "}", ")", "error", "{", "return", "m", ".", "Decode", "(", "bytes", ".", "NewReader", "(", "b", ")", ",", "obj", ")", "\n", "}" ]
// Unmarshal unmarshals the given CBOR byte slice into the given object.
[ "Unmarshal", "unmarshals", "the", "given", "CBOR", "byte", "slice", "into", "the", "given", "object", "." ]
59d81622555073ee8fdb6eed13c728a1fedeb724
https://github.com/ipfs/go-ipld-cbor/blob/59d81622555073ee8fdb6eed13c728a1fedeb724/encoding/unmarshaller.go#L43-L45
2,708
ipfs/go-ipld-cbor
encoding/unmarshaller.go
NewPooledUnmarshaller
func NewPooledUnmarshaller(atl atlas.Atlas) PooledUnmarshaller { return PooledUnmarshaller{ pool: sync.Pool{ New: func() interface{} { return NewUnmarshallerAtlased(atl) }, }, } }
go
func NewPooledUnmarshaller(atl atlas.Atlas) PooledUnmarshaller { return PooledUnmarshaller{ pool: sync.Pool{ New: func() interface{} { return NewUnmarshallerAtlased(atl) }, }, } }
[ "func", "NewPooledUnmarshaller", "(", "atl", "atlas", ".", "Atlas", ")", "PooledUnmarshaller", "{", "return", "PooledUnmarshaller", "{", "pool", ":", "sync", ".", "Pool", "{", "New", ":", "func", "(", ")", "interface", "{", "}", "{", "return", "NewUnmarshallerAtlased", "(", "atl", ")", "\n", "}", ",", "}", ",", "}", "\n", "}" ]
// NewPooledUnmarshaller returns a PooledUnmarshaller with the given atlas. Do // not copy after use.
[ "NewPooledUnmarshaller", "returns", "a", "PooledUnmarshaller", "with", "the", "given", "atlas", ".", "Do", "not", "copy", "after", "use", "." ]
59d81622555073ee8fdb6eed13c728a1fedeb724
https://github.com/ipfs/go-ipld-cbor/blob/59d81622555073ee8fdb6eed13c728a1fedeb724/encoding/unmarshaller.go#L54-L62
2,709
ipfs/go-ipld-cbor
encoding/unmarshaller.go
Decode
func (p *PooledUnmarshaller) Decode(r io.Reader, obj interface{}) error { u := p.pool.Get().(*Unmarshaller) err := u.Decode(r, obj) p.pool.Put(u) return err }
go
func (p *PooledUnmarshaller) Decode(r io.Reader, obj interface{}) error { u := p.pool.Get().(*Unmarshaller) err := u.Decode(r, obj) p.pool.Put(u) return err }
[ "func", "(", "p", "*", "PooledUnmarshaller", ")", "Decode", "(", "r", "io", ".", "Reader", ",", "obj", "interface", "{", "}", ")", "error", "{", "u", ":=", "p", ".", "pool", ".", "Get", "(", ")", ".", "(", "*", "Unmarshaller", ")", "\n", "err", ":=", "u", ".", "Decode", "(", "r", ",", "obj", ")", "\n", "p", ".", "pool", ".", "Put", "(", "u", ")", "\n", "return", "err", "\n", "}" ]
// Decode decodes an object from the passed reader into the given object using // the pool of unmarshallers.
[ "Decode", "decodes", "an", "object", "from", "the", "passed", "reader", "into", "the", "given", "object", "using", "the", "pool", "of", "unmarshallers", "." ]
59d81622555073ee8fdb6eed13c728a1fedeb724
https://github.com/ipfs/go-ipld-cbor/blob/59d81622555073ee8fdb6eed13c728a1fedeb724/encoding/unmarshaller.go#L66-L71
2,710
ipfs/go-ipld-cbor
encoding/unmarshaller.go
Unmarshal
func (p *PooledUnmarshaller) Unmarshal(b []byte, obj interface{}) error { u := p.pool.Get().(*Unmarshaller) err := u.Unmarshal(b, obj) p.pool.Put(u) return err }
go
func (p *PooledUnmarshaller) Unmarshal(b []byte, obj interface{}) error { u := p.pool.Get().(*Unmarshaller) err := u.Unmarshal(b, obj) p.pool.Put(u) return err }
[ "func", "(", "p", "*", "PooledUnmarshaller", ")", "Unmarshal", "(", "b", "[", "]", "byte", ",", "obj", "interface", "{", "}", ")", "error", "{", "u", ":=", "p", ".", "pool", ".", "Get", "(", ")", ".", "(", "*", "Unmarshaller", ")", "\n", "err", ":=", "u", ".", "Unmarshal", "(", "b", ",", "obj", ")", "\n", "p", ".", "pool", ".", "Put", "(", "u", ")", "\n", "return", "err", "\n", "}" ]
// Unmarshal unmarshals the passed object using the pool of unmarshallers.
[ "Unmarshal", "unmarshals", "the", "passed", "object", "using", "the", "pool", "of", "unmarshallers", "." ]
59d81622555073ee8fdb6eed13c728a1fedeb724
https://github.com/ipfs/go-ipld-cbor/blob/59d81622555073ee8fdb6eed13c728a1fedeb724/encoding/unmarshaller.go#L74-L79
2,711
fluent/fluent-logger-golang
fluent/fluent.go
Close
func (f *Fluent) Close() (err error) { if f.Config.Async { close(f.pending) f.wg.Wait() } f.close() return }
go
func (f *Fluent) Close() (err error) { if f.Config.Async { close(f.pending) f.wg.Wait() } f.close() return }
[ "func", "(", "f", "*", "Fluent", ")", "Close", "(", ")", "(", "err", "error", ")", "{", "if", "f", ".", "Config", ".", "Async", "{", "close", "(", "f", ".", "pending", ")", "\n", "f", ".", "wg", ".", "Wait", "(", ")", "\n", "}", "\n", "f", ".", "close", "(", ")", "\n", "return", "\n", "}" ]
// Close closes the connection, waiting for pending logs to be sent
[ "Close", "closes", "the", "connection", "waiting", "for", "pending", "logs", "to", "be", "sent" ]
7a6c9dcd7f14c2ed5d8c55c11b894e5455ee311b
https://github.com/fluent/fluent-logger-golang/blob/7a6c9dcd7f14c2ed5d8c55c11b894e5455ee311b/fluent/fluent.go#L294-L301
2,712
fluent/fluent-logger-golang
fluent/fluent.go
appendBuffer
func (f *Fluent) appendBuffer(msg *msgToSend) error { select { case f.pending <- msg: default: return fmt.Errorf("fluent#appendBuffer: Buffer full, limit %v", f.Config.BufferLimit) } return nil }
go
func (f *Fluent) appendBuffer(msg *msgToSend) error { select { case f.pending <- msg: default: return fmt.Errorf("fluent#appendBuffer: Buffer full, limit %v", f.Config.BufferLimit) } return nil }
[ "func", "(", "f", "*", "Fluent", ")", "appendBuffer", "(", "msg", "*", "msgToSend", ")", "error", "{", "select", "{", "case", "f", ".", "pending", "<-", "msg", ":", "default", ":", "return", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "f", ".", "Config", ".", "BufferLimit", ")", "\n", "}", "\n", "return", "nil", "\n", "}" ]
// appendBuffer appends data to buffer with lock.
[ "appendBuffer", "appends", "data", "to", "buffer", "with", "lock", "." ]
7a6c9dcd7f14c2ed5d8c55c11b894e5455ee311b
https://github.com/fluent/fluent-logger-golang/blob/7a6c9dcd7f14c2ed5d8c55c11b894e5455ee311b/fluent/fluent.go#L304-L311
2,713
fluent/fluent-logger-golang
fluent/fluent.go
close
func (f *Fluent) close() { f.muconn.Lock() if f.conn != nil { f.conn.Close() f.conn = nil } f.muconn.Unlock() }
go
func (f *Fluent) close() { f.muconn.Lock() if f.conn != nil { f.conn.Close() f.conn = nil } f.muconn.Unlock() }
[ "func", "(", "f", "*", "Fluent", ")", "close", "(", ")", "{", "f", ".", "muconn", ".", "Lock", "(", ")", "\n", "if", "f", ".", "conn", "!=", "nil", "{", "f", ".", "conn", ".", "Close", "(", ")", "\n", "f", ".", "conn", "=", "nil", "\n", "}", "\n", "f", ".", "muconn", ".", "Unlock", "(", ")", "\n", "}" ]
// close closes the connection.
[ "close", "closes", "the", "connection", "." ]
7a6c9dcd7f14c2ed5d8c55c11b894e5455ee311b
https://github.com/fluent/fluent-logger-golang/blob/7a6c9dcd7f14c2ed5d8c55c11b894e5455ee311b/fluent/fluent.go#L314-L321
2,714
fluent/fluent-logger-golang
fluent/fluent.go
connect
func (f *Fluent) connect() (err error) { switch f.Config.FluentNetwork { case "tcp": f.conn, err = net.DialTimeout(f.Config.FluentNetwork, f.Config.FluentHost+":"+strconv.Itoa(f.Config.FluentPort), f.Config.Timeout) case "unix": f.conn, err = net.DialTimeout(f.Config.FluentNetwork, f.Config.FluentSocketPath, f.Config.Timeout) default: err = net.UnknownNetworkError(f.Config.FluentNetwork) } return err }
go
func (f *Fluent) connect() (err error) { switch f.Config.FluentNetwork { case "tcp": f.conn, err = net.DialTimeout(f.Config.FluentNetwork, f.Config.FluentHost+":"+strconv.Itoa(f.Config.FluentPort), f.Config.Timeout) case "unix": f.conn, err = net.DialTimeout(f.Config.FluentNetwork, f.Config.FluentSocketPath, f.Config.Timeout) default: err = net.UnknownNetworkError(f.Config.FluentNetwork) } return err }
[ "func", "(", "f", "*", "Fluent", ")", "connect", "(", ")", "(", "err", "error", ")", "{", "switch", "f", ".", "Config", ".", "FluentNetwork", "{", "case", "\"", "\"", ":", "f", ".", "conn", ",", "err", "=", "net", ".", "DialTimeout", "(", "f", ".", "Config", ".", "FluentNetwork", ",", "f", ".", "Config", ".", "FluentHost", "+", "\"", "\"", "+", "strconv", ".", "Itoa", "(", "f", ".", "Config", ".", "FluentPort", ")", ",", "f", ".", "Config", ".", "Timeout", ")", "\n", "case", "\"", "\"", ":", "f", ".", "conn", ",", "err", "=", "net", ".", "DialTimeout", "(", "f", ".", "Config", ".", "FluentNetwork", ",", "f", ".", "Config", ".", "FluentSocketPath", ",", "f", ".", "Config", ".", "Timeout", ")", "\n", "default", ":", "err", "=", "net", ".", "UnknownNetworkError", "(", "f", ".", "Config", ".", "FluentNetwork", ")", "\n", "}", "\n", "return", "err", "\n", "}" ]
// connect establishes a new connection using the specified transport.
[ "connect", "establishes", "a", "new", "connection", "using", "the", "specified", "transport", "." ]
7a6c9dcd7f14c2ed5d8c55c11b894e5455ee311b
https://github.com/fluent/fluent-logger-golang/blob/7a6c9dcd7f14c2ed5d8c55c11b894e5455ee311b/fluent/fluent.go#L324-L335
2,715
VividCortex/gohistogram
numerichistogram.go
NewHistogram
func NewHistogram(n int) *NumericHistogram { return &NumericHistogram{ bins: make([]bin, 0), maxbins: n, total: 0, } }
go
func NewHistogram(n int) *NumericHistogram { return &NumericHistogram{ bins: make([]bin, 0), maxbins: n, total: 0, } }
[ "func", "NewHistogram", "(", "n", "int", ")", "*", "NumericHistogram", "{", "return", "&", "NumericHistogram", "{", "bins", ":", "make", "(", "[", "]", "bin", ",", "0", ")", ",", "maxbins", ":", "n", ",", "total", ":", "0", ",", "}", "\n", "}" ]
// NewHistogram returns a new NumericHistogram with a maximum of n bins. // // There is no "optimal" bin count, but somewhere between 20 and 80 bins // should be sufficient.
[ "NewHistogram", "returns", "a", "new", "NumericHistogram", "with", "a", "maximum", "of", "n", "bins", ".", "There", "is", "no", "optimal", "bin", "count", "but", "somewhere", "between", "20", "and", "80", "bins", "should", "be", "sufficient", "." ]
51564d9861991fb0ad0f531c99ef602d0f9866e6
https://github.com/VividCortex/gohistogram/blob/51564d9861991fb0ad0f531c99ef602d0f9866e6/numerichistogram.go#L20-L26
2,716
VividCortex/gohistogram
numerichistogram.go
Mean
func (h *NumericHistogram) Mean() float64 { if h.total == 0 { return 0 } sum := 0.0 for i := range h.bins { sum += h.bins[i].value * h.bins[i].count } return sum / float64(h.total) }
go
func (h *NumericHistogram) Mean() float64 { if h.total == 0 { return 0 } sum := 0.0 for i := range h.bins { sum += h.bins[i].value * h.bins[i].count } return sum / float64(h.total) }
[ "func", "(", "h", "*", "NumericHistogram", ")", "Mean", "(", ")", "float64", "{", "if", "h", ".", "total", "==", "0", "{", "return", "0", "\n", "}", "\n\n", "sum", ":=", "0.0", "\n\n", "for", "i", ":=", "range", "h", ".", "bins", "{", "sum", "+=", "h", ".", "bins", "[", "i", "]", ".", "value", "*", "h", ".", "bins", "[", "i", "]", ".", "count", "\n", "}", "\n\n", "return", "sum", "/", "float64", "(", "h", ".", "total", ")", "\n", "}" ]
// Mean returns the sample mean of the distribution
[ "Mean", "returns", "the", "sample", "mean", "of", "the", "distribution" ]
51564d9861991fb0ad0f531c99ef602d0f9866e6
https://github.com/VividCortex/gohistogram/blob/51564d9861991fb0ad0f531c99ef602d0f9866e6/numerichistogram.go#L79-L91
2,717
VividCortex/gohistogram
numerichistogram.go
trim
func (h *NumericHistogram) trim() { for len(h.bins) > h.maxbins { // Find closest bins in terms of value minDelta := 1e99 minDeltaIndex := 0 for i := range h.bins { if i == 0 { continue } if delta := h.bins[i].value - h.bins[i-1].value; delta < minDelta { minDelta = delta minDeltaIndex = i } } // We need to merge bins minDeltaIndex-1 and minDeltaIndex totalCount := h.bins[minDeltaIndex-1].count + h.bins[minDeltaIndex].count mergedbin := bin{ value: (h.bins[minDeltaIndex-1].value* h.bins[minDeltaIndex-1].count + h.bins[minDeltaIndex].value* h.bins[minDeltaIndex].count) / totalCount, // weighted average count: totalCount, // summed heights } head := append(make([]bin, 0), h.bins[0:minDeltaIndex-1]...) tail := append([]bin{mergedbin}, h.bins[minDeltaIndex+1:]...) h.bins = append(head, tail...) } }
go
func (h *NumericHistogram) trim() { for len(h.bins) > h.maxbins { // Find closest bins in terms of value minDelta := 1e99 minDeltaIndex := 0 for i := range h.bins { if i == 0 { continue } if delta := h.bins[i].value - h.bins[i-1].value; delta < minDelta { minDelta = delta minDeltaIndex = i } } // We need to merge bins minDeltaIndex-1 and minDeltaIndex totalCount := h.bins[minDeltaIndex-1].count + h.bins[minDeltaIndex].count mergedbin := bin{ value: (h.bins[minDeltaIndex-1].value* h.bins[minDeltaIndex-1].count + h.bins[minDeltaIndex].value* h.bins[minDeltaIndex].count) / totalCount, // weighted average count: totalCount, // summed heights } head := append(make([]bin, 0), h.bins[0:minDeltaIndex-1]...) tail := append([]bin{mergedbin}, h.bins[minDeltaIndex+1:]...) h.bins = append(head, tail...) } }
[ "func", "(", "h", "*", "NumericHistogram", ")", "trim", "(", ")", "{", "for", "len", "(", "h", ".", "bins", ")", ">", "h", ".", "maxbins", "{", "// Find closest bins in terms of value", "minDelta", ":=", "1e99", "\n", "minDeltaIndex", ":=", "0", "\n", "for", "i", ":=", "range", "h", ".", "bins", "{", "if", "i", "==", "0", "{", "continue", "\n", "}", "\n\n", "if", "delta", ":=", "h", ".", "bins", "[", "i", "]", ".", "value", "-", "h", ".", "bins", "[", "i", "-", "1", "]", ".", "value", ";", "delta", "<", "minDelta", "{", "minDelta", "=", "delta", "\n", "minDeltaIndex", "=", "i", "\n", "}", "\n", "}", "\n\n", "// We need to merge bins minDeltaIndex-1 and minDeltaIndex", "totalCount", ":=", "h", ".", "bins", "[", "minDeltaIndex", "-", "1", "]", ".", "count", "+", "h", ".", "bins", "[", "minDeltaIndex", "]", ".", "count", "\n", "mergedbin", ":=", "bin", "{", "value", ":", "(", "h", ".", "bins", "[", "minDeltaIndex", "-", "1", "]", ".", "value", "*", "h", ".", "bins", "[", "minDeltaIndex", "-", "1", "]", ".", "count", "+", "h", ".", "bins", "[", "minDeltaIndex", "]", ".", "value", "*", "h", ".", "bins", "[", "minDeltaIndex", "]", ".", "count", ")", "/", "totalCount", ",", "// weighted average", "count", ":", "totalCount", ",", "// summed heights", "}", "\n", "head", ":=", "append", "(", "make", "(", "[", "]", "bin", ",", "0", ")", ",", "h", ".", "bins", "[", "0", ":", "minDeltaIndex", "-", "1", "]", "...", ")", "\n", "tail", ":=", "append", "(", "[", "]", "bin", "{", "mergedbin", "}", ",", "h", ".", "bins", "[", "minDeltaIndex", "+", "1", ":", "]", "...", ")", "\n", "h", ".", "bins", "=", "append", "(", "head", ",", "tail", "...", ")", "\n", "}", "\n", "}" ]
// trim merges adjacent bins to decrease the bin count to the maximum value
[ "trim", "merges", "adjacent", "bins", "to", "decrease", "the", "bin", "count", "to", "the", "maximum", "value" ]
51564d9861991fb0ad0f531c99ef602d0f9866e6
https://github.com/VividCortex/gohistogram/blob/51564d9861991fb0ad0f531c99ef602d0f9866e6/numerichistogram.go#L114-L144
2,718
VividCortex/gohistogram
numerichistogram.go
String
func (h *NumericHistogram) String() (str string) { str += fmt.Sprintln("Total:", h.total) for i := range h.bins { var bar string for j := 0; j < int(float64(h.bins[i].count)/float64(h.total)*200); j++ { bar += "." } str += fmt.Sprintln(h.bins[i].value, "\t", bar) } return }
go
func (h *NumericHistogram) String() (str string) { str += fmt.Sprintln("Total:", h.total) for i := range h.bins { var bar string for j := 0; j < int(float64(h.bins[i].count)/float64(h.total)*200); j++ { bar += "." } str += fmt.Sprintln(h.bins[i].value, "\t", bar) } return }
[ "func", "(", "h", "*", "NumericHistogram", ")", "String", "(", ")", "(", "str", "string", ")", "{", "str", "+=", "fmt", ".", "Sprintln", "(", "\"", "\"", ",", "h", ".", "total", ")", "\n\n", "for", "i", ":=", "range", "h", ".", "bins", "{", "var", "bar", "string", "\n", "for", "j", ":=", "0", ";", "j", "<", "int", "(", "float64", "(", "h", ".", "bins", "[", "i", "]", ".", "count", ")", "/", "float64", "(", "h", ".", "total", ")", "*", "200", ")", ";", "j", "++", "{", "bar", "+=", "\"", "\"", "\n", "}", "\n", "str", "+=", "fmt", ".", "Sprintln", "(", "h", ".", "bins", "[", "i", "]", ".", "value", ",", "\"", "\\t", "\"", ",", "bar", ")", "\n", "}", "\n\n", "return", "\n", "}" ]
// String returns a string reprentation of the histogram, // which is useful for printing to a terminal.
[ "String", "returns", "a", "string", "reprentation", "of", "the", "histogram", "which", "is", "useful", "for", "printing", "to", "a", "terminal", "." ]
51564d9861991fb0ad0f531c99ef602d0f9866e6
https://github.com/VividCortex/gohistogram/blob/51564d9861991fb0ad0f531c99ef602d0f9866e6/numerichistogram.go#L148-L160
2,719
VividCortex/gohistogram
weightedhistogram.go
CDF
func (h *WeightedHistogram) CDF(x float64) float64 { count := 0.0 for i := range h.bins { if h.bins[i].value <= x { count += float64(h.bins[i].count) } } return count / h.total }
go
func (h *WeightedHistogram) CDF(x float64) float64 { count := 0.0 for i := range h.bins { if h.bins[i].value <= x { count += float64(h.bins[i].count) } } return count / h.total }
[ "func", "(", "h", "*", "WeightedHistogram", ")", "CDF", "(", "x", "float64", ")", "float64", "{", "count", ":=", "0.0", "\n", "for", "i", ":=", "range", "h", ".", "bins", "{", "if", "h", ".", "bins", "[", "i", "]", ".", "value", "<=", "x", "{", "count", "+=", "float64", "(", "h", ".", "bins", "[", "i", "]", ".", "count", ")", "\n", "}", "\n", "}", "\n\n", "return", "count", "/", "h", ".", "total", "\n", "}" ]
// CDF returns the value of the cumulative distribution function // at x
[ "CDF", "returns", "the", "value", "of", "the", "cumulative", "distribution", "function", "at", "x" ]
51564d9861991fb0ad0f531c99ef602d0f9866e6
https://github.com/VividCortex/gohistogram/blob/51564d9861991fb0ad0f531c99ef602d0f9866e6/weightedhistogram.go#L92-L101
2,720
wvanbergen/kafka
consumergroup/utils.go
dividePartitionsBetweenConsumers
func dividePartitionsBetweenConsumers(consumers kazoo.ConsumergroupInstanceList, partitions partitionLeaders) map[string][]*kazoo.Partition { result := make(map[string][]*kazoo.Partition) plen := len(partitions) clen := len(consumers) if clen == 0 { return result } sort.Sort(partitions) sort.Sort(consumers) n := plen / clen m := plen % clen p := 0 for i, consumer := range consumers { first := p last := first + n if m > 0 && i < m { last++ } if last > plen { last = plen } for _, pl := range partitions[first:last] { result[consumer.ID] = append(result[consumer.ID], pl.partition) } p = last } return result }
go
func dividePartitionsBetweenConsumers(consumers kazoo.ConsumergroupInstanceList, partitions partitionLeaders) map[string][]*kazoo.Partition { result := make(map[string][]*kazoo.Partition) plen := len(partitions) clen := len(consumers) if clen == 0 { return result } sort.Sort(partitions) sort.Sort(consumers) n := plen / clen m := plen % clen p := 0 for i, consumer := range consumers { first := p last := first + n if m > 0 && i < m { last++ } if last > plen { last = plen } for _, pl := range partitions[first:last] { result[consumer.ID] = append(result[consumer.ID], pl.partition) } p = last } return result }
[ "func", "dividePartitionsBetweenConsumers", "(", "consumers", "kazoo", ".", "ConsumergroupInstanceList", ",", "partitions", "partitionLeaders", ")", "map", "[", "string", "]", "[", "]", "*", "kazoo", ".", "Partition", "{", "result", ":=", "make", "(", "map", "[", "string", "]", "[", "]", "*", "kazoo", ".", "Partition", ")", "\n\n", "plen", ":=", "len", "(", "partitions", ")", "\n", "clen", ":=", "len", "(", "consumers", ")", "\n", "if", "clen", "==", "0", "{", "return", "result", "\n", "}", "\n\n", "sort", ".", "Sort", "(", "partitions", ")", "\n", "sort", ".", "Sort", "(", "consumers", ")", "\n\n", "n", ":=", "plen", "/", "clen", "\n", "m", ":=", "plen", "%", "clen", "\n", "p", ":=", "0", "\n", "for", "i", ",", "consumer", ":=", "range", "consumers", "{", "first", ":=", "p", "\n", "last", ":=", "first", "+", "n", "\n", "if", "m", ">", "0", "&&", "i", "<", "m", "{", "last", "++", "\n", "}", "\n", "if", "last", ">", "plen", "{", "last", "=", "plen", "\n", "}", "\n\n", "for", "_", ",", "pl", ":=", "range", "partitions", "[", "first", ":", "last", "]", "{", "result", "[", "consumer", ".", "ID", "]", "=", "append", "(", "result", "[", "consumer", ".", "ID", "]", ",", "pl", ".", "partition", ")", "\n", "}", "\n", "p", "=", "last", "\n", "}", "\n\n", "return", "result", "\n", "}" ]
// Divides a set of partitions between a set of consumers.
[ "Divides", "a", "set", "of", "partitions", "between", "a", "set", "of", "consumers", "." ]
e2edea948ddfee841ea9a263b32ccca15f7d6c2f
https://github.com/wvanbergen/kafka/blob/e2edea948ddfee841ea9a263b32ccca15f7d6c2f/consumergroup/utils.go#L30-L62
2,721
wvanbergen/kafka
consumergroup/offset_manager.go
NewZookeeperOffsetManager
func NewZookeeperOffsetManager(cg *ConsumerGroup, config *OffsetManagerConfig) OffsetManager { if config == nil { config = NewOffsetManagerConfig() } zom := &zookeeperOffsetManager{ config: config, cg: cg, offsets: make(offsetsMap), closing: make(chan struct{}), closed: make(chan struct{}), flush: make(chan struct{}), flushErr: make(chan error), } go zom.offsetCommitter() return zom }
go
func NewZookeeperOffsetManager(cg *ConsumerGroup, config *OffsetManagerConfig) OffsetManager { if config == nil { config = NewOffsetManagerConfig() } zom := &zookeeperOffsetManager{ config: config, cg: cg, offsets: make(offsetsMap), closing: make(chan struct{}), closed: make(chan struct{}), flush: make(chan struct{}), flushErr: make(chan error), } go zom.offsetCommitter() return zom }
[ "func", "NewZookeeperOffsetManager", "(", "cg", "*", "ConsumerGroup", ",", "config", "*", "OffsetManagerConfig", ")", "OffsetManager", "{", "if", "config", "==", "nil", "{", "config", "=", "NewOffsetManagerConfig", "(", ")", "\n", "}", "\n\n", "zom", ":=", "&", "zookeeperOffsetManager", "{", "config", ":", "config", ",", "cg", ":", "cg", ",", "offsets", ":", "make", "(", "offsetsMap", ")", ",", "closing", ":", "make", "(", "chan", "struct", "{", "}", ")", ",", "closed", ":", "make", "(", "chan", "struct", "{", "}", ")", ",", "flush", ":", "make", "(", "chan", "struct", "{", "}", ")", ",", "flushErr", ":", "make", "(", "chan", "error", ")", ",", "}", "\n\n", "go", "zom", ".", "offsetCommitter", "(", ")", "\n\n", "return", "zom", "\n", "}" ]
// NewZookeeperOffsetManager returns an offset manager that uses Zookeeper // to store offsets.
[ "NewZookeeperOffsetManager", "returns", "an", "offset", "manager", "that", "uses", "Zookeeper", "to", "store", "offsets", "." ]
e2edea948ddfee841ea9a263b32ccca15f7d6c2f
https://github.com/wvanbergen/kafka/blob/e2edea948ddfee841ea9a263b32ccca15f7d6c2f/consumergroup/offset_manager.go#L91-L109
2,722
wvanbergen/kafka
consumergroup/offset_manager.go
markAsProcessed
func (pot *partitionOffsetTracker) markAsProcessed(offset int64) bool { pot.l.Lock() defer pot.l.Unlock() if offset > pot.highestProcessedOffset { pot.highestProcessedOffset = offset if pot.waitingForOffset == pot.highestProcessedOffset { close(pot.done) } return true } else { return false } }
go
func (pot *partitionOffsetTracker) markAsProcessed(offset int64) bool { pot.l.Lock() defer pot.l.Unlock() if offset > pot.highestProcessedOffset { pot.highestProcessedOffset = offset if pot.waitingForOffset == pot.highestProcessedOffset { close(pot.done) } return true } else { return false } }
[ "func", "(", "pot", "*", "partitionOffsetTracker", ")", "markAsProcessed", "(", "offset", "int64", ")", "bool", "{", "pot", ".", "l", ".", "Lock", "(", ")", "\n", "defer", "pot", ".", "l", ".", "Unlock", "(", ")", "\n", "if", "offset", ">", "pot", ".", "highestProcessedOffset", "{", "pot", ".", "highestProcessedOffset", "=", "offset", "\n", "if", "pot", ".", "waitingForOffset", "==", "pot", ".", "highestProcessedOffset", "{", "close", "(", "pot", ".", "done", ")", "\n", "}", "\n", "return", "true", "\n", "}", "else", "{", "return", "false", "\n", "}", "\n", "}" ]
// MarkAsProcessed marks the provided offset as highest processed offset if // it's higher than any previous offset it has received.
[ "MarkAsProcessed", "marks", "the", "provided", "offset", "as", "highest", "processed", "offset", "if", "it", "s", "higher", "than", "any", "previous", "offset", "it", "has", "received", "." ]
e2edea948ddfee841ea9a263b32ccca15f7d6c2f
https://github.com/wvanbergen/kafka/blob/e2edea948ddfee841ea9a263b32ccca15f7d6c2f/consumergroup/offset_manager.go#L252-L264
2,723
wvanbergen/kafka
consumergroup/offset_manager.go
commit
func (pot *partitionOffsetTracker) commit(committer offsetCommitter) error { pot.l.Lock() defer pot.l.Unlock() if pot.highestProcessedOffset > pot.lastCommittedOffset { if err := committer(pot.highestProcessedOffset); err != nil { return err } pot.lastCommittedOffset = pot.highestProcessedOffset return nil } else { return nil } }
go
func (pot *partitionOffsetTracker) commit(committer offsetCommitter) error { pot.l.Lock() defer pot.l.Unlock() if pot.highestProcessedOffset > pot.lastCommittedOffset { if err := committer(pot.highestProcessedOffset); err != nil { return err } pot.lastCommittedOffset = pot.highestProcessedOffset return nil } else { return nil } }
[ "func", "(", "pot", "*", "partitionOffsetTracker", ")", "commit", "(", "committer", "offsetCommitter", ")", "error", "{", "pot", ".", "l", ".", "Lock", "(", ")", "\n", "defer", "pot", ".", "l", ".", "Unlock", "(", ")", "\n\n", "if", "pot", ".", "highestProcessedOffset", ">", "pot", ".", "lastCommittedOffset", "{", "if", "err", ":=", "committer", "(", "pot", ".", "highestProcessedOffset", ")", ";", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "pot", ".", "lastCommittedOffset", "=", "pot", ".", "highestProcessedOffset", "\n", "return", "nil", "\n", "}", "else", "{", "return", "nil", "\n", "}", "\n", "}" ]
// Commit calls a committer function if the highest processed offset is out // of sync with the last committed offset.
[ "Commit", "calls", "a", "committer", "function", "if", "the", "highest", "processed", "offset", "is", "out", "of", "sync", "with", "the", "last", "committed", "offset", "." ]
e2edea948ddfee841ea9a263b32ccca15f7d6c2f
https://github.com/wvanbergen/kafka/blob/e2edea948ddfee841ea9a263b32ccca15f7d6c2f/consumergroup/offset_manager.go#L268-L281
2,724
wvanbergen/kafka
consumergroup/consumer_group.go
JoinConsumerGroup
func JoinConsumerGroup(name string, topics []string, zookeeper []string, config *Config) (cg *ConsumerGroup, err error) { if name == "" { return nil, sarama.ConfigurationError("Empty consumergroup name") } if len(topics) == 0 { return nil, sarama.ConfigurationError("No topics provided") } if len(zookeeper) == 0 { return nil, errors.New("You need to provide at least one zookeeper node address!") } if config == nil { config = NewConfig() } config.ClientID = name // Validate configuration if err = config.Validate(); err != nil { return } var kz *kazoo.Kazoo if kz, err = kazoo.NewKazoo(zookeeper, config.Zookeeper); err != nil { return } brokers, err := kz.BrokerList() if err != nil { kz.Close() return } group := kz.Consumergroup(name) if config.Offsets.ResetOffsets { err = group.ResetOffsets() if err != nil { kz.Close() return } } instance := group.NewInstance() var consumer sarama.Consumer if consumer, err = sarama.NewConsumer(brokers, config.Config); err != nil { kz.Close() return } cg = &ConsumerGroup{ config: config, consumer: consumer, kazoo: kz, group: group, instance: instance, messages: make(chan *sarama.ConsumerMessage, config.ChannelBufferSize), errors: make(chan error, config.ChannelBufferSize), stopper: make(chan struct{}), } // Register consumer group if exists, err := cg.group.Exists(); err != nil { cg.Logf("FAILED to check for existence of consumergroup: %s!\n", err) _ = consumer.Close() _ = kz.Close() return nil, err } else if !exists { cg.Logf("Consumergroup `%s` does not yet exists, creating...\n", cg.group.Name) if err := cg.group.Create(); err != nil { cg.Logf("FAILED to create consumergroup in Zookeeper: %s!\n", err) _ = consumer.Close() _ = kz.Close() return nil, err } } // Register itself with zookeeper if err := cg.instance.Register(topics); err != nil { cg.Logf("FAILED to register consumer instance: %s!\n", err) return nil, err } else { cg.Logf("Consumer instance registered (%s).", cg.instance.ID) } offsetConfig := OffsetManagerConfig{CommitInterval: config.Offsets.CommitInterval} cg.offsetManager = NewZookeeperOffsetManager(cg, &offsetConfig) go cg.topicListConsumer(topics) return }
go
func JoinConsumerGroup(name string, topics []string, zookeeper []string, config *Config) (cg *ConsumerGroup, err error) { if name == "" { return nil, sarama.ConfigurationError("Empty consumergroup name") } if len(topics) == 0 { return nil, sarama.ConfigurationError("No topics provided") } if len(zookeeper) == 0 { return nil, errors.New("You need to provide at least one zookeeper node address!") } if config == nil { config = NewConfig() } config.ClientID = name // Validate configuration if err = config.Validate(); err != nil { return } var kz *kazoo.Kazoo if kz, err = kazoo.NewKazoo(zookeeper, config.Zookeeper); err != nil { return } brokers, err := kz.BrokerList() if err != nil { kz.Close() return } group := kz.Consumergroup(name) if config.Offsets.ResetOffsets { err = group.ResetOffsets() if err != nil { kz.Close() return } } instance := group.NewInstance() var consumer sarama.Consumer if consumer, err = sarama.NewConsumer(brokers, config.Config); err != nil { kz.Close() return } cg = &ConsumerGroup{ config: config, consumer: consumer, kazoo: kz, group: group, instance: instance, messages: make(chan *sarama.ConsumerMessage, config.ChannelBufferSize), errors: make(chan error, config.ChannelBufferSize), stopper: make(chan struct{}), } // Register consumer group if exists, err := cg.group.Exists(); err != nil { cg.Logf("FAILED to check for existence of consumergroup: %s!\n", err) _ = consumer.Close() _ = kz.Close() return nil, err } else if !exists { cg.Logf("Consumergroup `%s` does not yet exists, creating...\n", cg.group.Name) if err := cg.group.Create(); err != nil { cg.Logf("FAILED to create consumergroup in Zookeeper: %s!\n", err) _ = consumer.Close() _ = kz.Close() return nil, err } } // Register itself with zookeeper if err := cg.instance.Register(topics); err != nil { cg.Logf("FAILED to register consumer instance: %s!\n", err) return nil, err } else { cg.Logf("Consumer instance registered (%s).", cg.instance.ID) } offsetConfig := OffsetManagerConfig{CommitInterval: config.Offsets.CommitInterval} cg.offsetManager = NewZookeeperOffsetManager(cg, &offsetConfig) go cg.topicListConsumer(topics) return }
[ "func", "JoinConsumerGroup", "(", "name", "string", ",", "topics", "[", "]", "string", ",", "zookeeper", "[", "]", "string", ",", "config", "*", "Config", ")", "(", "cg", "*", "ConsumerGroup", ",", "err", "error", ")", "{", "if", "name", "==", "\"", "\"", "{", "return", "nil", ",", "sarama", ".", "ConfigurationError", "(", "\"", "\"", ")", "\n", "}", "\n\n", "if", "len", "(", "topics", ")", "==", "0", "{", "return", "nil", ",", "sarama", ".", "ConfigurationError", "(", "\"", "\"", ")", "\n", "}", "\n\n", "if", "len", "(", "zookeeper", ")", "==", "0", "{", "return", "nil", ",", "errors", ".", "New", "(", "\"", "\"", ")", "\n", "}", "\n\n", "if", "config", "==", "nil", "{", "config", "=", "NewConfig", "(", ")", "\n", "}", "\n", "config", ".", "ClientID", "=", "name", "\n\n", "// Validate configuration", "if", "err", "=", "config", ".", "Validate", "(", ")", ";", "err", "!=", "nil", "{", "return", "\n", "}", "\n\n", "var", "kz", "*", "kazoo", ".", "Kazoo", "\n", "if", "kz", ",", "err", "=", "kazoo", ".", "NewKazoo", "(", "zookeeper", ",", "config", ".", "Zookeeper", ")", ";", "err", "!=", "nil", "{", "return", "\n", "}", "\n\n", "brokers", ",", "err", ":=", "kz", ".", "BrokerList", "(", ")", "\n", "if", "err", "!=", "nil", "{", "kz", ".", "Close", "(", ")", "\n", "return", "\n", "}", "\n\n", "group", ":=", "kz", ".", "Consumergroup", "(", "name", ")", "\n\n", "if", "config", ".", "Offsets", ".", "ResetOffsets", "{", "err", "=", "group", ".", "ResetOffsets", "(", ")", "\n", "if", "err", "!=", "nil", "{", "kz", ".", "Close", "(", ")", "\n", "return", "\n", "}", "\n", "}", "\n\n", "instance", ":=", "group", ".", "NewInstance", "(", ")", "\n\n", "var", "consumer", "sarama", ".", "Consumer", "\n", "if", "consumer", ",", "err", "=", "sarama", ".", "NewConsumer", "(", "brokers", ",", "config", ".", "Config", ")", ";", "err", "!=", "nil", "{", "kz", ".", "Close", "(", ")", "\n", "return", "\n", "}", "\n\n", "cg", "=", "&", "ConsumerGroup", "{", "config", ":", "config", ",", "consumer", ":", "consumer", ",", "kazoo", ":", "kz", ",", "group", ":", "group", ",", "instance", ":", "instance", ",", "messages", ":", "make", "(", "chan", "*", "sarama", ".", "ConsumerMessage", ",", "config", ".", "ChannelBufferSize", ")", ",", "errors", ":", "make", "(", "chan", "error", ",", "config", ".", "ChannelBufferSize", ")", ",", "stopper", ":", "make", "(", "chan", "struct", "{", "}", ")", ",", "}", "\n\n", "// Register consumer group", "if", "exists", ",", "err", ":=", "cg", ".", "group", ".", "Exists", "(", ")", ";", "err", "!=", "nil", "{", "cg", ".", "Logf", "(", "\"", "\\n", "\"", ",", "err", ")", "\n", "_", "=", "consumer", ".", "Close", "(", ")", "\n", "_", "=", "kz", ".", "Close", "(", ")", "\n", "return", "nil", ",", "err", "\n", "}", "else", "if", "!", "exists", "{", "cg", ".", "Logf", "(", "\"", "\\n", "\"", ",", "cg", ".", "group", ".", "Name", ")", "\n", "if", "err", ":=", "cg", ".", "group", ".", "Create", "(", ")", ";", "err", "!=", "nil", "{", "cg", ".", "Logf", "(", "\"", "\\n", "\"", ",", "err", ")", "\n", "_", "=", "consumer", ".", "Close", "(", ")", "\n", "_", "=", "kz", ".", "Close", "(", ")", "\n", "return", "nil", ",", "err", "\n", "}", "\n", "}", "\n\n", "// Register itself with zookeeper", "if", "err", ":=", "cg", ".", "instance", ".", "Register", "(", "topics", ")", ";", "err", "!=", "nil", "{", "cg", ".", "Logf", "(", "\"", "\\n", "\"", ",", "err", ")", "\n", "return", "nil", ",", "err", "\n", "}", "else", "{", "cg", ".", "Logf", "(", "\"", "\"", ",", "cg", ".", "instance", ".", "ID", ")", "\n", "}", "\n\n", "offsetConfig", ":=", "OffsetManagerConfig", "{", "CommitInterval", ":", "config", ".", "Offsets", ".", "CommitInterval", "}", "\n", "cg", ".", "offsetManager", "=", "NewZookeeperOffsetManager", "(", "cg", ",", "&", "offsetConfig", ")", "\n\n", "go", "cg", ".", "topicListConsumer", "(", "topics", ")", "\n\n", "return", "\n", "}" ]
// Connects to a consumer group, using Zookeeper for auto-discovery
[ "Connects", "to", "a", "consumer", "group", "using", "Zookeeper", "for", "auto", "-", "discovery" ]
e2edea948ddfee841ea9a263b32ccca15f7d6c2f
https://github.com/wvanbergen/kafka/blob/e2edea948ddfee841ea9a263b32ccca15f7d6c2f/consumergroup/consumer_group.go#L86-L182
2,725
wvanbergen/kafka
consumergroup/consumer_group.go
partitionConsumer
func (cg *ConsumerGroup) partitionConsumer(topic string, partition int32, messages chan<- *sarama.ConsumerMessage, errors chan<- error, wg *sync.WaitGroup, stopper <-chan struct{}) { defer wg.Done() // Since ProcessingTimeout is the amount of time we'll wait for the final batch // of messages to be processed before releasing a partition, we need to wait slightly // longer than that before timing out here to ensure that another consumer has had // enough time to release the partition. Hence, +2 seconds. maxRetries := int(cg.config.Offsets.ProcessingTimeout/time.Second) + 2 partitionClaimLoop: for tries := 0; tries < maxRetries; tries++ { select { case <-stopper: return case <-time.After(1 * time.Second): if err := cg.instance.ClaimPartition(topic, partition); err == nil { break partitionClaimLoop } else if tries+1 < maxRetries { if err == kazoo.ErrPartitionClaimedByOther { // Another consumer still owns this partition. We should wait longer for it to release it. } else { // An unexpected error occurred. Log it and continue trying until we hit the timeout. cg.Logf("%s/%d :: FAILED to claim partition on attempt %v of %v; retrying in 1 second. Error: %v", topic, partition, tries+1, maxRetries, err) } } else { cg.Logf("%s/%d :: FAILED to claim the partition: %s\n", topic, partition, err) cg.errors <- &sarama.ConsumerError{ Topic: topic, Partition: partition, Err: err, } return } } } defer func() { err := cg.instance.ReleasePartition(topic, partition) if err != nil { cg.Logf("%s/%d :: FAILED to release partition: %s\n", topic, partition, err) cg.errors <- &sarama.ConsumerError{ Topic: topic, Partition: partition, Err: err, } } }() nextOffset, err := cg.offsetManager.InitializePartition(topic, partition) if err != nil { cg.Logf("%s/%d :: FAILED to determine initial offset: %s\n", topic, partition, err) return } if nextOffset >= 0 { cg.Logf("%s/%d :: Partition consumer starting at offset %d.\n", topic, partition, nextOffset) } else { nextOffset = cg.config.Offsets.Initial if nextOffset == sarama.OffsetOldest { cg.Logf("%s/%d :: Partition consumer starting at the oldest available offset.\n", topic, partition) } else if nextOffset == sarama.OffsetNewest { cg.Logf("%s/%d :: Partition consumer listening for new messages only.\n", topic, partition) } } consumer, err := cg.consumePartition(topic, partition, nextOffset) if err != nil { cg.Logf("%s/%d :: FAILED to start partition consumer: %s\n", topic, partition, err) return } defer consumer.Close() err = nil var lastOffset int64 = -1 // aka unknown partitionConsumerLoop: for { select { case <-stopper: break partitionConsumerLoop case err := <-consumer.Errors(): if err == nil { cg.Logf("%s/%d :: Consumer encountered an invalid state: re-establishing consumption of partition.\n", topic, partition) // Errors encountered (if any) are logged in the consumerPartition function var cErr error consumer, cErr = cg.consumePartition(topic, partition, lastOffset) if cErr != nil { break partitionConsumerLoop } continue partitionConsumerLoop } for { select { case errors <- err: continue partitionConsumerLoop case <-stopper: break partitionConsumerLoop } } case message := <-consumer.Messages(): if message == nil { cg.Logf("%s/%d :: Consumer encountered an invalid state: re-establishing consumption of partition.\n", topic, partition) // Errors encountered (if any) are logged in the consumerPartition function var cErr error consumer, cErr = cg.consumePartition(topic, partition, lastOffset) if cErr != nil { break partitionConsumerLoop } continue partitionConsumerLoop } for { select { case <-stopper: break partitionConsumerLoop case messages <- message: lastOffset = message.Offset continue partitionConsumerLoop } } } } cg.Logf("%s/%d :: Stopping partition consumer at offset %d\n", topic, partition, lastOffset) if err := cg.offsetManager.FinalizePartition(topic, partition, lastOffset, cg.config.Offsets.ProcessingTimeout); err != nil { cg.Logf("%s/%d :: %s\n", topic, partition, err) } }
go
func (cg *ConsumerGroup) partitionConsumer(topic string, partition int32, messages chan<- *sarama.ConsumerMessage, errors chan<- error, wg *sync.WaitGroup, stopper <-chan struct{}) { defer wg.Done() // Since ProcessingTimeout is the amount of time we'll wait for the final batch // of messages to be processed before releasing a partition, we need to wait slightly // longer than that before timing out here to ensure that another consumer has had // enough time to release the partition. Hence, +2 seconds. maxRetries := int(cg.config.Offsets.ProcessingTimeout/time.Second) + 2 partitionClaimLoop: for tries := 0; tries < maxRetries; tries++ { select { case <-stopper: return case <-time.After(1 * time.Second): if err := cg.instance.ClaimPartition(topic, partition); err == nil { break partitionClaimLoop } else if tries+1 < maxRetries { if err == kazoo.ErrPartitionClaimedByOther { // Another consumer still owns this partition. We should wait longer for it to release it. } else { // An unexpected error occurred. Log it and continue trying until we hit the timeout. cg.Logf("%s/%d :: FAILED to claim partition on attempt %v of %v; retrying in 1 second. Error: %v", topic, partition, tries+1, maxRetries, err) } } else { cg.Logf("%s/%d :: FAILED to claim the partition: %s\n", topic, partition, err) cg.errors <- &sarama.ConsumerError{ Topic: topic, Partition: partition, Err: err, } return } } } defer func() { err := cg.instance.ReleasePartition(topic, partition) if err != nil { cg.Logf("%s/%d :: FAILED to release partition: %s\n", topic, partition, err) cg.errors <- &sarama.ConsumerError{ Topic: topic, Partition: partition, Err: err, } } }() nextOffset, err := cg.offsetManager.InitializePartition(topic, partition) if err != nil { cg.Logf("%s/%d :: FAILED to determine initial offset: %s\n", topic, partition, err) return } if nextOffset >= 0 { cg.Logf("%s/%d :: Partition consumer starting at offset %d.\n", topic, partition, nextOffset) } else { nextOffset = cg.config.Offsets.Initial if nextOffset == sarama.OffsetOldest { cg.Logf("%s/%d :: Partition consumer starting at the oldest available offset.\n", topic, partition) } else if nextOffset == sarama.OffsetNewest { cg.Logf("%s/%d :: Partition consumer listening for new messages only.\n", topic, partition) } } consumer, err := cg.consumePartition(topic, partition, nextOffset) if err != nil { cg.Logf("%s/%d :: FAILED to start partition consumer: %s\n", topic, partition, err) return } defer consumer.Close() err = nil var lastOffset int64 = -1 // aka unknown partitionConsumerLoop: for { select { case <-stopper: break partitionConsumerLoop case err := <-consumer.Errors(): if err == nil { cg.Logf("%s/%d :: Consumer encountered an invalid state: re-establishing consumption of partition.\n", topic, partition) // Errors encountered (if any) are logged in the consumerPartition function var cErr error consumer, cErr = cg.consumePartition(topic, partition, lastOffset) if cErr != nil { break partitionConsumerLoop } continue partitionConsumerLoop } for { select { case errors <- err: continue partitionConsumerLoop case <-stopper: break partitionConsumerLoop } } case message := <-consumer.Messages(): if message == nil { cg.Logf("%s/%d :: Consumer encountered an invalid state: re-establishing consumption of partition.\n", topic, partition) // Errors encountered (if any) are logged in the consumerPartition function var cErr error consumer, cErr = cg.consumePartition(topic, partition, lastOffset) if cErr != nil { break partitionConsumerLoop } continue partitionConsumerLoop } for { select { case <-stopper: break partitionConsumerLoop case messages <- message: lastOffset = message.Offset continue partitionConsumerLoop } } } } cg.Logf("%s/%d :: Stopping partition consumer at offset %d\n", topic, partition, lastOffset) if err := cg.offsetManager.FinalizePartition(topic, partition, lastOffset, cg.config.Offsets.ProcessingTimeout); err != nil { cg.Logf("%s/%d :: %s\n", topic, partition, err) } }
[ "func", "(", "cg", "*", "ConsumerGroup", ")", "partitionConsumer", "(", "topic", "string", ",", "partition", "int32", ",", "messages", "chan", "<-", "*", "sarama", ".", "ConsumerMessage", ",", "errors", "chan", "<-", "error", ",", "wg", "*", "sync", ".", "WaitGroup", ",", "stopper", "<-", "chan", "struct", "{", "}", ")", "{", "defer", "wg", ".", "Done", "(", ")", "\n\n", "// Since ProcessingTimeout is the amount of time we'll wait for the final batch", "// of messages to be processed before releasing a partition, we need to wait slightly", "// longer than that before timing out here to ensure that another consumer has had", "// enough time to release the partition. Hence, +2 seconds.", "maxRetries", ":=", "int", "(", "cg", ".", "config", ".", "Offsets", ".", "ProcessingTimeout", "/", "time", ".", "Second", ")", "+", "2", "\n", "partitionClaimLoop", ":", "for", "tries", ":=", "0", ";", "tries", "<", "maxRetries", ";", "tries", "++", "{", "select", "{", "case", "<-", "stopper", ":", "return", "\n", "case", "<-", "time", ".", "After", "(", "1", "*", "time", ".", "Second", ")", ":", "if", "err", ":=", "cg", ".", "instance", ".", "ClaimPartition", "(", "topic", ",", "partition", ")", ";", "err", "==", "nil", "{", "break", "partitionClaimLoop", "\n", "}", "else", "if", "tries", "+", "1", "<", "maxRetries", "{", "if", "err", "==", "kazoo", ".", "ErrPartitionClaimedByOther", "{", "// Another consumer still owns this partition. We should wait longer for it to release it.", "}", "else", "{", "// An unexpected error occurred. Log it and continue trying until we hit the timeout.", "cg", ".", "Logf", "(", "\"", "\"", ",", "topic", ",", "partition", ",", "tries", "+", "1", ",", "maxRetries", ",", "err", ")", "\n", "}", "\n", "}", "else", "{", "cg", ".", "Logf", "(", "\"", "\\n", "\"", ",", "topic", ",", "partition", ",", "err", ")", "\n", "cg", ".", "errors", "<-", "&", "sarama", ".", "ConsumerError", "{", "Topic", ":", "topic", ",", "Partition", ":", "partition", ",", "Err", ":", "err", ",", "}", "\n", "return", "\n", "}", "\n", "}", "\n", "}", "\n\n", "defer", "func", "(", ")", "{", "err", ":=", "cg", ".", "instance", ".", "ReleasePartition", "(", "topic", ",", "partition", ")", "\n", "if", "err", "!=", "nil", "{", "cg", ".", "Logf", "(", "\"", "\\n", "\"", ",", "topic", ",", "partition", ",", "err", ")", "\n", "cg", ".", "errors", "<-", "&", "sarama", ".", "ConsumerError", "{", "Topic", ":", "topic", ",", "Partition", ":", "partition", ",", "Err", ":", "err", ",", "}", "\n", "}", "\n", "}", "(", ")", "\n\n", "nextOffset", ",", "err", ":=", "cg", ".", "offsetManager", ".", "InitializePartition", "(", "topic", ",", "partition", ")", "\n", "if", "err", "!=", "nil", "{", "cg", ".", "Logf", "(", "\"", "\\n", "\"", ",", "topic", ",", "partition", ",", "err", ")", "\n", "return", "\n", "}", "\n\n", "if", "nextOffset", ">=", "0", "{", "cg", ".", "Logf", "(", "\"", "\\n", "\"", ",", "topic", ",", "partition", ",", "nextOffset", ")", "\n", "}", "else", "{", "nextOffset", "=", "cg", ".", "config", ".", "Offsets", ".", "Initial", "\n", "if", "nextOffset", "==", "sarama", ".", "OffsetOldest", "{", "cg", ".", "Logf", "(", "\"", "\\n", "\"", ",", "topic", ",", "partition", ")", "\n", "}", "else", "if", "nextOffset", "==", "sarama", ".", "OffsetNewest", "{", "cg", ".", "Logf", "(", "\"", "\\n", "\"", ",", "topic", ",", "partition", ")", "\n", "}", "\n", "}", "\n\n", "consumer", ",", "err", ":=", "cg", ".", "consumePartition", "(", "topic", ",", "partition", ",", "nextOffset", ")", "\n\n", "if", "err", "!=", "nil", "{", "cg", ".", "Logf", "(", "\"", "\\n", "\"", ",", "topic", ",", "partition", ",", "err", ")", "\n", "return", "\n", "}", "\n\n", "defer", "consumer", ".", "Close", "(", ")", "\n\n", "err", "=", "nil", "\n", "var", "lastOffset", "int64", "=", "-", "1", "// aka unknown", "\n", "partitionConsumerLoop", ":", "for", "{", "select", "{", "case", "<-", "stopper", ":", "break", "partitionConsumerLoop", "\n\n", "case", "err", ":=", "<-", "consumer", ".", "Errors", "(", ")", ":", "if", "err", "==", "nil", "{", "cg", ".", "Logf", "(", "\"", "\\n", "\"", ",", "topic", ",", "partition", ")", "\n\n", "// Errors encountered (if any) are logged in the consumerPartition function", "var", "cErr", "error", "\n", "consumer", ",", "cErr", "=", "cg", ".", "consumePartition", "(", "topic", ",", "partition", ",", "lastOffset", ")", "\n", "if", "cErr", "!=", "nil", "{", "break", "partitionConsumerLoop", "\n", "}", "\n", "continue", "partitionConsumerLoop", "\n", "}", "\n\n", "for", "{", "select", "{", "case", "errors", "<-", "err", ":", "continue", "partitionConsumerLoop", "\n\n", "case", "<-", "stopper", ":", "break", "partitionConsumerLoop", "\n", "}", "\n", "}", "\n\n", "case", "message", ":=", "<-", "consumer", ".", "Messages", "(", ")", ":", "if", "message", "==", "nil", "{", "cg", ".", "Logf", "(", "\"", "\\n", "\"", ",", "topic", ",", "partition", ")", "\n\n", "// Errors encountered (if any) are logged in the consumerPartition function", "var", "cErr", "error", "\n", "consumer", ",", "cErr", "=", "cg", ".", "consumePartition", "(", "topic", ",", "partition", ",", "lastOffset", ")", "\n", "if", "cErr", "!=", "nil", "{", "break", "partitionConsumerLoop", "\n", "}", "\n", "continue", "partitionConsumerLoop", "\n\n", "}", "\n\n", "for", "{", "select", "{", "case", "<-", "stopper", ":", "break", "partitionConsumerLoop", "\n\n", "case", "messages", "<-", "message", ":", "lastOffset", "=", "message", ".", "Offset", "\n", "continue", "partitionConsumerLoop", "\n", "}", "\n", "}", "\n", "}", "\n", "}", "\n\n", "cg", ".", "Logf", "(", "\"", "\\n", "\"", ",", "topic", ",", "partition", ",", "lastOffset", ")", "\n", "if", "err", ":=", "cg", ".", "offsetManager", ".", "FinalizePartition", "(", "topic", ",", "partition", ",", "lastOffset", ",", "cg", ".", "config", ".", "Offsets", ".", "ProcessingTimeout", ")", ";", "err", "!=", "nil", "{", "cg", ".", "Logf", "(", "\"", "\\n", "\"", ",", "topic", ",", "partition", ",", "err", ")", "\n", "}", "\n", "}" ]
// Consumes a partition
[ "Consumes", "a", "partition" ]
e2edea948ddfee841ea9a263b32ccca15f7d6c2f
https://github.com/wvanbergen/kafka/blob/e2edea948ddfee841ea9a263b32ccca15f7d6c2f/consumergroup/consumer_group.go#L377-L512
2,726
ulule/deepcopier
deepcopier.go
WithContext
func (dc *DeepCopier) WithContext(ctx map[string]interface{}) *DeepCopier { dc.ctx = ctx return dc }
go
func (dc *DeepCopier) WithContext(ctx map[string]interface{}) *DeepCopier { dc.ctx = ctx return dc }
[ "func", "(", "dc", "*", "DeepCopier", ")", "WithContext", "(", "ctx", "map", "[", "string", "]", "interface", "{", "}", ")", "*", "DeepCopier", "{", "dc", ".", "ctx", "=", "ctx", "\n", "return", "dc", "\n", "}" ]
// WithContext injects the given context into the builder instance.
[ "WithContext", "injects", "the", "given", "context", "into", "the", "builder", "instance", "." ]
ca99b135e50f526fde9cd88705f0ff2f3f95b77c
https://github.com/ulule/deepcopier/blob/ca99b135e50f526fde9cd88705f0ff2f3f95b77c/deepcopier.go#L49-L52
2,727
ulule/deepcopier
deepcopier.go
To
func (dc *DeepCopier) To(dst interface{}) error { dc.dst = dst return process(dc.dst, dc.src, Options{Context: dc.ctx}) }
go
func (dc *DeepCopier) To(dst interface{}) error { dc.dst = dst return process(dc.dst, dc.src, Options{Context: dc.ctx}) }
[ "func", "(", "dc", "*", "DeepCopier", ")", "To", "(", "dst", "interface", "{", "}", ")", "error", "{", "dc", ".", "dst", "=", "dst", "\n", "return", "process", "(", "dc", ".", "dst", ",", "dc", ".", "src", ",", "Options", "{", "Context", ":", "dc", ".", "ctx", "}", ")", "\n", "}" ]
// To sets the destination.
[ "To", "sets", "the", "destination", "." ]
ca99b135e50f526fde9cd88705f0ff2f3f95b77c
https://github.com/ulule/deepcopier/blob/ca99b135e50f526fde9cd88705f0ff2f3f95b77c/deepcopier.go#L55-L58
2,728
ulule/deepcopier
deepcopier.go
From
func (dc *DeepCopier) From(src interface{}) error { dc.dst = dc.src dc.src = src return process(dc.dst, dc.src, Options{Context: dc.ctx, Reversed: true}) }
go
func (dc *DeepCopier) From(src interface{}) error { dc.dst = dc.src dc.src = src return process(dc.dst, dc.src, Options{Context: dc.ctx, Reversed: true}) }
[ "func", "(", "dc", "*", "DeepCopier", ")", "From", "(", "src", "interface", "{", "}", ")", "error", "{", "dc", ".", "dst", "=", "dc", ".", "src", "\n", "dc", ".", "src", "=", "src", "\n", "return", "process", "(", "dc", ".", "dst", ",", "dc", ".", "src", ",", "Options", "{", "Context", ":", "dc", ".", "ctx", ",", "Reversed", ":", "true", "}", ")", "\n", "}" ]
// From sets the given the source as destination and destination as source.
[ "From", "sets", "the", "given", "the", "source", "as", "destination", "and", "destination", "as", "source", "." ]
ca99b135e50f526fde9cd88705f0ff2f3f95b77c
https://github.com/ulule/deepcopier/blob/ca99b135e50f526fde9cd88705f0ff2f3f95b77c/deepcopier.go#L61-L65
2,729
ulule/deepcopier
deepcopier.go
getTagOptions
func getTagOptions(value string) TagOptions { options := TagOptions{} for _, opt := range strings.Split(value, ";") { o := strings.Split(opt, ":") // deepcopier:"keyword; without; value;" if len(o) == 1 { options[o[0]] = "" } // deepcopier:"key:value; anotherkey:anothervalue" if len(o) == 2 { options[strings.TrimSpace(o[0])] = strings.TrimSpace(o[1]) } } return options }
go
func getTagOptions(value string) TagOptions { options := TagOptions{} for _, opt := range strings.Split(value, ";") { o := strings.Split(opt, ":") // deepcopier:"keyword; without; value;" if len(o) == 1 { options[o[0]] = "" } // deepcopier:"key:value; anotherkey:anothervalue" if len(o) == 2 { options[strings.TrimSpace(o[0])] = strings.TrimSpace(o[1]) } } return options }
[ "func", "getTagOptions", "(", "value", "string", ")", "TagOptions", "{", "options", ":=", "TagOptions", "{", "}", "\n\n", "for", "_", ",", "opt", ":=", "range", "strings", ".", "Split", "(", "value", ",", "\"", "\"", ")", "{", "o", ":=", "strings", ".", "Split", "(", "opt", ",", "\"", "\"", ")", "\n\n", "// deepcopier:\"keyword; without; value;\"", "if", "len", "(", "o", ")", "==", "1", "{", "options", "[", "o", "[", "0", "]", "]", "=", "\"", "\"", "\n", "}", "\n\n", "// deepcopier:\"key:value; anotherkey:anothervalue\"", "if", "len", "(", "o", ")", "==", "2", "{", "options", "[", "strings", ".", "TrimSpace", "(", "o", "[", "0", "]", ")", "]", "=", "strings", ".", "TrimSpace", "(", "o", "[", "1", "]", ")", "\n", "}", "\n", "}", "\n\n", "return", "options", "\n", "}" ]
// getTagOptions parses deepcopier tag field and returns options.
[ "getTagOptions", "parses", "deepcopier", "tag", "field", "and", "returns", "options", "." ]
ca99b135e50f526fde9cd88705f0ff2f3f95b77c
https://github.com/ulule/deepcopier/blob/ca99b135e50f526fde9cd88705f0ff2f3f95b77c/deepcopier.go#L260-L278
2,730
ulule/deepcopier
deepcopier.go
getRelatedField
func getRelatedField(instance interface{}, name string) (string, TagOptions) { var ( value = reflect.Indirect(reflect.ValueOf(instance)) fieldName string tagOptions TagOptions ) for i := 0; i < value.NumField(); i++ { var ( vField = value.Field(i) tField = value.Type().Field(i) tagOptions = getTagOptions(tField.Tag.Get(TagName)) ) if tField.Type.Kind() == reflect.Struct && tField.Anonymous { if n, o := getRelatedField(vField.Interface(), name); n != "" { return n, o } } if v, ok := tagOptions[FieldOptionName]; ok && v == name { return tField.Name, tagOptions } if tField.Name == name { return tField.Name, tagOptions } } return fieldName, tagOptions }
go
func getRelatedField(instance interface{}, name string) (string, TagOptions) { var ( value = reflect.Indirect(reflect.ValueOf(instance)) fieldName string tagOptions TagOptions ) for i := 0; i < value.NumField(); i++ { var ( vField = value.Field(i) tField = value.Type().Field(i) tagOptions = getTagOptions(tField.Tag.Get(TagName)) ) if tField.Type.Kind() == reflect.Struct && tField.Anonymous { if n, o := getRelatedField(vField.Interface(), name); n != "" { return n, o } } if v, ok := tagOptions[FieldOptionName]; ok && v == name { return tField.Name, tagOptions } if tField.Name == name { return tField.Name, tagOptions } } return fieldName, tagOptions }
[ "func", "getRelatedField", "(", "instance", "interface", "{", "}", ",", "name", "string", ")", "(", "string", ",", "TagOptions", ")", "{", "var", "(", "value", "=", "reflect", ".", "Indirect", "(", "reflect", ".", "ValueOf", "(", "instance", ")", ")", "\n", "fieldName", "string", "\n", "tagOptions", "TagOptions", "\n", ")", "\n\n", "for", "i", ":=", "0", ";", "i", "<", "value", ".", "NumField", "(", ")", ";", "i", "++", "{", "var", "(", "vField", "=", "value", ".", "Field", "(", "i", ")", "\n", "tField", "=", "value", ".", "Type", "(", ")", ".", "Field", "(", "i", ")", "\n", "tagOptions", "=", "getTagOptions", "(", "tField", ".", "Tag", ".", "Get", "(", "TagName", ")", ")", "\n", ")", "\n\n", "if", "tField", ".", "Type", ".", "Kind", "(", ")", "==", "reflect", ".", "Struct", "&&", "tField", ".", "Anonymous", "{", "if", "n", ",", "o", ":=", "getRelatedField", "(", "vField", ".", "Interface", "(", ")", ",", "name", ")", ";", "n", "!=", "\"", "\"", "{", "return", "n", ",", "o", "\n", "}", "\n", "}", "\n\n", "if", "v", ",", "ok", ":=", "tagOptions", "[", "FieldOptionName", "]", ";", "ok", "&&", "v", "==", "name", "{", "return", "tField", ".", "Name", ",", "tagOptions", "\n", "}", "\n\n", "if", "tField", ".", "Name", "==", "name", "{", "return", "tField", ".", "Name", ",", "tagOptions", "\n", "}", "\n", "}", "\n\n", "return", "fieldName", ",", "tagOptions", "\n", "}" ]
// getRelatedField returns first matching field.
[ "getRelatedField", "returns", "first", "matching", "field", "." ]
ca99b135e50f526fde9cd88705f0ff2f3f95b77c
https://github.com/ulule/deepcopier/blob/ca99b135e50f526fde9cd88705f0ff2f3f95b77c/deepcopier.go#L281-L311
2,731
ulule/deepcopier
deepcopier.go
getMethodNames
func getMethodNames(instance interface{}) []string { var methods []string t := reflect.TypeOf(instance) for i := 0; i < t.NumMethod(); i++ { methods = append(methods, t.Method(i).Name) } return methods }
go
func getMethodNames(instance interface{}) []string { var methods []string t := reflect.TypeOf(instance) for i := 0; i < t.NumMethod(); i++ { methods = append(methods, t.Method(i).Name) } return methods }
[ "func", "getMethodNames", "(", "instance", "interface", "{", "}", ")", "[", "]", "string", "{", "var", "methods", "[", "]", "string", "\n\n", "t", ":=", "reflect", ".", "TypeOf", "(", "instance", ")", "\n", "for", "i", ":=", "0", ";", "i", "<", "t", ".", "NumMethod", "(", ")", ";", "i", "++", "{", "methods", "=", "append", "(", "methods", ",", "t", ".", "Method", "(", "i", ")", ".", "Name", ")", "\n", "}", "\n\n", "return", "methods", "\n", "}" ]
// getMethodNames returns instance's method names.
[ "getMethodNames", "returns", "instance", "s", "method", "names", "." ]
ca99b135e50f526fde9cd88705f0ff2f3f95b77c
https://github.com/ulule/deepcopier/blob/ca99b135e50f526fde9cd88705f0ff2f3f95b77c/deepcopier.go#L314-L323
2,732
ulule/deepcopier
deepcopier.go
getFieldNames
func getFieldNames(instance interface{}) []string { var ( fields []string v = reflect.Indirect(reflect.ValueOf(instance)) t = v.Type() ) if t.Kind() != reflect.Struct { return nil } for i := 0; i < v.NumField(); i++ { var ( vField = v.Field(i) tField = v.Type().Field(i) ) // Is exportable? if tField.PkgPath != "" { continue } if tField.Type.Kind() == reflect.Struct && tField.Anonymous { fields = append(fields, getFieldNames(vField.Interface())...) continue } fields = append(fields, tField.Name) } return fields }
go
func getFieldNames(instance interface{}) []string { var ( fields []string v = reflect.Indirect(reflect.ValueOf(instance)) t = v.Type() ) if t.Kind() != reflect.Struct { return nil } for i := 0; i < v.NumField(); i++ { var ( vField = v.Field(i) tField = v.Type().Field(i) ) // Is exportable? if tField.PkgPath != "" { continue } if tField.Type.Kind() == reflect.Struct && tField.Anonymous { fields = append(fields, getFieldNames(vField.Interface())...) continue } fields = append(fields, tField.Name) } return fields }
[ "func", "getFieldNames", "(", "instance", "interface", "{", "}", ")", "[", "]", "string", "{", "var", "(", "fields", "[", "]", "string", "\n", "v", "=", "reflect", ".", "Indirect", "(", "reflect", ".", "ValueOf", "(", "instance", ")", ")", "\n", "t", "=", "v", ".", "Type", "(", ")", "\n", ")", "\n\n", "if", "t", ".", "Kind", "(", ")", "!=", "reflect", ".", "Struct", "{", "return", "nil", "\n", "}", "\n\n", "for", "i", ":=", "0", ";", "i", "<", "v", ".", "NumField", "(", ")", ";", "i", "++", "{", "var", "(", "vField", "=", "v", ".", "Field", "(", "i", ")", "\n", "tField", "=", "v", ".", "Type", "(", ")", ".", "Field", "(", "i", ")", "\n", ")", "\n\n", "// Is exportable?", "if", "tField", ".", "PkgPath", "!=", "\"", "\"", "{", "continue", "\n", "}", "\n\n", "if", "tField", ".", "Type", ".", "Kind", "(", ")", "==", "reflect", ".", "Struct", "&&", "tField", ".", "Anonymous", "{", "fields", "=", "append", "(", "fields", ",", "getFieldNames", "(", "vField", ".", "Interface", "(", ")", ")", "...", ")", "\n", "continue", "\n", "}", "\n\n", "fields", "=", "append", "(", "fields", ",", "tField", ".", "Name", ")", "\n", "}", "\n\n", "return", "fields", "\n", "}" ]
// getFieldNames returns instance's field names.
[ "getFieldNames", "returns", "instance", "s", "field", "names", "." ]
ca99b135e50f526fde9cd88705f0ff2f3f95b77c
https://github.com/ulule/deepcopier/blob/ca99b135e50f526fde9cd88705f0ff2f3f95b77c/deepcopier.go#L326-L357
2,733
ulule/deepcopier
deepcopier.go
isNullableType
func isNullableType(t reflect.Type) bool { return t.ConvertibleTo(reflect.TypeOf((*driver.Valuer)(nil)).Elem()) }
go
func isNullableType(t reflect.Type) bool { return t.ConvertibleTo(reflect.TypeOf((*driver.Valuer)(nil)).Elem()) }
[ "func", "isNullableType", "(", "t", "reflect", ".", "Type", ")", "bool", "{", "return", "t", ".", "ConvertibleTo", "(", "reflect", ".", "TypeOf", "(", "(", "*", "driver", ".", "Valuer", ")", "(", "nil", ")", ")", ".", "Elem", "(", ")", ")", "\n", "}" ]
// isNullableType returns true if the given type is a nullable one.
[ "isNullableType", "returns", "true", "if", "the", "given", "type", "is", "a", "nullable", "one", "." ]
ca99b135e50f526fde9cd88705f0ff2f3f95b77c
https://github.com/ulule/deepcopier/blob/ca99b135e50f526fde9cd88705f0ff2f3f95b77c/deepcopier.go#L360-L362
2,734
goji/httpauth
basic_auth.go
ServeHTTP
func (b basicAuth) ServeHTTP(w http.ResponseWriter, r *http.Request) { // Check if we have a user-provided error handler, else set a default if b.opts.UnauthorizedHandler == nil { b.opts.UnauthorizedHandler = http.HandlerFunc(defaultUnauthorizedHandler) } // Check that the provided details match if b.authenticate(r) == false { b.requestAuth(w, r) return } // Call the next handler on success. b.h.ServeHTTP(w, r) }
go
func (b basicAuth) ServeHTTP(w http.ResponseWriter, r *http.Request) { // Check if we have a user-provided error handler, else set a default if b.opts.UnauthorizedHandler == nil { b.opts.UnauthorizedHandler = http.HandlerFunc(defaultUnauthorizedHandler) } // Check that the provided details match if b.authenticate(r) == false { b.requestAuth(w, r) return } // Call the next handler on success. b.h.ServeHTTP(w, r) }
[ "func", "(", "b", "basicAuth", ")", "ServeHTTP", "(", "w", "http", ".", "ResponseWriter", ",", "r", "*", "http", ".", "Request", ")", "{", "// Check if we have a user-provided error handler, else set a default", "if", "b", ".", "opts", ".", "UnauthorizedHandler", "==", "nil", "{", "b", ".", "opts", ".", "UnauthorizedHandler", "=", "http", ".", "HandlerFunc", "(", "defaultUnauthorizedHandler", ")", "\n", "}", "\n\n", "// Check that the provided details match", "if", "b", ".", "authenticate", "(", "r", ")", "==", "false", "{", "b", ".", "requestAuth", "(", "w", ",", "r", ")", "\n", "return", "\n", "}", "\n\n", "// Call the next handler on success.", "b", ".", "h", ".", "ServeHTTP", "(", "w", ",", "r", ")", "\n", "}" ]
// Satisfies the http.Handler interface for basicAuth.
[ "Satisfies", "the", "http", ".", "Handler", "interface", "for", "basicAuth", "." ]
2da839ab0f4df05a6db5eb277995589dadbd4fb9
https://github.com/goji/httpauth/blob/2da839ab0f4df05a6db5eb277995589dadbd4fb9/basic_auth.go#L31-L45
2,735
goji/httpauth
basic_auth.go
simpleBasicAuthFunc
func (b *basicAuth) simpleBasicAuthFunc(user, pass string, r *http.Request) bool { // Equalize lengths of supplied and required credentials // by hashing them givenUser := sha256.Sum256([]byte(user)) givenPass := sha256.Sum256([]byte(pass)) requiredUser := sha256.Sum256([]byte(b.opts.User)) requiredPass := sha256.Sum256([]byte(b.opts.Password)) // Compare the supplied credentials to those set in our options if subtle.ConstantTimeCompare(givenUser[:], requiredUser[:]) == 1 && subtle.ConstantTimeCompare(givenPass[:], requiredPass[:]) == 1 { return true } return false }
go
func (b *basicAuth) simpleBasicAuthFunc(user, pass string, r *http.Request) bool { // Equalize lengths of supplied and required credentials // by hashing them givenUser := sha256.Sum256([]byte(user)) givenPass := sha256.Sum256([]byte(pass)) requiredUser := sha256.Sum256([]byte(b.opts.User)) requiredPass := sha256.Sum256([]byte(b.opts.Password)) // Compare the supplied credentials to those set in our options if subtle.ConstantTimeCompare(givenUser[:], requiredUser[:]) == 1 && subtle.ConstantTimeCompare(givenPass[:], requiredPass[:]) == 1 { return true } return false }
[ "func", "(", "b", "*", "basicAuth", ")", "simpleBasicAuthFunc", "(", "user", ",", "pass", "string", ",", "r", "*", "http", ".", "Request", ")", "bool", "{", "// Equalize lengths of supplied and required credentials", "// by hashing them", "givenUser", ":=", "sha256", ".", "Sum256", "(", "[", "]", "byte", "(", "user", ")", ")", "\n", "givenPass", ":=", "sha256", ".", "Sum256", "(", "[", "]", "byte", "(", "pass", ")", ")", "\n", "requiredUser", ":=", "sha256", ".", "Sum256", "(", "[", "]", "byte", "(", "b", ".", "opts", ".", "User", ")", ")", "\n", "requiredPass", ":=", "sha256", ".", "Sum256", "(", "[", "]", "byte", "(", "b", ".", "opts", ".", "Password", ")", ")", "\n\n", "// Compare the supplied credentials to those set in our options", "if", "subtle", ".", "ConstantTimeCompare", "(", "givenUser", "[", ":", "]", ",", "requiredUser", "[", ":", "]", ")", "==", "1", "&&", "subtle", ".", "ConstantTimeCompare", "(", "givenPass", "[", ":", "]", ",", "requiredPass", "[", ":", "]", ")", "==", "1", "{", "return", "true", "\n", "}", "\n\n", "return", "false", "\n", "}" ]
// simpleBasicAuthFunc authenticates the supplied username and password against // the User and Password set in the Options struct.
[ "simpleBasicAuthFunc", "authenticates", "the", "supplied", "username", "and", "password", "against", "the", "User", "and", "Password", "set", "in", "the", "Options", "struct", "." ]
2da839ab0f4df05a6db5eb277995589dadbd4fb9
https://github.com/goji/httpauth/blob/2da839ab0f4df05a6db5eb277995589dadbd4fb9/basic_auth.go#L97-L112
2,736
goji/httpauth
basic_auth.go
requestAuth
func (b *basicAuth) requestAuth(w http.ResponseWriter, r *http.Request) { w.Header().Set("WWW-Authenticate", fmt.Sprintf(`Basic realm=%q`, b.opts.Realm)) b.opts.UnauthorizedHandler.ServeHTTP(w, r) }
go
func (b *basicAuth) requestAuth(w http.ResponseWriter, r *http.Request) { w.Header().Set("WWW-Authenticate", fmt.Sprintf(`Basic realm=%q`, b.opts.Realm)) b.opts.UnauthorizedHandler.ServeHTTP(w, r) }
[ "func", "(", "b", "*", "basicAuth", ")", "requestAuth", "(", "w", "http", ".", "ResponseWriter", ",", "r", "*", "http", ".", "Request", ")", "{", "w", ".", "Header", "(", ")", ".", "Set", "(", "\"", "\"", ",", "fmt", ".", "Sprintf", "(", "`Basic realm=%q`", ",", "b", ".", "opts", ".", "Realm", ")", ")", "\n", "b", ".", "opts", ".", "UnauthorizedHandler", ".", "ServeHTTP", "(", "w", ",", "r", ")", "\n", "}" ]
// Require authentication, and serve our error handler otherwise.
[ "Require", "authentication", "and", "serve", "our", "error", "handler", "otherwise", "." ]
2da839ab0f4df05a6db5eb277995589dadbd4fb9
https://github.com/goji/httpauth/blob/2da839ab0f4df05a6db5eb277995589dadbd4fb9/basic_auth.go#L115-L118
2,737
goji/httpauth
basic_auth.go
defaultUnauthorizedHandler
func defaultUnauthorizedHandler(w http.ResponseWriter, r *http.Request) { http.Error(w, http.StatusText(http.StatusUnauthorized), http.StatusUnauthorized) }
go
func defaultUnauthorizedHandler(w http.ResponseWriter, r *http.Request) { http.Error(w, http.StatusText(http.StatusUnauthorized), http.StatusUnauthorized) }
[ "func", "defaultUnauthorizedHandler", "(", "w", "http", ".", "ResponseWriter", ",", "r", "*", "http", ".", "Request", ")", "{", "http", ".", "Error", "(", "w", ",", "http", ".", "StatusText", "(", "http", ".", "StatusUnauthorized", ")", ",", "http", ".", "StatusUnauthorized", ")", "\n", "}" ]
// defaultUnauthorizedHandler provides a default HTTP 401 Unauthorized response.
[ "defaultUnauthorizedHandler", "provides", "a", "default", "HTTP", "401", "Unauthorized", "response", "." ]
2da839ab0f4df05a6db5eb277995589dadbd4fb9
https://github.com/goji/httpauth/blob/2da839ab0f4df05a6db5eb277995589dadbd4fb9/basic_auth.go#L121-L123
2,738
yalp/jsonpath
jsonpath.go
Prepare
func Prepare(path string) (FilterFunc, error) { p := newScanner(path) if err := p.parse(); err != nil { return nil, err } return p.prepareFilterFunc(), nil }
go
func Prepare(path string) (FilterFunc, error) { p := newScanner(path) if err := p.parse(); err != nil { return nil, err } return p.prepareFilterFunc(), nil }
[ "func", "Prepare", "(", "path", "string", ")", "(", "FilterFunc", ",", "error", ")", "{", "p", ":=", "newScanner", "(", "path", ")", "\n", "if", "err", ":=", "p", ".", "parse", "(", ")", ";", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "return", "p", ".", "prepareFilterFunc", "(", ")", ",", "nil", "\n", "}" ]
// Prepare will parse the path and return a filter function that can then be applied to decoded JSON values.
[ "Prepare", "will", "parse", "the", "path", "and", "return", "a", "filter", "function", "that", "can", "then", "be", "applied", "to", "decoded", "JSON", "values", "." ]
5cc68e5049a040829faef3a44c00ec4332f6dec7
https://github.com/yalp/jsonpath/blob/5cc68e5049a040829faef3a44c00ec4332f6dec7/jsonpath.go#L51-L57
2,739
yalp/jsonpath
jsonpath.go
next
func (a actions) next(r, c interface{}) (interface{}, error) { return a[0](r, c, a[1:]) }
go
func (a actions) next(r, c interface{}) (interface{}, error) { return a[0](r, c, a[1:]) }
[ "func", "(", "a", "actions", ")", "next", "(", "r", ",", "c", "interface", "{", "}", ")", "(", "interface", "{", "}", ",", "error", ")", "{", "return", "a", "[", "0", "]", "(", "r", ",", "c", ",", "a", "[", "1", ":", "]", ")", "\n", "}" ]
// next applies the next action function
[ "next", "applies", "the", "next", "action", "function" ]
5cc68e5049a040829faef3a44c00ec4332f6dec7
https://github.com/yalp/jsonpath/blob/5cc68e5049a040829faef3a44c00ec4332f6dec7/jsonpath.go#L77-L79
2,740
yalp/jsonpath
jsonpath.go
call
func (a actions) call(r, c interface{}) (interface{}, error) { return a[0](r, c, a) }
go
func (a actions) call(r, c interface{}) (interface{}, error) { return a[0](r, c, a) }
[ "func", "(", "a", "actions", ")", "call", "(", "r", ",", "c", "interface", "{", "}", ")", "(", "interface", "{", "}", ",", "error", ")", "{", "return", "a", "[", "0", "]", "(", "r", ",", "c", ",", "a", ")", "\n", "}" ]
// call applies the next action function without taking it out
[ "call", "applies", "the", "next", "action", "function", "without", "taking", "it", "out" ]
5cc68e5049a040829faef3a44c00ec4332f6dec7
https://github.com/yalp/jsonpath/blob/5cc68e5049a040829faef3a44c00ec4332f6dec7/jsonpath.go#L82-L84
2,741
yalp/jsonpath
jsonpath.go
parseBracket
func (p *parser) parseBracket() error { if p.peek() == '?' { return p.parseFilter() } else if p.peek() == '*' { p.scan() // eat * if p.scan() != ']' { return fmt.Errorf("expected closing bracket after [* at %d", p.column()) } return p.prepareWildcard() } return p.parseArray() }
go
func (p *parser) parseBracket() error { if p.peek() == '?' { return p.parseFilter() } else if p.peek() == '*' { p.scan() // eat * if p.scan() != ']' { return fmt.Errorf("expected closing bracket after [* at %d", p.column()) } return p.prepareWildcard() } return p.parseArray() }
[ "func", "(", "p", "*", "parser", ")", "parseBracket", "(", ")", "error", "{", "if", "p", ".", "peek", "(", ")", "==", "'?'", "{", "return", "p", ".", "parseFilter", "(", ")", "\n", "}", "else", "if", "p", ".", "peek", "(", ")", "==", "'*'", "{", "p", ".", "scan", "(", ")", "// eat *", "\n", "if", "p", ".", "scan", "(", ")", "!=", "']'", "{", "return", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "p", ".", "column", "(", ")", ")", "\n", "}", "\n", "return", "p", ".", "prepareWildcard", "(", ")", "\n", "}", "\n", "return", "p", ".", "parseArray", "(", ")", "\n", "}" ]
// bracket contains filter, wildcard or array access
[ "bracket", "contains", "filter", "wildcard", "or", "array", "access" ]
5cc68e5049a040829faef3a44c00ec4332f6dec7
https://github.com/yalp/jsonpath/blob/5cc68e5049a040829faef3a44c00ec4332f6dec7/jsonpath.go#L247-L258
2,742
jmoiron/modl
transaction.go
Rollback
func (t *Transaction) Rollback() error { t.dbmap.trace("rollback;") return t.Tx.Rollback() }
go
func (t *Transaction) Rollback() error { t.dbmap.trace("rollback;") return t.Tx.Rollback() }
[ "func", "(", "t", "*", "Transaction", ")", "Rollback", "(", ")", "error", "{", "t", ".", "dbmap", ".", "trace", "(", "\"", "\"", ")", "\n", "return", "t", ".", "Tx", ".", "Rollback", "(", ")", "\n", "}" ]
// Rollback rolls back the underlying database transaction.
[ "Rollback", "rolls", "back", "the", "underlying", "database", "transaction", "." ]
99654d091ece9b281eec23c9e6fe9ff960e1baa1
https://github.com/jmoiron/modl/blob/99654d091ece9b281eec23c9e6fe9ff960e1baa1/transaction.go#L60-L63
2,743
jmoiron/modl
dbmap.go
NewDbMap
func NewDbMap(db *sql.DB, dialect Dialect) *DbMap { return &DbMap{ Db: db, Dialect: dialect, Dbx: sqlx.NewDb(db, dialect.DriverName()), mapper: reflectx.NewMapperFunc("db", sqlx.NameMapper), } }
go
func NewDbMap(db *sql.DB, dialect Dialect) *DbMap { return &DbMap{ Db: db, Dialect: dialect, Dbx: sqlx.NewDb(db, dialect.DriverName()), mapper: reflectx.NewMapperFunc("db", sqlx.NameMapper), } }
[ "func", "NewDbMap", "(", "db", "*", "sql", ".", "DB", ",", "dialect", "Dialect", ")", "*", "DbMap", "{", "return", "&", "DbMap", "{", "Db", ":", "db", ",", "Dialect", ":", "dialect", ",", "Dbx", ":", "sqlx", ".", "NewDb", "(", "db", ",", "dialect", ".", "DriverName", "(", ")", ")", ",", "mapper", ":", "reflectx", ".", "NewMapperFunc", "(", "\"", "\"", ",", "sqlx", ".", "NameMapper", ")", ",", "}", "\n", "}" ]
// NewDbMap returns a new DbMap using the db connection and dialect.
[ "NewDbMap", "returns", "a", "new", "DbMap", "using", "the", "db", "connection", "and", "dialect", "." ]
99654d091ece9b281eec23c9e6fe9ff960e1baa1
https://github.com/jmoiron/modl/blob/99654d091ece9b281eec23c9e6fe9ff960e1baa1/dbmap.go#L53-L60
2,744
jmoiron/modl
dbmap.go
TraceOn
func (m *DbMap) TraceOn(prefix string, logger *log.Logger) { m.logger = logger if len(prefix) == 0 { m.logPrefix = prefix } else { m.logPrefix = prefix + " " } }
go
func (m *DbMap) TraceOn(prefix string, logger *log.Logger) { m.logger = logger if len(prefix) == 0 { m.logPrefix = prefix } else { m.logPrefix = prefix + " " } }
[ "func", "(", "m", "*", "DbMap", ")", "TraceOn", "(", "prefix", "string", ",", "logger", "*", "log", ".", "Logger", ")", "{", "m", ".", "logger", "=", "logger", "\n", "if", "len", "(", "prefix", ")", "==", "0", "{", "m", ".", "logPrefix", "=", "prefix", "\n", "}", "else", "{", "m", ".", "logPrefix", "=", "prefix", "+", "\"", "\"", "\n", "}", "\n", "}" ]
// TraceOn turns on SQL statement logging for this DbMap. After this is // called, all SQL statements will be sent to the logger. If prefix is // a non-empty string, it will be written to the front of all logged // strings, which can aid in filtering log lines. // // Use TraceOn if you want to spy on the SQL statements that modl // generates.
[ "TraceOn", "turns", "on", "SQL", "statement", "logging", "for", "this", "DbMap", ".", "After", "this", "is", "called", "all", "SQL", "statements", "will", "be", "sent", "to", "the", "logger", ".", "If", "prefix", "is", "a", "non", "-", "empty", "string", "it", "will", "be", "written", "to", "the", "front", "of", "all", "logged", "strings", "which", "can", "aid", "in", "filtering", "log", "lines", ".", "Use", "TraceOn", "if", "you", "want", "to", "spy", "on", "the", "SQL", "statements", "that", "modl", "generates", "." ]
99654d091ece9b281eec23c9e6fe9ff960e1baa1
https://github.com/jmoiron/modl/blob/99654d091ece9b281eec23c9e6fe9ff960e1baa1/dbmap.go#L69-L76
2,745
jmoiron/modl
dbmap.go
AddTableWithName
func (m *DbMap) AddTableWithName(i interface{}, name string) *TableMap { return m.AddTable(i, name) }
go
func (m *DbMap) AddTableWithName(i interface{}, name string) *TableMap { return m.AddTable(i, name) }
[ "func", "(", "m", "*", "DbMap", ")", "AddTableWithName", "(", "i", "interface", "{", "}", ",", "name", "string", ")", "*", "TableMap", "{", "return", "m", ".", "AddTable", "(", "i", ",", "name", ")", "\n", "}" ]
// AddTableWithName adds a new mapping of the interface to a table name.
[ "AddTableWithName", "adds", "a", "new", "mapping", "of", "the", "interface", "to", "a", "table", "name", "." ]
99654d091ece9b281eec23c9e6fe9ff960e1baa1
https://github.com/jmoiron/modl/blob/99654d091ece9b281eec23c9e6fe9ff960e1baa1/dbmap.go#L142-L144
2,746
jmoiron/modl
dbmap.go
CreateTablesSql
func (m *DbMap) CreateTablesSql() (map[string]string, error) { return m.createTables(false, false) }
go
func (m *DbMap) CreateTablesSql() (map[string]string, error) { return m.createTables(false, false) }
[ "func", "(", "m", "*", "DbMap", ")", "CreateTablesSql", "(", ")", "(", "map", "[", "string", "]", "string", ",", "error", ")", "{", "return", "m", ".", "createTables", "(", "false", ",", "false", ")", "\n", "}" ]
// CreateTablesSql returns create table SQL as a map of table names to // their associated CREATE TABLE statements.
[ "CreateTablesSql", "returns", "create", "table", "SQL", "as", "a", "map", "of", "table", "names", "to", "their", "associated", "CREATE", "TABLE", "statements", "." ]
99654d091ece9b281eec23c9e6fe9ff960e1baa1
https://github.com/jmoiron/modl/blob/99654d091ece9b281eec23c9e6fe9ff960e1baa1/dbmap.go#L148-L150
2,747
jmoiron/modl
dbmap.go
CreateTablesIfNotExistsSql
func (m *DbMap) CreateTablesIfNotExistsSql() (map[string]string, error) { return m.createTables(true, false) }
go
func (m *DbMap) CreateTablesIfNotExistsSql() (map[string]string, error) { return m.createTables(true, false) }
[ "func", "(", "m", "*", "DbMap", ")", "CreateTablesIfNotExistsSql", "(", ")", "(", "map", "[", "string", "]", "string", ",", "error", ")", "{", "return", "m", ".", "createTables", "(", "true", ",", "false", ")", "\n", "}" ]
// CreateTablesIfNotExistsSql returns create table SQL as a map of table names to // their associated CREATE TABLE IF NOT EXISTS statements.
[ "CreateTablesIfNotExistsSql", "returns", "create", "table", "SQL", "as", "a", "map", "of", "table", "names", "to", "their", "associated", "CREATE", "TABLE", "IF", "NOT", "EXISTS", "statements", "." ]
99654d091ece9b281eec23c9e6fe9ff960e1baa1
https://github.com/jmoiron/modl/blob/99654d091ece9b281eec23c9e6fe9ff960e1baa1/dbmap.go#L154-L156
2,748
jmoiron/modl
dbmap.go
CreateTables
func (m *DbMap) CreateTables() error { _, err := m.createTables(false, true) return err }
go
func (m *DbMap) CreateTables() error { _, err := m.createTables(false, true) return err }
[ "func", "(", "m", "*", "DbMap", ")", "CreateTables", "(", ")", "error", "{", "_", ",", "err", ":=", "m", ".", "createTables", "(", "false", ",", "true", ")", "\n", "return", "err", "\n", "}" ]
// CreateTables iterates through TableMaps registered to this DbMap and // executes "create table" statements against the database for each. // // This is particularly useful in unit tests where you want to create // and destroy the schema automatically.
[ "CreateTables", "iterates", "through", "TableMaps", "registered", "to", "this", "DbMap", "and", "executes", "create", "table", "statements", "against", "the", "database", "for", "each", ".", "This", "is", "particularly", "useful", "in", "unit", "tests", "where", "you", "want", "to", "create", "and", "destroy", "the", "schema", "automatically", "." ]
99654d091ece9b281eec23c9e6fe9ff960e1baa1
https://github.com/jmoiron/modl/blob/99654d091ece9b281eec23c9e6fe9ff960e1baa1/dbmap.go#L163-L166
2,749
jmoiron/modl
dbmap.go
CreateTablesIfNotExists
func (m *DbMap) CreateTablesIfNotExists() error { _, err := m.createTables(true, true) return err }
go
func (m *DbMap) CreateTablesIfNotExists() error { _, err := m.createTables(true, true) return err }
[ "func", "(", "m", "*", "DbMap", ")", "CreateTablesIfNotExists", "(", ")", "error", "{", "_", ",", "err", ":=", "m", ".", "createTables", "(", "true", ",", "true", ")", "\n", "return", "err", "\n", "}" ]
// CreateTablesIfNotExists is similar to CreateTables, but starts // each statement with "create table if not exists" so that existing // tables do not raise errors.
[ "CreateTablesIfNotExists", "is", "similar", "to", "CreateTables", "but", "starts", "each", "statement", "with", "create", "table", "if", "not", "exists", "so", "that", "existing", "tables", "do", "not", "raise", "errors", "." ]
99654d091ece9b281eec23c9e6fe9ff960e1baa1
https://github.com/jmoiron/modl/blob/99654d091ece9b281eec23c9e6fe9ff960e1baa1/dbmap.go#L171-L174
2,750
jmoiron/modl
dbmap.go
DropTables
func (m *DbMap) DropTables() error { var err error for i := range m.tables { table := m.tables[i] _, e := m.Exec(fmt.Sprintf("drop table %s;", m.Dialect.QuoteField(table.TableName))) if e != nil { err = e } } return err }
go
func (m *DbMap) DropTables() error { var err error for i := range m.tables { table := m.tables[i] _, e := m.Exec(fmt.Sprintf("drop table %s;", m.Dialect.QuoteField(table.TableName))) if e != nil { err = e } } return err }
[ "func", "(", "m", "*", "DbMap", ")", "DropTables", "(", ")", "error", "{", "var", "err", "error", "\n", "for", "i", ":=", "range", "m", ".", "tables", "{", "table", ":=", "m", ".", "tables", "[", "i", "]", "\n", "_", ",", "e", ":=", "m", ".", "Exec", "(", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "m", ".", "Dialect", ".", "QuoteField", "(", "table", ".", "TableName", ")", ")", ")", "\n", "if", "e", "!=", "nil", "{", "err", "=", "e", "\n", "}", "\n", "}", "\n", "return", "err", "\n", "}" ]
// DropTables iterates through TableMaps registered to this DbMap and // executes "drop table" statements against the database for each.
[ "DropTables", "iterates", "through", "TableMaps", "registered", "to", "this", "DbMap", "and", "executes", "drop", "table", "statements", "against", "the", "database", "for", "each", "." ]
99654d091ece9b281eec23c9e6fe9ff960e1baa1
https://github.com/jmoiron/modl/blob/99654d091ece9b281eec23c9e6fe9ff960e1baa1/dbmap.go#L260-L270
2,751
jmoiron/modl
dbmap.go
SelectOne
func (m *DbMap) SelectOne(dest interface{}, query string, args ...interface{}) error { return hookedget(m, m, dest, query, args...) }
go
func (m *DbMap) SelectOne(dest interface{}, query string, args ...interface{}) error { return hookedget(m, m, dest, query, args...) }
[ "func", "(", "m", "*", "DbMap", ")", "SelectOne", "(", "dest", "interface", "{", "}", ",", "query", "string", ",", "args", "...", "interface", "{", "}", ")", "error", "{", "return", "hookedget", "(", "m", ",", "m", ",", "dest", ",", "query", ",", "args", "...", ")", "\n", "}" ]
// SelectOne runs an arbitrary SQL Query, binding the columns in the result to // fields on the struct specified by dest.
[ "SelectOne", "runs", "an", "arbitrary", "SQL", "Query", "binding", "the", "columns", "in", "the", "result", "to", "fields", "on", "the", "struct", "specified", "by", "dest", "." ]
99654d091ece9b281eec23c9e6fe9ff960e1baa1
https://github.com/jmoiron/modl/blob/99654d091ece9b281eec23c9e6fe9ff960e1baa1/dbmap.go#L356-L358
2,752
jmoiron/modl
dbmap.go
Begin
func (m *DbMap) Begin() (*Transaction, error) { m.trace("begin;") tx, err := m.Dbx.Beginx() if err != nil { return nil, err } return &Transaction{m, tx}, nil }
go
func (m *DbMap) Begin() (*Transaction, error) { m.trace("begin;") tx, err := m.Dbx.Beginx() if err != nil { return nil, err } return &Transaction{m, tx}, nil }
[ "func", "(", "m", "*", "DbMap", ")", "Begin", "(", ")", "(", "*", "Transaction", ",", "error", ")", "{", "m", ".", "trace", "(", "\"", "\"", ")", "\n", "tx", ",", "err", ":=", "m", ".", "Dbx", ".", "Beginx", "(", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "return", "&", "Transaction", "{", "m", ",", "tx", "}", ",", "nil", "\n", "}" ]
// Begin starts a modl Transaction.
[ "Begin", "starts", "a", "modl", "Transaction", "." ]
99654d091ece9b281eec23c9e6fe9ff960e1baa1
https://github.com/jmoiron/modl/blob/99654d091ece9b281eec23c9e6fe9ff960e1baa1/dbmap.go#L373-L380
2,753
jmoiron/modl
hooks.go
setupHooks
func (t *TableMap) setupHooks(i interface{}) { // These hooks must be implemented on a pointer, so if a value is passed in // we have to get a pointer for a new value of that type in order for the // type assertions to pass. ptr := i if reflect.ValueOf(i).Kind() == reflect.Struct { ptr = reflect.New(reflect.ValueOf(i).Type()).Interface() } _, t.CanPreInsert = ptr.(PreInserter) _, t.CanPostInsert = ptr.(PostInserter) _, t.CanPostGet = ptr.(PostGetter) _, t.CanPreUpdate = ptr.(PreUpdater) _, t.CanPostUpdate = ptr.(PostUpdater) _, t.CanPreDelete = ptr.(PreDeleter) _, t.CanPostDelete = ptr.(PostDeleter) }
go
func (t *TableMap) setupHooks(i interface{}) { // These hooks must be implemented on a pointer, so if a value is passed in // we have to get a pointer for a new value of that type in order for the // type assertions to pass. ptr := i if reflect.ValueOf(i).Kind() == reflect.Struct { ptr = reflect.New(reflect.ValueOf(i).Type()).Interface() } _, t.CanPreInsert = ptr.(PreInserter) _, t.CanPostInsert = ptr.(PostInserter) _, t.CanPostGet = ptr.(PostGetter) _, t.CanPreUpdate = ptr.(PreUpdater) _, t.CanPostUpdate = ptr.(PostUpdater) _, t.CanPreDelete = ptr.(PreDeleter) _, t.CanPostDelete = ptr.(PostDeleter) }
[ "func", "(", "t", "*", "TableMap", ")", "setupHooks", "(", "i", "interface", "{", "}", ")", "{", "// These hooks must be implemented on a pointer, so if a value is passed in", "// we have to get a pointer for a new value of that type in order for the", "// type assertions to pass.", "ptr", ":=", "i", "\n", "if", "reflect", ".", "ValueOf", "(", "i", ")", ".", "Kind", "(", ")", "==", "reflect", ".", "Struct", "{", "ptr", "=", "reflect", ".", "New", "(", "reflect", ".", "ValueOf", "(", "i", ")", ".", "Type", "(", ")", ")", ".", "Interface", "(", ")", "\n", "}", "\n\n", "_", ",", "t", ".", "CanPreInsert", "=", "ptr", ".", "(", "PreInserter", ")", "\n", "_", ",", "t", ".", "CanPostInsert", "=", "ptr", ".", "(", "PostInserter", ")", "\n", "_", ",", "t", ".", "CanPostGet", "=", "ptr", ".", "(", "PostGetter", ")", "\n", "_", ",", "t", ".", "CanPreUpdate", "=", "ptr", ".", "(", "PreUpdater", ")", "\n", "_", ",", "t", ".", "CanPostUpdate", "=", "ptr", ".", "(", "PostUpdater", ")", "\n", "_", ",", "t", ".", "CanPreDelete", "=", "ptr", ".", "(", "PreDeleter", ")", "\n", "_", ",", "t", ".", "CanPostDelete", "=", "ptr", ".", "(", "PostDeleter", ")", "\n", "}" ]
// Determine which hooks are supported by the mapper struct i
[ "Determine", "which", "hooks", "are", "supported", "by", "the", "mapper", "struct", "i" ]
99654d091ece9b281eec23c9e6fe9ff960e1baa1
https://github.com/jmoiron/modl/blob/99654d091ece9b281eec23c9e6fe9ff960e1baa1/hooks.go#L50-L66
2,754
jmoiron/modl
dialect.go
InsertAutoIncr
func (d PostgresDialect) InsertAutoIncr(e SqlExecutor, insertSql string, params ...interface{}) (int64, error) { rows, err := e.handle().Queryx(insertSql, params...) if err != nil { return 0, err } defer rows.Close() if rows.Next() { var id int64 err := rows.Scan(&id) return id, err } return 0, errors.New("No serial value returned for insert: " + insertSql + ", error: " + rows.Err().Error()) }
go
func (d PostgresDialect) InsertAutoIncr(e SqlExecutor, insertSql string, params ...interface{}) (int64, error) { rows, err := e.handle().Queryx(insertSql, params...) if err != nil { return 0, err } defer rows.Close() if rows.Next() { var id int64 err := rows.Scan(&id) return id, err } return 0, errors.New("No serial value returned for insert: " + insertSql + ", error: " + rows.Err().Error()) }
[ "func", "(", "d", "PostgresDialect", ")", "InsertAutoIncr", "(", "e", "SqlExecutor", ",", "insertSql", "string", ",", "params", "...", "interface", "{", "}", ")", "(", "int64", ",", "error", ")", "{", "rows", ",", "err", ":=", "e", ".", "handle", "(", ")", ".", "Queryx", "(", "insertSql", ",", "params", "...", ")", "\n", "if", "err", "!=", "nil", "{", "return", "0", ",", "err", "\n", "}", "\n", "defer", "rows", ".", "Close", "(", ")", "\n\n", "if", "rows", ".", "Next", "(", ")", "{", "var", "id", "int64", "\n", "err", ":=", "rows", ".", "Scan", "(", "&", "id", ")", "\n", "return", "id", ",", "err", "\n", "}", "\n\n", "return", "0", ",", "errors", ".", "New", "(", "\"", "\"", "+", "insertSql", "+", "\"", "\"", "+", "rows", ".", "Err", "(", ")", ".", "Error", "(", ")", ")", "\n", "}" ]
// InsertAutoIncr inserts via a query and reads the resultant rows for the new // auto increment ID, as it's not returned with the result in PostgreSQL.
[ "InsertAutoIncr", "inserts", "via", "a", "query", "and", "reads", "the", "resultant", "rows", "for", "the", "new", "auto", "increment", "ID", "as", "it", "s", "not", "returned", "with", "the", "result", "in", "PostgreSQL", "." ]
99654d091ece9b281eec23c9e6fe9ff960e1baa1
https://github.com/jmoiron/modl/blob/99654d091ece9b281eec23c9e6fe9ff960e1baa1/dialect.go#L263-L277
2,755
jmoiron/modl
dialect.go
ToSqlType
func (d MySQLDialect) ToSqlType(col *ColumnMap) string { switch col.gotype.Kind() { case reflect.Bool: return "boolean" case reflect.Int, reflect.Int16, reflect.Int32, reflect.Uint16, reflect.Uint32: return "int" case reflect.Int64, reflect.Uint64: return "bigint" case reflect.Float64, reflect.Float32: return "double" case reflect.Slice: if col.gotype.Elem().Kind() == reflect.Uint8 { return "mediumblob" } } switch col.gotype.Name() { case "NullableInt64": return "bigint" case "NullableFloat64": return "double" case "NullableBool": return "tinyint" case "NullableBytes": return "mediumblob" case "Time", "NullTime": return "datetime" } maxsize := col.MaxSize if col.MaxSize < 1 { maxsize = 255 } return fmt.Sprintf("varchar(%d)", maxsize) }
go
func (d MySQLDialect) ToSqlType(col *ColumnMap) string { switch col.gotype.Kind() { case reflect.Bool: return "boolean" case reflect.Int, reflect.Int16, reflect.Int32, reflect.Uint16, reflect.Uint32: return "int" case reflect.Int64, reflect.Uint64: return "bigint" case reflect.Float64, reflect.Float32: return "double" case reflect.Slice: if col.gotype.Elem().Kind() == reflect.Uint8 { return "mediumblob" } } switch col.gotype.Name() { case "NullableInt64": return "bigint" case "NullableFloat64": return "double" case "NullableBool": return "tinyint" case "NullableBytes": return "mediumblob" case "Time", "NullTime": return "datetime" } maxsize := col.MaxSize if col.MaxSize < 1 { maxsize = 255 } return fmt.Sprintf("varchar(%d)", maxsize) }
[ "func", "(", "d", "MySQLDialect", ")", "ToSqlType", "(", "col", "*", "ColumnMap", ")", "string", "{", "switch", "col", ".", "gotype", ".", "Kind", "(", ")", "{", "case", "reflect", ".", "Bool", ":", "return", "\"", "\"", "\n", "case", "reflect", ".", "Int", ",", "reflect", ".", "Int16", ",", "reflect", ".", "Int32", ",", "reflect", ".", "Uint16", ",", "reflect", ".", "Uint32", ":", "return", "\"", "\"", "\n", "case", "reflect", ".", "Int64", ",", "reflect", ".", "Uint64", ":", "return", "\"", "\"", "\n", "case", "reflect", ".", "Float64", ",", "reflect", ".", "Float32", ":", "return", "\"", "\"", "\n", "case", "reflect", ".", "Slice", ":", "if", "col", ".", "gotype", ".", "Elem", "(", ")", ".", "Kind", "(", ")", "==", "reflect", ".", "Uint8", "{", "return", "\"", "\"", "\n", "}", "\n", "}", "\n\n", "switch", "col", ".", "gotype", ".", "Name", "(", ")", "{", "case", "\"", "\"", ":", "return", "\"", "\"", "\n", "case", "\"", "\"", ":", "return", "\"", "\"", "\n", "case", "\"", "\"", ":", "return", "\"", "\"", "\n", "case", "\"", "\"", ":", "return", "\"", "\"", "\n", "case", "\"", "\"", ",", "\"", "\"", ":", "return", "\"", "\"", "\n", "}", "\n\n", "maxsize", ":=", "col", ".", "MaxSize", "\n", "if", "col", ".", "MaxSize", "<", "1", "{", "maxsize", "=", "255", "\n", "}", "\n", "return", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "maxsize", ")", "\n", "}" ]
// ToSqlType maps go types to MySQL types.
[ "ToSqlType", "maps", "go", "types", "to", "MySQL", "types", "." ]
99654d091ece9b281eec23c9e6fe9ff960e1baa1
https://github.com/jmoiron/modl/blob/99654d091ece9b281eec23c9e6fe9ff960e1baa1/dialect.go#L318-L352
2,756
jmoiron/modl
dialect.go
CreateTableSuffix
func (d MySQLDialect) CreateTableSuffix() string { return fmt.Sprintf(" engine=%s charset=%s", d.Engine, d.Encoding) }
go
func (d MySQLDialect) CreateTableSuffix() string { return fmt.Sprintf(" engine=%s charset=%s", d.Engine, d.Encoding) }
[ "func", "(", "d", "MySQLDialect", ")", "CreateTableSuffix", "(", ")", "string", "{", "return", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "d", ".", "Engine", ",", "d", ".", "Encoding", ")", "\n", "}" ]
// CreateTableSuffix returns engine=%s charset=%s based on values stored on struct
[ "CreateTableSuffix", "returns", "engine", "=", "%s", "charset", "=", "%s", "based", "on", "values", "stored", "on", "struct" ]
99654d091ece9b281eec23c9e6fe9ff960e1baa1
https://github.com/jmoiron/modl/blob/99654d091ece9b281eec23c9e6fe9ff960e1baa1/dialect.go#L370-L372
2,757
jmoiron/modl
tablemap.go
tableForPointer
func tableForPointer(m *DbMap, i interface{}, checkPk bool) (*TableMap, reflect.Value, error) { v := reflect.ValueOf(i) if v.Kind() != reflect.Ptr { return nil, v, fmt.Errorf("value %v not a pointer", v) } v = v.Elem() t := m.TableForType(v.Type()) if t == nil { return nil, v, fmt.Errorf("could not find table for %v", v.Type()) } if checkPk && len(t.Keys) < 1 { return t, v, &NoKeysErr{t} } return t, v, nil }
go
func tableForPointer(m *DbMap, i interface{}, checkPk bool) (*TableMap, reflect.Value, error) { v := reflect.ValueOf(i) if v.Kind() != reflect.Ptr { return nil, v, fmt.Errorf("value %v not a pointer", v) } v = v.Elem() t := m.TableForType(v.Type()) if t == nil { return nil, v, fmt.Errorf("could not find table for %v", v.Type()) } if checkPk && len(t.Keys) < 1 { return t, v, &NoKeysErr{t} } return t, v, nil }
[ "func", "tableForPointer", "(", "m", "*", "DbMap", ",", "i", "interface", "{", "}", ",", "checkPk", "bool", ")", "(", "*", "TableMap", ",", "reflect", ".", "Value", ",", "error", ")", "{", "v", ":=", "reflect", ".", "ValueOf", "(", "i", ")", "\n", "if", "v", ".", "Kind", "(", ")", "!=", "reflect", ".", "Ptr", "{", "return", "nil", ",", "v", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "v", ")", "\n", "}", "\n", "v", "=", "v", ".", "Elem", "(", ")", "\n", "t", ":=", "m", ".", "TableForType", "(", "v", ".", "Type", "(", ")", ")", "\n", "if", "t", "==", "nil", "{", "return", "nil", ",", "v", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "v", ".", "Type", "(", ")", ")", "\n", "}", "\n", "if", "checkPk", "&&", "len", "(", "t", ".", "Keys", ")", "<", "1", "{", "return", "t", ",", "v", ",", "&", "NoKeysErr", "{", "t", "}", "\n", "}", "\n", "return", "t", ",", "v", ",", "nil", "\n", "}" ]
// Return a table for a pointer; error if i is not a pointer or if the // table is not found
[ "Return", "a", "table", "for", "a", "pointer", ";", "error", "if", "i", "is", "not", "a", "pointer", "or", "if", "the", "table", "is", "not", "found" ]
99654d091ece9b281eec23c9e6fe9ff960e1baa1
https://github.com/jmoiron/modl/blob/99654d091ece9b281eec23c9e6fe9ff960e1baa1/tablemap.go#L361-L375
2,758
stretchr/gomniauth
providers/soundcloud/soundcloud.go
TripperFactory
func (provider *SoundcloudProvider) TripperFactory() common.TripperFactory { if provider.tripperFactory == nil { provider.tripperFactory = new(oauth2.OAuth2TripperFactory) } return provider.tripperFactory }
go
func (provider *SoundcloudProvider) TripperFactory() common.TripperFactory { if provider.tripperFactory == nil { provider.tripperFactory = new(oauth2.OAuth2TripperFactory) } return provider.tripperFactory }
[ "func", "(", "provider", "*", "SoundcloudProvider", ")", "TripperFactory", "(", ")", "common", ".", "TripperFactory", "{", "if", "provider", ".", "tripperFactory", "==", "nil", "{", "provider", ".", "tripperFactory", "=", "new", "(", "oauth2", ".", "OAuth2TripperFactory", ")", "\n", "}", "\n\n", "return", "provider", ".", "tripperFactory", "\n", "}" ]
// TipperFactory gets an OAuth2TripperFactory
[ "TipperFactory", "gets", "an", "OAuth2TripperFactory" ]
4b6c822be2eb64551618722ff80cecde4d63d9be
https://github.com/stretchr/gomniauth/blob/4b6c822be2eb64551618722ff80cecde4d63d9be/providers/soundcloud/soundcloud.go#L42-L49
2,759
stretchr/gomniauth
providers/soundcloud/soundcloud.go
Get
func (provider *SoundcloudProvider) Get(creds *common.Credentials, endpoint string) (objx.Map, error) { return oauth2.Get(provider, creds, endpoint) }
go
func (provider *SoundcloudProvider) Get(creds *common.Credentials, endpoint string) (objx.Map, error) { return oauth2.Get(provider, creds, endpoint) }
[ "func", "(", "provider", "*", "SoundcloudProvider", ")", "Get", "(", "creds", "*", "common", ".", "Credentials", ",", "endpoint", "string", ")", "(", "objx", ".", "Map", ",", "error", ")", "{", "return", "oauth2", ".", "Get", "(", "provider", ",", "creds", ",", "endpoint", ")", "\n", "}" ]
// Get makes an authenticated request and returns the data in the // response as a data map.
[ "Get", "makes", "an", "authenticated", "request", "and", "returns", "the", "data", "in", "the", "response", "as", "a", "data", "map", "." ]
4b6c822be2eb64551618722ff80cecde4d63d9be
https://github.com/stretchr/gomniauth/blob/4b6c822be2eb64551618722ff80cecde4d63d9be/providers/soundcloud/soundcloud.go#L85-L87
2,760
stretchr/gomniauth
provider_list.go
WithProviders
func WithProviders(providers ...common.Provider) *ProviderList { GetSecurityKey() list := &ProviderList{providers} SharedProviderList = list return list }
go
func WithProviders(providers ...common.Provider) *ProviderList { GetSecurityKey() list := &ProviderList{providers} SharedProviderList = list return list }
[ "func", "WithProviders", "(", "providers", "...", "common", ".", "Provider", ")", "*", "ProviderList", "{", "GetSecurityKey", "(", ")", "\n", "list", ":=", "&", "ProviderList", "{", "providers", "}", "\n", "SharedProviderList", "=", "list", "\n", "return", "list", "\n", "}" ]
// WithProviders generates a new ProviderList which should be // used to interact with Gomniauth services.
[ "WithProviders", "generates", "a", "new", "ProviderList", "which", "should", "be", "used", "to", "interact", "with", "Gomniauth", "services", "." ]
4b6c822be2eb64551618722ff80cecde4d63d9be
https://github.com/stretchr/gomniauth/blob/4b6c822be2eb64551618722ff80cecde4d63d9be/provider_list.go#L20-L25
2,761
stretchr/gomniauth
provider_list.go
Add
func (l *ProviderList) Add(provider common.Provider) *ProviderList { l.providers = append(l.providers, provider) return l }
go
func (l *ProviderList) Add(provider common.Provider) *ProviderList { l.providers = append(l.providers, provider) return l }
[ "func", "(", "l", "*", "ProviderList", ")", "Add", "(", "provider", "common", ".", "Provider", ")", "*", "ProviderList", "{", "l", ".", "providers", "=", "append", "(", "l", ".", "providers", ",", "provider", ")", "\n", "return", "l", "\n", "}" ]
// Add adds a provider to this list.
[ "Add", "adds", "a", "provider", "to", "this", "list", "." ]
4b6c822be2eb64551618722ff80cecde4d63d9be
https://github.com/stretchr/gomniauth/blob/4b6c822be2eb64551618722ff80cecde4d63d9be/provider_list.go#L28-L31
2,762
stretchr/gomniauth
provider_list.go
Provider
func (l *ProviderList) Provider(name string) (common.Provider, error) { // panic on nil if l == nil { panic(common.PrefixForErrors + "No providers have been initialised. Make sure you have called gomniauth.WithProviders(...).") } for _, provider := range l.providers { if provider.Name() == name { return provider, nil } } return nil, &common.MissingProviderError{ProviderName: name} }
go
func (l *ProviderList) Provider(name string) (common.Provider, error) { // panic on nil if l == nil { panic(common.PrefixForErrors + "No providers have been initialised. Make sure you have called gomniauth.WithProviders(...).") } for _, provider := range l.providers { if provider.Name() == name { return provider, nil } } return nil, &common.MissingProviderError{ProviderName: name} }
[ "func", "(", "l", "*", "ProviderList", ")", "Provider", "(", "name", "string", ")", "(", "common", ".", "Provider", ",", "error", ")", "{", "// panic on nil", "if", "l", "==", "nil", "{", "panic", "(", "common", ".", "PrefixForErrors", "+", "\"", "\"", ")", "\n", "}", "\n\n", "for", "_", ",", "provider", ":=", "range", "l", ".", "providers", "{", "if", "provider", ".", "Name", "(", ")", "==", "name", "{", "return", "provider", ",", "nil", "\n", "}", "\n", "}", "\n\n", "return", "nil", ",", "&", "common", ".", "MissingProviderError", "{", "ProviderName", ":", "name", "}", "\n", "}" ]
// Provider gets a provider by name, or returns a common.MissingProviderError // if no provider with that name is registered.
[ "Provider", "gets", "a", "provider", "by", "name", "or", "returns", "a", "common", ".", "MissingProviderError", "if", "no", "provider", "with", "that", "name", "is", "registered", "." ]
4b6c822be2eb64551618722ff80cecde4d63d9be
https://github.com/stretchr/gomniauth/blob/4b6c822be2eb64551618722ff80cecde4d63d9be/provider_list.go#L35-L49
2,763
stretchr/gomniauth
oauth2/oauth2_tripper_factory.go
NewTripper
func (f *OAuth2TripperFactory) NewTripper(creds *common.Credentials, provider common.Provider) (common.Tripper, error) { return NewOAuth2Tripper(creds, provider), nil }
go
func (f *OAuth2TripperFactory) NewTripper(creds *common.Credentials, provider common.Provider) (common.Tripper, error) { return NewOAuth2Tripper(creds, provider), nil }
[ "func", "(", "f", "*", "OAuth2TripperFactory", ")", "NewTripper", "(", "creds", "*", "common", ".", "Credentials", ",", "provider", "common", ".", "Provider", ")", "(", "common", ".", "Tripper", ",", "error", ")", "{", "return", "NewOAuth2Tripper", "(", "creds", ",", "provider", ")", ",", "nil", "\n", "}" ]
// NewTripper creates a Tripper object for the OAuth2 authentication protocol.
[ "NewTripper", "creates", "a", "Tripper", "object", "for", "the", "OAuth2", "authentication", "protocol", "." ]
4b6c822be2eb64551618722ff80cecde4d63d9be
https://github.com/stretchr/gomniauth/blob/4b6c822be2eb64551618722ff80cecde4d63d9be/oauth2/oauth2_tripper_factory.go#L12-L14
2,764
stretchr/gomniauth
common/credentials.go
PublicData
func (c *Credentials) PublicData(options map[string]interface{}) (publicData interface{}, err error) { // ensure the ID is a string idValue := c.Map.Get(CredentialsKeyID).Data() var idStringValue string switch idValue.(type) { case float64: idStringValue = strconv.FormatFloat(idValue.(float64), 'g', -1, 64) case string: idStringValue = idValue.(string) default: idStringValue = fmt.Sprintf("%v", idValue) } c.Map.Set(CredentialsKeyID, idStringValue) return c.Map, nil }
go
func (c *Credentials) PublicData(options map[string]interface{}) (publicData interface{}, err error) { // ensure the ID is a string idValue := c.Map.Get(CredentialsKeyID).Data() var idStringValue string switch idValue.(type) { case float64: idStringValue = strconv.FormatFloat(idValue.(float64), 'g', -1, 64) case string: idStringValue = idValue.(string) default: idStringValue = fmt.Sprintf("%v", idValue) } c.Map.Set(CredentialsKeyID, idStringValue) return c.Map, nil }
[ "func", "(", "c", "*", "Credentials", ")", "PublicData", "(", "options", "map", "[", "string", "]", "interface", "{", "}", ")", "(", "publicData", "interface", "{", "}", ",", "err", "error", ")", "{", "// ensure the ID is a string", "idValue", ":=", "c", ".", "Map", ".", "Get", "(", "CredentialsKeyID", ")", ".", "Data", "(", ")", "\n", "var", "idStringValue", "string", "\n", "switch", "idValue", ".", "(", "type", ")", "{", "case", "float64", ":", "idStringValue", "=", "strconv", ".", "FormatFloat", "(", "idValue", ".", "(", "float64", ")", ",", "'g'", ",", "-", "1", ",", "64", ")", "\n", "case", "string", ":", "idStringValue", "=", "idValue", ".", "(", "string", ")", "\n", "default", ":", "idStringValue", "=", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "idValue", ")", "\n", "}", "\n", "c", ".", "Map", ".", "Set", "(", "CredentialsKeyID", ",", "idStringValue", ")", "\n\n", "return", "c", ".", "Map", ",", "nil", "\n", "}" ]
// PublicData gets the storable data from this credentials object.
[ "PublicData", "gets", "the", "storable", "data", "from", "this", "credentials", "object", "." ]
4b6c822be2eb64551618722ff80cecde4d63d9be
https://github.com/stretchr/gomniauth/blob/4b6c822be2eb64551618722ff80cecde4d63d9be/common/credentials.go#L22-L38
2,765
stretchr/gomniauth
providers/heroku/heroku.go
GetClient
func (provider *HerokuProvider) GetClient(creds *common.Credentials) (*http.Client, error) { return oauth2.GetClient(provider.TripperFactory(), creds, provider) }
go
func (provider *HerokuProvider) GetClient(creds *common.Credentials) (*http.Client, error) { return oauth2.GetClient(provider.TripperFactory(), creds, provider) }
[ "func", "(", "provider", "*", "HerokuProvider", ")", "GetClient", "(", "creds", "*", "common", ".", "Credentials", ")", "(", "*", "http", ".", "Client", ",", "error", ")", "{", "return", "oauth2", ".", "GetClient", "(", "provider", ".", "TripperFactory", "(", ")", ",", "creds", ",", "provider", ")", "\n", "}" ]
// GetClient returns an authenticated http.Client that can be used to make requests to // protected heroku resources
[ "GetClient", "returns", "an", "authenticated", "http", ".", "Client", "that", "can", "be", "used", "to", "make", "requests", "to", "protected", "heroku", "resources" ]
4b6c822be2eb64551618722ff80cecde4d63d9be
https://github.com/stretchr/gomniauth/blob/4b6c822be2eb64551618722ff80cecde4d63d9be/providers/heroku/heroku.go#L115-L117
2,766
stretchr/gomniauth
oauth2/get.go
Get
func Get(provider common.Provider, creds *common.Credentials, endpoint string) (objx.Map, error) { client, clientErr := provider.GetClient(creds) if clientErr != nil { return nil, clientErr } response, responseErr := client.Get(endpoint) if responseErr != nil { return nil, responseErr } body, bodyErr := ioutil.ReadAll(response.Body) if bodyErr != nil { return nil, bodyErr } defer response.Body.Close() codecs := services.NewWebCodecService() codec, getCodecErr := codecs.GetCodec(response.Header.Get("Content-Type")) if getCodecErr != nil { return nil, getCodecErr } var data objx.Map unmarshalErr := codec.Unmarshal(body, &data) if unmarshalErr != nil { return nil, unmarshalErr } return data, nil }
go
func Get(provider common.Provider, creds *common.Credentials, endpoint string) (objx.Map, error) { client, clientErr := provider.GetClient(creds) if clientErr != nil { return nil, clientErr } response, responseErr := client.Get(endpoint) if responseErr != nil { return nil, responseErr } body, bodyErr := ioutil.ReadAll(response.Body) if bodyErr != nil { return nil, bodyErr } defer response.Body.Close() codecs := services.NewWebCodecService() codec, getCodecErr := codecs.GetCodec(response.Header.Get("Content-Type")) if getCodecErr != nil { return nil, getCodecErr } var data objx.Map unmarshalErr := codec.Unmarshal(body, &data) if unmarshalErr != nil { return nil, unmarshalErr } return data, nil }
[ "func", "Get", "(", "provider", "common", ".", "Provider", ",", "creds", "*", "common", ".", "Credentials", ",", "endpoint", "string", ")", "(", "objx", ".", "Map", ",", "error", ")", "{", "client", ",", "clientErr", ":=", "provider", ".", "GetClient", "(", "creds", ")", "\n\n", "if", "clientErr", "!=", "nil", "{", "return", "nil", ",", "clientErr", "\n", "}", "\n\n", "response", ",", "responseErr", ":=", "client", ".", "Get", "(", "endpoint", ")", "\n\n", "if", "responseErr", "!=", "nil", "{", "return", "nil", ",", "responseErr", "\n", "}", "\n\n", "body", ",", "bodyErr", ":=", "ioutil", ".", "ReadAll", "(", "response", ".", "Body", ")", "\n\n", "if", "bodyErr", "!=", "nil", "{", "return", "nil", ",", "bodyErr", "\n", "}", "\n\n", "defer", "response", ".", "Body", ".", "Close", "(", ")", "\n\n", "codecs", ":=", "services", ".", "NewWebCodecService", "(", ")", "\n", "codec", ",", "getCodecErr", ":=", "codecs", ".", "GetCodec", "(", "response", ".", "Header", ".", "Get", "(", "\"", "\"", ")", ")", "\n\n", "if", "getCodecErr", "!=", "nil", "{", "return", "nil", ",", "getCodecErr", "\n", "}", "\n\n", "var", "data", "objx", ".", "Map", "\n", "unmarshalErr", ":=", "codec", ".", "Unmarshal", "(", "body", ",", "&", "data", ")", "\n\n", "if", "unmarshalErr", "!=", "nil", "{", "return", "nil", ",", "unmarshalErr", "\n", "}", "\n\n", "return", "data", ",", "nil", "\n\n", "}" ]
// Get executes an authenticated HTTP GET against the given provider and returns an // objx.Map of the response. // // The response type is automatically detected and used to unmarshal the response.
[ "Get", "executes", "an", "authenticated", "HTTP", "GET", "against", "the", "given", "provider", "and", "returns", "an", "objx", ".", "Map", "of", "the", "response", ".", "The", "response", "type", "is", "automatically", "detected", "and", "used", "to", "unmarshal", "the", "response", "." ]
4b6c822be2eb64551618722ff80cecde4d63d9be
https://github.com/stretchr/gomniauth/blob/4b6c822be2eb64551618722ff80cecde4d63d9be/oauth2/get.go#L14-L52
2,767
stretchr/gomniauth
oauth2/get_client.go
GetClient
func GetClient(tripperFactory common.TripperFactory, creds *common.Credentials, provider common.Provider) (*http.Client, error) { tripper, tripperErr := tripperFactory.NewTripper(creds, provider) if tripperErr != nil { return nil, tripperErr } return &http.Client{Transport: tripper}, nil }
go
func GetClient(tripperFactory common.TripperFactory, creds *common.Credentials, provider common.Provider) (*http.Client, error) { tripper, tripperErr := tripperFactory.NewTripper(creds, provider) if tripperErr != nil { return nil, tripperErr } return &http.Client{Transport: tripper}, nil }
[ "func", "GetClient", "(", "tripperFactory", "common", ".", "TripperFactory", ",", "creds", "*", "common", ".", "Credentials", ",", "provider", "common", ".", "Provider", ")", "(", "*", "http", ".", "Client", ",", "error", ")", "{", "tripper", ",", "tripperErr", ":=", "tripperFactory", ".", "NewTripper", "(", "creds", ",", "provider", ")", "\n\n", "if", "tripperErr", "!=", "nil", "{", "return", "nil", ",", "tripperErr", "\n", "}", "\n\n", "return", "&", "http", ".", "Client", "{", "Transport", ":", "tripper", "}", ",", "nil", "\n", "}" ]
// GetClient gets an http.Client authenticated with the specified // common.Credentials.
[ "GetClient", "gets", "an", "http", ".", "Client", "authenticated", "with", "the", "specified", "common", ".", "Credentials", "." ]
4b6c822be2eb64551618722ff80cecde4d63d9be
https://github.com/stretchr/gomniauth/blob/4b6c822be2eb64551618722ff80cecde4d63d9be/oauth2/get_client.go#L10-L19
2,768
stretchr/gomniauth
providers/soundcloud/user.go
IDForProvider
func (u *User) IDForProvider(provider string) string { id := u.ProviderCredentials()[provider].Get(common.CredentialsKeyID).Data() switch id.(type) { case string: return id.(string) case float64: return strconv.FormatFloat(id.(float64), 'f', 0, 64) } return "" }
go
func (u *User) IDForProvider(provider string) string { id := u.ProviderCredentials()[provider].Get(common.CredentialsKeyID).Data() switch id.(type) { case string: return id.(string) case float64: return strconv.FormatFloat(id.(float64), 'f', 0, 64) } return "" }
[ "func", "(", "u", "*", "User", ")", "IDForProvider", "(", "provider", "string", ")", "string", "{", "id", ":=", "u", ".", "ProviderCredentials", "(", ")", "[", "provider", "]", ".", "Get", "(", "common", ".", "CredentialsKeyID", ")", ".", "Data", "(", ")", "\n", "switch", "id", ".", "(", "type", ")", "{", "case", "string", ":", "return", "id", ".", "(", "string", ")", "\n", "case", "float64", ":", "return", "strconv", ".", "FormatFloat", "(", "id", ".", "(", "float64", ")", ",", "'f'", ",", "0", ",", "64", ")", "\n", "}", "\n", "return", "\"", "\"", "\n", "}" ]
// IDForProvider gets the ID value for the specified provider name for // this user from the ProviderCredentials data.
[ "IDForProvider", "gets", "the", "ID", "value", "for", "the", "specified", "provider", "name", "for", "this", "user", "from", "the", "ProviderCredentials", "data", "." ]
4b6c822be2eb64551618722ff80cecde4d63d9be
https://github.com/stretchr/gomniauth/blob/4b6c822be2eb64551618722ff80cecde4d63d9be/providers/soundcloud/user.go#L60-L69
2,769
stretchr/gomniauth
oauth2/url.go
GetBeginAuthURLWithBase
func GetBeginAuthURLWithBase(base string, state *common.State, config *common.Config) (string, error) { if config == nil { panic("OAuth2Handler: Must have valid Config specified.") } // copy the config params := objx.MSI( OAuth2KeyClientID, config.Get(OAuth2KeyClientID).Str(), OAuth2KeyRedirectUrl, config.Get(OAuth2KeyRedirectUrl).Str(), OAuth2KeyScope, config.Get(OAuth2KeyScope).Str(), OAuth2KeyAccessType, config.Get(OAuth2KeyAccessType).Str(), OAuth2KeyApprovalPrompt, config.Get(OAuth2KeyApprovalPrompt).Str(), OAuth2KeyResponseType, config.Get(OAuth2KeyResponseType).Str()) if state != nil { // set the state stateValue, stateErr := state.SignedBase64(common.GetSecurityKey()) if stateErr != nil { return "", stateErr } params.Set("state", stateValue) } // generate the query part query, queryErr := params.URLQuery() if queryErr != nil { return "", queryErr } // put the strings together return base + "?" + query, nil }
go
func GetBeginAuthURLWithBase(base string, state *common.State, config *common.Config) (string, error) { if config == nil { panic("OAuth2Handler: Must have valid Config specified.") } // copy the config params := objx.MSI( OAuth2KeyClientID, config.Get(OAuth2KeyClientID).Str(), OAuth2KeyRedirectUrl, config.Get(OAuth2KeyRedirectUrl).Str(), OAuth2KeyScope, config.Get(OAuth2KeyScope).Str(), OAuth2KeyAccessType, config.Get(OAuth2KeyAccessType).Str(), OAuth2KeyApprovalPrompt, config.Get(OAuth2KeyApprovalPrompt).Str(), OAuth2KeyResponseType, config.Get(OAuth2KeyResponseType).Str()) if state != nil { // set the state stateValue, stateErr := state.SignedBase64(common.GetSecurityKey()) if stateErr != nil { return "", stateErr } params.Set("state", stateValue) } // generate the query part query, queryErr := params.URLQuery() if queryErr != nil { return "", queryErr } // put the strings together return base + "?" + query, nil }
[ "func", "GetBeginAuthURLWithBase", "(", "base", "string", ",", "state", "*", "common", ".", "State", ",", "config", "*", "common", ".", "Config", ")", "(", "string", ",", "error", ")", "{", "if", "config", "==", "nil", "{", "panic", "(", "\"", "\"", ")", "\n", "}", "\n\n", "// copy the config", "params", ":=", "objx", ".", "MSI", "(", "OAuth2KeyClientID", ",", "config", ".", "Get", "(", "OAuth2KeyClientID", ")", ".", "Str", "(", ")", ",", "OAuth2KeyRedirectUrl", ",", "config", ".", "Get", "(", "OAuth2KeyRedirectUrl", ")", ".", "Str", "(", ")", ",", "OAuth2KeyScope", ",", "config", ".", "Get", "(", "OAuth2KeyScope", ")", ".", "Str", "(", ")", ",", "OAuth2KeyAccessType", ",", "config", ".", "Get", "(", "OAuth2KeyAccessType", ")", ".", "Str", "(", ")", ",", "OAuth2KeyApprovalPrompt", ",", "config", ".", "Get", "(", "OAuth2KeyApprovalPrompt", ")", ".", "Str", "(", ")", ",", "OAuth2KeyResponseType", ",", "config", ".", "Get", "(", "OAuth2KeyResponseType", ")", ".", "Str", "(", ")", ")", "\n\n", "if", "state", "!=", "nil", "{", "// set the state", "stateValue", ",", "stateErr", ":=", "state", ".", "SignedBase64", "(", "common", ".", "GetSecurityKey", "(", ")", ")", "\n\n", "if", "stateErr", "!=", "nil", "{", "return", "\"", "\"", ",", "stateErr", "\n", "}", "\n\n", "params", ".", "Set", "(", "\"", "\"", ",", "stateValue", ")", "\n\n", "}", "\n\n", "// generate the query part", "query", ",", "queryErr", ":=", "params", ".", "URLQuery", "(", ")", "\n\n", "if", "queryErr", "!=", "nil", "{", "return", "\"", "\"", ",", "queryErr", "\n", "}", "\n\n", "// put the strings together", "return", "base", "+", "\"", "\"", "+", "query", ",", "nil", "\n", "}" ]
// GetBeginAuthURLWithBase returns the OAuth2 authorization URL from the given arguments. // // The state object will be encoded to base64 and signed to ensure integrity.
[ "GetBeginAuthURLWithBase", "returns", "the", "OAuth2", "authorization", "URL", "from", "the", "given", "arguments", ".", "The", "state", "object", "will", "be", "encoded", "to", "base64", "and", "signed", "to", "ensure", "integrity", "." ]
4b6c822be2eb64551618722ff80cecde4d63d9be
https://github.com/stretchr/gomniauth/blob/4b6c822be2eb64551618722ff80cecde4d63d9be/oauth2/url.go#L11-L48
2,770
stretchr/gomniauth
oauth2/header.go
AuthorizationHeader
func AuthorizationHeader(creds *common.Credentials) (key, value string) { return "Authorization", "Bearer " + creds.Get(OAuth2KeyAccessToken).Str("Invalid") }
go
func AuthorizationHeader(creds *common.Credentials) (key, value string) { return "Authorization", "Bearer " + creds.Get(OAuth2KeyAccessToken).Str("Invalid") }
[ "func", "AuthorizationHeader", "(", "creds", "*", "common", ".", "Credentials", ")", "(", "key", ",", "value", "string", ")", "{", "return", "\"", "\"", ",", "\"", "\"", "+", "creds", ".", "Get", "(", "OAuth2KeyAccessToken", ")", ".", "Str", "(", "\"", "\"", ")", "\n", "}" ]
// AuthorizationHeader returns the key, value pair to insert into an authorized request.
[ "AuthorizationHeader", "returns", "the", "key", "value", "pair", "to", "insert", "into", "an", "authorized", "request", "." ]
4b6c822be2eb64551618722ff80cecde4d63d9be
https://github.com/stretchr/gomniauth/blob/4b6c822be2eb64551618722ff80cecde4d63d9be/oauth2/header.go#L8-L10
2,771
stretchr/gomniauth
facade.go
ProviderPublicData
func ProviderPublicData(provider common.Provider, options map[string]interface{}) (interface{}, error) { optionsx := objx.New(options) return map[string]interface{}{ "name": provider.Name(), "display": provider.DisplayName(), "loginpath": fmt.Sprintf(optionsx.Get("loginpathFormat").Str("auth/%s/login"), provider.Name()), }, nil }
go
func ProviderPublicData(provider common.Provider, options map[string]interface{}) (interface{}, error) { optionsx := objx.New(options) return map[string]interface{}{ "name": provider.Name(), "display": provider.DisplayName(), "loginpath": fmt.Sprintf(optionsx.Get("loginpathFormat").Str("auth/%s/login"), provider.Name()), }, nil }
[ "func", "ProviderPublicData", "(", "provider", "common", ".", "Provider", ",", "options", "map", "[", "string", "]", "interface", "{", "}", ")", "(", "interface", "{", "}", ",", "error", ")", "{", "optionsx", ":=", "objx", ".", "New", "(", "options", ")", "\n\n", "return", "map", "[", "string", "]", "interface", "{", "}", "{", "\"", "\"", ":", "provider", ".", "Name", "(", ")", ",", "\"", "\"", ":", "provider", ".", "DisplayName", "(", ")", ",", "\"", "\"", ":", "fmt", ".", "Sprintf", "(", "optionsx", ".", "Get", "(", "\"", "\"", ")", ".", "Str", "(", "\"", "\"", ")", ",", "provider", ".", "Name", "(", ")", ")", ",", "}", ",", "nil", "\n\n", "}" ]
// ProviderPublicData gets the public data for the specified provider. // // The options should contain the `loginpathFormat`, which will determine how the // loginpath value is created.
[ "ProviderPublicData", "gets", "the", "public", "data", "for", "the", "specified", "provider", ".", "The", "options", "should", "contain", "the", "loginpathFormat", "which", "will", "determine", "how", "the", "loginpath", "value", "is", "created", "." ]
4b6c822be2eb64551618722ff80cecde4d63d9be
https://github.com/stretchr/gomniauth/blob/4b6c822be2eb64551618722ff80cecde4d63d9be/facade.go#L13-L23
2,772
stretchr/gomniauth
shortcuts.go
StateFromParam
func StateFromParam(paramValue string) (*common.State, error) { stateMap, err := objx.FromSignedBase64(paramValue, GetSecurityKey()) if err != nil { return nil, err } return &common.State{Map: stateMap}, nil }
go
func StateFromParam(paramValue string) (*common.State, error) { stateMap, err := objx.FromSignedBase64(paramValue, GetSecurityKey()) if err != nil { return nil, err } return &common.State{Map: stateMap}, nil }
[ "func", "StateFromParam", "(", "paramValue", "string", ")", "(", "*", "common", ".", "State", ",", "error", ")", "{", "stateMap", ",", "err", ":=", "objx", ".", "FromSignedBase64", "(", "paramValue", ",", "GetSecurityKey", "(", ")", ")", "\n\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n\n", "return", "&", "common", ".", "State", "{", "Map", ":", "stateMap", "}", ",", "nil", "\n", "}" ]
// StateFromParam decodes the state parameter hash and turns it // into a usable State object.
[ "StateFromParam", "decodes", "the", "state", "parameter", "hash", "and", "turns", "it", "into", "a", "usable", "State", "object", "." ]
4b6c822be2eb64551618722ff80cecde4d63d9be
https://github.com/stretchr/gomniauth/blob/4b6c822be2eb64551618722ff80cecde4d63d9be/shortcuts.go#L23-L32
2,773
stretchr/gomniauth
oauth2/oauth2_tripper.go
NewOAuth2Tripper
func NewOAuth2Tripper(creds *common.Credentials, provider common.Provider) *OAuth2Tripper { return &OAuth2Tripper{common.GetRoundTripper(), creds, provider} }
go
func NewOAuth2Tripper(creds *common.Credentials, provider common.Provider) *OAuth2Tripper { return &OAuth2Tripper{common.GetRoundTripper(), creds, provider} }
[ "func", "NewOAuth2Tripper", "(", "creds", "*", "common", ".", "Credentials", ",", "provider", "common", ".", "Provider", ")", "*", "OAuth2Tripper", "{", "return", "&", "OAuth2Tripper", "{", "common", ".", "GetRoundTripper", "(", ")", ",", "creds", ",", "provider", "}", "\n", "}" ]
// NewOAuth2Tripper creates a new OAuth2Tripper with the given arguments.
[ "NewOAuth2Tripper", "creates", "a", "new", "OAuth2Tripper", "with", "the", "given", "arguments", "." ]
4b6c822be2eb64551618722ff80cecde4d63d9be
https://github.com/stretchr/gomniauth/blob/4b6c822be2eb64551618722ff80cecde4d63d9be/oauth2/oauth2_tripper.go#L15-L17
2,774
stretchr/gomniauth
oauth2/oauth2_tripper.go
RoundTrip
func (t *OAuth2Tripper) RoundTrip(req *http.Request) (*http.Response, error) { //TODO: check token expiration and renew if necessary if t.Credentials() != nil { // copy the request req = cloneRequest(req) // set the header headerK, headerV := AuthorizationHeader(t.Credentials()) req.Header.Set(headerK, headerV) // set the accept header to ask for JSON req.Header.Set("Accept", "application/json") } return t.underlyingTransport.RoundTrip(req) }
go
func (t *OAuth2Tripper) RoundTrip(req *http.Request) (*http.Response, error) { //TODO: check token expiration and renew if necessary if t.Credentials() != nil { // copy the request req = cloneRequest(req) // set the header headerK, headerV := AuthorizationHeader(t.Credentials()) req.Header.Set(headerK, headerV) // set the accept header to ask for JSON req.Header.Set("Accept", "application/json") } return t.underlyingTransport.RoundTrip(req) }
[ "func", "(", "t", "*", "OAuth2Tripper", ")", "RoundTrip", "(", "req", "*", "http", ".", "Request", ")", "(", "*", "http", ".", "Response", ",", "error", ")", "{", "//TODO: check token expiration and renew if necessary", "if", "t", ".", "Credentials", "(", ")", "!=", "nil", "{", "// copy the request", "req", "=", "cloneRequest", "(", "req", ")", "\n\n", "// set the header", "headerK", ",", "headerV", ":=", "AuthorizationHeader", "(", "t", ".", "Credentials", "(", ")", ")", "\n", "req", ".", "Header", ".", "Set", "(", "headerK", ",", "headerV", ")", "\n\n", "// set the accept header to ask for JSON", "req", ".", "Header", ".", "Set", "(", "\"", "\"", ",", "\"", "\"", ")", "\n\n", "}", "\n\n", "return", "t", ".", "underlyingTransport", ".", "RoundTrip", "(", "req", ")", "\n", "}" ]
// RoundTrip is called by the http package when making a request to a server. This // implementation of RoundTrip inserts the appropriate authorization headers // into the request in order to enable access of protected resources. // // If the auth token has expired, RoundTrip will attempt to renew it.
[ "RoundTrip", "is", "called", "by", "the", "http", "package", "when", "making", "a", "request", "to", "a", "server", ".", "This", "implementation", "of", "RoundTrip", "inserts", "the", "appropriate", "authorization", "headers", "into", "the", "request", "in", "order", "to", "enable", "access", "of", "protected", "resources", ".", "If", "the", "auth", "token", "has", "expired", "RoundTrip", "will", "attempt", "to", "renew", "it", "." ]
4b6c822be2eb64551618722ff80cecde4d63d9be
https://github.com/stretchr/gomniauth/blob/4b6c822be2eb64551618722ff80cecde4d63d9be/oauth2/oauth2_tripper.go#L24-L43
2,775
v2pro/plz
gls/goid.go
GoID
func GoID() int64 { g := getg() p_goid := (*int64)(unsafe.Pointer(g + goidOffset)) return *p_goid }
go
func GoID() int64 { g := getg() p_goid := (*int64)(unsafe.Pointer(g + goidOffset)) return *p_goid }
[ "func", "GoID", "(", ")", "int64", "{", "g", ":=", "getg", "(", ")", "\n", "p_goid", ":=", "(", "*", "int64", ")", "(", "unsafe", ".", "Pointer", "(", "g", "+", "goidOffset", ")", ")", "\n", "return", "*", "p_goid", "\n", "}" ]
// GoID returns the goroutine id of current goroutine
[ "GoID", "returns", "the", "goroutine", "id", "of", "current", "goroutine" ]
2d49b86ea38230256fa4bf998fad76b8878c7be3
https://github.com/v2pro/plz/blob/2d49b86ea38230256fa4bf998fad76b8878c7be3/gls/goid.go#L21-L25
2,776
v2pro/plz
msgfmt/jsonfmt/encoder_float.go
WriteFloat32
func WriteFloat32(space []byte, val float32) []byte { abs := math.Abs(float64(val)) fmt := byte('f') // Note: Must use float32 comparisons for underlying float32 value to get precise cutoffs right. if abs != 0 { if float32(abs) < 1e-6 || float32(abs) >= 1e21 { fmt = 'e' } } return append(space, strconv.FormatFloat(float64(val), fmt, -1, 32)...) }
go
func WriteFloat32(space []byte, val float32) []byte { abs := math.Abs(float64(val)) fmt := byte('f') // Note: Must use float32 comparisons for underlying float32 value to get precise cutoffs right. if abs != 0 { if float32(abs) < 1e-6 || float32(abs) >= 1e21 { fmt = 'e' } } return append(space, strconv.FormatFloat(float64(val), fmt, -1, 32)...) }
[ "func", "WriteFloat32", "(", "space", "[", "]", "byte", ",", "val", "float32", ")", "[", "]", "byte", "{", "abs", ":=", "math", ".", "Abs", "(", "float64", "(", "val", ")", ")", "\n", "fmt", ":=", "byte", "(", "'f'", ")", "\n", "// Note: Must use float32 comparisons for underlying float32 value to get precise cutoffs right.", "if", "abs", "!=", "0", "{", "if", "float32", "(", "abs", ")", "<", "1e-6", "||", "float32", "(", "abs", ")", ">=", "1e21", "{", "fmt", "=", "'e'", "\n", "}", "\n", "}", "\n", "return", "append", "(", "space", ",", "strconv", ".", "FormatFloat", "(", "float64", "(", "val", ")", ",", "fmt", ",", "-", "1", ",", "32", ")", "...", ")", "\n", "}" ]
// WriteFloat32 write float32 to stream
[ "WriteFloat32", "write", "float32", "to", "stream" ]
2d49b86ea38230256fa4bf998fad76b8878c7be3
https://github.com/v2pro/plz/blob/2d49b86ea38230256fa4bf998fad76b8878c7be3/msgfmt/jsonfmt/encoder_float.go#L71-L81
2,777
tyler-smith/go-bip32
bip32.go
NewMasterKey
func NewMasterKey(seed []byte) (*Key, error) { // Generate key and chaincode hmac := hmac.New(sha512.New, []byte("Bitcoin seed")) _, err := hmac.Write(seed) if err != nil { return nil, err } intermediary := hmac.Sum(nil) // Split it into our key and chain code keyBytes := intermediary[:32] chainCode := intermediary[32:] // Validate key err = validatePrivateKey(keyBytes) if err != nil { return nil, err } // Create the key struct key := &Key{ Version: PrivateWalletVersion, ChainCode: chainCode, Key: keyBytes, Depth: 0x0, ChildNumber: []byte{0x00, 0x00, 0x00, 0x00}, FingerPrint: []byte{0x00, 0x00, 0x00, 0x00}, IsPrivate: true, } return key, nil }
go
func NewMasterKey(seed []byte) (*Key, error) { // Generate key and chaincode hmac := hmac.New(sha512.New, []byte("Bitcoin seed")) _, err := hmac.Write(seed) if err != nil { return nil, err } intermediary := hmac.Sum(nil) // Split it into our key and chain code keyBytes := intermediary[:32] chainCode := intermediary[32:] // Validate key err = validatePrivateKey(keyBytes) if err != nil { return nil, err } // Create the key struct key := &Key{ Version: PrivateWalletVersion, ChainCode: chainCode, Key: keyBytes, Depth: 0x0, ChildNumber: []byte{0x00, 0x00, 0x00, 0x00}, FingerPrint: []byte{0x00, 0x00, 0x00, 0x00}, IsPrivate: true, } return key, nil }
[ "func", "NewMasterKey", "(", "seed", "[", "]", "byte", ")", "(", "*", "Key", ",", "error", ")", "{", "// Generate key and chaincode", "hmac", ":=", "hmac", ".", "New", "(", "sha512", ".", "New", ",", "[", "]", "byte", "(", "\"", "\"", ")", ")", "\n", "_", ",", "err", ":=", "hmac", ".", "Write", "(", "seed", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "intermediary", ":=", "hmac", ".", "Sum", "(", "nil", ")", "\n\n", "// Split it into our key and chain code", "keyBytes", ":=", "intermediary", "[", ":", "32", "]", "\n", "chainCode", ":=", "intermediary", "[", "32", ":", "]", "\n\n", "// Validate key", "err", "=", "validatePrivateKey", "(", "keyBytes", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n\n", "// Create the key struct", "key", ":=", "&", "Key", "{", "Version", ":", "PrivateWalletVersion", ",", "ChainCode", ":", "chainCode", ",", "Key", ":", "keyBytes", ",", "Depth", ":", "0x0", ",", "ChildNumber", ":", "[", "]", "byte", "{", "0x00", ",", "0x00", ",", "0x00", ",", "0x00", "}", ",", "FingerPrint", ":", "[", "]", "byte", "{", "0x00", ",", "0x00", ",", "0x00", ",", "0x00", "}", ",", "IsPrivate", ":", "true", ",", "}", "\n\n", "return", "key", ",", "nil", "\n", "}" ]
// NewMasterKey creates a new master extended key from a seed
[ "NewMasterKey", "creates", "a", "new", "master", "extended", "key", "from", "a", "seed" ]
2c9cfd17756470a0b7c3e4b7954bae7d11035504
https://github.com/tyler-smith/go-bip32/blob/2c9cfd17756470a0b7c3e4b7954bae7d11035504/bip32.go#L59-L90
2,778
tyler-smith/go-bip32
bip32.go
NewChildKey
func (key *Key) NewChildKey(childIdx uint32) (*Key, error) { // Fail early if trying to create hardned child from public key if !key.IsPrivate && childIdx >= FirstHardenedChild { return nil, ErrHardnedChildPublicKey } intermediary, err := key.getIntermediary(childIdx) if err != nil { return nil, err } // Create child Key with data common to all both scenarios childKey := &Key{ ChildNumber: uint32Bytes(childIdx), ChainCode: intermediary[32:], Depth: key.Depth + 1, IsPrivate: key.IsPrivate, } // Bip32 CKDpriv if key.IsPrivate { childKey.Version = PrivateWalletVersion fingerprint, err := hash160(publicKeyForPrivateKey(key.Key)) if err != nil { return nil, err } childKey.FingerPrint = fingerprint[:4] childKey.Key = addPrivateKeys(intermediary[:32], key.Key) // Validate key err = validatePrivateKey(childKey.Key) if err != nil { return nil, err } // Bip32 CKDpub } else { keyBytes := publicKeyForPrivateKey(intermediary[:32]) // Validate key err := validateChildPublicKey(keyBytes) if err != nil { return nil, err } childKey.Version = PublicWalletVersion fingerprint, err := hash160(key.Key) if err != nil { return nil, err } childKey.FingerPrint = fingerprint[:4] childKey.Key = addPublicKeys(keyBytes, key.Key) } return childKey, nil }
go
func (key *Key) NewChildKey(childIdx uint32) (*Key, error) { // Fail early if trying to create hardned child from public key if !key.IsPrivate && childIdx >= FirstHardenedChild { return nil, ErrHardnedChildPublicKey } intermediary, err := key.getIntermediary(childIdx) if err != nil { return nil, err } // Create child Key with data common to all both scenarios childKey := &Key{ ChildNumber: uint32Bytes(childIdx), ChainCode: intermediary[32:], Depth: key.Depth + 1, IsPrivate: key.IsPrivate, } // Bip32 CKDpriv if key.IsPrivate { childKey.Version = PrivateWalletVersion fingerprint, err := hash160(publicKeyForPrivateKey(key.Key)) if err != nil { return nil, err } childKey.FingerPrint = fingerprint[:4] childKey.Key = addPrivateKeys(intermediary[:32], key.Key) // Validate key err = validatePrivateKey(childKey.Key) if err != nil { return nil, err } // Bip32 CKDpub } else { keyBytes := publicKeyForPrivateKey(intermediary[:32]) // Validate key err := validateChildPublicKey(keyBytes) if err != nil { return nil, err } childKey.Version = PublicWalletVersion fingerprint, err := hash160(key.Key) if err != nil { return nil, err } childKey.FingerPrint = fingerprint[:4] childKey.Key = addPublicKeys(keyBytes, key.Key) } return childKey, nil }
[ "func", "(", "key", "*", "Key", ")", "NewChildKey", "(", "childIdx", "uint32", ")", "(", "*", "Key", ",", "error", ")", "{", "// Fail early if trying to create hardned child from public key", "if", "!", "key", ".", "IsPrivate", "&&", "childIdx", ">=", "FirstHardenedChild", "{", "return", "nil", ",", "ErrHardnedChildPublicKey", "\n", "}", "\n\n", "intermediary", ",", "err", ":=", "key", ".", "getIntermediary", "(", "childIdx", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n\n", "// Create child Key with data common to all both scenarios", "childKey", ":=", "&", "Key", "{", "ChildNumber", ":", "uint32Bytes", "(", "childIdx", ")", ",", "ChainCode", ":", "intermediary", "[", "32", ":", "]", ",", "Depth", ":", "key", ".", "Depth", "+", "1", ",", "IsPrivate", ":", "key", ".", "IsPrivate", ",", "}", "\n\n", "// Bip32 CKDpriv", "if", "key", ".", "IsPrivate", "{", "childKey", ".", "Version", "=", "PrivateWalletVersion", "\n", "fingerprint", ",", "err", ":=", "hash160", "(", "publicKeyForPrivateKey", "(", "key", ".", "Key", ")", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "childKey", ".", "FingerPrint", "=", "fingerprint", "[", ":", "4", "]", "\n", "childKey", ".", "Key", "=", "addPrivateKeys", "(", "intermediary", "[", ":", "32", "]", ",", "key", ".", "Key", ")", "\n\n", "// Validate key", "err", "=", "validatePrivateKey", "(", "childKey", ".", "Key", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "// Bip32 CKDpub", "}", "else", "{", "keyBytes", ":=", "publicKeyForPrivateKey", "(", "intermediary", "[", ":", "32", "]", ")", "\n\n", "// Validate key", "err", ":=", "validateChildPublicKey", "(", "keyBytes", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n\n", "childKey", ".", "Version", "=", "PublicWalletVersion", "\n", "fingerprint", ",", "err", ":=", "hash160", "(", "key", ".", "Key", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "childKey", ".", "FingerPrint", "=", "fingerprint", "[", ":", "4", "]", "\n", "childKey", ".", "Key", "=", "addPublicKeys", "(", "keyBytes", ",", "key", ".", "Key", ")", "\n", "}", "\n\n", "return", "childKey", ",", "nil", "\n", "}" ]
// NewChildKey derives a child key from a given parent as outlined by bip32
[ "NewChildKey", "derives", "a", "child", "key", "from", "a", "given", "parent", "as", "outlined", "by", "bip32" ]
2c9cfd17756470a0b7c3e4b7954bae7d11035504
https://github.com/tyler-smith/go-bip32/blob/2c9cfd17756470a0b7c3e4b7954bae7d11035504/bip32.go#L93-L147
2,779
tyler-smith/go-bip32
bip32.go
PublicKey
func (key *Key) PublicKey() *Key { keyBytes := key.Key if key.IsPrivate { keyBytes = publicKeyForPrivateKey(keyBytes) } return &Key{ Version: PublicWalletVersion, Key: keyBytes, Depth: key.Depth, ChildNumber: key.ChildNumber, FingerPrint: key.FingerPrint, ChainCode: key.ChainCode, IsPrivate: false, } }
go
func (key *Key) PublicKey() *Key { keyBytes := key.Key if key.IsPrivate { keyBytes = publicKeyForPrivateKey(keyBytes) } return &Key{ Version: PublicWalletVersion, Key: keyBytes, Depth: key.Depth, ChildNumber: key.ChildNumber, FingerPrint: key.FingerPrint, ChainCode: key.ChainCode, IsPrivate: false, } }
[ "func", "(", "key", "*", "Key", ")", "PublicKey", "(", ")", "*", "Key", "{", "keyBytes", ":=", "key", ".", "Key", "\n\n", "if", "key", ".", "IsPrivate", "{", "keyBytes", "=", "publicKeyForPrivateKey", "(", "keyBytes", ")", "\n", "}", "\n\n", "return", "&", "Key", "{", "Version", ":", "PublicWalletVersion", ",", "Key", ":", "keyBytes", ",", "Depth", ":", "key", ".", "Depth", ",", "ChildNumber", ":", "key", ".", "ChildNumber", ",", "FingerPrint", ":", "key", ".", "FingerPrint", ",", "ChainCode", ":", "key", ".", "ChainCode", ",", "IsPrivate", ":", "false", ",", "}", "\n", "}" ]
// PublicKey returns the public version of key or return a copy // The 'Neuter' function from the bip32 spec
[ "PublicKey", "returns", "the", "public", "version", "of", "key", "or", "return", "a", "copy", "The", "Neuter", "function", "from", "the", "bip32", "spec" ]
2c9cfd17756470a0b7c3e4b7954bae7d11035504
https://github.com/tyler-smith/go-bip32/blob/2c9cfd17756470a0b7c3e4b7954bae7d11035504/bip32.go#L177-L193
2,780
tyler-smith/go-bip32
bip32.go
Serialize
func (key *Key) Serialize() ([]byte, error) { // Private keys should be prepended with a single null byte keyBytes := key.Key if key.IsPrivate { keyBytes = append([]byte{0x0}, keyBytes...) } // Write fields to buffer in order buffer := new(bytes.Buffer) buffer.Write(key.Version) buffer.WriteByte(key.Depth) buffer.Write(key.FingerPrint) buffer.Write(key.ChildNumber) buffer.Write(key.ChainCode) buffer.Write(keyBytes) // Append the standard doublesha256 checksum serializedKey, err := addChecksumToBytes(buffer.Bytes()) if err != nil { return nil, err } return serializedKey, nil }
go
func (key *Key) Serialize() ([]byte, error) { // Private keys should be prepended with a single null byte keyBytes := key.Key if key.IsPrivate { keyBytes = append([]byte{0x0}, keyBytes...) } // Write fields to buffer in order buffer := new(bytes.Buffer) buffer.Write(key.Version) buffer.WriteByte(key.Depth) buffer.Write(key.FingerPrint) buffer.Write(key.ChildNumber) buffer.Write(key.ChainCode) buffer.Write(keyBytes) // Append the standard doublesha256 checksum serializedKey, err := addChecksumToBytes(buffer.Bytes()) if err != nil { return nil, err } return serializedKey, nil }
[ "func", "(", "key", "*", "Key", ")", "Serialize", "(", ")", "(", "[", "]", "byte", ",", "error", ")", "{", "// Private keys should be prepended with a single null byte", "keyBytes", ":=", "key", ".", "Key", "\n", "if", "key", ".", "IsPrivate", "{", "keyBytes", "=", "append", "(", "[", "]", "byte", "{", "0x0", "}", ",", "keyBytes", "...", ")", "\n", "}", "\n\n", "// Write fields to buffer in order", "buffer", ":=", "new", "(", "bytes", ".", "Buffer", ")", "\n", "buffer", ".", "Write", "(", "key", ".", "Version", ")", "\n", "buffer", ".", "WriteByte", "(", "key", ".", "Depth", ")", "\n", "buffer", ".", "Write", "(", "key", ".", "FingerPrint", ")", "\n", "buffer", ".", "Write", "(", "key", ".", "ChildNumber", ")", "\n", "buffer", ".", "Write", "(", "key", ".", "ChainCode", ")", "\n", "buffer", ".", "Write", "(", "keyBytes", ")", "\n\n", "// Append the standard doublesha256 checksum", "serializedKey", ",", "err", ":=", "addChecksumToBytes", "(", "buffer", ".", "Bytes", "(", ")", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n\n", "return", "serializedKey", ",", "nil", "\n", "}" ]
// Serialize a Key to a 78 byte byte slice
[ "Serialize", "a", "Key", "to", "a", "78", "byte", "byte", "slice" ]
2c9cfd17756470a0b7c3e4b7954bae7d11035504
https://github.com/tyler-smith/go-bip32/blob/2c9cfd17756470a0b7c3e4b7954bae7d11035504/bip32.go#L196-L219
2,781
tyler-smith/go-bip32
bip32.go
B58Serialize
func (key *Key) B58Serialize() string { serializedKey, err := key.Serialize() if err != nil { return "" } return base58Encode(serializedKey) }
go
func (key *Key) B58Serialize() string { serializedKey, err := key.Serialize() if err != nil { return "" } return base58Encode(serializedKey) }
[ "func", "(", "key", "*", "Key", ")", "B58Serialize", "(", ")", "string", "{", "serializedKey", ",", "err", ":=", "key", ".", "Serialize", "(", ")", "\n", "if", "err", "!=", "nil", "{", "return", "\"", "\"", "\n", "}", "\n\n", "return", "base58Encode", "(", "serializedKey", ")", "\n", "}" ]
// B58Serialize encodes the Key in the standard Bitcoin base58 encoding
[ "B58Serialize", "encodes", "the", "Key", "in", "the", "standard", "Bitcoin", "base58", "encoding" ]
2c9cfd17756470a0b7c3e4b7954bae7d11035504
https://github.com/tyler-smith/go-bip32/blob/2c9cfd17756470a0b7c3e4b7954bae7d11035504/bip32.go#L222-L229
2,782
tyler-smith/go-bip32
bip32.go
Deserialize
func Deserialize(data []byte) (*Key, error) { if len(data) != 82 { return nil, ErrSerializedKeyWrongSize } var key = &Key{} key.Version = data[0:4] key.Depth = data[4] key.FingerPrint = data[5:9] key.ChildNumber = data[9:13] key.ChainCode = data[13:45] if data[45] == byte(0) { key.IsPrivate = true key.Key = data[46:78] } else { key.IsPrivate = false key.Key = data[45:78] } // validate checksum cs1, err := checksum(data[0 : len(data)-4]) if err != nil { return nil, err } cs2 := data[len(data)-4:] for i := range cs1 { if cs1[i] != cs2[i] { return nil, ErrInvalidChecksum } } return key, nil }
go
func Deserialize(data []byte) (*Key, error) { if len(data) != 82 { return nil, ErrSerializedKeyWrongSize } var key = &Key{} key.Version = data[0:4] key.Depth = data[4] key.FingerPrint = data[5:9] key.ChildNumber = data[9:13] key.ChainCode = data[13:45] if data[45] == byte(0) { key.IsPrivate = true key.Key = data[46:78] } else { key.IsPrivate = false key.Key = data[45:78] } // validate checksum cs1, err := checksum(data[0 : len(data)-4]) if err != nil { return nil, err } cs2 := data[len(data)-4:] for i := range cs1 { if cs1[i] != cs2[i] { return nil, ErrInvalidChecksum } } return key, nil }
[ "func", "Deserialize", "(", "data", "[", "]", "byte", ")", "(", "*", "Key", ",", "error", ")", "{", "if", "len", "(", "data", ")", "!=", "82", "{", "return", "nil", ",", "ErrSerializedKeyWrongSize", "\n", "}", "\n", "var", "key", "=", "&", "Key", "{", "}", "\n", "key", ".", "Version", "=", "data", "[", "0", ":", "4", "]", "\n", "key", ".", "Depth", "=", "data", "[", "4", "]", "\n", "key", ".", "FingerPrint", "=", "data", "[", "5", ":", "9", "]", "\n", "key", ".", "ChildNumber", "=", "data", "[", "9", ":", "13", "]", "\n", "key", ".", "ChainCode", "=", "data", "[", "13", ":", "45", "]", "\n\n", "if", "data", "[", "45", "]", "==", "byte", "(", "0", ")", "{", "key", ".", "IsPrivate", "=", "true", "\n", "key", ".", "Key", "=", "data", "[", "46", ":", "78", "]", "\n", "}", "else", "{", "key", ".", "IsPrivate", "=", "false", "\n", "key", ".", "Key", "=", "data", "[", "45", ":", "78", "]", "\n", "}", "\n\n", "// validate checksum", "cs1", ",", "err", ":=", "checksum", "(", "data", "[", "0", ":", "len", "(", "data", ")", "-", "4", "]", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n\n", "cs2", ":=", "data", "[", "len", "(", "data", ")", "-", "4", ":", "]", "\n", "for", "i", ":=", "range", "cs1", "{", "if", "cs1", "[", "i", "]", "!=", "cs2", "[", "i", "]", "{", "return", "nil", ",", "ErrInvalidChecksum", "\n", "}", "\n", "}", "\n", "return", "key", ",", "nil", "\n", "}" ]
// Deserialize a byte slice into a Key
[ "Deserialize", "a", "byte", "slice", "into", "a", "Key" ]
2c9cfd17756470a0b7c3e4b7954bae7d11035504
https://github.com/tyler-smith/go-bip32/blob/2c9cfd17756470a0b7c3e4b7954bae7d11035504/bip32.go#L237-L269
2,783
tyler-smith/go-bip32
bip32.go
B58Deserialize
func B58Deserialize(data string) (*Key, error) { b, err := base58Decode(data) if err != nil { return nil, err } return Deserialize(b) }
go
func B58Deserialize(data string) (*Key, error) { b, err := base58Decode(data) if err != nil { return nil, err } return Deserialize(b) }
[ "func", "B58Deserialize", "(", "data", "string", ")", "(", "*", "Key", ",", "error", ")", "{", "b", ",", "err", ":=", "base58Decode", "(", "data", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "return", "Deserialize", "(", "b", ")", "\n", "}" ]
// B58Deserialize deserializes a Key encoded in base58 encoding
[ "B58Deserialize", "deserializes", "a", "Key", "encoded", "in", "base58", "encoding" ]
2c9cfd17756470a0b7c3e4b7954bae7d11035504
https://github.com/tyler-smith/go-bip32/blob/2c9cfd17756470a0b7c3e4b7954bae7d11035504/bip32.go#L272-L278
2,784
tyler-smith/go-bip32
bip32.go
NewSeed
func NewSeed() ([]byte, error) { // Well that easy, just make go read 256 random bytes into a slice s := make([]byte, 256) _, err := rand.Read(s) return s, err }
go
func NewSeed() ([]byte, error) { // Well that easy, just make go read 256 random bytes into a slice s := make([]byte, 256) _, err := rand.Read(s) return s, err }
[ "func", "NewSeed", "(", ")", "(", "[", "]", "byte", ",", "error", ")", "{", "// Well that easy, just make go read 256 random bytes into a slice", "s", ":=", "make", "(", "[", "]", "byte", ",", "256", ")", "\n", "_", ",", "err", ":=", "rand", ".", "Read", "(", "s", ")", "\n", "return", "s", ",", "err", "\n", "}" ]
// NewSeed returns a cryptographically secure seed
[ "NewSeed", "returns", "a", "cryptographically", "secure", "seed" ]
2c9cfd17756470a0b7c3e4b7954bae7d11035504
https://github.com/tyler-smith/go-bip32/blob/2c9cfd17756470a0b7c3e4b7954bae7d11035504/bip32.go#L281-L286
2,785
terraform-providers/terraform-provider-tls
tls/resource_certificate.go
generateSubjectKeyID
func generateSubjectKeyID(pub crypto.PublicKey) ([]byte, error) { var publicKeyBytes []byte var err error switch pub := pub.(type) { case *rsa.PublicKey: publicKeyBytes, err = asn1.Marshal(rsaPublicKey{N: pub.N, E: pub.E}) if err != nil { return nil, err } case *ecdsa.PublicKey: publicKeyBytes = elliptic.Marshal(pub.Curve, pub.X, pub.Y) default: return nil, errors.New("only RSA and ECDSA public keys supported") } hash := sha1.Sum(publicKeyBytes) return hash[:], nil }
go
func generateSubjectKeyID(pub crypto.PublicKey) ([]byte, error) { var publicKeyBytes []byte var err error switch pub := pub.(type) { case *rsa.PublicKey: publicKeyBytes, err = asn1.Marshal(rsaPublicKey{N: pub.N, E: pub.E}) if err != nil { return nil, err } case *ecdsa.PublicKey: publicKeyBytes = elliptic.Marshal(pub.Curve, pub.X, pub.Y) default: return nil, errors.New("only RSA and ECDSA public keys supported") } hash := sha1.Sum(publicKeyBytes) return hash[:], nil }
[ "func", "generateSubjectKeyID", "(", "pub", "crypto", ".", "PublicKey", ")", "(", "[", "]", "byte", ",", "error", ")", "{", "var", "publicKeyBytes", "[", "]", "byte", "\n", "var", "err", "error", "\n\n", "switch", "pub", ":=", "pub", ".", "(", "type", ")", "{", "case", "*", "rsa", ".", "PublicKey", ":", "publicKeyBytes", ",", "err", "=", "asn1", ".", "Marshal", "(", "rsaPublicKey", "{", "N", ":", "pub", ".", "N", ",", "E", ":", "pub", ".", "E", "}", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "case", "*", "ecdsa", ".", "PublicKey", ":", "publicKeyBytes", "=", "elliptic", ".", "Marshal", "(", "pub", ".", "Curve", ",", "pub", ".", "X", ",", "pub", ".", "Y", ")", "\n", "default", ":", "return", "nil", ",", "errors", ".", "New", "(", "\"", "\"", ")", "\n", "}", "\n\n", "hash", ":=", "sha1", ".", "Sum", "(", "publicKeyBytes", ")", "\n", "return", "hash", "[", ":", "]", ",", "nil", "\n", "}" ]
// generateSubjectKeyID generates a SHA-1 hash of the subject public key.
[ "generateSubjectKeyID", "generates", "a", "SHA", "-", "1", "hash", "of", "the", "subject", "public", "key", "." ]
0e19d1fe527ded944a5296f4568e1757ca259d60
https://github.com/terraform-providers/terraform-provider-tls/blob/0e19d1fe527ded944a5296f4568e1757ca259d60/tls/resource_certificate.go#L57-L75
2,786
templexxx/reedsolomon
mathtool/gentbls.go
genPrimitivePolynomial
func genPrimitivePolynomial() []polynomial { // drop Polynomial x,so the constant term must be 1 // so there are 2^(deg-1) Polynomials cnt := 1 << (deg - 1) var polynomials []polynomial var p polynomial p[0] = 1 p[deg] = 1 // gen all Polynomials for i := 0; i < cnt; i++ { p = genPolynomial(p, 1) polynomials = append(polynomials, p) } // drop Polynomial x+1, so the cnt of Polynomials is odd var psRaw []polynomial for _, p := range polynomials { var n int for _, v := range p { if v == 1 { n++ } } if n&1 != 0 { psRaw = append(psRaw, p) } } // order of primitive element == 2^deg -1 ? var ps []polynomial for _, p := range psRaw { lenTable := (1 << deg) - 1 table := genExpTable(p, lenTable) var numOf1 int for _, v := range table { // cnt 1 in ExpTable if int(v) == 1 { numOf1++ } } if numOf1 == 1 { ps = append(ps, p) } } return ps }
go
func genPrimitivePolynomial() []polynomial { // drop Polynomial x,so the constant term must be 1 // so there are 2^(deg-1) Polynomials cnt := 1 << (deg - 1) var polynomials []polynomial var p polynomial p[0] = 1 p[deg] = 1 // gen all Polynomials for i := 0; i < cnt; i++ { p = genPolynomial(p, 1) polynomials = append(polynomials, p) } // drop Polynomial x+1, so the cnt of Polynomials is odd var psRaw []polynomial for _, p := range polynomials { var n int for _, v := range p { if v == 1 { n++ } } if n&1 != 0 { psRaw = append(psRaw, p) } } // order of primitive element == 2^deg -1 ? var ps []polynomial for _, p := range psRaw { lenTable := (1 << deg) - 1 table := genExpTable(p, lenTable) var numOf1 int for _, v := range table { // cnt 1 in ExpTable if int(v) == 1 { numOf1++ } } if numOf1 == 1 { ps = append(ps, p) } } return ps }
[ "func", "genPrimitivePolynomial", "(", ")", "[", "]", "polynomial", "{", "// drop Polynomial x,so the constant term must be 1", "// so there are 2^(deg-1) Polynomials", "cnt", ":=", "1", "<<", "(", "deg", "-", "1", ")", "\n", "var", "polynomials", "[", "]", "polynomial", "\n", "var", "p", "polynomial", "\n", "p", "[", "0", "]", "=", "1", "\n", "p", "[", "deg", "]", "=", "1", "\n", "// gen all Polynomials", "for", "i", ":=", "0", ";", "i", "<", "cnt", ";", "i", "++", "{", "p", "=", "genPolynomial", "(", "p", ",", "1", ")", "\n", "polynomials", "=", "append", "(", "polynomials", ",", "p", ")", "\n", "}", "\n", "// drop Polynomial x+1, so the cnt of Polynomials is odd", "var", "psRaw", "[", "]", "polynomial", "\n", "for", "_", ",", "p", ":=", "range", "polynomials", "{", "var", "n", "int", "\n", "for", "_", ",", "v", ":=", "range", "p", "{", "if", "v", "==", "1", "{", "n", "++", "\n", "}", "\n", "}", "\n", "if", "n", "&", "1", "!=", "0", "{", "psRaw", "=", "append", "(", "psRaw", ",", "p", ")", "\n", "}", "\n", "}", "\n", "// order of primitive element == 2^deg -1 ?", "var", "ps", "[", "]", "polynomial", "\n", "for", "_", ",", "p", ":=", "range", "psRaw", "{", "lenTable", ":=", "(", "1", "<<", "deg", ")", "-", "1", "\n", "table", ":=", "genExpTable", "(", "p", ",", "lenTable", ")", "\n", "var", "numOf1", "int", "\n", "for", "_", ",", "v", ":=", "range", "table", "{", "// cnt 1 in ExpTable", "if", "int", "(", "v", ")", "==", "1", "{", "numOf1", "++", "\n", "}", "\n", "}", "\n", "if", "numOf1", "==", "1", "{", "ps", "=", "append", "(", "ps", ",", "p", ")", "\n", "}", "\n", "}", "\n", "return", "ps", "\n", "}" ]
// generate primitive Polynomial
[ "generate", "primitive", "Polynomial" ]
957cb02db396e7e9810e7a6e0177a6e195f72fd4
https://github.com/templexxx/reedsolomon/blob/957cb02db396e7e9810e7a6e0177a6e195f72fd4/mathtool/gentbls.go#L84-L127
2,787
templexxx/reedsolomon
rs.go
New
func New(dataCnt, parityCnt int) (r *RS, err error) { err = checkCfg(dataCnt, parityCnt) if err != nil { return } e := genEncMatrix(dataCnt, parityCnt) g := e[dataCnt*dataCnt:] r = &RS{DataCnt: dataCnt, ParityCnt: parityCnt, encodeMatrix: e, genMatrix: g, inverseMatrix: new(sync.Map)} r.enableCache() r.cpu = getCPUFeature() return }
go
func New(dataCnt, parityCnt int) (r *RS, err error) { err = checkCfg(dataCnt, parityCnt) if err != nil { return } e := genEncMatrix(dataCnt, parityCnt) g := e[dataCnt*dataCnt:] r = &RS{DataCnt: dataCnt, ParityCnt: parityCnt, encodeMatrix: e, genMatrix: g, inverseMatrix: new(sync.Map)} r.enableCache() r.cpu = getCPUFeature() return }
[ "func", "New", "(", "dataCnt", ",", "parityCnt", "int", ")", "(", "r", "*", "RS", ",", "err", "error", ")", "{", "err", "=", "checkCfg", "(", "dataCnt", ",", "parityCnt", ")", "\n", "if", "err", "!=", "nil", "{", "return", "\n", "}", "\n\n", "e", ":=", "genEncMatrix", "(", "dataCnt", ",", "parityCnt", ")", "\n", "g", ":=", "e", "[", "dataCnt", "*", "dataCnt", ":", "]", "\n", "r", "=", "&", "RS", "{", "DataCnt", ":", "dataCnt", ",", "ParityCnt", ":", "parityCnt", ",", "encodeMatrix", ":", "e", ",", "genMatrix", ":", "g", ",", "inverseMatrix", ":", "new", "(", "sync", ".", "Map", ")", "}", "\n", "r", ".", "enableCache", "(", ")", "\n\n", "r", ".", "cpu", "=", "getCPUFeature", "(", ")", "\n\n", "return", "\n", "}" ]
// New create an RS
[ "New", "create", "an", "RS" ]
957cb02db396e7e9810e7a6e0177a6e195f72fd4
https://github.com/templexxx/reedsolomon/blob/957cb02db396e7e9810e7a6e0177a6e195f72fd4/rs.go#L40-L56
2,788
templexxx/reedsolomon
rs.go
Encode
func (r *RS) Encode(vects [][]byte) (err error) { err = r.checkEncode(vects) if err != nil { return } r.encode(vects, false) return }
go
func (r *RS) Encode(vects [][]byte) (err error) { err = r.checkEncode(vects) if err != nil { return } r.encode(vects, false) return }
[ "func", "(", "r", "*", "RS", ")", "Encode", "(", "vects", "[", "]", "[", "]", "byte", ")", "(", "err", "error", ")", "{", "err", "=", "r", ".", "checkEncode", "(", "vects", ")", "\n", "if", "err", "!=", "nil", "{", "return", "\n", "}", "\n", "r", ".", "encode", "(", "vects", ",", "false", ")", "\n", "return", "\n", "}" ]
// Encode outputs parity into vects
[ "Encode", "outputs", "parity", "into", "vects" ]
957cb02db396e7e9810e7a6e0177a6e195f72fd4
https://github.com/templexxx/reedsolomon/blob/957cb02db396e7e9810e7a6e0177a6e195f72fd4/rs.go#L117-L124
2,789
templexxx/reedsolomon
rs.go
Update
func (r *RS) Update(oldData []byte, newData []byte, updateRow int, parity [][]byte) (err error) { // check args if len(parity) != r.ParityCnt { err = ErrMismatchParityCnt return } size := len(newData) if size <= 0 { err = ErrIllegalUpdateSize return } if size != len(oldData) { err = ErrIllegalUpdateSize return } for i := range parity { if len(parity[i]) != size { err = ErrIllegalUpdateSize return } } if updateRow >= r.DataCnt { err = ErrIllegalUpdateRow return } // step1: buf (old_data xor new_data) buf := make([]byte, size) xor.Encode(buf, [][]byte{oldData, newData}) // step2: reEnc parity updateVects := make([][]byte, 1+r.ParityCnt) updateVects[0] = buf updateGenMatrix := make([]byte, r.ParityCnt) // make update_generator_matrix & update_vects for i := 0; i < r.ParityCnt; i++ { col := updateRow off := i*r.DataCnt + col c := r.genMatrix[off] updateGenMatrix[i] = c updateVects[i+1] = parity[i] } updateRS := &RS{DataCnt: 1, ParityCnt: r.ParityCnt, genMatrix: updateGenMatrix, cpu: r.cpu} updateRS.encode(updateVects, true) return nil }
go
func (r *RS) Update(oldData []byte, newData []byte, updateRow int, parity [][]byte) (err error) { // check args if len(parity) != r.ParityCnt { err = ErrMismatchParityCnt return } size := len(newData) if size <= 0 { err = ErrIllegalUpdateSize return } if size != len(oldData) { err = ErrIllegalUpdateSize return } for i := range parity { if len(parity[i]) != size { err = ErrIllegalUpdateSize return } } if updateRow >= r.DataCnt { err = ErrIllegalUpdateRow return } // step1: buf (old_data xor new_data) buf := make([]byte, size) xor.Encode(buf, [][]byte{oldData, newData}) // step2: reEnc parity updateVects := make([][]byte, 1+r.ParityCnt) updateVects[0] = buf updateGenMatrix := make([]byte, r.ParityCnt) // make update_generator_matrix & update_vects for i := 0; i < r.ParityCnt; i++ { col := updateRow off := i*r.DataCnt + col c := r.genMatrix[off] updateGenMatrix[i] = c updateVects[i+1] = parity[i] } updateRS := &RS{DataCnt: 1, ParityCnt: r.ParityCnt, genMatrix: updateGenMatrix, cpu: r.cpu} updateRS.encode(updateVects, true) return nil }
[ "func", "(", "r", "*", "RS", ")", "Update", "(", "oldData", "[", "]", "byte", ",", "newData", "[", "]", "byte", ",", "updateRow", "int", ",", "parity", "[", "]", "[", "]", "byte", ")", "(", "err", "error", ")", "{", "// check args", "if", "len", "(", "parity", ")", "!=", "r", ".", "ParityCnt", "{", "err", "=", "ErrMismatchParityCnt", "\n", "return", "\n", "}", "\n", "size", ":=", "len", "(", "newData", ")", "\n", "if", "size", "<=", "0", "{", "err", "=", "ErrIllegalUpdateSize", "\n", "return", "\n", "}", "\n", "if", "size", "!=", "len", "(", "oldData", ")", "{", "err", "=", "ErrIllegalUpdateSize", "\n", "return", "\n", "}", "\n", "for", "i", ":=", "range", "parity", "{", "if", "len", "(", "parity", "[", "i", "]", ")", "!=", "size", "{", "err", "=", "ErrIllegalUpdateSize", "\n", "return", "\n", "}", "\n", "}", "\n", "if", "updateRow", ">=", "r", ".", "DataCnt", "{", "err", "=", "ErrIllegalUpdateRow", "\n", "return", "\n", "}", "\n\n", "// step1: buf (old_data xor new_data)", "buf", ":=", "make", "(", "[", "]", "byte", ",", "size", ")", "\n", "xor", ".", "Encode", "(", "buf", ",", "[", "]", "[", "]", "byte", "{", "oldData", ",", "newData", "}", ")", "\n", "// step2: reEnc parity", "updateVects", ":=", "make", "(", "[", "]", "[", "]", "byte", ",", "1", "+", "r", ".", "ParityCnt", ")", "\n", "updateVects", "[", "0", "]", "=", "buf", "\n", "updateGenMatrix", ":=", "make", "(", "[", "]", "byte", ",", "r", ".", "ParityCnt", ")", "\n", "// make update_generator_matrix & update_vects", "for", "i", ":=", "0", ";", "i", "<", "r", ".", "ParityCnt", ";", "i", "++", "{", "col", ":=", "updateRow", "\n", "off", ":=", "i", "*", "r", ".", "DataCnt", "+", "col", "\n", "c", ":=", "r", ".", "genMatrix", "[", "off", "]", "\n", "updateGenMatrix", "[", "i", "]", "=", "c", "\n", "updateVects", "[", "i", "+", "1", "]", "=", "parity", "[", "i", "]", "\n", "}", "\n", "updateRS", ":=", "&", "RS", "{", "DataCnt", ":", "1", ",", "ParityCnt", ":", "r", ".", "ParityCnt", ",", "genMatrix", ":", "updateGenMatrix", ",", "cpu", ":", "r", ".", "cpu", "}", "\n", "updateRS", ".", "encode", "(", "updateVects", ",", "true", ")", "\n", "return", "nil", "\n", "}" ]
// UpdateParity update parity_data when one data_vect changes
[ "UpdateParity", "update", "parity_data", "when", "one", "data_vect", "changes" ]
957cb02db396e7e9810e7a6e0177a6e195f72fd4
https://github.com/templexxx/reedsolomon/blob/957cb02db396e7e9810e7a6e0177a6e195f72fd4/rs.go#L229-L273
2,790
templexxx/reedsolomon
rs.go
SplitNeedReconst
func SplitNeedReconst(dataCnt int, needReconst []int) (dNeedReconst, pNeedReconst []int) { sort.Ints(needReconst) for i, l := range needReconst { if l >= dataCnt { return needReconst[:i], needReconst[i:] } } return needReconst, nil }
go
func SplitNeedReconst(dataCnt int, needReconst []int) (dNeedReconst, pNeedReconst []int) { sort.Ints(needReconst) for i, l := range needReconst { if l >= dataCnt { return needReconst[:i], needReconst[i:] } } return needReconst, nil }
[ "func", "SplitNeedReconst", "(", "dataCnt", "int", ",", "needReconst", "[", "]", "int", ")", "(", "dNeedReconst", ",", "pNeedReconst", "[", "]", "int", ")", "{", "sort", ".", "Ints", "(", "needReconst", ")", "\n", "for", "i", ",", "l", ":=", "range", "needReconst", "{", "if", "l", ">=", "dataCnt", "{", "return", "needReconst", "[", ":", "i", "]", ",", "needReconst", "[", "i", ":", "]", "\n", "}", "\n", "}", "\n", "return", "needReconst", ",", "nil", "\n", "}" ]
// SplitNeedReconst split data_lost & parity_lost
[ "SplitNeedReconst", "split", "data_lost", "&", "parity_lost" ]
957cb02db396e7e9810e7a6e0177a6e195f72fd4
https://github.com/templexxx/reedsolomon/blob/957cb02db396e7e9810e7a6e0177a6e195f72fd4/rs.go#L397-L405
2,791
templexxx/reedsolomon
rs.go
makeEncodeMatrix
func (r *RS) makeEncodeMatrix(dpHas []int) (em []byte, err error) { d := r.DataCnt m := make([]byte, d*d) for i, l := range dpHas { copy(m[i*d:i*d+d], r.encodeMatrix[l*d:l*d+d]) } em, err = matrix(m).invert(d) if err != nil { return } return }
go
func (r *RS) makeEncodeMatrix(dpHas []int) (em []byte, err error) { d := r.DataCnt m := make([]byte, d*d) for i, l := range dpHas { copy(m[i*d:i*d+d], r.encodeMatrix[l*d:l*d+d]) } em, err = matrix(m).invert(d) if err != nil { return } return }
[ "func", "(", "r", "*", "RS", ")", "makeEncodeMatrix", "(", "dpHas", "[", "]", "int", ")", "(", "em", "[", "]", "byte", ",", "err", "error", ")", "{", "d", ":=", "r", ".", "DataCnt", "\n", "m", ":=", "make", "(", "[", "]", "byte", ",", "d", "*", "d", ")", "\n", "for", "i", ",", "l", ":=", "range", "dpHas", "{", "copy", "(", "m", "[", "i", "*", "d", ":", "i", "*", "d", "+", "d", "]", ",", "r", ".", "encodeMatrix", "[", "l", "*", "d", ":", "l", "*", "d", "+", "d", "]", ")", "\n", "}", "\n", "em", ",", "err", "=", "matrix", "(", "m", ")", ".", "invert", "(", "d", ")", "\n", "if", "err", "!=", "nil", "{", "return", "\n", "}", "\n", "return", "\n", "}" ]
// according to encoding_matrix & dpHas make a new encoding_matrix
[ "according", "to", "encoding_matrix", "&", "dpHas", "make", "a", "new", "encoding_matrix" ]
957cb02db396e7e9810e7a6e0177a6e195f72fd4
https://github.com/templexxx/reedsolomon/blob/957cb02db396e7e9810e7a6e0177a6e195f72fd4/rs.go#L438-L449
2,792
ipfs/go-ds-leveldb
datastore.go
NewDatastore
func NewDatastore(path string, opts *Options) (*Datastore, error) { var nopts opt.Options if opts != nil { nopts = opt.Options(*opts) } var err error var db *leveldb.DB if path == "" { db, err = leveldb.Open(storage.NewMemStorage(), &nopts) } else { db, err = leveldb.OpenFile(path, &nopts) if errors.IsCorrupted(err) && !nopts.GetReadOnly() { db, err = leveldb.RecoverFile(path, &nopts) } } if err != nil { return nil, err } return &Datastore{ accessor: &accessor{ldb: db}, DB: db, path: path, }, nil }
go
func NewDatastore(path string, opts *Options) (*Datastore, error) { var nopts opt.Options if opts != nil { nopts = opt.Options(*opts) } var err error var db *leveldb.DB if path == "" { db, err = leveldb.Open(storage.NewMemStorage(), &nopts) } else { db, err = leveldb.OpenFile(path, &nopts) if errors.IsCorrupted(err) && !nopts.GetReadOnly() { db, err = leveldb.RecoverFile(path, &nopts) } } if err != nil { return nil, err } return &Datastore{ accessor: &accessor{ldb: db}, DB: db, path: path, }, nil }
[ "func", "NewDatastore", "(", "path", "string", ",", "opts", "*", "Options", ")", "(", "*", "Datastore", ",", "error", ")", "{", "var", "nopts", "opt", ".", "Options", "\n", "if", "opts", "!=", "nil", "{", "nopts", "=", "opt", ".", "Options", "(", "*", "opts", ")", "\n", "}", "\n\n", "var", "err", "error", "\n", "var", "db", "*", "leveldb", ".", "DB", "\n\n", "if", "path", "==", "\"", "\"", "{", "db", ",", "err", "=", "leveldb", ".", "Open", "(", "storage", ".", "NewMemStorage", "(", ")", ",", "&", "nopts", ")", "\n", "}", "else", "{", "db", ",", "err", "=", "leveldb", ".", "OpenFile", "(", "path", ",", "&", "nopts", ")", "\n", "if", "errors", ".", "IsCorrupted", "(", "err", ")", "&&", "!", "nopts", ".", "GetReadOnly", "(", ")", "{", "db", ",", "err", "=", "leveldb", ".", "RecoverFile", "(", "path", ",", "&", "nopts", ")", "\n", "}", "\n", "}", "\n\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n\n", "return", "&", "Datastore", "{", "accessor", ":", "&", "accessor", "{", "ldb", ":", "db", "}", ",", "DB", ":", "db", ",", "path", ":", "path", ",", "}", ",", "nil", "\n", "}" ]
// NewDatastore returns a new datastore backed by leveldb // // for path == "", an in memory bachend will be chosen
[ "NewDatastore", "returns", "a", "new", "datastore", "backed", "by", "leveldb", "for", "path", "==", "an", "in", "memory", "bachend", "will", "be", "chosen" ]
47a9627082eeb3e52570a75eb4fdfaff8b2f19a9
https://github.com/ipfs/go-ds-leveldb/blob/47a9627082eeb3e52570a75eb4fdfaff8b2f19a9/datastore.go#L33-L60
2,793
ipfs/go-ds-leveldb
datastore.go
DiskUsage
func (d *Datastore) DiskUsage() (uint64, error) { if d.path == "" { // in-mem return 0, nil } var du uint64 err := filepath.Walk(d.path, func(path string, info os.FileInfo, err error) error { if err != nil { return err } du += uint64(info.Size()) return nil }) if err != nil { return 0, err } return du, nil }
go
func (d *Datastore) DiskUsage() (uint64, error) { if d.path == "" { // in-mem return 0, nil } var du uint64 err := filepath.Walk(d.path, func(path string, info os.FileInfo, err error) error { if err != nil { return err } du += uint64(info.Size()) return nil }) if err != nil { return 0, err } return du, nil }
[ "func", "(", "d", "*", "Datastore", ")", "DiskUsage", "(", ")", "(", "uint64", ",", "error", ")", "{", "if", "d", ".", "path", "==", "\"", "\"", "{", "// in-mem", "return", "0", ",", "nil", "\n", "}", "\n\n", "var", "du", "uint64", "\n\n", "err", ":=", "filepath", ".", "Walk", "(", "d", ".", "path", ",", "func", "(", "path", "string", ",", "info", "os", ".", "FileInfo", ",", "err", "error", ")", "error", "{", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "du", "+=", "uint64", "(", "info", ".", "Size", "(", ")", ")", "\n", "return", "nil", "\n", "}", ")", "\n\n", "if", "err", "!=", "nil", "{", "return", "0", ",", "err", "\n", "}", "\n\n", "return", "du", ",", "nil", "\n", "}" ]
// DiskUsage returns the current disk size used by this levelDB. // For in-mem datastores, it will return 0.
[ "DiskUsage", "returns", "the", "current", "disk", "size", "used", "by", "this", "levelDB", ".", "For", "in", "-", "mem", "datastores", "it", "will", "return", "0", "." ]
47a9627082eeb3e52570a75eb4fdfaff8b2f19a9
https://github.com/ipfs/go-ds-leveldb/blob/47a9627082eeb3e52570a75eb4fdfaff8b2f19a9/datastore.go#L165-L185
2,794
m3db/m3x
ident/types.go
Finalize
func (t *Tag) Finalize() { if t.noFinalize { return } if t.Name != nil { t.Name.Finalize() t.Name = nil } if t.Value != nil { t.Value.Finalize() t.Value = nil } }
go
func (t *Tag) Finalize() { if t.noFinalize { return } if t.Name != nil { t.Name.Finalize() t.Name = nil } if t.Value != nil { t.Value.Finalize() t.Value = nil } }
[ "func", "(", "t", "*", "Tag", ")", "Finalize", "(", ")", "{", "if", "t", ".", "noFinalize", "{", "return", "\n", "}", "\n", "if", "t", ".", "Name", "!=", "nil", "{", "t", ".", "Name", ".", "Finalize", "(", ")", "\n", "t", ".", "Name", "=", "nil", "\n", "}", "\n", "if", "t", ".", "Value", "!=", "nil", "{", "t", ".", "Value", ".", "Finalize", "(", ")", "\n", "t", ".", "Value", "=", "nil", "\n", "}", "\n", "}" ]
// Finalize releases all resources held by the Tag, unless NoFinalize has // been called previously in which case this is a no-op.
[ "Finalize", "releases", "all", "resources", "held", "by", "the", "Tag", "unless", "NoFinalize", "has", "been", "called", "previously", "in", "which", "case", "this", "is", "a", "no", "-", "op", "." ]
ebf3c7b94afd62bad2aaa3ad20bb2d4142aa342e
https://github.com/m3db/m3x/blob/ebf3c7b94afd62bad2aaa3ad20bb2d4142aa342e/ident/types.go#L84-L96
2,795
m3db/m3x
ident/types.go
Equal
func (t Tag) Equal(value Tag) bool { return t.Name.Equal(value.Name) && t.Value.Equal(value.Value) }
go
func (t Tag) Equal(value Tag) bool { return t.Name.Equal(value.Name) && t.Value.Equal(value.Value) }
[ "func", "(", "t", "Tag", ")", "Equal", "(", "value", "Tag", ")", "bool", "{", "return", "t", ".", "Name", ".", "Equal", "(", "value", ".", "Name", ")", "&&", "t", ".", "Value", ".", "Equal", "(", "value", ".", "Value", ")", "\n", "}" ]
// Equal returns whether the two tags are equal.
[ "Equal", "returns", "whether", "the", "two", "tags", "are", "equal", "." ]
ebf3c7b94afd62bad2aaa3ad20bb2d4142aa342e
https://github.com/m3db/m3x/blob/ebf3c7b94afd62bad2aaa3ad20bb2d4142aa342e/ident/types.go#L99-L101
2,796
m3db/m3x
ident/types.go
Append
func (t *Tags) Append(tag Tag) { t.values = append(t.values, tag) }
go
func (t *Tags) Append(tag Tag) { t.values = append(t.values, tag) }
[ "func", "(", "t", "*", "Tags", ")", "Append", "(", "tag", "Tag", ")", "{", "t", ".", "values", "=", "append", "(", "t", ".", "values", ",", "tag", ")", "\n", "}" ]
// Append will append a tag.
[ "Append", "will", "append", "a", "tag", "." ]
ebf3c7b94afd62bad2aaa3ad20bb2d4142aa342e
https://github.com/m3db/m3x/blob/ebf3c7b94afd62bad2aaa3ad20bb2d4142aa342e/ident/types.go#L250-L252
2,797
m3db/m3x
ident/types.go
Finalize
func (t *Tags) Finalize() { if t.noFinalize { return } values := t.values t.values = nil for i := range values { values[i].Finalize() } if t.pool == nil { return } t.pool.PutTags(Tags{values: values}) }
go
func (t *Tags) Finalize() { if t.noFinalize { return } values := t.values t.values = nil for i := range values { values[i].Finalize() } if t.pool == nil { return } t.pool.PutTags(Tags{values: values}) }
[ "func", "(", "t", "*", "Tags", ")", "Finalize", "(", ")", "{", "if", "t", ".", "noFinalize", "{", "return", "\n", "}", "\n\n", "values", ":=", "t", ".", "values", "\n", "t", ".", "values", "=", "nil", "\n\n", "for", "i", ":=", "range", "values", "{", "values", "[", "i", "]", ".", "Finalize", "(", ")", "\n", "}", "\n\n", "if", "t", ".", "pool", "==", "nil", "{", "return", "\n", "}", "\n\n", "t", ".", "pool", ".", "PutTags", "(", "Tags", "{", "values", ":", "values", "}", ")", "\n", "}" ]
// Finalize finalizes all Tags, unless NoFinalize has been called previously // in which case this is a no-op.
[ "Finalize", "finalizes", "all", "Tags", "unless", "NoFinalize", "has", "been", "called", "previously", "in", "which", "case", "this", "is", "a", "no", "-", "op", "." ]
ebf3c7b94afd62bad2aaa3ad20bb2d4142aa342e
https://github.com/m3db/m3x/blob/ebf3c7b94afd62bad2aaa3ad20bb2d4142aa342e/ident/types.go#L267-L284
2,798
m3db/m3x
ident/types.go
Equal
func (t Tags) Equal(other Tags) bool { if len(t.Values()) != len(other.Values()) { return false } for i := 0; i < len(t.Values()); i++ { equal := t.values[i].Name.Equal(other.values[i].Name) && t.values[i].Value.Equal(other.values[i].Value) if !equal { return false } } return true }
go
func (t Tags) Equal(other Tags) bool { if len(t.Values()) != len(other.Values()) { return false } for i := 0; i < len(t.Values()); i++ { equal := t.values[i].Name.Equal(other.values[i].Name) && t.values[i].Value.Equal(other.values[i].Value) if !equal { return false } } return true }
[ "func", "(", "t", "Tags", ")", "Equal", "(", "other", "Tags", ")", "bool", "{", "if", "len", "(", "t", ".", "Values", "(", ")", ")", "!=", "len", "(", "other", ".", "Values", "(", ")", ")", "{", "return", "false", "\n", "}", "\n", "for", "i", ":=", "0", ";", "i", "<", "len", "(", "t", ".", "Values", "(", ")", ")", ";", "i", "++", "{", "equal", ":=", "t", ".", "values", "[", "i", "]", ".", "Name", ".", "Equal", "(", "other", ".", "values", "[", "i", "]", ".", "Name", ")", "&&", "t", ".", "values", "[", "i", "]", ".", "Value", ".", "Equal", "(", "other", ".", "values", "[", "i", "]", ".", "Value", ")", "\n", "if", "!", "equal", "{", "return", "false", "\n", "}", "\n", "}", "\n", "return", "true", "\n", "}" ]
// Equal returns a bool indicating if the tags are equal. It requires // the two slices are ordered the same.
[ "Equal", "returns", "a", "bool", "indicating", "if", "the", "tags", "are", "equal", ".", "It", "requires", "the", "two", "slices", "are", "ordered", "the", "same", "." ]
ebf3c7b94afd62bad2aaa3ad20bb2d4142aa342e
https://github.com/m3db/m3x/blob/ebf3c7b94afd62bad2aaa3ad20bb2d4142aa342e/ident/types.go#L288-L300
2,799
m3db/m3x
pool/bytes.go
NewBytesPool
func NewBytesPool(sizes []Bucket, opts ObjectPoolOptions) BytesPool { return &bytesPool{pool: NewBucketizedObjectPool(sizes, opts)} }
go
func NewBytesPool(sizes []Bucket, opts ObjectPoolOptions) BytesPool { return &bytesPool{pool: NewBucketizedObjectPool(sizes, opts)} }
[ "func", "NewBytesPool", "(", "sizes", "[", "]", "Bucket", ",", "opts", "ObjectPoolOptions", ")", "BytesPool", "{", "return", "&", "bytesPool", "{", "pool", ":", "NewBucketizedObjectPool", "(", "sizes", ",", "opts", ")", "}", "\n", "}" ]
// NewBytesPool creates a new bytes pool
[ "NewBytesPool", "creates", "a", "new", "bytes", "pool" ]
ebf3c7b94afd62bad2aaa3ad20bb2d4142aa342e
https://github.com/m3db/m3x/blob/ebf3c7b94afd62bad2aaa3ad20bb2d4142aa342e/pool/bytes.go#L28-L30