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
5,300
mitchellh/colorstring
colorstring.go
Fprint
func Fprint(w io.Writer, a string) (n int, err error) { return fmt.Fprint(w, Color(a)) }
go
func Fprint(w io.Writer, a string) (n int, err error) { return fmt.Fprint(w, Color(a)) }
[ "func", "Fprint", "(", "w", "io", ".", "Writer", ",", "a", "string", ")", "(", "n", "int", ",", "err", "error", ")", "{", "return", "fmt", ".", "Fprint", "(", "w", ",", "Color", "(", "a", ")", ")", "\n", "}" ]
// Fprint is a convenience wrapper for fmt.Fprint with support for color codes. // // Fprint formats using the default formats for its operands and writes to w // with support for color codes. Spaces are added between operands when neither // is a string. It returns the number of bytes written and any write error // encountered.
[ "Fprint", "is", "a", "convenience", "wrapper", "for", "fmt", ".", "Fprint", "with", "support", "for", "color", "codes", ".", "Fprint", "formats", "using", "the", "default", "formats", "for", "its", "operands", "and", "writes", "to", "w", "with", "support", "for", "color", "codes", ".", "Spaces", "are", "added", "between", "operands", "when", "neither", "is", "a", "string", ".", "It", "returns", "the", "number", "of", "bytes", "written", "and", "any", "write", "error", "encountered", "." ]
d06e56a500db4d08c33db0b79461e7c9beafca2d
https://github.com/mitchellh/colorstring/blob/d06e56a500db4d08c33db0b79461e7c9beafca2d/colorstring.go#L221-L223
5,301
koron/go-dproxy
type.go
detectType
func detectType(v interface{}) Type { if v == nil { return Tnil } switch v.(type) { case bool: return Tbool case int, int32, int64: return Tint64 case float32, float64: return Tfloat64 case string: return Tstring case []interface{}: return Tarray case map[string]interface{}: return Tmap default: return Tunknown } }
go
func detectType(v interface{}) Type { if v == nil { return Tnil } switch v.(type) { case bool: return Tbool case int, int32, int64: return Tint64 case float32, float64: return Tfloat64 case string: return Tstring case []interface{}: return Tarray case map[string]interface{}: return Tmap default: return Tunknown } }
[ "func", "detectType", "(", "v", "interface", "{", "}", ")", "Type", "{", "if", "v", "==", "nil", "{", "return", "Tnil", "\n", "}", "\n", "switch", "v", ".", "(", "type", ")", "{", "case", "bool", ":", "return", "Tbool", "\n", "case", "int", ",", "int32", ",", "int64", ":", "return", "Tint64", "\n", "case", "float32", ",", "float64", ":", "return", "Tfloat64", "\n", "case", "string", ":", "return", "Tstring", "\n", "case", "[", "]", "interface", "{", "}", ":", "return", "Tarray", "\n", "case", "map", "[", "string", "]", "interface", "{", "}", ":", "return", "Tmap", "\n", "default", ":", "return", "Tunknown", "\n", "}", "\n", "}" ]
// detectType returns type of a value.
[ "detectType", "returns", "type", "of", "a", "value", "." ]
fd990aff3734271e213a87f118319cf104bb2dd6
https://github.com/koron/go-dproxy/blob/fd990aff3734271e213a87f118319cf104bb2dd6/type.go#L33-L53
5,302
koron/go-dproxy
drain.go
First
func (d *Drain) First() error { if d == nil || len(d.errors) == 0 { return nil } return d.errors[0] }
go
func (d *Drain) First() error { if d == nil || len(d.errors) == 0 { return nil } return d.errors[0] }
[ "func", "(", "d", "*", "Drain", ")", "First", "(", ")", "error", "{", "if", "d", "==", "nil", "||", "len", "(", "d", ".", "errors", ")", "==", "0", "{", "return", "nil", "\n", "}", "\n", "return", "d", ".", "errors", "[", "0", "]", "\n", "}" ]
// First returns a stored error. Returns nil if there are no errors.
[ "First", "returns", "a", "stored", "error", ".", "Returns", "nil", "if", "there", "are", "no", "errors", "." ]
fd990aff3734271e213a87f118319cf104bb2dd6
https://github.com/koron/go-dproxy/blob/fd990aff3734271e213a87f118319cf104bb2dd6/drain.go#L16-L21
5,303
koron/go-dproxy
drain.go
All
func (d *Drain) All() []error { if d == nil || len(d.errors) == 0 { return nil } a := make([]error, 0, len(d.errors)) return append(a, d.errors...) }
go
func (d *Drain) All() []error { if d == nil || len(d.errors) == 0 { return nil } a := make([]error, 0, len(d.errors)) return append(a, d.errors...) }
[ "func", "(", "d", "*", "Drain", ")", "All", "(", ")", "[", "]", "error", "{", "if", "d", "==", "nil", "||", "len", "(", "d", ".", "errors", ")", "==", "0", "{", "return", "nil", "\n", "}", "\n", "a", ":=", "make", "(", "[", "]", "error", ",", "0", ",", "len", "(", "d", ".", "errors", ")", ")", "\n", "return", "append", "(", "a", ",", "d", ".", "errors", "...", ")", "\n", "}" ]
// All returns all errors which stored. Return nil if no errors stored.
[ "All", "returns", "all", "errors", "which", "stored", ".", "Return", "nil", "if", "no", "errors", "stored", "." ]
fd990aff3734271e213a87f118319cf104bb2dd6
https://github.com/koron/go-dproxy/blob/fd990aff3734271e213a87f118319cf104bb2dd6/drain.go#L24-L30
5,304
koron/go-dproxy
drain.go
CombineErrors
func (d *Drain) CombineErrors() error { if d == nil || len(d.errors) == 0 { return nil } return drainError(d.errors) }
go
func (d *Drain) CombineErrors() error { if d == nil || len(d.errors) == 0 { return nil } return drainError(d.errors) }
[ "func", "(", "d", "*", "Drain", ")", "CombineErrors", "(", ")", "error", "{", "if", "d", "==", "nil", "||", "len", "(", "d", ".", "errors", ")", "==", "0", "{", "return", "nil", "\n", "}", "\n", "return", "drainError", "(", "d", ".", "errors", ")", "\n", "}" ]
// CombineErrors returns an error which combined all stored errors. Return nil // if not erros stored.
[ "CombineErrors", "returns", "an", "error", "which", "combined", "all", "stored", "errors", ".", "Return", "nil", "if", "not", "erros", "stored", "." ]
fd990aff3734271e213a87f118319cf104bb2dd6
https://github.com/koron/go-dproxy/blob/fd990aff3734271e213a87f118319cf104bb2dd6/drain.go#L34-L39
5,305
koron/go-dproxy
drain.go
Bool
func (d *Drain) Bool(p Proxy) bool { v, err := p.Bool() d.put(err) return v }
go
func (d *Drain) Bool(p Proxy) bool { v, err := p.Bool() d.put(err) return v }
[ "func", "(", "d", "*", "Drain", ")", "Bool", "(", "p", "Proxy", ")", "bool", "{", "v", ",", "err", ":=", "p", ".", "Bool", "(", ")", "\n", "d", ".", "put", "(", "err", ")", "\n", "return", "v", "\n", "}" ]
// Bool returns bool value and stores an error.
[ "Bool", "returns", "bool", "value", "and", "stores", "an", "error", "." ]
fd990aff3734271e213a87f118319cf104bb2dd6
https://github.com/koron/go-dproxy/blob/fd990aff3734271e213a87f118319cf104bb2dd6/drain.go#L49-L53
5,306
koron/go-dproxy
drain.go
Int64
func (d *Drain) Int64(p Proxy) int64 { v, err := p.Int64() d.put(err) return v }
go
func (d *Drain) Int64(p Proxy) int64 { v, err := p.Int64() d.put(err) return v }
[ "func", "(", "d", "*", "Drain", ")", "Int64", "(", "p", "Proxy", ")", "int64", "{", "v", ",", "err", ":=", "p", ".", "Int64", "(", ")", "\n", "d", ".", "put", "(", "err", ")", "\n", "return", "v", "\n", "}" ]
// Int64 returns int64 value and stores an error.
[ "Int64", "returns", "int64", "value", "and", "stores", "an", "error", "." ]
fd990aff3734271e213a87f118319cf104bb2dd6
https://github.com/koron/go-dproxy/blob/fd990aff3734271e213a87f118319cf104bb2dd6/drain.go#L56-L60
5,307
koron/go-dproxy
drain.go
Float64
func (d *Drain) Float64(p Proxy) float64 { v, err := p.Float64() d.put(err) return v }
go
func (d *Drain) Float64(p Proxy) float64 { v, err := p.Float64() d.put(err) return v }
[ "func", "(", "d", "*", "Drain", ")", "Float64", "(", "p", "Proxy", ")", "float64", "{", "v", ",", "err", ":=", "p", ".", "Float64", "(", ")", "\n", "d", ".", "put", "(", "err", ")", "\n", "return", "v", "\n", "}" ]
// Float64 returns float64 value and stores an error.
[ "Float64", "returns", "float64", "value", "and", "stores", "an", "error", "." ]
fd990aff3734271e213a87f118319cf104bb2dd6
https://github.com/koron/go-dproxy/blob/fd990aff3734271e213a87f118319cf104bb2dd6/drain.go#L63-L67
5,308
seehuhn/mt19937
mt19937.go
Seed
func (mt *MT19937) Seed(seed int64) { x := mt.state x[0] = uint64(seed) for i := uint64(1); i < n; i++ { x[i] = 6364136223846793005*(x[i-1]^(x[i-1]>>62)) + i } mt.index = n }
go
func (mt *MT19937) Seed(seed int64) { x := mt.state x[0] = uint64(seed) for i := uint64(1); i < n; i++ { x[i] = 6364136223846793005*(x[i-1]^(x[i-1]>>62)) + i } mt.index = n }
[ "func", "(", "mt", "*", "MT19937", ")", "Seed", "(", "seed", "int64", ")", "{", "x", ":=", "mt", ".", "state", "\n", "x", "[", "0", "]", "=", "uint64", "(", "seed", ")", "\n", "for", "i", ":=", "uint64", "(", "1", ")", ";", "i", "<", "n", ";", "i", "++", "{", "x", "[", "i", "]", "=", "6364136223846793005", "*", "(", "x", "[", "i", "-", "1", "]", "^", "(", "x", "[", "i", "-", "1", "]", ">>", "62", ")", ")", "+", "i", "\n", "}", "\n", "mt", ".", "index", "=", "n", "\n", "}" ]
// Seed uses the given 64bit value to initialise the generator state. // This method is part of the rand.Source interface.
[ "Seed", "uses", "the", "given", "64bit", "value", "to", "initialise", "the", "generator", "state", ".", "This", "method", "is", "part", "of", "the", "rand", ".", "Source", "interface", "." ]
cc7708819361f78dfcab8d72169c86917da88816
https://github.com/seehuhn/mt19937/blob/cc7708819361f78dfcab8d72169c86917da88816/mt19937.go#L57-L64
5,309
seehuhn/mt19937
mt19937.go
SeedFromSlice
func (mt *MT19937) SeedFromSlice(key []uint64) { mt.Seed(19650218) x := mt.state i := uint64(1) j := 0 k := len(key) if n > k { k = n } for k > 0 { x[i] = (x[i] ^ ((x[i-1] ^ (x[i-1] >> 62)) * 3935559000370003845) + key[j] + uint64(j)) i++ if i >= n { x[0] = x[n-1] i = 1 } j++ if j >= len(key) { j = 0 } k-- } for j := uint64(0); j < n-1; j++ { x[i] = x[i] ^ ((x[i-1] ^ (x[i-1] >> 62)) * 2862933555777941757) - i i++ if i >= n { x[0] = x[n-1] i = 1 } } x[0] = 1 << 63 }
go
func (mt *MT19937) SeedFromSlice(key []uint64) { mt.Seed(19650218) x := mt.state i := uint64(1) j := 0 k := len(key) if n > k { k = n } for k > 0 { x[i] = (x[i] ^ ((x[i-1] ^ (x[i-1] >> 62)) * 3935559000370003845) + key[j] + uint64(j)) i++ if i >= n { x[0] = x[n-1] i = 1 } j++ if j >= len(key) { j = 0 } k-- } for j := uint64(0); j < n-1; j++ { x[i] = x[i] ^ ((x[i-1] ^ (x[i-1] >> 62)) * 2862933555777941757) - i i++ if i >= n { x[0] = x[n-1] i = 1 } } x[0] = 1 << 63 }
[ "func", "(", "mt", "*", "MT19937", ")", "SeedFromSlice", "(", "key", "[", "]", "uint64", ")", "{", "mt", ".", "Seed", "(", "19650218", ")", "\n\n", "x", ":=", "mt", ".", "state", "\n", "i", ":=", "uint64", "(", "1", ")", "\n", "j", ":=", "0", "\n", "k", ":=", "len", "(", "key", ")", "\n", "if", "n", ">", "k", "{", "k", "=", "n", "\n", "}", "\n", "for", "k", ">", "0", "{", "x", "[", "i", "]", "=", "(", "x", "[", "i", "]", "^", "(", "(", "x", "[", "i", "-", "1", "]", "^", "(", "x", "[", "i", "-", "1", "]", ">>", "62", ")", ")", "*", "3935559000370003845", ")", "+", "key", "[", "j", "]", "+", "uint64", "(", "j", ")", ")", "\n", "i", "++", "\n", "if", "i", ">=", "n", "{", "x", "[", "0", "]", "=", "x", "[", "n", "-", "1", "]", "\n", "i", "=", "1", "\n", "}", "\n", "j", "++", "\n", "if", "j", ">=", "len", "(", "key", ")", "{", "j", "=", "0", "\n", "}", "\n", "k", "--", "\n", "}", "\n", "for", "j", ":=", "uint64", "(", "0", ")", ";", "j", "<", "n", "-", "1", ";", "j", "++", "{", "x", "[", "i", "]", "=", "x", "[", "i", "]", "^", "(", "(", "x", "[", "i", "-", "1", "]", "^", "(", "x", "[", "i", "-", "1", "]", ">>", "62", ")", ")", "*", "2862933555777941757", ")", "-", "i", "\n", "i", "++", "\n", "if", "i", ">=", "n", "{", "x", "[", "0", "]", "=", "x", "[", "n", "-", "1", "]", "\n", "i", "=", "1", "\n", "}", "\n", "}", "\n", "x", "[", "0", "]", "=", "1", "<<", "63", "\n", "}" ]
// SeedFromSlice uses the given slice of 64bit values to set the // generator state.
[ "SeedFromSlice", "uses", "the", "given", "slice", "of", "64bit", "values", "to", "set", "the", "generator", "state", "." ]
cc7708819361f78dfcab8d72169c86917da88816
https://github.com/seehuhn/mt19937/blob/cc7708819361f78dfcab8d72169c86917da88816/mt19937.go#L68-L101
5,310
htcat/htcat
defrag.go
nextFragment
func (d *defrag) nextFragment() *fragment { atomic.AddInt64(&d.lastAlloc, 1) f := fragment{ord: d.lastAlloc} return &f }
go
func (d *defrag) nextFragment() *fragment { atomic.AddInt64(&d.lastAlloc, 1) f := fragment{ord: d.lastAlloc} return &f }
[ "func", "(", "d", "*", "defrag", ")", "nextFragment", "(", ")", "*", "fragment", "{", "atomic", ".", "AddInt64", "(", "&", "d", ".", "lastAlloc", ",", "1", ")", "\n", "f", ":=", "fragment", "{", "ord", ":", "d", ".", "lastAlloc", "}", "\n\n", "return", "&", "f", "\n", "}" ]
// Generate a new fragment. These are numbered in the order they // appear in the output stream.
[ "Generate", "a", "new", "fragment", ".", "These", "are", "numbered", "in", "the", "order", "they", "appear", "in", "the", "output", "stream", "." ]
2e876d1aa131bd5e3a427b9bfacc5db7dc5a553d
https://github.com/htcat/htcat/blob/2e876d1aa131bd5e3a427b9bfacc5db7dc5a553d/defrag.go#L79-L84
5,311
htcat/htcat
defrag.go
WriteTo
func (d *defrag) WriteTo(dst io.Writer) (written int64, err error) { defer close(d.done) // Early exit if previously canceled. if d.cancellation != nil { return d.written, d.cancellation } for { // Exit if all fragments have finished. // // A fragment ordinal of zero is indeterminate and is // specifically excluded from being able to satisfy // that criteria. if d.lastWritten >= d.lastOrdinal && d.lastOrdinal > 0 { break } select { case frag := <-d.registerNotify: // Got fragment. // // Figure out whether to write it now or not. next := d.lastWritten + 1 if frag.ord == next { // This fragment completes the next // contiguous swathe of bytes to be // written out. n, err := d.writeConsecutive(dst, frag) d.written += n if err != nil { return d.written, err } } else if frag.ord > next { // Got a fragment that can't be // emitted yet: store it for now. d.future[frag.ord] = frag } else { return d.written, assertErrf( "Unexpected retrograde fragment %v, "+ "expected at least %v", frag.ord, next) } case d.cancellation = <-d.cancelNotify: // Cancel and exit immediately with the // injected cancellation. d.future = nil return d.written, d.cancellation case d.lastOrdinal = <-d.lastOrdinalNotify: // Re-check the exit conditions as a // lastOrdinal has been set. continue } } return d.written, nil }
go
func (d *defrag) WriteTo(dst io.Writer) (written int64, err error) { defer close(d.done) // Early exit if previously canceled. if d.cancellation != nil { return d.written, d.cancellation } for { // Exit if all fragments have finished. // // A fragment ordinal of zero is indeterminate and is // specifically excluded from being able to satisfy // that criteria. if d.lastWritten >= d.lastOrdinal && d.lastOrdinal > 0 { break } select { case frag := <-d.registerNotify: // Got fragment. // // Figure out whether to write it now or not. next := d.lastWritten + 1 if frag.ord == next { // This fragment completes the next // contiguous swathe of bytes to be // written out. n, err := d.writeConsecutive(dst, frag) d.written += n if err != nil { return d.written, err } } else if frag.ord > next { // Got a fragment that can't be // emitted yet: store it for now. d.future[frag.ord] = frag } else { return d.written, assertErrf( "Unexpected retrograde fragment %v, "+ "expected at least %v", frag.ord, next) } case d.cancellation = <-d.cancelNotify: // Cancel and exit immediately with the // injected cancellation. d.future = nil return d.written, d.cancellation case d.lastOrdinal = <-d.lastOrdinalNotify: // Re-check the exit conditions as a // lastOrdinal has been set. continue } } return d.written, nil }
[ "func", "(", "d", "*", "defrag", ")", "WriteTo", "(", "dst", "io", ".", "Writer", ")", "(", "written", "int64", ",", "err", "error", ")", "{", "defer", "close", "(", "d", ".", "done", ")", "\n\n", "// Early exit if previously canceled.", "if", "d", ".", "cancellation", "!=", "nil", "{", "return", "d", ".", "written", ",", "d", ".", "cancellation", "\n", "}", "\n\n", "for", "{", "// Exit if all fragments have finished.", "//", "// A fragment ordinal of zero is indeterminate and is", "// specifically excluded from being able to satisfy", "// that criteria.", "if", "d", ".", "lastWritten", ">=", "d", ".", "lastOrdinal", "&&", "d", ".", "lastOrdinal", ">", "0", "{", "break", "\n", "}", "\n\n", "select", "{", "case", "frag", ":=", "<-", "d", ".", "registerNotify", ":", "// Got fragment.", "//", "// Figure out whether to write it now or not.", "next", ":=", "d", ".", "lastWritten", "+", "1", "\n", "if", "frag", ".", "ord", "==", "next", "{", "// This fragment completes the next", "// contiguous swathe of bytes to be", "// written out.", "n", ",", "err", ":=", "d", ".", "writeConsecutive", "(", "dst", ",", "frag", ")", "\n", "d", ".", "written", "+=", "n", "\n", "if", "err", "!=", "nil", "{", "return", "d", ".", "written", ",", "err", "\n", "}", "\n", "}", "else", "if", "frag", ".", "ord", ">", "next", "{", "// Got a fragment that can't be", "// emitted yet: store it for now.", "d", ".", "future", "[", "frag", ".", "ord", "]", "=", "frag", "\n", "}", "else", "{", "return", "d", ".", "written", ",", "assertErrf", "(", "\"", "\"", "+", "\"", "\"", ",", "frag", ".", "ord", ",", "next", ")", "\n", "}", "\n\n", "case", "d", ".", "cancellation", "=", "<-", "d", ".", "cancelNotify", ":", "// Cancel and exit immediately with the", "// injected cancellation.", "d", ".", "future", "=", "nil", "\n", "return", "d", ".", "written", ",", "d", ".", "cancellation", "\n\n", "case", "d", ".", "lastOrdinal", "=", "<-", "d", ".", "lastOrdinalNotify", ":", "// Re-check the exit conditions as a", "// lastOrdinal has been set.", "continue", "\n", "}", "\n", "}", "\n\n", "return", "d", ".", "written", ",", "nil", "\n", "}" ]
// Write the contents of the defragmenter out to the io.Writer dst.
[ "Write", "the", "contents", "of", "the", "defragmenter", "out", "to", "the", "io", ".", "Writer", "dst", "." ]
2e876d1aa131bd5e3a427b9bfacc5db7dc5a553d
https://github.com/htcat/htcat/blob/2e876d1aa131bd5e3a427b9bfacc5db7dc5a553d/defrag.go#L97-L155
5,312
htcat/htcat
defrag.go
setLast
func (d *defrag) setLast(lastOrdinal int64) { select { case d.lastOrdinalNotify <- lastOrdinal: case <-d.done: } }
go
func (d *defrag) setLast(lastOrdinal int64) { select { case d.lastOrdinalNotify <- lastOrdinal: case <-d.done: } }
[ "func", "(", "d", "*", "defrag", ")", "setLast", "(", "lastOrdinal", "int64", ")", "{", "select", "{", "case", "d", ".", "lastOrdinalNotify", "<-", "lastOrdinal", ":", "case", "<-", "d", ".", "done", ":", "}", "\n", "}" ]
// Set the last work ordinal to be processed once this is known, which // can allow defrag.WriteTo to terminate.
[ "Set", "the", "last", "work", "ordinal", "to", "be", "processed", "once", "this", "is", "known", "which", "can", "allow", "defrag", ".", "WriteTo", "to", "terminate", "." ]
2e876d1aa131bd5e3a427b9bfacc5db7dc5a553d
https://github.com/htcat/htcat/blob/2e876d1aa131bd5e3a427b9bfacc5db7dc5a553d/defrag.go#L159-L164
5,313
htcat/htcat
defrag.go
writeConsecutive
func (d *defrag) writeConsecutive(dst io.Writer, start *fragment) ( int64, error) { // Write out the explicitly passed fragment. written, err := start.contents.WriteTo(dst) if err != nil { return int64(written), err } if err := start.contents.Close(); err != nil { return int64(written), err } d.lastWritten += 1 // Write as many contiguous bytes as possible. for { // Check for sent cancellation between each fragment // to abort earlier, when possible. select { case d.cancellation = <-d.cancelNotify: d.future = nil return 0, d.cancellation default: } next := d.lastWritten + 1 if frag, ok := d.future[next]; ok { // Found a contiguous segment to write. delete(d.future, next) n, err := frag.contents.WriteTo(dst) written += n defer frag.contents.Close() if err != nil { return int64(written), err } d.lastWritten = next } else { // No contiguous segment found. return int64(written), nil } } }
go
func (d *defrag) writeConsecutive(dst io.Writer, start *fragment) ( int64, error) { // Write out the explicitly passed fragment. written, err := start.contents.WriteTo(dst) if err != nil { return int64(written), err } if err := start.contents.Close(); err != nil { return int64(written), err } d.lastWritten += 1 // Write as many contiguous bytes as possible. for { // Check for sent cancellation between each fragment // to abort earlier, when possible. select { case d.cancellation = <-d.cancelNotify: d.future = nil return 0, d.cancellation default: } next := d.lastWritten + 1 if frag, ok := d.future[next]; ok { // Found a contiguous segment to write. delete(d.future, next) n, err := frag.contents.WriteTo(dst) written += n defer frag.contents.Close() if err != nil { return int64(written), err } d.lastWritten = next } else { // No contiguous segment found. return int64(written), nil } } }
[ "func", "(", "d", "*", "defrag", ")", "writeConsecutive", "(", "dst", "io", ".", "Writer", ",", "start", "*", "fragment", ")", "(", "int64", ",", "error", ")", "{", "// Write out the explicitly passed fragment.", "written", ",", "err", ":=", "start", ".", "contents", ".", "WriteTo", "(", "dst", ")", "\n", "if", "err", "!=", "nil", "{", "return", "int64", "(", "written", ")", ",", "err", "\n", "}", "\n\n", "if", "err", ":=", "start", ".", "contents", ".", "Close", "(", ")", ";", "err", "!=", "nil", "{", "return", "int64", "(", "written", ")", ",", "err", "\n", "}", "\n\n", "d", ".", "lastWritten", "+=", "1", "\n\n", "// Write as many contiguous bytes as possible.", "for", "{", "// Check for sent cancellation between each fragment", "// to abort earlier, when possible.", "select", "{", "case", "d", ".", "cancellation", "=", "<-", "d", ".", "cancelNotify", ":", "d", ".", "future", "=", "nil", "\n", "return", "0", ",", "d", ".", "cancellation", "\n", "default", ":", "}", "\n\n", "next", ":=", "d", ".", "lastWritten", "+", "1", "\n", "if", "frag", ",", "ok", ":=", "d", ".", "future", "[", "next", "]", ";", "ok", "{", "// Found a contiguous segment to write.", "delete", "(", "d", ".", "future", ",", "next", ")", "\n", "n", ",", "err", ":=", "frag", ".", "contents", ".", "WriteTo", "(", "dst", ")", "\n", "written", "+=", "n", "\n", "defer", "frag", ".", "contents", ".", "Close", "(", ")", "\n", "if", "err", "!=", "nil", "{", "return", "int64", "(", "written", ")", ",", "err", "\n", "}", "\n\n", "d", ".", "lastWritten", "=", "next", "\n", "}", "else", "{", "// No contiguous segment found.", "return", "int64", "(", "written", ")", ",", "nil", "\n", "}", "\n", "}", "\n", "}" ]
// Write a contiguous swathe of fragments, starting at the work // ordinal in 'start'.
[ "Write", "a", "contiguous", "swathe", "of", "fragments", "starting", "at", "the", "work", "ordinal", "in", "start", "." ]
2e876d1aa131bd5e3a427b9bfacc5db7dc5a553d
https://github.com/htcat/htcat/blob/2e876d1aa131bd5e3a427b9bfacc5db7dc5a553d/defrag.go#L178-L220
5,314
samalba/dockerclient
auth.go
encode
func (c *AuthConfig) encode() (string, error) { var buf bytes.Buffer if err := json.NewEncoder(&buf).Encode(c); err != nil { return "", err } return base64.URLEncoding.EncodeToString(buf.Bytes()), nil }
go
func (c *AuthConfig) encode() (string, error) { var buf bytes.Buffer if err := json.NewEncoder(&buf).Encode(c); err != nil { return "", err } return base64.URLEncoding.EncodeToString(buf.Bytes()), nil }
[ "func", "(", "c", "*", "AuthConfig", ")", "encode", "(", ")", "(", "string", ",", "error", ")", "{", "var", "buf", "bytes", ".", "Buffer", "\n", "if", "err", ":=", "json", ".", "NewEncoder", "(", "&", "buf", ")", ".", "Encode", "(", "c", ")", ";", "err", "!=", "nil", "{", "return", "\"", "\"", ",", "err", "\n", "}", "\n", "return", "base64", ".", "URLEncoding", ".", "EncodeToString", "(", "buf", ".", "Bytes", "(", ")", ")", ",", "nil", "\n", "}" ]
// encode the auth configuration struct into base64 for the X-Registry-Auth header
[ "encode", "the", "auth", "configuration", "struct", "into", "base64", "for", "the", "X", "-", "Registry", "-", "Auth", "header" ]
a3036261847103270e9f732509f43b5f98710ace
https://github.com/samalba/dockerclient/blob/a3036261847103270e9f732509f43b5f98710ace/auth.go#L18-L24
5,315
jfreymuth/oggvorbis
reader.go
NewReader
func NewReader(in io.Reader) (*Reader, error) { r := new(Reader) r.r.source = in r.r.seeker, _ = in.(io.Seeker) if err := r.init(); err != nil { return nil, err } return r, nil }
go
func NewReader(in io.Reader) (*Reader, error) { r := new(Reader) r.r.source = in r.r.seeker, _ = in.(io.Seeker) if err := r.init(); err != nil { return nil, err } return r, nil }
[ "func", "NewReader", "(", "in", "io", ".", "Reader", ")", "(", "*", "Reader", ",", "error", ")", "{", "r", ":=", "new", "(", "Reader", ")", "\n", "r", ".", "r", ".", "source", "=", "in", "\n", "r", ".", "r", ".", "seeker", ",", "_", "=", "in", ".", "(", "io", ".", "Seeker", ")", "\n", "if", "err", ":=", "r", ".", "init", "(", ")", ";", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "return", "r", ",", "nil", "\n", "}" ]
// NewReader creates a new Reader. // Some of the returned reader's methods will only work if in also implements // io.Seeker
[ "NewReader", "creates", "a", "new", "Reader", ".", "Some", "of", "the", "returned", "reader", "s", "methods", "will", "only", "work", "if", "in", "also", "implements", "io", ".", "Seeker" ]
ae597dfe1dbbe0024c3ef962f9f8a8f7de3f158b
https://github.com/jfreymuth/oggvorbis/blob/ae597dfe1dbbe0024c3ef962f9f8a8f7de3f158b/reader.go#L26-L34
5,316
jfreymuth/oggvorbis
reader.go
Position
func (r *Reader) Position() int64 { return r.position - int64(len(r.buffer)/r.Channels()) + int64(r.toSkip/r.Channels()) }
go
func (r *Reader) Position() int64 { return r.position - int64(len(r.buffer)/r.Channels()) + int64(r.toSkip/r.Channels()) }
[ "func", "(", "r", "*", "Reader", ")", "Position", "(", ")", "int64", "{", "return", "r", ".", "position", "-", "int64", "(", "len", "(", "r", ".", "buffer", ")", "/", "r", ".", "Channels", "(", ")", ")", "+", "int64", "(", "r", ".", "toSkip", "/", "r", ".", "Channels", "(", ")", ")", "\n", "}" ]
// Position returns the current position in samples.
[ "Position", "returns", "the", "current", "position", "in", "samples", "." ]
ae597dfe1dbbe0024c3ef962f9f8a8f7de3f158b
https://github.com/jfreymuth/oggvorbis/blob/ae597dfe1dbbe0024c3ef962f9f8a8f7de3f158b/reader.go#L88-L90
5,317
jfreymuth/oggvorbis
reader.go
SetPosition
func (r *Reader) SetPosition(pos int64) error { if r.r.seeker == nil { return errors.New("oggvorbis: reader is not seekable") } r.buffer = nil if pos >= r.length { r.r.lastPacket = true r.position = r.length return nil } start, err := r.r.SeekPageBefore(pos) if err != nil { return err } packet, err := r.r.NextPacket() r.dec.Clear() r.dec.DecodeInto(packet, r.originalBuffer) r.position = start r.toSkip = int(pos-start) * r.Channels() return nil }
go
func (r *Reader) SetPosition(pos int64) error { if r.r.seeker == nil { return errors.New("oggvorbis: reader is not seekable") } r.buffer = nil if pos >= r.length { r.r.lastPacket = true r.position = r.length return nil } start, err := r.r.SeekPageBefore(pos) if err != nil { return err } packet, err := r.r.NextPacket() r.dec.Clear() r.dec.DecodeInto(packet, r.originalBuffer) r.position = start r.toSkip = int(pos-start) * r.Channels() return nil }
[ "func", "(", "r", "*", "Reader", ")", "SetPosition", "(", "pos", "int64", ")", "error", "{", "if", "r", ".", "r", ".", "seeker", "==", "nil", "{", "return", "errors", ".", "New", "(", "\"", "\"", ")", "\n", "}", "\n", "r", ".", "buffer", "=", "nil", "\n", "if", "pos", ">=", "r", ".", "length", "{", "r", ".", "r", ".", "lastPacket", "=", "true", "\n", "r", ".", "position", "=", "r", ".", "length", "\n", "return", "nil", "\n", "}", "\n", "start", ",", "err", ":=", "r", ".", "r", ".", "SeekPageBefore", "(", "pos", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "packet", ",", "err", ":=", "r", ".", "r", ".", "NextPacket", "(", ")", "\n", "r", ".", "dec", ".", "Clear", "(", ")", "\n", "r", ".", "dec", ".", "DecodeInto", "(", "packet", ",", "r", ".", "originalBuffer", ")", "\n", "r", ".", "position", "=", "start", "\n", "r", ".", "toSkip", "=", "int", "(", "pos", "-", "start", ")", "*", "r", ".", "Channels", "(", ")", "\n", "return", "nil", "\n", "}" ]
// SetPosition seeks to a position in samples. // It will return an error if the underlying reader is not seekable.
[ "SetPosition", "seeks", "to", "a", "position", "in", "samples", ".", "It", "will", "return", "an", "error", "if", "the", "underlying", "reader", "is", "not", "seekable", "." ]
ae597dfe1dbbe0024c3ef962f9f8a8f7de3f158b
https://github.com/jfreymuth/oggvorbis/blob/ae597dfe1dbbe0024c3ef962f9f8a8f7de3f158b/reader.go#L99-L119
5,318
jfreymuth/oggvorbis
util.go
ReadAll
func ReadAll(in io.Reader) ([]float32, *Format, error) { r, err := NewReader(in) if err != nil { return nil, nil, err } format := &Format{ SampleRate: r.SampleRate(), Channels: r.Channels(), Bitrate: r.Bitrate(), } if r.Length() > 0 { result := make([]float32, (r.Length()-r.Position())*int64(r.Channels())) read := 0 for { n, err := r.Read(result[read:]) read += n if err != nil || read == len(result) { if err == io.EOF { err = nil } return result[:read], format, err } if n == 0 { return result[:read], format, io.ErrNoProgress } } } buf := make([]float32, r.dec.BufferSize()) var result []float32 for { n, err := r.Read(buf) result = append(result, buf[:n]...) if err != nil { if err == io.EOF { err = nil } return result, format, err } if n == 0 { return result, format, io.ErrNoProgress } } }
go
func ReadAll(in io.Reader) ([]float32, *Format, error) { r, err := NewReader(in) if err != nil { return nil, nil, err } format := &Format{ SampleRate: r.SampleRate(), Channels: r.Channels(), Bitrate: r.Bitrate(), } if r.Length() > 0 { result := make([]float32, (r.Length()-r.Position())*int64(r.Channels())) read := 0 for { n, err := r.Read(result[read:]) read += n if err != nil || read == len(result) { if err == io.EOF { err = nil } return result[:read], format, err } if n == 0 { return result[:read], format, io.ErrNoProgress } } } buf := make([]float32, r.dec.BufferSize()) var result []float32 for { n, err := r.Read(buf) result = append(result, buf[:n]...) if err != nil { if err == io.EOF { err = nil } return result, format, err } if n == 0 { return result, format, io.ErrNoProgress } } }
[ "func", "ReadAll", "(", "in", "io", ".", "Reader", ")", "(", "[", "]", "float32", ",", "*", "Format", ",", "error", ")", "{", "r", ",", "err", ":=", "NewReader", "(", "in", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "nil", ",", "err", "\n", "}", "\n", "format", ":=", "&", "Format", "{", "SampleRate", ":", "r", ".", "SampleRate", "(", ")", ",", "Channels", ":", "r", ".", "Channels", "(", ")", ",", "Bitrate", ":", "r", ".", "Bitrate", "(", ")", ",", "}", "\n", "if", "r", ".", "Length", "(", ")", ">", "0", "{", "result", ":=", "make", "(", "[", "]", "float32", ",", "(", "r", ".", "Length", "(", ")", "-", "r", ".", "Position", "(", ")", ")", "*", "int64", "(", "r", ".", "Channels", "(", ")", ")", ")", "\n", "read", ":=", "0", "\n\n", "for", "{", "n", ",", "err", ":=", "r", ".", "Read", "(", "result", "[", "read", ":", "]", ")", "\n", "read", "+=", "n", "\n", "if", "err", "!=", "nil", "||", "read", "==", "len", "(", "result", ")", "{", "if", "err", "==", "io", ".", "EOF", "{", "err", "=", "nil", "\n", "}", "\n", "return", "result", "[", ":", "read", "]", ",", "format", ",", "err", "\n", "}", "\n", "if", "n", "==", "0", "{", "return", "result", "[", ":", "read", "]", ",", "format", ",", "io", ".", "ErrNoProgress", "\n", "}", "\n", "}", "\n", "}", "\n", "buf", ":=", "make", "(", "[", "]", "float32", ",", "r", ".", "dec", ".", "BufferSize", "(", ")", ")", "\n", "var", "result", "[", "]", "float32", "\n", "for", "{", "n", ",", "err", ":=", "r", ".", "Read", "(", "buf", ")", "\n", "result", "=", "append", "(", "result", ",", "buf", "[", ":", "n", "]", "...", ")", "\n", "if", "err", "!=", "nil", "{", "if", "err", "==", "io", ".", "EOF", "{", "err", "=", "nil", "\n", "}", "\n", "return", "result", ",", "format", ",", "err", "\n", "}", "\n", "if", "n", "==", "0", "{", "return", "result", ",", "format", ",", "io", ".", "ErrNoProgress", "\n", "}", "\n", "}", "\n", "}" ]
// ReadAll decodes audio from in until an error or EOF.
[ "ReadAll", "decodes", "audio", "from", "in", "until", "an", "error", "or", "EOF", "." ]
ae597dfe1dbbe0024c3ef962f9f8a8f7de3f158b
https://github.com/jfreymuth/oggvorbis/blob/ae597dfe1dbbe0024c3ef962f9f8a8f7de3f158b/util.go#L17-L60
5,319
jfreymuth/oggvorbis
util.go
GetFormat
func GetFormat(in io.Reader) (*Format, error) { var dec vorbis.Decoder r := oggReader{source: in} p, err := r.NextPacket() if err != nil { return nil, err } err = dec.ReadHeader(p) if err != nil { return nil, err } return &Format{ SampleRate: dec.SampleRate(), Channels: dec.Channels(), Bitrate: dec.Bitrate, }, nil }
go
func GetFormat(in io.Reader) (*Format, error) { var dec vorbis.Decoder r := oggReader{source: in} p, err := r.NextPacket() if err != nil { return nil, err } err = dec.ReadHeader(p) if err != nil { return nil, err } return &Format{ SampleRate: dec.SampleRate(), Channels: dec.Channels(), Bitrate: dec.Bitrate, }, nil }
[ "func", "GetFormat", "(", "in", "io", ".", "Reader", ")", "(", "*", "Format", ",", "error", ")", "{", "var", "dec", "vorbis", ".", "Decoder", "\n", "r", ":=", "oggReader", "{", "source", ":", "in", "}", "\n", "p", ",", "err", ":=", "r", ".", "NextPacket", "(", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "err", "=", "dec", ".", "ReadHeader", "(", "p", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "return", "&", "Format", "{", "SampleRate", ":", "dec", ".", "SampleRate", "(", ")", ",", "Channels", ":", "dec", ".", "Channels", "(", ")", ",", "Bitrate", ":", "dec", ".", "Bitrate", ",", "}", ",", "nil", "\n", "}" ]
// GetFormat reads the first ogg page from in to get the audio format.
[ "GetFormat", "reads", "the", "first", "ogg", "page", "from", "in", "to", "get", "the", "audio", "format", "." ]
ae597dfe1dbbe0024c3ef962f9f8a8f7de3f158b
https://github.com/jfreymuth/oggvorbis/blob/ae597dfe1dbbe0024c3ef962f9f8a8f7de3f158b/util.go#L63-L79
5,320
jfreymuth/oggvorbis
util.go
GetCommentHeader
func GetCommentHeader(in io.Reader) (vorbis.CommentHeader, error) { var dec vorbis.Decoder r := oggReader{source: in} for i := 0; i < 2; i++ { p, err := r.NextPacket() if err != nil { return vorbis.CommentHeader{}, err } err = dec.ReadHeader(p) if err != nil { return vorbis.CommentHeader{}, err } } return dec.CommentHeader, nil }
go
func GetCommentHeader(in io.Reader) (vorbis.CommentHeader, error) { var dec vorbis.Decoder r := oggReader{source: in} for i := 0; i < 2; i++ { p, err := r.NextPacket() if err != nil { return vorbis.CommentHeader{}, err } err = dec.ReadHeader(p) if err != nil { return vorbis.CommentHeader{}, err } } return dec.CommentHeader, nil }
[ "func", "GetCommentHeader", "(", "in", "io", ".", "Reader", ")", "(", "vorbis", ".", "CommentHeader", ",", "error", ")", "{", "var", "dec", "vorbis", ".", "Decoder", "\n", "r", ":=", "oggReader", "{", "source", ":", "in", "}", "\n", "for", "i", ":=", "0", ";", "i", "<", "2", ";", "i", "++", "{", "p", ",", "err", ":=", "r", ".", "NextPacket", "(", ")", "\n", "if", "err", "!=", "nil", "{", "return", "vorbis", ".", "CommentHeader", "{", "}", ",", "err", "\n", "}", "\n", "err", "=", "dec", ".", "ReadHeader", "(", "p", ")", "\n", "if", "err", "!=", "nil", "{", "return", "vorbis", ".", "CommentHeader", "{", "}", ",", "err", "\n", "}", "\n", "}", "\n", "return", "dec", ".", "CommentHeader", ",", "nil", "\n", "}" ]
// GetCommentHeader returns a struct containing info from the comment header.
[ "GetCommentHeader", "returns", "a", "struct", "containing", "info", "from", "the", "comment", "header", "." ]
ae597dfe1dbbe0024c3ef962f9f8a8f7de3f158b
https://github.com/jfreymuth/oggvorbis/blob/ae597dfe1dbbe0024c3ef962f9f8a8f7de3f158b/util.go#L82-L96
5,321
jfreymuth/oggvorbis
util.go
GetLength
func GetLength(in io.ReadSeeker) (int64, *Format, error) { r := oggReader{source: in, seeker: in} var dec vorbis.Decoder p, err := r.NextPacket() if err != nil { return 0, nil, err } err = dec.ReadHeader(p) if err != nil { return 0, nil, err } format := &Format{ SampleRate: dec.SampleRate(), Channels: dec.Channels(), Bitrate: dec.Bitrate, } length, err := r.LastPosition() return length, format, err }
go
func GetLength(in io.ReadSeeker) (int64, *Format, error) { r := oggReader{source: in, seeker: in} var dec vorbis.Decoder p, err := r.NextPacket() if err != nil { return 0, nil, err } err = dec.ReadHeader(p) if err != nil { return 0, nil, err } format := &Format{ SampleRate: dec.SampleRate(), Channels: dec.Channels(), Bitrate: dec.Bitrate, } length, err := r.LastPosition() return length, format, err }
[ "func", "GetLength", "(", "in", "io", ".", "ReadSeeker", ")", "(", "int64", ",", "*", "Format", ",", "error", ")", "{", "r", ":=", "oggReader", "{", "source", ":", "in", ",", "seeker", ":", "in", "}", "\n", "var", "dec", "vorbis", ".", "Decoder", "\n", "p", ",", "err", ":=", "r", ".", "NextPacket", "(", ")", "\n", "if", "err", "!=", "nil", "{", "return", "0", ",", "nil", ",", "err", "\n", "}", "\n", "err", "=", "dec", ".", "ReadHeader", "(", "p", ")", "\n", "if", "err", "!=", "nil", "{", "return", "0", ",", "nil", ",", "err", "\n", "}", "\n", "format", ":=", "&", "Format", "{", "SampleRate", ":", "dec", ".", "SampleRate", "(", ")", ",", "Channels", ":", "dec", ".", "Channels", "(", ")", ",", "Bitrate", ":", "dec", ".", "Bitrate", ",", "}", "\n", "length", ",", "err", ":=", "r", ".", "LastPosition", "(", ")", "\n", "return", "length", ",", "format", ",", "err", "\n", "}" ]
// GetLength returns the length of the file in samples and the audio format.
[ "GetLength", "returns", "the", "length", "of", "the", "file", "in", "samples", "and", "the", "audio", "format", "." ]
ae597dfe1dbbe0024c3ef962f9f8a8f7de3f158b
https://github.com/jfreymuth/oggvorbis/blob/ae597dfe1dbbe0024c3ef962f9f8a8f7de3f158b/util.go#L99-L117
5,322
coreos/locksmith
lock/semaphore.go
SetMax
func (s *Semaphore) SetMax(max int) error { diff := s.Max - max s.Semaphore = s.Semaphore - diff s.Max = s.Max - diff return nil }
go
func (s *Semaphore) SetMax(max int) error { diff := s.Max - max s.Semaphore = s.Semaphore - diff s.Max = s.Max - diff return nil }
[ "func", "(", "s", "*", "Semaphore", ")", "SetMax", "(", "max", "int", ")", "error", "{", "diff", ":=", "s", ".", "Max", "-", "max", "\n\n", "s", ".", "Semaphore", "=", "s", ".", "Semaphore", "-", "diff", "\n", "s", ".", "Max", "=", "s", ".", "Max", "-", "diff", "\n\n", "return", "nil", "\n", "}" ]
// SetMax sets the maximum number of holders of the semaphore
[ "SetMax", "sets", "the", "maximum", "number", "of", "holders", "of", "the", "semaphore" ]
ba572048b6baf84b4488656ca4f8b115243ab3d5
https://github.com/coreos/locksmith/blob/ba572048b6baf84b4488656ca4f8b115243ab3d5/lock/semaphore.go#L42-L49
5,323
coreos/locksmith
lock/semaphore.go
String
func (s *Semaphore) String() string { b, _ := json.Marshal(s) return string(b) }
go
func (s *Semaphore) String() string { b, _ := json.Marshal(s) return string(b) }
[ "func", "(", "s", "*", "Semaphore", ")", "String", "(", ")", "string", "{", "b", ",", "_", ":=", "json", ".", "Marshal", "(", "s", ")", "\n", "return", "string", "(", "b", ")", "\n", "}" ]
// String returns a json representation of the semaphore // if there is an error when marshalling the json, it is ignored and the empty // string is returned.
[ "String", "returns", "a", "json", "representation", "of", "the", "semaphore", "if", "there", "is", "an", "error", "when", "marshalling", "the", "json", "it", "is", "ignored", "and", "the", "empty", "string", "is", "returned", "." ]
ba572048b6baf84b4488656ca4f8b115243ab3d5
https://github.com/coreos/locksmith/blob/ba572048b6baf84b4488656ca4f8b115243ab3d5/lock/semaphore.go#L54-L57
5,324
coreos/locksmith
lock/semaphore.go
addHolder
func (s *Semaphore) addHolder(h string) error { loc := sort.SearchStrings(s.Holders, h) switch { case loc == len(s.Holders): s.Holders = append(s.Holders, h) case s.Holders[loc] == h: return ErrExist default: s.Holders = append(s.Holders[:loc], append([]string{h}, s.Holders[loc:]...)...) } return nil }
go
func (s *Semaphore) addHolder(h string) error { loc := sort.SearchStrings(s.Holders, h) switch { case loc == len(s.Holders): s.Holders = append(s.Holders, h) case s.Holders[loc] == h: return ErrExist default: s.Holders = append(s.Holders[:loc], append([]string{h}, s.Holders[loc:]...)...) } return nil }
[ "func", "(", "s", "*", "Semaphore", ")", "addHolder", "(", "h", "string", ")", "error", "{", "loc", ":=", "sort", ".", "SearchStrings", "(", "s", ".", "Holders", ",", "h", ")", "\n", "switch", "{", "case", "loc", "==", "len", "(", "s", ".", "Holders", ")", ":", "s", ".", "Holders", "=", "append", "(", "s", ".", "Holders", ",", "h", ")", "\n", "case", "s", ".", "Holders", "[", "loc", "]", "==", "h", ":", "return", "ErrExist", "\n", "default", ":", "s", ".", "Holders", "=", "append", "(", "s", ".", "Holders", "[", ":", "loc", "]", ",", "append", "(", "[", "]", "string", "{", "h", "}", ",", "s", ".", "Holders", "[", "loc", ":", "]", "...", ")", "...", ")", "\n", "}", "\n\n", "return", "nil", "\n", "}" ]
// addHolder adds a holder with id h to the list of holders in the semaphore // it returns ErrExist if the given id is in the list
[ "addHolder", "adds", "a", "holder", "with", "id", "h", "to", "the", "list", "of", "holders", "in", "the", "semaphore", "it", "returns", "ErrExist", "if", "the", "given", "id", "is", "in", "the", "list" ]
ba572048b6baf84b4488656ca4f8b115243ab3d5
https://github.com/coreos/locksmith/blob/ba572048b6baf84b4488656ca4f8b115243ab3d5/lock/semaphore.go#L61-L73
5,325
coreos/locksmith
lock/semaphore.go
removeHolder
func (s *Semaphore) removeHolder(h string) error { loc := sort.SearchStrings(s.Holders, h) if loc < len(s.Holders) && s.Holders[loc] == h { s.Holders = append(s.Holders[:loc], s.Holders[loc+1:]...) } else { return ErrNotExist } return nil }
go
func (s *Semaphore) removeHolder(h string) error { loc := sort.SearchStrings(s.Holders, h) if loc < len(s.Holders) && s.Holders[loc] == h { s.Holders = append(s.Holders[:loc], s.Holders[loc+1:]...) } else { return ErrNotExist } return nil }
[ "func", "(", "s", "*", "Semaphore", ")", "removeHolder", "(", "h", "string", ")", "error", "{", "loc", ":=", "sort", ".", "SearchStrings", "(", "s", ".", "Holders", ",", "h", ")", "\n", "if", "loc", "<", "len", "(", "s", ".", "Holders", ")", "&&", "s", ".", "Holders", "[", "loc", "]", "==", "h", "{", "s", ".", "Holders", "=", "append", "(", "s", ".", "Holders", "[", ":", "loc", "]", ",", "s", ".", "Holders", "[", "loc", "+", "1", ":", "]", "...", ")", "\n", "}", "else", "{", "return", "ErrNotExist", "\n", "}", "\n\n", "return", "nil", "\n", "}" ]
// removeHolder removes a holder with id h from the list of holders in the // semaphore. It returns ErrNotExist if the given id is not in the list
[ "removeHolder", "removes", "a", "holder", "with", "id", "h", "from", "the", "list", "of", "holders", "in", "the", "semaphore", ".", "It", "returns", "ErrNotExist", "if", "the", "given", "id", "is", "not", "in", "the", "list" ]
ba572048b6baf84b4488656ca4f8b115243ab3d5
https://github.com/coreos/locksmith/blob/ba572048b6baf84b4488656ca4f8b115243ab3d5/lock/semaphore.go#L77-L86
5,326
coreos/locksmith
lock/semaphore.go
Lock
func (s *Semaphore) Lock(h string) error { if s.Semaphore <= 0 { return fmt.Errorf("semaphore is at %v", s.Semaphore) } if err := s.addHolder(h); err != nil { return err } s.Semaphore = s.Semaphore - 1 return nil }
go
func (s *Semaphore) Lock(h string) error { if s.Semaphore <= 0 { return fmt.Errorf("semaphore is at %v", s.Semaphore) } if err := s.addHolder(h); err != nil { return err } s.Semaphore = s.Semaphore - 1 return nil }
[ "func", "(", "s", "*", "Semaphore", ")", "Lock", "(", "h", "string", ")", "error", "{", "if", "s", ".", "Semaphore", "<=", "0", "{", "return", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "s", ".", "Semaphore", ")", "\n", "}", "\n\n", "if", "err", ":=", "s", ".", "addHolder", "(", "h", ")", ";", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n\n", "s", ".", "Semaphore", "=", "s", ".", "Semaphore", "-", "1", "\n\n", "return", "nil", "\n", "}" ]
// Lock adds a holder with id h to the semaphore // It adds the id h to the list of holders, returning ErrExist the id already // exists, then it subtracts one from the semaphore. If the semaphore is already // held by the maximum number of people it returns an error.
[ "Lock", "adds", "a", "holder", "with", "id", "h", "to", "the", "semaphore", "It", "adds", "the", "id", "h", "to", "the", "list", "of", "holders", "returning", "ErrExist", "the", "id", "already", "exists", "then", "it", "subtracts", "one", "from", "the", "semaphore", ".", "If", "the", "semaphore", "is", "already", "held", "by", "the", "maximum", "number", "of", "people", "it", "returns", "an", "error", "." ]
ba572048b6baf84b4488656ca4f8b115243ab3d5
https://github.com/coreos/locksmith/blob/ba572048b6baf84b4488656ca4f8b115243ab3d5/lock/semaphore.go#L92-L104
5,327
coreos/locksmith
lock/semaphore.go
Unlock
func (s *Semaphore) Unlock(h string) error { if err := s.removeHolder(h); err != nil { return err } s.Semaphore = s.Semaphore + 1 return nil }
go
func (s *Semaphore) Unlock(h string) error { if err := s.removeHolder(h); err != nil { return err } s.Semaphore = s.Semaphore + 1 return nil }
[ "func", "(", "s", "*", "Semaphore", ")", "Unlock", "(", "h", "string", ")", "error", "{", "if", "err", ":=", "s", ".", "removeHolder", "(", "h", ")", ";", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n\n", "s", ".", "Semaphore", "=", "s", ".", "Semaphore", "+", "1", "\n\n", "return", "nil", "\n", "}" ]
// Unlock removes a holder with id h from the semaphore // It removes the id h from the list of holders, returning ErrNotExist if the id // does not exist in the list, then adds one to the semaphore.
[ "Unlock", "removes", "a", "holder", "with", "id", "h", "from", "the", "semaphore", "It", "removes", "the", "id", "h", "from", "the", "list", "of", "holders", "returning", "ErrNotExist", "if", "the", "id", "does", "not", "exist", "in", "the", "list", "then", "adds", "one", "to", "the", "semaphore", "." ]
ba572048b6baf84b4488656ca4f8b115243ab3d5
https://github.com/coreos/locksmith/blob/ba572048b6baf84b4488656ca4f8b115243ab3d5/lock/semaphore.go#L109-L117
5,328
coreos/locksmith
locksmithctl/locksmithctl.go
getClient
func getClient() (*lock.EtcdLockClient, error) { // copy of github.com/coreos/etcd/client.DefaultTransport so that // TLSClientConfig can be overridden. transport := &http.Transport{ Proxy: http.ProxyFromEnvironment, Dial: (&net.Dialer{ Timeout: 30 * time.Second, KeepAlive: 30 * time.Second, }).Dial, TLSHandshakeTimeout: 10 * time.Second, } if globalFlags.EtcdCAFile != "" || globalFlags.EtcdCertFile != "" || globalFlags.EtcdKeyFile != "" { cert, err := tls.LoadX509KeyPair(globalFlags.EtcdCertFile, globalFlags.EtcdKeyFile) if err != nil { return nil, err } ca, err := ioutil.ReadFile(globalFlags.EtcdCAFile) if err != nil { return nil, err } capool := x509.NewCertPool() capool.AppendCertsFromPEM(ca) tlsconf := &tls.Config{ Certificates: []tls.Certificate{cert}, RootCAs: capool, } tlsconf.BuildNameToCertificate() transport.TLSClientConfig = tlsconf } cfg := client.Config{ Endpoints: globalFlags.Endpoints, Transport: transport, Username: globalFlags.EtcdUsername, Password: globalFlags.EtcdPassword, } ec, err := client.New(cfg) if err != nil { return nil, err } kapi := client.NewKeysAPI(ec) lc, err := lock.NewEtcdLockClient(kapi, globalFlags.Group) if err != nil { return nil, err } return lc, err }
go
func getClient() (*lock.EtcdLockClient, error) { // copy of github.com/coreos/etcd/client.DefaultTransport so that // TLSClientConfig can be overridden. transport := &http.Transport{ Proxy: http.ProxyFromEnvironment, Dial: (&net.Dialer{ Timeout: 30 * time.Second, KeepAlive: 30 * time.Second, }).Dial, TLSHandshakeTimeout: 10 * time.Second, } if globalFlags.EtcdCAFile != "" || globalFlags.EtcdCertFile != "" || globalFlags.EtcdKeyFile != "" { cert, err := tls.LoadX509KeyPair(globalFlags.EtcdCertFile, globalFlags.EtcdKeyFile) if err != nil { return nil, err } ca, err := ioutil.ReadFile(globalFlags.EtcdCAFile) if err != nil { return nil, err } capool := x509.NewCertPool() capool.AppendCertsFromPEM(ca) tlsconf := &tls.Config{ Certificates: []tls.Certificate{cert}, RootCAs: capool, } tlsconf.BuildNameToCertificate() transport.TLSClientConfig = tlsconf } cfg := client.Config{ Endpoints: globalFlags.Endpoints, Transport: transport, Username: globalFlags.EtcdUsername, Password: globalFlags.EtcdPassword, } ec, err := client.New(cfg) if err != nil { return nil, err } kapi := client.NewKeysAPI(ec) lc, err := lock.NewEtcdLockClient(kapi, globalFlags.Group) if err != nil { return nil, err } return lc, err }
[ "func", "getClient", "(", ")", "(", "*", "lock", ".", "EtcdLockClient", ",", "error", ")", "{", "// copy of github.com/coreos/etcd/client.DefaultTransport so that", "// TLSClientConfig can be overridden.", "transport", ":=", "&", "http", ".", "Transport", "{", "Proxy", ":", "http", ".", "ProxyFromEnvironment", ",", "Dial", ":", "(", "&", "net", ".", "Dialer", "{", "Timeout", ":", "30", "*", "time", ".", "Second", ",", "KeepAlive", ":", "30", "*", "time", ".", "Second", ",", "}", ")", ".", "Dial", ",", "TLSHandshakeTimeout", ":", "10", "*", "time", ".", "Second", ",", "}", "\n\n", "if", "globalFlags", ".", "EtcdCAFile", "!=", "\"", "\"", "||", "globalFlags", ".", "EtcdCertFile", "!=", "\"", "\"", "||", "globalFlags", ".", "EtcdKeyFile", "!=", "\"", "\"", "{", "cert", ",", "err", ":=", "tls", ".", "LoadX509KeyPair", "(", "globalFlags", ".", "EtcdCertFile", ",", "globalFlags", ".", "EtcdKeyFile", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n\n", "ca", ",", "err", ":=", "ioutil", ".", "ReadFile", "(", "globalFlags", ".", "EtcdCAFile", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n\n", "capool", ":=", "x509", ".", "NewCertPool", "(", ")", "\n", "capool", ".", "AppendCertsFromPEM", "(", "ca", ")", "\n\n", "tlsconf", ":=", "&", "tls", ".", "Config", "{", "Certificates", ":", "[", "]", "tls", ".", "Certificate", "{", "cert", "}", ",", "RootCAs", ":", "capool", ",", "}", "\n\n", "tlsconf", ".", "BuildNameToCertificate", "(", ")", "\n\n", "transport", ".", "TLSClientConfig", "=", "tlsconf", "\n", "}", "\n\n", "cfg", ":=", "client", ".", "Config", "{", "Endpoints", ":", "globalFlags", ".", "Endpoints", ",", "Transport", ":", "transport", ",", "Username", ":", "globalFlags", ".", "EtcdUsername", ",", "Password", ":", "globalFlags", ".", "EtcdPassword", ",", "}", "\n\n", "ec", ",", "err", ":=", "client", ".", "New", "(", "cfg", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n\n", "kapi", ":=", "client", ".", "NewKeysAPI", "(", "ec", ")", "\n\n", "lc", ",", "err", ":=", "lock", ".", "NewEtcdLockClient", "(", "kapi", ",", "globalFlags", ".", "Group", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "return", "lc", ",", "err", "\n", "}" ]
// getLockClient returns an initialized EtcdLockClient, using an etcd // client configured from the global etcd flags
[ "getLockClient", "returns", "an", "initialized", "EtcdLockClient", "using", "an", "etcd", "client", "configured", "from", "the", "global", "etcd", "flags" ]
ba572048b6baf84b4488656ca4f8b115243ab3d5
https://github.com/coreos/locksmith/blob/ba572048b6baf84b4488656ca4f8b115243ab3d5/locksmithctl/locksmithctl.go#L183-L238
5,329
coreos/locksmith
updateengine/client.go
New
func New() (c *Client, err error) { c = new(Client) c.conn, err = dbus.SystemBusPrivate() if err != nil { return nil, err } methods := []dbus.Auth{dbus.AuthExternal(strconv.Itoa(os.Getuid()))} err = c.conn.Auth(methods) if err != nil { c.conn.Close() return nil, err } err = c.conn.Hello() if err != nil { c.conn.Close() return nil, err } c.object = c.conn.Object("com.coreos.update1", dbus.ObjectPath(dbusPath)) // Setup the filter for the StatusUpdate signals match := fmt.Sprintf("type='signal',interface='%s',member='%s'", dbusInterface, dbusMember) call := c.conn.BusObject().Call("org.freedesktop.DBus.AddMatch", 0, match) if call.Err != nil { return nil, err } c.ch = make(chan *dbus.Signal, signalBuffer) c.conn.Signal(c.ch) return c, nil }
go
func New() (c *Client, err error) { c = new(Client) c.conn, err = dbus.SystemBusPrivate() if err != nil { return nil, err } methods := []dbus.Auth{dbus.AuthExternal(strconv.Itoa(os.Getuid()))} err = c.conn.Auth(methods) if err != nil { c.conn.Close() return nil, err } err = c.conn.Hello() if err != nil { c.conn.Close() return nil, err } c.object = c.conn.Object("com.coreos.update1", dbus.ObjectPath(dbusPath)) // Setup the filter for the StatusUpdate signals match := fmt.Sprintf("type='signal',interface='%s',member='%s'", dbusInterface, dbusMember) call := c.conn.BusObject().Call("org.freedesktop.DBus.AddMatch", 0, match) if call.Err != nil { return nil, err } c.ch = make(chan *dbus.Signal, signalBuffer) c.conn.Signal(c.ch) return c, nil }
[ "func", "New", "(", ")", "(", "c", "*", "Client", ",", "err", "error", ")", "{", "c", "=", "new", "(", "Client", ")", "\n\n", "c", ".", "conn", ",", "err", "=", "dbus", ".", "SystemBusPrivate", "(", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n\n", "methods", ":=", "[", "]", "dbus", ".", "Auth", "{", "dbus", ".", "AuthExternal", "(", "strconv", ".", "Itoa", "(", "os", ".", "Getuid", "(", ")", ")", ")", "}", "\n", "err", "=", "c", ".", "conn", ".", "Auth", "(", "methods", ")", "\n", "if", "err", "!=", "nil", "{", "c", ".", "conn", ".", "Close", "(", ")", "\n", "return", "nil", ",", "err", "\n", "}", "\n\n", "err", "=", "c", ".", "conn", ".", "Hello", "(", ")", "\n", "if", "err", "!=", "nil", "{", "c", ".", "conn", ".", "Close", "(", ")", "\n", "return", "nil", ",", "err", "\n", "}", "\n\n", "c", ".", "object", "=", "c", ".", "conn", ".", "Object", "(", "\"", "\"", ",", "dbus", ".", "ObjectPath", "(", "dbusPath", ")", ")", "\n\n", "// Setup the filter for the StatusUpdate signals", "match", ":=", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "dbusInterface", ",", "dbusMember", ")", "\n\n", "call", ":=", "c", ".", "conn", ".", "BusObject", "(", ")", ".", "Call", "(", "\"", "\"", ",", "0", ",", "match", ")", "\n", "if", "call", ".", "Err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n\n", "c", ".", "ch", "=", "make", "(", "chan", "*", "dbus", ".", "Signal", ",", "signalBuffer", ")", "\n", "c", ".", "conn", ".", "Signal", "(", "c", ".", "ch", ")", "\n\n", "return", "c", ",", "nil", "\n", "}" ]
// New returns a Client connected to dbus over a private connection with a // subscription to updateengine.
[ "New", "returns", "a", "Client", "connected", "to", "dbus", "over", "a", "private", "connection", "with", "a", "subscription", "to", "updateengine", "." ]
ba572048b6baf84b4488656ca4f8b115243ab3d5
https://github.com/coreos/locksmith/blob/ba572048b6baf84b4488656ca4f8b115243ab3d5/updateengine/client.go#L45-L80
5,330
coreos/locksmith
updateengine/client.go
RebootNeededSignal
func (c *Client) RebootNeededSignal(rcvr chan Status, stop chan struct{}) { for { select { case <-stop: return case signal := <-c.ch: s, err := TryNewStatus(signal) if err != nil { continue } println(s.String()) if s.CurrentOperation == UpdateStatusUpdatedNeedReboot { rcvr <- s } } } }
go
func (c *Client) RebootNeededSignal(rcvr chan Status, stop chan struct{}) { for { select { case <-stop: return case signal := <-c.ch: s, err := TryNewStatus(signal) if err != nil { continue } println(s.String()) if s.CurrentOperation == UpdateStatusUpdatedNeedReboot { rcvr <- s } } } }
[ "func", "(", "c", "*", "Client", ")", "RebootNeededSignal", "(", "rcvr", "chan", "Status", ",", "stop", "chan", "struct", "{", "}", ")", "{", "for", "{", "select", "{", "case", "<-", "stop", ":", "return", "\n", "case", "signal", ":=", "<-", "c", ".", "ch", ":", "s", ",", "err", ":=", "TryNewStatus", "(", "signal", ")", "\n", "if", "err", "!=", "nil", "{", "continue", "\n", "}", "\n", "println", "(", "s", ".", "String", "(", ")", ")", "\n", "if", "s", ".", "CurrentOperation", "==", "UpdateStatusUpdatedNeedReboot", "{", "rcvr", "<-", "s", "\n", "}", "\n", "}", "\n", "}", "\n", "}" ]
// RebootNeededSignal watches the updateengine status update subscription and // passes the status on the rcvr channel whenever the status update is // UpdateStatusUpdatedNeedReboot. The stop channel terminates the function. // This function is intended to be called as a goroutine
[ "RebootNeededSignal", "watches", "the", "updateengine", "status", "update", "subscription", "and", "passes", "the", "status", "on", "the", "rcvr", "channel", "whenever", "the", "status", "update", "is", "UpdateStatusUpdatedNeedReboot", ".", "The", "stop", "channel", "terminates", "the", "function", ".", "This", "function", "is", "intended", "to", "be", "called", "as", "a", "goroutine" ]
ba572048b6baf84b4488656ca4f8b115243ab3d5
https://github.com/coreos/locksmith/blob/ba572048b6baf84b4488656ca4f8b115243ab3d5/updateengine/client.go#L86-L102
5,331
coreos/locksmith
updateengine/client.go
GetStatus
func (c *Client) GetStatus() (result Status, err error) { call := c.object.Call(dbusInterface+".GetStatus", 0) err = call.Err if err != nil { return } result = NewStatus(call.Body) return }
go
func (c *Client) GetStatus() (result Status, err error) { call := c.object.Call(dbusInterface+".GetStatus", 0) err = call.Err if err != nil { return } result = NewStatus(call.Body) return }
[ "func", "(", "c", "*", "Client", ")", "GetStatus", "(", ")", "(", "result", "Status", ",", "err", "error", ")", "{", "call", ":=", "c", ".", "object", ".", "Call", "(", "dbusInterface", "+", "\"", "\"", ",", "0", ")", "\n", "err", "=", "call", ".", "Err", "\n", "if", "err", "!=", "nil", "{", "return", "\n", "}", "\n\n", "result", "=", "NewStatus", "(", "call", ".", "Body", ")", "\n\n", "return", "\n", "}" ]
// GetStatus returns the current status of updateengine // it returns an error if there is a problem getting the status from dbus
[ "GetStatus", "returns", "the", "current", "status", "of", "updateengine", "it", "returns", "an", "error", "if", "there", "is", "a", "problem", "getting", "the", "status", "from", "dbus" ]
ba572048b6baf84b4488656ca4f8b115243ab3d5
https://github.com/coreos/locksmith/blob/ba572048b6baf84b4488656ca4f8b115243ab3d5/updateengine/client.go#L106-L116
5,332
coreos/locksmith
lock/etcd.go
NewEtcdLockClient
func NewEtcdLockClient(keyapi KeysAPI, group string) (*EtcdLockClient, error) { key := SemaphorePrefix if group != "" { key = path.Join(keyPrefix, groupBranch, url.QueryEscape(group), semaphoreBranch) } elc := &EtcdLockClient{keyapi, key} if err := elc.Init(); err != nil { return nil, err } return elc, nil }
go
func NewEtcdLockClient(keyapi KeysAPI, group string) (*EtcdLockClient, error) { key := SemaphorePrefix if group != "" { key = path.Join(keyPrefix, groupBranch, url.QueryEscape(group), semaphoreBranch) } elc := &EtcdLockClient{keyapi, key} if err := elc.Init(); err != nil { return nil, err } return elc, nil }
[ "func", "NewEtcdLockClient", "(", "keyapi", "KeysAPI", ",", "group", "string", ")", "(", "*", "EtcdLockClient", ",", "error", ")", "{", "key", ":=", "SemaphorePrefix", "\n", "if", "group", "!=", "\"", "\"", "{", "key", "=", "path", ".", "Join", "(", "keyPrefix", ",", "groupBranch", ",", "url", ".", "QueryEscape", "(", "group", ")", ",", "semaphoreBranch", ")", "\n", "}", "\n\n", "elc", ":=", "&", "EtcdLockClient", "{", "keyapi", ",", "key", "}", "\n", "if", "err", ":=", "elc", ".", "Init", "(", ")", ";", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n\n", "return", "elc", ",", "nil", "\n", "}" ]
// NewEtcdLockClient creates a new EtcdLockClient. The group parameter defines // the etcd key path in which the client will manipulate the semaphore. If the // group is the empty string, the default semaphore will be used.
[ "NewEtcdLockClient", "creates", "a", "new", "EtcdLockClient", ".", "The", "group", "parameter", "defines", "the", "etcd", "key", "path", "in", "which", "the", "client", "will", "manipulate", "the", "semaphore", ".", "If", "the", "group", "is", "the", "empty", "string", "the", "default", "semaphore", "will", "be", "used", "." ]
ba572048b6baf84b4488656ca4f8b115243ab3d5
https://github.com/coreos/locksmith/blob/ba572048b6baf84b4488656ca4f8b115243ab3d5/lock/etcd.go#L55-L67
5,333
coreos/locksmith
lock/etcd.go
Init
func (c *EtcdLockClient) Init() error { sem := newSemaphore() b, err := json.Marshal(sem) if err != nil { return err } if _, err := c.keyapi.Create(context.Background(), c.keypath, string(b)); err != nil { eerr, ok := err.(client.Error) if ok && eerr.Code == client.ErrorCodeNodeExist { return nil } return err } return nil }
go
func (c *EtcdLockClient) Init() error { sem := newSemaphore() b, err := json.Marshal(sem) if err != nil { return err } if _, err := c.keyapi.Create(context.Background(), c.keypath, string(b)); err != nil { eerr, ok := err.(client.Error) if ok && eerr.Code == client.ErrorCodeNodeExist { return nil } return err } return nil }
[ "func", "(", "c", "*", "EtcdLockClient", ")", "Init", "(", ")", "error", "{", "sem", ":=", "newSemaphore", "(", ")", "\n", "b", ",", "err", ":=", "json", ".", "Marshal", "(", "sem", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n\n", "if", "_", ",", "err", ":=", "c", ".", "keyapi", ".", "Create", "(", "context", ".", "Background", "(", ")", ",", "c", ".", "keypath", ",", "string", "(", "b", ")", ")", ";", "err", "!=", "nil", "{", "eerr", ",", "ok", ":=", "err", ".", "(", "client", ".", "Error", ")", "\n", "if", "ok", "&&", "eerr", ".", "Code", "==", "client", ".", "ErrorCodeNodeExist", "{", "return", "nil", "\n", "}", "\n\n", "return", "err", "\n", "}", "\n\n", "return", "nil", "\n", "}" ]
// Init sets an initial copy of the semaphore if it doesn't exist yet.
[ "Init", "sets", "an", "initial", "copy", "of", "the", "semaphore", "if", "it", "doesn", "t", "exist", "yet", "." ]
ba572048b6baf84b4488656ca4f8b115243ab3d5
https://github.com/coreos/locksmith/blob/ba572048b6baf84b4488656ca4f8b115243ab3d5/lock/etcd.go#L70-L87
5,334
coreos/locksmith
lock/etcd.go
Get
func (c *EtcdLockClient) Get() (*Semaphore, error) { resp, err := c.keyapi.Get(context.Background(), c.keypath, nil) if err != nil { return nil, err } sem := &Semaphore{} err = json.Unmarshal([]byte(resp.Node.Value), sem) if err != nil { return nil, err } sem.Index = resp.Node.ModifiedIndex return sem, nil }
go
func (c *EtcdLockClient) Get() (*Semaphore, error) { resp, err := c.keyapi.Get(context.Background(), c.keypath, nil) if err != nil { return nil, err } sem := &Semaphore{} err = json.Unmarshal([]byte(resp.Node.Value), sem) if err != nil { return nil, err } sem.Index = resp.Node.ModifiedIndex return sem, nil }
[ "func", "(", "c", "*", "EtcdLockClient", ")", "Get", "(", ")", "(", "*", "Semaphore", ",", "error", ")", "{", "resp", ",", "err", ":=", "c", ".", "keyapi", ".", "Get", "(", "context", ".", "Background", "(", ")", ",", "c", ".", "keypath", ",", "nil", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n\n", "sem", ":=", "&", "Semaphore", "{", "}", "\n", "err", "=", "json", ".", "Unmarshal", "(", "[", "]", "byte", "(", "resp", ".", "Node", ".", "Value", ")", ",", "sem", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n\n", "sem", ".", "Index", "=", "resp", ".", "Node", ".", "ModifiedIndex", "\n\n", "return", "sem", ",", "nil", "\n", "}" ]
// Get fetches the Semaphore from etcd.
[ "Get", "fetches", "the", "Semaphore", "from", "etcd", "." ]
ba572048b6baf84b4488656ca4f8b115243ab3d5
https://github.com/coreos/locksmith/blob/ba572048b6baf84b4488656ca4f8b115243ab3d5/lock/etcd.go#L90-L105
5,335
coreos/locksmith
lock/etcd.go
Set
func (c *EtcdLockClient) Set(sem *Semaphore) error { if sem == nil { return errors.New("cannot set nil semaphore") } b, err := json.Marshal(sem) if err != nil { return err } setopts := &client.SetOptions{ PrevIndex: sem.Index, } _, err = c.keyapi.Set(context.Background(), c.keypath, string(b), setopts) return err }
go
func (c *EtcdLockClient) Set(sem *Semaphore) error { if sem == nil { return errors.New("cannot set nil semaphore") } b, err := json.Marshal(sem) if err != nil { return err } setopts := &client.SetOptions{ PrevIndex: sem.Index, } _, err = c.keyapi.Set(context.Background(), c.keypath, string(b), setopts) return err }
[ "func", "(", "c", "*", "EtcdLockClient", ")", "Set", "(", "sem", "*", "Semaphore", ")", "error", "{", "if", "sem", "==", "nil", "{", "return", "errors", ".", "New", "(", "\"", "\"", ")", "\n", "}", "\n", "b", ",", "err", ":=", "json", ".", "Marshal", "(", "sem", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n\n", "setopts", ":=", "&", "client", ".", "SetOptions", "{", "PrevIndex", ":", "sem", ".", "Index", ",", "}", "\n\n", "_", ",", "err", "=", "c", ".", "keyapi", ".", "Set", "(", "context", ".", "Background", "(", ")", ",", "c", ".", "keypath", ",", "string", "(", "b", ")", ",", "setopts", ")", "\n", "return", "err", "\n", "}" ]
// Set sets a Semaphore in etcd.
[ "Set", "sets", "a", "Semaphore", "in", "etcd", "." ]
ba572048b6baf84b4488656ca4f8b115243ab3d5
https://github.com/coreos/locksmith/blob/ba572048b6baf84b4488656ca4f8b115243ab3d5/lock/etcd.go#L108-L123
5,336
coreos/locksmith
pkg/timeutil/periodic.go
ParsePeriodic
func ParsePeriodic(start, duration string) (*Periodic, error) { var err error pc := &Periodic{} if pc.start, err = parseStart(start); err != nil { return nil, fmt.Errorf("unable to parse start: %v", err) } if pc.duration, err = time.ParseDuration(duration); err != nil { return nil, fmt.Errorf("unable to parse duration: %v", err) } if pc.duration < time.Duration(0) { return nil, fmt.Errorf("duration cannot be negative") } // check that the duration of the window does not exceed the period. if (pc.start.dayOfWeek == -1 && pc.duration >= 24*time.Hour) || pc.duration >= 7*24*time.Hour { return nil, fmt.Errorf("duration cannot exceed period") } return pc, nil }
go
func ParsePeriodic(start, duration string) (*Periodic, error) { var err error pc := &Periodic{} if pc.start, err = parseStart(start); err != nil { return nil, fmt.Errorf("unable to parse start: %v", err) } if pc.duration, err = time.ParseDuration(duration); err != nil { return nil, fmt.Errorf("unable to parse duration: %v", err) } if pc.duration < time.Duration(0) { return nil, fmt.Errorf("duration cannot be negative") } // check that the duration of the window does not exceed the period. if (pc.start.dayOfWeek == -1 && pc.duration >= 24*time.Hour) || pc.duration >= 7*24*time.Hour { return nil, fmt.Errorf("duration cannot exceed period") } return pc, nil }
[ "func", "ParsePeriodic", "(", "start", ",", "duration", "string", ")", "(", "*", "Periodic", ",", "error", ")", "{", "var", "err", "error", "\n\n", "pc", ":=", "&", "Periodic", "{", "}", "\n\n", "if", "pc", ".", "start", ",", "err", "=", "parseStart", "(", "start", ")", ";", "err", "!=", "nil", "{", "return", "nil", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "err", ")", "\n", "}", "\n\n", "if", "pc", ".", "duration", ",", "err", "=", "time", ".", "ParseDuration", "(", "duration", ")", ";", "err", "!=", "nil", "{", "return", "nil", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "err", ")", "\n", "}", "\n\n", "if", "pc", ".", "duration", "<", "time", ".", "Duration", "(", "0", ")", "{", "return", "nil", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ")", "\n", "}", "\n\n", "// check that the duration of the window does not exceed the period.", "if", "(", "pc", ".", "start", ".", "dayOfWeek", "==", "-", "1", "&&", "pc", ".", "duration", ">=", "24", "*", "time", ".", "Hour", ")", "||", "pc", ".", "duration", ">=", "7", "*", "24", "*", "time", ".", "Hour", "{", "return", "nil", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ")", "\n", "}", "\n\n", "return", "pc", ",", "nil", "\n", "}" ]
// ParsePeriodic returns a Periodic specified as a start and duration.
[ "ParsePeriodic", "returns", "a", "Periodic", "specified", "as", "a", "start", "and", "duration", "." ]
ba572048b6baf84b4488656ca4f8b115243ab3d5
https://github.com/coreos/locksmith/blob/ba572048b6baf84b4488656ca4f8b115243ab3d5/pkg/timeutil/periodic.go#L43-L66
5,337
coreos/locksmith
pkg/timeutil/periodic.go
parseStart
func parseStart(start string) (*periodicStart, error) { ps := &periodicStart{} ps.dayOfWeek = -1 f := strings.Fields(start) switch len(f) { case 1: // no day provided case 2: if dow, ok := weekdays[strings.ToLower(f[0])]; ok { ps.dayOfWeek = dow } else { return nil, fmt.Errorf("invalid day of week %q", f[0]) } // shift f = f[1:] default: return nil, fmt.Errorf("wrong number of fields") } n, err := fmt.Sscanf(f[0], "%d:%d", &ps.hourOfDay, &ps.minuteOfHour) // check Sscanf failure if n != 2 || err != nil { return nil, fmt.Errorf("invalid time of day %q: %v", f[0], err) } // check hour range if ps.hourOfDay < 0 || ps.hourOfDay > 23 { return nil, fmt.Errorf("invalid time of day %q: hour must be >= 0 and <= 23", f[0]) } // check minute range if ps.minuteOfHour < 0 || ps.minuteOfHour > 59 { return nil, fmt.Errorf("invalid time of day %q: minute must be >= 0 and <= 59", f[0]) } return ps, nil }
go
func parseStart(start string) (*periodicStart, error) { ps := &periodicStart{} ps.dayOfWeek = -1 f := strings.Fields(start) switch len(f) { case 1: // no day provided case 2: if dow, ok := weekdays[strings.ToLower(f[0])]; ok { ps.dayOfWeek = dow } else { return nil, fmt.Errorf("invalid day of week %q", f[0]) } // shift f = f[1:] default: return nil, fmt.Errorf("wrong number of fields") } n, err := fmt.Sscanf(f[0], "%d:%d", &ps.hourOfDay, &ps.minuteOfHour) // check Sscanf failure if n != 2 || err != nil { return nil, fmt.Errorf("invalid time of day %q: %v", f[0], err) } // check hour range if ps.hourOfDay < 0 || ps.hourOfDay > 23 { return nil, fmt.Errorf("invalid time of day %q: hour must be >= 0 and <= 23", f[0]) } // check minute range if ps.minuteOfHour < 0 || ps.minuteOfHour > 59 { return nil, fmt.Errorf("invalid time of day %q: minute must be >= 0 and <= 59", f[0]) } return ps, nil }
[ "func", "parseStart", "(", "start", "string", ")", "(", "*", "periodicStart", ",", "error", ")", "{", "ps", ":=", "&", "periodicStart", "{", "}", "\n", "ps", ".", "dayOfWeek", "=", "-", "1", "\n", "f", ":=", "strings", ".", "Fields", "(", "start", ")", "\n\n", "switch", "len", "(", "f", ")", "{", "case", "1", ":", "// no day provided", "case", "2", ":", "if", "dow", ",", "ok", ":=", "weekdays", "[", "strings", ".", "ToLower", "(", "f", "[", "0", "]", ")", "]", ";", "ok", "{", "ps", ".", "dayOfWeek", "=", "dow", "\n", "}", "else", "{", "return", "nil", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "f", "[", "0", "]", ")", "\n", "}", "\n", "// shift", "f", "=", "f", "[", "1", ":", "]", "\n", "default", ":", "return", "nil", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ")", "\n", "}", "\n\n", "n", ",", "err", ":=", "fmt", ".", "Sscanf", "(", "f", "[", "0", "]", ",", "\"", "\"", ",", "&", "ps", ".", "hourOfDay", ",", "&", "ps", ".", "minuteOfHour", ")", "\n\n", "// check Sscanf failure", "if", "n", "!=", "2", "||", "err", "!=", "nil", "{", "return", "nil", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "f", "[", "0", "]", ",", "err", ")", "\n", "}", "\n\n", "// check hour range", "if", "ps", ".", "hourOfDay", "<", "0", "||", "ps", ".", "hourOfDay", ">", "23", "{", "return", "nil", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "f", "[", "0", "]", ")", "\n", "}", "\n\n", "// check minute range", "if", "ps", ".", "minuteOfHour", "<", "0", "||", "ps", ".", "minuteOfHour", ">", "59", "{", "return", "nil", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "f", "[", "0", "]", ")", "\n", "}", "\n\n", "return", "ps", ",", "nil", "\n", "}" ]
// parseStart parses a string into a periodicStart.
[ "parseStart", "parses", "a", "string", "into", "a", "periodicStart", "." ]
ba572048b6baf84b4488656ca4f8b115243ab3d5
https://github.com/coreos/locksmith/blob/ba572048b6baf84b4488656ca4f8b115243ab3d5/pkg/timeutil/periodic.go#L79-L116
5,338
coreos/locksmith
pkg/timeutil/periodic.go
Previous
func (pc *Periodic) Previous(ref time.Time) (p *Period) { p = &Period{} if pc.start.dayOfWeek != -1 { // Weekly if pc.cmpDayOfWeek(ref) >= 0 { // this week p.Start = pc.shiftTimeByDays(ref, -(int(ref.Weekday()) - pc.start.dayOfWeek)) } else { // last week p.Start = pc.shiftTimeByDays(ref, -(int(ref.Weekday()) + (7 - pc.start.dayOfWeek))) } } else if pc.start.hourOfDay != -1 { // Daily if pc.cmpHourOfDay(ref) >= 0 { // today p.Start = pc.shiftTimeByDays(ref, 0) } else { // yesterday p.Start = pc.shiftTimeByDays(ref, -1) } } // XXX(mischief): other intervals unsupported atm. p.End = p.Start.Add(pc.duration) return }
go
func (pc *Periodic) Previous(ref time.Time) (p *Period) { p = &Period{} if pc.start.dayOfWeek != -1 { // Weekly if pc.cmpDayOfWeek(ref) >= 0 { // this week p.Start = pc.shiftTimeByDays(ref, -(int(ref.Weekday()) - pc.start.dayOfWeek)) } else { // last week p.Start = pc.shiftTimeByDays(ref, -(int(ref.Weekday()) + (7 - pc.start.dayOfWeek))) } } else if pc.start.hourOfDay != -1 { // Daily if pc.cmpHourOfDay(ref) >= 0 { // today p.Start = pc.shiftTimeByDays(ref, 0) } else { // yesterday p.Start = pc.shiftTimeByDays(ref, -1) } } // XXX(mischief): other intervals unsupported atm. p.End = p.Start.Add(pc.duration) return }
[ "func", "(", "pc", "*", "Periodic", ")", "Previous", "(", "ref", "time", ".", "Time", ")", "(", "p", "*", "Period", ")", "{", "p", "=", "&", "Period", "{", "}", "\n", "if", "pc", ".", "start", ".", "dayOfWeek", "!=", "-", "1", "{", "// Weekly", "if", "pc", ".", "cmpDayOfWeek", "(", "ref", ")", ">=", "0", "{", "// this week", "p", ".", "Start", "=", "pc", ".", "shiftTimeByDays", "(", "ref", ",", "-", "(", "int", "(", "ref", ".", "Weekday", "(", ")", ")", "-", "pc", ".", "start", ".", "dayOfWeek", ")", ")", "\n", "}", "else", "{", "// last week", "p", ".", "Start", "=", "pc", ".", "shiftTimeByDays", "(", "ref", ",", "-", "(", "int", "(", "ref", ".", "Weekday", "(", ")", ")", "+", "(", "7", "-", "pc", ".", "start", ".", "dayOfWeek", ")", ")", ")", "\n", "}", "\n", "}", "else", "if", "pc", ".", "start", ".", "hourOfDay", "!=", "-", "1", "{", "// Daily", "if", "pc", ".", "cmpHourOfDay", "(", "ref", ")", ">=", "0", "{", "// today", "p", ".", "Start", "=", "pc", ".", "shiftTimeByDays", "(", "ref", ",", "0", ")", "\n", "}", "else", "{", "// yesterday", "p", ".", "Start", "=", "pc", ".", "shiftTimeByDays", "(", "ref", ",", "-", "1", ")", "\n", "}", "\n", "}", "// XXX(mischief): other intervals unsupported atm.", "\n\n", "p", ".", "End", "=", "p", ".", "Start", ".", "Add", "(", "pc", ".", "duration", ")", "\n", "return", "\n", "}" ]
// Previous returns Periodic's previous Period occurrence relative to ref.
[ "Previous", "returns", "Periodic", "s", "previous", "Period", "occurrence", "relative", "to", "ref", "." ]
ba572048b6baf84b4488656ca4f8b115243ab3d5
https://github.com/coreos/locksmith/blob/ba572048b6baf84b4488656ca4f8b115243ab3d5/pkg/timeutil/periodic.go#L145-L167
5,339
coreos/locksmith
pkg/timeutil/periodic.go
cmpDayOfWeek
func (pc *Periodic) cmpDayOfWeek(ref time.Time) time.Duration { pStart := pc.shiftTimeByDays(ref, -int(ref.Weekday())+pc.start.dayOfWeek) return ref.Sub(pStart) }
go
func (pc *Periodic) cmpDayOfWeek(ref time.Time) time.Duration { pStart := pc.shiftTimeByDays(ref, -int(ref.Weekday())+pc.start.dayOfWeek) return ref.Sub(pStart) }
[ "func", "(", "pc", "*", "Periodic", ")", "cmpDayOfWeek", "(", "ref", "time", ".", "Time", ")", "time", ".", "Duration", "{", "pStart", ":=", "pc", ".", "shiftTimeByDays", "(", "ref", ",", "-", "int", "(", "ref", ".", "Weekday", "(", ")", ")", "+", "pc", ".", "start", ".", "dayOfWeek", ")", "\n", "return", "ref", ".", "Sub", "(", "pStart", ")", "\n", "}" ]
// cmpDayOfWeek compares ref to Periodic occurring in the same week as ref. // The return value is less than, equal to, or greater than zero if ref occurs // before, equal to, or after the start of Periodic within the same week.
[ "cmpDayOfWeek", "compares", "ref", "to", "Periodic", "occurring", "in", "the", "same", "week", "as", "ref", ".", "The", "return", "value", "is", "less", "than", "equal", "to", "or", "greater", "than", "zero", "if", "ref", "occurs", "before", "equal", "to", "or", "after", "the", "start", "of", "Periodic", "within", "the", "same", "week", "." ]
ba572048b6baf84b4488656ca4f8b115243ab3d5
https://github.com/coreos/locksmith/blob/ba572048b6baf84b4488656ca4f8b115243ab3d5/pkg/timeutil/periodic.go#L197-L200
5,340
coreos/locksmith
pkg/timeutil/periodic.go
cmpHourOfDay
func (pc *Periodic) cmpHourOfDay(ref time.Time) time.Duration { pStart := pc.shiftTimeByDays(ref, 0) return ref.Sub(pStart) }
go
func (pc *Periodic) cmpHourOfDay(ref time.Time) time.Duration { pStart := pc.shiftTimeByDays(ref, 0) return ref.Sub(pStart) }
[ "func", "(", "pc", "*", "Periodic", ")", "cmpHourOfDay", "(", "ref", "time", ".", "Time", ")", "time", ".", "Duration", "{", "pStart", ":=", "pc", ".", "shiftTimeByDays", "(", "ref", ",", "0", ")", "\n", "return", "ref", ".", "Sub", "(", "pStart", ")", "\n", "}" ]
// cmpHourOfDay compares ref to Periodic occurring in the same day as ref. // The return value is less than, equal to, or greater than zero if ref occurs // before, equal to, or after the start of Periodic in the same day.
[ "cmpHourOfDay", "compares", "ref", "to", "Periodic", "occurring", "in", "the", "same", "day", "as", "ref", ".", "The", "return", "value", "is", "less", "than", "equal", "to", "or", "greater", "than", "zero", "if", "ref", "occurs", "before", "equal", "to", "or", "after", "the", "start", "of", "Periodic", "in", "the", "same", "day", "." ]
ba572048b6baf84b4488656ca4f8b115243ab3d5
https://github.com/coreos/locksmith/blob/ba572048b6baf84b4488656ca4f8b115243ab3d5/pkg/timeutil/periodic.go#L205-L208
5,341
coreos/locksmith
updateengine/status.go
NewStatus
func NewStatus(body []interface{}) (s Status) { s.LastCheckedTime = body[0].(int64) s.Progress = body[1].(float64) s.CurrentOperation = body[2].(string) s.NewVersion = body[3].(string) s.NewSize = body[4].(int64) return }
go
func NewStatus(body []interface{}) (s Status) { s.LastCheckedTime = body[0].(int64) s.Progress = body[1].(float64) s.CurrentOperation = body[2].(string) s.NewVersion = body[3].(string) s.NewSize = body[4].(int64) return }
[ "func", "NewStatus", "(", "body", "[", "]", "interface", "{", "}", ")", "(", "s", "Status", ")", "{", "s", ".", "LastCheckedTime", "=", "body", "[", "0", "]", ".", "(", "int64", ")", "\n", "s", ".", "Progress", "=", "body", "[", "1", "]", ".", "(", "float64", ")", "\n", "s", ".", "CurrentOperation", "=", "body", "[", "2", "]", ".", "(", "string", ")", "\n", "s", ".", "NewVersion", "=", "body", "[", "3", "]", ".", "(", "string", ")", "\n", "s", ".", "NewSize", "=", "body", "[", "4", "]", ".", "(", "int64", ")", "\n\n", "return", "\n", "}" ]
// NewStatus creates a new status from a list of fields. // this function will panic at runtime if there are less than five elements in // the provided list, or if they are not typed int64, float64, string, string, // int64 respectively.
[ "NewStatus", "creates", "a", "new", "status", "from", "a", "list", "of", "fields", ".", "this", "function", "will", "panic", "at", "runtime", "if", "there", "are", "less", "than", "five", "elements", "in", "the", "provided", "list", "or", "if", "they", "are", "not", "typed", "int64", "float64", "string", "string", "int64", "respectively", "." ]
ba572048b6baf84b4488656ca4f8b115243ab3d5
https://github.com/coreos/locksmith/blob/ba572048b6baf84b4488656ca4f8b115243ab3d5/updateengine/status.go#L86-L94
5,342
coreos/locksmith
updateengine/status.go
String
func (s *Status) String() string { return fmt.Sprintf("LastCheckedTime=%v Progress=%v CurrentOperation=%q NewVersion=%v NewSize=%v", s.LastCheckedTime, s.Progress, s.CurrentOperation, s.NewVersion, s.NewSize, ) }
go
func (s *Status) String() string { return fmt.Sprintf("LastCheckedTime=%v Progress=%v CurrentOperation=%q NewVersion=%v NewSize=%v", s.LastCheckedTime, s.Progress, s.CurrentOperation, s.NewVersion, s.NewSize, ) }
[ "func", "(", "s", "*", "Status", ")", "String", "(", ")", "string", "{", "return", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "s", ".", "LastCheckedTime", ",", "s", ".", "Progress", ",", "s", ".", "CurrentOperation", ",", "s", ".", "NewVersion", ",", "s", ".", "NewSize", ",", ")", "\n", "}" ]
// String returns a string representation of the Status struct. // It is of the form // "LastCheckedTime=%v Progress=%v CurrentOperation=%q NewVersion=%v NewSize=%v"
[ "String", "returns", "a", "string", "representation", "of", "the", "Status", "struct", ".", "It", "is", "of", "the", "form", "LastCheckedTime", "=", "%v", "Progress", "=", "%v", "CurrentOperation", "=", "%q", "NewVersion", "=", "%v", "NewSize", "=", "%v" ]
ba572048b6baf84b4488656ca4f8b115243ab3d5
https://github.com/coreos/locksmith/blob/ba572048b6baf84b4488656ca4f8b115243ab3d5/updateengine/status.go#L99-L107
5,343
coreos/locksmith
lock/lock.go
New
func New(id string, client LockClient) (lock *Lock) { return &Lock{id, client} }
go
func New(id string, client LockClient) (lock *Lock) { return &Lock{id, client} }
[ "func", "New", "(", "id", "string", ",", "client", "LockClient", ")", "(", "lock", "*", "Lock", ")", "{", "return", "&", "Lock", "{", "id", ",", "client", "}", "\n", "}" ]
// New returns a new lock with the provided arguments
[ "New", "returns", "a", "new", "lock", "with", "the", "provided", "arguments" ]
ba572048b6baf84b4488656ca4f8b115243ab3d5
https://github.com/coreos/locksmith/blob/ba572048b6baf84b4488656ca4f8b115243ab3d5/lock/lock.go#L24-L26
5,344
coreos/locksmith
lock/lock.go
Get
func (l *Lock) Get() (sem *Semaphore, err error) { sem, err = l.client.Get() if err != nil { return nil, err } return sem, nil }
go
func (l *Lock) Get() (sem *Semaphore, err error) { sem, err = l.client.Get() if err != nil { return nil, err } return sem, nil }
[ "func", "(", "l", "*", "Lock", ")", "Get", "(", ")", "(", "sem", "*", "Semaphore", ",", "err", "error", ")", "{", "sem", ",", "err", "=", "l", ".", "client", ".", "Get", "(", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n\n", "return", "sem", ",", "nil", "\n", "}" ]
// Get returns the current semaphore value // if the underlying client returns an error, Get passes it through
[ "Get", "returns", "the", "current", "semaphore", "value", "if", "the", "underlying", "client", "returns", "an", "error", "Get", "passes", "it", "through" ]
ba572048b6baf84b4488656ca4f8b115243ab3d5
https://github.com/coreos/locksmith/blob/ba572048b6baf84b4488656ca4f8b115243ab3d5/lock/lock.go#L48-L55
5,345
coreos/locksmith
lock/lock.go
SetMax
func (l *Lock) SetMax(max int) (sem *Semaphore, oldMax int, err error) { var ( semRet *Semaphore old int ) return semRet, old, l.store(func(sem *Semaphore) error { old = sem.Max semRet = sem return sem.SetMax(max) }) }
go
func (l *Lock) SetMax(max int) (sem *Semaphore, oldMax int, err error) { var ( semRet *Semaphore old int ) return semRet, old, l.store(func(sem *Semaphore) error { old = sem.Max semRet = sem return sem.SetMax(max) }) }
[ "func", "(", "l", "*", "Lock", ")", "SetMax", "(", "max", "int", ")", "(", "sem", "*", "Semaphore", ",", "oldMax", "int", ",", "err", "error", ")", "{", "var", "(", "semRet", "*", "Semaphore", "\n", "old", "int", "\n", ")", "\n\n", "return", "semRet", ",", "old", ",", "l", ".", "store", "(", "func", "(", "sem", "*", "Semaphore", ")", "error", "{", "old", "=", "sem", ".", "Max", "\n", "semRet", "=", "sem", "\n", "return", "sem", ".", "SetMax", "(", "max", ")", "\n", "}", ")", "\n", "}" ]
// SetMax sets the maximum number of holders the semaphore will allow // it returns the current semaphore and the previous maximum // if there is a problem getting or setting the semaphore, this function will // pass on errors from the underlying client
[ "SetMax", "sets", "the", "maximum", "number", "of", "holders", "the", "semaphore", "will", "allow", "it", "returns", "the", "current", "semaphore", "and", "the", "previous", "maximum", "if", "there", "is", "a", "problem", "getting", "or", "setting", "the", "semaphore", "this", "function", "will", "pass", "on", "errors", "from", "the", "underlying", "client" ]
ba572048b6baf84b4488656ca4f8b115243ab3d5
https://github.com/coreos/locksmith/blob/ba572048b6baf84b4488656ca4f8b115243ab3d5/lock/lock.go#L61-L72
5,346
coreos/locksmith
lock/lock.go
Lock
func (l *Lock) Lock() (err error) { return l.store(func(sem *Semaphore) error { return sem.Lock(l.id) }) }
go
func (l *Lock) Lock() (err error) { return l.store(func(sem *Semaphore) error { return sem.Lock(l.id) }) }
[ "func", "(", "l", "*", "Lock", ")", "Lock", "(", ")", "(", "err", "error", ")", "{", "return", "l", ".", "store", "(", "func", "(", "sem", "*", "Semaphore", ")", "error", "{", "return", "sem", ".", "Lock", "(", "l", ".", "id", ")", "\n", "}", ")", "\n", "}" ]
// Lock adds this lock id as a holder to the semaphore // it will return an error if there is a problem getting or setting the // semaphore, or if the maximum number of holders has been reached, or if a lock // with this id is already a holder
[ "Lock", "adds", "this", "lock", "id", "as", "a", "holder", "to", "the", "semaphore", "it", "will", "return", "an", "error", "if", "there", "is", "a", "problem", "getting", "or", "setting", "the", "semaphore", "or", "if", "the", "maximum", "number", "of", "holders", "has", "been", "reached", "or", "if", "a", "lock", "with", "this", "id", "is", "already", "a", "holder" ]
ba572048b6baf84b4488656ca4f8b115243ab3d5
https://github.com/coreos/locksmith/blob/ba572048b6baf84b4488656ca4f8b115243ab3d5/lock/lock.go#L78-L82
5,347
coreos/locksmith
lock/lock.go
Unlock
func (l *Lock) Unlock() error { return l.store(func(sem *Semaphore) error { return sem.Unlock(l.id) }) }
go
func (l *Lock) Unlock() error { return l.store(func(sem *Semaphore) error { return sem.Unlock(l.id) }) }
[ "func", "(", "l", "*", "Lock", ")", "Unlock", "(", ")", "error", "{", "return", "l", ".", "store", "(", "func", "(", "sem", "*", "Semaphore", ")", "error", "{", "return", "sem", ".", "Unlock", "(", "l", ".", "id", ")", "\n", "}", ")", "\n", "}" ]
// Unlock removes this lock id as a holder of the semaphore // it returns an error if there is a problem getting or setting the semaphore, // or if this lock is not locked.
[ "Unlock", "removes", "this", "lock", "id", "as", "a", "holder", "of", "the", "semaphore", "it", "returns", "an", "error", "if", "there", "is", "a", "problem", "getting", "or", "setting", "the", "semaphore", "or", "if", "this", "lock", "is", "not", "locked", "." ]
ba572048b6baf84b4488656ca4f8b115243ab3d5
https://github.com/coreos/locksmith/blob/ba572048b6baf84b4488656ca4f8b115243ab3d5/lock/lock.go#L87-L91
5,348
coreos/locksmith
pkg/filelock/filelock.go
NewExclusiveLock
func NewExclusiveLock(path string) (*UpdateableFileLock, error) { flock, err := lock.TryExclusiveLock(path, lock.RegFile) if err != nil { return nil, err } fi, err := os.Stat(path) if err != nil { return nil, err } // Note: if we expected the file to ever be deleted and recreated while an // ExLock isn't held, we would have to check the fd is still correct here. // However, the file is created once and never deleted outside of the safely // handled renames in this package, so it's safe to assume the fd hasn't // changed. // The rename call in this package is "safe" because it leaves no window // where the file at that path does not have an exclusive lock return &UpdateableFileLock{ lock: flock, path: path, isLocked: true, perms: fi.Mode(), }, nil }
go
func NewExclusiveLock(path string) (*UpdateableFileLock, error) { flock, err := lock.TryExclusiveLock(path, lock.RegFile) if err != nil { return nil, err } fi, err := os.Stat(path) if err != nil { return nil, err } // Note: if we expected the file to ever be deleted and recreated while an // ExLock isn't held, we would have to check the fd is still correct here. // However, the file is created once and never deleted outside of the safely // handled renames in this package, so it's safe to assume the fd hasn't // changed. // The rename call in this package is "safe" because it leaves no window // where the file at that path does not have an exclusive lock return &UpdateableFileLock{ lock: flock, path: path, isLocked: true, perms: fi.Mode(), }, nil }
[ "func", "NewExclusiveLock", "(", "path", "string", ")", "(", "*", "UpdateableFileLock", ",", "error", ")", "{", "flock", ",", "err", ":=", "lock", ".", "TryExclusiveLock", "(", "path", ",", "lock", ".", "RegFile", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "fi", ",", "err", ":=", "os", ".", "Stat", "(", "path", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "// Note: if we expected the file to ever be deleted and recreated while an", "// ExLock isn't held, we would have to check the fd is still correct here.", "// However, the file is created once and never deleted outside of the safely", "// handled renames in this package, so it's safe to assume the fd hasn't", "// changed.", "// The rename call in this package is \"safe\" because it leaves no window", "// where the file at that path does not have an exclusive lock", "return", "&", "UpdateableFileLock", "{", "lock", ":", "flock", ",", "path", ":", "path", ",", "isLocked", ":", "true", ",", "perms", ":", "fi", ".", "Mode", "(", ")", ",", "}", ",", "nil", "\n", "}" ]
// NewExclusiveLock creates a new exclusive filelock. // The given filepath must exist.
[ "NewExclusiveLock", "creates", "a", "new", "exclusive", "filelock", ".", "The", "given", "filepath", "must", "exist", "." ]
ba572048b6baf84b4488656ca4f8b115243ab3d5
https://github.com/coreos/locksmith/blob/ba572048b6baf84b4488656ca4f8b115243ab3d5/pkg/filelock/filelock.go#L48-L70
5,349
coreos/locksmith
pkg/filelock/filelock.go
Update
func (l *UpdateableFileLock) Update(contents io.Reader) error { lockDir := filepath.Dir(l.path) newFile, err := ioutil.TempFile(lockDir, fmt.Sprintf(".%s", filepath.Base(l.path))) if err != nil { return err } defer newFile.Close() if err := newFile.Chmod(l.perms); err != nil { os.Remove(newFile.Name()) return err } _, err = io.Copy(newFile, contents) if err != nil { os.Remove(newFile.Name()) return err } newFileLock, err := lock.TryExclusiveLock(newFile.Name(), lock.RegFile) if err != nil { os.Remove(newFile.Name()) return fmt.Errorf("could not lock tmpfile: %v", err) } l.lockLock.Lock() defer l.lockLock.Unlock() if !l.isLocked { os.Remove(newFile.Name()) return AlreadyUnlockedErr } // Overwrite the old lock with our new one that has the correct contents err = os.Rename(newFile.Name(), l.path) if err != nil { return err } // Lock overwritten, update our internal state while we still hold the mutex oldLock := l.lock l.lock = newFileLock oldLock.Unlock() return nil }
go
func (l *UpdateableFileLock) Update(contents io.Reader) error { lockDir := filepath.Dir(l.path) newFile, err := ioutil.TempFile(lockDir, fmt.Sprintf(".%s", filepath.Base(l.path))) if err != nil { return err } defer newFile.Close() if err := newFile.Chmod(l.perms); err != nil { os.Remove(newFile.Name()) return err } _, err = io.Copy(newFile, contents) if err != nil { os.Remove(newFile.Name()) return err } newFileLock, err := lock.TryExclusiveLock(newFile.Name(), lock.RegFile) if err != nil { os.Remove(newFile.Name()) return fmt.Errorf("could not lock tmpfile: %v", err) } l.lockLock.Lock() defer l.lockLock.Unlock() if !l.isLocked { os.Remove(newFile.Name()) return AlreadyUnlockedErr } // Overwrite the old lock with our new one that has the correct contents err = os.Rename(newFile.Name(), l.path) if err != nil { return err } // Lock overwritten, update our internal state while we still hold the mutex oldLock := l.lock l.lock = newFileLock oldLock.Unlock() return nil }
[ "func", "(", "l", "*", "UpdateableFileLock", ")", "Update", "(", "contents", "io", ".", "Reader", ")", "error", "{", "lockDir", ":=", "filepath", ".", "Dir", "(", "l", ".", "path", ")", "\n", "newFile", ",", "err", ":=", "ioutil", ".", "TempFile", "(", "lockDir", ",", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "filepath", ".", "Base", "(", "l", ".", "path", ")", ")", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "defer", "newFile", ".", "Close", "(", ")", "\n", "if", "err", ":=", "newFile", ".", "Chmod", "(", "l", ".", "perms", ")", ";", "err", "!=", "nil", "{", "os", ".", "Remove", "(", "newFile", ".", "Name", "(", ")", ")", "\n", "return", "err", "\n", "}", "\n\n", "_", ",", "err", "=", "io", ".", "Copy", "(", "newFile", ",", "contents", ")", "\n", "if", "err", "!=", "nil", "{", "os", ".", "Remove", "(", "newFile", ".", "Name", "(", ")", ")", "\n", "return", "err", "\n", "}", "\n\n", "newFileLock", ",", "err", ":=", "lock", ".", "TryExclusiveLock", "(", "newFile", ".", "Name", "(", ")", ",", "lock", ".", "RegFile", ")", "\n", "if", "err", "!=", "nil", "{", "os", ".", "Remove", "(", "newFile", ".", "Name", "(", ")", ")", "\n", "return", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "err", ")", "\n", "}", "\n\n", "l", ".", "lockLock", ".", "Lock", "(", ")", "\n", "defer", "l", ".", "lockLock", ".", "Unlock", "(", ")", "\n\n", "if", "!", "l", ".", "isLocked", "{", "os", ".", "Remove", "(", "newFile", ".", "Name", "(", ")", ")", "\n", "return", "AlreadyUnlockedErr", "\n", "}", "\n", "// Overwrite the old lock with our new one that has the correct contents", "err", "=", "os", ".", "Rename", "(", "newFile", ".", "Name", "(", ")", ",", "l", ".", "path", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "// Lock overwritten, update our internal state while we still hold the mutex", "oldLock", ":=", "l", ".", "lock", "\n", "l", ".", "lock", "=", "newFileLock", "\n", "oldLock", ".", "Unlock", "(", ")", "\n", "return", "nil", "\n", "}" ]
// Update writes the given contents into the filelock atomically
[ "Update", "writes", "the", "given", "contents", "into", "the", "filelock", "atomically" ]
ba572048b6baf84b4488656ca4f8b115243ab3d5
https://github.com/coreos/locksmith/blob/ba572048b6baf84b4488656ca4f8b115243ab3d5/pkg/filelock/filelock.go#L73-L114
5,350
coreos/locksmith
pkg/filelock/filelock.go
Unlock
func (l *UpdateableFileLock) Unlock() error { l.lockLock.Lock() defer l.lockLock.Unlock() if !l.isLocked { return AlreadyUnlockedErr } l.isLocked = false return l.lock.Unlock() }
go
func (l *UpdateableFileLock) Unlock() error { l.lockLock.Lock() defer l.lockLock.Unlock() if !l.isLocked { return AlreadyUnlockedErr } l.isLocked = false return l.lock.Unlock() }
[ "func", "(", "l", "*", "UpdateableFileLock", ")", "Unlock", "(", ")", "error", "{", "l", ".", "lockLock", ".", "Lock", "(", ")", "\n", "defer", "l", ".", "lockLock", ".", "Unlock", "(", ")", "\n\n", "if", "!", "l", ".", "isLocked", "{", "return", "AlreadyUnlockedErr", "\n", "}", "\n", "l", ".", "isLocked", "=", "false", "\n", "return", "l", ".", "lock", ".", "Unlock", "(", ")", "\n", "}" ]
// Unlock unlocks the filelock
[ "Unlock", "unlocks", "the", "filelock" ]
ba572048b6baf84b4488656ca4f8b115243ab3d5
https://github.com/coreos/locksmith/blob/ba572048b6baf84b4488656ca4f8b115243ab3d5/pkg/filelock/filelock.go#L117-L126
5,351
coreos/locksmith
locksmithctl/daemon.go
lockAndReboot
func (r rebooter) lockAndReboot(lck *lock.Lock) { interval := initialInterval for { err := lck.Lock() if err != nil && err != lock.ErrExist { interval = expBackoff(interval) dlog.Warningf("Failed to acquire lock: %v. Retrying in %v.", err, interval) time.Sleep(interval) continue } r.rebootAndSleep() return } }
go
func (r rebooter) lockAndReboot(lck *lock.Lock) { interval := initialInterval for { err := lck.Lock() if err != nil && err != lock.ErrExist { interval = expBackoff(interval) dlog.Warningf("Failed to acquire lock: %v. Retrying in %v.", err, interval) time.Sleep(interval) continue } r.rebootAndSleep() return } }
[ "func", "(", "r", "rebooter", ")", "lockAndReboot", "(", "lck", "*", "lock", ".", "Lock", ")", "{", "interval", ":=", "initialInterval", "\n", "for", "{", "err", ":=", "lck", ".", "Lock", "(", ")", "\n", "if", "err", "!=", "nil", "&&", "err", "!=", "lock", ".", "ErrExist", "{", "interval", "=", "expBackoff", "(", "interval", ")", "\n", "dlog", ".", "Warningf", "(", "\"", "\"", ",", "err", ",", "interval", ")", "\n", "time", ".", "Sleep", "(", "interval", ")", "\n\n", "continue", "\n", "}", "\n\n", "r", ".", "rebootAndSleep", "(", ")", "\n", "return", "\n", "}", "\n", "}" ]
// lockAndReboot attempts to acquire the lock and reboot the machine in an // infinite loop. Returns if the reboot failed.
[ "lockAndReboot", "attempts", "to", "acquire", "the", "lock", "and", "reboot", "the", "machine", "in", "an", "infinite", "loop", ".", "Returns", "if", "the", "reboot", "failed", "." ]
ba572048b6baf84b4488656ca4f8b115243ab3d5
https://github.com/coreos/locksmith/blob/ba572048b6baf84b4488656ca4f8b115243ab3d5/locksmithctl/daemon.go#L139-L154
5,352
coreos/locksmith
locksmithctl/daemon.go
unlockIfHeld
func unlockIfHeld(lck *lock.Lock) error { err := lck.Unlock() if err == lock.ErrNotExist { return nil } else if err == nil { dlog.Info("Unlocked existing lock for this machine") return nil } return err }
go
func unlockIfHeld(lck *lock.Lock) error { err := lck.Unlock() if err == lock.ErrNotExist { return nil } else if err == nil { dlog.Info("Unlocked existing lock for this machine") return nil } return err }
[ "func", "unlockIfHeld", "(", "lck", "*", "lock", ".", "Lock", ")", "error", "{", "err", ":=", "lck", ".", "Unlock", "(", ")", "\n", "if", "err", "==", "lock", ".", "ErrNotExist", "{", "return", "nil", "\n", "}", "else", "if", "err", "==", "nil", "{", "dlog", ".", "Info", "(", "\"", "\"", ")", "\n", "return", "nil", "\n", "}", "\n\n", "return", "err", "\n", "}" ]
// unlockIfHeld will unlock a lock, if it is held by this machine, or return an error.
[ "unlockIfHeld", "will", "unlock", "a", "lock", "if", "it", "is", "held", "by", "this", "machine", "or", "return", "an", "error", "." ]
ba572048b6baf84b4488656ca4f8b115243ab3d5
https://github.com/coreos/locksmith/blob/ba572048b6baf84b4488656ca4f8b115243ab3d5/locksmithctl/daemon.go#L219-L229
5,353
coreos/locksmith
locksmithctl/daemon.go
unlockHeldLocks
func unlockHeldLocks(strategy string, stop chan struct{}, wg *sync.WaitGroup) { defer wg.Done() interval := initialInterval for { var reason string select { case <-stop: return case <-time.After(interval): lck, err := setupLock() if err != nil { reason = "error setting up lock: " + err.Error() break } err = unlockIfHeld(lck) if err == nil { return } reason = err.Error() } interval = expBackoff(interval) dlog.Errorf("Unlocking old locks failed: %v. Retrying in %v.", reason, interval) } }
go
func unlockHeldLocks(strategy string, stop chan struct{}, wg *sync.WaitGroup) { defer wg.Done() interval := initialInterval for { var reason string select { case <-stop: return case <-time.After(interval): lck, err := setupLock() if err != nil { reason = "error setting up lock: " + err.Error() break } err = unlockIfHeld(lck) if err == nil { return } reason = err.Error() } interval = expBackoff(interval) dlog.Errorf("Unlocking old locks failed: %v. Retrying in %v.", reason, interval) } }
[ "func", "unlockHeldLocks", "(", "strategy", "string", ",", "stop", "chan", "struct", "{", "}", ",", "wg", "*", "sync", ".", "WaitGroup", ")", "{", "defer", "wg", ".", "Done", "(", ")", "\n", "interval", ":=", "initialInterval", "\n", "for", "{", "var", "reason", "string", "\n", "select", "{", "case", "<-", "stop", ":", "return", "\n", "case", "<-", "time", ".", "After", "(", "interval", ")", ":", "lck", ",", "err", ":=", "setupLock", "(", ")", "\n", "if", "err", "!=", "nil", "{", "reason", "=", "\"", "\"", "+", "err", ".", "Error", "(", ")", "\n", "break", "\n", "}", "\n\n", "err", "=", "unlockIfHeld", "(", "lck", ")", "\n", "if", "err", "==", "nil", "{", "return", "\n", "}", "\n", "reason", "=", "err", ".", "Error", "(", ")", "\n", "}", "\n\n", "interval", "=", "expBackoff", "(", "interval", ")", "\n", "dlog", ".", "Errorf", "(", "\"", "\"", ",", "reason", ",", "interval", ")", "\n", "}", "\n", "}" ]
// unlockHeldLocks will loop until it can confirm that any held locks are // released or a stop signal is sent.
[ "unlockHeldLocks", "will", "loop", "until", "it", "can", "confirm", "that", "any", "held", "locks", "are", "released", "or", "a", "stop", "signal", "is", "sent", "." ]
ba572048b6baf84b4488656ca4f8b115243ab3d5
https://github.com/coreos/locksmith/blob/ba572048b6baf84b4488656ca4f8b115243ab3d5/locksmithctl/daemon.go#L233-L258
5,354
coreos/locksmith
pkg/coordinatorconf/conf.go
New
func New(name string, strategy string) (CoordinatorConfigUpdater, error) { // filelock expects that the file already exists. // Because this file will never be deleted, just blindly creating it on every // run is safe from racing with any deletions. Just create it, then get // locking. if err := os.MkdirAll(filepath.Dir(UpdateCoordinatorConfPath), 0755); err != nil { return nil, err } if file, err := os.OpenFile(UpdateCoordinatorConfPath, os.O_CREATE, 0644); err != nil { return nil, err } else { file.Close() } lock, err := filelock.NewExclusiveLock(UpdateCoordinatorConfPath) if err != nil { return nil, err } coordinator := &coordinator{ lock: lock, config: map[string]string{ "NAME": name, "STRATEGY": strategy, }, } err = coordinator.UpdateState(CoordinatorStateStarting) return coordinator, err }
go
func New(name string, strategy string) (CoordinatorConfigUpdater, error) { // filelock expects that the file already exists. // Because this file will never be deleted, just blindly creating it on every // run is safe from racing with any deletions. Just create it, then get // locking. if err := os.MkdirAll(filepath.Dir(UpdateCoordinatorConfPath), 0755); err != nil { return nil, err } if file, err := os.OpenFile(UpdateCoordinatorConfPath, os.O_CREATE, 0644); err != nil { return nil, err } else { file.Close() } lock, err := filelock.NewExclusiveLock(UpdateCoordinatorConfPath) if err != nil { return nil, err } coordinator := &coordinator{ lock: lock, config: map[string]string{ "NAME": name, "STRATEGY": strategy, }, } err = coordinator.UpdateState(CoordinatorStateStarting) return coordinator, err }
[ "func", "New", "(", "name", "string", ",", "strategy", "string", ")", "(", "CoordinatorConfigUpdater", ",", "error", ")", "{", "// filelock expects that the file already exists.", "// Because this file will never be deleted, just blindly creating it on every", "// run is safe from racing with any deletions. Just create it, then get", "// locking.", "if", "err", ":=", "os", ".", "MkdirAll", "(", "filepath", ".", "Dir", "(", "UpdateCoordinatorConfPath", ")", ",", "0755", ")", ";", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "if", "file", ",", "err", ":=", "os", ".", "OpenFile", "(", "UpdateCoordinatorConfPath", ",", "os", ".", "O_CREATE", ",", "0644", ")", ";", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "else", "{", "file", ".", "Close", "(", ")", "\n", "}", "\n\n", "lock", ",", "err", ":=", "filelock", ".", "NewExclusiveLock", "(", "UpdateCoordinatorConfPath", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "coordinator", ":=", "&", "coordinator", "{", "lock", ":", "lock", ",", "config", ":", "map", "[", "string", "]", "string", "{", "\"", "\"", ":", "name", ",", "\"", "\"", ":", "strategy", ",", "}", ",", "}", "\n", "err", "=", "coordinator", ".", "UpdateState", "(", "CoordinatorStateStarting", ")", "\n", "return", "coordinator", ",", "err", "\n", "}" ]
// New creates a new CoordinatorConfigUpdater. The "name" must be specified. // Strategy can safely be left blank if desired. // New will implicitly set the update coordinator state to // "CoordinatorStateStarting"
[ "New", "creates", "a", "new", "CoordinatorConfigUpdater", ".", "The", "name", "must", "be", "specified", ".", "Strategy", "can", "safely", "be", "left", "blank", "if", "desired", ".", "New", "will", "implicitly", "set", "the", "update", "coordinator", "state", "to", "CoordinatorStateStarting" ]
ba572048b6baf84b4488656ca4f8b115243ab3d5
https://github.com/coreos/locksmith/blob/ba572048b6baf84b4488656ca4f8b115243ab3d5/pkg/coordinatorconf/conf.go#L83-L110
5,355
coreos/locksmith
pkg/coordinatorconf/conf.go
UpdateState
func (c *coordinator) UpdateState(s updateCoordinatorState) error { c.configLock.Lock() c.config["STATE"] = string(s) c.configLock.Unlock() return c.writeConfig() }
go
func (c *coordinator) UpdateState(s updateCoordinatorState) error { c.configLock.Lock() c.config["STATE"] = string(s) c.configLock.Unlock() return c.writeConfig() }
[ "func", "(", "c", "*", "coordinator", ")", "UpdateState", "(", "s", "updateCoordinatorState", ")", "error", "{", "c", ".", "configLock", ".", "Lock", "(", ")", "\n", "c", ".", "config", "[", "\"", "\"", "]", "=", "string", "(", "s", ")", "\n", "c", ".", "configLock", ".", "Unlock", "(", ")", "\n\n", "return", "c", ".", "writeConfig", "(", ")", "\n", "}" ]
// UpdateState updates the state the update coordinator claims to be in
[ "UpdateState", "updates", "the", "state", "the", "update", "coordinator", "claims", "to", "be", "in" ]
ba572048b6baf84b4488656ca4f8b115243ab3d5
https://github.com/coreos/locksmith/blob/ba572048b6baf84b4488656ca4f8b115243ab3d5/pkg/coordinatorconf/conf.go#L113-L119
5,356
lithammer/go-jump-consistent-hash
jump.go
Hash
func Hash(key uint64, buckets int32) int32 { var b, j int64 if buckets <= 0 { buckets = 1 } for j < int64(buckets) { b = j key = key*2862933555777941757 + 1 j = int64(float64(b+1) * (float64(int64(1)<<31) / float64((key>>33)+1))) } return int32(b) }
go
func Hash(key uint64, buckets int32) int32 { var b, j int64 if buckets <= 0 { buckets = 1 } for j < int64(buckets) { b = j key = key*2862933555777941757 + 1 j = int64(float64(b+1) * (float64(int64(1)<<31) / float64((key>>33)+1))) } return int32(b) }
[ "func", "Hash", "(", "key", "uint64", ",", "buckets", "int32", ")", "int32", "{", "var", "b", ",", "j", "int64", "\n\n", "if", "buckets", "<=", "0", "{", "buckets", "=", "1", "\n", "}", "\n\n", "for", "j", "<", "int64", "(", "buckets", ")", "{", "b", "=", "j", "\n", "key", "=", "key", "*", "2862933555777941757", "+", "1", "\n", "j", "=", "int64", "(", "float64", "(", "b", "+", "1", ")", "*", "(", "float64", "(", "int64", "(", "1", ")", "<<", "31", ")", "/", "float64", "(", "(", "key", ">>", "33", ")", "+", "1", ")", ")", ")", "\n", "}", "\n\n", "return", "int32", "(", "b", ")", "\n", "}" ]
// Hash takes a 64 bit key and the number of buckets. It outputs a bucket // number in the range [0, buckets). // If the number of buckets is less than or equal to 0 then one 1 is used.
[ "Hash", "takes", "a", "64", "bit", "key", "and", "the", "number", "of", "buckets", ".", "It", "outputs", "a", "bucket", "number", "in", "the", "range", "[", "0", "buckets", ")", ".", "If", "the", "number", "of", "buckets", "is", "less", "than", "or", "equal", "to", "0", "then", "one", "1", "is", "used", "." ]
33b8bdaea80f7cbd390ea2eaec8581d2da308dc1
https://github.com/lithammer/go-jump-consistent-hash/blob/33b8bdaea80f7cbd390ea2eaec8581d2da308dc1/jump.go#L14-L28
5,357
lithammer/go-jump-consistent-hash
jump.go
New
func New(n int, h KeyHasher) *Hasher { return &Hasher{int32(n), h} }
go
func New(n int, h KeyHasher) *Hasher { return &Hasher{int32(n), h} }
[ "func", "New", "(", "n", "int", ",", "h", "KeyHasher", ")", "*", "Hasher", "{", "return", "&", "Hasher", "{", "int32", "(", "n", ")", ",", "h", "}", "\n", "}" ]
// New returns a new instance of of Hasher.
[ "New", "returns", "a", "new", "instance", "of", "of", "Hasher", "." ]
33b8bdaea80f7cbd390ea2eaec8581d2da308dc1
https://github.com/lithammer/go-jump-consistent-hash/blob/33b8bdaea80f7cbd390ea2eaec8581d2da308dc1/jump.go#L62-L64
5,358
bsm/ratelimit
ratelimit.go
New
func New(rate int, per time.Duration) *RateLimiter { nano := uint64(per) if nano < 1 { nano = uint64(time.Second) } if rate < 1 { rate = 1 } return &RateLimiter{ rate: uint64(rate), // store the rate allowance: uint64(rate) * nano, // set our allowance to max in the beginning max: uint64(rate) * nano, // remember our maximum allowance unit: nano, // remember our unit size lastCheck: unixNano(), } }
go
func New(rate int, per time.Duration) *RateLimiter { nano := uint64(per) if nano < 1 { nano = uint64(time.Second) } if rate < 1 { rate = 1 } return &RateLimiter{ rate: uint64(rate), // store the rate allowance: uint64(rate) * nano, // set our allowance to max in the beginning max: uint64(rate) * nano, // remember our maximum allowance unit: nano, // remember our unit size lastCheck: unixNano(), } }
[ "func", "New", "(", "rate", "int", ",", "per", "time", ".", "Duration", ")", "*", "RateLimiter", "{", "nano", ":=", "uint64", "(", "per", ")", "\n", "if", "nano", "<", "1", "{", "nano", "=", "uint64", "(", "time", ".", "Second", ")", "\n", "}", "\n", "if", "rate", "<", "1", "{", "rate", "=", "1", "\n", "}", "\n\n", "return", "&", "RateLimiter", "{", "rate", ":", "uint64", "(", "rate", ")", ",", "// store the rate", "allowance", ":", "uint64", "(", "rate", ")", "*", "nano", ",", "// set our allowance to max in the beginning", "max", ":", "uint64", "(", "rate", ")", "*", "nano", ",", "// remember our maximum allowance", "unit", ":", "nano", ",", "// remember our unit size", "lastCheck", ":", "unixNano", "(", ")", ",", "}", "\n", "}" ]
// New creates a new rate limiter instance
[ "New", "creates", "a", "new", "rate", "limiter", "instance" ]
8e32603e22a2014227edb38946de25e32b199faf
https://github.com/bsm/ratelimit/blob/8e32603e22a2014227edb38946de25e32b199faf/ratelimit.go#L32-L49
5,359
bsm/ratelimit
ratelimit.go
UpdateRate
func (rl *RateLimiter) UpdateRate(rate int) { atomic.StoreUint64(&rl.rate, uint64(rate)) atomic.StoreUint64(&rl.max, uint64(rate)*rl.unit) }
go
func (rl *RateLimiter) UpdateRate(rate int) { atomic.StoreUint64(&rl.rate, uint64(rate)) atomic.StoreUint64(&rl.max, uint64(rate)*rl.unit) }
[ "func", "(", "rl", "*", "RateLimiter", ")", "UpdateRate", "(", "rate", "int", ")", "{", "atomic", ".", "StoreUint64", "(", "&", "rl", ".", "rate", ",", "uint64", "(", "rate", ")", ")", "\n", "atomic", ".", "StoreUint64", "(", "&", "rl", ".", "max", ",", "uint64", "(", "rate", ")", "*", "rl", ".", "unit", ")", "\n", "}" ]
// UpdateRate allows to update the allowed rate
[ "UpdateRate", "allows", "to", "update", "the", "allowed", "rate" ]
8e32603e22a2014227edb38946de25e32b199faf
https://github.com/bsm/ratelimit/blob/8e32603e22a2014227edb38946de25e32b199faf/ratelimit.go#L52-L55
5,360
bsm/ratelimit
ratelimit.go
Limit
func (rl *RateLimiter) Limit() bool { // Calculate the number of ns that have passed since our last call now := unixNano() passed := now - atomic.SwapUint64(&rl.lastCheck, now) // Add them to our allowance rate := atomic.LoadUint64(&rl.rate) current := atomic.AddUint64(&rl.allowance, passed*rate) // Ensure our allowance is not over maximum if max := atomic.LoadUint64(&rl.max); current > max { atomic.AddUint64(&rl.allowance, max-current) current = max } // If our allowance is less than one unit, rate-limit! if current < rl.unit { return true } // Not limited, subtract a unit atomic.AddUint64(&rl.allowance, -rl.unit) return false }
go
func (rl *RateLimiter) Limit() bool { // Calculate the number of ns that have passed since our last call now := unixNano() passed := now - atomic.SwapUint64(&rl.lastCheck, now) // Add them to our allowance rate := atomic.LoadUint64(&rl.rate) current := atomic.AddUint64(&rl.allowance, passed*rate) // Ensure our allowance is not over maximum if max := atomic.LoadUint64(&rl.max); current > max { atomic.AddUint64(&rl.allowance, max-current) current = max } // If our allowance is less than one unit, rate-limit! if current < rl.unit { return true } // Not limited, subtract a unit atomic.AddUint64(&rl.allowance, -rl.unit) return false }
[ "func", "(", "rl", "*", "RateLimiter", ")", "Limit", "(", ")", "bool", "{", "// Calculate the number of ns that have passed since our last call", "now", ":=", "unixNano", "(", ")", "\n", "passed", ":=", "now", "-", "atomic", ".", "SwapUint64", "(", "&", "rl", ".", "lastCheck", ",", "now", ")", "\n\n", "// Add them to our allowance", "rate", ":=", "atomic", ".", "LoadUint64", "(", "&", "rl", ".", "rate", ")", "\n", "current", ":=", "atomic", ".", "AddUint64", "(", "&", "rl", ".", "allowance", ",", "passed", "*", "rate", ")", "\n\n", "// Ensure our allowance is not over maximum", "if", "max", ":=", "atomic", ".", "LoadUint64", "(", "&", "rl", ".", "max", ")", ";", "current", ">", "max", "{", "atomic", ".", "AddUint64", "(", "&", "rl", ".", "allowance", ",", "max", "-", "current", ")", "\n", "current", "=", "max", "\n", "}", "\n\n", "// If our allowance is less than one unit, rate-limit!", "if", "current", "<", "rl", ".", "unit", "{", "return", "true", "\n", "}", "\n\n", "// Not limited, subtract a unit", "atomic", ".", "AddUint64", "(", "&", "rl", ".", "allowance", ",", "-", "rl", ".", "unit", ")", "\n", "return", "false", "\n", "}" ]
// Limit returns true if rate was exceeded
[ "Limit", "returns", "true", "if", "rate", "was", "exceeded" ]
8e32603e22a2014227edb38946de25e32b199faf
https://github.com/bsm/ratelimit/blob/8e32603e22a2014227edb38946de25e32b199faf/ratelimit.go#L58-L81
5,361
nvellon/hal
hal.go
AddNewLink
func (c CurieHandle) AddNewLink(rel Relation, href string) { rel = Relation(c.Name) + ":" + rel c.Resource.AddLink(rel, NewLink(href, nil)) }
go
func (c CurieHandle) AddNewLink(rel Relation, href string) { rel = Relation(c.Name) + ":" + rel c.Resource.AddLink(rel, NewLink(href, nil)) }
[ "func", "(", "c", "CurieHandle", ")", "AddNewLink", "(", "rel", "Relation", ",", "href", "string", ")", "{", "rel", "=", "Relation", "(", "c", ".", "Name", ")", "+", "\"", "\"", "+", "rel", "\n", "c", ".", "Resource", ".", "AddLink", "(", "rel", ",", "NewLink", "(", "href", ",", "nil", ")", ")", "\n", "}" ]
// AddNewLink adds a link to the resources_link collection // prepended with the curie Name
[ "AddNewLink", "adds", "a", "link", "to", "the", "resources_link", "collection", "prepended", "with", "the", "curie", "Name" ]
d5526dbaf6448b3cac35d44a2fb5c2ddb0081437
https://github.com/nvellon/hal/blob/d5526dbaf6448b3cac35d44a2fb5c2ddb0081437/hal.go#L58-L61
5,362
nvellon/hal
hal.go
AddCollection
func (e Embedded) AddCollection(rel Relation, r ResourceCollection) { n := e[rel] if n == nil { //new embed e[rel] = r return } if nc, ok := n.([]*Resource); ok { e[rel] = append(nc, r...) return } if nr, ok := n.(*Resource); ok { e[rel] = append([]*Resource{nr}, r...) } }
go
func (e Embedded) AddCollection(rel Relation, r ResourceCollection) { n := e[rel] if n == nil { //new embed e[rel] = r return } if nc, ok := n.([]*Resource); ok { e[rel] = append(nc, r...) return } if nr, ok := n.(*Resource); ok { e[rel] = append([]*Resource{nr}, r...) } }
[ "func", "(", "e", "Embedded", ")", "AddCollection", "(", "rel", "Relation", ",", "r", "ResourceCollection", ")", "{", "n", ":=", "e", "[", "rel", "]", "\n", "if", "n", "==", "nil", "{", "//new embed", "e", "[", "rel", "]", "=", "r", "\n", "return", "\n", "}", "\n\n", "if", "nc", ",", "ok", ":=", "n", ".", "(", "[", "]", "*", "Resource", ")", ";", "ok", "{", "e", "[", "rel", "]", "=", "append", "(", "nc", ",", "r", "...", ")", "\n", "return", "\n", "}", "\n\n", "if", "nr", ",", "ok", ":=", "n", ".", "(", "*", "Resource", ")", ";", "ok", "{", "e", "[", "rel", "]", "=", "append", "(", "[", "]", "*", "Resource", "{", "nr", "}", ",", "r", "...", ")", "\n", "}", "\n\n", "}" ]
// AddCollection appends the resource into the list of embedded // resources with the specified relation. // r should be a ResourceCollection
[ "AddCollection", "appends", "the", "resource", "into", "the", "list", "of", "embedded", "resources", "with", "the", "specified", "relation", ".", "r", "should", "be", "a", "ResourceCollection" ]
d5526dbaf6448b3cac35d44a2fb5c2ddb0081437
https://github.com/nvellon/hal/blob/d5526dbaf6448b3cac35d44a2fb5c2ddb0081437/hal.go#L66-L83
5,363
nvellon/hal
hal.go
Add
func (e Embedded) Add(rel Relation, r *Resource) { n := e[rel] if n == nil { //new embed e[rel] = r return } if nec, ok := n.([]*Resource); ok { e[rel] = append(nec, r) return } if nee, ok := n.(*Resource); ok { e[rel] = append([]*Resource{nee}, r) return } //something went wrong.. replace what is there with what is new e[rel] = []*Resource{r} }
go
func (e Embedded) Add(rel Relation, r *Resource) { n := e[rel] if n == nil { //new embed e[rel] = r return } if nec, ok := n.([]*Resource); ok { e[rel] = append(nec, r) return } if nee, ok := n.(*Resource); ok { e[rel] = append([]*Resource{nee}, r) return } //something went wrong.. replace what is there with what is new e[rel] = []*Resource{r} }
[ "func", "(", "e", "Embedded", ")", "Add", "(", "rel", "Relation", ",", "r", "*", "Resource", ")", "{", "n", ":=", "e", "[", "rel", "]", "\n", "if", "n", "==", "nil", "{", "//new embed", "e", "[", "rel", "]", "=", "r", "\n", "return", "\n", "}", "\n\n", "if", "nec", ",", "ok", ":=", "n", ".", "(", "[", "]", "*", "Resource", ")", ";", "ok", "{", "e", "[", "rel", "]", "=", "append", "(", "nec", ",", "r", ")", "\n", "return", "\n", "}", "\n\n", "if", "nee", ",", "ok", ":=", "n", ".", "(", "*", "Resource", ")", ";", "ok", "{", "e", "[", "rel", "]", "=", "append", "(", "[", "]", "*", "Resource", "{", "nee", "}", ",", "r", ")", "\n", "return", "\n", "}", "\n\n", "//something went wrong.. replace what is there with what is new", "e", "[", "rel", "]", "=", "[", "]", "*", "Resource", "{", "r", "}", "\n", "}" ]
// Add appends the resource into the list of embedded // resources with the specified relation. // r should be a Resource
[ "Add", "appends", "the", "resource", "into", "the", "list", "of", "embedded", "resources", "with", "the", "specified", "relation", ".", "r", "should", "be", "a", "Resource" ]
d5526dbaf6448b3cac35d44a2fb5c2ddb0081437
https://github.com/nvellon/hal/blob/d5526dbaf6448b3cac35d44a2fb5c2ddb0081437/hal.go#L88-L108
5,364
nvellon/hal
hal.go
Set
func (e Embedded) Set(rel Relation, r *Resource) { e[rel] = r }
go
func (e Embedded) Set(rel Relation, r *Resource) { e[rel] = r }
[ "func", "(", "e", "Embedded", ")", "Set", "(", "rel", "Relation", ",", "r", "*", "Resource", ")", "{", "e", "[", "rel", "]", "=", "r", "\n", "}" ]
// Set sets the resource into the list of embedded // resources with the specified relation. It replaces // any existing resources associated with the relation. // r should be a pointer to a Resource
[ "Set", "sets", "the", "resource", "into", "the", "list", "of", "embedded", "resources", "with", "the", "specified", "relation", ".", "It", "replaces", "any", "existing", "resources", "associated", "with", "the", "relation", ".", "r", "should", "be", "a", "pointer", "to", "a", "Resource" ]
d5526dbaf6448b3cac35d44a2fb5c2ddb0081437
https://github.com/nvellon/hal/blob/d5526dbaf6448b3cac35d44a2fb5c2ddb0081437/hal.go#L114-L116
5,365
nvellon/hal
hal.go
SetCollection
func (e Embedded) SetCollection(rel Relation, r ResourceCollection) { e[rel] = r }
go
func (e Embedded) SetCollection(rel Relation, r ResourceCollection) { e[rel] = r }
[ "func", "(", "e", "Embedded", ")", "SetCollection", "(", "rel", "Relation", ",", "r", "ResourceCollection", ")", "{", "e", "[", "rel", "]", "=", "r", "\n", "}" ]
// Set sets the resource into the list of embedded // resources with the specified relation. It replaces // any existing resources associated with the relation. // r should be a ResourceCollection
[ "Set", "sets", "the", "resource", "into", "the", "list", "of", "embedded", "resources", "with", "the", "specified", "relation", ".", "It", "replaces", "any", "existing", "resources", "associated", "with", "the", "relation", ".", "r", "should", "be", "a", "ResourceCollection" ]
d5526dbaf6448b3cac35d44a2fb5c2ddb0081437
https://github.com/nvellon/hal/blob/d5526dbaf6448b3cac35d44a2fb5c2ddb0081437/hal.go#L122-L124
5,366
nvellon/hal
hal.go
NewResource
func NewResource(p interface{}, selfUri string) *Resource { var r Resource r.Payload = p r.Links = make(LinkRelations) r.AddNewLink("self", selfUri) r.Embedded = make(Embedded) r.Curies = make(map[string]*CurieHandle) return &r }
go
func NewResource(p interface{}, selfUri string) *Resource { var r Resource r.Payload = p r.Links = make(LinkRelations) r.AddNewLink("self", selfUri) r.Embedded = make(Embedded) r.Curies = make(map[string]*CurieHandle) return &r }
[ "func", "NewResource", "(", "p", "interface", "{", "}", ",", "selfUri", "string", ")", "*", "Resource", "{", "var", "r", "Resource", "\n\n", "r", ".", "Payload", "=", "p", "\n\n", "r", ".", "Links", "=", "make", "(", "LinkRelations", ")", "\n", "r", ".", "AddNewLink", "(", "\"", "\"", ",", "selfUri", ")", "\n\n", "r", ".", "Embedded", "=", "make", "(", "Embedded", ")", "\n", "r", ".", "Curies", "=", "make", "(", "map", "[", "string", "]", "*", "CurieHandle", ")", "\n\n", "return", "&", "r", "\n", "}" ]
// NewResource creates a Resource object for a given struct // and its link.
[ "NewResource", "creates", "a", "Resource", "object", "for", "a", "given", "struct", "and", "its", "link", "." ]
d5526dbaf6448b3cac35d44a2fb5c2ddb0081437
https://github.com/nvellon/hal/blob/d5526dbaf6448b3cac35d44a2fb5c2ddb0081437/hal.go#L140-L152
5,367
nvellon/hal
hal.go
AddLinkCollection
func (r *Resource) AddLinkCollection(rel Relation, l LinkCollection) { n := r.Links[rel] if n == nil { //new link r.Links[rel] = l return } if nc, ok := n.(LinkCollection); ok { r.Links[rel] = append(nc, l...) return } if nl, ok := n.(Link); ok { //prepend existing link to collection r.Links[rel] = append(LinkCollection{nl}, l...) } }
go
func (r *Resource) AddLinkCollection(rel Relation, l LinkCollection) { n := r.Links[rel] if n == nil { //new link r.Links[rel] = l return } if nc, ok := n.(LinkCollection); ok { r.Links[rel] = append(nc, l...) return } if nl, ok := n.(Link); ok { //prepend existing link to collection r.Links[rel] = append(LinkCollection{nl}, l...) } }
[ "func", "(", "r", "*", "Resource", ")", "AddLinkCollection", "(", "rel", "Relation", ",", "l", "LinkCollection", ")", "{", "n", ":=", "r", ".", "Links", "[", "rel", "]", "\n", "if", "n", "==", "nil", "{", "//new link", "r", ".", "Links", "[", "rel", "]", "=", "l", "\n", "return", "\n", "}", "\n\n", "if", "nc", ",", "ok", ":=", "n", ".", "(", "LinkCollection", ")", ";", "ok", "{", "r", ".", "Links", "[", "rel", "]", "=", "append", "(", "nc", ",", "l", "...", ")", "\n", "return", "\n", "}", "\n\n", "if", "nl", ",", "ok", ":=", "n", ".", "(", "Link", ")", ";", "ok", "{", "//prepend existing link to collection", "r", ".", "Links", "[", "rel", "]", "=", "append", "(", "LinkCollection", "{", "nl", "}", ",", "l", "...", ")", "\n", "}", "\n", "}" ]
// AddLinkCollection appends a LinkCollection to the resource. // l should be a LinkCollection
[ "AddLinkCollection", "appends", "a", "LinkCollection", "to", "the", "resource", ".", "l", "should", "be", "a", "LinkCollection" ]
d5526dbaf6448b3cac35d44a2fb5c2ddb0081437
https://github.com/nvellon/hal/blob/d5526dbaf6448b3cac35d44a2fb5c2ddb0081437/hal.go#L156-L173
5,368
nvellon/hal
hal.go
AddNewLink
func (r *Resource) AddNewLink(rel Relation, href string) { r.AddLink(rel, NewLink(href, nil)) }
go
func (r *Resource) AddNewLink(rel Relation, href string) { r.AddLink(rel, NewLink(href, nil)) }
[ "func", "(", "r", "*", "Resource", ")", "AddNewLink", "(", "rel", "Relation", ",", "href", "string", ")", "{", "r", ".", "AddLink", "(", "rel", ",", "NewLink", "(", "href", ",", "nil", ")", ")", "\n", "}" ]
// AddNewLink appends a new Link object based on // the rel and href params.
[ "AddNewLink", "appends", "a", "new", "Link", "object", "based", "on", "the", "rel", "and", "href", "params", "." ]
d5526dbaf6448b3cac35d44a2fb5c2ddb0081437
https://github.com/nvellon/hal/blob/d5526dbaf6448b3cac35d44a2fb5c2ddb0081437/hal.go#L201-L203
5,369
nvellon/hal
hal.go
RegisterCurie
func (r *Resource) RegisterCurie(name, href string, templated bool) *CurieHandle { l := LinkCollection{ NewLink(href, LinkAttr{"name": name}, LinkAttr{"templated": templated}), } r.AddLinkCollection("curies", l) handle := &CurieHandle{Name: name, Resource: r} r.Curies[name] = handle return handle }
go
func (r *Resource) RegisterCurie(name, href string, templated bool) *CurieHandle { l := LinkCollection{ NewLink(href, LinkAttr{"name": name}, LinkAttr{"templated": templated}), } r.AddLinkCollection("curies", l) handle := &CurieHandle{Name: name, Resource: r} r.Curies[name] = handle return handle }
[ "func", "(", "r", "*", "Resource", ")", "RegisterCurie", "(", "name", ",", "href", "string", ",", "templated", "bool", ")", "*", "CurieHandle", "{", "l", ":=", "LinkCollection", "{", "NewLink", "(", "href", ",", "LinkAttr", "{", "\"", "\"", ":", "name", "}", ",", "LinkAttr", "{", "\"", "\"", ":", "templated", "}", ")", ",", "}", "\n", "r", ".", "AddLinkCollection", "(", "\"", "\"", ",", "l", ")", "\n\n", "handle", ":=", "&", "CurieHandle", "{", "Name", ":", "name", ",", "Resource", ":", "r", "}", "\n\n", "r", ".", "Curies", "[", "name", "]", "=", "handle", "\n", "return", "handle", "\n", "}" ]
// RegisterCurie adds a Link relation of type 'curies' and returns a CurieHandle // to allow users to fluently add new links that have this curie relation definition
[ "RegisterCurie", "adds", "a", "Link", "relation", "of", "type", "curies", "and", "returns", "a", "CurieHandle", "to", "allow", "users", "to", "fluently", "add", "new", "links", "that", "have", "this", "curie", "relation", "definition" ]
d5526dbaf6448b3cac35d44a2fb5c2ddb0081437
https://github.com/nvellon/hal/blob/d5526dbaf6448b3cac35d44a2fb5c2ddb0081437/hal.go#L207-L217
5,370
nvellon/hal
hal.go
Embed
func (r *Resource) Embed(rel Relation, re *Resource) { r.Embedded.Add(rel, re) }
go
func (r *Resource) Embed(rel Relation, re *Resource) { r.Embedded.Add(rel, re) }
[ "func", "(", "r", "*", "Resource", ")", "Embed", "(", "rel", "Relation", ",", "re", "*", "Resource", ")", "{", "r", ".", "Embedded", ".", "Add", "(", "rel", ",", "re", ")", "\n", "}" ]
// Embed appends a Resource to the array of // embedded resources. // re should be a pointer to a Resource
[ "Embed", "appends", "a", "Resource", "to", "the", "array", "of", "embedded", "resources", ".", "re", "should", "be", "a", "pointer", "to", "a", "Resource" ]
d5526dbaf6448b3cac35d44a2fb5c2ddb0081437
https://github.com/nvellon/hal/blob/d5526dbaf6448b3cac35d44a2fb5c2ddb0081437/hal.go#L222-L224
5,371
nvellon/hal
hal.go
EmbedCollection
func (r *Resource) EmbedCollection(rel Relation, re ResourceCollection) { r.Embedded.AddCollection(rel, re) }
go
func (r *Resource) EmbedCollection(rel Relation, re ResourceCollection) { r.Embedded.AddCollection(rel, re) }
[ "func", "(", "r", "*", "Resource", ")", "EmbedCollection", "(", "rel", "Relation", ",", "re", "ResourceCollection", ")", "{", "r", ".", "Embedded", ".", "AddCollection", "(", "rel", ",", "re", ")", "\n", "}" ]
// EmbedCollection appends a ResourceCollection to the array of // embedded resources. // re should be a ResourceCollection
[ "EmbedCollection", "appends", "a", "ResourceCollection", "to", "the", "array", "of", "embedded", "resources", ".", "re", "should", "be", "a", "ResourceCollection" ]
d5526dbaf6448b3cac35d44a2fb5c2ddb0081437
https://github.com/nvellon/hal/blob/d5526dbaf6448b3cac35d44a2fb5c2ddb0081437/hal.go#L229-L231
5,372
nvellon/hal
hal.go
GetMap
func (r Resource) GetMap() Entry { mapped := make(Entry) var mp Entry // Check if payload implements Mapper interface if mapper, ok := r.Payload.(Mapper); ok { mp = mapper.GetMap() } else { mp = r.getPayloadMap() } for k, v := range mp { mapped[k] = v } mapped["_links"] = r.Links if len(r.Embedded) > 0 { mapped["_embedded"] = r.Embedded } return mapped }
go
func (r Resource) GetMap() Entry { mapped := make(Entry) var mp Entry // Check if payload implements Mapper interface if mapper, ok := r.Payload.(Mapper); ok { mp = mapper.GetMap() } else { mp = r.getPayloadMap() } for k, v := range mp { mapped[k] = v } mapped["_links"] = r.Links if len(r.Embedded) > 0 { mapped["_embedded"] = r.Embedded } return mapped }
[ "func", "(", "r", "Resource", ")", "GetMap", "(", ")", "Entry", "{", "mapped", ":=", "make", "(", "Entry", ")", "\n\n", "var", "mp", "Entry", "\n", "// Check if payload implements Mapper interface", "if", "mapper", ",", "ok", ":=", "r", ".", "Payload", ".", "(", "Mapper", ")", ";", "ok", "{", "mp", "=", "mapper", ".", "GetMap", "(", ")", "\n", "}", "else", "{", "mp", "=", "r", ".", "getPayloadMap", "(", ")", "\n", "}", "\n\n", "for", "k", ",", "v", ":=", "range", "mp", "{", "mapped", "[", "k", "]", "=", "v", "\n", "}", "\n\n", "mapped", "[", "\"", "\"", "]", "=", "r", ".", "Links", "\n\n", "if", "len", "(", "r", ".", "Embedded", ")", ">", "0", "{", "mapped", "[", "\"", "\"", "]", "=", "r", ".", "Embedded", "\n", "}", "\n\n", "return", "mapped", "\n", "}" ]
// Map implements the interface Mapper.
[ "Map", "implements", "the", "interface", "Mapper", "." ]
d5526dbaf6448b3cac35d44a2fb5c2ddb0081437
https://github.com/nvellon/hal/blob/d5526dbaf6448b3cac35d44a2fb5c2ddb0081437/hal.go#L234-L256
5,373
nvellon/hal
hal.go
NewLink
func NewLink(href string, attrs ...LinkAttr) Link { l := make(Link) l["href"] = href for _, attr := range attrs { for k, v := range attr { l[k] = v } } return l }
go
func NewLink(href string, attrs ...LinkAttr) Link { l := make(Link) l["href"] = href for _, attr := range attrs { for k, v := range attr { l[k] = v } } return l }
[ "func", "NewLink", "(", "href", "string", ",", "attrs", "...", "LinkAttr", ")", "Link", "{", "l", ":=", "make", "(", "Link", ")", "\n\n", "l", "[", "\"", "\"", "]", "=", "href", "\n\n", "for", "_", ",", "attr", ":=", "range", "attrs", "{", "for", "k", ",", "v", ":=", "range", "attr", "{", "l", "[", "k", "]", "=", "v", "\n", "}", "\n", "}", "\n\n", "return", "l", "\n", "}" ]
// NewLink returns a new Link object.
[ "NewLink", "returns", "a", "new", "Link", "object", "." ]
d5526dbaf6448b3cac35d44a2fb5c2ddb0081437
https://github.com/nvellon/hal/blob/d5526dbaf6448b3cac35d44a2fb5c2ddb0081437/hal.go#L299-L311
5,374
dinever/golf
config.go
Error
func (err *ValueTypeError) Error() string { return fmt.Sprintf("%s, key: %s, value: %v (%s)", err.message, err.key, err.value, reflect.TypeOf(err.value).Name()) }
go
func (err *ValueTypeError) Error() string { return fmt.Sprintf("%s, key: %s, value: %v (%s)", err.message, err.key, err.value, reflect.TypeOf(err.value).Name()) }
[ "func", "(", "err", "*", "ValueTypeError", ")", "Error", "(", ")", "string", "{", "return", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "err", ".", "message", ",", "err", ".", "key", ",", "err", ".", "value", ",", "reflect", ".", "TypeOf", "(", "err", ".", "value", ")", ".", "Name", "(", ")", ")", "\n", "}" ]
// Error method implements Error method of Go standard library "error".
[ "Error", "method", "implements", "Error", "method", "of", "Go", "standard", "library", "error", "." ]
11abebbbb289ef6f35e518db394eaca39cee8732
https://github.com/dinever/golf/blob/11abebbbb289ef6f35e518db394eaca39cee8732/config.go#L31-L33
5,375
dinever/golf
config.go
GetString
func (config *Config) GetString(key string, defaultValue string) (string, error) { value, err := config.Get(key, defaultValue) if err != nil { return defaultValue, err } if result, ok := value.(string); ok { return result, nil } return defaultValue, &ValueTypeError{key: key, value: value, message: "Value is not a string."} }
go
func (config *Config) GetString(key string, defaultValue string) (string, error) { value, err := config.Get(key, defaultValue) if err != nil { return defaultValue, err } if result, ok := value.(string); ok { return result, nil } return defaultValue, &ValueTypeError{key: key, value: value, message: "Value is not a string."} }
[ "func", "(", "config", "*", "Config", ")", "GetString", "(", "key", "string", ",", "defaultValue", "string", ")", "(", "string", ",", "error", ")", "{", "value", ",", "err", ":=", "config", ".", "Get", "(", "key", ",", "defaultValue", ")", "\n", "if", "err", "!=", "nil", "{", "return", "defaultValue", ",", "err", "\n", "}", "\n", "if", "result", ",", "ok", ":=", "value", ".", "(", "string", ")", ";", "ok", "{", "return", "result", ",", "nil", "\n", "}", "\n", "return", "defaultValue", ",", "&", "ValueTypeError", "{", "key", ":", "key", ",", "value", ":", "value", ",", "message", ":", "\"", "\"", "}", "\n", "}" ]
// GetString fetches the string value by indicating the key. // It returns a ValueTypeError if the value is not a sring.
[ "GetString", "fetches", "the", "string", "value", "by", "indicating", "the", "key", ".", "It", "returns", "a", "ValueTypeError", "if", "the", "value", "is", "not", "a", "sring", "." ]
11abebbbb289ef6f35e518db394eaca39cee8732
https://github.com/dinever/golf/blob/11abebbbb289ef6f35e518db394eaca39cee8732/config.go#L48-L57
5,376
dinever/golf
config.go
Get
func (config *Config) Get(key string, defaultValue interface{}) (interface{}, error) { var ( tmp interface{} ) keys := strings.Split(key, "/") tmp = config.mapping for i, item := range keys { if len(item) == 0 { continue } if mapping, ok := tmp.(map[string]interface{}); ok { if value, exists := mapping[item]; exists { tmp = value } else if defaultValue != nil { return nil, &KeyError{key: path.Join(append(keys[:i], item)...)} } else { return nil, &KeyError{key: path.Join(append(keys[:i], item)...)} } } else { return nil, &ValueTypeError{key: path.Join(append(keys[:i], item)...), value: tmp, message: "Value is not a map"} } } return tmp, nil }
go
func (config *Config) Get(key string, defaultValue interface{}) (interface{}, error) { var ( tmp interface{} ) keys := strings.Split(key, "/") tmp = config.mapping for i, item := range keys { if len(item) == 0 { continue } if mapping, ok := tmp.(map[string]interface{}); ok { if value, exists := mapping[item]; exists { tmp = value } else if defaultValue != nil { return nil, &KeyError{key: path.Join(append(keys[:i], item)...)} } else { return nil, &KeyError{key: path.Join(append(keys[:i], item)...)} } } else { return nil, &ValueTypeError{key: path.Join(append(keys[:i], item)...), value: tmp, message: "Value is not a map"} } } return tmp, nil }
[ "func", "(", "config", "*", "Config", ")", "Get", "(", "key", "string", ",", "defaultValue", "interface", "{", "}", ")", "(", "interface", "{", "}", ",", "error", ")", "{", "var", "(", "tmp", "interface", "{", "}", "\n", ")", "\n", "keys", ":=", "strings", ".", "Split", "(", "key", ",", "\"", "\"", ")", "\n", "tmp", "=", "config", ".", "mapping", "\n", "for", "i", ",", "item", ":=", "range", "keys", "{", "if", "len", "(", "item", ")", "==", "0", "{", "continue", "\n", "}", "\n", "if", "mapping", ",", "ok", ":=", "tmp", ".", "(", "map", "[", "string", "]", "interface", "{", "}", ")", ";", "ok", "{", "if", "value", ",", "exists", ":=", "mapping", "[", "item", "]", ";", "exists", "{", "tmp", "=", "value", "\n", "}", "else", "if", "defaultValue", "!=", "nil", "{", "return", "nil", ",", "&", "KeyError", "{", "key", ":", "path", ".", "Join", "(", "append", "(", "keys", "[", ":", "i", "]", ",", "item", ")", "...", ")", "}", "\n", "}", "else", "{", "return", "nil", ",", "&", "KeyError", "{", "key", ":", "path", ".", "Join", "(", "append", "(", "keys", "[", ":", "i", "]", ",", "item", ")", "...", ")", "}", "\n", "}", "\n", "}", "else", "{", "return", "nil", ",", "&", "ValueTypeError", "{", "key", ":", "path", ".", "Join", "(", "append", "(", "keys", "[", ":", "i", "]", ",", "item", ")", "...", ")", ",", "value", ":", "tmp", ",", "message", ":", "\"", "\"", "}", "\n", "}", "\n", "}", "\n", "return", "tmp", ",", "nil", "\n", "}" ]
// Get is used to retrieve the value by indicating a key. // After calling this method you should indicate the type of the return value. // If one of the parent node is not a map, then return a ValueTypeError. // If the key is not found, return a KeyError.
[ "Get", "is", "used", "to", "retrieve", "the", "value", "by", "indicating", "a", "key", ".", "After", "calling", "this", "method", "you", "should", "indicate", "the", "type", "of", "the", "return", "value", ".", "If", "one", "of", "the", "parent", "node", "is", "not", "a", "map", "then", "return", "a", "ValueTypeError", ".", "If", "the", "key", "is", "not", "found", "return", "a", "KeyError", "." ]
11abebbbb289ef6f35e518db394eaca39cee8732
https://github.com/dinever/golf/blob/11abebbbb289ef6f35e518db394eaca39cee8732/config.go#L140-L163
5,377
dinever/golf
config.go
ConfigFromJSON
func ConfigFromJSON(reader io.Reader) (*Config, error) { jsonBytes, err := ioutil.ReadAll(reader) if err != nil { return nil, err } var obj map[string]interface{} if err := json.Unmarshal(jsonBytes, &obj); err != nil { return nil, err } return &Config{obj}, nil }
go
func ConfigFromJSON(reader io.Reader) (*Config, error) { jsonBytes, err := ioutil.ReadAll(reader) if err != nil { return nil, err } var obj map[string]interface{} if err := json.Unmarshal(jsonBytes, &obj); err != nil { return nil, err } return &Config{obj}, nil }
[ "func", "ConfigFromJSON", "(", "reader", "io", ".", "Reader", ")", "(", "*", "Config", ",", "error", ")", "{", "jsonBytes", ",", "err", ":=", "ioutil", ".", "ReadAll", "(", "reader", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "var", "obj", "map", "[", "string", "]", "interface", "{", "}", "\n", "if", "err", ":=", "json", ".", "Unmarshal", "(", "jsonBytes", ",", "&", "obj", ")", ";", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "return", "&", "Config", "{", "obj", "}", ",", "nil", "\n", "}" ]
// ConfigFromJSON creates a Config instance from a JSON io.reader.
[ "ConfigFromJSON", "creates", "a", "Config", "instance", "from", "a", "JSON", "io", ".", "reader", "." ]
11abebbbb289ef6f35e518db394eaca39cee8732
https://github.com/dinever/golf/blob/11abebbbb289ef6f35e518db394eaca39cee8732/config.go#L166-L176
5,378
dinever/golf
context.go
NewContext
func NewContext(req *http.Request, res http.ResponseWriter, app *Application) *Context { ctx := new(Context) ctx.Request = req ctx.Request.ParseForm() ctx.Response = res ctx.App = app ctx.statusCode = 200 // ctx.Header["Content-Type"] = "text/html;charset=UTF-8" ctx.Request.ParseForm() ctx.IsSent = false return ctx }
go
func NewContext(req *http.Request, res http.ResponseWriter, app *Application) *Context { ctx := new(Context) ctx.Request = req ctx.Request.ParseForm() ctx.Response = res ctx.App = app ctx.statusCode = 200 // ctx.Header["Content-Type"] = "text/html;charset=UTF-8" ctx.Request.ParseForm() ctx.IsSent = false return ctx }
[ "func", "NewContext", "(", "req", "*", "http", ".", "Request", ",", "res", "http", ".", "ResponseWriter", ",", "app", "*", "Application", ")", "*", "Context", "{", "ctx", ":=", "new", "(", "Context", ")", "\n", "ctx", ".", "Request", "=", "req", "\n", "ctx", ".", "Request", ".", "ParseForm", "(", ")", "\n", "ctx", ".", "Response", "=", "res", "\n", "ctx", ".", "App", "=", "app", "\n", "ctx", ".", "statusCode", "=", "200", "\n", "//\tctx.Header[\"Content-Type\"] = \"text/html;charset=UTF-8\"", "ctx", ".", "Request", ".", "ParseForm", "(", ")", "\n", "ctx", ".", "IsSent", "=", "false", "\n", "return", "ctx", "\n", "}" ]
// NewContext creates a Golf.Context instance.
[ "NewContext", "creates", "a", "Golf", ".", "Context", "instance", "." ]
11abebbbb289ef6f35e518db394eaca39cee8732
https://github.com/dinever/golf/blob/11abebbbb289ef6f35e518db394eaca39cee8732/context.go#L43-L54
5,379
dinever/golf
context.go
SendStatus
func (ctx *Context) SendStatus(statusCode int) { ctx.statusCode = statusCode ctx.Response.WriteHeader(statusCode) }
go
func (ctx *Context) SendStatus(statusCode int) { ctx.statusCode = statusCode ctx.Response.WriteHeader(statusCode) }
[ "func", "(", "ctx", "*", "Context", ")", "SendStatus", "(", "statusCode", "int", ")", "{", "ctx", ".", "statusCode", "=", "statusCode", "\n", "ctx", ".", "Response", ".", "WriteHeader", "(", "statusCode", ")", "\n", "}" ]
// SendStatus takes an integer and sets the response status to the integer given.
[ "SendStatus", "takes", "an", "integer", "and", "sets", "the", "response", "status", "to", "the", "integer", "given", "." ]
11abebbbb289ef6f35e518db394eaca39cee8732
https://github.com/dinever/golf/blob/11abebbbb289ef6f35e518db394eaca39cee8732/context.go#L86-L89
5,380
dinever/golf
context.go
SetHeader
func (ctx *Context) SetHeader(key, value string) { ctx.Response.Header().Set(key, value) }
go
func (ctx *Context) SetHeader(key, value string) { ctx.Response.Header().Set(key, value) }
[ "func", "(", "ctx", "*", "Context", ")", "SetHeader", "(", "key", ",", "value", "string", ")", "{", "ctx", ".", "Response", ".", "Header", "(", ")", ".", "Set", "(", "key", ",", "value", ")", "\n", "}" ]
// SetHeader sets the header entries associated with key to the single element value. It replaces any existing values associated with key.
[ "SetHeader", "sets", "the", "header", "entries", "associated", "with", "key", "to", "the", "single", "element", "value", ".", "It", "replaces", "any", "existing", "values", "associated", "with", "key", "." ]
11abebbbb289ef6f35e518db394eaca39cee8732
https://github.com/dinever/golf/blob/11abebbbb289ef6f35e518db394eaca39cee8732/context.go#L97-L99
5,381
dinever/golf
context.go
AddHeader
func (ctx *Context) AddHeader(key, value string) { ctx.Response.Header().Add(key, value) }
go
func (ctx *Context) AddHeader(key, value string) { ctx.Response.Header().Add(key, value) }
[ "func", "(", "ctx", "*", "Context", ")", "AddHeader", "(", "key", ",", "value", "string", ")", "{", "ctx", ".", "Response", ".", "Header", "(", ")", ".", "Add", "(", "key", ",", "value", ")", "\n", "}" ]
// AddHeader adds the key, value pair to the header. It appends to any existing values associated with key.
[ "AddHeader", "adds", "the", "key", "value", "pair", "to", "the", "header", ".", "It", "appends", "to", "any", "existing", "values", "associated", "with", "key", "." ]
11abebbbb289ef6f35e518db394eaca39cee8732
https://github.com/dinever/golf/blob/11abebbbb289ef6f35e518db394eaca39cee8732/context.go#L102-L104
5,382
dinever/golf
context.go
Header
func (ctx *Context) Header(key string) string { return ctx.Request.Header.Get(key) }
go
func (ctx *Context) Header(key string) string { return ctx.Request.Header.Get(key) }
[ "func", "(", "ctx", "*", "Context", ")", "Header", "(", "key", "string", ")", "string", "{", "return", "ctx", ".", "Request", ".", "Header", ".", "Get", "(", "key", ")", "\n", "}" ]
// Header gets the first value associated with the given key. If there are no values associated with the key, Get returns "".
[ "Header", "gets", "the", "first", "value", "associated", "with", "the", "given", "key", ".", "If", "there", "are", "no", "values", "associated", "with", "the", "key", "Get", "returns", "." ]
11abebbbb289ef6f35e518db394eaca39cee8732
https://github.com/dinever/golf/blob/11abebbbb289ef6f35e518db394eaca39cee8732/context.go#L107-L109
5,383
dinever/golf
context.go
Query
func (ctx *Context) Query(key string, index ...int) (string, error) { if val, ok := ctx.Request.Form[key]; ok { if len(index) == 1 { return val[index[0]], nil } return val[0], nil } return "", errors.New("Query key not found") }
go
func (ctx *Context) Query(key string, index ...int) (string, error) { if val, ok := ctx.Request.Form[key]; ok { if len(index) == 1 { return val[index[0]], nil } return val[0], nil } return "", errors.New("Query key not found") }
[ "func", "(", "ctx", "*", "Context", ")", "Query", "(", "key", "string", ",", "index", "...", "int", ")", "(", "string", ",", "error", ")", "{", "if", "val", ",", "ok", ":=", "ctx", ".", "Request", ".", "Form", "[", "key", "]", ";", "ok", "{", "if", "len", "(", "index", ")", "==", "1", "{", "return", "val", "[", "index", "[", "0", "]", "]", ",", "nil", "\n", "}", "\n", "return", "val", "[", "0", "]", ",", "nil", "\n", "}", "\n", "return", "\"", "\"", ",", "errors", ".", "New", "(", "\"", "\"", ")", "\n", "}" ]
// Query method retrieves the form data, return empty string if not found.
[ "Query", "method", "retrieves", "the", "form", "data", "return", "empty", "string", "if", "not", "found", "." ]
11abebbbb289ef6f35e518db394eaca39cee8732
https://github.com/dinever/golf/blob/11abebbbb289ef6f35e518db394eaca39cee8732/context.go#L112-L120
5,384
dinever/golf
context.go
Redirect
func (ctx *Context) Redirect(url string) { ctx.SetHeader("Location", url) ctx.SendStatus(302) }
go
func (ctx *Context) Redirect(url string) { ctx.SetHeader("Location", url) ctx.SendStatus(302) }
[ "func", "(", "ctx", "*", "Context", ")", "Redirect", "(", "url", "string", ")", "{", "ctx", ".", "SetHeader", "(", "\"", "\"", ",", "url", ")", "\n", "ctx", ".", "SendStatus", "(", "302", ")", "\n", "}" ]
// Redirect method sets the response as a 302 redirection.
[ "Redirect", "method", "sets", "the", "response", "as", "a", "302", "redirection", "." ]
11abebbbb289ef6f35e518db394eaca39cee8732
https://github.com/dinever/golf/blob/11abebbbb289ef6f35e518db394eaca39cee8732/context.go#L130-L133
5,385
dinever/golf
context.go
Redirect301
func (ctx *Context) Redirect301(url string) { ctx.SetHeader("Location", url) ctx.SendStatus(301) }
go
func (ctx *Context) Redirect301(url string) { ctx.SetHeader("Location", url) ctx.SendStatus(301) }
[ "func", "(", "ctx", "*", "Context", ")", "Redirect301", "(", "url", "string", ")", "{", "ctx", ".", "SetHeader", "(", "\"", "\"", ",", "url", ")", "\n", "ctx", ".", "SendStatus", "(", "301", ")", "\n", "}" ]
// Redirect301 method sets the response as a 301 redirection.
[ "Redirect301", "method", "sets", "the", "response", "as", "a", "301", "redirection", "." ]
11abebbbb289ef6f35e518db394eaca39cee8732
https://github.com/dinever/golf/blob/11abebbbb289ef6f35e518db394eaca39cee8732/context.go#L136-L139
5,386
dinever/golf
context.go
Cookie
func (ctx *Context) Cookie(key string) (string, error) { c, err := ctx.Request.Cookie(key) if err != nil { return "", err } return c.Value, nil }
go
func (ctx *Context) Cookie(key string) (string, error) { c, err := ctx.Request.Cookie(key) if err != nil { return "", err } return c.Value, nil }
[ "func", "(", "ctx", "*", "Context", ")", "Cookie", "(", "key", "string", ")", "(", "string", ",", "error", ")", "{", "c", ",", "err", ":=", "ctx", ".", "Request", ".", "Cookie", "(", "key", ")", "\n", "if", "err", "!=", "nil", "{", "return", "\"", "\"", ",", "err", "\n", "}", "\n", "return", "c", ".", "Value", ",", "nil", "\n", "}" ]
// Cookie returns the value of the cookie by indicating the key.
[ "Cookie", "returns", "the", "value", "of", "the", "cookie", "by", "indicating", "the", "key", "." ]
11abebbbb289ef6f35e518db394eaca39cee8732
https://github.com/dinever/golf/blob/11abebbbb289ef6f35e518db394eaca39cee8732/context.go#L142-L148
5,387
dinever/golf
context.go
SetCookie
func (ctx *Context) SetCookie(key string, value string, expire int) { now := time.Now() cookie := &http.Cookie{ Name: key, Value: value, Path: "/", MaxAge: expire, } if expire != 0 { expireTime := now.Add(time.Duration(expire) * time.Second) cookie.Expires = expireTime } http.SetCookie(ctx.Response, cookie) }
go
func (ctx *Context) SetCookie(key string, value string, expire int) { now := time.Now() cookie := &http.Cookie{ Name: key, Value: value, Path: "/", MaxAge: expire, } if expire != 0 { expireTime := now.Add(time.Duration(expire) * time.Second) cookie.Expires = expireTime } http.SetCookie(ctx.Response, cookie) }
[ "func", "(", "ctx", "*", "Context", ")", "SetCookie", "(", "key", "string", ",", "value", "string", ",", "expire", "int", ")", "{", "now", ":=", "time", ".", "Now", "(", ")", "\n", "cookie", ":=", "&", "http", ".", "Cookie", "{", "Name", ":", "key", ",", "Value", ":", "value", ",", "Path", ":", "\"", "\"", ",", "MaxAge", ":", "expire", ",", "}", "\n", "if", "expire", "!=", "0", "{", "expireTime", ":=", "now", ".", "Add", "(", "time", ".", "Duration", "(", "expire", ")", "*", "time", ".", "Second", ")", "\n", "cookie", ".", "Expires", "=", "expireTime", "\n", "}", "\n", "http", ".", "SetCookie", "(", "ctx", ".", "Response", ",", "cookie", ")", "\n", "}" ]
// SetCookie set cookies for the request. If expire is 0, create a session cookie.
[ "SetCookie", "set", "cookies", "for", "the", "request", ".", "If", "expire", "is", "0", "create", "a", "session", "cookie", "." ]
11abebbbb289ef6f35e518db394eaca39cee8732
https://github.com/dinever/golf/blob/11abebbbb289ef6f35e518db394eaca39cee8732/context.go#L151-L164
5,388
dinever/golf
context.go
JSON
func (ctx *Context) JSON(obj interface{}) { json, err := json.Marshal(obj) if err != nil { panic(err) } ctx.SetHeader("Content-Type", "application/json") ctx.Send(json) }
go
func (ctx *Context) JSON(obj interface{}) { json, err := json.Marshal(obj) if err != nil { panic(err) } ctx.SetHeader("Content-Type", "application/json") ctx.Send(json) }
[ "func", "(", "ctx", "*", "Context", ")", "JSON", "(", "obj", "interface", "{", "}", ")", "{", "json", ",", "err", ":=", "json", ".", "Marshal", "(", "obj", ")", "\n", "if", "err", "!=", "nil", "{", "panic", "(", "err", ")", "\n", "}", "\n", "ctx", ".", "SetHeader", "(", "\"", "\"", ",", "\"", "\"", ")", "\n", "ctx", ".", "Send", "(", "json", ")", "\n", "}" ]
// JSON Sends a JSON response.
[ "JSON", "Sends", "a", "JSON", "response", "." ]
11abebbbb289ef6f35e518db394eaca39cee8732
https://github.com/dinever/golf/blob/11abebbbb289ef6f35e518db394eaca39cee8732/context.go#L167-L174
5,389
dinever/golf
context.go
JSONIndent
func (ctx *Context) JSONIndent(obj interface{}, prefix, indent string) { jsonIndented, err := json.MarshalIndent(obj, prefix, indent) if err != nil { panic(err) } ctx.SetHeader("Content-Type", "application/json") ctx.Send(jsonIndented) }
go
func (ctx *Context) JSONIndent(obj interface{}, prefix, indent string) { jsonIndented, err := json.MarshalIndent(obj, prefix, indent) if err != nil { panic(err) } ctx.SetHeader("Content-Type", "application/json") ctx.Send(jsonIndented) }
[ "func", "(", "ctx", "*", "Context", ")", "JSONIndent", "(", "obj", "interface", "{", "}", ",", "prefix", ",", "indent", "string", ")", "{", "jsonIndented", ",", "err", ":=", "json", ".", "MarshalIndent", "(", "obj", ",", "prefix", ",", "indent", ")", "\n", "if", "err", "!=", "nil", "{", "panic", "(", "err", ")", "\n", "}", "\n", "ctx", ".", "SetHeader", "(", "\"", "\"", ",", "\"", "\"", ")", "\n", "ctx", ".", "Send", "(", "jsonIndented", ")", "\n", "}" ]
// JSONIndent Sends a JSON response, indenting the JSON as desired.
[ "JSONIndent", "Sends", "a", "JSON", "response", "indenting", "the", "JSON", "as", "desired", "." ]
11abebbbb289ef6f35e518db394eaca39cee8732
https://github.com/dinever/golf/blob/11abebbbb289ef6f35e518db394eaca39cee8732/context.go#L177-L184
5,390
dinever/golf
context.go
Send
func (ctx *Context) Send(body interface{}) { if ctx.IsSent { return } switch body.(type) { case []byte: ctx.Response.Write(body.([]byte)) case string: ctx.Response.Write([]byte(body.(string))) case *bytes.Buffer: ctx.Response.Write(body.(*bytes.Buffer).Bytes()) default: panic(fmt.Errorf("Body type not supported")) } ctx.IsSent = true }
go
func (ctx *Context) Send(body interface{}) { if ctx.IsSent { return } switch body.(type) { case []byte: ctx.Response.Write(body.([]byte)) case string: ctx.Response.Write([]byte(body.(string))) case *bytes.Buffer: ctx.Response.Write(body.(*bytes.Buffer).Bytes()) default: panic(fmt.Errorf("Body type not supported")) } ctx.IsSent = true }
[ "func", "(", "ctx", "*", "Context", ")", "Send", "(", "body", "interface", "{", "}", ")", "{", "if", "ctx", ".", "IsSent", "{", "return", "\n", "}", "\n", "switch", "body", ".", "(", "type", ")", "{", "case", "[", "]", "byte", ":", "ctx", ".", "Response", ".", "Write", "(", "body", ".", "(", "[", "]", "byte", ")", ")", "\n", "case", "string", ":", "ctx", ".", "Response", ".", "Write", "(", "[", "]", "byte", "(", "body", ".", "(", "string", ")", ")", ")", "\n", "case", "*", "bytes", ".", "Buffer", ":", "ctx", ".", "Response", ".", "Write", "(", "body", ".", "(", "*", "bytes", ".", "Buffer", ")", ".", "Bytes", "(", ")", ")", "\n", "default", ":", "panic", "(", "fmt", ".", "Errorf", "(", "\"", "\"", ")", ")", "\n", "}", "\n", "ctx", ".", "IsSent", "=", "true", "\n", "}" ]
// Send the response immediately. Set `ctx.IsSent` to `true` to make // sure that the response won't be sent twice.
[ "Send", "the", "response", "immediately", ".", "Set", "ctx", ".", "IsSent", "to", "true", "to", "make", "sure", "that", "the", "response", "won", "t", "be", "sent", "twice", "." ]
11abebbbb289ef6f35e518db394eaca39cee8732
https://github.com/dinever/golf/blob/11abebbbb289ef6f35e518db394eaca39cee8732/context.go#L188-L203
5,391
dinever/golf
context.go
Abort
func (ctx *Context) Abort(statusCode int, data ...map[string]interface{}) { ctx.App.handleError(ctx, statusCode, data...) }
go
func (ctx *Context) Abort(statusCode int, data ...map[string]interface{}) { ctx.App.handleError(ctx, statusCode, data...) }
[ "func", "(", "ctx", "*", "Context", ")", "Abort", "(", "statusCode", "int", ",", "data", "...", "map", "[", "string", "]", "interface", "{", "}", ")", "{", "ctx", ".", "App", ".", "handleError", "(", "ctx", ",", "statusCode", ",", "data", "...", ")", "\n", "}" ]
// Abort method returns an HTTP Error by indicating the status code, the corresponding // handler inside `App.errorHandler` will be called, if user has not set // the corresponding error handler, the defaultErrorHandler will be called.
[ "Abort", "method", "returns", "an", "HTTP", "Error", "by", "indicating", "the", "status", "code", "the", "corresponding", "handler", "inside", "App", ".", "errorHandler", "will", "be", "called", "if", "user", "has", "not", "set", "the", "corresponding", "error", "handler", "the", "defaultErrorHandler", "will", "be", "called", "." ]
11abebbbb289ef6f35e518db394eaca39cee8732
https://github.com/dinever/golf/blob/11abebbbb289ef6f35e518db394eaca39cee8732/context.go#L237-L239
5,392
dinever/golf
context.go
Loader
func (ctx *Context) Loader(name string) *Context { ctx.templateLoader = name return ctx }
go
func (ctx *Context) Loader(name string) *Context { ctx.templateLoader = name return ctx }
[ "func", "(", "ctx", "*", "Context", ")", "Loader", "(", "name", "string", ")", "*", "Context", "{", "ctx", ".", "templateLoader", "=", "name", "\n", "return", "ctx", "\n", "}" ]
// Loader method sets the template loader for this context. This should be done before calling // `ctx.Render`.
[ "Loader", "method", "sets", "the", "template", "loader", "for", "this", "context", ".", "This", "should", "be", "done", "before", "calling", "ctx", ".", "Render", "." ]
11abebbbb289ef6f35e518db394eaca39cee8732
https://github.com/dinever/golf/blob/11abebbbb289ef6f35e518db394eaca39cee8732/context.go#L243-L246
5,393
dinever/golf
context.go
Render
func (ctx *Context) Render(file string, data ...map[string]interface{}) { if ctx.templateLoader == "" { panic(fmt.Errorf("Template loader has not been set")) } var renderData map[string]interface{} if len(data) == 0 { renderData = make(map[string]interface{}) } else { renderData = data[0] } renderData["xsrf_token"] = ctx.xsrfToken() content, err := ctx.App.View.Render(ctx.templateLoader, file, renderData) if err != nil { panic(err) } ctx.Send(content) }
go
func (ctx *Context) Render(file string, data ...map[string]interface{}) { if ctx.templateLoader == "" { panic(fmt.Errorf("Template loader has not been set")) } var renderData map[string]interface{} if len(data) == 0 { renderData = make(map[string]interface{}) } else { renderData = data[0] } renderData["xsrf_token"] = ctx.xsrfToken() content, err := ctx.App.View.Render(ctx.templateLoader, file, renderData) if err != nil { panic(err) } ctx.Send(content) }
[ "func", "(", "ctx", "*", "Context", ")", "Render", "(", "file", "string", ",", "data", "...", "map", "[", "string", "]", "interface", "{", "}", ")", "{", "if", "ctx", ".", "templateLoader", "==", "\"", "\"", "{", "panic", "(", "fmt", ".", "Errorf", "(", "\"", "\"", ")", ")", "\n", "}", "\n", "var", "renderData", "map", "[", "string", "]", "interface", "{", "}", "\n", "if", "len", "(", "data", ")", "==", "0", "{", "renderData", "=", "make", "(", "map", "[", "string", "]", "interface", "{", "}", ")", "\n", "}", "else", "{", "renderData", "=", "data", "[", "0", "]", "\n", "}", "\n", "renderData", "[", "\"", "\"", "]", "=", "ctx", ".", "xsrfToken", "(", ")", "\n", "content", ",", "err", ":=", "ctx", ".", "App", ".", "View", ".", "Render", "(", "ctx", ".", "templateLoader", ",", "file", ",", "renderData", ")", "\n", "if", "err", "!=", "nil", "{", "panic", "(", "err", ")", "\n", "}", "\n", "ctx", ".", "Send", "(", "content", ")", "\n", "}" ]
// Render a template file using the built-in Go template engine.
[ "Render", "a", "template", "file", "using", "the", "built", "-", "in", "Go", "template", "engine", "." ]
11abebbbb289ef6f35e518db394eaca39cee8732
https://github.com/dinever/golf/blob/11abebbbb289ef6f35e518db394eaca39cee8732/context.go#L284-L300
5,394
dinever/golf
context.go
RenderFromString
func (ctx *Context) RenderFromString(tplSrc string, data ...map[string]interface{}) { var renderData map[string]interface{} if len(data) == 0 { renderData = make(map[string]interface{}) } else { renderData = data[0] } renderData["xsrf_token"] = ctx.xsrfToken() content, e := ctx.App.View.RenderFromString(ctx.templateLoader, tplSrc, renderData) if e != nil { panic(e) } ctx.Send(content) }
go
func (ctx *Context) RenderFromString(tplSrc string, data ...map[string]interface{}) { var renderData map[string]interface{} if len(data) == 0 { renderData = make(map[string]interface{}) } else { renderData = data[0] } renderData["xsrf_token"] = ctx.xsrfToken() content, e := ctx.App.View.RenderFromString(ctx.templateLoader, tplSrc, renderData) if e != nil { panic(e) } ctx.Send(content) }
[ "func", "(", "ctx", "*", "Context", ")", "RenderFromString", "(", "tplSrc", "string", ",", "data", "...", "map", "[", "string", "]", "interface", "{", "}", ")", "{", "var", "renderData", "map", "[", "string", "]", "interface", "{", "}", "\n", "if", "len", "(", "data", ")", "==", "0", "{", "renderData", "=", "make", "(", "map", "[", "string", "]", "interface", "{", "}", ")", "\n", "}", "else", "{", "renderData", "=", "data", "[", "0", "]", "\n", "}", "\n", "renderData", "[", "\"", "\"", "]", "=", "ctx", ".", "xsrfToken", "(", ")", "\n", "content", ",", "e", ":=", "ctx", ".", "App", ".", "View", ".", "RenderFromString", "(", "ctx", ".", "templateLoader", ",", "tplSrc", ",", "renderData", ")", "\n", "if", "e", "!=", "nil", "{", "panic", "(", "e", ")", "\n", "}", "\n", "ctx", ".", "Send", "(", "content", ")", "\n", "}" ]
// RenderFromString renders a input string.
[ "RenderFromString", "renders", "a", "input", "string", "." ]
11abebbbb289ef6f35e518db394eaca39cee8732
https://github.com/dinever/golf/blob/11abebbbb289ef6f35e518db394eaca39cee8732/context.go#L303-L316
5,395
dinever/golf
app.go
New
func New() *Application { app := new(Application) app.router = newRouter() app.staticRouter = make(map[string][]string) app.View = NewView() app.Config = NewConfig() app.errorHandler = make(map[int]ErrorHandlerFunc) app.middlewareChain = NewChain() app.DefaultErrorHandler = defaultErrorHandler app.pool.New = func() interface{} { return new(Context) } app.handlerChain = app.middlewareChain.Final(app.handler) return app }
go
func New() *Application { app := new(Application) app.router = newRouter() app.staticRouter = make(map[string][]string) app.View = NewView() app.Config = NewConfig() app.errorHandler = make(map[int]ErrorHandlerFunc) app.middlewareChain = NewChain() app.DefaultErrorHandler = defaultErrorHandler app.pool.New = func() interface{} { return new(Context) } app.handlerChain = app.middlewareChain.Final(app.handler) return app }
[ "func", "New", "(", ")", "*", "Application", "{", "app", ":=", "new", "(", "Application", ")", "\n", "app", ".", "router", "=", "newRouter", "(", ")", "\n", "app", ".", "staticRouter", "=", "make", "(", "map", "[", "string", "]", "[", "]", "string", ")", "\n", "app", ".", "View", "=", "NewView", "(", ")", "\n", "app", ".", "Config", "=", "NewConfig", "(", ")", "\n", "app", ".", "errorHandler", "=", "make", "(", "map", "[", "int", "]", "ErrorHandlerFunc", ")", "\n", "app", ".", "middlewareChain", "=", "NewChain", "(", ")", "\n", "app", ".", "DefaultErrorHandler", "=", "defaultErrorHandler", "\n", "app", ".", "pool", ".", "New", "=", "func", "(", ")", "interface", "{", "}", "{", "return", "new", "(", "Context", ")", "\n", "}", "\n", "app", ".", "handlerChain", "=", "app", ".", "middlewareChain", ".", "Final", "(", "app", ".", "handler", ")", "\n", "return", "app", "\n", "}" ]
// New is used for creating a new Golf Application instance.
[ "New", "is", "used", "for", "creating", "a", "new", "Golf", "Application", "instance", "." ]
11abebbbb289ef6f35e518db394eaca39cee8732
https://github.com/dinever/golf/blob/11abebbbb289ef6f35e518db394eaca39cee8732/app.go#L46-L60
5,396
dinever/golf
app.go
Use
func (app *Application) Use(m ...MiddlewareHandlerFunc) { for _, fn := range m { app.middlewareChain.Append(fn) } app.handlerChain = app.middlewareChain.Final(app.handler) }
go
func (app *Application) Use(m ...MiddlewareHandlerFunc) { for _, fn := range m { app.middlewareChain.Append(fn) } app.handlerChain = app.middlewareChain.Final(app.handler) }
[ "func", "(", "app", "*", "Application", ")", "Use", "(", "m", "...", "MiddlewareHandlerFunc", ")", "{", "for", "_", ",", "fn", ":=", "range", "m", "{", "app", ".", "middlewareChain", ".", "Append", "(", "fn", ")", "\n", "}", "\n", "app", ".", "handlerChain", "=", "app", ".", "middlewareChain", ".", "Final", "(", "app", ".", "handler", ")", "\n", "}" ]
// Use appends a middleware to the existing middleware chain.
[ "Use", "appends", "a", "middleware", "to", "the", "existing", "middleware", "chain", "." ]
11abebbbb289ef6f35e518db394eaca39cee8732
https://github.com/dinever/golf/blob/11abebbbb289ef6f35e518db394eaca39cee8732/app.go#L63-L68
5,397
dinever/golf
app.go
handler
func (app *Application) handler(ctx *Context) { for prefix, staticPathSlice := range app.staticRouter { if strings.HasPrefix(ctx.Request.URL.Path, prefix) { for _, staticPath := range staticPathSlice { filePath := path.Join(staticPath, ctx.Request.URL.Path[len(prefix):]) fileInfo, err := os.Stat(filePath) if err == nil && !fileInfo.IsDir() { staticHandler(ctx, filePath) return } } } } handler, params, err := app.router.FindRoute(ctx.Request.Method, ctx.Request.URL.Path) if err != nil { app.handleError(ctx, 404) } else { ctx.Params = params handler(ctx) } ctx.IsSent = true }
go
func (app *Application) handler(ctx *Context) { for prefix, staticPathSlice := range app.staticRouter { if strings.HasPrefix(ctx.Request.URL.Path, prefix) { for _, staticPath := range staticPathSlice { filePath := path.Join(staticPath, ctx.Request.URL.Path[len(prefix):]) fileInfo, err := os.Stat(filePath) if err == nil && !fileInfo.IsDir() { staticHandler(ctx, filePath) return } } } } handler, params, err := app.router.FindRoute(ctx.Request.Method, ctx.Request.URL.Path) if err != nil { app.handleError(ctx, 404) } else { ctx.Params = params handler(ctx) } ctx.IsSent = true }
[ "func", "(", "app", "*", "Application", ")", "handler", "(", "ctx", "*", "Context", ")", "{", "for", "prefix", ",", "staticPathSlice", ":=", "range", "app", ".", "staticRouter", "{", "if", "strings", ".", "HasPrefix", "(", "ctx", ".", "Request", ".", "URL", ".", "Path", ",", "prefix", ")", "{", "for", "_", ",", "staticPath", ":=", "range", "staticPathSlice", "{", "filePath", ":=", "path", ".", "Join", "(", "staticPath", ",", "ctx", ".", "Request", ".", "URL", ".", "Path", "[", "len", "(", "prefix", ")", ":", "]", ")", "\n", "fileInfo", ",", "err", ":=", "os", ".", "Stat", "(", "filePath", ")", "\n", "if", "err", "==", "nil", "&&", "!", "fileInfo", ".", "IsDir", "(", ")", "{", "staticHandler", "(", "ctx", ",", "filePath", ")", "\n", "return", "\n", "}", "\n", "}", "\n", "}", "\n", "}", "\n\n", "handler", ",", "params", ",", "err", ":=", "app", ".", "router", ".", "FindRoute", "(", "ctx", ".", "Request", ".", "Method", ",", "ctx", ".", "Request", ".", "URL", ".", "Path", ")", "\n", "if", "err", "!=", "nil", "{", "app", ".", "handleError", "(", "ctx", ",", "404", ")", "\n", "}", "else", "{", "ctx", ".", "Params", "=", "params", "\n", "handler", "(", "ctx", ")", "\n", "}", "\n", "ctx", ".", "IsSent", "=", "true", "\n", "}" ]
// First search if any of the static route matches the request. // If not, look up the URL in the router.
[ "First", "search", "if", "any", "of", "the", "static", "route", "matches", "the", "request", ".", "If", "not", "look", "up", "the", "URL", "in", "the", "router", "." ]
11abebbbb289ef6f35e518db394eaca39cee8732
https://github.com/dinever/golf/blob/11abebbbb289ef6f35e518db394eaca39cee8732/app.go#L72-L94
5,398
dinever/golf
app.go
staticHandler
func staticHandler(ctx *Context, filePath string) { http.ServeFile(ctx.Response, ctx.Request, filePath) }
go
func staticHandler(ctx *Context, filePath string) { http.ServeFile(ctx.Response, ctx.Request, filePath) }
[ "func", "staticHandler", "(", "ctx", "*", "Context", ",", "filePath", "string", ")", "{", "http", ".", "ServeFile", "(", "ctx", ".", "Response", ",", "ctx", ".", "Request", ",", "filePath", ")", "\n", "}" ]
// Serve a static file
[ "Serve", "a", "static", "file" ]
11abebbbb289ef6f35e518db394eaca39cee8732
https://github.com/dinever/golf/blob/11abebbbb289ef6f35e518db394eaca39cee8732/app.go#L97-L99
5,399
dinever/golf
app.go
ServeHTTP
func (app *Application) ServeHTTP(res http.ResponseWriter, req *http.Request) { ctx := app.pool.Get().(*Context) ctx.reset() ctx.Request = req ctx.Response = res ctx.App = app app.handlerChain(ctx) app.pool.Put(ctx) }
go
func (app *Application) ServeHTTP(res http.ResponseWriter, req *http.Request) { ctx := app.pool.Get().(*Context) ctx.reset() ctx.Request = req ctx.Response = res ctx.App = app app.handlerChain(ctx) app.pool.Put(ctx) }
[ "func", "(", "app", "*", "Application", ")", "ServeHTTP", "(", "res", "http", ".", "ResponseWriter", ",", "req", "*", "http", ".", "Request", ")", "{", "ctx", ":=", "app", ".", "pool", ".", "Get", "(", ")", ".", "(", "*", "Context", ")", "\n", "ctx", ".", "reset", "(", ")", "\n", "ctx", ".", "Request", "=", "req", "\n", "ctx", ".", "Response", "=", "res", "\n", "ctx", ".", "App", "=", "app", "\n", "app", ".", "handlerChain", "(", "ctx", ")", "\n", "app", ".", "pool", ".", "Put", "(", "ctx", ")", "\n", "}" ]
// Basic entrance of an `http.ResponseWriter` and an `http.Request`.
[ "Basic", "entrance", "of", "an", "http", ".", "ResponseWriter", "and", "an", "http", ".", "Request", "." ]
11abebbbb289ef6f35e518db394eaca39cee8732
https://github.com/dinever/golf/blob/11abebbbb289ef6f35e518db394eaca39cee8732/app.go#L102-L110